diff --git a/shared/package-files/06/0601c8a246923a8de7c099463bf71a247cf7ee7eb2a00f0678cf578e7e333297/__init__.py b/shared/package-files/06/0601c8a246923a8de7c099463bf71a247cf7ee7eb2a00f0678cf578e7e333297/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45412acad0ab9e5c7424b1888648a638ef208142 --- /dev/null +++ b/shared/package-files/06/0601c8a246923a8de7c099463bf71a247cf7ee7eb2a00f0678cf578e7e333297/__init__.py @@ -0,0 +1,18 @@ +r""" +The :py:mod:`~sympy.holonomic` module is intended to deal with holonomic functions along +with various operations on them like addition, multiplication, composition, +integration and differentiation. The module also implements various kinds of +conversions such as converting holonomic functions to a different form and the +other way around. +""" + +from .holonomic import (DifferentialOperator, HolonomicFunction, DifferentialOperators, + from_hyper, from_meijerg, expr_to_holonomic) +from .recurrence import RecurrenceOperators, RecurrenceOperator, HolonomicSequence + +__all__ = [ + 'DifferentialOperator', 'HolonomicFunction', 'DifferentialOperators', + 'from_hyper', 'from_meijerg', 'expr_to_holonomic', + + 'RecurrenceOperators', 'RecurrenceOperator', 'HolonomicSequence', +] diff --git a/shared/package-files/06/0608d0efcab1ab370a7fe56a4aa6f03fdc614d6e5842db40a23fa01ed0b5ea93/_upsample_nearest_exact1d_ops.h b/shared/package-files/06/0608d0efcab1ab370a7fe56a4aa6f03fdc614d6e5842db40a23fa01ed0b5ea93/_upsample_nearest_exact1d_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..df7d1d6cddbf5821c5c16a5eb9cfeeef0bc93250 --- /dev/null +++ b/shared/package-files/06/0608d0efcab1ab370a7fe56a4aa6f03fdc614d6e5842db40a23fa01ed0b5ea93/_upsample_nearest_exact1d_ops.h @@ -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 _upsample_nearest_exact1d_vec { + using schema = at::Tensor (const at::Tensor &, at::OptionalSymIntArrayRef, c10::optional>); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_upsample_nearest_exact1d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "vec") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_nearest_exact1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor") + static at::Tensor call(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, c10::optional> scale_factors); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::OptionalSymIntArrayRef output_size, c10::optional> scale_factors); +}; + +struct TORCH_API _upsample_nearest_exact1d_out { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, 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::_upsample_nearest_exact1d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional scales, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional scales, at::Tensor & out); +}; + +struct TORCH_API _upsample_nearest_exact1d { + 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::_upsample_nearest_exact1d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional scales); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional scales); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/060b265df364fc0e0d52935962d9740be0a3dfaf0388bae5ac1465a29f028b14/onedark.py b/shared/package-files/06/060b265df364fc0e0d52935962d9740be0a3dfaf0388bae5ac1465a29f028b14/onedark.py new file mode 100644 index 0000000000000000000000000000000000000000..e9e90fd8b8e01ef88c98c546208ad85f31f393b4 --- /dev/null +++ b/shared/package-files/06/060b265df364fc0e0d52935962d9740be0a3dfaf0388bae5ac1465a29f028b14/onedark.py @@ -0,0 +1,59 @@ +""" + pygments.styles.onedark + ~~~~~~~~~~~~~~~~~~~~~~~ + + One Dark Theme for Pygments by Tobias Zoghaib (https://github.com/TobiZog) + + Inspired by one-dark-ui for the code editor Atom + (https://atom.io/themes/one-dark-ui). + + :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 Comment, Keyword, Name, Number, Operator, \ + Punctuation, String, Token + + +class OneDarkStyle(Style): + """ + Theme inspired by One Dark Pro for Atom. + + .. versionadded:: 2.11 + """ + + background_color = '#282C34' + + styles = { + Token: '#ABB2BF', + + Punctuation: '#ABB2BF', + Punctuation.Marker: '#ABB2BF', + + Keyword: '#C678DD', + Keyword.Constant: '#E5C07B', + Keyword.Declaration: '#C678DD', + Keyword.Namespace: '#C678DD', + Keyword.Reserved: '#C678DD', + Keyword.Type: '#E5C07B', + + Name: '#E06C75', + Name.Attribute: '#E06C75', + Name.Builtin: '#E5C07B', + Name.Class: '#E5C07B', + Name.Function: 'bold #61AFEF', + Name.Function.Magic: 'bold #56B6C2', + Name.Other: '#E06C75', + Name.Tag: '#E06C75', + Name.Decorator: '#61AFEF', + Name.Variable.Class: '', + + String: '#98C379', + + Number: '#D19A66', + + Operator: '#56B6C2', + + Comment: '#7F848E' + } diff --git a/shared/package-files/06/060b8d3904bb5aa34de99cd03f48f24b13a234c366f96416f01bea90f22f22a9/wrapper.py b/shared/package-files/06/060b8d3904bb5aa34de99cd03f48f24b13a234c366f96416f01bea90f22f22a9/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2f7758ba646dc1260f88ec3223cff6ebf3502b --- /dev/null +++ b/shared/package-files/06/060b8d3904bb5aa34de99cd03f48f24b13a234c366f96416f01bea90f22f22a9/wrapper.py @@ -0,0 +1,133 @@ +import functools +import inspect +from textwrap import dedent + + +class ResultsWrapper: + """ + Class which wraps a statsmodels estimation Results class and steps in to + reattach metadata to results (if available) + """ + _wrap_attrs = {} + _wrap_methods = {} + + def __init__(self, results): + self._results = results + self.__doc__ = results.__doc__ + + def __dir__(self): + return list(dir(self._results)) + + def __getattribute__(self, attr): + def get(name): + return object.__getattribute__(self, name) + + try: + results = get("_results") + except AttributeError: + pass + + try: + return get(attr) + except AttributeError: + pass + + obj = getattr(results, attr) + data = results.model.data + how = self._wrap_attrs.get(attr) + if how and isinstance(how, tuple): + obj = data.wrap_output(obj, how[0], *how[1:]) + elif how: + obj = data.wrap_output(obj, how=how) + + return obj + + def __getstate__(self): + # print 'pickling wrapper', self.__dict__ + return self.__dict__ + + def __setstate__(self, dict_): + # print 'unpickling wrapper', dict_ + self.__dict__.update(dict_) + + def save(self, fname, remove_data=False): + """ + Save a pickle of this instance. + + Parameters + ---------- + fname : str or handle + Either a filename or a valid file handle. + remove_data : bool, optional + If False (default), then the instance is pickled without changes. + If True, then all arrays with length nobs are set to None before + pickling. See the remove_data method. + In some cases not all arrays will be set to None. + """ + from statsmodels.iolib.smpickle import save_pickle + + if remove_data: + self.remove_data() + + save_pickle(self, fname) + + @classmethod + def load(cls, fname): + """ + Load a pickled results instance + + .. warning:: + + Loading pickled models is not secure against erroneous or + maliciously constructed data. Never unpickle data received from + an untrusted or unauthenticated source. + + Parameters + ---------- + fname : str or handle + A string filename or a file handle. + + Returns + ------- + Results + The unpickled results instance. + """ + from statsmodels.iolib.smpickle import load_pickle + return load_pickle(fname) + + +def union_dicts(*dicts): + result = {} + for d in dicts: + result.update(d) + return result + + +def make_wrapper(func, how): + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + results = object.__getattribute__(self, "_results") + data = results.model.data + if how and isinstance(how, tuple): + obj = data.wrap_output(func(results, *args, **kwargs), how[0], how[1:]) + elif how: + obj = data.wrap_output(func(results, *args, **kwargs), how) + return obj + + sig = inspect.signature(func) + formatted = str(sig) + + doc = dedent(wrapper.__doc__) if wrapper.__doc__ else "" + wrapper.__doc__ = f"\n{func.__name__}{formatted}\n{doc}" + + return wrapper + + +def populate_wrapper(klass, wrapping): + for meth, how in klass._wrap_methods.items(): + if not hasattr(wrapping, meth): + continue + + func = getattr(wrapping, meth) + wrapper = make_wrapper(func, how) + setattr(klass, meth, wrapper) diff --git a/shared/package-files/06/061299b38f8bae11547ca8dc1b4c9e9724a313a6484ccc462016161831cc45bf/test_isfile.py b/shared/package-files/06/061299b38f8bae11547ca8dc1b4c9e9724a313a6484ccc462016161831cc45bf/test_isfile.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca2c9b21f94c37252fc6130f9f03a4ad4e04433 --- /dev/null +++ b/shared/package-files/06/061299b38f8bae11547ca8dc1b4c9e9724a313a6484ccc462016161831cc45bf/test_isfile.py @@ -0,0 +1,32 @@ +import os +import sys +from pathlib import Path + +import numpy as np +from numpy.testing import assert_ + +ROOT = Path(np.__file__).parents[0] +FILES = [ + ROOT / "py.typed", + ROOT / "__init__.pyi", + ROOT / "ctypeslib.pyi", + ROOT / "core" / "__init__.pyi", + ROOT / "f2py" / "__init__.pyi", + ROOT / "fft" / "__init__.pyi", + ROOT / "lib" / "__init__.pyi", + ROOT / "linalg" / "__init__.pyi", + ROOT / "ma" / "__init__.pyi", + ROOT / "matrixlib" / "__init__.pyi", + ROOT / "polynomial" / "__init__.pyi", + ROOT / "random" / "__init__.pyi", + ROOT / "testing" / "__init__.pyi", +] +if sys.version_info < (3, 12): + FILES += [ROOT / "distutils" / "__init__.pyi"] + + +class TestIsFile: + def test_isfile(self): + """Test if all ``.pyi`` files are properly installed.""" + for file in FILES: + assert_(os.path.isfile(file)) diff --git a/shared/package-files/06/0614b3def4c0fd0e8851b30bb212d0b1e119f42be35a58f6cac9f5a4d1c06239/ones_like_ops.h b/shared/package-files/06/0614b3def4c0fd0e8851b30bb212d0b1e119f42be35a58f6cac9f5a4d1c06239/ones_like_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eface803c598707906e98c687abc82d26919db1a --- /dev/null +++ b/shared/package-files/06/0614b3def4c0fd0e8851b30bb212d0b1e119f42be35a58f6cac9f5a4d1c06239/ones_like_ops.h @@ -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 ones_like { + using schema = at::Tensor (const at::Tensor &, c10::optional, c10::optional, c10::optional, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::ones_like") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ones_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format); +}; + +struct TORCH_API ones_like_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::ones_like") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ones_like.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::optional memory_format, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional memory_format, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/06156ade0ac8265a4b890ca6975ceb3a50307af09502bf9c699f4deae943902f/fbgemm_pack_gemm_matrix_fp16.h b/shared/package-files/06/06156ade0ac8265a4b890ca6975ceb3a50307af09502bf9c699f4deae943902f/fbgemm_pack_gemm_matrix_fp16.h new file mode 100644 index 0000000000000000000000000000000000000000..4f339a95049c013b67ea8e9775ffc29a2a894496 --- /dev/null +++ b/shared/package-files/06/06156ade0ac8265a4b890ca6975ceb3a50307af09502bf9c699f4deae943902f/fbgemm_pack_gemm_matrix_fp16.h @@ -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::fbgemm_pack_gemm_matrix_fp16(Tensor input) -> Tensor +inline at::Tensor fbgemm_pack_gemm_matrix_fp16(const at::Tensor & input) { + return at::_ops::fbgemm_pack_gemm_matrix_fp16::call(input); +} + +} diff --git a/shared/package-files/06/061ac0d79ef9c745baedeee80383727a8dd12bf8d4468a0ea24d66b5cac53404/round_meta.h b/shared/package-files/06/061ac0d79ef9c745baedeee80383727a8dd12bf8d4468a0ea24d66b5cac53404/round_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..64dd0589dd1a27c7e30c43c0bb40c03d021ee017 --- /dev/null +++ b/shared/package-files/06/061ac0d79ef9c745baedeee80383727a8dd12bf8d4468a0ea24d66b5cac53404/round_meta.h @@ -0,0 +1,32 @@ +#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_round : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; +struct TORCH_API structured_round_decimals : public TensorIteratorBase { + + + void meta(const at::Tensor & self, int64_t decimals); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/06/061b31fe08f972962fe0185525142887194a93fadca788c7b524654cffa6ff1b/test_pauli.py b/shared/package-files/06/061b31fe08f972962fe0185525142887194a93fadca788c7b524654cffa6ff1b/test_pauli.py new file mode 100644 index 0000000000000000000000000000000000000000..77bbed93ac5b4b49680be01aefa2f779b62fc7ee --- /dev/null +++ b/shared/package-files/06/061b31fe08f972962fe0185525142887194a93fadca788c7b524654cffa6ff1b/test_pauli.py @@ -0,0 +1,159 @@ +from sympy.core.mul import Mul +from sympy.core.numbers import I +from sympy.matrices.dense import Matrix +from sympy.printing.latex import latex +from sympy.physics.quantum import (Dagger, Commutator, AntiCommutator, qapply, + Operator, represent) +from sympy.physics.quantum.pauli import (SigmaOpBase, SigmaX, SigmaY, SigmaZ, + SigmaMinus, SigmaPlus, + qsimplify_pauli) +from sympy.physics.quantum.pauli import SigmaZKet, SigmaZBra +from sympy.testing.pytest import raises + + +sx, sy, sz = SigmaX(), SigmaY(), SigmaZ() +sx1, sy1, sz1 = SigmaX(1), SigmaY(1), SigmaZ(1) +sx2, sy2, sz2 = SigmaX(2), SigmaY(2), SigmaZ(2) + +sm, sp = SigmaMinus(), SigmaPlus() +sm1, sp1 = SigmaMinus(1), SigmaPlus(1) +A, B = Operator("A"), Operator("B") + + +def test_pauli_operators_types(): + + assert isinstance(sx, SigmaOpBase) and isinstance(sx, SigmaX) + assert isinstance(sy, SigmaOpBase) and isinstance(sy, SigmaY) + assert isinstance(sz, SigmaOpBase) and isinstance(sz, SigmaZ) + assert isinstance(sm, SigmaOpBase) and isinstance(sm, SigmaMinus) + assert isinstance(sp, SigmaOpBase) and isinstance(sp, SigmaPlus) + + +def test_pauli_operators_commutator(): + + assert Commutator(sx, sy).doit() == 2 * I * sz + assert Commutator(sy, sz).doit() == 2 * I * sx + assert Commutator(sz, sx).doit() == 2 * I * sy + + +def test_pauli_operators_commutator_with_labels(): + + assert Commutator(sx1, sy1).doit() == 2 * I * sz1 + assert Commutator(sy1, sz1).doit() == 2 * I * sx1 + assert Commutator(sz1, sx1).doit() == 2 * I * sy1 + + assert Commutator(sx2, sy2).doit() == 2 * I * sz2 + assert Commutator(sy2, sz2).doit() == 2 * I * sx2 + assert Commutator(sz2, sx2).doit() == 2 * I * sy2 + + assert Commutator(sx1, sy2).doit() == 0 + assert Commutator(sy1, sz2).doit() == 0 + assert Commutator(sz1, sx2).doit() == 0 + + +def test_pauli_operators_anticommutator(): + + assert AntiCommutator(sy, sz).doit() == 0 + assert AntiCommutator(sz, sx).doit() == 0 + assert AntiCommutator(sx, sm).doit() == 1 + assert AntiCommutator(sx, sp).doit() == 1 + + +def test_pauli_operators_adjoint(): + + assert Dagger(sx) == sx + assert Dagger(sy) == sy + assert Dagger(sz) == sz + + +def test_pauli_operators_adjoint_with_labels(): + + assert Dagger(sx1) == sx1 + assert Dagger(sy1) == sy1 + assert Dagger(sz1) == sz1 + + assert Dagger(sx1) != sx2 + assert Dagger(sy1) != sy2 + assert Dagger(sz1) != sz2 + + +def test_pauli_operators_multiplication(): + + assert qsimplify_pauli(sx * sx) == 1 + assert qsimplify_pauli(sy * sy) == 1 + assert qsimplify_pauli(sz * sz) == 1 + + assert qsimplify_pauli(sx * sy) == I * sz + assert qsimplify_pauli(sy * sz) == I * sx + assert qsimplify_pauli(sz * sx) == I * sy + + assert qsimplify_pauli(sy * sx) == - I * sz + assert qsimplify_pauli(sz * sy) == - I * sx + assert qsimplify_pauli(sx * sz) == - I * sy + + +def test_pauli_operators_multiplication_with_labels(): + + assert qsimplify_pauli(sx1 * sx1) == 1 + assert qsimplify_pauli(sy1 * sy1) == 1 + assert qsimplify_pauli(sz1 * sz1) == 1 + + assert isinstance(sx1 * sx2, Mul) + assert isinstance(sy1 * sy2, Mul) + assert isinstance(sz1 * sz2, Mul) + + assert qsimplify_pauli(sx1 * sy1 * sx2 * sy2) == - sz1 * sz2 + assert qsimplify_pauli(sy1 * sz1 * sz2 * sx2) == - sx1 * sy2 + + +def test_pauli_states(): + sx, sz = SigmaX(), SigmaZ() + + up = SigmaZKet(0) + down = SigmaZKet(1) + + assert qapply(sx * up) == down + assert qapply(sx * down) == up + assert qapply(sz * up) == up + assert qapply(sz * down) == - down + + up = SigmaZBra(0) + down = SigmaZBra(1) + + assert qapply(up * sx, dagger=True) == down + assert qapply(down * sx, dagger=True) == up + assert qapply(up * sz, dagger=True) == up + assert qapply(down * sz, dagger=True) == - down + + assert Dagger(SigmaZKet(0)) == SigmaZBra(0) + assert Dagger(SigmaZBra(1)) == SigmaZKet(1) + raises(ValueError, lambda: SigmaZBra(2)) + raises(ValueError, lambda: SigmaZKet(2)) + + +def test_use_name(): + assert sm.use_name is False + assert sm1.use_name is True + assert sx.use_name is False + assert sx1.use_name is True + + +def test_printing(): + assert latex(sx) == r'{\sigma_x}' + assert latex(sx1) == r'{\sigma_x^{(1)}}' + assert latex(sy) == r'{\sigma_y}' + assert latex(sy1) == r'{\sigma_y^{(1)}}' + assert latex(sz) == r'{\sigma_z}' + assert latex(sz1) == r'{\sigma_z^{(1)}}' + assert latex(sm) == r'{\sigma_-}' + assert latex(sm1) == r'{\sigma_-^{(1)}}' + assert latex(sp) == r'{\sigma_+}' + assert latex(sp1) == r'{\sigma_+^{(1)}}' + + +def test_represent(): + assert represent(sx) == Matrix([[0, 1], [1, 0]]) + assert represent(sy) == Matrix([[0, -I], [I, 0]]) + assert represent(sz) == Matrix([[1, 0], [0, -1]]) + assert represent(sm) == Matrix([[0, 0], [1, 0]]) + assert represent(sp) == Matrix([[0, 1], [0, 0]]) diff --git a/shared/package-files/06/061bade60c4a6fc1fe44dbbc2caa749c49b2413e45655440f9a3ab57a5fc8771/test_cuda_auto_context.py b/shared/package-files/06/061bade60c4a6fc1fe44dbbc2caa749c49b2413e45655440f9a3ab57a5fc8771/test_cuda_auto_context.py new file mode 100644 index 0000000000000000000000000000000000000000..4a4d59310dd34b36a1d8bd473a8f5e5d7eda5d93 --- /dev/null +++ b/shared/package-files/06/061bade60c4a6fc1fe44dbbc2caa749c49b2413e45655440f9a3ab57a5fc8771/test_cuda_auto_context.py @@ -0,0 +1,21 @@ +import numpy as np +from numba import cuda +from numba.cuda.testing import unittest, CUDATestCase + + +class TestCudaAutoContext(CUDATestCase): + def test_auto_context(self): + """A problem was revealed by a customer that the use cuda.to_device + does not create a CUDA context. + This tests the problem + """ + A = np.arange(10, dtype=np.float32) + newA = np.empty_like(A) + dA = cuda.to_device(A) + + dA.copy_to_host(newA) + self.assertTrue(np.allclose(A, newA)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/06/061c60d3203f41ed6dd8a11d995116d8dd5b984ed5651e9237311554d505baed/grid_sampler_3d_backward_ops.h b/shared/package-files/06/061c60d3203f41ed6dd8a11d995116d8dd5b984ed5651e9237311554d505baed/grid_sampler_3d_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..74d78b15aa4301194fb36806f2cdccc2ddc53f7b --- /dev/null +++ b/shared/package-files/06/061c60d3203f41ed6dd8a11d995116d8dd5b984ed5651e9237311554d505baed/grid_sampler_3d_backward_ops.h @@ -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 grid_sampler_3d_backward { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool, ::std::array); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::grid_sampler_3d_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "grid_sampler_3d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask); +}; + +struct TORCH_API grid_sampler_3d_backward_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool, ::std::array, 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::grid_sampler_3d_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "grid_sampler_3d_backward.out(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/061d04926ec6ed9a1bbd24fb080af251baa46049bedeec45bf37f3ed6264e361/special_modified_bessel_i1_meta.h b/shared/package-files/06/061d04926ec6ed9a1bbd24fb080af251baa46049bedeec45bf37f3ed6264e361/special_modified_bessel_i1_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..3962e4e0290ac9dc87735756291e94b320224708 --- /dev/null +++ b/shared/package-files/06/061d04926ec6ed9a1bbd24fb080af251baa46049bedeec45bf37f3ed6264e361/special_modified_bessel_i1_meta.h @@ -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_modified_bessel_i1 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/06/061db31605bf37551e63eb0784478ebc9407462d77656bafec824cb5fbc55ec9/xterm+alt+title b/shared/package-files/06/061db31605bf37551e63eb0784478ebc9407462d77656bafec824cb5fbc55ec9/xterm+alt+title new file mode 100644 index 0000000000000000000000000000000000000000..c3a2a19fbce74d4a671b5bc29ba81cca3516974d Binary files /dev/null and b/shared/package-files/06/061db31605bf37551e63eb0784478ebc9407462d77656bafec824cb5fbc55ec9/xterm+alt+title differ diff --git a/shared/package-files/06/06234ed24ba85fdaae4110d0b273cbaf4e1564b1ce8f9ec29ab2493793ae067e/urllib_robotparser.pyi b/shared/package-files/06/06234ed24ba85fdaae4110d0b273cbaf4e1564b1ce8f9ec29ab2493793ae067e/urllib_robotparser.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bbf5c3ce4cd1aa62eb1cb891f2fb1d7b1432079f --- /dev/null +++ b/shared/package-files/06/06234ed24ba85fdaae4110d0b273cbaf4e1564b1ce8f9ec29ab2493793ae067e/urllib_robotparser.pyi @@ -0,0 +1 @@ +from urllib.robotparser import * diff --git a/shared/package-files/06/06246ec9f0873add1dec5e35327eb41594e7c8be3cab7345f1336ff3e50bd9c1/dw4 b/shared/package-files/06/06246ec9f0873add1dec5e35327eb41594e7c8be3cab7345f1336ff3e50bd9c1/dw4 new file mode 100644 index 0000000000000000000000000000000000000000..e6c9bdf23c509a2d94733270ce385ed6adb63566 Binary files /dev/null and b/shared/package-files/06/06246ec9f0873add1dec5e35327eb41594e7c8be3cab7345f1336ff3e50bd9c1/dw4 differ diff --git a/shared/package-files/06/062495c2be304c1c2d12d7e01e4e20485b3cbf3b57fb71a9cf576ad344ac29b6/METADATA b/shared/package-files/06/062495c2be304c1c2d12d7e01e4e20485b3cbf3b57fb71a9cf576ad344ac29b6/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..192e9cf9b5949fdde40d5e989e1e2ffc96482731 --- /dev/null +++ b/shared/package-files/06/062495c2be304c1c2d12d7e01e4e20485b3cbf3b57fb71a9cf576ad344ac29b6/METADATA @@ -0,0 +1,79 @@ +Metadata-Version: 2.1 +Name: conda-libmamba-solver +Version: 23.7.0 +Summary: The fast mamba solver, now in conda +Project-URL: homepage, https://github.com/conda/conda-libmamba-solver +Author-email: "Anaconda, Inc." +License: BSD 3-Clause License + + Copyright (c) 2022, Anaconda, Inc. + Copyright (c) 2023, conda + 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 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. + + --- + + This work also includes code borrowed from mamba.utils v0.19, licensed as BSD 3-Clause +License-File: AUTHORS.md +License-File: LICENSE +Classifier: License :: OSI Approved :: BSD License +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 :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.8 +Requires-Dist: boltons>=23.0.0 +Requires-Dist: conda>=23.5.0 +Requires-Dist: libmambapy>=1.4.1 +Description-Content-Type: text/markdown + +# conda-libmamba-solver + +[![Anaconda-Server Badge](https://anaconda.org/main/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/main/conda-libmamba-solver) +[![Anaconda-Server Badge](https://anaconda.org/main/conda-libmamba-solver/badges/latest_release_date.svg)](https://anaconda.org/main/conda-libmamba-solver) +[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/conda/conda-libmamba-solver/tests.yml?branch=main&label=Tests&logo=github&style=flat-square)](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml) +[![CalVer version used YY.MM.MICRO](https://img.shields.io/badge/calver-YY.MM.MICRO-22bfda.svg?style=flat-square)](https://calver.org) + +The fast mamba solver, now in conda! + +## What is this exactly? + +conda-libmamba-solver is a new solver for the +[conda package manager](https://docs.conda.io/) which uses the solver from the +[mamba project](https://mamba.readthedocs.io/) behind the scenes, while +carefully implementing conda's functionality and expected behaviors on top. +The library used by mamba to do the heavy-lifting is called [libsolv](https://github.com/openSUSE/libsolv). + +Additional information about the project can be found in the blog post on Anaconda's weblog: +[A Faster Solver for Conda: Libmamba](https://www.anaconda.com/blog/a-faster-conda-for-a-growing-community). + +## Documentation + +Check the [documentation](https://conda.github.io/conda-libmamba-solver/) for +instructions on how to install, use and make the most out the new conda solver! diff --git a/shared/package-files/06/062823e5781d180eb73814ffe5fe3805fd0a90eedc468e77d05915bdafa53ab9/operator_name.h b/shared/package-files/06/062823e5781d180eb73814ffe5fe3805fd0a90eedc468e77d05915bdafa53ab9/operator_name.h new file mode 100644 index 0000000000000000000000000000000000000000..6440a695b55ec45e8d2346911fed2dc767e0afa3 --- /dev/null +++ b/shared/package-files/06/062823e5781d180eb73814ffe5fe3805fd0a90eedc468e77d05915bdafa53ab9/operator_name.h @@ -0,0 +1,92 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace c10 { + +// TODO: consider storing namespace separately too +struct OperatorName final { + std::string name; + std::string overload_name; + OperatorName(std::string name, std::string overload_name) + : name(std::move(name)), overload_name(std::move(overload_name)) {} + + // TODO: These two functions below are slow! Fix internal data structures so + // I don't have to manually reconstruct the namespaces! + + // Return the namespace of this OperatorName, if it exists. The + // returned string_view is only live as long as the OperatorName + // exists and name is not mutated + c10::optional getNamespace() const { + auto pos = name.find("::"); + if (pos == std::string::npos) { + return c10::nullopt; + } else { + return c10::make_optional(c10::string_view(name.data(), pos)); + } + } + + // Returns true if we successfully set the namespace + bool setNamespaceIfNotSet(const char* ns) { + if (!getNamespace().has_value()) { + const auto ns_len = strlen(ns); + const auto old_name_size = name.size(); + name.resize(ns_len + 2 + old_name_size); + // Shift current value of name to the end of the new space. + name.replace(name.size() - old_name_size, old_name_size, name, 0, old_name_size); + name.replace(0, ns_len, ns, ns_len); + name[ns_len] = ':'; + name[ns_len + 1] = ':'; + return true; + } else { + return false; + } + } +}; + +// Non-owning view of an OperatorName. Unlike OperatorName, most of +// its functions are constexpr, so it can be used for compile time +// computations +struct OperatorNameView final { + c10::string_view name; + c10::string_view overload_name; + constexpr OperatorNameView(c10::string_view name, c10::string_view overload_name) + : name(name), overload_name(overload_name) {} + // Parses strings like "foo.overload" and also "foo" + constexpr static OperatorNameView parse(c10::string_view full_name) { + auto i = full_name.find('.'); + if (i == c10::string_view::npos) { + return OperatorNameView(full_name, c10::string_view()); + } else { + return OperatorNameView(full_name.substr(0, i), full_name.substr(i + 1)); + } + } +}; + +inline bool operator==(const OperatorName& lhs, const OperatorName& rhs) { + return lhs.name == rhs.name && lhs.overload_name == rhs.overload_name; +} + +inline bool operator!=(const OperatorName& lhs, const OperatorName& rhs) { + return !operator==(lhs, rhs); +} + +TORCH_API std::string toString(const OperatorName& opName); +TORCH_API std::ostream& operator<<(std::ostream&, const OperatorName&); + +} // namespace c10 + +namespace std { + template <> + struct hash<::c10::OperatorName> { + size_t operator()(const ::c10::OperatorName& x) const { + return std::hash()(x.name) ^ (~ std::hash()(x.overload_name)); + } + }; +} diff --git a/shared/package-files/06/062a7186a599ccd871ba9ec9297e39bf3903a0c257e65225d55c9b0d62351208/is_leaf_ops.h b/shared/package-files/06/062a7186a599ccd871ba9ec9297e39bf3903a0c257e65225d55c9b0d62351208/is_leaf_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..9f33164af899f24c5898f2f51c3804f297020ec9 --- /dev/null +++ b/shared/package-files/06/062a7186a599ccd871ba9ec9297e39bf3903a0c257e65225d55c9b0d62351208/is_leaf_ops.h @@ -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_leaf { + 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_leaf") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "is_leaf(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/06/062dfb39ffb903e81f0a8101a3ad906c03673c3f5605d5bf3157187d8b1ecb8b/_rbm.py b/shared/package-files/06/062dfb39ffb903e81f0a8101a3ad906c03673c3f5605d5bf3157187d8b1ecb8b/_rbm.py new file mode 100644 index 0000000000000000000000000000000000000000..1e1d3c2e11b7cd8a43b57aefeda4a93903698264 --- /dev/null +++ b/shared/package-files/06/062dfb39ffb903e81f0a8101a3ad906c03673c3f5605d5bf3157187d8b1ecb8b/_rbm.py @@ -0,0 +1,445 @@ +"""Restricted Boltzmann Machine""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import time +from numbers import Integral, Real + +import numpy as np +import scipy.sparse as sp +from scipy.special import expit # logistic function + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, +) +from ..utils import check_random_state, gen_even_slices +from ..utils._param_validation import Interval +from ..utils.extmath import safe_sparse_dot +from ..utils.validation import check_is_fitted, validate_data + + +class BernoulliRBM(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + """Bernoulli Restricted Boltzmann Machine (RBM). + + A Restricted Boltzmann Machine with binary visible units and + binary hidden units. Parameters are estimated using Stochastic Maximum + Likelihood (SML), also known as Persistent Contrastive Divergence (PCD) + [2]. + + The time complexity of this implementation is ``O(d ** 2)`` assuming + d ~ n_features ~ n_components. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, default=256 + Number of binary hidden units. + + learning_rate : float, default=0.1 + The learning rate for weight updates. It is *highly* recommended + to tune this hyper-parameter. Reasonable values are in the + 10**[0., -3.] range. + + batch_size : int, default=10 + Number of examples per minibatch. + + n_iter : int, default=10 + Number of iterations/sweeps over the training dataset to perform + during training. + + verbose : int, default=0 + The verbosity level. The default, zero, means silent mode. Range + of values is [0, inf]. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for: + + - Gibbs sampling from visible and hidden layers. + + - Initializing components, sampling from layers during fit. + + - Corrupting the data when scoring samples. + + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + intercept_hidden_ : array-like of shape (n_components,) + Biases of the hidden units. + + intercept_visible_ : array-like of shape (n_features,) + Biases of the visible units. + + components_ : array-like of shape (n_components, n_features) + Weight matrix, where `n_features` is the number of + visible units and `n_components` is the number of hidden units. + + h_samples_ : array-like of shape (batch_size, n_components) + Hidden Activation sampled from the model distribution, + where `batch_size` is the number of examples per minibatch and + `n_components` is the number of hidden units. + + 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 + -------- + sklearn.neural_network.MLPRegressor : Multi-layer Perceptron regressor. + sklearn.neural_network.MLPClassifier : Multi-layer Perceptron classifier. + sklearn.decomposition.PCA : An unsupervised linear dimensionality + reduction model. + + References + ---------- + + [1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for + deep belief nets. Neural Computation 18, pp 1527-1554. + https://www.cs.toronto.edu/~hinton/absps/fastnc.pdf + + [2] Tieleman, T. Training Restricted Boltzmann Machines using + Approximations to the Likelihood Gradient. International Conference + on Machine Learning (ICML) 2008 + + Examples + -------- + + >>> import numpy as np + >>> from sklearn.neural_network import BernoulliRBM + >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) + >>> model = BernoulliRBM(n_components=2) + >>> model.fit(X) + BernoulliRBM(n_components=2) + + For a more detailed example usage, see + :ref:`sphx_glr_auto_examples_neural_networks_plot_rbm_logistic_classification.py`. + """ + + _parameter_constraints: dict = { + "n_components": [Interval(Integral, 1, None, closed="left")], + "learning_rate": [Interval(Real, 0, None, closed="neither")], + "batch_size": [Interval(Integral, 1, None, closed="left")], + "n_iter": [Interval(Integral, 0, None, closed="left")], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + n_components=256, + *, + learning_rate=0.1, + batch_size=10, + n_iter=10, + verbose=0, + random_state=None, + ): + self.n_components = n_components + self.learning_rate = learning_rate + self.batch_size = batch_size + self.n_iter = n_iter + self.verbose = verbose + self.random_state = random_state + + def transform(self, X): + """Compute the hidden layer activation probabilities, P(h=1|v=X). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to be transformed. + + Returns + ------- + h : ndarray of shape (n_samples, n_components) + Latent representations of the data. + """ + check_is_fitted(self) + + X = validate_data( + self, X, accept_sparse="csr", reset=False, dtype=(np.float64, np.float32) + ) + return self._mean_hiddens(X) + + def _mean_hiddens(self, v): + """Computes the probabilities P(h=1|v). + + Parameters + ---------- + v : ndarray of shape (n_samples, n_features) + Values of the visible layer. + + Returns + ------- + h : ndarray of shape (n_samples, n_components) + Corresponding mean field values for the hidden layer. + """ + p = safe_sparse_dot(v, self.components_.T) + p += self.intercept_hidden_ + return expit(p, out=p) + + def _sample_hiddens(self, v, rng): + """Sample from the distribution P(h|v). + + Parameters + ---------- + v : ndarray of shape (n_samples, n_features) + Values of the visible layer to sample from. + + rng : RandomState instance + Random number generator to use. + + Returns + ------- + h : ndarray of shape (n_samples, n_components) + Values of the hidden layer. + """ + p = self._mean_hiddens(v) + return rng.uniform(size=p.shape) < p + + def _sample_visibles(self, h, rng): + """Sample from the distribution P(v|h). + + Parameters + ---------- + h : ndarray of shape (n_samples, n_components) + Values of the hidden layer to sample from. + + rng : RandomState instance + Random number generator to use. + + Returns + ------- + v : ndarray of shape (n_samples, n_features) + Values of the visible layer. + """ + p = np.dot(h, self.components_) + p += self.intercept_visible_ + expit(p, out=p) + return rng.uniform(size=p.shape) < p + + def _free_energy(self, v): + """Computes the free energy F(v) = - log sum_h exp(-E(v,h)). + + Parameters + ---------- + v : ndarray of shape (n_samples, n_features) + Values of the visible layer. + + Returns + ------- + free_energy : ndarray of shape (n_samples,) + The value of the free energy. + """ + return -safe_sparse_dot(v, self.intercept_visible_) - np.logaddexp( + 0, safe_sparse_dot(v, self.components_.T) + self.intercept_hidden_ + ).sum(axis=1) + + def gibbs(self, v): + """Perform one Gibbs sampling step. + + Parameters + ---------- + v : ndarray of shape (n_samples, n_features) + Values of the visible layer to start from. + + Returns + ------- + v_new : ndarray of shape (n_samples, n_features) + Values of the visible layer after one Gibbs step. + """ + check_is_fitted(self) + if not hasattr(self, "random_state_"): + self.random_state_ = check_random_state(self.random_state) + h_ = self._sample_hiddens(v, self.random_state_) + v_ = self._sample_visibles(h_, self.random_state_) + + return v_ + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y=None): + """Fit the model to the partial segment of the data X. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None + Target values (None for unsupervised transformations). + + Returns + ------- + self : BernoulliRBM + The fitted model. + """ + first_pass = not hasattr(self, "components_") + X = validate_data( + self, X, accept_sparse="csr", dtype=np.float64, reset=first_pass + ) + if not hasattr(self, "random_state_"): + self.random_state_ = check_random_state(self.random_state) + if not hasattr(self, "components_"): + self.components_ = np.asarray( + self.random_state_.normal(0, 0.01, (self.n_components, X.shape[1])), + order="F", + ) + self._n_features_out = self.components_.shape[0] + if not hasattr(self, "intercept_hidden_"): + self.intercept_hidden_ = np.zeros( + self.n_components, + ) + if not hasattr(self, "intercept_visible_"): + self.intercept_visible_ = np.zeros( + X.shape[1], + ) + if not hasattr(self, "h_samples_"): + self.h_samples_ = np.zeros((self.batch_size, self.n_components)) + + self._fit(X, self.random_state_) + + def _fit(self, v_pos, rng): + """Inner fit for one mini-batch. + + Adjust the parameters to maximize the likelihood of v using + Stochastic Maximum Likelihood (SML). + + Parameters + ---------- + v_pos : ndarray of shape (n_samples, n_features) + The data to use for training. + + rng : RandomState instance + Random number generator to use for sampling. + """ + h_pos = self._mean_hiddens(v_pos) + v_neg = self._sample_visibles(self.h_samples_, rng) + h_neg = self._mean_hiddens(v_neg) + + lr = float(self.learning_rate) / v_pos.shape[0] + update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T + update -= np.dot(h_neg.T, v_neg) + self.components_ += lr * update + self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0)) + self.intercept_visible_ += lr * ( + np.asarray(v_pos.sum(axis=0)).squeeze() - v_neg.sum(axis=0) + ) + + h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial + self.h_samples_ = np.floor(h_neg, h_neg) + + def score_samples(self, X): + """Compute the pseudo-likelihood of X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Values of the visible layer. Must be all-boolean (not checked). + + Returns + ------- + pseudo_likelihood : ndarray of shape (n_samples,) + Value of the pseudo-likelihood (proxy for likelihood). + + Notes + ----- + This method is not deterministic: it computes a quantity called the + free energy on X, then on a randomly corrupted version of X, and + returns the log of the logistic function of the difference. + """ + check_is_fitted(self) + + v = validate_data(self, X, accept_sparse="csr", reset=False) + rng = check_random_state(self.random_state) + + # Randomly corrupt one feature in each sample in v. + ind = (np.arange(v.shape[0]), rng.randint(0, v.shape[1], v.shape[0])) + if sp.issparse(v): + data = -2 * v[ind] + 1 + if isinstance(data, np.matrix): # v is a sparse matrix + v_ = v + sp.csr_matrix((data.A.ravel(), ind), shape=v.shape) + else: # v is a sparse array + v_ = v + sp.csr_array((data.ravel(), ind), shape=v.shape) + else: + v_ = v.copy() + v_[ind] = 1 - v_[ind] + + fe = self._free_energy(v) + fe_ = self._free_energy(v_) + # log(expit(x)) = log(1 / (1 + exp(-x)) = -np.logaddexp(0, -x) + return -v.shape[1] * np.logaddexp(0, -(fe_ - fe)) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the model to the data X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None + Target values (None for unsupervised transformations). + + Returns + ------- + self : BernoulliRBM + The fitted model. + """ + X = validate_data(self, X, accept_sparse="csr", dtype=(np.float64, np.float32)) + n_samples = X.shape[0] + rng = check_random_state(self.random_state) + + self.components_ = np.asarray( + rng.normal(0, 0.01, (self.n_components, X.shape[1])), + order="F", + dtype=X.dtype, + ) + self._n_features_out = self.components_.shape[0] + self.intercept_hidden_ = np.zeros(self.n_components, dtype=X.dtype) + self.intercept_visible_ = np.zeros(X.shape[1], dtype=X.dtype) + self.h_samples_ = np.zeros((self.batch_size, self.n_components), dtype=X.dtype) + + n_batches = int(np.ceil(float(n_samples) / self.batch_size)) + batch_slices = list( + gen_even_slices(n_batches * self.batch_size, n_batches, n_samples=n_samples) + ) + verbose = self.verbose + begin = time.time() + for iteration in range(1, self.n_iter + 1): + for batch_slice in batch_slices: + self._fit(X[batch_slice], rng) + + if verbose: + end = time.time() + print( + "[%s] Iteration %d, pseudo-likelihood = %.2f, time = %.2fs" + % ( + type(self).__name__, + iteration, + self.score_samples(X).mean(), + end - begin, + ) + ) + begin = end + + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + return tags diff --git a/shared/package-files/06/062ff42827438675946e1f4a5b01a82e457805327a161d054fc990538d4851af/test__shgo.py b/shared/package-files/06/062ff42827438675946e1f4a5b01a82e457805327a161d054fc990538d4851af/test__shgo.py new file mode 100644 index 0000000000000000000000000000000000000000..82efb74beee92eacc75f64c6c705374fa5ada322 --- /dev/null +++ b/shared/package-files/06/062ff42827438675946e1f4a5b01a82e457805327a161d054fc990538d4851af/test__shgo.py @@ -0,0 +1,1156 @@ +import logging +import sys + +import numpy as np +import time +from multiprocessing import Pool +from numpy.testing import assert_allclose, IS_PYPY +import pytest +from pytest import raises as assert_raises, warns +from scipy.optimize import (shgo, Bounds, minimize_scalar, minimize, rosen, + rosen_der, rosen_hess, NonlinearConstraint) +from scipy.optimize._constraints import new_constraint_to_old +from scipy.optimize._shgo import SHGO + + +class StructTestFunction: + def __init__(self, bounds, expected_x, expected_fun=None, + expected_xl=None, expected_funl=None): + self.bounds = bounds + self.expected_x = expected_x + self.expected_fun = expected_fun + self.expected_xl = expected_xl + self.expected_funl = expected_funl + + +def wrap_constraints(g): + cons = [] + if g is not None: + if not isinstance(g, (tuple, list)): + g = (g,) + else: + pass + for g in g: + cons.append({'type': 'ineq', + 'fun': g}) + cons = tuple(cons) + else: + cons = None + return cons + + +class StructTest1(StructTestFunction): + def f(self, x): + return x[0] ** 2 + x[1] ** 2 + + def g(x): + return -(np.sum(x, axis=0) - 6.0) + + cons = wrap_constraints(g) + + +test1_1 = StructTest1(bounds=[(-1, 6), (-1, 6)], + expected_x=[0, 0]) +test1_2 = StructTest1(bounds=[(0, 1), (0, 1)], + expected_x=[0, 0]) +test1_3 = StructTest1(bounds=[(None, None), (None, None)], + expected_x=[0, 0]) + + +class StructTest2(StructTestFunction): + """ + Scalar function with several minima to test all minimiser retrievals + """ + + def f(self, x): + return (x - 30) * np.sin(x) + + def g(x): + return 58 - np.sum(x, axis=0) + + cons = wrap_constraints(g) + + +test2_1 = StructTest2(bounds=[(0, 60)], + expected_x=[1.53567906], + expected_fun=-28.44677132, + # Important: test that funl return is in the correct + # order + expected_xl=np.array([[1.53567906], + [55.01782167], + [7.80894889], + [48.74797493], + [14.07445705], + [42.4913859], + [20.31743841], + [36.28607535], + [26.43039605], + [30.76371366]]), + + expected_funl=np.array([-28.44677132, -24.99785984, + -22.16855376, -18.72136195, + -15.89423937, -12.45154942, + -9.63133158, -6.20801301, + -3.43727232, -0.46353338]) + ) + +test2_2 = StructTest2(bounds=[(0, 4.5)], + expected_x=[1.53567906], + expected_fun=[-28.44677132], + expected_xl=np.array([[1.53567906]]), + expected_funl=np.array([-28.44677132]) + ) + + +class StructTest3(StructTestFunction): + """ + Hock and Schittkowski 18 problem (HS18). Hoch and Schittkowski (1981) + http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf + Minimize: f = 0.01 * (x_1)**2 + (x_2)**2 + + Subject to: x_1 * x_2 - 25.0 >= 0, + (x_1)**2 + (x_2)**2 - 25.0 >= 0, + 2 <= x_1 <= 50, + 0 <= x_2 <= 50. + + Approx. Answer: + f([(250)**0.5 , (2.5)**0.5]) = 5.0 + + + """ + + # amended to test vectorisation of constraints + def f(self, x): + return 0.01 * (x[0]) ** 2 + (x[1]) ** 2 + + def g1(x): + return x[0] * x[1] - 25.0 + + def g2(x): + return x[0] ** 2 + x[1] ** 2 - 25.0 + + # g = (g1, g2) + # cons = wrap_constraints(g) + + def g(x): + return x[0] * x[1] - 25.0, x[0] ** 2 + x[1] ** 2 - 25.0 + + # this checks that shgo can be sent new-style constraints + __nlc = NonlinearConstraint(g, 0, np.inf) + cons = (__nlc,) + +test3_1 = StructTest3(bounds=[(2, 50), (0, 50)], + expected_x=[250 ** 0.5, 2.5 ** 0.5], + expected_fun=5.0 + ) + + +class StructTest4(StructTestFunction): + """ + Hock and Schittkowski 11 problem (HS11). Hoch and Schittkowski (1981) + + NOTE: Did not find in original reference to HS collection, refer to + Henderson (2015) problem 7 instead. 02.03.2016 + """ + + def f(self, x): + return ((x[0] - 10) ** 2 + 5 * (x[1] - 12) ** 2 + x[2] ** 4 + + 3 * (x[3] - 11) ** 2 + 10 * x[4] ** 6 + 7 * x[5] ** 2 + x[ + 6] ** 4 + - 4 * x[5] * x[6] - 10 * x[5] - 8 * x[6] + ) + + def g1(x): + return -(2 * x[0] ** 2 + 3 * x[1] ** 4 + x[2] + 4 * x[3] ** 2 + + 5 * x[4] - 127) + + def g2(x): + return -(7 * x[0] + 3 * x[1] + 10 * x[2] ** 2 + x[3] - x[4] - 282.0) + + def g3(x): + return -(23 * x[0] + x[1] ** 2 + 6 * x[5] ** 2 - 8 * x[6] - 196) + + def g4(x): + return -(4 * x[0] ** 2 + x[1] ** 2 - 3 * x[0] * x[1] + 2 * x[2] ** 2 + + 5 * x[5] - 11 * x[6]) + + g = (g1, g2, g3, g4) + + cons = wrap_constraints(g) + + +test4_1 = StructTest4(bounds=[(-10, 10), ] * 7, + expected_x=[2.330499, 1.951372, -0.4775414, + 4.365726, -0.6244870, 1.038131, 1.594227], + expected_fun=680.6300573 + ) + + +class StructTest5(StructTestFunction): + def f(self, x): + return ( + -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0)))) + - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) + ) + + g = None + cons = wrap_constraints(g) + + +test5_1 = StructTest5(bounds=[(-512, 512), (-512, 512)], + expected_fun=[-959.64066272085051], + expected_x=[512., 404.23180542]) + + +class StructTestLJ(StructTestFunction): + """ + LennardJones objective function. Used to test symmetry constraints + settings. + """ + + def f(self, x, *args): + print(f'x = {x}') + self.N = args[0] + k = int(self.N / 3) + s = 0.0 + + for i in range(k - 1): + for j in range(i + 1, k): + a = 3 * i + b = 3 * j + xd = x[a] - x[b] + yd = x[a + 1] - x[b + 1] + zd = x[a + 2] - x[b + 2] + ed = xd * xd + yd * yd + zd * zd + ud = ed * ed * ed + if ed > 0.0: + s += (1.0 / ud - 2.0) / ud + + return s + + g = None + cons = wrap_constraints(g) + + +N = 6 +boundsLJ = list(zip([-4.0] * 6, [4.0] * 6)) + +testLJ = StructTestLJ(bounds=boundsLJ, + expected_fun=[-1.0], + expected_x=None, + # expected_x=[-2.71247337e-08, + # -2.71247337e-08, + # -2.50000222e+00, + # -2.71247337e-08, + # -2.71247337e-08, + # -1.50000222e+00] + ) + + +class StructTestS(StructTestFunction): + def f(self, x): + return ((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2 + + (x[2] - 0.5) ** 2 + (x[3] - 0.5) ** 2) + + g = None + cons = wrap_constraints(g) + + +test_s = StructTestS(bounds=[(0, 2.0), ] * 4, + expected_fun=0.0, + expected_x=np.ones(4) - 0.5 + ) + + +class StructTestTable(StructTestFunction): + def f(self, x): + if x[0] == 3.0 and x[1] == 3.0: + return 50 + else: + return 100 + + g = None + cons = wrap_constraints(g) + + +test_table = StructTestTable(bounds=[(-10, 10), (-10, 10)], + expected_fun=[50], + expected_x=[3.0, 3.0]) + + +class StructTestInfeasible(StructTestFunction): + """ + Test function with no feasible domain. + """ + + def f(self, x, *args): + return x[0] ** 2 + x[1] ** 2 + + def g1(x): + return x[0] + x[1] - 1 + + def g2(x): + return -(x[0] + x[1] - 1) + + def g3(x): + return -x[0] + x[1] - 1 + + def g4(x): + return -(-x[0] + x[1] - 1) + + g = (g1, g2, g3, g4) + cons = wrap_constraints(g) + + +test_infeasible = StructTestInfeasible(bounds=[(2, 50), (-1, 1)], + expected_fun=None, + expected_x=None + ) + + +@pytest.mark.skip("Not a test") +def run_test(test, args=(), test_atol=1e-5, n=100, iters=None, + callback=None, minimizer_kwargs=None, options=None, + sampling_method='sobol', workers=1): + res = shgo(test.f, test.bounds, args=args, constraints=test.cons, + n=n, iters=iters, callback=callback, + minimizer_kwargs=minimizer_kwargs, options=options, + sampling_method=sampling_method, workers=workers) + + print(f'res = {res}') + logging.info(f'res = {res}') + if test.expected_x is not None: + np.testing.assert_allclose(res.x, test.expected_x, + rtol=test_atol, + atol=test_atol) + + # (Optional tests) + if test.expected_fun is not None: + np.testing.assert_allclose(res.fun, + test.expected_fun, + atol=test_atol) + + if test.expected_xl is not None: + np.testing.assert_allclose(res.xl, + test.expected_xl, + atol=test_atol) + + if test.expected_funl is not None: + np.testing.assert_allclose(res.funl, + test.expected_funl, + atol=test_atol) + return + + +# Base test functions: +class TestShgoSobolTestFunctions: + """ + Global optimisation tests with Sobol sampling: + """ + + # Sobol algorithm + def test_f1_1_sobol(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]""" + run_test(test1_1) + + def test_f1_2_sobol(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]""" + run_test(test1_2) + + def test_f1_3_sobol(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(None, None),(None, None)]""" + options = {'disp': True} + run_test(test1_3, options=options) + + def test_f2_1_sobol(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]""" + run_test(test2_1) + + def test_f2_2_sobol(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]""" + run_test(test2_2) + + def test_f3_sobol(self): + """NLP: Hock and Schittkowski problem 18""" + run_test(test3_1) + + @pytest.mark.slow + def test_f4_sobol(self): + """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)""" + options = {'infty_constraints': False} + # run_test(test4_1, n=990, options=options) + run_test(test4_1, n=990 * 2, options=options) + + def test_f5_1_sobol(self): + """NLP: Eggholder, multimodal""" + # run_test(test5_1, n=30) + run_test(test5_1, n=60) + + def test_f5_2_sobol(self): + """NLP: Eggholder, multimodal""" + # run_test(test5_1, n=60, iters=5) + run_test(test5_1, n=60, iters=5) + + # def test_t911(self): + # """1D tabletop function""" + # run_test(test11_1) + + +class TestShgoSimplicialTestFunctions: + """ + Global optimisation tests with Simplicial sampling: + """ + + def test_f1_1_simplicial(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]""" + run_test(test1_1, n=1, sampling_method='simplicial') + + def test_f1_2_simplicial(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]""" + run_test(test1_2, n=1, sampling_method='simplicial') + + def test_f1_3_simplicial(self): + """Multivariate test function 1: x[0]**2 + x[1]**2 + with bounds=[(None, None),(None, None)]""" + run_test(test1_3, n=5, sampling_method='simplicial') + + def test_f2_1_simplicial(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]""" + options = {'minimize_every_iter': False} + run_test(test2_1, n=200, iters=7, options=options, + sampling_method='simplicial') + + def test_f2_2_simplicial(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]""" + run_test(test2_2, n=1, sampling_method='simplicial') + + def test_f3_simplicial(self): + """NLP: Hock and Schittkowski problem 18""" + run_test(test3_1, n=1, sampling_method='simplicial') + + @pytest.mark.slow + def test_f4_simplicial(self): + """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)""" + run_test(test4_1, n=1, sampling_method='simplicial') + + def test_lj_symmetry_old(self): + """LJ: Symmetry-constrained test function""" + options = {'symmetry': True, + 'disp': True} + args = (6,) # Number of atoms + run_test(testLJ, args=args, n=300, + options=options, iters=1, + sampling_method='simplicial') + + def test_f5_1_lj_symmetry(self): + """LJ: Symmetry constrained test function""" + options = {'symmetry': [0, ] * 6, + 'disp': True} + args = (6,) # No. of atoms + + run_test(testLJ, args=args, n=300, + options=options, iters=1, + sampling_method='simplicial') + + def test_f5_2_cons_symmetry(self): + """Symmetry constrained test function""" + options = {'symmetry': [0, 0], + 'disp': True} + + run_test(test1_1, n=200, + options=options, iters=1, + sampling_method='simplicial') + + @pytest.mark.fail_slow(10) + def test_f5_3_cons_symmetry(self): + """Asymmetrically constrained test function""" + options = {'symmetry': [0, 0, 0, 3], + 'disp': True} + + run_test(test_s, n=10000, + options=options, + iters=1, + sampling_method='simplicial') + + @pytest.mark.skip("Not a test") + def test_f0_min_variance(self): + """Return a minimum on a perfectly symmetric problem, based on + gh10429""" + avg = 0.5 # Given average value of x + cons = {'type': 'eq', 'fun': lambda x: np.mean(x) - avg} + + # Minimize the variance of x under the given constraint + res = shgo(np.var, bounds=6 * [(0, 1)], constraints=cons) + assert res.success + assert_allclose(res.fun, 0, atol=1e-15) + assert_allclose(res.x, 0.5) + + @pytest.mark.skip("Not a test") + def test_f0_min_variance_1D(self): + """Return a minimum on a perfectly symmetric 1D problem, based on + gh10538""" + + def fun(x): + return x * (x - 1.0) * (x - 0.5) + + bounds = [(0, 1)] + res = shgo(fun, bounds=bounds) + ref = minimize_scalar(fun, bounds=bounds[0]) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x, rtol=1e-6) + +# Argument test functions +class TestShgoArguments: + def test_1_1_simpl_iter(self): + """Iterative simplicial sampling on TestFunction 1 (multivariate)""" + run_test(test1_2, n=None, iters=2, sampling_method='simplicial') + + def test_1_2_simpl_iter(self): + """Iterative simplicial on TestFunction 2 (univariate)""" + options = {'minimize_every_iter': False} + run_test(test2_1, n=None, iters=9, options=options, + sampling_method='simplicial') + + def test_2_1_sobol_iter(self): + """Iterative Sobol sampling on TestFunction 1 (multivariate)""" + run_test(test1_2, n=None, iters=1, sampling_method='sobol') + + def test_2_2_sobol_iter(self): + """Iterative Sobol sampling on TestFunction 2 (univariate)""" + res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons, + n=None, iters=1, sampling_method='sobol') + + np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(res.fun, test2_1.expected_fun, atol=1e-5) + + def test_3_1_disp_simplicial(self): + """Iterative sampling on TestFunction 1 and 2 (multi and univariate) + """ + + def callback_func(x): + print("Local minimization callback test") + + for test in [test1_1, test2_1]: + shgo(test.f, test.bounds, iters=1, + sampling_method='simplicial', + callback=callback_func, options={'disp': True}) + shgo(test.f, test.bounds, n=1, sampling_method='simplicial', + callback=callback_func, options={'disp': True}) + + def test_3_2_disp_sobol(self): + """Iterative sampling on TestFunction 1 and 2 (multi and univariate)""" + + def callback_func(x): + print("Local minimization callback test") + + for test in [test1_1, test2_1]: + shgo(test.f, test.bounds, iters=1, sampling_method='sobol', + callback=callback_func, options={'disp': True}) + + shgo(test.f, test.bounds, n=1, sampling_method='simplicial', + callback=callback_func, options={'disp': True}) + + def test_args_gh14589(self): + """Using `args` used to cause `shgo` to fail; see #14589, #15986, + #16506""" + res = shgo(func=lambda x, y, z: x * z + y, bounds=[(0, 3)], args=(1, 2) + ) + ref = shgo(func=lambda x: 2 * x + 1, bounds=[(0, 3)]) + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x) + + @pytest.mark.slow + def test_4_1_known_f_min(self): + """Test known function minima stopping criteria""" + # Specify known function value + options = {'f_min': test4_1.expected_fun, + 'f_tol': 1e-6, + 'minimize_every_iter': True} + # TODO: Make default n higher for faster tests + run_test(test4_1, n=None, test_atol=1e-5, options=options, + sampling_method='simplicial') + + @pytest.mark.slow + def test_4_2_known_f_min(self): + """Test Global mode limiting local evaluations""" + options = { # Specify known function value + 'f_min': test4_1.expected_fun, + 'f_tol': 1e-6, + # Specify number of local iterations to perform + 'minimize_every_iter': True, + 'local_iter': 1} + + run_test(test4_1, n=None, test_atol=1e-5, options=options, + sampling_method='simplicial') + + def test_4_4_known_f_min(self): + """Test Global mode limiting local evaluations for 1D funcs""" + options = { # Specify known function value + 'f_min': test2_1.expected_fun, + 'f_tol': 1e-6, + # Specify number of local iterations to perform+ + 'minimize_every_iter': True, + 'local_iter': 1, + 'infty_constraints': False} + + res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons, + n=None, iters=None, options=options, + sampling_method='sobol') + np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5) + + def test_5_1_simplicial_argless(self): + """Test Default simplicial sampling settings on TestFunction 1""" + res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons) + np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5) + + def test_5_2_sobol_argless(self): + """Test Default sobol sampling settings on TestFunction 1""" + res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons, + sampling_method='sobol') + np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5) + + def test_6_1_simplicial_max_iter(self): + """Test that maximum iteration option works on TestFunction 3""" + options = {'max_iter': 2} + res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons, + options=options, sampling_method='simplicial') + np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5) + + def test_6_2_simplicial_min_iter(self): + """Test that maximum iteration option works on TestFunction 3""" + options = {'min_iter': 2} + res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons, + options=options, sampling_method='simplicial') + np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5) + + def test_7_1_minkwargs(self): + """Test the minimizer_kwargs arguments for solvers with constraints""" + # Test solvers + for solver in ['COBYLA', 'COBYQA', 'SLSQP']: + # Note that passing global constraints to SLSQP is tested in other + # unittests which run test4_1 normally + minimizer_kwargs = {'method': solver, + 'constraints': test3_1.cons} + run_test(test3_1, n=100, test_atol=1e-3, + minimizer_kwargs=minimizer_kwargs, + sampling_method='sobol') + + def test_7_2_minkwargs(self): + """Test the minimizer_kwargs default inits""" + minimizer_kwargs = {'ftol': 1e-5} + options = {'disp': True} # For coverage purposes + SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0], + minimizer_kwargs=minimizer_kwargs, options=options) + + def test_7_3_minkwargs(self): + """Test minimizer_kwargs arguments for solvers without constraints""" + for solver in ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', + 'L-BFGS-B', 'TNC', 'dogleg', 'trust-ncg', 'trust-exact', + 'trust-krylov']: + def jac(x): + return np.array([2 * x[0], 2 * x[1]]).T + + def hess(x): + return np.array([[2, 0], [0, 2]]) + + minimizer_kwargs = {'method': solver, + 'jac': jac, + 'hess': hess} + logging.info(f"Solver = {solver}") + logging.info("=" * 100) + run_test(test1_1, n=100, test_atol=1e-3, + minimizer_kwargs=minimizer_kwargs, + sampling_method='sobol') + + def test_8_homology_group_diff(self): + options = {'minhgrd': 1, + 'minimize_every_iter': True} + + run_test(test1_1, n=None, iters=None, options=options, + sampling_method='simplicial') + + def test_9_cons_g(self): + """Test single function constraint passing""" + SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0]) + + @pytest.mark.xfail(IS_PYPY and sys.platform == 'win32', + reason="Failing and fix in PyPy not planned (see gh-18632)") + def test_10_finite_time(self): + """Test single function constraint passing""" + options = {'maxtime': 1e-15} + + def f(x): + time.sleep(1e-14) + return 0.0 + + res = shgo(f, test1_1.bounds, iters=5, options=options) + # Assert that only 1 rather than 5 requested iterations ran: + assert res.nit == 1 + + def test_11_f_min_0(self): + """Test to cover the case where f_lowest == 0""" + options = {'f_min': 0.0, + 'disp': True} + res = shgo(test1_2.f, test1_2.bounds, n=10, iters=None, + options=options, sampling_method='sobol') + np.testing.assert_equal(0, res.x[0]) + np.testing.assert_equal(0, res.x[1]) + + # @nottest + @pytest.mark.skip(reason="no way of currently testing this") + def test_12_sobol_inf_cons(self): + """Test to cover the case where f_lowest == 0""" + # TODO: This test doesn't cover anything new, it is unknown what the + # original test was intended for as it was never complete. Delete or + # replace in the future. + options = {'maxtime': 1e-15, + 'f_min': 0.0} + res = shgo(test1_2.f, test1_2.bounds, n=1, iters=None, + options=options, sampling_method='sobol') + np.testing.assert_equal(0.0, res.fun) + + def test_13_high_sobol(self): + """Test init of high-dimensional sobol sequences""" + + def f(x): + return 0 + + bounds = [(None, None), ] * 41 + SHGOc = SHGO(f, bounds, sampling_method='sobol') + # SHGOc.sobol_points(2, 50) + SHGOc.sampling_function(2, 50) + + def test_14_local_iter(self): + """Test limited local iterations for a pseudo-global mode""" + options = {'local_iter': 4} + run_test(test5_1, n=60, options=options) + + def test_15_min_every_iter(self): + """Test minimize every iter options and cover function cache""" + options = {'minimize_every_iter': True} + run_test(test1_1, n=1, iters=7, options=options, + sampling_method='sobol') + + def test_16_disp_bounds_minimizer(self, capsys): + """Test disp=True with minimizers that do not support bounds """ + options = {'disp': True} + minimizer_kwargs = {'method': 'nelder-mead'} + run_test(test1_2, sampling_method='simplicial', + options=options, minimizer_kwargs=minimizer_kwargs) + + def test_17_custom_sampling(self): + """Test the functionality to add custom sampling methods to shgo""" + + def sample(n, d): + return np.random.uniform(size=(n, d)) + + run_test(test1_1, n=30, sampling_method=sample) + + def test_18_bounds_class(self): + # test that new and old bounds yield same result + def f(x): + return np.square(x).sum() + + lb = [-6., 1., -5.] + ub = [-1., 3., 5.] + bounds_old = list(zip(lb, ub)) + bounds_new = Bounds(lb, ub) + + res_old_bounds = shgo(f, bounds_old) + res_new_bounds = shgo(f, bounds_new) + + assert res_new_bounds.nfev == res_old_bounds.nfev + assert res_new_bounds.message == res_old_bounds.message + assert res_new_bounds.success == res_old_bounds.success + x_opt = np.array([-1., 1., 0.]) + np.testing.assert_allclose(res_new_bounds.x, x_opt) + np.testing.assert_allclose(res_new_bounds.x, res_old_bounds.x) + + @pytest.mark.fail_slow(10) + def test_19_parallelization(self): + """Test the functionality to add custom sampling methods to shgo""" + + with Pool(2) as p: + run_test(test1_1, n=30, workers=p.map) # Constrained + run_test(test1_1, n=30, workers=map) # Constrained + with Pool(2) as p: + run_test(test_s, n=30, workers=p.map) # Unconstrained + run_test(test_s, n=30, workers=map) # Unconstrained + + def test_20_constrained_args(self): + """Test that constraints can be passed to arguments""" + + def eggholder(x): + return ( + -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0] / 2.0 + (x[1] + 47.0)))) + - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) + ) + + def f(x): # (cattle-feed) + return 24.55 * x[0] + 26.75 * x[1] + 39 * x[2] + 40.50 * x[3] + + bounds = [(0, 1.0), ] * 4 + + def g1_modified(x, i): + return i * 2.3 * x[0] + i * 5.6 * x[1] + 11.1 * x[2] + 1.3 * x[ + 3] - 5 # >=0 + + def g2(x): + return ( + 12*x[0] + 11.9*x[1] + 41.8*x[2] + 52.1*x[3] - 21 + - 1.645*np.sqrt( + 0.28*x[0]**2 + 0.19*x[1]**2 + 20.5*x[2]**2 + 0.62*x[3]**2 + ) + ) # >=0 + + def h1(x): + return x[0] + x[1] + x[2] + x[3] - 1 # == 0 + + cons = ({'type': 'ineq', 'fun': g1_modified, "args": (0,)}, + {'type': 'ineq', 'fun': g2}, + {'type': 'eq', 'fun': h1}) + + shgo(f, bounds, n=300, iters=1, constraints=cons) + # using constrain with arguments AND sampling method sobol + shgo(f, bounds, n=300, iters=1, constraints=cons, + sampling_method='sobol') + + def test_21_1_jac_true(self): + """Test that shgo can handle objective functions that return the + gradient alongside the objective value. Fixes gh-13547""" + # previous + def func(x): + return np.sum(np.power(x, 2)), 2 * x + + shgo( + func, + bounds=[[-1, 1], [1, 2]], + n=100, iters=5, + sampling_method="sobol", + minimizer_kwargs={'method': 'SLSQP', 'jac': True} + ) + + # new + def func(x): + return np.sum(x ** 2), 2 * x + + bounds = [[-1, 1], [1, 2], [-1, 1], [1, 2], [0, 3]] + + res = shgo(func, bounds=bounds, sampling_method="sobol", + minimizer_kwargs={'method': 'SLSQP', 'jac': True}) + ref = minimize(func, x0=[1, 1, 1, 1, 1], bounds=bounds, + jac=True) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x, atol=1e-15) + + @pytest.mark.parametrize('derivative', ['jac', 'hess', 'hessp']) + def test_21_2_derivative_options(self, derivative): + """shgo used to raise an error when passing `options` with 'jac' + # see gh-12963. check that this is resolved + """ + + def objective(x): + return 3 * x[0] * x[0] + 2 * x[0] + 5 + + def gradient(x): + return 6 * x[0] + 2 + + def hess(x): + return 6 + + def hessp(x, p): + return 6 * p + + derivative_funcs = {'jac': gradient, 'hess': hess, 'hessp': hessp} + options = {derivative: derivative_funcs[derivative]} + minimizer_kwargs = {'method': 'trust-constr'} + + bounds = [(-100, 100)] + res = shgo(objective, bounds, minimizer_kwargs=minimizer_kwargs, + options=options) + ref = minimize(objective, x0=[0], bounds=bounds, **minimizer_kwargs, + **options) + + assert res.success + np.testing.assert_allclose(res.fun, ref.fun) + np.testing.assert_allclose(res.x, ref.x) + + def test_21_3_hess_options_rosen(self): + """Ensure the Hessian gets passed correctly to the local minimizer + routine. Previous report gh-14533. + """ + bounds = [(0, 1.6), (0, 1.6), (0, 1.4), (0, 1.4), (0, 1.4)] + options = {'jac': rosen_der, 'hess': rosen_hess} + minimizer_kwargs = {'method': 'Newton-CG'} + res = shgo(rosen, bounds, minimizer_kwargs=minimizer_kwargs, + options=options) + ref = minimize(rosen, np.zeros(5), method='Newton-CG', + **options) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x, atol=1e-15) + + def test_21_arg_tuple_sobol(self): + """shgo used to raise an error when passing `args` with Sobol sampling + # see gh-12114. check that this is resolved""" + + def fun(x, k): + return x[0] ** k + + constraints = ({'type': 'ineq', 'fun': lambda x: x[0] - 1}) + + bounds = [(0, 10)] + res = shgo(fun, bounds, args=(1,), constraints=constraints, + sampling_method='sobol') + ref = minimize(fun, np.zeros(1), bounds=bounds, args=(1,), + constraints=constraints) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x) + + +# Failure test functions +class TestShgoFailures: + def test_1_maxiter(self): + """Test failure on insufficient iterations""" + options = {'maxiter': 2} + res = shgo(test4_1.f, test4_1.bounds, n=2, iters=None, + options=options, sampling_method='sobol') + + np.testing.assert_equal(False, res.success) + # np.testing.assert_equal(4, res.nfev) + np.testing.assert_equal(4, res.tnev) + + def test_2_sampling(self): + """Rejection of unknown sampling method""" + assert_raises(ValueError, shgo, test1_1.f, test1_1.bounds, + sampling_method='not_Sobol') + + def test_3_1_no_min_pool_sobol(self): + """Check that the routine stops when no minimiser is found + after maximum specified function evaluations""" + options = {'maxfev': 10, + # 'maxev': 10, + 'disp': True} + res = shgo(test_table.f, test_table.bounds, n=3, options=options, + sampling_method='sobol') + np.testing.assert_equal(False, res.success) + # np.testing.assert_equal(9, res.nfev) + np.testing.assert_equal(12, res.nfev) + + def test_3_2_no_min_pool_simplicial(self): + """Check that the routine stops when no minimiser is found + after maximum specified sampling evaluations""" + options = {'maxev': 10, + 'disp': True} + res = shgo(test_table.f, test_table.bounds, n=3, options=options, + sampling_method='simplicial') + np.testing.assert_equal(False, res.success) + + def test_4_1_bound_err(self): + """Specified bounds ub > lb""" + bounds = [(6, 3), (3, 5)] + assert_raises(ValueError, shgo, test1_1.f, bounds) + + def test_4_2_bound_err(self): + """Specified bounds are of the form (lb, ub)""" + bounds = [(3, 5, 5), (3, 5)] + assert_raises(ValueError, shgo, test1_1.f, bounds) + + def test_5_1_1_infeasible_sobol(self): + """Ensures the algorithm terminates on infeasible problems + after maxev is exceeded. Use infty constraints option""" + options = {'maxev': 100, + 'disp': True} + + res = shgo(test_infeasible.f, test_infeasible.bounds, + constraints=test_infeasible.cons, n=100, options=options, + sampling_method='sobol') + + np.testing.assert_equal(False, res.success) + + def test_5_1_2_infeasible_sobol(self): + """Ensures the algorithm terminates on infeasible problems + after maxev is exceeded. Do not use infty constraints option""" + options = {'maxev': 100, + 'disp': True, + 'infty_constraints': False} + + res = shgo(test_infeasible.f, test_infeasible.bounds, + constraints=test_infeasible.cons, n=100, options=options, + sampling_method='sobol') + + np.testing.assert_equal(False, res.success) + + def test_5_2_infeasible_simplicial(self): + """Ensures the algorithm terminates on infeasible problems + after maxev is exceeded.""" + options = {'maxev': 1000, + 'disp': False} + + res = shgo(test_infeasible.f, test_infeasible.bounds, + constraints=test_infeasible.cons, n=100, options=options, + sampling_method='simplicial') + + np.testing.assert_equal(False, res.success) + + @pytest.mark.thread_unsafe + def test_6_1_lower_known_f_min(self): + """Test Global mode limiting local evaluations with f* too high""" + options = { # Specify known function value + 'f_min': test2_1.expected_fun + 2.0, + 'f_tol': 1e-6, + # Specify number of local iterations to perform+ + 'minimize_every_iter': True, + 'local_iter': 1, + 'infty_constraints': False} + args = (test2_1.f, test2_1.bounds) + kwargs = {'constraints': test2_1.cons, + 'n': None, + 'iters': None, + 'options': options, + 'sampling_method': 'sobol' + } + warns(UserWarning, shgo, *args, **kwargs) + + def test(self): + from scipy.optimize import rosen, shgo + bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)] + + def fun(x): + fun.nfev += 1 + return rosen(x) + + fun.nfev = 0 + + result = shgo(fun, bounds) + print(result.x, result.fun, fun.nfev) # 50 + + +# Returns +class TestShgoReturns: + def test_1_nfev_simplicial(self): + bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)] + + def fun(x): + fun.nfev += 1 + return rosen(x) + + fun.nfev = 0 + + result = shgo(fun, bounds) + np.testing.assert_equal(fun.nfev, result.nfev) + + def test_1_nfev_sobol(self): + bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)] + + def fun(x): + fun.nfev += 1 + return rosen(x) + + fun.nfev = 0 + + result = shgo(fun, bounds, sampling_method='sobol') + np.testing.assert_equal(fun.nfev, result.nfev) + + +def test_vector_constraint(): + # gh15514 + def quad(x): + x = np.asarray(x) + return [np.sum(x ** 2)] + + nlc = NonlinearConstraint(quad, [2.2], [3]) + oldc = new_constraint_to_old(nlc, np.array([1.0, 1.0])) + + res = shgo(rosen, [(0, 10), (0, 10)], constraints=oldc, sampling_method='sobol') + assert np.all(np.sum((res.x)**2) >= 2.2) + assert np.all(np.sum((res.x) ** 2) <= 3.0) + assert res.success + + +@pytest.mark.filterwarnings("ignore:delta_grad") +def test_trust_constr(): + def quad(x): + x = np.asarray(x) + return [np.sum(x ** 2)] + + nlc = NonlinearConstraint(quad, [2.6], [3]) + minimizer_kwargs = {'method': 'trust-constr'} + # note that we don't supply the constraints in minimizer_kwargs, + # so if the final result obeys the constraints we know that shgo + # passed them on to 'trust-constr' + res = shgo( + rosen, + [(0, 10), (0, 10)], + constraints=nlc, + sampling_method='sobol', + minimizer_kwargs=minimizer_kwargs + ) + assert np.all(np.sum((res.x)**2) >= 2.6) + assert np.all(np.sum((res.x) ** 2) <= 3.0) + assert res.success + + +def test_equality_constraints(): + # gh16260 + bounds = [(0.9, 4.0)] * 2 # Constrain probabilities to 0 and 1. + + def faulty(x): + return x[0] + x[1] + + nlc = NonlinearConstraint(faulty, 3.9, 3.9) + res = shgo(rosen, bounds=bounds, constraints=nlc) + assert_allclose(np.sum(res.x), 3.9) + + def faulty(x): + return x[0] + x[1] - 3.9 + + constraints = {'type': 'eq', 'fun': faulty} + res = shgo(rosen, bounds=bounds, constraints=constraints) + assert_allclose(np.sum(res.x), 3.9) + + bounds = [(0, 1.0)] * 4 + # sum of variable should equal 1. + def faulty(x): + return x[0] + x[1] + x[2] + x[3] - 1 + + # options = {'minimize_every_iter': True, 'local_iter':10} + constraints = {'type': 'eq', 'fun': faulty} + res = shgo( + lambda x: - np.prod(x), + bounds=bounds, + constraints=constraints, + sampling_method='sobol' + ) + assert_allclose(np.sum(res.x), 1.0) + +def test_gh16971(): + def cons(x): + return np.sum(x**2) - 0 + + c = {'fun': cons, 'type': 'ineq'} + minimizer_kwargs = { + 'method': 'COBYLA', + 'options': {'rhobeg': 5, 'tol': 5e-1, 'catol': 0.05} + } + + s = SHGO( + rosen, [(0, 10)]*2, constraints=c, minimizer_kwargs=minimizer_kwargs + ) + + assert s.minimizer_kwargs['method'].lower() == 'cobyla' + assert s.minimizer_kwargs['options']['catol'] == 0.05 diff --git a/shared/package-files/06/0638a95de3398b9d3c9cc2ac7345556beb7d2c946ebeed367b3467f88e7642f6/mm_native.h b/shared/package-files/06/0638a95de3398b9d3c9cc2ac7345556beb7d2c946ebeed367b3467f88e7642f6/mm_native.h new file mode 100644 index 0000000000000000000000000000000000000000..fe54d62b75e1fd45c122cc900ffbaf3c6072dcff --- /dev/null +++ b/shared/package-files/06/0638a95de3398b9d3c9cc2ac7345556beb7d2c946ebeed367b3467f88e7642f6/mm_native.h @@ -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 { +struct TORCH_API structured_mm_out_cpu : public at::meta::structured_mm { +void impl(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out); +}; +struct TORCH_API structured_mm_out_cuda : public at::meta::structured_mm { +void impl(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out); +}; +TORCH_API at::Tensor _sparse_mm(const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & _sparse_mm_out(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); +TORCH_API at::Tensor _sparse_csr_mm(const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & _sparse_csr_mm_out(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/063bc02a80235e17483eec69635db81c9205b300dbd29abc0e3ca7cc9395c2a7/_macos.py b/shared/package-files/06/063bc02a80235e17483eec69635db81c9205b300dbd29abc0e3ca7cc9395c2a7/_macos.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc440bf3627641f71723bba5bc254aeb983d856 --- /dev/null +++ b/shared/package-files/06/063bc02a80235e17483eec69635db81c9205b300dbd29abc0e3ca7cc9395c2a7/_macos.py @@ -0,0 +1,501 @@ +import contextlib +import ctypes +import platform +import ssl +import typing +from ctypes import ( + CDLL, + POINTER, + c_bool, + c_char_p, + c_int32, + c_long, + c_uint32, + c_ulong, + c_void_p, +) +from ctypes.util import find_library + +from ._ssl_constants import _set_ssl_context_verify_mode + +_mac_version = platform.mac_ver()[0] +_mac_version_info = tuple(map(int, _mac_version.split("."))) +if _mac_version_info < (10, 8): + raise ImportError( + f"Only OS X 10.8 and newer are supported, not {_mac_version_info[0]}.{_mac_version_info[1]}" + ) + + +def _load_cdll(name: str, macos10_16_path: str) -> CDLL: + """Loads a CDLL by name, falling back to known path on 10.16+""" + try: + # Big Sur is technically 11 but we use 10.16 due to the Big Sur + # beta being labeled as 10.16. + path: str | None + if _mac_version_info >= (10, 16): + path = macos10_16_path + else: + path = find_library(name) + if not path: + raise OSError # Caught and reraised as 'ImportError' + return CDLL(path, use_errno=True) + except OSError: + raise ImportError(f"The library {name} failed to load") from None + + +Security = _load_cdll( + "Security", "/System/Library/Frameworks/Security.framework/Security" +) +CoreFoundation = _load_cdll( + "CoreFoundation", + "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", +) + +Boolean = c_bool +CFIndex = c_long +CFStringEncoding = c_uint32 +CFData = c_void_p +CFString = c_void_p +CFArray = c_void_p +CFMutableArray = c_void_p +CFError = c_void_p +CFType = c_void_p +CFTypeID = c_ulong +CFTypeRef = POINTER(CFType) +CFAllocatorRef = c_void_p + +OSStatus = c_int32 + +CFErrorRef = POINTER(CFError) +CFDataRef = POINTER(CFData) +CFStringRef = POINTER(CFString) +CFArrayRef = POINTER(CFArray) +CFMutableArrayRef = POINTER(CFMutableArray) +CFArrayCallBacks = c_void_p +CFOptionFlags = c_uint32 + +SecCertificateRef = POINTER(c_void_p) +SecPolicyRef = POINTER(c_void_p) +SecTrustRef = POINTER(c_void_p) +SecTrustResultType = c_uint32 +SecTrustOptionFlags = c_uint32 + +try: + Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef] + Security.SecCertificateCreateWithData.restype = SecCertificateRef + + Security.SecCertificateCopyData.argtypes = [SecCertificateRef] + Security.SecCertificateCopyData.restype = CFDataRef + + Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p] + Security.SecCopyErrorMessageString.restype = CFStringRef + + Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef] + Security.SecTrustSetAnchorCertificates.restype = OSStatus + + Security.SecTrustSetAnchorCertificatesOnly.argtypes = [SecTrustRef, Boolean] + Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus + + Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)] + Security.SecTrustEvaluate.restype = OSStatus + + Security.SecPolicyCreateRevocation.argtypes = [CFOptionFlags] + Security.SecPolicyCreateRevocation.restype = SecPolicyRef + + Security.SecPolicyCreateSSL.argtypes = [Boolean, CFStringRef] + Security.SecPolicyCreateSSL.restype = SecPolicyRef + + Security.SecTrustCreateWithCertificates.argtypes = [ + CFTypeRef, + CFTypeRef, + POINTER(SecTrustRef), + ] + Security.SecTrustCreateWithCertificates.restype = OSStatus + + Security.SecTrustGetTrustResult.argtypes = [ + SecTrustRef, + POINTER(SecTrustResultType), + ] + Security.SecTrustGetTrustResult.restype = OSStatus + + Security.SecTrustRef = SecTrustRef # type: ignore[attr-defined] + Security.SecTrustResultType = SecTrustResultType # type: ignore[attr-defined] + Security.OSStatus = OSStatus # type: ignore[attr-defined] + + kSecRevocationUseAnyAvailableMethod = 3 + kSecRevocationRequirePositiveResponse = 8 + + CoreFoundation.CFRelease.argtypes = [CFTypeRef] + CoreFoundation.CFRelease.restype = None + + CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef] + CoreFoundation.CFGetTypeID.restype = CFTypeID + + CoreFoundation.CFStringCreateWithCString.argtypes = [ + CFAllocatorRef, + c_char_p, + CFStringEncoding, + ] + CoreFoundation.CFStringCreateWithCString.restype = CFStringRef + + CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding] + CoreFoundation.CFStringGetCStringPtr.restype = c_char_p + + CoreFoundation.CFStringGetCString.argtypes = [ + CFStringRef, + c_char_p, + CFIndex, + CFStringEncoding, + ] + CoreFoundation.CFStringGetCString.restype = c_bool + + CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex] + CoreFoundation.CFDataCreate.restype = CFDataRef + + CoreFoundation.CFDataGetLength.argtypes = [CFDataRef] + CoreFoundation.CFDataGetLength.restype = CFIndex + + CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef] + CoreFoundation.CFDataGetBytePtr.restype = c_void_p + + CoreFoundation.CFArrayCreate.argtypes = [ + CFAllocatorRef, + POINTER(CFTypeRef), + CFIndex, + CFArrayCallBacks, + ] + CoreFoundation.CFArrayCreate.restype = CFArrayRef + + CoreFoundation.CFArrayCreateMutable.argtypes = [ + CFAllocatorRef, + CFIndex, + CFArrayCallBacks, + ] + CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef + + CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p] + CoreFoundation.CFArrayAppendValue.restype = None + + CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef] + CoreFoundation.CFArrayGetCount.restype = CFIndex + + CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex] + CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p + + CoreFoundation.CFErrorGetCode.argtypes = [CFErrorRef] + CoreFoundation.CFErrorGetCode.restype = CFIndex + + CoreFoundation.CFErrorCopyDescription.argtypes = [CFErrorRef] + CoreFoundation.CFErrorCopyDescription.restype = CFStringRef + + CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( # type: ignore[attr-defined] + CoreFoundation, "kCFAllocatorDefault" + ) + CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( # type: ignore[attr-defined] + CoreFoundation, "kCFTypeArrayCallBacks" + ) + + CoreFoundation.CFTypeRef = CFTypeRef # type: ignore[attr-defined] + CoreFoundation.CFArrayRef = CFArrayRef # type: ignore[attr-defined] + CoreFoundation.CFStringRef = CFStringRef # type: ignore[attr-defined] + CoreFoundation.CFErrorRef = CFErrorRef # type: ignore[attr-defined] + +except AttributeError: + raise ImportError("Error initializing ctypes") from None + + +def _handle_osstatus(result: OSStatus, _: typing.Any, args: typing.Any) -> typing.Any: + """ + Raises an error if the OSStatus value is non-zero. + """ + if int(result) == 0: + return args + + # Returns a CFString which we need to transform + # into a UTF-8 Python string. + error_message_cfstring = None + try: + error_message_cfstring = Security.SecCopyErrorMessageString(result, None) + + # First step is convert the CFString into a C string pointer. + # We try the fast no-copy way first. + error_message_cfstring_c_void_p = ctypes.cast( + error_message_cfstring, ctypes.POINTER(ctypes.c_void_p) + ) + message = CoreFoundation.CFStringGetCStringPtr( + error_message_cfstring_c_void_p, CFConst.kCFStringEncodingUTF8 + ) + + # Quoting the Apple dev docs: + # + # "A pointer to a C string or NULL if the internal + # storage of theString does not allow this to be + # returned efficiently." + # + # So we need to get our hands dirty. + if message is None: + buffer = ctypes.create_string_buffer(1024) + result = CoreFoundation.CFStringGetCString( + error_message_cfstring_c_void_p, + buffer, + 1024, + CFConst.kCFStringEncodingUTF8, + ) + if not result: + raise OSError("Error copying C string from CFStringRef") + message = buffer.value + + finally: + if error_message_cfstring is not None: + CoreFoundation.CFRelease(error_message_cfstring) + + # If no message can be found for this status we come + # up with a generic one that forwards the status code. + if message is None or message == "": + message = f"SecureTransport operation returned a non-zero OSStatus: {result}" + + raise ssl.SSLError(message) + + +Security.SecTrustCreateWithCertificates.errcheck = _handle_osstatus # type: ignore[assignment] +Security.SecTrustSetAnchorCertificates.errcheck = _handle_osstatus # type: ignore[assignment] +Security.SecTrustGetTrustResult.errcheck = _handle_osstatus # type: ignore[assignment] + + +class CFConst: + """CoreFoundation constants""" + + kCFStringEncodingUTF8 = CFStringEncoding(0x08000100) + + errSecIncompleteCertRevocationCheck = -67635 + errSecHostNameMismatch = -67602 + errSecCertificateExpired = -67818 + errSecNotTrusted = -67843 + + +def _bytes_to_cf_data_ref(value: bytes) -> CFDataRef: # type: ignore[valid-type] + return CoreFoundation.CFDataCreate( # type: ignore[no-any-return] + CoreFoundation.kCFAllocatorDefault, value, len(value) + ) + + +def _bytes_to_cf_string(value: bytes) -> CFString: + """ + Given a Python binary data, create a CFString. + The string must be CFReleased by the caller. + """ + c_str = ctypes.c_char_p(value) + cf_str = CoreFoundation.CFStringCreateWithCString( + CoreFoundation.kCFAllocatorDefault, + c_str, + CFConst.kCFStringEncodingUTF8, + ) + return cf_str # type: ignore[no-any-return] + + +def _cf_string_ref_to_str(cf_string_ref: CFStringRef) -> str | None: # type: ignore[valid-type] + """ + Creates a Unicode string from a CFString object. Used entirely for error + reporting. + Yes, it annoys me quite a lot that this function is this complex. + """ + + string = CoreFoundation.CFStringGetCStringPtr( + cf_string_ref, CFConst.kCFStringEncodingUTF8 + ) + if string is None: + buffer = ctypes.create_string_buffer(1024) + result = CoreFoundation.CFStringGetCString( + cf_string_ref, buffer, 1024, CFConst.kCFStringEncodingUTF8 + ) + if not result: + raise OSError("Error copying C string from CFStringRef") + string = buffer.value + if string is not None: + string = string.decode("utf-8") + return string # type: ignore[no-any-return] + + +def _der_certs_to_cf_cert_array(certs: list[bytes]) -> CFMutableArrayRef: # type: ignore[valid-type] + """Builds a CFArray of SecCertificateRefs from a list of DER-encoded certificates. + Responsibility of the caller to call CoreFoundation.CFRelease on the CFArray. + """ + cf_array = CoreFoundation.CFArrayCreateMutable( + CoreFoundation.kCFAllocatorDefault, + 0, + ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), + ) + if not cf_array: + raise MemoryError("Unable to allocate memory!") + + for cert_data in certs: + cf_data = None + sec_cert_ref = None + try: + cf_data = _bytes_to_cf_data_ref(cert_data) + sec_cert_ref = Security.SecCertificateCreateWithData( + CoreFoundation.kCFAllocatorDefault, cf_data + ) + CoreFoundation.CFArrayAppendValue(cf_array, sec_cert_ref) + finally: + if cf_data: + CoreFoundation.CFRelease(cf_data) + if sec_cert_ref: + CoreFoundation.CFRelease(sec_cert_ref) + + return cf_array # type: ignore[no-any-return] + + +@contextlib.contextmanager +def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]: + check_hostname = ctx.check_hostname + verify_mode = ctx.verify_mode + ctx.check_hostname = False + _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE) + try: + yield + finally: + ctx.check_hostname = check_hostname + _set_ssl_context_verify_mode(ctx, verify_mode) + + +def _verify_peercerts_impl( + ssl_context: ssl.SSLContext, + cert_chain: list[bytes], + server_hostname: str | None = None, +) -> None: + certs = None + policies = None + trust = None + cf_error = None + try: + if server_hostname is not None: + cf_str_hostname = None + try: + cf_str_hostname = _bytes_to_cf_string(server_hostname.encode("ascii")) + ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname) + finally: + if cf_str_hostname: + CoreFoundation.CFRelease(cf_str_hostname) + else: + ssl_policy = Security.SecPolicyCreateSSL(True, None) + + policies = ssl_policy + if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN: + # Add explicit policy requiring positive revocation checks + policies = CoreFoundation.CFArrayCreateMutable( + CoreFoundation.kCFAllocatorDefault, + 0, + ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), + ) + CoreFoundation.CFArrayAppendValue(policies, ssl_policy) + CoreFoundation.CFRelease(ssl_policy) + revocation_policy = Security.SecPolicyCreateRevocation( + kSecRevocationUseAnyAvailableMethod + | kSecRevocationRequirePositiveResponse + ) + CoreFoundation.CFArrayAppendValue(policies, revocation_policy) + CoreFoundation.CFRelease(revocation_policy) + elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF: + raise NotImplementedError("VERIFY_CRL_CHECK_LEAF not implemented for macOS") + + certs = None + try: + certs = _der_certs_to_cf_cert_array(cert_chain) + + # Now that we have certificates loaded and a SecPolicy + # we can finally create a SecTrust object! + trust = Security.SecTrustRef() + Security.SecTrustCreateWithCertificates( + certs, policies, ctypes.byref(trust) + ) + + finally: + # The certs are now being held by SecTrust so we can + # release our handles for the array. + if certs: + CoreFoundation.CFRelease(certs) + + # If there are additional trust anchors to load we need to transform + # the list of DER-encoded certificates into a CFArray. Otherwise + # pass 'None' to signal that we only want system / fetched certificates. + ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs( + binary_form=True + ) + if ctx_ca_certs_der: + ctx_ca_certs = None + try: + ctx_ca_certs = _der_certs_to_cf_cert_array(cert_chain) + Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs) + finally: + if ctx_ca_certs: + CoreFoundation.CFRelease(ctx_ca_certs) + else: + Security.SecTrustSetAnchorCertificates(trust, None) + + cf_error = CoreFoundation.CFErrorRef() + sec_trust_eval_result = Security.SecTrustEvaluateWithError( + trust, ctypes.byref(cf_error) + ) + # sec_trust_eval_result is a bool (0 or 1) + # where 1 means that the certs are trusted. + if sec_trust_eval_result == 1: + is_trusted = True + elif sec_trust_eval_result == 0: + is_trusted = False + else: + raise ssl.SSLError( + f"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}" + ) + + cf_error_code = 0 + if not is_trusted: + cf_error_code = CoreFoundation.CFErrorGetCode(cf_error) + + # If the error is a known failure that we're + # explicitly okay with from SSLContext configuration + # we can set is_trusted accordingly. + if ssl_context.verify_mode != ssl.CERT_REQUIRED and ( + cf_error_code == CFConst.errSecNotTrusted + or cf_error_code == CFConst.errSecCertificateExpired + ): + is_trusted = True + elif ( + not ssl_context.check_hostname + and cf_error_code == CFConst.errSecHostNameMismatch + ): + is_trusted = True + + # If we're still not trusted then we start to + # construct and raise the SSLCertVerificationError. + if not is_trusted: + cf_error_string_ref = None + try: + cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error) + + # Can this ever return 'None' if there's a CFError? + cf_error_message = ( + _cf_string_ref_to_str(cf_error_string_ref) + or "Certificate verification failed" + ) + + # TODO: Not sure if we need the SecTrustResultType for anything? + # We only care whether or not it's a success or failure for now. + sec_trust_result_type = Security.SecTrustResultType() + Security.SecTrustGetTrustResult( + trust, ctypes.byref(sec_trust_result_type) + ) + + err = ssl.SSLCertVerificationError(cf_error_message) + err.verify_message = cf_error_message + err.verify_code = cf_error_code + raise err + finally: + if cf_error_string_ref: + CoreFoundation.CFRelease(cf_error_string_ref) + + finally: + if policies: + CoreFoundation.CFRelease(policies) + if trust: + CoreFoundation.CFRelease(trust) diff --git a/shared/package-files/06/063c92d566e718c67fde87955ac5d62e93f9dbf0262ffc2d1eed273b41279a45/unfold_copy_ops.h b/shared/package-files/06/063c92d566e718c67fde87955ac5d62e93f9dbf0262ffc2d1eed273b41279a45/unfold_copy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..71d82e0d1412033137033691016d71f3209630e6 --- /dev/null +++ b/shared/package-files/06/063c92d566e718c67fde87955ac5d62e93f9dbf0262ffc2d1eed273b41279a45/unfold_copy_ops.h @@ -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 unfold_copy { + using schema = 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::unfold_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unfold_copy(Tensor self, int dimension, int size, int step) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dimension, int64_t size, int64_t step); +}; + +struct TORCH_API unfold_copy_out { + using schema = 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::unfold_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unfold_copy.out(Tensor self, int dimension, int size, int step, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dimension, int64_t size, int64_t step, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/063de18848173015f30e2d0b9a0f24f908380a13d9ad056a194d107e1ed2bfce/test_ticker.py b/shared/package-files/06/063de18848173015f30e2d0b9a0f24f908380a13d9ad056a194d107e1ed2bfce/test_ticker.py new file mode 100644 index 0000000000000000000000000000000000000000..77c0e917df8a1fd2c7deb450e3dd8b917391f3b8 --- /dev/null +++ b/shared/package-files/06/063de18848173015f30e2d0b9a0f24f908380a13d9ad056a194d107e1ed2bfce/test_ticker.py @@ -0,0 +1,1939 @@ +from contextlib import nullcontext +import itertools +import locale +import logging +import re +from packaging.version import parse as parse_version + +import numpy as np +from numpy.testing import assert_almost_equal, assert_array_equal +import pytest + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.ticker as mticker + + +class TestMaxNLocator: + basic_data = [ + (20, 100, np.array([20., 40., 60., 80., 100.])), + (0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])), + (-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])), + (0, 0.85e-50, np.arange(6) * 2e-51), + (-0.85e-50, 0, np.arange(-5, 1) * 2e-51), + ] + + integer_data = [ + (-0.1, 1.1, None, np.array([-1, 0, 1, 2])), + (-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])), + (1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])), + ] + + @pytest.mark.parametrize('vmin, vmax, expected', basic_data) + def test_basic(self, vmin, vmax, expected): + loc = mticker.MaxNLocator(nbins=5) + assert_almost_equal(loc.tick_values(vmin, vmax), expected) + + @pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data) + def test_integer(self, vmin, vmax, steps, expected): + loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps) + assert_almost_equal(loc.tick_values(vmin, vmax), expected) + + @pytest.mark.parametrize('kwargs, errortype, match', [ + ({'foo': 0}, TypeError, + re.escape("set_params() got an unexpected keyword argument 'foo'")), + ({'steps': [2, 1]}, ValueError, "steps argument must be an increasing"), + ({'steps': 2}, ValueError, "steps argument must be an increasing"), + ({'steps': [2, 11]}, ValueError, "steps argument must be an increasing"), + ]) + def test_errors(self, kwargs, errortype, match): + with pytest.raises(errortype, match=match): + mticker.MaxNLocator(**kwargs) + + @pytest.mark.parametrize('steps, result', [ + ([1, 2, 10], [1, 2, 10]), + ([2, 10], [1, 2, 10]), + ([1, 2], [1, 2, 10]), + ([2], [1, 2, 10]), + ]) + def test_padding(self, steps, result): + loc = mticker.MaxNLocator(steps=steps) + assert (loc._steps == result).all() + + +class TestLinearLocator: + def test_basic(self): + loc = mticker.LinearLocator(numticks=3) + test_value = np.array([-0.8, -0.3, 0.2]) + assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) + + def test_zero_numticks(self): + loc = mticker.LinearLocator(numticks=0) + loc.tick_values(-0.8, 0.2) == [] + + def test_set_params(self): + """ + Create linear locator with presets={}, numticks=2 and change it to + something else. See if change was successful. Should not exception. + """ + loc = mticker.LinearLocator(numticks=2) + loc.set_params(numticks=8, presets={(0, 1): []}) + assert loc.numticks == 8 + assert loc.presets == {(0, 1): []} + + def test_presets(self): + loc = mticker.LinearLocator(presets={(1, 2): [1, 1.25, 1.75], + (0, 2): [0.5, 1.5]}) + assert loc.tick_values(1, 2) == [1, 1.25, 1.75] + assert loc.tick_values(2, 1) == [1, 1.25, 1.75] + assert loc.tick_values(0, 2) == [0.5, 1.5] + assert loc.tick_values(0.0, 2.0) == [0.5, 1.5] + assert (loc.tick_values(0, 1) == np.linspace(0, 1, 11)).all() + + +class TestMultipleLocator: + def test_basic(self): + loc = mticker.MultipleLocator(base=3.147) + test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294, + 9.441, 12.588]) + assert_almost_equal(loc.tick_values(-7, 10), test_value) + + def test_basic_with_offset(self): + loc = mticker.MultipleLocator(base=3.147, offset=1.2) + test_value = np.array([-8.241, -5.094, -1.947, 1.2, 4.347, 7.494, + 10.641]) + assert_almost_equal(loc.tick_values(-7, 10), test_value) + + def test_view_limits(self): + """ + Test basic behavior of view limits. + """ + with mpl.rc_context({'axes.autolimit_mode': 'data'}): + loc = mticker.MultipleLocator(base=3.147) + assert_almost_equal(loc.view_limits(-5, 5), (-5, 5)) + + def test_view_limits_round_numbers(self): + """ + Test that everything works properly with 'round_numbers' for auto + limit. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MultipleLocator(base=3.147) + assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294)) + + def test_view_limits_round_numbers_with_offset(self): + """ + Test that everything works properly with 'round_numbers' for auto + limit. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MultipleLocator(base=3.147, offset=1.3) + assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447)) + + def test_view_limits_single_bin(self): + """ + Test that 'round_numbers' works properly with a single bin. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MaxNLocator(nbins=1) + assert_almost_equal(loc.view_limits(-2.3, 2.3), (-4, 4)) + + def test_set_params(self): + """ + Create multiple locator with 0.7 base, and change it to something else. + See if change was successful. + """ + mult = mticker.MultipleLocator(base=0.7) + mult.set_params(base=1.7) + assert mult._edge.step == 1.7 + mult.set_params(offset=3) + assert mult._offset == 3 + + +class TestAutoMinorLocator: + def test_basic(self): + fig, ax = plt.subplots() + ax.set_xlim(0, 1.39) + ax.minorticks_on() + test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, + 0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9, + 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) + + # NB: the following values are assuming that *xlim* is [0, 5] + params = [ + (0, 0), # no major tick => no minor tick either + (1, 0) # a single major tick => no minor tick + ] + + def test_first_and_last_minorticks(self): + """ + Test that first and last minor tick appear as expected. + """ + # This test is related to issue #22331 + fig, ax = plt.subplots() + ax.set_xlim(-1.9, 1.9) + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + test_value = np.array([-1.9, -1.8, -1.7, -1.6, -1.4, -1.3, -1.2, -1.1, + -0.9, -0.8, -0.7, -0.6, -0.4, -0.3, -0.2, -0.1, + 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.1, + 1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9]) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) + + ax.set_xlim(-5, 5) + test_value = np.array([-5.0, -4.5, -3.5, -3.0, -2.5, -1.5, -1.0, -0.5, + 0.5, 1.0, 1.5, 2.5, 3.0, 3.5, 4.5, 5.0]) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) + + @pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params) + def test_low_number_of_majorticks( + self, nb_majorticks, expected_nb_minorticks): + # This test is related to issue #8804 + fig, ax = plt.subplots() + xlims = (0, 5) # easier to test the different code paths + ax.set_xlim(*xlims) + ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks)) + ax.minorticks_on() + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks + + majorstep_minordivisions = [(1, 5), + (2, 4), + (2.5, 5), + (5, 5), + (10, 5)] + + # This test is meant to verify the parameterization for + # test_number_of_minor_ticks + def test_using_all_default_major_steps(self): + with mpl.rc_context({'_internal.classic_mode': False}): + majorsteps = [x[0] for x in self.majorstep_minordivisions] + np.testing.assert_allclose(majorsteps, + mticker.AutoLocator()._steps) + + @pytest.mark.parametrize('major_step, expected_nb_minordivisions', + majorstep_minordivisions) + def test_number_of_minor_ticks( + self, major_step, expected_nb_minordivisions): + fig, ax = plt.subplots() + xlims = (0, major_step) + ax.set_xlim(*xlims) + ax.set_xticks(xlims) + ax.minorticks_on() + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + nb_minor_divisions = len(ax.xaxis.get_minorticklocs()) + 1 + assert nb_minor_divisions == expected_nb_minordivisions + + limits = [(0, 1.39), (0, 0.139), + (0, 0.11e-19), (0, 0.112e-12), + (-2.0e-07, -3.3e-08), (1.20e-06, 1.42e-06), + (-1.34e-06, -1.44e-06), (-8.76e-07, -1.51e-06)] + + reference = [ + [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7, + 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35], + [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, 0.065, + 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, 0.125, 0.13, + 0.135], + [5.00e-22, 1.00e-21, 1.50e-21, 2.50e-21, 3.00e-21, 3.50e-21, 4.50e-21, + 5.00e-21, 5.50e-21, 6.50e-21, 7.00e-21, 7.50e-21, 8.50e-21, 9.00e-21, + 9.50e-21, 1.05e-20, 1.10e-20], + [5.00e-15, 1.00e-14, 1.50e-14, 2.50e-14, 3.00e-14, 3.50e-14, 4.50e-14, + 5.00e-14, 5.50e-14, 6.50e-14, 7.00e-14, 7.50e-14, 8.50e-14, 9.00e-14, + 9.50e-14, 1.05e-13, 1.10e-13], + [-1.95e-07, -1.90e-07, -1.85e-07, -1.75e-07, -1.70e-07, -1.65e-07, + -1.55e-07, -1.50e-07, -1.45e-07, -1.35e-07, -1.30e-07, -1.25e-07, + -1.15e-07, -1.10e-07, -1.05e-07, -9.50e-08, -9.00e-08, -8.50e-08, + -7.50e-08, -7.00e-08, -6.50e-08, -5.50e-08, -5.00e-08, -4.50e-08, + -3.50e-08], + [1.21e-06, 1.22e-06, 1.23e-06, 1.24e-06, 1.26e-06, 1.27e-06, 1.28e-06, + 1.29e-06, 1.31e-06, 1.32e-06, 1.33e-06, 1.34e-06, 1.36e-06, 1.37e-06, + 1.38e-06, 1.39e-06, 1.41e-06, 1.42e-06], + [-1.435e-06, -1.430e-06, -1.425e-06, -1.415e-06, -1.410e-06, + -1.405e-06, -1.395e-06, -1.390e-06, -1.385e-06, -1.375e-06, + -1.370e-06, -1.365e-06, -1.355e-06, -1.350e-06, -1.345e-06], + [-1.48e-06, -1.46e-06, -1.44e-06, -1.42e-06, -1.38e-06, -1.36e-06, + -1.34e-06, -1.32e-06, -1.28e-06, -1.26e-06, -1.24e-06, -1.22e-06, + -1.18e-06, -1.16e-06, -1.14e-06, -1.12e-06, -1.08e-06, -1.06e-06, + -1.04e-06, -1.02e-06, -9.80e-07, -9.60e-07, -9.40e-07, -9.20e-07, + -8.80e-07]] + + additional_data = list(zip(limits, reference)) + + @pytest.mark.parametrize('lim, ref', additional_data) + def test_additional(self, lim, ref): + fig, ax = plt.subplots() + + ax.minorticks_on() + ax.grid(True, 'minor', 'y', linewidth=1) + ax.grid(True, 'major', color='k', linewidth=1) + ax.set_ylim(lim) + + assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref) + + @pytest.mark.parametrize('use_rcparam', [False, True]) + @pytest.mark.parametrize( + 'lim, ref', [ + ((0, 1.39), + [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7, + 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]), + ((0, 0.139), + [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, + 0.065, 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, + 0.125, 0.13, 0.135]), + ]) + def test_number_of_minor_ticks_auto(self, lim, ref, use_rcparam): + if use_rcparam: + context = {'xtick.minor.ndivs': 'auto', 'ytick.minor.ndivs': 'auto'} + kwargs = {} + else: + context = {} + kwargs = {'n': 'auto'} + + with mpl.rc_context(context): + fig, ax = plt.subplots() + ax.set_xlim(*lim) + ax.set_ylim(*lim) + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref) + assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref) + + @pytest.mark.parametrize('use_rcparam', [False, True]) + @pytest.mark.parametrize( + 'n, lim, ref', [ + (2, (0, 4), [0.5, 1.5, 2.5, 3.5]), + (4, (0, 2), [0.25, 0.5, 0.75, 1.25, 1.5, 1.75]), + (10, (0, 1), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]), + ]) + def test_number_of_minor_ticks_int(self, n, lim, ref, use_rcparam): + if use_rcparam: + context = {'xtick.minor.ndivs': n, 'ytick.minor.ndivs': n} + kwargs = {} + else: + context = {} + kwargs = {'n': n} + + with mpl.rc_context(context): + fig, ax = plt.subplots() + ax.set_xlim(*lim) + ax.set_ylim(*lim) + ax.xaxis.set_major_locator(mticker.MultipleLocator(1)) + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + ax.yaxis.set_major_locator(mticker.MultipleLocator(1)) + ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref) + assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref) + + +class TestLogLocator: + def test_basic(self): + loc = mticker.LogLocator(numticks=5) + with pytest.raises(ValueError): + loc.tick_values(0, 1000) + + test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, + 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, + 1.00000000e+07, 1.000000000e+09]) + assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value) + + loc = mticker.LogLocator(base=2) + test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.]) + assert_almost_equal(loc.tick_values(1, 100), test_value) + + def test_polar_axes(self): + """ + Polar Axes have a different ticking logic. + """ + fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) + ax.set_yscale('log') + ax.set_ylim(1, 100) + assert_array_equal(ax.get_yticks(), [10, 100, 1000]) + + def test_switch_to_autolocator(self): + loc = mticker.LogLocator(subs="all") + assert_array_equal(loc.tick_values(0.45, 0.55), + [0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56]) + # check that we *skip* 1.0, and 10, because this is a minor locator + loc = mticker.LogLocator(subs=np.arange(2, 10)) + assert 1.0 not in loc.tick_values(0.9, 20.) + assert 10.0 not in loc.tick_values(0.9, 20.) + + def test_set_params(self): + """ + Create log locator with default value, base=10.0, subs=[1.0], + numticks=15 and change it to something else. + See if change was successful. Should not raise exception. + """ + loc = mticker.LogLocator() + loc.set_params(numticks=7, subs=[2.0], base=4) + assert loc.numticks == 7 + assert loc._base == 4 + assert list(loc._subs) == [2.0] + + def test_tick_values_correct(self): + ll = mticker.LogLocator(subs=(1, 2, 5)) + test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00, + 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02, + 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04, + 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06, + 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08]) + assert_almost_equal(ll.tick_values(1, 1e7), test_value) + + def test_tick_values_not_empty(self): + mpl.rcParams['_internal.classic_mode'] = False + ll = mticker.LogLocator(subs=(1, 2, 5)) + test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00, + 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02, + 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04, + 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06, + 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08, + 1.e+09, 2.e+09, 5.e+09]) + assert_almost_equal(ll.tick_values(1, 1e8), test_value) + + def test_multiple_shared_axes(self): + rng = np.random.default_rng(19680801) + dummy_data = [rng.normal(size=100), [], []] + fig, axes = plt.subplots(len(dummy_data), sharex=True, sharey=True) + + for ax, data in zip(axes.flatten(), dummy_data): + ax.hist(data, bins=10) + ax.set_yscale('log', nonpositive='clip') + + for ax in axes.flatten(): + assert all(ax.get_yticks() == axes[0].get_yticks()) + assert ax.get_ylim() == axes[0].get_ylim() + + +class TestNullLocator: + def test_set_params(self): + """ + Create null locator, and attempt to call set_params() on it. + Should not exception, and should raise a warning. + """ + loc = mticker.NullLocator() + with pytest.warns(UserWarning): + loc.set_params() + + +class _LogitHelper: + @staticmethod + def isclose(x, y): + return (np.isclose(-np.log(1/x-1), -np.log(1/y-1)) + if 0 < x < 1 and 0 < y < 1 else False) + + @staticmethod + def assert_almost_equal(x, y): + ax = np.array(x) + ay = np.array(y) + assert np.all(ax > 0) and np.all(ax < 1) + assert np.all(ay > 0) and np.all(ay < 1) + lx = -np.log(1/ax-1) + ly = -np.log(1/ay-1) + assert_almost_equal(lx, ly) + + +class TestLogitLocator: + ref_basic_limits = [ + (5e-2, 1 - 5e-2), + (5e-3, 1 - 5e-3), + (5e-4, 1 - 5e-4), + (5e-5, 1 - 5e-5), + (5e-6, 1 - 5e-6), + (5e-7, 1 - 5e-7), + (5e-8, 1 - 5e-8), + (5e-9, 1 - 5e-9), + ] + + ref_basic_major_ticks = [ + 1 / (10 ** np.arange(1, 3)), + 1 / (10 ** np.arange(1, 4)), + 1 / (10 ** np.arange(1, 5)), + 1 / (10 ** np.arange(1, 6)), + 1 / (10 ** np.arange(1, 7)), + 1 / (10 ** np.arange(1, 8)), + 1 / (10 ** np.arange(1, 9)), + 1 / (10 ** np.arange(1, 10)), + ] + + ref_maxn_limits = [(0.4, 0.6), (5e-2, 2e-1), (1 - 2e-1, 1 - 5e-2)] + + @pytest.mark.parametrize( + "lims, expected_low_ticks", + zip(ref_basic_limits, ref_basic_major_ticks), + ) + def test_basic_major(self, lims, expected_low_ticks): + """ + Create logit locator with huge number of major, and tests ticks. + """ + expected_ticks = sorted( + [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)] + ) + loc = mticker.LogitLocator(nbins=100) + _LogitHelper.assert_almost_equal( + loc.tick_values(*lims), + expected_ticks + ) + + @pytest.mark.parametrize("lims", ref_maxn_limits) + def test_maxn_major(self, lims): + """ + When the axis is zoomed, the locator must have the same behavior as + MaxNLocator. + """ + loc = mticker.LogitLocator(nbins=100) + maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10]) + for nbins in (4, 8, 16): + loc.set_params(nbins=nbins) + maxn_loc.set_params(nbins=nbins) + ticks = loc.tick_values(*lims) + maxn_ticks = maxn_loc.tick_values(*lims) + assert ticks.shape == maxn_ticks.shape + assert (ticks == maxn_ticks).all() + + @pytest.mark.parametrize("lims", ref_basic_limits + ref_maxn_limits) + def test_nbins_major(self, lims): + """ + Assert logit locator for respecting nbins param. + """ + + basic_needed = int(-np.floor(np.log10(lims[0]))) * 2 + 1 + loc = mticker.LogitLocator(nbins=100) + for nbins in range(basic_needed, 2, -1): + loc.set_params(nbins=nbins) + assert len(loc.tick_values(*lims)) <= nbins + 2 + + @pytest.mark.parametrize( + "lims, expected_low_ticks", + zip(ref_basic_limits, ref_basic_major_ticks), + ) + def test_minor(self, lims, expected_low_ticks): + """ + In large scale, test the presence of minor, + and assert no minor when major are subsampled. + """ + + expected_ticks = sorted( + [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)] + ) + basic_needed = len(expected_ticks) + loc = mticker.LogitLocator(nbins=100) + minor_loc = mticker.LogitLocator(nbins=100, minor=True) + for nbins in range(basic_needed, 2, -1): + loc.set_params(nbins=nbins) + minor_loc.set_params(nbins=nbins) + major_ticks = loc.tick_values(*lims) + minor_ticks = minor_loc.tick_values(*lims) + if len(major_ticks) >= len(expected_ticks): + # no subsample, we must have a lot of minors ticks + assert (len(major_ticks) - 1) * 5 < len(minor_ticks) + else: + # subsample + _LogitHelper.assert_almost_equal( + sorted([*major_ticks, *minor_ticks]), expected_ticks) + + def test_minor_attr(self): + loc = mticker.LogitLocator(nbins=100) + assert not loc.minor + loc.minor = True + assert loc.minor + loc.set_params(minor=False) + assert not loc.minor + + acceptable_vmin_vmax = [ + *(2.5 ** np.arange(-3, 0)), + *(1 - 2.5 ** np.arange(-3, 0)), + ] + + @pytest.mark.parametrize( + "lims", + [ + (a, b) + for (a, b) in itertools.product(acceptable_vmin_vmax, repeat=2) + if a != b + ], + ) + def test_nonsingular_ok(self, lims): + """ + Create logit locator, and test the nonsingular method for acceptable + value + """ + loc = mticker.LogitLocator() + lims2 = loc.nonsingular(*lims) + assert sorted(lims) == sorted(lims2) + + @pytest.mark.parametrize("okval", acceptable_vmin_vmax) + def test_nonsingular_nok(self, okval): + """ + Create logit locator, and test the nonsingular method for non + acceptable value + """ + loc = mticker.LogitLocator() + vmin, vmax = (-1, okval) + vmin2, vmax2 = loc.nonsingular(vmin, vmax) + assert vmax2 == vmax + assert 0 < vmin2 < vmax2 + vmin, vmax = (okval, 2) + vmin2, vmax2 = loc.nonsingular(vmin, vmax) + assert vmin2 == vmin + assert vmin2 < vmax2 < 1 + + +class TestFixedLocator: + def test_set_params(self): + """ + Create fixed locator with 5 nbins, and change it to something else. + See if change was successful. + Should not exception. + """ + fixed = mticker.FixedLocator(range(0, 24), nbins=5) + fixed.set_params(nbins=7) + assert fixed.nbins == 7 + + +class TestIndexLocator: + def test_set_params(self): + """ + Create index locator with 3 base, 4 offset. and change it to something + else. See if change was successful. + Should not exception. + """ + index = mticker.IndexLocator(base=3, offset=4) + index.set_params(base=7, offset=7) + assert index._base == 7 + assert index.offset == 7 + + +class TestSymmetricalLogLocator: + def test_set_params(self): + """ + Create symmetrical log locator with default subs =[1.0] numticks = 15, + and change it to something else. + See if change was successful. + Should not exception. + """ + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) + sym.set_params(subs=[2.0], numticks=8) + assert sym._subs == [2.0] + assert sym.numticks == 8 + + @pytest.mark.parametrize( + 'vmin, vmax, expected', + [ + (0, 1, [0, 1]), + (-1, 1, [-1, 0, 1]), + ], + ) + def test_values(self, vmin, vmax, expected): + # https://github.com/matplotlib/matplotlib/issues/25945 + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) + ticks = sym.tick_values(vmin=vmin, vmax=vmax) + assert_array_equal(ticks, expected) + + def test_subs(self): + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1, subs=[2.0, 4.0]) + sym.create_dummy_axis() + sym.axis.set_view_interval(-10, 10) + assert_array_equal(sym(), [-20, -40, -2, -4, 0, 2, 4, 20, 40]) + + def test_extending(self): + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) + sym.create_dummy_axis() + sym.axis.set_view_interval(8, 9) + assert (sym() == [1.0]).all() + sym.axis.set_view_interval(8, 12) + assert (sym() == [1.0, 10.0]).all() + assert sym.view_limits(10, 10) == (1, 100) + assert sym.view_limits(-10, -10) == (-100, -1) + assert sym.view_limits(0, 0) == (-0.001, 0.001) + + +class TestAsinhLocator: + def test_init(self): + lctr = mticker.AsinhLocator(linear_width=2.718, numticks=19) + assert lctr.linear_width == 2.718 + assert lctr.numticks == 19 + assert lctr.base == 10 + + def test_set_params(self): + lctr = mticker.AsinhLocator(linear_width=5, + numticks=17, symthresh=0.125, + base=4, subs=(2.5, 3.25)) + assert lctr.numticks == 17 + assert lctr.symthresh == 0.125 + assert lctr.base == 4 + assert lctr.subs == (2.5, 3.25) + + lctr.set_params(numticks=23) + assert lctr.numticks == 23 + lctr.set_params(None) + assert lctr.numticks == 23 + + lctr.set_params(symthresh=0.5) + assert lctr.symthresh == 0.5 + lctr.set_params(symthresh=None) + assert lctr.symthresh == 0.5 + + lctr.set_params(base=7) + assert lctr.base == 7 + lctr.set_params(base=None) + assert lctr.base == 7 + + lctr.set_params(subs=(2, 4.125)) + assert lctr.subs == (2, 4.125) + lctr.set_params(subs=None) + assert lctr.subs == (2, 4.125) + lctr.set_params(subs=[]) + assert lctr.subs is None + + def test_linear_values(self): + lctr = mticker.AsinhLocator(linear_width=100, numticks=11, base=0) + + assert_almost_equal(lctr.tick_values(-1, 1), + np.arange(-1, 1.01, 0.2)) + assert_almost_equal(lctr.tick_values(-0.1, 0.1), + np.arange(-0.1, 0.101, 0.02)) + assert_almost_equal(lctr.tick_values(-0.01, 0.01), + np.arange(-0.01, 0.0101, 0.002)) + + def test_wide_values(self): + lctr = mticker.AsinhLocator(linear_width=0.1, numticks=11, base=0) + + assert_almost_equal(lctr.tick_values(-100, 100), + [-100, -20, -5, -1, -0.2, + 0, 0.2, 1, 5, 20, 100]) + assert_almost_equal(lctr.tick_values(-1000, 1000), + [-1000, -100, -20, -3, -0.4, + 0, 0.4, 3, 20, 100, 1000]) + + def test_near_zero(self): + """Check that manually injected zero will supersede nearby tick""" + lctr = mticker.AsinhLocator(linear_width=100, numticks=3, base=0) + + assert_almost_equal(lctr.tick_values(-1.1, 0.9), [-1.0, 0.0, 0.9]) + + def test_fallback(self): + lctr = mticker.AsinhLocator(1.0, numticks=11) + + assert_almost_equal(lctr.tick_values(101, 102), + np.arange(101, 102.01, 0.1)) + + def test_symmetrizing(self): + lctr = mticker.AsinhLocator(linear_width=1, numticks=3, + symthresh=0.25, base=0) + lctr.create_dummy_axis() + + lctr.axis.set_view_interval(-1, 2) + assert_almost_equal(lctr(), [-1, 0, 2]) + + lctr.axis.set_view_interval(-1, 0.9) + assert_almost_equal(lctr(), [-1, 0, 1]) + + lctr.axis.set_view_interval(-0.85, 1.05) + assert_almost_equal(lctr(), [-1, 0, 1]) + + lctr.axis.set_view_interval(1, 1.1) + assert_almost_equal(lctr(), [1, 1.05, 1.1]) + + def test_base_rounding(self): + lctr10 = mticker.AsinhLocator(linear_width=1, numticks=8, + base=10, subs=(1, 3, 5)) + assert_almost_equal(lctr10.tick_values(-110, 110), + [-500, -300, -100, -50, -30, -10, -5, -3, -1, + -0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5, + 1, 3, 5, 10, 30, 50, 100, 300, 500]) + + lctr5 = mticker.AsinhLocator(linear_width=1, numticks=20, base=5) + assert_almost_equal(lctr5.tick_values(-1050, 1050), + [-625, -125, -25, -5, -1, -0.2, 0, + 0.2, 1, 5, 25, 125, 625]) + + +class TestScalarFormatter: + offset_data = [ + (123, 189, 0), + (-189, -123, 0), + (12341, 12349, 12340), + (-12349, -12341, -12340), + (99999.5, 100010.5, 100000), + (-100010.5, -99999.5, -100000), + (99990.5, 100000.5, 100000), + (-100000.5, -99990.5, -100000), + (1233999, 1234001, 1234000), + (-1234001, -1233999, -1234000), + (1, 1, 1), + (123, 123, 0), + # Test cases courtesy of @WeatherGod + (.4538, .4578, .45), + (3789.12, 3783.1, 3780), + (45124.3, 45831.75, 45000), + (0.000721, 0.0007243, 0.00072), + (12592.82, 12591.43, 12590), + (9., 12., 0), + (900., 1200., 0), + (1900., 1200., 0), + (0.99, 1.01, 1), + (9.99, 10.01, 10), + (99.99, 100.01, 100), + (5.99, 6.01, 6), + (15.99, 16.01, 16), + (-0.452, 0.492, 0), + (-0.492, 0.492, 0), + (12331.4, 12350.5, 12300), + (-12335.3, 12335.3, 0), + ] + + use_offset_data = [True, False] + + useMathText_data = [True, False] + + # (sci_type, scilimits, lim, orderOfMag, fewticks) + scilimits_data = [ + (False, (0, 0), (10.0, 20.0), 0, False), + (True, (-2, 2), (-10, 20), 0, False), + (True, (-2, 2), (-20, 10), 0, False), + (True, (-2, 2), (-110, 120), 2, False), + (True, (-2, 2), (-120, 110), 2, False), + (True, (-2, 2), (-.001, 0.002), -3, False), + (True, (-7, 7), (0.18e10, 0.83e10), 9, True), + (True, (0, 0), (-1e5, 1e5), 5, False), + (True, (6, 6), (-1e5, 1e5), 6, False), + ] + + cursor_data = [ + [0., "0.000"], + [0.0123, "0.012"], + [0.123, "0.123"], + [1.23, "1.230"], + [12.3, "12.300"], + ] + + format_data = [ + (.1, "1e-1"), + (.11, "1.1e-1"), + (1e8, "1e8"), + (1.1e8, "1.1e8"), + ] + + @pytest.mark.parametrize('unicode_minus, result', + [(True, "\N{MINUS SIGN}1"), (False, "-1")]) + def test_unicode_minus(self, unicode_minus, result): + mpl.rcParams['axes.unicode_minus'] = unicode_minus + assert ( + plt.gca().xaxis.get_major_formatter().format_data_short(-1).strip() + == result) + + @pytest.mark.parametrize('left, right, offset', offset_data) + def test_offset_value(self, left, right, offset): + fig, ax = plt.subplots() + formatter = ax.xaxis.get_major_formatter() + + with (pytest.warns(UserWarning, match='Attempting to set identical') + if left == right else nullcontext()): + ax.set_xlim(left, right) + ax.xaxis._update_ticks() + assert formatter.offset == offset + + with (pytest.warns(UserWarning, match='Attempting to set identical') + if left == right else nullcontext()): + ax.set_xlim(right, left) + ax.xaxis._update_ticks() + assert formatter.offset == offset + + @pytest.mark.parametrize('use_offset', use_offset_data) + def test_use_offset(self, use_offset): + with mpl.rc_context({'axes.formatter.useoffset': use_offset}): + tmp_form = mticker.ScalarFormatter() + assert use_offset == tmp_form.get_useOffset() + assert tmp_form.offset == 0 + + @pytest.mark.parametrize('use_math_text', useMathText_data) + def test_useMathText(self, use_math_text): + with mpl.rc_context({'axes.formatter.use_mathtext': use_math_text}): + tmp_form = mticker.ScalarFormatter() + assert use_math_text == tmp_form.get_useMathText() + + def test_set_use_offset_float(self): + tmp_form = mticker.ScalarFormatter() + tmp_form.set_useOffset(0.5) + assert not tmp_form.get_useOffset() + assert tmp_form.offset == 0.5 + + def test_use_locale(self): + conv = locale.localeconv() + sep = conv['thousands_sep'] + if not sep or conv['grouping'][-1:] in ([], [locale.CHAR_MAX]): + pytest.skip('Locale does not apply grouping') # pragma: no cover + + with mpl.rc_context({'axes.formatter.use_locale': True}): + tmp_form = mticker.ScalarFormatter() + assert tmp_form.get_useLocale() + + tmp_form.create_dummy_axis() + tmp_form.axis.set_data_interval(0, 10) + tmp_form.set_locs([1, 2, 3]) + assert sep in tmp_form(1e9) + + @pytest.mark.parametrize( + 'sci_type, scilimits, lim, orderOfMag, fewticks', scilimits_data) + def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks): + tmp_form = mticker.ScalarFormatter() + tmp_form.set_scientific(sci_type) + tmp_form.set_powerlimits(scilimits) + fig, ax = plt.subplots() + ax.yaxis.set_major_formatter(tmp_form) + ax.set_ylim(*lim) + if fewticks: + ax.yaxis.set_major_locator(mticker.MaxNLocator(4)) + + tmp_form.set_locs(ax.yaxis.get_majorticklocs()) + assert orderOfMag == tmp_form.orderOfMagnitude + + @pytest.mark.parametrize('value, expected', format_data) + def test_format_data(self, value, expected): + mpl.rcParams['axes.unicode_minus'] = False + sf = mticker.ScalarFormatter() + assert sf.format_data(value) == expected + + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_precision(self, data, expected): + fig, ax = plt.subplots() + ax.set_xlim(-1, 1) # Pointing precision of 0.001. + fmt = ax.xaxis.get_major_formatter().format_data_short + assert fmt(data) == expected + + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_dummy_axis(self, data, expected): + # Issue #17624 + sf = mticker.ScalarFormatter() + sf.create_dummy_axis() + sf.axis.set_view_interval(0, 10) + fmt = sf.format_data_short + assert fmt(data) == expected + assert sf.axis.get_tick_space() == 9 + assert sf.axis.get_minpos() == 0 + + def test_mathtext_ticks(self): + mpl.rcParams.update({ + 'font.family': 'serif', + 'font.serif': 'cmr10', + 'axes.formatter.use_mathtext': False + }) + + if parse_version(pytest.__version__).major < 8: + with pytest.warns(UserWarning, match='cmr10 font should ideally'): + fig, ax = plt.subplots() + ax.set_xticks([-1, 0, 1]) + fig.canvas.draw() + else: + with (pytest.warns(UserWarning, match="Glyph 8722"), + pytest.warns(UserWarning, match='cmr10 font should ideally')): + fig, ax = plt.subplots() + ax.set_xticks([-1, 0, 1]) + fig.canvas.draw() + + def test_cmr10_substitutions(self, caplog): + mpl.rcParams.update({ + 'font.family': 'cmr10', + 'mathtext.fontset': 'cm', + 'axes.formatter.use_mathtext': True, + }) + + # Test that it does not log a warning about missing glyphs. + with caplog.at_level(logging.WARNING, logger='matplotlib.mathtext'): + fig, ax = plt.subplots() + ax.plot([-0.03, 0.05], [40, 0.05]) + ax.set_yscale('log') + yticks = [0.02, 0.3, 4, 50] + formatter = mticker.LogFormatterSciNotation() + ax.set_yticks(yticks, map(formatter, yticks)) + fig.canvas.draw() + assert not caplog.text + + def test_empty_locs(self): + sf = mticker.ScalarFormatter() + sf.set_locs([]) + assert sf(0.5) == '' + + +class TestLogFormatterExponent: + param_data = [ + (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0), + ['-3', '-2', '-1', '0', '1', '2', '3']), + # With labelOnlyBase=False, non-integer powers should be nicely + # formatted. + (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]), + range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']), + (False, 50, np.array([3, 5, 12, 42], dtype=float), range(6), + ['3', '5', '12', '42']), + ] + + base_data = [2.0, 5.0, 10.0, np.pi, np.e] + + @pytest.mark.parametrize( + 'labelOnlyBase, exponent, locs, positions, expected', param_data) + @pytest.mark.parametrize('base', base_data) + def test_basic(self, labelOnlyBase, base, exponent, locs, positions, + expected): + formatter = mticker.LogFormatterExponent(base=base, + labelOnlyBase=labelOnlyBase) + formatter.create_dummy_axis() + formatter.axis.set_view_interval(1, base**exponent) + vals = base**locs + labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)] + expected = [label.replace('-', '\N{Minus Sign}') for label in expected] + assert labels == expected + + def test_blank(self): + # Should be a blank string for non-integer powers if labelOnlyBase=True + formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True) + formatter.create_dummy_axis() + formatter.axis.set_view_interval(1, 10) + assert formatter(10**0.1) == '' + + +class TestLogFormatterMathtext: + fmt = mticker.LogFormatterMathtext() + test_data = [ + (0, 1, '$\\mathdefault{10^{0}}$'), + (0, 1e-2, '$\\mathdefault{10^{-2}}$'), + (0, 1e2, '$\\mathdefault{10^{2}}$'), + (3, 1, '$\\mathdefault{1}$'), + (3, 1e-2, '$\\mathdefault{0.01}$'), + (3, 1e2, '$\\mathdefault{100}$'), + (3, 1e-3, '$\\mathdefault{10^{-3}}$'), + (3, 1e3, '$\\mathdefault{10^{3}}$'), + ] + + @pytest.mark.parametrize('min_exponent, value, expected', test_data) + def test_min_exponent(self, min_exponent, value, expected): + with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}): + assert self.fmt(value) == expected + + +class TestLogFormatterSciNotation: + test_data = [ + (2, 0.03125, '$\\mathdefault{2^{-5}}$'), + (2, 1, '$\\mathdefault{2^{0}}$'), + (2, 32, '$\\mathdefault{2^{5}}$'), + (2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'), + (2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'), + (2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'), + (10, -1, '$\\mathdefault{-10^{0}}$'), + (10, 1e-05, '$\\mathdefault{10^{-5}}$'), + (10, 1, '$\\mathdefault{10^{0}}$'), + (10, 100000, '$\\mathdefault{10^{5}}$'), + (10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'), + (10, 2, '$\\mathdefault{2\\times10^{0}}$'), + (10, 200000, '$\\mathdefault{2\\times10^{5}}$'), + (10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'), + (10, 5, '$\\mathdefault{5\\times10^{0}}$'), + (10, 500000, '$\\mathdefault{5\\times10^{5}}$'), + ] + + @mpl.style.context('default') + @pytest.mark.parametrize('base, value, expected', test_data) + def test_basic(self, base, value, expected): + formatter = mticker.LogFormatterSciNotation(base=base) + with mpl.rc_context({'text.usetex': False}): + assert formatter(value) == expected + + +class TestLogFormatter: + pprint_data = [ + (3.141592654e-05, 0.001, '3.142e-5'), + (0.0003141592654, 0.001, '3.142e-4'), + (0.003141592654, 0.001, '3.142e-3'), + (0.03141592654, 0.001, '3.142e-2'), + (0.3141592654, 0.001, '3.142e-1'), + (3.141592654, 0.001, '3.142'), + (31.41592654, 0.001, '3.142e1'), + (314.1592654, 0.001, '3.142e2'), + (3141.592654, 0.001, '3.142e3'), + (31415.92654, 0.001, '3.142e4'), + (314159.2654, 0.001, '3.142e5'), + (1e-05, 0.001, '1e-5'), + (0.0001, 0.001, '1e-4'), + (0.001, 0.001, '1e-3'), + (0.01, 0.001, '1e-2'), + (0.1, 0.001, '1e-1'), + (1, 0.001, '1'), + (10, 0.001, '10'), + (100, 0.001, '100'), + (1000, 0.001, '1000'), + (10000, 0.001, '1e4'), + (100000, 0.001, '1e5'), + (3.141592654e-05, 0.015, '0'), + (0.0003141592654, 0.015, '0'), + (0.003141592654, 0.015, '0.003'), + (0.03141592654, 0.015, '0.031'), + (0.3141592654, 0.015, '0.314'), + (3.141592654, 0.015, '3.142'), + (31.41592654, 0.015, '31.416'), + (314.1592654, 0.015, '314.159'), + (3141.592654, 0.015, '3141.593'), + (31415.92654, 0.015, '31415.927'), + (314159.2654, 0.015, '314159.265'), + (1e-05, 0.015, '0'), + (0.0001, 0.015, '0'), + (0.001, 0.015, '0.001'), + (0.01, 0.015, '0.01'), + (0.1, 0.015, '0.1'), + (1, 0.015, '1'), + (10, 0.015, '10'), + (100, 0.015, '100'), + (1000, 0.015, '1000'), + (10000, 0.015, '10000'), + (100000, 0.015, '100000'), + (3.141592654e-05, 0.5, '0'), + (0.0003141592654, 0.5, '0'), + (0.003141592654, 0.5, '0.003'), + (0.03141592654, 0.5, '0.031'), + (0.3141592654, 0.5, '0.314'), + (3.141592654, 0.5, '3.142'), + (31.41592654, 0.5, '31.416'), + (314.1592654, 0.5, '314.159'), + (3141.592654, 0.5, '3141.593'), + (31415.92654, 0.5, '31415.927'), + (314159.2654, 0.5, '314159.265'), + (1e-05, 0.5, '0'), + (0.0001, 0.5, '0'), + (0.001, 0.5, '0.001'), + (0.01, 0.5, '0.01'), + (0.1, 0.5, '0.1'), + (1, 0.5, '1'), + (10, 0.5, '10'), + (100, 0.5, '100'), + (1000, 0.5, '1000'), + (10000, 0.5, '10000'), + (100000, 0.5, '100000'), + (3.141592654e-05, 5, '0'), + (0.0003141592654, 5, '0'), + (0.003141592654, 5, '0'), + (0.03141592654, 5, '0.03'), + (0.3141592654, 5, '0.31'), + (3.141592654, 5, '3.14'), + (31.41592654, 5, '31.42'), + (314.1592654, 5, '314.16'), + (3141.592654, 5, '3141.59'), + (31415.92654, 5, '31415.93'), + (314159.2654, 5, '314159.27'), + (1e-05, 5, '0'), + (0.0001, 5, '0'), + (0.001, 5, '0'), + (0.01, 5, '0.01'), + (0.1, 5, '0.1'), + (1, 5, '1'), + (10, 5, '10'), + (100, 5, '100'), + (1000, 5, '1000'), + (10000, 5, '10000'), + (100000, 5, '100000'), + (3.141592654e-05, 100, '0'), + (0.0003141592654, 100, '0'), + (0.003141592654, 100, '0'), + (0.03141592654, 100, '0'), + (0.3141592654, 100, '0.3'), + (3.141592654, 100, '3.1'), + (31.41592654, 100, '31.4'), + (314.1592654, 100, '314.2'), + (3141.592654, 100, '3141.6'), + (31415.92654, 100, '31415.9'), + (314159.2654, 100, '314159.3'), + (1e-05, 100, '0'), + (0.0001, 100, '0'), + (0.001, 100, '0'), + (0.01, 100, '0'), + (0.1, 100, '0.1'), + (1, 100, '1'), + (10, 100, '10'), + (100, 100, '100'), + (1000, 100, '1000'), + (10000, 100, '10000'), + (100000, 100, '100000'), + (3.141592654e-05, 1000000.0, '3.1e-5'), + (0.0003141592654, 1000000.0, '3.1e-4'), + (0.003141592654, 1000000.0, '3.1e-3'), + (0.03141592654, 1000000.0, '3.1e-2'), + (0.3141592654, 1000000.0, '3.1e-1'), + (3.141592654, 1000000.0, '3.1'), + (31.41592654, 1000000.0, '3.1e1'), + (314.1592654, 1000000.0, '3.1e2'), + (3141.592654, 1000000.0, '3.1e3'), + (31415.92654, 1000000.0, '3.1e4'), + (314159.2654, 1000000.0, '3.1e5'), + (1e-05, 1000000.0, '1e-5'), + (0.0001, 1000000.0, '1e-4'), + (0.001, 1000000.0, '1e-3'), + (0.01, 1000000.0, '1e-2'), + (0.1, 1000000.0, '1e-1'), + (1, 1000000.0, '1'), + (10, 1000000.0, '10'), + (100, 1000000.0, '100'), + (1000, 1000000.0, '1000'), + (10000, 1000000.0, '1e4'), + (100000, 1000000.0, '1e5'), + ] + + @pytest.mark.parametrize('value, domain, expected', pprint_data) + def test_pprint(self, value, domain, expected): + fmt = mticker.LogFormatter() + label = fmt._pprint_val(value, domain) + assert label == expected + + @pytest.mark.parametrize('value, long, short', [ + (0.0, "0", "0"), + (0, "0", "0"), + (-1.0, "-10^0", "-1"), + (2e-10, "2x10^-10", "2e-10"), + (1e10, "10^10", "1e+10"), + ]) + def test_format_data(self, value, long, short): + fig, ax = plt.subplots() + ax.set_xscale('log') + fmt = ax.xaxis.get_major_formatter() + assert fmt.format_data(value) == long + assert fmt.format_data_short(value) == short + + def _sub_labels(self, axis, subs=()): + """Test whether locator marks subs to be labeled.""" + fmt = axis.get_minor_formatter() + minor_tlocs = axis.get_minorticklocs() + fmt.set_locs(minor_tlocs) + coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs))) + label_expected = [round(c) in subs for c in coefs] + label_test = [fmt(x) != '' for x in minor_tlocs] + assert label_test == label_expected + + @mpl.style.context('default') + def test_sublabel(self): + # test label locator + fig, ax = plt.subplots() + ax.set_xscale('log') + ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[])) + ax.xaxis.set_minor_locator(mticker.LogLocator(base=10, + subs=np.arange(2, 10))) + ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True)) + ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False)) + # axis range above 3 decades, only bases are labeled + ax.set_xlim(1, 1e4) + fmt = ax.xaxis.get_major_formatter() + fmt.set_locs(ax.xaxis.get_majorticklocs()) + show_major_labels = [fmt(x) != '' + for x in ax.xaxis.get_majorticklocs()] + assert np.all(show_major_labels) + self._sub_labels(ax.xaxis, subs=[]) + + # For the next two, if the numdec threshold in LogFormatter.set_locs + # were 3, then the label sub would be 3 for 2-3 decades and (2, 5) + # for 1-2 decades. With a threshold of 1, subs are not labeled. + # axis range at 2 to 3 decades + ax.set_xlim(1, 800) + self._sub_labels(ax.xaxis, subs=[]) + + # axis range at 1 to 2 decades + ax.set_xlim(1, 80) + self._sub_labels(ax.xaxis, subs=[]) + + # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6 + ax.set_xlim(1, 8) + self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6]) + + # axis range at 0 to 0.4 decades, label all + ax.set_xlim(0.5, 0.9) + self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int)) + + @pytest.mark.parametrize('val', [1, 10, 100, 1000]) + def test_LogFormatter_call(self, val): + # test _num_to_string method used in __call__ + temp_lf = mticker.LogFormatter() + temp_lf.create_dummy_axis() + temp_lf.axis.set_view_interval(1, 10) + assert temp_lf(val) == str(val) + + @pytest.mark.parametrize('val', [1e-323, 2e-323, 10e-323, 11e-323]) + def test_LogFormatter_call_tiny(self, val): + # test coeff computation in __call__ + temp_lf = mticker.LogFormatter() + temp_lf.create_dummy_axis() + temp_lf.axis.set_view_interval(1, 10) + temp_lf(val) + + +class TestLogitFormatter: + @staticmethod + def logit_deformatter(string): + r""" + Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in + float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float + 0.5, + """ + match = re.match( + r"[^\d]*" + r"(?P1-)?" + r"(?P\d*\.?\d*)?" + r"(?:\\cdot)?" + r"(?:10\^\{(?P-?\d*)})?" + r"[^\d]*$", + string, + ) + if match: + comp = match["comp"] is not None + mantissa = float(match["mant"]) if match["mant"] else 1 + expo = int(match["expo"]) if match["expo"] is not None else 0 + value = mantissa * 10 ** expo + if match["mant"] or match["expo"] is not None: + if comp: + return 1 - value + return value + match = re.match( + r"[^\d]*\\frac\{(?P\d+)\}\{(?P\d+)\}[^\d]*$", string + ) + if match: + num, deno = float(match["num"]), float(match["deno"]) + return num / deno + raise ValueError("Not formatted by LogitFormatter") + + @pytest.mark.parametrize( + "fx, x", + [ + (r"STUFF0.41OTHERSTUFF", 0.41), + (r"STUFF1.41\cdot10^{-2}OTHERSTUFF", 1.41e-2), + (r"STUFF1-0.41OTHERSTUFF", 1 - 0.41), + (r"STUFF1-1.41\cdot10^{-2}OTHERSTUFF", 1 - 1.41e-2), + (r"STUFF", None), + (r"STUFF12.4e-3OTHERSTUFF", None), + ], + ) + def test_logit_deformater(self, fx, x): + if x is None: + with pytest.raises(ValueError): + TestLogitFormatter.logit_deformatter(fx) + else: + y = TestLogitFormatter.logit_deformatter(fx) + assert _LogitHelper.isclose(x, y) + + decade_test = sorted( + [10 ** (-i) for i in range(1, 10)] + + [1 - 10 ** (-i) for i in range(1, 10)] + + [1 / 2] + ) + + @pytest.mark.parametrize("x", decade_test) + def test_basic(self, x): + """ + Test the formatted value correspond to the value for ideal ticks in + logit space. + """ + formatter = mticker.LogitFormatter(use_overline=False) + formatter.set_locs(self.decade_test) + s = formatter(x) + x2 = TestLogitFormatter.logit_deformatter(s) + assert _LogitHelper.isclose(x, x2) + + @pytest.mark.parametrize("x", (-1, -0.5, -0.1, 1.1, 1.5, 2)) + def test_invalid(self, x): + """ + Test that invalid value are formatted with empty string without + raising exception. + """ + formatter = mticker.LogitFormatter(use_overline=False) + formatter.set_locs(self.decade_test) + s = formatter(x) + assert s == "" + + @pytest.mark.parametrize("x", 1 / (1 + np.exp(-np.linspace(-7, 7, 10)))) + def test_variablelength(self, x): + """ + The format length should change depending on the neighbor labels. + """ + formatter = mticker.LogitFormatter(use_overline=False) + for N in (10, 20, 50, 100, 200, 1000, 2000, 5000, 10000): + if x + 1 / N < 1: + formatter.set_locs([x - 1 / N, x, x + 1 / N]) + sx = formatter(x) + sx1 = formatter(x + 1 / N) + d = ( + TestLogitFormatter.logit_deformatter(sx1) + - TestLogitFormatter.logit_deformatter(sx) + ) + assert 0 < d < 2 / N + + lims_minor_major = [ + (True, (5e-8, 1 - 5e-8), ((25, False), (75, False))), + (True, (5e-5, 1 - 5e-5), ((25, False), (75, True))), + (True, (5e-2, 1 - 5e-2), ((25, True), (75, True))), + (False, (0.75, 0.76, 0.77), ((7, True), (25, True), (75, True))), + ] + + @pytest.mark.parametrize("method, lims, cases", lims_minor_major) + def test_minor_vs_major(self, method, lims, cases): + """ + Test minor/major displays. + """ + + if method: + min_loc = mticker.LogitLocator(minor=True) + ticks = min_loc.tick_values(*lims) + else: + ticks = np.array(lims) + min_form = mticker.LogitFormatter(minor=True) + for threshold, has_minor in cases: + min_form.set_minor_threshold(threshold) + formatted = min_form.format_ticks(ticks) + labelled = [f for f in formatted if len(f) > 0] + if has_minor: + assert len(labelled) > 0, (threshold, has_minor) + else: + assert len(labelled) == 0, (threshold, has_minor) + + def test_minor_number(self): + """ + Test the parameter minor_number + """ + min_loc = mticker.LogitLocator(minor=True) + min_form = mticker.LogitFormatter(minor=True) + ticks = min_loc.tick_values(5e-2, 1 - 5e-2) + for minor_number in (2, 4, 8, 16): + min_form.set_minor_number(minor_number) + formatted = min_form.format_ticks(ticks) + labelled = [f for f in formatted if len(f) > 0] + assert len(labelled) == minor_number + + def test_use_overline(self): + """ + Test the parameter use_overline + """ + x = 1 - 1e-2 + fx1 = r"$\mathdefault{1-10^{-2}}$" + fx2 = r"$\mathdefault{\overline{10^{-2}}}$" + form = mticker.LogitFormatter(use_overline=False) + assert form(x) == fx1 + form.use_overline(True) + assert form(x) == fx2 + form.use_overline(False) + assert form(x) == fx1 + + def test_one_half(self): + """ + Test the parameter one_half + """ + form = mticker.LogitFormatter() + assert r"\frac{1}{2}" in form(1/2) + form.set_one_half("1/2") + assert "1/2" in form(1/2) + form.set_one_half("one half") + assert "one half" in form(1/2) + + @pytest.mark.parametrize("N", (100, 253, 754)) + def test_format_data_short(self, N): + locs = np.linspace(0, 1, N)[1:-1] + form = mticker.LogitFormatter() + for x in locs: + fx = form.format_data_short(x) + if fx.startswith("1-"): + x2 = 1 - float(fx[2:]) + else: + x2 = float(fx) + assert abs(x - x2) < 1 / N + + +class TestFormatStrFormatter: + def test_basic(self): + # test % style formatter + tmp_form = mticker.FormatStrFormatter('%05d') + assert '00002' == tmp_form(2) + + +class TestStrMethodFormatter: + test_data = [ + ('{x:05d}', (2,), False, '00002'), + ('{x:05d}', (2,), True, '00002'), + ('{x:05d}', (-2,), False, '-0002'), + ('{x:05d}', (-2,), True, '\N{MINUS SIGN}0002'), + ('{x:03d}-{pos:02d}', (2, 1), False, '002-01'), + ('{x:03d}-{pos:02d}', (2, 1), True, '002-01'), + ('{x:03d}-{pos:02d}', (-2, 1), False, '-02-01'), + ('{x:03d}-{pos:02d}', (-2, 1), True, '\N{MINUS SIGN}02-01'), + ] + + @pytest.mark.parametrize('format, input, unicode_minus, expected', test_data) + def test_basic(self, format, input, unicode_minus, expected): + with mpl.rc_context({"axes.unicode_minus": unicode_minus}): + fmt = mticker.StrMethodFormatter(format) + assert fmt(*input) == expected + + +class TestEngFormatter: + # (unicode_minus, input, expected) where ''expected'' corresponds to the + # outputs respectively returned when (places=None, places=0, places=2) + # unicode_minus is a boolean value for the rcParam['axes.unicode_minus'] + raw_format_data = [ + (False, -1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')), + (True, -1234.56789, ('\N{MINUS SIGN}1.23457 k', '\N{MINUS SIGN}1 k', + '\N{MINUS SIGN}1.23 k')), + (False, -1.23456789, ('-1.23457', '-1', '-1.23')), + (True, -1.23456789, ('\N{MINUS SIGN}1.23457', '\N{MINUS SIGN}1', + '\N{MINUS SIGN}1.23')), + (False, -0.123456789, ('-123.457 m', '-123 m', '-123.46 m')), + (True, -0.123456789, ('\N{MINUS SIGN}123.457 m', '\N{MINUS SIGN}123 m', + '\N{MINUS SIGN}123.46 m')), + (False, -0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')), + (True, -0.00123456789, ('\N{MINUS SIGN}1.23457 m', '\N{MINUS SIGN}1 m', + '\N{MINUS SIGN}1.23 m')), + (True, -0.0, ('0', '0', '0.00')), + (True, -0, ('0', '0', '0.00')), + (True, 0, ('0', '0', '0.00')), + (True, 1.23456789e-6, ('1.23457 µ', '1 µ', '1.23 µ')), + (True, 0.123456789, ('123.457 m', '123 m', '123.46 m')), + (True, 0.1, ('100 m', '100 m', '100.00 m')), + (True, 1, ('1', '1', '1.00')), + (True, 1.23456789, ('1.23457', '1', '1.23')), + # places=0: corner-case rounding + (True, 999.9, ('999.9', '1 k', '999.90')), + # corner-case rounding for all + (True, 999.9999, ('1 k', '1 k', '1.00 k')), + # negative corner-case + (False, -999.9999, ('-1 k', '-1 k', '-1.00 k')), + (True, -999.9999, ('\N{MINUS SIGN}1 k', '\N{MINUS SIGN}1 k', + '\N{MINUS SIGN}1.00 k')), + (True, 1000, ('1 k', '1 k', '1.00 k')), + (True, 1001, ('1.001 k', '1 k', '1.00 k')), + (True, 100001, ('100.001 k', '100 k', '100.00 k')), + (True, 987654.321, ('987.654 k', '988 k', '987.65 k')), + # OoR value (> 1000 Q) + (True, 1.23e33, ('1230 Q', '1230 Q', '1230.00 Q')) + ] + + @pytest.mark.parametrize('unicode_minus, input, expected', raw_format_data) + def test_params(self, unicode_minus, input, expected): + """ + Test the formatting of EngFormatter for various values of the 'places' + argument, in several cases: + + 0. without a unit symbol but with a (default) space separator; + 1. with both a unit symbol and a (default) space separator; + 2. with both a unit symbol and some non default separators; + 3. without a unit symbol but with some non default separators. + + Note that cases 2. and 3. are looped over several separator strings. + """ + + plt.rcParams['axes.unicode_minus'] = unicode_minus + UNIT = 's' # seconds + DIGITS = '0123456789' # %timeit showed 10-20% faster search than set + + # Case 0: unit='' (default) and sep=' ' (default). + # 'expected' already corresponds to this reference case. + exp_outputs = expected + formatters = ( + mticker.EngFormatter(), # places=None (default) + mticker.EngFormatter(places=0), + mticker.EngFormatter(places=2) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Case 1: unit=UNIT and sep=' ' (default). + # Append a unit symbol to the reference case. + # Beware of the values in [1, 1000), where there is no prefix! + exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix + else _s + UNIT for _s in expected) + formatters = ( + mticker.EngFormatter(unit=UNIT), # places=None (default) + mticker.EngFormatter(unit=UNIT, places=0), + mticker.EngFormatter(unit=UNIT, places=2) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Test several non default separators: no separator, a narrow + # no-break space (Unicode character) and an extravagant string. + for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"): + # Case 2: unit=UNIT and sep=_sep. + # Replace the default space separator from the reference case + # with the tested one `_sep` and append a unit symbol to it. + exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix + else _s.replace(" ", _sep) + UNIT + for _s in expected) + formatters = ( + mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None + mticker.EngFormatter(unit=UNIT, places=0, sep=_sep), + mticker.EngFormatter(unit=UNIT, places=2, sep=_sep) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Case 3: unit='' (default) and sep=_sep. + # Replace the default space separator from the reference case + # with the tested one `_sep`. Reference case is already unitless. + exp_outputs = (_s.replace(" ", _sep) for _s in expected) + formatters = ( + mticker.EngFormatter(sep=_sep), # places=None (default) + mticker.EngFormatter(places=0, sep=_sep), + mticker.EngFormatter(places=2, sep=_sep) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + +def test_engformatter_usetex_useMathText(): + fig, ax = plt.subplots() + ax.plot([0, 500, 1000], [0, 500, 1000]) + ax.set_xticks([0, 500, 1000]) + for formatter in (mticker.EngFormatter(usetex=True), + mticker.EngFormatter(useMathText=True)): + ax.xaxis.set_major_formatter(formatter) + fig.canvas.draw() + x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()] + # Checking if the dollar `$` signs have been inserted around numbers + # in tick labels. + assert x_tick_label_text == ['$0$', '$500$', '$1$ k'] + + +@pytest.mark.parametrize( + 'data_offset, noise, oom_center_desired, oom_noise_desired', [ + (271_490_000_000.0, 10, 9, 0), + (27_149_000_000_000.0, 10_000_000, 12, 6), + (27.149, 0.01, 0, -3), + (2_714.9, 0.01, 3, -3), + (271_490.0, 0.001, 3, -3), + (271.49, 0.001, 0, -3), + # The following sets of parameters demonstrates that when + # oom(data_offset)-1 and oom(noise)-2 equal a standard 3*N oom, we get + # that oom_noise_desired < oom(noise) + (27_149_000_000.0, 100, 9, +3), + (27.149, 1e-07, 0, -6), + (271.49, 0.0001, 0, -3), + (27.149, 0.0001, 0, -3), + # Tests where oom(data_offset) <= oom(noise), those are probably + # covered by the part where formatter.offset != 0 + (27_149.0, 10_000, 0, 3), + (27.149, 10_000, 0, 3), + (27.149, 1_000, 0, 3), + (27.149, 100, 0, 0), + (27.149, 10, 0, 0), + ] +) +def test_engformatter_offset_oom( + data_offset, + noise, + oom_center_desired, + oom_noise_desired +): + UNIT = "eV" + fig, ax = plt.subplots() + ydata = data_offset + np.arange(-5, 7, dtype=float)*noise + ax.plot(ydata) + formatter = mticker.EngFormatter(useOffset=True, unit=UNIT) + # So that offset strings will always have the same size + formatter.ENG_PREFIXES[0] = "_" + ax.yaxis.set_major_formatter(formatter) + fig.canvas.draw() + offset_got = formatter.get_offset() + ticks_got = [labl.get_text() for labl in ax.get_yticklabels()] + # Predicting whether offset should be 0 or not is essentially testing + # ScalarFormatter._compute_offset . This function is pretty complex and it + # would be nice to test it, but this is out of scope for this test which + # only makes sure that offset text and the ticks gets the correct unit + # prefixes and the ticks. + if formatter.offset: + prefix_noise_got = offset_got[2] + prefix_noise_desired = formatter.ENG_PREFIXES[oom_noise_desired] + prefix_center_got = offset_got[-1-len(UNIT)] + prefix_center_desired = formatter.ENG_PREFIXES[oom_center_desired] + assert prefix_noise_desired == prefix_noise_got + assert prefix_center_desired == prefix_center_got + # Make sure the ticks didn't get the UNIT + for tick in ticks_got: + assert UNIT not in tick + else: + assert oom_center_desired == 0 + assert offset_got == "" + # Make sure the ticks contain now the prefixes + for tick in ticks_got: + # 0 is zero on all orders of magnitudes, no matter what is + # oom_noise_desired + prefix_idx = 0 if tick[0] == "0" else oom_noise_desired + assert tick.endswith(formatter.ENG_PREFIXES[prefix_idx] + UNIT) + + +class TestPercentFormatter: + percent_data = [ + # Check explicitly set decimals over different intervals and values + (100, 0, '%', 120, 100, '120%'), + (100, 0, '%', 100, 90, '100%'), + (100, 0, '%', 90, 50, '90%'), + (100, 0, '%', -1.7, 40, '-2%'), + (100, 1, '%', 90.0, 100, '90.0%'), + (100, 1, '%', 80.1, 90, '80.1%'), + (100, 1, '%', 70.23, 50, '70.2%'), + # 60.554 instead of 60.55: see https://bugs.python.org/issue5118 + (100, 1, '%', -60.554, 40, '-60.6%'), + # Check auto decimals over different intervals and values + (100, None, '%', 95, 1, '95.00%'), + (1.0, None, '%', 3, 6, '300%'), + (17.0, None, '%', 1, 8.5, '6%'), + (17.0, None, '%', 1, 8.4, '5.9%'), + (5, None, '%', -100, 0.000001, '-2000.00000%'), + # Check percent symbol + (1.0, 2, None, 1.2, 100, '120.00'), + (75, 3, '', 50, 100, '66.667'), + (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'), + ] + + percent_ids = [ + # Check explicitly set decimals over different intervals and values + 'decimals=0, x>100%', + 'decimals=0, x=100%', + 'decimals=0, x<100%', + 'decimals=0, x<0%', + 'decimals=1, x>100%', + 'decimals=1, x=100%', + 'decimals=1, x<100%', + 'decimals=1, x<0%', + # Check auto decimals over different intervals and values + 'autodecimal, x<100%, display_range=1', + 'autodecimal, x>100%, display_range=6 (custom xmax test)', + 'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)', + 'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)', + 'autodecimal, x<-100%, display_range=1e-6 (tiny display range)', + # Check percent symbol + 'None as percent symbol', + 'Empty percent symbol', + 'Custom percent symbol', + ] + + latex_data = [ + (False, False, r'50\{t}%'), + (False, True, r'50\\\{t\}\%'), + (True, False, r'50\{t}%'), + (True, True, r'50\{t}%'), + ] + + @pytest.mark.parametrize( + 'xmax, decimals, symbol, x, display_range, expected', + percent_data, ids=percent_ids) + def test_basic(self, xmax, decimals, symbol, + x, display_range, expected): + formatter = mticker.PercentFormatter(xmax, decimals, symbol) + with mpl.rc_context(rc={'text.usetex': False}): + assert formatter.format_pct(x, display_range) == expected + + @pytest.mark.parametrize('is_latex, usetex, expected', latex_data) + def test_latex(self, is_latex, usetex, expected): + fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex) + with mpl.rc_context(rc={'text.usetex': usetex}): + assert fmt.format_pct(50, 100) == expected + + +def _impl_locale_comma(): + try: + locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8') + except locale.Error: + print('SKIP: Locale de_DE.UTF-8 is not supported on this machine') + return + ticks = mticker.ScalarFormatter(useMathText=True, useLocale=True) + fmt = '$\\mathdefault{%1.1f}$' + x = ticks._format_maybe_minus_and_locale(fmt, 0.5) + assert x == '$\\mathdefault{0{,}5}$' + # Do not change , in the format string + fmt = ',$\\mathdefault{,%1.1f},$' + x = ticks._format_maybe_minus_and_locale(fmt, 0.5) + assert x == ',$\\mathdefault{,0{,}5},$' + # Make sure no brackets are added if not using math text + ticks = mticker.ScalarFormatter(useMathText=False, useLocale=True) + fmt = '%1.1f' + x = ticks._format_maybe_minus_and_locale(fmt, 0.5) + assert x == '0,5' + + +def test_locale_comma(): + # On some systems/pytest versions, `pytest.skip` in an exception handler + # does not skip, but is treated as an exception, so directly running this + # test can incorrectly fail instead of skip. + # Instead, run this test in a subprocess, which avoids the problem, and the + # need to fix the locale after. + proc = mpl.testing.subprocess_run_helper(_impl_locale_comma, timeout=60, + extra_env={'MPLBACKEND': 'Agg'}) + skip_msg = next((line[len('SKIP:'):].strip() + for line in proc.stdout.splitlines() + if line.startswith('SKIP:')), + '') + if skip_msg: + pytest.skip(skip_msg) + + +def test_majformatter_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_major_formatter(mticker.LogLocator()) + + +def test_minformatter_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_minor_formatter(mticker.LogLocator()) + + +def test_majlocator_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_major_locator(mticker.LogFormatter()) + + +def test_minlocator_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_minor_locator(mticker.LogFormatter()) + + +def test_minorticks_rc(): + fig = plt.figure() + + def minorticksubplot(xminor, yminor, i): + rc = {'xtick.minor.visible': xminor, + 'ytick.minor.visible': yminor} + with plt.rc_context(rc=rc): + ax = fig.add_subplot(2, 2, i) + + assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor + assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor + + minorticksubplot(False, False, 1) + minorticksubplot(True, False, 2) + minorticksubplot(False, True, 3) + minorticksubplot(True, True, 4) + + +def test_minorticks_toggle(): + """ + Test toggling minor ticks + + Test `.Axis.minorticks_on()` and `.Axis.minorticks_off()`. Testing is + limited to a subset of built-in scales - `'linear'`, `'log'`, `'asinh'` + and `'logit'`. `symlog` scale does not seem to have a working minor + locator and is omitted. In future, this test should cover all scales in + `matplotlib.scale.get_scale_names()`. + """ + fig = plt.figure() + def minortickstoggle(xminor, yminor, scale, i): + ax = fig.add_subplot(2, 2, i) + ax.set_xscale(scale) + ax.set_yscale(scale) + if not xminor and not yminor: + ax.minorticks_off() + if xminor and not yminor: + ax.xaxis.minorticks_on() + ax.yaxis.minorticks_off() + if not xminor and yminor: + ax.xaxis.minorticks_off() + ax.yaxis.minorticks_on() + if xminor and yminor: + ax.minorticks_on() + + assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor + assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor + + scales = ['linear', 'log', 'asinh', 'logit'] + for scale in scales: + minortickstoggle(False, False, scale, 1) + minortickstoggle(True, False, scale, 2) + minortickstoggle(False, True, scale, 3) + minortickstoggle(True, True, scale, 4) + fig.clear() + + plt.close(fig) + + +@pytest.mark.parametrize('remove_overlapping_locs, expected_num', + ((True, 6), + (None, 6), # this tests the default + (False, 9))) +def test_remove_overlap(remove_overlapping_locs, expected_num): + t = np.arange("2018-11-03", "2018-11-06", dtype="datetime64") + x = np.ones(len(t)) + + fig, ax = plt.subplots() + ax.plot(t, x) + + ax.xaxis.set_major_locator(mpl.dates.DayLocator()) + ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%a')) + + ax.xaxis.set_minor_locator(mpl.dates.HourLocator((0, 6, 12, 18))) + ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%H:%M')) + # force there to be extra ticks + ax.xaxis.get_minor_ticks(15) + if remove_overlapping_locs is not None: + ax.xaxis.remove_overlapping_locs = remove_overlapping_locs + + # check that getter/setter exists + current = ax.xaxis.remove_overlapping_locs + assert (current == ax.xaxis.get_remove_overlapping_locs()) + plt.setp(ax.xaxis, remove_overlapping_locs=current) + new = ax.xaxis.remove_overlapping_locs + assert (new == ax.xaxis.remove_overlapping_locs) + + # check that the accessors filter correctly + # this is the method that does the actual filtering + assert len(ax.xaxis.get_minorticklocs()) == expected_num + # these three are derivative + assert len(ax.xaxis.get_minor_ticks()) == expected_num + assert len(ax.xaxis.get_minorticklabels()) == expected_num + assert len(ax.xaxis.get_minorticklines()) == expected_num*2 + + +@pytest.mark.parametrize('sub', [ + ['hi', 'aardvark'], + np.zeros((2, 2))]) +def test_bad_locator_subs(sub): + ll = mticker.LogLocator() + with pytest.raises(ValueError): + ll.set_params(subs=sub) + + +@pytest.mark.parametrize('numticks', [1, 2, 3, 9]) +@mpl.style.context('default') +def test_small_range_loglocator(numticks): + ll = mticker.LogLocator() + ll.set_params(numticks=numticks) + for top in [5, 7, 9, 11, 15, 50, 100, 1000]: + ticks = ll.tick_values(.5, top) + assert (np.diff(np.log10(ll.tick_values(6, 150))) == 1).all() + + +def test_NullFormatter(): + formatter = mticker.NullFormatter() + assert formatter(1.0) == '' + assert formatter.format_data(1.0) == '' + assert formatter.format_data_short(1.0) == '' + + +@pytest.mark.parametrize('formatter', ( + mticker.FuncFormatter(lambda a: f'val: {a}'), + mticker.FixedFormatter(('foo', 'bar')))) +def test_set_offset_string(formatter): + assert formatter.get_offset() == '' + formatter.set_offset_string('mpl') + assert formatter.get_offset() == 'mpl' + + +def test_minorticks_on_multi_fig(): + """ + Turning on minor gridlines in a multi-Axes Figure + that contains more than one boxplot and shares the x-axis + should not raise an exception. + """ + fig, ax = plt.subplots() + + ax.boxplot(np.arange(10), positions=[0]) + ax.boxplot(np.arange(10), positions=[0]) + ax.boxplot(np.arange(10), positions=[1]) + + ax.grid(which="major") + ax.grid(which="minor") + ax.minorticks_on() + fig.draw_without_rendering() + + assert ax.get_xgridlines() + assert isinstance(ax.xaxis.get_minor_locator(), mpl.ticker.AutoMinorLocator) diff --git a/shared/package-files/06/0642d38ff9e1addb42a845d6134f25a72d72b3a55c01e5022fdc234fe6329003/model.py b/shared/package-files/06/0642d38ff9e1addb42a845d6134f25a72d72b3a55c01e5022fdc234fe6329003/model.py new file mode 100644 index 0000000000000000000000000000000000000000..6fdb0bbd3ef9bf6b61c13fef6417d27116915d17 --- /dev/null +++ b/shared/package-files/06/0642d38ff9e1addb42a845d6134f25a72d72b3a55c01e5022fdc234fe6329003/model.py @@ -0,0 +1,3140 @@ +from __future__ import annotations + +from statsmodels.compat.python import lzip + +from collections import defaultdict +from functools import reduce +import warnings + +import numpy as np +import pandas as pd +from scipy import stats + +from statsmodels.base.data import handle_data +from statsmodels.base.optimizer import Optimizer +import statsmodels.base.wrapper as wrap +from statsmodels.formula import handle_formula_data +from statsmodels.formula._manager import FormulaManager +from statsmodels.stats.contrast import ( + ContrastResults, + WaldTestResults, + t_test_pairwise, +) +from statsmodels.tools._decorators import ( + cache_readonly, + cached_data, + cached_value, +) +from statsmodels.tools.data import _is_using_pandas +from statsmodels.tools.numdiff import approx_fprime +from statsmodels.tools.rng_qrng import check_random_state +from statsmodels.tools.sm_exceptions import ( + HessianInversionWarning, + ValueWarning, +) +from statsmodels.tools.tools import nan_dot, recipr +from statsmodels.tools.validation import bool_like + +ERROR_INIT_KWARGS = False + +_model_params_doc = """Parameters + ---------- + endog : array_like + A 1-d endogenous response variable. The dependent variable. + exog : array_like, optional + A nobs x k array where `nobs` is the number of observations and `k` + is the number of regressors. An intercept is not included by default + and should be added by the user. See + :func:`statsmodels.tools.add_constant`.""" + +_missing_param_doc = """\ +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'.""" +_extra_param_doc = """ + hasconst : None or bool, optional + Indicates whether the RHS includes a user-supplied constant. If True, + a constant is not checked for and k_constant is set to 1 and all + result statistics are calculated as if a constant is present. If + False, a constant is not checked for and k_constant is set to 0. + **kwargs + Extra arguments that are used to set model properties when using the + formula interface.""" + + +class Model: + __doc__ = f""" + A (predictive) statistical model. Intended to be subclassed, not used + directly + + {_model_params_doc} + {_missing_param_doc + _extra_param_doc} + + Attributes + ---------- + exog_names + endog_names + + Notes + ----- + `endog` and `exog` are references to any data provided. So if the data is + already stored in numpy arrays and it is changed then `endog` and `exog` + will change as well. + """ + + # Maximum number of endogenous variables when using a formula + # Default is 1, which is more common. Override in models when needed + # Set to None to skip check + _formula_max_endog = 1 + # kwargs that are generically allowed, maybe not supported in all models + _kwargs_allowed = [ + "missing", + "missing_idx", + "formula", + "model_spec", + "hasconst", + ] + + def __init__(self, endog, exog=None, **kwargs): + missing = kwargs.pop("missing", "none") + hasconst = kwargs.pop("hasconst", None) + self.data = self._handle_data(endog, exog, missing, hasconst, **kwargs) + self.k_constant = self.data.k_constant + self.exog = self.data.exog + self.endog = self.data.endog + self._data_attr = [] + self._data_attr.extend(["exog", "endog", "data.exog", "data.endog"]) + if "formula" not in kwargs: # will not be able to unpickle without these + self._data_attr.extend(["data.orig_endog", "data.orig_exog"]) + # store keys for extras if we need to recreate model instance + # we do not need 'missing', maybe we need 'hasconst' + self._init_keys = list(kwargs.keys()) + if hasconst is not None: + self._init_keys.append("hasconst") + + def _get_init_kwds(self): + """Return dictionary with extra keys used in model.__init__""" + kwds = {key: getattr(self, key, None) for key in self._init_keys} + + return kwds + + def _check_kwargs(self, kwargs, keys_extra=None, error=ERROR_INIT_KWARGS): + + kwargs_allowed = [ + "missing", + "missing_idx", + "formula", + "model_spec", + "hasconst", + ] + if keys_extra: + kwargs_allowed.extend(keys_extra) + + kwargs_invalid = [i for i in kwargs if i not in kwargs_allowed] + if kwargs_invalid: + msg = "unknown kwargs " + repr(kwargs_invalid) + if error is False: + warnings.warn(msg, ValueWarning, stacklevel=2) + else: + raise ValueError(msg) + + def _handle_data(self, endog, exog, missing, hasconst, **kwargs): + data = handle_data(endog, exog, missing, hasconst, **kwargs) + # kwargs arrays could have changed, easier to just attach here + for key in kwargs: + if key in ["model_spec", "formula"]: # leave attached to data + continue + # pop so we do not start keeping all these twice or references + try: + setattr(self, key, data.__dict__.pop(key)) + except KeyError: # panel already pops keys in data handling + pass + return data + + @classmethod + def from_formula(cls, formula, data, subset=None, drop_cols=None, *args, **kwargs): + """ + Create a Model from a formula and dataframe + + Parameters + ---------- + formula : str or generic Formula object + The formula specifying the model. + data : array_like + The data for the model. See Notes. + subset : array_like, optional + An array-like object of booleans, integers, or index values that + indicate the subset of df to use in the model. Assumes df is a + `pandas.DataFrame`. + drop_cols : array_like, optional + Columns to drop from the design matrix. Cannot be used to + drop terms involving categoricals. + *args + Additional positional argument that are passed to the model. + **kwargs + These are passed to the model with one exception. The + ``eval_env`` keyword is passed to patsy. It can be either a + :class:`patsy:patsy.EvalEnvironment` object or an integer + indicating the depth of the namespace to use. For example, the + default ``eval_env=0`` uses the calling namespace. If you wish + to use a "clean" environment set ``eval_env=-1``. + + Returns + ------- + model + The model instance. + + Notes + ----- + data must define __getitem__ with the keys in the formula terms + args and kwargs are passed on to the model instantiation. E.g., + a numpy structured or rec array, a dictionary, or a pandas DataFrame. + """ + # TODO: provide a docs template for args/kwargs from child models + # TODO: subset could use syntax. issue #469. + mgr = FormulaManager() + if subset is not None: + data = data.loc[subset] + eval_env = kwargs.pop("eval_env", None) + if eval_env is None: + eval_env = 2 + elif eval_env == -1: + eval_env = mgr.get_empty_eval_env() + elif isinstance(eval_env, int): + eval_env += 1 # we're going down the stack again + missing = kwargs.get("missing", "drop") + if missing == "none": # with patsy it's drop or raise. let's raise. + missing = "raise" + + tmp = handle_formula_data(data, None, formula, depth=eval_env, missing=missing) + (endog, exog), missing_idx, model_spec = tmp + max_endog = cls._formula_max_endog + if max_endog is not None and endog.ndim > 1 and endog.shape[1] > max_endog: + raise ValueError( + "endog has evaluated to an array with multiple " + f"columns that has shape {endog.shape}. This occurs when " + "the variable converted to endog is non-numeric" + " (e.g., bool or str)." + ) + if drop_cols is not None and len(drop_cols) > 0: + cols = [x for x in exog.columns if x not in drop_cols] + if len(cols) < len(exog.columns): + exog = exog[cols] + spec_cols = list(mgr.get_term_names(model_spec)) + for col in drop_cols: + try: + if mgr.engine == "formulaic" and col == "Intercept": + col = "1" + spec_cols.remove(col) + except ValueError: + pass # OK if not present + # TODO: Patsy migration, need to add method to handle + model_spec = model_spec.subset(spec_cols) + + kwargs.update( + { + "missing_idx": missing_idx, + "missing": missing, + "formula": formula, # attach formula for unpckling + "model_spec": model_spec, + } + ) + mod = cls(endog, exog, *args, **kwargs) + mod.formula = formula + # since we got a dataframe, attach the original + mod.data.frame = data + return mod + + @property + def endog_names(self): + """Names of endogenous variables""" + return self.data.ynames + + @property + def exog_names(self) -> list[str] | None: + """Names of exogenous variables""" + return self.data.xnames + + def fit(self): + """Fit a model to data""" + raise NotImplementedError + + def predict(self, params, exog=None, *args, **kwargs): + """ + After a model has been fit, predict returns the fitted values + + This is a placeholder intended to be overwritten by individual models. + + Parameters + ---------- + params : array_like + The model parameters. + exog : array_like, optional + The values for which you want to predict. + *args + Additional positional arguments to pass to the model. + **kwargs + Additional keyword arguments to pass to the model. + """ + raise NotImplementedError + + +class LikelihoodModel(Model): + """Likelihood model is a subclass of Model""" + + def __init__(self, endog, exog=None, **kwargs): + super().__init__(endog, exog, **kwargs) + self.initialize() + + def initialize(self): + """ + Initialize (possibly re-initialize) a Model instance + + For example, if the design matrix of a linear model changes then + initialize can be used to recompute values using the modified design + matrix. + """ + + # TODO: if the intent is to re-initialize the model with new data then this + # method needs to take inputs... + + def loglike(self, params): + """ + Log-likelihood of model + + Parameters + ---------- + params : ndarray + The model parameters used to compute the log-likelihood. + + Returns + ------- + float + The log-likelihood value evaluated at `params`. + + Notes + ----- + Must be overridden by subclasses. + """ + raise NotImplementedError + + def score(self, params): + """ + Score vector of model + + The gradient of logL with respect to each parameter. + + Parameters + ---------- + params : ndarray + The parameters to use when evaluating the score. + + Returns + ------- + ndarray + The score vector evaluated at the parameters. + """ + raise NotImplementedError + + def information(self, params): + """ + Fisher information matrix of model + + Returns -1 * Hessian of the log-likelihood evaluated at params. + + Parameters + ---------- + params : ndarray + The model parameters. + + Returns + ------- + ndarray + The information matrix evaluated at the parameters. + """ + raise NotImplementedError + + def hessian(self, params): + """ + The Hessian matrix of the model + + Parameters + ---------- + params : ndarray + The parameters to use when evaluating the Hessian. + + Returns + ------- + ndarray + The hessian evaluated at the parameters. + """ + raise NotImplementedError + + def fit( + self, + start_params=None, + method="newton", + maxiter=100, + full_output=True, + disp=True, + fargs=(), + callback=None, + retall=False, + skip_hessian=False, + **kwargs, + ): + """ + Fit method for likelihood based models + + Parameters + ---------- + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + method : str, optional + The `method` determines which solver from `scipy.optimize` + is used, and it can be chosen from among the following strings: + + - 'newton' for Newton-Raphson, 'nm' for Nelder-Mead + - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + - 'lbfgs' for limited-memory BFGS with optional box constraints + - 'powell' for modified Powell's method + - 'cg' for conjugate gradient + - 'ncg' for Newton-conjugate gradient + - 'basinhopping' for global basin-hopping solver + - 'minimize' for generic wrapper of scipy minimize (BFGS by default) + + The explicit arguments in `fit` are passed to the solver, + with the exception of the basin-hopping solver. Each + solver has several optional arguments that are not the same across + solvers. See the notes section below (or scipy.optimize) for the + available arguments and for the list of explicit arguments that the + basin-hopping solver supports. + maxiter : int, optional + The maximum number of iterations to perform. + full_output : bool, optional + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + disp : bool, optional + Set to True to print convergence messages. + fargs : tuple, optional + Extra arguments passed to the likelihood function, i.e., + loglike(x,*args) + callback : callable callback(xk), optional + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool, optional + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + skip_hessian : bool, optional + If False (default), then the negative inverse hessian is calculated + after the optimization. If True, then the hessian will not be + calculated. However, it will be available in methods that use the + hessian in the optimization (currently only with `"newton"`). + **kwargs + All kwargs are passed to the chosen solver with one exception. The + following keyword controls what happens after the fit:: + + warn_convergence : bool, optional + If True, checks the model for the converged flag. If the + converged flag is False, a ConvergenceWarning is issued. + + Returns + ------- + LikelihoodModelResults + The fitted model results. + + Notes + ----- + The 'basinhopping' solver ignores `maxiter`, `retall`, `full_output` + explicit arguments. + + Optional arguments for solvers (see returned Results.mle_settings):: + + 'newton' + tol : float + Relative error in params acceptable for convergence. + 'nm' -- Nelder Mead + xtol : float + Relative error in params acceptable for convergence + ftol : float + Relative error in loglike(params) acceptable for + convergence + maxfun : int + Maximum number of function evaluations to make. + 'bfgs' + gtol : float + Stop when norm of gradient is less than gtol. + norm : float + Order of norm (np.inf is max, -np.inf is min) + epsilon + If fprime is approximated, use this value for the step + size. Only relevant if LikelihoodModel.score is None. + 'lbfgs' + m : int + This many terms are used for the Hessian approximation. + factr : float + A stop condition that is a variant of relative error. + pgtol : float + A stop condition that uses the projected gradient. + epsilon + If fprime is approximated, use this value for the step + size. Only relevant if LikelihoodModel.score is None. + maxfun : int + Maximum number of function evaluations to make. + bounds : sequence + (min, max) pairs for each element in x, + defining the bounds on that parameter. + Use None for one of min or max when there is no bound + in that direction. + 'cg' + gtol : float + Stop when norm of gradient is less than gtol. + norm : float + Order of norm (np.inf is max, -np.inf is min) + epsilon : float + If fprime is approximated, use this value for the step + size. Can be scalar or vector. Only relevant if + Likelihoodmodel.score is None. + 'ncg' + fhess_p : callable f'(x,*args) + Function which computes the Hessian of f times an arbitrary + vector, p. Should only be supplied if + LikelihoodModel.hessian is None. + avextol : float + Stop when the average relative error in the minimizer + falls below this amount. + epsilon : float or ndarray + If fhess is approximated, use this value for the step size. + Only relevant if Likelihoodmodel.hessian is None. + 'powell' + xtol : float + Line-search error tolerance + ftol : float + Relative error in loglike(params) for acceptable for + convergence. + maxfun : int + Maximum number of function evaluations to make. + start_direc : ndarray + Initial direction set. + 'basinhopping' + niter : int + The number of basin hopping iterations. + niter_success : int + Stop the run if the global minimum candidate remains the + same for this number of iterations. + T : float + The "temperature" parameter for the accept or reject + criterion. Higher "temperatures" mean that larger jumps + in function value will be accepted. For best results + `T` should be comparable to the separation (in function + value) between local minima. + stepsize : float + Initial step size for use in the random displacement. + interval : int + The interval for how often to update the `stepsize`. + minimizer : dict + Extra keyword arguments to be passed to the minimizer + `scipy.optimize.minimize()`, for example 'method' - the + minimization method (e.g., 'L-BFGS-B'), or 'tol' - the + tolerance for termination. Other arguments are mapped from + explicit argument of `fit`: + - `args` <- `fargs` + - `jac` <- `score` + - `hess` <- `hess` + 'minimize' + min_method : str, optional + Name of minimization method to use. + Any method specific arguments can be passed directly. + For a list of methods and their arguments, see + documentation of `scipy.optimize.minimize`. + If no method is specified, then BFGS is used. + """ + if not full_output: + warnings.warn( + "full_output=False is deprecated and has no effect; fit always " + "computes the full optimizer output, which is required to know " + "whether the optimizer converged. This argument will be removed " + "in a future version.", + FutureWarning, + stacklevel=2, + ) + full_output = True + + Hinv = None # JP error if full_output=0, Hinv not defined + + if start_params is None: + if hasattr(self, "start_params"): + start_params = self.start_params + elif self.exog is not None: + # fails for shape (K,)? + start_params = [0.0] * self.exog.shape[1] + else: + raise ValueError( + "If exog is None, then start_params should be specified" + ) + + # TODO: separate args from nonarg taking score and hessian, ie., + # user-supplied and numerically evaluated estimate frprime does not take + # args in most (any?) of the optimize function + + nobs = self.endog.shape[0] + + def f(params, *args): + return -self.loglike(params, *args) / nobs + + def score(params, *args): + return -self.score(params, *args) / nobs + + def hess(params, *args): + return -self.hessian(params, *args) / nobs + + warn_convergence = kwargs.pop("warn_convergence", True) + + # Remove covariance args before calling fir to allow strict checking + if "cov_type" in kwargs: + cov_kwds = kwargs.get("cov_kwds", {}) + kwds = {"cov_type": kwargs["cov_type"], "cov_kwds": cov_kwds} + if cov_kwds: + del kwargs["cov_kwds"] + del kwargs["cov_type"] + else: + kwds = {} + if "use_t" in kwargs: + kwds["use_t"] = kwargs["use_t"] + del kwargs["use_t"] + + optimizer = Optimizer() + xopt, retvals, optim_settings = optimizer._fit( + f, + score, + start_params, + fargs, + kwargs, + hessian=hess, + method=method, + disp=disp, + maxiter=maxiter, + callback=callback, + retall=retall, + full_output=full_output, + ) + # Restore cov_type, cov_kwds and use_t + optim_settings.update(kwds) + # NOTE: this is for fit_regularized and should be generalized + cov_params_func = kwargs.setdefault("cov_params_func", None) + if cov_params_func: + Hinv = cov_params_func(self, xopt, retvals) + elif method == "newton" and full_output: + Hinv = np.linalg.inv(retvals["Hessian"]) / nobs + elif not skip_hessian: + H = -1 * self.hessian(xopt) + invertible = False + if np.all(np.isfinite(H)): + eigvals, eigvecs = np.linalg.eigh(H) + if np.min(eigvals) > 0: + invertible = True + + if invertible: + Hinv = eigvecs.dot(np.diag(1.0 / eigvals)).dot(eigvecs.T) + Hinv = np.asfortranarray((Hinv + Hinv.T) / 2.0) + else: + warnings.warn( + "Inverting hessian failed, no bse or cov_params available", + HessianInversionWarning, + stacklevel=2, + ) + Hinv = None + + # TODO: add Hessian approximation and change the above if needed + mlefit = LikelihoodModelResults(self, xopt, Hinv, scale=1.0, **kwds) + + # TODO: hardcode scale? + mlefit.mle_retvals = retvals + if isinstance(retvals, dict): + if warn_convergence and not retvals["converged"]: + from statsmodels.tools.sm_exceptions import ConvergenceWarning + + warnings.warn( + "Maximum Likelihood optimization failed to " + "converge. Check mle_retvals", + ConvergenceWarning, + stacklevel=2, + ) + + mlefit.mle_settings = optim_settings + return mlefit + + def _fit_zeros( + self, + keep_index=None, + start_params=None, + return_auxiliary=False, + k_params=None, + **fit_kwds, + ): + """ + Experimental, fit the model subject to zero constraints + + Intended for internal use cases until we know what we need. + API will need to change to handle models with two exog. + This is not yet supported by all model subclasses. + + This is essentially a simplified version of `fit_constrained`, and + does not need to use `offset`. + + The estimation creates a new model with transformed design matrix, + exog, and converts the results back to the original parameterization. + + Some subclasses could use a more efficient calculation than using a + new model. + + Parameters + ---------- + keep_index : array_like (int or bool) or slice, optional + variables that should be dropped. + start_params : array_like, optional + starting values for the optimization. `start_params` needs to be + given in the original parameter space and are internally + transformed. + return_auxiliary : bool, optional + If True, then return the auxiliary results. Currently not used. + k_params : int or None, optional + If None, then we try to infer from start_params or model. + **fit_kwds : keyword arguments + fit_kwds are used in the optimization of the transformed model. + + Returns + ------- + results : Results instance + """ + # we need to append index of extra params to keep_index as in + # NegativeBinomial + if hasattr(self, "k_extra") and self.k_extra > 0: + # we cannot change the original, TODO: should we add keep_index_params? + keep_index = np.array(keep_index, copy=True) + k = self.exog.shape[1] + extra_index = np.arange(k, k + self.k_extra) + keep_index_p = np.concatenate((keep_index, extra_index)) + else: + keep_index_p = keep_index + + # not all models support start_params, drop if None, hide them in fit_kwds + if start_params is not None: + fit_kwds["start_params"] = start_params[keep_index_p] + k_params = len(start_params) + # ignore k_params in this case, or verify consisteny? + + # build auxiliary model and fit + init_kwds = self._get_init_kwds() + mod_constr = self.__class__(self.endog, self.exog[:, keep_index], **init_kwds) + res_constr = mod_constr.fit(**fit_kwds) + # switch name, only need keep_index for params below + keep_index = keep_index_p + + if k_params is None: + k_params = self.exog.shape[1] + k_params += getattr(self, "k_extra", 0) + + params_full = np.zeros(k_params) + params_full[keep_index] = res_constr.params + + # create dummy results Instance, TODO: wire up properly + # TODO: this could be moved into separate private method if needed + # discrete L1 fit_regularized doens't reestimate AFAICS + # RLM does not have method, disp nor warn_convergence keywords + # OLS, WLS swallows extra kwds with **kwargs, but does not have method='nm' + try: + # Note: addding full_output=False causes exceptions + res = self.fit( + maxiter=0, + disp=0, + method="nm", + skip_hessian=True, + warn_convergence=False, + start_params=params_full, + ) + # we get a wrapper back + except (TypeError, ValueError): + res = self.fit() + + # Warning: make sure we are not just changing the wrapper instead of + # results #2400 + # TODO: do we need to change res._results.scale in some models? + if hasattr(res_constr.model, "scale"): + # Note: res.model is self + # GLM problem, see #2399, + # TODO: remove from model if not needed anymore + res.model.scale = res._results.scale = res_constr.model.scale + + if hasattr(res_constr, "mle_retvals"): + res._results.mle_retvals = res_constr.mle_retvals + # not available for not scipy optimization, e.g., glm irls + # TODO: what retvals should be required? + # res.mle_retvals['fcall'] = res_constr.mle_retvals.get('fcall', np.nan) + # res.mle_retvals['iterations'] = res_constr.mle_retvals.get( + # 'iterations', np.nan) + # res.mle_retvals['converged'] = res_constr.mle_retvals['converged'] + # overwrite all mle_settings + if hasattr(res_constr, "mle_settings"): + res._results.mle_settings = res_constr.mle_settings + + res._results.params = params_full + if ( + not hasattr(res._results, "normalized_cov_params") + or res._results.normalized_cov_params is None + ): + res._results.normalized_cov_params = np.zeros((k_params, k_params)) + else: + res._results.normalized_cov_params[...] = 0 + + # fancy indexing requires integer array + keep_index = np.array(keep_index) + res._results.normalized_cov_params[keep_index[:, None], keep_index] = ( + res_constr.normalized_cov_params + ) + k_constr = res_constr.df_resid - res._results.df_resid + if hasattr(res_constr, "cov_params_default"): + res._results.cov_params_default = np.zeros((k_params, k_params)) + res._results.cov_params_default[keep_index[:, None], keep_index] = ( + res_constr.cov_params_default + ) + if hasattr(res_constr, "cov_type"): + res._results.cov_type = res_constr.cov_type + res._results.cov_kwds = res_constr.cov_kwds + + res._results.keep_index = keep_index + res._results.df_resid = res_constr.df_resid + res._results.df_model = res_constr.df_model + + res._results.k_constr = k_constr + res._results.results_constrained = res_constr + + # special temporary workaround for RLM + # need to be able to override robust covariances + if hasattr(res.model, "M"): + del res._results._cache["resid"] + del res._results._cache["fittedvalues"] + del res._results._cache["sresid"] + cov = res._results._cache["bcov_scaled"] + # inplace adjustment + cov[...] = 0 + cov[keep_index[:, None], keep_index] = res_constr.bcov_scaled + res._results.cov_params_default = cov + + return res + + def _fit_collinear(self, atol=1e-14, rtol=1e-13, **kwds): + """ + Experimental, fit of the model without collinear variables + + This currently uses QR to drop variables based on the given + sequence. + Options will be added in future, when the supporting functions + to identify collinear variables become available. + + Parameters + ---------- + atol : float + Absolute tolerance to use when comparing the diagonal of R to + zero to determine collinearity. + rtol : float + Relative tolerance to use when comparing the diagonal of R to + zero to determine collinearity. + **kwds + Keyword arguments passed to `_fit_zeros`. + + Returns + ------- + Results instance + """ + + # ------ copied from PR #2380 remove when merged + x = self.exog + tol = atol + rtol * x.var(0) + r = np.linalg.qr(x, mode="r") + mask = np.abs(r.diagonal()) < np.sqrt(tol) + # TODO add to results instance + # idx_collinear = np.where(mask)[0] + idx_keep = np.where(~mask)[0] + return self._fit_zeros(keep_index=idx_keep, **kwds) + + +# TODO: the below is unfinished +class GenericLikelihoodModel(LikelihoodModel): + """ + Allows the fitting of any likelihood function via maximum likelihood + + A subclass needs to specify at least the log-likelihood + If the log-likelihood is specified for each observation, then results that + require the Jacobian will be available. (The other case is not tested yet.) + + Parameters + ---------- + endog : array_like + A 1-d endogenous response variable. The dependent variable. + exog : array_like, optional + A nobs x k array where `nobs` is the number of observations and `k` + is the number of regressors. An intercept is not included by default + and should be added by the user. + loglike : callable, optional + Log-likelihood function. If provided, it is used instead of the + class's `loglike`/`loglikeobs` methods for this instance. + score : callable, optional + Score (gradient) function. If provided, it is used instead of the + class's `score` method for this instance. + hessian : callable, optional + Hessian function. If provided, it is used instead of the class's + `hessian` method for this instance. + 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'. + extra_params_names : list of str, optional + Names for additional parameters that are not part of exog, appended + to `exog_names`. + **kwds + Extra arguments that are used to set model properties when using the + formula interface. + + Notes + ----- + Optimization methods that require only a likelihood function are 'nm' and + 'powell' + + Optimization methods that require a likelihood function and a + score/gradient are 'bfgs', 'cg', and 'ncg'. A function to compute the + Hessian is optional for 'ncg'. + + Optimization method that require a likelihood function, a score/gradient, + and a Hessian is 'newton' + + If they are not overwritten by a subclass, then numerical gradient, + Jacobian and Hessian of the log-likelihood are calculated by numerical + forward differentiation. This might results in some cases in precision + problems, and the Hessian might not be positive definite. Even if the + Hessian is not positive definite the covariance matrix of the parameter + estimates based on the outer product of the Jacobian might still be valid. + + + Examples + -------- + See also subclasses in directory miscmodels + + >>> import numpy as np + >>> import statsmodels.api as sm + >>> data = sm.datasets.spector.load() + >>> data.exog = sm.add_constant(data.exog) + >>> # in this dir + >>> from model import GenericLikelihoodModel + >>> probit_mod = sm.Probit(data.endog, data.exog) + >>> probit_res = probit_mod.fit() + >>> loglike = probit_mod.loglike + >>> score = probit_mod.score + >>> mod = GenericLikelihoodModel(data.endog, data.exog, loglike, score) + >>> res = mod.fit(method="nm", maxiter=500) + >>> np.allclose(res.params, probit_res.params) + """ + + def __init__( + self, + endog, + exog=None, + loglike=None, + score=None, + hessian=None, + missing="none", + extra_params_names=None, + **kwds, + ): + # let them be none in case user wants to use inheritance + if loglike is not None: + self.loglike = loglike + if score is not None: + self.score = score + if hessian is not None: + self.hessian = hessian + + hasconst = kwds.pop("hasconst", None) + self.__dict__.update(kwds) + + # TODO: data structures? + + # TODO temporary solution, force approx normal + # self.df_model = 9999 + # somewhere: CacheWriteWarning: 'df_model' cannot be overwritten + super().__init__(endog, exog, missing=missing, hasconst=hasconst, **kwds) + + # this will not work for ru2nmnl, maybe np.ndim of a dict? + if exog is not None: + self.nparams = exog.shape[1] if np.ndim(exog) == 2 else 1 + + if extra_params_names is not None: + self._set_extra_params_names(extra_params_names) + + def _set_extra_params_names(self, extra_params_names): + # check param_names + if extra_params_names is not None: + if self.exog is not None: + self.exog_names.extend(extra_params_names) + else: + self.data.xnames = extra_params_names + + self.k_extra = len(extra_params_names) + if hasattr(self, "df_resid"): + self.df_resid -= self.k_extra + + self.nparams = len(self.exog_names) + + # this is redundant and not used when subclassing + def initialize(self): + """ + Initialize (possibly re-initialize) a Model instance. For + instance, the design matrix of a linear model may change + and some things must be recomputed + """ + if not self.score: # right now score is not optional + self.score = lambda x: approx_fprime(x, self.loglike) + if not self.hessian: + pass + elif not self.hessian: + pass + # Initialize is called by + # statsmodels.model.LikelihoodModel.__init__ + # and should contain any preprocessing that needs to be done for a model + if self.exog is not None: + # assume constant + er = np.linalg.matrix_rank(self.exog) + self.df_model = float(er - 1) + self.df_resid = float(self.exog.shape[0] - er) + else: + self.df_model = np.nan + self.df_resid = np.nan + super().initialize() + + def expandparams(self, params): + """ + Expand to full parameter array when some parameters are fixed + + Parameters + ---------- + params : ndarray + Reduced parameter array. + + Returns + ------- + paramsfull : ndarray + Expanded parameter array where fixed parameters are included. + + Notes + ----- + Calling this requires that self.fixed_params and self.fixed_paramsmask + are defined. + + *developer notes:* + + This can be used in the log-likelihood to ... + + This could also be replaced by a more general parameter + transformation. + """ + paramsfull = self.fixed_params.copy() + paramsfull[self.fixed_paramsmask] = params + return paramsfull + + def reduceparams(self, params): + """Reduce parameters""" + return params[self.fixed_paramsmask] + + def loglike(self, params): + """Log-likelihood of model at params""" + return self.loglikeobs(params).sum(0) + + def nloglike(self, params): + """Negative log-likelihood of model at params""" + return -self.loglikeobs(params).sum(0) + + def loglikeobs(self, params): + """ + Log-likelihood of the model for all observations at params + + Parameters + ---------- + params : array_like + The parameters of the model. + + Returns + ------- + loglike : array_like + The log likelihood of the model evaluated at `params`. + """ + return -self.nloglikeobs(params) + + def score(self, params): + """Gradient of log-likelihood evaluated at params""" + kwds = {} + kwds.setdefault("centered", True) + return approx_fprime(params, self.loglike, **kwds).ravel() + + def score_obs(self, params, **kwds): + """ + Jacobian/Gradient of log-likelihood evaluated at params for each + observation + + Parameters + ---------- + params : array_like + The parameters of the model. + **kwds + Additional keyword arguments passed to the numerical + derivative function, e.g., `centered` or `epsilon`. + + Returns + ------- + ndarray + The Jacobian of the log-likelihood evaluated at `params` for + each observation. + """ + # kwds.setdefault('epsilon', 1e-4) + kwds.setdefault("centered", True) + return approx_fprime(params, self.loglikeobs, **kwds) + + def hessian(self, params): + """Hessian of log-likelihood evaluated at params""" + from statsmodels.tools.numdiff import approx_hess + + # need options for hess (epsilon) + return approx_hess(params, self.loglike) + + def hessian_factor(self, params, scale=None, observed=True): + """ + Weights for calculating Hessian + + Parameters + ---------- + params : ndarray + Parameter at which Hessian is evaluated. + scale : None or float, optional + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + observed : bool, optional + If True, then the observed Hessian is returned. If false then the + expected information matrix is returned. + + Returns + ------- + hessian_factor : ndarray, 1d + A 1d weight vector used in the calculation of the Hessian. + The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` + """ + + raise NotImplementedError + + def fit( + self, + start_params=None, + method="nm", + maxiter=500, + full_output=1, + disp=1, + callback=None, + retall=0, + **kwargs, + ): + """ + Fit the model via maximum likelihood + + Parameters + ---------- + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of 0.1 for each parameter. + method : str, optional + The `method` determines which solver from `scipy.optimize` + is used. See `LikelihoodModel.fit` for the available methods. + maxiter : int, optional + The maximum number of iterations to perform. + full_output : bool, optional + Set to True to have all available output in the Results object's + mle_retvals attribute. + disp : bool, optional + Set to True to print convergence messages. + callback : callable callback(xk), optional + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool, optional + Set to True to return list of solutions at each iteration. + **kwargs + Additional keyword arguments passed to `LikelihoodModel.fit`. + + Returns + ------- + GenericLikelihoodModelResults + The fitted model results. + """ + if start_params is None: + if hasattr(self, "start_params"): + start_params = self.start_params + else: + start_params = 0.1 * np.ones(self.nparams) + + if "cov_type" not in kwargs: + # this will add default cov_type name and description + kwargs["cov_type"] = "nonrobust" + + fit_method = super().fit + mlefit = fit_method( + start_params=start_params, + method=method, + maxiter=maxiter, + full_output=full_output, + disp=disp, + callback=callback, + **kwargs, + ) + + results_class = getattr(self, "results_class", GenericLikelihoodModelResults) + genericmlefit = results_class(self, mlefit) + + # amend param names + exog_names = [] if (self.exog_names is None) else self.exog_names + k_miss = len(exog_names) - len(mlefit.params) + if not k_miss == 0: + if k_miss < 0: + self._set_extra_params_names([f"par{i:d}" for i in range(-k_miss)]) + else: + # I do not want to raise after we have already fit() + warnings.warn( + "more exog_names than parameters", ValueWarning, stacklevel=2 + ) + + return genericmlefit + + +class Results: + """ + Class to contain model results + + Parameters + ---------- + model : class instance + The previously specified model instance. + params : ndarray + Parameter estimates from the fit model. + **kwd + Additional keyword arguments used to initialize the results + instance. + """ + + def __init__(self, model, params, **kwd): + self.__dict__.update(kwd) + self.initialize(model, params, **kwd) + self._data_attr = [] + # Variables to clear from cache + self._data_in_cache = ["fittedvalues", "resid", "wresid"] + + def initialize(self, model, params, **kwargs): + """ + Initialize (possibly re-initialize) a Results instance + + Parameters + ---------- + model : Model + The model instance. + params : ndarray + The model parameters. + **kwargs + Any additional keyword arguments required to initialize the model. + """ + self.params = params + self.model = model + if hasattr(model, "k_constant"): + self.k_constant = model.k_constant + + def _transform_predict_exog(self, exog, transform=True): + + is_pandas = _is_using_pandas(exog, None) + exog_index = None + if is_pandas: + if exog.ndim == 2 or self.params.size == 1: + exog_index = exog.index + else: + exog_index = [exog.index.name] + + if transform and hasattr(self.model, "formula") and (exog is not None): + # allow both location of model_spec, see #7043 + model_spec = ( + getattr(self.model, "model_spec", None) or self.model.data.model_spec + ) + mgr = FormulaManager() + if isinstance(exog, pd.Series): + # we are guessing whether it should be column or row + if ( + hasattr(exog, "name") + and isinstance(exog.name, str) + and exog.name in mgr.get_description(model_spec) + ): + # assume we need one column + exog = pd.DataFrame(exog) + else: + # assume we need a row + exog = pd.DataFrame(exog).T + exog_index = exog.index + orig_exog_len = len(exog) + is_dict = isinstance(exog, dict) + try: + exog = mgr.get_matrices(model_spec, exog, pandas=True, prediction=True) + except Exception as exc: + msg = ( + "predict requires that you use a DataFrame when " + "predicting from a model\nthat was created using the " + "formula api. \n\nThe original error message returned " + f"by {mgr.engine} is:\n {str(exc)!s}" + ) + raise exc.__class__(msg) from exc + if orig_exog_len > len(exog) and not is_dict: + if exog_index is None: + warnings.warn( + "nan values have been dropped", ValueWarning, stacklevel=2 + ) + else: + exog = exog.reindex(exog_index) + exog_index = exog.index + + if exog is not None: + exog = np.asarray(exog) + if exog.ndim == 1 and ( + self.model.exog.ndim == 1 or self.model.exog.shape[1] == 1 + ): + exog = exog[:, None] + exog = np.atleast_2d(exog) # needed in count model shape[1] + + return exog, exog_index + + def predict(self, exog=None, transform=True, *args, **kwargs): + """ + Call self.model.predict with self.params as the first argument + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. see Notes below. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + *args + Additional arguments to pass to the model, see the + predict method of the model for the details. + **kwargs + Additional keywords arguments to pass to the model, see the + predict method of the model for the details. + + Returns + ------- + ndarray or pandas object + See self.model.predict. + + Notes + ----- + The types of exog that are supported depends on whether a formula + was used in the specification of the model. + + If a formula was used, then exog is processed in the same way as + the original data. This transformation needs to have key access to the + same variable names, and can be a pandas DataFrame or a dict like + object that contains numpy arrays. + + If no formula was used, then the provided exog needs to have the + same number of columns as the original exog in the model. No + transformation of the data is performed except converting it to + a numpy array. In this case the columns are matched by position and + not by name, so a DataFrame must have its columns in the same order + as the exog used to fit the model; its column labels are ignored. + This differs from the formula case above, where the variables are + matched by name and the column order does not matter. + + Row indices as in pandas data frames are supported, and added to the + returned prediction. + """ + exog, exog_index = self._transform_predict_exog(exog, transform=transform) + + predict_results = self.model.predict(self.params, exog, *args, **kwargs) + + if exog_index is not None and not hasattr(predict_results, "predicted_values"): + if predict_results.ndim == 1: + return pd.Series(predict_results, index=exog_index) + else: + return pd.DataFrame(predict_results, index=exog_index) + else: + return predict_results + + def summary(self): + """Summary of Results, not implemented""" + raise NotImplementedError + + +# TODO: public method? +class LikelihoodModelResults(Results): + """ + Class to contain results from likelihood models + + Parameters + ---------- + model : LikelihoodModel instance or subclass instance + LikelihoodModelResults holds a reference to the model that is fit. + params : 1d array_like + Parameter estimates from estimated model. + normalized_cov_params : ndarray, optional + Normalized (before scaling) covariance of params. (dot(X.T,X))**-1 + scale : float, optional + For (some subset of models) scale will typically be the + mean square error from the estimated model (sigma^2). + + Attributes + ---------- + mle_retvals : dict + Contains the values returned from the chosen optimization method if + full_output is True during the fit. Available only if the model + is fit by maximum likelihood. See notes below for the output from + the different methods. + mle_settings : dict + Contains the arguments passed to the chosen optimization method. + Available if the model is fit by maximum likelihood. See + LikelihoodModel.fit for more information. + model : model instance + LikelihoodResults contains a reference to the model that is fit. + params : ndarray + The parameters estimated for the model. + scale : float + The scaling factor of the model given during instantiation. + tvalues : ndarray + The t-values of the standard errors. + + + Notes + ----- + The covariance of params is given by scale times normalized_cov_params. + + Return values by solver if full_output is True during fit: + + 'newton' + fopt : float + The value of the (negative) loglikelihood at its + minimum. + iterations : int + Number of iterations performed. + score : ndarray + The score vector at the optimum. + Hessian : ndarray + The Hessian at the optimum. + warnflag : int + 1 if maxiter is exceeded. 0 if successful convergence. + converged : bool + True: converged. False: did not converge. + allvecs : list + List of solutions at each iteration. + 'nm' + fopt : float + The value of the (negative) loglikelihood at its + minimum. + iterations : int + Number of iterations performed. + warnflag : int + 1: Maximum number of function evaluations made. + 2: Maximum number of iterations reached. + converged : bool + True: converged. False: did not converge. + allvecs : list + List of solutions at each iteration. + 'bfgs' + fopt : float + Value of the (negative) loglikelihood at its minimum. + gopt : float + Value of gradient at minimum, which should be near 0. + Hinv : ndarray + value of the inverse Hessian matrix at minimum. Note + that this is just an approximation and will often be + different from the value of the analytic Hessian. + fcalls : int + Number of calls to loglike. + gcalls : int + Number of calls to gradient/score. + warnflag : int + 1: Maximum number of iterations exceeded. 2: Gradient + and/or function calls are not changing. + converged : bool + True: converged. False: did not converge. + allvecs : list + Results at each iteration. + 'lbfgs' + fopt : float + Value of the (negative) loglikelihood at its minimum. + gopt : float + Value of gradient at minimum, which should be near 0. + fcalls : int + Number of calls to loglike. + warnflag : int + Warning flag: + + - 0 if converged + - 1 if too many function evaluations or too many iterations + - 2 if stopped for another reason + + converged : bool + True: converged. False: did not converge. + 'powell' + fopt : float + Value of the (negative) loglikelihood at its minimum. + direc : ndarray + Current direction set. + iterations : int + Number of iterations performed. + fcalls : int + Number of calls to loglike. + warnflag : int + 1: Maximum number of function evaluations. 2: Maximum number + of iterations. + converged : bool + True : converged. False: did not converge. + allvecs : list + Results at each iteration. + 'cg' + fopt : float + Value of the (negative) loglikelihood at its minimum. + fcalls : int + Number of calls to loglike. + gcalls : int + Number of calls to gradient/score. + warnflag : int + 1: Maximum number of iterations exceeded. 2: Gradient and/ + or function calls not changing. + converged : bool + True: converged. False: did not converge. + allvecs : list + Results at each iteration. + 'ncg' + fopt : float + Value of the (negative) loglikelihood at its minimum. + fcalls : int + Number of calls to loglike. + gcalls : int + Number of calls to gradient/score. + hcalls : int + Number of calls to hessian. + warnflag : int + 1: Maximum number of iterations exceeded. + converged : bool + True: converged. False: did not converge. + allvecs : list + Results at each iteration. + """ + + # by default we use normal distribution + # can be overwritten by instances or subclasses + + def __init__(self, model, params, normalized_cov_params=None, scale=1.0, **kwargs): + super().__init__(model, params) + self.normalized_cov_params = normalized_cov_params + self.scale = scale + self._use_t = False + # robust covariance + # We put cov_type in kwargs so subclasses can decide in fit whether to + # use this generic implementation + if "use_t" in kwargs: + use_t = kwargs["use_t"] + self.use_t = use_t if use_t is not None else False + if "cov_type" in kwargs: + cov_type = kwargs.get("cov_type", "nonrobust") + cov_kwds = kwargs.get("cov_kwds", {}) + + if cov_type == "nonrobust": + self.cov_type = "nonrobust" + self.cov_kwds = { + "description": "Standard Errors assume that the covariance matrix " + "of the errors is correctly specified." + } + else: + from statsmodels.base.covtype import get_robustcov_results + + if cov_kwds is None: + cov_kwds = {} + use_t = self.use_t + # TODO: we should not need use_t in get_robustcov_results + get_robustcov_results( + self, cov_type=cov_type, use_self=True, use_t=use_t, **cov_kwds + ) + + def normalized_cov_params(self): + """See specific model class docstring""" + raise NotImplementedError + + def _get_robustcov_results( + self, cov_type="nonrobust", use_self=True, use_t=None, **cov_kwds + ): + if use_self is False: + raise ValueError("use_self should have been removed long ago. See GH#4401") + from statsmodels.base.covtype import get_robustcov_results + + if cov_kwds is None: + cov_kwds = {} + + if cov_type == "nonrobust": + self.cov_type = "nonrobust" + self.cov_kwds = { + "description": "Standard Errors assume that the covariance matrix " + "of the errors is correctly specified." + } + else: + # TODO: we should not need use_t in get_robustcov_results + get_robustcov_results( + self, cov_type=cov_type, use_self=True, use_t=use_t, **cov_kwds + ) + + @property + def use_t(self): + """Flag indicating to use the Student's distribution in inference""" + return self._use_t + + @use_t.setter + def use_t(self, value): + self._use_t = bool(value) + + @cached_value + def llf(self): + """Log-likelihood of model""" + return self.model.loglike(self.params) + + @cached_value + def bse(self): + """The standard errors of the parameter estimates""" + # Issue 3299 + if (not hasattr(self, "cov_params_default")) and ( + self.normalized_cov_params is None + ): + bse_ = np.empty(len(self.params)) + bse_[:] = np.nan + else: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + bse_ = np.sqrt(np.diag(self.cov_params())) + return bse_ + + @cached_value + def tvalues(self): + """Return the t-statistic for a given parameter estimate""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + return self.params / self.bse + + @cached_value + def pvalues(self): + """The two-tailed p values for the t-stats of the params""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + if self.use_t: + df_resid = getattr(self, "df_resid_inference", self.df_resid) + return stats.t.sf(np.abs(self.tvalues), df_resid) * 2 + else: + return stats.norm.sf(np.abs(self.tvalues)) * 2 + + def cov_params( + self, r_matrix=None, column=None, scale=None, cov_p=None, other=None + ): + """ + Compute the variance/covariance matrix + + The variance/covariance matrix can be of a linear contrast of the + estimated parameters or all params multiplied by scale which will + usually be an estimate of sigma^2. Scale is assumed to be a scalar. + + Parameters + ---------- + r_matrix : array_like, optional + Can be 1d, or 2d. Can be used alone or with other. + column : array_like, optional + Must be used on its own. Can be 0d or 1d see below. + scale : float, optional + Can be specified or not. Default is None, which means that + the scale argument is taken from the model. + cov_p : ndarray, optional + The covariance of the parameters. If not provided, this value is + read from `self.normalized_cov_params` or + `self.cov_params_default`. + other : array_like, optional + Can be used when r_matrix is specified. + + Returns + ------- + ndarray + The covariance matrix of the parameter estimates or of linear + combination of parameter estimates. See Notes. + + Notes + ----- + (The below are assumed to be in matrix notation.) + + If no argument is specified returns the covariance matrix of a model + ``(scale)*(X.T X)^(-1)`` + + If contrast is specified it pre and post-multiplies as follows + ``(scale) * r_matrix (X.T X)^(-1) r_matrix.T`` + + If contrast and other are specified returns + ``(scale) * r_matrix (X.T X)^(-1) other.T`` + + If column is specified returns + ``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d + + OR + + ``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d + """ + if getattr(self, "mle_settings", None) and self.mle_settings["optimizer"] in [ + "l1", + "l1_cvxopt_cp", + ]: + dot_fun = nan_dot + else: + dot_fun = np.dot + + if ( + cov_p is None + and self.normalized_cov_params is None + and not hasattr(self, "cov_params_default") + ): + raise ValueError( + "need covariance of parameters for computing " + "(unnormalized) covariances" + ) + if column is not None and (r_matrix is not None or other is not None): + raise ValueError("Column should be specified without other arguments.") + if other is not None and r_matrix is None: + raise ValueError("other can only be specified with r_matrix") + + if cov_p is None: + if hasattr(self, "cov_params_default"): + cov_p = self.cov_params_default + else: + if scale is None: + scale = self.scale + cov_p = self.normalized_cov_params * scale + + if column is not None: + column = np.asarray(column) + if column.shape == (): + return cov_p[column, column] + else: + return cov_p[column[:, None], column] + elif r_matrix is not None: + r_matrix = np.asarray(r_matrix) + if r_matrix.shape == (): + raise ValueError("r_matrix should be 1d or 2d") + if other is None: + other = r_matrix + else: + other = np.asarray(other) + tmp = dot_fun(r_matrix, dot_fun(cov_p, np.transpose(other))) + return tmp + else: # if r_matrix is None and column is None: + return cov_p + + # TODO: make sure this works as needed for GLMs + def t_test(self, r_matrix, cov_p=None, use_t=None): + """ + Compute a t-test for each linear hypothesis of the form Rb = q + + Parameters + ---------- + r_matrix : array_like, str, or tuple + One of: + + - array : If an array is given, a p x k 2d array or length k 1d + array specifying the linear restrictions. It is assumed + that the linear combination is equal to zero. + - str : The full hypotheses to test can be given as a string. + See the examples. + - tuple : A tuple of arrays in the form (R, q). If q is given, + can be either a scalar or a length p row vector. + + cov_p : array_like, optional + An alternative estimate for the parameter covariance matrix. + If None is given, self.normalized_cov_params is used. + use_t : bool, optional + If use_t is None, then the default of the model is used. If use_t + is True, then the p-values are based on the t distribution. If + use_t is False, then the p-values are based on the normal + distribution. + + Returns + ------- + ContrastResults + The results for the test are attributes of this results instance. + The available results have the same elements as the parameter table + in `summary()`. + + See Also + -------- + tvalues : Individual t statistics for the estimated parameters. + f_test : Perform an F tests on model parameters. + patsy.DesignInfo.linear_constraint : Specify a linear constraint. + + Examples + -------- + >>> import numpy as np + >>> import statsmodels.api as sm + >>> data = sm.datasets.longley.load() + >>> data.exog = sm.add_constant(data.exog) + >>> results = sm.OLS(data.endog, data.exog).fit() + >>> r = np.zeros_like(results.params) + >>> r[5:] = [1,-1] + >>> print(r) + [ 0. 0. 0. 0. 0. 1. -1.] + + r tests that the coefficients on the 5th and 6th independent + variable are the same. + + >>> T_test = results.t_test(r) + >>> print(T_test) + Test for Constraints + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 + ============================================================================== + >>> T_test.effect + -1829.2025687192481 + >>> T_test.sd + 455.39079425193762 + >>> T_test.tvalue + -4.0167754636411717 + >>> T_test.pvalue + 0.0015163772380899498 + + Alternatively, you can specify the hypothesis tests using a string + + >>> from statsmodels.formula.api import ols + >>> dta = sm.datasets.longley.load_pandas().data + >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' + >>> results = ols(formula, dta).fit() + >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' + >>> t_test = results.t_test(hypotheses) + >>> print(t_test) + Test for Constraints + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + c0 15.0977 84.937 0.178 0.863 -177.042 207.238 + c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 + c2 1.0001 0.249 0.000 1.000 0.437 1.563 + ============================================================================== + """ + use_t = bool_like(use_t, "use_t", strict=True, optional=True) + if self.params.ndim == 2: + names = [f"y{i[0]}_{i[1]}" for i in self.model.data.cov_names] + else: + names = self.model.data.cov_names + mgr = FormulaManager() + lc = mgr.get_linear_constraints(r_matrix, names) + r_matrix, q_matrix = lc.constraint_matrix, lc.constraint_values + num_ttests = r_matrix.shape[0] + num_params = r_matrix.shape[1] + + if ( + cov_p is None + and self.normalized_cov_params is None + and not hasattr(self, "cov_params_default") + ): + raise ValueError("Need covariance of parameters for computing T statistics") + params = self.params.ravel(order="F") + if num_params != params.shape[0]: + raise ValueError("r_matrix and params are not aligned") + if q_matrix is None: + q_matrix = np.zeros(num_ttests) + else: + q_matrix = np.asarray(q_matrix) + q_matrix = q_matrix.squeeze() + if q_matrix.size > 1: + if q_matrix.shape[0] != num_ttests: + raise ValueError( + "r_matrix and q_matrix must have the same number of rows" + ) + + if use_t is None: + # switch to use_t false if undefined + use_t = hasattr(self, "use_t") and self.use_t + + _effect = np.dot(r_matrix, params) + + # Perform the test + if num_ttests > 1: + _sd = np.sqrt(np.diag(self.cov_params(r_matrix=r_matrix, cov_p=cov_p))) + else: + _sd = np.sqrt(self.cov_params(r_matrix=r_matrix, cov_p=cov_p)) + _t = (_effect - q_matrix) * recipr(_sd) + + df_resid = getattr(self, "df_resid_inference", self.df_resid) + + if use_t: + return ContrastResults(effect=_effect, t=_t, sd=_sd, df_denom=df_resid) + else: + return ContrastResults( + effect=_effect, + statistic=_t, + sd=_sd, + df_denom=df_resid, + distribution="norm", + ) + + def f_test(self, r_matrix, cov_p=None, invcov=None): + """ + Compute the F-test for a joint linear hypothesis + + This is a special case of `wald_test` that always uses the F + distribution. + + Parameters + ---------- + r_matrix : array_like, str, or tuple + One of: + + - array : An r x k array where r is the number of restrictions to + test and k is the number of regressors. It is assumed + that the linear combination is equal to zero. + - str : The full hypotheses to test can be given as a string. + See the examples. + - tuple : A tuple of arrays in the form (R, q), ``q`` can be + either a scalar or a length k row vector. + + cov_p : array_like, optional + An alternative estimate for the parameter covariance matrix. + If None is given, self.normalized_cov_params is used. + invcov : array_like, optional + A q x q array to specify an inverse covariance matrix based on a + restrictions matrix. + + Returns + ------- + ContrastResults + The results for the test are attributes of this results instance. + + See Also + -------- + t_test : Perform a single hypothesis test. + wald_test : Perform a Wald-test using a quadratic form. + statsmodels.stats.contrast.ContrastResults : Test results. + patsy.DesignInfo.linear_constraint : Specify a linear constraint. + + Notes + ----- + The matrix `r_matrix` is assumed to be non-singular. More precisely, + + r_matrix (pX pX.T) r_matrix.T + + is assumed invertible. Here, pX is the generalized inverse of the + design matrix of the model. There can be problems in non-OLS models + where the rank of the covariance of the noise is not full. + + Examples + -------- + >>> import numpy as np + >>> import statsmodels.api as sm + >>> data = sm.datasets.longley.load() + >>> data.exog = sm.add_constant(data.exog) + >>> results = sm.OLS(data.endog, data.exog).fit() + >>> A = np.identity(len(results.params)) + >>> A = A[1:,:] + + This tests that each coefficient is jointly statistically + significantly different from zero. + + >>> print(results.f_test(A)) + + + Compare this to + + >>> results.fvalue + 330.2853392346658 + >>> results.f_pvalue + 4.98403096572e-10 + + >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) + + This tests that the coefficient on the 2nd and 3rd regressors are + equal and jointly that the coefficient on the 5th and 6th regressors + are equal. + + >>> print(results.f_test(B)) + + + Alternatively, you can specify the hypothesis tests using a string + + >>> from statsmodels.datasets import longley + >>> from statsmodels.formula.api import ols + >>> dta = longley.load_pandas().data + >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' + >>> results = ols(formula, dta).fit() + >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' + >>> f_test = results.f_test(hypotheses) + >>> print(f_test) + + """ + res = self.wald_test( + r_matrix, cov_p=cov_p, invcov=invcov, use_f=True, scalar=True + ) + return res + + # TODO: untested for GLMs? + def wald_test( + self, + r_matrix, + cov_p=None, + invcov=None, + use_f=None, + df_constraints=None, + scalar=True, + ): + """ + Compute a Wald-test for a joint linear hypothesis + + Parameters + ---------- + r_matrix : array_like, str, or tuple + One of: + + - array : An r x k array where r is the number of restrictions to + test and k is the number of regressors. It is assumed that the + linear combination is equal to zero. + - str : The full hypotheses to test can be given as a string. + See the examples. + - tuple : A tuple of arrays in the form (R, q), ``q`` can be + either a scalar or a length p row vector. + + cov_p : array_like, optional + An alternative estimate for the parameter covariance matrix. + If None is given, self.normalized_cov_params is used. + invcov : array_like, optional + A q x q array to specify an inverse covariance matrix based on a + restrictions matrix. + use_f : bool, optional + If True, then the F-distribution is used. If False, then the + asymptotic distribution, chisquare is used. If use_f is None, then + the F distribution is used if the model specifies that use_t is True. + The test statistic is proportionally adjusted for the distribution + by the number of constraints in the hypothesis. + df_constraints : int, optional + The number of constraints. If not provided the number of + constraints is determined from r_matrix. + scalar : bool, optional + Flag indicating whether the Wald test statistic should be + returned as a scalar float (the default) or as an array. + + Returns + ------- + ContrastResults + The results for the test are attributes of this results instance. + + See Also + -------- + f_test : Perform an F tests on model parameters. + t_test : Perform a single hypothesis test. + statsmodels.stats.contrast.ContrastResults : Test results. + patsy.DesignInfo.linear_constraint : Specify a linear constraint. + + Notes + ----- + The matrix `r_matrix` is assumed to be non-singular. More precisely, + + r_matrix (pX pX.T) r_matrix.T + + is assumed invertible. Here, pX is the generalized inverse of the + design matrix of the model. There can be problems in non-OLS models + where the rank of the covariance of the noise is not full. + """ + use_f = bool_like(use_f, "use_f", strict=True, optional=True) + scalar = bool_like(scalar, "scalar", strict=True) + if use_f is None: + # switch to use_t false if undefined + use_f = hasattr(self, "use_t") and self.use_t + + if self.params.ndim == 2: + names = [f"y{i[0]}_{i[1]}" for i in self.model.data.cov_names] + else: + names = self.model.data.cov_names + params = self.params.ravel(order="F") + + mgr = FormulaManager() + lc = mgr.get_linear_constraints(r_matrix, names) + r_matrix, q_matrix = lc.constraint_matrix, lc.constraint_values + + if ( + self.normalized_cov_params is None + and cov_p is None + and invcov is None + and not hasattr(self, "cov_params_default") + ): + raise ValueError("need covariance of parameters for computing F statistics") + + cparams = np.dot(r_matrix, params[:, None]) + J = float(r_matrix.shape[0]) # number of restrictions + + if q_matrix is None: + q_matrix = np.zeros(J) + else: + q_matrix = np.asarray(q_matrix) + if q_matrix.ndim == 1: + q_matrix = q_matrix[:, None] + if q_matrix.shape[0] != J: + raise ValueError( + "r_matrix and q_matrix must have the same number of rows" + ) + Rbq = cparams - q_matrix + if invcov is None: + cov_p = self.cov_params(r_matrix=r_matrix, cov_p=cov_p) + if np.isnan(cov_p).max(): + raise ValueError( + "r_matrix performs f_test for using " + "dimensions that are asymptotically " + "non-normal" + ) + invcov = np.linalg.pinv(cov_p) + J_ = np.linalg.matrix_rank(cov_p) + if J_ < J: + warnings.warn( + "covariance of constraints does not have full " + f"rank. The number of constraints is {int(J):d}, but " + f"rank is {J_:d}", + ValueWarning, + stacklevel=2, + ) + J = J_ + + # TODO streamline computation, we do not need to compute J if given + if df_constraints is not None: + # let caller override J by df_constraint + J = df_constraints + + if getattr(self, "mle_settings", None) and self.mle_settings["optimizer"] in [ + "l1", + "l1_cvxopt_cp", + ]: + F = nan_dot(nan_dot(Rbq.T, invcov), Rbq) + else: + F = np.dot(np.dot(Rbq.T, invcov), Rbq) + + if scalar and F.size == 1: + F = float(np.squeeze(F)) + if use_f: + # Defer since only needed in F test + if hasattr(self, "df_resid_inference"): + df_resid = self.df_resid_inference + else: + df_resid = self.df_resid + + F /= J + return ContrastResults(F=F, df_denom=df_resid, df_num=J) # invcov.shape[0]) + else: + return ContrastResults( + chi2=F, df_denom=J, statistic=F, distribution="chi2", distargs=(J,) + ) + + def wald_test_terms( + self, skip_single=False, extra_constraints=None, combine_terms=None, scalar=True + ): + """ + Compute a sequence of Wald tests for terms over multiple columns + + This computes joined Wald tests for the hypothesis that all + coefficients corresponding to a `term` are zero. + `Terms` are defined by the underlying formula or by string matching. + + Parameters + ---------- + skip_single : bool, optional + If true, then terms that consist only of a single column and, + therefore, refers only to a single parameter is skipped. + If false, then all terms are included. + extra_constraints : list[tuple], optional + Additional constraints to test, given as a list of (name, + constraint_matrix) tuples in the same form as the automatically + generated term constraints. Note that this input has not been + tested. + combine_terms : list of str, optional + Each string in this list is matched to the name of the terms or + the name of the exogenous variables. All columns whose name + includes that string are combined in one joint test. + scalar : bool, optional + Flag indicating whether the Wald test statistic should be + returned as a scalar float (the default) or as an array. + + Returns + ------- + WaldTestResults + The result instance contains `table` which is a pandas DataFrame + with the test results: test statistic, degrees of freedom and + pvalues. + + Examples + -------- + >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() + >>> res_ols.wald_test_terms() + + F P>F df constraint df denom + Intercept 279.754525 2.37985521351e-22 1 51 + C(Duration, Sum) 5.367071 0.0245738436636 1 51 + C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 + C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 + + >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", + ... data).fit(cov_type='HC0') + >>> wt = res_poi.wald_test_terms(skip_single=False, + ... combine_terms=['Duration', 'Weight']) + >>> print(wt) + chi2 P>chi2 df constraint + Intercept 15.695625 7.43960374424e-05 1 + C(Weight) 16.132616 0.000313940174705 2 + C(Duration) 1.009147 0.315107378931 1 + C(Weight):C(Duration) 0.216694 0.897315972824 2 + Duration 11.187849 0.010752286833 3 + Weight 30.263368 4.32586407145e-06 4 + """ + # lazy import + mgr = FormulaManager() + + result = self + if extra_constraints is None: + extra_constraints = [] + if combine_terms is None: + combine_terms = [] + model_spec = getattr(result.model.data, "model_spec", None) + + if model_spec is None and extra_constraints is None: + raise ValueError("no constraints, nothing to do") + + identity = np.eye(len(result.params)) + constraints = [] + combined = defaultdict(list) + if model_spec is not None: + for term in model_spec.terms: + cols = mgr.get_slice(model_spec, term) + name = mgr.get_term_name(term) + constraint_matrix = identity[cols] + + # check if in combined + for cname in combine_terms: + if cname in name: + combined[cname].append(constraint_matrix) + + k_constraint = constraint_matrix.shape[0] + if skip_single: + if k_constraint == 1: + continue + + constraints.append((name, constraint_matrix)) + + combined_constraints = [] + for cname in combine_terms: + combined_constraints.append((cname, np.vstack(combined[cname]))) + else: + # check by exog/params names if there is no formula info + for col, name in enumerate(result.model.exog_names): + constraint_matrix = np.atleast_2d(identity[col]) + + # check if in combined + for cname in combine_terms: + if cname in name: + combined[cname].append(constraint_matrix) + + if skip_single: + continue + + constraints.append((name, constraint_matrix)) + + combined_constraints = [] + for cname in combine_terms: + combined_constraints.append((cname, np.vstack(combined[cname]))) + + use_t = result.use_t + distribution = ["chi2", "F"][use_t] + + res_wald = [] + index = [] + for name, constraint in constraints + combined_constraints + extra_constraints: + wt = result.wald_test(constraint, scalar=scalar) + # Use rank-adjusted df from wald_test instead of + # constraint.shape[0] which ignores rank deficiency. + if use_t: + df_c = int(wt.df_num) + else: + df_c = int(wt.df_denom) + row = [wt.statistic, wt.pvalue, df_c] + if use_t: + row.append(wt.df_denom) + res_wald.append(row) + index.append(name) + + # distribution nerutral names + col_names = ["statistic", "pvalue", "df_constraint"] + if use_t: + col_names.append("df_denom") + # TODO: maybe move DataFrame creation to results class + from pandas import DataFrame + + table = DataFrame(res_wald, index=index, columns=col_names) + res = WaldTestResults(None, distribution, None, table=table) + # TODO: remove temp again, added for testing + res.temp = constraints + combined_constraints + extra_constraints + return res + + def t_test_pairwise(self, term_name, method="hs", alpha=0.05, factor_labels=None): + """ + Perform pairwise t_test with multiple testing corrected p-values + + This uses the formula's model_spec encoding contrast matrix and should + work for all encodings of a main effect. + + Parameters + ---------- + term_name : str + The name of the term for which pairwise comparisons are computed. + Term names for categorical effects are created by patsy and + correspond to the main part of the exog names. + method : str or list of str, optional + The multiple testing p-value correction to apply. The default is + 'hs'. See stats.multipletesting. + alpha : float, optional + The significance level for multiple testing reject decision. + factor_labels : list of str, optional + Labels for the factor levels used for pairwise labels. If not + provided, then the labels from the formula's model_spec are used. + + Returns + ------- + MultiCompResult + The results are stored as attributes, the main attributes are the + following two. Other attributes are added for debugging purposes + or as background information. + + - result_frame : pandas DataFrame with t_test results and multiple + testing corrected p-values. + - contrasts : matrix of constraints of the null hypothesis in the + t_test. + + Notes + ----- + Status: experimental. Currently only checked for treatment coding with + and without specified reference level. + + Currently there are no multiple testing corrected confidence intervals + available. + + Examples + -------- + >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() + >>> pw = res.t_test_pairwise("C(Weight)") + >>> pw.result_frame + coef std err t P>|t| Conf. Int. Low + 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 + 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 + 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 + Conf. Int. Upp. pvalue-hs reject-hs + 2-1 1.093067 0.010212 True + 3-1 1.763307 0.000002 True + 3-2 1.130992 0.010212 True + """ + res = t_test_pairwise( + self, term_name, method=method, alpha=alpha, factor_labels=factor_labels + ) + return res + + def _get_wald_nonlinear(self, func, deriv=None): + """ + Experimental method for nonlinear prediction and tests + + Parameters + ---------- + func : callable, f(params) + Nonlinear function of the estimation parameters. The return of + the function can be vector valued, i.e., a 1-D array. + deriv : function or None + First derivative or Jacobian of func. If deriv is None, then a + numerical derivative will be used. If func returns a 1-D array, + then the `deriv` should have rows corresponding to the elements + of the return of func. + + Returns + ------- + nl : instance of `NonlinearDeltaCov` with attributes and methods to + calculate the results for the prediction or tests + + """ + from statsmodels.stats._delta_method import NonlinearDeltaCov + + func_args = None # TODO: not yet implemented, maybe skip - use partial + nl = NonlinearDeltaCov( + func, self.params, self.cov_params(), deriv=deriv, func_args=func_args + ) + + return nl + + def conf_int(self, alpha=0.05): + """ + Construct confidence interval for the fitted parameters + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. The default + `alpha` = .05 returns a 95% confidence interval. + + Returns + ------- + ndarray + Each row contains [lower, upper] limits of the confidence interval + for the corresponding parameter. The first column contains all + lower, the second column contains all upper limits. + + Notes + ----- + The confidence interval is based on the standard normal distribution + if self.use_t is False. If self.use_t is True, then uses a Student's t + with self.df_resid_inference (or self.df_resid if df_resid_inference is + not defined) degrees of freedom. + + Examples + -------- + >>> import statsmodels.api as sm + >>> data = sm.datasets.longley.load() + >>> data.exog = sm.add_constant(data.exog) + >>> results = sm.OLS(data.endog, data.exog).fit() + >>> results.conf_int() + array([[-5496529.48322745, -1467987.78596704], + [ -177.02903529, 207.15277984], + [ -0.1115811 , 0.03994274], + [ -3.12506664, -0.91539297], + [ -1.5179487 , -0.54850503], + [ -0.56251721, 0.460309 ], + [ 798.7875153 , 2859.51541392]]) + + >>> results.conf_int()[2:4] + array([[-0.1115811 , 0.03994274], + [-3.12506664, -0.91539297]]) + """ + bse = self.bse + + if self.use_t: + dist = stats.t + df_resid = getattr(self, "df_resid_inference", self.df_resid) + q = dist.ppf(1 - alpha / 2, df_resid) + else: + dist = stats.norm + q = dist.ppf(1 - alpha / 2) + + params = self.params + lower = params - q * bse + upper = params + q * bse + return np.asarray(lzip(lower, upper)) + + def save(self, fname, remove_data=False): + """ + Save a pickle of this instance + + Parameters + ---------- + fname : str or handle + A string filename or a file handle. + remove_data : bool, optional + If False (default), then the instance is pickled without changes. + If True, then all arrays with length nobs are set to None before + pickling. See the remove_data method. + In some cases not all arrays will be set to None. + + Notes + ----- + If remove_data is true and the model result does not implement a + remove_data method then this will raise an exception. + """ + + from statsmodels.iolib.smpickle import save_pickle + + if remove_data: + self.remove_data() + + save_pickle(self, fname) + + @classmethod + def load(cls, fname): + """ + Load a pickled results instance + + .. warning:: + + Loading pickled models is not secure against erroneous or + maliciously constructed data. Never unpickle data received from + an untrusted or unauthenticated source. + + Parameters + ---------- + fname : str, handle, or pathlib.Path + A string filename or a file handle. + + Returns + ------- + Results + The unpickled results instance. + """ + + from statsmodels.iolib.smpickle import load_pickle + + return load_pickle(fname) + + def remove_data(self): + """ + Remove data arrays, all nobs arrays from result and model + + This reduces the size of the instance, so it can be pickled with less + memory. Currently tested for use with predict from an unpickled + results and model instance. + + .. warning:: + + Any data-dependent statistics needed for displaying a model summary + can be calculated and memoized by calling ``summary()`` prior to + calling ``remove_data()``. In general, if ``summary()`` is not + called before ``remove_data()``, ``summary()`` will fail. + + .. warning:: + + Since data and some intermediate results have been removed + calculating new statistics that require them will raise exceptions. + The exception will occur the first time an attribute is accessed + that has been set to None. + + Not fully tested for time series models, tsa, and might delete too much + for prediction or not all that would be possible. + + The lists of arrays to delete are maintained as attributes of + the result and model instance, except for cached values. These + lists could be changed before calling remove_data. + + The attributes to remove are named in: + + model._data_attr : arrays attached to both the model instance + and the results instance with the same attribute name. + + result._data_in_cache : arrays that may exist as values in + result._cache + + result._data_attr_model : arrays attached to the model + instance but not to the results instance + """ + cls = self.__class__ + # Note: we cannot just use `getattr(cls, x)` or `getattr(self, x)` + # because of redirection involved with property-like accessors + cls_attrs = {} + for name in dir(cls): + try: + attr = object.__getattribute__(cls, name) + except AttributeError: + pass + else: + cls_attrs[name] = attr + data_attrs = [x for x in cls_attrs if isinstance(cls_attrs[x], cached_data)] + for name in data_attrs: + self._cache[name] = None + + def wipe(obj, att): + # get to last element in attribute path + p = att.split(".") + att_ = p.pop(-1) + try: + obj_ = reduce(getattr, [obj] + p) + if hasattr(obj_, att_): + setattr(obj_, att_, None) + except AttributeError: + pass + + model_only = ["model." + i for i in getattr(self, "_data_attr_model", [])] + model_attr = ["model." + i for i in self.model._data_attr] + for att in self._data_attr + model_attr + model_only: + if att in data_attrs: + # these have been handled above, and trying to call wipe + # would raise an Exception anyway, so skip these + continue + wipe(self, att) + + for key in self._data_in_cache: + try: + self._cache[key] = None + except (AttributeError, KeyError): + pass + + def _summary_cache(self, key, compute): + """ + Compute and memoize a value that must survive remove_data(). + + ``cache_readonly`` values are unconditionally cleared by + ``remove_data()`` (see its docstring), so anything a `summary()` + (or similar) implementation needs after `remove_data()` has been + called must be memoized some other way. This stores the result of + ``compute()`` in a plain dict on the instance, keyed by ``key`` -- + untouched by ``remove_data()`` -- and only calls ``compute()`` the + first time a given ``key`` is requested. + + Parameters + ---------- + key : str + Name under which to cache the computed value. + compute : callable + Zero-argument callable that computes the value; only invoked + on the first call for a given ``key``. + + Returns + ------- + The cached (or newly computed) value. + """ + cache = self.__dict__.setdefault("_summary_statistics_cache", {}) + if key not in cache: + cache[key] = compute() + return cache[key] + + +class LikelihoodResultsWrapper(wrap.ResultsWrapper): + _attrs = { + "params": "columns", + "bse": "columns", + "pvalues": "columns", + "tvalues": "columns", + "resid": "rows", + "fittedvalues": "rows", + "normalized_cov_params": "cov", + } + + _wrap_attrs = _attrs + _wrap_methods = {"cov_params": "cov", "conf_int": "columns"} + + +wrap.populate_wrapper(LikelihoodResultsWrapper, LikelihoodModelResults) + + +class ResultMixin: + + @cache_readonly + def df_modelwc(self): + """Model WC""" + # collect different ways of defining the number of parameters, used for + # aic, bic + k_extra = getattr(self.model, "k_extra", 0) + if hasattr(self, "df_model"): + if hasattr(self, "k_constant"): + hasconst = self.k_constant + elif hasattr(self, "hasconst"): + hasconst = self.hasconst + else: + # default assumption + hasconst = 1 + return self.df_model + hasconst + k_extra + else: + return self.params.size + + @cache_readonly + def aic(self): + """Akaike information criterion""" + return -2 * self.llf + 2 * (self.df_modelwc) + + @cache_readonly + def bic(self): + """Bayesian information criterion""" + return -2 * self.llf + np.log(self.nobs) * (self.df_modelwc) + + @cache_readonly + def score_obsv(self): + """Cached Jacobian of log-likelihood""" + return self.model.score_obs(self.params) + + @cache_readonly + def hessv(self): + """Cached Hessian of log-likelihood""" + return self.model.hessian(self.params) + + @cache_readonly + def covjac(self): + """ + Covariance of parameters based on outer product of jacobian of + log-likelihood + """ + # if not hasattr(self, '_results'): + # raise ValueError('need to call fit first') + # # self.fit() + # self.jacv = jacv = self.jac(self._results.params) + jacv = self.score_obsv + return np.linalg.inv(np.dot(jacv.T, jacv)) + + @cache_readonly + def covjhj(self): + """ + Covariance of parameters based on HJJH + + dot product of Hessian, Jacobian, Jacobian, Hessian of likelihood + + name should be covhjh + """ + jacv = self.score_obsv + hessv = self.hessv + hessinv = np.linalg.inv(hessv) + # self.hessinv = hessin = self.cov_params() + return np.dot(hessinv, np.dot(np.dot(jacv.T, jacv), hessinv)) + + @cache_readonly + def bsejhj(self): + """Standard deviation of parameter estimates based on covHJH""" + return np.sqrt(np.diag(self.covjhj)) + + @cache_readonly + def bsejac(self): + """Standard deviation of parameter estimates based on covjac""" + return np.sqrt(np.diag(self.covjac)) + + def bootstrap(self, nrep=100, method="nm", disp=0, store=1, rng=None): + """ + Simple bootstrap to get mean and variance of estimator + + See notes + + Parameters + ---------- + nrep : int, optional + Number of bootstrap replications. + method : str, optional + Optimization method to use. + disp : bool, optional + If true, then optimization prints results. + store : bool, optional + If true, then parameter estimates for all bootstrap iterations + are attached in self.bootstrap_results. + rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional + If `rng` is None, a new ``Generator`` is created using fresh + entropy from the operating system. If `rng` is an int or array + of ints, a new ``Generator`` is created, seeded with `rng`. If + `rng` is already a ``Generator`` or ``RandomState`` instance, + that instance is used. + + Returns + ------- + mean : ndarray + Mean of parameter estimates over bootstrap replications. + std : ndarray + Standard deviation of parameter estimates over bootstrap + replications. + results : ndarray + Parameter estimates for each bootstrap replication. + + Notes + ----- + This was mainly written to compare estimators of the standard errors of + the parameter estimates. It uses independent random sampling from the + original endog and exog, and therefore is only correct if observations + are independently distributed. + + This will be moved to apply only to models with independently + distributed observations. + """ + results = [] + hascloneattr = True if hasattr(self.model, "cloneattr") else False + for _ in range(nrep): + rng = check_random_state(rng) + if isinstance(rng, np.random.Generator): + rvsind = rng.integers(self.nobs, size=self.nobs) + else: + assert isinstance(rng, np.random.RandomState) + rvsind = rng.randint(self.nobs, size=self.nobs) + # this needs to set startparam and get other defining attributes + # need a clone method on model + if self.exog is not None: + exog_resamp = self.exog[rvsind, :] + else: + exog_resamp = None + # build auxiliary model and fit + init_kwds = self.model._get_init_kwds() + fitmod = self.model.__class__( + self.endog[rvsind], exog=exog_resamp, **init_kwds + ) + if hascloneattr: + for attr in self.model.cloneattr: + setattr(fitmod, attr, getattr(self.model, attr)) + + fitres = fitmod.fit(method=method, disp=disp) + results.append(fitres.params) + results = np.array(results) + if store: + self.bootstrap_results = results + return results.mean(0), results.std(0), results + + def get_nlfun(self, fun): + """Get delta-method function for nonlinear tests, not implemented""" + # I think this is supposed to get the delta method that is currently + # in miscmodels count (as part of Poisson example) + raise NotImplementedError + + +class _LLRMixin: + """Mixin class for Null model and likelihood ratio""" + + # methods copied from DiscreteResults, adjusted pseudo R2 + + def pseudo_rsquared(self, kind="mcf"): + """McFadden's pseudo-R-squared. `1 - (llf / llnull)`""" + kind = kind.lower() + if kind.startswith("mcf"): + prsq = 1 - self.llf / self.llnull + elif kind.startswith("cox") or kind in ["cs", "lr"]: + prsq = 1 - np.exp((self.llnull - self.llf) * (2 / self.nobs)) + else: + raise ValueError("only McFadden and Cox-Snell are available") + return prsq + + @cache_readonly + def llr(self): + """Likelihood ratio chi-squared statistic; `-2*(llnull - llf)`""" + return -2 * (self.llnull - self.llf) + + @cache_readonly + def llr_pvalue(self): + """ + The chi-squared probability of getting a log-likelihood ratio + statistic greater than llr. llr has a chi-squared distribution + with degrees of freedom `df_model` + """ + # see also RegressionModel compare_lr_test + llr = self.llr + df_full = self.df_resid + df_restr = self.df_resid_null + lrdf = df_restr - df_full + self.df_lr_null = lrdf + return stats.distributions.chi2.sf(llr, lrdf) + + def set_null_options(self, llnull=None, attach_results=True, **kwargs): + """ + Set the fit options for the Null (constant-only) model + + This resets the cache for related attributes which is potentially + fragile. This only sets the option, the null model is estimated + when llnull is accessed, if llnull is not yet in cache. + + Parameters + ---------- + llnull : float, optional + If llnull is not None, then the value will be directly assigned to + the cached attribute "llnull". + attach_results : bool, optional + Sets an internal flag whether the results instance of the null + model should be attached. By default without calling this method, + the null model results are not attached and only the loglikelihood + value llnull is stored. + **kwargs + Additional keyword arguments used as fit keyword arguments for the + null model. These override the model default values. + + Notes + ----- + Modifies attributes of this instance, and so has no return. + """ + # reset cache, note we need to add here anything that depends on + # llnull or the null model. If something is missing, then the attribute + # might be incorrect. + self._cache.pop("llnull", None) + self._cache.pop("llr", None) + self._cache.pop("llr_pvalue", None) + self._cache.pop("prsquared", None) + if hasattr(self, "res_null"): + del self.res_null + + if llnull is not None: + self._cache["llnull"] = llnull + self._attach_nullmodel = attach_results + self._optim_kwds_null = kwargs + + @cache_readonly + def llnull(self): + """Value of the constant-only loglikelihood""" + model = self.model + kwds = model._get_init_kwds().copy() + for key in getattr(model, "_null_drop_keys", []): + del kwds[key] + # TODO: what parameters to pass to fit? + mod_null = model.__class__(model.endog, np.ones(self.nobs), **kwds) + # TODO: consider catching and warning on convergence failure? + # in the meantime, try hard to converge. see + # TestPoissonConstrained1a.test_smoke + + optim_kwds = getattr(self, "_optim_kwds_null", {}).copy() + + if "start_params" in optim_kwds: + # user provided + sp_null = optim_kwds.pop("start_params") + elif hasattr(model, "_get_start_params_null"): + # get moment estimates if available + sp_null = model._get_start_params_null() + else: + sp_null = None + + opt_kwds = dict(method="bfgs", warn_convergence=False, maxiter=10000, disp=0) + opt_kwds.update(optim_kwds) + + if optim_kwds: + res_null = mod_null.fit(start_params=sp_null, **opt_kwds) + else: + # this should be a reasonably method case across versions + res_null = mod_null.fit( + start_params=sp_null, + method="nm", + warn_convergence=False, + maxiter=10000, + disp=0, + ) + res_null = mod_null.fit( + start_params=res_null.params, + method="bfgs", + warn_convergence=False, + maxiter=10000, + disp=0, + ) + + if getattr(self, "_attach_nullmodel", False) is not False: + self.res_null = res_null + + self.k_null = len(res_null.params) + self.df_resid_null = res_null.df_resid + return res_null.llf + + +class GenericLikelihoodModelResults(LikelihoodModelResults, ResultMixin): + """ + A results class for the discrete dependent variable models + + Parameters + ---------- + model : GenericLikelihoodModel instance + The fitted model instance. + mlefit : LikelihoodModelResults instance + This contains the numerical optimization results as returned by + LikelihoodModel.fit(), in a superclass of GenericLikelihoodModels. + + Attributes + ---------- + aic : float + Akaike information criterion. -2*(`llf` - p) where p is the number + of regressors including the intercept. + bic : float + Bayesian information criterion. -2*`llf` + ln(`nobs`)*p where p is the + number of regressors including the intercept. + bse : ndarray + The standard errors of the coefficients. + df_resid : float + See model definition. + df_model : float + See model definition. + fittedvalues : ndarray + Linear predictor XB. + llf : float + Value of the loglikelihood + llnull : float + Value of the constant-only loglikelihood + llr : float + Likelihood ratio chi-squared statistic; -2*(`llnull` - `llf`) + llr_pvalue : float + The chi-squared probability of getting a log-likelihood ratio + statistic greater than llr. llr has a chi-squared distribution + with degrees of freedom `df_model`. + prsquared : float + McFadden's pseudo-R-squared. 1 - (`llf`/`llnull`) + """ + + def __init__(self, model, mlefit): + self.model = model + self.endog = model.endog + self.exog = model.exog + self.nobs = model.endog.shape[0] + # Does not call Results.__init__, so set these directly; needed for + # remove_data() to work (it assumes both attributes exist). + self._data_attr = ["endog", "exog"] + self._data_in_cache = ["fittedvalues", "resid", "wresid"] + + # TODO: possibly move to model.fit() + # and outsource together with patching names + k_extra = getattr(self.model, "k_extra", 0) + if hasattr(model, "df_model") and not np.isnan(model.df_model): + self.df_model = model.df_model + else: + df_model = len(mlefit.params) - self.model.k_constant - k_extra + self.df_model = df_model + # retrofitting the model, used in t_test TODO: check design + self.model.df_model = df_model + + if hasattr(model, "df_resid") and not np.isnan(model.df_resid): + self.df_resid = model.df_resid + else: + self.df_resid = self.endog.shape[0] - self.df_model - k_extra + # retrofitting the model, used in t_test TODO: check design + self.model.df_resid = self.df_resid + + self._cache = {} + self.__dict__.update(mlefit.__dict__) + + k_params = len(mlefit.params) + # checks mainly for adding new models or subclassing + + if self.df_model + self.model.k_constant + k_extra != k_params: + warnings.warn( + "df_model + k_constant + k_extra differs from k_params", + UserWarning, + stacklevel=2, + ) + + if self.df_resid != self.nobs - k_params: + warnings.warn("df_resid differs from nobs - k_params", stacklevel=2) + + def get_prediction( + self, + exog=None, + which="mean", + transform=True, + row_labels=None, + average=False, + agg_weights=None, + **kwargs, + ): + """ + Compute prediction results when endpoint transformation is valid + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + which : str, optional + Which statistic is to be predicted. Default is "mean". + The available statistics and options depend on the model. + See the model.predict docstring. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str or None, optional + If row_labels are provided, then they will replace the generated + labels. + average : bool, optional + If average is True, then the mean prediction is computed, that is, + predictions are computed for individual exog and then the average + over observation is used. + If average is False, then the results are the predictions for all + observations, i.e., same length as ``exog``. + agg_weights : ndarray, optional + Aggregation weights, only used if average is True. + The weights are not normalized. + **kwargs : + Some models can take additional keyword arguments, such as offset, + exposure or additional exog in multi-part models like zero inflated + models. + See the predict method of the model for the details. + + Returns + ------- + prediction_results : PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and + summary dataframe for the prediction. + + Notes + ----- + Status: new in 0.14, experimental + """ + from statsmodels.base._prediction_inference import get_prediction + + pred_kwds = kwargs + + res = get_prediction( + self, + exog=exog, + which=which, + transform=transform, + row_labels=row_labels, + average=average, + agg_weights=agg_weights, + pred_kwds=pred_kwds, + ) + return res + + def summary(self, yname=None, xname=None, title=None, alpha=0.05): + """ + Summarize the Regression Results + + Parameters + ---------- + yname : str, optional + Default is `y` + xname : list of str, optional + Names for the exogenous variables, default is "var_xx". + Must match the number of parameters in the model + title : str, optional + Title for the top table. If not None, then this replaces the + default title + alpha : float, optional + significance level for the confidence intervals + + Returns + ------- + smry : Summary instance + this holds the summary tables and text, which can be printed or + converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary.Summary : class to hold summary results + """ + + top_left = [ + ("Dep. Variable:", None), + ("Model:", None), + ("Method:", ["Maximum Likelihood"]), + ("Date:", None), + ("Time:", None), + ("No. Observations:", None), + ("Df Residuals:", None), + ("Df Model:", None), + ] + + top_right = [ + ("Log-Likelihood:", None), + ("AIC:", [f"{self.aic:#8.4g}"]), + ("BIC:", [f"{self.bic:#8.4g}"]), + ] + + if title is None: + title = self.model.__class__.__name__ + " " + "Results" + + # create summary table instance + from statsmodels.iolib.summary import Summary + + smry = Summary() + smry.add_table_2cols( + self, + gleft=top_left, + gright=top_right, + yname=yname, + xname=xname, + title=title, + ) + smry.add_table_params( + self, yname=yname, xname=xname, alpha=alpha, use_t=self.use_t + ) + + return smry diff --git a/shared/package-files/06/06443070da247d3f658ce4042c0a69e5b785a902808279427f097122843658ce/special_digamma_native.h b/shared/package-files/06/06443070da247d3f658ce4042c0a69e5b785a902808279427f097122843658ce/special_digamma_native.h new file mode 100644 index 0000000000000000000000000000000000000000..dc90fbdefc4a1477bed4f34f7e2fec3929f5aea6 --- /dev/null +++ b/shared/package-files/06/06443070da247d3f658ce4042c0a69e5b785a902808279427f097122843658ce/special_digamma_native.h @@ -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 special_digamma(const at::Tensor & self); +TORCH_API at::Tensor & special_digamma_out(const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/0644947fedb1a228fe7977e9576b7bcb5245286d730f582d57a6808375e2ff01/matplotlib.pdf b/shared/package-files/06/0644947fedb1a228fe7977e9576b7bcb5245286d730f582d57a6808375e2ff01/matplotlib.pdf new file mode 100644 index 0000000000000000000000000000000000000000..6c44566ad819ba31e93bf50d3b7c2b9fa1bb8f64 Binary files /dev/null and b/shared/package-files/06/0644947fedb1a228fe7977e9576b7bcb5245286d730f582d57a6808375e2ff01/matplotlib.pdf differ diff --git a/shared/package-files/06/0645aef3d7df9a27e405d2c7fbe210ec3896d21bc3915122b9d531e0745599c2/_onenormest.py b/shared/package-files/06/0645aef3d7df9a27e405d2c7fbe210ec3896d21bc3915122b9d531e0745599c2/_onenormest.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e806ab6fbd5a2910de823a1046bce225d60a13 --- /dev/null +++ b/shared/package-files/06/0645aef3d7df9a27e405d2c7fbe210ec3896d21bc3915122b9d531e0745599c2/_onenormest.py @@ -0,0 +1,467 @@ +"""Sparse block 1-norm estimator. +""" + +import numpy as np +from scipy.sparse.linalg import aslinearoperator + + +__all__ = ['onenormest'] + + +def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False): + """ + Compute a lower bound of the 1-norm of a sparse array. + + Parameters + ---------- + A : ndarray or other linear operator + A linear operator that can be transposed and that can + produce matrix products. + t : int, optional + A positive parameter controlling the tradeoff between + accuracy versus time and memory usage. + Larger values take longer and use more memory + but give more accurate output. + itmax : int, optional + Use at most this many iterations. + compute_v : bool, optional + Request a norm-maximizing linear operator input vector if True. + compute_w : bool, optional + Request a norm-maximizing linear operator output vector if True. + + Returns + ------- + est : float + An underestimate of the 1-norm of the sparse array. + v : ndarray, optional + The vector such that ||Av||_1 == est*||v||_1. + It can be thought of as an input to the linear operator + that gives an output with particularly large norm. + w : ndarray, optional + The vector Av which has relatively large 1-norm. + It can be thought of as an output of the linear operator + that is relatively large in norm compared to the input. + + Notes + ----- + This is algorithm 2.4 of [1]. + + In [2] it is described as follows. + "This algorithm typically requires the evaluation of + about 4t matrix-vector products and almost invariably + produces a norm estimate (which is, in fact, a lower + bound on the norm) correct to within a factor 3." + + .. versionadded:: 0.13.0 + + References + ---------- + .. [1] Nicholas J. Higham and Francoise Tisseur (2000), + "A Block Algorithm for Matrix 1-Norm Estimation, + with an Application to 1-Norm Pseudospectra." + SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201. + + .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009), + "A new scaling and squaring algorithm for the matrix exponential." + SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import onenormest + >>> A = csc_array([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float) + >>> A.toarray() + array([[ 1., 0., 0.], + [ 5., 8., 2.], + [ 0., -1., 0.]]) + >>> onenormest(A) + 9.0 + >>> np.linalg.norm(A.toarray(), ord=1) + 9.0 + """ + + # Check the input. + A = aslinearoperator(A) + if A.shape[0] != A.shape[1]: + raise ValueError('expected the operator to act like a square matrix') + + # If the operator size is small compared to t, + # then it is easier to compute the exact norm. + # Otherwise estimate the norm. + n = A.shape[1] + if t >= n: + A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n))) + if A_explicit.shape != (n, n): + raise Exception('internal error: ', + 'unexpected shape ' + str(A_explicit.shape)) + col_abs_sums = abs(A_explicit).sum(axis=0) + if col_abs_sums.shape != (n, ): + raise Exception('internal error: ', + 'unexpected shape ' + str(col_abs_sums.shape)) + argmax_j = np.argmax(col_abs_sums) + v = elementary_vector(n, argmax_j) + w = A_explicit[:, argmax_j] + est = col_abs_sums[argmax_j] + else: + est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax) + + # Report the norm estimate along with some certificates of the estimate. + if compute_v or compute_w: + result = (est,) + if compute_v: + result += (v,) + if compute_w: + result += (w,) + return result + else: + return est + + +def _blocked_elementwise(func): + """ + Decorator for an elementwise function, to apply it blockwise along + first dimension, to avoid excessive memory usage in temporaries. + """ + block_size = 2**20 + + def wrapper(x): + if x.shape[0] < block_size: + return func(x) + else: + y0 = func(x[:block_size]) + y = np.zeros((x.shape[0],) + y0.shape[1:], dtype=y0.dtype) + y[:block_size] = y0 + del y0 + for j in range(block_size, x.shape[0], block_size): + y[j:j+block_size] = func(x[j:j+block_size]) + return y + return wrapper + + +@_blocked_elementwise +def sign_round_up(X): + """ + This should do the right thing for both real and complex matrices. + + From Higham and Tisseur: + "Everything in this section remains valid for complex matrices + provided that sign(A) is redefined as the matrix (aij / |aij|) + (and sign(0) = 1) transposes are replaced by conjugate transposes." + + """ + Y = X.copy() + Y[Y == 0] = 1 + Y /= np.abs(Y) + return Y + + +@_blocked_elementwise +def _max_abs_axis1(X): + return np.max(np.abs(X), axis=1) + + +def _sum_abs_axis0(X): + block_size = 2**20 + r = None + for j in range(0, X.shape[0], block_size): + y = np.sum(np.abs(X[j:j+block_size]), axis=0) + if r is None: + r = y + else: + r += y + return r + + +def elementary_vector(n, i): + v = np.zeros(n, dtype=float) + v[i] = 1 + return v + + +def vectors_are_parallel(v, w): + # Columns are considered parallel when they are equal or negative. + # Entries are required to be in {-1, 1}, + # which guarantees that the magnitudes of the vectors are identical. + if v.ndim != 1 or v.shape != w.shape: + raise ValueError('expected conformant vectors with entries in {-1,1}') + n = v.shape[0] + return np.dot(v, w) == n + + +def every_col_of_X_is_parallel_to_a_col_of_Y(X, Y): + for v in X.T: + if not any(vectors_are_parallel(v, w) for w in Y.T): + return False + return True + + +def column_needs_resampling(i, X, Y=None): + # column i of X needs resampling if either + # it is parallel to a previous column of X or + # it is parallel to a column of Y + n, t = X.shape + v = X[:, i] + if any(vectors_are_parallel(v, X[:, j]) for j in range(i)): + return True + if Y is not None: + if any(vectors_are_parallel(v, w) for w in Y.T): + return True + return False + + +def resample_column(i, X): + X[:, i] = np.random.randint(0, 2, size=X.shape[0])*2 - 1 + + +def less_than_or_close(a, b): + return np.allclose(a, b) or (a < b) + + +def _algorithm_2_2(A, AT, t): + """ + This is Algorithm 2.2. + + Parameters + ---------- + A : ndarray or other linear operator + A linear operator that can produce matrix products. + AT : ndarray or other linear operator + The transpose of A. + t : int, optional + A positive parameter controlling the tradeoff between + accuracy versus time and memory usage. + + Returns + ------- + g : sequence + A non-negative decreasing vector + such that g[j] is a lower bound for the 1-norm + of the column of A of jth largest 1-norm. + The first entry of this vector is therefore a lower bound + on the 1-norm of the linear operator A. + This sequence has length t. + ind : sequence + The ith entry of ind is the index of the column A whose 1-norm + is given by g[i]. + This sequence of indices has length t, and its entries are + chosen from range(n), possibly with repetition, + where n is the order of the operator A. + + Notes + ----- + This algorithm is mainly for testing. + It uses the 'ind' array in a way that is similar to + its usage in algorithm 2.4. This algorithm 2.2 may be easier to test, + so it gives a chance of uncovering bugs related to indexing + which could have propagated less noticeably to algorithm 2.4. + + """ + A_linear_operator = aslinearoperator(A) + AT_linear_operator = aslinearoperator(AT) + n = A_linear_operator.shape[0] + + # Initialize the X block with columns of unit 1-norm. + X = np.ones((n, t)) + if t > 1: + X[:, 1:] = np.random.randint(0, 2, size=(n, t-1))*2 - 1 + X /= float(n) + + # Iteratively improve the lower bounds. + # Track extra things, to assert invariants for debugging. + g_prev = None + h_prev = None + k = 1 + ind = range(t) + while True: + Y = np.asarray(A_linear_operator.matmat(X)) + g = _sum_abs_axis0(Y) + best_j = np.argmax(g) + g.sort() + g = g[::-1] + S = sign_round_up(Y) + Z = np.asarray(AT_linear_operator.matmat(S)) + h = _max_abs_axis1(Z) + + # If this algorithm runs for fewer than two iterations, + # then its return values do not have the properties indicated + # in the description of the algorithm. + # In particular, the entries of g are not 1-norms of any + # column of A until the second iteration. + # Therefore we will require the algorithm to run for at least + # two iterations, even though this requirement is not stated + # in the description of the algorithm. + if k >= 2: + if less_than_or_close(max(h), np.dot(Z[:, best_j], X[:, best_j])): + break + ind = np.argsort(h)[::-1][:t] + h = h[ind] + for j in range(t): + X[:, j] = elementary_vector(n, ind[j]) + + # Check invariant (2.2). + if k >= 2: + if not less_than_or_close(g_prev[0], h_prev[0]): + raise Exception('invariant (2.2) is violated') + if not less_than_or_close(h_prev[0], g[0]): + raise Exception('invariant (2.2) is violated') + + # Check invariant (2.3). + if k >= 3: + for j in range(t): + if not less_than_or_close(g[j], g_prev[j]): + raise Exception('invariant (2.3) is violated') + + # Update for the next iteration. + g_prev = g + h_prev = h + k += 1 + + # Return the lower bounds and the corresponding column indices. + return g, ind + + +def _onenormest_core(A, AT, t, itmax): + """ + Compute a lower bound of the 1-norm of a sparse array. + + Parameters + ---------- + A : ndarray or other linear operator + A linear operator that can produce matrix products. + AT : ndarray or other linear operator + The transpose of A. + t : int, optional + A positive parameter controlling the tradeoff between + accuracy versus time and memory usage. + itmax : int, optional + Use at most this many iterations. + + Returns + ------- + est : float + An underestimate of the 1-norm of the sparse array. + v : ndarray, optional + The vector such that ||Av||_1 == est*||v||_1. + It can be thought of as an input to the linear operator + that gives an output with particularly large norm. + w : ndarray, optional + The vector Av which has relatively large 1-norm. + It can be thought of as an output of the linear operator + that is relatively large in norm compared to the input. + nmults : int, optional + The number of matrix products that were computed. + nresamples : int, optional + The number of times a parallel column was observed, + necessitating a re-randomization of the column. + + Notes + ----- + This is algorithm 2.4. + + """ + # This function is a more or less direct translation + # of Algorithm 2.4 from the Higham and Tisseur (2000) paper. + A_linear_operator = aslinearoperator(A) + AT_linear_operator = aslinearoperator(AT) + if itmax < 2: + raise ValueError('at least two iterations are required') + if t < 1: + raise ValueError('at least one column is required') + n = A.shape[0] + if t >= n: + raise ValueError('t should be smaller than the order of A') + # Track the number of big*small matrix multiplications + # and the number of resamplings. + nmults = 0 + nresamples = 0 + # "We now explain our choice of starting matrix. We take the first + # column of X to be the vector of 1s [...] This has the advantage that + # for a matrix with nonnegative elements the algorithm converges + # with an exact estimate on the second iteration, and such matrices + # arise in applications [...]" + X = np.ones((n, t), dtype=float) + # "The remaining columns are chosen as rand{-1,1}, + # with a check for and correction of parallel columns, + # exactly as for S in the body of the algorithm." + if t > 1: + for i in range(1, t): + # These are technically initial samples, not resamples, + # so the resampling count is not incremented. + resample_column(i, X) + for i in range(t): + while column_needs_resampling(i, X): + resample_column(i, X) + nresamples += 1 + # "Choose starting matrix X with columns of unit 1-norm." + X /= float(n) + # "indices of used unit vectors e_j" + ind_hist = np.zeros(0, dtype=np.intp) + est_old = 0 + S = np.zeros((n, t), dtype=float) + k = 1 + ind = None + while True: + Y = np.asarray(A_linear_operator.matmat(X)) + nmults += 1 + mags = _sum_abs_axis0(Y) + est = np.max(mags) + best_j = np.argmax(mags) + if est > est_old or k == 2: + if k >= 2: + ind_best = ind[best_j] + w = Y[:, best_j] + # (1) + if k >= 2 and est <= est_old: + est = est_old + break + est_old = est + S_old = S + if k > itmax: + break + S = sign_round_up(Y) + del Y + # (2) + if every_col_of_X_is_parallel_to_a_col_of_Y(S, S_old): + break + if t > 1: + # "Ensure that no column of S is parallel to another column of S + # or to a column of S_old by replacing columns of S by rand{-1,1}." + for i in range(t): + while column_needs_resampling(i, S, S_old): + resample_column(i, S) + nresamples += 1 + del S_old + # (3) + Z = np.asarray(AT_linear_operator.matmat(S)) + nmults += 1 + h = _max_abs_axis1(Z) + del Z + # (4) + if k >= 2 and max(h) == h[ind_best]: + break + # "Sort h so that h_first >= ... >= h_last + # and re-order ind correspondingly." + # + # Later on, we will need at most t+len(ind_hist) largest + # entries, so drop the rest + ind = np.argsort(h)[::-1][:t+len(ind_hist)].copy() + del h + if t > 1: + # (5) + # Break if the most promising t vectors have been visited already. + if np.isin(ind[:t], ind_hist).all(): + break + # Put the most promising unvisited vectors at the front of the list + # and put the visited vectors at the end of the list. + # Preserve the order of the indices induced by the ordering of h. + seen = np.isin(ind, ind_hist) + ind = np.concatenate((ind[~seen], ind[seen])) + for j in range(t): + X[:, j] = elementary_vector(n, ind[j]) + + new_ind = ind[:t][~np.isin(ind[:t], ind_hist)] + ind_hist = np.concatenate((ind_hist, new_ind)) + k += 1 + v = elementary_vector(n, ind_best) + return est, v, w, nmults, nresamples diff --git a/shared/package-files/06/06474d45271bdfef20742bf0414eb87935942601969000a4be23fa345ba63f3a/native_layer_norm_backward_native.h b/shared/package-files/06/06474d45271bdfef20742bf0414eb87935942601969000a4be23fa345ba63f3a/native_layer_norm_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..814a88d116834f88290c3c8f9fe4f1ab8942bc2f --- /dev/null +++ b/shared/package-files/06/06474d45271bdfef20742bf0414eb87935942601969000a4be23fa345ba63f3a/native_layer_norm_backward_native.h @@ -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 native_layer_norm_backward_out_symint(const at::Tensor & grad_out, const at::Tensor & input, c10::SymIntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional & weight, const c10::optional & bias, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +TORCH_API ::std::tuple layer_norm_backward_cpu(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional & weight, const c10::optional & bias, ::std::array output_mask); +TORCH_API ::std::tuple layer_norm_backward_cuda(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional & weight, const c10::optional & bias, ::std::array output_mask); +TORCH_API ::std::tuple layer_norm_backward_nested(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional & weight, const c10::optional & bias, ::std::array output_mask); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/064c0c5a812384deb8751898da757ca6696daa03c14cd3dcb303273e3879beec/ttkmenu.tcl b/shared/package-files/06/064c0c5a812384deb8751898da757ca6696daa03c14cd3dcb303273e3879beec/ttkmenu.tcl new file mode 100644 index 0000000000000000000000000000000000000000..0084dd6ae436940e9bd866ba04437d32f7841a02 --- /dev/null +++ b/shared/package-files/06/064c0c5a812384deb8751898da757ca6696daa03c14cd3dcb303273e3879beec/ttkmenu.tcl @@ -0,0 +1,53 @@ +# ttkmenu.tcl -- +# +# This demonstration script creates a toplevel window containing several Ttk +# menubutton widgets. + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +package require Tk + +set w .ttkmenu +catch {destroy $w} +toplevel $w +wm title $w "Ttk Menu Buttons" +wm iconname $w "ttkmenu" +positionWindow $w + +ttk::label $w.msg -font $font -wraplength 4i -justify left -text "Ttk is the new Tk themed widget set, and one widget that is available in themed form is the menubutton. Below are some themed menu buttons that allow you to pick the current theme in use. Notice how picking a theme changes the way that the menu buttons themselves look, and that the central menu button is styled differently (in a way that is normally suitable for toolbars). However, there are no themed menus; the standard Tk menus were judged to have a sufficiently good look-and-feel on all platforms, especially as they are implemented as native controls in many places." +pack $w.msg [ttk::separator $w.msgSep] -side top -fill x + +## See Code / Dismiss +pack [addSeeDismiss $w.seeDismiss $w] -side bottom -fill x + +ttk::menubutton $w.m1 -menu $w.m1.menu -text "Select a theme" -direction above +ttk::menubutton $w.m2 -menu $w.m1.menu -text "Select a theme" -direction left +ttk::menubutton $w.m3 -menu $w.m1.menu -text "Select a theme" -direction right +ttk::menubutton $w.m4 -menu $w.m1.menu -text "Select a theme" \ + -direction flush -style TMenubutton.Toolbutton +ttk::menubutton $w.m5 -menu $w.m1.menu -text "Select a theme" -direction below + +menu $w.m1.menu -tearoff 0 +menu $w.m2.menu -tearoff 0 +menu $w.m3.menu -tearoff 0 +menu $w.m4.menu -tearoff 0 +menu $w.m5.menu -tearoff 0 + +foreach theme [ttk::themes] { + $w.m1.menu add command -label $theme -command [list ttk::setTheme $theme] + $w.m2.menu add command -label $theme -command [list ttk::setTheme $theme] + $w.m3.menu add command -label $theme -command [list ttk::setTheme $theme] + $w.m4.menu add command -label $theme -command [list ttk::setTheme $theme] + $w.m5.menu add command -label $theme -command [list ttk::setTheme $theme] +} + +pack [ttk::frame $w.f] -fill x +pack [ttk::frame $w.f1] -fill both -expand yes +lower $w.f + +grid anchor $w.f center +grid x $w.m1 x -in $w.f -padx 3 -pady 2 +grid $w.m2 $w.m4 $w.m3 -in $w.f -padx 3 -pady 2 +grid x $w.m5 x -in $w.f -padx 3 -pady 2 diff --git a/shared/package-files/06/064d6dd8bb636b3af33f338112552beb14d7c26d5b4914fdcaa5fcef1ac475e4/converters.pyi b/shared/package-files/06/064d6dd8bb636b3af33f338112552beb14d7c26d5b4914fdcaa5fcef1ac475e4/converters.pyi new file mode 100644 index 0000000000000000000000000000000000000000..70cb260642bacad8b8e9632fddbfaf0ccec7403c --- /dev/null +++ b/shared/package-files/06/064d6dd8bb636b3af33f338112552beb14d7c26d5b4914fdcaa5fcef1ac475e4/converters.pyi @@ -0,0 +1,11 @@ +from typing import Callable, Optional, TypeVar, overload + +from . import _ConverterType + +_T = TypeVar("_T") + +def optional(converter: _ConverterType[_T]) -> _ConverterType[Optional[_T]]: ... +@overload +def default_if_none(default: _T) -> _ConverterType[_T]: ... +@overload +def default_if_none(*, factory: Callable[[], _T]) -> _ConverterType[_T]: ... diff --git a/shared/package-files/06/06512b22eb481311b9b644a58e810bbb239dda1854d815488c067748dd852ddb/_triton_multi_head_attention_native.h b/shared/package-files/06/06512b22eb481311b9b644a58e810bbb239dda1854d815488c067748dd852ddb/_triton_multi_head_attention_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4d4176426ededc8d9b0b7733a4714085093c17c4 --- /dev/null +++ b/shared/package-files/06/06512b22eb481311b9b644a58e810bbb239dda1854d815488c067748dd852ddb/_triton_multi_head_attention_native.h @@ -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 & _triton_multi_head_attention_out(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional & mask, at::Tensor & out); +TORCH_API at::Tensor triton_multi_head_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional & mask={}); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06517ec2f74f1c6562d0a1a500c48ba43f2e6e9d0c3d28356d747f274f1a4c8d/cp1254.py b/shared/package-files/06/06517ec2f74f1c6562d0a1a500c48ba43f2e6e9d0c3d28356d747f274f1a4c8d/cp1254.py new file mode 100644 index 0000000000000000000000000000000000000000..4912327a5bcfc46a62579db4f6edfd89cde7bd5f --- /dev/null +++ b/shared/package-files/06/06517ec2f74f1c6562d0a1a500c48ba43f2e6e9d0c3d28356d747f274f1a4c8d/cp1254.py @@ -0,0 +1,307 @@ +""" Python Character Mapping Codec cp1254 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1254.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='cp1254', + 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 + '\u20ac' # 0x80 -> EURO SIGN + '\ufffe' # 0x81 -> UNDEFINED + '\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK + '\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK + '\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK + '\u2026' # 0x85 -> HORIZONTAL ELLIPSIS + '\u2020' # 0x86 -> DAGGER + '\u2021' # 0x87 -> DOUBLE DAGGER + '\u02c6' # 0x88 -> MODIFIER LETTER CIRCUMFLEX ACCENT + '\u2030' # 0x89 -> PER MILLE SIGN + '\u0160' # 0x8A -> LATIN CAPITAL LETTER S WITH CARON + '\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK + '\u0152' # 0x8C -> LATIN CAPITAL LIGATURE OE + '\ufffe' # 0x8D -> UNDEFINED + '\ufffe' # 0x8E -> UNDEFINED + '\ufffe' # 0x8F -> UNDEFINED + '\ufffe' # 0x90 -> UNDEFINED + '\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 + '\u02dc' # 0x98 -> SMALL TILDE + '\u2122' # 0x99 -> TRADE MARK SIGN + '\u0161' # 0x9A -> LATIN SMALL LETTER S WITH CARON + '\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + '\u0153' # 0x9C -> LATIN SMALL LIGATURE OE + '\ufffe' # 0x9D -> UNDEFINED + '\ufffe' # 0x9E -> UNDEFINED + '\u0178' # 0x9F -> LATIN CAPITAL LETTER Y WITH DIAERESIS + '\xa0' # 0xA0 -> NO-BREAK SPACE + '\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK + '\xa2' # 0xA2 -> CENT SIGN + '\xa3' # 0xA3 -> POUND SIGN + '\xa4' # 0xA4 -> CURRENCY SIGN + '\xa5' # 0xA5 -> YEN SIGN + '\xa6' # 0xA6 -> BROKEN BAR + '\xa7' # 0xA7 -> SECTION SIGN + '\xa8' # 0xA8 -> DIAERESIS + '\xa9' # 0xA9 -> COPYRIGHT SIGN + '\xaa' # 0xAA -> FEMININE ORDINAL INDICATOR + '\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xac' # 0xAC -> NOT SIGN + '\xad' # 0xAD -> SOFT HYPHEN + '\xae' # 0xAE -> REGISTERED SIGN + '\xaf' # 0xAF -> MACRON + '\xb0' # 0xB0 -> DEGREE SIGN + '\xb1' # 0xB1 -> PLUS-MINUS SIGN + '\xb2' # 0xB2 -> SUPERSCRIPT TWO + '\xb3' # 0xB3 -> SUPERSCRIPT THREE + '\xb4' # 0xB4 -> ACUTE ACCENT + '\xb5' # 0xB5 -> MICRO SIGN + '\xb6' # 0xB6 -> PILCROW SIGN + '\xb7' # 0xB7 -> MIDDLE DOT + '\xb8' # 0xB8 -> CEDILLA + '\xb9' # 0xB9 -> SUPERSCRIPT ONE + '\xba' # 0xBA -> MASCULINE ORDINAL INDICATOR + '\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER + '\xbd' # 0xBD -> VULGAR FRACTION ONE HALF + '\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS + '\xbf' # 0xBF -> INVERTED QUESTION MARK + '\xc0' # 0xC0 -> LATIN CAPITAL LETTER A WITH GRAVE + '\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE + '\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX + '\xc3' # 0xC3 -> LATIN CAPITAL LETTER A WITH TILDE + '\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS + '\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE + '\xc6' # 0xC6 -> LATIN CAPITAL LETTER AE + '\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA + '\xc8' # 0xC8 -> LATIN CAPITAL LETTER E WITH GRAVE + '\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE + '\xca' # 0xCA -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX + '\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS + '\xcc' # 0xCC -> LATIN CAPITAL LETTER I WITH GRAVE + '\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE + '\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX + '\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS + '\u011e' # 0xD0 -> LATIN CAPITAL LETTER G WITH BREVE + '\xd1' # 0xD1 -> LATIN CAPITAL LETTER N WITH TILDE + '\xd2' # 0xD2 -> LATIN CAPITAL LETTER O WITH GRAVE + '\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE + '\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX + '\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE + '\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS + '\xd7' # 0xD7 -> MULTIPLICATION SIGN + '\xd8' # 0xD8 -> LATIN CAPITAL LETTER O WITH STROKE + '\xd9' # 0xD9 -> LATIN CAPITAL LETTER U WITH GRAVE + '\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE + '\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX + '\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS + '\u0130' # 0xDD -> LATIN CAPITAL LETTER I WITH DOT ABOVE + '\u015e' # 0xDE -> LATIN CAPITAL LETTER S WITH CEDILLA + '\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S + '\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE + '\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE + '\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX + '\xe3' # 0xE3 -> LATIN SMALL LETTER A WITH TILDE + '\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS + '\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE + '\xe6' # 0xE6 -> LATIN SMALL LETTER AE + '\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA + '\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE + '\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE + '\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX + '\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS + '\xec' # 0xEC -> LATIN SMALL LETTER I WITH GRAVE + '\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE + '\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX + '\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS + '\u011f' # 0xF0 -> LATIN SMALL LETTER G WITH BREVE + '\xf1' # 0xF1 -> LATIN SMALL LETTER N WITH TILDE + '\xf2' # 0xF2 -> LATIN SMALL LETTER O WITH GRAVE + '\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE + '\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX + '\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE + '\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS + '\xf7' # 0xF7 -> DIVISION SIGN + '\xf8' # 0xF8 -> LATIN SMALL LETTER O WITH STROKE + '\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE + '\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE + '\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX + '\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS + '\u0131' # 0xFD -> LATIN SMALL LETTER DOTLESS I + '\u015f' # 0xFE -> LATIN SMALL LETTER S WITH CEDILLA + '\xff' # 0xFF -> LATIN SMALL LETTER Y WITH DIAERESIS +) + +### Encoding table +encoding_table=codecs.charmap_build(decoding_table) diff --git a/shared/package-files/06/065295d14dfa8ea9e5c4ce7e3f19fc388898e6424470b96ddd0668f86b0cce56/Dawson b/shared/package-files/06/065295d14dfa8ea9e5c4ce7e3f19fc388898e6424470b96ddd0668f86b0cce56/Dawson new file mode 100644 index 0000000000000000000000000000000000000000..07e4c5f4ac3852571b17cb33fe565a5ea2c49f0a Binary files /dev/null and b/shared/package-files/06/065295d14dfa8ea9e5c4ce7e3f19fc388898e6424470b96ddd0668f86b0cce56/Dawson differ diff --git a/shared/package-files/06/0652de1cead19b444d340db8c639054e7b1fb41dce25baab5633241d5c2107c2/linalg_norm_ops.h b/shared/package-files/06/0652de1cead19b444d340db8c639054e7b1fb41dce25baab5633241d5c2107c2/linalg_norm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..53c04c0687c1de681332bfc876a6b9d5c473de8c --- /dev/null +++ b/shared/package-files/06/0652de1cead19b444d340db8c639054e7b1fb41dce25baab5633241d5c2107c2/linalg_norm_ops.h @@ -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 linalg_norm { + using schema = at::Tensor (const at::Tensor &, const c10::optional &, at::OptionalIntArrayRef, bool, 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_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, const c10::optional & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype); +}; + +struct TORCH_API linalg_norm_ord_str { + using schema = at::Tensor (const at::Tensor &, c10::string_view, at::OptionalIntArrayRef, bool, 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_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ord_str") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm.ord_str(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype); +}; + +struct TORCH_API linalg_norm_out { + using schema = at::Tensor & (const at::Tensor &, const c10::optional &, at::OptionalIntArrayRef, bool, 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_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm.out(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const c10::optional & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); +}; + +struct TORCH_API linalg_norm_ord_str_out { + using schema = at::Tensor & (const at::Tensor &, c10::string_view, at::OptionalIntArrayRef, bool, 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_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ord_str_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm.ord_str_out(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/06539aac034cde1ba42acc1401fd615f521c2874306ac54869e5fe1d71be92c9/ttkpane.tcl b/shared/package-files/06/06539aac034cde1ba42acc1401fd615f521c2874306ac54869e5fe1d71be92c9/ttkpane.tcl new file mode 100644 index 0000000000000000000000000000000000000000..3f8898725d4a1f9b2d7ddd697e562b75e06ad56b --- /dev/null +++ b/shared/package-files/06/06539aac034cde1ba42acc1401fd615f521c2874306ac54869e5fe1d71be92c9/ttkpane.tcl @@ -0,0 +1,112 @@ +# ttkpane.tcl -- +# +# This demonstration script creates a Ttk pane with some content. + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +package require Tk + +set w .ttkpane +catch {destroy $w} +toplevel $w +wm title $w "Themed Nested Panes" +wm iconname $w "ttkpane" +positionWindow $w + +ttk::label $w.msg -font $font -wraplength 4i -justify left -text "This demonstration shows off a nested set of themed paned windows. Their sizes can be changed by grabbing the area between each contained pane and dragging the divider." +pack $w.msg [ttk::separator $w.msgSep] -side top -fill x + +## See Code / Dismiss +pack [addSeeDismiss $w.seeDismiss $w] -side bottom -fill x + +ttk::frame $w.f +pack $w.f -fill both -expand 1 +set w $w.f +ttk::panedwindow $w.outer -orient horizontal +$w.outer add [ttk::panedwindow $w.outer.inLeft -orient vertical] +$w.outer add [ttk::panedwindow $w.outer.inRight -orient vertical] +$w.outer.inLeft add [ttk::labelframe $w.outer.inLeft.top -text Button] +$w.outer.inLeft add [ttk::labelframe $w.outer.inLeft.bot -text Clocks] +$w.outer.inRight add [ttk::labelframe $w.outer.inRight.top -text Progress] +$w.outer.inRight add [ttk::labelframe $w.outer.inRight.bot -text Text] +if {[tk windowingsystem] eq "aqua"} { + foreach i [list inLeft.top inLeft.bot inRight.top inRight.bot] { + $w.outer.$i configure -padding 3 + } +} + +# Fill the button pane +ttk::button $w.outer.inLeft.top.b -text "Press Me" -command { + tk_messageBox -type ok -icon info -message "Ouch!" -detail "That hurt..." \ + -parent .ttkpane -title "Button Pressed" +} +pack $w.outer.inLeft.top.b -padx 2 -pady 5 + +# Fill the clocks pane +set i 0 +proc every {delay script} { + uplevel #0 $script + after $delay [list every $delay $script] +} +set testzones { + :Europe/Berlin + :America/Argentina/Buenos_Aires + :Africa/Johannesburg + :Europe/London + :America/Los_Angeles + :Europe/Moscow + :America/New_York + :Asia/Singapore + :Australia/Sydney + :Asia/Tokyo +} +# Force a pre-load of all the timezones needed; otherwise can end up +# poor-looking synch problems! +set zones {} +foreach zone $testzones { + if {![catch {clock format 0 -timezone $zone}]} { + lappend zones $zone + } +} +if {[llength $zones] < 2} { lappend zones -0200 :GMT :UTC +0200 } +foreach zone $zones { + set city [string map {_ " "} [regexp -inline {[^/]+$} $zone]] + if {$i} { + pack [ttk::separator $w.outer.inLeft.bot.s$i] -fill x + } + ttk::label $w.outer.inLeft.bot.l$i -text $city -anchor w + ttk::label $w.outer.inLeft.bot.t$i -textvariable time($zone) -anchor w + pack $w.outer.inLeft.bot.l$i $w.outer.inLeft.bot.t$i -fill x + every 1000 "set time($zone) \[clock format \[clock seconds\] -timezone $zone -format %T\]" + incr i +} + +# Fill the progress pane +ttk::progressbar $w.outer.inRight.top.progress -mode indeterminate +pack $w.outer.inRight.top.progress -fill both -expand 1 +$w.outer.inRight.top.progress start + +# Fill the text pane +if {[tk windowingsystem] ne "aqua"} { + # The trick with the ttk::frame makes the text widget look like it fits with + # the current Ttk theme despite not being a themed widget itself. It is done + # by styling the frame like an entry, turning off the border in the text + # widget, and putting the text widget in the frame with enough space to allow + # the surrounding border to show through (2 pixels seems to be enough). + ttk::frame $w.outer.inRight.bot.f -style TEntry + text $w.txt -wrap word -yscroll "$w.sb set" -width 30 -borderwidth 0 + pack $w.txt -fill both -expand 1 -in $w.outer.inRight.bot.f -pady 2 -padx 2 + ttk::scrollbar $w.sb -orient vertical -command "$w.txt yview" + pack $w.sb -side right -fill y -in $w.outer.inRight.bot + pack $w.outer.inRight.bot.f -fill both -expand 1 + pack $w.outer -fill both -expand 1 +} else { + text $w.txt -wrap word -yscroll "$w.sb set" -width 30 -borderwidth 0 + ttk::scrollbar $w.sb -orient vertical -command "$w.txt yview" + pack $w.sb -side right -fill y -in $w.outer.inRight.bot + pack $w.txt -fill both -expand 1 -in $w.outer.inRight.bot + pack $w.outer -fill both -expand 1 -padx 10 -pady {6 10} +} + diff --git a/shared/package-files/06/065a77e08b2cf3ba737881076f45f3fa301f3b3c694fe3629c6e8b8d73594979/METADATA b/shared/package-files/06/065a77e08b2cf3ba737881076f45f3fa301f3b3c694fe3629c6e8b8d73594979/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5ee9c18afa8b6ef49806d44a7fc794562087b3ab --- /dev/null +++ b/shared/package-files/06/065a77e08b2cf3ba737881076f45f3fa301f3b3c694fe3629c6e8b8d73594979/METADATA @@ -0,0 +1,119 @@ +Metadata-Version: 2.1 +Name: requests +Version: 2.31.0 +Summary: Python HTTP for Humans. +Home-page: https://requests.readthedocs.io +Author: Kenneth Reitz +Author-email: me@kennethreitz.org +License: Apache 2.0 +Project-URL: Documentation, https://requests.readthedocs.io +Project-URL: Source, https://github.com/psf/requests +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +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 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: charset-normalizer <4,>=2 +Requires-Dist: idna <4,>=2.5 +Requires-Dist: urllib3 <3,>=1.21.1 +Requires-Dist: certifi >=2017.4.17 +Provides-Extra: security +Provides-Extra: socks +Requires-Dist: PySocks !=1.5.7,>=1.5.6 ; extra == 'socks' +Provides-Extra: use_chardet_on_py3 +Requires-Dist: chardet <6,>=3.0.2 ; extra == 'use_chardet_on_py3' + +# Requests + +**Requests** is a simple, yet elegant, HTTP library. + +```python +>>> import requests +>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass')) +>>> r.status_code +200 +>>> r.headers['content-type'] +'application/json; charset=utf8' +>>> r.encoding +'utf-8' +>>> r.text +'{"authenticated": true, ...' +>>> r.json() +{'authenticated': True, ...} +``` + +Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your `PUT` & `POST` data — but nowadays, just use the `json` method! + +Requests is one of the most downloaded Python packages today, pulling in around `30M downloads / week`— according to GitHub, Requests is currently [depended upon](https://github.com/psf/requests/network/dependents?package_id=UGFja2FnZS01NzA4OTExNg%3D%3D) by `1,000,000+` repositories. You may certainly put your trust in this code. + +[![Downloads](https://pepy.tech/badge/requests/month)](https://pepy.tech/project/requests) +[![Supported Versions](https://img.shields.io/pypi/pyversions/requests.svg)](https://pypi.org/project/requests) +[![Contributors](https://img.shields.io/github/contributors/psf/requests.svg)](https://github.com/psf/requests/graphs/contributors) + +## Installing Requests and Supported Versions + +Requests is available on PyPI: + +```console +$ python -m pip install requests +``` + +Requests officially supports Python 3.7+. + +## Supported Features & Best–Practices + +Requests is ready for the demands of building robust and reliable HTTP–speaking applications, for the needs of today. + +- Keep-Alive & Connection Pooling +- International Domains and URLs +- Sessions with Cookie Persistence +- Browser-style TLS/SSL Verification +- Basic & Digest Authentication +- Familiar `dict`–like Cookies +- Automatic Content Decompression and Decoding +- Multi-part File Uploads +- SOCKS Proxy Support +- Connection Timeouts +- Streaming Downloads +- Automatic honoring of `.netrc` +- Chunked HTTP Requests + +## API Reference and User Guide available on [Read the Docs](https://requests.readthedocs.io) + +[![Read the Docs](https://raw.githubusercontent.com/psf/requests/main/ext/ss.png)](https://requests.readthedocs.io) + +## Cloning the repository + +When cloning the Requests repository, you may need to add the `-c +fetch.fsck.badTimezone=ignore` flag to avoid an error about a bad commit (see +[this issue](https://github.com/psf/requests/issues/2690) for more background): + +```shell +git clone -c fetch.fsck.badTimezone=ignore https://github.com/psf/requests.git +``` + +You can also apply this setting to your global Git config: + +```shell +git config --global fetch.fsck.badTimezone ignore +``` + +--- + +[![Kenneth Reitz](https://raw.githubusercontent.com/psf/requests/main/ext/kr.png)](https://kennethreitz.org) [![Python Software Foundation](https://raw.githubusercontent.com/psf/requests/main/ext/psf.png)](https://www.python.org/psf) diff --git a/shared/package-files/06/065c39bcfce917a75c4f2be1391b08c2c9ab2bf8c89311f78786172c4d1d5941/METADATA b/shared/package-files/06/065c39bcfce917a75c4f2be1391b08c2c9ab2bf8c89311f78786172c4d1d5941/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..de85e9e2fa8404b10ab116d3b7f17004233d538a --- /dev/null +++ b/shared/package-files/06/065c39bcfce917a75c4f2be1391b08c2c9ab2bf8c89311f78786172c4d1d5941/METADATA @@ -0,0 +1,55 @@ +Metadata-Version: 2.1 +Name: jsonschema +Version: 4.19.2 +Summary: An implementation of JSON Schema validation for Python +Project-URL: Documentation, https://python-jsonschema.readthedocs.io/ +Project-URL: Homepage, https://github.com/python-jsonschema/jsonschema +Project-URL: Issues, https://github.com/python-jsonschema/jsonschema/issues/ +Project-URL: Funding, https://github.com/sponsors/Julian +Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-jsonschema?utm_source=pypi-jsonschema&utm_medium=referral&utm_campaign=pypi-link +Project-URL: Changelog, https://github.com/python-jsonschema/jsonschema/blob/main/CHANGELOG.rst +Project-URL: Source, https://github.com/python-jsonschema/jsonschema +Author: Julian Berman +Author-email: Julian+jsonschema@GrayVines.com +License: MIT +License-File: COPYING +Keywords: data validation,json,jsonschema,validation +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +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 +Classifier: Topic :: File Formats :: JSON +Classifier: Topic :: File Formats :: JSON :: JSON Schema +Requires-Python: >=3.8 +Requires-Dist: attrs>=22.2.0 +Requires-Dist: importlib-resources>=1.4.0; python_version < '3.9' +Requires-Dist: jsonschema-specifications>=2023.03.6 +Requires-Dist: pkgutil-resolve-name>=1.3.10; python_version < '3.9' +Requires-Dist: referencing>=0.28.4 +Requires-Dist: rpds-py>=0.7.1 +Provides-Extra: format +Requires-Dist: fqdn; extra == 'format' +Requires-Dist: idna; extra == 'format' +Requires-Dist: isoduration; extra == 'format' +Requires-Dist: jsonpointer>1.13; extra == 'format' +Requires-Dist: rfc3339-validator; extra == 'format' +Requires-Dist: rfc3987; extra == 'format' +Requires-Dist: uri-template; extra == 'format' +Requires-Dist: webcolors>=1.11; extra == 'format' +Provides-Extra: format-nongpl +Requires-Dist: fqdn; extra == 'format-nongpl' +Requires-Dist: idna; extra == 'format-nongpl' +Requires-Dist: isoduration; extra == 'format-nongpl' +Requires-Dist: jsonpointer>1.13; extra == 'format-nongpl' +Requires-Dist: rfc3339-validator; extra == 'format-nongpl' +Requires-Dist: rfc3986-validator>0.1.0; extra == 'format-nongpl' +Requires-Dist: uri-template; extra == 'format-nongpl' +Requires-Dist: webcolors>=1.11; extra == 'format-nongpl' diff --git a/shared/package-files/06/065d481c6f109875b7d9e7686ef29f9440b857127e998896ebbe3961b4008abe/test_json_table_schema.py b/shared/package-files/06/065d481c6f109875b7d9e7686ef29f9440b857127e998896ebbe3961b4008abe/test_json_table_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..aac271b3f1f79f1a4bacf64b86e092d9fee6a773 --- /dev/null +++ b/shared/package-files/06/065d481c6f109875b7d9e7686ef29f9440b857127e998896ebbe3961b4008abe/test_json_table_schema.py @@ -0,0 +1,873 @@ +"""Tests for Table Schema integration.""" +from collections import OrderedDict +from io import StringIO +import json + +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + DatetimeTZDtype, + PeriodDtype, +) + +import pandas as pd +from pandas import DataFrame +import pandas._testing as tm + +from pandas.io.json._table_schema import ( + as_json_table_type, + build_table_schema, + convert_json_field_to_pandas_type, + convert_pandas_type_to_json_field, + set_default_names, +) + + +@pytest.fixture +def df_schema(): + return DataFrame( + { + "A": [1, 2, 3, 4], + "B": ["a", "b", "c", "c"], + "C": pd.date_range("2016-01-01", freq="d", periods=4), + "D": pd.timedelta_range("1h", periods=4, freq="min"), + }, + index=pd.Index(range(4), name="idx"), + ) + + +@pytest.fixture +def df_table(): + return DataFrame( + { + "A": [1, 2, 3, 4], + "B": ["a", "b", "c", "c"], + "C": pd.date_range("2016-01-01", freq="d", periods=4), + "D": pd.timedelta_range("1h", periods=4, freq="min"), + "E": pd.Series(pd.Categorical(["a", "b", "c", "c"])), + "F": pd.Series(pd.Categorical(["a", "b", "c", "c"], ordered=True)), + "G": [1.0, 2.0, 3, 4.0], + "H": pd.date_range("2016-01-01", freq="d", periods=4, tz="US/Central"), + }, + index=pd.Index(range(4), name="idx"), + ) + + +class TestBuildSchema: + def test_build_table_schema(self, df_schema, using_infer_string): + result = build_table_schema(df_schema, version=False) + expected = { + "fields": [ + {"name": "idx", "type": "integer"}, + {"name": "A", "type": "integer"}, + {"name": "B", "type": "string"}, + {"name": "C", "type": "datetime"}, + {"name": "D", "type": "duration"}, + ], + "primaryKey": ["idx"], + } + if using_infer_string: + expected["fields"][2] = {"name": "B", "type": "string", "extDtype": "str"} + assert result == expected + result = build_table_schema(df_schema) + assert "pandas_version" in result + + def test_series(self): + s = pd.Series([1, 2, 3], name="foo") + result = build_table_schema(s, version=False) + expected = { + "fields": [ + {"name": "index", "type": "integer"}, + {"name": "foo", "type": "integer"}, + ], + "primaryKey": ["index"], + } + assert result == expected + result = build_table_schema(s) + assert "pandas_version" in result + + def test_series_unnamed(self): + result = build_table_schema(pd.Series([1, 2, 3]), version=False) + expected = { + "fields": [ + {"name": "index", "type": "integer"}, + {"name": "values", "type": "integer"}, + ], + "primaryKey": ["index"], + } + assert result == expected + + def test_multiindex(self, df_schema, using_infer_string): + df = df_schema + idx = pd.MultiIndex.from_product([("a", "b"), (1, 2)]) + df.index = idx + + result = build_table_schema(df, version=False) + expected = { + "fields": [ + {"name": "level_0", "type": "string"}, + {"name": "level_1", "type": "integer"}, + {"name": "A", "type": "integer"}, + {"name": "B", "type": "string"}, + {"name": "C", "type": "datetime"}, + {"name": "D", "type": "duration"}, + ], + "primaryKey": ["level_0", "level_1"], + } + if using_infer_string: + expected["fields"][0] = { + "name": "level_0", + "type": "string", + "extDtype": "str", + } + expected["fields"][3] = {"name": "B", "type": "string", "extDtype": "str"} + assert result == expected + + df.index.names = ["idx0", None] + expected["fields"][0]["name"] = "idx0" + expected["primaryKey"] = ["idx0", "level_1"] + result = build_table_schema(df, version=False) + assert result == expected + + +class TestTableSchemaType: + @pytest.mark.parametrize("int_type", [int, np.int16, np.int32, np.int64]) + def test_as_json_table_type_int_data(self, int_type): + int_data = [1, 2, 3] + assert as_json_table_type(np.array(int_data, dtype=int_type).dtype) == "integer" + + @pytest.mark.parametrize("float_type", [float, np.float16, np.float32, np.float64]) + def test_as_json_table_type_float_data(self, float_type): + float_data = [1.0, 2.0, 3.0] + assert ( + as_json_table_type(np.array(float_data, dtype=float_type).dtype) == "number" + ) + + @pytest.mark.parametrize("bool_type", [bool, np.bool_]) + def test_as_json_table_type_bool_data(self, bool_type): + bool_data = [True, False] + assert ( + as_json_table_type(np.array(bool_data, dtype=bool_type).dtype) == "boolean" + ) + + @pytest.mark.parametrize( + "date_data", + [ + pd.to_datetime(["2016"]), + pd.to_datetime(["2016"], utc=True), + pd.Series(pd.to_datetime(["2016"])), + pd.Series(pd.to_datetime(["2016"], utc=True)), + pd.period_range("2016", freq="Y", periods=3), + ], + ) + def test_as_json_table_type_date_data(self, date_data): + assert as_json_table_type(date_data.dtype) == "datetime" + + @pytest.mark.parametrize( + "str_data", + [pd.Series(["a", "b"], dtype=object), pd.Index(["a", "b"], dtype=object)], + ) + def test_as_json_table_type_string_data(self, str_data): + assert as_json_table_type(str_data.dtype) == "string" + + @pytest.mark.parametrize( + "cat_data", + [ + pd.Categorical(["a"]), + pd.Categorical([1]), + pd.Series(pd.Categorical([1])), + pd.CategoricalIndex([1]), + pd.Categorical([1]), + ], + ) + def test_as_json_table_type_categorical_data(self, cat_data): + assert as_json_table_type(cat_data.dtype) == "any" + + # ------ + # dtypes + # ------ + @pytest.mark.parametrize("int_dtype", [int, np.int16, np.int32, np.int64]) + def test_as_json_table_type_int_dtypes(self, int_dtype): + assert as_json_table_type(int_dtype) == "integer" + + @pytest.mark.parametrize("float_dtype", [float, np.float16, np.float32, np.float64]) + def test_as_json_table_type_float_dtypes(self, float_dtype): + assert as_json_table_type(float_dtype) == "number" + + @pytest.mark.parametrize("bool_dtype", [bool, np.bool_]) + def test_as_json_table_type_bool_dtypes(self, bool_dtype): + assert as_json_table_type(bool_dtype) == "boolean" + + @pytest.mark.parametrize( + "date_dtype", + [ + np.dtype("3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", + 'f': r"(?P[0-9]{1,6})", + 'H': r"(?P2[0-3]|[0-1]\d|\d)", + 'I': r"(?P1[0-2]|0[1-9]|[1-9])", + 'G': r"(?P\d\d\d\d)", + 'j': r"(?P36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])", + 'm': r"(?P1[0-2]|0[1-9]|[1-9])", + 'M': r"(?P[0-5]\d|\d)", + 'S': r"(?P6[0-1]|[0-5]\d|\d)", + 'U': r"(?P5[0-3]|[0-4]\d|\d)", + 'w': r"(?P[0-6])", + 'u': r"(?P[1-7])", + 'V': r"(?P5[0-3]|0[1-9]|[1-4]\d|\d)", + # W is set below by using 'U' + 'y': r"(?P\d\d)", + #XXX: Does 'Y' need to worry about having less or more than + # 4 digits? + 'Y': r"(?P\d\d\d\d)", + 'z': r"(?P[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|(?-i:Z))", + 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'), + 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'), + 'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'), + 'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'), + 'p': self.__seqToRE(self.locale_time.am_pm, 'p'), + 'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone + for tz in tz_names), + 'Z'), + '%': '%'}) + base.__setitem__('W', base.__getitem__('U').replace('U', 'W')) + base.__setitem__('c', self.pattern(self.locale_time.LC_date_time)) + base.__setitem__('x', self.pattern(self.locale_time.LC_date)) + base.__setitem__('X', self.pattern(self.locale_time.LC_time)) + + def __seqToRE(self, to_convert, directive): + """Convert a list to a regex string for matching a directive. + + Want possible matching values to be from longest to shortest. This + prevents the possibility of a match occurring for a value that also + a substring of a larger value that should have matched (e.g., 'abc' + matching when 'abcdef' should have been the match). + + """ + to_convert = sorted(to_convert, key=len, reverse=True) + for value in to_convert: + if value != '': + break + else: + return '' + regex = '|'.join(re_escape(stuff) for stuff in to_convert) + regex = '(?P<%s>%s' % (directive, regex) + return '%s)' % regex + + def pattern(self, format): + """Return regex pattern for the format string. + + Need to make sure that any characters that might be interpreted as + regex syntax are escaped. + + """ + processed_format = '' + # The sub() call escapes all characters that might be misconstrued + # as regex syntax. Cannot use re.escape since we have to deal with + # format directives (%m, etc.). + regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])") + format = regex_chars.sub(r"\\\1", format) + whitespace_replacement = re_compile(r'\s+') + format = whitespace_replacement.sub(r'\\s+', format) + while '%' in format: + directive_index = format.index('%')+1 + processed_format = "%s%s%s" % (processed_format, + format[:directive_index-1], + self[format[directive_index]]) + format = format[directive_index+1:] + return "%s%s" % (processed_format, format) + + def compile(self, format): + """Return a compiled re object for the format string.""" + return re_compile(self.pattern(format), IGNORECASE) + +_cache_lock = _thread_allocate_lock() +# DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock +# first! +_TimeRE_cache = TimeRE() +_CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache +_regex_cache = {} + +def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon): + """Calculate the Julian day based on the year, week of the year, and day of + the week, with week_start_day representing whether the week of the year + assumes the week starts on Sunday or Monday (6 or 0).""" + first_weekday = datetime_date(year, 1, 1).weekday() + # If we are dealing with the %U directive (week starts on Sunday), it's + # easier to just shift the view to Sunday being the first day of the + # week. + if not week_starts_Mon: + first_weekday = (first_weekday + 1) % 7 + day_of_week = (day_of_week + 1) % 7 + # Need to watch out for a week 0 (when the first day of the year is not + # the same as that specified by %U or %W). + week_0_length = (7 - first_weekday) % 7 + if week_of_year == 0: + return 1 + day_of_week - first_weekday + else: + days_to_week = week_0_length + (7 * (week_of_year - 1)) + return 1 + days_to_week + day_of_week + + +def _calc_julian_from_V(iso_year, iso_week, iso_weekday): + """Calculate the Julian day based on the ISO 8601 year, week, and weekday. + ISO weeks start on Mondays, with week 01 being the week containing 4 Jan. + ISO week days range from 1 (Monday) to 7 (Sunday). + """ + correction = datetime_date(iso_year, 1, 4).isoweekday() + 3 + ordinal = (iso_week * 7) + iso_weekday - correction + # ordinal may be negative or 0 now, which means the date is in the previous + # calendar year + if ordinal < 1: + ordinal += datetime_date(iso_year, 1, 1).toordinal() + iso_year -= 1 + ordinal -= datetime_date(iso_year, 1, 1).toordinal() + return iso_year, ordinal + + +def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"): + """Return a 2-tuple consisting of a time struct and an int containing + the number of microseconds based on the input string and the + format string.""" + + for index, arg in enumerate([data_string, format]): + if not isinstance(arg, str): + msg = "strptime() argument {} must be str, not {}" + raise TypeError(msg.format(index, type(arg))) + + global _TimeRE_cache, _regex_cache + with _cache_lock: + locale_time = _TimeRE_cache.locale_time + if (_getlang() != locale_time.lang or + time.tzname != locale_time.tzname or + time.daylight != locale_time.daylight): + _TimeRE_cache = TimeRE() + _regex_cache.clear() + locale_time = _TimeRE_cache.locale_time + if len(_regex_cache) > _CACHE_MAX_SIZE: + _regex_cache.clear() + format_regex = _regex_cache.get(format) + if not format_regex: + try: + format_regex = _TimeRE_cache.compile(format) + # KeyError raised when a bad format is found; can be specified as + # \\, in which case it was a stray % but with a space after it + except KeyError as err: + bad_directive = err.args[0] + if bad_directive == "\\": + bad_directive = "%" + del err + raise ValueError("'%s' is a bad directive in format '%s'" % + (bad_directive, format)) from None + # IndexError only occurs when the format string is "%" + except IndexError: + raise ValueError("stray %% in format '%s'" % format) from None + _regex_cache[format] = format_regex + found = format_regex.match(data_string) + if not found: + raise ValueError("time data %r does not match format %r" % + (data_string, format)) + if len(data_string) != found.end(): + raise ValueError("unconverted data remains: %s" % + data_string[found.end():]) + + iso_year = year = None + month = day = 1 + hour = minute = second = fraction = 0 + tz = -1 + gmtoff = None + gmtoff_fraction = 0 + # Default to -1 to signify that values not known; not critical to have, + # though + iso_week = week_of_year = None + week_of_year_start = None + # weekday and julian defaulted to None so as to signal need to calculate + # values + weekday = julian = None + found_dict = found.groupdict() + for group_key in found_dict.keys(): + # Directives not explicitly handled below: + # c, x, X + # handled by making out of other directives + # U, W + # worthless without day of the week + if group_key == 'y': + year = int(found_dict['y']) + # Open Group specification for strptime() states that a %y + #value in the range of [00, 68] is in the century 2000, while + #[69,99] is in the century 1900 + if year <= 68: + year += 2000 + else: + year += 1900 + elif group_key == 'Y': + year = int(found_dict['Y']) + elif group_key == 'G': + iso_year = int(found_dict['G']) + elif group_key == 'm': + month = int(found_dict['m']) + elif group_key == 'B': + month = locale_time.f_month.index(found_dict['B'].lower()) + elif group_key == 'b': + month = locale_time.a_month.index(found_dict['b'].lower()) + elif group_key == 'd': + day = int(found_dict['d']) + elif group_key == 'H': + hour = int(found_dict['H']) + elif group_key == 'I': + hour = int(found_dict['I']) + ampm = found_dict.get('p', '').lower() + # If there was no AM/PM indicator, we'll treat this like AM + if ampm in ('', locale_time.am_pm[0]): + # We're in AM so the hour is correct unless we're + # looking at 12 midnight. + # 12 midnight == 12 AM == hour 0 + if hour == 12: + hour = 0 + elif ampm == locale_time.am_pm[1]: + # We're in PM so we need to add 12 to the hour unless + # we're looking at 12 noon. + # 12 noon == 12 PM == hour 12 + if hour != 12: + hour += 12 + elif group_key == 'M': + minute = int(found_dict['M']) + elif group_key == 'S': + second = int(found_dict['S']) + elif group_key == 'f': + s = found_dict['f'] + # Pad to always return microseconds. + s += "0" * (6 - len(s)) + fraction = int(s) + elif group_key == 'A': + weekday = locale_time.f_weekday.index(found_dict['A'].lower()) + elif group_key == 'a': + weekday = locale_time.a_weekday.index(found_dict['a'].lower()) + elif group_key == 'w': + weekday = int(found_dict['w']) + if weekday == 0: + weekday = 6 + else: + weekday -= 1 + elif group_key == 'u': + weekday = int(found_dict['u']) + weekday -= 1 + elif group_key == 'j': + julian = int(found_dict['j']) + elif group_key in ('U', 'W'): + week_of_year = int(found_dict[group_key]) + if group_key == 'U': + # U starts week on Sunday. + week_of_year_start = 6 + else: + # W starts week on Monday. + week_of_year_start = 0 + elif group_key == 'V': + iso_week = int(found_dict['V']) + elif group_key == 'z': + z = found_dict['z'] + if z == 'Z': + gmtoff = 0 + else: + if z[3] == ':': + z = z[:3] + z[4:] + if len(z) > 5: + if z[5] != ':': + msg = f"Inconsistent use of : in {found_dict['z']}" + raise ValueError(msg) + z = z[:5] + z[6:] + hours = int(z[1:3]) + minutes = int(z[3:5]) + seconds = int(z[5:7] or 0) + gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds + gmtoff_remainder = z[8:] + # Pad to always return microseconds. + gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder)) + gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding) + if z.startswith("-"): + gmtoff = -gmtoff + gmtoff_fraction = -gmtoff_fraction + elif group_key == 'Z': + # Since -1 is default value only need to worry about setting tz if + # it can be something other than -1. + found_zone = found_dict['Z'].lower() + for value, tz_values in enumerate(locale_time.timezone): + if found_zone in tz_values: + # Deal with bad locale setup where timezone names are the + # same and yet time.daylight is true; too ambiguous to + # be able to tell what timezone has daylight savings + if (time.tzname[0] == time.tzname[1] and + time.daylight and found_zone not in ("utc", "gmt")): + break + else: + tz = value + break + # Deal with the cases where ambiguities arize + # don't assume default values for ISO week/year + if year is None and iso_year is not None: + if iso_week is None or weekday is None: + raise ValueError("ISO year directive '%G' must be used with " + "the ISO week directive '%V' and a weekday " + "directive ('%A', '%a', '%w', or '%u').") + if julian is not None: + raise ValueError("Day of the year directive '%j' is not " + "compatible with ISO year directive '%G'. " + "Use '%Y' instead.") + elif week_of_year is None and iso_week is not None: + if weekday is None: + raise ValueError("ISO week directive '%V' must be used with " + "the ISO year directive '%G' and a weekday " + "directive ('%A', '%a', '%w', or '%u').") + else: + raise ValueError("ISO week directive '%V' is incompatible with " + "the year directive '%Y'. Use the ISO year '%G' " + "instead.") + + leap_year_fix = False + if year is None and month == 2 and day == 29: + year = 1904 # 1904 is first leap year of 20th century + leap_year_fix = True + elif year is None: + year = 1900 + + + # If we know the week of the year and what day of that week, we can figure + # out the Julian day of the year. + if julian is None and weekday is not None: + if week_of_year is not None: + week_starts_Mon = True if week_of_year_start == 0 else False + julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, + week_starts_Mon) + elif iso_year is not None and iso_week is not None: + year, julian = _calc_julian_from_V(iso_year, iso_week, weekday + 1) + if julian is not None and julian <= 0: + year -= 1 + yday = 366 if calendar.isleap(year) else 365 + julian += yday + + if julian is None: + # Cannot pre-calculate datetime_date() since can change in Julian + # calculation and thus could have different value for the day of + # the week calculation. + # Need to add 1 to result since first day of the year is 1, not 0. + julian = datetime_date(year, month, day).toordinal() - \ + datetime_date(year, 1, 1).toordinal() + 1 + else: # Assume that if they bothered to include Julian day (or if it was + # calculated above with year/week/weekday) it will be accurate. + datetime_result = datetime_date.fromordinal( + (julian - 1) + + datetime_date(year, 1, 1).toordinal()) + year = datetime_result.year + month = datetime_result.month + day = datetime_result.day + if weekday is None: + weekday = datetime_date(year, month, day).weekday() + # Add timezone info + tzname = found_dict.get("Z") + + if leap_year_fix: + # the caller didn't supply a year but asked for Feb 29th. We couldn't + # use the default of 1900 for computations. We set it back to ensure + # that February 29th is smaller than March 1st. + year = 1900 + + return (year, month, day, + hour, minute, second, + weekday, julian, tz, tzname, gmtoff), fraction, gmtoff_fraction + +def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"): + """Return a time struct based on the input string and the + format string.""" + tt = _strptime(data_string, format)[0] + return time.struct_time(tt[:time._STRUCT_TM_ITEMS]) + +def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"): + """Return a class cls instance based on the input string and the + format string.""" + tt, fraction, gmtoff_fraction = _strptime(data_string, format) + tzname, gmtoff = tt[-2:] + args = tt[:6] + (fraction,) + if gmtoff is not None: + tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction) + if tzname: + tz = datetime_timezone(tzdelta, tzname) + else: + tz = datetime_timezone(tzdelta) + args += (tz,) + + return cls(*args) diff --git a/shared/package-files/06/06619670ff86b58913d1659471b92ef6f1c259f095e95f299e2ba52ac6f2aef5/__init__.py b/shared/package-files/06/06619670ff86b58913d1659471b92ef6f1c259f095e95f299e2ba52ac6f2aef5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c471c35096f8ab59d042ea4c0758d88d8819282 --- /dev/null +++ b/shared/package-files/06/06619670ff86b58913d1659471b92ef6f1c259f095e95f299e2ba52ac6f2aef5/__init__.py @@ -0,0 +1,16 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from .glm import ( + GammaRegressor, + PoissonRegressor, + TweedieRegressor, + _GeneralizedLinearRegressor, +) + +__all__ = [ + "GammaRegressor", + "PoissonRegressor", + "TweedieRegressor", + "_GeneralizedLinearRegressor", +] diff --git a/shared/package-files/06/0663c5c7805e9b2f331ecb92aae1ad8b59913f2ff047be8a2a77c8f62c4716d2/_prelu_kernel_backward_cpu_dispatch.h b/shared/package-files/06/0663c5c7805e9b2f331ecb92aae1ad8b59913f2ff047be8a2a77c8f62c4716d2/_prelu_kernel_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f07826d1595e93b983ffe2ff77d6a0dac3345870 --- /dev/null +++ b/shared/package-files/06/0663c5c7805e9b2f331ecb92aae1ad8b59913f2ff047be8a2a77c8f62c4716d2/_prelu_kernel_backward_cpu_dispatch.h @@ -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 ::std::tuple _prelu_kernel_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/06/0669132a68939389b6723fa2b9e9626adc33deeb7ff52b000415b9d6f9d09d95/scripts.py b/shared/package-files/06/0669132a68939389b6723fa2b9e9626adc33deeb7ff52b000415b9d6f9d09d95/scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..d2706242b8aac125a66450d5ce8dcd3395336182 --- /dev/null +++ b/shared/package-files/06/0669132a68939389b6723fa2b9e9626adc33deeb7ff52b000415b9d6f9d09d95/scripts.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2013-2015 Vinay Sajip. +# Licensed to the Python Software Foundation under a contributor agreement. +# See LICENSE.txt and CONTRIBUTORS.txt. +# +from io import BytesIO +import logging +import os +import re +import struct +import sys +import time +from zipfile import ZipInfo + +from .compat import sysconfig, detect_encoding, ZipFile +from .resources import finder +from .util import (FileOperator, get_export_entry, convert_path, + get_executable, get_platform, in_venv) + +logger = logging.getLogger(__name__) + +_DEFAULT_MANIFEST = ''' + + + + + + + + + + + + +'''.strip() + +# check if Python is called on the first line with this expression +FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$') +SCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*- +import re +import sys +from %(module)s import %(import_name)s +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(%(func)s()) +''' + + +def enquote_executable(executable): + if ' ' in executable: + # make sure we quote only the executable in case of env + # for example /usr/bin/env "/dir with spaces/bin/jython" + # instead of "/usr/bin/env /dir with spaces/bin/jython" + # otherwise whole + if executable.startswith('/usr/bin/env '): + env, _executable = executable.split(' ', 1) + if ' ' in _executable and not _executable.startswith('"'): + executable = '%s "%s"' % (env, _executable) + else: + if not executable.startswith('"'): + executable = '"%s"' % executable + return executable + +# Keep the old name around (for now), as there is at least one project using it! +_enquote_executable = enquote_executable + +class ScriptMaker(object): + """ + A class to copy or create scripts from source scripts or callable + specifications. + """ + script_template = SCRIPT_TEMPLATE + + executable = None # for shebangs + + def __init__(self, source_dir, target_dir, add_launchers=True, + dry_run=False, fileop=None): + self.source_dir = source_dir + self.target_dir = target_dir + self.add_launchers = add_launchers + self.force = False + self.clobber = False + # It only makes sense to set mode bits on POSIX. + self.set_mode = (os.name == 'posix') or (os.name == 'java' and + os._name == 'posix') + self.variants = set(('', 'X.Y')) + self._fileop = fileop or FileOperator(dry_run) + + self._is_nt = os.name == 'nt' or ( + os.name == 'java' and os._name == 'nt') + self.version_info = sys.version_info + + def _get_alternate_executable(self, executable, options): + if options.get('gui', False) and self._is_nt: # pragma: no cover + dn, fn = os.path.split(executable) + fn = fn.replace('python', 'pythonw') + executable = os.path.join(dn, fn) + return executable + + if sys.platform.startswith('java'): # pragma: no cover + def _is_shell(self, executable): + """ + Determine if the specified executable is a script + (contains a #! line) + """ + try: + with open(executable) as fp: + return fp.read(2) == '#!' + except (OSError, IOError): + logger.warning('Failed to open %s', executable) + return False + + def _fix_jython_executable(self, executable): + if self._is_shell(executable): + # Workaround for Jython is not needed on Linux systems. + import java + + if java.lang.System.getProperty('os.name') == 'Linux': + return executable + elif executable.lower().endswith('jython.exe'): + # Use wrapper exe for Jython on Windows + return executable + return '/usr/bin/env %s' % executable + + def _build_shebang(self, executable, post_interp): + """ + Build a shebang line. In the simple case (on Windows, or a shebang line + which is not too long or contains spaces) use a simple formulation for + the shebang. Otherwise, use /bin/sh as the executable, with a contrived + shebang which allows the script to run either under Python or sh, using + suitable quoting. Thanks to Harald Nordgren for his input. + + See also: http://www.in-ulm.de/~mascheck/various/shebang/#length + https://hg.mozilla.org/mozilla-central/file/tip/mach + """ + if os.name != 'posix': + simple_shebang = True + else: + # Add 3 for '#!' prefix and newline suffix. + shebang_length = len(executable) + len(post_interp) + 3 + if sys.platform == 'darwin': + max_shebang_length = 512 + else: + max_shebang_length = 127 + simple_shebang = ((b' ' not in executable) and + (shebang_length <= max_shebang_length)) + + if simple_shebang: + result = b'#!' + executable + post_interp + b'\n' + else: + result = b'#!/bin/sh\n' + result += b"'''exec' " + executable + post_interp + b' "$0" "$@"\n' + result += b"' '''" + return result + + def _get_shebang(self, encoding, post_interp=b'', options=None): + enquote = True + if self.executable: + executable = self.executable + enquote = False # assume this will be taken care of + elif not sysconfig.is_python_build(): + executable = get_executable() + elif in_venv(): # pragma: no cover + executable = os.path.join(sysconfig.get_path('scripts'), + 'python%s' % sysconfig.get_config_var('EXE')) + else: # pragma: no cover + executable = os.path.join( + sysconfig.get_config_var('BINDIR'), + 'python%s%s' % (sysconfig.get_config_var('VERSION'), + sysconfig.get_config_var('EXE'))) + if not os.path.isfile(executable): + # for Python builds from source on Windows, no Python executables with + # a version suffix are created, so we use python.exe + executable = os.path.join(sysconfig.get_config_var('BINDIR'), + 'python%s' % (sysconfig.get_config_var('EXE'))) + if options: + executable = self._get_alternate_executable(executable, options) + + if sys.platform.startswith('java'): # pragma: no cover + executable = self._fix_jython_executable(executable) + + # Normalise case for Windows - COMMENTED OUT + # executable = os.path.normcase(executable) + # N.B. The normalising operation above has been commented out: See + # issue #124. Although paths in Windows are generally case-insensitive, + # they aren't always. For example, a path containing a ẞ (which is a + # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a + # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by + # Windows as equivalent in path names. + + # If the user didn't specify an executable, it may be necessary to + # cater for executable paths with spaces (not uncommon on Windows) + if enquote: + executable = enquote_executable(executable) + # Issue #51: don't use fsencode, since we later try to + # check that the shebang is decodable using utf-8. + executable = executable.encode('utf-8') + # in case of IronPython, play safe and enable frames support + if (sys.platform == 'cli' and '-X:Frames' not in post_interp + and '-X:FullFrames' not in post_interp): # pragma: no cover + post_interp += b' -X:Frames' + shebang = self._build_shebang(executable, post_interp) + # Python parser starts to read a script using UTF-8 until + # it gets a #coding:xxx cookie. The shebang has to be the + # first line of a file, the #coding:xxx cookie cannot be + # written before. So the shebang has to be decodable from + # UTF-8. + try: + shebang.decode('utf-8') + except UnicodeDecodeError: # pragma: no cover + raise ValueError( + 'The shebang (%r) is not decodable from utf-8' % shebang) + # If the script is encoded to a custom encoding (use a + # #coding:xxx cookie), the shebang has to be decodable from + # the script encoding too. + if encoding != 'utf-8': + try: + shebang.decode(encoding) + except UnicodeDecodeError: # pragma: no cover + raise ValueError( + 'The shebang (%r) is not decodable ' + 'from the script encoding (%r)' % (shebang, encoding)) + return shebang + + def _get_script_text(self, entry): + return self.script_template % dict(module=entry.prefix, + import_name=entry.suffix.split('.')[0], + func=entry.suffix) + + manifest = _DEFAULT_MANIFEST + + def get_manifest(self, exename): + base = os.path.basename(exename) + return self.manifest % base + + def _write_script(self, names, shebang, script_bytes, filenames, ext): + use_launcher = self.add_launchers and self._is_nt + linesep = os.linesep.encode('utf-8') + if not shebang.endswith(linesep): + shebang += linesep + if not use_launcher: + script_bytes = shebang + script_bytes + else: # pragma: no cover + if ext == 'py': + launcher = self._get_launcher('t') + else: + launcher = self._get_launcher('w') + stream = BytesIO() + with ZipFile(stream, 'w') as zf: + source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH') + if source_date_epoch: + date_time = time.gmtime(int(source_date_epoch))[:6] + zinfo = ZipInfo(filename='__main__.py', date_time=date_time) + zf.writestr(zinfo, script_bytes) + else: + zf.writestr('__main__.py', script_bytes) + zip_data = stream.getvalue() + script_bytes = launcher + shebang + zip_data + for name in names: + outname = os.path.join(self.target_dir, name) + if use_launcher: # pragma: no cover + n, e = os.path.splitext(outname) + if e.startswith('.py'): + outname = n + outname = '%s.exe' % outname + try: + self._fileop.write_binary_file(outname, script_bytes) + except Exception: + # Failed writing an executable - it might be in use. + logger.warning('Failed to write executable - trying to ' + 'use .deleteme logic') + dfname = '%s.deleteme' % outname + if os.path.exists(dfname): + os.remove(dfname) # Not allowed to fail here + os.rename(outname, dfname) # nor here + self._fileop.write_binary_file(outname, script_bytes) + logger.debug('Able to replace executable using ' + '.deleteme logic') + try: + os.remove(dfname) + except Exception: + pass # still in use - ignore error + else: + if self._is_nt and not outname.endswith('.' + ext): # pragma: no cover + outname = '%s.%s' % (outname, ext) + if os.path.exists(outname) and not self.clobber: + logger.warning('Skipping existing file %s', outname) + continue + self._fileop.write_binary_file(outname, script_bytes) + if self.set_mode: + self._fileop.set_executable_mode([outname]) + filenames.append(outname) + + variant_separator = '-' + + def get_script_filenames(self, name): + result = set() + if '' in self.variants: + result.add(name) + if 'X' in self.variants: + result.add('%s%s' % (name, self.version_info[0])) + if 'X.Y' in self.variants: + result.add('%s%s%s.%s' % (name, self.variant_separator, + self.version_info[0], self.version_info[1])) + return result + + def _make_script(self, entry, filenames, options=None): + post_interp = b'' + if options: + args = options.get('interpreter_args', []) + if args: + args = ' %s' % ' '.join(args) + post_interp = args.encode('utf-8') + shebang = self._get_shebang('utf-8', post_interp, options=options) + script = self._get_script_text(entry).encode('utf-8') + scriptnames = self.get_script_filenames(entry.name) + if options and options.get('gui', False): + ext = 'pyw' + else: + ext = 'py' + self._write_script(scriptnames, shebang, script, filenames, ext) + + def _copy_script(self, script, filenames): + adjust = False + script = os.path.join(self.source_dir, convert_path(script)) + outname = os.path.join(self.target_dir, os.path.basename(script)) + if not self.force and not self._fileop.newer(script, outname): + logger.debug('not copying %s (up-to-date)', script) + return + + # Always open the file, but ignore failures in dry-run mode -- + # that way, we'll get accurate feedback if we can read the + # script. + try: + f = open(script, 'rb') + except IOError: # pragma: no cover + if not self.dry_run: + raise + f = None + else: + first_line = f.readline() + if not first_line: # pragma: no cover + logger.warning('%s is an empty file (skipping)', script) + return + + match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n')) + if match: + adjust = True + post_interp = match.group(1) or b'' + + if not adjust: + if f: + f.close() + self._fileop.copy_file(script, outname) + if self.set_mode: + self._fileop.set_executable_mode([outname]) + filenames.append(outname) + else: + logger.info('copying and adjusting %s -> %s', script, + self.target_dir) + if not self._fileop.dry_run: + encoding, lines = detect_encoding(f.readline) + f.seek(0) + shebang = self._get_shebang(encoding, post_interp) + if b'pythonw' in first_line: # pragma: no cover + ext = 'pyw' + else: + ext = 'py' + n = os.path.basename(outname) + self._write_script([n], shebang, f.read(), filenames, ext) + if f: + f.close() + + @property + def dry_run(self): + return self._fileop.dry_run + + @dry_run.setter + def dry_run(self, value): + self._fileop.dry_run = value + + if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'): # pragma: no cover + # Executable launcher support. + # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/ + + def _get_launcher(self, kind): + if struct.calcsize('P') == 8: # 64-bit + bits = '64' + else: + bits = '32' + platform_suffix = '-arm' if get_platform() == 'win-arm64' else '' + name = '%s%s%s.exe' % (kind, bits, platform_suffix) + # Issue 31: don't hardcode an absolute package name, but + # determine it relative to the current package + distlib_package = __name__.rsplit('.', 1)[0] + resource = finder(distlib_package).find(name) + if not resource: + msg = ('Unable to find resource %s in package %s' % (name, + distlib_package)) + raise ValueError(msg) + return resource.bytes + + # Public API follows + + def make(self, specification, options=None): + """ + Make a script. + + :param specification: The specification, which is either a valid export + entry specification (to make a script from a + callable) or a filename (to make a script by + copying from a source location). + :param options: A dictionary of options controlling script generation. + :return: A list of all absolute pathnames written to. + """ + filenames = [] + entry = get_export_entry(specification) + if entry is None: + self._copy_script(specification, filenames) + else: + self._make_script(entry, filenames, options=options) + return filenames + + def make_multiple(self, specifications, options=None): + """ + Take a list of specifications and make scripts from them, + :param specifications: A list of specifications. + :return: A list of all absolute pathnames written to, + """ + filenames = [] + for specification in specifications: + filenames.extend(self.make(specification, options)) + return filenames diff --git a/shared/package-files/06/0669a58a817af3261c88ad611491ae32a55c708efbb5c3b694e2edb845859729/bitwise_and_ops.h b/shared/package-files/06/0669a58a817af3261c88ad611491ae32a55c708efbb5c3b694e2edb845859729/bitwise_and_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..af66882c390b5aed1ad14bff4b0cce3692b18de0 --- /dev/null +++ b/shared/package-files/06/0669a58a817af3261c88ad611491ae32a55c708efbb5c3b694e2edb845859729/bitwise_and_ops.h @@ -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_and_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_and") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.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_and_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_and") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.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_and_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_and") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.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_and_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_and") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.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_and_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_and") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.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_and__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_and_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and_.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_and__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_and_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and_.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_and_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_and") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.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/06/0669c432544417b1b4079cdd68946c773a8845d87c7628938ac05b09523a169d/common.py b/shared/package-files/06/0669c432544417b1b4079cdd68946c773a8845d87c7628938ac05b09523a169d/common.py new file mode 100644 index 0000000000000000000000000000000000000000..fc41d7907a240f0dd9dc19e0ae1296bee86be421 --- /dev/null +++ b/shared/package-files/06/0669c432544417b1b4079cdd68946c773a8845d87c7628938ac05b09523a169d/common.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pandas import ( + DataFrame, + concat, +) + +if TYPE_CHECKING: + from pandas._typing import AxisInt + + +def _check_mixed_float(df, dtype=None): + # float16 are most likely to be upcasted to float32 + dtypes = {"A": "float32", "B": "float32", "C": "float16", "D": "float64"} + if isinstance(dtype, str): + dtypes = {k: dtype for k, v in dtypes.items()} + elif isinstance(dtype, dict): + dtypes.update(dtype) + if dtypes.get("A"): + assert df.dtypes["A"] == dtypes["A"] + if dtypes.get("B"): + assert df.dtypes["B"] == dtypes["B"] + if dtypes.get("C"): + assert df.dtypes["C"] == dtypes["C"] + if dtypes.get("D"): + assert df.dtypes["D"] == dtypes["D"] + + +def _check_mixed_int(df, dtype=None): + dtypes = {"A": "int32", "B": "uint64", "C": "uint8", "D": "int64"} + if isinstance(dtype, str): + dtypes = {k: dtype for k, v in dtypes.items()} + elif isinstance(dtype, dict): + dtypes.update(dtype) + if dtypes.get("A"): + assert df.dtypes["A"] == dtypes["A"] + if dtypes.get("B"): + assert df.dtypes["B"] == dtypes["B"] + if dtypes.get("C"): + assert df.dtypes["C"] == dtypes["C"] + if dtypes.get("D"): + assert df.dtypes["D"] == dtypes["D"] + + +def zip_frames(frames: list[DataFrame], axis: AxisInt = 1) -> DataFrame: + """ + take a list of frames, zip them together under the + assumption that these all have the first frames' index/columns. + + Returns + ------- + new_frame : DataFrame + """ + if axis == 1: + columns = frames[0].columns + zipped = [f.loc[:, c] for c in columns for f in frames] + return concat(zipped, axis=1) + else: + index = frames[0].index + zipped = [f.loc[i, :] for i in index for f in frames] + return DataFrame(zipped) diff --git a/shared/package-files/06/066a541e6d38ead952d63cc32afbac51a33acf354799f235c582eab17488105d/tty.py b/shared/package-files/06/066a541e6d38ead952d63cc32afbac51a33acf354799f235c582eab17488105d/tty.py new file mode 100644 index 0000000000000000000000000000000000000000..a72eb6755450bb07d9bb77fb9cdc3cf2f0148534 --- /dev/null +++ b/shared/package-files/06/066a541e6d38ead952d63cc32afbac51a33acf354799f235c582eab17488105d/tty.py @@ -0,0 +1,36 @@ +"""Terminal utilities.""" + +# Author: Steen Lumholt. + +from termios import * + +__all__ = ["setraw", "setcbreak"] + +# Indexes for termios list. +IFLAG = 0 +OFLAG = 1 +CFLAG = 2 +LFLAG = 3 +ISPEED = 4 +OSPEED = 5 +CC = 6 + +def setraw(fd, when=TCSAFLUSH): + """Put terminal into a raw mode.""" + mode = tcgetattr(fd) + mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON) + mode[OFLAG] = mode[OFLAG] & ~(OPOST) + mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB) + mode[CFLAG] = mode[CFLAG] | CS8 + mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG) + mode[CC][VMIN] = 1 + mode[CC][VTIME] = 0 + tcsetattr(fd, when, mode) + +def setcbreak(fd, when=TCSAFLUSH): + """Put terminal into a cbreak mode.""" + mode = tcgetattr(fd) + mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON) + mode[CC][VMIN] = 1 + mode[CC][VTIME] = 0 + tcsetattr(fd, when, mode) diff --git a/shared/package-files/06/066ec787f6844f1e8c4cddd6bbb4a28f2e2b60647fd6168d1ac8b7c5fceb00a3/test_digamma.py b/shared/package-files/06/066ec787f6844f1e8c4cddd6bbb4a28f2e2b60647fd6168d1ac8b7c5fceb00a3/test_digamma.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f27dc7b71c1ae928b4bdd8bd987df9ca420bab --- /dev/null +++ b/shared/package-files/06/066ec787f6844f1e8c4cddd6bbb4a28f2e2b60647fd6168d1ac8b7c5fceb00a3/test_digamma.py @@ -0,0 +1,45 @@ +import numpy as np +from numpy import pi, log, sqrt +from numpy.testing import assert_, assert_equal + +from scipy.special._testutils import FuncData +import scipy.special as sc + +# Euler-Mascheroni constant +euler = 0.57721566490153286 + + +def test_consistency(): + # Make sure the implementation of digamma for real arguments + # agrees with the implementation of digamma for complex arguments. + + # It's all poles after -1e16 + x = np.r_[-np.logspace(15, -30, 200), np.logspace(-30, 300, 200)] + dataset = np.vstack((x + 0j, sc.digamma(x))).T + FuncData(sc.digamma, dataset, 0, 1, rtol=5e-14, nan_ok=True).check() + + +def test_special_values(): + # Test special values from Gauss's digamma theorem. See + # + # https://en.wikipedia.org/wiki/Digamma_function + + dataset = [ + (1, -euler), + (0.5, -2*log(2) - euler), + (1/3, -pi/(2*sqrt(3)) - 3*log(3)/2 - euler), + (1/4, -pi/2 - 3*log(2) - euler), + (1/6, -pi*sqrt(3)/2 - 2*log(2) - 3*log(3)/2 - euler), + (1/8, + -pi/2 - 4*log(2) - (pi + log(2 + sqrt(2)) - log(2 - sqrt(2)))/sqrt(2) - euler) + ] + + dataset = np.asarray(dataset) + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check() + + +def test_nonfinite(): + pts = [0.0, -0.0, np.inf] + std = [-np.inf, np.inf, np.inf] + assert_equal(sc.digamma(pts), std) + assert_(all(np.isnan(sc.digamma([-np.inf, -1])))) diff --git a/shared/package-files/06/0670145a35bbb055059594c037004fc42d9a35eeef98e1324eceaa53915fba22/__init__.py b/shared/package-files/06/0670145a35bbb055059594c037004fc42d9a35eeef98e1324eceaa53915fba22/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6195cd3478fe981977cba4d5e2facfd26c5c3d91 --- /dev/null +++ b/shared/package-files/06/0670145a35bbb055059594c037004fc42d9a35eeef98e1324eceaa53915fba22/__init__.py @@ -0,0 +1,130 @@ +""" +Wrapt is a library for decorators, wrappers and monkey patching. +""" + + +def _format_version(parts): + base = ".".join(parts[:3]) + if len(parts) == 3: + return base + suffix = parts[3] + return ( + f"{base}.{suffix}" if suffix.startswith(("dev", "post")) else f"{base}{suffix}" + ) + + +__version_info__ = ("2", "5", "1") +__version__ = _format_version(__version_info__) + +from .__wrapt__ import ( + BaseObjectProxy, + BoundFunctionWrapper, + CallableObjectProxy, + FunctionWrapper, + PartialCallableObjectProxy, + partial, +) +from .caching import lru_cache +from .decorators import ( + AdapterFactory, + adapter_factory, + bind_state_to_wrapper, + decorator, +) +from .doc import with_doc +from .exceptions import ( + PathResolutionError, + TargetModuleNotFoundError, + WrapperChainTooDeepError, + WrapperNotFoundError, + WrapperNotInitializedError, + WrapperNotOutermostError, +) +from .importer import ( + discover_post_import_hooks, + notify_module_loaded, + register_post_import_hook, + when_imported, +) +from .patches import ( + MISSING, + AttributeWrapper, + apply_patch, + find_wrapper, + function_wrapper, + is_wrapped_by, + patch_function_wrapper, + resolve_owner, + resolve_path, + scoped_function_wrapper, + transient_function_wrapper, + unwrap_object, + unwrapped, + wrap_function_wrapper, + wrap_object, + wrap_object_attribute, + wrapper_chain, +) +from .proxies import AutoObjectProxy, LazyObjectProxy, ObjectProxy, lazy_import +from .signature import with_signature +from .synchronization import ( + async_to_sync, + mark_as_async, + mark_as_sync, + sync_to_async, + synchronized, +) +from .weakrefs import WeakFunctionProxy + +__all__ = ( + "AutoObjectProxy", + "BaseObjectProxy", + "BoundFunctionWrapper", + "CallableObjectProxy", + "FunctionWrapper", + "LazyObjectProxy", + "ObjectProxy", + "PartialCallableObjectProxy", + "PathResolutionError", + "TargetModuleNotFoundError", + "WrapperChainTooDeepError", + "WrapperNotFoundError", + "WrapperNotInitializedError", + "WrapperNotOutermostError", + "partial", + "AdapterFactory", + "adapter_factory", + "bind_state_to_wrapper", + "async_to_sync", + "decorator", + "lru_cache", + "mark_as_async", + "mark_as_sync", + "sync_to_async", + "synchronized", + "with_doc", + "with_signature", + "discover_post_import_hooks", + "notify_module_loaded", + "register_post_import_hook", + "when_imported", + "MISSING", + "AttributeWrapper", + "apply_patch", + "find_wrapper", + "function_wrapper", + "is_wrapped_by", + "lazy_import", + "patch_function_wrapper", + "resolve_owner", + "resolve_path", + "scoped_function_wrapper", + "transient_function_wrapper", + "unwrap_object", + "unwrapped", + "wrap_function_wrapper", + "wrap_object", + "wrap_object_attribute", + "wrapper_chain", + "WeakFunctionProxy", +) diff --git a/shared/package-files/06/06705a8a4257644a5ad1df45722647238d0f0c97b88355af9f934bda6ca815fc/graphmatrix.py b/shared/package-files/06/06705a8a4257644a5ad1df45722647238d0f0c97b88355af9f934bda6ca815fc/graphmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..24354e5f39bab9f39cef11a63ea72528e3d20b55 --- /dev/null +++ b/shared/package-files/06/06705a8a4257644a5ad1df45722647238d0f0c97b88355af9f934bda6ca815fc/graphmatrix.py @@ -0,0 +1,157 @@ +""" +Adjacency matrix and incidence matrix of graphs. +""" +import networkx as nx + +__all__ = ["incidence_matrix", "adjacency_matrix"] + + +def incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=None): + """Returns incidence matrix of G. + + The incidence matrix assigns each row to a node and each column to an edge. + For a standard incidence matrix a 1 appears wherever a row's node is + incident on the column's edge. For an oriented incidence matrix each + edge is assigned an orientation (arbitrarily for undirected and aligning to + direction for directed). A -1 appears for the source (tail) of an edge and + 1 for the destination (head) of the edge. The elements are zero otherwise. + + Parameters + ---------- + G : graph + A NetworkX graph + + nodelist : list, optional (default= all nodes in G) + The rows are ordered according to the nodes in nodelist. + If nodelist is None, then the ordering is produced by G.nodes(). + + edgelist : list, optional (default= all edges in G) + The columns are ordered according to the edges in edgelist. + If edgelist is None, then the ordering is produced by G.edges(). + + oriented: bool, optional (default=False) + If True, matrix elements are +1 or -1 for the head or tail node + respectively of each edge. If False, +1 occurs at both nodes. + + weight : string or None, optional (default=None) + The edge data key used to provide each value in the matrix. + If None, then each edge has weight 1. Edge weights, if used, + should be positive so that the orientation can provide the sign. + + Returns + ------- + A : SciPy sparse array + The incidence matrix of G. + + Notes + ----- + For MultiGraph/MultiDiGraph, the edges in edgelist should be + (u,v,key) 3-tuples. + + "Networks are the best discrete model for so many problems in + applied mathematics" [1]_. + + References + ---------- + .. [1] Gil Strang, Network applications: A = incidence matrix, + http://videolectures.net/mit18085f07_strang_lec03/ + """ + import scipy as sp + import scipy.sparse # call as sp.sparse + + if nodelist is None: + nodelist = list(G) + if edgelist is None: + if G.is_multigraph(): + edgelist = list(G.edges(keys=True)) + else: + edgelist = list(G.edges()) + A = sp.sparse.lil_array((len(nodelist), len(edgelist))) + node_index = {node: i for i, node in enumerate(nodelist)} + for ei, e in enumerate(edgelist): + (u, v) = e[:2] + if u == v: + continue # self loops give zero column + try: + ui = node_index[u] + vi = node_index[v] + except KeyError as err: + raise nx.NetworkXError( + f"node {u} or {v} in edgelist but not in nodelist" + ) from err + if weight is None: + wt = 1 + else: + if G.is_multigraph(): + ekey = e[2] + wt = G[u][v][ekey].get(weight, 1) + else: + wt = G[u][v].get(weight, 1) + if oriented: + A[ui, ei] = -wt + A[vi, ei] = wt + else: + A[ui, ei] = wt + A[vi, ei] = wt + return A.asformat("csc") + + +def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"): + """Returns adjacency matrix of G. + + Parameters + ---------- + G : graph + A NetworkX graph + + 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(). + + dtype : NumPy data-type, optional + The desired data-type for the array. + If None, then the NumPy default is used. + + weight : string or None, optional (default='weight') + The edge data key used to provide each value in the matrix. + If None, then each edge has weight 1. + + Returns + ------- + A : SciPy sparse array + Adjacency matrix representation of G. + + Notes + ----- + For directed graphs, entry i,j corresponds to an edge from i to j. + + If you want a pure Python adjacency matrix representation try + networkx.convert.to_dict_of_dicts which will return a + dictionary-of-dictionaries format that can be addressed as a + sparse matrix. + + For MultiGraph/MultiDiGraph with parallel edges the weights are summed. + See `to_numpy_array` for other options. + + The convention used for self-loop edges in graphs is to assign the + diagonal matrix entry value to the edge weight attribute + (or the number 1 if the edge has no weight attribute). If the + alternate convention of doubling the edge weight is desired the + resulting SciPy sparse array can be modified as follows: + + >>> G = nx.Graph([(1, 1)]) + >>> A = nx.adjacency_matrix(G) + >>> print(A.todense()) + [[1]] + >>> A.setdiag(A.diagonal() * 2) + >>> print(A.todense()) + [[2]] + + See Also + -------- + to_numpy_array + to_scipy_sparse_array + to_dict_of_dicts + adjacency_spectrum + """ + return nx.to_scipy_sparse_array(G, nodelist=nodelist, dtype=dtype, weight=weight) diff --git a/shared/package-files/06/067298ce39044746278cb1c81360130a8b514f0e97fdea9ad28210836ce6ed26/vi200 b/shared/package-files/06/067298ce39044746278cb1c81360130a8b514f0e97fdea9ad28210836ce6ed26/vi200 new file mode 100644 index 0000000000000000000000000000000000000000..71f185db7fe197727a3a4aed5108b77b1d4e2e95 Binary files /dev/null and b/shared/package-files/06/067298ce39044746278cb1c81360130a8b514f0e97fdea9ad28210836ce6ed26/vi200 differ diff --git a/shared/package-files/06/0673a0e29638ac7869029b4d3ada6b6259ea74709d9c5ca05e5b2166efe0eb66/dumpdata.pyi b/shared/package-files/06/0673a0e29638ac7869029b4d3ada6b6259ea74709d9c5ca05e5b2166efe0eb66/dumpdata.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bc3c4ce8cced78fe7a0091fd35e8fac05ddaa3e7 --- /dev/null +++ b/shared/package-files/06/0673a0e29638ac7869029b4d3ada6b6259ea74709d9c5ca05e5b2166efe0eb66/dumpdata.pyi @@ -0,0 +1,4 @@ +from django.core.management.base import BaseCommand + +class ProxyModelWarning(Warning): ... +class Command(BaseCommand): ... diff --git a/shared/package-files/06/0676fbb7fe92fdce7eddd66b43e5d7f446b338a85fb547dc09e8d75d6c9dd445/parse.py b/shared/package-files/06/0676fbb7fe92fdce7eddd66b43e5d7f446b338a85fb547dc09e8d75d6c9dd445/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..d41c4c2db23df58f2ee8755e2088b1e7b4aba8e1 --- /dev/null +++ b/shared/package-files/06/0676fbb7fe92fdce7eddd66b43e5d7f446b338a85fb547dc09e8d75d6c9dd445/parse.py @@ -0,0 +1,54 @@ +import os + + +def parse_distributions_h(ffi, inc_dir): + """ + Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef + + Read the function declarations without the "#define ..." macros that will + be filled in when loading the library. + """ + + with open(os.path.join(inc_dir, 'random', 'bitgen.h')) as fid: + s = [] + for line in fid: + # massage the include file + if line.strip().startswith('#'): + continue + s.append(line) + ffi.cdef('\n'.join(s)) + + with open(os.path.join(inc_dir, 'random', 'distributions.h')) as fid: + s = [] + in_skip = 0 + ignoring = False + for line in fid: + # check for and remove extern "C" guards + if ignoring: + if line.strip().startswith('#endif'): + ignoring = False + continue + if line.strip().startswith('#ifdef __cplusplus'): + ignoring = True + + # massage the include file + if line.strip().startswith('#'): + continue + + # skip any inlined function definition + # which starts with 'static inline xxx(...) {' + # and ends with a closing '}' + if line.strip().startswith('static inline'): + in_skip += line.count('{') + continue + elif in_skip > 0: + in_skip += line.count('{') + in_skip -= line.count('}') + continue + + # replace defines with their value or remove them + line = line.replace('DECLDIR', '') + line = line.replace('RAND_INT_TYPE', 'int64_t') + s.append(line) + ffi.cdef('\n'.join(s)) + diff --git a/shared/package-files/06/0678223154bd9f2af6db3eb332b3ab1cb7829687bfe65b9785fe53e6662e7202/extra_vsx_asm.c b/shared/package-files/06/0678223154bd9f2af6db3eb332b3ab1cb7829687bfe65b9785fe53e6662e7202/extra_vsx_asm.c new file mode 100644 index 0000000000000000000000000000000000000000..b73a6f43808eeb5af2bd212ee88b6c1002a29901 --- /dev/null +++ b/shared/package-files/06/0678223154bd9f2af6db3eb332b3ab1cb7829687bfe65b9785fe53e6662e7202/extra_vsx_asm.c @@ -0,0 +1,36 @@ +/** + * Testing ASM VSX register number fixer '%x' + * + * old versions of CLANG doesn't support %x in the inline asm template + * which fixes register number when using any of the register constraints wa, wd, wf. + * + * xref: + * - https://bugs.llvm.org/show_bug.cgi?id=31837 + * - https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html + */ +#ifndef __VSX__ + #error "VSX is not supported" +#endif +#include + +#if (defined(__GNUC__) && !defined(vec_xl)) || (defined(__clang__) && !defined(__IBMC__)) + #define vsx_ld vec_vsx_ld + #define vsx_st vec_vsx_st +#else + #define vsx_ld vec_xl + #define vsx_st vec_xst +#endif + +int main(void) +{ + float z4[] = {0, 0, 0, 0}; + signed int zout[] = {0, 0, 0, 0}; + + __vector float vz4 = vsx_ld(0, z4); + __vector signed int asm_ret = vsx_ld(0, zout); + + __asm__ ("xvcvspsxws %x0,%x1" : "=wa" (vz4) : "wa" (asm_ret)); + + vsx_st(asm_ret, 0, zout); + return zout[0]; +} diff --git a/shared/package-files/06/067cbf4c71a2dadc94787c5c3aec34d4eee1344f01fe06af7b900101942dc134/datetime.h b/shared/package-files/06/067cbf4c71a2dadc94787c5c3aec34d4eee1344f01fe06af7b900101942dc134/datetime.h new file mode 100644 index 0000000000000000000000000000000000000000..9b21eeb4342170f5462ee6a532003985fe5882f6 --- /dev/null +++ b/shared/package-files/06/067cbf4c71a2dadc94787c5c3aec34d4eee1344f01fe06af7b900101942dc134/datetime.h @@ -0,0 +1,231 @@ +// 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/python/platform.h" +#include "arrow/python/visibility.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_fwd.h" +#include "arrow/util/int_util_overflow.h" +#include "arrow/util/logging.h" + +// By default, PyDateTimeAPI is a *static* variable. This forces +// PyDateTime_IMPORT to be called in every C/C++ module using the +// C datetime API. This is error-prone and potentially costly. +// Instead, we redefine PyDateTimeAPI to point to a global variable, +// which is initialized once by calling InitDatetime(). +#ifdef PYPY_VERSION +# include "datetime.h" +#else +# define PyDateTimeAPI ::arrow::py::internal::datetime_api +#endif + +namespace arrow { +using internal::AddWithOverflow; +using internal::MultiplyWithOverflow; +namespace py { +namespace internal { + +#ifndef PYPY_VERSION +extern PyDateTime_CAPI* datetime_api; + +ARROW_PYTHON_EXPORT +void InitDatetime(); +#endif + +// Returns the MonthDayNano namedtuple type (increments the reference count). +ARROW_PYTHON_EXPORT +PyObject* NewMonthDayNanoTupleType(); + +ARROW_PYTHON_EXPORT +inline int64_t PyTime_to_us(PyObject* pytime) { + return (PyDateTime_TIME_GET_HOUR(pytime) * 3600000000LL + + PyDateTime_TIME_GET_MINUTE(pytime) * 60000000LL + + PyDateTime_TIME_GET_SECOND(pytime) * 1000000LL + + PyDateTime_TIME_GET_MICROSECOND(pytime)); +} + +ARROW_PYTHON_EXPORT +inline int64_t PyTime_to_s(PyObject* pytime) { return PyTime_to_us(pytime) / 1000000; } + +ARROW_PYTHON_EXPORT +inline int64_t PyTime_to_ms(PyObject* pytime) { return PyTime_to_us(pytime) / 1000; } + +ARROW_PYTHON_EXPORT +inline int64_t PyTime_to_ns(PyObject* pytime) { return PyTime_to_us(pytime) * 1000; } + +ARROW_PYTHON_EXPORT +Status PyTime_from_int(int64_t val, const TimeUnit::type unit, PyObject** out); + +ARROW_PYTHON_EXPORT +Status PyDate_from_int(int64_t val, const DateUnit unit, PyObject** out); + +// WARNING: This function returns a naive datetime. +ARROW_PYTHON_EXPORT +Status PyDateTime_from_int(int64_t val, const TimeUnit::type unit, PyObject** out); + +// This declaration must be the same as in filesystem/filesystem.h +using TimePoint = + std::chrono::time_point; + +ARROW_PYTHON_EXPORT +int64_t PyDate_to_days(PyDateTime_Date* pydate); + +ARROW_PYTHON_EXPORT +inline int64_t PyDate_to_s(PyDateTime_Date* pydate) { + return PyDate_to_days(pydate) * 86400LL; +} + +ARROW_PYTHON_EXPORT +inline int64_t PyDate_to_ms(PyDateTime_Date* pydate) { + return PyDate_to_days(pydate) * 86400000LL; +} + +ARROW_PYTHON_EXPORT +inline int64_t PyDateTime_to_s(PyDateTime_DateTime* pydatetime) { + return (PyDate_to_s(reinterpret_cast(pydatetime)) + + PyDateTime_DATE_GET_HOUR(pydatetime) * 3600LL + + PyDateTime_DATE_GET_MINUTE(pydatetime) * 60LL + + PyDateTime_DATE_GET_SECOND(pydatetime)); +} + +ARROW_PYTHON_EXPORT +inline int64_t PyDateTime_to_ms(PyDateTime_DateTime* pydatetime) { + return (PyDateTime_to_s(pydatetime) * 1000LL + + PyDateTime_DATE_GET_MICROSECOND(pydatetime) / 1000); +} + +ARROW_PYTHON_EXPORT +inline int64_t PyDateTime_to_us(PyDateTime_DateTime* pydatetime) { + return (PyDateTime_to_s(pydatetime) * 1000000LL + + PyDateTime_DATE_GET_MICROSECOND(pydatetime)); +} + +ARROW_PYTHON_EXPORT +inline int64_t PyDateTime_to_ns(PyDateTime_DateTime* pydatetime) { + return PyDateTime_to_us(pydatetime) * 1000LL; +} + +ARROW_PYTHON_EXPORT +inline TimePoint PyDateTime_to_TimePoint(PyDateTime_DateTime* pydatetime) { + return TimePoint(TimePoint::duration(PyDateTime_to_ns(pydatetime))); +} + +ARROW_PYTHON_EXPORT +inline int64_t TimePoint_to_ns(TimePoint val) { return val.time_since_epoch().count(); } + +ARROW_PYTHON_EXPORT +inline TimePoint TimePoint_from_s(double val) { + return TimePoint(TimePoint::duration(static_cast(1e9 * val))); +} + +ARROW_PYTHON_EXPORT +inline TimePoint TimePoint_from_ns(int64_t val) { + return TimePoint(TimePoint::duration(val)); +} + +ARROW_PYTHON_EXPORT +inline int64_t PyDelta_to_s(PyDateTime_Delta* pytimedelta) { + return (PyDateTime_DELTA_GET_DAYS(pytimedelta) * 86400LL + + PyDateTime_DELTA_GET_SECONDS(pytimedelta)); +} + +ARROW_PYTHON_EXPORT +inline int64_t PyDelta_to_ms(PyDateTime_Delta* pytimedelta) { + return (PyDelta_to_s(pytimedelta) * 1000LL + + PyDateTime_DELTA_GET_MICROSECONDS(pytimedelta) / 1000); +} + +ARROW_PYTHON_EXPORT +inline Result PyDelta_to_us(PyDateTime_Delta* pytimedelta) { + int64_t result = PyDelta_to_s(pytimedelta); + if (MultiplyWithOverflow(result, 1000000LL, &result)) { + return Status::Invalid("Timedelta too large to fit in 64-bit integer"); + } + if (AddWithOverflow(result, PyDateTime_DELTA_GET_MICROSECONDS(pytimedelta), &result)) { + return Status::Invalid("Timedelta too large to fit in 64-bit integer"); + } + return result; +} + +ARROW_PYTHON_EXPORT +inline Result PyDelta_to_ns(PyDateTime_Delta* pytimedelta) { + ARROW_ASSIGN_OR_RAISE(int64_t result, PyDelta_to_us(pytimedelta)); + if (MultiplyWithOverflow(result, 1000LL, &result)) { + return Status::Invalid("Timedelta too large to fit in 64-bit integer"); + } + return result; +} + +ARROW_PYTHON_EXPORT +Result PyDateTime_utcoffset_s(PyObject* pydatetime); + +/// \brief Convert a time zone name into a time zone object. +/// +/// Supported input strings are: +/// * As used in the Olson time zone database (the "tz database" or +/// "tzdata"), such as "America/New_York" +/// * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30 +/// GIL must be held when calling this method. +ARROW_PYTHON_EXPORT +Result StringToTzinfo(const std::string& tz); + +/// \brief Convert a time zone object to a string representation. +/// +/// The output strings are: +/// * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30 +/// if the input object is either an instance of pytz._FixedOffset or +/// datetime.timedelta +/// * The timezone's name if the input object's tzname() method returns with a +/// non-empty timezone name such as "UTC" or "America/New_York" +/// +/// GIL must be held when calling this method. +ARROW_PYTHON_EXPORT +Result TzinfoToString(PyObject* pytzinfo); + +/// \brief Convert MonthDayNano to a python namedtuple. +/// +/// Return a named tuple (pyarrow.MonthDayNano) containing attributes +/// "months", "days", "nanoseconds" in the given order +/// with values extracted from the fields on interval. +/// +/// GIL must be held when calling this method. +ARROW_PYTHON_EXPORT +PyObject* MonthDayNanoIntervalToNamedTuple( + const MonthDayNanoIntervalType::MonthDayNanos& interval); + +/// \brief Convert the given Array to a PyList object containing +/// pyarrow.MonthDayNano objects. +ARROW_PYTHON_EXPORT +Result MonthDayNanoIntervalArrayToPyList( + const MonthDayNanoIntervalArray& array); + +/// \brief Convert the Scalar object to a pyarrow.MonthDayNano (or None if +/// is isn't valid). +ARROW_PYTHON_EXPORT +Result MonthDayNanoIntervalScalarToPyObject( + const MonthDayNanoIntervalScalar& scalar); + +} // namespace internal +} // namespace py +} // namespace arrow diff --git a/shared/package-files/06/067cf90582fe3175a05fd9d8418133510a966b32cb158c13f2f44a4c1db359f4/_export.py b/shared/package-files/06/067cf90582fe3175a05fd9d8418133510a966b32cb158c13f2f44a4c1db359f4/_export.py new file mode 100644 index 0000000000000000000000000000000000000000..6726d0c67bfb135aaa54392bb1f89fabe3b996ff --- /dev/null +++ b/shared/package-files/06/067cf90582fe3175a05fd9d8418133510a966b32cb158c13f2f44a4c1db359f4/_export.py @@ -0,0 +1,1167 @@ +""" +This module defines export functions for decision trees. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from collections.abc import Iterable +from io import StringIO +from numbers import Integral + +import numpy as np + +from ..base import is_classifier +from ..utils._param_validation import HasMethods, Interval, StrOptions, validate_params +from ..utils.validation import check_array, check_is_fitted +from . import DecisionTreeClassifier, DecisionTreeRegressor, _criterion, _tree +from ._reingold_tilford import Tree, buchheim + + +def _color_brew(n): + """Generate n colors with equally spaced hues. + + Parameters + ---------- + n : int + The number of colors required. + + Returns + ------- + color_list : list, length n + List of n tuples of form (R, G, B) being the components of each color. + """ + color_list = [] + + # Initialize saturation & value; calculate chroma & value shift + s, v = 0.75, 0.9 + c = s * v + m = v - c + + for h in np.arange(25, 385, 360.0 / n).astype(int): + # Calculate some intermediate values + h_bar = h / 60.0 + x = c * (1 - abs((h_bar % 2) - 1)) + # Initialize RGB with same hue & chroma as our color + rgb = [ + (c, x, 0), + (x, c, 0), + (0, c, x), + (0, x, c), + (x, 0, c), + (c, 0, x), + (c, x, 0), + ] + r, g, b = rgb[int(h_bar)] + # Shift the initial RGB values to match value and store + rgb = [(int(255 * (r + m))), (int(255 * (g + m))), (int(255 * (b + m)))] + color_list.append(rgb) + + return color_list + + +class Sentinel: + def __repr__(self): + return '"tree.dot"' + + +SENTINEL = Sentinel() + + +@validate_params( + { + "decision_tree": [DecisionTreeClassifier, DecisionTreeRegressor], + "max_depth": [Interval(Integral, 0, None, closed="left"), None], + "feature_names": ["array-like", None], + "class_names": ["array-like", "boolean", None], + "label": [StrOptions({"all", "root", "none"})], + "filled": ["boolean"], + "impurity": ["boolean"], + "node_ids": ["boolean"], + "proportion": ["boolean"], + "rounded": ["boolean"], + "precision": [Interval(Integral, 0, None, closed="left"), None], + "ax": "no_validation", # delegate validation to matplotlib + "fontsize": [Interval(Integral, 0, None, closed="left"), None], + }, + prefer_skip_nested_validation=True, +) +def plot_tree( + decision_tree, + *, + max_depth=None, + feature_names=None, + class_names=None, + label="all", + filled=False, + impurity=True, + node_ids=False, + proportion=False, + rounded=False, + precision=3, + ax=None, + fontsize=None, +): + """Plot a decision tree. + + The sample counts that are shown are weighted with any sample_weights that + might be present. + + The visualization is fit automatically to the size of the axis. + Use the ``figsize`` or ``dpi`` arguments of ``plt.figure`` to control + the size of the rendering. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.21 + + Parameters + ---------- + decision_tree : decision tree regressor or classifier + The decision tree to be plotted. + + max_depth : int, default=None + The maximum depth of the representation. If None, the tree is fully + generated. + + feature_names : array-like of str, default=None + Names of each of the features. + If None, generic names will be used ("x[0]", "x[1]", ...). + + class_names : array-like of str or True, default=None + Names of each of the target classes in ascending numerical order. + Only relevant for classification and not supported for multi-output. + If ``True``, shows a symbolic representation of the class name. + + label : {'all', 'root', 'none'}, default='all' + Whether to show informative labels for impurity, etc. + Options include 'all' to show at every node, 'root' to show only at + the top root node, or 'none' to not show at any node. + + filled : bool, default=False + When set to ``True``, paint nodes to indicate majority class for + classification, extremity of values for regression, or purity of node + for multi-output. + + impurity : bool, default=True + When set to ``True``, show the impurity at each node. + + node_ids : bool, default=False + When set to ``True``, show the ID number on each node. + + proportion : bool, default=False + When set to ``True``, change the display of 'values' and/or 'samples' + to be proportions and percentages respectively. + + rounded : bool, default=False + When set to ``True``, draw node boxes with rounded corners and use + Helvetica fonts instead of Times-Roman. + + precision : int, default=3 + Number of digits of precision for floating point in the values of + impurity, threshold and value attributes of each node. + + ax : matplotlib axis, default=None + Axes to plot to. If None, use current axis. Any previous content + is cleared. + + fontsize : int, default=None + Size of text font. If None, determined automatically to fit figure. + + Returns + ------- + annotations : list of artists + List containing the artists for the annotation boxes making up the + tree. + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn import tree + + >>> clf = tree.DecisionTreeClassifier(random_state=0) + >>> iris = load_iris() + + >>> clf = clf.fit(iris.data, iris.target) + >>> tree.plot_tree(clf) + [...] + """ + + check_is_fitted(decision_tree) + + exporter = _MPLTreeExporter( + max_depth=max_depth, + feature_names=feature_names, + class_names=class_names, + label=label, + filled=filled, + impurity=impurity, + node_ids=node_ids, + proportion=proportion, + rounded=rounded, + precision=precision, + fontsize=fontsize, + ) + return exporter.export(decision_tree, ax=ax) + + +class _BaseTreeExporter: + def __init__( + self, + max_depth=None, + feature_names=None, + class_names=None, + label="all", + filled=False, + impurity=True, + node_ids=False, + proportion=False, + rounded=False, + precision=3, + fontsize=None, + ): + self.max_depth = max_depth + self.feature_names = feature_names + self.class_names = class_names + self.label = label + self.filled = filled + self.impurity = impurity + self.node_ids = node_ids + self.proportion = proportion + self.rounded = rounded + self.precision = precision + self.fontsize = fontsize + + def get_color(self, value): + # Find the appropriate color & intensity for a node + if self.colors["bounds"] is None: + # Classification tree + color = list(self.colors["rgb"][np.argmax(value)]) + sorted_values = sorted(value, reverse=True) + if len(sorted_values) == 1: + alpha = 0.0 + else: + alpha = (sorted_values[0] - sorted_values[1]) / (1 - sorted_values[1]) + else: + # Regression tree or multi-output + color = list(self.colors["rgb"][0]) + alpha = (value - self.colors["bounds"][0]) / ( + self.colors["bounds"][1] - self.colors["bounds"][0] + ) + # compute the color as alpha against white + color = [int(round(alpha * c + (1 - alpha) * 255, 0)) for c in color] + # Return html color code in #RRGGBB format + return "#%2x%2x%2x" % tuple(color) + + def get_fill_color(self, tree, node_id): + # Fetch appropriate color for node + if "rgb" not in self.colors: + # Initialize colors and bounds if required + self.colors["rgb"] = _color_brew(tree.n_classes[0]) + if tree.n_outputs != 1: + # Find max and min impurities for multi-output + # The next line uses -max(impurity) instead of min(-impurity) + # and -min(impurity) instead of max(-impurity) on purpose, in + # order to avoid what looks like an issue with SIMD on non + # memory aligned arrays on 32bit OS. For more details see + # https://github.com/scikit-learn/scikit-learn/issues/27506. + self.colors["bounds"] = (-np.max(tree.impurity), -np.min(tree.impurity)) + elif tree.n_classes[0] == 1 and len(np.unique(tree.value)) != 1: + # Find max and min values in leaf nodes for regression + self.colors["bounds"] = (np.min(tree.value), np.max(tree.value)) + if tree.n_outputs == 1: + node_val = tree.value[node_id][0, :] + if ( + tree.n_classes[0] == 1 + and isinstance(node_val, Iterable) + and self.colors["bounds"] is not None + ): + # Unpack the float only for the regression tree case. + # Classification tree requires an Iterable in `get_color`. + node_val = node_val.item() + else: + # If multi-output color node by impurity + node_val = -tree.impurity[node_id] + return self.get_color(node_val) + + def node_to_str(self, tree, node_id, criterion): + # Generate the node content string + if tree.n_outputs == 1: + value = tree.value[node_id][0, :] + else: + value = tree.value[node_id] + + # Should labels be shown? + labels = (self.label == "root" and node_id == 0) or self.label == "all" + + characters = self.characters + node_string = characters[-1] + + # Write node ID + if self.node_ids: + if labels: + node_string += "node " + node_string += characters[0] + str(node_id) + characters[4] + + # Write decision criteria + if tree.children_left[node_id] != _tree.TREE_LEAF: + # Always write node decision criteria, except for leaves + if self.feature_names is not None: + feature = self.feature_names[tree.feature[node_id]] + feature = self.str_escape(feature) + else: + feature = "x%s%s%s" % ( + characters[1], + tree.feature[node_id], + characters[2], + ) + node_string += "%s %s %s%s" % ( + feature, + characters[3], + round(tree.threshold[node_id], self.precision), + characters[4], + ) + + # Write impurity + if self.impurity: + if isinstance(criterion, _criterion.FriedmanMSE): + criterion = "friedman_mse" + elif isinstance(criterion, _criterion.MSE) or criterion == "squared_error": + criterion = "squared_error" + elif not isinstance(criterion, str): + criterion = "impurity" + if labels: + node_string += "%s = " % criterion + node_string += ( + str(round(tree.impurity[node_id], self.precision)) + characters[4] + ) + + # Write node sample count + if labels: + node_string += "samples = " + if self.proportion: + percent = ( + 100.0 * tree.n_node_samples[node_id] / float(tree.n_node_samples[0]) + ) + node_string += str(round(percent, 1)) + "%" + characters[4] + else: + node_string += str(tree.n_node_samples[node_id]) + characters[4] + + # Write node class distribution / regression value + if not self.proportion and tree.n_classes[0] != 1: + # For classification this will show the proportion of samples + value = value * tree.weighted_n_node_samples[node_id] + if labels: + node_string += "value = " + if tree.n_classes[0] == 1: + # Regression + value_text = np.around(value, self.precision) + elif self.proportion: + # Classification + value_text = np.around(value, self.precision) + elif np.all(np.equal(np.mod(value, 1), 0)): + # Classification without floating-point weights + value_text = value.astype(int) + else: + # Classification with floating-point weights + value_text = np.around(value, self.precision) + # Strip whitespace + value_text = str(value_text.astype("S32")).replace("b'", "'") + value_text = value_text.replace("' '", ", ").replace("'", "") + if tree.n_classes[0] == 1 and tree.n_outputs == 1: + value_text = value_text.replace("[", "").replace("]", "") + value_text = value_text.replace("\n ", characters[4]) + node_string += value_text + characters[4] + + # Write node majority class + if ( + self.class_names is not None + and tree.n_classes[0] != 1 + and tree.n_outputs == 1 + ): + # Only done for single-output classification trees + if labels: + node_string += "class = " + if self.class_names is not True: + class_name = self.class_names[np.argmax(value)] + class_name = self.str_escape(class_name) + else: + class_name = "y%s%s%s" % ( + characters[1], + np.argmax(value), + characters[2], + ) + node_string += class_name + + # Clean up any trailing newlines + if node_string.endswith(characters[4]): + node_string = node_string[: -len(characters[4])] + + return node_string + characters[5] + + def str_escape(self, string): + return string + + +class _DOTTreeExporter(_BaseTreeExporter): + def __init__( + self, + out_file=SENTINEL, + max_depth=None, + feature_names=None, + class_names=None, + label="all", + filled=False, + leaves_parallel=False, + impurity=True, + node_ids=False, + proportion=False, + rotate=False, + rounded=False, + special_characters=False, + precision=3, + fontname="helvetica", + ): + super().__init__( + max_depth=max_depth, + feature_names=feature_names, + class_names=class_names, + label=label, + filled=filled, + impurity=impurity, + node_ids=node_ids, + proportion=proportion, + rounded=rounded, + precision=precision, + ) + self.leaves_parallel = leaves_parallel + self.out_file = out_file + self.special_characters = special_characters + self.fontname = fontname + self.rotate = rotate + + # PostScript compatibility for special characters + if special_characters: + self.characters = ["#", "", "", "≤", "
", ">", "<"] + else: + self.characters = ["#", "[", "]", "<=", "\\n", '"', '"'] + + # The depth of each node for plotting with 'leaf' option + self.ranks = {"leaves": []} + # The colors to render each node with + self.colors = {"bounds": None} + + def export(self, decision_tree): + # Check length of feature_names before getting into the tree node + # Raise error if length of feature_names does not match + # n_features_in_ in the decision_tree + if self.feature_names is not None: + if len(self.feature_names) != decision_tree.n_features_in_: + raise ValueError( + "Length of feature_names, %d does not match number of features, %d" + % (len(self.feature_names), decision_tree.n_features_in_) + ) + # each part writes to out_file + self.head() + # Now recurse the tree and add node & edge attributes + if isinstance(decision_tree, _tree.Tree): + self.recurse(decision_tree, 0, criterion="impurity") + else: + self.recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion) + + self.tail() + + def tail(self): + # If required, draw leaf nodes at same depth as each other + if self.leaves_parallel: + for rank in sorted(self.ranks): + self.out_file.write( + "{rank=same ; " + "; ".join(r for r in self.ranks[rank]) + "} ;\n" + ) + self.out_file.write("}") + + def head(self): + self.out_file.write("digraph Tree {\n") + + # Specify node aesthetics + self.out_file.write("node [shape=box") + rounded_filled = [] + if self.filled: + rounded_filled.append("filled") + if self.rounded: + rounded_filled.append("rounded") + if len(rounded_filled) > 0: + self.out_file.write( + ', style="%s", color="black"' % ", ".join(rounded_filled) + ) + + self.out_file.write(', fontname="%s"' % self.fontname) + self.out_file.write("] ;\n") + + # Specify graph & edge aesthetics + if self.leaves_parallel: + self.out_file.write("graph [ranksep=equally, splines=polyline] ;\n") + + self.out_file.write('edge [fontname="%s"] ;\n' % self.fontname) + + if self.rotate: + self.out_file.write("rankdir=LR ;\n") + + def recurse(self, tree, node_id, criterion, parent=None, depth=0): + if node_id == _tree.TREE_LEAF: + raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF) + + left_child = tree.children_left[node_id] + right_child = tree.children_right[node_id] + + # Add node with description + if self.max_depth is None or depth <= self.max_depth: + # Collect ranks for 'leaf' option in plot_options + if left_child == _tree.TREE_LEAF: + self.ranks["leaves"].append(str(node_id)) + elif str(depth) not in self.ranks: + self.ranks[str(depth)] = [str(node_id)] + else: + self.ranks[str(depth)].append(str(node_id)) + + self.out_file.write( + "%d [label=%s" % (node_id, self.node_to_str(tree, node_id, criterion)) + ) + + if self.filled: + self.out_file.write( + ', fillcolor="%s"' % self.get_fill_color(tree, node_id) + ) + self.out_file.write("] ;\n") + + if parent is not None: + # Add edge to parent + self.out_file.write("%d -> %d" % (parent, node_id)) + if parent == 0: + # Draw True/False labels if parent is root node + angles = np.array([45, -45]) * ((self.rotate - 0.5) * -2) + self.out_file.write(" [labeldistance=2.5, labelangle=") + if node_id == 1: + self.out_file.write('%d, headlabel="True"]' % angles[0]) + else: + self.out_file.write('%d, headlabel="False"]' % angles[1]) + self.out_file.write(" ;\n") + + if left_child != _tree.TREE_LEAF: + self.recurse( + tree, + left_child, + criterion=criterion, + parent=node_id, + depth=depth + 1, + ) + self.recurse( + tree, + right_child, + criterion=criterion, + parent=node_id, + depth=depth + 1, + ) + + else: + self.ranks["leaves"].append(str(node_id)) + + self.out_file.write('%d [label="(...)"' % node_id) + if self.filled: + # color cropped nodes grey + self.out_file.write(', fillcolor="#C0C0C0"') + self.out_file.write("] ;\n" % node_id) + + if parent is not None: + # Add edge to parent + self.out_file.write("%d -> %d ;\n" % (parent, node_id)) + + def str_escape(self, string): + # override default escaping for graphviz + return string.replace('"', r"\"") + + +class _MPLTreeExporter(_BaseTreeExporter): + def __init__( + self, + max_depth=None, + feature_names=None, + class_names=None, + label="all", + filled=False, + impurity=True, + node_ids=False, + proportion=False, + rounded=False, + precision=3, + fontsize=None, + ): + super().__init__( + max_depth=max_depth, + feature_names=feature_names, + class_names=class_names, + label=label, + filled=filled, + impurity=impurity, + node_ids=node_ids, + proportion=proportion, + rounded=rounded, + precision=precision, + ) + self.fontsize = fontsize + + # The depth of each node for plotting with 'leaf' option + self.ranks = {"leaves": []} + # The colors to render each node with + self.colors = {"bounds": None} + + self.characters = ["#", "[", "]", "<=", "\n", "", ""] + self.bbox_args = dict() + if self.rounded: + self.bbox_args["boxstyle"] = "round" + + self.arrow_args = dict(arrowstyle="<-") + + def _make_tree(self, node_id, et, criterion, depth=0): + # traverses _tree.Tree recursively, builds intermediate + # "_reingold_tilford.Tree" object + name = self.node_to_str(et, node_id, criterion=criterion) + if et.children_left[node_id] != _tree.TREE_LEAF and ( + self.max_depth is None or depth <= self.max_depth + ): + children = [ + self._make_tree( + et.children_left[node_id], et, criterion, depth=depth + 1 + ), + self._make_tree( + et.children_right[node_id], et, criterion, depth=depth + 1 + ), + ] + else: + return Tree(name, node_id) + return Tree(name, node_id, *children) + + def export(self, decision_tree, ax=None): + import matplotlib.pyplot as plt + from matplotlib.text import Annotation + + if ax is None: + ax = plt.gca() + ax.clear() + ax.set_axis_off() + my_tree = self._make_tree(0, decision_tree.tree_, decision_tree.criterion) + draw_tree = buchheim(my_tree) + + # important to make sure we're still + # inside the axis after drawing the box + # this makes sense because the width of a box + # is about the same as the distance between boxes + max_x, max_y = draw_tree.max_extents() + 1 + ax_width = ax.get_window_extent().width + ax_height = ax.get_window_extent().height + + scale_x = ax_width / max_x + scale_y = ax_height / max_y + self.recurse(draw_tree, decision_tree.tree_, ax, max_x, max_y) + + anns = [ann for ann in ax.get_children() if isinstance(ann, Annotation)] + + # update sizes of all bboxes + renderer = ax.figure.canvas.get_renderer() + + for ann in anns: + ann.update_bbox_position_size(renderer) + + if self.fontsize is None: + # get figure to data transform + # adjust fontsize to avoid overlap + # get max box width and height + extents = [ + bbox_patch.get_window_extent() + for ann in anns + if (bbox_patch := ann.get_bbox_patch()) is not None + ] + max_width = max([extent.width for extent in extents]) + max_height = max([extent.height for extent in extents]) + # width should be around scale_x in axis coordinates + size = anns[0].get_fontsize() * min( + scale_x / max_width, scale_y / max_height + ) + for ann in anns: + ann.set_fontsize(size) + + return anns + + def recurse(self, node, tree, ax, max_x, max_y, depth=0): + import matplotlib.pyplot as plt + + # kwargs for annotations without a bounding box + common_kwargs = dict( + zorder=100 - 10 * depth, + xycoords="axes fraction", + ) + if self.fontsize is not None: + common_kwargs["fontsize"] = self.fontsize + + # kwargs for annotations with a bounding box + kwargs = dict( + ha="center", + va="center", + bbox=self.bbox_args.copy(), + arrowprops=self.arrow_args.copy(), + **common_kwargs, + ) + kwargs["arrowprops"]["edgecolor"] = plt.rcParams["text.color"] + + # offset things by .5 to center them in plot + xy = ((node.x + 0.5) / max_x, (max_y - node.y - 0.5) / max_y) + + if self.max_depth is None or depth <= self.max_depth: + if self.filled: + kwargs["bbox"]["fc"] = self.get_fill_color(tree, node.tree.node_id) + else: + kwargs["bbox"]["fc"] = ax.get_facecolor() + + if node.parent is None: + # root + ax.annotate(node.tree.label, xy, **kwargs) + else: + xy_parent = ( + (node.parent.x + 0.5) / max_x, + (max_y - node.parent.y - 0.5) / max_y, + ) + ax.annotate(node.tree.label, xy_parent, xy, **kwargs) + + # Draw True/False labels if parent is root node + if node.parent.parent is None: + # Adjust the position for the text to be slightly above the arrow + text_pos = ( + (xy_parent[0] + xy[0]) / 2, + (xy_parent[1] + xy[1]) / 2, + ) + # Annotate the arrow with the edge label to indicate the child + # where the sample-split condition is satisfied + if node.parent.left() == node: + label_text, label_ha = ("True ", "right") + else: + label_text, label_ha = (" False", "left") + ax.annotate(label_text, text_pos, ha=label_ha, **common_kwargs) + for child in node.children: + self.recurse(child, tree, ax, max_x, max_y, depth=depth + 1) + + else: + xy_parent = ( + (node.parent.x + 0.5) / max_x, + (max_y - node.parent.y - 0.5) / max_y, + ) + kwargs["bbox"]["fc"] = "grey" + ax.annotate("\n (...) \n", xy_parent, xy, **kwargs) + + +@validate_params( + { + "decision_tree": "no_validation", + "out_file": [str, None, HasMethods("write")], + "max_depth": [Interval(Integral, 0, None, closed="left"), None], + "feature_names": ["array-like", None], + "class_names": ["array-like", "boolean", None], + "label": [StrOptions({"all", "root", "none"})], + "filled": ["boolean"], + "leaves_parallel": ["boolean"], + "impurity": ["boolean"], + "node_ids": ["boolean"], + "proportion": ["boolean"], + "rotate": ["boolean"], + "rounded": ["boolean"], + "special_characters": ["boolean"], + "precision": [Interval(Integral, 0, None, closed="left"), None], + "fontname": [str], + }, + prefer_skip_nested_validation=True, +) +def export_graphviz( + decision_tree, + out_file=None, + *, + max_depth=None, + feature_names=None, + class_names=None, + label="all", + filled=False, + leaves_parallel=False, + impurity=True, + node_ids=False, + proportion=False, + rotate=False, + rounded=False, + special_characters=False, + precision=3, + fontname="helvetica", +): + """Export a decision tree in DOT format. + + This function generates a GraphViz representation of the decision tree, + which is then written into `out_file`. Once exported, graphical renderings + can be generated using, for example:: + + $ dot -Tps tree.dot -o tree.ps (PostScript format) + $ dot -Tpng tree.dot -o tree.png (PNG format) + + The sample counts that are shown are weighted with any sample_weights that + might be present. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + decision_tree : object + The decision tree estimator to be exported to GraphViz. + + out_file : object or str, default=None + Handle or name of the output file. If ``None``, the result is + returned as a string. + + .. versionchanged:: 0.20 + Default of out_file changed from "tree.dot" to None. + + max_depth : int, default=None + The maximum depth of the representation. If None, the tree is fully + generated. + + feature_names : array-like of shape (n_features,), default=None + An array containing the feature names. + If None, generic names will be used ("x[0]", "x[1]", ...). + + class_names : array-like of shape (n_classes,) or bool, default=None + Names of each of the target classes in ascending numerical order. + Only relevant for classification and not supported for multi-output. + If ``True``, shows a symbolic representation of the class name. + + label : {'all', 'root', 'none'}, default='all' + Whether to show informative labels for impurity, etc. + Options include 'all' to show at every node, 'root' to show only at + the top root node, or 'none' to not show at any node. + + filled : bool, default=False + When set to ``True``, paint nodes to indicate majority class for + classification, extremity of values for regression, or purity of node + for multi-output. + + leaves_parallel : bool, default=False + When set to ``True``, draw all leaf nodes at the bottom of the tree. + + impurity : bool, default=True + When set to ``True``, show the impurity at each node. + + node_ids : bool, default=False + When set to ``True``, show the ID number on each node. + + proportion : bool, default=False + When set to ``True``, change the display of 'values' and/or 'samples' + to be proportions and percentages respectively. + + rotate : bool, default=False + When set to ``True``, orient tree left to right rather than top-down. + + rounded : bool, default=False + When set to ``True``, draw node boxes with rounded corners. + + special_characters : bool, default=False + When set to ``False``, ignore special characters for PostScript + compatibility. + + precision : int, default=3 + Number of digits of precision for floating point in the values of + impurity, threshold and value attributes of each node. + + fontname : str, default='helvetica' + Name of font used to render text. + + Returns + ------- + dot_data : str + String representation of the input tree in GraphViz dot format. + Only returned if ``out_file`` is None. + + .. versionadded:: 0.18 + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn import tree + + >>> clf = tree.DecisionTreeClassifier() + >>> iris = load_iris() + + >>> clf = clf.fit(iris.data, iris.target) + >>> tree.export_graphviz(clf) + 'digraph Tree {... + """ + if feature_names is not None: + feature_names = check_array( + feature_names, ensure_2d=False, dtype=None, ensure_min_samples=0 + ) + if class_names is not None and not isinstance(class_names, bool): + class_names = check_array( + class_names, ensure_2d=False, dtype=None, ensure_min_samples=0 + ) + + check_is_fitted(decision_tree) + own_file = False + return_string = False + try: + if isinstance(out_file, str): + out_file = open(out_file, "w", encoding="utf-8") + own_file = True + + if out_file is None: + return_string = True + out_file = StringIO() + + exporter = _DOTTreeExporter( + out_file=out_file, + max_depth=max_depth, + feature_names=feature_names, + class_names=class_names, + label=label, + filled=filled, + leaves_parallel=leaves_parallel, + impurity=impurity, + node_ids=node_ids, + proportion=proportion, + rotate=rotate, + rounded=rounded, + special_characters=special_characters, + precision=precision, + fontname=fontname, + ) + exporter.export(decision_tree) + + if return_string: + return exporter.out_file.getvalue() + + finally: + if own_file: + out_file.close() + + +def _compute_depth(tree, node): + """ + Returns the depth of the subtree rooted in node. + """ + + def compute_depth_( + current_node, current_depth, children_left, children_right, depths + ): + depths += [current_depth] + left = children_left[current_node] + right = children_right[current_node] + if left != -1 and right != -1: + compute_depth_( + left, current_depth + 1, children_left, children_right, depths + ) + compute_depth_( + right, current_depth + 1, children_left, children_right, depths + ) + + depths = [] + compute_depth_(node, 1, tree.children_left, tree.children_right, depths) + return max(depths) + + +@validate_params( + { + "decision_tree": [DecisionTreeClassifier, DecisionTreeRegressor], + "feature_names": ["array-like", None], + "class_names": ["array-like", None], + "max_depth": [Interval(Integral, 0, None, closed="left"), None], + "spacing": [Interval(Integral, 1, None, closed="left"), None], + "decimals": [Interval(Integral, 0, None, closed="left"), None], + "show_weights": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def export_text( + decision_tree, + *, + feature_names=None, + class_names=None, + max_depth=10, + spacing=3, + decimals=2, + show_weights=False, +): + """Build a text report showing the rules of a decision tree. + + Note that backwards compatibility may not be supported. + + Parameters + ---------- + decision_tree : object + The decision tree estimator to be exported. + It can be an instance of + DecisionTreeClassifier or DecisionTreeRegressor. + + feature_names : array-like of shape (n_features,), default=None + An array containing the feature names. + If None generic names will be used ("feature_0", "feature_1", ...). + + class_names : array-like of shape (n_classes,), default=None + Names of each of the target classes in ascending numerical order. + Only relevant for classification and not supported for multi-output. + + - if `None`, the class names are delegated to `decision_tree.classes_`; + - otherwise, `class_names` will be used as class names instead of + `decision_tree.classes_`. The length of `class_names` must match + the length of `decision_tree.classes_`. + + .. versionadded:: 1.3 + + max_depth : int, default=10 + Only the first max_depth levels of the tree are exported. + Truncated branches will be marked with "...". + + spacing : int, default=3 + Number of spaces between edges. The higher it is, the wider the result. + + decimals : int, default=2 + Number of decimal digits to display. + + show_weights : bool, default=False + If true the classification weights will be exported on each leaf. + The classification weights are the number of samples each class. + + Returns + ------- + report : str + Text summary of all the rules in the decision tree. + + Examples + -------- + + >>> from sklearn.datasets import load_iris + >>> from sklearn.tree import DecisionTreeClassifier + >>> from sklearn.tree import export_text + >>> iris = load_iris() + >>> X = iris['data'] + >>> y = iris['target'] + >>> decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2) + >>> decision_tree = decision_tree.fit(X, y) + >>> r = export_text(decision_tree, feature_names=iris['feature_names']) + >>> print(r) + |--- petal width (cm) <= 0.80 + | |--- class: 0 + |--- petal width (cm) > 0.80 + | |--- petal width (cm) <= 1.75 + | | |--- class: 1 + | |--- petal width (cm) > 1.75 + | | |--- class: 2 + """ + if feature_names is not None: + feature_names = check_array( + feature_names, ensure_2d=False, dtype=None, ensure_min_samples=0 + ) + if class_names is not None: + class_names = check_array( + class_names, ensure_2d=False, dtype=None, ensure_min_samples=0 + ) + + check_is_fitted(decision_tree) + tree_ = decision_tree.tree_ + if is_classifier(decision_tree): + if class_names is None: + class_names = decision_tree.classes_ + elif len(class_names) != len(decision_tree.classes_): + raise ValueError( + "When `class_names` is an array, it should contain as" + " many items as `decision_tree.classes_`. Got" + f" {len(class_names)} while the tree was fitted with" + f" {len(decision_tree.classes_)} classes." + ) + right_child_fmt = "{} {} <= {}\n" + left_child_fmt = "{} {} > {}\n" + truncation_fmt = "{} {}\n" + + if feature_names is not None and len(feature_names) != tree_.n_features: + raise ValueError( + "feature_names must contain %d elements, got %d" + % (tree_.n_features, len(feature_names)) + ) + + if isinstance(decision_tree, DecisionTreeClassifier): + value_fmt = "{}{} weights: {}\n" + if not show_weights: + value_fmt = "{}{}{}\n" + else: + value_fmt = "{}{} value: {}\n" + + if feature_names is not None: + feature_names_ = [ + feature_names[i] if i != _tree.TREE_UNDEFINED else None + for i in tree_.feature + ] + else: + feature_names_ = ["feature_{}".format(i) for i in tree_.feature] + + export_text.report = "" + + def _add_leaf(value, weighted_n_node_samples, class_name, indent): + val = "" + if isinstance(decision_tree, DecisionTreeClassifier): + if show_weights: + val = [ + "{1:.{0}f}, ".format(decimals, v * weighted_n_node_samples) + for v in value + ] + val = "[" + "".join(val)[:-2] + "]" + weighted_n_node_samples + val += " class: " + str(class_name) + else: + val = ["{1:.{0}f}, ".format(decimals, v) for v in value] + val = "[" + "".join(val)[:-2] + "]" + export_text.report += value_fmt.format(indent, "", val) + + def print_tree_recurse(node, depth): + indent = ("|" + (" " * spacing)) * depth + indent = indent[:-spacing] + "-" * spacing + + value = None + if tree_.n_outputs == 1: + value = tree_.value[node][0] + else: + value = tree_.value[node].T[0] + class_name = np.argmax(value) + + if tree_.n_classes[0] != 1 and tree_.n_outputs == 1: + class_name = class_names[class_name] + + weighted_n_node_samples = tree_.weighted_n_node_samples[node] + + if depth <= max_depth + 1: + info_fmt = "" + info_fmt_left = info_fmt + info_fmt_right = info_fmt + + if tree_.feature[node] != _tree.TREE_UNDEFINED: + name = feature_names_[node] + threshold = tree_.threshold[node] + threshold = "{1:.{0}f}".format(decimals, threshold) + export_text.report += right_child_fmt.format(indent, name, threshold) + export_text.report += info_fmt_left + print_tree_recurse(tree_.children_left[node], depth + 1) + + export_text.report += left_child_fmt.format(indent, name, threshold) + export_text.report += info_fmt_right + print_tree_recurse(tree_.children_right[node], depth + 1) + else: # leaf + _add_leaf(value, weighted_n_node_samples, class_name, indent) + else: + subtree_depth = _compute_depth(tree_, node) + if subtree_depth == 1: + _add_leaf(value, weighted_n_node_samples, class_name, indent) + else: + trunc_report = "truncated branch of depth %d" % subtree_depth + export_text.report += truncation_fmt.format(indent, trunc_report) + + print_tree_recurse(0, 1) + return export_text.report diff --git a/shared/package-files/06/067e087be4dbc1d7b660bf5ced76fe9d4bbf52ccbab2f01a82d0225c36e966a8/test_parfors.py b/shared/package-files/06/067e087be4dbc1d7b660bf5ced76fe9d4bbf52ccbab2f01a82d0225c36e966a8/test_parfors.py new file mode 100644 index 0000000000000000000000000000000000000000..cfda6ed6b44142ce875e47afbefae3aac45aec7d --- /dev/null +++ b/shared/package-files/06/067e087be4dbc1d7b660bf5ced76fe9d4bbf52ccbab2f01a82d0225c36e966a8/test_parfors.py @@ -0,0 +1,4978 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + + +import math +import os +import re +import dis +import numbers +import platform +import sys +import subprocess +import types as pytypes +import warnings +from functools import reduce +import numpy as np +from numpy.random import randn +import operator +from collections import defaultdict, namedtuple +import copy +from itertools import cycle, chain +import subprocess as subp + +import numba.parfors.parfor +from numba import (njit, prange, parallel_chunksize, + get_parallel_chunksize, set_parallel_chunksize, + set_num_threads, get_num_threads, typeof) +from numba.core import (types, errors, ir, rewrites, + typed_passes, inline_closurecall, config, compiler, cpu) +from numba.typed import Dict, List + +from numba.extending import (overload_method, register_model, + typeof_impl, unbox, NativeValue, models) +from numba.core.registry import cpu_target +from numba.core.annotations import type_annotations +from numba.core.ir_utils import (find_callname, guard, build_definitions, + get_definition, is_getitem, is_setitem, + index_var_of_get_setitem) +from numba.np.unsafe.ndarray import empty_inferred as unsafe_empty +from numba.core.compiler import (CompilerBase, DefaultPassBuilder) +from numba.core.compiler_machinery import register_pass, AnalysisPass +from numba.core.typed_passes import IRLegalization +from numba.tests.support import (TestCase, captured_stdout, MemoryLeakMixin, + override_env_config, linux_only, tag, + skip_parfors_unsupported, _32bit, needs_blas, + needs_lapack, disabled_test, skip_unless_scipy, + needs_subprocess, + skip_ppc64le_invalid_ctr_loop) +from numba.core.extending import register_jitable +from numba.core.bytecode import _fix_LOAD_GLOBAL_arg +from numba.core import utils + +import cmath +import unittest + +# NOTE: Each parfors test class is run in separate subprocess, this is to reduce +# memory pressure in CI settings. The environment variable "SUBPROC_TEST" is +# used to determine whether a test is skipped or not, such that if you want to +# run any parfors test directly this environment variable can be set. The +# subprocesses running the test classes set this environment variable as the new +# process starts which enables the tests within the process. The decorator +# @needs_subprocess is used to ensure the appropriate test skips are made. + + +@skip_parfors_unsupported +class TestParforsRunner(TestCase): + + _numba_parallel_test_ = False + + # Each test class can run for 30 minutes before time out. Extend this to an + # hour on aarch64 (some public CI systems were timing out). + _TIMEOUT = 1800 if platform.machine() != 'aarch64' else 3600 + + """This is the test runner for all the parfors tests, it runs them in + subprocesses as described above. The convention for the test method naming + is: `test_` where is the name of the test class in + this module. + """ + def runner(self): + themod = self.__module__ + test_clazz_name = self.id().split('.')[-1].split('_')[-1] + # don't specify a given test, it's an entire class that needs running + self.subprocess_test_runner(test_module=themod, + test_class=test_clazz_name, + timeout=self._TIMEOUT) + + def test_TestParforBasic(self): + self.runner() + + def test_TestParforNumericalMisc(self): + self.runner() + + def test_TestParforNumPy(self): + self.runner() + + def test_TestParfors(self): + self.runner() + + def test_TestParforsBitMask(self): + self.runner() + + def test_TestParforsDiagnostics(self): + self.runner() + + def test_TestParforsLeaks(self): + self.runner() + + def test_TestParforsMisc(self): + self.runner() + + def test_TestParforsOptions(self): + self.runner() + + def test_TestParforsSlice(self): + self.runner() + + def test_TestParforsVectorizer(self): + self.runner() + + def test_TestPrangeBasic(self): + self.runner() + + def test_TestPrangeSpecific(self): + self.runner() + + +x86_only = unittest.skipIf(platform.machine() not in ('i386', 'x86_64'), 'x86 only test') + +_GLOBAL_INT_FOR_TESTING1 = 17 +_GLOBAL_INT_FOR_TESTING2 = 5 + +TestNamedTuple = namedtuple('TestNamedTuple', ('part0', 'part1')) + + +def null_comparer(a, b): + """ + Used with check_arq_equality to indicate that we do not care + whether the value of the parameter at the end of the function + has a particular value. + """ + pass + + +@needs_subprocess +class TestParforsBase(TestCase): + """ + Base class for testing parfors. + Provides functions for compilation and three way comparison between + python functions, njit'd functions and parfor njit'd functions. + """ + + _numba_parallel_test_ = False + + def _compile_this(self, func, sig, **flags): + # This method originally used `compile_isolated` which returns a + # "CompileResult", hence this does the same. + return njit(sig, **flags)(func).overloads[sig] + + def compile_parallel(self, func, sig): + return self._compile_this(func, sig, parallel=True) + + def compile_parallel_fastmath(self, func, sig): + return self._compile_this(func, sig, parallel=True, fastmath=True) + + def compile_njit(self, func, sig): + return self._compile_this(func, sig) + + def compile_all(self, pyfunc, *args, **kwargs): + sig = tuple([numba.typeof(x) for x in args]) + + # compile the prange injected function + cpfunc = self.compile_parallel(pyfunc, sig) + + # compile a standard njit of the original function + cfunc = self.compile_njit(pyfunc, sig) + + return cfunc, cpfunc + + def check_parfors_vs_others(self, pyfunc, cfunc, cpfunc, *args, **kwargs): + """ + Checks python, njit and parfor impls produce the same result. + + Arguments: + pyfunc - the python function to test + cfunc - CompilerResult from njit of pyfunc + cpfunc - CompilerResult from njit(parallel=True) of pyfunc + args - arguments for the function being tested + Keyword Arguments: + scheduler_type - 'signed', 'unsigned' or None, default is None. + Supply in cases where the presence of a specific + scheduler is to be asserted. + fastmath_pcres - a fastmath parallel compile result, if supplied + will be run to make sure the result is correct + check_arg_equality - some functions need to check that a + parameter is modified rather than a certain + value returned. If this keyword argument + is supplied, it should be a list of + comparison functions such that the i'th + function in the list is used to compare the + i'th parameter of the njit and parallel=True + functions against the i'th parameter of the + standard Python function, asserting if they + differ. The length of this list must be equal + to the number of parameters to the function. + The null comparator is available for use + when you do not desire to test if some + particular parameter is changed. + Remaining kwargs are passed to np.testing.assert_almost_equal + """ + scheduler_type = kwargs.pop('scheduler_type', None) + check_fastmath = kwargs.pop('check_fastmath', None) + fastmath_pcres = kwargs.pop('fastmath_pcres', None) + check_scheduling = kwargs.pop('check_scheduling', True) + check_args_for_equality = kwargs.pop('check_arg_equality', None) + + def copy_args(*args): + if not args: + return tuple() + new_args = [] + for x in args: + if isinstance(x, np.ndarray): + new_args.append(x.copy('k')) + elif isinstance(x, np.number): + new_args.append(x.copy()) + elif isinstance(x, numbers.Number): + new_args.append(x) + elif x is None: + new_args.append(x) + elif isinstance(x, tuple): + new_args.append(copy.deepcopy(x)) + elif isinstance(x, list): + new_args.append(x[:]) + elif isinstance(x, Dict): + new_args.append(copy.copy(x)) + elif isinstance(x, List): + new_args.append(copy.copy(x)) + else: + raise ValueError('Unsupported argument type encountered') + return tuple(new_args) + + # python result + py_args = copy_args(*args) + py_expected = pyfunc(*py_args) + + # njit result + njit_args = copy_args(*args) + njit_output = cfunc.entry_point(*njit_args) + + # parfor result + parfor_args = copy_args(*args) + parfor_output = cpfunc.entry_point(*parfor_args) + + if check_args_for_equality is None: + np.testing.assert_almost_equal(njit_output, py_expected, **kwargs) + np.testing.assert_almost_equal(parfor_output, py_expected, **kwargs) + self.assertEqual(type(njit_output), type(parfor_output)) + else: + assert(len(py_args) == len(check_args_for_equality)) + for pyarg, njitarg, parforarg, argcomp in zip( + py_args, njit_args, parfor_args, check_args_for_equality): + argcomp(njitarg, pyarg, **kwargs) + argcomp(parforarg, pyarg, **kwargs) + + if check_scheduling: + self.check_scheduling(cpfunc, scheduler_type) + + # if requested check fastmath variant + if fastmath_pcres is not None: + parfor_fastmath_output = fastmath_pcres.entry_point(*copy_args(*args)) + np.testing.assert_almost_equal(parfor_fastmath_output, py_expected, + **kwargs) + + def check(self, pyfunc, *args, **kwargs): + """Checks that pyfunc compiles for *args under parallel=True and njit + and asserts that all version execute and produce the same result""" + cfunc, cpfunc = self.compile_all(pyfunc, *args) + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + + def check_variants(self, impl, arg_gen, **kwargs): + """Run self.check(impl, ...) on array data generated from arg_gen. + """ + for args in arg_gen(): + with self.subTest(list(map(typeof, args))): + self.check(impl, *args, **kwargs) + + def count_parfors_variants(self, impl, arg_gen, **kwargs): + """Run self.countParfors(impl, ...) on array types generated from + arg_gen. + """ + for args in arg_gen(): + with self.subTest(list(map(typeof, args))): + argtys = tuple(map(typeof, args)) + # At least one parfors + self.assertGreaterEqual(countParfors(impl, argtys), 1) + + def check_scheduling(self, cres, scheduler_type): + # make sure parfor set up scheduling + scheduler_str = '@do_scheduling' + if scheduler_type is not None: + if scheduler_type in ['signed', 'unsigned']: + scheduler_str += '_' + scheduler_type + else: + msg = "Unknown scheduler_type specified: %s" + raise ValueError(msg % scheduler_type) + + self.assertIn(scheduler_str, cres.library.get_llvm_str()) + + def gen_linspace(self, n, ct): + """Make *ct* sample 1D arrays of length *n* using np.linspace(). + """ + def gen(): + yield np.linspace(0, 1, n) + yield np.linspace(2, 1, n) + yield np.linspace(1, 2, n) + + src = cycle(gen()) + return [next(src) for i in range(ct)] + + def gen_linspace_variants(self, ct): + """Make 1D, 2D, 3D variants of the data in C and F orders + """ + # 1D + yield self.gen_linspace(10, ct=ct) + + # 2D + arr2ds = [x.reshape((2, 3)) + for x in self.gen_linspace(n=2 * 3, ct=ct)] + yield arr2ds + # Fortran order + yield [np.asfortranarray(x) for x in arr2ds] + + # 3D + arr3ds = [x.reshape((2, 3, 4)) + for x in self.gen_linspace(n=2 * 3 * 4, ct=ct)] + yield arr3ds + # Fortran order + yield [np.asfortranarray(x) for x in arr3ds] + + def _filter_mod(self, mod, magicstr, checkstr=None): + """ helper function to filter out modules by name""" + filt = [x for x in mod if magicstr in x.name] + if checkstr is not None: + for x in filt: + assert checkstr in str(x) + return filt + + def _get_gufunc_modules(self, cres, magicstr, checkstr=None): + """ gets the gufunc LLVM Modules""" + _modules = [x for x in cres.library._codegen._engine._ee._modules] + # make sure to only use modules that are actually used by cres and + # aren't just in the EE by virtue of shared compilation context. + potential_matches = self._filter_mod(_modules, magicstr, + checkstr=checkstr) + + lib_asm = cres.library.get_asm_str() + ret = [] + for mod in potential_matches: + if mod.name in lib_asm: + ret.append(mod) + return ret + + def _get_gufunc_info(self, cres, fn): + """ helper for gufunc IR/asm generation""" + # get the gufunc modules + magicstr = '__numba_parfor_gufunc' + gufunc_mods = self._get_gufunc_modules(cres, magicstr) + x = dict() + for mod in gufunc_mods: + x[mod.name] = fn(mod) + return x + + def _get_gufunc_ir(self, cres): + """ + Returns the IR of the gufuncs used as parfor kernels + as a dict mapping the gufunc name to its IR. + + Arguments: + cres - a CompileResult from `njit(parallel=True, ...)` + """ + return self._get_gufunc_info(cres, str) + + def _get_gufunc_asm(self, cres): + """ + Returns the assembly of the gufuncs used as parfor kernels + as a dict mapping the gufunc name to its assembly. + + Arguments: + cres - a CompileResult from `njit(parallel=True, ...)` + """ + tm = cres.library._codegen._tm + def emit_asm(mod): + return str(tm.emit_assembly(mod)) + return self._get_gufunc_info(cres, emit_asm) + + def assert_fastmath(self, pyfunc, sig): + """ + Asserts that the fastmath flag has some effect in that suitable + instructions are now labelled as `fast`. Whether LLVM can actually do + anything to optimise better now the derestrictions are supplied is + another matter! + + Arguments: + pyfunc - a function that contains operations with parallel semantics + sig - the type signature of pyfunc + """ + + cres = self.compile_parallel_fastmath(pyfunc, sig) + _ir = self._get_gufunc_ir(cres) + + def _get_fast_instructions(ir): + splitted = ir.splitlines() + fast_inst = [] + for x in splitted: + m = re.search(r'\bfast\b', x) # \b for wholeword + if m is not None: + fast_inst.append(x) + return fast_inst + + def _assert_fast(instrs): + ops = ('fadd', 'fsub', 'fmul', 'fdiv', 'frem', 'fcmp', 'call') + for inst in instrs: + count = 0 + for op in ops: + match = op + ' fast' + if match in inst: + count += 1 + self.assertTrue(count > 0) + + for name, guir in _ir.items(): + inst = _get_fast_instructions(guir) + _assert_fast(inst) + + +def blackscholes_impl(sptprice, strike, rate, volatility, timev): + # blackscholes example + logterm = np.log(sptprice / strike) + powterm = 0.5 * volatility * volatility + den = volatility * np.sqrt(timev) + d1 = (((rate + powterm) * timev) + logterm) / den + d2 = d1 - den + NofXd1 = 0.5 + 0.5 * 2.0 * d1 + NofXd2 = 0.5 + 0.5 * 2.0 * d2 + futureValue = strike * np.exp(- rate * timev) + c1 = futureValue * NofXd2 + call = sptprice * NofXd1 - c1 + put = call - futureValue + sptprice + return put + + +def lr_impl(Y, X, w, iterations): + # logistic regression example + for i in range(iterations): + w -= np.dot(((1.0 / (1.0 + np.exp(-Y * np.dot(X, w))) - 1.0) * Y), X) + return w + +def example_kmeans_test(A, numCenter, numIter, init_centroids): + centroids = init_centroids + N, D = A.shape + + for l in range(numIter): + dist = np.array([[math.sqrt(np.sum((A[i,:]-centroids[j,:])**2)) + for j in range(numCenter)] for i in range(N)]) + labels = np.array([dist[i,:].argmin() for i in range(N)]) + + centroids = np.array([[np.sum(A[labels==i, j])/np.sum(labels==i) + for j in range(D)] for i in range(numCenter)]) + + return centroids + +def get_optimized_numba_ir(test_func, args, **kws): + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + test_ir = compiler.run_frontend(test_func) + if kws: + options = cpu.ParallelOptions(kws) + else: + options = cpu.ParallelOptions(True) + + tp = TestPipeline(typingctx, targetctx, args, test_ir) + + typingctx.refresh() + targetctx.refresh() + + inline_pass = inline_closurecall.InlineClosureCallPass(tp.state.func_ir, + options, + typed=True) + inline_pass.run() + + rewrites.rewrite_registry.apply('before-inference', tp.state) + + tp.state.typemap, tp.state.return_type, tp.state.calltypes, _ = \ + typed_passes.type_inference_stage(tp.state.typingctx, + tp.state.targetctx, tp.state.func_ir, tp.state.args, None) + + type_annotations.TypeAnnotation( + func_ir=tp.state.func_ir, + typemap=tp.state.typemap, + calltypes=tp.state.calltypes, + lifted=(), + lifted_from=None, + args=tp.state.args, + return_type=tp.state.return_type, + html_output=config.HTML) + + diagnostics = numba.parfors.parfor.ParforDiagnostics() + + preparfor_pass = numba.parfors.parfor.PreParforPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.typingctx, tp.state.targetctx, options, + swapped=diagnostics.replaced_fns) + preparfor_pass.run() + + rewrites.rewrite_registry.apply('after-inference', tp.state) + + flags = compiler.Flags() + parfor_pass = numba.parfors.parfor.ParforPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.return_type, tp.state.typingctx, tp.state.targetctx, + options, flags, tp.state.metadata, diagnostics=diagnostics) + parfor_pass.run() + parfor_pass = numba.parfors.parfor.ParforFusionPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.return_type, tp.state.typingctx, tp.state.targetctx, + options, flags, tp.state.metadata, diagnostics=diagnostics) + parfor_pass.run() + parfor_pass = numba.parfors.parfor.ParforPreLoweringPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.return_type, tp.state.typingctx, tp.state.targetctx, + options, flags, tp.state.metadata, diagnostics=diagnostics) + parfor_pass.run() + test_ir._definitions = build_definitions(test_ir.blocks) + + return test_ir, tp + +def countParfors(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + ret_count = 0 + + for label, block in test_ir.blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, numba.parfors.parfor.Parfor): + ret_count += 1 + + return ret_count + + +def countArrays(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + return _count_arrays_inner(test_ir.blocks, tp.state.typemap) + +def get_init_block_size(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + blocks = test_ir.blocks + + ret_count = 0 + + for label, block in blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, numba.parfors.parfor.Parfor): + ret_count += len(inst.init_block.body) + + return ret_count + +def _count_arrays_inner(blocks, typemap): + ret_count = 0 + arr_set = set() + + for label, block in blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, numba.parfors.parfor.Parfor): + parfor_blocks = inst.loop_body.copy() + parfor_blocks[0] = inst.init_block + ret_count += _count_arrays_inner(parfor_blocks, typemap) + if (isinstance(inst, ir.Assign) + and isinstance(typemap[inst.target.name], + types.ArrayCompatible)): + arr_set.add(inst.target.name) + + ret_count += len(arr_set) + return ret_count + +def countArrayAllocs(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + ret_count = 0 + + for block in test_ir.blocks.values(): + ret_count += _count_array_allocs_inner(test_ir, block) + + return ret_count + +def _count_array_allocs_inner(func_ir, block): + ret_count = 0 + for inst in block.body: + if isinstance(inst, numba.parfors.parfor.Parfor): + ret_count += _count_array_allocs_inner(func_ir, inst.init_block) + for b in inst.loop_body.values(): + ret_count += _count_array_allocs_inner(func_ir, b) + + if (isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and (guard(find_callname, func_ir, inst.value) == ('empty', 'numpy') + or guard(find_callname, func_ir, inst.value) + == ('empty_inferred', 'numba.np.unsafe.ndarray'))): + ret_count += 1 + + return ret_count + +def countNonParforArrayAccesses(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + return _count_non_parfor_array_accesses_inner(test_ir, test_ir.blocks, + tp.state.typemap) + +def _count_non_parfor_array_accesses_inner(f_ir, blocks, typemap, parfor_indices=None): + ret_count = 0 + if parfor_indices is None: + parfor_indices = set() + + for label, block in blocks.items(): + for stmt in block.body: + if isinstance(stmt, numba.parfors.parfor.Parfor): + parfor_indices.add(stmt.index_var.name) + parfor_blocks = stmt.loop_body.copy() + parfor_blocks[0] = stmt.init_block + ret_count += _count_non_parfor_array_accesses_inner( + f_ir, parfor_blocks, typemap, parfor_indices) + + # getitem + elif (is_getitem(stmt) and isinstance(typemap[stmt.value.value.name], + types.ArrayCompatible) and not _uses_indices( + f_ir, index_var_of_get_setitem(stmt), parfor_indices)): + ret_count += 1 + + # setitem + elif (is_setitem(stmt) and isinstance(typemap[stmt.target.name], + types.ArrayCompatible) and not _uses_indices( + f_ir, index_var_of_get_setitem(stmt), parfor_indices)): + ret_count += 1 + + # find parfor_index aliases + elif (isinstance(stmt, ir.Assign) and + isinstance(stmt.value, ir.Var) and + stmt.value.name in parfor_indices): + parfor_indices.add(stmt.target.name) + + return ret_count + +def _uses_indices(f_ir, index, index_set): + if index.name in index_set: + return True + + ind_def = guard(get_definition, f_ir, index) + if isinstance(ind_def, ir.Expr) and ind_def.op == 'build_tuple': + varnames = set(v.name for v in ind_def.items) + return len(varnames & index_set) != 0 + + return False + + +class TestPipeline(object): + def __init__(self, typingctx, targetctx, args, test_ir): + self.state = compiler.StateDict() + self.state.typingctx = typingctx + self.state.targetctx = targetctx + self.state.args = args + self.state.func_ir = test_ir + self.state.typemap = None + self.state.return_type = None + self.state.calltypes = None + self.state.metadata = {} + + +@skip_parfors_unsupported +class TestParforBasic(TestParforsBase): + """Smoke tests for the parfors transforms. These tests check the most basic + functionality""" + + def __init__(self, *args): + TestParforsBase.__init__(self, *args) + # these are used in the mass of simple tests + m = np.reshape(np.arange(12.), (3, 4)) + self.simple_args = [np.arange(3.), np.arange(4.), m, m.T] + + def test_simple01(self): + def test_impl(): + return np.ones(()) + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_simple02(self): + def test_impl(): + return np.ones((1,)) + self.check(test_impl) + + def test_simple03(self): + def test_impl(): + return np.ones((1, 2)) + self.check(test_impl) + + def test_simple04(self): + def test_impl(): + return np.ones(1) + self.check(test_impl) + + def test_simple07(self): + def test_impl(): + return np.ones((1, 2), dtype=np.complex128) + self.check(test_impl) + + def test_simple08(self): + def test_impl(): + return np.ones((1, 2)) + np.ones((1, 2)) + self.check(test_impl) + + def test_simple09(self): + def test_impl(): + return np.ones((1, 1)) + self.check(test_impl) + + def test_simple10(self): + def test_impl(): + return np.ones((0, 0)) + self.check(test_impl) + + def test_simple11(self): + def test_impl(): + return np.ones((10, 10)) + 1. + self.check(test_impl) + + def test_simple12(self): + def test_impl(): + return np.ones((10, 10)) + np.complex128(1.) + self.check(test_impl) + + def test_simple13(self): + def test_impl(): + return np.complex128(1.) + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_simple14(self): + def test_impl(): + return np.ones((10, 10))[0::20] + self.check(test_impl) + + def test_simple15(self): + def test_impl(v1, v2, m1, m2): + return v1 + v1 + self.check(test_impl, *self.simple_args) + + def test_simple16(self): + def test_impl(v1, v2, m1, m2): + return m1 + m1 + self.check(test_impl, *self.simple_args) + + def test_simple17(self): + def test_impl(v1, v2, m1, m2): + return m2 + v1 + self.check(test_impl, *self.simple_args) + + @needs_lapack + def test_simple18(self): + def test_impl(v1, v2, m1, m2): + return m1.T + np.linalg.svd(m2)[1] + self.check(test_impl, *self.simple_args) + + @needs_blas + def test_simple19(self): + def test_impl(v1, v2, m1, m2): + return np.dot(m1, v2) + self.check(test_impl, *self.simple_args) + + @needs_blas + def test_simple20(self): + def test_impl(v1, v2, m1, m2): + return np.dot(m1, m2) + # gemm is left to BLAS + with self.assertRaises(AssertionError) as raises: + self.check(test_impl, *self.simple_args) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + @needs_blas + def test_simple21(self): + def test_impl(v1, v2, m1, m2): + return np.dot(v1, v1) + self.check(test_impl, *self.simple_args) + + def test_simple22(self): + def test_impl(v1, v2, m1, m2): + return np.sum(v1 + v1) + self.check(test_impl, *self.simple_args) + + def test_simple23(self): + def test_impl(v1, v2, m1, m2): + x = 2 * v1 + y = 2 * v1 + return 4 * np.sum(x**2 + y**2 < 1) / 10 + self.check(test_impl, *self.simple_args) + + def test_simple24(self): + def test_impl(): + n = 20 + A = np.ones((n, n)) + b = np.arange(n) + return np.sum(A[:, b]) + self.check(test_impl) + + @disabled_test + def test_simple_operator_15(self): + """same as corresponding test_simple_ case but using operator.add""" + def test_impl(v1, v2, m1, m2): + return operator.add(v1, v1) + + self.check(test_impl, *self.simple_args) + + @disabled_test + def test_simple_operator_16(self): + def test_impl(v1, v2, m1, m2): + return operator.add(m1, m1) + + self.check(test_impl, *self.simple_args) + + @disabled_test + def test_simple_operator_17(self): + def test_impl(v1, v2, m1, m2): + return operator.add(m2, v1) + + self.check(test_impl, *self.simple_args) + + def test_inplace_alias(self): + # issue7201 + def test_impl(a): + a += 1 + a[:] = 3 + + def comparer(a, b): + np.testing.assert_equal(a, b) + + x = np.ones(1) + self.check(test_impl, x, check_arg_equality=[comparer]) + + +@skip_parfors_unsupported +class TestParforNumericalMisc(TestParforsBase): + """ Miscellaneous 'classical' numerical tests """ + + def test_pi(self): + def test_impl(n): + x = 2 * np.random.ranf(n) - 1 + y = 2 * np.random.ranf(n) - 1 + return 4 * np.sum(x**2 + y**2 < 1) / n + + self.check(test_impl, 100000, decimal=1) + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + self.assertEqual(countArrays(test_impl, (types.intp,)), 0) + + def test_blackscholes(self): + # blackscholes takes 5 1D float array args + args = (numba.float64[:], ) * 5 + self.assertEqual(countParfors(blackscholes_impl, args), 1) + + @needs_blas + def test_logistic_regression(self): + args = (numba.float64[:], numba.float64[:,:], numba.float64[:], + numba.int64) + self.assertEqual(countParfors(lr_impl, args), 2) + self.assertEqual(countArrayAllocs(lr_impl, args), 1) + + def test_kmeans(self): + np.random.seed(0) + N = 1024 + D = 10 + centers = 3 + A = np.random.ranf((N, D)) + init_centroids = np.random.ranf((centers, D)) + self.check(example_kmeans_test, A, centers, 3, init_centroids, + decimal=1) + # TODO: count parfors after k-means fusion is working + # requires recursive parfor counting + arg_typs = (types.Array(types.float64, 2, 'C'), types.intp, types.intp, + types.Array(types.float64, 2, 'C')) + self.assertEqual( + countNonParforArrayAccesses(example_kmeans_test, arg_typs), 0) + + +@skip_parfors_unsupported +class TestParforNumPy(TestParforsBase): + """Tests NumPy functionality under parfors""" + + @needs_blas + def test_mvdot(self): + def test_impl(a, v): + return np.dot(a, v) + + A = np.linspace(0, 1, 20).reshape(2, 10) + v = np.linspace(2, 1, 10) + + self.check(test_impl, A, v) + + def test_fuse_argmin_argmax_max_min(self): + for op in [np.argmin, np.argmax, np.min, np.max]: + def test_impl(n): + A = np.ones(n) + C = op(A) + B = A.sum() + return B + C + self.check(test_impl, 256) + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + self.assertEqual(countArrays(test_impl, (types.intp,)), 0) + + def test_np_random_func_direct_import(self): + def test_impl(n): + A = randn(n) + return A[0] + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + + def test_arange(self): + # test with stop only + def test_impl1(n): + return np.arange(n) + # start and stop + def test_impl2(s, n): + return np.arange(s, n) + # start, step, stop + def test_impl3(s, n, t): + return np.arange(s, n, t) + + for arg in [11, 128, 30.0, complex(4,5), complex(5,4)]: + self.check(test_impl1, arg) + self.check(test_impl2, 2, arg) + self.check(test_impl3, 2, arg, 2) + + def test_arange_dtype(self): + # test with stop only + def test_impl1(n): + return np.arange(n, dtype=np.float32) + # start and stop + def test_impl2(s, n): + return np.arange(s, n, dtype=np.float32) + # start, step, stop + def test_impl3(s, n, t): + return np.arange(s, n, t, dtype=np.float32) + + for arg in [11, 128, 30.0]: + self.check(test_impl1, arg) + self.check(test_impl2, 2, arg) + self.check(test_impl3, 2, arg, 2) + + def test_linspace(self): + # without num + def test_impl1(start, stop): + return np.linspace(start, stop) + # with num + def test_impl2(start, stop, num): + return np.linspace(start, stop, num) + + for arg in [11, 128, 30.0, complex(4,5), complex(5,4)]: + self.check(test_impl1, 2, arg) + self.check(test_impl2, 2, arg, 30) + + def test_mean(self): + def test_impl(A): + return A.mean() + N = 100 + A = np.random.ranf(N) + B = np.random.randint(10, size=(N, 3)) + self.check(test_impl, A) + self.check(test_impl, B) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 1, 'C'), )), 1) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 2, 'C'), )), 1) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_var(self): + def test_impl(A): + return A.var() + N = 100 + A = np.random.ranf(N) + B = np.random.randint(10, size=(N, 3)) + C = A + 1j * A + self.check(test_impl, A) + self.check(test_impl, B) + self.check(test_impl, C) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 1, 'C'), )), 2) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 2, 'C'), )), 2) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_std(self): + def test_impl(A): + return A.std() + N = 100 + A = np.random.ranf(N) + B = np.random.randint(10, size=(N, 3)) + C = A + 1j * A + self.check(test_impl, A) + self.check(test_impl, B) + self.check(test_impl, C) + argty = (types.Array(types.float64, 1, 'C'),) + self.assertEqual(countParfors(test_impl, argty), 2) + self.assertEqual(countParfors(test_impl, argty), 2) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_random_parfor(self): + """ + Test function with only a random call to make sure a random function + like ranf is actually translated to a parfor. + """ + def test_impl(n): + A = np.random.ranf((n, n)) + return A + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + + def test_randoms(self): + def test_impl(n): + A = np.random.standard_normal(size=(n, n)) + B = np.random.randn(n, n) + C = np.random.normal(0.0, 1.0, (n, n)) + D = np.random.chisquare(1.0, (n, n)) + E = np.random.randint(1, high=3, size=(n, n)) + F = np.random.triangular(1, 2, 3, (n, n)) + return np.sum(A+B+C+D+E+F) + + n = 128 + cpfunc = self.compile_parallel(test_impl, (numba.typeof(n),)) + parfor_output = cpfunc.entry_point(n) + py_output = test_impl(n) + # check results within 5% since random numbers generated in parallel + np.testing.assert_allclose(parfor_output, py_output, rtol=0.05) + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + + def test_dead_randoms(self): + def test_impl(n): + A = np.random.standard_normal(size=(n, n)) + B = np.random.randn(n, n) + C = np.random.normal(0.0, 1.0, (n, n)) + D = np.random.chisquare(1.0, (n, n)) + E = np.random.randint(1, high=3, size=(n, n)) + F = np.random.triangular(1, 2, 3, (n, n)) + return 3 + + n = 128 + cpfunc = self.compile_parallel(test_impl, (numba.typeof(n),)) + parfor_output = cpfunc.entry_point(n) + py_output = test_impl(n) + self.assertEqual(parfor_output, py_output) + self.assertEqual(countParfors(test_impl, (types.int64, )), 0) + + def test_min(self): + def test_impl1(A): + return A.min() + + def test_impl2(A): + return np.min(A) + + n = 211 + A = np.random.ranf(n) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([np.inf, np.inf]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = ("zero-size array to reduction operation " + "minimum which has no identity") + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_max(self): + def test_impl1(A): + return A.max() + + def test_impl2(A): + return np.max(A) + + n = 211 + A = np.random.ranf(n) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([-np.inf, -np.inf]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = ("zero-size array to reduction operation " + "maximum which has no identity") + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_argmax(self): + def test_impl1(A): + return A.argmax() + + def test_impl2(A): + return np.argmax(A) + + n = 211 + A = np.array([1., 0., 3., 2., 3.]) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([1., 0., np.nan, 2., 3.]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = 'attempt to get argmax of an empty sequence' + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_argmin(self): + def test_impl1(A): + return A.argmin() + + def test_impl2(A): + return np.argmin(A) + + n = 211 + A = np.array([1., 0., 2., 0., 3.]) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([1., 0., np.nan, 0., 3.]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = 'attempt to get argmin of an empty sequence' + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_ndarray_fill(self): + def test_impl(x): + x.fill(7.0) + return x + x = np.zeros(10) + self.check(test_impl, x) + argty = (types.Array(types.float64, 1, 'C'),) + self.assertEqual(countParfors(test_impl, argty), 1) + + def test_ndarray_fill2d(self): + def test_impl(x): + x.fill(7.0) + return x + x = np.zeros((2,2)) + self.check(test_impl, x) + argty = (types.Array(types.float64, 2, 'C'),) + self.assertEqual(countParfors(test_impl, argty), 1) + + def test_reshape_with_neg_one(self): + # issue3314 + def test_impl(a, b): + result_matrix = np.zeros((b, b, 1), dtype=np.float64) + sub_a = a[0:b] + a = sub_a.size + b = a / 1 + z = sub_a.reshape(-1, 1) + result_data = sub_a / z + result_matrix[:,:,0] = result_data + return result_matrix + + a = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]) + b = 3 + + self.check(test_impl, a, b) + + def test_reshape_with_large_neg(self): + # issue3314 + def test_impl(a, b): + result_matrix = np.zeros((b, b, 1), dtype=np.float64) + sub_a = a[0:b] + a = sub_a.size + b = a / 1 + z = sub_a.reshape(-1307, 1) + result_data = sub_a / z + result_matrix[:,:,0] = result_data + return result_matrix + + a = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]) + b = 3 + + self.check(test_impl, a, b) + + def test_reshape_with_too_many_neg_one(self): + # issue3314 + with self.assertRaises(errors.UnsupportedRewriteError) as raised: + @njit(parallel=True) + def test_impl(a, b): + rm = np.zeros((b, b, 1), dtype=np.float64) + sub_a = a[0:b] + a = sub_a.size + b = a / 1 + z = sub_a.reshape(-1, -1) + result_data = sub_a / z + rm[:,:,0] = result_data + return rm + + a = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]) + b = 3 + test_impl(a, b) + + msg = ("The reshape API may only include one negative argument.") + self.assertIn(msg, str(raised.exception)) + + def test_0d_array(self): + def test_impl(n): + return np.sum(n) + np.prod(n) + np.min(n) + np.max(n) + np.var(n) + self.check(test_impl, np.array(7), check_scheduling=False) + + def test_real_imag_attr(self): + # See issue 8012 + def test_impl(z): + return np.sum(z.real ** 2 + z.imag ** 2) + + z = np.arange(5) * (1 + 1j) + self.check(test_impl, z) + self.assertEqual(countParfors(test_impl, (types.complex128[::1],)), 1) + + +class TestParforsUnsupported(TestCase): + """Tests for unsupported use of parfors""" + @unittest.skipIf(not _32bit, "Only impacts 32 bit hardware") + @needs_blas + def test_unsupported_combination_raises(self): + """ + This test is in place until issues with the 'parallel' + target on 32 bit hardware are fixed. + """ + with self.assertRaises(errors.UnsupportedParforsError) as raised: + @njit(parallel=True) + def ddot(a, v): + return np.dot(a, v) + + A = np.linspace(0, 1, 20).reshape(2, 10) + v = np.linspace(2, 1, 10) + ddot(A, v) + + msg = ("The 'parallel' target is not currently supported on 32 bit " + "hardware") + self.assertIn(msg, str(raised.exception)) + +@skip_parfors_unsupported +class TestParfors(TestParforsBase): + """ Tests cpython, reduction and various parfors features""" + + def test_arraymap(self): + def test_impl(a, x, y): + return a * x + y + + self.check_variants(test_impl, lambda: self.gen_linspace_variants(3)) + + def test_0d_broadcast(self): + def test_impl(): + X = np.array(1) + Y = np.ones((10, 12)) + return np.sum(X + Y) + self.check(test_impl) + self.assertEqual(countParfors(test_impl, ()), 1) + + def test_2d_parfor(self): + def test_impl(): + X = np.ones((10, 12)) + Y = np.zeros((10, 12)) + return np.sum(X + Y) + self.check(test_impl) + self.assertEqual(countParfors(test_impl, ()), 1) + + def test_nd_parfor(self): + def case1(): + X = np.ones((10, 12)) + Y = np.zeros((10, 12)) + yield (X, Y) + + data_gen = lambda: chain(case1(), self.gen_linspace_variants(2)) + + def test_impl(X, Y): + return np.sum(X + Y) + + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_np_func_direct_import(self): + from numpy import ones # import here becomes FreeVar + def test_impl(n): + A = ones(n) + return A[0] + n = 111 + self.check(test_impl, n) + + def test_size_assertion(self): + def test_impl(m, n): + A = np.ones(m) + B = np.ones(n) + return np.sum(A + B) + + self.check(test_impl, 10, 10) + with self.assertRaises(AssertionError) as raises: + cfunc = njit(parallel=True)(test_impl) + cfunc(10, 9) + msg = "Sizes of A, B do not match" + self.assertIn(msg, str(raises.exception)) + + def test_cfg(self): + # from issue #2477 + def test_impl(x, is_positive, N): + for i in numba.prange(2): + for j in range( i*N//2, (i+1)*N//2 ): + is_positive[j] = 0 + if x[j] > 0: + is_positive[j] = 1 + + return is_positive + + N = 100 + x = np.random.rand(N) + is_positive = np.zeros(N) + self.check(test_impl, x, is_positive, N) + + def test_reduce(self): + def test_impl(A): + init_val = 10 + return reduce(lambda a,b: min(a, b), A, init_val) + + n = 211 + A = np.random.ranf(n) + self.check(test_impl, A) + A = np.random.randint(10, size=n).astype(np.int32) + self.check(test_impl, A) + + # test checking the number of arguments for the reduce function + def test_impl(): + g = lambda x: x ** 2 + return reduce(g, np.array([1, 2, 3, 4, 5]), 2) + with self.assertTypingError(): + self.check(test_impl) + + # test checking reduction over bitarray masked arrays + n = 160 + A = np.random.randint(10, size=n).astype(np.int32) + def test_impl(A): + return np.sum(A[A>=3]) + self.check(test_impl, A) + # TODO: this should fuse + # self.assertTrue(countParfors(test_impl, (numba.float64[:],)) == 1) + + def test_impl(A): + B = A[:,0] + return np.sum(A[B>=3,1]) + self.check(test_impl, A.reshape((16,10))) + # TODO: this should also fuse + #self.assertTrue(countParfors(test_impl, (numba.float64[:,:],)) == 1) + + def test_impl(A): + B = A[:,0] + return np.sum(A[B>=3,1:2]) + self.check(test_impl, A.reshape((16,10))) + # this doesn't fuse due to mixed indices + self.assertEqual(countParfors(test_impl, (numba.float64[:,:],)), 2) + + def test_impl(A): + min_val = np.amin(A) + return A - min_val + self.check(test_impl, A) + # this doesn't fuse due to use of reduction variable + self.assertEqual(countParfors(test_impl, (numba.float64[:],)), 2) + + def test_use_of_reduction_var1(self): + def test_impl(): + acc = 0 + for i in prange(1): + acc = cmath.sqrt(acc) + return acc + + # checks that invalid use of reduction variable is detected + msg = ("Use of reduction variable acc in an unsupported reduction function.") + with self.assertRaises(ValueError) as e: + pcfunc = self.compile_parallel(test_impl, ()) + self.assertIn(msg, str(e.exception)) + + def test_unsupported_floordiv1(self): + def test_impl(): + acc = 100 + for i in prange(2): + acc //= 2 + return acc + + # checks that invalid use of ifloordiv reduction operator is detected + msg = ("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.") + with self.assertRaises(errors.NumbaValueError) as e: + pcfunc = self.compile_parallel(test_impl, ()) + self.assertIn(msg, str(e.exception)) + + def test_unsupported_xor1(self): + def test_impl(): + acc = 100 + for i in prange(2): + acc ^= i + 2 + return acc + + msg = ("Use of reduction variable acc in an unsupported reduction function.") + with self.assertRaises(ValueError) as e: + pcfunc = self.compile_parallel(test_impl, ()) + self.assertIn(msg, str(e.exception)) + + def test_parfor_array_access1(self): + # signed index of the prange generated by sum() should be replaced + # resulting in array A to be eliminated (see issue #2846) + def test_impl(n): + A = np.ones(n) + return A.sum() + + n = 211 + self.check(test_impl, n) + self.assertEqual(countArrays(test_impl, (types.intp,)), 0) + + def test_parfor_array_access2(self): + # in this test, the prange index has the same name (i) in two loops + # thus, i has multiple definitions and is harder to replace + def test_impl(n): + A = np.ones(n) + m = 0 + n = 0 + for i in numba.prange(len(A)): + m += A[i] + + for i in numba.prange(len(A)): + if m == n: # access in another block + n += A[i] + + return m + n + + n = 211 + self.check(test_impl, n) + self.assertEqual(countNonParforArrayAccesses(test_impl, (types.intp,)), 0) + + def test_parfor_array_access3(self): + def test_impl(n): + A = np.ones(n, np.int64) + m = 0 + for i in numba.prange(len(A)): + m += A[i] + if m==2: + i = m + + n = 211 + with self.assertRaises(errors.UnsupportedRewriteError) as raises: + self.check(test_impl, n) + self.assertIn("Overwrite of parallel loop index", str(raises.exception)) + + @needs_blas + def test_parfor_array_access4(self): + # in this test, one index of a multi-dim access should be replaced + # np.dot parallel implementation produces this case + def test_impl(A, b): + return np.dot(A, b) + + n = 211 + d = 4 + A = np.random.ranf((n, d)) + b = np.random.ranf(d) + self.check(test_impl, A, b) + # make sure the parfor index is replaced in build_tuple of access to A + test_ir, tp = get_optimized_numba_ir( + test_impl, (types.Array(types.float64, 2, 'C'), + types.Array(types.float64, 1, 'C'))) + # this code should have one basic block after optimization + self.assertTrue(len(test_ir.blocks) == 1 and 0 in test_ir.blocks) + block = test_ir.blocks[0] + parfor_found = False + parfor = None + for stmt in block.body: + if isinstance(stmt, numba.parfors.parfor.Parfor): + parfor_found = True + parfor = stmt + + self.assertTrue(parfor_found) + build_tuple_found = False + # there should be only one build_tuple + for bl in parfor.loop_body.values(): + for stmt in bl.body: + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'build_tuple'): + build_tuple_found = True + self.assertTrue(parfor.index_var in stmt.value.items) + + self.assertTrue(build_tuple_found) + + def test_parfor_dtype_type(self): + # test array type replacement creates proper type + def test_impl(a): + for i in numba.prange(len(a)): + a[i] = a.dtype.type(0) + return a[4] + + a = np.ones(10) + self.check(test_impl, a) + + def test_parfor_array_access5(self): + # one dim is slice in multi-dim access + def test_impl(n): + X = np.ones((n, 3)) + y = 0 + for i in numba.prange(n): + y += X[i,:].sum() + return y + + n = 211 + self.check(test_impl, n) + self.assertEqual(countNonParforArrayAccesses(test_impl, (types.intp,)), 0) + + @disabled_test # Test itself is problematic, see #3155 + def test_parfor_hoist_setitem(self): + # Make sure that read of out is not hoisted. + def test_impl(out): + for i in prange(10): + out[0] = 2 * out[0] + return out[0] + + out = np.ones(1) + self.check(test_impl, out) + + @needs_blas + def test_parfor_generate_fuse(self): + # issue #2857 + def test_impl(N, D): + w = np.ones(D) + X = np.ones((N, D)) + Y = np.ones(N) + for i in range(3): + B = (-Y * np.dot(X, w)) + + return B + + n = 211 + d = 3 + self.check(test_impl, n, d) + self.assertEqual(countArrayAllocs(test_impl, (types.intp, types.intp)), 4) + self.assertEqual(countParfors(test_impl, (types.intp, types.intp)), 4) + + def test_ufunc_expr(self): + # issue #2885 + def test_impl(A, B): + return np.bitwise_and(A, B) + + A = np.ones(3, np.uint8) + B = np.ones(3, np.uint8) + B[1] = 0 + self.check(test_impl, A, B) + + def test_find_callname_intrinsic(self): + def test_impl(n): + A = unsafe_empty((n,)) + for i in range(n): + A[i] = i + 2.0 + return A + + # the unsafe allocation should be found even though it is imported + # as a different name + self.assertEqual(countArrayAllocs(test_impl, (types.intp,)), 1) + + def test_reduction_var_reuse(self): + # issue #3139 + def test_impl(n): + acc = 0 + for i in prange(n): + acc += 1 + + for i in prange(n): + acc += 2 + + return acc + self.check(test_impl, 16) + + def test_non_identity_initial(self): + # issue #7344 + def test_impl(A, cond): + s = 1 + for i in prange(A.shape[0]): + if cond[i]: + s += 1 + return s + self.check(test_impl, np.ones(10), np.ones(10).astype('bool')) + + def test_if_not_else_reduction(self): + # issue #7344 + def test_impl(A, cond): + s = 1 + t = 10 + for i in prange(A.shape[0]): + if cond[i]: + s += 1 + t += 1 + else: + s += 2 + return s + t + self.check(test_impl, np.ones(10), np.ones(10).astype('bool')) + + def test_two_d_array_reduction_reuse(self): + def test_impl(n): + shp = (13, 17) + size = shp[0] * shp[1] + result1 = np.zeros(shp, np.int_) + tmp = np.arange(size).reshape(shp) + + for i in numba.prange(n): + result1 += tmp + + for i in numba.prange(n): + result1 += tmp + + return result1 + + self.check(test_impl, 100) + + def test_one_d_array_reduction(self): + def test_impl(n): + result = np.zeros(1, np.int_) + + for i in numba.prange(n): + result += np.array([i], np.int_) + + return result + + self.check(test_impl, 100) + + def test_two_d_array_reduction(self): + def test_impl(n): + shp = (13, 17) + size = shp[0] * shp[1] + result1 = np.zeros(shp, np.int_) + tmp = np.arange(size).reshape(shp) + + for i in numba.prange(n): + result1 += tmp + + return result1 + + self.check(test_impl, 100) + + def test_two_d_array_reduction_with_float_sizes(self): + # result1 is float32 and tmp is float64. + # Tests reduction with differing dtypes. + def test_impl(n): + shp = (2, 3) + result1 = np.zeros(shp, np.float32) + tmp = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).reshape(shp) + + for i in numba.prange(n): + result1 += tmp + + return result1 + + self.check(test_impl, 100) + + def test_two_d_array_reduction_prod(self): + def test_impl(n): + shp = (13, 17) + result1 = 2 * np.ones(shp, np.int_) + tmp = 2 * np.ones_like(result1) + + for i in numba.prange(n): + result1 *= tmp + + return result1 + + self.check(test_impl, 100) + + def test_three_d_array_reduction(self): + def test_impl(n): + shp = (3, 2, 7) + result1 = np.zeros(shp, np.int_) + + for i in numba.prange(n): + result1 += np.ones(shp, np.int_) + + return result1 + + self.check(test_impl, 100) + + def test_preparfor_canonicalize_kws(self): + # test canonicalize_array_math typing for calls with kw args + def test_impl(A): + return A.argsort() + 1 + + n = 211 + A = np.arange(n) + self.check(test_impl, A) + + def test_preparfor_datetime64(self): + # test array.dtype transformation for datetime64 + def test_impl(A): + return A.dtype + + A = np.empty(1, np.dtype('datetime64[ns]')) + cpfunc = self.compile_parallel(test_impl, (numba.typeof(A),)) + self.assertEqual(cpfunc.entry_point(A), test_impl(A)) + + def test_no_hoisting_with_member_function_call(self): + def test_impl(X): + n = X.shape[0] + acc = 0 + for i in prange(n): + R = {1, 2, 3} + R.add(i) + tmp = 0 + for x in R: + tmp += x + acc += tmp + return acc + + self.check(test_impl, np.random.ranf(128)) + + def test_array_compare_scalar(self): + """ issue3671: X != 0 becomes an arrayexpr with operator.ne. + That is turned into a parfor by devectorizing. Make sure + the return type of the devectorized operator.ne + on integer types works properly. + """ + def test_impl(): + X = np.zeros(10, dtype=np.int_) + return X != 0 + + self.check(test_impl) + + def test_array_analysis_optional_def(self): + def test_impl(x, half): + size = len(x) + parr = x[0:size] + + if half: + parr = x[0:size//2] + + return parr.sum() + x = np.ones(20) + self.check(test_impl, x, True, check_scheduling=False) + + def test_prange_side_effects(self): + def test_impl(a, b): + data = np.empty(len(a), dtype=np.float64) + size = len(data) + for i in numba.prange(size): + data[i] = a[i] + for i in numba.prange(size): + data[i] = data[i] + b[i] + return data + + x = np.arange(10 ** 2, dtype=float) + y = np.arange(10 ** 2, dtype=float) + + self.check(test_impl, x, y) + self.assertEqual(countParfors(test_impl, + (types.Array(types.float64, 1, 'C'), + types.Array(types.float64, 1, 'C'))), 1) + + def test_tuple1(self): + def test_impl(a): + atup = (3, 4) + b = 7 + for i in numba.prange(len(a)): + a[i] += atup[0] + atup[1] + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_tuple2(self): + def test_impl(a): + atup = a.shape + b = 7 + for i in numba.prange(len(a)): + a[i] += atup[0] + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_tuple3(self): + def test_impl(a): + atup = (np.arange(10), 4) + b = 7 + for i in numba.prange(len(a)): + a[i] += atup[0][5] + atup[1] + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_namedtuple1(self): + def test_impl(a): + antup = TestNamedTuple(part0=3, part1=4) + b = 7 + for i in numba.prange(len(a)): + a[i] += antup.part0 + antup.part1 + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_namedtuple2(self): + TestNamedTuple2 = namedtuple('TestNamedTuple2', ('part0', 'part1')) + def test_impl(a): + antup = TestNamedTuple2(part0=3, part1=4) + b = 7 + for i in numba.prange(len(a)): + a[i] += antup.part0 + antup.part1 + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_namedtuple3(self): + # issue5872: test that a.y[:] = 5 is not removed as + # deadcode. + TestNamedTuple3 = namedtuple(f'TestNamedTuple3',['y']) + + def test_impl(a): + a.y[:] = 5 + + def comparer(a, b): + np.testing.assert_almost_equal(a.y, b.y) + + x = TestNamedTuple3(y=np.zeros(10)) + self.check(test_impl, x, check_arg_equality=[comparer]) + + def test_inplace_binop(self): + def test_impl(a, b): + b += a + return b + + X = np.arange(10) + 10 + Y = np.arange(10) + 100 + self.check(test_impl, X, Y) + self.assertEqual(countParfors(test_impl, + (types.Array(types.float64, 1, 'C'), + types.Array(types.float64, 1, 'C'))), 1) + + def test_tuple_concat(self): + # issue5383 + def test_impl(a): + n = len(a) + array_shape = n, n + indices = np.zeros(((1,) + array_shape + (1,)), dtype=np.uint64) + k_list = indices[0, :] + + for i, g in enumerate(a): + k_list[i, i] = i + return k_list + + x = np.array([1, 1]) + self.check(test_impl, x) + + def test_tuple_concat_with_reverse_slice(self): + # issue5383 + def test_impl(a): + n = len(a) + array_shape = n, n + indices = np.zeros(((1,) + array_shape + (1,))[:-1], + dtype=np.uint64) + k_list = indices[0, :] + + for i, g in enumerate(a): + k_list[i, i] = i + return k_list + + x = np.array([1, 1]) + self.check(test_impl, x) + + def test_array_tuple_concat(self): + # issue6399 + def test_impl(a): + S = (a,) + (a, a) + return S[0].sum() + + x = np.ones((3,3)) + self.check(test_impl, x) + + def test_high_dimension1(self): + # issue6749 + def test_impl(x): + return x * 5.0 + x = np.ones((2, 2, 2, 2, 2, 15)) + self.check(test_impl, x) + + def test_tuple_arg(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.empty(sz), sz) + + def test_tuple_arg_not_whole_array(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.zeros(sz), (10, 3)) + + def test_tuple_for_pndindex(self): + def test_impl(x): + sz = (10, 5) + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.zeros(sz)) + + def test_tuple_arg_literal(self): + def test_impl(x, first): + sz = (first, 5) + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.zeros(sz), 10) + + def test_tuple_of_literal_nonliteral(self): + # This test has to be done manually as the self.check uses + # compile_isolated and one function cannot "see" the other + + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + + def call(x, fn): + return fn(x, (10, 3)) # Only want to iterate to the 3rd + + get_input = lambda: np.zeros((10, 10)) + expected = call(get_input(), test_impl) + + def check(dec): + f1 = dec(test_impl) + f2 = njit(call) # no parallel semantics in the caller + got = f2(get_input(), f1) + self.assertPreciseEqual(expected, got) + + for d in (njit, njit(parallel=True)): + check(d) + + def test_tuple_arg_1d(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10,) + self.check(test_impl, np.zeros(sz), sz) + + def test_tuple_arg_1d_literal(self): + def test_impl(x): + sz = (10,) + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10,) + self.check(test_impl, np.zeros(sz)) + + def test_int_arg_pndindex(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + self.check(test_impl, np.zeros((10, 10)), 3) + + def test_partial_sum_1d_parallel(self): + def test_impl(A): + result = np.zeros(A.shape, dtype=A.dtype) + for idx in numba.pndindex(A.shape): + result[idx] = A[idx] + return result + self.check(test_impl, np.random.random((2,))) + + def test_prange_unknown_call1(self): + @register_jitable + def issue7854_proc(u, i, even, size): + for j in range((even + i + 1) % 2 + 1, size - 1, 2): + u[i, j] = u[i + 1, j] + 1 + + # issue7854 + # Forbid fusion in unanalyzable call inside prange. + def test_impl(u, size): + for i in numba.prange(1, size - 1): + issue7854_proc(u, i, 0, size) + for i in numba.prange(1, size - 1): + issue7854_proc(u, i, 1, size) + return u + + size = 4 + u = np.zeros((size, size)) + cptypes = (numba.float64[:, ::1], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, u, size) + + def test_prange_index_calc1(self): + # Should forbid fusion due to cross-iteration dependency as + # detected by loop index calcuation (i+1) as array index. + def test_impl(u, size): + for i in numba.prange(1, size - 1): + for j in range((i + 1) % 2 + 1, size - 1, 2): + u[i, j] = u[i + 1, j] + 1 + for i in numba.prange(1, size - 1): + for j in range(i % 2 + 1, size - 1, 2): + u[i, j] = u[i + 1, j] + 1 + return u + + size = 4 + u = np.zeros((size, size)) + cptypes = (numba.float64[:, ::1], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, u, size) + + def test_prange_reverse_order1(self): + # Testing if reversed loop index usage as array index + # prevents fusion. + def test_impl(a, b, size): + for i in numba.prange(size): + for j in range(size): + a[i, j] = b[i, j] + 1 + for i in numba.prange(size): + for j in range(size): + b[j, i] = 3 + return a[0, 0] + b[0, 0] + + size = 10 + a = np.zeros((size, size)) + b = np.zeros((size, size)) + cptypes = (numba.float64[:, ::1], numba.float64[:, ::1], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, a, b, size) + + def test_prange_parfor_index_then_not(self): + # Testing if accessing an array first with a parfor index then + # without will prevent fusion. + def test_impl(a, size): + b = 0 + for i in numba.prange(size): + a[i] = i + for i in numba.prange(size): + b += a[5] + return b + + size = 10 + a = np.zeros(size) + cptypes = (numba.float64[:], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, a, size) + + def test_prange_parfor_index_const_tuple_fusion(self): + # Testing if accessing a tuple with prange index + # and later with a constant will not prevent fusion. + def test_impl(a, tup, size): + acc = 0 + for i in numba.prange(size): + a[i] = i + tup[i] + for i in numba.prange(size): + acc += a[i] + tup[1] + return acc + + size = 10 + a = np.zeros(size) + b = tuple(a) + cptypes = (numba.float64[:], + types.containers.UniTuple(types.float64, size), + types.intp) + self.assertEqual(countParfors(test_impl, cptypes), 1) + self.check(test_impl, a, b, size) + + def test_prange_non_parfor_index_then_opposite(self): + # Testing if accessing an array first without a parfor index then + # with will prevent fusion. + def test_impl(a, b, size): + for i in numba.prange(size): + b[i] = a[5] + for i in numba.prange(size): + a[i] = i + # Need this to stop previous prange from being optimized away. + b[0] += a[0] + return b + + size = 10 + a = np.zeros(size) + b = np.zeros(size) + cptypes = (numba.float64[:], numba.float64[:], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, a, b, size) + + def test_prange_optional(self): + def test_impl(arr, pred=None): + for i in prange(1): + if pred is not None: + arr[i] = 0.0 + + arr = np.ones(10) + self.check(test_impl, arr, None, + check_arg_equality=[np.testing.assert_almost_equal, + lambda x, y: x == y]) + self.assertEqual(arr.sum(), 10.0) + + def test_untraced_value_tuple(self): + # This is a test for issue #6478. + def test_impl(): + a = (1.2, 1.3) + return a[0] + + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_recursive_untraced_value_tuple(self): + # This is a test for issue #6478. + def test_impl(): + a = ((1.2, 1.3),) + return a[0][0] + + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_untraced_value_parfor(self): + # This is a test for issue #6478. + def test_impl(arr): + a = (1.2, 1.3) + n1 = len(arr) + arr2 = np.empty(n1, np.float64) + for i in prange(n1): + arr2[i] = arr[i] * a[0] + n2 = len(arr2) + arr3 = np.empty(n2, np.float64) + for j in prange(n2): + arr3[j] = arr2[j] - a[1] + total = 0.0 + n3 = len(arr3) + for k in prange(n3): + total += arr3[k] + return total + a[0] + + arg = (types.Array(types.int64, 1, 'C'), ) + self.assertEqual(countParfors(test_impl, arg), 1) + + arr = np.arange(10, dtype=np.int64) + self.check(test_impl, arr) + + def test_setitem_2d_one_replaced(self): + # issue7843 + def test_impl(x): + count = 0 + for n in range(x.shape[0]): + # Useless "if" necessary to trigger bug. + if n: + n + x[count, :] = 1 + count += 1 + return x + + self.check(test_impl, np.zeros((3, 1))) + + def test_1array_control_flow(self): + # issue8146 + def test_impl(arr, flag1, flag2): + inv = np.arange(arr.size) + if flag1: + return inv.astype(np.float64) + if flag2: + ret = inv[inv] + else: + ret = inv[inv - 1] + return ret / arr.size + + arr = np.arange(100) + self.check(test_impl, arr, True, False) + self.check(test_impl, arr, True, True) + self.check(test_impl, arr, False, False) + + def test_2array_1_control_flow(self): + # issue8146 + def test_impl(arr, l, flag): + inv1 = np.arange(arr.size) + inv2 = np.arange(l, arr.size + l) + if flag: + ret = inv1[inv1] + else: + ret = inv1[inv1 - 1] + return ret / inv2 + + arr = np.arange(100) + self.check(test_impl, arr, 10, True) + self.check(test_impl, arr, 10, False) + + def test_2array_2_control_flow(self): + # issue8146 + def test_impl(arr, l, flag): + inv1 = np.arange(arr.size) + inv2 = np.arange(l, arr.size + l) + if flag: + ret1 = inv1[inv1] + ret2 = inv2[inv1] + else: + ret1 = inv1[inv1 - 1] + ret2 = inv2[inv1 - 1] + return ret1 / ret2 + + arr = np.arange(100) + self.check(test_impl, arr, 10, True) + self.check(test_impl, arr, 10, False) + + def test_issue8515(self): + # issue8515: an array is filled in the first prange and + # then accessed with c[i - 1] in the next prange which + # should prevent fusion with the previous prange. + def test_impl(n): + r = np.zeros(n, dtype=np.intp) + c = np.zeros(n, dtype=np.intp) + for i in prange(n): + for j in range(i): + c[i] += 1 + + for i in prange(n): + if i == 0: + continue + r[i] = c[i] - c[i - 1] + return r[1:] + + self.check(test_impl, 15) + self.assertEqual(countParfors(test_impl, (types.int64, )), 2) + + def test_issue9029(self): + # issue9029: too many parfors executed in one function + # overflowed the stack. + def test_impl(i1, i2): + N = 30 + S = 3 + a = np.empty((N,N)) + # The stack should overflow if there are 30*30*2 (# of parfors) + # iterations. + for y in range(N): + for x in range(N): + values = np.ones(S) + v = values[0] + + p2 = np.empty(S) + for i in prange(i1, i2): + p2[i] = 1 + j = p2[0] + + a[y,x] = v + j + return a + + # We pass in 0 and 3 so that the function can't analyze the loop + # bounds on the prange to generate a signed loop whereas the + # np.ones will be an unsigned loop. + self.check(test_impl, 0, 3) + + def test_fusion_no_side_effects(self): + def test_impl(a, b): + X = np.ones(100) + b = math.ceil(b) + Y = np.ones(100) + c = int(max(a, b)) + return X + Y + c + self.check(test_impl, 3.7, 4.3) + self.assertEqual(countParfors(test_impl, (types.float64, types.float64)), 1) + + def test_issue9256_lower_sroa_conflict(self): + @njit(parallel=True) + def def_in_loop(x): + c = 0 + set_num_threads(1) + for i in prange(x): + c = i + return c + + self.assertEqual(def_in_loop(10), def_in_loop.py_func(10)) + + def test_issue9256_lower_sroa_conflict_variant1(self): + def def_in_loop(x): + c = x + set_num_threads(1) + for _i in prange(x): + if c: # forces 3 SSA versions + d = x + 4 + return c, d > 0 + + expected = def_in_loop(4) + self.assertEqual(expected, njit(parallel=False)(def_in_loop)(4)) + self.assertEqual(expected, njit(parallel=True)(def_in_loop)(4)) + + def test_issue9256_lower_sroa_conflict_variant2(self): + def def_in_loop(x): + c = x + set_num_threads(1) + for _i in prange(x): + if c: + for _j in range(x): # forces 4 SSA versions + d = x + 4 + return c, d > 0 + + expected = def_in_loop(4) + self.assertEqual(expected, njit(parallel=False)(def_in_loop)(4)) + self.assertEqual(expected, njit(parallel=True)(def_in_loop)(4)) + + @needs_lapack # use of np.linalg.solve + @skip_ppc64le_invalid_ctr_loop + def test_issue9490_non_det_ssa_problem(self): + # Test modified to include https://github.com/numba/numba/issues/9581 + # which is an issue with hoisting + cmd = [ + sys.executable, + "-m", + "numba.tests.parfor_iss9490_usecase", + ] + envs = { + **os.environ, + # Reproducer consistently fail with the following hashseed. + "PYTHONHASHSEED": "1", + # See https://github.com/numba/numba/issues/9501 + # for details of why num-thread pinning is needed. + "NUMBA_NUM_THREADS": "1", + } + try: + subp.check_output(cmd, env=envs, + stderr=subp.STDOUT, + encoding='utf-8') + except subp.CalledProcessError as e: + msg = f"subprocess failed with output:\n{e.output}" + self.fail(msg=msg) + + +@skip_parfors_unsupported +class TestParforsLeaks(MemoryLeakMixin, TestParforsBase): + def check(self, pyfunc, *args, **kwargs): + cfunc, cpfunc = self.compile_all(pyfunc, *args) + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + + def test_reduction(self): + # issue4299 + def test_impl(arr): + return arr.sum() + + arr = np.arange(10).astype(np.float64) + self.check(test_impl, arr) + + def test_multiple_reduction_vars(self): + + def test_impl(arr): + a = 0. + b = 1. + for i in prange(arr.size): + a += arr[i] + b += 1. / (arr[i] + 1) + return a * b + arr = np.arange(10).astype(np.float64) + self.check(test_impl, arr) + + +@skip_parfors_unsupported +class TestParforsSlice(TestParforsBase): + + def test_parfor_slice1(self): + def test_impl(a): + (n,) = a.shape + b = a[0:n-2] + a[1:n-1] + return b + + self.check(test_impl, np.ones(10)) + + def test_parfor_slice2(self): + def test_impl(a, m): + (n,) = a.shape + b = a[0:n-2] + a[1:m] + return b + + # runtime assertion should succeed + self.check(test_impl, np.ones(10), 9) + # next we expect failure + with self.assertRaises(AssertionError) as raises: + njit(parallel=True)(test_impl)(np.ones(10),10) + self.assertIn("do not match", str(raises.exception)) + + def test_parfor_slice3(self): + def test_impl(a): + (m,n) = a.shape + b = a[0:m-1,0:n-1] + a[1:m,1:n] + return b + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice4(self): + def test_impl(a): + (m,n) = a.shape + b = a[:,0:n-1] + a[:,1:n] + return b + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice5(self): + def test_impl(a): + (m,n) = a.shape + b = a[0:m-1,:] + a[1:m,:] + return b + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice6(self): + def test_impl(a): + b = a.transpose() + c = a[1,:] + b[:,1] + return c + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice7(self): + def test_impl(a): + b = a.transpose() + c = a[1,:] + b[1,:] + return c + + # runtime check should succeed + self.check(test_impl, np.ones((3,3))) + # next we expect failure + with self.assertRaises(AssertionError) as raises: + njit(parallel=True)(test_impl)(np.ones((3,4))) + self.assertIn("do not match", str(raises.exception)) + + @disabled_test + def test_parfor_slice8(self): + def test_impl(a): + (m,n) = a.shape + b = a.transpose() + b[1:m,1:n] = a[1:m,1:n] + return b + + self.check(test_impl, np.arange(9).reshape((3,3))) + + @disabled_test + def test_parfor_slice9(self): + def test_impl(a): + (m,n) = a.shape + b = a.transpose() + b[1:n,1:m] = a[:,1:m] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + @disabled_test + def test_parfor_slice10(self): + def test_impl(a): + (m,n) = a.shape + b = a.transpose() + b[2,1:m] = a[2,1:m] + return b + + self.check(test_impl, np.arange(9).reshape((3,3))) + + def test_parfor_slice11(self): + def test_impl(a): + (m,n,l) = a.shape + b = a.copy() + b[:,1,1:l] = a[:,2,1:l] + return b + + self.check(test_impl, np.arange(27).reshape((3,3,3))) + + def test_parfor_slice12(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + b[1,1:-1] = a[0,:-2] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + def test_parfor_slice13(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + c = -1 + b[1,1:c] = a[0,-n:c-1] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + def test_parfor_slice14(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + b[1,:-1] = a[0,-3:4] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + def test_parfor_slice15(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + b[1,-(n-1):] = a[0,-3:4] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + @disabled_test + def test_parfor_slice16(self): + """ This test is disabled because if n is larger than the array size + then n and n-1 will both be the end of the array and thus the + slices will in fact be of different sizes and unable to fuse. + """ + def test_impl(a, b, n): + assert(a.shape == b.shape) + a[1:n] = 10 + b[0:(n-1)] = 10 + return a * b + + self.check(test_impl, np.ones(10), np.zeros(10), 8) + args = (numba.float64[:], numba.float64[:], numba.int64) + self.assertEqual(countParfors(test_impl, args), 2) + + def test_parfor_slice17(self): + def test_impl(m, A): + B = np.zeros(m) + n = len(A) + B[-n:] = A + return B + + self.check(test_impl, 10, np.ones(10)) + + def test_parfor_slice18(self): + # issue 3534 + def test_impl(): + a = np.zeros(10) + a[1:8] = np.arange(0, 7) + y = a[3] + return y + + self.check(test_impl) + + def test_parfor_slice19(self): + # issues #3561 and #3554, empty slice binop + def test_impl(X): + X[:0] += 1 + return X + + self.check(test_impl, np.ones(10)) + + def test_parfor_slice20(self): + # issue #4075, slice size + def test_impl(): + a = np.ones(10) + c = a[1:] + s = len(c) + return s + + self.check(test_impl, check_scheduling=False) + + def test_parfor_slice21(self): + def test_impl(x1, x2): + x1 = x1.reshape(x1.size, 1) + x2 = x2.reshape(x2.size, 1) + return x1 >= x2[:-1, :] + + x1 = np.random.rand(5) + x2 = np.random.rand(6) + self.check(test_impl, x1, x2) + + def test_parfor_slice22(self): + def test_impl(x1, x2): + b = np.zeros((10,)) + for i in prange(1): + b += x1[:, x2] + return b + + x1 = np.zeros((10,7)) + x2 = np.array(4) + self.check(test_impl, x1, x2) + + def test_parfor_slice23(self): + # issue #4630 + def test_impl(x): + x[:0] = 2 + return x + + self.check(test_impl, np.ones(10)) + + def test_parfor_slice24(self): + def test_impl(m, A, n): + B = np.zeros(m) + C = B[n:] + C = A[:len(C)] + return B + + for i in range(-15, 15): + self.check(test_impl, 10, np.ones(10), i) + + def test_parfor_slice25(self): + def test_impl(m, A, n): + B = np.zeros(m) + C = B[:n] + C = A[:len(C)] + return B + + for i in range(-15, 15): + self.check(test_impl, 10, np.ones(10), i) + + def test_parfor_slice26(self): + def test_impl(a): + (n,) = a.shape + b = a.copy() + b[-(n-1):] = a[-3:4] + return b + + self.check(test_impl, np.arange(4)) + + def test_parfor_slice27(self): + # issue5601: tests array analysis of the slice with + # n_valid_vals of unknown size. + def test_impl(a): + n_valid_vals = 0 + + for i in prange(a.shape[0]): + if a[i] != 0: + n_valid_vals += 1 + + if n_valid_vals: + unused = a[:n_valid_vals] + + return 0 + + self.check(test_impl, np.arange(3)) + + def test_parfor_array_access_lower_slice(self): + for ts in [slice(1, 3, None), slice(2, None, None), slice(None, 2, -1), + slice(None, None, None), slice(None, None, -2)]: + + def test_impl(n): + X = np.arange(n * 4).reshape((n, 4)) + y = 0 + for i in numba.prange(n): + y += X[i, ts].sum() + return y + + n = 10 + self.check(test_impl, n) + + X = np.arange(n * 4).reshape((n, 4)) + + def test_impl(X): + y = 0 + for i in numba.prange(X.shape[0]): + y += X[i, ts].sum() + return y + + self.check(test_impl, X) + + +@skip_parfors_unsupported +class TestParforsOptions(TestParforsBase): + + def test_parfor_options(self): + def test_impl(a): + n = a.shape[0] + b = np.ones(n) + c = np.array([ i for i in range(n) ]) + b[:n] = a + b * c + for i in prange(n): + c[i] = b[i] * a[i] + return reduce(lambda x,y:x+y, c, 0) + + self.check(test_impl, np.ones(10)) + args = (numba.float64[:],) + # everything should fuse with default option + self.assertEqual(countParfors(test_impl, args), 1) + # with no fusion + self.assertEqual(countParfors(test_impl, args, fusion=False), 6) + # with no fusion, comprehension + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False), 5) + #with no fusion, comprehension, setitem + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False), 4) + # with no fusion, comprehension, prange + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False, prange=False), 3) + # with no fusion, comprehension, prange, reduction + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False, prange=False, + reduction=False), 2) + # with no fusion, comprehension, prange, reduction, numpy + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False, prange=False, + reduction=False, numpy=False), 0) + + +@skip_parfors_unsupported +class TestParforsBitMask(TestParforsBase): + + def test_parfor_bitmask1(self): + def test_impl(a, n): + b = a > n + a[b] = 0 + return a + + self.check(test_impl, np.arange(10), 5) + + def test_parfor_bitmask2(self): + def test_impl(a, b): + a[b] = 0 + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask3(self): + def test_impl(a, b): + a[b] = a[b] + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask4(self): + def test_impl(a, b): + a[b] = (2 * a)[b] + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask5(self): + def test_impl(a, b): + a[b] = a[b] * a[b] + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask6(self): + def test_impl(a, b, c): + a[b] = c + return a + + a = np.arange(10) + b = a > 5 + c = np.zeros(sum(b)) + + # expect failure due to lack of parallelism + with self.assertRaises(AssertionError) as raises: + self.check(test_impl, a, b, c) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + +@skip_parfors_unsupported +class TestParforsMisc(TestParforsBase): + """ + Tests miscellaneous parts of ParallelAccelerator use. + """ + def test_no_warn_if_cache_set(self): + + def pyfunc(): + arr = np.ones(100) + for i in prange(arr.size): + arr[i] += i + return arr + + cfunc = njit(parallel=True, cache=True)(pyfunc) + + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter('always') + warnings.filterwarnings(action="ignore", + module="typeguard") + # Filter out warnings about TBB interface mismatch + warnings.filterwarnings(action='ignore', + message=r".*TBB_INTERFACE_VERSION.*", + category=numba.errors.NumbaWarning, + module=r'numba\.np\.ufunc\.parallel.*') + cfunc() + + self.assertEqual(len(raised_warnings), 0) + + # Make sure the dynamic globals flag is set + has_dynamic_globals = [cres.library.has_dynamic_globals + for cres in cfunc.overloads.values()] + self.assertEqual(has_dynamic_globals, [False]) + + def test_statement_reordering_respects_aliasing(self): + def impl(): + a = np.zeros(10) + a[1:8] = np.arange(0, 7) + print('a[3]:', a[3]) + print('a[3]:', a[3]) + return a + + cres = self.compile_parallel(impl, ()) + with captured_stdout() as stdout: + cres.entry_point() + for line in stdout.getvalue().splitlines(): + self.assertEqual('a[3]: 2.0', line) + + def test_parfor_ufunc_typing(self): + def test_impl(A): + return np.isinf(A) + + A = np.array([np.inf, 0.0]) + cfunc = njit(parallel=True)(test_impl) + # save global state + old_seq_flag = numba.parfors.parfor.sequential_parfor_lowering + try: + numba.parfors.parfor.sequential_parfor_lowering = True + np.testing.assert_array_equal(test_impl(A), cfunc(A)) + finally: + # recover global state + numba.parfors.parfor.sequential_parfor_lowering = old_seq_flag + + def test_init_block_dce(self): + # issue4690 + def test_impl(): + res = 0 + arr = [1,2,3,4,5] + numba.parfors.parfor.init_prange() + dummy = arr + for i in numba.prange(5): + res += arr[i] + return res + dummy[2] + + self.assertEqual(get_init_block_size(test_impl, ()), 0) + + def test_alias_analysis_for_parfor1(self): + def test_impl(): + acc = 0 + for _ in range(4): + acc += 1 + + data = np.zeros((acc,)) + return data + + self.check(test_impl) + + def test_no_state_change_in_gufunc_lowering_on_error(self): + # tests #5098, if there's an exception arising in gufunc lowering the + # sequential_parfor_lowering global variable should remain as False on + # stack unwind. + + BROKEN_MSG = 'BROKEN_MSG' + + @register_pass(mutates_CFG=True, analysis_only=False) + class BreakParfors(AnalysisPass): + _name = "break_parfors" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + for blk in state.func_ir.blocks.values(): + for stmt in blk.body: + if isinstance(stmt, numba.parfors.parfor.Parfor): + # races should be a set(), that list is iterable + # permits it to get through to the + # _create_gufunc_for_parfor_body routine at which + # point it needs to be a set so e.g. set.difference + # can be computed, this therefore creates an error + # in the right location. + class Broken(list): + + def difference(self, other): + raise errors.LoweringError(BROKEN_MSG) + + stmt.races = Broken() + return True + + + class BreakParforsCompiler(CompilerBase): + + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(BreakParfors, IRLegalization) + pm.finalize() + return [pm] + + + @njit(parallel=True, pipeline_class=BreakParforsCompiler) + def foo(): + x = 1 + for _ in prange(1): + x += 1 + return x + + # assert default state for global + self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering) + + with self.assertRaises(errors.LoweringError) as raises: + foo() + + self.assertIn(BROKEN_MSG, str(raises.exception)) + + # assert state has not changed + self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering) + + def test_issue_5098(self): + class DummyType(types.Opaque): + pass + + dummy_type = DummyType("my_dummy") + register_model(DummyType)(models.OpaqueModel) + + class Dummy(object): + pass + + @typeof_impl.register(Dummy) + def typeof_Dummy(val, c): + return dummy_type + + @unbox(DummyType) + def unbox_index(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + @overload_method(DummyType, "method1", jit_options={"parallel":True}) + def _get_method1(obj, arr, func): + def _foo(obj, arr, func): + def baz(a, f): + c = a.copy() + c[np.isinf(a)] = np.nan + return f(c) + + length = len(arr) + output_arr = np.empty(length, dtype=np.float64) + for i in prange(length): + output_arr[i] = baz(arr[i], func) + for i in prange(length - 1): + output_arr[i] += baz(arr[i], func) + return output_arr + return _foo + + @njit + def bar(v): + return v.mean() + + @njit + def test1(d): + return d.method1(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), bar) + + save_state = numba.parfors.parfor.sequential_parfor_lowering + self.assertFalse(save_state) + try: + test1(Dummy()) + self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering) + finally: + # always set the sequential_parfor_lowering state back to the + # original state + numba.parfors.parfor.sequential_parfor_lowering = save_state + + def test_oversized_tuple_as_arg_to_kernel(self): + + @njit(parallel=True) + def oversize_tuple(idx): + big_tup = (1,2,3,4) + z = 0 + for x in prange(10): + z += big_tup[idx] + return z + + with override_env_config('NUMBA_PARFOR_MAX_TUPLE_SIZE', '3'): + with self.assertRaises(errors.UnsupportedParforsError) as raises: + oversize_tuple(0) + + errstr = str(raises.exception) + self.assertIn("Use of a tuple", errstr) + self.assertIn("in a parallel region", errstr) + + def test_issue5167(self): + + def ndvi_njit(img_nir, img_red): + fillvalue = 0 + out_img = np.full(img_nir.shape, fillvalue, dtype=img_nir.dtype) + dims = img_nir.shape + for y in prange(dims[0]): + for x in prange(dims[1]): + out_img[y, x] = ((img_nir[y, x] - img_red[y, x]) / + (img_nir[y, x] + img_red[y, x])) + return out_img + + tile_shape = (4, 4) + array1 = np.random.uniform(low=1.0, high=10000.0, size=tile_shape) + array2 = np.random.uniform(low=1.0, high=10000.0, size=tile_shape) + self.check(ndvi_njit, array1, array2) + + def test_issue5065(self): + + def reproducer(a, dist, dist_args): + result = np.zeros((a.shape[0], a.shape[0]), dtype=np.float32) + for i in prange(a.shape[0]): + for j in range(i + 1, a.shape[0]): + d = dist(a[i], a[j], *dist_args) + result[i, j] = d + result[j, i] = d + return result + + @njit + def euclidean(x, y): + result = 0.0 + for i in range(x.shape[0]): + result += (x[i] - y[i]) ** 2 + return np.sqrt(result) + + a = np.random.random(size=(5, 2)) + + got = njit(parallel=True)(reproducer)(a.copy(), euclidean,()) + expected = reproducer(a.copy(), euclidean,()) + + np.testing.assert_allclose(got, expected) + + def test_issue5001(self): + + def test_numba_parallel(myarray): + result = [0] * len(myarray) + for i in prange(len(myarray)): + result[i] = len(myarray[i]) + return result + + myarray = (np.empty(100),np.empty(50)) + self.check(test_numba_parallel, myarray) + + def test_issue3169(self): + + @njit + def foo(grids): + pass + + @njit(parallel=True) + def bar(grids): + for x in prange(1): + foo(grids) + + # returns nothing, just check it compiles + bar(([1],) * 2) + + @disabled_test + def test_issue4846(self): + + mytype = namedtuple("mytype", ("a", "b")) + + def outer(mydata): + for k in prange(3): + inner(k, mydata) + return mydata.a + + @njit(nogil=True) + def inner(k, mydata): + f = (k, mydata.a) + g = (k, mydata.b) + + mydata = mytype(a="a", b="b") + + self.check(outer, mydata) + + def test_issue3748(self): + + def test1b(): + x = (1, 2, 3, 4, 5) + a = 0 + for i in prange(len(x)): + a += x[i] + return a + + self.check(test1b,) + + def test_issue5277(self): + + def parallel_test(size, arr): + for x in prange(size[0]): + for y in prange(size[1]): + arr[y][x] = x * 4.5 + y + return arr + + size = (10, 10) + arr = np.zeros(size, dtype=int) + + self.check(parallel_test, size, arr) + + def test_issue5570_ssa_races(self): + @njit(parallel=True) + def foo(src, method, out): + for i in prange(1): + for j in range(1): + out[i, j] = 1 + if method: + out += 1 + return out + + src = np.zeros((5,5)) + method = 57 + out = np.zeros((2, 2)) + + self.assertPreciseEqual( + foo(src, method, out), + foo.py_func(src, method, out) + ) + + def test_issue6095_numpy_max(self): + @njit(parallel=True) + def find_maxima_3D_jit(args): + package = args + for index in range(0, 10): + z_stack = package[index, :, :] + return np.max(z_stack) + + np.random.seed(0) + args = np.random.random((10, 10, 10)) + self.assertPreciseEqual( + find_maxima_3D_jit(args), + find_maxima_3D_jit.py_func(args), + ) + + def test_issue5942_1(self): + # issue5942: tests statement reordering of + # aliased arguments. + def test_impl(gg, gg_next): + gs = gg.shape + d = gs[0] + for i_gg in prange(d): + gg_next[i_gg, :] = gg[i_gg, :] + gg_next[i_gg, 0] += 1 + + return gg_next + + d = 4 + k = 2 + + gg = np.zeros((d, k), dtype = np.int32) + gg_next = np.zeros((d, k), dtype = np.int32) + self.check(test_impl, gg, gg_next) + + def test_issue5942_2(self): + # issue5942: tests statement reordering + def test_impl(d, k): + gg = np.zeros((d, k), dtype = np.int32) + gg_next = np.zeros((d, k), dtype = np.int32) + + for i_gg in prange(d): + for n in range(k): + gg[i_gg, n] = i_gg + gg_next[i_gg, :] = gg[i_gg, :] + gg_next[i_gg, 0] += 1 + + return gg_next + + d = 4 + k = 2 + + self.check(test_impl, d, k) + + @skip_unless_scipy + def test_issue6102(self): + # The problem is originally observed on Python3.8 because of the + # changes in how loops are represented in 3.8 bytecode. + @njit(parallel=True) + def f(r): + for ir in prange(r.shape[0]): + dist = np.inf + tr = np.array([0, 0, 0], dtype=np.float32) + for i in [1, 0, -1]: + dist_t = np.linalg.norm(r[ir, :] + i) + if dist_t < dist: + dist = dist_t + tr = np.array([i, i, i], dtype=np.float32) + r[ir, :] += tr + return r + + r = np.array([[0., 0., 0.], [0., 0., 1.]]) + self.assertPreciseEqual(f(r), f.py_func(r)) + + def test_issue6774(self): + + def test_impl(): + n = 5 + na_mask = np.ones((n,)) + result = np.empty((n - 1,)) + for i in prange(len(result)): + result[i] = np.sum(na_mask[i:i + 1]) + return result + + self.check(test_impl) + + def test_issue4963_globals(self): + def test_impl(): + buf = np.zeros((_GLOBAL_INT_FOR_TESTING1, _GLOBAL_INT_FOR_TESTING2)) + return buf + self.check(test_impl) + + def test_issue4963_freevars(self): + _FREEVAR_INT_FOR_TESTING1 = 17 + _FREEVAR_INT_FOR_TESTING2 = 5 + def test_impl(): + buf = np.zeros((_FREEVAR_INT_FOR_TESTING1, _FREEVAR_INT_FOR_TESTING2)) + return buf + self.check(test_impl) + + def test_issue_9182_recursion_error(self): + from numba.types import ListType, Tuple, intp + + @numba.njit + def _sink(x): + pass + + + @numba.njit(cache=False, parallel=True) + def _ground_node_rule( + clauses, + nodes, + ): + for piter in prange(len(nodes)): + for clause in clauses: + clause_type = clause[0] + clause_variables = clause[2] + if clause_type == 0: + clause_var_1 = clause_variables[0] + elif len(clause_variables) == 2: + clause_var_1, clause_var_2 = ( + clause_variables[0], + clause_variables[1], + ) + + elif len(clause_variables) == 4: + pass + + if clause_type == 1: + _sink(clause_var_1) + _sink(clause_var_2) + + _ground_node_rule.compile( + ( + ListType(Tuple([intp, intp, ListType(intp)])), + ListType(intp), + ) + ) + + def test_lookup_cycle_detection(self): + # This test is added due to a bug discovered in the PR 9244 patch. + # The cyclic detection was incorrectly flagging cycles. + @njit(parallel=True) + def foo(): + # The following `acc` variable is used in the `lookup()` function + # in parfor's reduction code. + acc = 0 + for n in prange(1): + for i in range(1): + for j in range(1): + acc += 1 + return acc + + self.assertEqual(foo(), foo.py_func()) + + def test_issue_9678_build_map(self): + def issue_9678(num_nodes): + out = 0 + for inode_uint in numba.prange(num_nodes): + inode = numba.int64(inode_uint) + p = {inode: 0.0} # mainly this build_map bytecode here + for _ in range(5): + p[inode] += 1 # and here + out += p[inode] + return out + + num_nodes = 12 + issue_9678_serial = numba.jit(parallel=False)(issue_9678) + issue_9678_parallel = numba.jit(parallel=True)(issue_9678) + self.assertEqual(issue_9678_serial(num_nodes), + issue_9678_parallel(num_nodes)) + + +@skip_parfors_unsupported +class TestParforsDiagnostics(TestParforsBase): + + def check(self, pyfunc, *args, **kwargs): + cfunc, cpfunc = self.compile_all(pyfunc, *args) + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + + def assert_fusion_equivalence(self, got, expected): + a = self._fusion_equivalent(got) + b = self._fusion_equivalent(expected) + self.assertEqual(a, b) + + def _fusion_equivalent(self, thing): + # parfors indexes the Parfors class instance id's from wherever the + # internal state happens to be. To assert fusion equivalence we just + # check that the relative difference between fusion adjacency lists + # is the same. For example: + # {3: [2, 1]} is the same as {13: [12, 11]} + # this function strips the indexing etc out returning something suitable + # for checking equivalence + new = defaultdict(list) + min_key = min(thing.keys()) + for k in sorted(thing.keys()): + new[k - min_key] = [x - min_key for x in thing[k]] + return new + + def assert_diagnostics(self, diagnostics, parfors_count=None, + fusion_info=None, nested_fusion_info=None, + replaced_fns=None, hoisted_allocations=None): + if parfors_count is not None: + self.assertEqual(parfors_count, diagnostics.count_parfors()) + if fusion_info is not None: + self.assert_fusion_equivalence(fusion_info, diagnostics.fusion_info) + if nested_fusion_info is not None: + self.assert_fusion_equivalence(nested_fusion_info, + diagnostics.nested_fusion_info) + if replaced_fns is not None: + repl = diagnostics.replaced_fns.values() + for x in replaced_fns: + for replaced in repl: + if replaced[0] == x: + break + else: + msg = "Replacement for %s was not found. Had %s" % (x, repl) + raise AssertionError(msg) + + if hoisted_allocations is not None: + hoisted_allocs = diagnostics.hoisted_allocations() + self.assertEqual(hoisted_allocations, len(hoisted_allocs)) + + # just make sure that the dump() function doesn't have an issue! + with captured_stdout(): + for x in range(1, 5): + diagnostics.dump(x) + + def test_array_expr(self): + def test_impl(): + n = 10 + a = np.ones(n) + b = np.zeros(n) + return a + b + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1, + fusion_info = {3: [4, 5]}) + + def test_prange(self): + def test_impl(): + n = 10 + a = np.empty(n) + for i in prange(n): + a[i] = i * 10 + return a + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1) + + def test_user_varname(self): + """make sure original user variable name is used in fusion info + """ + def test_impl(): + n = 10 + x = np.ones(n) + a = np.sin(x) + b = np.cos(a * a) + acc = 0 + for i in prange(n - 2): + for j in prange(n - 1): + acc += b[i] + b[j + 1] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + # make sure original 'n' variable name is used in fusion report for loop + # dimension mismatch + self.assertTrue( + any("slice(0, n, 1)" in r.message for r in diagnostics.fusion_reports)) + + def test_nested_prange(self): + def test_impl(): + n = 10 + a = np.empty((n, n)) + for i in prange(n): + for j in prange(n): + a[i, j] = i * 10 + j + return a + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=2, + nested_fusion_info={2: [1]}) + + def test_function_replacement(self): + def test_impl(): + n = 10 + a = np.ones(n) + b = np.argmin(a) + return b + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1, + fusion_info={2: [3]}, + replaced_fns = [('argmin', 'numpy'),]) + + def test_reduction(self): + def test_impl(): + n = 10 + a = np.ones(n + 1) # prevent fusion + acc = 0 + for i in prange(n): + acc += a[i] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=2) + + def test_reduction_binop(self): + def test_impl(): + n = 10 + a = np.ones(n + 1) # prevent fusion + acc = 0 + for i in prange(n): + acc = acc - a[i] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=2) + + def test_setitem(self): + def test_impl(): + n = 10 + a = np.ones(n) + a[:] = 7 + return a + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1) + + def test_allocation_hoisting(self): + def test_impl(): + n = 10 + m = 5 + acc = 0 + for i in prange(n): + temp = np.zeros((m,)) # the np.empty call should get hoisted + for j in range(m): + temp[j] = i + acc += temp[-1] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, hoisted_allocations=1) + + +class TestPrangeBase(TestParforsBase): + + def generate_prange_func(self, pyfunc, patch_instance): + """ + This function does the actual code augmentation to enable the explicit + testing of `prange` calls in place of `range`. + """ + pyfunc_code = pyfunc.__code__ + + prange_names = list(pyfunc_code.co_names) + + if patch_instance is None: + # patch all instances, cheat by just switching + # range for prange + assert 'range' in pyfunc_code.co_names + prange_names = tuple([x if x != 'range' else 'prange' + for x in pyfunc_code.co_names]) + new_code = bytes(pyfunc_code.co_code) + else: + # patch specified instances... + # find where 'range' is in co_names + range_idx = pyfunc_code.co_names.index('range') + range_locations = [] + # look for LOAD_GLOBALs that point to 'range' + for instr in dis.Bytecode(pyfunc_code): + if instr.opname == 'LOAD_GLOBAL': + if _fix_LOAD_GLOBAL_arg(instr.arg) == range_idx: + range_locations.append(instr.offset + 1) + # add in 'prange' ref + prange_names.append('prange') + prange_names = tuple(prange_names) + prange_idx = len(prange_names) - 1 + if utils.PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14), (3, 15)): + # this is the inverse of _fix_LOAD_GLOBAL_arg + prange_idx = 1 + (prange_idx << 1) + elif utils.PYVERSION in ((3, 10),): + pass + else: + raise NotImplementedError(utils.PYVERSION) + new_code = bytearray(pyfunc_code.co_code) + assert len(patch_instance) <= len(range_locations) + # patch up the new byte code + for i in patch_instance: + idx = range_locations[i] + new_code[idx] = prange_idx + new_code = bytes(new_code) + + # create code object with prange mutation + prange_code = pyfunc_code.replace(co_code=new_code, + co_names=prange_names) + + # get function + pfunc = pytypes.FunctionType(prange_code, globals()) + + return pfunc + + def prange_tester(self, pyfunc, *args, **kwargs): + """ + The `prange` tester + This is a hack. It basically switches out range calls for prange. + It does this by copying the live code object of a function + containing 'range' then copying the .co_names and mutating it so + that 'range' is replaced with 'prange'. It then creates a new code + object containing the mutation and instantiates a function to contain + it. At this point three results are created: + 1. The result of calling the original python function. + 2. The result of calling a njit compiled version of the original + python function. + 3. The result of calling a njit(parallel=True) version of the mutated + function containing `prange`. + The three results are then compared and the `prange` based function's + llvm_ir is inspected to ensure the scheduler code is present. + + Arguments: + pyfunc - the python function to test + args - data arguments to pass to the pyfunc under test + + Keyword Arguments: + patch_instance - iterable containing which instances of `range` to + replace. If not present all instance of `range` are + replaced. + scheduler_type - 'signed', 'unsigned' or None, default is None. + Supply in cases where the presence of a specific + scheduler is to be asserted. + check_fastmath - if True then a check will be performed to ensure the + IR contains instructions labelled with 'fast' + check_fastmath_result - if True then a check will be performed to + ensure the result of running with fastmath + on matches that of the pyfunc + Remaining kwargs are passed to np.testing.assert_almost_equal + + + Example: + def foo(): + acc = 0 + for x in range(5): + for y in range(10): + acc +=1 + return acc + + # calling as + prange_tester(foo) + # will test code equivalent to + # def foo(): + # acc = 0 + # for x in prange(5): # <- changed + # for y in prange(10): # <- changed + # acc +=1 + # return acc + + # calling as + prange_tester(foo, patch_instance=[1]) + # will test code equivalent to + # def foo(): + # acc = 0 + # for x in range(5): # <- outer loop (0) unchanged + # for y in prange(10): # <- inner loop (1) changed + # acc +=1 + # return acc + + """ + patch_instance = kwargs.pop('patch_instance', None) + check_fastmath = kwargs.pop('check_fastmath', False) + check_fastmath_result = kwargs.pop('check_fastmath_result', False) + + pfunc = self.generate_prange_func(pyfunc, patch_instance) + + # Compile functions + # compile a standard njit of the original function + sig = tuple([numba.typeof(x) for x in args]) + cfunc = self.compile_njit(pyfunc, sig) + + # compile the prange injected function + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter('always') + cpfunc = self.compile_parallel(pfunc, sig) + + # if check_fastmath is True then check fast instructions + if check_fastmath: + self.assert_fastmath(pfunc, sig) + + # if check_fastmath_result is True then compile a function + # so that the parfors checker can assert the result is ok. + if check_fastmath_result: + fastcpfunc = self.compile_parallel_fastmath(pfunc, sig) + kwargs = dict({'fastmath_pcres': fastcpfunc}, **kwargs) + + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + return raised_warnings + + +@skip_parfors_unsupported +class TestPrangeBasic(TestPrangeBase): + """ Tests Prange """ + + def test_prange01(self): + def test_impl(): + n = 4 + A = np.zeros(n) + for i in range(n): + A[i] = 2.0 * i + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange02(self): + def test_impl(): + n = 4 + A = np.zeros(n - 1) + for i in range(1, n): + A[i - 1] = 2.0 * i + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03(self): + def test_impl(): + s = 10 + for i in range(10): + s += 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03mul(self): + def test_impl(): + s = 3 + for i in range(10): + s *= 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03sub(self): + def test_impl(): + s = 100 + for i in range(10): + s -= 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03div(self): + def test_impl(): + s = 10 + for i in range(10): + s /= 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange04(self): + def test_impl(): + a = 2 + b = 3 + A = np.empty(4) + for i in range(4): + if i == a: + A[i] = b + else: + A[i] = 0 + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange05(self): + def test_impl(): + n = 4 + A = np.ones((n), dtype=np.float64) + s = 0 + for i in range(1, n - 1, 1): + s += A[i] + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange06(self): + def test_impl(): + n = 4 + A = np.ones((n), dtype=np.float64) + s = 0 + for i in range(1, 1, 1): + s += A[i] + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange07(self): + def test_impl(): + n = 4 + A = np.ones((n), dtype=np.float64) + s = 0 + for i in range(n, 1): + s += A[i] + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange08(self): + def test_impl(): + n = 4 + A = np.ones((n)) + acc = 0 + for i in range(len(A)): + for j in range(len(A)): + acc += A[i] + return acc + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange08_1(self): + def test_impl(): + n = 4 + A = np.ones((n)) + acc = 0 + for i in range(4): + for j in range(4): + acc += A[i] + return acc + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange09(self): + def test_impl(): + n = 4 + acc = 0 + for i in range(n): + for j in range(n): + acc += 1 + return acc + # patch inner loop to 'prange' + self.prange_tester(test_impl, patch_instance=[1], + scheduler_type='unsigned', + check_fastmath=True) + + def test_prange10(self): + def test_impl(): + n = 4 + acc2 = 0 + for j in range(n): + acc1 = 0 + for i in range(n): + acc1 += 1 + acc2 += acc1 + return acc2 + # patch outer loop to 'prange' + self.prange_tester(test_impl, patch_instance=[0], + scheduler_type='unsigned', + check_fastmath=True) + + @unittest.skip("list append is not thread-safe yet (#2391, #2408)") + def test_prange11(self): + def test_impl(): + n = 4 + return [np.sin(j) for j in range(n)] + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange12(self): + def test_impl(): + acc = 0 + n = 4 + X = np.ones(n) + for i in range(-len(X)): + acc += X[i] + return acc + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange13(self): + def test_impl(n): + acc = 0 + for i in range(n): + acc += 1 + return acc + self.prange_tester(test_impl, np.int32(4), scheduler_type='unsigned', + check_fastmath=True) + + def test_prange14(self): + def test_impl(A): + s = 3 + for i in range(len(A)): + s += A[i]*2 + return s + # this tests reduction detection well since the accumulated variable + # is initialized before the parfor and the value accessed from the array + # is updated before accumulation + self.prange_tester(test_impl, np.random.ranf(4), + scheduler_type='unsigned', + check_fastmath=True) + + def test_prange15(self): + # from issue 2587 + # test parfor type inference when there is multi-dimensional indexing + def test_impl(N): + acc = 0 + for i in range(N): + x = np.ones((1, 1)) + acc += x[0, 0] + return acc + self.prange_tester(test_impl, 1024, scheduler_type='unsigned', + check_fastmath=True) + + # Tests for negative ranges + def test_prange16(self): + def test_impl(N): + acc = 0 + for i in range(-N, N): + acc += 2 + return acc + self.prange_tester(test_impl, 1024, scheduler_type='signed', + check_fastmath=True) + + def test_prange17(self): + def test_impl(N): + acc = 0 + X = np.ones(N) + for i in range(-N, N): + acc += X[i] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange18(self): + def test_impl(N): + acc = 0 + X = np.ones(N) + for i in range(-N, 5): + acc += X[i] + for j in range(-4, N): + acc += X[j] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange19(self): + def test_impl(N): + acc = 0 + M = N + 4 + X = np.ones((N, M)) + for i in range(-N, N): + for j in range(-M, M): + acc += X[i, j] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange20(self): + def test_impl(N): + acc = 0 + X = np.ones(N) + for i in range(-1, N): + acc += X[i] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange21(self): + def test_impl(N): + acc = 0 + for i in range(-3, -1): + acc += 3 + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange22(self): + def test_impl(): + a = 0 + b = 3 + A = np.empty(4) + for i in range(-2, 2): + if i == a: + A[i] = b + elif i < 1: + A[i] = -1 + else: + A[i] = 7 + return A + self.prange_tester(test_impl, scheduler_type='signed', + check_fastmath=True, check_fastmath_result=True) + + def test_prange23(self): + # test non-contig input + def test_impl(A): + for i in range(len(A)): + A[i] = i + return A + A = np.zeros(32)[::2] + self.prange_tester(test_impl, A, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + + def test_prange24(self): + # test non-contig input, signed range + def test_impl(A): + for i in range(-len(A), 0): + A[i] = i + return A + A = np.zeros(32)[::2] + self.prange_tester(test_impl, A, scheduler_type='signed', + check_fastmath=True, check_fastmath_result=True) + + def test_prange25(self): + def test_impl(A): + n = len(A) + buf = [np.zeros_like(A) for _ in range(n)] + for i in range(n): + buf[i] = A + i + return buf + A = np.ones((10,)) + self.prange_tester(test_impl, A, patch_instance=[1], + scheduler_type='unsigned', check_fastmath=True, + check_fastmath_result=True) + + cpfunc = self.compile_parallel(test_impl, (numba.typeof(A),)) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + hoisted_allocs = diagnostics.hoisted_allocations() + self.assertEqual(len(hoisted_allocs), 0) + + def test_prange26(self): + def test_impl(A): + B = A[::3] + for i in range(len(B)): + B[i] = i + return A + A = np.zeros(32)[::2] + self.prange_tester(test_impl, A, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + + def test_prange27(self): + # issue5597: usedef error in parfor + def test_impl(a, b, c): + for j in range(b[0]-1): + for k in range(2): + z = np.abs(a[c-1:c+1]) + return 0 + + # patch inner loop to 'prange' + self.prange_tester(test_impl, + np.arange(20), + np.asarray([4,4,4,4,4,4,4,4,4,4]), + 0, + patch_instance=[1], + scheduler_type='unsigned', + check_fastmath=True) + + def test_prange28(self): + # issue7105: label conflict in nested parfor + def test_impl(x, y): + out = np.zeros(len(y)) + for idx in range(0, len(y)): + i0 = y[idx, 0] + i1 = y[idx, 1] + Pt1 = x[i0] + Pt2 = x[i1] + v = Pt1 - Pt2 + vl2 = v[0] + v[1] + out[idx] = vl2 + return out + + X = np.array([[-1., -1.], + [-1., 1.], + [ 0., 0.], + [ 1., -1.], + [ 1., 0.], + [ 1., 1.]]) + + Y = np.array([[0, 1], + [1, 2], + [2, 3], + [3, 4], + [4, 5]]) + + self.prange_tester(test_impl, X, Y, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + + def test_prange29(self): + # issue7630: SSA renaming in prange header + def test_impl(flag): + result = 0 + if flag: + for i in range(1): + result += 1 + else: + for i in range(1): + result -= 3 + return result + + self.prange_tester(test_impl, True) + self.prange_tester(test_impl, False) + + def test_prange30(self): + # issue7675: broadcast setitem + def test_impl(x, par, numthreads): + n_par = par.shape[0] + n_x = len(x) + result = np.zeros((n_par, n_x), dtype=np.float64) + chunklen = (len(x) + numthreads - 1) // numthreads + + for i in range(numthreads): + start = i * chunklen + stop = (i + 1) * chunklen + result[:, start:stop] = x[start:stop] * par[:] + + return result + + x = np.array(np.arange(0, 6, 1.0)) + par = np.array([1.0, 2.0, 3.0]) + + self.prange_tester(test_impl, x, par, 2) + + +@register_jitable +def test_call_hoisting_outcall(a,b): + return (a, b) + + +@skip_parfors_unsupported +class TestPrangeSpecific(TestPrangeBase): + """ Tests specific features/problems found under prange""" + + def test_prange_two_instances_same_reduction_var(self): + # issue4922 - multiple uses of same reduction variable + def test_impl(n): + c = 0 + for i in range(n): + c += 1 + if i > 10: + c += 1 + return c + self.prange_tester(test_impl, 9) + + def test_prange_conflicting_reduction_ops(self): + def test_impl(n): + c = 0 + for i in range(n): + c += 1 + if i > 10: + c *= 1 + return c + + with self.assertRaises(errors.UnsupportedError) as raises: + self.prange_tester(test_impl, 9) + msg = ('Reduction variable c has multiple conflicting reduction ' + 'operators.') + self.assertIn(msg, str(raises.exception)) + + def test_prange_two_conditional_reductions(self): + # issue6414 + def test_impl(): + A = B = 0 + for k in range(1): + if k == 2: + A += 1 + else: + x = np.zeros((1, 1)) + if x[0, 0]: + B += 1 + return A, B + self.prange_tester(test_impl) + + def test_prange_nested_reduction1(self): + def test_impl(): + A = 0 + for k in range(1): + for i in range(1): + if i == 0: + A += 1 + return A + self.prange_tester(test_impl) + + @disabled_test + def test_check_error_model(self): + def test_impl(): + n = 32 + A = np.zeros(n) + for i in range(n): + A[i] = 1 / i # div-by-zero when i = 0 + return A + + with self.assertRaises(ZeroDivisionError) as raises: + test_impl() + + # compile parallel functions + pfunc = self.generate_prange_func(test_impl, None) + pcres = self.compile_parallel(pfunc, ()) + pfcres = self.compile_parallel_fastmath(pfunc, ()) + + # should raise + with self.assertRaises(ZeroDivisionError) as raises: + pcres.entry_point() + + # should not raise + result = pfcres.entry_point() + self.assertEqual(result[0], np.inf) + + def test_check_alias_analysis(self): + # check alias analysis reports ok + def test_impl(A): + for i in range(len(A)): + B = A[i] + B[:] = 1 + return A + A = np.zeros(32).reshape(4, 8) + self.prange_tester(test_impl, A, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + pfunc = self.generate_prange_func(test_impl, None) + sig = tuple([numba.typeof(A)]) + cres = self.compile_parallel_fastmath(pfunc, sig) + _ir = self._get_gufunc_ir(cres) + for k, v in _ir.items(): + for line in v.splitlines(): + # get the fn definition line + if 'define' in line and k in line: + # there should only be 2x noalias, one on each of the first + # 2 args (retptr, excinfo). + # Note: used to be 3x no noalias, but env arg is dropped. + self.assertEqual(line.count('noalias'), 2) + break + + def test_prange_raises_invalid_step_size(self): + def test_impl(N): + acc = 0 + for i in range(0, N, 2): + acc += 2 + return acc + + with self.assertRaises(errors.UnsupportedRewriteError) as raises: + self.prange_tester(test_impl, 1024) + msg = 'Only constant step size of 1 is supported for prange' + self.assertIn(msg, str(raises.exception)) + + @unittest.skip("skip due to issue #10203: https://github.com/numba/numba/issues/10203") + def test_prange_fastmath_check_works(self): + # this function will benefit from `fastmath`, the div will + # get optimised to a multiply by reciprocal and the accumulator + # then becomes an fmadd: A = A + i * 0.5 + def test_impl(): + n = 128 + A = 0 + for i in range(n): + A += i / 2.0 + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + pfunc = self.generate_prange_func(test_impl, None) + cres = self.compile_parallel_fastmath(pfunc, ()) + ir = self._get_gufunc_ir(cres) + _id = '%[A-Z_0-9]?(.[0-9]+)+[.]?[i]?' + recipr_str = r'\s+%s = fmul fast double %s, 5.000000e-01' + reciprocal_inst = re.compile(recipr_str % (_id, _id)) + fadd_inst = re.compile(r'\s+%s = fadd fast double %s, %s' + % (_id, _id, _id)) + # check there is something like: + # %.329 = fmul fast double %.325, 5.000000e-01 + # %.337 = fadd fast double %A.07, %.329 + found = False + for name, kernel in ir.items(): + # make sure to look at the kernel corresponding to the cres/pfunc + if name in cres.library.get_llvm_str(): + splitted = kernel.splitlines() + for i, x in enumerate(splitted): + if reciprocal_inst.match(x): + self.assertTrue(fadd_inst.match(splitted[i + 1])) + found = True + break + + self.assertTrue(found, "fast instruction pattern was not found.") + + def test_parfor_alias1(self): + def test_impl(n): + b = np.zeros((n, n)) + a = b[0] + for j in range(n): + a[j] = j + 1 + return b.sum() + self.prange_tester(test_impl, 4) + + def test_parfor_alias2(self): + def test_impl(n): + b = np.zeros((n, n)) + for i in range(n): + a = b[i] + for j in range(n): + a[j] = i + j + return b.sum() + self.prange_tester(test_impl, 4) + + def test_parfor_alias3(self): + def test_impl(n): + b = np.zeros((n, n, n)) + for i in range(n): + a = b[i] + for j in range(n): + c = a[j] + for k in range(n): + c[k] = i + j + k + return b.sum() + self.prange_tester(test_impl, 4) + + def test_parfor_race_1(self): + def test_impl(x, y): + for j in range(y): + k = x + return k + raised_warnings = self.prange_tester(test_impl, 10, 20) + warning_obj = raised_warnings[0] + expected_msg = ("Variable k used in parallel loop may be written to " + "simultaneously by multiple workers and may result " + "in non-deterministic or unintended results.") + self.assertIn(expected_msg, str(warning_obj.message)) + + def test_nested_parfor_push_call_vars(self): + """ issue 3686: if a prange has something inside it that causes + a nested parfor to be generated and both the inner and outer + parfor use the same call variable defined outside the parfors + then ensure that when that call variable is pushed into the + parfor that the call variable isn't duplicated with the same + name resulting in a redundant type lock. + """ + def test_impl(): + B = 0 + f = np.negative + for i in range(1): + this_matters = f(1.) + B += f(np.zeros(1,))[0] + for i in range(2): + this_matters = f(1.) + B += f(np.zeros(1,))[0] + + return B + self.prange_tester(test_impl) + + def test_copy_global_for_parfor(self): + """ issue4903: a global is copied next to a parfor so that + it can be inlined into the parfor and thus not have to be + passed to the parfor (i.e., an unsupported function type). + This global needs to be renamed in the block into which + it is copied. + """ + def test_impl(zz, tc): + lh = np.zeros(len(tc)) + lc = np.zeros(len(tc)) + for i in range(1): + nt = tc[i] + for t in range(nt): + lh += np.exp(zz[i, t]) + for t in range(nt): + lc += np.exp(zz[i, t]) + return lh, lc + + m = 2 + zz = np.ones((m, m, m)) + tc = np.ones(m, dtype=np.int_) + self.prange_tester(test_impl, zz, tc, patch_instance=[0]) + + def test_multiple_call_getattr_object(self): + def test_impl(n): + B = 0 + f = np.negative + for i in range(1): + this_matters = f(1.0) + B += f(n) + + return B + self.prange_tester(test_impl, 1.0) + + def test_argument_alias_recarray_field(self): + # Test for issue4007. + def test_impl(n): + for i in range(len(n)): + n.x[i] = 7.0 + return n + X1 = np.zeros(10, dtype=[('x', float), ('y', int), ]) + X2 = np.zeros(10, dtype=[('x', float), ('y', int), ]) + X3 = np.zeros(10, dtype=[('x', float), ('y', int), ]) + v1 = X1.view(np.recarray) + v2 = X2.view(np.recarray) + v3 = X3.view(np.recarray) + + # Numpy doesn't seem to support almost equal on recarray. + # So, we convert to list and use assertEqual instead. + python_res = list(test_impl(v1)) + njit_res = list(njit(test_impl)(v2)) + pa_func = njit(test_impl, parallel=True) + pa_res = list(pa_func(v3)) + self.assertEqual(python_res, njit_res) + self.assertEqual(python_res, pa_res) + + def test_mutable_list_param(self): + """ issue3699: test that mutable variable to call in loop + is not hoisted. The call in test_impl forces a manual + check here rather than using prange_tester. + """ + @njit + def list_check(X): + """ If the variable X is hoisted in the test_impl prange + then subsequent list_check calls would return increasing + values. + """ + ret = X[-1] + a = X[-1] + 1 + X.append(a) + return ret + def test_impl(n): + for i in prange(n): + X = [100] + a = list_check(X) + return a + python_res = test_impl(10) + njit_res = njit(test_impl)(10) + pa_func = njit(test_impl, parallel=True) + pa_res = pa_func(10) + self.assertEqual(python_res, njit_res) + self.assertEqual(python_res, pa_res) + + def test_list_comprehension_prange(self): + # issue4569 + def test_impl(x): + return np.array([len(x[i]) for i in range(len(x))]) + x = [np.array([1,2,3], dtype=int),np.array([1,2], dtype=int)] + self.prange_tester(test_impl, x) + + def test_ssa_false_reduction(self): + # issue5698 + # SSA for h creates assignments to h that make it look like a + # reduction variable except that it lacks an associated + # reduction operator. Test here that h is excluded as a + # reduction variable. + def test_impl(image, a, b): + empty = np.zeros(image.shape) + for i in range(image.shape[0]): + r = image[i][0] / 255.0 + if a == 0: + h = 0 + if b == 0: + h = 0 + empty[i] = [h, h, h] + return empty + + image = np.zeros((3, 3), dtype=np.int32) + self.prange_tester(test_impl, image, 0, 0) + + def test_list_setitem_hoisting(self): + # issue5979 + # Don't hoist list initialization if list item set. + def test_impl(): + n = 5 + a = np.empty(n, dtype=np.int64) + for k in range(5): + X = [0] + X[0] = 1 + a[k] = X[0] + return a + + self.prange_tester(test_impl) + + def test_tuple_hoisting(self): + # issue9529 + def test_impl(inputs): + outputs = [(Dict.empty(key_type=types.int64, value_type=types.float64), np.zeros(1)) for _ in range(len(inputs))] + for i in range(len(inputs)): + y = inputs[i] + out = np.zeros(1) + out[0] = i + outputs[i] = (inputs[i], out) + return outputs[0][1][0] + + N = config.NUMBA_NUM_THREADS + 1 + self.prange_tester(test_impl, [Dict.empty(key_type=types.int64, value_type=types.float64) for i in range(N)], patch_instance=[1]) + + def test_call_hoisting(self): + # issue9529 + def test_impl(inputs): + outputs = [(Dict.empty(key_type=types.int64, value_type=types.float64), np.zeros(1)) for _ in range(len(inputs))] + for i in range(len(inputs)): + y = inputs[i] + out = np.zeros(1) + out[0] = i + outputs[i] = test_call_hoisting_outcall(inputs[i], out) + return outputs[0][1][0] + + N = config.NUMBA_NUM_THREADS + 1 + self.prange_tester(test_impl, [Dict.empty(key_type=types.int64, value_type=types.float64) for i in range(N)], patch_instance=[1]) + + def test_record_array_setitem(self): + # issue6704 + state_dtype = np.dtype([('var', np.int32)]) + + def test_impl(states): + for i in range(1): + states[i]['var'] = 1 + + def comparer(a, b): + assert(a[0]['var'] == b[0]['var']) + + self.prange_tester(test_impl, + np.zeros(shape=1, dtype=state_dtype), + check_arg_equality=[comparer]) + + def test_record_array_setitem_yield_array(self): + state_dtype = np.dtype([('x', np.intp)]) + + def test_impl(states): + n = states.size + for i in range(states.size): + states["x"][i] = 7 + i + return states + + states = np.zeros(10, dtype=state_dtype) + + def comparer(a, b): + np.testing.assert_equal(a, b) + + self.prange_tester(test_impl, + states, + check_arg_equality=[comparer]) + + def test_issue7501(self): + def test_impl(size, case): + result = np.zeros((size,)) + if case == 1: + for i in range(size): + result[i] += 1 + else: + for i in range(size): + result[i] += 2 + return result[0] + + self.prange_tester(test_impl, 3, 1) + + def test_kde_example(self): + def test_impl(X): + # KDE example + b = 0.5 + points = np.array([-1.0, 2.0, 5.0]) + N = points.shape[0] + n = X.shape[0] + exps = 0 + for i in range(n): + p = X[i] + d = (-(p - points)**2) / (2 * b**2) + m = np.min(d) + exps += m - np.log(b * N) + np.log(np.sum(np.exp(d - m))) + return exps + + n = 128 + X = np.random.ranf(n) + self.prange_tester(test_impl, X) + + @skip_parfors_unsupported + def test_issue7578(self): + def test_impl(x): + A = np.zeros_like(x) + tmp = np.cos(x) # this can be any 1-arity ufunc + + for i in range(len(x)): + A[i] = tmp.sum() + + return A + + x = np.arange(10.) + self.prange_tester(test_impl, x) + +@skip_parfors_unsupported +class TestParforChunksizing(TestCase): + """ + Tests chunksize handling in ParallelAccelerator. + """ + _numba_parallel_test_ = False + + def setUp(self): + set_parallel_chunksize(0) + + def tearDown(self): + set_parallel_chunksize(0) + + def test_python_parallel_chunksize_basic(self): + # Test basic chunksize operations outside njit. + self.assertEqual(get_parallel_chunksize(), 0) + set_parallel_chunksize(8) + self.assertEqual(get_parallel_chunksize(), 8) + set_parallel_chunksize(0) + self.assertEqual(get_parallel_chunksize(), 0) + + def test_python_with_chunksize(self): + # Test "with parallel_chunksize" outside njit. + self.assertEqual(get_parallel_chunksize(), 0) + with parallel_chunksize(8): + self.assertEqual(get_parallel_chunksize(), 8) + self.assertEqual(get_parallel_chunksize(), 0) + + def test_njit_parallel_chunksize_basic(self): + # Test basic chunksize operations inside njit. + @njit + def get_cs(): + return get_parallel_chunksize() + + @njit + def set_cs(x): + return set_parallel_chunksize(x) + + self.assertEqual(get_cs(), 0) + set_cs(8) + self.assertEqual(get_cs(), 8) + set_cs(0) + self.assertEqual(get_cs(), 0) + + def test_njit_with_chunksize(self): + # Test "with parallel_chunksize" inside njit. + @njit + def test_impl(x): + cs1 = get_parallel_chunksize() + with parallel_chunksize(8): + cs2 = get_parallel_chunksize() + cs3 = get_parallel_chunksize() + return cs1, cs2, cs3 + + cs1, cs2, cs3 = test_impl(8) + + self.assertEqual(cs1, 0) + self.assertEqual(cs2, 8) + self.assertEqual(cs3, 0) + + def test_all_iterations_reset_chunksize(self): + """ Test that all the iterations get run if you set the + chunksize. Also check that the chunksize that each + worker thread sees has been reset to 0. """ + + @njit(parallel=True) + def test_impl(cs, n): + res = np.zeros(n) + inner_cs = np.full(n, -13) + with numba.parallel_chunksize(cs): + for i in numba.prange(n): + inner_cs[i] = numba.get_parallel_chunksize() + res[i] = 13 + return res, inner_cs + + # Test a variety of array and chunk sizes. + # 1000 is a round number, 997 is prime, 943 is product of two + # primes, 961 is square of a prime. + for j in [1000, 997, 943, 961]: + for i in range(15): + res, inner_cs = test_impl(i+1, j) + self.assertTrue(np.all(res == 13)) + self.assertTrue(np.all(inner_cs == 0)) + + def test_njit_parallel_chunksize_negative(self): + # Test negative set_parallel_chunksize inside njit. + with self.assertRaises(ValueError) as raised: + @njit + def neg_test(): + set_parallel_chunksize(-1) + + neg_test() + + msg = "chunksize must be greater than or equal to zero" + self.assertIn(msg, str(raised.exception)) + + def test_python_parallel_chunksize_negative(self): + # Test negative set_parallel_chunksize outside njit. + with self.assertRaises(ValueError) as raised: + set_parallel_chunksize(-1) + + msg = "chunksize must be greater than or equal to zero" + self.assertIn(msg, str(raised.exception)) + + def test_njit_parallel_chunksize_invalid_type(self): + with self.assertRaises(errors.TypingError) as raised: + @njit + def impl(): + set_parallel_chunksize('invalid_type') + + impl() + + msg = "The parallel chunksize must be an integer" + self.assertIn(msg, str(raised.exception)) + + def test_python_parallel_chunksize_invalid_type(self): + with self.assertRaises(TypeError) as raised: + set_parallel_chunksize('invalid_type') + + msg = "The parallel chunksize must be an integer" + self.assertIn(msg, str(raised.exception)) + + +@skip_parfors_unsupported +@x86_only +class TestParforsVectorizer(TestPrangeBase): + + # env mutating test + _numba_parallel_test_ = False + + def get_gufunc_asm(self, func, schedule_type, *args, **kwargs): + + fastmath = kwargs.pop('fastmath', False) + cpu_name = kwargs.pop('cpu_name', 'skylake-avx512') + assertions = kwargs.pop('assertions', True) + # force LLVM to use zmm registers for vectorization + # https://reviews.llvm.org/D67259 + cpu_features = kwargs.pop('cpu_features', '-prefer-256-bit') + + env_opts = {'NUMBA_CPU_NAME': cpu_name, + 'NUMBA_CPU_FEATURES': cpu_features, + } + + overrides = [] + for k, v in env_opts.items(): + overrides.append(override_env_config(k, v)) + + with overrides[0], overrides[1]: + sig = tuple([numba.typeof(x) for x in args]) + pfunc_vectorizable = self.generate_prange_func(func, None) + if fastmath == True: + cres = self.compile_parallel_fastmath(pfunc_vectorizable, sig) + else: + cres = self.compile_parallel(pfunc_vectorizable, sig) + + # get the gufunc asm + asm = self._get_gufunc_asm(cres) + + if assertions: + schedty = re.compile(r'call\s+\w+\*\s+@do_scheduling_(\w+)\(') + matches = schedty.findall(cres.library.get_llvm_str()) + self.assertGreaterEqual(len(matches), 1) # at least 1 parfor call + self.assertEqual(matches[0], schedule_type) + self.assertNotEqual(asm, {}) + + return asm + + @linux_only + @TestCase.run_test_in_subprocess + def test_vectorizer_fastmath_asm(self): + """ This checks that if fastmath is set and the underlying hardware + is suitable, and the function supplied is amenable to fastmath based + vectorization, that the vectorizer actually runs. + """ + + # This function will benefit from `fastmath` if run on a suitable + # target. The vectorizer should unwind the loop and generate + # packed dtype=double add and sqrt instructions. + def will_vectorize(A): + n = len(A) + acc = 0 + for i in range(n): + acc += np.sqrt(i) + return acc + + arg = np.zeros(10) + + fast_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg, + fastmath=True) + slow_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg, + fastmath=False) + for v in fast_asm.values(): + # should unwind and call vector sqrt then vector add + # all on packed doubles using zmm's + self.assertTrue('vaddpd' in v) + self.assertTrue('vsqrtpd' in v or '__svml_sqrt' in v) + self.assertTrue('zmm' in v) + + for v in slow_asm.values(): + # vector variants should not be present + self.assertTrue('vaddpd' not in v) + self.assertTrue('vsqrtpd' not in v) + # check scalar variant is present + self.assertTrue('vsqrtsd' in v and '__svml_sqrt' not in v) + self.assertTrue('vaddsd' in v) + # check no zmm addressing is present + self.assertTrue('zmm' not in v) + + @linux_only + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'}) + def test_unsigned_refusal_to_vectorize(self): + """ This checks that if fastmath is set and the underlying hardware + is suitable, and the function supplied is amenable to fastmath based + vectorization, that the vectorizer actually runs. + """ + + def will_not_vectorize(A): + n = len(A) + for i in range(-n, 0): + A[i] = np.sqrt(A[i]) + return A + + def will_vectorize(A): + n = len(A) + for i in range(n): + A[i] = np.sqrt(A[i]) + return A + + arg = np.zeros(10) + + # Boundschecking breaks vectorization + self.assertFalse(config.BOUNDSCHECK) + novec_asm = self.get_gufunc_asm(will_not_vectorize, 'signed', arg, + fastmath=True) + + vec_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg, + fastmath=True) + + for v in novec_asm.values(): + # vector variant should not be present + self.assertTrue('vsqrtpd' not in v) + # check scalar variant is present + self.assertTrue('vsqrtsd' in v) + # check no zmm addressing is present + self.assertTrue('zmm' not in v) + + for v in vec_asm.values(): + # should unwind and call vector sqrt then vector mov + # all on packed doubles using zmm's + self.assertTrue('vsqrtpd' in v or '__svml_sqrt' in v) + self.assertTrue('vmovupd' in v) + self.assertTrue('zmm' in v) + + @linux_only + # needed as 32bit doesn't have equivalent signed/unsigned instruction + # generation for this function + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'}) + def test_signed_vs_unsigned_vec_asm(self): + """ This checks vectorization for signed vs unsigned variants of a + trivial accumulator, the only meaningful difference should be the + presence of signed vs. unsigned unpack instructions (for the + induction var). + """ + def signed_variant(): + n = 4096 + A = 0. + for i in range(-n, 0): + A += i + return A + + def unsigned_variant(): + n = 4096 + A = 0. + for i in range(n): + A += i + return A + + # Boundschecking breaks the diff check below because of the pickled exception + self.assertFalse(config.BOUNDSCHECK) + signed_asm = self.get_gufunc_asm(signed_variant, 'signed', + fastmath=True) + unsigned_asm = self.get_gufunc_asm(unsigned_variant, 'unsigned', + fastmath=True) + + def strip_instrs(asm): + acc = [] + for x in asm.splitlines(): + spd = x.strip() + # filter out anything that isn't a trivial instruction + # and anything with the gufunc id as it contains an address + if spd != '' and not (spd.startswith('.') + or spd.startswith('_') + or spd.startswith('"') + or '__numba_parfor_gufunc' in spd): + acc.append(re.sub('[\t]', '', spd)) + return acc + + for k, v in signed_asm.items(): + signed_instr = strip_instrs(v) + break + + for k, v in unsigned_asm.items(): + unsigned_instr = strip_instrs(v) + break + + from difflib import SequenceMatcher as sm + # make sure that the only difference in instruction (if there is a + # difference) is the char 'u'. For example: + # vcvtsi2sdq vs. vcvtusi2sdq + self.assertEqual(len(signed_instr), len(unsigned_instr)) + for a, b in zip(signed_instr, unsigned_instr): + if a == b: + continue + else: + s = sm(lambda x: x == '\t', a, b) + ops = s.get_opcodes() + for op in ops: + if op[0] == 'insert': + self.assertEqual(b[op[-2]:op[-1]], 'u') + + +@skip_parfors_unsupported +class TestParforReductionSetNumThreads(TestCase): + """Test execution correctness on reductions with set_num_threads. + """ + def test_add(self): + N = config.NUMBA_NUM_THREADS + M = 2 * N + mask = N - 1 + + @njit(parallel=True) + def udt(nthreads): + acc = 0 + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + set_num_threads(local_mask) + gnt = get_num_threads() + acc += gnt + return acc + + expect = udt.py_func(mask) + got = udt(mask) + self.assertPreciseEqual(expect, got) + + def test_mul(self): + # This min will prevent larger thread counts from generating + # overflow in the loop below. + N = min(4, config.NUMBA_NUM_THREADS) + M = 2 * N + mask = N - 1 + + @njit(parallel=True) + def udt(nthreads): + acc = 1 + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + set_num_threads(local_mask) + gnt = get_num_threads() + acc *= gnt + return acc + + expect = udt.py_func(mask) + got = udt(mask) + self.assertPreciseEqual(expect, got) + + def test_max(self): + N = config.NUMBA_NUM_THREADS + M = 2 * N + mask = N - 1 + + @njit(parallel=True) + def udt(nthreads): + acc = 1 + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + set_num_threads(local_mask) + gnt = get_num_threads() + acc = max(acc, gnt) + return acc + + expect = udt.py_func(mask) + got = udt(mask) + self.assertPreciseEqual(expect, got) + + +@skip_parfors_unsupported +class TestDiagnosticEnvVar(TestCase): + @TestCase.run_test_in_subprocess() + def test_diagnostics_env_var1(self): + os.environ['NUMBA_PARALLEL_DIAGNOSTICS']='4' + with captured_stdout() as stdout: + @njit(parallel=True) + def impl(): + n = 100 + b = np.zeros((n), dtype=np.float64) + for i in prange(n): + b[i] = 1 + return b + + impl() + the_output = stdout.getvalue() + self.assertIn("Parallel Accelerator Optimizing", the_output) + + +if __name__ == "__main__": + unittest.main() diff --git a/shared/package-files/06/068572b5fe8fecf0585f2ce7721125299485bc4b05ca2981fad2c5770d0050da/python_to_arrow.h b/shared/package-files/06/068572b5fe8fecf0585f2ce7721125299485bc4b05ca2981fad2c5770d0050da/python_to_arrow.h new file mode 100644 index 0000000000000000000000000000000000000000..d167996ba8da6796ac62da0fa0186419a3211930 --- /dev/null +++ b/shared/package-files/06/068572b5fe8fecf0585f2ce7721125299485bc4b05ca2981fad2c5770d0050da/python_to_arrow.h @@ -0,0 +1,80 @@ +// 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. + +// Functions for converting between CPython built-in data structures and Arrow +// data structures + +#pragma once + +#include "arrow/python/platform.h" + +#include +#include + +#include "arrow/python/visibility.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" + +#include "arrow/python/common.h" + +namespace arrow { + +class Array; +class Status; + +namespace py { + +struct PyConversionOptions { + PyConversionOptions() = default; + + PyConversionOptions(const std::shared_ptr& type, int64_t size, + MemoryPool* pool, bool from_pandas) + : type(type), size(size), from_pandas(from_pandas) {} + + // Set to null if to be inferred + std::shared_ptr type; + + // Default is -1, which indicates the size should the same as the input sequence + int64_t size = -1; + + bool from_pandas = false; + + /// Used to maintain backwards compatibility for + /// timezone bugs (see ARROW-9528). Should be removed + /// after Arrow 2.0 release. + bool ignore_timezone = false; + + bool strict = false; +}; + +/// \brief Convert sequence (list, generator, NumPy array with dtype object) of +/// Python objects. +/// \param[in] obj the sequence to convert +/// \param[in] mask a NumPy array of true/false values to indicate whether +/// values in the sequence are null (true) or not null (false). This parameter +/// may be null +/// \param[in] options various conversion options +/// \param[in] pool MemoryPool to use for allocations +/// \return Result ChunkedArray +ARROW_PYTHON_EXPORT +Result> ConvertPySequence( + PyObject* obj, PyObject* mask, PyConversionOptions options, + MemoryPool* pool = default_memory_pool()); + +} // namespace py + +} // namespace arrow diff --git a/shared/package-files/06/068aeb2bcfd925b3791d67085fd7c23fe05b4c2689b20006522cdae48c2162be/test_indexing.py b/shared/package-files/06/068aeb2bcfd925b3791d67085fd7c23fe05b4c2689b20006522cdae48c2162be/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7daea16963c99fb7c4bbcd4b122d6af53d2576 --- /dev/null +++ b/shared/package-files/06/068aeb2bcfd925b3791d67085fd7c23fe05b4c2689b20006522cdae48c2162be/test_indexing.py @@ -0,0 +1,13 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize("na", [None, np.nan, pd.NA]) +def test_setitem_missing_values(na): + arr = pd.array([True, False, None], dtype="boolean") + expected = pd.array([True, None, None], dtype="boolean") + arr[1] = na + tm.assert_extension_array_equal(arr, expected) diff --git a/shared/package-files/06/0691beec28fe54d7b54fbfd59e72f2730e5b766f2bce096ea99ce8cd97290a0a/HermeticPyObjectTLS.h b/shared/package-files/06/0691beec28fe54d7b54fbfd59e72f2730e5b766f2bce096ea99ce8cd97290a0a/HermeticPyObjectTLS.h new file mode 100644 index 0000000000000000000000000000000000000000..741132b9f967c19a29e2d130890e0f5ef99289a2 --- /dev/null +++ b/shared/package-files/06/0691beec28fe54d7b54fbfd59e72f2730e5b766f2bce096ea99ce8cd97290a0a/HermeticPyObjectTLS.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include + +namespace c10::impl { + +// This TLS controls whether or not we permanently associate PyObject +// with Tensor the first time it is allocated. When hermetic PyObject +// TLS is enabled (state is true), we DO NOT save PyObjects to Tensor, +// meaning you get a distinct PyObject whenever you execute the code in +// question. +struct C10_API HermeticPyObjectTLS { + static void set_state(bool state); + static bool get_state() { + // Hypothetical fastpath if torchdeploy/multipy isn't used. Per + // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2055r0.pdf + // this qualifies relaxed access because it is a single-location data + // structure (only the boolean here). + // + // Forgetting about data races for a moment, is there a logical race? + // + // - Boolean only ever transitions from false to true. So the + // critical situation is when one interpreter is already running + // when a second interpreter switches haveState from false to true. + // + // - The first interpreter is indifferent whether or not it sees + // hasState true/false; obviously false works (this is what the + // interpreter was previously using; more directly, the interpreter + // calls into itself as the handler, so being hermetic is not + // required), and true simply means serviced python operator calls will + // be hermetic; in these cases it is expected to be functionally + // equivalent. + // + // - The second interpreter MUST see hasState true (as its requests will + // be forwarded to the first interpreter), but it is assumed that there + // is a synchronization between the interpreter initialization, and + // when we actually perform operations, so it is guaranteed to see + // hasState true. + // + // QED. + // + // This fastpath is currently disabled so that we can more easily test that + // hermetic mode works correctly even on stock build of PyTorch. + if (false && !haveState_.load(std::memory_order_relaxed)) + return false; + return get_tls_state(); + } + // Call this from the multipy/torchdeploy top level + static void init_state(); + + private: + // This only flipped once from false to true during torchdeploy/multipy + // initialization, and never again. + static std::atomic haveState_; + static bool get_tls_state(); +}; + +} // namespace c10::impl diff --git a/shared/package-files/06/0696387ae52f082e9e1db3ac73b862a4457cabf1ff19482947ff1a5da68c20e5/deterministic.py b/shared/package-files/06/0696387ae52f082e9e1db3ac73b862a4457cabf1ff19482947ff1a5da68c20e5/deterministic.py new file mode 100644 index 0000000000000000000000000000000000000000..98a6d30b067bb496e2a1a77e142974a98494997a --- /dev/null +++ b/shared/package-files/06/0696387ae52f082e9e1db3ac73b862a4457cabf1ff19482947ff1a5da68c20e5/deterministic.py @@ -0,0 +1,21 @@ +import sys +import types + +import torch + + +class _Deterministic(types.ModuleType): + @property + def fill_uninitialized_memory(self): + """ + Whether to fill uninitialized memory with a known value when + :meth:`torch.use_deterministic_algorithms()` is set to ``True``. + """ + return torch._C._get_deterministic_fill_uninitialized_memory() + + @fill_uninitialized_memory.setter + def fill_uninitialized_memory(self, mode): + return torch._C._set_deterministic_fill_uninitialized_memory(mode) + + +sys.modules[__name__].__class__ = _Deterministic diff --git a/shared/package-files/06/06968e91e34eec79631e5d7151b6158a44319d7ee329166163b3aa09a74b4e4c/BinaryInternal.h b/shared/package-files/06/06968e91e34eec79631e5d7151b6158a44319d7ee329166163b3aa09a74b4e4c/BinaryInternal.h new file mode 100644 index 0000000000000000000000000000000000000000..e098d32b114d604f6d9a1b5160dbe87de52c4595 --- /dev/null +++ b/shared/package-files/06/06968e91e34eec79631e5d7151b6158a44319d7ee329166163b3aa09a74b4e4c/BinaryInternal.h @@ -0,0 +1,48 @@ +// DON'T include this except from Binary*.cu files. It should not leak into +// headers. +#pragma once +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at { +namespace native { +namespace binary_internal { + +template +struct DivFunctor { + __device__ scalar_t operator()(scalar_t a, scalar_t b) const { + return a / b; + } +}; + +template +struct MulFunctor { + __device__ T operator()(T a, T b) const { + return a * b; + } +}; + +// Workaround for the error: '*' in boolean context, suggest '&&' instead +// [-Werror=int-in-bool-context] +template <> +struct MulFunctor { + __device__ bool operator()(bool a, bool b) const { + return a && b; + } +}; +void div_true_kernel_cuda(TensorIteratorBase& iter); +void div_trunc_kernel_cuda(TensorIteratorBase& iter); +} // namespace binary_internal +} // namespace native +} // namespace at diff --git a/shared/package-files/06/0696e309979cee7fae3a3fdc226bbe701d629950b8a1e2fcac95308f16e63787/widgets.pyi b/shared/package-files/06/0696e309979cee7fae3a3fdc226bbe701d629950b8a1e2fcac95308f16e63787/widgets.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ae88fbc5111fdbbb6f786fbf8dc112040b3d90c2 --- /dev/null +++ b/shared/package-files/06/0696e309979cee7fae3a3fdc226bbe701d629950b8a1e2fcac95308f16e63787/widgets.pyi @@ -0,0 +1,488 @@ +from .artist import Artist +from .axes import Axes +from .backend_bases import FigureCanvasBase, Event, MouseEvent, MouseButton +from .collections import LineCollection +from .figure import Figure +from .lines import Line2D +from .patches import Polygon, Rectangle +from .text import Text + +import PIL.Image + +from collections.abc import Callable, Collection, Iterable, Sequence +from typing import Any, Literal +from numpy.typing import ArrayLike +from .typing import ColorType +import numpy as np + +class LockDraw: + def __init__(self) -> None: ... + def __call__(self, o: Any) -> None: ... + def release(self, o: Any) -> None: ... + def available(self, o: Any) -> bool: ... + def isowner(self, o: Any) -> bool: ... + def locked(self) -> bool: ... + +class Widget: + drawon: bool + eventson: bool + active: bool + def set_active(self, active: bool) -> None: ... + def get_active(self) -> None: ... + def ignore(self, event) -> bool: ... + +class AxesWidget(Widget): + ax: Axes + def __init__(self, ax: Axes) -> None: ... + @property + def canvas(self) -> FigureCanvasBase | None: ... + def connect_event(self, event: Event, callback: Callable) -> None: ... + def disconnect_events(self) -> None: ... + +class Button(AxesWidget): + label: Text + color: ColorType + hovercolor: ColorType + def __init__( + self, + ax: Axes, + label: str, + image: ArrayLike | PIL.Image.Image | None = ..., + color: ColorType = ..., + hovercolor: ColorType = ..., + *, + useblit: bool = ... + ) -> None: ... + def on_clicked(self, func: Callable[[Event], Any]) -> int: ... + def disconnect(self, cid: int) -> None: ... + +class SliderBase(AxesWidget): + orientation: Literal["horizontal", "vertical"] + closedmin: bool + closedmax: bool + valmin: float + valmax: float + valstep: float | ArrayLike | None + drag_active: bool + valfmt: str + def __init__( + self, + ax: Axes, + orientation: Literal["horizontal", "vertical"], + closedmin: bool, + closedmax: bool, + valmin: float, + valmax: float, + valfmt: str, + dragging: Slider | None, + valstep: float | ArrayLike | None, + ) -> None: ... + def disconnect(self, cid: int) -> None: ... + def reset(self) -> None: ... + +class Slider(SliderBase): + slidermin: Slider | None + slidermax: Slider | None + val: float + valinit: float + track: Rectangle + poly: Polygon + hline: Line2D + vline: Line2D + label: Text + valtext: Text + def __init__( + self, + ax: Axes, + label: str, + valmin: float, + valmax: float, + *, + valinit: float = ..., + valfmt: str | None = ..., + closedmin: bool = ..., + closedmax: bool = ..., + slidermin: Slider | None = ..., + slidermax: Slider | None = ..., + dragging: bool = ..., + valstep: float | ArrayLike | None = ..., + orientation: Literal["horizontal", "vertical"] = ..., + initcolor: ColorType = ..., + track_color: ColorType = ..., + handle_style: dict[str, Any] | None = ..., + **kwargs + ) -> None: ... + def set_val(self, val: float) -> None: ... + def on_changed(self, func: Callable[[float], Any]) -> int: ... + +class RangeSlider(SliderBase): + val: tuple[float, float] + valinit: tuple[float, float] + track: Rectangle + poly: Polygon + label: Text + valtext: Text + def __init__( + self, + ax: Axes, + label: str, + valmin: float, + valmax: float, + *, + valinit: tuple[float, float] | None = ..., + valfmt: str | None = ..., + closedmin: bool = ..., + closedmax: bool = ..., + dragging: bool = ..., + valstep: float | ArrayLike | None = ..., + orientation: Literal["horizontal", "vertical"] = ..., + track_color: ColorType = ..., + handle_style: dict[str, Any] | None = ..., + **kwargs + ) -> None: ... + def set_min(self, min: float) -> None: ... + def set_max(self, max: float) -> None: ... + def set_val(self, val: ArrayLike) -> None: ... + def on_changed(self, func: Callable[[tuple[float, float]], Any]) -> int: ... + +class CheckButtons(AxesWidget): + labels: list[Text] + def __init__( + self, + ax: Axes, + labels: Sequence[str], + actives: Iterable[bool] | None = ..., + *, + useblit: bool = ..., + label_props: dict[str, Sequence[Any]] | None = ..., + frame_props: dict[str, Any] | None = ..., + check_props: dict[str, Any] | None = ..., + ) -> None: ... + def set_label_props(self, props: dict[str, Sequence[Any]]) -> None: ... + def set_frame_props(self, props: dict[str, Any]) -> None: ... + def set_check_props(self, props: dict[str, Any]) -> None: ... + def set_active(self, index: int, state: bool | None = ...) -> None: ... # type: ignore[override] + def clear(self) -> None: ... + def get_status(self) -> list[bool]: ... + def get_checked_labels(self) -> list[str]: ... + def on_clicked(self, func: Callable[[str | None], Any]) -> int: ... + def disconnect(self, cid: int) -> None: ... + +class TextBox(AxesWidget): + label: Text + text_disp: Text + cursor_index: int + cursor: LineCollection + color: ColorType + hovercolor: ColorType + capturekeystrokes: bool + def __init__( + self, + ax: Axes, + label: str, + initial: str = ..., + *, + color: ColorType = ..., + hovercolor: ColorType = ..., + label_pad: float = ..., + textalignment: Literal["left", "center", "right"] = ..., + ) -> None: ... + @property + def text(self) -> str: ... + def set_val(self, val: str) -> None: ... + def begin_typing(self) -> None: ... + def stop_typing(self) -> None: ... + def on_text_change(self, func: Callable[[str], Any]) -> int: ... + def on_submit(self, func: Callable[[str], Any]) -> int: ... + def disconnect(self, cid: int) -> None: ... + +class RadioButtons(AxesWidget): + activecolor: ColorType + value_selected: str + labels: list[Text] + def __init__( + self, + ax: Axes, + labels: Iterable[str], + active: int = ..., + activecolor: ColorType | None = ..., + *, + useblit: bool = ..., + label_props: dict[str, Sequence[Any]] | None = ..., + radio_props: dict[str, Any] | None = ..., + ) -> None: ... + def set_label_props(self, props: dict[str, Sequence[Any]]) -> None: ... + def set_radio_props(self, props: dict[str, Any]) -> None: ... + def set_active(self, index: int) -> None: ... + def clear(self) -> None: ... + def on_clicked(self, func: Callable[[str | None], Any]) -> int: ... + def disconnect(self, cid: int) -> None: ... + +class SubplotTool(Widget): + figure: Figure + targetfig: Figure + buttonreset: Button + def __init__(self, targetfig: Figure, toolfig: Figure) -> None: ... + +class Cursor(AxesWidget): + visible: bool + horizOn: bool + vertOn: bool + useblit: bool + lineh: Line2D + linev: Line2D + background: Any + needclear: bool + def __init__( + self, + ax: Axes, + *, + horizOn: bool = ..., + vertOn: bool = ..., + useblit: bool = ..., + **lineprops + ) -> None: ... + def clear(self, event: Event) -> None: ... + def onmove(self, event: Event) -> None: ... + +class MultiCursor(Widget): + axes: Sequence[Axes] + horizOn: bool + vertOn: bool + visible: bool + useblit: bool + vlines: list[Line2D] + hlines: list[Line2D] + def __init__( + self, + canvas: Any, + axes: Sequence[Axes], + *, + useblit: bool = ..., + horizOn: bool = ..., + vertOn: bool = ..., + **lineprops + ) -> None: ... + def connect(self) -> None: ... + def disconnect(self) -> None: ... + def clear(self, event: Event) -> None: ... + def onmove(self, event: Event) -> None: ... + +class _SelectorWidget(AxesWidget): + onselect: Callable[[float, float], Any] + useblit: bool + background: Any + validButtons: list[MouseButton] + def __init__( + self, + ax: Axes, + onselect: Callable[[float, float], Any] | None = ..., + useblit: bool = ..., + button: MouseButton | Collection[MouseButton] | None = ..., + state_modifier_keys: dict[str, str] | None = ..., + use_data_coordinates: bool = ..., + ) -> None: ... + def update_background(self, event: Event) -> None: ... + def connect_default_events(self) -> None: ... + def ignore(self, event: Event) -> bool: ... + def update(self) -> None: ... + def press(self, event: Event) -> bool: ... + def release(self, event: Event) -> bool: ... + def onmove(self, event: Event) -> bool: ... + def on_scroll(self, event: Event) -> None: ... + def on_key_press(self, event: Event) -> None: ... + def on_key_release(self, event: Event) -> None: ... + def set_visible(self, visible: bool) -> None: ... + def get_visible(self) -> bool: ... + def clear(self) -> None: ... + @property + def artists(self) -> tuple[Artist]: ... + def set_props(self, **props) -> None: ... + def set_handle_props(self, **handle_props) -> None: ... + def add_state(self, state: str) -> None: ... + def remove_state(self, state: str) -> None: ... + +class SpanSelector(_SelectorWidget): + snap_values: ArrayLike | None + onmove_callback: Callable[[float, float], Any] + minspan: float + grab_range: float + drag_from_anywhere: bool + ignore_event_outside: bool + def __init__( + self, + ax: Axes, + onselect: Callable[[float, float], Any], + direction: Literal["horizontal", "vertical"], + *, + minspan: float = ..., + useblit: bool = ..., + props: dict[str, Any] | None = ..., + onmove_callback: Callable[[float, float], Any] | None = ..., + interactive: bool = ..., + button: MouseButton | Collection[MouseButton] | None = ..., + handle_props: dict[str, Any] | None = ..., + grab_range: float = ..., + state_modifier_keys: dict[str, str] | None = ..., + drag_from_anywhere: bool = ..., + ignore_event_outside: bool = ..., + snap_values: ArrayLike | None = ..., + ) -> None: ... + def new_axes( + self, + ax: Axes, + *, + _props: dict[str, Any] | None = ..., + _init: bool = ..., + ) -> None: ... + def connect_default_events(self) -> None: ... + @property + def direction(self) -> Literal["horizontal", "vertical"]: ... + @direction.setter + def direction(self, direction: Literal["horizontal", "vertical"]) -> None: ... + @property + def extents(self) -> tuple[float, float]: ... + @extents.setter + def extents(self, extents: tuple[float, float]) -> None: ... + +class ToolLineHandles: + ax: Axes + def __init__( + self, + ax: Axes, + positions: ArrayLike, + direction: Literal["horizontal", "vertical"], + *, + line_props: dict[str, Any] | None = ..., + useblit: bool = ..., + ) -> None: ... + @property + def artists(self) -> tuple[Line2D]: ... + @property + def positions(self) -> list[float]: ... + @property + def direction(self) -> Literal["horizontal", "vertical"]: ... + def set_data(self, positions: ArrayLike) -> None: ... + def set_visible(self, value: bool) -> None: ... + def set_animated(self, value: bool) -> None: ... + def remove(self) -> None: ... + def closest(self, x: float, y: float) -> tuple[int, float]: ... + +class ToolHandles: + ax: Axes + def __init__( + self, + ax: Axes, + x: ArrayLike, + y: ArrayLike, + *, + marker: str = ..., + marker_props: dict[str, Any] | None = ..., + useblit: bool = ..., + ) -> None: ... + @property + def x(self) -> ArrayLike: ... + @property + def y(self) -> ArrayLike: ... + @property + def artists(self) -> tuple[Line2D]: ... + def set_data(self, pts: ArrayLike, y: ArrayLike | None = ...) -> None: ... + def set_visible(self, val: bool) -> None: ... + def set_animated(self, val: bool) -> None: ... + def closest(self, x: float, y: float) -> tuple[int, float]: ... + +class RectangleSelector(_SelectorWidget): + drag_from_anywhere: bool + ignore_event_outside: bool + minspanx: float + minspany: float + spancoords: Literal["data", "pixels"] + grab_range: float + def __init__( + self, + ax: Axes, + onselect: Callable[[MouseEvent, MouseEvent], Any] | None = ..., + *, + minspanx: float = ..., + minspany: float = ..., + useblit: bool = ..., + props: dict[str, Any] | None = ..., + spancoords: Literal["data", "pixels"] = ..., + button: MouseButton | Collection[MouseButton] | None = ..., + grab_range: float = ..., + handle_props: dict[str, Any] | None = ..., + interactive: bool = ..., + state_modifier_keys: dict[str, str] | None = ..., + drag_from_anywhere: bool = ..., + ignore_event_outside: bool = ..., + use_data_coordinates: bool = ..., + ) -> None: ... + @property + def corners(self) -> tuple[np.ndarray, np.ndarray]: ... + @property + def edge_centers(self) -> tuple[np.ndarray, np.ndarray]: ... + @property + def center(self) -> tuple[float, float]: ... + @property + def extents(self) -> tuple[float, float, float, float]: ... + @extents.setter + def extents(self, extents: tuple[float, float, float, float]) -> None: ... + @property + def rotation(self) -> float: ... + @rotation.setter + def rotation(self, value: float) -> None: ... + @property + def geometry(self) -> np.ndarray: ... + +class EllipseSelector(RectangleSelector): ... + +class LassoSelector(_SelectorWidget): + verts: None | list[tuple[float, float]] + def __init__( + self, + ax: Axes, + onselect: Callable[[list[tuple[float, float]]], Any] | None = ..., + *, + useblit: bool = ..., + props: dict[str, Any] | None = ..., + button: MouseButton | Collection[MouseButton] | None = ..., + ) -> None: ... + +class PolygonSelector(_SelectorWidget): + grab_range: float + def __init__( + self, + ax: Axes, + onselect: Callable[[ArrayLike, ArrayLike], Any] | None = ..., + *, + useblit: bool = ..., + props: dict[str, Any] | None = ..., + handle_props: dict[str, Any] | None = ..., + grab_range: float = ..., + draw_bounding_box: bool = ..., + box_handle_props: dict[str, Any] | None = ..., + box_props: dict[str, Any] | None = ... + ) -> None: ... + def onmove(self, event: Event) -> bool: ... + @property + def verts(self) -> list[tuple[float, float]]: ... + @verts.setter + def verts(self, xys: Sequence[tuple[float, float]]) -> None: ... + +class Lasso(AxesWidget): + useblit: bool + background: Any + verts: list[tuple[float, float]] | None + line: Line2D + callback: Callable[[list[tuple[float, float]]], Any] + def __init__( + self, + ax: Axes, + xy: tuple[float, float], + callback: Callable[[list[tuple[float, float]]], Any], + *, + useblit: bool = ..., + props: dict[str, Any] | None = ..., + ) -> None: ... + def onrelease(self, event: Event) -> None: ... + def onmove(self, event: Event) -> None: ... diff --git a/shared/package-files/06/069723f7ea5e8585b6d2f9f8298f7ca400d07790348330d4b94936cb8f07cf23/test_warning.py b/shared/package-files/06/069723f7ea5e8585b6d2f9f8298f7ca400d07790348330d4b94936cb8f07cf23/test_warning.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b32dbb0a709174c89726d304c0629d2ef1651f --- /dev/null +++ b/shared/package-files/06/069723f7ea5e8585b6d2f9f8298f7ca400d07790348330d4b94936cb8f07cf23/test_warning.py @@ -0,0 +1,139 @@ +import numpy as np +from numba import cuda +from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim +from numba.tests.support import linux_only, override_config +from numba.core.errors import NumbaPerformanceWarning +import warnings + + +@skip_on_cudasim('cudasim does not raise performance warnings') +class TestWarnings(CUDATestCase): + def test_inefficient_launch_configuration(self): + @cuda.jit + def kernel(): + pass + + with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1): + with warnings.catch_warnings(record=True) as w: + kernel[1, 1]() + + self.assertEqual(w[0].category, NumbaPerformanceWarning) + self.assertIn('Grid size', str(w[0].message)) + self.assertIn('low occupancy', str(w[0].message)) + + def test_efficient_launch_configuration(self): + @cuda.jit + def kernel(): + pass + + with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1): + with warnings.catch_warnings(record=True) as w: + kernel[256, 256]() + + self.assertEqual(len(w), 0) + + def test_warn_on_host_array(self): + @cuda.jit + def foo(r, x): + r[0] = x + 1 + + N = 10 + arr_f32 = np.zeros(N, dtype=np.float32) + with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1): + with warnings.catch_warnings(record=True) as w: + foo[1, N](arr_f32, N) + + self.assertEqual(w[0].category, NumbaPerformanceWarning) + self.assertIn('Host array used in CUDA kernel will incur', + str(w[0].message)) + self.assertIn('copy overhead', str(w[0].message)) + + def test_pinned_warn_on_host_array(self): + @cuda.jit + def foo(r, x): + r[0] = x + 1 + + N = 10 + ary = cuda.pinned_array(N, dtype=np.float32) + + with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1): + with warnings.catch_warnings(record=True) as w: + foo[1, N](ary, N) + + self.assertEqual(w[0].category, NumbaPerformanceWarning) + self.assertIn('Host array used in CUDA kernel will incur', + str(w[0].message)) + self.assertIn('copy overhead', str(w[0].message)) + + def test_nowarn_on_mapped_array(self): + @cuda.jit + def foo(r, x): + r[0] = x + 1 + + N = 10 + ary = cuda.mapped_array(N, dtype=np.float32) + + with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1): + with warnings.catch_warnings(record=True) as w: + foo[1, N](ary, N) + + self.assertEqual(len(w), 0) + + @linux_only + def test_nowarn_on_managed_array(self): + @cuda.jit + def foo(r, x): + r[0] = x + 1 + + N = 10 + ary = cuda.managed_array(N, dtype=np.float32) + + with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1): + with warnings.catch_warnings(record=True) as w: + foo[1, N](ary, N) + + self.assertEqual(len(w), 0) + + def test_nowarn_on_device_array(self): + @cuda.jit + def foo(r, x): + r[0] = x + 1 + + N = 10 + ary = cuda.device_array(N, dtype=np.float32) + + with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1): + with warnings.catch_warnings(record=True) as w: + foo[1, N](ary, N) + + self.assertEqual(len(w), 0) + + def test_warn_on_debug_and_opt(self): + with warnings.catch_warnings(record=True) as w: + cuda.jit(debug=True, opt=True) + + self.assertEqual(len(w), 1) + self.assertIn('not supported by CUDA', str(w[0].message)) + + def test_warn_on_debug_and_opt_default(self): + with warnings.catch_warnings(record=True) as w: + cuda.jit(debug=True) + + self.assertEqual(len(w), 1) + self.assertIn('not supported by CUDA', str(w[0].message)) + + def test_no_warn_on_debug_and_no_opt(self): + with warnings.catch_warnings(record=True) as w: + cuda.jit(debug=True, opt=False) + + self.assertEqual(len(w), 0) + + def test_no_warn_with_no_debug_and_opt_kwargs(self): + with warnings.catch_warnings(record=True) as w: + cuda.jit() + + self.assertEqual(len(w), 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/06/069ad718312002b3c0a162ef04ff183de7efe6fbca3f338dcc1d5b4ab467cda1/test_min_dependencies_readme.py b/shared/package-files/06/069ad718312002b3c0a162ef04ff183de7efe6fbca3f338dcc1d5b4ab467cda1/test_min_dependencies_readme.py new file mode 100644 index 0000000000000000000000000000000000000000..6afcd3e57ca04b4a6e200925f59a5318770b307c --- /dev/null +++ b/shared/package-files/06/069ad718312002b3c0a162ef04ff183de7efe6fbca3f338dcc1d5b4ab467cda1/test_min_dependencies_readme.py @@ -0,0 +1,133 @@ +"""Tests for the minimum dependencies in README.rst and pyproject.toml""" + +import os +import re +from collections import defaultdict +from pathlib import Path + +import pytest + +import sklearn +from sklearn._min_dependencies import dependent_packages +from sklearn.utils.fixes import parse_version + +min_depencies_tag_to_packages_without_version = defaultdict(list) +for package, (min_version, extras) in dependent_packages.items(): + for extra in extras.split(", "): + min_depencies_tag_to_packages_without_version[extra].append(package) + +min_dependencies_tag_to_pyproject_section = { + "build": "build-system.requires", + "install": "project.dependencies", +} +for tag in min_depencies_tag_to_packages_without_version: + min_dependencies_tag_to_pyproject_section[tag] = ( + f"project.optional-dependencies.{tag}" + ) + + +def test_min_dependencies_readme(): + # Test that the minimum dependencies in the README.rst file are + # consistent with the minimum dependencies defined at the file: + # sklearn/_min_dependencies.py + + pattern = re.compile( + r"\.\. \|" + r"([A-Za-z-]+)" + r"MinVersion\| replace::" + r"( [0-9]+\.[0-9]+(\.[0-9]+)?)" + ) + + readme_path = Path(sklearn.__file__).parent.parent + readme_file = readme_path / "README.rst" + + if not os.path.exists(readme_file): + # Skip the test if the README.rst file is not available. + # For instance, when installing scikit-learn from wheels + pytest.skip("The README.rst file is not available.") + + with readme_file.open("r") as f: + for line in f: + matched = pattern.match(line) + + if not matched: + continue + + package, version = matched.group(0), matched.group(1) + package = package.lower() + + if package in dependent_packages: + version = parse_version(version) + min_version = parse_version(dependent_packages[package][0]) + + assert version == min_version, f"{package} has a mismatched version" + + +def check_pyproject_section( + pyproject_section, min_dependencies_tag, skip_version_check_for=None +): + # tomllib is available in Python 3.11 + tomllib = pytest.importorskip("tomllib") + + if skip_version_check_for is None: + skip_version_check_for = [] + + expected_packages = min_depencies_tag_to_packages_without_version[ + min_dependencies_tag + ] + + root_directory = Path(sklearn.__file__).parent.parent + pyproject_toml_path = root_directory / "pyproject.toml" + + if not pyproject_toml_path.exists(): + # Skip the test if the pyproject.toml file is not available. + # For instance, when installing scikit-learn from wheels + pytest.skip("pyproject.toml is not available.") + + with pyproject_toml_path.open("rb") as f: + pyproject_toml = tomllib.load(f) + + pyproject_section_keys = pyproject_section.split(".") + info = pyproject_toml + for key in pyproject_section_keys: + info = info[key] + + pyproject_build_min_versions = {} + for requirement in info: + if ">=" in requirement: + package, version = requirement.split(">=") + elif "==" in requirement: + package, version = requirement.split("==") + else: + raise NotImplementedError( + f"{requirement} not supported yet in this test. " + "Only >= and == are supported for version requirements" + ) + + pyproject_build_min_versions[package] = version + + assert sorted(pyproject_build_min_versions) == sorted(expected_packages) + + for package, version in pyproject_build_min_versions.items(): + version = parse_version(version) + expected_min_version = parse_version(dependent_packages[package][0]) + if package in skip_version_check_for: + continue + + assert version == expected_min_version, f"{package} has a mismatched version" + + +@pytest.mark.parametrize( + "min_dependencies_tag, pyproject_section", + min_dependencies_tag_to_pyproject_section.items(), +) +def test_min_dependencies_pyproject_toml(pyproject_section, min_dependencies_tag): + """Check versions in pyproject.toml is consistent with _min_dependencies.""" + # NumPy is more complex because build-time (>=1.25) and run-time (>=1.19.5) + # requirement currently don't match + skip_version_check_for = ["numpy"] if min_dependencies_tag == "build" else None + check_pyproject_section( + pyproject_section, + min_dependencies_tag, + skip_version_check_for=skip_version_check_for, + ) diff --git a/shared/package-files/06/069d4ee48ec2edb74e10982f4c730a0d8d39bd5c9f7d2cc97ff5322a179999ea/special_bessel_y0.h b/shared/package-files/06/069d4ee48ec2edb74e10982f4c730a0d8d39bd5c9f7d2cc97ff5322a179999ea/special_bessel_y0.h new file mode 100644 index 0000000000000000000000000000000000000000..0af360b48aa33ef101d0bca001227d09611dea6d --- /dev/null +++ b/shared/package-files/06/069d4ee48ec2edb74e10982f4c730a0d8d39bd5c9f7d2cc97ff5322a179999ea/special_bessel_y0.h @@ -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::special_bessel_y0(Tensor self) -> Tensor +inline at::Tensor special_bessel_y0(const at::Tensor & self) { + return at::_ops::special_bessel_y0::call(self); +} + +// aten::special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_bessel_y0_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_bessel_y0_out::call(self, out); +} +// aten::special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_bessel_y0_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_bessel_y0_out::call(self, out); +} + +} diff --git a/shared/package-files/06/069d8f07866ea9e33218850c0e8d5d0a08397899e08d6983aae65c6e82e582fa/test_pca.py b/shared/package-files/06/069d8f07866ea9e33218850c0e8d5d0a08397899e08d6983aae65c6e82e582fa/test_pca.py new file mode 100644 index 0000000000000000000000000000000000000000..87ce9456a6211905f6ccd5da472e63b0b3bb2f25 --- /dev/null +++ b/shared/package-files/06/069d8f07866ea9e33218850c0e8d5d0a08397899e08d6983aae65c6e82e582fa/test_pca.py @@ -0,0 +1,472 @@ +from statsmodels.compat.platform import PLATFORM_WIN32 + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pandas as pd +import pytest + +from statsmodels.multivariate.pca import PCA, pca +from statsmodels.multivariate.tests.results.datamlw import ( + data, + princomp1, + princomp2, +) +from statsmodels.tools.sm_exceptions import EstimationWarning, ValueWarning + +DECIMAL_5 = 0.00001 + + +class TestPCA: + @classmethod + def setup_class(cls): + rs = np.random.RandomState() + rs.seed(1234) + k = 3 + n = 100 + t = 200 + lam = 2 + + norm_rng = rs.standard_normal + e = norm_rng((t, n)) + f = norm_rng((t, k)) + b = rs.standard_gamma(lam, size=(k, n)) / lam + cls.x = f.dot(b) + e + cls.x_copy = cls.x + 0.0 + cls.rs = rs + + k = 3 + n = 300 + t = 200 + lam = 2 + + norm_rng = rs.standard_normal + e = norm_rng((t, n)) + f = norm_rng((t, k)) + b = rs.standard_gamma(lam, size=(k, n)) / lam + cls.x_wide = f.dot(b) + e + + @pytest.mark.smoke + @pytest.mark.thread_unsafe(reason="Uses matplotlib") + @pytest.mark.matplotlib + def test_smoke_plot_and_repr(self, close_figures): + pc = PCA(self.x) + pc.plot_scree() + pc.plot_scree(ncomp=10) + pc.plot_scree(log_scale=False) + pc.plot_scree(cumulative=True) + pc.plot_rsquare() + pc.plot_rsquare(ncomp=5) + # Additional smoke test + pc.__repr__() + pc = PCA(self.x, standardize=False) + pc.__repr__() + pc = PCA(self.x, standardize=False, demean=False) + pc.__repr__() + pc = PCA(self.x, ncomp=2, gls=True) + assert "GLS" in pc.__repr__() + # Check data for no changes + assert_equal(self.x, pc.data) + + def test_eig_svd_equiv(self): + # Test leading components since the tail end can differ + pc_eig = PCA(self.x) + pc_svd = PCA(self.x, method="svd") + + assert_allclose(pc_eig.projection, pc_svd.projection) + assert_allclose(np.abs(pc_eig.factors[:, :2]), np.abs(pc_svd.factors[:, :2])) + assert_allclose(np.abs(pc_eig.coeff[:2, :]), np.abs(pc_svd.coeff[:2, :])) + assert_allclose(pc_eig.eigenvals, pc_svd.eigenvals) + assert_allclose( + np.abs(pc_eig.eigenvecs[:, :2]), np.abs(pc_svd.eigenvecs[:, :2]) + ) + + pc_svd = PCA(self.x, method="svd", ncomp=2) + pc_nipals = PCA(self.x, method="nipals", ncomp=2) + assert_allclose( + np.abs(pc_nipals.factors), np.abs(pc_svd.factors), atol=DECIMAL_5 + ) + assert_allclose(np.abs(pc_nipals.coeff), np.abs(pc_svd.coeff), atol=DECIMAL_5) + assert_allclose(pc_nipals.eigenvals, pc_svd.eigenvals, atol=DECIMAL_5) + assert_allclose( + np.abs(pc_nipals.eigenvecs), np.abs(pc_svd.eigenvecs), atol=DECIMAL_5 + ) + # Check data for no changes + assert_equal(self.x, pc_svd.data) + # Check data for no changes + assert_equal(self.x, pc_eig.data) + # Check data for no changes + assert_equal(self.x, pc_nipals.data) + + def test_options(self): + pc = PCA(self.x) + pc_no_norm = PCA(self.x, normalize=False) + assert_allclose( + pc.factors.dot(pc.coeff), pc_no_norm.factors.dot(pc_no_norm.coeff) + ) + princomp = pc.factors + assert_allclose(princomp.T.dot(princomp), np.eye(100), atol=1e-5) + weights = pc_no_norm.coeff + assert_allclose(weights.T.dot(weights), np.eye(100), atol=1e-5) + + pc_10 = PCA(self.x, ncomp=10) + assert_allclose(pc.factors[:, :10], pc_10.factors) + assert_allclose(pc.coeff[:10, :], pc_10.coeff) + assert_allclose(pc.rsquare[: (10 + 1)], pc_10.rsquare) + assert_allclose(pc.eigenvals[:10], pc_10.eigenvals) + assert_allclose(pc.eigenvecs[:, :10], pc_10.eigenvecs) + + pc = PCA(self.x, standardize=False, normalize=False) + mu = self.x.mean(0) + xdm = self.x - mu + xpx = xdm.T.dot(xdm) + val, vec = np.linalg.eigh(xpx) + ind = np.argsort(val) + ind = ind[::-1] + val = val[ind] + vec = vec[:, ind] + assert_allclose(xdm, pc.transformed_data) + assert_allclose(val, pc.eigenvals) + assert_allclose(np.abs(vec), np.abs(pc.eigenvecs)) + assert_allclose(np.abs(pc.factors), np.abs(xdm.dot(vec))) + assert_allclose(pc.projection, xdm + mu) + + pc = PCA(self.x, standardize=False, demean=False, normalize=False) + x = self.x + xpx = x.T.dot(x) + val, vec = np.linalg.eigh(xpx) + ind = np.argsort(val) + ind = ind[::-1] + val = val[ind] + vec = vec[:, ind] + assert_allclose(x, pc.transformed_data) + assert_allclose(val, pc.eigenvals) + assert_allclose(np.abs(vec), np.abs(pc.eigenvecs)) + assert_allclose(np.abs(pc.factors), np.abs(x.dot(vec))) + + def test_against_reference(self): + # Test against MATLAB, which by default demeans but does not standardize + x = data.xo / 1000.0 + pc = PCA(x, normalize=False, standardize=False) + + ref = princomp1 + assert_allclose(np.abs(pc.factors), np.abs(ref.factors)) + assert_allclose(pc.factors.dot(pc.coeff) + x.mean(0), x) + assert_allclose(np.abs(pc.coeff), np.abs(ref.coef.T)) + assert_allclose(pc.factors.dot(pc.coeff), ref.factors.dot(ref.coef.T)) + + pc = PCA(x[:20], normalize=False, standardize=False) + mu = x[:20].mean(0) + ref = princomp2 + assert_allclose(np.abs(pc.factors), np.abs(ref.factors)) + assert_allclose(pc.factors.dot(pc.coeff) + mu, x[:20]) + assert_allclose(np.abs(pc.coeff), np.abs(ref.coef.T)) + assert_allclose(pc.factors.dot(pc.coeff), ref.factors.dot(ref.coef.T)) + + @pytest.mark.thread_unsafe(reason="Issues and checks warnings") + def test_warnings(self): + with pytest.warns(ValueWarning, match="The requested number of components"): + PCA(self.x, ncomp=300) + + rs = self.rs + x = rs.standard_normal((200, 1)) * np.ones(200) + with pytest.warns(EstimationWarning, match="Only"): + PCA(x, method="eig") + + def test_errors(self): + with pytest.raises(ValueError): + PCA(self.x, method="unknown") + with pytest.raises(ValueError): + PCA(self.x, missing="unknown") + with pytest.raises(ValueError): + PCA(self.x, tol=2.0) + with pytest.raises(ValueError): + PCA(np.nan * np.ones((200, 100)), tol=2.0) + + @pytest.mark.thread_unsafe(reason="Uses matplotlib") + @pytest.mark.matplotlib + def test_pandas(self, close_figures): + pc = PCA(pd.DataFrame(self.x)) + pc1 = PCA(self.x) + assert_allclose(pc.factors.values, pc1.factors) + pc.plot_scree() + pc.plot_scree(ncomp=10) + pc.plot_scree(log_scale=False) + pc.plot_rsquare() + pc.plot_rsquare(ncomp=5) + pc.project(2) + PCA(pd.DataFrame(self.x), ncomp=4, gls=True) + PCA(pd.DataFrame(self.x), ncomp=4, standardize=False) + + def test_gls_and_weights(self): + with pytest.raises(ValueError): + PCA(self.x, gls=True) + with pytest.raises(ValueError): + PCA(self.x, weights=np.array([1.0, 1.0])) + + # Pre-standardize to make comparison simple + x = self.x - self.x.mean(0) + x = x / (x**2.0).mean(0) + pc_gls = PCA(x, ncomp=1, standardize=False, demean=False, gls=True) + pc = PCA(x, ncomp=1, standardize=False, demean=False) + errors = x - pc.projection + var = (errors**2.0).mean(0) + weights = 1.0 / var + weights = weights / np.sqrt((weights**2.0).mean()) + + assert_allclose(weights, pc_gls.weights) + assert_equal(x, pc_gls.data) + assert_equal(x, pc.data) + + pc_weights = PCA(x, ncomp=1, standardize=False, demean=False, weights=weights) + + assert_allclose(weights, pc_weights.weights) + assert_allclose(np.abs(pc_weights.factors), np.abs(pc_gls.factors)) + + @pytest.mark.slow + def test_wide(self): + pc = PCA(self.x_wide) + assert_equal(pc.factors.shape[1], self.x_wide.shape[0]) + assert_equal(pc.eigenvecs.shape[1], min(np.array(self.x_wide.shape))) + + pc = PCA(pd.DataFrame(self.x_wide)) + assert_equal(pc.factors.shape[1], self.x_wide.shape[0]) + assert_equal(pc.eigenvecs.shape[1], min(np.array(self.x_wide.shape))) + + def test_projection(self): + pc = PCA(self.x, ncomp=5) + mu = self.x.mean(0) + demean_x = self.x - mu + coef = np.linalg.pinv(pc.factors).dot(demean_x) + direct = pc.factors.dot(coef) + assert_allclose(pc.projection, direct + mu) + + pc = PCA(self.x, standardize=False, ncomp=5) + coef = np.linalg.pinv(pc.factors).dot(demean_x) + direct = pc.factors.dot(coef) + assert_allclose(pc.projection, direct + mu) + + pc = PCA(self.x, standardize=False, demean=False, ncomp=5) + coef = np.linalg.pinv(pc.factors).dot(self.x) + direct = pc.factors.dot(coef) + assert_allclose(pc.projection, direct) + + pc = PCA(self.x, ncomp=5, gls=True) + mu = self.x.mean(0) + demean_x = self.x - mu + coef = np.linalg.pinv(pc.factors).dot(demean_x) + direct = pc.factors.dot(coef) + assert_allclose(pc.projection, direct + mu) + + pc = PCA(self.x, standardize=False, ncomp=5) + coef = np.linalg.pinv(pc.factors).dot(demean_x) + direct = pc.factors.dot(coef) + assert_allclose(pc.projection, direct + mu) + + pc = PCA(self.x, standardize=False, demean=False, ncomp=5, gls=True) + coef = np.linalg.pinv(pc.factors).dot(self.x) + direct = pc.factors.dot(coef) + assert_allclose(pc.projection, direct) + + # Test error for too many factors + project = pc.project + with pytest.raises(ValueError): + project(6) + + @pytest.mark.skipif(PLATFORM_WIN32, reason="Windows 32-bit") + def test_replace_missing(self): + x = self.x.copy() + x[::5, ::7] = np.nan + + pc = PCA(x, missing="drop-row") + x_dropped_row = x[np.logical_not(np.any(np.isnan(x), 1))] + pc_dropped = PCA(x_dropped_row) + assert_allclose(pc.projection, pc_dropped.projection) + assert_equal(x, pc.data) + + pc = PCA(x, missing="drop-col") + x_dropped_col = x[:, np.logical_not(np.any(np.isnan(x), 0))] + pc_dropped = PCA(x_dropped_col) + assert_allclose(pc.projection, pc_dropped.projection) + assert_equal(x, pc.data) + + pc = PCA(x, missing="drop-min") + if x_dropped_row.size > x_dropped_col.size: + x_dropped_min = x_dropped_row + else: + x_dropped_min = x_dropped_col + pc_dropped = PCA(x_dropped_min) + assert_allclose(pc.projection, pc_dropped.projection) + assert_equal(x, pc.data) + + pc = PCA(x, ncomp=3, missing="fill-em") + missing = np.isnan(x) + mu = np.nanmean(x, axis=0) + errors = x - mu + sigma = np.sqrt(np.nanmean(errors**2, axis=0)) + x_std = errors / sigma + x_std[missing] = 0.0 + last = x_std[missing] + delta = 1.0 + count = 0 + while delta > 5e-8: + pc_temp = PCA(x_std, ncomp=3, standardize=False, demean=False) + x_std[missing] = pc_temp.projection[missing] + current = x_std[missing] + diff = current - last + delta = np.sqrt(np.sum(diff**2)) / np.sqrt(np.sum(current**2)) + last = current + count += 1 + x = self.x + 0.0 + projection = pc_temp.projection * sigma + mu + x[missing] = projection[missing] + assert_allclose(pc._adjusted_data, x) + # Check data for no changes + assert_equal(self.x, self.x_copy) + + x = self.x + pc = PCA(x) + pc_dropped = PCA(x, missing="drop-row") + assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5) + + pc_dropped = PCA(x, missing="drop-col") + assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5) + + pc_dropped = PCA(x, missing="drop-min") + assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5) + + pc = PCA(x, ncomp=3) + pc_dropped = PCA(x, ncomp=3, missing="fill-em") + assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5) + + # Test too many missing for missing='fill-em' + x = self.x.copy() + x[:, :] = np.nan + with pytest.raises(ValueError): + PCA(x, missing="drop-row") + with pytest.raises(ValueError): + PCA(x, missing="drop-col") + with pytest.raises(ValueError): + PCA(x, missing="drop-min") + with pytest.raises(ValueError): + PCA(x, missing="fill-em") + + def test_rsquare(self): + x = self.x + 0.0 + mu = x.mean(0) + x_demean = x - mu + std = np.std(x, 0) + x_std = x_demean / std + + pc = PCA(self.x) + nvar = x.shape[1] + rsquare = np.zeros(nvar + 1) + tss = np.sum(x_std**2) + for i in range(nvar + 1): + errors = x_std - pc.project(i, transform=False, unweight=False) + rsquare[i] = 1.0 - np.sum(errors**2) / tss + assert_allclose(rsquare, pc.rsquare) + + pc = PCA(self.x, standardize=False) + tss = np.sum(x_demean**2) + for i in range(nvar + 1): + errors = x_demean - pc.project(i, transform=False, unweight=False) + rsquare[i] = 1.0 - np.sum(errors**2) / tss + assert_allclose(rsquare, pc.rsquare) + + pc = PCA(self.x, standardize=False, demean=False) + tss = np.sum(x**2) + for i in range(nvar + 1): + errors = x - pc.project(i, transform=False, unweight=False) + rsquare[i] = 1.0 - np.sum(errors**2) / tss + assert_allclose(rsquare, pc.rsquare) + + @pytest.mark.slow + def test_missing_dataframe(self): + x = self.x.copy() + x[::5, ::7] = np.nan + pc = PCA(x, ncomp=3, missing="fill-em") + + x = pd.DataFrame(x) + pc_df = PCA(x, ncomp=3, missing="fill-em") + assert_allclose(pc.coeff, pc_df.coeff) + assert_allclose(pc.factors, pc_df.factors) + + pc_df_nomissing = PCA(pd.DataFrame(self.x.copy()), ncomp=3) + assert isinstance(pc_df.coeff, type(pc_df_nomissing.coeff)) + assert isinstance(pc_df.data, type(pc_df_nomissing.data)) + assert isinstance(pc_df.eigenvals, type(pc_df_nomissing.eigenvals)) + assert isinstance(pc_df.eigenvecs, type(pc_df_nomissing.eigenvecs)) + + x = self.x.copy() + x[::5, ::7] = np.nan + x_df = pd.DataFrame(x) + pc = PCA(x, missing="drop-row") + pc_df = PCA(x_df, missing="drop-row") + assert_allclose(pc.coeff, pc_df.coeff) + assert_allclose(pc.factors, pc_df.factors) + + pc = PCA(x, missing="drop-col") + pc_df = PCA(x_df, missing="drop-col") + assert_allclose(pc.coeff, pc_df.coeff) + assert_allclose(pc.factors, pc_df.factors) + + pc = PCA(x, missing="drop-min") + pc_df = PCA(x_df, missing="drop-min") + assert_allclose(pc.coeff, pc_df.coeff) + assert_allclose(pc.factors, pc_df.factors) + + def test_equivalence(self): + x = self.x.copy() + assert_allclose(PCA(x).factors, pca(x)[0]) + + def test_equivalence_full_matrices(self): + x = self.x.copy() + pca_true = PCA(x, svd_full_matrices=True) + svd_full_matrices_true = pca_true.factors + assert pca_true._svd_full_matrices + pca_false = PCA(x) + svd_full_matrices_false = pca_false.factors + assert not pca_false._svd_full_matrices + assert_allclose(svd_full_matrices_true, svd_full_matrices_false) + + +def test_missing(): + data = np.empty((200, 50)) + data[0, 0] = np.nan + with pytest.raises(ValueError, match="data contains non-finite values"): + PCA(data) + + +def test_too_many_missing(): + rs = np.random.RandomState(83429421) + data = rs.standard_normal((200, 50)) + data[0, :-3] = np.nan + with pytest.raises(ValueError): + PCA(data, ncomp=5, missing="drop-col") + p = PCA(data, missing="drop-min") + assert max(p.factors.shape) == max(data.shape) - 1 + + +def test_prepare_data_all_nan(): + # GH: _prepare_data's all-NaN branch did + # `return np.empty(adj_data.shape[1]).fill(np.nan)`, but ndarray.fill() + # mutates in place and returns None, so the branch returned None + # instead of a NaN-filled array. + rs = np.random.RandomState(0) + data = rs.standard_normal((10, 4)) + p = PCA(data) + p._adjusted_data = np.full_like(data, np.nan) + + result = p._prepare_data() + assert result is not None + assert result.shape == (4,) + assert np.all(np.isnan(result)) + + +def test_gls_warning(): + rs = np.random.RandomState(83429421) + data = rs.standard_normal((400, 200)) + data[:, 1:] = data[:, :1] + 0.01 * data[:, 1:] + with pytest.warns(EstimationWarning, match="Many series are being down weighted"): + factors = PCA(data, ncomp=2, gls=True).factors + assert factors.shape == (data.shape[0], 2) diff --git a/shared/package-files/06/06a1fa254fd8466f82510151513bd68696779988974e6617aaa6992a5a5379bb/diag_embed_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/06/06a1fa254fd8466f82510151513bd68696779988974e6617aaa6992a5a5379bb/diag_embed_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..860f46781fb8638d9e7c5c708d65a6f75a94842f --- /dev/null +++ b/shared/package-files/06/06a1fa254fd8466f82510151513bd68696779988974e6617aaa6992a5a5379bb/diag_embed_compositeexplicitautogradnonfunctional_dispatch.h @@ -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 diag_embed(const at::Tensor & self, int64_t offset=0, int64_t dim1=-2, int64_t dim2=-1); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/06/06a3179ec5e260fa1a94ccc46a49fa9980f18325b937650f174028ef13ee1956/__init__.pyi b/shared/package-files/06/06a3179ec5e260fa1a94ccc46a49fa9980f18325b937650f174028ef13ee1956/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c524ac2b1cfcaaccaf5b0985a22a7576fd7e4f31 --- /dev/null +++ b/shared/package-files/06/06a3179ec5e260fa1a94ccc46a49fa9980f18325b937650f174028ef13ee1956/__init__.pyi @@ -0,0 +1 @@ +import xml.parsers as parsers diff --git a/shared/package-files/06/06a420d1fa970ff4e600124f4960c2f87d9acedec1e7735f384d520ba99b5e22/dviread.py b/shared/package-files/06/06a420d1fa970ff4e600124f4960c2f87d9acedec1e7735f384d520ba99b5e22/dviread.py new file mode 100644 index 0000000000000000000000000000000000000000..bd21367ce73dc39658ab3c671c2ec2ebba5341f3 --- /dev/null +++ b/shared/package-files/06/06a420d1fa970ff4e600124f4960c2f87d9acedec1e7735f384d520ba99b5e22/dviread.py @@ -0,0 +1,1139 @@ +""" +A module for reading dvi files output by TeX. Several limitations make +this not (currently) useful as a general-purpose dvi preprocessor, but +it is currently used by the pdf backend for processing usetex text. + +Interface:: + + with Dvi(filename, 72) as dvi: + # iterate over pages: + for page in dvi: + w, h, d = page.width, page.height, page.descent + for x, y, font, glyph, width in page.text: + fontname = font.texname + pointsize = font.size + ... + for x, y, height, width in page.boxes: + ... +""" + +from collections import namedtuple +import enum +from functools import lru_cache, partial, wraps +import logging +import os +from pathlib import Path +import re +import struct +import subprocess +import sys + +import numpy as np + +from matplotlib import _api, cbook + +_log = logging.getLogger(__name__) + +# Many dvi related files are looked for by external processes, require +# additional parsing, and are used many times per rendering, which is why they +# are cached using lru_cache(). + +# Dvi is a bytecode format documented in +# https://ctan.org/pkg/dvitype +# https://texdoc.org/serve/dvitype.pdf/0 +# +# The file consists of a preamble, some number of pages, a postamble, +# and a finale. Different opcodes are allowed in different contexts, +# so the Dvi object has a parser state: +# +# pre: expecting the preamble +# outer: between pages (followed by a page or the postamble, +# also e.g. font definitions are allowed) +# page: processing a page +# post_post: state after the postamble (our current implementation +# just stops reading) +# finale: the finale (unimplemented in our current implementation) + +_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale') + +# The marks on a page consist of text and boxes. A page also has dimensions. +Page = namedtuple('Page', 'text boxes height width descent') +Box = namedtuple('Box', 'x y height width') + + +# Also a namedtuple, for backcompat. +class Text(namedtuple('Text', 'x y font glyph width')): + """ + A glyph in the dvi file. + + The *x* and *y* attributes directly position the glyph. The *font*, + *glyph*, and *width* attributes are kept public for back-compatibility, + but users wanting to draw the glyph themselves are encouraged to instead + load the font specified by `font_path` at `font_size`, warp it with the + effects specified by `font_effects`, and load the glyph specified by + `glyph_name_or_index`. + """ + + def _get_pdftexmap_entry(self): + return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname] + + @property + def font_path(self): + """The `~pathlib.Path` to the font for this glyph.""" + psfont = self._get_pdftexmap_entry() + if psfont.filename is None: + raise ValueError("No usable font file found for {} ({}); " + "the font may lack a Type-1 version" + .format(psfont.psname.decode("ascii"), + psfont.texname.decode("ascii"))) + return Path(psfont.filename) + + @property + def font_size(self): + """The font size.""" + return self.font.size + + @property + def font_effects(self): + """ + The "font effects" dict for this glyph. + + This dict contains the values for this glyph of SlantFont and + ExtendFont (if any), read off :file:`pdftex.map`. + """ + return self._get_pdftexmap_entry().effects + + @property + def glyph_name_or_index(self): + """ + Either the glyph name or the native charmap glyph index. + + If :file:`pdftex.map` specifies an encoding for this glyph's font, that + is a mapping of glyph indices to Adobe glyph names; use it to convert + dvi indices to glyph names. Callers can then convert glyph names to + glyph indices (with FT_Get_Name_Index/get_name_index), and load the + glyph using FT_Load_Glyph/load_glyph. + + If :file:`pdftex.map` specifies no encoding, the indices directly map + to the font's "native" charmap; glyphs should directly load using + FT_Load_Char/load_char after selecting the native charmap. + """ + entry = self._get_pdftexmap_entry() + return (_parse_enc(entry.encoding)[self.glyph] + if entry.encoding is not None else self.glyph) + + +# Opcode argument parsing +# +# Each of the following functions takes a Dvi object and delta, which is the +# difference between the opcode and the minimum opcode with the same meaning. +# Dvi opcodes often encode the number of argument bytes in this delta. +_arg_mapping = dict( + # raw: Return delta as is. + raw=lambda dvi, delta: delta, + # u1: Read 1 byte as an unsigned number. + u1=lambda dvi, delta: dvi._read_arg(1, signed=False), + # u4: Read 4 bytes as an unsigned number. + u4=lambda dvi, delta: dvi._read_arg(4, signed=False), + # s4: Read 4 bytes as a signed number. + s4=lambda dvi, delta: dvi._read_arg(4, signed=True), + # slen: Read delta bytes as a signed number, or None if delta is None. + slen=lambda dvi, delta: dvi._read_arg(delta, signed=True) if delta else None, + # slen1: Read (delta + 1) bytes as a signed number. + slen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=True), + # ulen1: Read (delta + 1) bytes as an unsigned number. + ulen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=False), + # olen1: Read (delta + 1) bytes as an unsigned number if less than 4 bytes, + # as a signed number if 4 bytes. + olen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=(delta == 3)), +) + + +def _dispatch(table, min, max=None, state=None, args=('raw',)): + """ + Decorator for dispatch by opcode. Sets the values in *table* + from *min* to *max* to this method, adds a check that the Dvi state + matches *state* if not None, reads arguments from the file according + to *args*. + + Parameters + ---------- + table : dict[int, callable] + The dispatch table to be filled in. + + min, max : int + Range of opcodes that calls the registered function; *max* defaults to + *min*. + + state : _dvistate, optional + State of the Dvi object in which these opcodes are allowed. + + args : list[str], default: ['raw'] + Sequence of argument specifications: + + - 'raw': opcode minus minimum + - 'u1': read one unsigned byte + - 'u4': read four bytes, treat as an unsigned number + - 's4': read four bytes, treat as a signed number + - 'slen': read (opcode - minimum) bytes, treat as signed + - 'slen1': read (opcode - minimum + 1) bytes, treat as signed + - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned + - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned + if under four bytes, signed if four bytes + """ + def decorate(method): + get_args = [_arg_mapping[x] for x in args] + + @wraps(method) + def wrapper(self, byte): + if state is not None and self.state != state: + raise ValueError("state precondition failed") + return method(self, *[f(self, byte-min) for f in get_args]) + if max is None: + table[min] = wrapper + else: + for i in range(min, max+1): + assert table[i] is None + table[i] = wrapper + return wrapper + return decorate + + +class Dvi: + """ + A reader for a dvi ("device-independent") file, as produced by TeX. + + The current implementation can only iterate through pages in order, + and does not even attempt to verify the postamble. + + This class can be used as a context manager to close the underlying + file upon exit. Pages can be read via iteration. Here is an overly + simple way to extract text without trying to detect whitespace:: + + >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi: + ... for page in dvi: + ... print(''.join(chr(t.glyph) for t in page.text)) + """ + # dispatch table + _dtable = [None] * 256 + _dispatch = partial(_dispatch, _dtable) + + def __init__(self, filename, dpi): + """ + Read the data from the file named *filename* and convert + TeX's internal units to units of *dpi* per inch. + *dpi* only sets the units and does not limit the resolution. + Use None to return TeX's internal units. + """ + _log.debug('Dvi: %s', filename) + self.file = open(filename, 'rb') + self.dpi = dpi + self.fonts = {} + self.state = _dvistate.pre + self._missing_font = None + + def __enter__(self): + """Context manager enter method, does nothing.""" + return self + + def __exit__(self, etype, evalue, etrace): + """ + Context manager exit method, closes the underlying file if it is open. + """ + self.close() + + def __iter__(self): + """ + Iterate through the pages of the file. + + Yields + ------ + Page + Details of all the text and box objects on the page. + The Page tuple contains lists of Text and Box tuples and + the page dimensions, and the Text and Box tuples contain + coordinates transformed into a standard Cartesian + coordinate system at the dpi value given when initializing. + The coordinates are floating point numbers, but otherwise + precision is not lost and coordinate values are not clipped to + integers. + """ + while self._read(): + yield self._output() + + def close(self): + """Close the underlying file if it is open.""" + if not self.file.closed: + self.file.close() + + def _output(self): + """ + Output the text and boxes belonging to the most recent page. + page = dvi._output() + """ + minx = miny = np.inf + maxx = maxy = -np.inf + maxy_pure = -np.inf + for elt in self.text + self.boxes: + if isinstance(elt, Box): + x, y, h, w = elt + e = 0 # zero depth + else: # glyph + x, y, font, g, w = elt + h, e = font._height_depth_of(g) + minx = min(minx, x) + miny = min(miny, y - h) + maxx = max(maxx, x + w) + maxy = max(maxy, y + e) + maxy_pure = max(maxy_pure, y) + if self._baseline_v is not None: + maxy_pure = self._baseline_v # This should normally be the case. + self._baseline_v = None + + if not self.text and not self.boxes: # Avoid infs/nans from inf+/-inf. + return Page(text=[], boxes=[], width=0, height=0, descent=0) + + if self.dpi is None: + # special case for ease of debugging: output raw dvi coordinates + return Page(text=self.text, boxes=self.boxes, + width=maxx-minx, height=maxy_pure-miny, + descent=maxy-maxy_pure) + + # convert from TeX's "scaled points" to dpi units + d = self.dpi / (72.27 * 2**16) + descent = (maxy - maxy_pure) * d + + text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d) + for (x, y, f, g, w) in self.text] + boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d) + for (x, y, h, w) in self.boxes] + + return Page(text=text, boxes=boxes, width=(maxx-minx)*d, + height=(maxy_pure-miny)*d, descent=descent) + + def _read(self): + """ + Read one page from the file. Return True if successful, + False if there were no more pages. + """ + # Pages appear to start with the sequence + # bop (begin of page) + # xxx comment + # # if using chemformula + # down + # push + # down + # # if using xcolor + # down + # push + # down (possibly multiple) + # push <= here, v is the baseline position. + # etc. + # (dviasm is useful to explore this structure.) + # Thus, we use the vertical position at the first time the stack depth + # reaches 3, while at least three "downs" have been executed (excluding + # those popped out (corresponding to the chemformula preamble)), as the + # baseline (the "down" count is necessary to handle xcolor). + down_stack = [0] + self._baseline_v = None + while True: + byte = self.file.read(1)[0] + self._dtable[byte](self, byte) + if self._missing_font: + raise self._missing_font.to_exception() + name = self._dtable[byte].__name__ + if name == "_push": + down_stack.append(down_stack[-1]) + elif name == "_pop": + down_stack.pop() + elif name == "_down": + down_stack[-1] += 1 + if (self._baseline_v is None + and len(getattr(self, "stack", [])) == 3 + and down_stack[-1] >= 4): + self._baseline_v = self.v + if byte == 140: # end of page + return True + if self.state is _dvistate.post_post: # end of file + self.close() + return False + + def _read_arg(self, nbytes, signed=False): + """ + Read and return a big-endian integer *nbytes* long. + Signedness is determined by the *signed* keyword. + """ + return int.from_bytes(self.file.read(nbytes), "big", signed=signed) + + @_dispatch(min=0, max=127, state=_dvistate.inpage) + def _set_char_immediate(self, char): + self._put_char_real(char) + if isinstance(self.fonts[self.f], cbook._ExceptionInfo): + return + self.h += self.fonts[self.f]._width_of(char) + + @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',)) + def _set_char(self, char): + self._put_char_real(char) + if isinstance(self.fonts[self.f], cbook._ExceptionInfo): + return + self.h += self.fonts[self.f]._width_of(char) + + @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4')) + def _set_rule(self, a, b): + self._put_rule_real(a, b) + self.h += b + + @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',)) + def _put_char(self, char): + self._put_char_real(char) + + def _put_char_real(self, char): + font = self.fonts[self.f] + if isinstance(font, cbook._ExceptionInfo): + self._missing_font = font + elif font._vf is None: + self.text.append(Text(self.h, self.v, font, char, + font._width_of(char))) + else: + scale = font._scale + for x, y, f, g, w in font._vf[char].text: + newf = DviFont(scale=_mul2012(scale, f._scale), + tfm=f._tfm, texname=f.texname, vf=f._vf) + self.text.append(Text(self.h + _mul2012(x, scale), + self.v + _mul2012(y, scale), + newf, g, newf._width_of(g))) + self.boxes.extend([Box(self.h + _mul2012(x, scale), + self.v + _mul2012(y, scale), + _mul2012(a, scale), _mul2012(b, scale)) + for x, y, a, b in font._vf[char].boxes]) + + @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4')) + def _put_rule(self, a, b): + self._put_rule_real(a, b) + + def _put_rule_real(self, a, b): + if a > 0 and b > 0: + self.boxes.append(Box(self.h, self.v, a, b)) + + @_dispatch(138) + def _nop(self, _): + pass + + @_dispatch(139, state=_dvistate.outer, args=('s4',)*11) + def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p): + self.state = _dvistate.inpage + self.h = self.v = self.w = self.x = self.y = self.z = 0 + self.stack = [] + self.text = [] # list of Text objects + self.boxes = [] # list of Box objects + + @_dispatch(140, state=_dvistate.inpage) + def _eop(self, _): + self.state = _dvistate.outer + del self.h, self.v, self.w, self.x, self.y, self.z, self.stack + + @_dispatch(141, state=_dvistate.inpage) + def _push(self, _): + self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z)) + + @_dispatch(142, state=_dvistate.inpage) + def _pop(self, _): + self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop() + + @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',)) + def _right(self, b): + self.h += b + + @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',)) + def _right_w(self, new_w): + if new_w is not None: + self.w = new_w + self.h += self.w + + @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',)) + def _right_x(self, new_x): + if new_x is not None: + self.x = new_x + self.h += self.x + + @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',)) + def _down(self, a): + self.v += a + + @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',)) + def _down_y(self, new_y): + if new_y is not None: + self.y = new_y + self.v += self.y + + @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',)) + def _down_z(self, new_z): + if new_z is not None: + self.z = new_z + self.v += self.z + + @_dispatch(min=171, max=234, state=_dvistate.inpage) + def _fnt_num_immediate(self, k): + self.f = k + + @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',)) + def _fnt_num(self, new_f): + self.f = new_f + + @_dispatch(min=239, max=242, args=('ulen1',)) + def _xxx(self, datalen): + special = self.file.read(datalen) + _log.debug( + 'Dvi._xxx: encountered special: %s', + ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch + for ch in special])) + + @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1')) + def _fnt_def(self, k, c, s, d, a, l): + self._fnt_def_real(k, c, s, d, a, l) + + def _fnt_def_real(self, k, c, s, d, a, l): + n = self.file.read(a + l) + fontname = n[-l:].decode('ascii') + try: + tfm = _tfmfile(fontname) + except FileNotFoundError as exc: + # Explicitly allow defining missing fonts for Vf support; we only + # register an error when trying to load a glyph from a missing font + # and throw that error in Dvi._read. For Vf, _finalize_packet + # checks whether a missing glyph has been used, and in that case + # skips the glyph definition. + self.fonts[k] = cbook._ExceptionInfo.from_exception(exc) + return + if c != 0 and tfm.checksum != 0 and c != tfm.checksum: + raise ValueError(f'tfm checksum mismatch: {n}') + try: + vf = _vffile(fontname) + except FileNotFoundError: + vf = None + self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf) + + @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1')) + def _pre(self, i, num, den, mag, k): + self.file.read(k) # comment in the dvi file + if i != 2: + raise ValueError(f"Unknown dvi format {i}") + if num != 25400000 or den != 7227 * 2**16: + raise ValueError("Nonstandard units in dvi file") + # meaning: TeX always uses those exact values, so it + # should be enough for us to support those + # (There are 72.27 pt to an inch so 7227 pt = + # 7227 * 2**16 sp to 100 in. The numerator is multiplied + # by 10^5 to get units of 10**-7 meters.) + if mag != 1000: + raise ValueError("Nonstandard magnification in dvi file") + # meaning: LaTeX seems to frown on setting \mag, so + # I think we can assume this is constant + self.state = _dvistate.outer + + @_dispatch(248, state=_dvistate.outer) + def _post(self, _): + self.state = _dvistate.post_post + # TODO: actually read the postamble and finale? + # currently post_post just triggers closing the file + + @_dispatch(249) + def _post_post(self, _): + raise NotImplementedError + + @_dispatch(min=250, max=255) + def _malformed(self, offset): + raise ValueError(f"unknown command: byte {250 + offset}") + + +class DviFont: + """ + Encapsulation of a font that a DVI file can refer to. + + This class holds a font's texname and size, supports comparison, + and knows the widths of glyphs in the same units as the AFM file. + There are also internal attributes (for use by dviread.py) that + are *not* used for comparison. + + The size is in Adobe points (converted from TeX points). + + Parameters + ---------- + scale : float + Factor by which the font is scaled from its natural size. + tfm : Tfm + TeX font metrics for this font + texname : bytes + Name of the font as used internally by TeX and friends, as an ASCII + bytestring. This is usually very different from any external font + names; `PsfontsMap` can be used to find the external name of the font. + vf : Vf + A TeX "virtual font" file, or None if this font is not virtual. + + Attributes + ---------- + texname : bytes + size : float + Size of the font in Adobe points, converted from the slightly + smaller TeX points. + widths : list + Widths of glyphs in glyph-space units, typically 1/1000ths of + the point size. + + """ + __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm') + + def __init__(self, scale, tfm, texname, vf): + _api.check_isinstance(bytes, texname=texname) + self._scale = scale + self._tfm = tfm + self.texname = texname + self._vf = vf + self.size = scale * (72.0 / (72.27 * 2**16)) + try: + nchars = max(tfm.width) + 1 + except ValueError: + nchars = 0 + self.widths = [(1000*tfm.width.get(char, 0)) >> 20 + for char in range(nchars)] + + def __eq__(self, other): + return (type(self) is type(other) + and self.texname == other.texname and self.size == other.size) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + return f"<{type(self).__name__}: {self.texname}>" + + def _width_of(self, char): + """Width of char in dvi units.""" + width = self._tfm.width.get(char, None) + if width is not None: + return _mul2012(width, self._scale) + _log.debug('No width for char %d in font %s.', char, self.texname) + return 0 + + def _height_depth_of(self, char): + """Height and depth of char in dvi units.""" + result = [] + for metric, name in ((self._tfm.height, "height"), + (self._tfm.depth, "depth")): + value = metric.get(char, None) + if value is None: + _log.debug('No %s for char %d in font %s', + name, char, self.texname) + result.append(0) + else: + result.append(_mul2012(value, self._scale)) + # cmsyXX (symbols font) glyph 0 ("minus") has a nonzero descent + # so that TeX aligns equations properly + # (https://tex.stackexchange.com/q/526103/) + # but we actually care about the rasterization depth to align + # the dvipng-generated images. + if re.match(br'^cmsy\d+$', self.texname) and char == 0: + result[-1] = 0 + return result + + +class Vf(Dvi): + r""" + A virtual font (\*.vf file) containing subroutines for dvi files. + + Parameters + ---------- + filename : str or path-like + + Notes + ----- + The virtual font format is a derivative of dvi: + http://mirrors.ctan.org/info/knuth/virtual-fonts + This class reuses some of the machinery of `Dvi` + but replaces the `_read` loop and dispatch mechanism. + + Examples + -------- + :: + + vf = Vf(filename) + glyph = vf[code] + glyph.text, glyph.boxes, glyph.width + """ + + def __init__(self, filename): + super().__init__(filename, 0) + try: + self._first_font = None + self._chars = {} + self._read() + finally: + self.close() + + def __getitem__(self, code): + return self._chars[code] + + def _read(self): + """ + Read one page from the file. Return True if successful, + False if there were no more pages. + """ + packet_char = packet_ends = None + packet_len = packet_width = None + while True: + byte = self.file.read(1)[0] + # If we are in a packet, execute the dvi instructions + if self.state is _dvistate.inpage: + byte_at = self.file.tell()-1 + if byte_at == packet_ends: + self._finalize_packet(packet_char, packet_width) + packet_len = packet_char = packet_width = None + # fall through to out-of-packet code + elif byte_at > packet_ends: + raise ValueError("Packet length mismatch in vf file") + else: + if byte in (139, 140) or byte >= 243: + raise ValueError(f"Inappropriate opcode {byte} in vf file") + Dvi._dtable[byte](self, byte) + continue + + # We are outside a packet + if byte < 242: # a short packet (length given by byte) + packet_len = byte + packet_char = self._read_arg(1) + packet_width = self._read_arg(3) + packet_ends = self._init_packet(byte) + self.state = _dvistate.inpage + elif byte == 242: # a long packet + packet_len = self._read_arg(4) + packet_char = self._read_arg(4) + packet_width = self._read_arg(4) + self._init_packet(packet_len) + elif 243 <= byte <= 246: + k = self._read_arg(byte - 242, byte == 246) + c = self._read_arg(4) + s = self._read_arg(4) + d = self._read_arg(4) + a = self._read_arg(1) + l = self._read_arg(1) + self._fnt_def_real(k, c, s, d, a, l) + if self._first_font is None: + self._first_font = k + elif byte == 247: # preamble + i = self._read_arg(1) + k = self._read_arg(1) + x = self.file.read(k) + cs = self._read_arg(4) + ds = self._read_arg(4) + self._pre(i, x, cs, ds) + elif byte == 248: # postamble (just some number of 248s) + break + else: + raise ValueError(f"Unknown vf opcode {byte}") + + def _init_packet(self, pl): + if self.state != _dvistate.outer: + raise ValueError("Misplaced packet in vf file") + self.h = self.v = self.w = self.x = self.y = self.z = 0 + self.stack = [] + self.text = [] + self.boxes = [] + self.f = self._first_font + self._missing_font = None + return self.file.tell() + pl + + def _finalize_packet(self, packet_char, packet_width): + if not self._missing_font: # Otherwise we don't have full glyph definition. + self._chars[packet_char] = Page( + text=self.text, boxes=self.boxes, width=packet_width, + height=None, descent=None) + self.state = _dvistate.outer + + def _pre(self, i, x, cs, ds): + if self.state is not _dvistate.pre: + raise ValueError("pre command in middle of vf file") + if i != 202: + raise ValueError(f"Unknown vf format {i}") + if len(x): + _log.debug('vf file comment: %s', x) + self.state = _dvistate.outer + # cs = checksum, ds = design size + + +def _mul2012(num1, num2): + """Multiply two numbers in 20.12 fixed point format.""" + # Separated into a function because >> has surprising precedence + return (num1*num2) >> 20 + + +class Tfm: + """ + A TeX Font Metric file. + + This implementation covers only the bare minimum needed by the Dvi class. + + Parameters + ---------- + filename : str or path-like + + Attributes + ---------- + checksum : int + Used for verifying against the dvi file. + design_size : int + Design size of the font (unknown units) + width, height, depth : dict + Dimensions of each character, need to be scaled by the factor + specified in the dvi file. These are dicts because indexing may + not start from 0. + """ + __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth') + + def __init__(self, filename): + _log.debug('opening tfm file %s', filename) + with open(filename, 'rb') as file: + header1 = file.read(24) + lh, bc, ec, nw, nh, nd = struct.unpack('!6H', header1[2:14]) + _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d', + lh, bc, ec, nw, nh, nd) + header2 = file.read(4*lh) + self.checksum, self.design_size = struct.unpack('!2I', header2[:8]) + # there is also encoding information etc. + char_info = file.read(4*(ec-bc+1)) + widths = struct.unpack(f'!{nw}i', file.read(4*nw)) + heights = struct.unpack(f'!{nh}i', file.read(4*nh)) + depths = struct.unpack(f'!{nd}i', file.read(4*nd)) + self.width = {} + self.height = {} + self.depth = {} + for idx, char in enumerate(range(bc, ec+1)): + byte0 = char_info[4*idx] + byte1 = char_info[4*idx+1] + self.width[char] = widths[byte0] + self.height[char] = heights[byte1 >> 4] + self.depth[char] = depths[byte1 & 0xf] + + +PsFont = namedtuple('PsFont', 'texname psname effects encoding filename') + + +class PsfontsMap: + """ + A psfonts.map formatted file, mapping TeX fonts to PS fonts. + + Parameters + ---------- + filename : str or path-like + + Notes + ----- + For historical reasons, TeX knows many Type-1 fonts by different + names than the outside world. (For one thing, the names have to + fit in eight characters.) Also, TeX's native fonts are not Type-1 + but Metafont, which is nontrivial to convert to PostScript except + as a bitmap. While high-quality conversions to Type-1 format exist + and are shipped with modern TeX distributions, we need to know + which Type-1 fonts are the counterparts of which native fonts. For + these reasons a mapping is needed from internal font names to font + file names. + + A texmf tree typically includes mapping files called e.g. + :file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`. + The file :file:`psfonts.map` is used by :program:`dvips`, + :file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map` + by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding + the 35 PostScript fonts (i.e., have no filename for them, as in + the Times-Bold example above), while the pdf-related files perhaps + only avoid the "Base 14" pdf fonts. But the user may have + configured these files differently. + + Examples + -------- + >>> map = PsfontsMap(find_tex_file('pdftex.map')) + >>> entry = map[b'ptmbo8r'] + >>> entry.texname + b'ptmbo8r' + >>> entry.psname + b'Times-Bold' + >>> entry.encoding + '/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc' + >>> entry.effects + {'slant': 0.16700000000000001} + >>> entry.filename + """ + __slots__ = ('_filename', '_unparsed', '_parsed') + + # Create a filename -> PsfontsMap cache, so that calling + # `PsfontsMap(filename)` with the same filename a second time immediately + # returns the same object. + @lru_cache + def __new__(cls, filename): + self = object.__new__(cls) + self._filename = os.fsdecode(filename) + # Some TeX distributions have enormous pdftex.map files which would + # take hundreds of milliseconds to parse, but it is easy enough to just + # store the unparsed lines (keyed by the first word, which is the + # texname) and parse them on-demand. + with open(filename, 'rb') as file: + self._unparsed = {} + for line in file: + tfmname = line.split(b' ', 1)[0] + self._unparsed.setdefault(tfmname, []).append(line) + self._parsed = {} + return self + + def __getitem__(self, texname): + assert isinstance(texname, bytes) + if texname in self._unparsed: + for line in self._unparsed.pop(texname): + if self._parse_and_cache_line(line): + break + try: + return self._parsed[texname] + except KeyError: + raise LookupError( + f"An associated PostScript font (required by Matplotlib) " + f"could not be found for TeX font {texname.decode('ascii')!r} " + f"in {self._filename!r}; this problem can often be solved by " + f"installing a suitable PostScript font package in your TeX " + f"package manager") from None + + def _parse_and_cache_line(self, line): + """ + Parse a line in the font mapping file. + + The format is (partially) documented at + http://mirrors.ctan.org/systems/doc/pdftex/manual/pdftex-a.pdf + https://tug.org/texinfohtml/dvips.html#psfonts_002emap + Each line can have the following fields: + + - tfmname (first, only required field), + - psname (defaults to tfmname, must come immediately after tfmname if + present), + - fontflags (integer, must come immediately after psname if present, + ignored by us), + - special (SlantFont and ExtendFont, only field that is double-quoted), + - fontfile, encodingfile (optional, prefixed by <, <<, or <[; << always + precedes a font, <[ always precedes an encoding, < can precede either + but then an encoding file must have extension .enc; < and << also + request different font subsetting behaviors but we ignore that; < can + be separated from the filename by whitespace). + + special, fontfile, and encodingfile can appear in any order. + """ + # If the map file specifies multiple encodings for a font, we + # follow pdfTeX in choosing the last one specified. Such + # entries are probably mistakes but they have occurred. + # https://tex.stackexchange.com/q/10826/ + + if not line or line.startswith((b" ", b"%", b"*", b";", b"#")): + return + tfmname = basename = special = encodingfile = fontfile = None + is_subsetted = is_t1 = is_truetype = False + matches = re.finditer(br'"([^"]*)(?:"|$)|(\S+)', line) + for match in matches: + quoted, unquoted = match.groups() + if unquoted: + if unquoted.startswith(b"<<"): # font + fontfile = unquoted[2:] + elif unquoted.startswith(b"<["): # encoding + encodingfile = unquoted[2:] + elif unquoted.startswith(b"<"): # font or encoding + word = ( + # foo + unquoted[1:] + # < by itself => read the next word + or next(filter(None, next(matches).groups()))) + if word.endswith(b".enc"): + encodingfile = word + else: + fontfile = word + is_subsetted = True + elif tfmname is None: + tfmname = unquoted + elif basename is None: + basename = unquoted + elif quoted: + special = quoted + effects = {} + if special: + words = reversed(special.split()) + for word in words: + if word == b"SlantFont": + effects["slant"] = float(next(words)) + elif word == b"ExtendFont": + effects["extend"] = float(next(words)) + + # Verify some properties of the line that would cause it to be ignored + # otherwise. + if fontfile is not None: + if fontfile.endswith((b".ttf", b".ttc")): + is_truetype = True + elif not fontfile.endswith(b".otf"): + is_t1 = True + elif basename is not None: + is_t1 = True + if is_truetype and is_subsetted and encodingfile is None: + return + if not is_t1 and ("slant" in effects or "extend" in effects): + return + if abs(effects.get("slant", 0)) > 1: + return + if abs(effects.get("extend", 0)) > 2: + return + + if basename is None: + basename = tfmname + if encodingfile is not None: + encodingfile = find_tex_file(encodingfile) + if fontfile is not None: + fontfile = find_tex_file(fontfile) + self._parsed[tfmname] = PsFont( + texname=tfmname, psname=basename, effects=effects, + encoding=encodingfile, filename=fontfile) + return True + + +def _parse_enc(path): + r""" + Parse a \*.enc file referenced from a psfonts.map style file. + + The format supported by this function is a tiny subset of PostScript. + + Parameters + ---------- + path : `os.PathLike` + + Returns + ------- + list + The nth entry of the list is the PostScript glyph name of the nth + glyph. + """ + no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii")) + array = re.search(r"(?s)\[(.*)\]", no_comments).group(1) + lines = [line for line in array.split() if line] + if all(line.startswith("/") for line in lines): + return [line[1:] for line in lines] + else: + raise ValueError(f"Failed to parse {path} as Postscript encoding") + + +class _LuatexKpsewhich: + @lru_cache # A singleton. + def __new__(cls): + self = object.__new__(cls) + self._proc = self._new_proc() + return self + + def _new_proc(self): + return subprocess.Popen( + ["luatex", "--luaonly", + str(cbook._get_data_path("kpsewhich.lua"))], + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + def search(self, filename): + if self._proc.poll() is not None: # Dead, restart it. + self._proc = self._new_proc() + self._proc.stdin.write(os.fsencode(filename) + b"\n") + self._proc.stdin.flush() + out = self._proc.stdout.readline().rstrip() + return None if out == b"nil" else os.fsdecode(out) + + +@lru_cache +def find_tex_file(filename): + """ + Find a file in the texmf tree using kpathsea_. + + The kpathsea library, provided by most existing TeX distributions, both + on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived + luatex process if luatex is installed, or via kpsewhich otherwise. + + .. _kpathsea: https://www.tug.org/kpathsea/ + + Parameters + ---------- + filename : str or path-like + + Raises + ------ + FileNotFoundError + If the file is not found. + """ + + # we expect these to always be ascii encoded, but use utf-8 + # out of caution + if isinstance(filename, bytes): + filename = filename.decode('utf-8', errors='replace') + + try: + lk = _LuatexKpsewhich() + except FileNotFoundError: + lk = None # Fallback to directly calling kpsewhich, as below. + + if lk: + path = lk.search(filename) + else: + if sys.platform == 'win32': + # On Windows only, kpathsea can use utf-8 for cmd args and output. + # The `command_line_encoding` environment variable is set to force + # it to always use utf-8 encoding. See Matplotlib issue #11848. + kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'}, + 'encoding': 'utf-8'} + else: # On POSIX, run through the equivalent of os.fsdecode(). + kwargs = {'encoding': sys.getfilesystemencoding(), + 'errors': 'surrogateescape'} + + try: + path = (cbook._check_and_log_subprocess(['kpsewhich', filename], + _log, **kwargs) + .rstrip('\n')) + except (FileNotFoundError, RuntimeError): + path = None + + if path: + return path + else: + raise FileNotFoundError( + f"Matplotlib's TeX implementation searched for a file named " + f"{filename!r} in your texmf tree, but could not find it") + + +@lru_cache +def _fontfile(cls, suffix, texname): + return cls(find_tex_file(texname + suffix)) + + +_tfmfile = partial(_fontfile, Tfm, ".tfm") +_vffile = partial(_fontfile, Vf, ".vf") + + +if __name__ == '__main__': + from argparse import ArgumentParser + import itertools + + parser = ArgumentParser() + parser.add_argument("filename") + parser.add_argument("dpi", nargs="?", type=float, default=None) + args = parser.parse_args() + with Dvi(args.filename, args.dpi) as dvi: + fontmap = PsfontsMap(find_tex_file('pdftex.map')) + for page in dvi: + print(f"=== new page === " + f"(w: {page.width}, h: {page.height}, d: {page.descent})") + for font, group in itertools.groupby( + page.text, lambda text: text.font): + print(f"font: {font.texname.decode('latin-1')!r}\t" + f"scale: {font._scale / 2 ** 20}") + print("x", "y", "glyph", "chr", "w", "(glyphs)", sep="\t") + for text in group: + print(text.x, text.y, text.glyph, + chr(text.glyph) if chr(text.glyph).isprintable() + else ".", + text.width, sep="\t") + if page.boxes: + print("x", "y", "h", "w", "", "(boxes)", sep="\t") + for box in page.boxes: + print(box.x, box.y, box.height, box.width, sep="\t") diff --git a/shared/package-files/06/06a5c5ca12950e815126549205bfe3c4e9163f333632943aec12a2411f39d80f/polyoptions.py b/shared/package-files/06/06a5c5ca12950e815126549205bfe3c4e9163f333632943aec12a2411f39d80f/polyoptions.py new file mode 100644 index 0000000000000000000000000000000000000000..4392a543f185d77af3eeb18708867cf54b7d0b5f --- /dev/null +++ b/shared/package-files/06/06a5c5ca12950e815126549205bfe3c4e9163f333632943aec12a2411f39d80f/polyoptions.py @@ -0,0 +1,788 @@ +"""Options manager for :class:`~.Poly` and public API functions. """ + +from __future__ import annotations + +__all__ = ["Options"] + +from sympy.core import Basic, sympify +from sympy.polys.polyerrors import GeneratorsError, OptionError, FlagError +from sympy.utilities import numbered_symbols, topological_sort, public +from sympy.utilities.iterables import has_dups, is_sequence + +import sympy.polys + +import re + +class Option: + """Base class for all kinds of options. """ + + option: str | None = None + + is_Flag = False + + requires: list[str] = [] + excludes: list[str] = [] + + after: list[str] = [] + before: list[str] = [] + + @classmethod + def default(cls): + return None + + @classmethod + def preprocess(cls, option): + return None + + @classmethod + def postprocess(cls, options): + pass + + +class Flag(Option): + """Base class for all kinds of flags. """ + + is_Flag = True + + +class BooleanOption(Option): + """An option that must have a boolean value or equivalent assigned. """ + + @classmethod + def preprocess(cls, value): + if value in [True, False]: + return bool(value) + else: + raise OptionError("'%s' must have a boolean value assigned, got %s" % (cls.option, value)) + + +class OptionType(type): + """Base type for all options that does registers options. """ + + def __init__(cls, *args, **kwargs): + @property + def getter(self): + try: + return self[cls.option] + except KeyError: + return cls.default() + + setattr(Options, cls.option, getter) + Options.__options__[cls.option] = cls + + +@public +class Options(dict): + """ + Options manager for polynomial manipulation module. + + Examples + ======== + + >>> from sympy.polys.polyoptions import Options + >>> from sympy.polys.polyoptions import build_options + + >>> from sympy.abc import x, y, z + + >>> Options((x, y, z), {'domain': 'ZZ'}) + {'auto': False, 'domain': ZZ, 'gens': (x, y, z)} + + >>> build_options((x, y, z), {'domain': 'ZZ'}) + {'auto': False, 'domain': ZZ, 'gens': (x, y, z)} + + **Options** + + * Expand --- boolean option + * Gens --- option + * Wrt --- option + * Sort --- option + * Order --- option + * Field --- boolean option + * Greedy --- boolean option + * Domain --- option + * Split --- boolean option + * Gaussian --- boolean option + * Extension --- option + * Modulus --- option + * Symmetric --- boolean option + * Strict --- boolean option + + **Flags** + + * Auto --- boolean flag + * Frac --- boolean flag + * Formal --- boolean flag + * Polys --- boolean flag + * Include --- boolean flag + * All --- boolean flag + * Gen --- flag + * Series --- boolean flag + + """ + + __order__ = None + __options__: dict[str, type[Option]] = {} + + def __init__(self, gens, args, flags=None, strict=False): + dict.__init__(self) + + if gens and args.get('gens', ()): + raise OptionError( + "both '*gens' and keyword argument 'gens' supplied") + elif gens: + args = dict(args) + args['gens'] = gens + + defaults = args.pop('defaults', {}) + + def preprocess_options(args): + for option, value in args.items(): + try: + cls = self.__options__[option] + except KeyError: + raise OptionError("'%s' is not a valid option" % option) + + if issubclass(cls, Flag): + if flags is None or option not in flags: + if strict: + raise OptionError("'%s' flag is not allowed in this context" % option) + + if value is not None: + self[option] = cls.preprocess(value) + + preprocess_options(args) + + for key, value in dict(defaults).items(): + if key in self: + del defaults[key] + else: + for option in self.keys(): + cls = self.__options__[option] + + if key in cls.excludes: + del defaults[key] + break + + preprocess_options(defaults) + + for option in self.keys(): + cls = self.__options__[option] + + for require_option in cls.requires: + if self.get(require_option) is None: + raise OptionError("'%s' option is only allowed together with '%s'" % (option, require_option)) + + for exclude_option in cls.excludes: + if self.get(exclude_option) is not None: + raise OptionError("'%s' option is not allowed together with '%s'" % (option, exclude_option)) + + for option in self.__order__: + self.__options__[option].postprocess(self) + + @classmethod + def _init_dependencies_order(cls): + """Resolve the order of options' processing. """ + if cls.__order__ is None: + vertices, edges = [], set() + + for name, option in cls.__options__.items(): + vertices.append(name) + + for _name in option.after: + edges.add((_name, name)) + + for _name in option.before: + edges.add((name, _name)) + + try: + cls.__order__ = topological_sort((vertices, list(edges))) + except ValueError: + raise RuntimeError( + "cycle detected in sympy.polys options framework") + + def clone(self, updates={}): + """Clone ``self`` and update specified options. """ + obj = dict.__new__(self.__class__) + + for option, value in self.items(): + obj[option] = value + + for option, value in updates.items(): + obj[option] = value + + return obj + + def __setattr__(self, attr, value): + if attr in self.__options__: + self[attr] = value + else: + super().__setattr__(attr, value) + + @property + def args(self): + args = {} + + for option, value in self.items(): + if value is not None and option != 'gens': + cls = self.__options__[option] + + if not issubclass(cls, Flag): + args[option] = value + + return args + + @property + def options(self): + options = {} + + for option, cls in self.__options__.items(): + if not issubclass(cls, Flag): + options[option] = getattr(self, option) + + return options + + @property + def flags(self): + flags = {} + + for option, cls in self.__options__.items(): + if issubclass(cls, Flag): + flags[option] = getattr(self, option) + + return flags + + +class Expand(BooleanOption, metaclass=OptionType): + """``expand`` option to polynomial manipulation functions. """ + + option = 'expand' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return True + + +class Gens(Option, metaclass=OptionType): + """``gens`` option to polynomial manipulation functions. """ + + option = 'gens' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return () + + @classmethod + def preprocess(cls, gens): + if isinstance(gens, Basic): + gens = (gens,) + elif len(gens) == 1 and is_sequence(gens[0]): + gens = gens[0] + + if gens == (None,): + gens = () + elif has_dups(gens): + raise GeneratorsError("duplicated generators: %s" % str(gens)) + elif any(gen.is_commutative is False for gen in gens): + raise GeneratorsError("non-commutative generators: %s" % str(gens)) + + return tuple(gens) + + +class Wrt(Option, metaclass=OptionType): + """``wrt`` option to polynomial manipulation functions. """ + + option = 'wrt' + + requires: list[str] = [] + excludes: list[str] = [] + + _re_split = re.compile(r"\s*,\s*|\s+") + + @classmethod + def preprocess(cls, wrt): + if isinstance(wrt, Basic): + return [str(wrt)] + elif isinstance(wrt, str): + wrt = wrt.strip() + if wrt.endswith(','): + raise OptionError('Bad input: missing parameter.') + if not wrt: + return [] + return list(cls._re_split.split(wrt)) + elif hasattr(wrt, '__getitem__'): + return list(map(str, wrt)) + else: + raise OptionError("invalid argument for 'wrt' option") + + +class Sort(Option, metaclass=OptionType): + """``sort`` option to polynomial manipulation functions. """ + + option = 'sort' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return [] + + @classmethod + def preprocess(cls, sort): + if isinstance(sort, str): + return [ gen.strip() for gen in sort.split('>') ] + elif hasattr(sort, '__getitem__'): + return list(map(str, sort)) + else: + raise OptionError("invalid argument for 'sort' option") + + +class Order(Option, metaclass=OptionType): + """``order`` option to polynomial manipulation functions. """ + + option = 'order' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return sympy.polys.orderings.lex + + @classmethod + def preprocess(cls, order): + return sympy.polys.orderings.monomial_key(order) + + +class Field(BooleanOption, metaclass=OptionType): + """``field`` option to polynomial manipulation functions. """ + + option = 'field' + + requires: list[str] = [] + excludes = ['domain', 'split', 'gaussian'] + + +class Greedy(BooleanOption, metaclass=OptionType): + """``greedy`` option to polynomial manipulation functions. """ + + option = 'greedy' + + requires: list[str] = [] + excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric'] + + +class Composite(BooleanOption, metaclass=OptionType): + """``composite`` option to polynomial manipulation functions. """ + + option = 'composite' + + @classmethod + def default(cls): + return None + + requires: list[str] = [] + excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric'] + + +class Domain(Option, metaclass=OptionType): + """``domain`` option to polynomial manipulation functions. """ + + option = 'domain' + + requires: list[str] = [] + excludes = ['field', 'greedy', 'split', 'gaussian', 'extension'] + + after = ['gens'] + + _re_realfield = re.compile(r"^(R|RR)(_(\d+))?$") + _re_complexfield = re.compile(r"^(C|CC)(_(\d+))?$") + _re_finitefield = re.compile(r"^(FF|GF)\((\d+)\)$") + _re_polynomial = re.compile(r"^(Z|ZZ|Q|QQ|ZZ_I|QQ_I|R|RR|C|CC)\[(.+)\]$") + _re_fraction = re.compile(r"^(Z|ZZ|Q|QQ)\((.+)\)$") + _re_algebraic = re.compile(r"^(Q|QQ)\<(.+)\>$") + + @classmethod + def preprocess(cls, domain): + if isinstance(domain, sympy.polys.domains.Domain): + return domain + elif hasattr(domain, 'to_domain'): + return domain.to_domain() + elif isinstance(domain, str): + if domain in ['Z', 'ZZ']: + return sympy.polys.domains.ZZ + + if domain in ['Q', 'QQ']: + return sympy.polys.domains.QQ + + if domain == 'ZZ_I': + return sympy.polys.domains.ZZ_I + + if domain == 'QQ_I': + return sympy.polys.domains.QQ_I + + if domain == 'EX': + return sympy.polys.domains.EX + + r = cls._re_realfield.match(domain) + + if r is not None: + _, _, prec = r.groups() + + if prec is None: + return sympy.polys.domains.RR + else: + return sympy.polys.domains.RealField(int(prec)) + + r = cls._re_complexfield.match(domain) + + if r is not None: + _, _, prec = r.groups() + + if prec is None: + return sympy.polys.domains.CC + else: + return sympy.polys.domains.ComplexField(int(prec)) + + r = cls._re_finitefield.match(domain) + + if r is not None: + return sympy.polys.domains.FF(int(r.groups()[1])) + + r = cls._re_polynomial.match(domain) + + if r is not None: + ground, gens = r.groups() + + gens = list(map(sympify, gens.split(','))) + + if ground in ['Z', 'ZZ']: + return sympy.polys.domains.ZZ.poly_ring(*gens) + elif ground in ['Q', 'QQ']: + return sympy.polys.domains.QQ.poly_ring(*gens) + elif ground in ['R', 'RR']: + return sympy.polys.domains.RR.poly_ring(*gens) + elif ground == 'ZZ_I': + return sympy.polys.domains.ZZ_I.poly_ring(*gens) + elif ground == 'QQ_I': + return sympy.polys.domains.QQ_I.poly_ring(*gens) + else: + return sympy.polys.domains.CC.poly_ring(*gens) + + r = cls._re_fraction.match(domain) + + if r is not None: + ground, gens = r.groups() + + gens = list(map(sympify, gens.split(','))) + + if ground in ['Z', 'ZZ']: + return sympy.polys.domains.ZZ.frac_field(*gens) + else: + return sympy.polys.domains.QQ.frac_field(*gens) + + r = cls._re_algebraic.match(domain) + + if r is not None: + gens = list(map(sympify, r.groups()[1].split(','))) + return sympy.polys.domains.QQ.algebraic_field(*gens) + + raise OptionError('expected a valid domain specification, got %s' % domain) + + @classmethod + def postprocess(cls, options): + if 'gens' in options and 'domain' in options and options['domain'].is_Composite and \ + (set(options['domain'].symbols) & set(options['gens'])): + raise GeneratorsError( + "ground domain and generators interfere together") + elif ('gens' not in options or not options['gens']) and \ + 'domain' in options and options['domain'] == sympy.polys.domains.EX: + raise GeneratorsError("you have to provide generators because EX domain was requested") + + +class Split(BooleanOption, metaclass=OptionType): + """``split`` option to polynomial manipulation functions. """ + + option = 'split' + + requires: list[str] = [] + excludes = ['field', 'greedy', 'domain', 'gaussian', 'extension', + 'modulus', 'symmetric'] + + @classmethod + def postprocess(cls, options): + if 'split' in options: + raise NotImplementedError("'split' option is not implemented yet") + + +class Gaussian(BooleanOption, metaclass=OptionType): + """``gaussian`` option to polynomial manipulation functions. """ + + option = 'gaussian' + + requires: list[str] = [] + excludes = ['field', 'greedy', 'domain', 'split', 'extension', + 'modulus', 'symmetric'] + + @classmethod + def postprocess(cls, options): + if 'gaussian' in options and options['gaussian'] is True: + options['domain'] = sympy.polys.domains.QQ_I + Extension.postprocess(options) + + +class Extension(Option, metaclass=OptionType): + """``extension`` option to polynomial manipulation functions. """ + + option = 'extension' + + requires: list[str] = [] + excludes = ['greedy', 'domain', 'split', 'gaussian', 'modulus', + 'symmetric'] + + @classmethod + def preprocess(cls, extension): + if extension == 1: + return bool(extension) + elif extension == 0: + raise OptionError("'False' is an invalid argument for 'extension'") + else: + if not hasattr(extension, '__iter__'): + extension = {extension} + else: + if not extension: + extension = None + else: + extension = set(extension) + + return extension + + @classmethod + def postprocess(cls, options): + if 'extension' in options and options['extension'] is not True: + options['domain'] = sympy.polys.domains.QQ.algebraic_field( + *options['extension']) + + +class Modulus(Option, metaclass=OptionType): + """``modulus`` option to polynomial manipulation functions. """ + + option = 'modulus' + + requires: list[str] = [] + excludes = ['greedy', 'split', 'domain', 'gaussian', 'extension'] + + @classmethod + def preprocess(cls, modulus): + modulus = sympify(modulus) + + if modulus.is_Integer and modulus > 0: + return int(modulus) + else: + raise OptionError( + "'modulus' must a positive integer, got %s" % modulus) + + @classmethod + def postprocess(cls, options): + if 'modulus' in options: + modulus = options['modulus'] + symmetric = options.get('symmetric', True) + options['domain'] = sympy.polys.domains.FF(modulus, symmetric) + + +class Symmetric(BooleanOption, metaclass=OptionType): + """``symmetric`` option to polynomial manipulation functions. """ + + option = 'symmetric' + + requires = ['modulus'] + excludes = ['greedy', 'domain', 'split', 'gaussian', 'extension'] + + +class Strict(BooleanOption, metaclass=OptionType): + """``strict`` option to polynomial manipulation functions. """ + + option = 'strict' + + @classmethod + def default(cls): + return True + + +class Auto(BooleanOption, Flag, metaclass=OptionType): + """``auto`` flag to polynomial manipulation functions. """ + + option = 'auto' + + after = ['field', 'domain', 'extension', 'gaussian'] + + @classmethod + def default(cls): + return True + + @classmethod + def postprocess(cls, options): + if ('domain' in options or 'field' in options) and 'auto' not in options: + options['auto'] = False + + +class Frac(BooleanOption, Flag, metaclass=OptionType): + """``auto`` option to polynomial manipulation functions. """ + + option = 'frac' + + @classmethod + def default(cls): + return False + + +class Formal(BooleanOption, Flag, metaclass=OptionType): + """``formal`` flag to polynomial manipulation functions. """ + + option = 'formal' + + @classmethod + def default(cls): + return False + + +class Polys(BooleanOption, Flag, metaclass=OptionType): + """``polys`` flag to polynomial manipulation functions. """ + + option = 'polys' + + +class Include(BooleanOption, Flag, metaclass=OptionType): + """``include`` flag to polynomial manipulation functions. """ + + option = 'include' + + @classmethod + def default(cls): + return False + + +class All(BooleanOption, Flag, metaclass=OptionType): + """``all`` flag to polynomial manipulation functions. """ + + option = 'all' + + @classmethod + def default(cls): + return False + + +class Gen(Flag, metaclass=OptionType): + """``gen`` flag to polynomial manipulation functions. """ + + option = 'gen' + + @classmethod + def default(cls): + return 0 + + @classmethod + def preprocess(cls, gen): + if isinstance(gen, (Basic, int)): + return gen + else: + raise OptionError("invalid argument for 'gen' option") + + +class Series(BooleanOption, Flag, metaclass=OptionType): + """``series`` flag to polynomial manipulation functions. """ + + option = 'series' + + @classmethod + def default(cls): + return False + + +class Symbols(Flag, metaclass=OptionType): + """``symbols`` flag to polynomial manipulation functions. """ + + option = 'symbols' + + @classmethod + def default(cls): + return numbered_symbols('s', start=1) + + @classmethod + def preprocess(cls, symbols): + if hasattr(symbols, '__iter__'): + return iter(symbols) + else: + raise OptionError("expected an iterator or iterable container, got %s" % symbols) + + +class Method(Flag, metaclass=OptionType): + """``method`` flag to polynomial manipulation functions. """ + + option = 'method' + + @classmethod + def preprocess(cls, method): + if isinstance(method, str): + return method.lower() + else: + raise OptionError("expected a string, got %s" % method) + + +def build_options(gens, args=None): + """Construct options from keyword arguments or ... options. """ + if args is None: + gens, args = (), gens + + if len(args) != 1 or 'opt' not in args or gens: + return Options(gens, args) + else: + return args['opt'] + + +def allowed_flags(args, flags): + """ + Allow specified flags to be used in the given context. + + Examples + ======== + + >>> from sympy.polys.polyoptions import allowed_flags + >>> from sympy.polys.domains import ZZ + + >>> allowed_flags({'domain': ZZ}, []) + + >>> allowed_flags({'domain': ZZ, 'frac': True}, []) + Traceback (most recent call last): + ... + FlagError: 'frac' flag is not allowed in this context + + >>> allowed_flags({'domain': ZZ, 'frac': True}, ['frac']) + + """ + flags = set(flags) + + for arg in args.keys(): + try: + if Options.__options__[arg].is_Flag and arg not in flags: + raise FlagError( + "'%s' flag is not allowed in this context" % arg) + except KeyError: + raise OptionError("'%s' is not a valid option" % arg) + + +def set_defaults(options, **defaults): + """Update options with default values. """ + if 'defaults' not in options: + options = dict(options) + options['defaults'] = defaults + + return options + +Options._init_dependencies_order() diff --git a/shared/package-files/06/06a76dad17702ab297ea355df38eb0d44f9707ac4a0e8d0e73291ee6aa4ab3af/is_set_to_native.h b/shared/package-files/06/06a76dad17702ab297ea355df38eb0d44f9707ac4a0e8d0e73291ee6aa4ab3af/is_set_to_native.h new file mode 100644 index 0000000000000000000000000000000000000000..c912d4021778db272ac4e35e7776216f1126e54c --- /dev/null +++ b/shared/package-files/06/06a76dad17702ab297ea355df38eb0d44f9707ac4a0e8d0e73291ee6aa4ab3af/is_set_to_native.h @@ -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 bool is_set_to(const at::Tensor & self, const at::Tensor & tensor); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06afee4a9a5e3b6753f3cc5af979dc409fe959763cb7dedb2c632bc8c21a8bc4/_functional_tensor.py b/shared/package-files/06/06afee4a9a5e3b6753f3cc5af979dc409fe959763cb7dedb2c632bc8c21a8bc4/_functional_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..88dc9ca21cc802b6a5b142a52cb5d63597b74ca0 --- /dev/null +++ b/shared/package-files/06/06afee4a9a5e3b6753f3cc5af979dc409fe959763cb7dedb2c632bc8c21a8bc4/_functional_tensor.py @@ -0,0 +1,960 @@ +import warnings +from typing import List, Optional, Tuple, Union + +import torch +from torch import Tensor +from torch.nn.functional import conv2d, grid_sample, interpolate, pad as torch_pad + + +def _is_tensor_a_torch_image(x: Tensor) -> bool: + return x.ndim >= 2 + + +def _assert_image_tensor(img: Tensor) -> None: + if not _is_tensor_a_torch_image(img): + raise TypeError("Tensor is not a torch image.") + + +def get_dimensions(img: Tensor) -> List[int]: + _assert_image_tensor(img) + channels = 1 if img.ndim == 2 else img.shape[-3] + height, width = img.shape[-2:] + return [channels, height, width] + + +def get_image_size(img: Tensor) -> List[int]: + # Returns (w, h) of tensor image + _assert_image_tensor(img) + return [img.shape[-1], img.shape[-2]] + + +def get_image_num_channels(img: Tensor) -> int: + _assert_image_tensor(img) + if img.ndim == 2: + return 1 + elif img.ndim > 2: + return img.shape[-3] + + raise TypeError(f"Input ndim should be 2 or more. Got {img.ndim}") + + +def _max_value(dtype: torch.dtype) -> int: + if dtype == torch.uint8: + return 255 + elif dtype == torch.int8: + return 127 + elif dtype == torch.int16: + return 32767 + elif dtype == torch.int32: + return 2147483647 + elif dtype == torch.int64: + return 9223372036854775807 + else: + # This is only here for completeness. This value is implicitly assumed in a lot of places so changing it is not + # easy. + return 1 + + +def _assert_channels(img: Tensor, permitted: List[int]) -> None: + c = get_dimensions(img)[0] + if c not in permitted: + raise TypeError(f"Input image tensor permitted channel values are {permitted}, but found {c}") + + +def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor: + if image.dtype == dtype: + return image + + if image.is_floating_point(): + + # TODO: replace with dtype.is_floating_point when torchscript supports it + if torch.tensor(0, dtype=dtype).is_floating_point(): + return image.to(dtype) + + # float to int + if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or ( + image.dtype == torch.float64 and dtype == torch.int64 + ): + msg = f"The cast from {image.dtype} to {dtype} cannot be performed safely." + raise RuntimeError(msg) + + # https://github.com/pytorch/vision/pull/2078#issuecomment-612045321 + # For data in the range 0-1, (float * 255).to(uint) is only 255 + # when float is exactly 1.0. + # `max + 1 - epsilon` provides more evenly distributed mapping of + # ranges of floats to ints. + eps = 1e-3 + max_val = float(_max_value(dtype)) + result = image.mul(max_val + 1.0 - eps) + return result.to(dtype) + else: + input_max = float(_max_value(image.dtype)) + + # int to float + # TODO: replace with dtype.is_floating_point when torchscript supports it + if torch.tensor(0, dtype=dtype).is_floating_point(): + image = image.to(dtype) + return image / input_max + + output_max = float(_max_value(dtype)) + + # int to int + if input_max > output_max: + # factor should be forced to int for torch jit script + # otherwise factor is a float and image // factor can produce different results + factor = int((input_max + 1) // (output_max + 1)) + image = torch.div(image, factor, rounding_mode="floor") + return image.to(dtype) + else: + # factor should be forced to int for torch jit script + # otherwise factor is a float and image * factor can produce different results + factor = int((output_max + 1) // (input_max + 1)) + image = image.to(dtype) + return image * factor + + +def vflip(img: Tensor) -> Tensor: + _assert_image_tensor(img) + + return img.flip(-2) + + +def hflip(img: Tensor) -> Tensor: + _assert_image_tensor(img) + + return img.flip(-1) + + +def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: + _assert_image_tensor(img) + + _, h, w = get_dimensions(img) + right = left + width + bottom = top + height + + if left < 0 or top < 0 or right > w or bottom > h: + padding_ltrb = [ + max(-left + min(0, right), 0), + max(-top + min(0, bottom), 0), + max(right - max(w, left), 0), + max(bottom - max(h, top), 0), + ] + return pad(img[..., max(top, 0) : bottom, max(left, 0) : right], padding_ltrb, fill=0) + return img[..., top:bottom, left:right] + + +def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor: + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + _assert_channels(img, [1, 3]) + + if num_output_channels not in (1, 3): + raise ValueError("num_output_channels should be either 1 or 3") + + if img.shape[-3] == 3: + r, g, b = img.unbind(dim=-3) + # This implementation closely follows the TF one: + # https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/ops/image_ops_impl.py#L2105-L2138 + l_img = (0.2989 * r + 0.587 * g + 0.114 * b).to(img.dtype) + l_img = l_img.unsqueeze(dim=-3) + else: + l_img = img.clone() + + if num_output_channels == 3: + return l_img.expand(img.shape) + + return l_img + + +def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor: + if brightness_factor < 0: + raise ValueError(f"brightness_factor ({brightness_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + return _blend(img, torch.zeros_like(img), brightness_factor) + + +def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor: + if contrast_factor < 0: + raise ValueError(f"contrast_factor ({contrast_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [3, 1]) + c = get_dimensions(img)[0] + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + if c == 3: + mean = torch.mean(rgb_to_grayscale(img).to(dtype), dim=(-3, -2, -1), keepdim=True) + else: + mean = torch.mean(img.to(dtype), dim=(-3, -2, -1), keepdim=True) + + return _blend(img, mean, contrast_factor) + + +def adjust_hue(img: Tensor, hue_factor: float) -> Tensor: + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") + + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor image") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + if get_dimensions(img)[0] == 1: # Match PIL behaviour + return img + + orig_dtype = img.dtype + img = convert_image_dtype(img, torch.float32) + + img = _rgb2hsv(img) + h, s, v = img.unbind(dim=-3) + h = (h + hue_factor) % 1.0 + img = torch.stack((h, s, v), dim=-3) + img_hue_adj = _hsv2rgb(img) + + return convert_image_dtype(img_hue_adj, orig_dtype) + + +def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor: + if saturation_factor < 0: + raise ValueError(f"saturation_factor ({saturation_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + if get_dimensions(img)[0] == 1: # Match PIL behaviour + return img + + return _blend(img, rgb_to_grayscale(img), saturation_factor) + + +def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor: + if not isinstance(img, torch.Tensor): + raise TypeError("Input img should be a Tensor.") + + _assert_channels(img, [1, 3]) + + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number") + + result = img + dtype = img.dtype + if not torch.is_floating_point(img): + result = convert_image_dtype(result, torch.float32) + + result = (gain * result**gamma).clamp(0, 1) + + result = convert_image_dtype(result, dtype) + return result + + +def _blend(img1: Tensor, img2: Tensor, ratio: float) -> Tensor: + ratio = float(ratio) + bound = _max_value(img1.dtype) + return (ratio * img1 + (1.0 - ratio) * img2).clamp(0, bound).to(img1.dtype) + + +def _rgb2hsv(img: Tensor) -> Tensor: + r, g, b = img.unbind(dim=-3) + + # Implementation is based on https://github.com/python-pillow/Pillow/blob/4174d4267616897df3746d315d5a2d0f82c656ee/ + # src/libImaging/Convert.c#L330 + maxc = torch.max(img, dim=-3).values + minc = torch.min(img, dim=-3).values + + # The algorithm erases S and H channel where `maxc = minc`. This avoids NaN + # from happening in the results, because + # + S channel has division by `maxc`, which is zero only if `maxc = minc` + # + H channel has division by `(maxc - minc)`. + # + # Instead of overwriting NaN afterwards, we just prevent it from occurring, so + # we don't need to deal with it in case we save the NaN in a buffer in + # backprop, if it is ever supported, but it doesn't hurt to do so. + eqc = maxc == minc + + cr = maxc - minc + # Since `eqc => cr = 0`, replacing denominator with 1 when `eqc` is fine. + ones = torch.ones_like(maxc) + s = cr / torch.where(eqc, ones, maxc) + # Note that `eqc => maxc = minc = r = g = b`. So the following calculation + # of `h` would reduce to `bc - gc + 2 + rc - bc + 4 + rc - bc = 6` so it + # would not matter what values `rc`, `gc`, and `bc` have here, and thus + # replacing denominator with 1 when `eqc` is fine. + cr_divisor = torch.where(eqc, ones, cr) + rc = (maxc - r) / cr_divisor + gc = (maxc - g) / cr_divisor + bc = (maxc - b) / cr_divisor + + hr = (maxc == r) * (bc - gc) + hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc) + hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc) + h = hr + hg + hb + h = torch.fmod((h / 6.0 + 1.0), 1.0) + return torch.stack((h, s, maxc), dim=-3) + + +def _hsv2rgb(img: Tensor) -> Tensor: + h, s, v = img.unbind(dim=-3) + i = torch.floor(h * 6.0) + f = (h * 6.0) - i + i = i.to(dtype=torch.int32) + + p = torch.clamp((v * (1.0 - s)), 0.0, 1.0) + q = torch.clamp((v * (1.0 - s * f)), 0.0, 1.0) + t = torch.clamp((v * (1.0 - s * (1.0 - f))), 0.0, 1.0) + i = i % 6 + + mask = i.unsqueeze(dim=-3) == torch.arange(6, device=i.device).view(-1, 1, 1) + + a1 = torch.stack((v, q, p, p, t, v), dim=-3) + a2 = torch.stack((t, v, v, q, p, p), dim=-3) + a3 = torch.stack((p, p, t, v, v, q), dim=-3) + a4 = torch.stack((a1, a2, a3), dim=-4) + + return torch.einsum("...ijk, ...xijk -> ...xjk", mask.to(dtype=img.dtype), a4) + + +def _pad_symmetric(img: Tensor, padding: List[int]) -> Tensor: + # padding is left, right, top, bottom + + # crop if needed + if padding[0] < 0 or padding[1] < 0 or padding[2] < 0 or padding[3] < 0: + neg_min_padding = [-min(x, 0) for x in padding] + crop_left, crop_right, crop_top, crop_bottom = neg_min_padding + img = img[..., crop_top : img.shape[-2] - crop_bottom, crop_left : img.shape[-1] - crop_right] + padding = [max(x, 0) for x in padding] + + in_sizes = img.size() + + _x_indices = [i for i in range(in_sizes[-1])] # [0, 1, 2, 3, ...] + left_indices = [i for i in range(padding[0] - 1, -1, -1)] # e.g. [3, 2, 1, 0] + right_indices = [-(i + 1) for i in range(padding[1])] # e.g. [-1, -2, -3] + x_indices = torch.tensor(left_indices + _x_indices + right_indices, device=img.device) + + _y_indices = [i for i in range(in_sizes[-2])] + top_indices = [i for i in range(padding[2] - 1, -1, -1)] + bottom_indices = [-(i + 1) for i in range(padding[3])] + y_indices = torch.tensor(top_indices + _y_indices + bottom_indices, device=img.device) + + ndim = img.ndim + if ndim == 3: + return img[:, y_indices[:, None], x_indices[None, :]] + elif ndim == 4: + return img[:, :, y_indices[:, None], x_indices[None, :]] + else: + raise RuntimeError("Symmetric padding of N-D tensors are not supported yet") + + +def _parse_pad_padding(padding: Union[int, List[int]]) -> List[int]: + if isinstance(padding, int): + if torch.jit.is_scripting(): + # This maybe unreachable + raise ValueError("padding can't be an int while torchscripting, set it as a list [value, ]") + pad_left = pad_right = pad_top = pad_bottom = padding + elif len(padding) == 1: + pad_left = pad_right = pad_top = pad_bottom = padding[0] + elif len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + else: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + return [pad_left, pad_right, pad_top, pad_bottom] + + +def pad( + img: Tensor, padding: Union[int, List[int]], fill: Optional[Union[int, float]] = 0, padding_mode: str = "constant" +) -> Tensor: + _assert_image_tensor(img) + + if fill is None: + fill = 0 + + if not isinstance(padding, (int, tuple, list)): + raise TypeError("Got inappropriate padding arg") + if not isinstance(fill, (int, float)): + raise TypeError("Got inappropriate fill arg") + if not isinstance(padding_mode, str): + raise TypeError("Got inappropriate padding_mode arg") + + if isinstance(padding, tuple): + padding = list(padding) + + if isinstance(padding, list): + # TODO: Jit is failing on loading this op when scripted and saved + # https://github.com/pytorch/pytorch/issues/81100 + if len(padding) not in [1, 2, 4]: + raise ValueError( + f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple" + ) + + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + p = _parse_pad_padding(padding) + + if padding_mode == "edge": + # remap padding_mode str + padding_mode = "replicate" + elif padding_mode == "symmetric": + # route to another implementation + return _pad_symmetric(img, p) + + need_squeeze = False + if img.ndim < 4: + img = img.unsqueeze(dim=0) + need_squeeze = True + + out_dtype = img.dtype + need_cast = False + if (padding_mode != "constant") and img.dtype not in (torch.float32, torch.float64): + # Here we temporarily cast input tensor to float + # until pytorch issue is resolved : + # https://github.com/pytorch/pytorch/issues/40763 + need_cast = True + img = img.to(torch.float32) + + if padding_mode in ("reflect", "replicate"): + img = torch_pad(img, p, mode=padding_mode) + else: + img = torch_pad(img, p, mode=padding_mode, value=float(fill)) + + if need_squeeze: + img = img.squeeze(dim=0) + + if need_cast: + img = img.to(out_dtype) + + return img + + +def resize( + img: Tensor, + size: List[int], + interpolation: str = "bilinear", + antialias: Optional[bool] = True, +) -> Tensor: + _assert_image_tensor(img) + + if isinstance(size, tuple): + size = list(size) + + if antialias is None: + antialias = False + + if antialias and interpolation not in ["bilinear", "bicubic"]: + # We manually set it to False to avoid an error downstream in interpolate() + # This behaviour is documented: the parameter is irrelevant for modes + # that are not bilinear or bicubic. We used to raise an error here, but + # now we don't as True is the default. + antialias = False + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [torch.float32, torch.float64]) + + # Define align_corners to avoid warnings + align_corners = False if interpolation in ["bilinear", "bicubic"] else None + + img = interpolate(img, size=size, mode=interpolation, align_corners=align_corners, antialias=antialias) + + if interpolation == "bicubic" and out_dtype == torch.uint8: + img = img.clamp(min=0, max=255) + + img = _cast_squeeze_out(img, need_cast=need_cast, need_squeeze=need_squeeze, out_dtype=out_dtype) + + return img + + +def _assert_grid_transform_inputs( + img: Tensor, + matrix: Optional[List[float]], + interpolation: str, + fill: Optional[Union[int, float, List[float]]], + supported_interpolation_modes: List[str], + coeffs: Optional[List[float]] = None, +) -> None: + + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor") + + _assert_image_tensor(img) + + if matrix is not None and not isinstance(matrix, list): + raise TypeError("Argument matrix should be a list") + + if matrix is not None and len(matrix) != 6: + raise ValueError("Argument matrix should have 6 float values") + + if coeffs is not None and len(coeffs) != 8: + raise ValueError("Argument coeffs should have 8 float values") + + if fill is not None and not isinstance(fill, (int, float, tuple, list)): + warnings.warn("Argument fill should be either int, float, tuple or list") + + # Check fill + num_channels = get_dimensions(img)[0] + if fill is not None and isinstance(fill, (tuple, list)) and len(fill) > 1 and len(fill) != num_channels: + msg = ( + "The number of elements in 'fill' cannot broadcast to match the number of " + "channels of the image ({} != {})" + ) + raise ValueError(msg.format(len(fill), num_channels)) + + if interpolation not in supported_interpolation_modes: + raise ValueError(f"Interpolation mode '{interpolation}' is unsupported with Tensor input") + + +def _cast_squeeze_in(img: Tensor, req_dtypes: List[torch.dtype]) -> Tuple[Tensor, bool, bool, torch.dtype]: + need_squeeze = False + # make image NCHW + if img.ndim < 4: + img = img.unsqueeze(dim=0) + need_squeeze = True + + out_dtype = img.dtype + need_cast = False + if out_dtype not in req_dtypes: + need_cast = True + req_dtype = req_dtypes[0] + img = img.to(req_dtype) + return img, need_cast, need_squeeze, out_dtype + + +def _cast_squeeze_out(img: Tensor, need_cast: bool, need_squeeze: bool, out_dtype: torch.dtype) -> Tensor: + if need_squeeze: + img = img.squeeze(dim=0) + + if need_cast: + if out_dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64): + # it is better to round before cast + img = torch.round(img) + img = img.to(out_dtype) + + return img + + +def _apply_grid_transform( + img: Tensor, grid: Tensor, mode: str, fill: Optional[Union[int, float, List[float]]] +) -> Tensor: + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [grid.dtype]) + + if img.shape[0] > 1: + # Apply same grid to a batch of images + grid = grid.expand(img.shape[0], grid.shape[1], grid.shape[2], grid.shape[3]) + + # Append a dummy mask for customized fill colors, should be faster than grid_sample() twice + if fill is not None: + mask = torch.ones((img.shape[0], 1, img.shape[2], img.shape[3]), dtype=img.dtype, device=img.device) + img = torch.cat((img, mask), dim=1) + + img = grid_sample(img, grid, mode=mode, padding_mode="zeros", align_corners=False) + + # Fill with required color + if fill is not None: + mask = img[:, -1:, :, :] # N * 1 * H * W + img = img[:, :-1, :, :] # N * C * H * W + mask = mask.expand_as(img) + fill_list, len_fill = (fill, len(fill)) if isinstance(fill, (tuple, list)) else ([float(fill)], 1) + fill_img = torch.tensor(fill_list, dtype=img.dtype, device=img.device).view(1, len_fill, 1, 1).expand_as(img) + if mode == "nearest": + mask = mask < 0.5 + img[mask] = fill_img[mask] + else: # 'bilinear' + img = img * mask + (1.0 - mask) * fill_img + + img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype) + return img + + +def _gen_affine_grid( + theta: Tensor, + w: int, + h: int, + ow: int, + oh: int, +) -> Tensor: + # https://github.com/pytorch/pytorch/blob/74b65c32be68b15dc7c9e8bb62459efbfbde33d8/aten/src/ATen/native/ + # AffineGridGenerator.cpp#L18 + # Difference with AffineGridGenerator is that: + # 1) we normalize grid values after applying theta + # 2) we can normalize by other image size, such that it covers "extend" option like in PIL.Image.rotate + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=theta.dtype, device=theta.device) + x_grid = torch.linspace(-ow * 0.5 + d, ow * 0.5 + d - 1, steps=ow, device=theta.device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(-oh * 0.5 + d, oh * 0.5 + d - 1, steps=oh, device=theta.device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta = theta.transpose(1, 2) / torch.tensor([0.5 * w, 0.5 * h], dtype=theta.dtype, device=theta.device) + output_grid = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta) + return output_grid.view(1, oh, ow, 2) + + +def affine( + img: Tensor, + matrix: List[float], + interpolation: str = "nearest", + fill: Optional[Union[int, float, List[float]]] = None, +) -> Tensor: + _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"]) + + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3) + shape = img.shape + # grid will be generated on the same device as theta and img + grid = _gen_affine_grid(theta, w=shape[-1], h=shape[-2], ow=shape[-1], oh=shape[-2]) + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _compute_affine_output_size(matrix: List[float], w: int, h: int) -> Tuple[int, int]: + + # Inspired of PIL implementation: + # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054 + + # pts are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + # Points are shifted due to affine matrix torch convention about + # the center point. Center is (0, 0) for image center pivot point (w * 0.5, h * 0.5) + pts = torch.tensor( + [ + [-0.5 * w, -0.5 * h, 1.0], + [-0.5 * w, 0.5 * h, 1.0], + [0.5 * w, 0.5 * h, 1.0], + [0.5 * w, -0.5 * h, 1.0], + ] + ) + theta = torch.tensor(matrix, dtype=torch.float).view(2, 3) + new_pts = torch.matmul(pts, theta.T) + min_vals, _ = new_pts.min(dim=0) + max_vals, _ = new_pts.max(dim=0) + + # shift points to [0, w] and [0, h] interval to match PIL results + min_vals += torch.tensor((w * 0.5, h * 0.5)) + max_vals += torch.tensor((w * 0.5, h * 0.5)) + + # Truncate precision to 1e-4 to avoid ceil of Xe-15 to 1.0 + tol = 1e-4 + cmax = torch.ceil((max_vals / tol).trunc_() * tol) + cmin = torch.floor((min_vals / tol).trunc_() * tol) + size = cmax - cmin + return int(size[0]), int(size[1]) # w, h + + +def rotate( + img: Tensor, + matrix: List[float], + interpolation: str = "nearest", + expand: bool = False, + fill: Optional[Union[int, float, List[float]]] = None, +) -> Tensor: + _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"]) + w, h = img.shape[-1], img.shape[-2] + ow, oh = _compute_affine_output_size(matrix, w, h) if expand else (w, h) + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3) + # grid will be generated on the same device as theta and img + grid = _gen_affine_grid(theta, w=w, h=h, ow=ow, oh=oh) + + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _perspective_grid(coeffs: List[float], ow: int, oh: int, dtype: torch.dtype, device: torch.device) -> Tensor: + # https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/ + # src/libImaging/Geometry.c#L394 + + # + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + # + theta1 = torch.tensor( + [[[coeffs[0], coeffs[1], coeffs[2]], [coeffs[3], coeffs[4], coeffs[5]]]], dtype=dtype, device=device + ) + theta2 = torch.tensor([[[coeffs[6], coeffs[7], 1.0], [coeffs[6], coeffs[7], 1.0]]], dtype=dtype, device=device) + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device) + x_grid = torch.linspace(d, ow * 1.0 + d - 1.0, steps=ow, device=device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(d, oh * 1.0 + d - 1.0, steps=oh, device=device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta1 = theta1.transpose(1, 2) / torch.tensor([0.5 * ow, 0.5 * oh], dtype=dtype, device=device) + output_grid1 = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta1) + output_grid2 = base_grid.view(1, oh * ow, 3).bmm(theta2.transpose(1, 2)) + + output_grid = output_grid1 / output_grid2 - 1.0 + return output_grid.view(1, oh, ow, 2) + + +def perspective( + img: Tensor, + perspective_coeffs: List[float], + interpolation: str = "bilinear", + fill: Optional[Union[int, float, List[float]]] = None, +) -> Tensor: + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor.") + + _assert_image_tensor(img) + + _assert_grid_transform_inputs( + img, + matrix=None, + interpolation=interpolation, + fill=fill, + supported_interpolation_modes=["nearest", "bilinear"], + coeffs=perspective_coeffs, + ) + + ow, oh = img.shape[-1], img.shape[-2] + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + grid = _perspective_grid(perspective_coeffs, ow=ow, oh=oh, dtype=dtype, device=img.device) + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _get_gaussian_kernel1d(kernel_size: int, sigma: float) -> Tensor: + ksize_half = (kernel_size - 1) * 0.5 + + x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size) + pdf = torch.exp(-0.5 * (x / sigma).pow(2)) + kernel1d = pdf / pdf.sum() + + return kernel1d + + +def _get_gaussian_kernel2d( + kernel_size: List[int], sigma: List[float], dtype: torch.dtype, device: torch.device +) -> Tensor: + kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0]).to(device, dtype=dtype) + kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1]).to(device, dtype=dtype) + kernel2d = torch.mm(kernel1d_y[:, None], kernel1d_x[None, :]) + return kernel2d + + +def gaussian_blur(img: Tensor, kernel_size: List[int], sigma: List[float]) -> Tensor: + if not (isinstance(img, torch.Tensor)): + raise TypeError(f"img should be Tensor. Got {type(img)}") + + _assert_image_tensor(img) + + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype, device=img.device) + kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype]) + + # padding = (left, right, top, bottom) + padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2] + img = torch_pad(img, padding, mode="reflect") + img = conv2d(img, kernel, groups=img.shape[-3]) + + img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype) + return img + + +def invert(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + return _max_value(img.dtype) - img + + +def posterize(img: Tensor, bits: int) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + if img.dtype != torch.uint8: + raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}") + + _assert_channels(img, [1, 3]) + mask = -int(2 ** (8 - bits)) # JIT-friendly for: ~(2 ** (8 - bits) - 1) + return img & mask + + +def solarize(img: Tensor, threshold: float) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + if threshold > _max_value(img.dtype): + raise TypeError("Threshold should be less than bound of img.") + + inverted_img = invert(img) + return torch.where(img >= threshold, inverted_img, img) + + +def _blurred_degenerate_image(img: Tensor) -> Tensor: + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + + kernel = torch.ones((3, 3), dtype=dtype, device=img.device) + kernel[1, 1] = 5.0 + kernel /= kernel.sum() + kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + result_tmp, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype]) + result_tmp = conv2d(result_tmp, kernel, groups=result_tmp.shape[-3]) + result_tmp = _cast_squeeze_out(result_tmp, need_cast, need_squeeze, out_dtype) + + result = img.clone() + result[..., 1:-1, 1:-1] = result_tmp + + return result + + +def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor: + if sharpness_factor < 0: + raise ValueError(f"sharpness_factor ({sharpness_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + if img.size(-1) <= 2 or img.size(-2) <= 2: + return img + + return _blend(img, _blurred_degenerate_image(img), sharpness_factor) + + +def autocontrast(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + bound = _max_value(img.dtype) + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + + minimum = img.amin(dim=(-2, -1), keepdim=True).to(dtype) + maximum = img.amax(dim=(-2, -1), keepdim=True).to(dtype) + scale = bound / (maximum - minimum) + eq_idxs = torch.isfinite(scale).logical_not() + minimum[eq_idxs] = 0 + scale[eq_idxs] = 1 + + return ((img - minimum) * scale).clamp(0, bound).to(img.dtype) + + +def _scale_channel(img_chan: Tensor) -> Tensor: + # TODO: we should expect bincount to always be faster than histc, but this + # isn't always the case. Once + # https://github.com/pytorch/pytorch/issues/53194 is fixed, remove the if + # block and only use bincount. + if img_chan.is_cuda: + hist = torch.histc(img_chan.to(torch.float32), bins=256, min=0, max=255) + else: + hist = torch.bincount(img_chan.reshape(-1), minlength=256) + + nonzero_hist = hist[hist != 0] + step = torch.div(nonzero_hist[:-1].sum(), 255, rounding_mode="floor") + if step == 0: + return img_chan + + lut = torch.div(torch.cumsum(hist, 0) + torch.div(step, 2, rounding_mode="floor"), step, rounding_mode="floor") + lut = torch.nn.functional.pad(lut, [1, 0])[:-1].clamp(0, 255) + + return lut[img_chan.to(torch.int64)].to(torch.uint8) + + +def _equalize_single_image(img: Tensor) -> Tensor: + return torch.stack([_scale_channel(img[c]) for c in range(img.size(0))]) + + +def equalize(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if not (3 <= img.ndim <= 4): + raise TypeError(f"Input image tensor should have 3 or 4 dimensions, but found {img.ndim}") + if img.dtype != torch.uint8: + raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}") + + _assert_channels(img, [1, 3]) + + if img.ndim == 3: + return _equalize_single_image(img) + + return torch.stack([_equalize_single_image(x) for x in img]) + + +def normalize(tensor: Tensor, mean: List[float], std: List[float], inplace: bool = False) -> Tensor: + _assert_image_tensor(tensor) + + if not tensor.is_floating_point(): + raise TypeError(f"Input tensor should be a float tensor. Got {tensor.dtype}.") + + if tensor.ndim < 3: + raise ValueError( + f"Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = {tensor.size()}" + ) + + if not inplace: + tensor = tensor.clone() + + dtype = tensor.dtype + mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device) + std = torch.as_tensor(std, dtype=dtype, device=tensor.device) + if (std == 0).any(): + raise ValueError(f"std evaluated to zero after conversion to {dtype}, leading to division by zero.") + if mean.ndim == 1: + mean = mean.view(-1, 1, 1) + if std.ndim == 1: + std = std.view(-1, 1, 1) + return tensor.sub_(mean).div_(std) + + +def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor: + _assert_image_tensor(img) + + if not inplace: + img = img.clone() + + img[..., i : i + h, j : j + w] = v + return img + + +def _create_identity_grid(size: List[int]) -> Tensor: + hw_space = [torch.linspace((-s + 1) / s, (s - 1) / s, s) for s in size] + grid_y, grid_x = torch.meshgrid(hw_space, indexing="ij") + return torch.stack([grid_x, grid_y], -1).unsqueeze(0) # 1 x H x W x 2 + + +def elastic_transform( + img: Tensor, + displacement: Tensor, + interpolation: str = "bilinear", + fill: Optional[Union[int, float, List[float]]] = None, +) -> Tensor: + + if not (isinstance(img, torch.Tensor)): + raise TypeError(f"img should be Tensor. Got {type(img)}") + + size = list(img.shape[-2:]) + displacement = displacement.to(img.device) + + identity_grid = _create_identity_grid(size) + grid = identity_grid.to(img.device) + displacement + return _apply_grid_transform(img, grid, interpolation, fill) diff --git a/shared/package-files/06/06b040956a82a017f58a62be3255645dd5d545658338157d2730bc543b8aa64a/_dirichlet_grad_cuda_dispatch.h b/shared/package-files/06/06b040956a82a017f58a62be3255645dd5d545658338157d2730bc543b8aa64a/_dirichlet_grad_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..293418670ce1b9ac2ded03c65c016faff5a428bb --- /dev/null +++ b/shared/package-files/06/06b040956a82a017f58a62be3255645dd5d545658338157d2730bc543b8aa64a/_dirichlet_grad_cuda_dispatch.h @@ -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 _dirichlet_grad(const at::Tensor & x, const at::Tensor & alpha, const at::Tensor & total); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/06/06b381caddd5de9c6cedd3e0e350791f7b89745b22a86f514ef65e88772e12aa/special_zeta_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/06/06b381caddd5de9c6cedd3e0e350791f7b89745b22a86f514ef65e88772e12aa/special_zeta_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..dbaa2ea7751a49ac5fe43b690948b675d02bdadc --- /dev/null +++ b/shared/package-files/06/06b381caddd5de9c6cedd3e0e350791f7b89745b22a86f514ef65e88772e12aa/special_zeta_compositeexplicitautogradnonfunctional_dispatch.h @@ -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 special_zeta(const at::Tensor & self, const at::Tensor & other); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/06/06b39b66efb6f772121ab44293451f5d2f1ce5b7ce8c198808f967c889db9977/_screening.py b/shared/package-files/06/06b39b66efb6f772121ab44293451f5d2f1ce5b7ce8c198808f967c889db9977/_screening.py new file mode 100644 index 0000000000000000000000000000000000000000..edb77aff725df51e83c98d90d787cc6718d48ed8 --- /dev/null +++ b/shared/package-files/06/06b39b66efb6f772121ab44293451f5d2f1ce5b7ce8c198808f967c889db9977/_screening.py @@ -0,0 +1,442 @@ +""" +Created on Sat May 19 15:53:21 2018 + +Author: Josef Perktold +License: BSD-3 +""" + +from collections import defaultdict + +import numpy as np + +from statsmodels.base._penalties import SCADSmoothed + + +class ScreeningResults: + """Results for Variable Screening + + Note: Indices except for exog_idx and in the iterated case also + idx_nonzero_batches are based on the combined [exog_keep, exog] array. + + Attributes + ---------- + results_final : instance + Results instance returned by the final fit of the penalized model, i.e. + after trimming exog with params below trimming threshold. + results_pen : results instance + Results instance of the penalized model before trimming. This includes + variables from the last forward selection. + idx_nonzero : ndarray + Index of exog columns in the final selection including exog_keep. + idx_exog : ndarray + Index of exog columns in the final selection for exog candidates, i.e. + without exog_keep. + idx_excl : ndarray + Index of excluded exog based on combined [exog_keep, exog] array. This + is the complement of idx_nonzero. + converged : bool + True if the iteration has converged and stopped before maxiter has been + reached. False if maxiter has been reached. + iterations : int + Number of iterations in the screening process. Each iteration consists + of a forward selection step and a trimming step. + history : dict of lists + Results collected for each iteration during the screening process. + Keys are 'idx_nonzero', 'keep', 'params_keep' and 'idx_added', each + holding a list with one entry appended per iteration. + screener : instance of VariableScreening + The VariableScreening instance that produced these results. + + The ScreeningResults returned by `screen_exog_iterator` has additional + attributes: + + idx_nonzero_batches : ndarray, 2-D + Two-dimensional array with batch index in the first column and variable + index within batch in the second column. They can be used jointly as + index for the data in the exog_iterator. + exog_final_names : list of str + 'var_' where `bidx` is the batch index and `idx` is the + index of the selected column within batch `bidx`. + history_batches : dict of lists + This provides information about the selected variables within each + batch during the first round screening. + 'idx_nonzero' is based on the array that includes exog_keep, while + 'idx_exog' is the index based on the exog of the batch. + """ + def __init__(self, screener, **kwds): + self.screener = screener + self.__dict__.update(**kwds) + + +class VariableScreening: + """Ultra-high, conditional sure independence screening + + This is an adjusted version of Fan's sure independence screening. + + Parameters + ---------- + model : instance of penalizing model + Examples: GLMPenalized, PoissonPenalized and LogitPenalized. + The attributes of the model instance `pen_weight` and `penal` will be + ignored. + pen_weight : float, optional + Penalization weight use in SCAD penalized MLE. + use_weights : bool, optional + If True, penalty weights are used so that `exog_keep` is not + penalized (weight 0) while candidate exog have weight 1. If False, + all penalty weights are set equally. + k_add : int, optional + Number of exog to add during expansion or forward selection. + See Notes section for tie handling. + k_max_add : int, optional + Maximum number of variables to include during variable addition, i.e. + forward selection. Default is 30. + threshold_trim : float, optional + Threshold for trimming parameters to zero, default is 1e-4. + k_max_included : int, optional + Maximum total number of variables to include in model. + ranking_attr : str, optional + This determines the result attribute or model method that is used for + the ranking of exog to include. The availability of attributes depends + on the model. + Default is 'resid_pearson', 'model.score_factor' can be used in GLM. + ranking_project : bool, optional + If ranking_project is True, then the exog candidates for inclusion are + first projected on the already included exog before the computation + of the ranking measure. This brings the ranking measure closer to + the statistic of a score test for variable addition. + + Notes + ----- + Status: experimental, tested only on a limited set of models and + with a limited set of model options. + + Tie handling: If there are ties at the decision threshold, then all those + tied exog columns are treated in the same way. During forward selection + all exog columns with the same boundary value are included. During + elimination, the tied columns are not dropped. Consequently, if ties are + present, then the number of included exog can be larger than specified + by k_add, k_max_add and k_max_included. + + The screening algorithm works similar to step wise regression. Each + iteration of the screening algorithm includes a forward selection step + where variables are added to the model, and a backwards selection step + where variables are removed. In contrast to step wise regression, we add + a fixed number of variables at each forward selection step. The + backwards selection step is based on SCAD penalized estimation and + trimming of variables with estimated coefficients below a threshold. + The tuning parameters can be used to adjust the number of variables to add + and to include depending on the size of the dataset. + + There is currently no automatic tuning parameter selection. Candidate + explanatory variables should be standardized or should be on a similar + scale because penalization and trimming are based on the absolute values + of the parameters. + + + TODOs and current limitations: + + freq_weights are not supported in this. Candidate ranking uses + moment condition with resid_pearson or others without freq_weights. + pearson_resid: GLM resid_pearson does not include freq_weights. + + variable names: do we keep track of those? currently made-up names + + currently only supports numpy arrays, no exog type check or conversion + + currently only single columns are selected, no terms (multi column exog) + """ + + def __init__(self, model, pen_weight=None, use_weights=True, k_add=30, + k_max_add=30, threshold_trim=1e-4, k_max_included=20, + ranking_attr="resid_pearson", ranking_project=True): + + self.model = model + self.model_class = model.__class__ + self.init_kwds = model._get_init_kwds() + # pen_weight and penal are explicitly included + # TODO: check what we want to do here + self.init_kwds.pop("pen_weight", None) + self.init_kwds.pop("penal", None) + + self.endog = model.endog + self.exog_keep = model.exog + self.k_keep = model.exog.shape[1] + self.nobs = len(self.endog) + self.penal = self._get_penal() + + if pen_weight is not None: + self.pen_weight = pen_weight + else: + self.pen_weight = self.nobs * 10 + + # option for screening algorithm + self.use_weights = use_weights + self.k_add = k_add + self.k_max_add = k_max_add + self.threshold_trim = threshold_trim + self.k_max_included = k_max_included + self.ranking_attr = ranking_attr + self.ranking_project = ranking_project + + def _get_penal(self, weights=None): + """Create new Penalty instance""" + return SCADSmoothed(0.1, c0=0.0001, weights=weights) + + def ranking_measure(self, res_pen, exog, keep=None): + """Compute measure for ranking exog candidates for inclusion""" + endog = self.endog + + if self.ranking_project: + assert res_pen.model.exog.shape[1] == len(keep) + ex_incl = res_pen.model.exog[:, keep] + exog = exog - ex_incl.dot(np.linalg.pinv(ex_incl).dot(exog)) + + if self.ranking_attr == "predicted_poisson": + # I keep this for more experiments + + # TODO: does it really help to change/trim params + # we are not reestimating with trimmed model + p = res_pen.params.copy() + if keep is not None: + p[~keep] = 0 + predicted = res_pen.model.predict(p) + # this is currently hardcoded for Poisson + resid_factor = (endog - predicted) / np.sqrt(predicted) + elif self.ranking_attr[:6] == "model.": + # use model method, this is intended for score_factor + attr = self.ranking_attr.split(".")[1] + resid_factor = getattr(res_pen.model, attr)(res_pen.params) + if resid_factor.ndim == 2: + # for score_factor when extra params are in model + resid_factor = resid_factor[:, 0] + mom_cond = np.abs(resid_factor.dot(exog))**2 + else: + # use results attribute + resid_factor = getattr(res_pen, self.ranking_attr) + mom_cond = np.abs(resid_factor.dot(exog))**2 + return mom_cond + + def screen_exog(self, exog, endog=None, maxiter=100, method="bfgs", + disp=False, fit_kwds=None): + """Screen and select variables (columns) in exog + + Parameters + ---------- + exog : ndarray + Candidate explanatory variables that are screened for inclusion in + the model. + endog : ndarray, optional + Use a new endog in the screening model. + This is not tested yet, and might not work correctly. + maxiter : int, optional + Number of screening iterations. + method : str, optional + Optimization method to use in fit, needs to be only of the gradient + optimizers. + disp : bool, optional + Display option for fit during optimization. + fit_kwds : dict-like, optional + Additional keyword arguments passed to the model's `fit` method. + + Returns + ------- + res_screen : instance of ScreeningResults + The attribute `results_final` contains the results instance + with the final model selection. + `idx_nonzero` contains the index of the selected exog in the full + exog, combined exog that are always kept plus exog_candidates. + See ScreeningResults for a full description. + """ + model_class = self.model_class + if endog is None: + # allow a different endog than used in model + endog = self.endog + x0 = self.exog_keep + k_keep = self.k_keep + x1 = exog + k_current = x0.shape[1] + # TODO: remove the need for x, use x1 separately from x0 + # needs change to idx to be based on x1 (candidate variables) + x = np.column_stack((x0, x1)) + nobs, k_vars = x.shape + fkwds = fit_kwds if fit_kwds is not None else {} + fit_kwds = {"maxiter": 200, "disp": False} + fit_kwds.update(fkwds) + + history = defaultdict(list) + idx_nonzero = np.arange(k_keep, dtype=int) + keep = np.ones(k_keep, np.bool_) + idx_excl = np.arange(k_keep, k_vars) + mod_pen = model_class(endog, x0, **self.init_kwds) + # do not penalize initial estimate + mod_pen.pen_weight = 0 + res_pen = mod_pen.fit(**fit_kwds) + start_params = res_pen.params + converged = False + idx_old = [] + iterations = 0 + for _ in range(maxiter): + iterations += 1 + # candidates for inclusion in next iteration + x1 = x[:, idx_excl] + mom_cond = self.ranking_measure(res_pen, x1, keep=keep) + assert len(mom_cond) == len(idx_excl) + mcs = np.sort(mom_cond)[::-1] + idx_thr = min((self.k_max_add, k_current + self.k_add, len(mcs))) + threshold = mcs[idx_thr] + # indices of exog in current expansion model + idx = np.concatenate((idx_nonzero, idx_excl[mom_cond > threshold])) + start_params2 = np.zeros(len(idx)) + start_params2[:len(start_params)] = start_params + + if self.use_weights: + weights = np.ones(len(idx)) + weights[:k_keep] = 0 + # modify Penalty instance attached to self + # damgerous if res_pen is reused + self.penal.weights = weights + mod_pen = model_class(endog, x[:, idx], penal=self.penal, + pen_weight=self.pen_weight, + **self.init_kwds) + + res_pen = mod_pen.fit(method=method, + start_params=start_params2, + warn_convergence=False, skip_hessian=True, + **fit_kwds) + + keep = np.abs(res_pen.params) > self.threshold_trim + # use largest params to keep + if keep.sum() > self.k_max_included: + # TODO we can use now np.partition with partial sort + thresh_params = np.sort(np.abs(res_pen.params))[ + -self.k_max_included] + keep2 = np.abs(res_pen.params) > thresh_params + keep = np.logical_and(keep, keep2) + + # Note: idx and keep are for current expansion model + # idx_nonzero has indices of selected variables in full exog + keep[:k_keep] = True # always keep exog_keep + idx_nonzero = idx[keep] + + if disp: + print(keep) + print(idx_nonzero) + # x0 is exog of currently selected model, not used in iteration + # x0 = x[:, idx_nonzero] + k_current = len(idx_nonzero) + start_params = res_pen.params[keep] + + # use mask to get excluded indices + mask_excl = np.ones(k_vars, dtype=bool) + mask_excl[idx_nonzero] = False + idx_excl = np.nonzero(mask_excl)[0] + history["idx_nonzero"].append(idx_nonzero) + history["keep"].append(keep) + history["params_keep"].append(start_params) + history["idx_added"].append(idx) + + if (len(idx_nonzero) == len(idx_old) and + (idx_nonzero == idx_old).all()): + converged = True + break + idx_old = idx_nonzero + + # final esimate + # check that we still have exog_keep + assert np.all(idx_nonzero[:k_keep] == np.arange(k_keep)) + if self.use_weights: + weights = np.ones(len(idx_nonzero)) + weights[:k_keep] = 0 + # create new Penalty instance to avoide sharing attached penal + penal = self._get_penal(weights=weights) + else: + penal = self.penal + mod_final = model_class(endog, x[:, idx_nonzero], + penal=penal, + pen_weight=self.pen_weight, + **self.init_kwds) + + res_final = mod_final.fit(method=method, + start_params=start_params, + warn_convergence=False, + **fit_kwds) + # set exog_names for final model + xnames = [f"var{ii:4d}" for ii in idx_nonzero] + res_final.model.exog_names[k_keep:] = xnames[k_keep:] + + res = ScreeningResults(self, + results_pen=res_pen, + results_final=res_final, + idx_nonzero=idx_nonzero, + idx_exog=idx_nonzero[k_keep:] - k_keep, + idx_excl=idx_excl, + history=history, + converged=converged, + iterations=iterations + ) + return res + + def screen_exog_iterator(self, exog_iterator): + """ + Batched version of screen exog + + This screens variables in a two step process: + + In the first step screen_exog is used on each element of the + exog_iterator, and the batch winners are collected. + + In the second step all batch winners are combined into a new array + of exog candidates and `screen_exog` is used to select a final + model. + + Parameters + ---------- + exog_iterator : iterator over ndarrays + Batches of candidate explanatory variables that are screened + for inclusion in the model. + + Returns + ------- + res_screen_final : instance of ScreeningResults + This is the instance returned by the second round call to + `screen_exog`. Additional attributes are added to provide + more information about the batched selection process. + The index of final nonzero variables is + `idx_nonzero_batches` which is a 2-dimensional array with batch + index in the first column and variable index within batch in the + second column. They can be used jointly as index for the data + in the exog_iterator. + See ScreeningResults for a full description. + """ + k_keep = self.k_keep + # res_batches = [] + res_idx = [] + exog_winner = [] + exog_idx = [] + for ex in exog_iterator: + res_screen = self.screen_exog(ex, maxiter=20) + # avoid storing res_screen, only for debugging + # res_batches.append(res_screen) + res_idx.append(res_screen.idx_nonzero) + exog_winner.append(ex[:, res_screen.idx_nonzero[k_keep:] - k_keep]) + exog_idx.append(res_screen.idx_nonzero[k_keep:] - k_keep) + + exog_winner = np.column_stack(exog_winner) + res_screen_final = self.screen_exog(exog_winner, maxiter=20) + + exog_winner_names = [f"var{bidx:d}_{idx:d}" + for bidx, batch in enumerate(exog_idx) + for idx in batch] + + idx_full = [(bidx, idx) + for bidx, batch in enumerate(exog_idx) + for idx in batch] + ex_final_idx = res_screen_final.idx_nonzero[k_keep:] - k_keep + final_names = np.array(exog_winner_names)[ex_final_idx] + res_screen_final.idx_nonzero_batches = np.array(idx_full)[ex_final_idx] + res_screen_final.exog_final_names = final_names + history = {"idx_nonzero": res_idx, + "idx_exog": exog_idx} + res_screen_final.history_batches = history + return res_screen_final diff --git a/shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/ibm6154-c b/shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/ibm6154-c new file mode 100644 index 0000000000000000000000000000000000000000..5f9b30a0ce5412015b14e31341215b33b1c85410 Binary files /dev/null and b/shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/ibm6154-c differ diff --git a/shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/ibmapa8c-c b/shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/ibmapa8c-c new file mode 100644 index 0000000000000000000000000000000000000000..5f9b30a0ce5412015b14e31341215b33b1c85410 Binary files /dev/null and b/shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/ibmapa8c-c differ diff --git a/shared/package-files/06/06b83b8b3586648dc1ad136c0ed25301883cc7e7d7f03b3286981416a15b3057/clone_ops.h b/shared/package-files/06/06b83b8b3586648dc1ad136c0ed25301883cc7e7d7f03b3286981416a15b3057/clone_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..960b2e1d4625fe0375339deed4514f2de6a6ba7b --- /dev/null +++ b/shared/package-files/06/06b83b8b3586648dc1ad136c0ed25301883cc7e7d7f03b3286981416a15b3057/clone_ops.h @@ -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 clone { + 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::clone") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::optional memory_format); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional memory_format); +}; + +struct TORCH_API clone_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::clone") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clone.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::optional memory_format, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional memory_format, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/06b881b824f71e95d72af4ab865de4c35553e791b6d959a125caac61401cc350/encoder.py b/shared/package-files/06/06b881b824f71e95d72af4ab865de4c35553e791b6d959a125caac61401cc350/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..687c50683a09c06a9315bc6511e26dd474dad638 --- /dev/null +++ b/shared/package-files/06/06b881b824f71e95d72af4ab865de4c35553e791b6d959a125caac61401cc350/encoder.py @@ -0,0 +1,442 @@ +"""Implementation of JSONEncoder +""" +import re + +try: + from _json import encode_basestring_ascii as c_encode_basestring_ascii +except ImportError: + c_encode_basestring_ascii = None +try: + from _json import encode_basestring as c_encode_basestring +except ImportError: + c_encode_basestring = None +try: + from _json import make_encoder as c_make_encoder +except ImportError: + c_make_encoder = None + +ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') +ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') +HAS_UTF8 = re.compile(b'[\x80-\xff]') +ESCAPE_DCT = { + '\\': '\\\\', + '"': '\\"', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', +} +for i in range(0x20): + ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i)) + #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) + +INFINITY = float('inf') + +def py_encode_basestring(s): + """Return a JSON representation of a Python string + + """ + def replace(match): + return ESCAPE_DCT[match.group(0)] + return '"' + ESCAPE.sub(replace, s) + '"' + + +encode_basestring = (c_encode_basestring or py_encode_basestring) + + +def py_encode_basestring_ascii(s): + """Return an ASCII-only JSON representation of a Python string + + """ + def replace(match): + s = match.group(0) + try: + return ESCAPE_DCT[s] + except KeyError: + n = ord(s) + if n < 0x10000: + return '\\u{0:04x}'.format(n) + #return '\\u%04x' % (n,) + else: + # surrogate pair + n -= 0x10000 + s1 = 0xd800 | ((n >> 10) & 0x3ff) + s2 = 0xdc00 | (n & 0x3ff) + return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) + return '"' + ESCAPE_ASCII.sub(replace, s) + '"' + + +encode_basestring_ascii = ( + c_encode_basestring_ascii or py_encode_basestring_ascii) + +class JSONEncoder(object): + """Extensible JSON encoder for Python data structures. + + Supports the following objects and types by default: + + +-------------------+---------------+ + | Python | JSON | + +===================+===============+ + | dict | object | + +-------------------+---------------+ + | list, tuple | array | + +-------------------+---------------+ + | str | string | + +-------------------+---------------+ + | int, float | number | + +-------------------+---------------+ + | True | true | + +-------------------+---------------+ + | False | false | + +-------------------+---------------+ + | None | null | + +-------------------+---------------+ + + To extend this to recognize other objects, subclass and implement a + ``.default()`` method with another method that returns a serializable + object for ``o`` if possible, otherwise it should call the superclass + implementation (to raise ``TypeError``). + + """ + item_separator = ', ' + key_separator = ': ' + def __init__(self, *, skipkeys=False, ensure_ascii=True, + check_circular=True, allow_nan=True, sort_keys=False, + indent=None, separators=None, default=None): + """Constructor for JSONEncoder, with sensible defaults. + + If skipkeys is false, then it is a TypeError to attempt + encoding of keys that are not str, int, float or None. If + skipkeys is True, such items are simply skipped. + + If ensure_ascii is true, the output is guaranteed to be str + objects with all incoming non-ASCII characters escaped. If + ensure_ascii is false, the output can contain non-ASCII characters. + + If check_circular is true, then lists, dicts, and custom encoded + objects will be checked for circular references during encoding to + prevent an infinite recursion (which would cause an RecursionError). + Otherwise, no such check takes place. + + If allow_nan is true, then NaN, Infinity, and -Infinity will be + encoded as such. This behavior is not JSON specification compliant, + but is consistent with most JavaScript based encoders and decoders. + Otherwise, it will be a ValueError to encode such floats. + + If sort_keys is true, then the output of dictionaries will be + sorted by key; this is useful for regression tests to ensure + that JSON serializations can be compared on a day-to-day basis. + + If indent is a non-negative integer, then JSON array + elements and object members will be pretty-printed with that + indent level. An indent level of 0 will only insert newlines. + None is the most compact representation. + + If specified, separators should be an (item_separator, key_separator) + tuple. The default is (', ', ': ') if *indent* is ``None`` and + (',', ': ') otherwise. To get the most compact JSON representation, + you should specify (',', ':') to eliminate whitespace. + + If specified, default is a function that gets called for objects + that can't otherwise be serialized. It should return a JSON encodable + version of the object or raise a ``TypeError``. + + """ + + self.skipkeys = skipkeys + self.ensure_ascii = ensure_ascii + self.check_circular = check_circular + self.allow_nan = allow_nan + self.sort_keys = sort_keys + self.indent = indent + if separators is not None: + self.item_separator, self.key_separator = separators + elif indent is not None: + self.item_separator = ',' + if default is not None: + self.default = default + + def default(self, o): + """Implement this method in a subclass such that it returns + a serializable object for ``o``, or calls the base implementation + (to raise a ``TypeError``). + + For example, to support arbitrary iterators, you could + implement default like this:: + + def default(self, o): + try: + iterable = iter(o) + except TypeError: + pass + else: + return list(iterable) + # Let the base class default method raise the TypeError + return JSONEncoder.default(self, o) + + """ + raise TypeError(f'Object of type {o.__class__.__name__} ' + f'is not JSON serializable') + + def encode(self, o): + """Return a JSON string representation of a Python data structure. + + >>> from json.encoder import JSONEncoder + >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) + '{"foo": ["bar", "baz"]}' + + """ + # This is for extremely simple cases and benchmarks. + if isinstance(o, str): + if self.ensure_ascii: + return encode_basestring_ascii(o) + else: + return encode_basestring(o) + # This doesn't pass the iterator directly to ''.join() because the + # exceptions aren't as detailed. The list call should be roughly + # equivalent to the PySequence_Fast that ''.join() would do. + chunks = self.iterencode(o, _one_shot=True) + if not isinstance(chunks, (list, tuple)): + chunks = list(chunks) + return ''.join(chunks) + + def iterencode(self, o, _one_shot=False): + """Encode the given object and yield each string + representation as available. + + For example:: + + for chunk in JSONEncoder().iterencode(bigobject): + mysocket.write(chunk) + + """ + if self.check_circular: + markers = {} + else: + markers = None + if self.ensure_ascii: + _encoder = encode_basestring_ascii + else: + _encoder = encode_basestring + + def floatstr(o, allow_nan=self.allow_nan, + _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY): + # Check for specials. Note that this type of test is processor + # and/or platform-specific, so do tests which don't depend on the + # internals. + + if o != o: + text = 'NaN' + elif o == _inf: + text = 'Infinity' + elif o == _neginf: + text = '-Infinity' + else: + return _repr(o) + + if not allow_nan: + raise ValueError( + "Out of range float values are not JSON compliant: " + + repr(o)) + + return text + + + if (_one_shot and c_make_encoder is not None + and self.indent is None): + _iterencode = c_make_encoder( + markers, self.default, _encoder, self.indent, + self.key_separator, self.item_separator, self.sort_keys, + self.skipkeys, self.allow_nan) + else: + _iterencode = _make_iterencode( + markers, self.default, _encoder, self.indent, floatstr, + self.key_separator, self.item_separator, self.sort_keys, + self.skipkeys, _one_shot) + return _iterencode(o, 0) + +def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, + _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, + ## HACK: hand-optimized bytecode; turn globals into locals + ValueError=ValueError, + dict=dict, + float=float, + id=id, + int=int, + isinstance=isinstance, + list=list, + str=str, + tuple=tuple, + _intstr=int.__repr__, + ): + + if _indent is not None and not isinstance(_indent, str): + _indent = ' ' * _indent + + def _iterencode_list(lst, _current_indent_level): + if not lst: + yield '[]' + return + if markers is not None: + markerid = id(lst) + if markerid in markers: + raise ValueError("Circular reference detected") + markers[markerid] = lst + buf = '[' + if _indent is not None: + _current_indent_level += 1 + newline_indent = '\n' + _indent * _current_indent_level + separator = _item_separator + newline_indent + buf += newline_indent + else: + newline_indent = None + separator = _item_separator + first = True + for value in lst: + if first: + first = False + else: + buf = separator + if isinstance(value, str): + yield buf + _encoder(value) + elif value is None: + yield buf + 'null' + elif value is True: + yield buf + 'true' + elif value is False: + yield buf + 'false' + elif isinstance(value, int): + # Subclasses of int/float may override __repr__, but we still + # want to encode them as integers/floats in JSON. One example + # within the standard library is IntEnum. + yield buf + _intstr(value) + elif isinstance(value, float): + # see comment above for int + yield buf + _floatstr(value) + else: + yield buf + if isinstance(value, (list, tuple)): + chunks = _iterencode_list(value, _current_indent_level) + elif isinstance(value, dict): + chunks = _iterencode_dict(value, _current_indent_level) + else: + chunks = _iterencode(value, _current_indent_level) + yield from chunks + if newline_indent is not None: + _current_indent_level -= 1 + yield '\n' + _indent * _current_indent_level + yield ']' + if markers is not None: + del markers[markerid] + + def _iterencode_dict(dct, _current_indent_level): + if not dct: + yield '{}' + return + if markers is not None: + markerid = id(dct) + if markerid in markers: + raise ValueError("Circular reference detected") + markers[markerid] = dct + yield '{' + if _indent is not None: + _current_indent_level += 1 + newline_indent = '\n' + _indent * _current_indent_level + item_separator = _item_separator + newline_indent + yield newline_indent + else: + newline_indent = None + item_separator = _item_separator + first = True + if _sort_keys: + items = sorted(dct.items()) + else: + items = dct.items() + for key, value in items: + if isinstance(key, str): + pass + # JavaScript is weakly typed for these, so it makes sense to + # also allow them. Many encoders seem to do something like this. + elif isinstance(key, float): + # see comment for int/float in _make_iterencode + key = _floatstr(key) + elif key is True: + key = 'true' + elif key is False: + key = 'false' + elif key is None: + key = 'null' + elif isinstance(key, int): + # see comment for int/float in _make_iterencode + key = _intstr(key) + elif _skipkeys: + continue + else: + raise TypeError(f'keys must be str, int, float, bool or None, ' + f'not {key.__class__.__name__}') + if first: + first = False + else: + yield item_separator + yield _encoder(key) + yield _key_separator + if isinstance(value, str): + yield _encoder(value) + elif value is None: + yield 'null' + elif value is True: + yield 'true' + elif value is False: + yield 'false' + elif isinstance(value, int): + # see comment for int/float in _make_iterencode + yield _intstr(value) + elif isinstance(value, float): + # see comment for int/float in _make_iterencode + yield _floatstr(value) + else: + if isinstance(value, (list, tuple)): + chunks = _iterencode_list(value, _current_indent_level) + elif isinstance(value, dict): + chunks = _iterencode_dict(value, _current_indent_level) + else: + chunks = _iterencode(value, _current_indent_level) + yield from chunks + if newline_indent is not None: + _current_indent_level -= 1 + yield '\n' + _indent * _current_indent_level + yield '}' + if markers is not None: + del markers[markerid] + + def _iterencode(o, _current_indent_level): + if isinstance(o, str): + yield _encoder(o) + elif o is None: + yield 'null' + elif o is True: + yield 'true' + elif o is False: + yield 'false' + elif isinstance(o, int): + # see comment for int/float in _make_iterencode + yield _intstr(o) + elif isinstance(o, float): + # see comment for int/float in _make_iterencode + yield _floatstr(o) + elif isinstance(o, (list, tuple)): + yield from _iterencode_list(o, _current_indent_level) + elif isinstance(o, dict): + yield from _iterencode_dict(o, _current_indent_level) + else: + if markers is not None: + markerid = id(o) + if markerid in markers: + raise ValueError("Circular reference detected") + markers[markerid] = o + o = _default(o) + yield from _iterencode(o, _current_indent_level) + if markers is not None: + del markers[markerid] + return _iterencode diff --git a/shared/package-files/06/06b8b7396bb8964915e9818b68b518b5d03de58f1e84ae4ca1b313843a024edd/utils.py b/shared/package-files/06/06b8b7396bb8964915e9818b68b518b5d03de58f1e84ae4ca1b313843a024edd/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7111d893400f2f2aee77cf51fe2f6ac914ccd58e --- /dev/null +++ b/shared/package-files/06/06b8b7396bb8964915e9818b68b518b5d03de58f1e84ae4ca1b313843a024edd/utils.py @@ -0,0 +1,62 @@ +import operator +from functools import reduce + + +def maybe_view(tensor, size, check_same_size=True): + if check_same_size and tensor.size() == size: + return tensor + return tensor.contiguous().view(size) + + +def maybe_unexpand(tensor, old_size, check_same_size=True): + if check_same_size and tensor.size() == old_size: + return tensor + num_unsqueezed = tensor.dim() - len(old_size) + expanded_dims = [ + dim + for dim, (expanded, original) in enumerate( + zip(tensor.size()[num_unsqueezed:], old_size) + ) + if expanded != original + ] + + for _ in range(num_unsqueezed): + tensor = tensor.sum(0, keepdim=False) + for dim in expanded_dims: + tensor = tensor.sum(dim, keepdim=True) + return tensor + + +# Check whether the op enable broadcasting, and whether it is supported by ONNX. +# If dims1 and dims2 are different, then broadcast is True. +# We always assume the combination of dims1 and dims2 is broadcastable. +# The following types of broadcasting are supported in ONNX: +# 1) Only one element in dims2, such as dims2 = [1, 1] +# 2) dims2 is suffix of dims1, such as dims1 = [2, 3, 4], and dims2 = [3, 4] +# Details can be found here: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Gemm +def check_onnx_broadcast(dims1, dims2): + broadcast = False + supported = True + len1 = len(dims1) + len2 = len(dims2) + numel1 = reduce(operator.mul, dims1) + numel2 = reduce(operator.mul, dims2) + if len1 < len2: + broadcast = True + if numel2 != 1: + supported = False + elif len1 > len2: + broadcast = True + if numel2 != 1 and dims1[len1 - len2 :] != dims2: + supported = False + else: + if dims1 != dims2: + broadcast = True + if numel2 != 1: + supported = False + + if not supported: + raise ValueError( + f"Numpy style broadcasting is not supported in ONNX. Input dims are: {dims1}, {dims2}" + ) + return broadcast diff --git a/shared/package-files/06/06bcfff317bfc97d78441e81f29564e8169c33a1e2cea914088439bdcf54fbf2/parser.pyi b/shared/package-files/06/06bcfff317bfc97d78441e81f29564e8169c33a1e2cea914088439bdcf54fbf2/parser.pyi new file mode 100644 index 0000000000000000000000000000000000000000..78c6965afde020458ffd198c9497f518611d4eb6 --- /dev/null +++ b/shared/package-files/06/06bcfff317bfc97d78441e81f29564e8169c33a1e2cea914088439bdcf54fbf2/parser.pyi @@ -0,0 +1,51 @@ +from datetime import datetime, tzinfo +from typing import IO, Any, Dict, List, Mapping, Optional, Text, Tuple, Union + +_FileOrStr = Union[bytes, Text, IO[str], IO[Any]] + +class parserinfo(object): + JUMP: List[str] + WEEKDAYS: List[Tuple[str, str]] + MONTHS: List[Tuple[str, str]] + HMS: List[Tuple[str, str, str]] + AMPM: List[Tuple[str, str]] + UTCZONE: List[str] + PERTAIN: List[str] + TZOFFSET: Dict[str, int] + def __init__(self, dayfirst: bool = ..., yearfirst: bool = ...) -> None: ... + def jump(self, name: Text) -> bool: ... + def weekday(self, name: Text) -> Optional[int]: ... + def month(self, name: Text) -> Optional[int]: ... + def hms(self, name: Text) -> Optional[int]: ... + def ampm(self, name: Text) -> Optional[int]: ... + def pertain(self, name: Text) -> bool: ... + def utczone(self, name: Text) -> bool: ... + def tzoffset(self, name: Text) -> Optional[int]: ... + def convertyear(self, year: int) -> int: ... + def validate(self, res: datetime) -> bool: ... + +class parser(object): + def __init__(self, info: Optional[parserinfo] = ...) -> None: ... + def parse( + self, + timestr: _FileOrStr, + default: Optional[datetime] = ..., + ignoretz: bool = ..., + tzinfos: Optional[Mapping[Text, tzinfo]] = ..., + **kwargs: Any, + ) -> datetime: ... + +def isoparse(dt_str: Union[str, bytes, IO[str], IO[bytes]]) -> datetime: ... + +DEFAULTPARSER: parser + +def parse(timestr: _FileOrStr, parserinfo: Optional[parserinfo] = ..., **kwargs: Any) -> datetime: ... + +class _tzparser: ... + +DEFAULTTZPARSER: _tzparser + +class InvalidDatetimeError(ValueError): ... +class InvalidDateError(InvalidDatetimeError): ... +class InvalidTimeError(InvalidDatetimeError): ... +class ParserError(ValueError): ... diff --git a/shared/package-files/06/06befcb259155c51e608af2dade2b9489b0fa76c41343c193b5e073f142b203e/reproc-config.cmake b/shared/package-files/06/06befcb259155c51e608af2dade2b9489b0fa76c41343c193b5e073f142b203e/reproc-config.cmake new file mode 100644 index 0000000000000000000000000000000000000000..05d4638f258aec916975777fabc5ada29a56caca --- /dev/null +++ b/shared/package-files/06/06befcb259155c51e608af2dade2b9489b0fa76c41343c193b5e073f142b203e/reproc-config.cmake @@ -0,0 +1,36 @@ + +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was reproc-config.cmake.in ######## + +get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE) + +macro(set_and_check _var _file) + set(${_var} "${_file}") + if(NOT EXISTS "${_file}") + message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !") + endif() +endmacro() + +macro(check_required_components _NAME) + foreach(comp ${${_NAME}_FIND_COMPONENTS}) + if(NOT ${_NAME}_${comp}_FOUND) + if(${_NAME}_FIND_REQUIRED_${comp}) + set(${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() + +#################################################################################### + +set(REPROC_MULTITHREADED ON) + +include(CMakeFindDependencyMacro) + +if(REPROC_MULTITHREADED) + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_dependency(Threads) +endif() + +include(${CMAKE_CURRENT_LIST_DIR}/reproc-targets.cmake) diff --git a/shared/package-files/06/06bf5768b6f7ada260d4f4009d5e66799ddfb647e56d702c17a66d0cd7ce88cb/arctanh_ops.h b/shared/package-files/06/06bf5768b6f7ada260d4f4009d5e66799ddfb647e56d702c17a66d0cd7ce88cb/arctanh_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cc74d29b879eb8376c06995774289e328f98f5f5 --- /dev/null +++ b/shared/package-files/06/06bf5768b6f7ada260d4f4009d5e66799ddfb647e56d702c17a66d0cd7ce88cb/arctanh_ops.h @@ -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 arctanh { + 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::arctanh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arctanh(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 arctanh_ { + 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::arctanh_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arctanh_(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 arctanh_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::arctanh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arctanh.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/06/06c51c6abfc2d276733c657669c92b27d0a9554f3fd16fe91d82b0a5d9d675d3/top_level.txt b/shared/package-files/06/06c51c6abfc2d276733c657669c92b27d0a9554f3fd16fe91d82b0a5d9d675d3/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d4375536666f86a4a1cbd7467fff002705c7d36 --- /dev/null +++ b/shared/package-files/06/06c51c6abfc2d276733c657669c92b27d0a9554f3fd16fe91d82b0a5d9d675d3/top_level.txt @@ -0,0 +1 @@ +jsonpointer diff --git a/shared/package-files/06/06c640bb2cf3469d4affb4fc801035db3b053729306a5faa542e9a35104932ed/_native_multi_head_attention_native.h b/shared/package-files/06/06c640bb2cf3469d4affb4fc801035db3b053729306a5faa542e9a35104932ed/_native_multi_head_attention_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b9a19951274dc858e3062b0da5e8fdf975d4b71e --- /dev/null +++ b/shared/package-files/06/06c640bb2cf3469d4affb4fc801035db3b053729306a5faa542e9a35104932ed/_native_multi_head_attention_native.h @@ -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 ::std::tuple _native_multi_head_attention_out(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional & mask, bool need_weights, bool average_attn_weights, c10::optional mask_type, at::Tensor & out0, at::Tensor & out1); +TORCH_API ::std::tuple native_multi_head_attention_cpu(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional & mask={}, bool need_weights=true, bool average_attn_weights=true, c10::optional mask_type=c10::nullopt); +TORCH_API ::std::tuple native_multi_head_attention_cuda(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional & mask={}, bool need_weights=true, bool average_attn_weights=true, c10::optional mask_type=c10::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06c8ab6557752e63d64f8b41233ea5a193e365c227a10ac819f0bbaefcea989c/tableau-colorblind10.mplstyle b/shared/package-files/06/06c8ab6557752e63d64f8b41233ea5a193e365c227a10ac819f0bbaefcea989c/tableau-colorblind10.mplstyle new file mode 100644 index 0000000000000000000000000000000000000000..2d8cb0208d5a2af8915bc605931931605229e263 --- /dev/null +++ b/shared/package-files/06/06c8ab6557752e63d64f8b41233ea5a193e365c227a10ac819f0bbaefcea989c/tableau-colorblind10.mplstyle @@ -0,0 +1,3 @@ +# Tableau colorblind 10 palette +axes.prop_cycle: cycler('color', ['006BA4', 'FF800E', 'ABABAB', '595959', '5F9ED1', 'C85200', '898989', 'A2C8EC', 'FFBC79', 'CFCFCF']) +patch.facecolor: 006BA4 \ No newline at end of file diff --git a/shared/package-files/06/06cbdf88bccd27374d0fe0b31052b363769d1faaa425d3910e6ec2d9968b9433/eye_ops.h b/shared/package-files/06/06cbdf88bccd27374d0fe0b31052b363769d1faaa425d3910e6ec2d9968b9433/eye_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..8a00dc9e7a1c23222702720b7ba9241396b2cd9b --- /dev/null +++ b/shared/package-files/06/06cbdf88bccd27374d0fe0b31052b363769d1faaa425d3910e6ec2d9968b9433/eye_ops.h @@ -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 eye { + using schema = at::Tensor (c10::SymInt, c10::optional, c10::optional, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye(SymInt n, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor") + static at::Tensor call(c10::SymInt n, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +}; + +struct TORCH_API eye_m { + using schema = at::Tensor (c10::SymInt, c10::SymInt, c10::optional, c10::optional, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "m") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye.m(SymInt n, SymInt m, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor") + static at::Tensor call(c10::SymInt n, c10::SymInt m, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, c10::SymInt m, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +}; + +struct TORCH_API eye_out { + using schema = at::Tensor & (c10::SymInt, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(c10::SymInt n, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, at::Tensor & out); +}; + +struct TORCH_API eye_m_out { + using schema = at::Tensor & (c10::SymInt, c10::SymInt, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "m_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye.m_out(SymInt n, SymInt m, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(c10::SymInt n, c10::SymInt m, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, c10::SymInt m, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so b/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so new file mode 100644 index 0000000000000000000000000000000000000000..22fb691366fe276d87f1aa5e29191f17254f1f74 Binary files /dev/null and b/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so differ diff --git a/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so.0 b/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so.0 new file mode 100644 index 0000000000000000000000000000000000000000..22fb691366fe276d87f1aa5e29191f17254f1f74 Binary files /dev/null and b/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so.0 differ diff --git a/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so.0.0 b/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..22fb691366fe276d87f1aa5e29191f17254f1f74 Binary files /dev/null and b/shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/libkrad.so.0.0 differ diff --git a/shared/package-files/06/06cdac7a4743272c3fc2b5291bbbd94061f4cb44b80b801bc464a9794ffc0b6b/test_functions.py b/shared/package-files/06/06cdac7a4743272c3fc2b5291bbbd94061f4cb44b80b801bc464a9794ffc0b6b/test_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdf9821b6c853755ce12d0cbdfa599bd4f312e4 --- /dev/null +++ b/shared/package-files/06/06cdac7a4743272c3fc2b5291bbbd94061f4cb44b80b801bc464a9794ffc0b6b/test_functions.py @@ -0,0 +1,184 @@ +from sympy.vector.vector import Vector +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.functions import express, matrix_to_vector, orthogonalize +from sympy.core.numbers import Rational +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.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.testing.pytest import raises + +N = CoordSys3D('N') +q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5') +A = N.orient_new_axis('A', q1, N.k) # type: ignore +B = A.orient_new_axis('B', q2, A.i) +C = B.orient_new_axis('C', q3, B.j) + + +def test_express(): + assert express(Vector.zero, N) == Vector.zero + assert express(S.Zero, N) is S.Zero + assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k + assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \ + sin(q2)*cos(q3)*C.k + assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \ + cos(q2)*cos(q3)*C.k + assert express(A.i, N) == cos(q1)*N.i + sin(q1)*N.j + assert express(A.j, N) == -sin(q1)*N.i + cos(q1)*N.j + assert express(A.k, N) == N.k + assert express(A.i, A) == A.i + assert express(A.j, A) == A.j + assert express(A.k, A) == A.k + assert express(A.i, B) == B.i + assert express(A.j, B) == cos(q2)*B.j - sin(q2)*B.k + assert express(A.k, B) == sin(q2)*B.j + cos(q2)*B.k + assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k + assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \ + sin(q2)*cos(q3)*C.k + assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \ + cos(q2)*cos(q3)*C.k + # Check to make sure UnitVectors get converted properly + assert express(N.i, N) == N.i + assert express(N.j, N) == N.j + assert express(N.k, N) == N.k + assert express(N.i, A) == (cos(q1)*A.i - sin(q1)*A.j) + assert express(N.j, A) == (sin(q1)*A.i + cos(q1)*A.j) + assert express(N.k, A) == A.k + assert express(N.i, B) == (cos(q1)*B.i - sin(q1)*cos(q2)*B.j + + sin(q1)*sin(q2)*B.k) + assert express(N.j, B) == (sin(q1)*B.i + cos(q1)*cos(q2)*B.j - + sin(q2)*cos(q1)*B.k) + assert express(N.k, B) == (sin(q2)*B.j + cos(q2)*B.k) + assert express(N.i, C) == ( + (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*C.i - + sin(q1)*cos(q2)*C.j + + (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*C.k) + assert express(N.j, C) == ( + (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.i + + cos(q1)*cos(q2)*C.j + + (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.k) + assert express(N.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + + cos(q2)*cos(q3)*C.k) + + assert express(A.i, N) == (cos(q1)*N.i + sin(q1)*N.j) + assert express(A.j, N) == (-sin(q1)*N.i + cos(q1)*N.j) + assert express(A.k, N) == N.k + assert express(A.i, A) == A.i + assert express(A.j, A) == A.j + assert express(A.k, A) == A.k + assert express(A.i, B) == B.i + assert express(A.j, B) == (cos(q2)*B.j - sin(q2)*B.k) + assert express(A.k, B) == (sin(q2)*B.j + cos(q2)*B.k) + assert express(A.i, C) == (cos(q3)*C.i + sin(q3)*C.k) + assert express(A.j, C) == (sin(q2)*sin(q3)*C.i + cos(q2)*C.j - + sin(q2)*cos(q3)*C.k) + assert express(A.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + + cos(q2)*cos(q3)*C.k) + + assert express(B.i, N) == (cos(q1)*N.i + sin(q1)*N.j) + assert express(B.j, N) == (-sin(q1)*cos(q2)*N.i + + cos(q1)*cos(q2)*N.j + sin(q2)*N.k) + assert express(B.k, N) == (sin(q1)*sin(q2)*N.i - + sin(q2)*cos(q1)*N.j + cos(q2)*N.k) + assert express(B.i, A) == A.i + assert express(B.j, A) == (cos(q2)*A.j + sin(q2)*A.k) + assert express(B.k, A) == (-sin(q2)*A.j + cos(q2)*A.k) + assert express(B.i, B) == B.i + assert express(B.j, B) == B.j + assert express(B.k, B) == B.k + assert express(B.i, C) == (cos(q3)*C.i + sin(q3)*C.k) + assert express(B.j, C) == C.j + assert express(B.k, C) == (-sin(q3)*C.i + cos(q3)*C.k) + + assert express(C.i, N) == ( + (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*N.i + + (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*N.j - + sin(q3)*cos(q2)*N.k) + assert express(C.j, N) == ( + -sin(q1)*cos(q2)*N.i + cos(q1)*cos(q2)*N.j + sin(q2)*N.k) + assert express(C.k, N) == ( + (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*N.i + + (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*N.j + + cos(q2)*cos(q3)*N.k) + assert express(C.i, A) == (cos(q3)*A.i + sin(q2)*sin(q3)*A.j - + sin(q3)*cos(q2)*A.k) + assert express(C.j, A) == (cos(q2)*A.j + sin(q2)*A.k) + assert express(C.k, A) == (sin(q3)*A.i - sin(q2)*cos(q3)*A.j + + cos(q2)*cos(q3)*A.k) + assert express(C.i, B) == (cos(q3)*B.i - sin(q3)*B.k) + assert express(C.j, B) == B.j + assert express(C.k, B) == (sin(q3)*B.i + cos(q3)*B.k) + assert express(C.i, C) == C.i + assert express(C.j, C) == C.j + assert express(C.k, C) == C.k == (C.k) + + # Check to make sure Vectors get converted back to UnitVectors + assert N.i == express((cos(q1)*A.i - sin(q1)*A.j), N).simplify() + assert N.j == express((sin(q1)*A.i + cos(q1)*A.j), N).simplify() + assert N.i == express((cos(q1)*B.i - sin(q1)*cos(q2)*B.j + + sin(q1)*sin(q2)*B.k), N).simplify() + assert N.j == express((sin(q1)*B.i + cos(q1)*cos(q2)*B.j - + sin(q2)*cos(q1)*B.k), N).simplify() + assert N.k == express((sin(q2)*B.j + cos(q2)*B.k), N).simplify() + + + assert A.i == express((cos(q1)*N.i + sin(q1)*N.j), A).simplify() + assert A.j == express((-sin(q1)*N.i + cos(q1)*N.j), A).simplify() + + assert A.j == express((cos(q2)*B.j - sin(q2)*B.k), A).simplify() + assert A.k == express((sin(q2)*B.j + cos(q2)*B.k), A).simplify() + + assert A.i == express((cos(q3)*C.i + sin(q3)*C.k), A).simplify() + assert A.j == express((sin(q2)*sin(q3)*C.i + cos(q2)*C.j - + sin(q2)*cos(q3)*C.k), A).simplify() + + assert A.k == express((-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + + cos(q2)*cos(q3)*C.k), A).simplify() + assert B.i == express((cos(q1)*N.i + sin(q1)*N.j), B).simplify() + assert B.j == express((-sin(q1)*cos(q2)*N.i + + cos(q1)*cos(q2)*N.j + sin(q2)*N.k), B).simplify() + + assert B.k == express((sin(q1)*sin(q2)*N.i - + sin(q2)*cos(q1)*N.j + cos(q2)*N.k), B).simplify() + + assert B.j == express((cos(q2)*A.j + sin(q2)*A.k), B).simplify() + assert B.k == express((-sin(q2)*A.j + cos(q2)*A.k), B).simplify() + assert B.i == express((cos(q3)*C.i + sin(q3)*C.k), B).simplify() + assert B.k == express((-sin(q3)*C.i + cos(q3)*C.k), B).simplify() + assert C.i == express((cos(q3)*A.i + sin(q2)*sin(q3)*A.j - + sin(q3)*cos(q2)*A.k), C).simplify() + assert C.j == express((cos(q2)*A.j + sin(q2)*A.k), C).simplify() + assert C.k == express((sin(q3)*A.i - sin(q2)*cos(q3)*A.j + + cos(q2)*cos(q3)*A.k), C).simplify() + assert C.i == express((cos(q3)*B.i - sin(q3)*B.k), C).simplify() + assert C.k == express((sin(q3)*B.i + cos(q3)*B.k), C).simplify() + + +def test_matrix_to_vector(): + m = Matrix([[1], [2], [3]]) + assert matrix_to_vector(m, C) == C.i + 2*C.j + 3*C.k + m = Matrix([[0], [0], [0]]) + assert matrix_to_vector(m, N) == matrix_to_vector(m, C) == \ + Vector.zero + m = Matrix([[q1], [q2], [q3]]) + assert matrix_to_vector(m, N) == q1*N.i + q2*N.j + q3*N.k + + +def test_orthogonalize(): + C = CoordSys3D('C') + a, b = symbols('a b', integer=True) + i, j, k = C.base_vectors() + v1 = i + 2*j + v2 = 2*i + 3*j + v3 = 3*i + 5*j + v4 = 3*i + j + v5 = 2*i + 2*j + v6 = a*i + b*j + v7 = 4*a*i + 4*b*j + assert orthogonalize(v1, v2) == [C.i + 2*C.j, C.i*Rational(2, 5) + -C.j/5] + # from wikipedia + assert orthogonalize(v4, v5, orthonormal=True) == \ + [(3*sqrt(10))*C.i/10 + (sqrt(10))*C.j/10, (-sqrt(10))*C.i/10 + (3*sqrt(10))*C.j/10] + raises(ValueError, lambda: orthogonalize(v1, v2, v3)) + raises(ValueError, lambda: orthogonalize(v6, v7)) diff --git a/shared/package-files/06/06ce13e038f1e1764e6ddd251af78123ab55b15bcf19ebf9476dc6b1a8a8768b/any.h b/shared/package-files/06/06ce13e038f1e1764e6ddd251af78123ab55b15bcf19ebf9476dc6b1a8a8768b/any.h new file mode 100644 index 0000000000000000000000000000000000000000..05983b1ea1064c5b1c025931f5f3e53a8dda7f8e --- /dev/null +++ b/shared/package-files/06/06ce13e038f1e1764e6ddd251af78123ab55b15bcf19ebf9476dc6b1a8a8768b/any.h @@ -0,0 +1,372 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace torch { +namespace nn { + +/// Stores a type erased `Module`. +/// +/// The PyTorch C++ API does not impose an interface on the signature of +/// `forward()` in `Module` subclasses. This gives you complete freedom to +/// design your `forward()` methods to your liking. However, this also means +/// there is no unified base type you could store in order to call `forward()` +/// polymorphically for any module. This is where the `AnyModule` comes in. +/// Instead of inheritance, it relies on type erasure for polymorphism. +/// +/// An `AnyModule` can store any `nn::Module` subclass that provides a +/// `forward()` method. This `forward()` may accept any types and return any +/// type. Once stored in an `AnyModule`, you can invoke the underlying module's +/// `forward()` by calling `AnyModule::forward()` with the arguments you would +/// supply to the stored module (though see one important limitation below). +/// Example: +/// +/// \rst +/// .. code-block:: cpp +/// +/// struct GenericTrainer { +/// torch::nn::AnyModule module; +/// +/// void train(torch::Tensor input) { +/// module.forward(input); +/// } +/// }; +/// +/// GenericTrainer trainer1{torch::nn::Linear(3, 4)}; +/// GenericTrainer trainer2{torch::nn::Conv2d(3, 4, 2)}; +/// \endrst +/// +/// As `AnyModule` erases the static type of the stored module (and its +/// `forward()` method) to achieve polymorphism, type checking of arguments is +/// moved to runtime. That is, passing an argument with an incorrect type to an +/// `AnyModule` will compile, but throw an exception at runtime: +/// +/// \rst +/// .. code-block:: cpp +/// +/// torch::nn::AnyModule module(torch::nn::Linear(3, 4)); +/// // Linear takes a tensor as input, but we are passing an integer. +/// // This will compile, but throw a `torch::Error` exception at runtime. +/// module.forward(123); +/// \endrst +/// +/// \rst +/// .. attention:: +/// One noteworthy limitation of `AnyModule` is that its `forward()` method +/// does not support implicit conversion of argument types. For example, if +/// the stored module's `forward()` method accepts a `float` and you call +/// `any_module.forward(3.4)` (where `3.4` is a `double`), this will throw +/// an exception. +/// \endrst +/// +/// The return type of the `AnyModule`'s `forward()` method is controlled via +/// the first template argument to `AnyModule::forward()`. It defaults to +/// `torch::Tensor`. To change it, you can write `any_module.forward()`, +/// for example. +/// +/// \rst +/// .. code-block:: cpp +/// +/// torch::nn::AnyModule module(torch::nn::Linear(3, 4)); +/// auto output = module.forward(torch::ones({2, 3})); +/// +/// struct IntModule { +/// int forward(int x) { return x; } +/// }; +/// torch::nn::AnyModule module(IntModule{}); +/// int output = module.forward(5); +/// \endrst +/// +/// The only other method an `AnyModule` provides access to on the stored +/// module is `clone()`. However, you may acquire a handle on the module via +/// `.ptr()`, which returns a `shared_ptr`. Further, if you know +/// the concrete type of the stored module, you can get a concrete handle to it +/// using `.get()` where `T` is the concrete module type. +/// +/// \rst +/// .. code-block:: cpp +/// +/// torch::nn::AnyModule module(torch::nn::Linear(3, 4)); +/// std::shared_ptr ptr = module.ptr(); +/// torch::nn::Linear linear(module.get()); +/// \endrst +class AnyModule { + public: + /// A default-constructed `AnyModule` is in an empty state. + AnyModule() = default; + + /// Constructs an `AnyModule` from a `shared_ptr` to concrete module object. + template + explicit AnyModule(std::shared_ptr module); + + /// Constructs an `AnyModule` from a concrete module object. + template < + typename ModuleType, + typename = torch::detail::enable_if_module_t> + explicit AnyModule(ModuleType&& module); + + /// Constructs an `AnyModule` from a module holder. + template + explicit AnyModule(const ModuleHolder& module_holder); + + /// Move construction and assignment is allowed, and follows the default + /// behavior of move for `std::unique_ptr`. + AnyModule(AnyModule&&) = default; + AnyModule& operator=(AnyModule&&) = default; + + /// Creates a shallow copy of an `AnyModule`. + AnyModule(const AnyModule& other); + AnyModule& operator=(const AnyModule& other); + + /// Creates a deep copy of an `AnyModule` if it contains a module, else an + /// empty `AnyModule` if it is empty. + AnyModule clone(optional device = nullopt) const; + + /// Assigns a module to the `AnyModule` (to circumvent the explicit + /// constructor). + template + AnyModule& operator=(std::shared_ptr module); + + /// Invokes `forward()` on the contained module with the given arguments, and + /// returns the return value as an `AnyValue`. Use this method when chaining + /// `AnyModule`s in a loop. + template + AnyValue any_forward(ArgumentTypes&&... arguments); + + /// Invokes `forward()` on the contained module with the given arguments, and + /// casts the returned `AnyValue` to the supplied `ReturnType` (which defaults + /// to `torch::Tensor`). + template + ReturnType forward(ArgumentTypes&&... arguments); + + /// Attempts to cast the underlying module to the given module type. Throws an + /// exception if the types do not match. + template > + T& get(); + + /// Attempts to cast the underlying module to the given module type. Throws an + /// exception if the types do not match. + template > + const T& get() const; + + /// Returns the contained module in a `nn::ModuleHolder` subclass if possible + /// (i.e. if `T` has a constructor for the underlying module type). + template + T get() const; + + /// Returns a `std::shared_ptr` whose dynamic type is that of the underlying + /// module. + std::shared_ptr ptr() const; + + /// Like `ptr()`, but casts the pointer to the given type. + template > + std::shared_ptr ptr() const; + + /// Returns the `type_info` object of the contained value. + const std::type_info& type_info() const; + + /// Returns true if the `AnyModule` does not contain a module. + bool is_empty() const noexcept; + + private: + /// Creates a `unique_ptr` pointing to a + /// `AnyModuleHolder` of the correct type. This method is used to deduce the + /// arguments of the module's `forward()` method. + template < + typename ModuleType, + typename Class, + typename ReturnType, + typename... ArgumentTypes> + std::unique_ptr make_holder( + std::shared_ptr&& module, + ReturnType (Class::*)(ArgumentTypes...)); + + /// Helper method invoked by const and non-const `get()`. + template + ModuleType& get_(ReturnType (ModuleType::*)(ArgumentTypes...)) const; + + /// Helper method invoked by const and non-const `get()`. + template + ModuleType& get_() const; + + /// The type erased module. + std::unique_ptr content_; +}; + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AnyModule ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template +AnyModule::AnyModule(std::shared_ptr module) + : content_(make_holder( + std::move(module), + &std::remove_reference::type::forward)) { + // `AnyModule` can only store an `nn::Module` subclass object that provides + // a `forward()` method that has a non-templatized return type. + // (e.g. `AnyModule` cannot store `nn::Sequential`, because `nn::Sequential`'s + // `forward()` method has a templatized return type.) + static_assert( + torch::detail::is_module::value, + "Can only store object derived from nn::Module into AnyModule"); + static_assert( + torch::detail::has_forward::value, + "Can only store module with a forward() method that has a non-templatized" + " argument type and return type into AnyModule (e.g. we cannot store nn::Sequential" + "into AnyModule, because its forward() method's argument type and return type are templatized." + " If you need to use nn::Sequentials inside each other you can subclass " + "nn::Sequential and write a non-templatized forward function for it. You can checkout " + "https://github.com/pytorch/vision/blob/2f46070f3cb1ea894d82578f3dc5677f82f34958/torchvision/csrc/models/mnasnet.cpp#L59 " + "for an example on how to do this.)."); +} + +template +AnyModule::AnyModule(ModuleType&& module) + : AnyModule( + std::make_shared(std::forward(module))) {} + +template +AnyModule::AnyModule(const ModuleHolder& module_holder) + : AnyModule(module_holder.ptr()) {} + +inline AnyModule::AnyModule(const AnyModule& other) + : content_(other.content_ ? other.content_->copy() : nullptr) {} + +inline AnyModule& AnyModule::operator=(const AnyModule& other) { + if (this != &other) { + content_ = other.content_ ? other.content_->copy() : nullptr; + } + return *this; +} + +inline AnyModule AnyModule::clone(optional device) const { + AnyModule clone; + clone.content_ = content_ ? content_->clone_module(device) : nullptr; + return clone; +} + +template +AnyModule& AnyModule::operator=(std::shared_ptr module) { + // NOLINTNEXTLINE(cppcoreguidelines-c-copy-assignment-signature) + return (*this = AnyModule(std::move(module))); +} + +template +AnyValue AnyModule::any_forward(ArgumentTypes&&... arguments) { + TORCH_CHECK(!is_empty(), "Cannot call forward() on an empty AnyModule"); + std::vector values; + values.reserve(sizeof...(ArgumentTypes)); + torch::apply( + [&values](AnyValue&& value) { values.push_back(std::move(value)); }, + AnyValue(std::forward(arguments))...); + return content_->forward(std::move(values)); +} + +template +ReturnType AnyModule::forward(ArgumentTypes&&... arguments) { + return any_forward(std::forward(arguments)...) + .template get(); +} + +template +T& AnyModule::get() { + TORCH_CHECK(!is_empty(), "Cannot call get() on an empty AnyModule"); + return get_(); +} + +template +const T& AnyModule::get() const { + TORCH_CHECK(!is_empty(), "Cannot call get() on an empty AnyModule"); + return get_(); +} + +template +T AnyModule::get() const { + return T(ptr()); +} + +inline std::shared_ptr AnyModule::ptr() const { + TORCH_CHECK(!is_empty(), "Cannot call ptr() on an empty AnyModule"); + return content_->ptr(); +} + +template +std::shared_ptr AnyModule::ptr() const { + TORCH_CHECK(!is_empty(), "Cannot call ptr() on an empty AnyModule"); + // Call get() but discard the value, just to do the type checking. + get_(); + return std::dynamic_pointer_cast(ptr()); +} + +inline const std::type_info& AnyModule::type_info() const { + TORCH_CHECK(!is_empty(), "Cannot call type_info() on an empty AnyModule"); + return content_->type_info; +} + +inline bool AnyModule::is_empty() const noexcept { + return content_ == nullptr; +} + +// Private Methods + +template < + typename ModuleType, + typename Class, + typename ReturnType, + typename... ArgumentTypes> +std::unique_ptr AnyModule::make_holder( + std::shared_ptr&& module, + ReturnType (Class::*)(ArgumentTypes...)) { + static_assert( + torch::detail::check_not_lvalue_references(), + "Modules stored inside AnyModule must not take references. " + "Use pointers instead."); + static_assert( + !std::is_void::value, + "AnyModule cannot store modules that return void " + "(you can return a dummy value)."); + return std::make_unique< + AnyModuleHolder, ArgumentTypes...>>( + std::move(module)); +} + +template +ModuleType& AnyModule::get_() const { + using M = typename std::remove_reference::type; + static_assert( + torch::detail::has_forward::value, + "Can only call AnyModule::get with a type T that has a forward method"); + return get_(&M::forward); +} + +template +ModuleType& AnyModule::get_( + ReturnType (ModuleType::*)(ArgumentTypes...)) const { + if (typeid(ModuleType).hash_code() == type_info().hash_code()) { + return *static_cast&>( + *content_) + .module; + } + AT_ERROR( + "Attempted to cast module of type ", + c10::demangle(type_info().name()), + " to type ", + c10::demangle(typeid(ModuleType).name())); +} + +} // namespace nn +} // namespace torch diff --git a/shared/package-files/06/06d043d88fb3f0ae88e46420f5080735f8995747a72a2e483128b14fee094525/lowrank_multivariate_normal.py b/shared/package-files/06/06d043d88fb3f0ae88e46420f5080735f8995747a72a2e483128b14fee094525/lowrank_multivariate_normal.py new file mode 100644 index 0000000000000000000000000000000000000000..a3acaa990966eda76387f0fbf92f06c42454b8c9 --- /dev/null +++ b/shared/package-files/06/06d043d88fb3f0ae88e46420f5080735f8995747a72a2e483128b14fee094525/lowrank_multivariate_normal.py @@ -0,0 +1,237 @@ +import math + +import torch +from torch.distributions import constraints +from torch.distributions.distribution import Distribution +from torch.distributions.multivariate_normal import _batch_mahalanobis, _batch_mv +from torch.distributions.utils import _standard_normal, lazy_property + +__all__ = ["LowRankMultivariateNormal"] + + +def _batch_capacitance_tril(W, D): + r""" + Computes Cholesky of :math:`I + W.T @ inv(D) @ W` for a batch of matrices :math:`W` + and a batch of vectors :math:`D`. + """ + m = W.size(-1) + Wt_Dinv = W.mT / D.unsqueeze(-2) + K = torch.matmul(Wt_Dinv, W).contiguous() + K.view(-1, m * m)[:, :: m + 1] += 1 # add identity matrix to K + return torch.linalg.cholesky(K) + + +def _batch_lowrank_logdet(W, D, capacitance_tril): + r""" + Uses "matrix determinant lemma":: + log|W @ W.T + D| = log|C| + log|D|, + where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute + the log determinant. + """ + return 2 * capacitance_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) + D.log().sum( + -1 + ) + + +def _batch_lowrank_mahalanobis(W, D, x, capacitance_tril): + r""" + Uses "Woodbury matrix identity":: + inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D), + where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute the squared + Mahalanobis distance :math:`x.T @ inv(W @ W.T + D) @ x`. + """ + Wt_Dinv = W.mT / D.unsqueeze(-2) + Wt_Dinv_x = _batch_mv(Wt_Dinv, x) + mahalanobis_term1 = (x.pow(2) / D).sum(-1) + mahalanobis_term2 = _batch_mahalanobis(capacitance_tril, Wt_Dinv_x) + return mahalanobis_term1 - mahalanobis_term2 + + +class LowRankMultivariateNormal(Distribution): + r""" + Creates a multivariate normal distribution with covariance matrix having a low-rank form + parameterized by :attr:`cov_factor` and :attr:`cov_diag`:: + + covariance_matrix = cov_factor @ cov_factor.T + cov_diag + + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK) + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = LowRankMultivariateNormal(torch.zeros(2), torch.tensor([[1.], [0.]]), torch.ones(2)) + >>> m.sample() # normally distributed with mean=`[0,0]`, cov_factor=`[[1],[0]]`, cov_diag=`[1,1]` + tensor([-0.2102, -0.5429]) + + Args: + loc (Tensor): mean of the distribution with shape `batch_shape + event_shape` + cov_factor (Tensor): factor part of low-rank form of covariance matrix with shape + `batch_shape + event_shape + (rank,)` + cov_diag (Tensor): diagonal part of low-rank form of covariance matrix with shape + `batch_shape + event_shape` + + Note: + The computation for determinant and inverse of covariance matrix is avoided when + `cov_factor.shape[1] << cov_factor.shape[0]` thanks to `Woodbury matrix identity + `_ and + `matrix determinant lemma `_. + Thanks to these formulas, we just need to compute the determinant and inverse of + the small size "capacitance" matrix:: + + capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor + """ + arg_constraints = { + "loc": constraints.real_vector, + "cov_factor": constraints.independent(constraints.real, 2), + "cov_diag": constraints.independent(constraints.positive, 1), + } + support = constraints.real_vector + has_rsample = True + + def __init__(self, loc, cov_factor, cov_diag, validate_args=None): + if loc.dim() < 1: + raise ValueError("loc must be at least one-dimensional.") + event_shape = loc.shape[-1:] + if cov_factor.dim() < 2: + raise ValueError( + "cov_factor must be at least two-dimensional, " + "with optional leading batch dimensions" + ) + if cov_factor.shape[-2:-1] != event_shape: + raise ValueError( + f"cov_factor must be a batch of matrices with shape {event_shape[0]} x m" + ) + if cov_diag.shape[-1:] != event_shape: + raise ValueError( + f"cov_diag must be a batch of vectors with shape {event_shape}" + ) + + loc_ = loc.unsqueeze(-1) + cov_diag_ = cov_diag.unsqueeze(-1) + try: + loc_, self.cov_factor, cov_diag_ = torch.broadcast_tensors( + loc_, cov_factor, cov_diag_ + ) + except RuntimeError as e: + raise ValueError( + f"Incompatible batch shapes: loc {loc.shape}, cov_factor {cov_factor.shape}, cov_diag {cov_diag.shape}" + ) from e + self.loc = loc_[..., 0] + self.cov_diag = cov_diag_[..., 0] + batch_shape = self.loc.shape[:-1] + + self._unbroadcasted_cov_factor = cov_factor + self._unbroadcasted_cov_diag = cov_diag + self._capacitance_tril = _batch_capacitance_tril(cov_factor, cov_diag) + super().__init__(batch_shape, event_shape, validate_args=validate_args) + + def expand(self, batch_shape, _instance=None): + new = self._get_checked_instance(LowRankMultivariateNormal, _instance) + batch_shape = torch.Size(batch_shape) + loc_shape = batch_shape + self.event_shape + new.loc = self.loc.expand(loc_shape) + new.cov_diag = self.cov_diag.expand(loc_shape) + new.cov_factor = self.cov_factor.expand(loc_shape + self.cov_factor.shape[-1:]) + new._unbroadcasted_cov_factor = self._unbroadcasted_cov_factor + new._unbroadcasted_cov_diag = self._unbroadcasted_cov_diag + new._capacitance_tril = self._capacitance_tril + super(LowRankMultivariateNormal, new).__init__( + batch_shape, self.event_shape, validate_args=False + ) + new._validate_args = self._validate_args + return new + + @property + def mean(self): + return self.loc + + @property + def mode(self): + return self.loc + + @lazy_property + def variance(self): + return ( + self._unbroadcasted_cov_factor.pow(2).sum(-1) + self._unbroadcasted_cov_diag + ).expand(self._batch_shape + self._event_shape) + + @lazy_property + def scale_tril(self): + # The following identity is used to increase the numerically computation stability + # for Cholesky decomposition (see http://www.gaussianprocess.org/gpml/, Section 3.4.3): + # W @ W.T + D = D1/2 @ (I + D-1/2 @ W @ W.T @ D-1/2) @ D1/2 + # The matrix "I + D-1/2 @ W @ W.T @ D-1/2" has eigenvalues bounded from below by 1, + # hence it is well-conditioned and safe to take Cholesky decomposition. + n = self._event_shape[0] + cov_diag_sqrt_unsqueeze = self._unbroadcasted_cov_diag.sqrt().unsqueeze(-1) + Dinvsqrt_W = self._unbroadcasted_cov_factor / cov_diag_sqrt_unsqueeze + K = torch.matmul(Dinvsqrt_W, Dinvsqrt_W.mT).contiguous() + K.view(-1, n * n)[:, :: n + 1] += 1 # add identity matrix to K + scale_tril = cov_diag_sqrt_unsqueeze * torch.linalg.cholesky(K) + return scale_tril.expand( + self._batch_shape + self._event_shape + self._event_shape + ) + + @lazy_property + def covariance_matrix(self): + covariance_matrix = torch.matmul( + self._unbroadcasted_cov_factor, self._unbroadcasted_cov_factor.mT + ) + torch.diag_embed(self._unbroadcasted_cov_diag) + return covariance_matrix.expand( + self._batch_shape + self._event_shape + self._event_shape + ) + + @lazy_property + def precision_matrix(self): + # We use "Woodbury matrix identity" to take advantage of low rank form:: + # inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D) + # where :math:`C` is the capacitance matrix. + Wt_Dinv = ( + self._unbroadcasted_cov_factor.mT + / self._unbroadcasted_cov_diag.unsqueeze(-2) + ) + A = torch.linalg.solve_triangular(self._capacitance_tril, Wt_Dinv, upper=False) + precision_matrix = ( + torch.diag_embed(self._unbroadcasted_cov_diag.reciprocal()) - A.mT @ A + ) + return precision_matrix.expand( + self._batch_shape + self._event_shape + self._event_shape + ) + + def rsample(self, sample_shape=torch.Size()): + shape = self._extended_shape(sample_shape) + W_shape = shape[:-1] + self.cov_factor.shape[-1:] + eps_W = _standard_normal(W_shape, dtype=self.loc.dtype, device=self.loc.device) + eps_D = _standard_normal(shape, dtype=self.loc.dtype, device=self.loc.device) + return ( + self.loc + + _batch_mv(self._unbroadcasted_cov_factor, eps_W) + + self._unbroadcasted_cov_diag.sqrt() * eps_D + ) + + def log_prob(self, value): + if self._validate_args: + self._validate_sample(value) + diff = value - self.loc + M = _batch_lowrank_mahalanobis( + self._unbroadcasted_cov_factor, + self._unbroadcasted_cov_diag, + diff, + self._capacitance_tril, + ) + log_det = _batch_lowrank_logdet( + self._unbroadcasted_cov_factor, + self._unbroadcasted_cov_diag, + self._capacitance_tril, + ) + return -0.5 * (self._event_shape[0] * math.log(2 * math.pi) + log_det + M) + + def entropy(self): + log_det = _batch_lowrank_logdet( + self._unbroadcasted_cov_factor, + self._unbroadcasted_cov_diag, + self._capacitance_tril, + ) + H = 0.5 * (self._event_shape[0] * (1.0 + math.log(2 * math.pi)) + log_det) + if len(self._batch_shape) == 0: + return H + else: + return H.expand(self._batch_shape) diff --git a/shared/package-files/06/06d0d1944c1296f3a1c68d38997407a73cada15f8523f2b9c95b344405fc7812/_nonlin.py b/shared/package-files/06/06d0d1944c1296f3a1c68d38997407a73cada15f8523f2b9c95b344405fc7812/_nonlin.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e07683500bb01c195b1cdfa8a13157353b5370 --- /dev/null +++ b/shared/package-files/06/06d0d1944c1296f3a1c68d38997407a73cada15f8523f2b9c95b344405fc7812/_nonlin.py @@ -0,0 +1,1603 @@ +# Copyright (C) 2009, Pauli Virtanen +# Distributed under the same license as SciPy. + +import inspect +import sys +import warnings + +import numpy as np +from numpy import asarray, dot, vdot + +from scipy.linalg import norm, solve, inv, qr, svd, LinAlgError +import scipy.sparse.linalg +import scipy.sparse +from scipy.linalg import get_blas_funcs +from scipy._lib._util import copy_if_needed +from scipy._lib._util import getfullargspec_no_self as _getfullargspec +from ._linesearch import scalar_search_wolfe1, scalar_search_armijo + + +__all__ = [ + 'broyden1', 'broyden2', 'anderson', 'linearmixing', + 'diagbroyden', 'excitingmixing', 'newton_krylov', + 'BroydenFirst', 'KrylovJacobian', 'InverseJacobian', 'NoConvergence'] + +#------------------------------------------------------------------------------ +# Utility functions +#------------------------------------------------------------------------------ + + +class NoConvergence(Exception): + """Exception raised when nonlinear solver fails to converge within the specified + `maxiter`.""" + pass + + +def maxnorm(x): + return np.absolute(x).max() + + +def _as_inexact(x): + """Return `x` as an array, of either floats or complex floats""" + x = asarray(x) + if not np.issubdtype(x.dtype, np.inexact): + return asarray(x, dtype=np.float64) + return x + + +def _array_like(x, x0): + """Return ndarray `x` as same array subclass and shape as `x0`""" + x = np.reshape(x, np.shape(x0)) + wrap = getattr(x0, '__array_wrap__', x.__array_wrap__) + return wrap(x) + + +def _safe_norm(v): + if not np.isfinite(v).all(): + return np.array(np.inf) + return norm(v) + +#------------------------------------------------------------------------------ +# Generic nonlinear solver machinery +#------------------------------------------------------------------------------ + + +_doc_parts = dict( + params_basic=""" + F : function(x) -> f + Function whose root to find; should take and return an array-like + object. + xin : array_like + Initial guess for the solution + """.strip(), + params_extra=""" + iter : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + verbose : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. If more are needed to + meet convergence, `NoConvergence` is raised. + f_tol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + f_rtol : float, optional + Relative tolerance for the residual. If omitted, not used. + x_tol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + x_rtol : float, optional + Relative minimum step size. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in the + direction given by the Jacobian approximation. Defaults to 'armijo'. + callback : function, optional + Optional callback function. It is called on every iteration as + ``callback(x, f)`` where `x` is the current solution and `f` + the corresponding residual. + + Returns + ------- + sol : ndarray + An array (of similar array type as `x0`) containing the final solution. + + Raises + ------ + NoConvergence + When a solution was not found. + + """.strip() +) + + +def _set_doc(obj): + if obj.__doc__: + obj.__doc__ = obj.__doc__ % _doc_parts + + +def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False, + maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + tol_norm=None, line_search='armijo', callback=None, + full_output=False, raise_exception=True): + """ + Find a root of a function, in a way suitable for large-scale problems. + + Parameters + ---------- + %(params_basic)s + jacobian : Jacobian + A Jacobian approximation: `Jacobian` object or something that + `asjacobian` can transform to one. Alternatively, a string specifying + which of the builtin Jacobian approximations to use: + + krylov, broyden1, broyden2, anderson + diagbroyden, linearmixing, excitingmixing + + %(params_extra)s + full_output : bool + If true, returns a dictionary `info` containing convergence + information. + raise_exception : bool + If True, a `NoConvergence` exception is raise if no solution is found. + + See Also + -------- + asjacobian, Jacobian + + Notes + ----- + This algorithm implements the inexact Newton method, with + backtracking or full line searches. Several Jacobian + approximations are available, including Krylov and Quasi-Newton + methods. + + References + ---------- + .. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear + Equations\". Society for Industrial and Applied Mathematics. (1995) + https://archive.siam.org/books/kelley/fr16/ + + """ + # Can't use default parameters because it's being explicitly passed as None + # from the calling function, so we need to set it here. + tol_norm = maxnorm if tol_norm is None else tol_norm + condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol, + x_tol=x_tol, x_rtol=x_rtol, + iter=iter, norm=tol_norm) + + x0 = _as_inexact(x0) + def func(z): + return _as_inexact(F(_array_like(z, x0))).flatten() + x = x0.flatten() + + dx = np.full_like(x, np.inf) + Fx = func(x) + Fx_norm = norm(Fx) + + jacobian = asjacobian(jacobian) + jacobian.setup(x.copy(), Fx, func) + + if maxiter is None: + if iter is not None: + maxiter = iter + 1 + else: + maxiter = 100*(x.size+1) + + if line_search is True: + line_search = 'armijo' + elif line_search is False: + line_search = None + + if line_search not in (None, 'armijo', 'wolfe'): + raise ValueError("Invalid line search") + + # Solver tolerance selection + gamma = 0.9 + eta_max = 0.9999 + eta_treshold = 0.1 + eta = 1e-3 + + for n in range(maxiter): + status = condition.check(Fx, x, dx) + if status: + break + + # The tolerance, as computed for scipy.sparse.linalg.* routines + tol = min(eta, eta*Fx_norm) + dx = -jacobian.solve(Fx, tol=tol) + + if norm(dx) == 0: + raise ValueError("Jacobian inversion yielded zero vector. " + "This indicates a bug in the Jacobian " + "approximation.") + + # Line search, or Newton step + if line_search: + s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx, + line_search) + else: + s = 1.0 + x = x + dx + Fx = func(x) + Fx_norm_new = norm(Fx) + + jacobian.update(x.copy(), Fx) + + if callback: + callback(x, Fx) + + # Adjust forcing parameters for inexact methods + eta_A = gamma * Fx_norm_new**2 / Fx_norm**2 + if gamma * eta**2 < eta_treshold: + eta = min(eta_max, eta_A) + else: + eta = min(eta_max, max(eta_A, gamma*eta**2)) + + Fx_norm = Fx_norm_new + + # Print status + if verbose: + sys.stdout.write("%d: |F(x)| = %g; step %g\n" % ( + n, tol_norm(Fx), s)) + sys.stdout.flush() + else: + if raise_exception: + raise NoConvergence(_array_like(x, x0)) + else: + status = 2 + + if full_output: + info = {'nit': condition.iteration, + 'fun': Fx, + 'status': status, + 'success': status == 1, + 'message': {1: 'A solution was found at the specified ' + 'tolerance.', + 2: 'The maximum number of iterations allowed ' + 'has been reached.' + }[status] + } + return _array_like(x, x0), info + else: + return _array_like(x, x0) + + +_set_doc(nonlin_solve) + + +def _nonlin_line_search(func, x, Fx, dx, search_type='armijo', rdiff=1e-8, + smin=1e-2): + tmp_s = [0] + tmp_Fx = [Fx] + tmp_phi = [norm(Fx)**2] + s_norm = norm(x) / norm(dx) + + def phi(s, store=True): + if s == tmp_s[0]: + return tmp_phi[0] + xt = x + s*dx + v = func(xt) + p = _safe_norm(v)**2 + if store: + tmp_s[0] = s + tmp_phi[0] = p + tmp_Fx[0] = v + return p + + def derphi(s): + ds = (abs(s) + s_norm + 1) * rdiff + return (phi(s+ds, store=False) - phi(s)) / ds + + if search_type == 'wolfe': + s, phi1, phi0 = scalar_search_wolfe1(phi, derphi, tmp_phi[0], + xtol=1e-2, amin=smin) + elif search_type == 'armijo': + s, phi1 = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0], + amin=smin) + + if s is None: + # XXX: No suitable step length found. Take the full Newton step, + # and hope for the best. + s = 1.0 + + x = x + s*dx + if s == tmp_s[0]: + Fx = tmp_Fx[0] + else: + Fx = func(x) + Fx_norm = norm(Fx) + + return s, x, Fx, Fx_norm + + +class TerminationCondition: + """ + Termination condition for an iteration. It is terminated if + + - |F| < f_rtol*|F_0|, AND + - |F| < f_tol + + AND + + - |dx| < x_rtol*|x|, AND + - |dx| < x_tol + + """ + def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + iter=None, norm=maxnorm): + + if f_tol is None: + f_tol = np.finfo(np.float64).eps ** (1./3) + if f_rtol is None: + f_rtol = np.inf + if x_tol is None: + x_tol = np.inf + if x_rtol is None: + x_rtol = np.inf + + self.x_tol = x_tol + self.x_rtol = x_rtol + self.f_tol = f_tol + self.f_rtol = f_rtol + + self.norm = norm + + self.iter = iter + + self.f0_norm = None + self.iteration = 0 + + def check(self, f, x, dx): + self.iteration += 1 + f_norm = self.norm(f) + x_norm = self.norm(x) + dx_norm = self.norm(dx) + + if self.f0_norm is None: + self.f0_norm = f_norm + + if f_norm == 0: + return 1 + + if self.iter is not None: + # backwards compatibility with SciPy 0.6.0 + return 2 * (self.iteration > self.iter) + + # NB: condition must succeed for rtol=inf even if norm == 0 + return int((f_norm <= self.f_tol + and f_norm/self.f_rtol <= self.f0_norm) + and (dx_norm <= self.x_tol + and dx_norm/self.x_rtol <= x_norm)) + + +#------------------------------------------------------------------------------ +# Generic Jacobian approximation +#------------------------------------------------------------------------------ + +class Jacobian: + """ + Common interface for Jacobians or Jacobian approximations. + + The optional methods come useful when implementing trust region + etc., algorithms that often require evaluating transposes of the + Jacobian. + + Methods + ------- + solve + Returns J^-1 * v + update + Updates Jacobian to point `x` (where the function has residual `Fx`) + + matvec : optional + Returns J * v + rmatvec : optional + Returns A^H * v + rsolve : optional + Returns A^-H * v + matmat : optional + Returns A * V, where V is a dense matrix with dimensions (N,K). + todense : optional + Form the dense Jacobian matrix. Necessary for dense trust region + algorithms, and useful for testing. + + Attributes + ---------- + shape + Matrix dimensions (M, N) + dtype + Data type of the matrix. + func : callable, optional + Function the Jacobian corresponds to + + """ + + def __init__(self, **kw): + names = ["solve", "update", "matvec", "rmatvec", "rsolve", + "matmat", "todense", "shape", "dtype"] + for name, value in kw.items(): + if name not in names: + raise ValueError(f"Unknown keyword argument {name}") + if value is not None: + setattr(self, name, kw[name]) + + + if hasattr(self, "todense"): + def __array__(self, dtype=None, copy=None): + if dtype is not None: + raise ValueError(f"`dtype` must be None, was {dtype}") + return self.todense() + + def aspreconditioner(self): + return InverseJacobian(self) + + def solve(self, v, tol=0): + raise NotImplementedError + + def update(self, x, F): + pass + + def setup(self, x, F, func): + self.func = func + self.shape = (F.size, x.size) + self.dtype = F.dtype + if self.__class__.setup is Jacobian.setup: + # Call on the first point unless overridden + self.update(x, F) + + +class InverseJacobian: + """ + A simple wrapper that inverts the Jacobian using the `solve` method. + + .. legacy:: class + + See the newer, more consistent interfaces in :mod:`scipy.optimize`. + + Parameters + ---------- + jacobian : Jacobian + The Jacobian to invert. + + Attributes + ---------- + shape + Matrix dimensions (M, N) + dtype + Data type of the matrix. + + """ + def __init__(self, jacobian): + self.jacobian = jacobian + self.matvec = jacobian.solve + self.update = jacobian.update + if hasattr(jacobian, 'setup'): + self.setup = jacobian.setup + if hasattr(jacobian, 'rsolve'): + self.rmatvec = jacobian.rsolve + + @property + def shape(self): + return self.jacobian.shape + + @property + def dtype(self): + return self.jacobian.dtype + + +def asjacobian(J): + """ + Convert given object to one suitable for use as a Jacobian. + """ + spsolve = scipy.sparse.linalg.spsolve + if isinstance(J, Jacobian): + return J + elif inspect.isclass(J) and issubclass(J, Jacobian): + return J() + elif isinstance(J, np.ndarray): + if J.ndim > 2: + raise ValueError('array must have rank <= 2') + J = np.atleast_2d(np.asarray(J)) + if J.shape[0] != J.shape[1]: + raise ValueError('array must be square') + + return Jacobian(matvec=lambda v: dot(J, v), + rmatvec=lambda v: dot(J.conj().T, v), + solve=lambda v, tol=0: solve(J, v), + rsolve=lambda v, tol=0: solve(J.conj().T, v), + dtype=J.dtype, shape=J.shape) + elif scipy.sparse.issparse(J): + if J.shape[0] != J.shape[1]: + raise ValueError('matrix must be square') + return Jacobian(matvec=lambda v: J @ v, + rmatvec=lambda v: J.conj().T @ v, + solve=lambda v, tol=0: spsolve(J, v), + rsolve=lambda v, tol=0: spsolve(J.conj().T, v), + dtype=J.dtype, shape=J.shape) + elif hasattr(J, 'shape') and hasattr(J, 'dtype') and hasattr(J, 'solve'): + return Jacobian(matvec=getattr(J, 'matvec'), + rmatvec=getattr(J, 'rmatvec'), + solve=J.solve, + rsolve=getattr(J, 'rsolve'), + update=getattr(J, 'update'), + setup=getattr(J, 'setup'), + dtype=J.dtype, + shape=J.shape) + elif callable(J): + # Assume it's a function J(x) that returns the Jacobian + class Jac(Jacobian): + def update(self, x, F): + self.x = x + + def solve(self, v, tol=0): + m = J(self.x) + if isinstance(m, np.ndarray): + return solve(m, v) + elif scipy.sparse.issparse(m): + return spsolve(m, v) + else: + raise ValueError("Unknown matrix type") + + def matvec(self, v): + m = J(self.x) + if isinstance(m, np.ndarray): + return dot(m, v) + elif scipy.sparse.issparse(m): + return m @ v + else: + raise ValueError("Unknown matrix type") + + def rsolve(self, v, tol=0): + m = J(self.x) + if isinstance(m, np.ndarray): + return solve(m.conj().T, v) + elif scipy.sparse.issparse(m): + return spsolve(m.conj().T, v) + else: + raise ValueError("Unknown matrix type") + + def rmatvec(self, v): + m = J(self.x) + if isinstance(m, np.ndarray): + return dot(m.conj().T, v) + elif scipy.sparse.issparse(m): + return m.conj().T @ v + else: + raise ValueError("Unknown matrix type") + return Jac() + elif isinstance(J, str): + return dict(broyden1=BroydenFirst, + broyden2=BroydenSecond, + anderson=Anderson, + diagbroyden=DiagBroyden, + linearmixing=LinearMixing, + excitingmixing=ExcitingMixing, + krylov=KrylovJacobian)[J]() + else: + raise TypeError('Cannot convert object to a Jacobian') + + +#------------------------------------------------------------------------------ +# Broyden +#------------------------------------------------------------------------------ + +class GenericBroyden(Jacobian): + def setup(self, x0, f0, func): + Jacobian.setup(self, x0, f0, func) + self.last_f = f0 + self.last_x = x0 + + if hasattr(self, 'alpha') and self.alpha is None: + # Autoscale the initial Jacobian parameter + # unless we have already guessed the solution. + normf0 = norm(f0) + if normf0: + self.alpha = 0.5*max(norm(x0), 1) / normf0 + else: + self.alpha = 1.0 + + def _update(self, x, f, dx, df, dx_norm, df_norm): + raise NotImplementedError + + def update(self, x, f): + df = f - self.last_f + dx = x - self.last_x + self._update(x, f, dx, df, norm(dx), norm(df)) + self.last_f = f + self.last_x = x + + +class LowRankMatrix: + r""" + A matrix represented as + + .. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger + + However, if the rank of the matrix reaches the dimension of the vectors, + full matrix representation will be used thereon. + + """ + + def __init__(self, alpha, n, dtype): + self.alpha = alpha + self.cs = [] + self.ds = [] + self.n = n + self.dtype = dtype + self.collapsed = None + + @staticmethod + def _matvec(v, alpha, cs, ds): + axpy, scal, dotc = get_blas_funcs(['axpy', 'scal', 'dotc'], + cs[:1] + [v]) + w = alpha * v + for c, d in zip(cs, ds): + a = dotc(d, v) + w = axpy(c, w, w.size, a) + return w + + @staticmethod + def _solve(v, alpha, cs, ds): + """Evaluate w = M^-1 v""" + if len(cs) == 0: + return v/alpha + + # (B + C D^H)^-1 = B^-1 - B^-1 C (I + D^H B^-1 C)^-1 D^H B^-1 + + axpy, dotc = get_blas_funcs(['axpy', 'dotc'], cs[:1] + [v]) + + c0 = cs[0] + A = alpha * np.identity(len(cs), dtype=c0.dtype) + for i, d in enumerate(ds): + for j, c in enumerate(cs): + A[i,j] += dotc(d, c) + + q = np.zeros(len(cs), dtype=c0.dtype) + for j, d in enumerate(ds): + q[j] = dotc(d, v) + q /= alpha + q = solve(A, q) + + w = v/alpha + for c, qc in zip(cs, q): + w = axpy(c, w, w.size, -qc) + + return w + + def matvec(self, v): + """Evaluate w = M v""" + if self.collapsed is not None: + return np.dot(self.collapsed, v) + return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds) + + def rmatvec(self, v): + """Evaluate w = M^H v""" + if self.collapsed is not None: + return np.dot(self.collapsed.T.conj(), v) + return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs) + + def solve(self, v, tol=0): + """Evaluate w = M^-1 v""" + if self.collapsed is not None: + return solve(self.collapsed, v) + return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds) + + def rsolve(self, v, tol=0): + """Evaluate w = M^-H v""" + if self.collapsed is not None: + return solve(self.collapsed.T.conj(), v) + return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs) + + def append(self, c, d): + if self.collapsed is not None: + self.collapsed += c[:,None] * d[None,:].conj() + return + + self.cs.append(c) + self.ds.append(d) + + if len(self.cs) > c.size: + self.collapse() + + def __array__(self, dtype=None, copy=None): + if dtype is not None: + warnings.warn("LowRankMatrix is scipy-internal code, `dtype` " + f"should only be None but was {dtype} (not handled)", + stacklevel=3) + if copy is not None: + warnings.warn("LowRankMatrix is scipy-internal code, `copy` " + f"should only be None but was {copy} (not handled)", + stacklevel=3) + if self.collapsed is not None: + return self.collapsed + + Gm = self.alpha*np.identity(self.n, dtype=self.dtype) + for c, d in zip(self.cs, self.ds): + Gm += c[:,None]*d[None,:].conj() + return Gm + + def collapse(self): + """Collapse the low-rank matrix to a full-rank one.""" + self.collapsed = np.array(self, copy=copy_if_needed) + self.cs = None + self.ds = None + self.alpha = None + + def restart_reduce(self, rank): + """ + Reduce the rank of the matrix by dropping all vectors. + """ + if self.collapsed is not None: + return + assert rank > 0 + if len(self.cs) > rank: + del self.cs[:] + del self.ds[:] + + def simple_reduce(self, rank): + """ + Reduce the rank of the matrix by dropping oldest vectors. + """ + if self.collapsed is not None: + return + assert rank > 0 + while len(self.cs) > rank: + del self.cs[0] + del self.ds[0] + + def svd_reduce(self, max_rank, to_retain=None): + """ + Reduce the rank of the matrix by retaining some SVD components. + + This corresponds to the \"Broyden Rank Reduction Inverse\" + algorithm described in [1]_. + + Note that the SVD decomposition can be done by solving only a + problem whose size is the effective rank of this matrix, which + is viable even for large problems. + + Parameters + ---------- + max_rank : int + Maximum rank of this matrix after reduction. + to_retain : int, optional + Number of SVD components to retain when reduction is done + (ie. rank > max_rank). Default is ``max_rank - 2``. + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + \"A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations\". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + + https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf + + """ + if self.collapsed is not None: + return + + p = max_rank + if to_retain is not None: + q = to_retain + else: + q = p - 2 + + if self.cs: + p = min(p, len(self.cs[0])) + q = max(0, min(q, p-1)) + + m = len(self.cs) + if m < p: + # nothing to do + return + + C = np.array(self.cs).T + D = np.array(self.ds).T + + D, R = qr(D, mode='economic') + C = dot(C, R.T.conj()) + + U, S, WH = svd(C, full_matrices=False) + + C = dot(C, inv(WH)) + D = dot(D, WH.T.conj()) + + for k in range(q): + self.cs[k] = C[:,k].copy() + self.ds[k] = D[:,k].copy() + + del self.cs[q:] + del self.ds[q:] + + +_doc_parts['broyden_params'] = """ + alpha : float, optional + Initial guess for the Jacobian is ``(-1/alpha)``. + reduction_method : str or tuple, optional + Method used in ensuring that the rank of the Broyden matrix + stays low. Can either be a string giving the name of the method, + or a tuple of the form ``(method, param1, param2, ...)`` + that gives the name of the method and values for additional parameters. + + Methods available: + + - ``restart``: drop all matrix columns. Has no extra parameters. + - ``simple``: drop oldest matrix column. Has no extra parameters. + - ``svd``: keep only the most significant SVD components. + Takes an extra parameter, ``to_retain``, which determines the + number of SVD components to retain when rank reduction is done. + Default is ``max_rank - 2``. + + max_rank : int, optional + Maximum rank for the Broyden matrix. + Default is infinity (i.e., no rank reduction). + """.strip() + + +class BroydenFirst(GenericBroyden): + """ + Find a root of a function, using Broyden's first Jacobian approximation. + + This method is also known as "Broyden's good method". + + Parameters + ---------- + %(params_basic)s + %(broyden_params)s + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='broyden1'`` in particular. + + Notes + ----- + This algorithm implements the inverse Jacobian Quasi-Newton update + + .. math:: H_+ = H + (dx - H df) dx^\\dagger H / ( dx^\\dagger H df) + + which corresponds to Broyden's first Jacobian update + + .. math:: J_+ = J + (df - J dx) dx^\\dagger / dx^\\dagger dx + + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + "A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + https://math.leidenuniv.nl/scripties/Rotten.pdf + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.broyden1(fun, [0, 0]) + >>> sol + array([0.84116396, 0.15883641]) + + """ + + def __init__(self, alpha=None, reduction_method='restart', max_rank=None): + GenericBroyden.__init__(self) + self.alpha = alpha + self.Gm = None + + if max_rank is None: + max_rank = np.inf + self.max_rank = max_rank + + if isinstance(reduction_method, str): + reduce_params = () + else: + reduce_params = reduction_method[1:] + reduction_method = reduction_method[0] + reduce_params = (max_rank - 1,) + reduce_params + + if reduction_method == 'svd': + self._reduce = lambda: self.Gm.svd_reduce(*reduce_params) + elif reduction_method == 'simple': + self._reduce = lambda: self.Gm.simple_reduce(*reduce_params) + elif reduction_method == 'restart': + self._reduce = lambda: self.Gm.restart_reduce(*reduce_params) + else: + raise ValueError(f"Unknown rank reduction method '{reduction_method}'") + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.Gm = LowRankMatrix(-self.alpha, self.shape[0], self.dtype) + + def todense(self): + return inv(self.Gm) + + def solve(self, f, tol=0): + r = self.Gm.matvec(f) + if not np.isfinite(r).all(): + # singular; reset the Jacobian approximation + self.setup(self.last_x, self.last_f, self.func) + return self.Gm.matvec(f) + return r + + def matvec(self, f): + return self.Gm.solve(f) + + def rsolve(self, f, tol=0): + return self.Gm.rmatvec(f) + + def rmatvec(self, f): + return self.Gm.rsolve(f) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self._reduce() # reduce first to preserve secant condition + + v = self.Gm.rmatvec(dx) + c = dx - self.Gm.matvec(df) + d = v / vdot(df, v) + + self.Gm.append(c, d) + + +class BroydenSecond(BroydenFirst): + """ + Find a root of a function, using Broyden\'s second Jacobian approximation. + + This method is also known as \"Broyden's bad method\". + + Parameters + ---------- + %(params_basic)s + %(broyden_params)s + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='broyden2'`` in particular. + + Notes + ----- + This algorithm implements the inverse Jacobian Quasi-Newton update + + .. math:: H_+ = H + (dx - H df) df^\\dagger / ( df^\\dagger df) + + corresponding to Broyden's second method. + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + \"A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations\". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + + https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.broyden2(fun, [0, 0]) + >>> sol + array([0.84116365, 0.15883529]) + + """ + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self._reduce() # reduce first to preserve secant condition + + v = df + c = dx - self.Gm.matvec(df) + d = v / df_norm**2 + self.Gm.append(c, d) + + +#------------------------------------------------------------------------------ +# Broyden-like (restricted memory) +#------------------------------------------------------------------------------ + +class Anderson(GenericBroyden): + """ + Find a root of a function, using (extended) Anderson mixing. + + The Jacobian is formed by for a 'best' solution in the space + spanned by last `M` vectors. As a result, only a MxM matrix + inversions and MxN multiplications are required. [Ey]_ + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + M : float, optional + Number of previous vectors to retain. Defaults to 5. + w0 : float, optional + Regularization parameter for numerical stability. + Compared to unity, good values of the order of 0.01. + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='anderson'`` in particular. + + References + ---------- + .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996). + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.anderson(fun, [0, 0]) + >>> sol + array([0.84116588, 0.15883789]) + + """ + + # Note: + # + # Anderson method maintains a rank M approximation of the inverse Jacobian, + # + # J^-1 v ~ -v*alpha + (dX + alpha dF) A^-1 dF^H v + # A = W + dF^H dF + # W = w0^2 diag(dF^H dF) + # + # so that for w0 = 0 the secant condition applies for last M iterates, i.e., + # + # J^-1 df_j = dx_j + # + # for all j = 0 ... M-1. + # + # Moreover, (from Sherman-Morrison-Woodbury formula) + # + # J v ~ [ b I - b^2 C (I + b dF^H A^-1 C)^-1 dF^H ] v + # C = (dX + alpha dF) A^-1 + # b = -1/alpha + # + # and after simplification + # + # J v ~ -v/alpha + (dX/alpha + dF) (dF^H dX - alpha W)^-1 dF^H v + # + + def __init__(self, alpha=None, w0=0.01, M=5): + GenericBroyden.__init__(self) + self.alpha = alpha + self.M = M + self.dx = [] + self.df = [] + self.gamma = None + self.w0 = w0 + + def solve(self, f, tol=0): + dx = -self.alpha*f + + n = len(self.dx) + if n == 0: + return dx + + df_f = np.empty(n, dtype=f.dtype) + for k in range(n): + df_f[k] = vdot(self.df[k], f) + + try: + gamma = solve(self.a, df_f) + except LinAlgError: + # singular; reset the Jacobian approximation + del self.dx[:] + del self.df[:] + return dx + + for m in range(n): + dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m]) + return dx + + def matvec(self, f): + dx = -f/self.alpha + + n = len(self.dx) + if n == 0: + return dx + + df_f = np.empty(n, dtype=f.dtype) + for k in range(n): + df_f[k] = vdot(self.df[k], f) + + b = np.empty((n, n), dtype=f.dtype) + for i in range(n): + for j in range(n): + b[i,j] = vdot(self.df[i], self.dx[j]) + if i == j and self.w0 != 0: + b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha + gamma = solve(b, df_f) + + for m in range(n): + dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha) + return dx + + def _update(self, x, f, dx, df, dx_norm, df_norm): + if self.M == 0: + return + + self.dx.append(dx) + self.df.append(df) + + while len(self.dx) > self.M: + self.dx.pop(0) + self.df.pop(0) + + n = len(self.dx) + a = np.zeros((n, n), dtype=f.dtype) + + for i in range(n): + for j in range(i, n): + if i == j: + wd = self.w0**2 + else: + wd = 0 + a[i,j] = (1+wd)*vdot(self.df[i], self.df[j]) + + a += np.triu(a, 1).T.conj() + self.a = a + +#------------------------------------------------------------------------------ +# Simple iterations +#------------------------------------------------------------------------------ + + +class DiagBroyden(GenericBroyden): + """ + Find a root of a function, using diagonal Broyden Jacobian approximation. + + The Jacobian approximation is derived from previous iterations, by + retaining only the diagonal of Broyden matrices. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='diagbroyden'`` in particular. + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.diagbroyden(fun, [0, 0]) + >>> sol + array([0.84116403, 0.15883384]) + + """ + + def __init__(self, alpha=None): + GenericBroyden.__init__(self) + self.alpha = alpha + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.d = np.full((self.shape[0],), 1 / self.alpha, dtype=self.dtype) + + def solve(self, f, tol=0): + return -f / self.d + + def matvec(self, f): + return -f * self.d + + def rsolve(self, f, tol=0): + return -f / self.d.conj() + + def rmatvec(self, f): + return -f * self.d.conj() + + def todense(self): + return np.diag(-self.d) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self.d -= (df + self.d*dx)*dx/dx_norm**2 + + +class LinearMixing(GenericBroyden): + """ + Find a root of a function, using a scalar Jacobian approximation. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + The Jacobian approximation is (-1/alpha). + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='linearmixing'`` in particular. + + """ + + def __init__(self, alpha=None): + GenericBroyden.__init__(self) + self.alpha = alpha + + def solve(self, f, tol=0): + return -f*self.alpha + + def matvec(self, f): + return -f/self.alpha + + def rsolve(self, f, tol=0): + return -f*np.conj(self.alpha) + + def rmatvec(self, f): + return -f/np.conj(self.alpha) + + def todense(self): + return np.diag(np.full(self.shape[0], -1/self.alpha)) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + pass + + +class ExcitingMixing(GenericBroyden): + """ + Find a root of a function, using a tuned diagonal Jacobian approximation. + + The Jacobian matrix is diagonal and is tuned on each iteration. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='excitingmixing'`` in particular. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial Jacobian approximation is (-1/alpha). + alphamax : float, optional + The entries of the diagonal Jacobian are kept in the range + ``[alpha, alphamax]``. + %(params_extra)s + """ + + def __init__(self, alpha=None, alphamax=1.0): + GenericBroyden.__init__(self) + self.alpha = alpha + self.alphamax = alphamax + self.beta = None + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.beta = np.full((self.shape[0],), self.alpha, dtype=self.dtype) + + def solve(self, f, tol=0): + return -f*self.beta + + def matvec(self, f): + return -f/self.beta + + def rsolve(self, f, tol=0): + return -f*self.beta.conj() + + def rmatvec(self, f): + return -f/self.beta.conj() + + def todense(self): + return np.diag(-1/self.beta) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + incr = f*self.last_f > 0 + self.beta[incr] += self.alpha + self.beta[~incr] = self.alpha + np.clip(self.beta, 0, self.alphamax, out=self.beta) + + +#------------------------------------------------------------------------------ +# Iterative/Krylov approximated Jacobians +#------------------------------------------------------------------------------ + +class KrylovJacobian(Jacobian): + """ + Find a root of a function, using Krylov approximation for inverse Jacobian. + + This method is suitable for solving large-scale problems. + + Parameters + ---------- + %(params_basic)s + rdiff : float, optional + Relative step size to use in numerical differentiation. + method : str or callable, optional + Krylov method to use to approximate the Jacobian. Can be a string, + or a function implementing the same interface as the iterative + solvers in `scipy.sparse.linalg`. If a string, needs to be one of: + ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``, + ``'tfqmr'``. + + The default is `scipy.sparse.linalg.lgmres`. + inner_maxiter : int, optional + Parameter to pass to the "inner" Krylov solver: maximum number of + iterations. Iteration will stop after maxiter steps even if the + specified tolerance has not been achieved. + inner_M : LinearOperator or InverseJacobian + Preconditioner for the inner Krylov iteration. + Note that you can use also inverse Jacobians as (adaptive) + preconditioners. For example, + + >>> from scipy.optimize import BroydenFirst, KrylovJacobian + >>> from scipy.optimize import InverseJacobian + >>> jac = BroydenFirst() + >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac)) + + If the preconditioner has a method named 'update', it will be called + as ``update(x, f)`` after each nonlinear step, with ``x`` giving + the current point, and ``f`` the current function value. + outer_k : int, optional + Size of the subspace kept across LGMRES nonlinear iterations. + See `scipy.sparse.linalg.lgmres` for details. + inner_kwargs : kwargs + Keyword parameters for the "inner" Krylov solver + (defined with `method`). Parameter names must start with + the `inner_` prefix which will be stripped before passing on + the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details. + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='krylov'`` in particular. + scipy.sparse.linalg.gmres + scipy.sparse.linalg.lgmres + + Notes + ----- + This function implements a Newton-Krylov solver. The basic idea is + to compute the inverse of the Jacobian with an iterative Krylov + method. These methods require only evaluating the Jacobian-vector + products, which are conveniently approximated by a finite difference: + + .. math:: J v \\approx (f(x + \\omega*v/|v|) - f(x)) / \\omega + + Due to the use of iterative matrix inverses, these methods can + deal with large nonlinear problems. + + SciPy's `scipy.sparse.linalg` module offers a selection of Krylov + solvers to choose from. The default here is `lgmres`, which is a + variant of restarted GMRES iteration that reuses some of the + information obtained in the previous Newton steps to invert + Jacobians in subsequent steps. + + For a review on Newton-Krylov methods, see for example [1]_, + and for the LGMRES sparse inverse method, see [2]_. + + References + ---------- + .. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method, + SIAM, pp.57-83, 2003. + :doi:`10.1137/1.9780898718898.ch3` + .. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004). + :doi:`10.1016/j.jcp.2003.08.010` + .. [3] A.H. Baker and E.R. Jessup and T. Manteuffel, + SIAM J. Matrix Anal. Appl. 26, 962 (2005). + :doi:`10.1137/S0895479803422014` + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * x[1] - 1.0, + ... 0.5 * (x[1] - x[0]) ** 2] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.newton_krylov(fun, [0, 0]) + >>> sol + array([0.66731771, 0.66536458]) + + """ + + def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20, + inner_M=None, outer_k=10, **kw): + self.preconditioner = inner_M + self.rdiff = rdiff + # Note that this retrieves one of the named functions, or otherwise + # uses `method` as is (i.e., for a user-provided callable). + self.method = dict( + bicgstab=scipy.sparse.linalg.bicgstab, + gmres=scipy.sparse.linalg.gmres, + lgmres=scipy.sparse.linalg.lgmres, + cgs=scipy.sparse.linalg.cgs, + minres=scipy.sparse.linalg.minres, + tfqmr=scipy.sparse.linalg.tfqmr, + ).get(method, method) + + self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner) + + if self.method is scipy.sparse.linalg.gmres: + # Replace GMRES's outer iteration with Newton steps + self.method_kw['restart'] = inner_maxiter + self.method_kw['maxiter'] = 1 + self.method_kw.setdefault('atol', 0) + elif self.method in (scipy.sparse.linalg.gcrotmk, + scipy.sparse.linalg.bicgstab, + scipy.sparse.linalg.cgs): + self.method_kw.setdefault('atol', 0) + elif self.method is scipy.sparse.linalg.lgmres: + self.method_kw['outer_k'] = outer_k + # Replace LGMRES's outer iteration with Newton steps + self.method_kw['maxiter'] = 1 + # Carry LGMRES's `outer_v` vectors across nonlinear iterations + self.method_kw.setdefault('outer_v', []) + self.method_kw.setdefault('prepend_outer_v', True) + # But don't carry the corresponding Jacobian*v products, in case + # the Jacobian changes a lot in the nonlinear step + # + # XXX: some trust-region inspired ideas might be more efficient... + # See e.g., Brown & Saad. But needs to be implemented separately + # since it's not an inexact Newton method. + self.method_kw.setdefault('store_outer_Av', False) + self.method_kw.setdefault('atol', 0) + + for key, value in kw.items(): + if not key.startswith('inner_'): + raise ValueError(f"Unknown parameter {key}") + self.method_kw[key[6:]] = value + + def _update_diff_step(self): + mx = abs(self.x0).max() + mf = abs(self.f0).max() + self.omega = self.rdiff * max(1, mx) / max(1, mf) + + def matvec(self, v): + nv = norm(v) + if nv == 0: + return 0*v + sc = self.omega / nv + r = (self.func(self.x0 + sc*v) - self.f0) / sc + if not np.all(np.isfinite(r)) and np.all(np.isfinite(v)): + raise ValueError('Function returned non-finite results') + return r + + def solve(self, rhs, tol=0): + if 'rtol' in self.method_kw: + sol, info = self.method(self.op, rhs, **self.method_kw) + else: + sol, info = self.method(self.op, rhs, rtol=tol, **self.method_kw) + return sol + + def update(self, x, f): + self.x0 = x + self.f0 = f + self._update_diff_step() + + # Update also the preconditioner, if possible + if self.preconditioner is not None: + if hasattr(self.preconditioner, 'update'): + self.preconditioner.update(x, f) + + def setup(self, x, f, func): + Jacobian.setup(self, x, f, func) + self.x0 = x + self.f0 = f + self.op = scipy.sparse.linalg.aslinearoperator(self) + + if self.rdiff is None: + self.rdiff = np.finfo(x.dtype).eps ** (1./2) + + self._update_diff_step() + + # Setup also the preconditioner, if possible + if self.preconditioner is not None: + if hasattr(self.preconditioner, 'setup'): + self.preconditioner.setup(x, f, func) + + +#------------------------------------------------------------------------------ +# Wrapper functions +#------------------------------------------------------------------------------ + +def _nonlin_wrapper(name, jac): + """ + Construct a solver wrapper with given name and Jacobian approx. + + It inspects the keyword arguments of ``jac.__init__``, and allows to + use the same arguments in the wrapper function, in addition to the + keyword arguments of `nonlin_solve` + + """ + signature = _getfullargspec(jac.__init__) + args, varargs, varkw, defaults, kwonlyargs, kwdefaults, _ = signature + kwargs = list(zip(args[-len(defaults):], defaults)) + kw_str = ", ".join([f"{k}={v!r}" for k, v in kwargs]) + if kw_str: + kw_str = ", " + kw_str + kwkw_str = ", ".join([f"{k}={k}" for k, v in kwargs]) + if kwkw_str: + kwkw_str = kwkw_str + ", " + if kwonlyargs: + raise ValueError(f'Unexpected signature {signature}') + + # Construct the wrapper function so that its keyword arguments + # are visible in pydoc.help etc. + wrapper = """ +def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None, + f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + tol_norm=None, line_search='armijo', callback=None, **kw): + jac = %(jac)s(%(kwkw)s **kw) + return nonlin_solve(F, xin, jac, iter, verbose, maxiter, + f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search, + callback) +""" + + wrapper = wrapper % dict(name=name, kw=kw_str, jac=jac.__name__, + kwkw=kwkw_str) + ns = {} + ns.update(globals()) + exec(wrapper, ns) + func = ns[name] + func.__doc__ = jac.__doc__ + _set_doc(func) + return func + + +broyden1 = _nonlin_wrapper('broyden1', BroydenFirst) +broyden2 = _nonlin_wrapper('broyden2', BroydenSecond) +anderson = _nonlin_wrapper('anderson', Anderson) +linearmixing = _nonlin_wrapper('linearmixing', LinearMixing) +diagbroyden = _nonlin_wrapper('diagbroyden', DiagBroyden) +excitingmixing = _nonlin_wrapper('excitingmixing', ExcitingMixing) +newton_krylov = _nonlin_wrapper('newton_krylov', KrylovJacobian) diff --git a/shared/package-files/06/06d3b49e34f00c5ad736bde730aabfa7c3c384fcc7f517f30ab9cb909c73e5fc/test_indexing.py b/shared/package-files/06/06d3b49e34f00c5ad736bde730aabfa7c3c384fcc7f517f30ab9cb909c73e5fc/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..262ec1eac6f4a9ff9adfc01675d83bd98bf96f1f --- /dev/null +++ b/shared/package-files/06/06d3b49e34f00c5ad736bde730aabfa7c3c384fcc7f517f30ab9cb909c73e5fc/test_indexing.py @@ -0,0 +1,364 @@ +""" +test_indexing tests the following Index methods: + __getitem__ + get_loc + get_value + __contains__ + take + where + get_indexer + get_indexer_for + slice_locs + asof_locs + +The corresponding tests.indexes.[index_type].test_indexing files +contain tests for the corresponding methods specific to those Index subclasses. +""" +import numpy as np +import pytest + +from pandas.compat import PY314 +from pandas.errors import InvalidIndexError + +from pandas.core.dtypes.common import ( + is_float_dtype, + is_scalar, +) + +from pandas import ( + NA, + DatetimeIndex, + Index, + IntervalIndex, + MultiIndex, + NaT, + PeriodIndex, + TimedeltaIndex, +) +import pandas._testing as tm + + +class TestTake: + def test_take_invalid_kwargs(self, index): + indices = [1, 2] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + index.take(indices, foo=2) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + index.take(indices, out=indices) + + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + index.take(indices, mode="clip") + + def test_take(self, index): + indexer = [4, 3, 0, 2] + if len(index) < 5: + pytest.skip("Test doesn't make sense since not enough elements") + + result = index.take(indexer) + expected = index[indexer] + assert result.equals(expected) + + if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)): + # GH 10791 + msg = r"'(.*Index)' object has no attribute 'freq'" + with pytest.raises(AttributeError, match=msg): + index.freq + + def test_take_indexer_type(self): + # GH#42875 + integer_index = Index([0, 1, 2, 3]) + scalar_index = 1 + msg = "Expected indices to be array-like" + with pytest.raises(TypeError, match=msg): + integer_index.take(scalar_index) + + def test_take_minus1_without_fill(self, index): + # -1 does not get treated as NA unless allow_fill=True is passed + if len(index) == 0: + # Test is not applicable + pytest.skip("Test doesn't make sense for empty index") + + result = index.take([0, 0, -1]) + + expected = index.take([0, 0, len(index) - 1]) + tm.assert_index_equal(result, expected) + + +class TestContains: + @pytest.mark.parametrize( + "index,val", + [ + (Index([0, 1, 2]), 2), + (Index([0, 1, "2"]), "2"), + (Index([0, 1, 2, np.inf, 4]), 4), + (Index([0, 1, 2, np.nan, 4]), 4), + (Index([0, 1, 2, np.inf]), np.inf), + (Index([0, 1, 2, np.nan]), np.nan), + ], + ) + def test_index_contains(self, index, val): + assert val in index + + @pytest.mark.parametrize( + "index,val", + [ + (Index([0, 1, 2]), "2"), + (Index([0, 1, "2"]), 2), + (Index([0, 1, 2, np.inf]), 4), + (Index([0, 1, 2, np.nan]), 4), + (Index([0, 1, 2, np.inf]), np.nan), + (Index([0, 1, 2, np.nan]), np.inf), + # Checking if np.inf in int64 Index should not cause an OverflowError + # Related to GH 16957 + (Index([0, 1, 2], dtype=np.int64), np.inf), + (Index([0, 1, 2], dtype=np.int64), np.nan), + (Index([0, 1, 2], dtype=np.uint64), np.inf), + (Index([0, 1, 2], dtype=np.uint64), np.nan), + ], + ) + def test_index_not_contains(self, index, val): + assert val not in index + + @pytest.mark.parametrize( + "index,val", [(Index([0, 1, "2"]), 0), (Index([0, 1, "2"]), "2")] + ) + def test_mixed_index_contains(self, index, val): + # GH#19860 + assert val in index + + @pytest.mark.parametrize( + "index,val", [(Index([0, 1, "2"]), "1"), (Index([0, 1, "2"]), 2)] + ) + def test_mixed_index_not_contains(self, index, val): + # GH#19860 + assert val not in index + + def test_contains_with_float_index(self, any_real_numpy_dtype): + # GH#22085 + dtype = any_real_numpy_dtype + data = [0, 1, 2, 3] if not is_float_dtype(dtype) else [0.1, 1.1, 2.2, 3.3] + index = Index(data, dtype=dtype) + + if not is_float_dtype(index.dtype): + assert 1.1 not in index + assert 1.0 in index + assert 1 in index + else: + assert 1.1 in index + assert 1.0 not in index + assert 1 not in index + + def test_contains_requires_hashable_raises(self, index): + if isinstance(index, MultiIndex): + return # TODO: do we want this to raise? + + msg = "unhashable type: 'list'" + with pytest.raises(TypeError, match=msg): + [] in index + + if PY314: + container_or_iterable = "a container or iterable" + else: + container_or_iterable = "iterable" + + msg = "|".join( + [ + r"unhashable type: 'dict'", + r"must be real number, not dict", + r"an integer is required", + r"\{\}", + r"pandas\._libs\.interval\.IntervalTree' is not " + f"{container_or_iterable}", + ] + ) + with pytest.raises(TypeError, match=msg): + {} in index._engine + + +class TestGetLoc: + def test_get_loc_non_hashable(self, index): + with pytest.raises(InvalidIndexError, match="[0, 1]"): + index.get_loc([0, 1]) + + def test_get_loc_non_scalar_hashable(self, index): + # GH52877 + from enum import Enum + + class E(Enum): + X1 = "x1" + + assert not is_scalar(E.X1) + + exc = KeyError + msg = "" + if isinstance( + index, + ( + DatetimeIndex, + TimedeltaIndex, + PeriodIndex, + IntervalIndex, + ), + ): + # TODO: make these more consistent? + exc = InvalidIndexError + msg = "E.X1" + with pytest.raises(exc, match=msg): + index.get_loc(E.X1) + + def test_get_loc_generator(self, index): + exc = KeyError + if isinstance( + index, + ( + DatetimeIndex, + TimedeltaIndex, + PeriodIndex, + IntervalIndex, + MultiIndex, + ), + ): + # TODO: make these more consistent? + exc = InvalidIndexError + with pytest.raises(exc, match="generator object"): + # MultiIndex specifically checks for generator; others for scalar + index.get_loc(x for x in range(5)) + + def test_get_loc_masked_duplicated_na(self): + # GH#48411 + idx = Index([1, 2, NA, NA], dtype="Int64") + result = idx.get_loc(NA) + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(result, expected) + + +class TestGetIndexer: + def test_get_indexer_base(self, index): + if index._index_as_unique: + expected = np.arange(index.size, dtype=np.intp) + actual = index.get_indexer(index) + tm.assert_numpy_array_equal(expected, actual) + else: + msg = "Reindexing only valid with uniquely valued Index objects" + with pytest.raises(InvalidIndexError, match=msg): + index.get_indexer(index) + + with pytest.raises(ValueError, match="Invalid fill method"): + index.get_indexer(index, method="invalid") + + def test_get_indexer_consistency(self, index): + # See GH#16819 + + if index._index_as_unique: + indexer = index.get_indexer(index[0:2]) + assert isinstance(indexer, np.ndarray) + assert indexer.dtype == np.intp + else: + msg = "Reindexing only valid with uniquely valued Index objects" + with pytest.raises(InvalidIndexError, match=msg): + index.get_indexer(index[0:2]) + + indexer, _ = index.get_indexer_non_unique(index[0:2]) + assert isinstance(indexer, np.ndarray) + assert indexer.dtype == np.intp + + def test_get_indexer_masked_duplicated_na(self): + # GH#48411 + idx = Index([1, 2, NA, NA], dtype="Int64") + result = idx.get_indexer_for(Index([1, NA], dtype="Int64")) + expected = np.array([0, 2, 3], dtype=result.dtype) + tm.assert_numpy_array_equal(result, expected) + + +class TestConvertSliceIndexer: + def test_convert_almost_null_slice(self, index): + # slice with None at both ends, but not step + + key = slice(None, None, "foo") + + if isinstance(index, IntervalIndex): + msg = "label-based slicing with step!=1 is not supported for IntervalIndex" + with pytest.raises(ValueError, match=msg): + index._convert_slice_indexer(key, "loc") + else: + msg = "'>=' not supported between instances of 'str' and 'int'" + with pytest.raises(TypeError, match=msg): + index._convert_slice_indexer(key, "loc") + + +class TestPutmask: + def test_putmask_with_wrong_mask(self, index): + # GH#18368 + if not len(index): + pytest.skip("Test doesn't make sense for empty index") + + fill = index[0] + + msg = "putmask: mask and data must be the same size" + with pytest.raises(ValueError, match=msg): + index.putmask(np.ones(len(index) + 1, np.bool_), fill) + + with pytest.raises(ValueError, match=msg): + index.putmask(np.ones(len(index) - 1, np.bool_), fill) + + with pytest.raises(ValueError, match=msg): + index.putmask("foo", fill) + + +@pytest.mark.parametrize( + "idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])] +) +def test_getitem_deprecated_float(idx): + # https://github.com/pandas-dev/pandas/issues/34191 + + msg = "Indexing with a float is no longer supported" + with pytest.raises(IndexError, match=msg): + idx[1.0] + + +@pytest.mark.parametrize( + "idx,target,expected", + [ + ([np.nan, "var1", np.nan], [np.nan], np.array([0, 2], dtype=np.intp)), + ( + [np.nan, "var1", np.nan], + [np.nan, "var1"], + np.array([0, 2, 1], dtype=np.intp), + ), + ( + np.array([np.nan, "var1", np.nan], dtype=object), + [np.nan], + np.array([0, 2], dtype=np.intp), + ), + ( + DatetimeIndex(["2020-08-05", NaT, NaT]), + [NaT], + np.array([1, 2], dtype=np.intp), + ), + (["a", "b", "a", np.nan], [np.nan], np.array([3], dtype=np.intp)), + ( + np.array(["b", np.nan, float("NaN"), "b"], dtype=object), + Index([np.nan], dtype=object), + np.array([1, 2], dtype=np.intp), + ), + ], +) +def test_get_indexer_non_unique_multiple_nans(idx, target, expected): + # GH 35392 + axis = Index(idx) + actual = axis.get_indexer_for(target) + tm.assert_numpy_array_equal(actual, expected) + + +def test_get_indexer_non_unique_nans_in_object_dtype_target(nulls_fixture): + idx = Index([1.0, 2.0]) + target = Index([1, nulls_fixture], dtype="object") + + result_idx, result_missing = idx.get_indexer_non_unique(target) + tm.assert_numpy_array_equal(result_idx, np.array([0, -1], dtype=np.intp)) + tm.assert_numpy_array_equal(result_missing, np.array([1], dtype=np.intp)) diff --git a/shared/package-files/06/06d5a05ca7ad5be95f0bdccef3be5c8990d91c7cd8407c5c8d5079664130493a/_newrand.cpython-310-x86_64-linux-gnu.so b/shared/package-files/06/06d5a05ca7ad5be95f0bdccef3be5c8990d91c7cd8407c5c8d5079664130493a/_newrand.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ffe8074557337d37e7281ead250e762eb40da0ad Binary files /dev/null and b/shared/package-files/06/06d5a05ca7ad5be95f0bdccef3be5c8990d91c7cd8407c5c8d5079664130493a/_newrand.cpython-310-x86_64-linux-gnu.so differ diff --git a/shared/package-files/06/06d81abe6df0ddcf6677fe7215faba55ea3fe482bd2ad94b1752443de1e16685/fortran-sf8-1x1x5.dat b/shared/package-files/06/06d81abe6df0ddcf6677fe7215faba55ea3fe482bd2ad94b1752443de1e16685/fortran-sf8-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..3d3f27f88eef4e02451d18204cdcfd51f96f6d15 Binary files /dev/null and b/shared/package-files/06/06d81abe6df0ddcf6677fe7215faba55ea3fe482bd2ad94b1752443de1e16685/fortran-sf8-1x1x5.dat differ diff --git a/shared/package-files/06/06dd7572626df5cb0a8d3affbac9bb74cb12469076836d66fd19ae5b5fab42c7/de.msg b/shared/package-files/06/06dd7572626df5cb0a8d3affbac9bb74cb12469076836d66fd19ae5b5fab42c7/de.msg new file mode 100644 index 0000000000000000000000000000000000000000..e420f8a2ec887b04f24b666f8145214656e6b769 --- /dev/null +++ b/shared/package-files/06/06dd7572626df5cb0a8d3affbac9bb74cb12469076836d66fd19ae5b5fab42c7/de.msg @@ -0,0 +1,91 @@ +namespace eval ::tk { + ::msgcat::mcset de "&Abort" "&Abbruch" + ::msgcat::mcset de "&About..." "&\u00dcber..." + ::msgcat::mcset de "All Files" "Alle Dateien" + ::msgcat::mcset de "Application Error" "Applikationsfehler" + ::msgcat::mcset de "&Apply" "&Anwenden" + ::msgcat::mcset de "Bold" "Fett" + ::msgcat::mcset de "Bold Italic" "Fett kursiv" + ::msgcat::mcset de "&Blue" "&Blau" + ::msgcat::mcset de "Cancel" "Abbruch" + ::msgcat::mcset de "&Cancel" "&Abbruch" + ::msgcat::mcset de "Cannot change to the directory \"%1\$s\".\nPermission denied." "Kann nicht in das Verzeichnis \"%1\$s\" wechseln.\nKeine Rechte vorhanden." + ::msgcat::mcset de "Choose Directory" "W\u00e4hle Verzeichnis" + ::msgcat::mcset de "Cl&ear" "&R\u00fccksetzen" + ::msgcat::mcset de "&Clear Console" "&Konsole l\u00f6schen" + ::msgcat::mcset de "Color" "Farbe" + ::msgcat::mcset de "Console" "Konsole" + ::msgcat::mcset de "&Copy" "&Kopieren" + ::msgcat::mcset de "Cu&t" "Aus&schneiden" + ::msgcat::mcset de "&Delete" "&L\u00f6schen" + ::msgcat::mcset de "Details >>" + ::msgcat::mcset de "Directory \"%1\$s\" does not exist." "Das Verzeichnis \"%1\$s\" existiert nicht." + ::msgcat::mcset de "&Directory:" "&Verzeichnis:" + ::msgcat::mcset de "&Edit" "&Bearbeiten" + ::msgcat::mcset de "Effects" "Effekte" + ::msgcat::mcset de "Error: %1\$s" "Fehler: %1\$s" + ::msgcat::mcset de "E&xit" "&Ende" + ::msgcat::mcset de "&File" "&Datei" + ::msgcat::mcset de "File \"%1\$s\" already exists.\nDo you want to overwrite it?" "Die Datei \"%1\$s\" ist bereits vorhanden.\nWollen sie diese Datei \u00fcberschreiben ?" + ::msgcat::mcset de "File \"%1\$s\" already exists.\n\n" "Die Datei \"%1\$s\" ist bereits vorhanden.\n\n" + ::msgcat::mcset de "File \"%1\$s\" does not exist." "Die Datei \"%1\$s\" existiert nicht." + ::msgcat::mcset de "File &name:" "Datei&name:" + ::msgcat::mcset de "File &names:" "Datei&namen:" + ::msgcat::mcset de "Files of &type:" "Dateien des &Typs:" + ::msgcat::mcset de "Fi&les:" "Dat&eien:" + ::msgcat::mcset de "&Filter" + ::msgcat::mcset de "Fil&ter:" + ::msgcat::mcset de "Font" "Schriftart" + ::msgcat::mcset de "&Font:" "Schriftart:" + ::msgcat::mcset de "Font st&yle:" "Schriftschnitt:" + ::msgcat::mcset de "&Green" "&Gr\u00fcn" + ::msgcat::mcset de "&Help" "&Hilfe" + ::msgcat::mcset de "Hi" "Hallo" + ::msgcat::mcset de "&Hide Console" "&Konsole unsichtbar machen" + ::msgcat::mcset de "&Ignore" "&Ignorieren" + ::msgcat::mcset de "Invalid file name \"%1\$s\"." "Ung\u00fcltiger Dateiname \"%1\$s\"." + ::msgcat::mcset de "Italic" "Kursiv" + ::msgcat::mcset de "Log Files" "Protokolldatei" + ::msgcat::mcset de "&No" "&Nein" + ::msgcat::mcset de "&OK" + ::msgcat::mcset de "OK" + ::msgcat::mcset de "Ok" + ::msgcat::mcset de "Open" "\u00d6ffnen" + ::msgcat::mcset de "&Open" "\u00d6&ffnen" + ::msgcat::mcset de "Open Multiple Files" "Mehrere Dateien \u00F6ffnen" + ::msgcat::mcset de "P&aste" "E&inf\u00fcgen" + ::msgcat::mcset de "&Quit" "&Beenden" + ::msgcat::mcset de "&Red" "&Rot" + ::msgcat::mcset de "Regular" "Standard" + ::msgcat::mcset de "Replace existing file?" "Existierende Datei ersetzen?" + ::msgcat::mcset de "&Retry" "&Wiederholen" + ::msgcat::mcset de "Sample" "Beispiel" + ::msgcat::mcset de "&Save" "&Speichern" + ::msgcat::mcset de "Save As" "Speichern unter" + ::msgcat::mcset de "Save To Log" "In Protokoll speichern" + ::msgcat::mcset de "Select Log File" "Protokolldatei ausw\u00e4hlen" + ::msgcat::mcset de "Select a file to source" "Auszuf\u00fchrende Datei ausw\u00e4hlen" + ::msgcat::mcset de "&Selection:" "Auswah&l:" + ::msgcat::mcset de "&Size:" "Schriftgrad:" + ::msgcat::mcset de "Show &Hidden Directories" "Zeige versteckte Dateien" + ::msgcat::mcset de "Show &Hidden Files and Directories" "Zeige versteckte Dateien und Verzeichnisse" + ::msgcat::mcset de "Skip Messages" "Weitere Nachrichten \u00fcberspringen" + ::msgcat::mcset de "&Source..." "&Ausf\u00fchren..." + ::msgcat::mcset de "Stri&keout" "&Durchgestrichen" + ::msgcat::mcset de "Tcl Scripts" "Tcl-Skripte" + ::msgcat::mcset de "Tcl for Windows" "Tcl f\u00fcr Windows" + ::msgcat::mcset de "Text Files" "Textdateien" + ::msgcat::mcset de "&Underline" "&Unterstrichen" + ::msgcat::mcset de "&Yes" "&Ja" + ::msgcat::mcset de "abort" "abbrechen" + ::msgcat::mcset de "blue" "blau" + ::msgcat::mcset de "cancel" "abbrechen" + ::msgcat::mcset de "extension" "Erweiterung" + ::msgcat::mcset de "extensions" "Erweiterungen" + ::msgcat::mcset de "green" "gr\u00fcn" + ::msgcat::mcset de "ignore" "ignorieren" + ::msgcat::mcset de "ok" + ::msgcat::mcset de "red" "rot" + ::msgcat::mcset de "retry" "wiederholen" + ::msgcat::mcset de "yes" "ja" +} diff --git a/shared/package-files/06/06e073b6b3d045ab149956615ebdbf36026e8dd513361370779f696591e4de50/dtypes.py b/shared/package-files/06/06e073b6b3d045ab149956615ebdbf36026e8dd513361370779f696591e4de50/dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..068a6a1a0f5b5382a7d0c4fcc2b6cd33f989fdfa --- /dev/null +++ b/shared/package-files/06/06e073b6b3d045ab149956615ebdbf36026e8dd513361370779f696591e4de50/dtypes.py @@ -0,0 +1,77 @@ +""" +DType classes and utility (:mod:`numpy.dtypes`) +=============================================== + +This module is home to specific dtypes related functionality and their classes. +For more general information about dtypes, also see `numpy.dtype` and +:ref:`arrays.dtypes`. + +Similar to the builtin ``types`` module, this submodule defines types (classes) +that are not widely used directly. + +.. versionadded:: NumPy 1.25 + + The dtypes module is new in NumPy 1.25. Previously DType classes were + only accessible indirectly. + + +DType classes +------------- + +The following are the classes of the corresponding NumPy dtype instances and +NumPy scalar types. The classes can be used in ``isinstance`` checks and can +also be instantiated or used directly. Direct use of these classes is not +typical, since their scalar counterparts (e.g. ``np.float64``) or strings +like ``"float64"`` can be used. + +.. list-table:: + :header-rows: 1 + + * - Group + - DType class + + * - Boolean + - ``BoolDType`` + + * - Bit-sized integers + - ``Int8DType``, ``UInt8DType``, ``Int16DType``, ``UInt16DType``, + ``Int32DType``, ``UInt32DType``, ``Int64DType``, ``UInt64DType`` + + * - C-named integers (may be aliases) + - ``ByteDType``, ``UByteDType``, ``ShortDType``, ``UShortDType``, + ``IntDType``, ``UIntDType``, ``LongDType``, ``ULongDType``, + ``LongLongDType``, ``ULongLongDType`` + + * - Floating point + - ``Float16DType``, ``Float32DType``, ``Float64DType``, + ``LongDoubleDType`` + + * - Complex + - ``Complex64DType``, ``Complex128DType``, ``CLongDoubleDType`` + + * - Strings + - ``BytesDType``, ``BytesDType`` + + * - Times + - ``DateTime64DType``, ``TimeDelta64DType`` + + * - Others + - ``ObjectDType``, ``VoidDType`` + +""" + +__all__ = [] + + +def _add_dtype_helper(DType, alias): + # Function to add DTypes a bit more conveniently without channeling them + # through `numpy.core._multiarray_umath` namespace or similar. + from numpy import dtypes + + setattr(dtypes, DType.__name__, DType) + __all__.append(DType.__name__) + + if alias: + alias = alias.removeprefix("numpy.dtypes.") + setattr(dtypes, alias, DType) + __all__.append(alias) diff --git a/shared/package-files/06/06e09e6fc73ad2e0c7a626e83a4281976baedd3f84121ad841cb5ea2a23186a4/WHEEL b/shared/package-files/06/06e09e6fc73ad2e0c7a626e83a4281976baedd3f84121ad841cb5ea2a23186a4/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f5b7a38dffac35dc10eae78b87abf9c1ed603087 --- /dev/null +++ b/shared/package-files/06/06e09e6fc73ad2e0c7a626e83a4281976baedd3f84121ad841cb5ea2a23186a4/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_12_x86_64 +Tag: cp310-cp310-manylinux2010_x86_64 + diff --git a/shared/package-files/06/06e1e22eec6eeae11f64568f256dd13e93dac5a55cb44400de47522520cbd61c/_tqdm_notebook.py b/shared/package-files/06/06e1e22eec6eeae11f64568f256dd13e93dac5a55cb44400de47522520cbd61c/_tqdm_notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..f225fbf5b52d04987ccf68f4d5ee4b735e3158b0 --- /dev/null +++ b/shared/package-files/06/06e1e22eec6eeae11f64568f256dd13e93dac5a55cb44400de47522520cbd61c/_tqdm_notebook.py @@ -0,0 +1,9 @@ +from warnings import warn + +from .notebook import * # NOQA +from .notebook import __all__ # NOQA +from .std import TqdmDeprecationWarning + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.notebook.*` instead of `tqdm._tqdm_notebook.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/shared/package-files/06/06e2998258a8a448014c373041a91ca92f11ae7ed3cfbafe012ea3c45085f5c2/training_provenance.json b/shared/package-files/06/06e2998258a8a448014c373041a91ca92f11ae7ed3cfbafe012ea3c45085f5c2/training_provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..5348fca85396b434154006d71e6d7c6aa7a3ac35 --- /dev/null +++ b/shared/package-files/06/06e2998258a8a448014c373041a91ca92f11ae7ed3cfbafe012ea3c45085f5c2/training_provenance.json @@ -0,0 +1,35007 @@ +{ + "initialization": { + "distribution": "Normal(0,0.01)", + "seed": 20261021, + "pretrained_weights": false + }, + "training_data": "all 19880 supplied training shots per condition; all 130 conditions", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "validation_manifest_sha256": "482bb7268c6c827ebbf1f756ee6994750acfcd011adab08eaa2ada703e5faea1", + "calibration_exception": "Supplied even-fitted DEMs include validation syndromes but no logical labels or test data.", + "optimizer": "L-BFGS-B binary cross entropy plus 1e-5 L2, maximum 300 iterations", + "selection": "First trained candidate; validation reported without parameter fitting or hyperparameter selection", + "test_data_used": false, + "released_per_shot_predictions_used": false, + "history": [ + { + "group": "d3_bX_center_3_5", + "train_loss": 0.49244210477855016, + "iterations": 88, + "failure": 0.26941105769230766, + "plain_failure": 0.2847205528846154, + "correlated_failure": 0.2704326923076923, + "coset_failure": 0.2847205528846154, + "optimizer_success": true + }, + { + "group": "d3_bX_center_5_3", + "train_loss": 0.4947914557869911, + "iterations": 85, + "failure": 0.2706430288461538, + "plain_failure": 0.29103064903846154, + "correlated_failure": 0.27076322115384616, + "coset_failure": 0.29103064903846154, + "optimizer_success": true + }, + { + "group": "d3_bX_center_5_7", + "train_loss": 0.4786369068642458, + "iterations": 79, + "failure": 0.25964543269230766, + "plain_failure": 0.2741887019230769, + "correlated_failure": 0.2598106971153846, + "coset_failure": 0.2741887019230769, + "optimizer_success": true + }, + { + "group": "d3_bX_center_7_5", + "train_loss": 0.48299120621578956, + "iterations": 81, + "failure": 0.26062199519230766, + "plain_failure": 0.2762920673076923, + "correlated_failure": 0.2615234375, + "coset_failure": 0.2762920673076923, + "optimizer_success": true + }, + { + "group": "d3_bZ_center_3_5", + "train_loss": 0.4903180822446507, + "iterations": 62, + "failure": 0.2718299278846154, + "plain_failure": 0.2878605769230769, + "correlated_failure": 0.2736778846153846, + "coset_failure": 0.2878605769230769, + "optimizer_success": true + }, + { + "group": "d3_bZ_center_5_3", + "train_loss": 0.4886621962442568, + "iterations": 90, + "failure": 0.25896935096153845, + "plain_failure": 0.27548076923076925, + "correlated_failure": 0.2588942307692308, + "coset_failure": 0.27548076923076925, + "optimizer_success": true + }, + { + "group": "d3_bZ_center_5_7", + "train_loss": 0.4822654448634678, + "iterations": 71, + "failure": 0.2594200721153846, + "plain_failure": 0.2823016826923077, + "correlated_failure": 0.25961538461538464, + "coset_failure": 0.2823016826923077, + "optimizer_success": true + }, + { + "group": "d3_bZ_center_7_5", + "train_loss": 0.47379411844328495, + "iterations": 69, + "failure": 0.2542067307692308, + "plain_failure": 0.27393329326923077, + "correlated_failure": 0.2547776442307692, + "coset_failure": 0.27393329326923077, + "optimizer_success": true + }, + { + "group": "d5_bX_center_5_5", + "train_loss": 0.4801955727360068, + "iterations": 85, + "failure": 0.2616887019230769, + "plain_failure": 0.293359375, + "correlated_failure": 0.2609375, + "coset_failure": 0.293359375, + "optimizer_success": true + }, + { + "group": "d5_bZ_center_5_5", + "train_loss": 0.4661361209861219, + "iterations": 87, + "failure": 0.2465294471153846, + "plain_failure": 0.2799729567307692, + "correlated_failure": 0.24618389423076922, + "coset_failure": 0.2799729567307692, + "optimizer_success": true + } + ], + "elapsed_seconds": 30.247901678085327, + "experiment_2": { + "method": "Exact contraction of supplied DEM for d3; learned logistic mixture with matching features", + "initialization": { + "distribution": "Normal(0,0.01)", + "seed": 20261022, + "pretrained_weights": false + }, + "selection": "Minimum validation condition-mean failure per group among raw exact, calibrated exact, exact plus matching ensemble", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "exact_raw": { + "failure": 0.253125 + }, + "exact_calibrated": { + "failure": 0.25378605769230766, + "train_loss": 0.46127817271552574, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.2522686298076923, + "train_loss": 0.459112999306209, + "iterations": 115 + } + }, + "selected": "exact_ensemble" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "exact_raw": { + "failure": 0.2569711538461538 + }, + "exact_calibrated": { + "failure": 0.25790264423076925, + "train_loss": 0.46654812103904, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.257421875, + "train_loss": 0.4647701206688181, + "iterations": 80 + } + }, + "selected": "exact_raw" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "exact_raw": { + "failure": 0.23622295673076923 + }, + "exact_calibrated": { + "failure": 0.23608774038461539, + "train_loss": 0.43883548729746, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.2357421875, + "train_loss": 0.43779428254411507, + "iterations": 82 + } + }, + "selected": "exact_ensemble" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "exact_raw": { + "failure": 0.24507211538461537 + }, + "exact_calibrated": { + "failure": 0.24541766826923078, + "train_loss": 0.4551514021617466, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.24453125, + "train_loss": 0.4531701181347552, + "iterations": 87 + } + }, + "selected": "exact_ensemble" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "exact_raw": { + "failure": 0.25402644230769234 + }, + "exact_calibrated": { + "failure": 0.2541316105769231, + "train_loss": 0.4629309494609537, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.25310997596153845, + "train_loss": 0.45978815429050657, + "iterations": 96 + } + }, + "selected": "exact_ensemble" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "exact_raw": { + "failure": 0.24298377403846153 + }, + "exact_calibrated": { + "failure": 0.24182692307692308, + "train_loss": 0.4539302799880139, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.2408203125, + "train_loss": 0.45299183982324187, + "iterations": 100 + } + }, + "selected": "exact_ensemble" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "exact_raw": { + "failure": 0.24226262019230768 + }, + "exact_calibrated": { + "failure": 0.24166165865384615, + "train_loss": 0.4465993958308988, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.24064002403846155, + "train_loss": 0.4446921891727968, + "iterations": 121 + } + }, + "selected": "exact_ensemble" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "exact_raw": { + "failure": 0.23793569711538462 + }, + "exact_calibrated": { + "failure": 0.2377253605769231, + "train_loss": 0.43773570264641537, + "iterations": 8 + }, + "exact_ensemble": { + "failure": 0.2367638221153846, + "train_loss": 0.4363258121838859, + "iterations": 103 + } + }, + "selected": "exact_ensemble" + } + ], + "numerical_check": "r01 all syndromes agrees with exhaustive enumeration to 1.2e-7" + }, + "experiment_3": { + "method": "Exact complementary CSS edge posterior marginals reweight joint error probabilities before relevant CSS exact contraction; induced correlations are factorized", + "initialization": { + "distribution": "Normal(0,0.01)", + "seed": 20261024, + "pretrained_weights": false + }, + "training": "4096 training shots sampled without replacement from each of all 26 d5 conditions, RNG seed 20261023; original matching components retain their all-training-shot fit", + "selection": "Minimum full-validation condition-mean failure per group among previous matching, raw conditional (strength 1), calibrated conditional, and learned combination of strengths 0/.5/1 with matching", + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "matching": { + "failure": 0.2616887019230769 + }, + "conditional_raw": { + "failure": 0.24053485576923078 + }, + "conditional_calibrated": { + "failure": 0.24064002403846155, + "train_loss": 0.4375296643032495, + "iterations": 8 + }, + "conditional_ensemble": { + "failure": 0.24024939903846154, + "train_loss": 0.43518462432711086, + "iterations": 107 + } + }, + "selected": "conditional_ensemble" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "matching": { + "failure": 0.2465294471153846 + }, + "conditional_raw": { + "failure": 0.229296875 + }, + "conditional_calibrated": { + "failure": 0.22944711538461537, + "train_loss": 0.42155058672043744, + "iterations": 9 + }, + "conditional_ensemble": { + "failure": 0.22627704326923076, + "train_loss": 0.4183033939719488, + "iterations": 150 + } + }, + "selected": "conditional_ensemble" + } + ], + "approximation": "Complementary-check conditioning induces error dependencies. This candidate uses their marginal probabilities independently; d5 contraction is therefore approximate." + }, + "contextual_d3_pilot": { + "training": { + "initialization": "Random variance-scaled normal first two layers, random Normal(0,.001) output; zero biases; seed 20261025", + "architecture": "Two 32-unit SiLU layers, output 2*tanh correction to original hyperedge logit; 40 local detection bits and 57 static error/geometry features", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "steps": 512, + "batch_size": 128, + "optimizer": "AdamW 1e-3, weight decay 1e-4, global gradient norm clip 1", + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 512, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.5264908075332642, + "error": 0.2578125, + "gradient_norm": 0.06699763983488083, + "elapsed": 432.866411447525 + }, + { + "step": 16, + "loss": 0.3703196942806244, + "error": 0.1484375, + "gradient_norm": 0.030896008014678955, + "elapsed": 437.98383259773254 + }, + { + "step": 32, + "loss": 0.5410848259925842, + "error": 0.3125, + "gradient_norm": 0.023287978023290634, + "elapsed": 443.36136960983276 + }, + { + "step": 48, + "loss": 0.6548658609390259, + "error": 0.3984375, + "gradient_norm": 0.08600008487701416, + "elapsed": 448.5753285884857 + }, + { + "step": 64, + "loss": 0.3396199345588684, + "error": 0.1875, + "gradient_norm": 0.09408964961767197, + "elapsed": 453.55865502357483 + }, + { + "step": 80, + "loss": 0.22403547167778015, + "error": 0.09375, + "gradient_norm": 0.11353142559528351, + "elapsed": 458.8852906227112 + }, + { + "step": 96, + "loss": 0.5754531621932983, + "error": 0.34375, + "gradient_norm": 0.10487920045852661, + "elapsed": 466.05401706695557 + }, + { + "step": 112, + "loss": 0.6411566734313965, + "error": 0.4609375, + "gradient_norm": 0.0897318571805954, + "elapsed": 472.25429010391235 + }, + { + "step": 128, + "loss": 0.4312451481819153, + "error": 0.1875, + "gradient_norm": 0.024307778105139732, + "elapsed": 477.15532541275024 + }, + { + "step": 144, + "loss": 0.18217915296554565, + "error": 0.0625, + "gradient_norm": 0.02471880242228508, + "elapsed": 481.5596089363098 + }, + { + "step": 160, + "loss": 0.3044101595878601, + "error": 0.140625, + "gradient_norm": 0.11279744654893875, + "elapsed": 485.47020196914673 + }, + { + "step": 176, + "loss": 0.6485109329223633, + "error": 0.421875, + "gradient_norm": 0.09296684712171555, + "elapsed": 489.5691695213318 + }, + { + "step": 192, + "loss": 0.2566836178302765, + "error": 0.09375, + "gradient_norm": 0.03372751921415329, + "elapsed": 493.5000331401825 + }, + { + "step": 208, + "loss": 0.5453524589538574, + "error": 0.296875, + "gradient_norm": 0.09404441714286804, + "elapsed": 497.62110686302185 + }, + { + "step": 224, + "loss": 0.19316628575325012, + "error": 0.0859375, + "gradient_norm": 0.03877737745642662, + "elapsed": 501.7119605541229 + }, + { + "step": 240, + "loss": 0.5537517070770264, + "error": 0.328125, + "gradient_norm": 0.030214278027415276, + "elapsed": 505.71154594421387 + }, + { + "step": 256, + "loss": 0.5224764347076416, + "error": 0.2734375, + "gradient_norm": 0.13780595362186432, + "elapsed": 509.65054631233215 + }, + { + "step": 272, + "loss": 0.5350009202957153, + "error": 0.3046875, + "gradient_norm": 0.08942794054746628, + "elapsed": 553.2619364261627 + }, + { + "step": 288, + "loss": 0.4561898112297058, + "error": 0.21875, + "gradient_norm": 0.02774384245276451, + "elapsed": 557.1897430419922 + }, + { + "step": 304, + "loss": 0.6102809309959412, + "error": 0.390625, + "gradient_norm": 0.04374801740050316, + "elapsed": 561.1394822597504 + }, + { + "step": 320, + "loss": 0.37536823749542236, + "error": 0.171875, + "gradient_norm": 0.10325513035058975, + "elapsed": 565.0790395736694 + }, + { + "step": 336, + "loss": 0.419940710067749, + "error": 0.2265625, + "gradient_norm": 0.04723379388451576, + "elapsed": 569.050211429596 + }, + { + "step": 352, + "loss": 0.6458156108856201, + "error": 0.4609375, + "gradient_norm": 0.04816316068172455, + "elapsed": 573.0114912986755 + }, + { + "step": 368, + "loss": 0.5628451108932495, + "error": 0.328125, + "gradient_norm": 0.09256711602210999, + "elapsed": 576.9429559707642 + }, + { + "step": 384, + "loss": 0.5773618221282959, + "error": 0.359375, + "gradient_norm": 0.16693103313446045, + "elapsed": 580.8791544437408 + }, + { + "step": 400, + "loss": 0.12261693179607391, + "error": 0.046875, + "gradient_norm": 0.06734084337949753, + "elapsed": 584.8116250038147 + }, + { + "step": 416, + "loss": 0.33368560671806335, + "error": 0.125, + "gradient_norm": 0.04156317561864853, + "elapsed": 588.7308163642883 + }, + { + "step": 432, + "loss": 0.2161063849925995, + "error": 0.109375, + "gradient_norm": 0.06895668804645538, + "elapsed": 592.6584475040436 + }, + { + "step": 448, + "loss": 0.6331151723861694, + "error": 0.3828125, + "gradient_norm": 0.12380247563123703, + "elapsed": 596.5997920036316 + }, + { + "step": 464, + "loss": 0.28776052594184875, + "error": 0.1484375, + "gradient_norm": 0.03920985758304596, + "elapsed": 600.5359675884247 + }, + { + "step": 480, + "loss": 0.639541745185852, + "error": 0.421875, + "gradient_norm": 0.029632505029439926, + "elapsed": 604.4547488689423 + }, + { + "step": 496, + "loss": 0.5919073820114136, + "error": 0.359375, + "gradient_norm": 0.11676646769046783, + "elapsed": 608.3825929164886 + }, + { + "step": 512, + "loss": 0.5479233264923096, + "error": 0.265625, + "gradient_norm": 0.03692208230495453, + "elapsed": 612.3190803527832 + } + ] + }, + "selection": "Per-group minimum failure among previous decoder and pilot steps 256 and 512, using all 532480 d3 validation shots", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "previous": 0.25226862980769227, + "256": 0.2515625, + "512": 0.2510216346153846 + }, + "selected": "512" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "previous": 0.2569711538461539, + "256": 0.2557542067307692, + "512": 0.256640625 + }, + "selected": "256" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "previous": 0.23574218750000003, + "256": 0.2356820913461538, + "512": 0.23511117788461539 + }, + "selected": "512" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "previous": 0.24453125000000003, + "256": 0.24275841346153845, + "512": 0.24224759615384617 + }, + "selected": "512" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "previous": 0.25310997596153845, + "256": 0.2524188701923077, + "512": 0.2513822115384615 + }, + "selected": "512" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "previous": 0.24082031250000002, + "256": 0.2387469951923077, + "512": 0.23933293269230768 + }, + "selected": "256" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "previous": 0.24064002403846155, + "256": 0.24053485576923073, + "512": 0.24002403846153844 + }, + "selected": "512" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "previous": 0.2367638221153846, + "256": 0.23635817307692306, + "512": 0.23584735576923077 + }, + "selected": "512" + } + ], + "initial_validation_subset": "First 512 validation rows/condition; then both trained checkpoints evaluated on full validation", + "features": "40 detection bits within five frames and 57 static error/geometry features; detector indices come from the ideal geometry/DEM; sample IDs are not features", + "derivative_check": "Relative error 1.16e-7 versus automatic differentiation on a small d3 example" + }, + "previous_package_validation": { + "performance": 0.7671762319711538, + "failure_by_distance": { + "d3": 0.2398212139423077, + "d5": 0.22582632211538461 + }, + "scorer": "Supplied qecbench.scoring on all 130 validation conditions and 665600 shots", + "contract_checks": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "shots": 1, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d3_r25_center_5_3", + "shots": 37, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d3_r13_center_5_7", + "shots": 1025, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 7, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 257, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 17, + "maximum_probability_difference": 0.0 + } + ], + "prediction_generation": "All26 d5 conditions replayed from the assembled package; unchanged d3 predictions retained. Full trusted scoring and relocated arbitrary-ID/subset checks.", + "runtime_evidence": "Full133120-shot d5 replay took 339.68s on one H100; d3 paths unchanged from the recorded incumbent.", + "d5_validation_runtime_seconds": 339.67785930633545, + "contract_execution": { + "requested_verifier_uid": 10001, + "effective_uid": 1000, + "effective_gid": 1000, + "supplementary_groups": [], + "identity_status": "Development process is already unprivileged and cannot change UID; verifier UID10001 was not executed", + "model_and_input_copy": "Owned by development UID 1000,directories0555,files0444,relocated under a fresh accessible temporary parent", + "output_directory": "Owned by execution UID 1000,mode0700", + "PYTHONPATH": "", + "backend": "Runtime default; full selected subset cases", + "scope": "Local contract check; not a Docker/network/mount-isolation test" + } + }, + "previous_model_manifest_sha256": "d8bed57d4619a87ad756d2347796e396b3169d4146f69ab426f99f9934ef1a8f", + "contextual_updates": [ + { + "name": "large512", + "training": { + "initialization": "This session's pilot checkpoint 512; original random initialization seed 20261025", + "run_config": { + "steps": 2048, + "batch": 2048, + "output": "/run-state/workspace/research/learned_exact/continuation1", + "validation_shots": 1024, + "init_weights": "/workspace/research/learned_exact/pilot/weights-512.npz", + "learning_rate": 0.001, + "eval_every": 512, + "seed": 20261028, + "validation_batch": 1024, + "uniform_validation": true, + "original_random_seed": 20261025, + "starting_checkpoint_sha256": "b14f7bf663b0484b9a79a759455ad09aca456f83a7cc29ed2e9e1d210683c180", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "validation_manifest_sha256": "482bb7268c6c827ebbf1f756ee6994750acfcd011adab08eaa2ada703e5faea1" + }, + "completed_checkpoint_steps": 512, + "new_sampled_training_shots": 1048576, + "optimizer": "AdamW 1e-3, weight decay 1e-4, global norm clip 1; optimizer reset at phase start", + "data": "Uniform sampling over all 104 d3 training conditions; training rows only", + "selection": "Checkpoint 512 evaluated on all 532480 d3 validation shots", + "full_validation_failure": 0.2428973858173077, + "termination": "Saved checkpoint 512, then stopped to restart with corrected validation NLL reporting. Any later in-flight updates were discarded.", + "reporting_correction": "Recomputed with float labels from the full checkpoint predictions; original in-flight diagnostic negated uint8 labels. Training loss and failure metrics were unaffected.", + "test_data_used": false + }, + "selection": "Minimum full validation mean failure per group between the incumbent and this trained checkpoint", + "history": [ + { + "group": "d3_bX_center_3_5", + "previous_failure": 0.2510216346153846, + "candidate_failure": 0.2491436298076923, + "selected_new": true + }, + { + "group": "d3_bX_center_5_3", + "previous_failure": 0.2557542067307692, + "candidate_failure": 0.256640625, + "selected_new": false + }, + { + "group": "d3_bX_center_5_7", + "previous_failure": 0.23511117788461539, + "candidate_failure": 0.23515625, + "selected_new": false + }, + { + "group": "d3_bX_center_7_5", + "previous_failure": 0.24224759615384617, + "candidate_failure": 0.2403996394230769, + "selected_new": true + }, + { + "group": "d3_bZ_center_3_5", + "previous_failure": 0.2513822115384615, + "candidate_failure": 0.24893329326923078, + "selected_new": true + }, + { + "group": "d3_bZ_center_5_3", + "previous_failure": 0.2387469951923077, + "candidate_failure": 0.23925781249999997, + "selected_new": false + }, + { + "group": "d3_bZ_center_5_7", + "previous_failure": 0.24002403846153844, + "candidate_failure": 0.23885216346153845, + "selected_new": true + }, + { + "group": "d3_bZ_center_7_5", + "previous_failure": 0.23584735576923077, + "candidate_failure": 0.23479567307692306, + "selected_new": true + }, + { + "group": "d5_bX_center_5_5", + "previous_failure": 0.24024939903846157, + "candidate_failure": 0.24024939903846157, + "selected_new": false + }, + { + "group": "d5_bZ_center_5_5", + "previous_failure": 0.22627704326923076, + "candidate_failure": 0.22627704326923076, + "selected_new": false + } + ], + "source_checkpoint_sha256": "7a7579b1bded95bcea7b1d26b2cf26de333c1a0f417fac6a0143eeb3a0c93aa2" + }, + { + "name": "continuation2", + "training_run": { + "initialization": "Continue from this session's trained checkpoint", + "original_initialization": "Random variance-scaled normal first two layers, random Normal(0,.001) output; zero biases; seed 20261025", + "architecture": "Two 32-unit SiLU layers, output 2*tanh correction to original hyperedge logit; 40 local detection bits and 57 static error/geometry features", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "steps": 1536, + "batch_size": 2048, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.001, + "sampling_seed": 20261028, + "optimizer_restored": true, + "rng_restored": true, + "session_trained_starting_checkpoint": "/workspace/research/learned_exact/continuation1/weights-512.npz", + "starting_checkpoint_sha256": "7a7579b1bded95bcea7b1d26b2cf26de333c1a0f417fac6a0143eeb3a0c93aa2", + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.05675870552659035, + "error": 0.0166015625, + "gradient_norm": 0.007466103881597519, + "elapsed": 30.636001586914062 + }, + { + "step": 16, + "loss": 0.44421544671058655, + "error": 0.22412109375, + "gradient_norm": 0.029868461191654205, + "elapsed": 35.424378871917725 + }, + { + "step": 32, + "loss": 0.46525052189826965, + "error": 0.23681640625, + "gradient_norm": 0.022205814719200134, + "elapsed": 40.526121854782104 + }, + { + "step": 48, + "loss": 0.6177924871444702, + "error": 0.3544921875, + "gradient_norm": 0.022866439074277878, + "elapsed": 45.67929220199585 + }, + { + "step": 64, + "loss": 0.5046484470367432, + "error": 0.2666015625, + "gradient_norm": 0.0222865492105484, + "elapsed": 50.80926203727722 + }, + { + "step": 80, + "loss": 0.638379693031311, + "error": 0.41064453125, + "gradient_norm": 0.012645655311644077, + "elapsed": 55.93321657180786 + }, + { + "step": 96, + "loss": 0.18619170784950256, + "error": 0.0732421875, + "gradient_norm": 0.012208878062665462, + "elapsed": 61.002137899398804 + }, + { + "step": 112, + "loss": 0.4269826412200928, + "error": 0.2109375, + "gradient_norm": 0.021279584616422653, + "elapsed": 66.13066720962524 + }, + { + "step": 128, + "loss": 0.47232550382614136, + "error": 0.25244140625, + "gradient_norm": 0.03405005484819412, + "elapsed": 85.5297167301178 + }, + { + "step": 144, + "loss": 0.2528073787689209, + "error": 0.11279296875, + "gradient_norm": 0.013145577162504196, + "elapsed": 90.68786001205444 + }, + { + "step": 160, + "loss": 0.5877531170845032, + "error": 0.35595703125, + "gradient_norm": 0.019021881744265556, + "elapsed": 95.76396131515503 + }, + { + "step": 176, + "loss": 0.45082807540893555, + "error": 0.2314453125, + "gradient_norm": 0.023904386907815933, + "elapsed": 100.9375216960907 + }, + { + "step": 192, + "loss": 0.4175146222114563, + "error": 0.19921875, + "gradient_norm": 0.021031895652413368, + "elapsed": 105.98947334289551 + }, + { + "step": 208, + "loss": 0.5424385070800781, + "error": 0.30078125, + "gradient_norm": 0.01396750845015049, + "elapsed": 111.17936706542969 + }, + { + "step": 224, + "loss": 0.29304587841033936, + "error": 0.1259765625, + "gradient_norm": 0.014725692570209503, + "elapsed": 116.36282753944397 + }, + { + "step": 240, + "loss": 0.056691475212574005, + "error": 0.015625, + "gradient_norm": 0.002859376836568117, + "elapsed": 121.54807162284851 + }, + { + "step": 256, + "loss": 0.17413178086280823, + "error": 0.06689453125, + "gradient_norm": 0.02666049636900425, + "elapsed": 126.718514919281 + }, + { + "step": 272, + "loss": 0.6115483641624451, + "error": 0.3466796875, + "gradient_norm": 0.03685307130217552, + "elapsed": 131.77990794181824 + }, + { + "step": 288, + "loss": 0.5973552465438843, + "error": 0.3349609375, + "gradient_norm": 0.02574622817337513, + "elapsed": 138.0202260017395 + }, + { + "step": 304, + "loss": 0.18595321476459503, + "error": 0.0732421875, + "gradient_norm": 0.012303492985665798, + "elapsed": 144.16412949562073 + }, + { + "step": 320, + "loss": 0.5418114066123962, + "error": 0.30126953125, + "gradient_norm": 0.018640751019120216, + "elapsed": 150.969500541687 + }, + { + "step": 336, + "loss": 0.5024716258049011, + "error": 0.26708984375, + "gradient_norm": 0.011490182019770145, + "elapsed": 158.32421374320984 + }, + { + "step": 352, + "loss": 0.5002061128616333, + "error": 0.255859375, + "gradient_norm": 0.03905056416988373, + "elapsed": 165.20316648483276 + }, + { + "step": 368, + "loss": 0.5892350077629089, + "error": 0.33837890625, + "gradient_norm": 0.046964384615421295, + "elapsed": 171.98852562904358 + }, + { + "step": 384, + "loss": 0.526427149772644, + "error": 0.2900390625, + "gradient_norm": 0.021478066220879555, + "elapsed": 178.02048754692078 + }, + { + "step": 400, + "loss": 0.5563177466392517, + "error": 0.306640625, + "gradient_norm": 0.024061864241957664, + "elapsed": 184.09671759605408 + }, + { + "step": 416, + "loss": 0.060019996017217636, + "error": 0.0205078125, + "gradient_norm": 0.006343841087073088, + "elapsed": 190.31260657310486 + }, + { + "step": 432, + "loss": 0.5484405755996704, + "error": 0.3115234375, + "gradient_norm": 0.020139696076512337, + "elapsed": 195.41702342033386 + }, + { + "step": 448, + "loss": 0.6163954138755798, + "error": 0.37646484375, + "gradient_norm": 0.011381164193153381, + "elapsed": 200.53582382202148 + }, + { + "step": 464, + "loss": 0.47678378224372864, + "error": 0.25927734375, + "gradient_norm": 0.03807748854160309, + "elapsed": 205.69636607170105 + }, + { + "step": 480, + "loss": 0.5176759362220764, + "error": 0.2705078125, + "gradient_norm": 0.017451826483011246, + "elapsed": 210.7581787109375 + }, + { + "step": 496, + "loss": 0.3626214563846588, + "error": 0.16455078125, + "gradient_norm": 0.019456032663583755, + "elapsed": 215.82069444656372 + }, + { + "step": 512, + "loss": 0.6202600598335266, + "error": 0.35302734375, + "gradient_norm": 0.013814727775752544, + "elapsed": 220.93863129615784 + }, + { + "step": 528, + "loss": 0.5610182285308838, + "error": 0.29833984375, + "gradient_norm": 0.03955027833580971, + "elapsed": 238.0407817363739 + }, + { + "step": 544, + "loss": 0.332148015499115, + "error": 0.15380859375, + "gradient_norm": 0.013710199855268002, + "elapsed": 243.12822461128235 + }, + { + "step": 560, + "loss": 0.4678276777267456, + "error": 0.23974609375, + "gradient_norm": 0.016155347228050232, + "elapsed": 248.3209776878357 + }, + { + "step": 576, + "loss": 0.6166238784790039, + "error": 0.3740234375, + "gradient_norm": 0.017382115125656128, + "elapsed": 253.49981307983398 + }, + { + "step": 592, + "loss": 0.6137416362762451, + "error": 0.373046875, + "gradient_norm": 0.007819767110049725, + "elapsed": 258.68269968032837 + }, + { + "step": 608, + "loss": 0.2780998647212982, + "error": 0.126953125, + "gradient_norm": 0.03436559438705444, + "elapsed": 263.82615661621094 + }, + { + "step": 624, + "loss": 0.6059691309928894, + "error": 0.3623046875, + "gradient_norm": 0.010842837393283844, + "elapsed": 268.9659583568573 + }, + { + "step": 640, + "loss": 0.058036163449287415, + "error": 0.02001953125, + "gradient_norm": 0.004723707213997841, + "elapsed": 274.09823632240295 + }, + { + "step": 656, + "loss": 0.6149133443832397, + "error": 0.37255859375, + "gradient_norm": 0.008533184416592121, + "elapsed": 279.26951336860657 + }, + { + "step": 672, + "loss": 0.3015868663787842, + "error": 0.1318359375, + "gradient_norm": 0.012536457739770412, + "elapsed": 284.41987442970276 + }, + { + "step": 688, + "loss": 0.16231489181518555, + "error": 0.06494140625, + "gradient_norm": 0.0067833056673407555, + "elapsed": 289.56297039985657 + }, + { + "step": 704, + "loss": 0.04929213970899582, + "error": 0.015625, + "gradient_norm": 0.005747381132096052, + "elapsed": 294.6839826107025 + }, + { + "step": 720, + "loss": 0.5615487098693848, + "error": 0.31689453125, + "gradient_norm": 0.02115021087229252, + "elapsed": 299.8546531200409 + }, + { + "step": 736, + "loss": 0.6306260228157043, + "error": 0.3759765625, + "gradient_norm": 0.02629203163087368, + "elapsed": 305.0923271179199 + }, + { + "step": 752, + "loss": 0.03828414902091026, + "error": 0.0126953125, + "gradient_norm": 0.008905005641281605, + "elapsed": 310.5417342185974 + }, + { + "step": 768, + "loss": 0.48764050006866455, + "error": 0.2626953125, + "gradient_norm": 0.024667929857969284, + "elapsed": 316.01200103759766 + }, + { + "step": 784, + "loss": 0.5836235284805298, + "error": 0.3505859375, + "gradient_norm": 0.023319393396377563, + "elapsed": 321.33294105529785 + }, + { + "step": 800, + "loss": 0.5693534016609192, + "error": 0.31396484375, + "gradient_norm": 0.048126742243766785, + "elapsed": 326.52227997779846 + }, + { + "step": 816, + "loss": 0.5710973739624023, + "error": 0.33349609375, + "gradient_norm": 0.022565416991710663, + "elapsed": 331.62225437164307 + }, + { + "step": 832, + "loss": 0.2818760275840759, + "error": 0.11865234375, + "gradient_norm": 0.025756066665053368, + "elapsed": 336.7874104976654 + }, + { + "step": 848, + "loss": 0.6127357482910156, + "error": 0.3583984375, + "gradient_norm": 0.020077377557754517, + "elapsed": 341.92783546447754 + }, + { + "step": 864, + "loss": 0.5109728574752808, + "error": 0.26171875, + "gradient_norm": 0.022484255954623222, + "elapsed": 347.0137662887573 + }, + { + "step": 880, + "loss": 0.16892661154270172, + "error": 0.06103515625, + "gradient_norm": 0.01363676693290472, + "elapsed": 352.0768094062805 + }, + { + "step": 896, + "loss": 0.593660831451416, + "error": 0.34423828125, + "gradient_norm": 0.01379447989165783, + "elapsed": 357.1796865463257 + }, + { + "step": 912, + "loss": 0.635499119758606, + "error": 0.39306640625, + "gradient_norm": 0.012278803624212742, + "elapsed": 362.29547691345215 + }, + { + "step": 928, + "loss": 0.3966389000415802, + "error": 0.19482421875, + "gradient_norm": 0.019856182858347893, + "elapsed": 367.3532474040985 + }, + { + "step": 944, + "loss": 0.05235423520207405, + "error": 0.01611328125, + "gradient_norm": 0.005415339022874832, + "elapsed": 372.4516806602478 + }, + { + "step": 960, + "loss": 0.5913074612617493, + "error": 0.3330078125, + "gradient_norm": 0.021171825006604195, + "elapsed": 377.5324194431305 + }, + { + "step": 976, + "loss": 0.6479356288909912, + "error": 0.41650390625, + "gradient_norm": 0.02845155820250511, + "elapsed": 382.5862877368927 + }, + { + "step": 992, + "loss": 0.5470497608184814, + "error": 0.30908203125, + "gradient_norm": 0.02726798877120018, + "elapsed": 387.6820628643036 + }, + { + "step": 1008, + "loss": 0.5729615688323975, + "error": 0.32861328125, + "gradient_norm": 0.011548872105777264, + "elapsed": 392.7741017341614 + }, + { + "step": 1024, + "loss": 0.0691118910908699, + "error": 0.0205078125, + "gradient_norm": 0.009204022586345673, + "elapsed": 397.8671176433563 + }, + { + "step": 1040, + "loss": 0.5171630382537842, + "error": 0.2685546875, + "gradient_norm": 0.015718232840299606, + "elapsed": 415.6616735458374 + }, + { + "step": 1056, + "loss": 0.6505192518234253, + "error": 0.39990234375, + "gradient_norm": 0.023937702178955078, + "elapsed": 420.7646098136902 + }, + { + "step": 1072, + "loss": 0.5660485625267029, + "error": 0.32666015625, + "gradient_norm": 0.026201115921139717, + "elapsed": 426.09313225746155 + }, + { + "step": 1088, + "loss": 0.4945259094238281, + "error": 0.25048828125, + "gradient_norm": 0.014495921321213245, + "elapsed": 431.2104251384735 + }, + { + "step": 1104, + "loss": 0.5695121884346008, + "error": 0.33837890625, + "gradient_norm": 0.029924258589744568, + "elapsed": 436.3099756240845 + }, + { + "step": 1120, + "loss": 0.3591366112232208, + "error": 0.16015625, + "gradient_norm": 0.017803259193897247, + "elapsed": 441.4024531841278 + }, + { + "step": 1136, + "loss": 0.3302019536495209, + "error": 0.1572265625, + "gradient_norm": 0.01632549799978733, + "elapsed": 446.55403757095337 + }, + { + "step": 1152, + "loss": 0.6093119382858276, + "error": 0.35107421875, + "gradient_norm": 0.014888457022607327, + "elapsed": 451.6241090297699 + }, + { + "step": 1168, + "loss": 0.3500004708766937, + "error": 0.1650390625, + "gradient_norm": 0.011492405086755753, + "elapsed": 456.7753965854645 + }, + { + "step": 1184, + "loss": 0.3738429844379425, + "error": 0.1845703125, + "gradient_norm": 0.015336514450609684, + "elapsed": 461.90868854522705 + }, + { + "step": 1200, + "loss": 0.2892451882362366, + "error": 0.12890625, + "gradient_norm": 0.010124214924871922, + "elapsed": 467.1151931285858 + }, + { + "step": 1216, + "loss": 0.45089617371559143, + "error": 0.23046875, + "gradient_norm": 0.03627275303006172, + "elapsed": 472.30455207824707 + }, + { + "step": 1232, + "loss": 0.6207081079483032, + "error": 0.36376953125, + "gradient_norm": 0.028164058923721313, + "elapsed": 477.4041998386383 + }, + { + "step": 1248, + "loss": 0.6022387742996216, + "error": 0.32470703125, + "gradient_norm": 0.05243176594376564, + "elapsed": 482.5445365905762 + }, + { + "step": 1264, + "loss": 0.6383136510848999, + "error": 0.38818359375, + "gradient_norm": 0.021598732098937035, + "elapsed": 488.21457719802856 + }, + { + "step": 1280, + "loss": 0.28611207008361816, + "error": 0.13037109375, + "gradient_norm": 0.010211448185145855, + "elapsed": 494.3161232471466 + }, + { + "step": 1296, + "loss": 0.5970274209976196, + "error": 0.35009765625, + "gradient_norm": 0.025076791644096375, + "elapsed": 500.2585813999176 + }, + { + "step": 1312, + "loss": 0.48383909463882446, + "error": 0.2529296875, + "gradient_norm": 0.02830139547586441, + "elapsed": 505.9930474758148 + }, + { + "step": 1328, + "loss": 0.6087884902954102, + "error": 0.365234375, + "gradient_norm": 0.01881619170308113, + "elapsed": 512.0680301189423 + }, + { + "step": 1344, + "loss": 0.49332645535469055, + "error": 0.25634765625, + "gradient_norm": 0.02215457707643509, + "elapsed": 517.9840953350067 + }, + { + "step": 1360, + "loss": 0.6202782392501831, + "error": 0.36767578125, + "gradient_norm": 0.018839120864868164, + "elapsed": 524.07217669487 + }, + { + "step": 1376, + "loss": 0.5857731699943542, + "error": 0.3330078125, + "gradient_norm": 0.015682006254792213, + "elapsed": 529.8370056152344 + }, + { + "step": 1392, + "loss": 0.52056485414505, + "error": 0.263671875, + "gradient_norm": 0.02431550808250904, + "elapsed": 535.9721219539642 + }, + { + "step": 1408, + "loss": 0.6433448791503906, + "error": 0.40625, + "gradient_norm": 0.016954610124230385, + "elapsed": 542.0041825771332 + }, + { + "step": 1424, + "loss": 0.6105660200119019, + "error": 0.35107421875, + "gradient_norm": 0.007737957406789064, + "elapsed": 547.4241607189178 + }, + { + "step": 1440, + "loss": 0.27237576246261597, + "error": 0.12451171875, + "gradient_norm": 0.01314462162554264, + "elapsed": 553.5436873435974 + }, + { + "step": 1456, + "loss": 0.5954712629318237, + "error": 0.3623046875, + "gradient_norm": 0.03746134042739868, + "elapsed": 558.7123465538025 + }, + { + "step": 1472, + "loss": 0.4519508481025696, + "error": 0.2255859375, + "gradient_norm": 0.010652865283191204, + "elapsed": 563.8585436344147 + }, + { + "step": 1488, + "loss": 0.41647869348526, + "error": 0.212890625, + "gradient_norm": 0.028575479984283447, + "elapsed": 569.0573513507843 + }, + { + "step": 1504, + "loss": 0.4384400248527527, + "error": 0.21337890625, + "gradient_norm": 0.017627721652388573, + "elapsed": 574.296462059021 + }, + { + "step": 1520, + "loss": 0.6105232238769531, + "error": 0.37109375, + "gradient_norm": 0.016302449628710747, + "elapsed": 579.4641361236572 + }, + { + "step": 1536, + "loss": 0.6215546131134033, + "error": 0.39013671875, + "gradient_norm": 0.032154034823179245, + "elapsed": 584.5684258937836 + } + ] + }, + "selected_checkpoint_steps": [ + 512, + 1024, + 1536 + ], + "checkpoint_records": { + "1536": { + "step": 1536, + "new_training_shots": 3145728, + "weights": "weights-1536.npz", + "weights_sha256": "785132032c12fa38abbb1103774d91b41828fdc5027e1fe4d42053476eb28199", + "validation": "validation-1536.json", + "complete": true + }, + "512": { + "step": 512, + "new_training_shots": 1048576, + "weights": "weights-512.npz", + "weights_sha256": "e9ebeb958eec680c5458b3a5c39aecf0a21c926aee816517b5f9d3bac5815d7f", + "validation": "validation-512.json", + "complete": true + }, + "1024": { + "step": 1024, + "new_training_shots": 2097152, + "weights": "weights-1024.npz", + "weights_sha256": "f45c568b13c92eb4e768146debbc8c50a8ad51882523938932ba26f4afde66f2", + "validation": "validation-1024.json", + "complete": true + } + }, + "selection": "Minimum full-validation mean failure per group among incumbent and listed session-trained checkpoints", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "incumbent": 0.2491436298076923, + "512": 0.2478215144230769, + "1024": 0.24774639423076922, + "1536": 0.2476862980769231 + }, + "selected": "1536" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "incumbent": 0.2557542067307692, + "512": 0.2544320913461538, + "1024": 0.2548527644230769, + "1536": 0.2545673076923076 + }, + "selected": "512" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "incumbent": 0.23511117788461539, + "512": 0.23602764423076927, + "1024": 0.23553185096153847, + "1536": 0.2345402644230769 + }, + "selected": "1536" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "incumbent": 0.2403996394230769, + "512": 0.23999399038461539, + "1024": 0.24008413461538464, + "1536": 0.2401141826923077 + }, + "selected": "512" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "incumbent": 0.24893329326923078, + "512": 0.24894831730769235, + "1024": 0.24735576923076924, + "1536": 0.24664963942307694 + }, + "selected": "1536" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "incumbent": 0.2387469951923077, + "512": 0.23849158653846156, + "1024": 0.23789062500000002, + "1536": 0.2381610576923077 + }, + "selected": "1024" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "incumbent": 0.23885216346153845, + "512": 0.23807091346153844, + "1024": 0.2377704326923077, + "1536": 0.23733473557692303 + }, + "selected": "1536" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "incumbent": 0.23479567307692306, + "512": 0.2340895432692308, + "1024": 0.2340444711538461, + "1536": 0.23431490384615386 + }, + "selected": "1024" + }, + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.24024939903846157 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22627704326923076 + }, + "selected": "incumbent" + } + ] + }, + { + "name": "rich1", + "training_run": { + "initialization": "Random initialization in this session", + "original_initialization": "Random variance-scaled normal first two layers, random Normal(0,.001) output; zero biases; seed 20261030", + "architecture": "Two 128-unit SiLU layers, output 4*tanh correction to original hyperedge logit; 40 local events, 40 reconstructed measurements, 8 per-stabilizer full-shot densities and 57 static features", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "steps": 1024, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.001, + "sampling_seed": 20261030, + "optimizer_restored": false, + "rng_restored": false, + "session_trained_starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.1747799664735794, + "error": 0.068359375, + "gradient_norm": 0.03163275867700577, + "elapsed": 30.666016340255737 + }, + { + "step": 16, + "loss": 0.5729950666427612, + "error": 0.30859375, + "gradient_norm": 0.03532477840781212, + "elapsed": 34.992138385772705 + }, + { + "step": 32, + "loss": 0.33759093284606934, + "error": 0.1435546875, + "gradient_norm": 0.03938521817326546, + "elapsed": 40.51379442214966 + }, + { + "step": 48, + "loss": 0.574704647064209, + "error": 0.3212890625, + "gradient_norm": 0.03584429249167442, + "elapsed": 46.82174754142761 + }, + { + "step": 64, + "loss": 0.6351712942123413, + "error": 0.4072265625, + "gradient_norm": 0.027485841885209084, + "elapsed": 52.75151348114014 + }, + { + "step": 80, + "loss": 0.36342084407806396, + "error": 0.1708984375, + "gradient_norm": 0.040388718247413635, + "elapsed": 58.42134428024292 + }, + { + "step": 96, + "loss": 0.613252580165863, + "error": 0.3525390625, + "gradient_norm": 0.035148631781339645, + "elapsed": 64.40935254096985 + }, + { + "step": 112, + "loss": 0.6042842864990234, + "error": 0.3564453125, + "gradient_norm": 0.06634438037872314, + "elapsed": 70.4053041934967 + }, + { + "step": 128, + "loss": 0.4366868734359741, + "error": 0.20703125, + "gradient_norm": 0.040233220905065536, + "elapsed": 76.10137701034546 + }, + { + "step": 144, + "loss": 0.340861976146698, + "error": 0.154296875, + "gradient_norm": 0.03881179168820381, + "elapsed": 81.10126686096191 + }, + { + "step": 160, + "loss": 0.5801218748092651, + "error": 0.32421875, + "gradient_norm": 0.06090407446026802, + "elapsed": 86.1252555847168 + }, + { + "step": 176, + "loss": 0.37582841515541077, + "error": 0.19140625, + "gradient_norm": 0.06935373693704605, + "elapsed": 91.53376078605652 + }, + { + "step": 192, + "loss": 0.5213879346847534, + "error": 0.291015625, + "gradient_norm": 0.038788966834545135, + "elapsed": 96.78960609436035 + }, + { + "step": 208, + "loss": 0.26441627740859985, + "error": 0.115234375, + "gradient_norm": 0.04845435172319412, + "elapsed": 101.85743975639343 + }, + { + "step": 224, + "loss": 0.4369240701198578, + "error": 0.2119140625, + "gradient_norm": 0.098305843770504, + "elapsed": 106.94148802757263 + }, + { + "step": 240, + "loss": 0.5520763397216797, + "error": 0.3037109375, + "gradient_norm": 0.04845161736011505, + "elapsed": 112.27297902107239 + }, + { + "step": 256, + "loss": 0.595374345779419, + "error": 0.3369140625, + "gradient_norm": 0.03840416297316551, + "elapsed": 117.4812536239624 + }, + { + "step": 272, + "loss": 0.2569020390510559, + "error": 0.103515625, + "gradient_norm": 0.050126779824495316, + "elapsed": 137.86142945289612 + }, + { + "step": 288, + "loss": 0.32830360531806946, + "error": 0.1455078125, + "gradient_norm": 0.035532038658857346, + "elapsed": 142.83670139312744 + }, + { + "step": 304, + "loss": 0.6040379405021667, + "error": 0.36328125, + "gradient_norm": 0.0313950814306736, + "elapsed": 148.05078554153442 + }, + { + "step": 320, + "loss": 0.35434311628341675, + "error": 0.1748046875, + "gradient_norm": 0.03184249624609947, + "elapsed": 153.22213292121887 + }, + { + "step": 336, + "loss": 0.2326659858226776, + "error": 0.099609375, + "gradient_norm": 0.06624855101108551, + "elapsed": 158.455664396286 + }, + { + "step": 352, + "loss": 0.06233043968677521, + "error": 0.017578125, + "gradient_norm": 0.02635284699499607, + "elapsed": 163.10541248321533 + }, + { + "step": 368, + "loss": 0.31427502632141113, + "error": 0.1435546875, + "gradient_norm": 0.04170582816004753, + "elapsed": 167.78928112983704 + }, + { + "step": 384, + "loss": 0.41268765926361084, + "error": 0.19921875, + "gradient_norm": 0.10103361308574677, + "elapsed": 172.34387755393982 + }, + { + "step": 400, + "loss": 0.42649346590042114, + "error": 0.2119140625, + "gradient_norm": 0.03481302782893181, + "elapsed": 176.83626103401184 + }, + { + "step": 416, + "loss": 0.6373635530471802, + "error": 0.4013671875, + "gradient_norm": 0.06979350745677948, + "elapsed": 181.35168766975403 + }, + { + "step": 432, + "loss": 0.17961856722831726, + "error": 0.072265625, + "gradient_norm": 0.018565824255347252, + "elapsed": 185.80416321754456 + }, + { + "step": 448, + "loss": 0.5501771569252014, + "error": 0.287109375, + "gradient_norm": 0.04828835278749466, + "elapsed": 190.30530858039856 + }, + { + "step": 464, + "loss": 0.5648394823074341, + "error": 0.2978515625, + "gradient_norm": 0.07398489862680435, + "elapsed": 194.7985327243805 + }, + { + "step": 480, + "loss": 0.5675262212753296, + "error": 0.3125, + "gradient_norm": 0.036255236715078354, + "elapsed": 199.30496096611023 + }, + { + "step": 496, + "loss": 0.6156162023544312, + "error": 0.3779296875, + "gradient_norm": 0.02318546548485756, + "elapsed": 203.8355917930603 + }, + { + "step": 512, + "loss": 0.0660151019692421, + "error": 0.021484375, + "gradient_norm": 0.020883027464151382, + "elapsed": 208.32652711868286 + }, + { + "step": 528, + "loss": 0.6096083521842957, + "error": 0.37890625, + "gradient_norm": 0.04742306470870972, + "elapsed": 225.1866319179535 + }, + { + "step": 544, + "loss": 0.3829265236854553, + "error": 0.18359375, + "gradient_norm": 0.05981605872511864, + "elapsed": 229.68251276016235 + }, + { + "step": 560, + "loss": 0.537099301815033, + "error": 0.2900390625, + "gradient_norm": 0.0949595719575882, + "elapsed": 234.20215129852295 + }, + { + "step": 576, + "loss": 0.5903713703155518, + "error": 0.3447265625, + "gradient_norm": 0.06430540233850479, + "elapsed": 238.70998644828796 + }, + { + "step": 592, + "loss": 0.5619152188301086, + "error": 0.298828125, + "gradient_norm": 0.03404757007956505, + "elapsed": 243.21307158470154 + }, + { + "step": 608, + "loss": 0.5997255444526672, + "error": 0.3623046875, + "gradient_norm": 0.03946321830153465, + "elapsed": 247.7153992652893 + }, + { + "step": 624, + "loss": 0.5695509910583496, + "error": 0.310546875, + "gradient_norm": 0.02815800905227661, + "elapsed": 252.3102250099182 + }, + { + "step": 640, + "loss": 0.5901973247528076, + "error": 0.34765625, + "gradient_norm": 0.04673359915614128, + "elapsed": 256.89224338531494 + }, + { + "step": 656, + "loss": 0.621924877166748, + "error": 0.37890625, + "gradient_norm": 0.04227908328175545, + "elapsed": 261.43869185447693 + }, + { + "step": 672, + "loss": 0.610299825668335, + "error": 0.35546875, + "gradient_norm": 0.036825064569711685, + "elapsed": 265.97225284576416 + }, + { + "step": 688, + "loss": 0.5249245166778564, + "error": 0.2841796875, + "gradient_norm": 0.0948338434100151, + "elapsed": 270.4997045993805 + }, + { + "step": 704, + "loss": 0.2573642134666443, + "error": 0.111328125, + "gradient_norm": 0.055987801402807236, + "elapsed": 275.0399034023285 + }, + { + "step": 720, + "loss": 0.04867870360612869, + "error": 0.0146484375, + "gradient_norm": 0.03132430091500282, + "elapsed": 279.55093908309937 + }, + { + "step": 736, + "loss": 0.24808242917060852, + "error": 0.1015625, + "gradient_norm": 0.051910530775785446, + "elapsed": 284.08127522468567 + }, + { + "step": 752, + "loss": 0.4981001615524292, + "error": 0.2529296875, + "gradient_norm": 0.06427812576293945, + "elapsed": 288.70672821998596 + }, + { + "step": 768, + "loss": 0.5241370797157288, + "error": 0.28125, + "gradient_norm": 0.10227487236261368, + "elapsed": 293.331086397171 + }, + { + "step": 784, + "loss": 0.6427845358848572, + "error": 0.400390625, + "gradient_norm": 0.08984753489494324, + "elapsed": 311.0226716995239 + }, + { + "step": 800, + "loss": 0.5990085601806641, + "error": 0.3544921875, + "gradient_norm": 0.08950027078390121, + "elapsed": 315.6725699901581 + }, + { + "step": 816, + "loss": 0.5930870771408081, + "error": 0.353515625, + "gradient_norm": 0.03096434287726879, + "elapsed": 320.38578844070435 + }, + { + "step": 832, + "loss": 0.5945324897766113, + "error": 0.359375, + "gradient_norm": 0.052297625690698624, + "elapsed": 325.3292770385742 + }, + { + "step": 848, + "loss": 0.6031227111816406, + "error": 0.3642578125, + "gradient_norm": 0.032976675778627396, + "elapsed": 330.2292652130127 + }, + { + "step": 864, + "loss": 0.3953525125980377, + "error": 0.1748046875, + "gradient_norm": 0.07015999406576157, + "elapsed": 335.1212799549103 + }, + { + "step": 880, + "loss": 0.4324202835559845, + "error": 0.2080078125, + "gradient_norm": 0.1018647849559784, + "elapsed": 339.9696366786957 + }, + { + "step": 896, + "loss": 0.5024446249008179, + "error": 0.265625, + "gradient_norm": 0.03973893076181412, + "elapsed": 344.8794775009155 + }, + { + "step": 912, + "loss": 0.5731178522109985, + "error": 0.33203125, + "gradient_norm": 0.047838907688856125, + "elapsed": 349.57729148864746 + }, + { + "step": 928, + "loss": 0.6279090642929077, + "error": 0.412109375, + "gradient_norm": 0.030738679692149162, + "elapsed": 354.4736604690552 + }, + { + "step": 944, + "loss": 0.6028326153755188, + "error": 0.341796875, + "gradient_norm": 0.04459983482956886, + "elapsed": 359.2764792442322 + }, + { + "step": 960, + "loss": 0.19082097709178925, + "error": 0.0791015625, + "gradient_norm": 0.02478513866662979, + "elapsed": 364.1252644062042 + }, + { + "step": 976, + "loss": 0.443341463804245, + "error": 0.2197265625, + "gradient_norm": 0.14411240816116333, + "elapsed": 368.8472623825073 + }, + { + "step": 992, + "loss": 0.5665505528450012, + "error": 0.3125, + "gradient_norm": 0.06498897075653076, + "elapsed": 373.6812598705292 + }, + { + "step": 1008, + "loss": 0.4306175112724304, + "error": 0.1875, + "gradient_norm": 0.04873151704668999, + "elapsed": 378.56014752388 + }, + { + "step": 1024, + "loss": 0.46258389949798584, + "error": 0.244140625, + "gradient_norm": 0.09452047199010849, + "elapsed": 383.46526074409485 + } + ] + }, + "selected_checkpoint_steps": [ + 1024 + ], + "checkpoint_records": { + "1024": { + "step": 1024, + "new_training_shots": 1048576, + "weights": "weights-1024.npz", + "weights_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "validation": "validation-1024.json", + "complete": true + } + }, + "selection": "Minimum full-validation mean failure per group among incumbent and listed session-trained checkpoints; when listed, blend candidates average incumbent and new probabilities equally", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "incumbent": 0.2476862980769231, + "512": 0.24981971153846153, + "1024": 0.24861778846153845, + "blend-512": 0.24816706730769234, + "blend-1024": 0.24764122596153845 + }, + "selected": "blend-1024" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "incumbent": 0.2544320913461538, + "512": 0.25530348557692306, + "1024": 0.2538461538461539, + "blend-512": 0.2550330528846154, + "blend-1024": 0.25369591346153847 + }, + "selected": "blend-1024" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "incumbent": 0.2345402644230769, + "512": 0.2346905048076923, + "1024": 0.23502103365384613, + "blend-512": 0.23520132211538458, + "blend-1024": 0.23484074519230771 + }, + "selected": "incumbent" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "incumbent": 0.23999399038461539, + "512": 0.24036959134615385, + "1024": 0.23987379807692305, + "blend-512": 0.240234375, + "blend-1024": 0.24008413461538464 + }, + "selected": "1024" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "incumbent": 0.24664963942307694, + "512": 0.24878305288461539, + "1024": 0.24810697115384614, + "blend-512": 0.2468900240384615, + "blend-1024": 0.24661959134615385 + }, + "selected": "blend-1024" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "incumbent": 0.23789062500000002, + "512": 0.23919771634615386, + "1024": 0.23847656250000002, + "blend-512": 0.23802584134615382, + "blend-1024": 0.2378155048076923 + }, + "selected": "blend-1024" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "incumbent": 0.23733473557692303, + "512": 0.23939302884615382, + "1024": 0.2384465144230769, + "blend-512": 0.23829627403846151, + "blend-1024": 0.23727463942307694 + }, + "selected": "blend-1024" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "incumbent": 0.2340444711538461, + "512": 0.23482572115384615, + "1024": 0.23378906249999998, + "blend-512": 0.23434495192307692, + "blend-1024": 0.23345853365384614 + }, + "selected": "blend-1024" + }, + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.24024939903846157 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22627704326923076 + }, + "selected": "incumbent" + } + ] + }, + { + "name": "temporal1", + "training_run": { + "initialization": "Continue from rich weights trained from random initialization in this session; new temporal parameters randomly initialized now", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "steps": 2048, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.001, + "sampling_seed": 20261111, + "optimizer_restored": false, + "rng_restored": false, + "session_trained_starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.6317505836486816, + "error": 0.3681640625, + "gradient_norm": 0.04013459011912346, + "elapsed": 30.971998691558838 + }, + { + "step": 16, + "loss": 0.5091081857681274, + "error": 0.291015625, + "gradient_norm": 0.042228709906339645, + "elapsed": 35.17463397979736 + }, + { + "step": 32, + "loss": 0.626472532749176, + "error": 0.3642578125, + "gradient_norm": 0.05872415751218796, + "elapsed": 39.678136110305786 + }, + { + "step": 48, + "loss": 0.6005369424819946, + "error": 0.3515625, + "gradient_norm": 0.03848014399409294, + "elapsed": 44.16946887969971 + }, + { + "step": 64, + "loss": 0.5523768663406372, + "error": 0.302734375, + "gradient_norm": 0.06031862646341324, + "elapsed": 48.65217089653015 + }, + { + "step": 80, + "loss": 0.3981674611568451, + "error": 0.19921875, + "gradient_norm": 0.0542079322040081, + "elapsed": 53.21601867675781 + }, + { + "step": 96, + "loss": 0.5601426362991333, + "error": 0.2978515625, + "gradient_norm": 0.04770371690392494, + "elapsed": 57.81089663505554 + }, + { + "step": 112, + "loss": 0.5878150463104248, + "error": 0.34765625, + "gradient_norm": 0.10699950158596039, + "elapsed": 62.42190766334534 + }, + { + "step": 128, + "loss": 0.5232458114624023, + "error": 0.2861328125, + "gradient_norm": 0.0911584198474884, + "elapsed": 67.00223755836487 + }, + { + "step": 144, + "loss": 0.6119767427444458, + "error": 0.3623046875, + "gradient_norm": 0.062474437057971954, + "elapsed": 71.54070782661438 + }, + { + "step": 160, + "loss": 0.3037984371185303, + "error": 0.1474609375, + "gradient_norm": 0.05718141421675682, + "elapsed": 76.08167362213135 + }, + { + "step": 176, + "loss": 0.6038273572921753, + "error": 0.3662109375, + "gradient_norm": 0.0437164381146431, + "elapsed": 80.71864247322083 + }, + { + "step": 192, + "loss": 0.3304370641708374, + "error": 0.1572265625, + "gradient_norm": 0.05684761330485344, + "elapsed": 85.54437017440796 + }, + { + "step": 208, + "loss": 0.5785484313964844, + "error": 0.3251953125, + "gradient_norm": 0.09597272425889969, + "elapsed": 91.51522874832153 + }, + { + "step": 224, + "loss": 0.3110499978065491, + "error": 0.13671875, + "gradient_norm": 0.04815748706459999, + "elapsed": 97.1228940486908 + }, + { + "step": 240, + "loss": 0.6213864684104919, + "error": 0.3623046875, + "gradient_norm": 0.0540502592921257, + "elapsed": 102.90286135673523 + }, + { + "step": 256, + "loss": 0.2535272240638733, + "error": 0.1064453125, + "gradient_norm": 0.029962118715047836, + "elapsed": 108.39288640022278 + }, + { + "step": 272, + "loss": 0.6126939058303833, + "error": 0.3671875, + "gradient_norm": 0.06887879222631454, + "elapsed": 113.83897161483765 + }, + { + "step": 288, + "loss": 0.4556676149368286, + "error": 0.2236328125, + "gradient_norm": 0.16127081215381622, + "elapsed": 119.93085813522339 + }, + { + "step": 304, + "loss": 0.4973585605621338, + "error": 0.255859375, + "gradient_norm": 0.08082302659749985, + "elapsed": 125.90891909599304 + }, + { + "step": 320, + "loss": 0.6455868482589722, + "error": 0.419921875, + "gradient_norm": 0.04339660331606865, + "elapsed": 131.20537638664246 + }, + { + "step": 336, + "loss": 0.5343132615089417, + "error": 0.2880859375, + "gradient_norm": 0.07518009096384048, + "elapsed": 136.59086871147156 + }, + { + "step": 352, + "loss": 0.6505346894264221, + "error": 0.4033203125, + "gradient_norm": 0.03800992667675018, + "elapsed": 142.21085906028748 + }, + { + "step": 368, + "loss": 0.4882712960243225, + "error": 0.251953125, + "gradient_norm": 0.08170920610427856, + "elapsed": 146.95903658866882 + }, + { + "step": 384, + "loss": 0.5292021036148071, + "error": 0.296875, + "gradient_norm": 0.08454013615846634, + "elapsed": 151.6385259628296 + }, + { + "step": 400, + "loss": 0.6272899508476257, + "error": 0.3837890625, + "gradient_norm": 0.051436979323625565, + "elapsed": 156.3343904018402 + }, + { + "step": 416, + "loss": 0.052130259573459625, + "error": 0.0166015625, + "gradient_norm": 0.02377190627157688, + "elapsed": 160.92345547676086 + }, + { + "step": 432, + "loss": 0.5256737470626831, + "error": 0.3046875, + "gradient_norm": 0.07986386120319366, + "elapsed": 165.52879118919373 + }, + { + "step": 448, + "loss": 0.15193665027618408, + "error": 0.0576171875, + "gradient_norm": 0.06491660326719284, + "elapsed": 170.14827823638916 + }, + { + "step": 464, + "loss": 0.6418055295944214, + "error": 0.40625, + "gradient_norm": 0.07290885597467422, + "elapsed": 174.64974284172058 + }, + { + "step": 480, + "loss": 0.6055159568786621, + "error": 0.357421875, + "gradient_norm": 0.0795595794916153, + "elapsed": 179.17218685150146 + }, + { + "step": 496, + "loss": 0.6372283697128296, + "error": 0.3916015625, + "gradient_norm": 0.04387903958559036, + "elapsed": 183.77568197250366 + }, + { + "step": 512, + "loss": 0.637977123260498, + "error": 0.408203125, + "gradient_norm": 0.060665905475616455, + "elapsed": 188.31205368041992 + }, + { + "step": 528, + "loss": 0.4668862223625183, + "error": 0.2451171875, + "gradient_norm": 0.08566711097955704, + "elapsed": 206.40719985961914 + }, + { + "step": 544, + "loss": 0.4584413170814514, + "error": 0.244140625, + "gradient_norm": 0.08538200706243515, + "elapsed": 211.02819895744324 + }, + { + "step": 560, + "loss": 0.5615692138671875, + "error": 0.3291015625, + "gradient_norm": 0.043748609721660614, + "elapsed": 215.66470766067505 + }, + { + "step": 576, + "loss": 0.5151895880699158, + "error": 0.2880859375, + "gradient_norm": 0.05164863541722298, + "elapsed": 220.18949556350708 + }, + { + "step": 592, + "loss": 0.5618112087249756, + "error": 0.3291015625, + "gradient_norm": 0.05998719856142998, + "elapsed": 224.7216100692749 + }, + { + "step": 608, + "loss": 0.659294843673706, + "error": 0.431640625, + "gradient_norm": 0.09910348802804947, + "elapsed": 229.26827573776245 + }, + { + "step": 624, + "loss": 0.5895233154296875, + "error": 0.3447265625, + "gradient_norm": 0.045334093272686005, + "elapsed": 233.83731055259705 + }, + { + "step": 640, + "loss": 0.6081801056861877, + "error": 0.3388671875, + "gradient_norm": 0.06578423827886581, + "elapsed": 238.36345624923706 + }, + { + "step": 656, + "loss": 0.5349816083908081, + "error": 0.2939453125, + "gradient_norm": 0.09989562630653381, + "elapsed": 242.95086026191711 + }, + { + "step": 672, + "loss": 0.5871994495391846, + "error": 0.328125, + "gradient_norm": 0.08132346719503403, + "elapsed": 247.67088556289673 + }, + { + "step": 688, + "loss": 0.06012660637497902, + "error": 0.0146484375, + "gradient_norm": 0.012170507572591305, + "elapsed": 252.3202247619629 + }, + { + "step": 704, + "loss": 0.42179757356643677, + "error": 0.21484375, + "gradient_norm": 0.08384513854980469, + "elapsed": 256.91991782188416 + }, + { + "step": 720, + "loss": 0.6111758947372437, + "error": 0.3720703125, + "gradient_norm": 0.06689880788326263, + "elapsed": 261.56407928466797 + }, + { + "step": 736, + "loss": 0.29969727993011475, + "error": 0.1318359375, + "gradient_norm": 0.0743367150425911, + "elapsed": 266.22199630737305 + }, + { + "step": 752, + "loss": 0.051849883049726486, + "error": 0.0166015625, + "gradient_norm": 0.017005126923322678, + "elapsed": 270.8602342605591 + }, + { + "step": 768, + "loss": 0.6178420186042786, + "error": 0.3759765625, + "gradient_norm": 0.027732960879802704, + "elapsed": 275.47888374328613 + }, + { + "step": 784, + "loss": 0.45798996090888977, + "error": 0.228515625, + "gradient_norm": 0.0630083829164505, + "elapsed": 280.1709156036377 + }, + { + "step": 800, + "loss": 0.5104988813400269, + "error": 0.2724609375, + "gradient_norm": 0.041733670979738235, + "elapsed": 286.17937707901 + }, + { + "step": 816, + "loss": 0.6336112022399902, + "error": 0.3837890625, + "gradient_norm": 0.0755191296339035, + "elapsed": 291.7506103515625 + }, + { + "step": 832, + "loss": 0.6260952353477478, + "error": 0.3603515625, + "gradient_norm": 0.0318005345761776, + "elapsed": 297.31094622612 + }, + { + "step": 848, + "loss": 0.5870074033737183, + "error": 0.3525390625, + "gradient_norm": 0.12073405832052231, + "elapsed": 303.11089158058167 + }, + { + "step": 864, + "loss": 0.5125640034675598, + "error": 0.26953125, + "gradient_norm": 0.038650237023830414, + "elapsed": 308.7288725376129 + }, + { + "step": 880, + "loss": 0.19194915890693665, + "error": 0.0703125, + "gradient_norm": 0.061878547072410583, + "elapsed": 314.37042355537415 + }, + { + "step": 896, + "loss": 0.5409250259399414, + "error": 0.2919921875, + "gradient_norm": 0.06288820505142212, + "elapsed": 319.9398190975189 + }, + { + "step": 912, + "loss": 0.6164936423301697, + "error": 0.3701171875, + "gradient_norm": 0.043224163353443146, + "elapsed": 325.361323595047 + }, + { + "step": 928, + "loss": 0.16032151877880096, + "error": 0.0625, + "gradient_norm": 0.030957572162151337, + "elapsed": 331.21752285957336 + }, + { + "step": 944, + "loss": 0.646601676940918, + "error": 0.3818359375, + "gradient_norm": 0.05670839175581932, + "elapsed": 336.7825517654419 + }, + { + "step": 960, + "loss": 0.402952641248703, + "error": 0.1865234375, + "gradient_norm": 0.07500886172056198, + "elapsed": 342.6888346672058 + }, + { + "step": 976, + "loss": 0.5537433624267578, + "error": 0.2939453125, + "gradient_norm": 0.04955969750881195, + "elapsed": 348.5554690361023 + }, + { + "step": 992, + "loss": 0.559626579284668, + "error": 0.294921875, + "gradient_norm": 0.048295993357896805, + "elapsed": 354.3531894683838 + }, + { + "step": 1008, + "loss": 0.5034694671630859, + "error": 0.2705078125, + "gradient_norm": 0.05729879066348076, + "elapsed": 360.0949149131775 + }, + { + "step": 1024, + "loss": 0.3119734525680542, + "error": 0.1259765625, + "gradient_norm": 0.052326612174510956, + "elapsed": 365.7881224155426 + }, + { + "step": 1040, + "loss": 0.35799849033355713, + "error": 0.173828125, + "gradient_norm": 0.03801804035902023, + "elapsed": 386.5749418735504 + }, + { + "step": 1056, + "loss": 0.6178948879241943, + "error": 0.3515625, + "gradient_norm": 0.03620661422610283, + "elapsed": 391.48247838020325 + }, + { + "step": 1072, + "loss": 0.49231401085853577, + "error": 0.24609375, + "gradient_norm": 0.04391559213399887, + "elapsed": 396.08718824386597 + }, + { + "step": 1088, + "loss": 0.4119300842285156, + "error": 0.2001953125, + "gradient_norm": 0.1104700043797493, + "elapsed": 400.5326828956604 + }, + { + "step": 1104, + "loss": 0.4926626682281494, + "error": 0.265625, + "gradient_norm": 0.04246886447072029, + "elapsed": 404.95741271972656 + }, + { + "step": 1120, + "loss": 0.5027930736541748, + "error": 0.2607421875, + "gradient_norm": 0.0547240674495697, + "elapsed": 409.40319633483887 + }, + { + "step": 1136, + "loss": 0.5948058366775513, + "error": 0.3544921875, + "gradient_norm": 0.06810063123703003, + "elapsed": 413.8514006137848 + }, + { + "step": 1152, + "loss": 0.26567256450653076, + "error": 0.125, + "gradient_norm": 0.06689104437828064, + "elapsed": 418.29868721961975 + }, + { + "step": 1168, + "loss": 0.2866836190223694, + "error": 0.1240234375, + "gradient_norm": 0.029536213725805283, + "elapsed": 422.75131845474243 + }, + { + "step": 1184, + "loss": 0.6342021822929382, + "error": 0.4091796875, + "gradient_norm": 0.0704190731048584, + "elapsed": 427.1991722583771 + }, + { + "step": 1200, + "loss": 0.41626787185668945, + "error": 0.212890625, + "gradient_norm": 0.04480795934796333, + "elapsed": 431.6600706577301 + }, + { + "step": 1216, + "loss": 0.28460952639579773, + "error": 0.1337890625, + "gradient_norm": 0.03666983172297478, + "elapsed": 436.14414525032043 + }, + { + "step": 1232, + "loss": 0.044482216238975525, + "error": 0.0146484375, + "gradient_norm": 0.04537617415189743, + "elapsed": 440.6220428943634 + }, + { + "step": 1248, + "loss": 0.42564862966537476, + "error": 0.2119140625, + "gradient_norm": 0.03382417559623718, + "elapsed": 445.06736421585083 + }, + { + "step": 1264, + "loss": 0.27150213718414307, + "error": 0.123046875, + "gradient_norm": 0.033046118915081024, + "elapsed": 449.544029712677 + }, + { + "step": 1280, + "loss": 0.4927375912666321, + "error": 0.255859375, + "gradient_norm": 0.06812550127506256, + "elapsed": 454.07198667526245 + }, + { + "step": 1296, + "loss": 0.5541940927505493, + "error": 0.28125, + "gradient_norm": 0.1435294896364212, + "elapsed": 458.6031415462494 + }, + { + "step": 1312, + "loss": 0.5575842261314392, + "error": 0.2958984375, + "gradient_norm": 0.03811952844262123, + "elapsed": 463.1806228160858 + }, + { + "step": 1328, + "loss": 0.3479428291320801, + "error": 0.1591796875, + "gradient_norm": 0.0709012895822525, + "elapsed": 467.84689688682556 + }, + { + "step": 1344, + "loss": 0.1685580611228943, + "error": 0.0693359375, + "gradient_norm": 0.05423415079712868, + "elapsed": 472.6908576488495 + }, + { + "step": 1360, + "loss": 0.18506410717964172, + "error": 0.0771484375, + "gradient_norm": 0.03418596833944321, + "elapsed": 477.4269769191742 + }, + { + "step": 1376, + "loss": 0.5654555559158325, + "error": 0.3173828125, + "gradient_norm": 0.0685155838727951, + "elapsed": 482.08285188674927 + }, + { + "step": 1392, + "loss": 0.6116407513618469, + "error": 0.3603515625, + "gradient_norm": 0.05198948457837105, + "elapsed": 486.7167499065399 + }, + { + "step": 1408, + "loss": 0.4014682471752167, + "error": 0.19140625, + "gradient_norm": 0.1024075523018837, + "elapsed": 491.4308760166168 + }, + { + "step": 1424, + "loss": 0.051035866141319275, + "error": 0.0166015625, + "gradient_norm": 0.010207361541688442, + "elapsed": 496.1818380355835 + }, + { + "step": 1440, + "loss": 0.4725648760795593, + "error": 0.2412109375, + "gradient_norm": 0.03977378085255623, + "elapsed": 500.8668632507324 + }, + { + "step": 1456, + "loss": 0.5407818555831909, + "error": 0.2939453125, + "gradient_norm": 0.088577501475811, + "elapsed": 505.49274134635925 + }, + { + "step": 1472, + "loss": 0.5655064582824707, + "error": 0.3076171875, + "gradient_norm": 0.04452778398990631, + "elapsed": 510.2188584804535 + }, + { + "step": 1488, + "loss": 0.5799556374549866, + "error": 0.30859375, + "gradient_norm": 0.03976206108927727, + "elapsed": 514.9319434165955 + }, + { + "step": 1504, + "loss": 0.4660354256629944, + "error": 0.25390625, + "gradient_norm": 0.04365506023168564, + "elapsed": 519.5848798751831 + }, + { + "step": 1520, + "loss": 0.5505894422531128, + "error": 0.30859375, + "gradient_norm": 0.057772211730480194, + "elapsed": 524.3388590812683 + }, + { + "step": 1536, + "loss": 0.6251416206359863, + "error": 0.400390625, + "gradient_norm": 0.09649194777011871, + "elapsed": 529.483047246933 + }, + { + "step": 1552, + "loss": 0.05424533039331436, + "error": 0.0185546875, + "gradient_norm": 0.011683990247547626, + "elapsed": 548.1828610897064 + }, + { + "step": 1568, + "loss": 0.33612310886383057, + "error": 0.1611328125, + "gradient_norm": 0.051817383617162704, + "elapsed": 553.4256420135498 + }, + { + "step": 1584, + "loss": 0.045015305280685425, + "error": 0.0166015625, + "gradient_norm": 0.022604886442422867, + "elapsed": 558.6308543682098 + }, + { + "step": 1600, + "loss": 0.2701840102672577, + "error": 0.119140625, + "gradient_norm": 0.02910422720015049, + "elapsed": 563.8571691513062 + }, + { + "step": 1616, + "loss": 0.18982334434986115, + "error": 0.0849609375, + "gradient_norm": 0.025524422526359558, + "elapsed": 568.8628678321838 + }, + { + "step": 1632, + "loss": 0.3950161337852478, + "error": 0.185546875, + "gradient_norm": 0.08419577777385712, + "elapsed": 574.0815451145172 + }, + { + "step": 1648, + "loss": 0.49384528398513794, + "error": 0.255859375, + "gradient_norm": 0.08879344165325165, + "elapsed": 579.1229114532471 + }, + { + "step": 1664, + "loss": 0.5671384930610657, + "error": 0.3115234375, + "gradient_norm": 0.05374513566493988, + "elapsed": 584.114851474762 + }, + { + "step": 1680, + "loss": 0.6192574501037598, + "error": 0.37890625, + "gradient_norm": 0.043836336582899094, + "elapsed": 589.0708522796631 + }, + { + "step": 1696, + "loss": 0.2619469463825226, + "error": 0.1171875, + "gradient_norm": 0.040093280375003815, + "elapsed": 594.2814819812775 + }, + { + "step": 1712, + "loss": 0.33178141713142395, + "error": 0.162109375, + "gradient_norm": 0.04902712255716324, + "elapsed": 599.3068840503693 + }, + { + "step": 1728, + "loss": 0.385281503200531, + "error": 0.171875, + "gradient_norm": 0.03541380167007446, + "elapsed": 604.5308682918549 + }, + { + "step": 1744, + "loss": 0.1628715693950653, + "error": 0.0693359375, + "gradient_norm": 0.06111741065979004, + "elapsed": 609.309522151947 + }, + { + "step": 1760, + "loss": 0.5239119529724121, + "error": 0.2861328125, + "gradient_norm": 0.08513613045215607, + "elapsed": 614.0396001338959 + }, + { + "step": 1776, + "loss": 0.35721707344055176, + "error": 0.150390625, + "gradient_norm": 0.06337940692901611, + "elapsed": 618.6857132911682 + }, + { + "step": 1792, + "loss": 0.5985626578330994, + "error": 0.33203125, + "gradient_norm": 0.035725343972444534, + "elapsed": 623.3352344036102 + }, + { + "step": 1808, + "loss": 0.34676820039749146, + "error": 0.15234375, + "gradient_norm": 0.08163885772228241, + "elapsed": 627.9495220184326 + }, + { + "step": 1824, + "loss": 0.5633711814880371, + "error": 0.3037109375, + "gradient_norm": 0.05938677117228508, + "elapsed": 632.5820379257202 + }, + { + "step": 1840, + "loss": 0.6256523132324219, + "error": 0.384765625, + "gradient_norm": 0.04545137286186218, + "elapsed": 637.205274105072 + }, + { + "step": 1856, + "loss": 0.28091639280319214, + "error": 0.1298828125, + "gradient_norm": 0.04705077037215233, + "elapsed": 641.883561372757 + }, + { + "step": 1872, + "loss": 0.516182541847229, + "error": 0.263671875, + "gradient_norm": 0.08828777819871902, + "elapsed": 646.5188939571381 + }, + { + "step": 1888, + "loss": 0.48386621475219727, + "error": 0.25390625, + "gradient_norm": 0.05322824418544769, + "elapsed": 651.148512840271 + }, + { + "step": 1904, + "loss": 0.6141921281814575, + "error": 0.388671875, + "gradient_norm": 0.050139278173446655, + "elapsed": 655.7796437740326 + }, + { + "step": 1920, + "loss": 0.18002840876579285, + "error": 0.0712890625, + "gradient_norm": 0.04201133921742439, + "elapsed": 660.4064948558807 + }, + { + "step": 1936, + "loss": 0.17531852424144745, + "error": 0.0732421875, + "gradient_norm": 0.024726318195462227, + "elapsed": 664.9991583824158 + }, + { + "step": 1952, + "loss": 0.5088322758674622, + "error": 0.2744140625, + "gradient_norm": 0.04693225398659706, + "elapsed": 669.5544555187225 + }, + { + "step": 1968, + "loss": 0.5684165358543396, + "error": 0.3310546875, + "gradient_norm": 0.031029095873236656, + "elapsed": 674.2354445457458 + }, + { + "step": 1984, + "loss": 0.06459524482488632, + "error": 0.017578125, + "gradient_norm": 0.03600892797112465, + "elapsed": 678.7982559204102 + }, + { + "step": 2000, + "loss": 0.3614455461502075, + "error": 0.1748046875, + "gradient_norm": 0.07060294598340988, + "elapsed": 683.2650325298309 + }, + { + "step": 2016, + "loss": 0.35535523295402527, + "error": 0.166015625, + "gradient_norm": 0.05873403698205948, + "elapsed": 687.7125518321991 + }, + { + "step": 2032, + "loss": 0.5638720989227295, + "error": 0.3232421875, + "gradient_norm": 0.07380504906177521, + "elapsed": 692.1461188793182 + }, + { + "step": 2048, + "loss": 0.5301838517189026, + "error": 0.2919921875, + "gradient_norm": 0.05435395985841751, + "elapsed": 696.6235508918762 + } + ] + }, + "selected_checkpoint_steps": [ + 1024, + 1536, + 2048 + ], + "checkpoint_records": { + "2048": { + "step": 2048, + "new_training_shots": 2097152, + "weights": "weights-2048.npz", + "weights_sha256": "26be9e0259b69a5870bf73e80a5a29fcf3519a3ff63e1d219c57a2113d9d34be", + "validation": "validation-2048.json", + "complete": true + }, + "1024": { + "step": 1024, + "new_training_shots": 1048576, + "weights": "weights-1024.npz", + "weights_sha256": "6ab63cf2443420bfa5f2a817a90432dfc969348a8b23b0e6ccf3ffad3c381672", + "validation": "validation-1024.json", + "complete": true + }, + "1536": { + "step": 1536, + "new_training_shots": 1572864, + "weights": "weights-1536.npz", + "weights_sha256": "a4c6152c3b8f2f8ab8cdda41e92045ebc7eb944f9931a7937bf49c404bf96668", + "validation": "validation-1536.json", + "complete": true + } + }, + "selection": "Minimum full-validation mean failure per group among incumbent and listed session-trained checkpoints; when listed, blend candidates average the recorded small-contextual reference and new probabilities equally", + "blend_reference": "/run-state/workspace/research/context_upgrades/continuation2/predictions", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "incumbent": 0.24764122596153845, + "512": 0.24836237980769232, + "1024": 0.24783653846153847, + "1536": 0.24682992788461539, + "2048": 0.246875, + "blend-512": 0.24767127403846154, + "blend-1024": 0.24747596153846155, + "blend-1536": 0.24684495192307693, + "blend-2048": 0.24672475961538465 + }, + "selected": "blend-2048" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "incumbent": 0.25369591346153847, + "512": 0.25387620192307697, + "1024": 0.25365084134615384, + "1536": 0.25392127403846154, + "2048": 0.2531550480769231, + "blend-512": 0.25429687500000003, + "blend-1024": 0.25419170673076924, + "blend-1536": 0.25338040865384615, + "blend-2048": 0.2532301682692308 + }, + "selected": "2048" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "incumbent": 0.2345402644230769, + "512": 0.23535156250000003, + "1024": 0.23467548076923078, + "1536": 0.23575721153846152, + "2048": 0.23529146634615386, + "blend-512": 0.23494591346153842, + "blend-1024": 0.2351862980769231, + "blend-1536": 0.23535156249999997, + "blend-2048": 0.23446514423076925 + }, + "selected": "blend-2048" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "incumbent": 0.23987379807692305, + "512": 0.2393028846153846, + "1024": 0.2391676682692308, + "1536": 0.2397686298076923, + "2048": 0.23969350961538463, + "blend-512": 0.23972355769230771, + "blend-1024": 0.23967848557692312, + "blend-1536": 0.24044471153846153, + "blend-2048": 0.24048978365384613 + }, + "selected": "1024" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "incumbent": 0.24661959134615385, + "512": 0.24767127403846156, + "1024": 0.24747596153846155, + "1536": 0.24658954326923077, + "2048": 0.2467397836538462, + "blend-512": 0.24634915865384613, + "blend-1024": 0.24684495192307693, + "blend-1536": 0.24640925480769232, + "blend-2048": 0.24625901442307693 + }, + "selected": "blend-2048" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "incumbent": 0.2378155048076923, + "512": 0.23912259615384615, + "1024": 0.23805588942307693, + "1536": 0.2381610576923077, + "2048": 0.2376802884615385, + "blend-512": 0.2378155048076923, + "blend-1024": 0.23765024038461538, + "blend-1536": 0.23783052884615388, + "blend-2048": 0.23760516826923078 + }, + "selected": "blend-2048" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "incumbent": 0.23727463942307694, + "512": 0.23766526442307695, + "1024": 0.23789062500000005, + "1536": 0.23713942307692307, + "2048": 0.23778545673076923, + "blend-512": 0.2376201923076923, + "blend-1024": 0.23743990384615382, + "blend-1536": 0.2375, + "blend-2048": 0.2376201923076923 + }, + "selected": "1536" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "incumbent": 0.23345853365384614, + "512": 0.2344200721153846, + "1024": 0.23431490384615386, + "1536": 0.23435997596153843, + "2048": 0.23390925480769229, + "blend-512": 0.23448016826923074, + "blend-1024": 0.2340895432692308, + "blend-1536": 0.23360877403846156, + "blend-2048": 0.2338792067307692 + }, + "selected": "incumbent" + }, + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.2338341346153846 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22182992788461542 + }, + "selected": "incumbent" + } + ] + }, + { + "name": "temporal2", + "training_run": { + "initialization": "Continue from this session's trained checkpoint", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "training_source_sha256": { + "learned_exact__temporal_train.py": "7d48d2fc7f62d0bec3023b3df1c2ac28537d0417966131ae3a156697a34cda5f", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "eligible_training_shots": 2067520, + "unique_training_rows_seen_in_this_phase": 1778773, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_3_5": 18357, + "surface_code_bX_d3_r03_center_3_5": 16816, + "surface_code_bX_d3_r05_center_3_5": 17999, + "surface_code_bX_d3_r07_center_3_5": 15225, + "surface_code_bX_d3_r09_center_3_5": 16132, + "surface_code_bX_d3_r11_center_3_5": 17041, + "surface_code_bX_d3_r13_center_3_5": 18477, + "surface_code_bX_d3_r15_center_3_5": 18214, + "surface_code_bX_d3_r17_center_3_5": 16505, + "surface_code_bX_d3_r19_center_3_5": 17120, + "surface_code_bX_d3_r21_center_3_5": 17563, + "surface_code_bX_d3_r23_center_3_5": 16681, + "surface_code_bX_d3_r25_center_3_5": 18379, + "surface_code_bX_d3_r01_center_5_3": 17450, + "surface_code_bX_d3_r03_center_5_3": 17161, + "surface_code_bX_d3_r05_center_5_3": 15797, + "surface_code_bX_d3_r07_center_5_3": 17800, + "surface_code_bX_d3_r09_center_5_3": 17190, + "surface_code_bX_d3_r11_center_5_3": 15840, + "surface_code_bX_d3_r13_center_5_3": 15178, + "surface_code_bX_d3_r15_center_5_3": 14897, + "surface_code_bX_d3_r17_center_5_3": 18252, + "surface_code_bX_d3_r19_center_5_3": 17083, + "surface_code_bX_d3_r21_center_5_3": 17229, + "surface_code_bX_d3_r23_center_5_3": 14735, + "surface_code_bX_d3_r25_center_5_3": 17949, + "surface_code_bX_d3_r01_center_5_7": 17431, + "surface_code_bX_d3_r03_center_5_7": 16583, + "surface_code_bX_d3_r05_center_5_7": 16891, + "surface_code_bX_d3_r07_center_5_7": 17969, + "surface_code_bX_d3_r09_center_5_7": 17966, + "surface_code_bX_d3_r11_center_5_7": 14424, + "surface_code_bX_d3_r13_center_5_7": 16930, + "surface_code_bX_d3_r15_center_5_7": 15205, + "surface_code_bX_d3_r17_center_5_7": 18252, + "surface_code_bX_d3_r19_center_5_7": 17077, + "surface_code_bX_d3_r21_center_5_7": 16770, + "surface_code_bX_d3_r23_center_5_7": 17308, + "surface_code_bX_d3_r25_center_5_7": 17481, + "surface_code_bX_d3_r01_center_7_5": 16630, + "surface_code_bX_d3_r03_center_7_5": 17439, + "surface_code_bX_d3_r05_center_7_5": 15811, + "surface_code_bX_d3_r07_center_7_5": 16637, + "surface_code_bX_d3_r09_center_7_5": 18306, + "surface_code_bX_d3_r11_center_7_5": 18327, + "surface_code_bX_d3_r13_center_7_5": 17974, + "surface_code_bX_d3_r15_center_7_5": 16106, + "surface_code_bX_d3_r17_center_7_5": 15834, + "surface_code_bX_d3_r19_center_7_5": 17242, + "surface_code_bX_d3_r21_center_7_5": 17889, + "surface_code_bX_d3_r23_center_7_5": 17440, + "surface_code_bX_d3_r25_center_7_5": 17087, + "surface_code_bZ_d3_r01_center_3_5": 16236, + "surface_code_bZ_d3_r03_center_3_5": 17278, + "surface_code_bZ_d3_r05_center_3_5": 16577, + "surface_code_bZ_d3_r07_center_3_5": 17376, + "surface_code_bZ_d3_r09_center_3_5": 16000, + "surface_code_bZ_d3_r11_center_3_5": 15634, + "surface_code_bZ_d3_r13_center_3_5": 14950, + "surface_code_bZ_d3_r15_center_3_5": 16600, + "surface_code_bZ_d3_r17_center_3_5": 15381, + "surface_code_bZ_d3_r19_center_3_5": 16823, + "surface_code_bZ_d3_r21_center_3_5": 18789, + "surface_code_bZ_d3_r23_center_3_5": 15616, + "surface_code_bZ_d3_r25_center_3_5": 17088, + "surface_code_bZ_d3_r01_center_5_3": 17935, + "surface_code_bZ_d3_r03_center_5_3": 16256, + "surface_code_bZ_d3_r05_center_5_3": 17959, + "surface_code_bZ_d3_r07_center_5_3": 18401, + "surface_code_bZ_d3_r09_center_5_3": 16405, + "surface_code_bZ_d3_r11_center_5_3": 17274, + "surface_code_bZ_d3_r13_center_5_3": 18172, + "surface_code_bZ_d3_r15_center_5_3": 17525, + "surface_code_bZ_d3_r17_center_5_3": 18643, + "surface_code_bZ_d3_r19_center_5_3": 17816, + "surface_code_bZ_d3_r21_center_5_3": 17404, + "surface_code_bZ_d3_r23_center_5_3": 17253, + "surface_code_bZ_d3_r25_center_5_3": 17667, + "surface_code_bZ_d3_r01_center_5_7": 16203, + "surface_code_bZ_d3_r03_center_5_7": 17214, + "surface_code_bZ_d3_r05_center_5_7": 16799, + "surface_code_bZ_d3_r07_center_5_7": 17896, + "surface_code_bZ_d3_r09_center_5_7": 16411, + "surface_code_bZ_d3_r11_center_5_7": 17726, + "surface_code_bZ_d3_r13_center_5_7": 16313, + "surface_code_bZ_d3_r15_center_5_7": 17824, + "surface_code_bZ_d3_r17_center_5_7": 15656, + "surface_code_bZ_d3_r19_center_5_7": 17169, + "surface_code_bZ_d3_r21_center_5_7": 17194, + "surface_code_bZ_d3_r23_center_5_7": 16779, + "surface_code_bZ_d3_r25_center_5_7": 16970, + "surface_code_bZ_d3_r01_center_7_5": 16762, + "surface_code_bZ_d3_r03_center_7_5": 17320, + "surface_code_bZ_d3_r05_center_7_5": 17522, + "surface_code_bZ_d3_r07_center_7_5": 17914, + "surface_code_bZ_d3_r09_center_7_5": 18439, + "surface_code_bZ_d3_r11_center_7_5": 18218, + "surface_code_bZ_d3_r13_center_7_5": 17907, + "surface_code_bZ_d3_r15_center_7_5": 17597, + "surface_code_bZ_d3_r17_center_7_5": 18252, + "surface_code_bZ_d3_r19_center_7_5": 18379, + "surface_code_bZ_d3_r21_center_7_5": 16818, + "surface_code_bZ_d3_r23_center_7_5": 18430, + "surface_code_bZ_d3_r25_center_7_5": 17924 + }, + "steps": 4096, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.0005, + "sampling_seed": 20261121, + "optimizer_restored": true, + "rng_restored": true, + "sampling_state_source": "/run-state/workspace/research/learned_exact/temporal1/rng-2048.json", + "session_trained_starting_checkpoint": "/run-state/workspace/research/learned_exact/temporal1/weights-2048.npz", + "starting_checkpoint_sha256": "26be9e0259b69a5870bf73e80a5a29fcf3519a3ff63e1d219c57a2113d9d34be", + "starting_training_provenance": { + "initialization": "Continue from rich weights trained from random initialization in this session; new temporal parameters randomly initialized now", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "steps": 2048, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.001, + "sampling_seed": 20261111, + "optimizer_restored": false, + "rng_restored": false, + "session_trained_starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.6317505836486816, + "error": 0.3681640625, + "gradient_norm": 0.04013459011912346, + "elapsed": 30.971998691558838 + }, + { + "step": 16, + "loss": 0.5091081857681274, + "error": 0.291015625, + "gradient_norm": 0.042228709906339645, + "elapsed": 35.17463397979736 + }, + { + "step": 32, + "loss": 0.626472532749176, + "error": 0.3642578125, + "gradient_norm": 0.05872415751218796, + "elapsed": 39.678136110305786 + }, + { + "step": 48, + "loss": 0.6005369424819946, + "error": 0.3515625, + "gradient_norm": 0.03848014399409294, + "elapsed": 44.16946887969971 + }, + { + "step": 64, + "loss": 0.5523768663406372, + "error": 0.302734375, + "gradient_norm": 0.06031862646341324, + "elapsed": 48.65217089653015 + }, + { + "step": 80, + "loss": 0.3981674611568451, + "error": 0.19921875, + "gradient_norm": 0.0542079322040081, + "elapsed": 53.21601867675781 + }, + { + "step": 96, + "loss": 0.5601426362991333, + "error": 0.2978515625, + "gradient_norm": 0.04770371690392494, + "elapsed": 57.81089663505554 + }, + { + "step": 112, + "loss": 0.5878150463104248, + "error": 0.34765625, + "gradient_norm": 0.10699950158596039, + "elapsed": 62.42190766334534 + }, + { + "step": 128, + "loss": 0.5232458114624023, + "error": 0.2861328125, + "gradient_norm": 0.0911584198474884, + "elapsed": 67.00223755836487 + }, + { + "step": 144, + "loss": 0.6119767427444458, + "error": 0.3623046875, + "gradient_norm": 0.062474437057971954, + "elapsed": 71.54070782661438 + }, + { + "step": 160, + "loss": 0.3037984371185303, + "error": 0.1474609375, + "gradient_norm": 0.05718141421675682, + "elapsed": 76.08167362213135 + }, + { + "step": 176, + "loss": 0.6038273572921753, + "error": 0.3662109375, + "gradient_norm": 0.0437164381146431, + "elapsed": 80.71864247322083 + }, + { + "step": 192, + "loss": 0.3304370641708374, + "error": 0.1572265625, + "gradient_norm": 0.05684761330485344, + "elapsed": 85.54437017440796 + }, + { + "step": 208, + "loss": 0.5785484313964844, + "error": 0.3251953125, + "gradient_norm": 0.09597272425889969, + "elapsed": 91.51522874832153 + }, + { + "step": 224, + "loss": 0.3110499978065491, + "error": 0.13671875, + "gradient_norm": 0.04815748706459999, + "elapsed": 97.1228940486908 + }, + { + "step": 240, + "loss": 0.6213864684104919, + "error": 0.3623046875, + "gradient_norm": 0.0540502592921257, + "elapsed": 102.90286135673523 + }, + { + "step": 256, + "loss": 0.2535272240638733, + "error": 0.1064453125, + "gradient_norm": 0.029962118715047836, + "elapsed": 108.39288640022278 + }, + { + "step": 272, + "loss": 0.6126939058303833, + "error": 0.3671875, + "gradient_norm": 0.06887879222631454, + "elapsed": 113.83897161483765 + }, + { + "step": 288, + "loss": 0.4556676149368286, + "error": 0.2236328125, + "gradient_norm": 0.16127081215381622, + "elapsed": 119.93085813522339 + }, + { + "step": 304, + "loss": 0.4973585605621338, + "error": 0.255859375, + "gradient_norm": 0.08082302659749985, + "elapsed": 125.90891909599304 + }, + { + "step": 320, + "loss": 0.6455868482589722, + "error": 0.419921875, + "gradient_norm": 0.04339660331606865, + "elapsed": 131.20537638664246 + }, + { + "step": 336, + "loss": 0.5343132615089417, + "error": 0.2880859375, + "gradient_norm": 0.07518009096384048, + "elapsed": 136.59086871147156 + }, + { + "step": 352, + "loss": 0.6505346894264221, + "error": 0.4033203125, + "gradient_norm": 0.03800992667675018, + "elapsed": 142.21085906028748 + }, + { + "step": 368, + "loss": 0.4882712960243225, + "error": 0.251953125, + "gradient_norm": 0.08170920610427856, + "elapsed": 146.95903658866882 + }, + { + "step": 384, + "loss": 0.5292021036148071, + "error": 0.296875, + "gradient_norm": 0.08454013615846634, + "elapsed": 151.6385259628296 + }, + { + "step": 400, + "loss": 0.6272899508476257, + "error": 0.3837890625, + "gradient_norm": 0.051436979323625565, + "elapsed": 156.3343904018402 + }, + { + "step": 416, + "loss": 0.052130259573459625, + "error": 0.0166015625, + "gradient_norm": 0.02377190627157688, + "elapsed": 160.92345547676086 + }, + { + "step": 432, + "loss": 0.5256737470626831, + "error": 0.3046875, + "gradient_norm": 0.07986386120319366, + "elapsed": 165.52879118919373 + }, + { + "step": 448, + "loss": 0.15193665027618408, + "error": 0.0576171875, + "gradient_norm": 0.06491660326719284, + "elapsed": 170.14827823638916 + }, + { + "step": 464, + "loss": 0.6418055295944214, + "error": 0.40625, + "gradient_norm": 0.07290885597467422, + "elapsed": 174.64974284172058 + }, + { + "step": 480, + "loss": 0.6055159568786621, + "error": 0.357421875, + "gradient_norm": 0.0795595794916153, + "elapsed": 179.17218685150146 + }, + { + "step": 496, + "loss": 0.6372283697128296, + "error": 0.3916015625, + "gradient_norm": 0.04387903958559036, + "elapsed": 183.77568197250366 + }, + { + "step": 512, + "loss": 0.637977123260498, + "error": 0.408203125, + "gradient_norm": 0.060665905475616455, + "elapsed": 188.31205368041992 + }, + { + "step": 528, + "loss": 0.4668862223625183, + "error": 0.2451171875, + "gradient_norm": 0.08566711097955704, + "elapsed": 206.40719985961914 + }, + { + "step": 544, + "loss": 0.4584413170814514, + "error": 0.244140625, + "gradient_norm": 0.08538200706243515, + "elapsed": 211.02819895744324 + }, + { + "step": 560, + "loss": 0.5615692138671875, + "error": 0.3291015625, + "gradient_norm": 0.043748609721660614, + "elapsed": 215.66470766067505 + }, + { + "step": 576, + "loss": 0.5151895880699158, + "error": 0.2880859375, + "gradient_norm": 0.05164863541722298, + "elapsed": 220.18949556350708 + }, + { + "step": 592, + "loss": 0.5618112087249756, + "error": 0.3291015625, + "gradient_norm": 0.05998719856142998, + "elapsed": 224.7216100692749 + }, + { + "step": 608, + "loss": 0.659294843673706, + "error": 0.431640625, + "gradient_norm": 0.09910348802804947, + "elapsed": 229.26827573776245 + }, + { + "step": 624, + "loss": 0.5895233154296875, + "error": 0.3447265625, + "gradient_norm": 0.045334093272686005, + "elapsed": 233.83731055259705 + }, + { + "step": 640, + "loss": 0.6081801056861877, + "error": 0.3388671875, + "gradient_norm": 0.06578423827886581, + "elapsed": 238.36345624923706 + }, + { + "step": 656, + "loss": 0.5349816083908081, + "error": 0.2939453125, + "gradient_norm": 0.09989562630653381, + "elapsed": 242.95086026191711 + }, + { + "step": 672, + "loss": 0.5871994495391846, + "error": 0.328125, + "gradient_norm": 0.08132346719503403, + "elapsed": 247.67088556289673 + }, + { + "step": 688, + "loss": 0.06012660637497902, + "error": 0.0146484375, + "gradient_norm": 0.012170507572591305, + "elapsed": 252.3202247619629 + }, + { + "step": 704, + "loss": 0.42179757356643677, + "error": 0.21484375, + "gradient_norm": 0.08384513854980469, + "elapsed": 256.91991782188416 + }, + { + "step": 720, + "loss": 0.6111758947372437, + "error": 0.3720703125, + "gradient_norm": 0.06689880788326263, + "elapsed": 261.56407928466797 + }, + { + "step": 736, + "loss": 0.29969727993011475, + "error": 0.1318359375, + "gradient_norm": 0.0743367150425911, + "elapsed": 266.22199630737305 + }, + { + "step": 752, + "loss": 0.051849883049726486, + "error": 0.0166015625, + "gradient_norm": 0.017005126923322678, + "elapsed": 270.8602342605591 + }, + { + "step": 768, + "loss": 0.6178420186042786, + "error": 0.3759765625, + "gradient_norm": 0.027732960879802704, + "elapsed": 275.47888374328613 + }, + { + "step": 784, + "loss": 0.45798996090888977, + "error": 0.228515625, + "gradient_norm": 0.0630083829164505, + "elapsed": 280.1709156036377 + }, + { + "step": 800, + "loss": 0.5104988813400269, + "error": 0.2724609375, + "gradient_norm": 0.041733670979738235, + "elapsed": 286.17937707901 + }, + { + "step": 816, + "loss": 0.6336112022399902, + "error": 0.3837890625, + "gradient_norm": 0.0755191296339035, + "elapsed": 291.7506103515625 + }, + { + "step": 832, + "loss": 0.6260952353477478, + "error": 0.3603515625, + "gradient_norm": 0.0318005345761776, + "elapsed": 297.31094622612 + }, + { + "step": 848, + "loss": 0.5870074033737183, + "error": 0.3525390625, + "gradient_norm": 0.12073405832052231, + "elapsed": 303.11089158058167 + }, + { + "step": 864, + "loss": 0.5125640034675598, + "error": 0.26953125, + "gradient_norm": 0.038650237023830414, + "elapsed": 308.7288725376129 + }, + { + "step": 880, + "loss": 0.19194915890693665, + "error": 0.0703125, + "gradient_norm": 0.061878547072410583, + "elapsed": 314.37042355537415 + }, + { + "step": 896, + "loss": 0.5409250259399414, + "error": 0.2919921875, + "gradient_norm": 0.06288820505142212, + "elapsed": 319.9398190975189 + }, + { + "step": 912, + "loss": 0.6164936423301697, + "error": 0.3701171875, + "gradient_norm": 0.043224163353443146, + "elapsed": 325.361323595047 + }, + { + "step": 928, + "loss": 0.16032151877880096, + "error": 0.0625, + "gradient_norm": 0.030957572162151337, + "elapsed": 331.21752285957336 + }, + { + "step": 944, + "loss": 0.646601676940918, + "error": 0.3818359375, + "gradient_norm": 0.05670839175581932, + "elapsed": 336.7825517654419 + }, + { + "step": 960, + "loss": 0.402952641248703, + "error": 0.1865234375, + "gradient_norm": 0.07500886172056198, + "elapsed": 342.6888346672058 + }, + { + "step": 976, + "loss": 0.5537433624267578, + "error": 0.2939453125, + "gradient_norm": 0.04955969750881195, + "elapsed": 348.5554690361023 + }, + { + "step": 992, + "loss": 0.559626579284668, + "error": 0.294921875, + "gradient_norm": 0.048295993357896805, + "elapsed": 354.3531894683838 + }, + { + "step": 1008, + "loss": 0.5034694671630859, + "error": 0.2705078125, + "gradient_norm": 0.05729879066348076, + "elapsed": 360.0949149131775 + }, + { + "step": 1024, + "loss": 0.3119734525680542, + "error": 0.1259765625, + "gradient_norm": 0.052326612174510956, + "elapsed": 365.7881224155426 + }, + { + "step": 1040, + "loss": 0.35799849033355713, + "error": 0.173828125, + "gradient_norm": 0.03801804035902023, + "elapsed": 386.5749418735504 + }, + { + "step": 1056, + "loss": 0.6178948879241943, + "error": 0.3515625, + "gradient_norm": 0.03620661422610283, + "elapsed": 391.48247838020325 + }, + { + "step": 1072, + "loss": 0.49231401085853577, + "error": 0.24609375, + "gradient_norm": 0.04391559213399887, + "elapsed": 396.08718824386597 + }, + { + "step": 1088, + "loss": 0.4119300842285156, + "error": 0.2001953125, + "gradient_norm": 0.1104700043797493, + "elapsed": 400.5326828956604 + }, + { + "step": 1104, + "loss": 0.4926626682281494, + "error": 0.265625, + "gradient_norm": 0.04246886447072029, + "elapsed": 404.95741271972656 + }, + { + "step": 1120, + "loss": 0.5027930736541748, + "error": 0.2607421875, + "gradient_norm": 0.0547240674495697, + "elapsed": 409.40319633483887 + }, + { + "step": 1136, + "loss": 0.5948058366775513, + "error": 0.3544921875, + "gradient_norm": 0.06810063123703003, + "elapsed": 413.8514006137848 + }, + { + "step": 1152, + "loss": 0.26567256450653076, + "error": 0.125, + "gradient_norm": 0.06689104437828064, + "elapsed": 418.29868721961975 + }, + { + "step": 1168, + "loss": 0.2866836190223694, + "error": 0.1240234375, + "gradient_norm": 0.029536213725805283, + "elapsed": 422.75131845474243 + }, + { + "step": 1184, + "loss": 0.6342021822929382, + "error": 0.4091796875, + "gradient_norm": 0.0704190731048584, + "elapsed": 427.1991722583771 + }, + { + "step": 1200, + "loss": 0.41626787185668945, + "error": 0.212890625, + "gradient_norm": 0.04480795934796333, + "elapsed": 431.6600706577301 + }, + { + "step": 1216, + "loss": 0.28460952639579773, + "error": 0.1337890625, + "gradient_norm": 0.03666983172297478, + "elapsed": 436.14414525032043 + }, + { + "step": 1232, + "loss": 0.044482216238975525, + "error": 0.0146484375, + "gradient_norm": 0.04537617415189743, + "elapsed": 440.6220428943634 + }, + { + "step": 1248, + "loss": 0.42564862966537476, + "error": 0.2119140625, + "gradient_norm": 0.03382417559623718, + "elapsed": 445.06736421585083 + }, + { + "step": 1264, + "loss": 0.27150213718414307, + "error": 0.123046875, + "gradient_norm": 0.033046118915081024, + "elapsed": 449.544029712677 + }, + { + "step": 1280, + "loss": 0.4927375912666321, + "error": 0.255859375, + "gradient_norm": 0.06812550127506256, + "elapsed": 454.07198667526245 + }, + { + "step": 1296, + "loss": 0.5541940927505493, + "error": 0.28125, + "gradient_norm": 0.1435294896364212, + "elapsed": 458.6031415462494 + }, + { + "step": 1312, + "loss": 0.5575842261314392, + "error": 0.2958984375, + "gradient_norm": 0.03811952844262123, + "elapsed": 463.1806228160858 + }, + { + "step": 1328, + "loss": 0.3479428291320801, + "error": 0.1591796875, + "gradient_norm": 0.0709012895822525, + "elapsed": 467.84689688682556 + }, + { + "step": 1344, + "loss": 0.1685580611228943, + "error": 0.0693359375, + "gradient_norm": 0.05423415079712868, + "elapsed": 472.6908576488495 + }, + { + "step": 1360, + "loss": 0.18506410717964172, + "error": 0.0771484375, + "gradient_norm": 0.03418596833944321, + "elapsed": 477.4269769191742 + }, + { + "step": 1376, + "loss": 0.5654555559158325, + "error": 0.3173828125, + "gradient_norm": 0.0685155838727951, + "elapsed": 482.08285188674927 + }, + { + "step": 1392, + "loss": 0.6116407513618469, + "error": 0.3603515625, + "gradient_norm": 0.05198948457837105, + "elapsed": 486.7167499065399 + }, + { + "step": 1408, + "loss": 0.4014682471752167, + "error": 0.19140625, + "gradient_norm": 0.1024075523018837, + "elapsed": 491.4308760166168 + }, + { + "step": 1424, + "loss": 0.051035866141319275, + "error": 0.0166015625, + "gradient_norm": 0.010207361541688442, + "elapsed": 496.1818380355835 + }, + { + "step": 1440, + "loss": 0.4725648760795593, + "error": 0.2412109375, + "gradient_norm": 0.03977378085255623, + "elapsed": 500.8668632507324 + }, + { + "step": 1456, + "loss": 0.5407818555831909, + "error": 0.2939453125, + "gradient_norm": 0.088577501475811, + "elapsed": 505.49274134635925 + }, + { + "step": 1472, + "loss": 0.5655064582824707, + "error": 0.3076171875, + "gradient_norm": 0.04452778398990631, + "elapsed": 510.2188584804535 + }, + { + "step": 1488, + "loss": 0.5799556374549866, + "error": 0.30859375, + "gradient_norm": 0.03976206108927727, + "elapsed": 514.9319434165955 + }, + { + "step": 1504, + "loss": 0.4660354256629944, + "error": 0.25390625, + "gradient_norm": 0.04365506023168564, + "elapsed": 519.5848798751831 + }, + { + "step": 1520, + "loss": 0.5505894422531128, + "error": 0.30859375, + "gradient_norm": 0.057772211730480194, + "elapsed": 524.3388590812683 + }, + { + "step": 1536, + "loss": 0.6251416206359863, + "error": 0.400390625, + "gradient_norm": 0.09649194777011871, + "elapsed": 529.483047246933 + }, + { + "step": 1552, + "loss": 0.05424533039331436, + "error": 0.0185546875, + "gradient_norm": 0.011683990247547626, + "elapsed": 548.1828610897064 + }, + { + "step": 1568, + "loss": 0.33612310886383057, + "error": 0.1611328125, + "gradient_norm": 0.051817383617162704, + "elapsed": 553.4256420135498 + }, + { + "step": 1584, + "loss": 0.045015305280685425, + "error": 0.0166015625, + "gradient_norm": 0.022604886442422867, + "elapsed": 558.6308543682098 + }, + { + "step": 1600, + "loss": 0.2701840102672577, + "error": 0.119140625, + "gradient_norm": 0.02910422720015049, + "elapsed": 563.8571691513062 + }, + { + "step": 1616, + "loss": 0.18982334434986115, + "error": 0.0849609375, + "gradient_norm": 0.025524422526359558, + "elapsed": 568.8628678321838 + }, + { + "step": 1632, + "loss": 0.3950161337852478, + "error": 0.185546875, + "gradient_norm": 0.08419577777385712, + "elapsed": 574.0815451145172 + }, + { + "step": 1648, + "loss": 0.49384528398513794, + "error": 0.255859375, + "gradient_norm": 0.08879344165325165, + "elapsed": 579.1229114532471 + }, + { + "step": 1664, + "loss": 0.5671384930610657, + "error": 0.3115234375, + "gradient_norm": 0.05374513566493988, + "elapsed": 584.114851474762 + }, + { + "step": 1680, + "loss": 0.6192574501037598, + "error": 0.37890625, + "gradient_norm": 0.043836336582899094, + "elapsed": 589.0708522796631 + }, + { + "step": 1696, + "loss": 0.2619469463825226, + "error": 0.1171875, + "gradient_norm": 0.040093280375003815, + "elapsed": 594.2814819812775 + }, + { + "step": 1712, + "loss": 0.33178141713142395, + "error": 0.162109375, + "gradient_norm": 0.04902712255716324, + "elapsed": 599.3068840503693 + }, + { + "step": 1728, + "loss": 0.385281503200531, + "error": 0.171875, + "gradient_norm": 0.03541380167007446, + "elapsed": 604.5308682918549 + }, + { + "step": 1744, + "loss": 0.1628715693950653, + "error": 0.0693359375, + "gradient_norm": 0.06111741065979004, + "elapsed": 609.309522151947 + }, + { + "step": 1760, + "loss": 0.5239119529724121, + "error": 0.2861328125, + "gradient_norm": 0.08513613045215607, + "elapsed": 614.0396001338959 + }, + { + "step": 1776, + "loss": 0.35721707344055176, + "error": 0.150390625, + "gradient_norm": 0.06337940692901611, + "elapsed": 618.6857132911682 + }, + { + "step": 1792, + "loss": 0.5985626578330994, + "error": 0.33203125, + "gradient_norm": 0.035725343972444534, + "elapsed": 623.3352344036102 + }, + { + "step": 1808, + "loss": 0.34676820039749146, + "error": 0.15234375, + "gradient_norm": 0.08163885772228241, + "elapsed": 627.9495220184326 + }, + { + "step": 1824, + "loss": 0.5633711814880371, + "error": 0.3037109375, + "gradient_norm": 0.05938677117228508, + "elapsed": 632.5820379257202 + }, + { + "step": 1840, + "loss": 0.6256523132324219, + "error": 0.384765625, + "gradient_norm": 0.04545137286186218, + "elapsed": 637.205274105072 + }, + { + "step": 1856, + "loss": 0.28091639280319214, + "error": 0.1298828125, + "gradient_norm": 0.04705077037215233, + "elapsed": 641.883561372757 + }, + { + "step": 1872, + "loss": 0.516182541847229, + "error": 0.263671875, + "gradient_norm": 0.08828777819871902, + "elapsed": 646.5188939571381 + }, + { + "step": 1888, + "loss": 0.48386621475219727, + "error": 0.25390625, + "gradient_norm": 0.05322824418544769, + "elapsed": 651.148512840271 + }, + { + "step": 1904, + "loss": 0.6141921281814575, + "error": 0.388671875, + "gradient_norm": 0.050139278173446655, + "elapsed": 655.7796437740326 + }, + { + "step": 1920, + "loss": 0.18002840876579285, + "error": 0.0712890625, + "gradient_norm": 0.04201133921742439, + "elapsed": 660.4064948558807 + }, + { + "step": 1936, + "loss": 0.17531852424144745, + "error": 0.0732421875, + "gradient_norm": 0.024726318195462227, + "elapsed": 664.9991583824158 + }, + { + "step": 1952, + "loss": 0.5088322758674622, + "error": 0.2744140625, + "gradient_norm": 0.04693225398659706, + "elapsed": 669.5544555187225 + }, + { + "step": 1968, + "loss": 0.5684165358543396, + "error": 0.3310546875, + "gradient_norm": 0.031029095873236656, + "elapsed": 674.2354445457458 + }, + { + "step": 1984, + "loss": 0.06459524482488632, + "error": 0.017578125, + "gradient_norm": 0.03600892797112465, + "elapsed": 678.7982559204102 + }, + { + "step": 2000, + "loss": 0.3614455461502075, + "error": 0.1748046875, + "gradient_norm": 0.07060294598340988, + "elapsed": 683.2650325298309 + }, + { + "step": 2016, + "loss": 0.35535523295402527, + "error": 0.166015625, + "gradient_norm": 0.05873403698205948, + "elapsed": 687.7125518321991 + }, + { + "step": 2032, + "loss": 0.5638720989227295, + "error": 0.3232421875, + "gradient_norm": 0.07380504906177521, + "elapsed": 692.1461188793182 + }, + { + "step": 2048, + "loss": 0.5301838517189026, + "error": 0.2919921875, + "gradient_norm": 0.05435395985841751, + "elapsed": 696.6235508918762 + } + ] + }, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.250907301902771, + "error": 0.1083984375, + "gradient_norm": 0.07171476632356644, + "elapsed": 44.811134576797485 + }, + { + "step": 16, + "loss": 0.5958679914474487, + "error": 0.3662109375, + "gradient_norm": 0.07673005014657974, + "elapsed": 49.90856671333313 + }, + { + "step": 32, + "loss": 0.47648972272872925, + "error": 0.2421875, + "gradient_norm": 0.08561501652002335, + "elapsed": 55.179388761520386 + }, + { + "step": 48, + "loss": 0.06145006790757179, + "error": 0.0234375, + "gradient_norm": 0.01556467730551958, + "elapsed": 61.0339195728302 + }, + { + "step": 64, + "loss": 0.3687053918838501, + "error": 0.1884765625, + "gradient_norm": 0.08752371370792389, + "elapsed": 65.95811891555786 + }, + { + "step": 80, + "loss": 0.6481984853744507, + "error": 0.4140625, + "gradient_norm": 0.05311283841729164, + "elapsed": 70.56021332740784 + }, + { + "step": 96, + "loss": 0.42319929599761963, + "error": 0.2138671875, + "gradient_norm": 0.05047478526830673, + "elapsed": 75.11613631248474 + }, + { + "step": 112, + "loss": 0.47527259588241577, + "error": 0.24609375, + "gradient_norm": 0.038366906344890594, + "elapsed": 79.53446984291077 + }, + { + "step": 128, + "loss": 0.5996723175048828, + "error": 0.3369140625, + "gradient_norm": 0.1213272362947464, + "elapsed": 83.97515749931335 + }, + { + "step": 144, + "loss": 0.04971993714570999, + "error": 0.0146484375, + "gradient_norm": 0.008080735802650452, + "elapsed": 88.44039463996887 + }, + { + "step": 160, + "loss": 0.35900360345840454, + "error": 0.162109375, + "gradient_norm": 0.03359593451023102, + "elapsed": 92.89548206329346 + }, + { + "step": 176, + "loss": 0.5342063903808594, + "error": 0.2978515625, + "gradient_norm": 0.04794691130518913, + "elapsed": 97.35658049583435 + }, + { + "step": 192, + "loss": 0.6300076246261597, + "error": 0.369140625, + "gradient_norm": 0.081769198179245, + "elapsed": 101.81493759155273 + }, + { + "step": 208, + "loss": 0.6191903948783875, + "error": 0.3828125, + "gradient_norm": 0.07145775109529495, + "elapsed": 106.2480263710022 + }, + { + "step": 224, + "loss": 0.5155678391456604, + "error": 0.28515625, + "gradient_norm": 0.06772179156541824, + "elapsed": 110.71284222602844 + }, + { + "step": 240, + "loss": 0.634708046913147, + "error": 0.3857421875, + "gradient_norm": 0.09493093192577362, + "elapsed": 115.14978742599487 + }, + { + "step": 256, + "loss": 0.1840895414352417, + "error": 0.0751953125, + "gradient_norm": 0.025586696341633797, + "elapsed": 119.61202120780945 + }, + { + "step": 272, + "loss": 0.2775103449821472, + "error": 0.12890625, + "gradient_norm": 0.06913147866725922, + "elapsed": 124.02584528923035 + }, + { + "step": 288, + "loss": 0.6163080334663391, + "error": 0.3642578125, + "gradient_norm": 0.05895426496863365, + "elapsed": 128.46512532234192 + }, + { + "step": 304, + "loss": 0.5276986360549927, + "error": 0.287109375, + "gradient_norm": 0.06955187022686005, + "elapsed": 132.89240765571594 + }, + { + "step": 320, + "loss": 0.44859516620635986, + "error": 0.22265625, + "gradient_norm": 0.07272452116012573, + "elapsed": 137.32864713668823 + }, + { + "step": 336, + "loss": 0.48315611481666565, + "error": 0.2626953125, + "gradient_norm": 0.03321139141917229, + "elapsed": 141.80009770393372 + }, + { + "step": 352, + "loss": 0.6107717752456665, + "error": 0.3544921875, + "gradient_norm": 0.05243214592337608, + "elapsed": 146.36439752578735 + }, + { + "step": 368, + "loss": 0.6215153932571411, + "error": 0.357421875, + "gradient_norm": 0.04383325204253197, + "elapsed": 150.99996852874756 + }, + { + "step": 384, + "loss": 0.6130329966545105, + "error": 0.35546875, + "gradient_norm": 0.04113119840621948, + "elapsed": 155.62374639511108 + }, + { + "step": 400, + "loss": 0.30471885204315186, + "error": 0.142578125, + "gradient_norm": 0.04447556659579277, + "elapsed": 160.17594957351685 + }, + { + "step": 416, + "loss": 0.6154489517211914, + "error": 0.37109375, + "gradient_norm": 0.04456057772040367, + "elapsed": 164.7639675140381 + }, + { + "step": 432, + "loss": 0.6134694218635559, + "error": 0.337890625, + "gradient_norm": 0.04219559207558632, + "elapsed": 169.32792139053345 + }, + { + "step": 448, + "loss": 0.5463185906410217, + "error": 0.2939453125, + "gradient_norm": 0.07746092975139618, + "elapsed": 173.88445162773132 + }, + { + "step": 464, + "loss": 0.06016772612929344, + "error": 0.01953125, + "gradient_norm": 0.01364185381680727, + "elapsed": 178.42725706100464 + }, + { + "step": 480, + "loss": 0.388141393661499, + "error": 0.18359375, + "gradient_norm": 0.04870256036520004, + "elapsed": 182.99062085151672 + }, + { + "step": 496, + "loss": 0.44524821639060974, + "error": 0.2216796875, + "gradient_norm": 0.03453445807099342, + "elapsed": 187.56396961212158 + }, + { + "step": 512, + "loss": 0.34312355518341064, + "error": 0.154296875, + "gradient_norm": 0.06794509291648865, + "elapsed": 192.27511191368103 + }, + { + "step": 528, + "loss": 0.19467462599277496, + "error": 0.0771484375, + "gradient_norm": 0.042381469160318375, + "elapsed": 197.7108268737793 + }, + { + "step": 544, + "loss": 0.46226584911346436, + "error": 0.2421875, + "gradient_norm": 0.06073570251464844, + "elapsed": 202.97405791282654 + }, + { + "step": 560, + "loss": 0.525318443775177, + "error": 0.2822265625, + "gradient_norm": 0.06954885274171829, + "elapsed": 208.69676971435547 + }, + { + "step": 576, + "loss": 0.6158387064933777, + "error": 0.349609375, + "gradient_norm": 0.07587578892707825, + "elapsed": 214.80397653579712 + }, + { + "step": 592, + "loss": 0.5515886545181274, + "error": 0.298828125, + "gradient_norm": 0.04969338700175285, + "elapsed": 220.27399611473083 + }, + { + "step": 608, + "loss": 0.18365338444709778, + "error": 0.0654296875, + "gradient_norm": 0.08657706528902054, + "elapsed": 224.81246256828308 + }, + { + "step": 624, + "loss": 0.4578855633735657, + "error": 0.2421875, + "gradient_norm": 0.04942100867629051, + "elapsed": 229.45902252197266 + }, + { + "step": 640, + "loss": 0.37826013565063477, + "error": 0.1865234375, + "gradient_norm": 0.047499872744083405, + "elapsed": 233.9695644378662 + }, + { + "step": 656, + "loss": 0.40863412618637085, + "error": 0.2001953125, + "gradient_norm": 0.07845330238342285, + "elapsed": 238.584894657135 + }, + { + "step": 672, + "loss": 0.5640332698822021, + "error": 0.2880859375, + "gradient_norm": 0.057469289749860764, + "elapsed": 243.0929844379425 + }, + { + "step": 688, + "loss": 0.030216243118047714, + "error": 0.0078125, + "gradient_norm": 0.04682641476392746, + "elapsed": 247.581125497818 + }, + { + "step": 704, + "loss": 0.375002384185791, + "error": 0.1826171875, + "gradient_norm": 0.04864194989204407, + "elapsed": 252.1564691066742 + }, + { + "step": 720, + "loss": 0.5145515203475952, + "error": 0.2744140625, + "gradient_norm": 0.052671682089567184, + "elapsed": 256.6466488838196 + }, + { + "step": 736, + "loss": 0.067174531519413, + "error": 0.0224609375, + "gradient_norm": 0.019299577921628952, + "elapsed": 261.1185076236725 + }, + { + "step": 752, + "loss": 0.24909992516040802, + "error": 0.111328125, + "gradient_norm": 0.06907463818788528, + "elapsed": 265.61960339546204 + }, + { + "step": 768, + "loss": 0.5088074207305908, + "error": 0.2744140625, + "gradient_norm": 0.06963017582893372, + "elapsed": 270.07474064826965 + }, + { + "step": 784, + "loss": 0.3783387839794159, + "error": 0.1826171875, + "gradient_norm": 0.05537794530391693, + "elapsed": 274.52722239494324 + }, + { + "step": 800, + "loss": 0.6107200980186462, + "error": 0.3623046875, + "gradient_norm": 0.0470259003341198, + "elapsed": 279.0401859283447 + }, + { + "step": 816, + "loss": 0.5778236389160156, + "error": 0.3212890625, + "gradient_norm": 0.10146680474281311, + "elapsed": 283.5114622116089 + }, + { + "step": 832, + "loss": 0.576002299785614, + "error": 0.3076171875, + "gradient_norm": 0.07760787010192871, + "elapsed": 288.04797434806824 + }, + { + "step": 848, + "loss": 0.6179666519165039, + "error": 0.3740234375, + "gradient_norm": 0.07383852452039719, + "elapsed": 292.60600209236145 + }, + { + "step": 864, + "loss": 0.3105512857437134, + "error": 0.1455078125, + "gradient_norm": 0.052953749895095825, + "elapsed": 297.12180352211 + }, + { + "step": 880, + "loss": 0.4802623987197876, + "error": 0.2548828125, + "gradient_norm": 0.07736275345087051, + "elapsed": 301.6091134548187 + }, + { + "step": 896, + "loss": 0.5572722554206848, + "error": 0.318359375, + "gradient_norm": 0.053303152322769165, + "elapsed": 306.1978073120117 + }, + { + "step": 912, + "loss": 0.34814420342445374, + "error": 0.1669921875, + "gradient_norm": 0.037726350128650665, + "elapsed": 310.78571581840515 + }, + { + "step": 928, + "loss": 0.41743016242980957, + "error": 0.21875, + "gradient_norm": 0.05238872766494751, + "elapsed": 315.24156188964844 + }, + { + "step": 944, + "loss": 0.5757850408554077, + "error": 0.3173828125, + "gradient_norm": 0.05837905779480934, + "elapsed": 319.78475165367126 + }, + { + "step": 960, + "loss": 0.40727972984313965, + "error": 0.197265625, + "gradient_norm": 0.059294261038303375, + "elapsed": 324.2090265750885 + }, + { + "step": 976, + "loss": 0.32715001702308655, + "error": 0.1533203125, + "gradient_norm": 0.11543179303407669, + "elapsed": 328.6462152004242 + }, + { + "step": 992, + "loss": 0.5578742623329163, + "error": 0.314453125, + "gradient_norm": 0.06282714009284973, + "elapsed": 333.0712504386902 + }, + { + "step": 1008, + "loss": 0.5052692294120789, + "error": 0.265625, + "gradient_norm": 0.04039420187473297, + "elapsed": 337.5182821750641 + }, + { + "step": 1024, + "loss": 0.18790806829929352, + "error": 0.08203125, + "gradient_norm": 0.028905188664793968, + "elapsed": 342.08340406417847 + }, + { + "step": 1040, + "loss": 0.6317684650421143, + "error": 0.3681640625, + "gradient_norm": 0.03441835194826126, + "elapsed": 358.8279616832733 + }, + { + "step": 1056, + "loss": 0.40474164485931396, + "error": 0.2021484375, + "gradient_norm": 0.036449309438467026, + "elapsed": 363.30218267440796 + }, + { + "step": 1072, + "loss": 0.518299400806427, + "error": 0.2666015625, + "gradient_norm": 0.0886964276432991, + "elapsed": 367.87997555732727 + }, + { + "step": 1088, + "loss": 0.2522922158241272, + "error": 0.099609375, + "gradient_norm": 0.07553310692310333, + "elapsed": 372.4414882659912 + }, + { + "step": 1104, + "loss": 0.6214810609817505, + "error": 0.3701171875, + "gradient_norm": 0.10188957303762436, + "elapsed": 376.9120502471924 + }, + { + "step": 1120, + "loss": 0.6307054162025452, + "error": 0.3720703125, + "gradient_norm": 0.07353860139846802, + "elapsed": 381.3824534416199 + }, + { + "step": 1136, + "loss": 0.5259381532669067, + "error": 0.2763671875, + "gradient_norm": 0.05779678374528885, + "elapsed": 385.8413143157959 + }, + { + "step": 1152, + "loss": 0.4995541572570801, + "error": 0.259765625, + "gradient_norm": 0.046648140996694565, + "elapsed": 390.28326058387756 + }, + { + "step": 1168, + "loss": 0.6075694561004639, + "error": 0.3701171875, + "gradient_norm": 0.10612073540687561, + "elapsed": 394.8162364959717 + }, + { + "step": 1184, + "loss": 0.2105136513710022, + "error": 0.080078125, + "gradient_norm": 0.0716402605175972, + "elapsed": 399.2960283756256 + }, + { + "step": 1200, + "loss": 0.6371631026268005, + "error": 0.3857421875, + "gradient_norm": 0.0549108125269413, + "elapsed": 403.7899103164673 + }, + { + "step": 1216, + "loss": 0.5450670719146729, + "error": 0.2939453125, + "gradient_norm": 0.11688558012247086, + "elapsed": 408.34677600860596 + }, + { + "step": 1232, + "loss": 0.035783201456069946, + "error": 0.01171875, + "gradient_norm": 0.02951689623296261, + "elapsed": 412.8558337688446 + }, + { + "step": 1248, + "loss": 0.5582903623580933, + "error": 0.3046875, + "gradient_norm": 0.055107031017541885, + "elapsed": 417.29854226112366 + }, + { + "step": 1264, + "loss": 0.5154441595077515, + "error": 0.27734375, + "gradient_norm": 0.04474929720163345, + "elapsed": 421.7792055606842 + }, + { + "step": 1280, + "loss": 0.35227546095848083, + "error": 0.16015625, + "gradient_norm": 0.05024837702512741, + "elapsed": 426.54427456855774 + }, + { + "step": 1296, + "loss": 0.19417589902877808, + "error": 0.0830078125, + "gradient_norm": 0.026926057413220406, + "elapsed": 431.320588350296 + }, + { + "step": 1312, + "loss": 0.4768218398094177, + "error": 0.248046875, + "gradient_norm": 0.15099607408046722, + "elapsed": 435.96817326545715 + }, + { + "step": 1328, + "loss": 0.48580923676490784, + "error": 0.2509765625, + "gradient_norm": 0.08925126492977142, + "elapsed": 440.64917039871216 + }, + { + "step": 1344, + "loss": 0.42041274905204773, + "error": 0.1982421875, + "gradient_norm": 0.08321093022823334, + "elapsed": 445.34370946884155 + }, + { + "step": 1360, + "loss": 0.06403929740190506, + "error": 0.0185546875, + "gradient_norm": 0.03817005455493927, + "elapsed": 449.98669385910034 + }, + { + "step": 1376, + "loss": 0.463126003742218, + "error": 0.2275390625, + "gradient_norm": 0.08894515782594681, + "elapsed": 454.6478977203369 + }, + { + "step": 1392, + "loss": 0.5995306968688965, + "error": 0.373046875, + "gradient_norm": 0.06733685731887817, + "elapsed": 459.35924530029297 + }, + { + "step": 1408, + "loss": 0.49053263664245605, + "error": 0.25, + "gradient_norm": 0.10475508868694305, + "elapsed": 464.100093126297 + }, + { + "step": 1424, + "loss": 0.6220744848251343, + "error": 0.3818359375, + "gradient_norm": 0.03653963655233383, + "elapsed": 468.89601135253906 + }, + { + "step": 1440, + "loss": 0.39706122875213623, + "error": 0.2021484375, + "gradient_norm": 0.04344598576426506, + "elapsed": 474.03999519348145 + }, + { + "step": 1456, + "loss": 0.5386708974838257, + "error": 0.3095703125, + "gradient_norm": 0.12589037418365479, + "elapsed": 478.8600504398346 + }, + { + "step": 1472, + "loss": 0.49776726961135864, + "error": 0.271484375, + "gradient_norm": 0.058137863874435425, + "elapsed": 483.5920066833496 + }, + { + "step": 1488, + "loss": 0.4757428765296936, + "error": 0.2412109375, + "gradient_norm": 0.050453316420316696, + "elapsed": 488.4611999988556 + }, + { + "step": 1504, + "loss": 0.5694847702980042, + "error": 0.337890625, + "gradient_norm": 0.052419569343328476, + "elapsed": 493.26151037216187 + }, + { + "step": 1520, + "loss": 0.5997745990753174, + "error": 0.3603515625, + "gradient_norm": 0.04338108375668526, + "elapsed": 498.0421245098114 + }, + { + "step": 1536, + "loss": 0.6195274591445923, + "error": 0.3876953125, + "gradient_norm": 0.04848463833332062, + "elapsed": 502.8808298110962 + }, + { + "step": 1552, + "loss": 0.46315908432006836, + "error": 0.2353515625, + "gradient_norm": 0.06380566209554672, + "elapsed": 507.5519721508026 + }, + { + "step": 1568, + "loss": 0.605262041091919, + "error": 0.36328125, + "gradient_norm": 0.05077619478106499, + "elapsed": 512.457685470581 + }, + { + "step": 1584, + "loss": 0.48782041668891907, + "error": 0.232421875, + "gradient_norm": 0.09017211943864822, + "elapsed": 517.2960062026978 + }, + { + "step": 1600, + "loss": 0.3881351947784424, + "error": 0.1875, + "gradient_norm": 0.07205695658922195, + "elapsed": 522.0911631584167 + }, + { + "step": 1616, + "loss": 0.4966873526573181, + "error": 0.24609375, + "gradient_norm": 0.0582038015127182, + "elapsed": 526.8861901760101 + }, + { + "step": 1632, + "loss": 0.5844199657440186, + "error": 0.33203125, + "gradient_norm": 0.05101500824093819, + "elapsed": 531.6640138626099 + }, + { + "step": 1648, + "loss": 0.31010180711746216, + "error": 0.1318359375, + "gradient_norm": 0.053135693073272705, + "elapsed": 536.4960391521454 + }, + { + "step": 1664, + "loss": 0.6174807548522949, + "error": 0.3779296875, + "gradient_norm": 0.04161194711923599, + "elapsed": 541.2560484409332 + }, + { + "step": 1680, + "loss": 0.18213607370853424, + "error": 0.0751953125, + "gradient_norm": 0.07171957194805145, + "elapsed": 546.0000085830688 + }, + { + "step": 1696, + "loss": 0.5445692539215088, + "error": 0.2998046875, + "gradient_norm": 0.054499462246894836, + "elapsed": 551.1221191883087 + }, + { + "step": 1712, + "loss": 0.05744167044758797, + "error": 0.017578125, + "gradient_norm": 0.013108699582517147, + "elapsed": 556.5286149978638 + }, + { + "step": 1728, + "loss": 0.6381571292877197, + "error": 0.3896484375, + "gradient_norm": 0.05157556012272835, + "elapsed": 561.8000066280365 + }, + { + "step": 1744, + "loss": 0.5301004648208618, + "error": 0.28125, + "gradient_norm": 0.04218568280339241, + "elapsed": 567.2760035991669 + }, + { + "step": 1760, + "loss": 0.5275102257728577, + "error": 0.26953125, + "gradient_norm": 0.06798839569091797, + "elapsed": 572.5601994991302 + }, + { + "step": 1776, + "loss": 0.6443773508071899, + "error": 0.4091796875, + "gradient_norm": 0.07035460323095322, + "elapsed": 577.9789206981659 + }, + { + "step": 1792, + "loss": 0.6012362241744995, + "error": 0.337890625, + "gradient_norm": 0.05189951881766319, + "elapsed": 583.028017282486 + }, + { + "step": 1808, + "loss": 0.2939091920852661, + "error": 0.12109375, + "gradient_norm": 0.05555355176329613, + "elapsed": 588.0501506328583 + }, + { + "step": 1824, + "loss": 0.2059091478586197, + "error": 0.08984375, + "gradient_norm": 0.045679714530706406, + "elapsed": 593.2120039463043 + }, + { + "step": 1840, + "loss": 0.6289581060409546, + "error": 0.349609375, + "gradient_norm": 0.04742642492055893, + "elapsed": 598.7767763137817 + }, + { + "step": 1856, + "loss": 0.5532636642456055, + "error": 0.294921875, + "gradient_norm": 0.05997413396835327, + "elapsed": 604.0475382804871 + }, + { + "step": 1872, + "loss": 0.45995670557022095, + "error": 0.228515625, + "gradient_norm": 0.05674462765455246, + "elapsed": 609.292379617691 + }, + { + "step": 1888, + "loss": 0.6178656816482544, + "error": 0.359375, + "gradient_norm": 0.08857566863298416, + "elapsed": 614.5639882087708 + }, + { + "step": 1904, + "loss": 0.5531284213066101, + "error": 0.287109375, + "gradient_norm": 0.10257937759160995, + "elapsed": 619.5600035190582 + }, + { + "step": 1920, + "loss": 0.04184349626302719, + "error": 0.013671875, + "gradient_norm": 0.04087059944868088, + "elapsed": 624.6679775714874 + }, + { + "step": 1936, + "loss": 0.5924860239028931, + "error": 0.3505859375, + "gradient_norm": 0.036822713911533356, + "elapsed": 629.936680316925 + }, + { + "step": 1952, + "loss": 0.46996980905532837, + "error": 0.2421875, + "gradient_norm": 0.034442272037267685, + "elapsed": 635.1109762191772 + }, + { + "step": 1968, + "loss": 0.17859068512916565, + "error": 0.0712890625, + "gradient_norm": 0.03440066799521446, + "elapsed": 640.32000207901 + }, + { + "step": 1984, + "loss": 0.6192275285720825, + "error": 0.3701171875, + "gradient_norm": 0.04386439174413681, + "elapsed": 645.6040184497833 + }, + { + "step": 2000, + "loss": 0.6160917282104492, + "error": 0.35546875, + "gradient_norm": 0.06268990784883499, + "elapsed": 650.7723731994629 + }, + { + "step": 2016, + "loss": 0.6343611478805542, + "error": 0.388671875, + "gradient_norm": 0.04243326932191849, + "elapsed": 655.972663640976 + }, + { + "step": 2032, + "loss": 0.062292590737342834, + "error": 0.021484375, + "gradient_norm": 0.016680095344781876, + "elapsed": 660.8079733848572 + }, + { + "step": 2048, + "loss": 0.5316072702407837, + "error": 0.26953125, + "gradient_norm": 0.057860780507326126, + "elapsed": 665.5760209560394 + }, + { + "step": 2064, + "loss": 0.605312705039978, + "error": 0.3623046875, + "gradient_norm": 0.04028146713972092, + "elapsed": 682.7294294834137 + }, + { + "step": 2080, + "loss": 0.56633460521698, + "error": 0.3330078125, + "gradient_norm": 0.09528280049562454, + "elapsed": 687.4644649028778 + }, + { + "step": 2096, + "loss": 0.3905397057533264, + "error": 0.1943359375, + "gradient_norm": 0.049456462264060974, + "elapsed": 692.1492264270782 + }, + { + "step": 2112, + "loss": 0.28124868869781494, + "error": 0.1259765625, + "gradient_norm": 0.059239838272333145, + "elapsed": 696.8701393604279 + }, + { + "step": 2128, + "loss": 0.6364338994026184, + "error": 0.392578125, + "gradient_norm": 0.08667811006307602, + "elapsed": 701.683988571167 + }, + { + "step": 2144, + "loss": 0.20683243870735168, + "error": 0.07421875, + "gradient_norm": 0.1100710779428482, + "elapsed": 706.4000360965729 + }, + { + "step": 2160, + "loss": 0.5912737250328064, + "error": 0.341796875, + "gradient_norm": 0.05641854554414749, + "elapsed": 711.2359964847565 + }, + { + "step": 2176, + "loss": 0.27793264389038086, + "error": 0.12109375, + "gradient_norm": 0.0893034040927887, + "elapsed": 715.9508004188538 + }, + { + "step": 2192, + "loss": 0.6474133133888245, + "error": 0.4072265625, + "gradient_norm": 0.06980258971452713, + "elapsed": 720.651974439621 + }, + { + "step": 2208, + "loss": 0.5961858630180359, + "error": 0.35546875, + "gradient_norm": 0.06530112773180008, + "elapsed": 725.496098279953 + }, + { + "step": 2224, + "loss": 0.47581571340560913, + "error": 0.263671875, + "gradient_norm": 0.04470043256878853, + "elapsed": 730.2880010604858 + }, + { + "step": 2240, + "loss": 0.577988862991333, + "error": 0.318359375, + "gradient_norm": 0.07201159745454788, + "elapsed": 735.006133556366 + }, + { + "step": 2256, + "loss": 0.28444671630859375, + "error": 0.1181640625, + "gradient_norm": 0.048656050115823746, + "elapsed": 739.6868116855621 + }, + { + "step": 2272, + "loss": 0.2776409089565277, + "error": 0.1201171875, + "gradient_norm": 0.05783981829881668, + "elapsed": 744.3517308235168 + }, + { + "step": 2288, + "loss": 0.621599555015564, + "error": 0.37109375, + "gradient_norm": 0.09731200337409973, + "elapsed": 749.0351710319519 + }, + { + "step": 2304, + "loss": 0.3333754539489746, + "error": 0.1513671875, + "gradient_norm": 0.07069239765405655, + "elapsed": 753.7588081359863 + }, + { + "step": 2320, + "loss": 0.4687051773071289, + "error": 0.2490234375, + "gradient_norm": 0.044891707599163055, + "elapsed": 758.4588432312012 + }, + { + "step": 2336, + "loss": 0.19801637530326843, + "error": 0.078125, + "gradient_norm": 0.10036595165729523, + "elapsed": 763.256409406662 + }, + { + "step": 2352, + "loss": 0.6186277866363525, + "error": 0.388671875, + "gradient_norm": 0.09069584310054779, + "elapsed": 767.9986386299133 + }, + { + "step": 2368, + "loss": 0.6177258491516113, + "error": 0.373046875, + "gradient_norm": 0.049019571393728256, + "elapsed": 772.730831861496 + }, + { + "step": 2384, + "loss": 0.17707547545433044, + "error": 0.0673828125, + "gradient_norm": 0.045190781354904175, + "elapsed": 777.4072704315186 + }, + { + "step": 2400, + "loss": 0.20144733786582947, + "error": 0.08203125, + "gradient_norm": 0.04537162929773331, + "elapsed": 782.0841658115387 + }, + { + "step": 2416, + "loss": 0.6151775121688843, + "error": 0.365234375, + "gradient_norm": 0.050534047186374664, + "elapsed": 786.762966632843 + }, + { + "step": 2432, + "loss": 0.5533859133720398, + "error": 0.314453125, + "gradient_norm": 0.06006559729576111, + "elapsed": 791.4656012058258 + }, + { + "step": 2448, + "loss": 0.5329082012176514, + "error": 0.2880859375, + "gradient_norm": 0.04018115997314453, + "elapsed": 796.1704161167145 + }, + { + "step": 2464, + "loss": 0.6338047981262207, + "error": 0.4140625, + "gradient_norm": 0.06069163978099823, + "elapsed": 800.9180119037628 + }, + { + "step": 2480, + "loss": 0.1603008508682251, + "error": 0.0673828125, + "gradient_norm": 0.040350593626499176, + "elapsed": 805.6127603054047 + }, + { + "step": 2496, + "loss": 0.505940318107605, + "error": 0.2568359375, + "gradient_norm": 0.05209952965378761, + "elapsed": 810.3740313053131 + }, + { + "step": 2512, + "loss": 0.5528728365898132, + "error": 0.298828125, + "gradient_norm": 0.11757992953062057, + "elapsed": 815.1708807945251 + }, + { + "step": 2528, + "loss": 0.5028313994407654, + "error": 0.2666015625, + "gradient_norm": 0.08823780715465546, + "elapsed": 819.8585045337677 + }, + { + "step": 2544, + "loss": 0.5002262592315674, + "error": 0.2783203125, + "gradient_norm": 0.04888603836297989, + "elapsed": 824.5714073181152 + }, + { + "step": 2560, + "loss": 0.6007894277572632, + "error": 0.328125, + "gradient_norm": 0.05186954140663147, + "elapsed": 829.3080432415009 + }, + { + "step": 2576, + "loss": 0.18641480803489685, + "error": 0.076171875, + "gradient_norm": 0.03799928352236748, + "elapsed": 834.044020652771 + }, + { + "step": 2592, + "loss": 0.3050769865512848, + "error": 0.1396484375, + "gradient_norm": 0.10119257122278214, + "elapsed": 838.8401296138763 + }, + { + "step": 2608, + "loss": 0.6063439846038818, + "error": 0.361328125, + "gradient_norm": 0.04979367554187775, + "elapsed": 844.3572654724121 + }, + { + "step": 2624, + "loss": 0.5751967430114746, + "error": 0.3369140625, + "gradient_norm": 0.04269539937376976, + "elapsed": 849.0660374164581 + }, + { + "step": 2640, + "loss": 0.3902108669281006, + "error": 0.193359375, + "gradient_norm": 0.10029696673154831, + "elapsed": 853.8638062477112 + }, + { + "step": 2656, + "loss": 0.15081660449504852, + "error": 0.0625, + "gradient_norm": 0.0303852129727602, + "elapsed": 858.9793758392334 + }, + { + "step": 2672, + "loss": 0.6503090858459473, + "error": 0.400390625, + "gradient_norm": 0.12611964344978333, + "elapsed": 863.9151141643524 + }, + { + "step": 2688, + "loss": 0.5587317943572998, + "error": 0.31640625, + "gradient_norm": 0.10028114914894104, + "elapsed": 868.7600305080414 + }, + { + "step": 2704, + "loss": 0.4399867355823517, + "error": 0.21484375, + "gradient_norm": 0.06889455020427704, + "elapsed": 873.4544236660004 + }, + { + "step": 2720, + "loss": 0.5865127444267273, + "error": 0.337890625, + "gradient_norm": 0.03671631962060928, + "elapsed": 878.0982644557953 + }, + { + "step": 2736, + "loss": 0.6078637838363647, + "error": 0.3701171875, + "gradient_norm": 0.04679318517446518, + "elapsed": 883.0424642562866 + }, + { + "step": 2752, + "loss": 0.5825340151786804, + "error": 0.337890625, + "gradient_norm": 0.05619681254029274, + "elapsed": 887.908124923706 + }, + { + "step": 2768, + "loss": 0.5970422029495239, + "error": 0.3369140625, + "gradient_norm": 0.041302867233753204, + "elapsed": 892.6760206222534 + }, + { + "step": 2784, + "loss": 0.3870226740837097, + "error": 0.1826171875, + "gradient_norm": 0.05731065198779106, + "elapsed": 897.6246056556702 + }, + { + "step": 2800, + "loss": 0.38130277395248413, + "error": 0.1943359375, + "gradient_norm": 0.059244755655527115, + "elapsed": 902.3360238075256 + }, + { + "step": 2816, + "loss": 0.2617901563644409, + "error": 0.1064453125, + "gradient_norm": 0.041736964136362076, + "elapsed": 907.1600468158722 + }, + { + "step": 2832, + "loss": 0.5819337368011475, + "error": 0.314453125, + "gradient_norm": 0.04097156226634979, + "elapsed": 912.0244295597076 + }, + { + "step": 2848, + "loss": 0.41393283009529114, + "error": 0.2001953125, + "gradient_norm": 0.10456771403551102, + "elapsed": 916.8225846290588 + }, + { + "step": 2864, + "loss": 0.5019145011901855, + "error": 0.2548828125, + "gradient_norm": 0.04843736067414284, + "elapsed": 921.538754940033 + }, + { + "step": 2880, + "loss": 0.04561338573694229, + "error": 0.0146484375, + "gradient_norm": 0.025407327339053154, + "elapsed": 926.2588667869568 + }, + { + "step": 2896, + "loss": 0.4338858723640442, + "error": 0.205078125, + "gradient_norm": 0.09900517761707306, + "elapsed": 930.9781975746155 + }, + { + "step": 2912, + "loss": 0.33922863006591797, + "error": 0.162109375, + "gradient_norm": 0.10189604014158249, + "elapsed": 935.6816267967224 + }, + { + "step": 2928, + "loss": 0.5294322967529297, + "error": 0.2822265625, + "gradient_norm": 0.09060791879892349, + "elapsed": 940.4373068809509 + }, + { + "step": 2944, + "loss": 0.037007369101047516, + "error": 0.01171875, + "gradient_norm": 0.05506489425897598, + "elapsed": 945.1270468235016 + }, + { + "step": 2960, + "loss": 0.6096771359443665, + "error": 0.349609375, + "gradient_norm": 0.04987221211194992, + "elapsed": 949.8300130367279 + }, + { + "step": 2976, + "loss": 0.6157823801040649, + "error": 0.373046875, + "gradient_norm": 0.03614233434200287, + "elapsed": 954.5701997280121 + }, + { + "step": 2992, + "loss": 0.1978239268064499, + "error": 0.080078125, + "gradient_norm": 0.05847112461924553, + "elapsed": 959.2756471633911 + }, + { + "step": 3008, + "loss": 0.5237340927124023, + "error": 0.2841796875, + "gradient_norm": 0.06993591040372849, + "elapsed": 963.9875864982605 + }, + { + "step": 3024, + "loss": 0.4559935927391052, + "error": 0.2373046875, + "gradient_norm": 0.05698448419570923, + "elapsed": 968.7997305393219 + }, + { + "step": 3040, + "loss": 0.5025208592414856, + "error": 0.259765625, + "gradient_norm": 0.14909739792346954, + "elapsed": 973.6042547225952 + }, + { + "step": 3056, + "loss": 0.3223109245300293, + "error": 0.1416015625, + "gradient_norm": 0.032974764704704285, + "elapsed": 978.4760546684265 + }, + { + "step": 3072, + "loss": 0.06682582199573517, + "error": 0.021484375, + "gradient_norm": 0.04433188587427139, + "elapsed": 983.2894048690796 + }, + { + "step": 3088, + "loss": 0.5919550061225891, + "error": 0.34765625, + "gradient_norm": 0.06721373647451401, + "elapsed": 1000.9520287513733 + }, + { + "step": 3104, + "loss": 0.5988063812255859, + "error": 0.3642578125, + "gradient_norm": 0.05654948577284813, + "elapsed": 1005.7442932128906 + }, + { + "step": 3120, + "loss": 0.4922299385070801, + "error": 0.2470703125, + "gradient_norm": 0.07545466721057892, + "elapsed": 1010.4616096019745 + }, + { + "step": 3136, + "loss": 0.4533671736717224, + "error": 0.236328125, + "gradient_norm": 0.06288722902536392, + "elapsed": 1015.3559956550598 + }, + { + "step": 3152, + "loss": 0.5070517063140869, + "error": 0.2666015625, + "gradient_norm": 0.07274917513132095, + "elapsed": 1020.0764343738556 + }, + { + "step": 3168, + "loss": 0.5999464988708496, + "error": 0.3408203125, + "gradient_norm": 0.05777016654610634, + "elapsed": 1024.9410600662231 + }, + { + "step": 3184, + "loss": 0.5758363008499146, + "error": 0.3427734375, + "gradient_norm": 0.051027461886405945, + "elapsed": 1029.7082171440125 + }, + { + "step": 3200, + "loss": 0.05016190931200981, + "error": 0.017578125, + "gradient_norm": 0.009175656363368034, + "elapsed": 1034.3982915878296 + }, + { + "step": 3216, + "loss": 0.5471057295799255, + "error": 0.318359375, + "gradient_norm": 0.07572721689939499, + "elapsed": 1039.117841243744 + }, + { + "step": 3232, + "loss": 0.4141446352005005, + "error": 0.193359375, + "gradient_norm": 0.10056859254837036, + "elapsed": 1043.880026102066 + }, + { + "step": 3248, + "loss": 0.5812438726425171, + "error": 0.3212890625, + "gradient_norm": 0.05781616270542145, + "elapsed": 1048.6406455039978 + }, + { + "step": 3264, + "loss": 0.19184701144695282, + "error": 0.078125, + "gradient_norm": 0.05367236211895943, + "elapsed": 1053.5672237873077 + }, + { + "step": 3280, + "loss": 0.5420833826065063, + "error": 0.28515625, + "gradient_norm": 0.052405405789613724, + "elapsed": 1058.3841104507446 + }, + { + "step": 3296, + "loss": 0.4419598877429962, + "error": 0.2177734375, + "gradient_norm": 0.05814693495631218, + "elapsed": 1063.1880333423615 + }, + { + "step": 3312, + "loss": 0.4525642991065979, + "error": 0.208984375, + "gradient_norm": 0.1061021164059639, + "elapsed": 1068.1370933055878 + }, + { + "step": 3328, + "loss": 0.32664671540260315, + "error": 0.154296875, + "gradient_norm": 0.05649850144982338, + "elapsed": 1073.1963467597961 + }, + { + "step": 3344, + "loss": 0.2655770182609558, + "error": 0.1220703125, + "gradient_norm": 0.04070372134447098, + "elapsed": 1078.2698318958282 + }, + { + "step": 3360, + "loss": 0.5894330739974976, + "error": 0.3544921875, + "gradient_norm": 0.0643400028347969, + "elapsed": 1083.0184152126312 + }, + { + "step": 3376, + "loss": 0.6118791103363037, + "error": 0.361328125, + "gradient_norm": 0.08537904173135757, + "elapsed": 1087.834038734436 + }, + { + "step": 3392, + "loss": 0.40694907307624817, + "error": 0.19921875, + "gradient_norm": 0.11411692947149277, + "elapsed": 1092.8119947910309 + }, + { + "step": 3408, + "loss": 0.04629015550017357, + "error": 0.0146484375, + "gradient_norm": 0.017204072326421738, + "elapsed": 1097.5751783847809 + }, + { + "step": 3424, + "loss": 0.20639702677726746, + "error": 0.0849609375, + "gradient_norm": 0.04801144450902939, + "elapsed": 1102.2970931529999 + }, + { + "step": 3440, + "loss": 0.6051071286201477, + "error": 0.33984375, + "gradient_norm": 0.045392412692308426, + "elapsed": 1107.1080610752106 + }, + { + "step": 3456, + "loss": 0.6553700566291809, + "error": 0.40625, + "gradient_norm": 0.05593863129615784, + "elapsed": 1111.8409752845764 + }, + { + "step": 3472, + "loss": 0.591402530670166, + "error": 0.3515625, + "gradient_norm": 0.051181379705667496, + "elapsed": 1116.5800333023071 + }, + { + "step": 3488, + "loss": 0.30494624376296997, + "error": 0.12109375, + "gradient_norm": 0.05175542086362839, + "elapsed": 1121.276373386383 + }, + { + "step": 3504, + "loss": 0.5065370798110962, + "error": 0.279296875, + "gradient_norm": 0.10419930517673492, + "elapsed": 1125.9883344173431 + }, + { + "step": 3520, + "loss": 0.3915700614452362, + "error": 0.1953125, + "gradient_norm": 0.060416825115680695, + "elapsed": 1130.7958455085754 + }, + { + "step": 3536, + "loss": 0.624374270439148, + "error": 0.3759765625, + "gradient_norm": 0.06069556251168251, + "elapsed": 1135.5360939502716 + }, + { + "step": 3552, + "loss": 0.5830206274986267, + "error": 0.3359375, + "gradient_norm": 0.046013280749320984, + "elapsed": 1140.312029838562 + }, + { + "step": 3568, + "loss": 0.4201379716396332, + "error": 0.2119140625, + "gradient_norm": 0.06909621506929398, + "elapsed": 1145.0904593467712 + }, + { + "step": 3584, + "loss": 0.28215405344963074, + "error": 0.1181640625, + "gradient_norm": 0.07625982910394669, + "elapsed": 1149.8156151771545 + }, + { + "step": 3600, + "loss": 0.5229164361953735, + "error": 0.275390625, + "gradient_norm": 0.055048178881406784, + "elapsed": 1154.5280592441559 + }, + { + "step": 3616, + "loss": 0.47238075733184814, + "error": 0.2314453125, + "gradient_norm": 0.06473162025213242, + "elapsed": 1159.2720873355865 + }, + { + "step": 3632, + "loss": 0.46245503425598145, + "error": 0.228515625, + "gradient_norm": 0.07382887601852417, + "elapsed": 1164.0119998455048 + }, + { + "step": 3648, + "loss": 0.37509745359420776, + "error": 0.171875, + "gradient_norm": 0.051260266453027725, + "elapsed": 1168.7440350055695 + }, + { + "step": 3664, + "loss": 0.1948484629392624, + "error": 0.080078125, + "gradient_norm": 0.059623416513204575, + "elapsed": 1173.3906588554382 + }, + { + "step": 3680, + "loss": 0.5552756786346436, + "error": 0.3115234375, + "gradient_norm": 0.08073585480451584, + "elapsed": 1178.0645008087158 + }, + { + "step": 3696, + "loss": 0.6405904293060303, + "error": 0.39453125, + "gradient_norm": 0.05899551138281822, + "elapsed": 1182.730489730835 + }, + { + "step": 3712, + "loss": 0.2767012119293213, + "error": 0.119140625, + "gradient_norm": 0.06593579798936844, + "elapsed": 1187.377315044403 + }, + { + "step": 3728, + "loss": 0.315812885761261, + "error": 0.134765625, + "gradient_norm": 0.035905495285987854, + "elapsed": 1192.0582301616669 + }, + { + "step": 3744, + "loss": 0.6033951640129089, + "error": 0.3544921875, + "gradient_norm": 0.05226197466254234, + "elapsed": 1196.7101175785065 + }, + { + "step": 3760, + "loss": 0.5202592611312866, + "error": 0.275390625, + "gradient_norm": 0.06367512047290802, + "elapsed": 1201.3543090820312 + }, + { + "step": 3776, + "loss": 0.24639368057250977, + "error": 0.1083984375, + "gradient_norm": 0.09370873868465424, + "elapsed": 1206.0717165470123 + }, + { + "step": 3792, + "loss": 0.6175658702850342, + "error": 0.375, + "gradient_norm": 0.06221585348248482, + "elapsed": 1210.754029750824 + }, + { + "step": 3808, + "loss": 0.41153696179389954, + "error": 0.2119140625, + "gradient_norm": 0.05355365574359894, + "elapsed": 1215.4374370574951 + }, + { + "step": 3824, + "loss": 0.28002214431762695, + "error": 0.1123046875, + "gradient_norm": 0.03846330568194389, + "elapsed": 1220.1207013130188 + }, + { + "step": 3840, + "loss": 0.0484195351600647, + "error": 0.013671875, + "gradient_norm": 0.03470242768526077, + "elapsed": 1224.8153104782104 + }, + { + "step": 3856, + "loss": 0.1407160609960556, + "error": 0.0458984375, + "gradient_norm": 0.04061700031161308, + "elapsed": 1229.5512235164642 + }, + { + "step": 3872, + "loss": 0.5881794691085815, + "error": 0.3427734375, + "gradient_norm": 0.062013477087020874, + "elapsed": 1234.3750183582306 + }, + { + "step": 3888, + "loss": 0.17833612859249115, + "error": 0.06640625, + "gradient_norm": 0.038856204599142075, + "elapsed": 1239.110375881195 + }, + { + "step": 3904, + "loss": 0.06211477518081665, + "error": 0.0224609375, + "gradient_norm": 0.02150108851492405, + "elapsed": 1243.800644159317 + }, + { + "step": 3920, + "loss": 0.06039723381400108, + "error": 0.01953125, + "gradient_norm": 0.019367367029190063, + "elapsed": 1248.4831748008728 + }, + { + "step": 3936, + "loss": 0.6010214686393738, + "error": 0.3525390625, + "gradient_norm": 0.051659151911735535, + "elapsed": 1253.1423478126526 + }, + { + "step": 3952, + "loss": 0.5867137312889099, + "error": 0.3388671875, + "gradient_norm": 0.058528851717710495, + "elapsed": 1257.9799931049347 + }, + { + "step": 3968, + "loss": 0.5231834650039673, + "error": 0.2578125, + "gradient_norm": 0.10128334909677505, + "elapsed": 1262.6990082263947 + }, + { + "step": 3984, + "loss": 0.6251651644706726, + "error": 0.353515625, + "gradient_norm": 0.06211795285344124, + "elapsed": 1267.4289934635162 + }, + { + "step": 4000, + "loss": 0.06667037308216095, + "error": 0.01953125, + "gradient_norm": 0.048018258064985275, + "elapsed": 1272.132089138031 + }, + { + "step": 4016, + "loss": 0.5286938548088074, + "error": 0.2744140625, + "gradient_norm": 0.05509360507130623, + "elapsed": 1276.8878977298737 + }, + { + "step": 4032, + "loss": 0.34016552567481995, + "error": 0.1591796875, + "gradient_norm": 0.07597329467535019, + "elapsed": 1281.7364926338196 + }, + { + "step": 4048, + "loss": 0.17750494182109833, + "error": 0.078125, + "gradient_norm": 0.06314503401517868, + "elapsed": 1286.5033600330353 + }, + { + "step": 4064, + "loss": 0.5882893800735474, + "error": 0.34375, + "gradient_norm": 0.10986580699682236, + "elapsed": 1291.1944887638092 + }, + { + "step": 4080, + "loss": 0.4923543930053711, + "error": 0.2568359375, + "gradient_norm": 0.050325747579336166, + "elapsed": 1295.9372322559357 + }, + { + "step": 4096, + "loss": 0.44146978855133057, + "error": 0.2236328125, + "gradient_norm": 0.06535191088914871, + "elapsed": 1300.641023159027 + } + ] + }, + "training_source_snapshot": "training_sources/temporal2", + "selected_checkpoint_steps": [ + "1024", + "2048", + "4096" + ], + "checkpoint_records": { + "1024": { + "step": 1024, + "new_training_shots": 1048576, + "unique_training_rows_seen_in_this_phase": 804757, + "weights": "weights-1024.npz", + "weights_sha256": "0d809362d5afe1dc781f716e3aee1a9bc5a8f75fed6cc0ff6339b9abcf600ada", + "validation": "validation-1024.json", + "complete": true + }, + "2048": { + "step": 2048, + "new_training_shots": 2097152, + "unique_training_rows_seen_in_this_phase": 1293629, + "weights": "weights-2048.npz", + "weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "validation": "validation-2048.json", + "complete": true + }, + "4096": { + "step": 4096, + "new_training_shots": 4194304, + "unique_training_rows_seen_in_this_phase": 1778773, + "weights": "weights-4096.npz", + "weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "validation": "validation-4096.json", + "complete": true + } + }, + "selection": "Minimum full-validation mean failure per group among incumbent and listed session-trained checkpoints; when listed, blend candidates average the recorded small-contextual reference and new probabilities equally", + "blend_reference": "/run-state/workspace/research/context_upgrades/continuation2/predictions", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "incumbent": 0.24672475961538465, + "1024": 0.24571814903846154, + "2048": 0.24504206730769232, + "3072": 0.2456129807692308, + "4096": 0.2445763221153846, + "blend-1024": 0.2469501201923077, + "blend-2048": 0.24583834134615387, + "blend-3072": 0.2458984375, + "blend-4096": 0.2456580528846154 + }, + "selected": "4096" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "incumbent": 0.2530348557692308, + "1024": 0.2528545673076923, + "2048": 0.25342548076923077, + "3072": 0.25369591346153847, + "4096": 0.25446213942307694, + "blend-1024": 0.2531550480769231, + "blend-2048": 0.2536658653846154, + "blend-3072": 0.25329026442307695, + "blend-4096": 0.2540264423076923 + }, + "selected": "1024" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "incumbent": 0.23442007211538465, + "1024": 0.23445012019230768, + "2048": 0.2340895432692308, + "3072": 0.23431490384615383, + "4096": 0.23366887019230773, + "blend-1024": 0.23440504807692308, + "blend-2048": 0.2341496394230769, + "blend-3072": 0.23416466346153844, + "blend-4096": 0.23413461538461536 + }, + "selected": "4096" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "incumbent": 0.2392427884615385, + "1024": 0.23949819711538464, + "2048": 0.23907752403846155, + "3072": 0.24014423076923078, + "4096": 0.24064002403846152, + "blend-1024": 0.23916766826923075, + "blend-2048": 0.23886718750000002, + "blend-3072": 0.2392578125, + "blend-4096": 0.23900240384615387 + }, + "selected": "blend-2048" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "incumbent": 0.24630408653846156, + "1024": 0.24649939903846152, + "2048": 0.2460486778846154, + "3072": 0.24523737980769228, + "4096": 0.24463641826923077, + "blend-1024": 0.24615384615384614, + "blend-2048": 0.2456580528846154, + "blend-3072": 0.24583834134615384, + "blend-4096": 0.24576322115384613 + }, + "selected": "4096" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "incumbent": 0.23760516826923078, + "1024": 0.23733473557692308, + "2048": 0.23652343749999996, + "3072": 0.23795072115384613, + "4096": 0.2379807692307692, + "blend-1024": 0.23713942307692307, + "blend-2048": 0.23740985576923077, + "blend-3072": 0.23811598557692307, + "blend-4096": 0.23780048076923077 + }, + "selected": "2048" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "incumbent": 0.2371694711538461, + "1024": 0.23689903846153845, + "2048": 0.2371243990384615, + "3072": 0.2371844951923077, + "4096": 0.23562199519230764, + "blend-1024": 0.23715444711538464, + "blend-2048": 0.23662860576923078, + "blend-3072": 0.23712439903846153, + "blend-4096": 0.23643329326923077 + }, + "selected": "4096" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "incumbent": 0.23342848557692306, + "1024": 0.23353365384615385, + "2048": 0.23429987980769232, + "3072": 0.2335637019230769, + "4096": 0.2329627403846154, + "blend-1024": 0.23350360576923074, + "blend-2048": 0.23383413461538463, + "blend-3072": 0.23357872596153847, + "blend-4096": 0.2333533653846154 + }, + "selected": "4096" + }, + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.2325420673076923 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22017728365384615 + }, + "selected": "incumbent" + } + ] + }, + { + "name": "temporal2_swa", + "training_run": { + "initialization": "Uniform averages of the same session-trained temporal trajectory; no external weights", + "optimizer_updates_in_derived_run": 0, + "source_training_provenance": { + "initialization": "Continue from this session's trained checkpoint", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "training_source_sha256": { + "learned_exact__temporal_train.py": "7d48d2fc7f62d0bec3023b3df1c2ac28537d0417966131ae3a156697a34cda5f", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "eligible_training_shots": 2067520, + "unique_training_rows_seen_in_this_phase": 1778773, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_3_5": 18357, + "surface_code_bX_d3_r03_center_3_5": 16816, + "surface_code_bX_d3_r05_center_3_5": 17999, + "surface_code_bX_d3_r07_center_3_5": 15225, + "surface_code_bX_d3_r09_center_3_5": 16132, + "surface_code_bX_d3_r11_center_3_5": 17041, + "surface_code_bX_d3_r13_center_3_5": 18477, + "surface_code_bX_d3_r15_center_3_5": 18214, + "surface_code_bX_d3_r17_center_3_5": 16505, + "surface_code_bX_d3_r19_center_3_5": 17120, + "surface_code_bX_d3_r21_center_3_5": 17563, + "surface_code_bX_d3_r23_center_3_5": 16681, + "surface_code_bX_d3_r25_center_3_5": 18379, + "surface_code_bX_d3_r01_center_5_3": 17450, + "surface_code_bX_d3_r03_center_5_3": 17161, + "surface_code_bX_d3_r05_center_5_3": 15797, + "surface_code_bX_d3_r07_center_5_3": 17800, + "surface_code_bX_d3_r09_center_5_3": 17190, + "surface_code_bX_d3_r11_center_5_3": 15840, + "surface_code_bX_d3_r13_center_5_3": 15178, + "surface_code_bX_d3_r15_center_5_3": 14897, + "surface_code_bX_d3_r17_center_5_3": 18252, + "surface_code_bX_d3_r19_center_5_3": 17083, + "surface_code_bX_d3_r21_center_5_3": 17229, + "surface_code_bX_d3_r23_center_5_3": 14735, + "surface_code_bX_d3_r25_center_5_3": 17949, + "surface_code_bX_d3_r01_center_5_7": 17431, + "surface_code_bX_d3_r03_center_5_7": 16583, + "surface_code_bX_d3_r05_center_5_7": 16891, + "surface_code_bX_d3_r07_center_5_7": 17969, + "surface_code_bX_d3_r09_center_5_7": 17966, + "surface_code_bX_d3_r11_center_5_7": 14424, + "surface_code_bX_d3_r13_center_5_7": 16930, + "surface_code_bX_d3_r15_center_5_7": 15205, + "surface_code_bX_d3_r17_center_5_7": 18252, + "surface_code_bX_d3_r19_center_5_7": 17077, + "surface_code_bX_d3_r21_center_5_7": 16770, + "surface_code_bX_d3_r23_center_5_7": 17308, + "surface_code_bX_d3_r25_center_5_7": 17481, + "surface_code_bX_d3_r01_center_7_5": 16630, + "surface_code_bX_d3_r03_center_7_5": 17439, + "surface_code_bX_d3_r05_center_7_5": 15811, + "surface_code_bX_d3_r07_center_7_5": 16637, + "surface_code_bX_d3_r09_center_7_5": 18306, + "surface_code_bX_d3_r11_center_7_5": 18327, + "surface_code_bX_d3_r13_center_7_5": 17974, + "surface_code_bX_d3_r15_center_7_5": 16106, + "surface_code_bX_d3_r17_center_7_5": 15834, + "surface_code_bX_d3_r19_center_7_5": 17242, + "surface_code_bX_d3_r21_center_7_5": 17889, + "surface_code_bX_d3_r23_center_7_5": 17440, + "surface_code_bX_d3_r25_center_7_5": 17087, + "surface_code_bZ_d3_r01_center_3_5": 16236, + "surface_code_bZ_d3_r03_center_3_5": 17278, + "surface_code_bZ_d3_r05_center_3_5": 16577, + "surface_code_bZ_d3_r07_center_3_5": 17376, + "surface_code_bZ_d3_r09_center_3_5": 16000, + "surface_code_bZ_d3_r11_center_3_5": 15634, + "surface_code_bZ_d3_r13_center_3_5": 14950, + "surface_code_bZ_d3_r15_center_3_5": 16600, + "surface_code_bZ_d3_r17_center_3_5": 15381, + "surface_code_bZ_d3_r19_center_3_5": 16823, + "surface_code_bZ_d3_r21_center_3_5": 18789, + "surface_code_bZ_d3_r23_center_3_5": 15616, + "surface_code_bZ_d3_r25_center_3_5": 17088, + "surface_code_bZ_d3_r01_center_5_3": 17935, + "surface_code_bZ_d3_r03_center_5_3": 16256, + "surface_code_bZ_d3_r05_center_5_3": 17959, + "surface_code_bZ_d3_r07_center_5_3": 18401, + "surface_code_bZ_d3_r09_center_5_3": 16405, + "surface_code_bZ_d3_r11_center_5_3": 17274, + "surface_code_bZ_d3_r13_center_5_3": 18172, + "surface_code_bZ_d3_r15_center_5_3": 17525, + "surface_code_bZ_d3_r17_center_5_3": 18643, + "surface_code_bZ_d3_r19_center_5_3": 17816, + "surface_code_bZ_d3_r21_center_5_3": 17404, + "surface_code_bZ_d3_r23_center_5_3": 17253, + "surface_code_bZ_d3_r25_center_5_3": 17667, + "surface_code_bZ_d3_r01_center_5_7": 16203, + "surface_code_bZ_d3_r03_center_5_7": 17214, + "surface_code_bZ_d3_r05_center_5_7": 16799, + "surface_code_bZ_d3_r07_center_5_7": 17896, + "surface_code_bZ_d3_r09_center_5_7": 16411, + "surface_code_bZ_d3_r11_center_5_7": 17726, + "surface_code_bZ_d3_r13_center_5_7": 16313, + "surface_code_bZ_d3_r15_center_5_7": 17824, + "surface_code_bZ_d3_r17_center_5_7": 15656, + "surface_code_bZ_d3_r19_center_5_7": 17169, + "surface_code_bZ_d3_r21_center_5_7": 17194, + "surface_code_bZ_d3_r23_center_5_7": 16779, + "surface_code_bZ_d3_r25_center_5_7": 16970, + "surface_code_bZ_d3_r01_center_7_5": 16762, + "surface_code_bZ_d3_r03_center_7_5": 17320, + "surface_code_bZ_d3_r05_center_7_5": 17522, + "surface_code_bZ_d3_r07_center_7_5": 17914, + "surface_code_bZ_d3_r09_center_7_5": 18439, + "surface_code_bZ_d3_r11_center_7_5": 18218, + "surface_code_bZ_d3_r13_center_7_5": 17907, + "surface_code_bZ_d3_r15_center_7_5": 17597, + "surface_code_bZ_d3_r17_center_7_5": 18252, + "surface_code_bZ_d3_r19_center_7_5": 18379, + "surface_code_bZ_d3_r21_center_7_5": 16818, + "surface_code_bZ_d3_r23_center_7_5": 18430, + "surface_code_bZ_d3_r25_center_7_5": 17924 + }, + "steps": 4096, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.0005, + "sampling_seed": 20261121, + "optimizer_restored": true, + "rng_restored": true, + "sampling_state_source": "/run-state/workspace/research/learned_exact/temporal1/rng-2048.json", + "session_trained_starting_checkpoint": "/run-state/workspace/research/learned_exact/temporal1/weights-2048.npz", + "starting_checkpoint_sha256": "26be9e0259b69a5870bf73e80a5a29fcf3519a3ff63e1d219c57a2113d9d34be", + "starting_training_provenance": { + "initialization": "Continue from rich weights trained from random initialization in this session; new temporal parameters randomly initialized now", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "steps": 2048, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.001, + "sampling_seed": 20261111, + "optimizer_restored": false, + "rng_restored": false, + "session_trained_starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.6317505836486816, + "error": 0.3681640625, + "gradient_norm": 0.04013459011912346, + "elapsed": 30.971998691558838 + }, + { + "step": 16, + "loss": 0.5091081857681274, + "error": 0.291015625, + "gradient_norm": 0.042228709906339645, + "elapsed": 35.17463397979736 + }, + { + "step": 32, + "loss": 0.626472532749176, + "error": 0.3642578125, + "gradient_norm": 0.05872415751218796, + "elapsed": 39.678136110305786 + }, + { + "step": 48, + "loss": 0.6005369424819946, + "error": 0.3515625, + "gradient_norm": 0.03848014399409294, + "elapsed": 44.16946887969971 + }, + { + "step": 64, + "loss": 0.5523768663406372, + "error": 0.302734375, + "gradient_norm": 0.06031862646341324, + "elapsed": 48.65217089653015 + }, + { + "step": 80, + "loss": 0.3981674611568451, + "error": 0.19921875, + "gradient_norm": 0.0542079322040081, + "elapsed": 53.21601867675781 + }, + { + "step": 96, + "loss": 0.5601426362991333, + "error": 0.2978515625, + "gradient_norm": 0.04770371690392494, + "elapsed": 57.81089663505554 + }, + { + "step": 112, + "loss": 0.5878150463104248, + "error": 0.34765625, + "gradient_norm": 0.10699950158596039, + "elapsed": 62.42190766334534 + }, + { + "step": 128, + "loss": 0.5232458114624023, + "error": 0.2861328125, + "gradient_norm": 0.0911584198474884, + "elapsed": 67.00223755836487 + }, + { + "step": 144, + "loss": 0.6119767427444458, + "error": 0.3623046875, + "gradient_norm": 0.062474437057971954, + "elapsed": 71.54070782661438 + }, + { + "step": 160, + "loss": 0.3037984371185303, + "error": 0.1474609375, + "gradient_norm": 0.05718141421675682, + "elapsed": 76.08167362213135 + }, + { + "step": 176, + "loss": 0.6038273572921753, + "error": 0.3662109375, + "gradient_norm": 0.0437164381146431, + "elapsed": 80.71864247322083 + }, + { + "step": 192, + "loss": 0.3304370641708374, + "error": 0.1572265625, + "gradient_norm": 0.05684761330485344, + "elapsed": 85.54437017440796 + }, + { + "step": 208, + "loss": 0.5785484313964844, + "error": 0.3251953125, + "gradient_norm": 0.09597272425889969, + "elapsed": 91.51522874832153 + }, + { + "step": 224, + "loss": 0.3110499978065491, + "error": 0.13671875, + "gradient_norm": 0.04815748706459999, + "elapsed": 97.1228940486908 + }, + { + "step": 240, + "loss": 0.6213864684104919, + "error": 0.3623046875, + "gradient_norm": 0.0540502592921257, + "elapsed": 102.90286135673523 + }, + { + "step": 256, + "loss": 0.2535272240638733, + "error": 0.1064453125, + "gradient_norm": 0.029962118715047836, + "elapsed": 108.39288640022278 + }, + { + "step": 272, + "loss": 0.6126939058303833, + "error": 0.3671875, + "gradient_norm": 0.06887879222631454, + "elapsed": 113.83897161483765 + }, + { + "step": 288, + "loss": 0.4556676149368286, + "error": 0.2236328125, + "gradient_norm": 0.16127081215381622, + "elapsed": 119.93085813522339 + }, + { + "step": 304, + "loss": 0.4973585605621338, + "error": 0.255859375, + "gradient_norm": 0.08082302659749985, + "elapsed": 125.90891909599304 + }, + { + "step": 320, + "loss": 0.6455868482589722, + "error": 0.419921875, + "gradient_norm": 0.04339660331606865, + "elapsed": 131.20537638664246 + }, + { + "step": 336, + "loss": 0.5343132615089417, + "error": 0.2880859375, + "gradient_norm": 0.07518009096384048, + "elapsed": 136.59086871147156 + }, + { + "step": 352, + "loss": 0.6505346894264221, + "error": 0.4033203125, + "gradient_norm": 0.03800992667675018, + "elapsed": 142.21085906028748 + }, + { + "step": 368, + "loss": 0.4882712960243225, + "error": 0.251953125, + "gradient_norm": 0.08170920610427856, + "elapsed": 146.95903658866882 + }, + { + "step": 384, + "loss": 0.5292021036148071, + "error": 0.296875, + "gradient_norm": 0.08454013615846634, + "elapsed": 151.6385259628296 + }, + { + "step": 400, + "loss": 0.6272899508476257, + "error": 0.3837890625, + "gradient_norm": 0.051436979323625565, + "elapsed": 156.3343904018402 + }, + { + "step": 416, + "loss": 0.052130259573459625, + "error": 0.0166015625, + "gradient_norm": 0.02377190627157688, + "elapsed": 160.92345547676086 + }, + { + "step": 432, + "loss": 0.5256737470626831, + "error": 0.3046875, + "gradient_norm": 0.07986386120319366, + "elapsed": 165.52879118919373 + }, + { + "step": 448, + "loss": 0.15193665027618408, + "error": 0.0576171875, + "gradient_norm": 0.06491660326719284, + "elapsed": 170.14827823638916 + }, + { + "step": 464, + "loss": 0.6418055295944214, + "error": 0.40625, + "gradient_norm": 0.07290885597467422, + "elapsed": 174.64974284172058 + }, + { + "step": 480, + "loss": 0.6055159568786621, + "error": 0.357421875, + "gradient_norm": 0.0795595794916153, + "elapsed": 179.17218685150146 + }, + { + "step": 496, + "loss": 0.6372283697128296, + "error": 0.3916015625, + "gradient_norm": 0.04387903958559036, + "elapsed": 183.77568197250366 + }, + { + "step": 512, + "loss": 0.637977123260498, + "error": 0.408203125, + "gradient_norm": 0.060665905475616455, + "elapsed": 188.31205368041992 + }, + { + "step": 528, + "loss": 0.4668862223625183, + "error": 0.2451171875, + "gradient_norm": 0.08566711097955704, + "elapsed": 206.40719985961914 + }, + { + "step": 544, + "loss": 0.4584413170814514, + "error": 0.244140625, + "gradient_norm": 0.08538200706243515, + "elapsed": 211.02819895744324 + }, + { + "step": 560, + "loss": 0.5615692138671875, + "error": 0.3291015625, + "gradient_norm": 0.043748609721660614, + "elapsed": 215.66470766067505 + }, + { + "step": 576, + "loss": 0.5151895880699158, + "error": 0.2880859375, + "gradient_norm": 0.05164863541722298, + "elapsed": 220.18949556350708 + }, + { + "step": 592, + "loss": 0.5618112087249756, + "error": 0.3291015625, + "gradient_norm": 0.05998719856142998, + "elapsed": 224.7216100692749 + }, + { + "step": 608, + "loss": 0.659294843673706, + "error": 0.431640625, + "gradient_norm": 0.09910348802804947, + "elapsed": 229.26827573776245 + }, + { + "step": 624, + "loss": 0.5895233154296875, + "error": 0.3447265625, + "gradient_norm": 0.045334093272686005, + "elapsed": 233.83731055259705 + }, + { + "step": 640, + "loss": 0.6081801056861877, + "error": 0.3388671875, + "gradient_norm": 0.06578423827886581, + "elapsed": 238.36345624923706 + }, + { + "step": 656, + "loss": 0.5349816083908081, + "error": 0.2939453125, + "gradient_norm": 0.09989562630653381, + "elapsed": 242.95086026191711 + }, + { + "step": 672, + "loss": 0.5871994495391846, + "error": 0.328125, + "gradient_norm": 0.08132346719503403, + "elapsed": 247.67088556289673 + }, + { + "step": 688, + "loss": 0.06012660637497902, + "error": 0.0146484375, + "gradient_norm": 0.012170507572591305, + "elapsed": 252.3202247619629 + }, + { + "step": 704, + "loss": 0.42179757356643677, + "error": 0.21484375, + "gradient_norm": 0.08384513854980469, + "elapsed": 256.91991782188416 + }, + { + "step": 720, + "loss": 0.6111758947372437, + "error": 0.3720703125, + "gradient_norm": 0.06689880788326263, + "elapsed": 261.56407928466797 + }, + { + "step": 736, + "loss": 0.29969727993011475, + "error": 0.1318359375, + "gradient_norm": 0.0743367150425911, + "elapsed": 266.22199630737305 + }, + { + "step": 752, + "loss": 0.051849883049726486, + "error": 0.0166015625, + "gradient_norm": 0.017005126923322678, + "elapsed": 270.8602342605591 + }, + { + "step": 768, + "loss": 0.6178420186042786, + "error": 0.3759765625, + "gradient_norm": 0.027732960879802704, + "elapsed": 275.47888374328613 + }, + { + "step": 784, + "loss": 0.45798996090888977, + "error": 0.228515625, + "gradient_norm": 0.0630083829164505, + "elapsed": 280.1709156036377 + }, + { + "step": 800, + "loss": 0.5104988813400269, + "error": 0.2724609375, + "gradient_norm": 0.041733670979738235, + "elapsed": 286.17937707901 + }, + { + "step": 816, + "loss": 0.6336112022399902, + "error": 0.3837890625, + "gradient_norm": 0.0755191296339035, + "elapsed": 291.7506103515625 + }, + { + "step": 832, + "loss": 0.6260952353477478, + "error": 0.3603515625, + "gradient_norm": 0.0318005345761776, + "elapsed": 297.31094622612 + }, + { + "step": 848, + "loss": 0.5870074033737183, + "error": 0.3525390625, + "gradient_norm": 0.12073405832052231, + "elapsed": 303.11089158058167 + }, + { + "step": 864, + "loss": 0.5125640034675598, + "error": 0.26953125, + "gradient_norm": 0.038650237023830414, + "elapsed": 308.7288725376129 + }, + { + "step": 880, + "loss": 0.19194915890693665, + "error": 0.0703125, + "gradient_norm": 0.061878547072410583, + "elapsed": 314.37042355537415 + }, + { + "step": 896, + "loss": 0.5409250259399414, + "error": 0.2919921875, + "gradient_norm": 0.06288820505142212, + "elapsed": 319.9398190975189 + }, + { + "step": 912, + "loss": 0.6164936423301697, + "error": 0.3701171875, + "gradient_norm": 0.043224163353443146, + "elapsed": 325.361323595047 + }, + { + "step": 928, + "loss": 0.16032151877880096, + "error": 0.0625, + "gradient_norm": 0.030957572162151337, + "elapsed": 331.21752285957336 + }, + { + "step": 944, + "loss": 0.646601676940918, + "error": 0.3818359375, + "gradient_norm": 0.05670839175581932, + "elapsed": 336.7825517654419 + }, + { + "step": 960, + "loss": 0.402952641248703, + "error": 0.1865234375, + "gradient_norm": 0.07500886172056198, + "elapsed": 342.6888346672058 + }, + { + "step": 976, + "loss": 0.5537433624267578, + "error": 0.2939453125, + "gradient_norm": 0.04955969750881195, + "elapsed": 348.5554690361023 + }, + { + "step": 992, + "loss": 0.559626579284668, + "error": 0.294921875, + "gradient_norm": 0.048295993357896805, + "elapsed": 354.3531894683838 + }, + { + "step": 1008, + "loss": 0.5034694671630859, + "error": 0.2705078125, + "gradient_norm": 0.05729879066348076, + "elapsed": 360.0949149131775 + }, + { + "step": 1024, + "loss": 0.3119734525680542, + "error": 0.1259765625, + "gradient_norm": 0.052326612174510956, + "elapsed": 365.7881224155426 + }, + { + "step": 1040, + "loss": 0.35799849033355713, + "error": 0.173828125, + "gradient_norm": 0.03801804035902023, + "elapsed": 386.5749418735504 + }, + { + "step": 1056, + "loss": 0.6178948879241943, + "error": 0.3515625, + "gradient_norm": 0.03620661422610283, + "elapsed": 391.48247838020325 + }, + { + "step": 1072, + "loss": 0.49231401085853577, + "error": 0.24609375, + "gradient_norm": 0.04391559213399887, + "elapsed": 396.08718824386597 + }, + { + "step": 1088, + "loss": 0.4119300842285156, + "error": 0.2001953125, + "gradient_norm": 0.1104700043797493, + "elapsed": 400.5326828956604 + }, + { + "step": 1104, + "loss": 0.4926626682281494, + "error": 0.265625, + "gradient_norm": 0.04246886447072029, + "elapsed": 404.95741271972656 + }, + { + "step": 1120, + "loss": 0.5027930736541748, + "error": 0.2607421875, + "gradient_norm": 0.0547240674495697, + "elapsed": 409.40319633483887 + }, + { + "step": 1136, + "loss": 0.5948058366775513, + "error": 0.3544921875, + "gradient_norm": 0.06810063123703003, + "elapsed": 413.8514006137848 + }, + { + "step": 1152, + "loss": 0.26567256450653076, + "error": 0.125, + "gradient_norm": 0.06689104437828064, + "elapsed": 418.29868721961975 + }, + { + "step": 1168, + "loss": 0.2866836190223694, + "error": 0.1240234375, + "gradient_norm": 0.029536213725805283, + "elapsed": 422.75131845474243 + }, + { + "step": 1184, + "loss": 0.6342021822929382, + "error": 0.4091796875, + "gradient_norm": 0.0704190731048584, + "elapsed": 427.1991722583771 + }, + { + "step": 1200, + "loss": 0.41626787185668945, + "error": 0.212890625, + "gradient_norm": 0.04480795934796333, + "elapsed": 431.6600706577301 + }, + { + "step": 1216, + "loss": 0.28460952639579773, + "error": 0.1337890625, + "gradient_norm": 0.03666983172297478, + "elapsed": 436.14414525032043 + }, + { + "step": 1232, + "loss": 0.044482216238975525, + "error": 0.0146484375, + "gradient_norm": 0.04537617415189743, + "elapsed": 440.6220428943634 + }, + { + "step": 1248, + "loss": 0.42564862966537476, + "error": 0.2119140625, + "gradient_norm": 0.03382417559623718, + "elapsed": 445.06736421585083 + }, + { + "step": 1264, + "loss": 0.27150213718414307, + "error": 0.123046875, + "gradient_norm": 0.033046118915081024, + "elapsed": 449.544029712677 + }, + { + "step": 1280, + "loss": 0.4927375912666321, + "error": 0.255859375, + "gradient_norm": 0.06812550127506256, + "elapsed": 454.07198667526245 + }, + { + "step": 1296, + "loss": 0.5541940927505493, + "error": 0.28125, + "gradient_norm": 0.1435294896364212, + "elapsed": 458.6031415462494 + }, + { + "step": 1312, + "loss": 0.5575842261314392, + "error": 0.2958984375, + "gradient_norm": 0.03811952844262123, + "elapsed": 463.1806228160858 + }, + { + "step": 1328, + "loss": 0.3479428291320801, + "error": 0.1591796875, + "gradient_norm": 0.0709012895822525, + "elapsed": 467.84689688682556 + }, + { + "step": 1344, + "loss": 0.1685580611228943, + "error": 0.0693359375, + "gradient_norm": 0.05423415079712868, + "elapsed": 472.6908576488495 + }, + { + "step": 1360, + "loss": 0.18506410717964172, + "error": 0.0771484375, + "gradient_norm": 0.03418596833944321, + "elapsed": 477.4269769191742 + }, + { + "step": 1376, + "loss": 0.5654555559158325, + "error": 0.3173828125, + "gradient_norm": 0.0685155838727951, + "elapsed": 482.08285188674927 + }, + { + "step": 1392, + "loss": 0.6116407513618469, + "error": 0.3603515625, + "gradient_norm": 0.05198948457837105, + "elapsed": 486.7167499065399 + }, + { + "step": 1408, + "loss": 0.4014682471752167, + "error": 0.19140625, + "gradient_norm": 0.1024075523018837, + "elapsed": 491.4308760166168 + }, + { + "step": 1424, + "loss": 0.051035866141319275, + "error": 0.0166015625, + "gradient_norm": 0.010207361541688442, + "elapsed": 496.1818380355835 + }, + { + "step": 1440, + "loss": 0.4725648760795593, + "error": 0.2412109375, + "gradient_norm": 0.03977378085255623, + "elapsed": 500.8668632507324 + }, + { + "step": 1456, + "loss": 0.5407818555831909, + "error": 0.2939453125, + "gradient_norm": 0.088577501475811, + "elapsed": 505.49274134635925 + }, + { + "step": 1472, + "loss": 0.5655064582824707, + "error": 0.3076171875, + "gradient_norm": 0.04452778398990631, + "elapsed": 510.2188584804535 + }, + { + "step": 1488, + "loss": 0.5799556374549866, + "error": 0.30859375, + "gradient_norm": 0.03976206108927727, + "elapsed": 514.9319434165955 + }, + { + "step": 1504, + "loss": 0.4660354256629944, + "error": 0.25390625, + "gradient_norm": 0.04365506023168564, + "elapsed": 519.5848798751831 + }, + { + "step": 1520, + "loss": 0.5505894422531128, + "error": 0.30859375, + "gradient_norm": 0.057772211730480194, + "elapsed": 524.3388590812683 + }, + { + "step": 1536, + "loss": 0.6251416206359863, + "error": 0.400390625, + "gradient_norm": 0.09649194777011871, + "elapsed": 529.483047246933 + }, + { + "step": 1552, + "loss": 0.05424533039331436, + "error": 0.0185546875, + "gradient_norm": 0.011683990247547626, + "elapsed": 548.1828610897064 + }, + { + "step": 1568, + "loss": 0.33612310886383057, + "error": 0.1611328125, + "gradient_norm": 0.051817383617162704, + "elapsed": 553.4256420135498 + }, + { + "step": 1584, + "loss": 0.045015305280685425, + "error": 0.0166015625, + "gradient_norm": 0.022604886442422867, + "elapsed": 558.6308543682098 + }, + { + "step": 1600, + "loss": 0.2701840102672577, + "error": 0.119140625, + "gradient_norm": 0.02910422720015049, + "elapsed": 563.8571691513062 + }, + { + "step": 1616, + "loss": 0.18982334434986115, + "error": 0.0849609375, + "gradient_norm": 0.025524422526359558, + "elapsed": 568.8628678321838 + }, + { + "step": 1632, + "loss": 0.3950161337852478, + "error": 0.185546875, + "gradient_norm": 0.08419577777385712, + "elapsed": 574.0815451145172 + }, + { + "step": 1648, + "loss": 0.49384528398513794, + "error": 0.255859375, + "gradient_norm": 0.08879344165325165, + "elapsed": 579.1229114532471 + }, + { + "step": 1664, + "loss": 0.5671384930610657, + "error": 0.3115234375, + "gradient_norm": 0.05374513566493988, + "elapsed": 584.114851474762 + }, + { + "step": 1680, + "loss": 0.6192574501037598, + "error": 0.37890625, + "gradient_norm": 0.043836336582899094, + "elapsed": 589.0708522796631 + }, + { + "step": 1696, + "loss": 0.2619469463825226, + "error": 0.1171875, + "gradient_norm": 0.040093280375003815, + "elapsed": 594.2814819812775 + }, + { + "step": 1712, + "loss": 0.33178141713142395, + "error": 0.162109375, + "gradient_norm": 0.04902712255716324, + "elapsed": 599.3068840503693 + }, + { + "step": 1728, + "loss": 0.385281503200531, + "error": 0.171875, + "gradient_norm": 0.03541380167007446, + "elapsed": 604.5308682918549 + }, + { + "step": 1744, + "loss": 0.1628715693950653, + "error": 0.0693359375, + "gradient_norm": 0.06111741065979004, + "elapsed": 609.309522151947 + }, + { + "step": 1760, + "loss": 0.5239119529724121, + "error": 0.2861328125, + "gradient_norm": 0.08513613045215607, + "elapsed": 614.0396001338959 + }, + { + "step": 1776, + "loss": 0.35721707344055176, + "error": 0.150390625, + "gradient_norm": 0.06337940692901611, + "elapsed": 618.6857132911682 + }, + { + "step": 1792, + "loss": 0.5985626578330994, + "error": 0.33203125, + "gradient_norm": 0.035725343972444534, + "elapsed": 623.3352344036102 + }, + { + "step": 1808, + "loss": 0.34676820039749146, + "error": 0.15234375, + "gradient_norm": 0.08163885772228241, + "elapsed": 627.9495220184326 + }, + { + "step": 1824, + "loss": 0.5633711814880371, + "error": 0.3037109375, + "gradient_norm": 0.05938677117228508, + "elapsed": 632.5820379257202 + }, + { + "step": 1840, + "loss": 0.6256523132324219, + "error": 0.384765625, + "gradient_norm": 0.04545137286186218, + "elapsed": 637.205274105072 + }, + { + "step": 1856, + "loss": 0.28091639280319214, + "error": 0.1298828125, + "gradient_norm": 0.04705077037215233, + "elapsed": 641.883561372757 + }, + { + "step": 1872, + "loss": 0.516182541847229, + "error": 0.263671875, + "gradient_norm": 0.08828777819871902, + "elapsed": 646.5188939571381 + }, + { + "step": 1888, + "loss": 0.48386621475219727, + "error": 0.25390625, + "gradient_norm": 0.05322824418544769, + "elapsed": 651.148512840271 + }, + { + "step": 1904, + "loss": 0.6141921281814575, + "error": 0.388671875, + "gradient_norm": 0.050139278173446655, + "elapsed": 655.7796437740326 + }, + { + "step": 1920, + "loss": 0.18002840876579285, + "error": 0.0712890625, + "gradient_norm": 0.04201133921742439, + "elapsed": 660.4064948558807 + }, + { + "step": 1936, + "loss": 0.17531852424144745, + "error": 0.0732421875, + "gradient_norm": 0.024726318195462227, + "elapsed": 664.9991583824158 + }, + { + "step": 1952, + "loss": 0.5088322758674622, + "error": 0.2744140625, + "gradient_norm": 0.04693225398659706, + "elapsed": 669.5544555187225 + }, + { + "step": 1968, + "loss": 0.5684165358543396, + "error": 0.3310546875, + "gradient_norm": 0.031029095873236656, + "elapsed": 674.2354445457458 + }, + { + "step": 1984, + "loss": 0.06459524482488632, + "error": 0.017578125, + "gradient_norm": 0.03600892797112465, + "elapsed": 678.7982559204102 + }, + { + "step": 2000, + "loss": 0.3614455461502075, + "error": 0.1748046875, + "gradient_norm": 0.07060294598340988, + "elapsed": 683.2650325298309 + }, + { + "step": 2016, + "loss": 0.35535523295402527, + "error": 0.166015625, + "gradient_norm": 0.05873403698205948, + "elapsed": 687.7125518321991 + }, + { + "step": 2032, + "loss": 0.5638720989227295, + "error": 0.3232421875, + "gradient_norm": 0.07380504906177521, + "elapsed": 692.1461188793182 + }, + { + "step": 2048, + "loss": 0.5301838517189026, + "error": 0.2919921875, + "gradient_norm": 0.05435395985841751, + "elapsed": 696.6235508918762 + } + ] + }, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.250907301902771, + "error": 0.1083984375, + "gradient_norm": 0.07171476632356644, + "elapsed": 44.811134576797485 + }, + { + "step": 16, + "loss": 0.5958679914474487, + "error": 0.3662109375, + "gradient_norm": 0.07673005014657974, + "elapsed": 49.90856671333313 + }, + { + "step": 32, + "loss": 0.47648972272872925, + "error": 0.2421875, + "gradient_norm": 0.08561501652002335, + "elapsed": 55.179388761520386 + }, + { + "step": 48, + "loss": 0.06145006790757179, + "error": 0.0234375, + "gradient_norm": 0.01556467730551958, + "elapsed": 61.0339195728302 + }, + { + "step": 64, + "loss": 0.3687053918838501, + "error": 0.1884765625, + "gradient_norm": 0.08752371370792389, + "elapsed": 65.95811891555786 + }, + { + "step": 80, + "loss": 0.6481984853744507, + "error": 0.4140625, + "gradient_norm": 0.05311283841729164, + "elapsed": 70.56021332740784 + }, + { + "step": 96, + "loss": 0.42319929599761963, + "error": 0.2138671875, + "gradient_norm": 0.05047478526830673, + "elapsed": 75.11613631248474 + }, + { + "step": 112, + "loss": 0.47527259588241577, + "error": 0.24609375, + "gradient_norm": 0.038366906344890594, + "elapsed": 79.53446984291077 + }, + { + "step": 128, + "loss": 0.5996723175048828, + "error": 0.3369140625, + "gradient_norm": 0.1213272362947464, + "elapsed": 83.97515749931335 + }, + { + "step": 144, + "loss": 0.04971993714570999, + "error": 0.0146484375, + "gradient_norm": 0.008080735802650452, + "elapsed": 88.44039463996887 + }, + { + "step": 160, + "loss": 0.35900360345840454, + "error": 0.162109375, + "gradient_norm": 0.03359593451023102, + "elapsed": 92.89548206329346 + }, + { + "step": 176, + "loss": 0.5342063903808594, + "error": 0.2978515625, + "gradient_norm": 0.04794691130518913, + "elapsed": 97.35658049583435 + }, + { + "step": 192, + "loss": 0.6300076246261597, + "error": 0.369140625, + "gradient_norm": 0.081769198179245, + "elapsed": 101.81493759155273 + }, + { + "step": 208, + "loss": 0.6191903948783875, + "error": 0.3828125, + "gradient_norm": 0.07145775109529495, + "elapsed": 106.2480263710022 + }, + { + "step": 224, + "loss": 0.5155678391456604, + "error": 0.28515625, + "gradient_norm": 0.06772179156541824, + "elapsed": 110.71284222602844 + }, + { + "step": 240, + "loss": 0.634708046913147, + "error": 0.3857421875, + "gradient_norm": 0.09493093192577362, + "elapsed": 115.14978742599487 + }, + { + "step": 256, + "loss": 0.1840895414352417, + "error": 0.0751953125, + "gradient_norm": 0.025586696341633797, + "elapsed": 119.61202120780945 + }, + { + "step": 272, + "loss": 0.2775103449821472, + "error": 0.12890625, + "gradient_norm": 0.06913147866725922, + "elapsed": 124.02584528923035 + }, + { + "step": 288, + "loss": 0.6163080334663391, + "error": 0.3642578125, + "gradient_norm": 0.05895426496863365, + "elapsed": 128.46512532234192 + }, + { + "step": 304, + "loss": 0.5276986360549927, + "error": 0.287109375, + "gradient_norm": 0.06955187022686005, + "elapsed": 132.89240765571594 + }, + { + "step": 320, + "loss": 0.44859516620635986, + "error": 0.22265625, + "gradient_norm": 0.07272452116012573, + "elapsed": 137.32864713668823 + }, + { + "step": 336, + "loss": 0.48315611481666565, + "error": 0.2626953125, + "gradient_norm": 0.03321139141917229, + "elapsed": 141.80009770393372 + }, + { + "step": 352, + "loss": 0.6107717752456665, + "error": 0.3544921875, + "gradient_norm": 0.05243214592337608, + "elapsed": 146.36439752578735 + }, + { + "step": 368, + "loss": 0.6215153932571411, + "error": 0.357421875, + "gradient_norm": 0.04383325204253197, + "elapsed": 150.99996852874756 + }, + { + "step": 384, + "loss": 0.6130329966545105, + "error": 0.35546875, + "gradient_norm": 0.04113119840621948, + "elapsed": 155.62374639511108 + }, + { + "step": 400, + "loss": 0.30471885204315186, + "error": 0.142578125, + "gradient_norm": 0.04447556659579277, + "elapsed": 160.17594957351685 + }, + { + "step": 416, + "loss": 0.6154489517211914, + "error": 0.37109375, + "gradient_norm": 0.04456057772040367, + "elapsed": 164.7639675140381 + }, + { + "step": 432, + "loss": 0.6134694218635559, + "error": 0.337890625, + "gradient_norm": 0.04219559207558632, + "elapsed": 169.32792139053345 + }, + { + "step": 448, + "loss": 0.5463185906410217, + "error": 0.2939453125, + "gradient_norm": 0.07746092975139618, + "elapsed": 173.88445162773132 + }, + { + "step": 464, + "loss": 0.06016772612929344, + "error": 0.01953125, + "gradient_norm": 0.01364185381680727, + "elapsed": 178.42725706100464 + }, + { + "step": 480, + "loss": 0.388141393661499, + "error": 0.18359375, + "gradient_norm": 0.04870256036520004, + "elapsed": 182.99062085151672 + }, + { + "step": 496, + "loss": 0.44524821639060974, + "error": 0.2216796875, + "gradient_norm": 0.03453445807099342, + "elapsed": 187.56396961212158 + }, + { + "step": 512, + "loss": 0.34312355518341064, + "error": 0.154296875, + "gradient_norm": 0.06794509291648865, + "elapsed": 192.27511191368103 + }, + { + "step": 528, + "loss": 0.19467462599277496, + "error": 0.0771484375, + "gradient_norm": 0.042381469160318375, + "elapsed": 197.7108268737793 + }, + { + "step": 544, + "loss": 0.46226584911346436, + "error": 0.2421875, + "gradient_norm": 0.06073570251464844, + "elapsed": 202.97405791282654 + }, + { + "step": 560, + "loss": 0.525318443775177, + "error": 0.2822265625, + "gradient_norm": 0.06954885274171829, + "elapsed": 208.69676971435547 + }, + { + "step": 576, + "loss": 0.6158387064933777, + "error": 0.349609375, + "gradient_norm": 0.07587578892707825, + "elapsed": 214.80397653579712 + }, + { + "step": 592, + "loss": 0.5515886545181274, + "error": 0.298828125, + "gradient_norm": 0.04969338700175285, + "elapsed": 220.27399611473083 + }, + { + "step": 608, + "loss": 0.18365338444709778, + "error": 0.0654296875, + "gradient_norm": 0.08657706528902054, + "elapsed": 224.81246256828308 + }, + { + "step": 624, + "loss": 0.4578855633735657, + "error": 0.2421875, + "gradient_norm": 0.04942100867629051, + "elapsed": 229.45902252197266 + }, + { + "step": 640, + "loss": 0.37826013565063477, + "error": 0.1865234375, + "gradient_norm": 0.047499872744083405, + "elapsed": 233.9695644378662 + }, + { + "step": 656, + "loss": 0.40863412618637085, + "error": 0.2001953125, + "gradient_norm": 0.07845330238342285, + "elapsed": 238.584894657135 + }, + { + "step": 672, + "loss": 0.5640332698822021, + "error": 0.2880859375, + "gradient_norm": 0.057469289749860764, + "elapsed": 243.0929844379425 + }, + { + "step": 688, + "loss": 0.030216243118047714, + "error": 0.0078125, + "gradient_norm": 0.04682641476392746, + "elapsed": 247.581125497818 + }, + { + "step": 704, + "loss": 0.375002384185791, + "error": 0.1826171875, + "gradient_norm": 0.04864194989204407, + "elapsed": 252.1564691066742 + }, + { + "step": 720, + "loss": 0.5145515203475952, + "error": 0.2744140625, + "gradient_norm": 0.052671682089567184, + "elapsed": 256.6466488838196 + }, + { + "step": 736, + "loss": 0.067174531519413, + "error": 0.0224609375, + "gradient_norm": 0.019299577921628952, + "elapsed": 261.1185076236725 + }, + { + "step": 752, + "loss": 0.24909992516040802, + "error": 0.111328125, + "gradient_norm": 0.06907463818788528, + "elapsed": 265.61960339546204 + }, + { + "step": 768, + "loss": 0.5088074207305908, + "error": 0.2744140625, + "gradient_norm": 0.06963017582893372, + "elapsed": 270.07474064826965 + }, + { + "step": 784, + "loss": 0.3783387839794159, + "error": 0.1826171875, + "gradient_norm": 0.05537794530391693, + "elapsed": 274.52722239494324 + }, + { + "step": 800, + "loss": 0.6107200980186462, + "error": 0.3623046875, + "gradient_norm": 0.0470259003341198, + "elapsed": 279.0401859283447 + }, + { + "step": 816, + "loss": 0.5778236389160156, + "error": 0.3212890625, + "gradient_norm": 0.10146680474281311, + "elapsed": 283.5114622116089 + }, + { + "step": 832, + "loss": 0.576002299785614, + "error": 0.3076171875, + "gradient_norm": 0.07760787010192871, + "elapsed": 288.04797434806824 + }, + { + "step": 848, + "loss": 0.6179666519165039, + "error": 0.3740234375, + "gradient_norm": 0.07383852452039719, + "elapsed": 292.60600209236145 + }, + { + "step": 864, + "loss": 0.3105512857437134, + "error": 0.1455078125, + "gradient_norm": 0.052953749895095825, + "elapsed": 297.12180352211 + }, + { + "step": 880, + "loss": 0.4802623987197876, + "error": 0.2548828125, + "gradient_norm": 0.07736275345087051, + "elapsed": 301.6091134548187 + }, + { + "step": 896, + "loss": 0.5572722554206848, + "error": 0.318359375, + "gradient_norm": 0.053303152322769165, + "elapsed": 306.1978073120117 + }, + { + "step": 912, + "loss": 0.34814420342445374, + "error": 0.1669921875, + "gradient_norm": 0.037726350128650665, + "elapsed": 310.78571581840515 + }, + { + "step": 928, + "loss": 0.41743016242980957, + "error": 0.21875, + "gradient_norm": 0.05238872766494751, + "elapsed": 315.24156188964844 + }, + { + "step": 944, + "loss": 0.5757850408554077, + "error": 0.3173828125, + "gradient_norm": 0.05837905779480934, + "elapsed": 319.78475165367126 + }, + { + "step": 960, + "loss": 0.40727972984313965, + "error": 0.197265625, + "gradient_norm": 0.059294261038303375, + "elapsed": 324.2090265750885 + }, + { + "step": 976, + "loss": 0.32715001702308655, + "error": 0.1533203125, + "gradient_norm": 0.11543179303407669, + "elapsed": 328.6462152004242 + }, + { + "step": 992, + "loss": 0.5578742623329163, + "error": 0.314453125, + "gradient_norm": 0.06282714009284973, + "elapsed": 333.0712504386902 + }, + { + "step": 1008, + "loss": 0.5052692294120789, + "error": 0.265625, + "gradient_norm": 0.04039420187473297, + "elapsed": 337.5182821750641 + }, + { + "step": 1024, + "loss": 0.18790806829929352, + "error": 0.08203125, + "gradient_norm": 0.028905188664793968, + "elapsed": 342.08340406417847 + }, + { + "step": 1040, + "loss": 0.6317684650421143, + "error": 0.3681640625, + "gradient_norm": 0.03441835194826126, + "elapsed": 358.8279616832733 + }, + { + "step": 1056, + "loss": 0.40474164485931396, + "error": 0.2021484375, + "gradient_norm": 0.036449309438467026, + "elapsed": 363.30218267440796 + }, + { + "step": 1072, + "loss": 0.518299400806427, + "error": 0.2666015625, + "gradient_norm": 0.0886964276432991, + "elapsed": 367.87997555732727 + }, + { + "step": 1088, + "loss": 0.2522922158241272, + "error": 0.099609375, + "gradient_norm": 0.07553310692310333, + "elapsed": 372.4414882659912 + }, + { + "step": 1104, + "loss": 0.6214810609817505, + "error": 0.3701171875, + "gradient_norm": 0.10188957303762436, + "elapsed": 376.9120502471924 + }, + { + "step": 1120, + "loss": 0.6307054162025452, + "error": 0.3720703125, + "gradient_norm": 0.07353860139846802, + "elapsed": 381.3824534416199 + }, + { + "step": 1136, + "loss": 0.5259381532669067, + "error": 0.2763671875, + "gradient_norm": 0.05779678374528885, + "elapsed": 385.8413143157959 + }, + { + "step": 1152, + "loss": 0.4995541572570801, + "error": 0.259765625, + "gradient_norm": 0.046648140996694565, + "elapsed": 390.28326058387756 + }, + { + "step": 1168, + "loss": 0.6075694561004639, + "error": 0.3701171875, + "gradient_norm": 0.10612073540687561, + "elapsed": 394.8162364959717 + }, + { + "step": 1184, + "loss": 0.2105136513710022, + "error": 0.080078125, + "gradient_norm": 0.0716402605175972, + "elapsed": 399.2960283756256 + }, + { + "step": 1200, + "loss": 0.6371631026268005, + "error": 0.3857421875, + "gradient_norm": 0.0549108125269413, + "elapsed": 403.7899103164673 + }, + { + "step": 1216, + "loss": 0.5450670719146729, + "error": 0.2939453125, + "gradient_norm": 0.11688558012247086, + "elapsed": 408.34677600860596 + }, + { + "step": 1232, + "loss": 0.035783201456069946, + "error": 0.01171875, + "gradient_norm": 0.02951689623296261, + "elapsed": 412.8558337688446 + }, + { + "step": 1248, + "loss": 0.5582903623580933, + "error": 0.3046875, + "gradient_norm": 0.055107031017541885, + "elapsed": 417.29854226112366 + }, + { + "step": 1264, + "loss": 0.5154441595077515, + "error": 0.27734375, + "gradient_norm": 0.04474929720163345, + "elapsed": 421.7792055606842 + }, + { + "step": 1280, + "loss": 0.35227546095848083, + "error": 0.16015625, + "gradient_norm": 0.05024837702512741, + "elapsed": 426.54427456855774 + }, + { + "step": 1296, + "loss": 0.19417589902877808, + "error": 0.0830078125, + "gradient_norm": 0.026926057413220406, + "elapsed": 431.320588350296 + }, + { + "step": 1312, + "loss": 0.4768218398094177, + "error": 0.248046875, + "gradient_norm": 0.15099607408046722, + "elapsed": 435.96817326545715 + }, + { + "step": 1328, + "loss": 0.48580923676490784, + "error": 0.2509765625, + "gradient_norm": 0.08925126492977142, + "elapsed": 440.64917039871216 + }, + { + "step": 1344, + "loss": 0.42041274905204773, + "error": 0.1982421875, + "gradient_norm": 0.08321093022823334, + "elapsed": 445.34370946884155 + }, + { + "step": 1360, + "loss": 0.06403929740190506, + "error": 0.0185546875, + "gradient_norm": 0.03817005455493927, + "elapsed": 449.98669385910034 + }, + { + "step": 1376, + "loss": 0.463126003742218, + "error": 0.2275390625, + "gradient_norm": 0.08894515782594681, + "elapsed": 454.6478977203369 + }, + { + "step": 1392, + "loss": 0.5995306968688965, + "error": 0.373046875, + "gradient_norm": 0.06733685731887817, + "elapsed": 459.35924530029297 + }, + { + "step": 1408, + "loss": 0.49053263664245605, + "error": 0.25, + "gradient_norm": 0.10475508868694305, + "elapsed": 464.100093126297 + }, + { + "step": 1424, + "loss": 0.6220744848251343, + "error": 0.3818359375, + "gradient_norm": 0.03653963655233383, + "elapsed": 468.89601135253906 + }, + { + "step": 1440, + "loss": 0.39706122875213623, + "error": 0.2021484375, + "gradient_norm": 0.04344598576426506, + "elapsed": 474.03999519348145 + }, + { + "step": 1456, + "loss": 0.5386708974838257, + "error": 0.3095703125, + "gradient_norm": 0.12589037418365479, + "elapsed": 478.8600504398346 + }, + { + "step": 1472, + "loss": 0.49776726961135864, + "error": 0.271484375, + "gradient_norm": 0.058137863874435425, + "elapsed": 483.5920066833496 + }, + { + "step": 1488, + "loss": 0.4757428765296936, + "error": 0.2412109375, + "gradient_norm": 0.050453316420316696, + "elapsed": 488.4611999988556 + }, + { + "step": 1504, + "loss": 0.5694847702980042, + "error": 0.337890625, + "gradient_norm": 0.052419569343328476, + "elapsed": 493.26151037216187 + }, + { + "step": 1520, + "loss": 0.5997745990753174, + "error": 0.3603515625, + "gradient_norm": 0.04338108375668526, + "elapsed": 498.0421245098114 + }, + { + "step": 1536, + "loss": 0.6195274591445923, + "error": 0.3876953125, + "gradient_norm": 0.04848463833332062, + "elapsed": 502.8808298110962 + }, + { + "step": 1552, + "loss": 0.46315908432006836, + "error": 0.2353515625, + "gradient_norm": 0.06380566209554672, + "elapsed": 507.5519721508026 + }, + { + "step": 1568, + "loss": 0.605262041091919, + "error": 0.36328125, + "gradient_norm": 0.05077619478106499, + "elapsed": 512.457685470581 + }, + { + "step": 1584, + "loss": 0.48782041668891907, + "error": 0.232421875, + "gradient_norm": 0.09017211943864822, + "elapsed": 517.2960062026978 + }, + { + "step": 1600, + "loss": 0.3881351947784424, + "error": 0.1875, + "gradient_norm": 0.07205695658922195, + "elapsed": 522.0911631584167 + }, + { + "step": 1616, + "loss": 0.4966873526573181, + "error": 0.24609375, + "gradient_norm": 0.0582038015127182, + "elapsed": 526.8861901760101 + }, + { + "step": 1632, + "loss": 0.5844199657440186, + "error": 0.33203125, + "gradient_norm": 0.05101500824093819, + "elapsed": 531.6640138626099 + }, + { + "step": 1648, + "loss": 0.31010180711746216, + "error": 0.1318359375, + "gradient_norm": 0.053135693073272705, + "elapsed": 536.4960391521454 + }, + { + "step": 1664, + "loss": 0.6174807548522949, + "error": 0.3779296875, + "gradient_norm": 0.04161194711923599, + "elapsed": 541.2560484409332 + }, + { + "step": 1680, + "loss": 0.18213607370853424, + "error": 0.0751953125, + "gradient_norm": 0.07171957194805145, + "elapsed": 546.0000085830688 + }, + { + "step": 1696, + "loss": 0.5445692539215088, + "error": 0.2998046875, + "gradient_norm": 0.054499462246894836, + "elapsed": 551.1221191883087 + }, + { + "step": 1712, + "loss": 0.05744167044758797, + "error": 0.017578125, + "gradient_norm": 0.013108699582517147, + "elapsed": 556.5286149978638 + }, + { + "step": 1728, + "loss": 0.6381571292877197, + "error": 0.3896484375, + "gradient_norm": 0.05157556012272835, + "elapsed": 561.8000066280365 + }, + { + "step": 1744, + "loss": 0.5301004648208618, + "error": 0.28125, + "gradient_norm": 0.04218568280339241, + "elapsed": 567.2760035991669 + }, + { + "step": 1760, + "loss": 0.5275102257728577, + "error": 0.26953125, + "gradient_norm": 0.06798839569091797, + "elapsed": 572.5601994991302 + }, + { + "step": 1776, + "loss": 0.6443773508071899, + "error": 0.4091796875, + "gradient_norm": 0.07035460323095322, + "elapsed": 577.9789206981659 + }, + { + "step": 1792, + "loss": 0.6012362241744995, + "error": 0.337890625, + "gradient_norm": 0.05189951881766319, + "elapsed": 583.028017282486 + }, + { + "step": 1808, + "loss": 0.2939091920852661, + "error": 0.12109375, + "gradient_norm": 0.05555355176329613, + "elapsed": 588.0501506328583 + }, + { + "step": 1824, + "loss": 0.2059091478586197, + "error": 0.08984375, + "gradient_norm": 0.045679714530706406, + "elapsed": 593.2120039463043 + }, + { + "step": 1840, + "loss": 0.6289581060409546, + "error": 0.349609375, + "gradient_norm": 0.04742642492055893, + "elapsed": 598.7767763137817 + }, + { + "step": 1856, + "loss": 0.5532636642456055, + "error": 0.294921875, + "gradient_norm": 0.05997413396835327, + "elapsed": 604.0475382804871 + }, + { + "step": 1872, + "loss": 0.45995670557022095, + "error": 0.228515625, + "gradient_norm": 0.05674462765455246, + "elapsed": 609.292379617691 + }, + { + "step": 1888, + "loss": 0.6178656816482544, + "error": 0.359375, + "gradient_norm": 0.08857566863298416, + "elapsed": 614.5639882087708 + }, + { + "step": 1904, + "loss": 0.5531284213066101, + "error": 0.287109375, + "gradient_norm": 0.10257937759160995, + "elapsed": 619.5600035190582 + }, + { + "step": 1920, + "loss": 0.04184349626302719, + "error": 0.013671875, + "gradient_norm": 0.04087059944868088, + "elapsed": 624.6679775714874 + }, + { + "step": 1936, + "loss": 0.5924860239028931, + "error": 0.3505859375, + "gradient_norm": 0.036822713911533356, + "elapsed": 629.936680316925 + }, + { + "step": 1952, + "loss": 0.46996980905532837, + "error": 0.2421875, + "gradient_norm": 0.034442272037267685, + "elapsed": 635.1109762191772 + }, + { + "step": 1968, + "loss": 0.17859068512916565, + "error": 0.0712890625, + "gradient_norm": 0.03440066799521446, + "elapsed": 640.32000207901 + }, + { + "step": 1984, + "loss": 0.6192275285720825, + "error": 0.3701171875, + "gradient_norm": 0.04386439174413681, + "elapsed": 645.6040184497833 + }, + { + "step": 2000, + "loss": 0.6160917282104492, + "error": 0.35546875, + "gradient_norm": 0.06268990784883499, + "elapsed": 650.7723731994629 + }, + { + "step": 2016, + "loss": 0.6343611478805542, + "error": 0.388671875, + "gradient_norm": 0.04243326932191849, + "elapsed": 655.972663640976 + }, + { + "step": 2032, + "loss": 0.062292590737342834, + "error": 0.021484375, + "gradient_norm": 0.016680095344781876, + "elapsed": 660.8079733848572 + }, + { + "step": 2048, + "loss": 0.5316072702407837, + "error": 0.26953125, + "gradient_norm": 0.057860780507326126, + "elapsed": 665.5760209560394 + }, + { + "step": 2064, + "loss": 0.605312705039978, + "error": 0.3623046875, + "gradient_norm": 0.04028146713972092, + "elapsed": 682.7294294834137 + }, + { + "step": 2080, + "loss": 0.56633460521698, + "error": 0.3330078125, + "gradient_norm": 0.09528280049562454, + "elapsed": 687.4644649028778 + }, + { + "step": 2096, + "loss": 0.3905397057533264, + "error": 0.1943359375, + "gradient_norm": 0.049456462264060974, + "elapsed": 692.1492264270782 + }, + { + "step": 2112, + "loss": 0.28124868869781494, + "error": 0.1259765625, + "gradient_norm": 0.059239838272333145, + "elapsed": 696.8701393604279 + }, + { + "step": 2128, + "loss": 0.6364338994026184, + "error": 0.392578125, + "gradient_norm": 0.08667811006307602, + "elapsed": 701.683988571167 + }, + { + "step": 2144, + "loss": 0.20683243870735168, + "error": 0.07421875, + "gradient_norm": 0.1100710779428482, + "elapsed": 706.4000360965729 + }, + { + "step": 2160, + "loss": 0.5912737250328064, + "error": 0.341796875, + "gradient_norm": 0.05641854554414749, + "elapsed": 711.2359964847565 + }, + { + "step": 2176, + "loss": 0.27793264389038086, + "error": 0.12109375, + "gradient_norm": 0.0893034040927887, + "elapsed": 715.9508004188538 + }, + { + "step": 2192, + "loss": 0.6474133133888245, + "error": 0.4072265625, + "gradient_norm": 0.06980258971452713, + "elapsed": 720.651974439621 + }, + { + "step": 2208, + "loss": 0.5961858630180359, + "error": 0.35546875, + "gradient_norm": 0.06530112773180008, + "elapsed": 725.496098279953 + }, + { + "step": 2224, + "loss": 0.47581571340560913, + "error": 0.263671875, + "gradient_norm": 0.04470043256878853, + "elapsed": 730.2880010604858 + }, + { + "step": 2240, + "loss": 0.577988862991333, + "error": 0.318359375, + "gradient_norm": 0.07201159745454788, + "elapsed": 735.006133556366 + }, + { + "step": 2256, + "loss": 0.28444671630859375, + "error": 0.1181640625, + "gradient_norm": 0.048656050115823746, + "elapsed": 739.6868116855621 + }, + { + "step": 2272, + "loss": 0.2776409089565277, + "error": 0.1201171875, + "gradient_norm": 0.05783981829881668, + "elapsed": 744.3517308235168 + }, + { + "step": 2288, + "loss": 0.621599555015564, + "error": 0.37109375, + "gradient_norm": 0.09731200337409973, + "elapsed": 749.0351710319519 + }, + { + "step": 2304, + "loss": 0.3333754539489746, + "error": 0.1513671875, + "gradient_norm": 0.07069239765405655, + "elapsed": 753.7588081359863 + }, + { + "step": 2320, + "loss": 0.4687051773071289, + "error": 0.2490234375, + "gradient_norm": 0.044891707599163055, + "elapsed": 758.4588432312012 + }, + { + "step": 2336, + "loss": 0.19801637530326843, + "error": 0.078125, + "gradient_norm": 0.10036595165729523, + "elapsed": 763.256409406662 + }, + { + "step": 2352, + "loss": 0.6186277866363525, + "error": 0.388671875, + "gradient_norm": 0.09069584310054779, + "elapsed": 767.9986386299133 + }, + { + "step": 2368, + "loss": 0.6177258491516113, + "error": 0.373046875, + "gradient_norm": 0.049019571393728256, + "elapsed": 772.730831861496 + }, + { + "step": 2384, + "loss": 0.17707547545433044, + "error": 0.0673828125, + "gradient_norm": 0.045190781354904175, + "elapsed": 777.4072704315186 + }, + { + "step": 2400, + "loss": 0.20144733786582947, + "error": 0.08203125, + "gradient_norm": 0.04537162929773331, + "elapsed": 782.0841658115387 + }, + { + "step": 2416, + "loss": 0.6151775121688843, + "error": 0.365234375, + "gradient_norm": 0.050534047186374664, + "elapsed": 786.762966632843 + }, + { + "step": 2432, + "loss": 0.5533859133720398, + "error": 0.314453125, + "gradient_norm": 0.06006559729576111, + "elapsed": 791.4656012058258 + }, + { + "step": 2448, + "loss": 0.5329082012176514, + "error": 0.2880859375, + "gradient_norm": 0.04018115997314453, + "elapsed": 796.1704161167145 + }, + { + "step": 2464, + "loss": 0.6338047981262207, + "error": 0.4140625, + "gradient_norm": 0.06069163978099823, + "elapsed": 800.9180119037628 + }, + { + "step": 2480, + "loss": 0.1603008508682251, + "error": 0.0673828125, + "gradient_norm": 0.040350593626499176, + "elapsed": 805.6127603054047 + }, + { + "step": 2496, + "loss": 0.505940318107605, + "error": 0.2568359375, + "gradient_norm": 0.05209952965378761, + "elapsed": 810.3740313053131 + }, + { + "step": 2512, + "loss": 0.5528728365898132, + "error": 0.298828125, + "gradient_norm": 0.11757992953062057, + "elapsed": 815.1708807945251 + }, + { + "step": 2528, + "loss": 0.5028313994407654, + "error": 0.2666015625, + "gradient_norm": 0.08823780715465546, + "elapsed": 819.8585045337677 + }, + { + "step": 2544, + "loss": 0.5002262592315674, + "error": 0.2783203125, + "gradient_norm": 0.04888603836297989, + "elapsed": 824.5714073181152 + }, + { + "step": 2560, + "loss": 0.6007894277572632, + "error": 0.328125, + "gradient_norm": 0.05186954140663147, + "elapsed": 829.3080432415009 + }, + { + "step": 2576, + "loss": 0.18641480803489685, + "error": 0.076171875, + "gradient_norm": 0.03799928352236748, + "elapsed": 834.044020652771 + }, + { + "step": 2592, + "loss": 0.3050769865512848, + "error": 0.1396484375, + "gradient_norm": 0.10119257122278214, + "elapsed": 838.8401296138763 + }, + { + "step": 2608, + "loss": 0.6063439846038818, + "error": 0.361328125, + "gradient_norm": 0.04979367554187775, + "elapsed": 844.3572654724121 + }, + { + "step": 2624, + "loss": 0.5751967430114746, + "error": 0.3369140625, + "gradient_norm": 0.04269539937376976, + "elapsed": 849.0660374164581 + }, + { + "step": 2640, + "loss": 0.3902108669281006, + "error": 0.193359375, + "gradient_norm": 0.10029696673154831, + "elapsed": 853.8638062477112 + }, + { + "step": 2656, + "loss": 0.15081660449504852, + "error": 0.0625, + "gradient_norm": 0.0303852129727602, + "elapsed": 858.9793758392334 + }, + { + "step": 2672, + "loss": 0.6503090858459473, + "error": 0.400390625, + "gradient_norm": 0.12611964344978333, + "elapsed": 863.9151141643524 + }, + { + "step": 2688, + "loss": 0.5587317943572998, + "error": 0.31640625, + "gradient_norm": 0.10028114914894104, + "elapsed": 868.7600305080414 + }, + { + "step": 2704, + "loss": 0.4399867355823517, + "error": 0.21484375, + "gradient_norm": 0.06889455020427704, + "elapsed": 873.4544236660004 + }, + { + "step": 2720, + "loss": 0.5865127444267273, + "error": 0.337890625, + "gradient_norm": 0.03671631962060928, + "elapsed": 878.0982644557953 + }, + { + "step": 2736, + "loss": 0.6078637838363647, + "error": 0.3701171875, + "gradient_norm": 0.04679318517446518, + "elapsed": 883.0424642562866 + }, + { + "step": 2752, + "loss": 0.5825340151786804, + "error": 0.337890625, + "gradient_norm": 0.05619681254029274, + "elapsed": 887.908124923706 + }, + { + "step": 2768, + "loss": 0.5970422029495239, + "error": 0.3369140625, + "gradient_norm": 0.041302867233753204, + "elapsed": 892.6760206222534 + }, + { + "step": 2784, + "loss": 0.3870226740837097, + "error": 0.1826171875, + "gradient_norm": 0.05731065198779106, + "elapsed": 897.6246056556702 + }, + { + "step": 2800, + "loss": 0.38130277395248413, + "error": 0.1943359375, + "gradient_norm": 0.059244755655527115, + "elapsed": 902.3360238075256 + }, + { + "step": 2816, + "loss": 0.2617901563644409, + "error": 0.1064453125, + "gradient_norm": 0.041736964136362076, + "elapsed": 907.1600468158722 + }, + { + "step": 2832, + "loss": 0.5819337368011475, + "error": 0.314453125, + "gradient_norm": 0.04097156226634979, + "elapsed": 912.0244295597076 + }, + { + "step": 2848, + "loss": 0.41393283009529114, + "error": 0.2001953125, + "gradient_norm": 0.10456771403551102, + "elapsed": 916.8225846290588 + }, + { + "step": 2864, + "loss": 0.5019145011901855, + "error": 0.2548828125, + "gradient_norm": 0.04843736067414284, + "elapsed": 921.538754940033 + }, + { + "step": 2880, + "loss": 0.04561338573694229, + "error": 0.0146484375, + "gradient_norm": 0.025407327339053154, + "elapsed": 926.2588667869568 + }, + { + "step": 2896, + "loss": 0.4338858723640442, + "error": 0.205078125, + "gradient_norm": 0.09900517761707306, + "elapsed": 930.9781975746155 + }, + { + "step": 2912, + "loss": 0.33922863006591797, + "error": 0.162109375, + "gradient_norm": 0.10189604014158249, + "elapsed": 935.6816267967224 + }, + { + "step": 2928, + "loss": 0.5294322967529297, + "error": 0.2822265625, + "gradient_norm": 0.09060791879892349, + "elapsed": 940.4373068809509 + }, + { + "step": 2944, + "loss": 0.037007369101047516, + "error": 0.01171875, + "gradient_norm": 0.05506489425897598, + "elapsed": 945.1270468235016 + }, + { + "step": 2960, + "loss": 0.6096771359443665, + "error": 0.349609375, + "gradient_norm": 0.04987221211194992, + "elapsed": 949.8300130367279 + }, + { + "step": 2976, + "loss": 0.6157823801040649, + "error": 0.373046875, + "gradient_norm": 0.03614233434200287, + "elapsed": 954.5701997280121 + }, + { + "step": 2992, + "loss": 0.1978239268064499, + "error": 0.080078125, + "gradient_norm": 0.05847112461924553, + "elapsed": 959.2756471633911 + }, + { + "step": 3008, + "loss": 0.5237340927124023, + "error": 0.2841796875, + "gradient_norm": 0.06993591040372849, + "elapsed": 963.9875864982605 + }, + { + "step": 3024, + "loss": 0.4559935927391052, + "error": 0.2373046875, + "gradient_norm": 0.05698448419570923, + "elapsed": 968.7997305393219 + }, + { + "step": 3040, + "loss": 0.5025208592414856, + "error": 0.259765625, + "gradient_norm": 0.14909739792346954, + "elapsed": 973.6042547225952 + }, + { + "step": 3056, + "loss": 0.3223109245300293, + "error": 0.1416015625, + "gradient_norm": 0.032974764704704285, + "elapsed": 978.4760546684265 + }, + { + "step": 3072, + "loss": 0.06682582199573517, + "error": 0.021484375, + "gradient_norm": 0.04433188587427139, + "elapsed": 983.2894048690796 + }, + { + "step": 3088, + "loss": 0.5919550061225891, + "error": 0.34765625, + "gradient_norm": 0.06721373647451401, + "elapsed": 1000.9520287513733 + }, + { + "step": 3104, + "loss": 0.5988063812255859, + "error": 0.3642578125, + "gradient_norm": 0.05654948577284813, + "elapsed": 1005.7442932128906 + }, + { + "step": 3120, + "loss": 0.4922299385070801, + "error": 0.2470703125, + "gradient_norm": 0.07545466721057892, + "elapsed": 1010.4616096019745 + }, + { + "step": 3136, + "loss": 0.4533671736717224, + "error": 0.236328125, + "gradient_norm": 0.06288722902536392, + "elapsed": 1015.3559956550598 + }, + { + "step": 3152, + "loss": 0.5070517063140869, + "error": 0.2666015625, + "gradient_norm": 0.07274917513132095, + "elapsed": 1020.0764343738556 + }, + { + "step": 3168, + "loss": 0.5999464988708496, + "error": 0.3408203125, + "gradient_norm": 0.05777016654610634, + "elapsed": 1024.9410600662231 + }, + { + "step": 3184, + "loss": 0.5758363008499146, + "error": 0.3427734375, + "gradient_norm": 0.051027461886405945, + "elapsed": 1029.7082171440125 + }, + { + "step": 3200, + "loss": 0.05016190931200981, + "error": 0.017578125, + "gradient_norm": 0.009175656363368034, + "elapsed": 1034.3982915878296 + }, + { + "step": 3216, + "loss": 0.5471057295799255, + "error": 0.318359375, + "gradient_norm": 0.07572721689939499, + "elapsed": 1039.117841243744 + }, + { + "step": 3232, + "loss": 0.4141446352005005, + "error": 0.193359375, + "gradient_norm": 0.10056859254837036, + "elapsed": 1043.880026102066 + }, + { + "step": 3248, + "loss": 0.5812438726425171, + "error": 0.3212890625, + "gradient_norm": 0.05781616270542145, + "elapsed": 1048.6406455039978 + }, + { + "step": 3264, + "loss": 0.19184701144695282, + "error": 0.078125, + "gradient_norm": 0.05367236211895943, + "elapsed": 1053.5672237873077 + }, + { + "step": 3280, + "loss": 0.5420833826065063, + "error": 0.28515625, + "gradient_norm": 0.052405405789613724, + "elapsed": 1058.3841104507446 + }, + { + "step": 3296, + "loss": 0.4419598877429962, + "error": 0.2177734375, + "gradient_norm": 0.05814693495631218, + "elapsed": 1063.1880333423615 + }, + { + "step": 3312, + "loss": 0.4525642991065979, + "error": 0.208984375, + "gradient_norm": 0.1061021164059639, + "elapsed": 1068.1370933055878 + }, + { + "step": 3328, + "loss": 0.32664671540260315, + "error": 0.154296875, + "gradient_norm": 0.05649850144982338, + "elapsed": 1073.1963467597961 + }, + { + "step": 3344, + "loss": 0.2655770182609558, + "error": 0.1220703125, + "gradient_norm": 0.04070372134447098, + "elapsed": 1078.2698318958282 + }, + { + "step": 3360, + "loss": 0.5894330739974976, + "error": 0.3544921875, + "gradient_norm": 0.0643400028347969, + "elapsed": 1083.0184152126312 + }, + { + "step": 3376, + "loss": 0.6118791103363037, + "error": 0.361328125, + "gradient_norm": 0.08537904173135757, + "elapsed": 1087.834038734436 + }, + { + "step": 3392, + "loss": 0.40694907307624817, + "error": 0.19921875, + "gradient_norm": 0.11411692947149277, + "elapsed": 1092.8119947910309 + }, + { + "step": 3408, + "loss": 0.04629015550017357, + "error": 0.0146484375, + "gradient_norm": 0.017204072326421738, + "elapsed": 1097.5751783847809 + }, + { + "step": 3424, + "loss": 0.20639702677726746, + "error": 0.0849609375, + "gradient_norm": 0.04801144450902939, + "elapsed": 1102.2970931529999 + }, + { + "step": 3440, + "loss": 0.6051071286201477, + "error": 0.33984375, + "gradient_norm": 0.045392412692308426, + "elapsed": 1107.1080610752106 + }, + { + "step": 3456, + "loss": 0.6553700566291809, + "error": 0.40625, + "gradient_norm": 0.05593863129615784, + "elapsed": 1111.8409752845764 + }, + { + "step": 3472, + "loss": 0.591402530670166, + "error": 0.3515625, + "gradient_norm": 0.051181379705667496, + "elapsed": 1116.5800333023071 + }, + { + "step": 3488, + "loss": 0.30494624376296997, + "error": 0.12109375, + "gradient_norm": 0.05175542086362839, + "elapsed": 1121.276373386383 + }, + { + "step": 3504, + "loss": 0.5065370798110962, + "error": 0.279296875, + "gradient_norm": 0.10419930517673492, + "elapsed": 1125.9883344173431 + }, + { + "step": 3520, + "loss": 0.3915700614452362, + "error": 0.1953125, + "gradient_norm": 0.060416825115680695, + "elapsed": 1130.7958455085754 + }, + { + "step": 3536, + "loss": 0.624374270439148, + "error": 0.3759765625, + "gradient_norm": 0.06069556251168251, + "elapsed": 1135.5360939502716 + }, + { + "step": 3552, + "loss": 0.5830206274986267, + "error": 0.3359375, + "gradient_norm": 0.046013280749320984, + "elapsed": 1140.312029838562 + }, + { + "step": 3568, + "loss": 0.4201379716396332, + "error": 0.2119140625, + "gradient_norm": 0.06909621506929398, + "elapsed": 1145.0904593467712 + }, + { + "step": 3584, + "loss": 0.28215405344963074, + "error": 0.1181640625, + "gradient_norm": 0.07625982910394669, + "elapsed": 1149.8156151771545 + }, + { + "step": 3600, + "loss": 0.5229164361953735, + "error": 0.275390625, + "gradient_norm": 0.055048178881406784, + "elapsed": 1154.5280592441559 + }, + { + "step": 3616, + "loss": 0.47238075733184814, + "error": 0.2314453125, + "gradient_norm": 0.06473162025213242, + "elapsed": 1159.2720873355865 + }, + { + "step": 3632, + "loss": 0.46245503425598145, + "error": 0.228515625, + "gradient_norm": 0.07382887601852417, + "elapsed": 1164.0119998455048 + }, + { + "step": 3648, + "loss": 0.37509745359420776, + "error": 0.171875, + "gradient_norm": 0.051260266453027725, + "elapsed": 1168.7440350055695 + }, + { + "step": 3664, + "loss": 0.1948484629392624, + "error": 0.080078125, + "gradient_norm": 0.059623416513204575, + "elapsed": 1173.3906588554382 + }, + { + "step": 3680, + "loss": 0.5552756786346436, + "error": 0.3115234375, + "gradient_norm": 0.08073585480451584, + "elapsed": 1178.0645008087158 + }, + { + "step": 3696, + "loss": 0.6405904293060303, + "error": 0.39453125, + "gradient_norm": 0.05899551138281822, + "elapsed": 1182.730489730835 + }, + { + "step": 3712, + "loss": 0.2767012119293213, + "error": 0.119140625, + "gradient_norm": 0.06593579798936844, + "elapsed": 1187.377315044403 + }, + { + "step": 3728, + "loss": 0.315812885761261, + "error": 0.134765625, + "gradient_norm": 0.035905495285987854, + "elapsed": 1192.0582301616669 + }, + { + "step": 3744, + "loss": 0.6033951640129089, + "error": 0.3544921875, + "gradient_norm": 0.05226197466254234, + "elapsed": 1196.7101175785065 + }, + { + "step": 3760, + "loss": 0.5202592611312866, + "error": 0.275390625, + "gradient_norm": 0.06367512047290802, + "elapsed": 1201.3543090820312 + }, + { + "step": 3776, + "loss": 0.24639368057250977, + "error": 0.1083984375, + "gradient_norm": 0.09370873868465424, + "elapsed": 1206.0717165470123 + }, + { + "step": 3792, + "loss": 0.6175658702850342, + "error": 0.375, + "gradient_norm": 0.06221585348248482, + "elapsed": 1210.754029750824 + }, + { + "step": 3808, + "loss": 0.41153696179389954, + "error": 0.2119140625, + "gradient_norm": 0.05355365574359894, + "elapsed": 1215.4374370574951 + }, + { + "step": 3824, + "loss": 0.28002214431762695, + "error": 0.1123046875, + "gradient_norm": 0.03846330568194389, + "elapsed": 1220.1207013130188 + }, + { + "step": 3840, + "loss": 0.0484195351600647, + "error": 0.013671875, + "gradient_norm": 0.03470242768526077, + "elapsed": 1224.8153104782104 + }, + { + "step": 3856, + "loss": 0.1407160609960556, + "error": 0.0458984375, + "gradient_norm": 0.04061700031161308, + "elapsed": 1229.5512235164642 + }, + { + "step": 3872, + "loss": 0.5881794691085815, + "error": 0.3427734375, + "gradient_norm": 0.062013477087020874, + "elapsed": 1234.3750183582306 + }, + { + "step": 3888, + "loss": 0.17833612859249115, + "error": 0.06640625, + "gradient_norm": 0.038856204599142075, + "elapsed": 1239.110375881195 + }, + { + "step": 3904, + "loss": 0.06211477518081665, + "error": 0.0224609375, + "gradient_norm": 0.02150108851492405, + "elapsed": 1243.800644159317 + }, + { + "step": 3920, + "loss": 0.06039723381400108, + "error": 0.01953125, + "gradient_norm": 0.019367367029190063, + "elapsed": 1248.4831748008728 + }, + { + "step": 3936, + "loss": 0.6010214686393738, + "error": 0.3525390625, + "gradient_norm": 0.051659151911735535, + "elapsed": 1253.1423478126526 + }, + { + "step": 3952, + "loss": 0.5867137312889099, + "error": 0.3388671875, + "gradient_norm": 0.058528851717710495, + "elapsed": 1257.9799931049347 + }, + { + "step": 3968, + "loss": 0.5231834650039673, + "error": 0.2578125, + "gradient_norm": 0.10128334909677505, + "elapsed": 1262.6990082263947 + }, + { + "step": 3984, + "loss": 0.6251651644706726, + "error": 0.353515625, + "gradient_norm": 0.06211795285344124, + "elapsed": 1267.4289934635162 + }, + { + "step": 4000, + "loss": 0.06667037308216095, + "error": 0.01953125, + "gradient_norm": 0.048018258064985275, + "elapsed": 1272.132089138031 + }, + { + "step": 4016, + "loss": 0.5286938548088074, + "error": 0.2744140625, + "gradient_norm": 0.05509360507130623, + "elapsed": 1276.8878977298737 + }, + { + "step": 4032, + "loss": 0.34016552567481995, + "error": 0.1591796875, + "gradient_norm": 0.07597329467535019, + "elapsed": 1281.7364926338196 + }, + { + "step": 4048, + "loss": 0.17750494182109833, + "error": 0.078125, + "gradient_norm": 0.06314503401517868, + "elapsed": 1286.5033600330353 + }, + { + "step": 4064, + "loss": 0.5882893800735474, + "error": 0.34375, + "gradient_norm": 0.10986580699682236, + "elapsed": 1291.1944887638092 + }, + { + "step": 4080, + "loss": 0.4923543930053711, + "error": 0.2568359375, + "gradient_norm": 0.050325747579336166, + "elapsed": 1295.9372322559357 + }, + { + "step": 4096, + "loss": 0.44146978855133057, + "error": 0.2236328125, + "gradient_norm": 0.06535191088914871, + "elapsed": 1300.641023159027 + } + ] + }, + "derived_checkpoints": { + "mean3": { + "checkpoint_label": "mean3", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_optimizer_steps": [ + 2048, + 3072, + 4096 + ], + "source_training_run": "temporal2", + "source_weights_sha256": { + "2048": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "3072": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "4096": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea" + }, + "source_checkpoint_records": { + "2048": { + "step": 2048, + "new_training_shots": 2097152, + "unique_training_rows_seen_in_this_phase": 1293629, + "weights": "weights-2048.npz", + "weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "validation": "validation-2048.json", + "complete": true + }, + "3072": { + "step": 3072, + "new_training_shots": 3145728, + "unique_training_rows_seen_in_this_phase": 1594502, + "weights": "weights-3072.npz", + "weights_sha256": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "validation": "validation-3072.json", + "complete": true + }, + "4096": { + "step": 4096, + "new_training_shots": 4194304, + "unique_training_rows_seen_in_this_phase": 1778773, + "weights": "weights-4096.npz", + "weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "validation": "validation-4096.json", + "complete": true + } + }, + "weights_sha256": "a61fb22f803b795c2a39b6c19dc3a368d536cb21419ba773778601b28e4403fe", + "complete": true + }, + "mean4": { + "checkpoint_label": "mean4", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_optimizer_steps": [ + 1024, + 2048, + 3072, + 4096 + ], + "source_training_run": "temporal2", + "source_weights_sha256": { + "1024": "0d809362d5afe1dc781f716e3aee1a9bc5a8f75fed6cc0ff6339b9abcf600ada", + "2048": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "3072": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "4096": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea" + }, + "source_checkpoint_records": { + "1024": { + "step": 1024, + "new_training_shots": 1048576, + "unique_training_rows_seen_in_this_phase": 804757, + "weights": "weights-1024.npz", + "weights_sha256": "0d809362d5afe1dc781f716e3aee1a9bc5a8f75fed6cc0ff6339b9abcf600ada", + "validation": "validation-1024.json", + "complete": true + }, + "2048": { + "step": 2048, + "new_training_shots": 2097152, + "unique_training_rows_seen_in_this_phase": 1293629, + "weights": "weights-2048.npz", + "weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "validation": "validation-2048.json", + "complete": true + }, + "3072": { + "step": 3072, + "new_training_shots": 3145728, + "unique_training_rows_seen_in_this_phase": 1594502, + "weights": "weights-3072.npz", + "weights_sha256": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "validation": "validation-3072.json", + "complete": true + }, + "4096": { + "step": 4096, + "new_training_shots": 4194304, + "unique_training_rows_seen_in_this_phase": 1778773, + "weights": "weights-4096.npz", + "weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "validation": "validation-4096.json", + "complete": true + } + }, + "weights_sha256": "ff4595e8f3eb7cfaa8da5a58a31e106d9684c7b8437f330573a1291f19f5777a", + "complete": true + } + }, + "selection": "Predefined last-three and all-four noninitial temporal2 checkpoint means; every validation condition evaluated before group selection", + "test_data_used": false, + "derivation_source_sha256": "b68813c7dab697a554185020c430ef05f1c35bedcda5b85b7d165af75461e914" + }, + "training_source_snapshot": "training_sources/temporal2_swa", + "selected_checkpoint_steps": [ + "mean3" + ], + "checkpoint_records": { + "mean3": { + "checkpoint_label": "mean3", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_optimizer_steps": [ + 2048, + 3072, + 4096 + ], + "source_training_run": "temporal2", + "source_weights_sha256": { + "2048": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "3072": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "4096": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea" + }, + "source_checkpoint_records": { + "2048": { + "step": 2048, + "new_training_shots": 2097152, + "unique_training_rows_seen_in_this_phase": 1293629, + "weights": "weights-2048.npz", + "weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "validation": "validation-2048.json", + "complete": true + }, + "3072": { + "step": 3072, + "new_training_shots": 3145728, + "unique_training_rows_seen_in_this_phase": 1594502, + "weights": "weights-3072.npz", + "weights_sha256": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "validation": "validation-3072.json", + "complete": true + }, + "4096": { + "step": 4096, + "new_training_shots": 4194304, + "unique_training_rows_seen_in_this_phase": 1778773, + "weights": "weights-4096.npz", + "weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "validation": "validation-4096.json", + "complete": true + } + }, + "weights_sha256": "a61fb22f803b795c2a39b6c19dc3a368d536cb21419ba773778601b28e4403fe", + "complete": true + } + }, + "selection": "Minimum full-validation mean failure per group among incumbent and listed session-trained checkpoints; when listed, blend candidates average the recorded small-contextual reference and new probabilities equally", + "blend_reference": "/run-state/workspace/research/context_upgrades/continuation2/predictions", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "incumbent": 0.2445763221153846, + "mean3": 0.24451622596153846, + "mean4": 0.24484675480769236, + "blend-mean3": 0.24570312499999997, + "blend-mean4": 0.24591346153846153 + }, + "selected": "mean3" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "incumbent": 0.2528545673076923, + "mean3": 0.25321514423076924, + "mean4": 0.2538611778846154, + "blend-mean3": 0.25310997596153845, + "blend-mean4": 0.2530498798076923 + }, + "selected": "incumbent" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "incumbent": 0.23366887019230773, + "mean3": 0.23392427884615385, + "mean4": 0.234375, + "blend-mean3": 0.2338792067307692, + "blend-mean4": 0.23404447115384613 + }, + "selected": "incumbent" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "incumbent": 0.23886718750000002, + "mean3": 0.23937800480769234, + "mean4": 0.2393780048076923, + "blend-mean3": 0.23942307692307693, + "blend-mean4": 0.2392578125 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "incumbent": 0.24463641826923077, + "mean3": 0.24471153846153845, + "mean4": 0.24505709134615386, + "blend-mean3": 0.24580829326923076, + "blend-mean4": 0.2457782451923077 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "incumbent": 0.23652343749999996, + "mean3": 0.2379957932692308, + "mean4": 0.23756009615384613, + "blend-mean3": 0.23751502403846153, + "blend-mean4": 0.23737980769230768 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "incumbent": 0.23562199519230764, + "mean3": 0.23643329326923077, + "mean4": 0.2361177884615384, + "blend-mean3": 0.23662860576923078, + "blend-mean4": 0.23634314903846157 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "incumbent": 0.2329627403846154, + "mean3": 0.2335186298076923, + "mean4": 0.23344350961538457, + "blend-mean3": 0.23333834134615383, + "blend-mean4": 0.2334134615384615 + }, + "selected": "incumbent" + }, + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.2325420673076923 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22017728365384615 + }, + "selected": "incumbent" + } + ] + }, + { + "name": "condition_same1", + "training_run": { + "initialization": "Continue from this session's trained checkpoint", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "training_source_sha256": { + "learned_exact__temporal_accumulate_train.py": "9f672468a8b72966b3aa04fd22e5d40b47b0768f1c802c267a1da08244c4323b", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "eligible_training_shots": 2067520, + "unique_training_rows_seen_in_this_phase": 803777, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_3_5": 11639, + "surface_code_bX_d3_r03_center_3_5": 10232, + "surface_code_bX_d3_r05_center_3_5": 9180, + "surface_code_bX_d3_r07_center_3_5": 10239, + "surface_code_bX_d3_r09_center_3_5": 6051, + "surface_code_bX_d3_r11_center_3_5": 8012, + "surface_code_bX_d3_r13_center_3_5": 6713, + "surface_code_bX_d3_r15_center_3_5": 6022, + "surface_code_bX_d3_r17_center_3_5": 7425, + "surface_code_bX_d3_r19_center_3_5": 8635, + "surface_code_bX_d3_r21_center_3_5": 10217, + "surface_code_bX_d3_r23_center_3_5": 6026, + "surface_code_bX_d3_r25_center_3_5": 4490, + "surface_code_bX_d3_r01_center_5_3": 7371, + "surface_code_bX_d3_r03_center_5_3": 5992, + "surface_code_bX_d3_r05_center_5_3": 6712, + "surface_code_bX_d3_r07_center_5_3": 6716, + "surface_code_bX_d3_r09_center_5_3": 7941, + "surface_code_bX_d3_r11_center_5_3": 6001, + "surface_code_bX_d3_r13_center_5_3": 8037, + "surface_code_bX_d3_r15_center_5_3": 8542, + "surface_code_bX_d3_r17_center_5_3": 10153, + "surface_code_bX_d3_r19_center_5_3": 10675, + "surface_code_bX_d3_r21_center_5_3": 7993, + "surface_code_bX_d3_r23_center_5_3": 6652, + "surface_code_bX_d3_r25_center_5_3": 8608, + "surface_code_bX_d3_r01_center_5_7": 8590, + "surface_code_bX_d3_r03_center_5_7": 11633, + "surface_code_bX_d3_r05_center_5_7": 8588, + "surface_code_bX_d3_r07_center_5_7": 10695, + "surface_code_bX_d3_r09_center_5_7": 7964, + "surface_code_bX_d3_r11_center_5_7": 11658, + "surface_code_bX_d3_r13_center_5_7": 6021, + "surface_code_bX_d3_r15_center_5_7": 9727, + "surface_code_bX_d3_r17_center_5_7": 4526, + "surface_code_bX_d3_r19_center_5_7": 9642, + "surface_code_bX_d3_r21_center_5_7": 3708, + "surface_code_bX_d3_r23_center_5_7": 6687, + "surface_code_bX_d3_r25_center_5_7": 7972, + "surface_code_bX_d3_r01_center_7_5": 6757, + "surface_code_bX_d3_r03_center_7_5": 6726, + "surface_code_bX_d3_r05_center_7_5": 4504, + "surface_code_bX_d3_r07_center_7_5": 8034, + "surface_code_bX_d3_r09_center_7_5": 8633, + "surface_code_bX_d3_r11_center_7_5": 11109, + "surface_code_bX_d3_r13_center_7_5": 9695, + "surface_code_bX_d3_r15_center_7_5": 7370, + "surface_code_bX_d3_r17_center_7_5": 7323, + "surface_code_bX_d3_r19_center_7_5": 10247, + "surface_code_bX_d3_r21_center_7_5": 6718, + "surface_code_bX_d3_r23_center_7_5": 8064, + "surface_code_bX_d3_r25_center_7_5": 8018, + "surface_code_bZ_d3_r01_center_3_5": 2856, + "surface_code_bZ_d3_r03_center_3_5": 6780, + "surface_code_bZ_d3_r05_center_3_5": 8610, + "surface_code_bZ_d3_r07_center_3_5": 9152, + "surface_code_bZ_d3_r09_center_3_5": 4522, + "surface_code_bZ_d3_r11_center_3_5": 3703, + "surface_code_bZ_d3_r13_center_3_5": 6001, + "surface_code_bZ_d3_r15_center_3_5": 7377, + "surface_code_bZ_d3_r17_center_3_5": 4517, + "surface_code_bZ_d3_r19_center_3_5": 10242, + "surface_code_bZ_d3_r21_center_3_5": 6747, + "surface_code_bZ_d3_r23_center_3_5": 7422, + "surface_code_bZ_d3_r25_center_3_5": 10606, + "surface_code_bZ_d3_r01_center_5_3": 5272, + "surface_code_bZ_d3_r03_center_5_3": 11200, + "surface_code_bZ_d3_r05_center_5_3": 4514, + "surface_code_bZ_d3_r07_center_5_3": 8002, + "surface_code_bZ_d3_r09_center_5_3": 8008, + "surface_code_bZ_d3_r11_center_5_3": 8689, + "surface_code_bZ_d3_r13_center_5_3": 8604, + "surface_code_bZ_d3_r15_center_5_3": 5981, + "surface_code_bZ_d3_r17_center_5_3": 5307, + "surface_code_bZ_d3_r19_center_5_3": 6713, + "surface_code_bZ_d3_r21_center_5_3": 8570, + "surface_code_bZ_d3_r23_center_5_3": 6700, + "surface_code_bZ_d3_r25_center_5_3": 10199, + "surface_code_bZ_d3_r01_center_5_7": 6730, + "surface_code_bZ_d3_r03_center_5_7": 7959, + "surface_code_bZ_d3_r05_center_5_7": 9741, + "surface_code_bZ_d3_r07_center_5_7": 10727, + "surface_code_bZ_d3_r09_center_5_7": 11979, + "surface_code_bZ_d3_r11_center_5_7": 3694, + "surface_code_bZ_d3_r13_center_5_7": 6746, + "surface_code_bZ_d3_r15_center_5_7": 6686, + "surface_code_bZ_d3_r17_center_5_7": 10647, + "surface_code_bZ_d3_r19_center_5_7": 8011, + "surface_code_bZ_d3_r21_center_5_7": 6000, + "surface_code_bZ_d3_r23_center_5_7": 9176, + "surface_code_bZ_d3_r25_center_5_7": 6009, + "surface_code_bZ_d3_r01_center_7_5": 9076, + "surface_code_bZ_d3_r03_center_7_5": 9182, + "surface_code_bZ_d3_r05_center_7_5": 6769, + "surface_code_bZ_d3_r07_center_7_5": 11140, + "surface_code_bZ_d3_r09_center_7_5": 7359, + "surface_code_bZ_d3_r11_center_7_5": 8582, + "surface_code_bZ_d3_r13_center_7_5": 5284, + "surface_code_bZ_d3_r15_center_7_5": 6694, + "surface_code_bZ_d3_r17_center_7_5": 5965, + "surface_code_bZ_d3_r19_center_7_5": 6016, + "surface_code_bZ_d3_r21_center_7_5": 9225, + "surface_code_bZ_d3_r23_center_7_5": 4509, + "surface_code_bZ_d3_r25_center_7_5": 6694 + }, + "steps": 1024, + "batch_size": 256, + "accumulate_conditions": 4, + "effective_batch_size": 1024, + "condition_policy": "same", + "training_draws": 1048576, + "condition_sampling": "Draw one condition index per microbatch in both arms; same-condition control reuses the first index while mixed arm uses all indices. Both arms consume identical RNG draws with equal-sized condition pools.", + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.00025, + "sampling_seed": 20261190, + "optimizer_restored": false, + "rng_restored": false, + "explicit_optimizer_reset": true, + "explicit_rng_reset": true, + "sampling_state_source": "Fresh NumPy default_rng seed 20261190", + "session_trained_starting_checkpoint": "/run-state/workspace/research/learned_exact/temporal2_swa/weights-mean3.npz", + "starting_checkpoint_sha256": "a61fb22f803b795c2a39b6c19dc3a368d536cb21419ba773778601b28e4403fe", + "starting_training_provenance": { + "initialization": "Uniform averages of the same session-trained temporal trajectory; no external weights", + "optimizer_updates_in_derived_run": 0, + "source_training_provenance": { + "initialization": "Continue from this session's trained checkpoint", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "training_source_sha256": { + "learned_exact__temporal_train.py": "7d48d2fc7f62d0bec3023b3df1c2ac28537d0417966131ae3a156697a34cda5f", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "eligible_training_shots": 2067520, + "unique_training_rows_seen_in_this_phase": 1778773, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_3_5": 18357, + "surface_code_bX_d3_r03_center_3_5": 16816, + "surface_code_bX_d3_r05_center_3_5": 17999, + "surface_code_bX_d3_r07_center_3_5": 15225, + "surface_code_bX_d3_r09_center_3_5": 16132, + "surface_code_bX_d3_r11_center_3_5": 17041, + "surface_code_bX_d3_r13_center_3_5": 18477, + "surface_code_bX_d3_r15_center_3_5": 18214, + "surface_code_bX_d3_r17_center_3_5": 16505, + "surface_code_bX_d3_r19_center_3_5": 17120, + "surface_code_bX_d3_r21_center_3_5": 17563, + "surface_code_bX_d3_r23_center_3_5": 16681, + "surface_code_bX_d3_r25_center_3_5": 18379, + "surface_code_bX_d3_r01_center_5_3": 17450, + "surface_code_bX_d3_r03_center_5_3": 17161, + "surface_code_bX_d3_r05_center_5_3": 15797, + "surface_code_bX_d3_r07_center_5_3": 17800, + "surface_code_bX_d3_r09_center_5_3": 17190, + "surface_code_bX_d3_r11_center_5_3": 15840, + "surface_code_bX_d3_r13_center_5_3": 15178, + "surface_code_bX_d3_r15_center_5_3": 14897, + "surface_code_bX_d3_r17_center_5_3": 18252, + "surface_code_bX_d3_r19_center_5_3": 17083, + "surface_code_bX_d3_r21_center_5_3": 17229, + "surface_code_bX_d3_r23_center_5_3": 14735, + "surface_code_bX_d3_r25_center_5_3": 17949, + "surface_code_bX_d3_r01_center_5_7": 17431, + "surface_code_bX_d3_r03_center_5_7": 16583, + "surface_code_bX_d3_r05_center_5_7": 16891, + "surface_code_bX_d3_r07_center_5_7": 17969, + "surface_code_bX_d3_r09_center_5_7": 17966, + "surface_code_bX_d3_r11_center_5_7": 14424, + "surface_code_bX_d3_r13_center_5_7": 16930, + "surface_code_bX_d3_r15_center_5_7": 15205, + "surface_code_bX_d3_r17_center_5_7": 18252, + "surface_code_bX_d3_r19_center_5_7": 17077, + "surface_code_bX_d3_r21_center_5_7": 16770, + "surface_code_bX_d3_r23_center_5_7": 17308, + "surface_code_bX_d3_r25_center_5_7": 17481, + "surface_code_bX_d3_r01_center_7_5": 16630, + "surface_code_bX_d3_r03_center_7_5": 17439, + "surface_code_bX_d3_r05_center_7_5": 15811, + "surface_code_bX_d3_r07_center_7_5": 16637, + "surface_code_bX_d3_r09_center_7_5": 18306, + "surface_code_bX_d3_r11_center_7_5": 18327, + "surface_code_bX_d3_r13_center_7_5": 17974, + "surface_code_bX_d3_r15_center_7_5": 16106, + "surface_code_bX_d3_r17_center_7_5": 15834, + "surface_code_bX_d3_r19_center_7_5": 17242, + "surface_code_bX_d3_r21_center_7_5": 17889, + "surface_code_bX_d3_r23_center_7_5": 17440, + "surface_code_bX_d3_r25_center_7_5": 17087, + "surface_code_bZ_d3_r01_center_3_5": 16236, + "surface_code_bZ_d3_r03_center_3_5": 17278, + "surface_code_bZ_d3_r05_center_3_5": 16577, + "surface_code_bZ_d3_r07_center_3_5": 17376, + "surface_code_bZ_d3_r09_center_3_5": 16000, + "surface_code_bZ_d3_r11_center_3_5": 15634, + "surface_code_bZ_d3_r13_center_3_5": 14950, + "surface_code_bZ_d3_r15_center_3_5": 16600, + "surface_code_bZ_d3_r17_center_3_5": 15381, + "surface_code_bZ_d3_r19_center_3_5": 16823, + "surface_code_bZ_d3_r21_center_3_5": 18789, + "surface_code_bZ_d3_r23_center_3_5": 15616, + "surface_code_bZ_d3_r25_center_3_5": 17088, + "surface_code_bZ_d3_r01_center_5_3": 17935, + "surface_code_bZ_d3_r03_center_5_3": 16256, + "surface_code_bZ_d3_r05_center_5_3": 17959, + "surface_code_bZ_d3_r07_center_5_3": 18401, + "surface_code_bZ_d3_r09_center_5_3": 16405, + "surface_code_bZ_d3_r11_center_5_3": 17274, + "surface_code_bZ_d3_r13_center_5_3": 18172, + "surface_code_bZ_d3_r15_center_5_3": 17525, + "surface_code_bZ_d3_r17_center_5_3": 18643, + "surface_code_bZ_d3_r19_center_5_3": 17816, + "surface_code_bZ_d3_r21_center_5_3": 17404, + "surface_code_bZ_d3_r23_center_5_3": 17253, + "surface_code_bZ_d3_r25_center_5_3": 17667, + "surface_code_bZ_d3_r01_center_5_7": 16203, + "surface_code_bZ_d3_r03_center_5_7": 17214, + "surface_code_bZ_d3_r05_center_5_7": 16799, + "surface_code_bZ_d3_r07_center_5_7": 17896, + "surface_code_bZ_d3_r09_center_5_7": 16411, + "surface_code_bZ_d3_r11_center_5_7": 17726, + "surface_code_bZ_d3_r13_center_5_7": 16313, + "surface_code_bZ_d3_r15_center_5_7": 17824, + "surface_code_bZ_d3_r17_center_5_7": 15656, + "surface_code_bZ_d3_r19_center_5_7": 17169, + "surface_code_bZ_d3_r21_center_5_7": 17194, + "surface_code_bZ_d3_r23_center_5_7": 16779, + "surface_code_bZ_d3_r25_center_5_7": 16970, + "surface_code_bZ_d3_r01_center_7_5": 16762, + "surface_code_bZ_d3_r03_center_7_5": 17320, + "surface_code_bZ_d3_r05_center_7_5": 17522, + "surface_code_bZ_d3_r07_center_7_5": 17914, + "surface_code_bZ_d3_r09_center_7_5": 18439, + "surface_code_bZ_d3_r11_center_7_5": 18218, + "surface_code_bZ_d3_r13_center_7_5": 17907, + "surface_code_bZ_d3_r15_center_7_5": 17597, + "surface_code_bZ_d3_r17_center_7_5": 18252, + "surface_code_bZ_d3_r19_center_7_5": 18379, + "surface_code_bZ_d3_r21_center_7_5": 16818, + "surface_code_bZ_d3_r23_center_7_5": 18430, + "surface_code_bZ_d3_r25_center_7_5": 17924 + }, + "steps": 4096, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.0005, + "sampling_seed": 20261121, + "optimizer_restored": true, + "rng_restored": true, + "sampling_state_source": "/run-state/workspace/research/learned_exact/temporal1/rng-2048.json", + "session_trained_starting_checkpoint": "/run-state/workspace/research/learned_exact/temporal1/weights-2048.npz", + "starting_checkpoint_sha256": "26be9e0259b69a5870bf73e80a5a29fcf3519a3ff63e1d219c57a2113d9d34be", + "starting_training_provenance": { + "initialization": "Continue from rich weights trained from random initialization in this session; new temporal parameters randomly initialized now", + "original_initialization": "Rich network random seed20261030; new 32-channel temporal network random seed20261104; rich parameters retained, new input rows Normal(0,.001)", + "rich_starting_checkpoint": "/run-state/workspace/research/learned_exact/rich1/weights-1024.npz", + "rich_checkpoint_sha256": "04fea2cf8c598cd5587d450b50cdce58aee9a8c770a2c2da57d7a48e3bf3e2a6", + "architecture": "Rich 128-unit MLP plus 32-channel temporal encoder: four residual kernel3 convolutions with dilations1/2/4/8 and channel normalization. Receptive field31 rounds. Encoder sees events, measurements and presence masks. Per-edge 177 input features. Output4*tanh.", + "training": "Uniform condition sampling from all 104 d3 conditions; batch drawn from the supplied training split only", + "steps": 2048, + "batch_size": 1024, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "learning_rate": 0.001, + "sampling_seed": 20261111, + "optimizer_restored": false, + "rng_restored": false, + "session_trained_starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.6317505836486816, + "error": 0.3681640625, + "gradient_norm": 0.04013459011912346, + "elapsed": 30.971998691558838 + }, + { + "step": 16, + "loss": 0.5091081857681274, + "error": 0.291015625, + "gradient_norm": 0.042228709906339645, + "elapsed": 35.17463397979736 + }, + { + "step": 32, + "loss": 0.626472532749176, + "error": 0.3642578125, + "gradient_norm": 0.05872415751218796, + "elapsed": 39.678136110305786 + }, + { + "step": 48, + "loss": 0.6005369424819946, + "error": 0.3515625, + "gradient_norm": 0.03848014399409294, + "elapsed": 44.16946887969971 + }, + { + "step": 64, + "loss": 0.5523768663406372, + "error": 0.302734375, + "gradient_norm": 0.06031862646341324, + "elapsed": 48.65217089653015 + }, + { + "step": 80, + "loss": 0.3981674611568451, + "error": 0.19921875, + "gradient_norm": 0.0542079322040081, + "elapsed": 53.21601867675781 + }, + { + "step": 96, + "loss": 0.5601426362991333, + "error": 0.2978515625, + "gradient_norm": 0.04770371690392494, + "elapsed": 57.81089663505554 + }, + { + "step": 112, + "loss": 0.5878150463104248, + "error": 0.34765625, + "gradient_norm": 0.10699950158596039, + "elapsed": 62.42190766334534 + }, + { + "step": 128, + "loss": 0.5232458114624023, + "error": 0.2861328125, + "gradient_norm": 0.0911584198474884, + "elapsed": 67.00223755836487 + }, + { + "step": 144, + "loss": 0.6119767427444458, + "error": 0.3623046875, + "gradient_norm": 0.062474437057971954, + "elapsed": 71.54070782661438 + }, + { + "step": 160, + "loss": 0.3037984371185303, + "error": 0.1474609375, + "gradient_norm": 0.05718141421675682, + "elapsed": 76.08167362213135 + }, + { + "step": 176, + "loss": 0.6038273572921753, + "error": 0.3662109375, + "gradient_norm": 0.0437164381146431, + "elapsed": 80.71864247322083 + }, + { + "step": 192, + "loss": 0.3304370641708374, + "error": 0.1572265625, + "gradient_norm": 0.05684761330485344, + "elapsed": 85.54437017440796 + }, + { + "step": 208, + "loss": 0.5785484313964844, + "error": 0.3251953125, + "gradient_norm": 0.09597272425889969, + "elapsed": 91.51522874832153 + }, + { + "step": 224, + "loss": 0.3110499978065491, + "error": 0.13671875, + "gradient_norm": 0.04815748706459999, + "elapsed": 97.1228940486908 + }, + { + "step": 240, + "loss": 0.6213864684104919, + "error": 0.3623046875, + "gradient_norm": 0.0540502592921257, + "elapsed": 102.90286135673523 + }, + { + "step": 256, + "loss": 0.2535272240638733, + "error": 0.1064453125, + "gradient_norm": 0.029962118715047836, + "elapsed": 108.39288640022278 + }, + { + "step": 272, + "loss": 0.6126939058303833, + "error": 0.3671875, + "gradient_norm": 0.06887879222631454, + "elapsed": 113.83897161483765 + }, + { + "step": 288, + "loss": 0.4556676149368286, + "error": 0.2236328125, + "gradient_norm": 0.16127081215381622, + "elapsed": 119.93085813522339 + }, + { + "step": 304, + "loss": 0.4973585605621338, + "error": 0.255859375, + "gradient_norm": 0.08082302659749985, + "elapsed": 125.90891909599304 + }, + { + "step": 320, + "loss": 0.6455868482589722, + "error": 0.419921875, + "gradient_norm": 0.04339660331606865, + "elapsed": 131.20537638664246 + }, + { + "step": 336, + "loss": 0.5343132615089417, + "error": 0.2880859375, + "gradient_norm": 0.07518009096384048, + "elapsed": 136.59086871147156 + }, + { + "step": 352, + "loss": 0.6505346894264221, + "error": 0.4033203125, + "gradient_norm": 0.03800992667675018, + "elapsed": 142.21085906028748 + }, + { + "step": 368, + "loss": 0.4882712960243225, + "error": 0.251953125, + "gradient_norm": 0.08170920610427856, + "elapsed": 146.95903658866882 + }, + { + "step": 384, + "loss": 0.5292021036148071, + "error": 0.296875, + "gradient_norm": 0.08454013615846634, + "elapsed": 151.6385259628296 + }, + { + "step": 400, + "loss": 0.6272899508476257, + "error": 0.3837890625, + "gradient_norm": 0.051436979323625565, + "elapsed": 156.3343904018402 + }, + { + "step": 416, + "loss": 0.052130259573459625, + "error": 0.0166015625, + "gradient_norm": 0.02377190627157688, + "elapsed": 160.92345547676086 + }, + { + "step": 432, + "loss": 0.5256737470626831, + "error": 0.3046875, + "gradient_norm": 0.07986386120319366, + "elapsed": 165.52879118919373 + }, + { + "step": 448, + "loss": 0.15193665027618408, + "error": 0.0576171875, + "gradient_norm": 0.06491660326719284, + "elapsed": 170.14827823638916 + }, + { + "step": 464, + "loss": 0.6418055295944214, + "error": 0.40625, + "gradient_norm": 0.07290885597467422, + "elapsed": 174.64974284172058 + }, + { + "step": 480, + "loss": 0.6055159568786621, + "error": 0.357421875, + "gradient_norm": 0.0795595794916153, + "elapsed": 179.17218685150146 + }, + { + "step": 496, + "loss": 0.6372283697128296, + "error": 0.3916015625, + "gradient_norm": 0.04387903958559036, + "elapsed": 183.77568197250366 + }, + { + "step": 512, + "loss": 0.637977123260498, + "error": 0.408203125, + "gradient_norm": 0.060665905475616455, + "elapsed": 188.31205368041992 + }, + { + "step": 528, + "loss": 0.4668862223625183, + "error": 0.2451171875, + "gradient_norm": 0.08566711097955704, + "elapsed": 206.40719985961914 + }, + { + "step": 544, + "loss": 0.4584413170814514, + "error": 0.244140625, + "gradient_norm": 0.08538200706243515, + "elapsed": 211.02819895744324 + }, + { + "step": 560, + "loss": 0.5615692138671875, + "error": 0.3291015625, + "gradient_norm": 0.043748609721660614, + "elapsed": 215.66470766067505 + }, + { + "step": 576, + "loss": 0.5151895880699158, + "error": 0.2880859375, + "gradient_norm": 0.05164863541722298, + "elapsed": 220.18949556350708 + }, + { + "step": 592, + "loss": 0.5618112087249756, + "error": 0.3291015625, + "gradient_norm": 0.05998719856142998, + "elapsed": 224.7216100692749 + }, + { + "step": 608, + "loss": 0.659294843673706, + "error": 0.431640625, + "gradient_norm": 0.09910348802804947, + "elapsed": 229.26827573776245 + }, + { + "step": 624, + "loss": 0.5895233154296875, + "error": 0.3447265625, + "gradient_norm": 0.045334093272686005, + "elapsed": 233.83731055259705 + }, + { + "step": 640, + "loss": 0.6081801056861877, + "error": 0.3388671875, + "gradient_norm": 0.06578423827886581, + "elapsed": 238.36345624923706 + }, + { + "step": 656, + "loss": 0.5349816083908081, + "error": 0.2939453125, + "gradient_norm": 0.09989562630653381, + "elapsed": 242.95086026191711 + }, + { + "step": 672, + "loss": 0.5871994495391846, + "error": 0.328125, + "gradient_norm": 0.08132346719503403, + "elapsed": 247.67088556289673 + }, + { + "step": 688, + "loss": 0.06012660637497902, + "error": 0.0146484375, + "gradient_norm": 0.012170507572591305, + "elapsed": 252.3202247619629 + }, + { + "step": 704, + "loss": 0.42179757356643677, + "error": 0.21484375, + "gradient_norm": 0.08384513854980469, + "elapsed": 256.91991782188416 + }, + { + "step": 720, + "loss": 0.6111758947372437, + "error": 0.3720703125, + "gradient_norm": 0.06689880788326263, + "elapsed": 261.56407928466797 + }, + { + "step": 736, + "loss": 0.29969727993011475, + "error": 0.1318359375, + "gradient_norm": 0.0743367150425911, + "elapsed": 266.22199630737305 + }, + { + "step": 752, + "loss": 0.051849883049726486, + "error": 0.0166015625, + "gradient_norm": 0.017005126923322678, + "elapsed": 270.8602342605591 + }, + { + "step": 768, + "loss": 0.6178420186042786, + "error": 0.3759765625, + "gradient_norm": 0.027732960879802704, + "elapsed": 275.47888374328613 + }, + { + "step": 784, + "loss": 0.45798996090888977, + "error": 0.228515625, + "gradient_norm": 0.0630083829164505, + "elapsed": 280.1709156036377 + }, + { + "step": 800, + "loss": 0.5104988813400269, + "error": 0.2724609375, + "gradient_norm": 0.041733670979738235, + "elapsed": 286.17937707901 + }, + { + "step": 816, + "loss": 0.6336112022399902, + "error": 0.3837890625, + "gradient_norm": 0.0755191296339035, + "elapsed": 291.7506103515625 + }, + { + "step": 832, + "loss": 0.6260952353477478, + "error": 0.3603515625, + "gradient_norm": 0.0318005345761776, + "elapsed": 297.31094622612 + }, + { + "step": 848, + "loss": 0.5870074033737183, + "error": 0.3525390625, + "gradient_norm": 0.12073405832052231, + "elapsed": 303.11089158058167 + }, + { + "step": 864, + "loss": 0.5125640034675598, + "error": 0.26953125, + "gradient_norm": 0.038650237023830414, + "elapsed": 308.7288725376129 + }, + { + "step": 880, + "loss": 0.19194915890693665, + "error": 0.0703125, + "gradient_norm": 0.061878547072410583, + "elapsed": 314.37042355537415 + }, + { + "step": 896, + "loss": 0.5409250259399414, + "error": 0.2919921875, + "gradient_norm": 0.06288820505142212, + "elapsed": 319.9398190975189 + }, + { + "step": 912, + "loss": 0.6164936423301697, + "error": 0.3701171875, + "gradient_norm": 0.043224163353443146, + "elapsed": 325.361323595047 + }, + { + "step": 928, + "loss": 0.16032151877880096, + "error": 0.0625, + "gradient_norm": 0.030957572162151337, + "elapsed": 331.21752285957336 + }, + { + "step": 944, + "loss": 0.646601676940918, + "error": 0.3818359375, + "gradient_norm": 0.05670839175581932, + "elapsed": 336.7825517654419 + }, + { + "step": 960, + "loss": 0.402952641248703, + "error": 0.1865234375, + "gradient_norm": 0.07500886172056198, + "elapsed": 342.6888346672058 + }, + { + "step": 976, + "loss": 0.5537433624267578, + "error": 0.2939453125, + "gradient_norm": 0.04955969750881195, + "elapsed": 348.5554690361023 + }, + { + "step": 992, + "loss": 0.559626579284668, + "error": 0.294921875, + "gradient_norm": 0.048295993357896805, + "elapsed": 354.3531894683838 + }, + { + "step": 1008, + "loss": 0.5034694671630859, + "error": 0.2705078125, + "gradient_norm": 0.05729879066348076, + "elapsed": 360.0949149131775 + }, + { + "step": 1024, + "loss": 0.3119734525680542, + "error": 0.1259765625, + "gradient_norm": 0.052326612174510956, + "elapsed": 365.7881224155426 + }, + { + "step": 1040, + "loss": 0.35799849033355713, + "error": 0.173828125, + "gradient_norm": 0.03801804035902023, + "elapsed": 386.5749418735504 + }, + { + "step": 1056, + "loss": 0.6178948879241943, + "error": 0.3515625, + "gradient_norm": 0.03620661422610283, + "elapsed": 391.48247838020325 + }, + { + "step": 1072, + "loss": 0.49231401085853577, + "error": 0.24609375, + "gradient_norm": 0.04391559213399887, + "elapsed": 396.08718824386597 + }, + { + "step": 1088, + "loss": 0.4119300842285156, + "error": 0.2001953125, + "gradient_norm": 0.1104700043797493, + "elapsed": 400.5326828956604 + }, + { + "step": 1104, + "loss": 0.4926626682281494, + "error": 0.265625, + "gradient_norm": 0.04246886447072029, + "elapsed": 404.95741271972656 + }, + { + "step": 1120, + "loss": 0.5027930736541748, + "error": 0.2607421875, + "gradient_norm": 0.0547240674495697, + "elapsed": 409.40319633483887 + }, + { + "step": 1136, + "loss": 0.5948058366775513, + "error": 0.3544921875, + "gradient_norm": 0.06810063123703003, + "elapsed": 413.8514006137848 + }, + { + "step": 1152, + "loss": 0.26567256450653076, + "error": 0.125, + "gradient_norm": 0.06689104437828064, + "elapsed": 418.29868721961975 + }, + { + "step": 1168, + "loss": 0.2866836190223694, + "error": 0.1240234375, + "gradient_norm": 0.029536213725805283, + "elapsed": 422.75131845474243 + }, + { + "step": 1184, + "loss": 0.6342021822929382, + "error": 0.4091796875, + "gradient_norm": 0.0704190731048584, + "elapsed": 427.1991722583771 + }, + { + "step": 1200, + "loss": 0.41626787185668945, + "error": 0.212890625, + "gradient_norm": 0.04480795934796333, + "elapsed": 431.6600706577301 + }, + { + "step": 1216, + "loss": 0.28460952639579773, + "error": 0.1337890625, + "gradient_norm": 0.03666983172297478, + "elapsed": 436.14414525032043 + }, + { + "step": 1232, + "loss": 0.044482216238975525, + "error": 0.0146484375, + "gradient_norm": 0.04537617415189743, + "elapsed": 440.6220428943634 + }, + { + "step": 1248, + "loss": 0.42564862966537476, + "error": 0.2119140625, + "gradient_norm": 0.03382417559623718, + "elapsed": 445.06736421585083 + }, + { + "step": 1264, + "loss": 0.27150213718414307, + "error": 0.123046875, + "gradient_norm": 0.033046118915081024, + "elapsed": 449.544029712677 + }, + { + "step": 1280, + "loss": 0.4927375912666321, + "error": 0.255859375, + "gradient_norm": 0.06812550127506256, + "elapsed": 454.07198667526245 + }, + { + "step": 1296, + "loss": 0.5541940927505493, + "error": 0.28125, + "gradient_norm": 0.1435294896364212, + "elapsed": 458.6031415462494 + }, + { + "step": 1312, + "loss": 0.5575842261314392, + "error": 0.2958984375, + "gradient_norm": 0.03811952844262123, + "elapsed": 463.1806228160858 + }, + { + "step": 1328, + "loss": 0.3479428291320801, + "error": 0.1591796875, + "gradient_norm": 0.0709012895822525, + "elapsed": 467.84689688682556 + }, + { + "step": 1344, + "loss": 0.1685580611228943, + "error": 0.0693359375, + "gradient_norm": 0.05423415079712868, + "elapsed": 472.6908576488495 + }, + { + "step": 1360, + "loss": 0.18506410717964172, + "error": 0.0771484375, + "gradient_norm": 0.03418596833944321, + "elapsed": 477.4269769191742 + }, + { + "step": 1376, + "loss": 0.5654555559158325, + "error": 0.3173828125, + "gradient_norm": 0.0685155838727951, + "elapsed": 482.08285188674927 + }, + { + "step": 1392, + "loss": 0.6116407513618469, + "error": 0.3603515625, + "gradient_norm": 0.05198948457837105, + "elapsed": 486.7167499065399 + }, + { + "step": 1408, + "loss": 0.4014682471752167, + "error": 0.19140625, + "gradient_norm": 0.1024075523018837, + "elapsed": 491.4308760166168 + }, + { + "step": 1424, + "loss": 0.051035866141319275, + "error": 0.0166015625, + "gradient_norm": 0.010207361541688442, + "elapsed": 496.1818380355835 + }, + { + "step": 1440, + "loss": 0.4725648760795593, + "error": 0.2412109375, + "gradient_norm": 0.03977378085255623, + "elapsed": 500.8668632507324 + }, + { + "step": 1456, + "loss": 0.5407818555831909, + "error": 0.2939453125, + "gradient_norm": 0.088577501475811, + "elapsed": 505.49274134635925 + }, + { + "step": 1472, + "loss": 0.5655064582824707, + "error": 0.3076171875, + "gradient_norm": 0.04452778398990631, + "elapsed": 510.2188584804535 + }, + { + "step": 1488, + "loss": 0.5799556374549866, + "error": 0.30859375, + "gradient_norm": 0.03976206108927727, + "elapsed": 514.9319434165955 + }, + { + "step": 1504, + "loss": 0.4660354256629944, + "error": 0.25390625, + "gradient_norm": 0.04365506023168564, + "elapsed": 519.5848798751831 + }, + { + "step": 1520, + "loss": 0.5505894422531128, + "error": 0.30859375, + "gradient_norm": 0.057772211730480194, + "elapsed": 524.3388590812683 + }, + { + "step": 1536, + "loss": 0.6251416206359863, + "error": 0.400390625, + "gradient_norm": 0.09649194777011871, + "elapsed": 529.483047246933 + }, + { + "step": 1552, + "loss": 0.05424533039331436, + "error": 0.0185546875, + "gradient_norm": 0.011683990247547626, + "elapsed": 548.1828610897064 + }, + { + "step": 1568, + "loss": 0.33612310886383057, + "error": 0.1611328125, + "gradient_norm": 0.051817383617162704, + "elapsed": 553.4256420135498 + }, + { + "step": 1584, + "loss": 0.045015305280685425, + "error": 0.0166015625, + "gradient_norm": 0.022604886442422867, + "elapsed": 558.6308543682098 + }, + { + "step": 1600, + "loss": 0.2701840102672577, + "error": 0.119140625, + "gradient_norm": 0.02910422720015049, + "elapsed": 563.8571691513062 + }, + { + "step": 1616, + "loss": 0.18982334434986115, + "error": 0.0849609375, + "gradient_norm": 0.025524422526359558, + "elapsed": 568.8628678321838 + }, + { + "step": 1632, + "loss": 0.3950161337852478, + "error": 0.185546875, + "gradient_norm": 0.08419577777385712, + "elapsed": 574.0815451145172 + }, + { + "step": 1648, + "loss": 0.49384528398513794, + "error": 0.255859375, + "gradient_norm": 0.08879344165325165, + "elapsed": 579.1229114532471 + }, + { + "step": 1664, + "loss": 0.5671384930610657, + "error": 0.3115234375, + "gradient_norm": 0.05374513566493988, + "elapsed": 584.114851474762 + }, + { + "step": 1680, + "loss": 0.6192574501037598, + "error": 0.37890625, + "gradient_norm": 0.043836336582899094, + "elapsed": 589.0708522796631 + }, + { + "step": 1696, + "loss": 0.2619469463825226, + "error": 0.1171875, + "gradient_norm": 0.040093280375003815, + "elapsed": 594.2814819812775 + }, + { + "step": 1712, + "loss": 0.33178141713142395, + "error": 0.162109375, + "gradient_norm": 0.04902712255716324, + "elapsed": 599.3068840503693 + }, + { + "step": 1728, + "loss": 0.385281503200531, + "error": 0.171875, + "gradient_norm": 0.03541380167007446, + "elapsed": 604.5308682918549 + }, + { + "step": 1744, + "loss": 0.1628715693950653, + "error": 0.0693359375, + "gradient_norm": 0.06111741065979004, + "elapsed": 609.309522151947 + }, + { + "step": 1760, + "loss": 0.5239119529724121, + "error": 0.2861328125, + "gradient_norm": 0.08513613045215607, + "elapsed": 614.0396001338959 + }, + { + "step": 1776, + "loss": 0.35721707344055176, + "error": 0.150390625, + "gradient_norm": 0.06337940692901611, + "elapsed": 618.6857132911682 + }, + { + "step": 1792, + "loss": 0.5985626578330994, + "error": 0.33203125, + "gradient_norm": 0.035725343972444534, + "elapsed": 623.3352344036102 + }, + { + "step": 1808, + "loss": 0.34676820039749146, + "error": 0.15234375, + "gradient_norm": 0.08163885772228241, + "elapsed": 627.9495220184326 + }, + { + "step": 1824, + "loss": 0.5633711814880371, + "error": 0.3037109375, + "gradient_norm": 0.05938677117228508, + "elapsed": 632.5820379257202 + }, + { + "step": 1840, + "loss": 0.6256523132324219, + "error": 0.384765625, + "gradient_norm": 0.04545137286186218, + "elapsed": 637.205274105072 + }, + { + "step": 1856, + "loss": 0.28091639280319214, + "error": 0.1298828125, + "gradient_norm": 0.04705077037215233, + "elapsed": 641.883561372757 + }, + { + "step": 1872, + "loss": 0.516182541847229, + "error": 0.263671875, + "gradient_norm": 0.08828777819871902, + "elapsed": 646.5188939571381 + }, + { + "step": 1888, + "loss": 0.48386621475219727, + "error": 0.25390625, + "gradient_norm": 0.05322824418544769, + "elapsed": 651.148512840271 + }, + { + "step": 1904, + "loss": 0.6141921281814575, + "error": 0.388671875, + "gradient_norm": 0.050139278173446655, + "elapsed": 655.7796437740326 + }, + { + "step": 1920, + "loss": 0.18002840876579285, + "error": 0.0712890625, + "gradient_norm": 0.04201133921742439, + "elapsed": 660.4064948558807 + }, + { + "step": 1936, + "loss": 0.17531852424144745, + "error": 0.0732421875, + "gradient_norm": 0.024726318195462227, + "elapsed": 664.9991583824158 + }, + { + "step": 1952, + "loss": 0.5088322758674622, + "error": 0.2744140625, + "gradient_norm": 0.04693225398659706, + "elapsed": 669.5544555187225 + }, + { + "step": 1968, + "loss": 0.5684165358543396, + "error": 0.3310546875, + "gradient_norm": 0.031029095873236656, + "elapsed": 674.2354445457458 + }, + { + "step": 1984, + "loss": 0.06459524482488632, + "error": 0.017578125, + "gradient_norm": 0.03600892797112465, + "elapsed": 678.7982559204102 + }, + { + "step": 2000, + "loss": 0.3614455461502075, + "error": 0.1748046875, + "gradient_norm": 0.07060294598340988, + "elapsed": 683.2650325298309 + }, + { + "step": 2016, + "loss": 0.35535523295402527, + "error": 0.166015625, + "gradient_norm": 0.05873403698205948, + "elapsed": 687.7125518321991 + }, + { + "step": 2032, + "loss": 0.5638720989227295, + "error": 0.3232421875, + "gradient_norm": 0.07380504906177521, + "elapsed": 692.1461188793182 + }, + { + "step": 2048, + "loss": 0.5301838517189026, + "error": 0.2919921875, + "gradient_norm": 0.05435395985841751, + "elapsed": 696.6235508918762 + } + ] + }, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.250907301902771, + "error": 0.1083984375, + "gradient_norm": 0.07171476632356644, + "elapsed": 44.811134576797485 + }, + { + "step": 16, + "loss": 0.5958679914474487, + "error": 0.3662109375, + "gradient_norm": 0.07673005014657974, + "elapsed": 49.90856671333313 + }, + { + "step": 32, + "loss": 0.47648972272872925, + "error": 0.2421875, + "gradient_norm": 0.08561501652002335, + "elapsed": 55.179388761520386 + }, + { + "step": 48, + "loss": 0.06145006790757179, + "error": 0.0234375, + "gradient_norm": 0.01556467730551958, + "elapsed": 61.0339195728302 + }, + { + "step": 64, + "loss": 0.3687053918838501, + "error": 0.1884765625, + "gradient_norm": 0.08752371370792389, + "elapsed": 65.95811891555786 + }, + { + "step": 80, + "loss": 0.6481984853744507, + "error": 0.4140625, + "gradient_norm": 0.05311283841729164, + "elapsed": 70.56021332740784 + }, + { + "step": 96, + "loss": 0.42319929599761963, + "error": 0.2138671875, + "gradient_norm": 0.05047478526830673, + "elapsed": 75.11613631248474 + }, + { + "step": 112, + "loss": 0.47527259588241577, + "error": 0.24609375, + "gradient_norm": 0.038366906344890594, + "elapsed": 79.53446984291077 + }, + { + "step": 128, + "loss": 0.5996723175048828, + "error": 0.3369140625, + "gradient_norm": 0.1213272362947464, + "elapsed": 83.97515749931335 + }, + { + "step": 144, + "loss": 0.04971993714570999, + "error": 0.0146484375, + "gradient_norm": 0.008080735802650452, + "elapsed": 88.44039463996887 + }, + { + "step": 160, + "loss": 0.35900360345840454, + "error": 0.162109375, + "gradient_norm": 0.03359593451023102, + "elapsed": 92.89548206329346 + }, + { + "step": 176, + "loss": 0.5342063903808594, + "error": 0.2978515625, + "gradient_norm": 0.04794691130518913, + "elapsed": 97.35658049583435 + }, + { + "step": 192, + "loss": 0.6300076246261597, + "error": 0.369140625, + "gradient_norm": 0.081769198179245, + "elapsed": 101.81493759155273 + }, + { + "step": 208, + "loss": 0.6191903948783875, + "error": 0.3828125, + "gradient_norm": 0.07145775109529495, + "elapsed": 106.2480263710022 + }, + { + "step": 224, + "loss": 0.5155678391456604, + "error": 0.28515625, + "gradient_norm": 0.06772179156541824, + "elapsed": 110.71284222602844 + }, + { + "step": 240, + "loss": 0.634708046913147, + "error": 0.3857421875, + "gradient_norm": 0.09493093192577362, + "elapsed": 115.14978742599487 + }, + { + "step": 256, + "loss": 0.1840895414352417, + "error": 0.0751953125, + "gradient_norm": 0.025586696341633797, + "elapsed": 119.61202120780945 + }, + { + "step": 272, + "loss": 0.2775103449821472, + "error": 0.12890625, + "gradient_norm": 0.06913147866725922, + "elapsed": 124.02584528923035 + }, + { + "step": 288, + "loss": 0.6163080334663391, + "error": 0.3642578125, + "gradient_norm": 0.05895426496863365, + "elapsed": 128.46512532234192 + }, + { + "step": 304, + "loss": 0.5276986360549927, + "error": 0.287109375, + "gradient_norm": 0.06955187022686005, + "elapsed": 132.89240765571594 + }, + { + "step": 320, + "loss": 0.44859516620635986, + "error": 0.22265625, + "gradient_norm": 0.07272452116012573, + "elapsed": 137.32864713668823 + }, + { + "step": 336, + "loss": 0.48315611481666565, + "error": 0.2626953125, + "gradient_norm": 0.03321139141917229, + "elapsed": 141.80009770393372 + }, + { + "step": 352, + "loss": 0.6107717752456665, + "error": 0.3544921875, + "gradient_norm": 0.05243214592337608, + "elapsed": 146.36439752578735 + }, + { + "step": 368, + "loss": 0.6215153932571411, + "error": 0.357421875, + "gradient_norm": 0.04383325204253197, + "elapsed": 150.99996852874756 + }, + { + "step": 384, + "loss": 0.6130329966545105, + "error": 0.35546875, + "gradient_norm": 0.04113119840621948, + "elapsed": 155.62374639511108 + }, + { + "step": 400, + "loss": 0.30471885204315186, + "error": 0.142578125, + "gradient_norm": 0.04447556659579277, + "elapsed": 160.17594957351685 + }, + { + "step": 416, + "loss": 0.6154489517211914, + "error": 0.37109375, + "gradient_norm": 0.04456057772040367, + "elapsed": 164.7639675140381 + }, + { + "step": 432, + "loss": 0.6134694218635559, + "error": 0.337890625, + "gradient_norm": 0.04219559207558632, + "elapsed": 169.32792139053345 + }, + { + "step": 448, + "loss": 0.5463185906410217, + "error": 0.2939453125, + "gradient_norm": 0.07746092975139618, + "elapsed": 173.88445162773132 + }, + { + "step": 464, + "loss": 0.06016772612929344, + "error": 0.01953125, + "gradient_norm": 0.01364185381680727, + "elapsed": 178.42725706100464 + }, + { + "step": 480, + "loss": 0.388141393661499, + "error": 0.18359375, + "gradient_norm": 0.04870256036520004, + "elapsed": 182.99062085151672 + }, + { + "step": 496, + "loss": 0.44524821639060974, + "error": 0.2216796875, + "gradient_norm": 0.03453445807099342, + "elapsed": 187.56396961212158 + }, + { + "step": 512, + "loss": 0.34312355518341064, + "error": 0.154296875, + "gradient_norm": 0.06794509291648865, + "elapsed": 192.27511191368103 + }, + { + "step": 528, + "loss": 0.19467462599277496, + "error": 0.0771484375, + "gradient_norm": 0.042381469160318375, + "elapsed": 197.7108268737793 + }, + { + "step": 544, + "loss": 0.46226584911346436, + "error": 0.2421875, + "gradient_norm": 0.06073570251464844, + "elapsed": 202.97405791282654 + }, + { + "step": 560, + "loss": 0.525318443775177, + "error": 0.2822265625, + "gradient_norm": 0.06954885274171829, + "elapsed": 208.69676971435547 + }, + { + "step": 576, + "loss": 0.6158387064933777, + "error": 0.349609375, + "gradient_norm": 0.07587578892707825, + "elapsed": 214.80397653579712 + }, + { + "step": 592, + "loss": 0.5515886545181274, + "error": 0.298828125, + "gradient_norm": 0.04969338700175285, + "elapsed": 220.27399611473083 + }, + { + "step": 608, + "loss": 0.18365338444709778, + "error": 0.0654296875, + "gradient_norm": 0.08657706528902054, + "elapsed": 224.81246256828308 + }, + { + "step": 624, + "loss": 0.4578855633735657, + "error": 0.2421875, + "gradient_norm": 0.04942100867629051, + "elapsed": 229.45902252197266 + }, + { + "step": 640, + "loss": 0.37826013565063477, + "error": 0.1865234375, + "gradient_norm": 0.047499872744083405, + "elapsed": 233.9695644378662 + }, + { + "step": 656, + "loss": 0.40863412618637085, + "error": 0.2001953125, + "gradient_norm": 0.07845330238342285, + "elapsed": 238.584894657135 + }, + { + "step": 672, + "loss": 0.5640332698822021, + "error": 0.2880859375, + "gradient_norm": 0.057469289749860764, + "elapsed": 243.0929844379425 + }, + { + "step": 688, + "loss": 0.030216243118047714, + "error": 0.0078125, + "gradient_norm": 0.04682641476392746, + "elapsed": 247.581125497818 + }, + { + "step": 704, + "loss": 0.375002384185791, + "error": 0.1826171875, + "gradient_norm": 0.04864194989204407, + "elapsed": 252.1564691066742 + }, + { + "step": 720, + "loss": 0.5145515203475952, + "error": 0.2744140625, + "gradient_norm": 0.052671682089567184, + "elapsed": 256.6466488838196 + }, + { + "step": 736, + "loss": 0.067174531519413, + "error": 0.0224609375, + "gradient_norm": 0.019299577921628952, + "elapsed": 261.1185076236725 + }, + { + "step": 752, + "loss": 0.24909992516040802, + "error": 0.111328125, + "gradient_norm": 0.06907463818788528, + "elapsed": 265.61960339546204 + }, + { + "step": 768, + "loss": 0.5088074207305908, + "error": 0.2744140625, + "gradient_norm": 0.06963017582893372, + "elapsed": 270.07474064826965 + }, + { + "step": 784, + "loss": 0.3783387839794159, + "error": 0.1826171875, + "gradient_norm": 0.05537794530391693, + "elapsed": 274.52722239494324 + }, + { + "step": 800, + "loss": 0.6107200980186462, + "error": 0.3623046875, + "gradient_norm": 0.0470259003341198, + "elapsed": 279.0401859283447 + }, + { + "step": 816, + "loss": 0.5778236389160156, + "error": 0.3212890625, + "gradient_norm": 0.10146680474281311, + "elapsed": 283.5114622116089 + }, + { + "step": 832, + "loss": 0.576002299785614, + "error": 0.3076171875, + "gradient_norm": 0.07760787010192871, + "elapsed": 288.04797434806824 + }, + { + "step": 848, + "loss": 0.6179666519165039, + "error": 0.3740234375, + "gradient_norm": 0.07383852452039719, + "elapsed": 292.60600209236145 + }, + { + "step": 864, + "loss": 0.3105512857437134, + "error": 0.1455078125, + "gradient_norm": 0.052953749895095825, + "elapsed": 297.12180352211 + }, + { + "step": 880, + "loss": 0.4802623987197876, + "error": 0.2548828125, + "gradient_norm": 0.07736275345087051, + "elapsed": 301.6091134548187 + }, + { + "step": 896, + "loss": 0.5572722554206848, + "error": 0.318359375, + "gradient_norm": 0.053303152322769165, + "elapsed": 306.1978073120117 + }, + { + "step": 912, + "loss": 0.34814420342445374, + "error": 0.1669921875, + "gradient_norm": 0.037726350128650665, + "elapsed": 310.78571581840515 + }, + { + "step": 928, + "loss": 0.41743016242980957, + "error": 0.21875, + "gradient_norm": 0.05238872766494751, + "elapsed": 315.24156188964844 + }, + { + "step": 944, + "loss": 0.5757850408554077, + "error": 0.3173828125, + "gradient_norm": 0.05837905779480934, + "elapsed": 319.78475165367126 + }, + { + "step": 960, + "loss": 0.40727972984313965, + "error": 0.197265625, + "gradient_norm": 0.059294261038303375, + "elapsed": 324.2090265750885 + }, + { + "step": 976, + "loss": 0.32715001702308655, + "error": 0.1533203125, + "gradient_norm": 0.11543179303407669, + "elapsed": 328.6462152004242 + }, + { + "step": 992, + "loss": 0.5578742623329163, + "error": 0.314453125, + "gradient_norm": 0.06282714009284973, + "elapsed": 333.0712504386902 + }, + { + "step": 1008, + "loss": 0.5052692294120789, + "error": 0.265625, + "gradient_norm": 0.04039420187473297, + "elapsed": 337.5182821750641 + }, + { + "step": 1024, + "loss": 0.18790806829929352, + "error": 0.08203125, + "gradient_norm": 0.028905188664793968, + "elapsed": 342.08340406417847 + }, + { + "step": 1040, + "loss": 0.6317684650421143, + "error": 0.3681640625, + "gradient_norm": 0.03441835194826126, + "elapsed": 358.8279616832733 + }, + { + "step": 1056, + "loss": 0.40474164485931396, + "error": 0.2021484375, + "gradient_norm": 0.036449309438467026, + "elapsed": 363.30218267440796 + }, + { + "step": 1072, + "loss": 0.518299400806427, + "error": 0.2666015625, + "gradient_norm": 0.0886964276432991, + "elapsed": 367.87997555732727 + }, + { + "step": 1088, + "loss": 0.2522922158241272, + "error": 0.099609375, + "gradient_norm": 0.07553310692310333, + "elapsed": 372.4414882659912 + }, + { + "step": 1104, + "loss": 0.6214810609817505, + "error": 0.3701171875, + "gradient_norm": 0.10188957303762436, + "elapsed": 376.9120502471924 + }, + { + "step": 1120, + "loss": 0.6307054162025452, + "error": 0.3720703125, + "gradient_norm": 0.07353860139846802, + "elapsed": 381.3824534416199 + }, + { + "step": 1136, + "loss": 0.5259381532669067, + "error": 0.2763671875, + "gradient_norm": 0.05779678374528885, + "elapsed": 385.8413143157959 + }, + { + "step": 1152, + "loss": 0.4995541572570801, + "error": 0.259765625, + "gradient_norm": 0.046648140996694565, + "elapsed": 390.28326058387756 + }, + { + "step": 1168, + "loss": 0.6075694561004639, + "error": 0.3701171875, + "gradient_norm": 0.10612073540687561, + "elapsed": 394.8162364959717 + }, + { + "step": 1184, + "loss": 0.2105136513710022, + "error": 0.080078125, + "gradient_norm": 0.0716402605175972, + "elapsed": 399.2960283756256 + }, + { + "step": 1200, + "loss": 0.6371631026268005, + "error": 0.3857421875, + "gradient_norm": 0.0549108125269413, + "elapsed": 403.7899103164673 + }, + { + "step": 1216, + "loss": 0.5450670719146729, + "error": 0.2939453125, + "gradient_norm": 0.11688558012247086, + "elapsed": 408.34677600860596 + }, + { + "step": 1232, + "loss": 0.035783201456069946, + "error": 0.01171875, + "gradient_norm": 0.02951689623296261, + "elapsed": 412.8558337688446 + }, + { + "step": 1248, + "loss": 0.5582903623580933, + "error": 0.3046875, + "gradient_norm": 0.055107031017541885, + "elapsed": 417.29854226112366 + }, + { + "step": 1264, + "loss": 0.5154441595077515, + "error": 0.27734375, + "gradient_norm": 0.04474929720163345, + "elapsed": 421.7792055606842 + }, + { + "step": 1280, + "loss": 0.35227546095848083, + "error": 0.16015625, + "gradient_norm": 0.05024837702512741, + "elapsed": 426.54427456855774 + }, + { + "step": 1296, + "loss": 0.19417589902877808, + "error": 0.0830078125, + "gradient_norm": 0.026926057413220406, + "elapsed": 431.320588350296 + }, + { + "step": 1312, + "loss": 0.4768218398094177, + "error": 0.248046875, + "gradient_norm": 0.15099607408046722, + "elapsed": 435.96817326545715 + }, + { + "step": 1328, + "loss": 0.48580923676490784, + "error": 0.2509765625, + "gradient_norm": 0.08925126492977142, + "elapsed": 440.64917039871216 + }, + { + "step": 1344, + "loss": 0.42041274905204773, + "error": 0.1982421875, + "gradient_norm": 0.08321093022823334, + "elapsed": 445.34370946884155 + }, + { + "step": 1360, + "loss": 0.06403929740190506, + "error": 0.0185546875, + "gradient_norm": 0.03817005455493927, + "elapsed": 449.98669385910034 + }, + { + "step": 1376, + "loss": 0.463126003742218, + "error": 0.2275390625, + "gradient_norm": 0.08894515782594681, + "elapsed": 454.6478977203369 + }, + { + "step": 1392, + "loss": 0.5995306968688965, + "error": 0.373046875, + "gradient_norm": 0.06733685731887817, + "elapsed": 459.35924530029297 + }, + { + "step": 1408, + "loss": 0.49053263664245605, + "error": 0.25, + "gradient_norm": 0.10475508868694305, + "elapsed": 464.100093126297 + }, + { + "step": 1424, + "loss": 0.6220744848251343, + "error": 0.3818359375, + "gradient_norm": 0.03653963655233383, + "elapsed": 468.89601135253906 + }, + { + "step": 1440, + "loss": 0.39706122875213623, + "error": 0.2021484375, + "gradient_norm": 0.04344598576426506, + "elapsed": 474.03999519348145 + }, + { + "step": 1456, + "loss": 0.5386708974838257, + "error": 0.3095703125, + "gradient_norm": 0.12589037418365479, + "elapsed": 478.8600504398346 + }, + { + "step": 1472, + "loss": 0.49776726961135864, + "error": 0.271484375, + "gradient_norm": 0.058137863874435425, + "elapsed": 483.5920066833496 + }, + { + "step": 1488, + "loss": 0.4757428765296936, + "error": 0.2412109375, + "gradient_norm": 0.050453316420316696, + "elapsed": 488.4611999988556 + }, + { + "step": 1504, + "loss": 0.5694847702980042, + "error": 0.337890625, + "gradient_norm": 0.052419569343328476, + "elapsed": 493.26151037216187 + }, + { + "step": 1520, + "loss": 0.5997745990753174, + "error": 0.3603515625, + "gradient_norm": 0.04338108375668526, + "elapsed": 498.0421245098114 + }, + { + "step": 1536, + "loss": 0.6195274591445923, + "error": 0.3876953125, + "gradient_norm": 0.04848463833332062, + "elapsed": 502.8808298110962 + }, + { + "step": 1552, + "loss": 0.46315908432006836, + "error": 0.2353515625, + "gradient_norm": 0.06380566209554672, + "elapsed": 507.5519721508026 + }, + { + "step": 1568, + "loss": 0.605262041091919, + "error": 0.36328125, + "gradient_norm": 0.05077619478106499, + "elapsed": 512.457685470581 + }, + { + "step": 1584, + "loss": 0.48782041668891907, + "error": 0.232421875, + "gradient_norm": 0.09017211943864822, + "elapsed": 517.2960062026978 + }, + { + "step": 1600, + "loss": 0.3881351947784424, + "error": 0.1875, + "gradient_norm": 0.07205695658922195, + "elapsed": 522.0911631584167 + }, + { + "step": 1616, + "loss": 0.4966873526573181, + "error": 0.24609375, + "gradient_norm": 0.0582038015127182, + "elapsed": 526.8861901760101 + }, + { + "step": 1632, + "loss": 0.5844199657440186, + "error": 0.33203125, + "gradient_norm": 0.05101500824093819, + "elapsed": 531.6640138626099 + }, + { + "step": 1648, + "loss": 0.31010180711746216, + "error": 0.1318359375, + "gradient_norm": 0.053135693073272705, + "elapsed": 536.4960391521454 + }, + { + "step": 1664, + "loss": 0.6174807548522949, + "error": 0.3779296875, + "gradient_norm": 0.04161194711923599, + "elapsed": 541.2560484409332 + }, + { + "step": 1680, + "loss": 0.18213607370853424, + "error": 0.0751953125, + "gradient_norm": 0.07171957194805145, + "elapsed": 546.0000085830688 + }, + { + "step": 1696, + "loss": 0.5445692539215088, + "error": 0.2998046875, + "gradient_norm": 0.054499462246894836, + "elapsed": 551.1221191883087 + }, + { + "step": 1712, + "loss": 0.05744167044758797, + "error": 0.017578125, + "gradient_norm": 0.013108699582517147, + "elapsed": 556.5286149978638 + }, + { + "step": 1728, + "loss": 0.6381571292877197, + "error": 0.3896484375, + "gradient_norm": 0.05157556012272835, + "elapsed": 561.8000066280365 + }, + { + "step": 1744, + "loss": 0.5301004648208618, + "error": 0.28125, + "gradient_norm": 0.04218568280339241, + "elapsed": 567.2760035991669 + }, + { + "step": 1760, + "loss": 0.5275102257728577, + "error": 0.26953125, + "gradient_norm": 0.06798839569091797, + "elapsed": 572.5601994991302 + }, + { + "step": 1776, + "loss": 0.6443773508071899, + "error": 0.4091796875, + "gradient_norm": 0.07035460323095322, + "elapsed": 577.9789206981659 + }, + { + "step": 1792, + "loss": 0.6012362241744995, + "error": 0.337890625, + "gradient_norm": 0.05189951881766319, + "elapsed": 583.028017282486 + }, + { + "step": 1808, + "loss": 0.2939091920852661, + "error": 0.12109375, + "gradient_norm": 0.05555355176329613, + "elapsed": 588.0501506328583 + }, + { + "step": 1824, + "loss": 0.2059091478586197, + "error": 0.08984375, + "gradient_norm": 0.045679714530706406, + "elapsed": 593.2120039463043 + }, + { + "step": 1840, + "loss": 0.6289581060409546, + "error": 0.349609375, + "gradient_norm": 0.04742642492055893, + "elapsed": 598.7767763137817 + }, + { + "step": 1856, + "loss": 0.5532636642456055, + "error": 0.294921875, + "gradient_norm": 0.05997413396835327, + "elapsed": 604.0475382804871 + }, + { + "step": 1872, + "loss": 0.45995670557022095, + "error": 0.228515625, + "gradient_norm": 0.05674462765455246, + "elapsed": 609.292379617691 + }, + { + "step": 1888, + "loss": 0.6178656816482544, + "error": 0.359375, + "gradient_norm": 0.08857566863298416, + "elapsed": 614.5639882087708 + }, + { + "step": 1904, + "loss": 0.5531284213066101, + "error": 0.287109375, + "gradient_norm": 0.10257937759160995, + "elapsed": 619.5600035190582 + }, + { + "step": 1920, + "loss": 0.04184349626302719, + "error": 0.013671875, + "gradient_norm": 0.04087059944868088, + "elapsed": 624.6679775714874 + }, + { + "step": 1936, + "loss": 0.5924860239028931, + "error": 0.3505859375, + "gradient_norm": 0.036822713911533356, + "elapsed": 629.936680316925 + }, + { + "step": 1952, + "loss": 0.46996980905532837, + "error": 0.2421875, + "gradient_norm": 0.034442272037267685, + "elapsed": 635.1109762191772 + }, + { + "step": 1968, + "loss": 0.17859068512916565, + "error": 0.0712890625, + "gradient_norm": 0.03440066799521446, + "elapsed": 640.32000207901 + }, + { + "step": 1984, + "loss": 0.6192275285720825, + "error": 0.3701171875, + "gradient_norm": 0.04386439174413681, + "elapsed": 645.6040184497833 + }, + { + "step": 2000, + "loss": 0.6160917282104492, + "error": 0.35546875, + "gradient_norm": 0.06268990784883499, + "elapsed": 650.7723731994629 + }, + { + "step": 2016, + "loss": 0.6343611478805542, + "error": 0.388671875, + "gradient_norm": 0.04243326932191849, + "elapsed": 655.972663640976 + }, + { + "step": 2032, + "loss": 0.062292590737342834, + "error": 0.021484375, + "gradient_norm": 0.016680095344781876, + "elapsed": 660.8079733848572 + }, + { + "step": 2048, + "loss": 0.5316072702407837, + "error": 0.26953125, + "gradient_norm": 0.057860780507326126, + "elapsed": 665.5760209560394 + }, + { + "step": 2064, + "loss": 0.605312705039978, + "error": 0.3623046875, + "gradient_norm": 0.04028146713972092, + "elapsed": 682.7294294834137 + }, + { + "step": 2080, + "loss": 0.56633460521698, + "error": 0.3330078125, + "gradient_norm": 0.09528280049562454, + "elapsed": 687.4644649028778 + }, + { + "step": 2096, + "loss": 0.3905397057533264, + "error": 0.1943359375, + "gradient_norm": 0.049456462264060974, + "elapsed": 692.1492264270782 + }, + { + "step": 2112, + "loss": 0.28124868869781494, + "error": 0.1259765625, + "gradient_norm": 0.059239838272333145, + "elapsed": 696.8701393604279 + }, + { + "step": 2128, + "loss": 0.6364338994026184, + "error": 0.392578125, + "gradient_norm": 0.08667811006307602, + "elapsed": 701.683988571167 + }, + { + "step": 2144, + "loss": 0.20683243870735168, + "error": 0.07421875, + "gradient_norm": 0.1100710779428482, + "elapsed": 706.4000360965729 + }, + { + "step": 2160, + "loss": 0.5912737250328064, + "error": 0.341796875, + "gradient_norm": 0.05641854554414749, + "elapsed": 711.2359964847565 + }, + { + "step": 2176, + "loss": 0.27793264389038086, + "error": 0.12109375, + "gradient_norm": 0.0893034040927887, + "elapsed": 715.9508004188538 + }, + { + "step": 2192, + "loss": 0.6474133133888245, + "error": 0.4072265625, + "gradient_norm": 0.06980258971452713, + "elapsed": 720.651974439621 + }, + { + "step": 2208, + "loss": 0.5961858630180359, + "error": 0.35546875, + "gradient_norm": 0.06530112773180008, + "elapsed": 725.496098279953 + }, + { + "step": 2224, + "loss": 0.47581571340560913, + "error": 0.263671875, + "gradient_norm": 0.04470043256878853, + "elapsed": 730.2880010604858 + }, + { + "step": 2240, + "loss": 0.577988862991333, + "error": 0.318359375, + "gradient_norm": 0.07201159745454788, + "elapsed": 735.006133556366 + }, + { + "step": 2256, + "loss": 0.28444671630859375, + "error": 0.1181640625, + "gradient_norm": 0.048656050115823746, + "elapsed": 739.6868116855621 + }, + { + "step": 2272, + "loss": 0.2776409089565277, + "error": 0.1201171875, + "gradient_norm": 0.05783981829881668, + "elapsed": 744.3517308235168 + }, + { + "step": 2288, + "loss": 0.621599555015564, + "error": 0.37109375, + "gradient_norm": 0.09731200337409973, + "elapsed": 749.0351710319519 + }, + { + "step": 2304, + "loss": 0.3333754539489746, + "error": 0.1513671875, + "gradient_norm": 0.07069239765405655, + "elapsed": 753.7588081359863 + }, + { + "step": 2320, + "loss": 0.4687051773071289, + "error": 0.2490234375, + "gradient_norm": 0.044891707599163055, + "elapsed": 758.4588432312012 + }, + { + "step": 2336, + "loss": 0.19801637530326843, + "error": 0.078125, + "gradient_norm": 0.10036595165729523, + "elapsed": 763.256409406662 + }, + { + "step": 2352, + "loss": 0.6186277866363525, + "error": 0.388671875, + "gradient_norm": 0.09069584310054779, + "elapsed": 767.9986386299133 + }, + { + "step": 2368, + "loss": 0.6177258491516113, + "error": 0.373046875, + "gradient_norm": 0.049019571393728256, + "elapsed": 772.730831861496 + }, + { + "step": 2384, + "loss": 0.17707547545433044, + "error": 0.0673828125, + "gradient_norm": 0.045190781354904175, + "elapsed": 777.4072704315186 + }, + { + "step": 2400, + "loss": 0.20144733786582947, + "error": 0.08203125, + "gradient_norm": 0.04537162929773331, + "elapsed": 782.0841658115387 + }, + { + "step": 2416, + "loss": 0.6151775121688843, + "error": 0.365234375, + "gradient_norm": 0.050534047186374664, + "elapsed": 786.762966632843 + }, + { + "step": 2432, + "loss": 0.5533859133720398, + "error": 0.314453125, + "gradient_norm": 0.06006559729576111, + "elapsed": 791.4656012058258 + }, + { + "step": 2448, + "loss": 0.5329082012176514, + "error": 0.2880859375, + "gradient_norm": 0.04018115997314453, + "elapsed": 796.1704161167145 + }, + { + "step": 2464, + "loss": 0.6338047981262207, + "error": 0.4140625, + "gradient_norm": 0.06069163978099823, + "elapsed": 800.9180119037628 + }, + { + "step": 2480, + "loss": 0.1603008508682251, + "error": 0.0673828125, + "gradient_norm": 0.040350593626499176, + "elapsed": 805.6127603054047 + }, + { + "step": 2496, + "loss": 0.505940318107605, + "error": 0.2568359375, + "gradient_norm": 0.05209952965378761, + "elapsed": 810.3740313053131 + }, + { + "step": 2512, + "loss": 0.5528728365898132, + "error": 0.298828125, + "gradient_norm": 0.11757992953062057, + "elapsed": 815.1708807945251 + }, + { + "step": 2528, + "loss": 0.5028313994407654, + "error": 0.2666015625, + "gradient_norm": 0.08823780715465546, + "elapsed": 819.8585045337677 + }, + { + "step": 2544, + "loss": 0.5002262592315674, + "error": 0.2783203125, + "gradient_norm": 0.04888603836297989, + "elapsed": 824.5714073181152 + }, + { + "step": 2560, + "loss": 0.6007894277572632, + "error": 0.328125, + "gradient_norm": 0.05186954140663147, + "elapsed": 829.3080432415009 + }, + { + "step": 2576, + "loss": 0.18641480803489685, + "error": 0.076171875, + "gradient_norm": 0.03799928352236748, + "elapsed": 834.044020652771 + }, + { + "step": 2592, + "loss": 0.3050769865512848, + "error": 0.1396484375, + "gradient_norm": 0.10119257122278214, + "elapsed": 838.8401296138763 + }, + { + "step": 2608, + "loss": 0.6063439846038818, + "error": 0.361328125, + "gradient_norm": 0.04979367554187775, + "elapsed": 844.3572654724121 + }, + { + "step": 2624, + "loss": 0.5751967430114746, + "error": 0.3369140625, + "gradient_norm": 0.04269539937376976, + "elapsed": 849.0660374164581 + }, + { + "step": 2640, + "loss": 0.3902108669281006, + "error": 0.193359375, + "gradient_norm": 0.10029696673154831, + "elapsed": 853.8638062477112 + }, + { + "step": 2656, + "loss": 0.15081660449504852, + "error": 0.0625, + "gradient_norm": 0.0303852129727602, + "elapsed": 858.9793758392334 + }, + { + "step": 2672, + "loss": 0.6503090858459473, + "error": 0.400390625, + "gradient_norm": 0.12611964344978333, + "elapsed": 863.9151141643524 + }, + { + "step": 2688, + "loss": 0.5587317943572998, + "error": 0.31640625, + "gradient_norm": 0.10028114914894104, + "elapsed": 868.7600305080414 + }, + { + "step": 2704, + "loss": 0.4399867355823517, + "error": 0.21484375, + "gradient_norm": 0.06889455020427704, + "elapsed": 873.4544236660004 + }, + { + "step": 2720, + "loss": 0.5865127444267273, + "error": 0.337890625, + "gradient_norm": 0.03671631962060928, + "elapsed": 878.0982644557953 + }, + { + "step": 2736, + "loss": 0.6078637838363647, + "error": 0.3701171875, + "gradient_norm": 0.04679318517446518, + "elapsed": 883.0424642562866 + }, + { + "step": 2752, + "loss": 0.5825340151786804, + "error": 0.337890625, + "gradient_norm": 0.05619681254029274, + "elapsed": 887.908124923706 + }, + { + "step": 2768, + "loss": 0.5970422029495239, + "error": 0.3369140625, + "gradient_norm": 0.041302867233753204, + "elapsed": 892.6760206222534 + }, + { + "step": 2784, + "loss": 0.3870226740837097, + "error": 0.1826171875, + "gradient_norm": 0.05731065198779106, + "elapsed": 897.6246056556702 + }, + { + "step": 2800, + "loss": 0.38130277395248413, + "error": 0.1943359375, + "gradient_norm": 0.059244755655527115, + "elapsed": 902.3360238075256 + }, + { + "step": 2816, + "loss": 0.2617901563644409, + "error": 0.1064453125, + "gradient_norm": 0.041736964136362076, + "elapsed": 907.1600468158722 + }, + { + "step": 2832, + "loss": 0.5819337368011475, + "error": 0.314453125, + "gradient_norm": 0.04097156226634979, + "elapsed": 912.0244295597076 + }, + { + "step": 2848, + "loss": 0.41393283009529114, + "error": 0.2001953125, + "gradient_norm": 0.10456771403551102, + "elapsed": 916.8225846290588 + }, + { + "step": 2864, + "loss": 0.5019145011901855, + "error": 0.2548828125, + "gradient_norm": 0.04843736067414284, + "elapsed": 921.538754940033 + }, + { + "step": 2880, + "loss": 0.04561338573694229, + "error": 0.0146484375, + "gradient_norm": 0.025407327339053154, + "elapsed": 926.2588667869568 + }, + { + "step": 2896, + "loss": 0.4338858723640442, + "error": 0.205078125, + "gradient_norm": 0.09900517761707306, + "elapsed": 930.9781975746155 + }, + { + "step": 2912, + "loss": 0.33922863006591797, + "error": 0.162109375, + "gradient_norm": 0.10189604014158249, + "elapsed": 935.6816267967224 + }, + { + "step": 2928, + "loss": 0.5294322967529297, + "error": 0.2822265625, + "gradient_norm": 0.09060791879892349, + "elapsed": 940.4373068809509 + }, + { + "step": 2944, + "loss": 0.037007369101047516, + "error": 0.01171875, + "gradient_norm": 0.05506489425897598, + "elapsed": 945.1270468235016 + }, + { + "step": 2960, + "loss": 0.6096771359443665, + "error": 0.349609375, + "gradient_norm": 0.04987221211194992, + "elapsed": 949.8300130367279 + }, + { + "step": 2976, + "loss": 0.6157823801040649, + "error": 0.373046875, + "gradient_norm": 0.03614233434200287, + "elapsed": 954.5701997280121 + }, + { + "step": 2992, + "loss": 0.1978239268064499, + "error": 0.080078125, + "gradient_norm": 0.05847112461924553, + "elapsed": 959.2756471633911 + }, + { + "step": 3008, + "loss": 0.5237340927124023, + "error": 0.2841796875, + "gradient_norm": 0.06993591040372849, + "elapsed": 963.9875864982605 + }, + { + "step": 3024, + "loss": 0.4559935927391052, + "error": 0.2373046875, + "gradient_norm": 0.05698448419570923, + "elapsed": 968.7997305393219 + }, + { + "step": 3040, + "loss": 0.5025208592414856, + "error": 0.259765625, + "gradient_norm": 0.14909739792346954, + "elapsed": 973.6042547225952 + }, + { + "step": 3056, + "loss": 0.3223109245300293, + "error": 0.1416015625, + "gradient_norm": 0.032974764704704285, + "elapsed": 978.4760546684265 + }, + { + "step": 3072, + "loss": 0.06682582199573517, + "error": 0.021484375, + "gradient_norm": 0.04433188587427139, + "elapsed": 983.2894048690796 + }, + { + "step": 3088, + "loss": 0.5919550061225891, + "error": 0.34765625, + "gradient_norm": 0.06721373647451401, + "elapsed": 1000.9520287513733 + }, + { + "step": 3104, + "loss": 0.5988063812255859, + "error": 0.3642578125, + "gradient_norm": 0.05654948577284813, + "elapsed": 1005.7442932128906 + }, + { + "step": 3120, + "loss": 0.4922299385070801, + "error": 0.2470703125, + "gradient_norm": 0.07545466721057892, + "elapsed": 1010.4616096019745 + }, + { + "step": 3136, + "loss": 0.4533671736717224, + "error": 0.236328125, + "gradient_norm": 0.06288722902536392, + "elapsed": 1015.3559956550598 + }, + { + "step": 3152, + "loss": 0.5070517063140869, + "error": 0.2666015625, + "gradient_norm": 0.07274917513132095, + "elapsed": 1020.0764343738556 + }, + { + "step": 3168, + "loss": 0.5999464988708496, + "error": 0.3408203125, + "gradient_norm": 0.05777016654610634, + "elapsed": 1024.9410600662231 + }, + { + "step": 3184, + "loss": 0.5758363008499146, + "error": 0.3427734375, + "gradient_norm": 0.051027461886405945, + "elapsed": 1029.7082171440125 + }, + { + "step": 3200, + "loss": 0.05016190931200981, + "error": 0.017578125, + "gradient_norm": 0.009175656363368034, + "elapsed": 1034.3982915878296 + }, + { + "step": 3216, + "loss": 0.5471057295799255, + "error": 0.318359375, + "gradient_norm": 0.07572721689939499, + "elapsed": 1039.117841243744 + }, + { + "step": 3232, + "loss": 0.4141446352005005, + "error": 0.193359375, + "gradient_norm": 0.10056859254837036, + "elapsed": 1043.880026102066 + }, + { + "step": 3248, + "loss": 0.5812438726425171, + "error": 0.3212890625, + "gradient_norm": 0.05781616270542145, + "elapsed": 1048.6406455039978 + }, + { + "step": 3264, + "loss": 0.19184701144695282, + "error": 0.078125, + "gradient_norm": 0.05367236211895943, + "elapsed": 1053.5672237873077 + }, + { + "step": 3280, + "loss": 0.5420833826065063, + "error": 0.28515625, + "gradient_norm": 0.052405405789613724, + "elapsed": 1058.3841104507446 + }, + { + "step": 3296, + "loss": 0.4419598877429962, + "error": 0.2177734375, + "gradient_norm": 0.05814693495631218, + "elapsed": 1063.1880333423615 + }, + { + "step": 3312, + "loss": 0.4525642991065979, + "error": 0.208984375, + "gradient_norm": 0.1061021164059639, + "elapsed": 1068.1370933055878 + }, + { + "step": 3328, + "loss": 0.32664671540260315, + "error": 0.154296875, + "gradient_norm": 0.05649850144982338, + "elapsed": 1073.1963467597961 + }, + { + "step": 3344, + "loss": 0.2655770182609558, + "error": 0.1220703125, + "gradient_norm": 0.04070372134447098, + "elapsed": 1078.2698318958282 + }, + { + "step": 3360, + "loss": 0.5894330739974976, + "error": 0.3544921875, + "gradient_norm": 0.0643400028347969, + "elapsed": 1083.0184152126312 + }, + { + "step": 3376, + "loss": 0.6118791103363037, + "error": 0.361328125, + "gradient_norm": 0.08537904173135757, + "elapsed": 1087.834038734436 + }, + { + "step": 3392, + "loss": 0.40694907307624817, + "error": 0.19921875, + "gradient_norm": 0.11411692947149277, + "elapsed": 1092.8119947910309 + }, + { + "step": 3408, + "loss": 0.04629015550017357, + "error": 0.0146484375, + "gradient_norm": 0.017204072326421738, + "elapsed": 1097.5751783847809 + }, + { + "step": 3424, + "loss": 0.20639702677726746, + "error": 0.0849609375, + "gradient_norm": 0.04801144450902939, + "elapsed": 1102.2970931529999 + }, + { + "step": 3440, + "loss": 0.6051071286201477, + "error": 0.33984375, + "gradient_norm": 0.045392412692308426, + "elapsed": 1107.1080610752106 + }, + { + "step": 3456, + "loss": 0.6553700566291809, + "error": 0.40625, + "gradient_norm": 0.05593863129615784, + "elapsed": 1111.8409752845764 + }, + { + "step": 3472, + "loss": 0.591402530670166, + "error": 0.3515625, + "gradient_norm": 0.051181379705667496, + "elapsed": 1116.5800333023071 + }, + { + "step": 3488, + "loss": 0.30494624376296997, + "error": 0.12109375, + "gradient_norm": 0.05175542086362839, + "elapsed": 1121.276373386383 + }, + { + "step": 3504, + "loss": 0.5065370798110962, + "error": 0.279296875, + "gradient_norm": 0.10419930517673492, + "elapsed": 1125.9883344173431 + }, + { + "step": 3520, + "loss": 0.3915700614452362, + "error": 0.1953125, + "gradient_norm": 0.060416825115680695, + "elapsed": 1130.7958455085754 + }, + { + "step": 3536, + "loss": 0.624374270439148, + "error": 0.3759765625, + "gradient_norm": 0.06069556251168251, + "elapsed": 1135.5360939502716 + }, + { + "step": 3552, + "loss": 0.5830206274986267, + "error": 0.3359375, + "gradient_norm": 0.046013280749320984, + "elapsed": 1140.312029838562 + }, + { + "step": 3568, + "loss": 0.4201379716396332, + "error": 0.2119140625, + "gradient_norm": 0.06909621506929398, + "elapsed": 1145.0904593467712 + }, + { + "step": 3584, + "loss": 0.28215405344963074, + "error": 0.1181640625, + "gradient_norm": 0.07625982910394669, + "elapsed": 1149.8156151771545 + }, + { + "step": 3600, + "loss": 0.5229164361953735, + "error": 0.275390625, + "gradient_norm": 0.055048178881406784, + "elapsed": 1154.5280592441559 + }, + { + "step": 3616, + "loss": 0.47238075733184814, + "error": 0.2314453125, + "gradient_norm": 0.06473162025213242, + "elapsed": 1159.2720873355865 + }, + { + "step": 3632, + "loss": 0.46245503425598145, + "error": 0.228515625, + "gradient_norm": 0.07382887601852417, + "elapsed": 1164.0119998455048 + }, + { + "step": 3648, + "loss": 0.37509745359420776, + "error": 0.171875, + "gradient_norm": 0.051260266453027725, + "elapsed": 1168.7440350055695 + }, + { + "step": 3664, + "loss": 0.1948484629392624, + "error": 0.080078125, + "gradient_norm": 0.059623416513204575, + "elapsed": 1173.3906588554382 + }, + { + "step": 3680, + "loss": 0.5552756786346436, + "error": 0.3115234375, + "gradient_norm": 0.08073585480451584, + "elapsed": 1178.0645008087158 + }, + { + "step": 3696, + "loss": 0.6405904293060303, + "error": 0.39453125, + "gradient_norm": 0.05899551138281822, + "elapsed": 1182.730489730835 + }, + { + "step": 3712, + "loss": 0.2767012119293213, + "error": 0.119140625, + "gradient_norm": 0.06593579798936844, + "elapsed": 1187.377315044403 + }, + { + "step": 3728, + "loss": 0.315812885761261, + "error": 0.134765625, + "gradient_norm": 0.035905495285987854, + "elapsed": 1192.0582301616669 + }, + { + "step": 3744, + "loss": 0.6033951640129089, + "error": 0.3544921875, + "gradient_norm": 0.05226197466254234, + "elapsed": 1196.7101175785065 + }, + { + "step": 3760, + "loss": 0.5202592611312866, + "error": 0.275390625, + "gradient_norm": 0.06367512047290802, + "elapsed": 1201.3543090820312 + }, + { + "step": 3776, + "loss": 0.24639368057250977, + "error": 0.1083984375, + "gradient_norm": 0.09370873868465424, + "elapsed": 1206.0717165470123 + }, + { + "step": 3792, + "loss": 0.6175658702850342, + "error": 0.375, + "gradient_norm": 0.06221585348248482, + "elapsed": 1210.754029750824 + }, + { + "step": 3808, + "loss": 0.41153696179389954, + "error": 0.2119140625, + "gradient_norm": 0.05355365574359894, + "elapsed": 1215.4374370574951 + }, + { + "step": 3824, + "loss": 0.28002214431762695, + "error": 0.1123046875, + "gradient_norm": 0.03846330568194389, + "elapsed": 1220.1207013130188 + }, + { + "step": 3840, + "loss": 0.0484195351600647, + "error": 0.013671875, + "gradient_norm": 0.03470242768526077, + "elapsed": 1224.8153104782104 + }, + { + "step": 3856, + "loss": 0.1407160609960556, + "error": 0.0458984375, + "gradient_norm": 0.04061700031161308, + "elapsed": 1229.5512235164642 + }, + { + "step": 3872, + "loss": 0.5881794691085815, + "error": 0.3427734375, + "gradient_norm": 0.062013477087020874, + "elapsed": 1234.3750183582306 + }, + { + "step": 3888, + "loss": 0.17833612859249115, + "error": 0.06640625, + "gradient_norm": 0.038856204599142075, + "elapsed": 1239.110375881195 + }, + { + "step": 3904, + "loss": 0.06211477518081665, + "error": 0.0224609375, + "gradient_norm": 0.02150108851492405, + "elapsed": 1243.800644159317 + }, + { + "step": 3920, + "loss": 0.06039723381400108, + "error": 0.01953125, + "gradient_norm": 0.019367367029190063, + "elapsed": 1248.4831748008728 + }, + { + "step": 3936, + "loss": 0.6010214686393738, + "error": 0.3525390625, + "gradient_norm": 0.051659151911735535, + "elapsed": 1253.1423478126526 + }, + { + "step": 3952, + "loss": 0.5867137312889099, + "error": 0.3388671875, + "gradient_norm": 0.058528851717710495, + "elapsed": 1257.9799931049347 + }, + { + "step": 3968, + "loss": 0.5231834650039673, + "error": 0.2578125, + "gradient_norm": 0.10128334909677505, + "elapsed": 1262.6990082263947 + }, + { + "step": 3984, + "loss": 0.6251651644706726, + "error": 0.353515625, + "gradient_norm": 0.06211795285344124, + "elapsed": 1267.4289934635162 + }, + { + "step": 4000, + "loss": 0.06667037308216095, + "error": 0.01953125, + "gradient_norm": 0.048018258064985275, + "elapsed": 1272.132089138031 + }, + { + "step": 4016, + "loss": 0.5286938548088074, + "error": 0.2744140625, + "gradient_norm": 0.05509360507130623, + "elapsed": 1276.8878977298737 + }, + { + "step": 4032, + "loss": 0.34016552567481995, + "error": 0.1591796875, + "gradient_norm": 0.07597329467535019, + "elapsed": 1281.7364926338196 + }, + { + "step": 4048, + "loss": 0.17750494182109833, + "error": 0.078125, + "gradient_norm": 0.06314503401517868, + "elapsed": 1286.5033600330353 + }, + { + "step": 4064, + "loss": 0.5882893800735474, + "error": 0.34375, + "gradient_norm": 0.10986580699682236, + "elapsed": 1291.1944887638092 + }, + { + "step": 4080, + "loss": 0.4923543930053711, + "error": 0.2568359375, + "gradient_norm": 0.050325747579336166, + "elapsed": 1295.9372322559357 + }, + { + "step": 4096, + "loss": 0.44146978855133057, + "error": 0.2236328125, + "gradient_norm": 0.06535191088914871, + "elapsed": 1300.641023159027 + } + ] + }, + "derived_checkpoints": { + "mean3": { + "checkpoint_label": "mean3", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_optimizer_steps": [ + 2048, + 3072, + 4096 + ], + "source_training_run": "temporal2", + "source_weights_sha256": { + "2048": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "3072": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "4096": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea" + }, + "source_checkpoint_records": { + "2048": { + "step": 2048, + "new_training_shots": 2097152, + "unique_training_rows_seen_in_this_phase": 1293629, + "weights": "weights-2048.npz", + "weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "validation": "validation-2048.json", + "complete": true + }, + "3072": { + "step": 3072, + "new_training_shots": 3145728, + "unique_training_rows_seen_in_this_phase": 1594502, + "weights": "weights-3072.npz", + "weights_sha256": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "validation": "validation-3072.json", + "complete": true + }, + "4096": { + "step": 4096, + "new_training_shots": 4194304, + "unique_training_rows_seen_in_this_phase": 1778773, + "weights": "weights-4096.npz", + "weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "validation": "validation-4096.json", + "complete": true + } + }, + "weights_sha256": "a61fb22f803b795c2a39b6c19dc3a368d536cb21419ba773778601b28e4403fe", + "complete": true + }, + "mean4": { + "checkpoint_label": "mean4", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_optimizer_steps": [ + 1024, + 2048, + 3072, + 4096 + ], + "source_training_run": "temporal2", + "source_weights_sha256": { + "1024": "0d809362d5afe1dc781f716e3aee1a9bc5a8f75fed6cc0ff6339b9abcf600ada", + "2048": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "3072": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "4096": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea" + }, + "source_checkpoint_records": { + "1024": { + "step": 1024, + "new_training_shots": 1048576, + "unique_training_rows_seen_in_this_phase": 804757, + "weights": "weights-1024.npz", + "weights_sha256": "0d809362d5afe1dc781f716e3aee1a9bc5a8f75fed6cc0ff6339b9abcf600ada", + "validation": "validation-1024.json", + "complete": true + }, + "2048": { + "step": 2048, + "new_training_shots": 2097152, + "unique_training_rows_seen_in_this_phase": 1293629, + "weights": "weights-2048.npz", + "weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "validation": "validation-2048.json", + "complete": true + }, + "3072": { + "step": 3072, + "new_training_shots": 3145728, + "unique_training_rows_seen_in_this_phase": 1594502, + "weights": "weights-3072.npz", + "weights_sha256": "fabbb42432fb0975023f0a367a366b8db591c6866719b4c7efb85cfe91934c65", + "validation": "validation-3072.json", + "complete": true + }, + "4096": { + "step": 4096, + "new_training_shots": 4194304, + "unique_training_rows_seen_in_this_phase": 1778773, + "weights": "weights-4096.npz", + "weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "validation": "validation-4096.json", + "complete": true + } + }, + "weights_sha256": "ff4595e8f3eb7cfaa8da5a58a31e106d9684c7b8437f330573a1291f19f5777a", + "complete": true + } + }, + "selection": "Predefined last-three and all-four noninitial temporal2 checkpoint means; every validation condition evaluated before group selection", + "test_data_used": false, + "derivation_source_sha256": "b68813c7dab697a554185020c430ef05f1c35bedcda5b85b7d165af75461e914" + }, + "loss": "Binary conditional logical likelihood computed by exact frontier elimination", + "validation_shots_per_condition": 1024, + "uniform_validation": true, + "uniform_validation_seed": 20261028, + "test_data_used": false, + "log": [ + { + "step": 1, + "loss": 0.5063965320587158, + "error": 0.263671875, + "gradient_norm": 0.05583755671977997, + "elapsed": 33.61826181411743 + }, + { + "step": 16, + "loss": 0.5231766700744629, + "error": 0.2822265625, + "gradient_norm": 0.05158894136548042, + "elapsed": 48.65802335739136 + }, + { + "step": 32, + "loss": 0.2955678701400757, + "error": 0.1376953125, + "gradient_norm": 0.0717208981513977, + "elapsed": 64.75103712081909 + }, + { + "step": 48, + "loss": 0.5808531045913696, + "error": 0.337890625, + "gradient_norm": 0.0497879758477211, + "elapsed": 81.12590050697327 + }, + { + "step": 64, + "loss": 0.6466071605682373, + "error": 0.3955078125, + "gradient_norm": 0.05340445786714554, + "elapsed": 97.40131282806396 + }, + { + "step": 80, + "loss": 0.43967077136039734, + "error": 0.2197265625, + "gradient_norm": 0.05488451197743416, + "elapsed": 113.68819904327393 + }, + { + "step": 96, + "loss": 0.3481931686401367, + "error": 0.166015625, + "gradient_norm": 0.08198399841785431, + "elapsed": 129.79422783851624 + }, + { + "step": 112, + "loss": 0.37728914618492126, + "error": 0.177734375, + "gradient_norm": 0.04957005754113197, + "elapsed": 146.01310849189758 + }, + { + "step": 128, + "loss": 0.19336706399917603, + "error": 0.07421875, + "gradient_norm": 0.03228567913174629, + "elapsed": 162.3233504295349 + }, + { + "step": 144, + "loss": 0.05673666670918465, + "error": 0.013671875, + "gradient_norm": 0.010086167603731155, + "elapsed": 178.27910375595093 + }, + { + "step": 160, + "loss": 0.05576886981725693, + "error": 0.0185546875, + "gradient_norm": 0.015833213925361633, + "elapsed": 194.4404194355011 + }, + { + "step": 176, + "loss": 0.6271512508392334, + "error": 0.39453125, + "gradient_norm": 0.0890795886516571, + "elapsed": 210.55058026313782 + }, + { + "step": 192, + "loss": 0.5520341992378235, + "error": 0.2998046875, + "gradient_norm": 0.12568876147270203, + "elapsed": 226.60093927383423 + }, + { + "step": 208, + "loss": 0.5262938737869263, + "error": 0.2822265625, + "gradient_norm": 0.055265434086322784, + "elapsed": 244.85273218154907 + }, + { + "step": 224, + "loss": 0.5956001281738281, + "error": 0.3369140625, + "gradient_norm": 0.06895016878843307, + "elapsed": 264.53393387794495 + }, + { + "step": 240, + "loss": 0.25704875588417053, + "error": 0.1259765625, + "gradient_norm": 0.11300098150968552, + "elapsed": 283.89024353027344 + }, + { + "step": 256, + "loss": 0.6143664121627808, + "error": 0.369140625, + "gradient_norm": 0.05419369786977768, + "elapsed": 300.05279064178467 + }, + { + "step": 272, + "loss": 0.5590812563896179, + "error": 0.294921875, + "gradient_norm": 0.06284675002098083, + "elapsed": 315.92391777038574 + }, + { + "step": 288, + "loss": 0.6163386106491089, + "error": 0.353515625, + "gradient_norm": 0.06826888024806976, + "elapsed": 331.96330738067627 + }, + { + "step": 304, + "loss": 0.6250298619270325, + "error": 0.37890625, + "gradient_norm": 0.0710018053650856, + "elapsed": 348.11866188049316 + }, + { + "step": 320, + "loss": 0.3802686631679535, + "error": 0.1796875, + "gradient_norm": 0.05896822363138199, + "elapsed": 364.3013961315155 + }, + { + "step": 336, + "loss": 0.2594846487045288, + "error": 0.1123046875, + "gradient_norm": 0.0468285046517849, + "elapsed": 380.80411195755005 + }, + { + "step": 352, + "loss": 0.19520026445388794, + "error": 0.076171875, + "gradient_norm": 0.032125141471624374, + "elapsed": 396.8971872329712 + }, + { + "step": 368, + "loss": 0.621718168258667, + "error": 0.37890625, + "gradient_norm": 0.0545712448656559, + "elapsed": 412.920996427536 + }, + { + "step": 384, + "loss": 0.6092393398284912, + "error": 0.349609375, + "gradient_norm": 0.04697328060865402, + "elapsed": 428.92249155044556 + }, + { + "step": 400, + "loss": 0.33656495809555054, + "error": 0.171875, + "gradient_norm": 0.04851065203547478, + "elapsed": 444.8614237308502 + }, + { + "step": 416, + "loss": 0.563441812992096, + "error": 0.302734375, + "gradient_norm": 0.06761237233877182, + "elapsed": 460.89916157722473 + }, + { + "step": 432, + "loss": 0.41032207012176514, + "error": 0.205078125, + "gradient_norm": 0.07552587240934372, + "elapsed": 476.91754388809204 + }, + { + "step": 448, + "loss": 0.6176105737686157, + "error": 0.3583984375, + "gradient_norm": 0.03991354629397392, + "elapsed": 492.909494638443 + }, + { + "step": 464, + "loss": 0.47970300912857056, + "error": 0.26171875, + "gradient_norm": 0.08514834195375443, + "elapsed": 508.9842050075531 + }, + { + "step": 480, + "loss": 0.6145294904708862, + "error": 0.3779296875, + "gradient_norm": 0.04053078964352608, + "elapsed": 525.0681574344635 + }, + { + "step": 496, + "loss": 0.5232605934143066, + "error": 0.28125, + "gradient_norm": 0.07535209506750107, + "elapsed": 541.048586845398 + }, + { + "step": 512, + "loss": 0.06574343144893646, + "error": 0.01953125, + "gradient_norm": 0.038100212812423706, + "elapsed": 557.0923149585724 + }, + { + "step": 528, + "loss": 0.052529145032167435, + "error": 0.021484375, + "gradient_norm": 0.017167840152978897, + "elapsed": 588.7646441459656 + }, + { + "step": 544, + "loss": 0.5886420011520386, + "error": 0.3447265625, + "gradient_norm": 0.04695608466863632, + "elapsed": 607.2257866859436 + }, + { + "step": 560, + "loss": 0.6055985689163208, + "error": 0.3466796875, + "gradient_norm": 0.032950498163700104, + "elapsed": 625.9134004116058 + }, + { + "step": 576, + "loss": 0.4632350206375122, + "error": 0.2431640625, + "gradient_norm": 0.07214360684156418, + "elapsed": 642.5683023929596 + }, + { + "step": 592, + "loss": 0.5995157361030579, + "error": 0.33984375, + "gradient_norm": 0.05927892401814461, + "elapsed": 659.0285487174988 + }, + { + "step": 608, + "loss": 0.2751845121383667, + "error": 0.1171875, + "gradient_norm": 0.06076137721538544, + "elapsed": 675.2659955024719 + }, + { + "step": 624, + "loss": 0.0518009215593338, + "error": 0.0205078125, + "gradient_norm": 0.017002176493406296, + "elapsed": 691.3256914615631 + }, + { + "step": 640, + "loss": 0.6293823719024658, + "error": 0.4013671875, + "gradient_norm": 0.07381543517112732, + "elapsed": 707.3796145915985 + }, + { + "step": 656, + "loss": 0.2956032454967499, + "error": 0.126953125, + "gradient_norm": 0.06658996641635895, + "elapsed": 723.4796185493469 + }, + { + "step": 672, + "loss": 0.5275129079818726, + "error": 0.28125, + "gradient_norm": 0.0742238238453865, + "elapsed": 739.52592253685 + }, + { + "step": 688, + "loss": 0.48426946997642517, + "error": 0.251953125, + "gradient_norm": 0.08587855845689774, + "elapsed": 755.599978685379 + }, + { + "step": 704, + "loss": 0.5284034013748169, + "error": 0.298828125, + "gradient_norm": 0.07507473230361938, + "elapsed": 771.6798233985901 + }, + { + "step": 720, + "loss": 0.45124661922454834, + "error": 0.2333984375, + "gradient_norm": 0.040898919105529785, + "elapsed": 787.8532867431641 + }, + { + "step": 736, + "loss": 0.04965062811970711, + "error": 0.0146484375, + "gradient_norm": 0.013609266839921474, + "elapsed": 804.1182470321655 + }, + { + "step": 752, + "loss": 0.04790960252285004, + "error": 0.01171875, + "gradient_norm": 0.01157061941921711, + "elapsed": 820.3099284172058 + }, + { + "step": 768, + "loss": 0.046329010277986526, + "error": 0.0146484375, + "gradient_norm": 0.013687756843864918, + "elapsed": 836.2443821430206 + }, + { + "step": 784, + "loss": 0.20798391103744507, + "error": 0.0830078125, + "gradient_norm": 0.10879658162593842, + "elapsed": 853.994068145752 + }, + { + "step": 800, + "loss": 0.3236527144908905, + "error": 0.1494140625, + "gradient_norm": 0.04277466610074043, + "elapsed": 872.6724886894226 + }, + { + "step": 816, + "loss": 0.5978351831436157, + "error": 0.3310546875, + "gradient_norm": 0.09687308222055435, + "elapsed": 890.0722959041595 + }, + { + "step": 832, + "loss": 0.5914890766143799, + "error": 0.3515625, + "gradient_norm": 0.05389918386936188, + "elapsed": 907.574702501297 + }, + { + "step": 848, + "loss": 0.3500230312347412, + "error": 0.154296875, + "gradient_norm": 0.05182121321558952, + "elapsed": 925.516667842865 + }, + { + "step": 864, + "loss": 0.3173527717590332, + "error": 0.126953125, + "gradient_norm": 0.10333289951086044, + "elapsed": 943.2102818489075 + }, + { + "step": 880, + "loss": 0.6407152414321899, + "error": 0.41015625, + "gradient_norm": 0.03933756425976753, + "elapsed": 960.0137810707092 + }, + { + "step": 896, + "loss": 0.3448338210582733, + "error": 0.1591796875, + "gradient_norm": 0.048397257924079895, + "elapsed": 976.2672023773193 + }, + { + "step": 912, + "loss": 0.2199687361717224, + "error": 0.0830078125, + "gradient_norm": 0.11513829976320267, + "elapsed": 992.4728758335114 + }, + { + "step": 928, + "loss": 0.16880497336387634, + "error": 0.072265625, + "gradient_norm": 0.031767718493938446, + "elapsed": 1008.5988037586212 + }, + { + "step": 944, + "loss": 0.053500816226005554, + "error": 0.017578125, + "gradient_norm": 0.014627245254814625, + "elapsed": 1024.7008044719696 + }, + { + "step": 960, + "loss": 0.5974152684211731, + "error": 0.341796875, + "gradient_norm": 0.09594274312257767, + "elapsed": 1040.908540725708 + }, + { + "step": 976, + "loss": 0.34772756695747375, + "error": 0.1572265625, + "gradient_norm": 0.04134370759129524, + "elapsed": 1056.9926254749298 + }, + { + "step": 992, + "loss": 0.4953954815864563, + "error": 0.2744140625, + "gradient_norm": 0.09671331197023392, + "elapsed": 1073.0582761764526 + }, + { + "step": 1008, + "loss": 0.6424463987350464, + "error": 0.4013671875, + "gradient_norm": 0.13621115684509277, + "elapsed": 1089.2002465724945 + }, + { + "step": 1024, + "loss": 0.1914748251438141, + "error": 0.0771484375, + "gradient_norm": 0.05097605288028717, + "elapsed": 1105.341599225998 + } + ], + "condition_mixing_plan": { + "hypothesis": "Mixing uniformly sampled geometry/basis/duration conditions in each gradient update reduces condition-gradient fluctuations", + "parent": "temporal2_swa/weights-mean3.npz", + "new_random_parameter_initializations": 0, + "sampling_seed": 20261190, + "arms": [ + "same", + "mixed" + ], + "microbatches_per_update": 4, + "microbatch_size": 256, + "effective_batch_size": 1024, + "optimizer_updates": 1024, + "learning_rate": 0.00025, + "optimizer": "Fresh AdamW state, weight decay1e-4, global gradient norm clip1 after averaging gradients", + "sampling_control": "Both arms draw four condition indices then four256-row batches per update. Same arm reuses the first condition index; mixed uses all four. Equal-sized condition pools make RNG states identical.", + "training": "All104 d3 conditions and all supplied training rows eligible;1,048,576 training draws in each arm", + "selection": "Full validation checkpoints512/1024, per-group mean across all13 durations; raw or equal blend with recorded small contextual reference; incumbent retained on ties", + "test_data_used": false + }, + "accumulation_numerical_control": { + "status": "passed", + "device": "cpu", + "condition": "surface_code_bZ_d3_r13_center_5_7", + "parent_checkpoint_sha256": "a61fb22f803b795c2a39b6c19dc3a368d536cb21419ba773778601b28e4403fe", + "trainer_source_sha256": "9f672468a8b72966b3aa04fd22e5d40b47b0768f1c802c267a1da08244c4323b", + "gradient_relative_l2_difference": 1.0312139158546257e-06, + "maximum_gradient_difference": 4.023313522338867e-07, + "mean_loss_difference": 0.0, + "maximum_optimizer_update_difference": 1.0697840480133891e-06, + "matched_rng_state_after_1024_updates": true, + "precision_audit": { + "float64_full_vs_accumulated_gradient_relative_l2": 2.4022986924332267e-15, + "float64_full_vs_accumulated_update_maximum_difference": 1.6631390275384517e-15, + "float32_full_gradient_relative_l2_vs_float64": 1.1454018534911662e-06, + "float32_accumulated_gradient_relative_l2_vs_float64": 9.16593382832008e-07, + "float32_full_update_maximum_difference_vs_float64": 6.5271394129382524e-06, + "float32_accumulated_update_maximum_difference_vs_float64": 7.5969234609516415e-06, + "initial_failed_check": { + "maximum_float32_update_difference": 1.0697840480133891e-06, + "original_tolerance": 1e-06 + }, + "interpretation": "Float64 audit checks accumulation algebra independently of float32 reduction rounding and first-Adam-step sensitivity near zero gradients. Original failure is retained; production model/gradient precision and optimizer are unchanged." + }, + "training_draws_each_arm": 1048576, + "draws_by_condition": { + "same": [ + 17408, + 14336, + 12288, + 14336, + 7168, + 10240, + 8192, + 7168, + 9216, + 11264, + 14336, + 7168, + 5120, + 9216, + 7168, + 8192, + 8192, + 10240, + 7168, + 10240, + 11264, + 14336, + 15360, + 10240, + 8192, + 11264, + 11264, + 17408, + 11264, + 15360, + 10240, + 17408, + 7168, + 13312, + 5120, + 13312, + 4096, + 8192, + 10240, + 8192, + 8192, + 5120, + 10240, + 11264, + 16384, + 13312, + 9216, + 9216, + 14336, + 8192, + 10240, + 10240, + 3072, + 8192, + 11264, + 12288, + 5120, + 4096, + 7168, + 9216, + 5120, + 14336, + 8192, + 9216, + 15360, + 6144, + 16384, + 5120, + 10240, + 10240, + 11264, + 11264, + 7168, + 6144, + 8192, + 11264, + 8192, + 14336, + 8192, + 10240, + 13312, + 15360, + 18432, + 4096, + 8192, + 8192, + 15360, + 10240, + 7168, + 12288, + 7168, + 12288, + 12288, + 8192, + 16384, + 9216, + 11264, + 6144, + 8192, + 7168, + 7168, + 12288, + 5120, + 8192 + ], + "mixed": [ + 14336, + 9472, + 8448, + 12032, + 8960, + 11776, + 9984, + 8448, + 9216, + 11264, + 12288, + 11008, + 7936, + 11008, + 9984, + 8448, + 11776, + 9984, + 9984, + 10752, + 8448, + 9984, + 9728, + 10240, + 8704, + 8448, + 8192, + 10496, + 8704, + 11008, + 9984, + 13824, + 8960, + 11264, + 9984, + 11008, + 13824, + 11264, + 9984, + 9216, + 9472, + 11008, + 9472, + 11776, + 12800, + 10240, + 8192, + 8192, + 9728, + 11008, + 8960, + 11264, + 8704, + 10496, + 10240, + 11776, + 7936, + 9216, + 9472, + 10752, + 8448, + 12288, + 9216, + 9728, + 11008, + 9472, + 11008, + 10240, + 8704, + 8448, + 9216, + 9728, + 9728, + 8960, + 10496, + 11520, + 9216, + 8704, + 6400, + 12032, + 11008, + 12288, + 12288, + 7936, + 10752, + 7936, + 12032, + 9216, + 8448, + 9472, + 9472, + 10752, + 10752, + 10752, + 12800, + 10496, + 10496, + 12032, + 8448, + 8960, + 7680, + 9472, + 11008, + 8448 + ] + }, + "scope": "Numerical and sampling controls only. All gradient/update probes are discarded; no trained candidate checkpoint or validation score is produced.", + "test_data_used": false + } + }, + "training_source_snapshot": "training_sources/condition_same1", + "selected_checkpoint_steps": [ + "1024", + "512" + ], + "checkpoint_records": { + "512": { + "step": 512, + "new_training_shots": 524288, + "unique_training_rows_seen_in_this_phase": 451734, + "weights": "weights-512.npz", + "weights_sha256": "4cf3ebae65f19ed882d90aac2157db4127d715f9c688c987280c9aac28efad84", + "validation": "validation-512.json", + "complete": true + }, + "1024": { + "step": 1024, + "new_training_shots": 1048576, + "unique_training_rows_seen_in_this_phase": 803777, + "weights": "weights-1024.npz", + "weights_sha256": "c515815d285cc2eafe52d8ced2df1c754ac578ba54786b98770e15238dc4eaad", + "validation": "validation-1024.json", + "complete": true + } + }, + "selection": "Minimum full-validation mean failure per group among incumbent and listed session-trained checkpoints; when listed, blend candidates average the recorded small-contextual reference and new probabilities equally", + "blend_reference": "/run-state/workspace/research/context_upgrades/continuation2/predictions", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "incumbent": 0.24451622596153846, + "512": 0.24528245192307693, + "1024": 0.24529747596153847, + "blend-512": 0.24562800480769229, + "blend-1024": 0.24574819711538462 + }, + "selected": "incumbent" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "incumbent": 0.2527794471153846, + "512": 0.25326021634615387, + "1024": 0.252734375, + "blend-512": 0.2533954326923077, + "blend-1024": 0.25307992788461536 + }, + "selected": "1024" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "incumbent": 0.23366887019230773, + "512": 0.23359375, + "1024": 0.2334435096153846, + "blend-512": 0.23426983173076926, + "blend-1024": 0.23384915865384612 + }, + "selected": "1024" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "incumbent": 0.23889723557692305, + "512": 0.23933293269230774, + "1024": 0.23951322115384613, + "blend-512": 0.23915264423076918, + "blend-1024": 0.239453125 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "incumbent": 0.2446213942307692, + "512": 0.2444561298076923, + "1024": 0.24489182692307693, + "blend-512": 0.24508713942307692, + "blend-1024": 0.24568810096153845 + }, + "selected": "512" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "incumbent": 0.23652343749999996, + "512": 0.23765024038461538, + "1024": 0.2379206730769231, + "blend-512": 0.23787560096153845, + "blend-1024": 0.23759014423076924 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "incumbent": 0.2356670673076923, + "512": 0.23619290865384618, + "1024": 0.23629807692307692, + "blend-512": 0.23610276442307693, + "blend-1024": 0.23593750000000002 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "incumbent": 0.23294771634615385, + "512": 0.23398437499999997, + "1024": 0.23342848557692308, + "blend-512": 0.2337590144230769, + "blend-1024": 0.2334435096153846 + }, + "selected": "incumbent" + }, + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23228665865384618 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.21953124999999998 + }, + "selected": "incumbent" + } + ] + }, + { + "name": "group_specialize1", + "training_run": { + "experiment": "group-specific d3 continuation", + "groups": { + "d3_bX_center_3_5": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bX_center_3_5", + "parent_model": { + "weights": "weights/contextual-temporal2_swa-mean3.npz", + "training_checkpoint": "temporal2_swa/mean3" + }, + "parent_weights_sha256": "a61fb22f803b795c2a39b6c19dc3a368d536cb21419ba773778601b28e4403fe", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 162496, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_3_5": 11586, + "surface_code_bX_d3_r03_center_3_5": 13164, + "surface_code_bX_d3_r05_center_3_5": 14692, + "surface_code_bX_d3_r07_center_3_5": 12423, + "surface_code_bX_d3_r09_center_3_5": 13507, + "surface_code_bX_d3_r11_center_3_5": 9165, + "surface_code_bX_d3_r13_center_3_5": 14569, + "surface_code_bX_d3_r15_center_3_5": 11563, + "surface_code_bX_d3_r17_center_3_5": 14132, + "surface_code_bX_d3_r19_center_3_5": 9704, + "surface_code_bX_d3_r21_center_3_5": 12014, + "surface_code_bX_d3_r23_center_3_5": 13117, + "surface_code_bX_d3_r25_center_3_5": 12860 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261200, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bX_center_3_5", + "step": 1, + "loss": 0.5817165970802307, + "error": 0.3388671875, + "gradient_norm": 0.07810031622648239, + "elapsed": 23.888731479644775 + }, + { + "group": "d3_bX_center_3_5", + "step": 16, + "loss": 0.43716299533843994, + "error": 0.2177734375, + "gradient_norm": 0.05689458176493645, + "elapsed": 28.204753398895264 + }, + { + "group": "d3_bX_center_3_5", + "step": 32, + "loss": 0.44627559185028076, + "error": 0.208984375, + "gradient_norm": 0.056756604462862015, + "elapsed": 32.84233617782593 + }, + { + "group": "d3_bX_center_3_5", + "step": 48, + "loss": 0.4319554567337036, + "error": 0.234375, + "gradient_norm": 0.05750993266701698, + "elapsed": 37.434494495391846 + }, + { + "group": "d3_bX_center_3_5", + "step": 64, + "loss": 0.2955609858036041, + "error": 0.1279296875, + "gradient_norm": 0.07982950657606125, + "elapsed": 42.03733849525452 + }, + { + "group": "d3_bX_center_3_5", + "step": 80, + "loss": 0.051099054515361786, + "error": 0.01953125, + "gradient_norm": 0.01472504436969757, + "elapsed": 46.64323449134827 + }, + { + "group": "d3_bX_center_3_5", + "step": 96, + "loss": 0.3553770184516907, + "error": 0.1767578125, + "gradient_norm": 0.04556305333971977, + "elapsed": 51.289584159851074 + }, + { + "group": "d3_bX_center_3_5", + "step": 112, + "loss": 0.49853652715682983, + "error": 0.255859375, + "gradient_norm": 0.05837372690439224, + "elapsed": 55.921807527542114 + }, + { + "group": "d3_bX_center_3_5", + "step": 128, + "loss": 0.6128357648849487, + "error": 0.3759765625, + "gradient_norm": 0.04268687590956688, + "elapsed": 60.54293370246887 + }, + { + "group": "d3_bX_center_3_5", + "step": 144, + "loss": 0.40158310532569885, + "error": 0.2109375, + "gradient_norm": 0.06899380683898926, + "elapsed": 66.70903372764587 + }, + { + "group": "d3_bX_center_3_5", + "step": 160, + "loss": 0.6189148426055908, + "error": 0.369140625, + "gradient_norm": 0.049649614840745926, + "elapsed": 71.31301522254944 + }, + { + "group": "d3_bX_center_3_5", + "step": 176, + "loss": 0.5736979246139526, + "error": 0.3271484375, + "gradient_norm": 0.06365907937288284, + "elapsed": 75.90330648422241 + }, + { + "group": "d3_bX_center_3_5", + "step": 192, + "loss": 0.5324695706367493, + "error": 0.294921875, + "gradient_norm": 0.05174271762371063, + "elapsed": 80.51115894317627 + }, + { + "group": "d3_bX_center_3_5", + "step": 208, + "loss": 0.6137855052947998, + "error": 0.3623046875, + "gradient_norm": 0.04891493543982506, + "elapsed": 85.1122133731842 + }, + { + "group": "d3_bX_center_3_5", + "step": 224, + "loss": 0.6262054443359375, + "error": 0.400390625, + "gradient_norm": 0.0478600338101387, + "elapsed": 89.77170705795288 + }, + { + "group": "d3_bX_center_3_5", + "step": 240, + "loss": 0.5114355087280273, + "error": 0.2802734375, + "gradient_norm": 0.06124471500515938, + "elapsed": 94.34836196899414 + }, + { + "group": "d3_bX_center_3_5", + "step": 256, + "loss": 0.3812999129295349, + "error": 0.181640625, + "gradient_norm": 0.050427597016096115, + "elapsed": 98.88006901741028 + } + ] + }, + "d3_bX_center_5_3": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bX_center_5_3", + "parent_model": { + "weights": "weights/contextual-condition_same1-1024.npz", + "training_checkpoint": "condition_same1/1024" + }, + "parent_weights_sha256": "c515815d285cc2eafe52d8ced2df1c754ac578ba54786b98770e15238dc4eaad", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 161233, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_5_3": 11129, + "surface_code_bX_d3_r03_center_5_3": 15369, + "surface_code_bX_d3_r05_center_5_3": 14677, + "surface_code_bX_d3_r07_center_5_3": 9707, + "surface_code_bX_d3_r09_center_5_3": 11152, + "surface_code_bX_d3_r11_center_5_3": 12800, + "surface_code_bX_d3_r13_center_5_3": 13443, + "surface_code_bX_d3_r15_center_5_3": 12388, + "surface_code_bX_d3_r17_center_5_3": 15158, + "surface_code_bX_d3_r19_center_5_3": 10218, + "surface_code_bX_d3_r21_center_5_3": 10711, + "surface_code_bX_d3_r23_center_5_3": 13773, + "surface_code_bX_d3_r25_center_5_3": 10708 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261201, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bX_center_5_3", + "step": 1, + "loss": 0.4805193245410919, + "error": 0.2578125, + "gradient_norm": 0.05444623902440071, + "elapsed": 102.3664813041687 + }, + { + "group": "d3_bX_center_5_3", + "step": 16, + "loss": 0.2784017324447632, + "error": 0.11328125, + "gradient_norm": 0.08824625611305237, + "elapsed": 106.75308656692505 + }, + { + "group": "d3_bX_center_5_3", + "step": 32, + "loss": 0.6410393118858337, + "error": 0.412109375, + "gradient_norm": 0.03859763592481613, + "elapsed": 111.4091112613678 + }, + { + "group": "d3_bX_center_5_3", + "step": 48, + "loss": 0.42605704069137573, + "error": 0.2099609375, + "gradient_norm": 0.050592850893735886, + "elapsed": 116.04315447807312 + }, + { + "group": "d3_bX_center_5_3", + "step": 64, + "loss": 0.5663277506828308, + "error": 0.298828125, + "gradient_norm": 0.055698245763778687, + "elapsed": 120.68257761001587 + }, + { + "group": "d3_bX_center_5_3", + "step": 80, + "loss": 0.6572779417037964, + "error": 0.4267578125, + "gradient_norm": 0.07223570346832275, + "elapsed": 125.41016721725464 + }, + { + "group": "d3_bX_center_5_3", + "step": 96, + "loss": 0.5440086126327515, + "error": 0.2998046875, + "gradient_norm": 0.08954599499702454, + "elapsed": 130.22392392158508 + }, + { + "group": "d3_bX_center_5_3", + "step": 112, + "loss": 0.5094837546348572, + "error": 0.2548828125, + "gradient_norm": 0.06551362574100494, + "elapsed": 134.7945008277893 + }, + { + "group": "d3_bX_center_5_3", + "step": 128, + "loss": 0.5803394317626953, + "error": 0.3193359375, + "gradient_norm": 0.06082230061292648, + "elapsed": 139.35728001594543 + }, + { + "group": "d3_bX_center_5_3", + "step": 144, + "loss": 0.616602897644043, + "error": 0.375, + "gradient_norm": 0.050001099705696106, + "elapsed": 145.55171418190002 + }, + { + "group": "d3_bX_center_5_3", + "step": 160, + "loss": 0.5520708560943604, + "error": 0.2880859375, + "gradient_norm": 0.06085196137428284, + "elapsed": 150.15428566932678 + }, + { + "group": "d3_bX_center_5_3", + "step": 176, + "loss": 0.6117234230041504, + "error": 0.3740234375, + "gradient_norm": 0.0825766772031784, + "elapsed": 154.74532389640808 + }, + { + "group": "d3_bX_center_5_3", + "step": 192, + "loss": 0.5692043304443359, + "error": 0.3203125, + "gradient_norm": 0.07800327241420746, + "elapsed": 159.3635880947113 + }, + { + "group": "d3_bX_center_5_3", + "step": 208, + "loss": 0.30638742446899414, + "error": 0.130859375, + "gradient_norm": 0.049805574119091034, + "elapsed": 163.99608540534973 + }, + { + "group": "d3_bX_center_5_3", + "step": 224, + "loss": 0.5141903758049011, + "error": 0.28515625, + "gradient_norm": 0.06405262649059296, + "elapsed": 168.6415627002716 + }, + { + "group": "d3_bX_center_5_3", + "step": 240, + "loss": 0.5797978639602661, + "error": 0.34765625, + "gradient_norm": 0.10031016170978546, + "elapsed": 173.26013374328613 + }, + { + "group": "d3_bX_center_5_3", + "step": 256, + "loss": 0.2809719741344452, + "error": 0.12890625, + "gradient_norm": 0.04573458060622215, + "elapsed": 177.8879518508911 + } + ] + }, + "d3_bX_center_5_7": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bX_center_5_7", + "parent_model": { + "weights": "weights/contextual-condition_same1-1024.npz", + "training_checkpoint": "condition_same1/1024" + }, + "parent_weights_sha256": "c515815d285cc2eafe52d8ced2df1c754ac578ba54786b98770e15238dc4eaad", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 162612, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_5_7": 13532, + "surface_code_bX_d3_r03_center_5_7": 12060, + "surface_code_bX_d3_r05_center_5_7": 14744, + "surface_code_bX_d3_r07_center_5_7": 11642, + "surface_code_bX_d3_r09_center_5_7": 13167, + "surface_code_bX_d3_r11_center_5_7": 8639, + "surface_code_bX_d3_r13_center_5_7": 14627, + "surface_code_bX_d3_r15_center_5_7": 11178, + "surface_code_bX_d3_r17_center_5_7": 10160, + "surface_code_bX_d3_r19_center_5_7": 13125, + "surface_code_bX_d3_r21_center_5_7": 13464, + "surface_code_bX_d3_r23_center_5_7": 13143, + "surface_code_bX_d3_r25_center_5_7": 13131 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261202, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bX_center_5_7", + "step": 1, + "loss": 0.18060244619846344, + "error": 0.0712890625, + "gradient_norm": 0.035179879516363144, + "elapsed": 181.32161450386047 + }, + { + "group": "d3_bX_center_5_7", + "step": 16, + "loss": 0.5082811117172241, + "error": 0.2705078125, + "gradient_norm": 0.07098715752363205, + "elapsed": 185.63990426063538 + }, + { + "group": "d3_bX_center_5_7", + "step": 32, + "loss": 0.5253040790557861, + "error": 0.2880859375, + "gradient_norm": 0.16328570246696472, + "elapsed": 190.24219703674316 + }, + { + "group": "d3_bX_center_5_7", + "step": 48, + "loss": 0.631301760673523, + "error": 0.3994140625, + "gradient_norm": 0.057355962693691254, + "elapsed": 194.84725713729858 + }, + { + "group": "d3_bX_center_5_7", + "step": 64, + "loss": 0.27920418977737427, + "error": 0.1240234375, + "gradient_norm": 0.06183589994907379, + "elapsed": 199.47137212753296 + }, + { + "group": "d3_bX_center_5_7", + "step": 80, + "loss": 0.611309289932251, + "error": 0.3544921875, + "gradient_norm": 0.07737621665000916, + "elapsed": 204.0849051475525 + }, + { + "group": "d3_bX_center_5_7", + "step": 96, + "loss": 0.2803115248680115, + "error": 0.1279296875, + "gradient_norm": 0.05086443945765495, + "elapsed": 208.7057957649231 + }, + { + "group": "d3_bX_center_5_7", + "step": 112, + "loss": 0.5856442451477051, + "error": 0.330078125, + "gradient_norm": 0.09568645805120468, + "elapsed": 213.3731656074524 + }, + { + "group": "d3_bX_center_5_7", + "step": 128, + "loss": 0.6120781898498535, + "error": 0.3486328125, + "gradient_norm": 0.07464266568422318, + "elapsed": 218.0141613483429 + }, + { + "group": "d3_bX_center_5_7", + "step": 144, + "loss": 0.4921022355556488, + "error": 0.24609375, + "gradient_norm": 0.04171774536371231, + "elapsed": 224.291086435318 + }, + { + "group": "d3_bX_center_5_7", + "step": 160, + "loss": 0.6169480085372925, + "error": 0.375, + "gradient_norm": 0.06097063049674034, + "elapsed": 229.43670320510864 + }, + { + "group": "d3_bX_center_5_7", + "step": 176, + "loss": 0.6014459729194641, + "error": 0.3720703125, + "gradient_norm": 0.049403320997953415, + "elapsed": 235.6041157245636 + }, + { + "group": "d3_bX_center_5_7", + "step": 192, + "loss": 0.5643549561500549, + "error": 0.3076171875, + "gradient_norm": 0.034399617463350296, + "elapsed": 242.02996158599854 + }, + { + "group": "d3_bX_center_5_7", + "step": 208, + "loss": 0.04667453467845917, + "error": 0.0146484375, + "gradient_norm": 0.021298106759786606, + "elapsed": 247.37174129486084 + }, + { + "group": "d3_bX_center_5_7", + "step": 224, + "loss": 0.5067787170410156, + "error": 0.2607421875, + "gradient_norm": 0.056687332689762115, + "elapsed": 251.9976110458374 + }, + { + "group": "d3_bX_center_5_7", + "step": 240, + "loss": 0.42991048097610474, + "error": 0.2255859375, + "gradient_norm": 0.061536215245723724, + "elapsed": 256.75613379478455 + }, + { + "group": "d3_bX_center_5_7", + "step": 256, + "loss": 0.47317343950271606, + "error": 0.2529296875, + "gradient_norm": 0.060076676309108734, + "elapsed": 261.4124813079834 + } + ] + }, + "d3_bX_center_7_5": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bX_center_7_5", + "parent_model": { + "weights": "weights/contextual-temporal2-2048.npz", + "training_checkpoint": "temporal2/2048", + "blend_contextual": true + }, + "parent_weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 162880, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_7_5": 13450, + "surface_code_bX_d3_r03_center_7_5": 11109, + "surface_code_bX_d3_r05_center_7_5": 14012, + "surface_code_bX_d3_r07_center_7_5": 13898, + "surface_code_bX_d3_r09_center_7_5": 12398, + "surface_code_bX_d3_r11_center_7_5": 9664, + "surface_code_bX_d3_r13_center_7_5": 11550, + "surface_code_bX_d3_r15_center_7_5": 12809, + "surface_code_bX_d3_r17_center_7_5": 10673, + "surface_code_bX_d3_r19_center_7_5": 13751, + "surface_code_bX_d3_r21_center_7_5": 13442, + "surface_code_bX_d3_r23_center_7_5": 13774, + "surface_code_bX_d3_r25_center_7_5": 12350 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261203, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bX_center_7_5", + "step": 1, + "loss": 0.6286593675613403, + "error": 0.3916015625, + "gradient_norm": 0.048550695180892944, + "elapsed": 264.77757954597473 + }, + { + "group": "d3_bX_center_7_5", + "step": 16, + "loss": 0.5998052954673767, + "error": 0.3564453125, + "gradient_norm": 0.04667327180504799, + "elapsed": 269.1457931995392 + }, + { + "group": "d3_bX_center_7_5", + "step": 32, + "loss": 0.6372991800308228, + "error": 0.3984375, + "gradient_norm": 0.03931272402405739, + "elapsed": 273.81044721603394 + }, + { + "group": "d3_bX_center_7_5", + "step": 48, + "loss": 0.32325083017349243, + "error": 0.1455078125, + "gradient_norm": 0.053585249930620193, + "elapsed": 278.48719453811646 + }, + { + "group": "d3_bX_center_7_5", + "step": 64, + "loss": 0.6184052228927612, + "error": 0.3974609375, + "gradient_norm": 0.04405878111720085, + "elapsed": 283.16093349456787 + }, + { + "group": "d3_bX_center_7_5", + "step": 80, + "loss": 0.30300217866897583, + "error": 0.1318359375, + "gradient_norm": 0.03475452959537506, + "elapsed": 287.8628993034363 + }, + { + "group": "d3_bX_center_7_5", + "step": 96, + "loss": 0.4532725214958191, + "error": 0.23828125, + "gradient_norm": 0.053579334169626236, + "elapsed": 292.54087567329407 + }, + { + "group": "d3_bX_center_7_5", + "step": 112, + "loss": 0.5722991824150085, + "error": 0.333984375, + "gradient_norm": 0.05200285091996193, + "elapsed": 297.2698106765747 + }, + { + "group": "d3_bX_center_7_5", + "step": 128, + "loss": 0.47720301151275635, + "error": 0.248046875, + "gradient_norm": 0.08435481041669846, + "elapsed": 301.9647386074066 + }, + { + "group": "d3_bX_center_7_5", + "step": 144, + "loss": 0.49832063913345337, + "error": 0.2666015625, + "gradient_norm": 0.06509781628847122, + "elapsed": 308.208101272583 + }, + { + "group": "d3_bX_center_7_5", + "step": 160, + "loss": 0.05153600126504898, + "error": 0.015625, + "gradient_norm": 0.018944455310702324, + "elapsed": 312.88946986198425 + }, + { + "group": "d3_bX_center_7_5", + "step": 176, + "loss": 0.3049379885196686, + "error": 0.1376953125, + "gradient_norm": 0.03572608530521393, + "elapsed": 317.5962097644806 + }, + { + "group": "d3_bX_center_7_5", + "step": 192, + "loss": 0.4833422899246216, + "error": 0.2275390625, + "gradient_norm": 0.11588290333747864, + "elapsed": 322.2771329879761 + }, + { + "group": "d3_bX_center_7_5", + "step": 208, + "loss": 0.5812653303146362, + "error": 0.34765625, + "gradient_norm": 0.04924288019537926, + "elapsed": 326.9544439315796 + }, + { + "group": "d3_bX_center_7_5", + "step": 224, + "loss": 0.5518968105316162, + "error": 0.2919921875, + "gradient_norm": 0.049676258116960526, + "elapsed": 331.7683095932007 + }, + { + "group": "d3_bX_center_7_5", + "step": 240, + "loss": 0.599678099155426, + "error": 0.353515625, + "gradient_norm": 0.09019427001476288, + "elapsed": 337.0053963661194 + }, + { + "group": "d3_bX_center_7_5", + "step": 256, + "loss": 0.6168051362037659, + "error": 0.373046875, + "gradient_norm": 0.045873139053583145, + "elapsed": 342.27088832855225 + } + ] + }, + "d3_bZ_center_3_5": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bZ_center_3_5", + "parent_model": { + "weights": "weights/contextual-condition_same1-512.npz", + "training_checkpoint": "condition_same1/512" + }, + "parent_weights_sha256": "4cf3ebae65f19ed882d90aac2157db4127d715f9c688c987280c9aac28efad84", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 162257, + "unique_rows_by_condition": { + "surface_code_bZ_d3_r01_center_3_5": 13149, + "surface_code_bZ_d3_r03_center_3_5": 12112, + "surface_code_bZ_d3_r05_center_3_5": 12434, + "surface_code_bZ_d3_r07_center_3_5": 13778, + "surface_code_bZ_d3_r09_center_3_5": 12830, + "surface_code_bZ_d3_r11_center_3_5": 6034, + "surface_code_bZ_d3_r13_center_3_5": 13524, + "surface_code_bZ_d3_r15_center_3_5": 13160, + "surface_code_bZ_d3_r17_center_3_5": 12823, + "surface_code_bZ_d3_r19_center_3_5": 11129, + "surface_code_bZ_d3_r21_center_3_5": 13793, + "surface_code_bZ_d3_r23_center_3_5": 14080, + "surface_code_bZ_d3_r25_center_3_5": 13411 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261204, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bZ_center_3_5", + "step": 1, + "loss": 0.36515435576438904, + "error": 0.17578125, + "gradient_norm": 0.068653903901577, + "elapsed": 346.68829584121704 + }, + { + "group": "d3_bZ_center_3_5", + "step": 16, + "loss": 0.2806941568851471, + "error": 0.1318359375, + "gradient_norm": 0.06498919427394867, + "elapsed": 352.6486053466797 + }, + { + "group": "d3_bZ_center_3_5", + "step": 32, + "loss": 0.5172728300094604, + "error": 0.2578125, + "gradient_norm": 0.06919123977422714, + "elapsed": 358.0916488170624 + }, + { + "group": "d3_bZ_center_3_5", + "step": 48, + "loss": 0.5654157400131226, + "error": 0.3134765625, + "gradient_norm": 0.062110695987939835, + "elapsed": 364.1197271347046 + }, + { + "group": "d3_bZ_center_3_5", + "step": 64, + "loss": 0.5950935482978821, + "error": 0.349609375, + "gradient_norm": 0.06901932507753372, + "elapsed": 370.44589829444885 + }, + { + "group": "d3_bZ_center_3_5", + "step": 80, + "loss": 0.3655591607093811, + "error": 0.1865234375, + "gradient_norm": 0.06035780534148216, + "elapsed": 376.3442976474762 + }, + { + "group": "d3_bZ_center_3_5", + "step": 96, + "loss": 0.5849340558052063, + "error": 0.345703125, + "gradient_norm": 0.0669141560792923, + "elapsed": 381.8527054786682 + }, + { + "group": "d3_bZ_center_3_5", + "step": 112, + "loss": 0.04215944558382034, + "error": 0.013671875, + "gradient_norm": 0.029389331117272377, + "elapsed": 386.54820346832275 + }, + { + "group": "d3_bZ_center_3_5", + "step": 128, + "loss": 0.619553804397583, + "error": 0.3876953125, + "gradient_norm": 0.053926873952150345, + "elapsed": 391.31534695625305 + }, + { + "group": "d3_bZ_center_3_5", + "step": 144, + "loss": 0.3793254494667053, + "error": 0.1923828125, + "gradient_norm": 0.07844529300928116, + "elapsed": 397.51641821861267 + }, + { + "group": "d3_bZ_center_3_5", + "step": 160, + "loss": 0.3429756164550781, + "error": 0.1572265625, + "gradient_norm": 0.06213530898094177, + "elapsed": 402.1174716949463 + }, + { + "group": "d3_bZ_center_3_5", + "step": 176, + "loss": 0.2883482277393341, + "error": 0.1416015625, + "gradient_norm": 0.07786665111780167, + "elapsed": 406.72908902168274 + }, + { + "group": "d3_bZ_center_3_5", + "step": 192, + "loss": 0.03280383348464966, + "error": 0.0087890625, + "gradient_norm": 0.035463444888591766, + "elapsed": 411.33272552490234 + }, + { + "group": "d3_bZ_center_3_5", + "step": 208, + "loss": 0.6251656413078308, + "error": 0.38671875, + "gradient_norm": 0.08498021215200424, + "elapsed": 415.93534207344055 + }, + { + "group": "d3_bZ_center_3_5", + "step": 224, + "loss": 0.43049943447113037, + "error": 0.232421875, + "gradient_norm": 0.08405832201242447, + "elapsed": 420.54495644569397 + }, + { + "group": "d3_bZ_center_3_5", + "step": 240, + "loss": 0.5978946089744568, + "error": 0.3349609375, + "gradient_norm": 0.06633604317903519, + "elapsed": 425.1712546348572 + }, + { + "group": "d3_bZ_center_3_5", + "step": 256, + "loss": 0.5690029859542847, + "error": 0.341796875, + "gradient_norm": 0.06171220913529396, + "elapsed": 430.0519812107086 + } + ] + }, + "d3_bZ_center_5_3": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bZ_center_5_3", + "parent_model": { + "weights": "weights/contextual-temporal2-2048.npz", + "training_checkpoint": "temporal2/2048" + }, + "parent_weights_sha256": "ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 162569, + "unique_rows_by_condition": { + "surface_code_bZ_d3_r01_center_5_3": 11619, + "surface_code_bZ_d3_r03_center_5_3": 13126, + "surface_code_bZ_d3_r05_center_5_3": 12742, + "surface_code_bZ_d3_r07_center_5_3": 9136, + "surface_code_bZ_d3_r09_center_5_3": 15337, + "surface_code_bZ_d3_r11_center_5_3": 11996, + "surface_code_bZ_d3_r13_center_5_3": 12732, + "surface_code_bZ_d3_r15_center_5_3": 13128, + "surface_code_bZ_d3_r17_center_5_3": 14689, + "surface_code_bZ_d3_r19_center_5_3": 11983, + "surface_code_bZ_d3_r21_center_5_3": 11992, + "surface_code_bZ_d3_r23_center_5_3": 11625, + "surface_code_bZ_d3_r25_center_5_3": 12464 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261205, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bZ_center_5_3", + "step": 1, + "loss": 0.6346971988677979, + "error": 0.3818359375, + "gradient_norm": 0.046160198748111725, + "elapsed": 433.7457048892975 + }, + { + "group": "d3_bZ_center_5_3", + "step": 16, + "loss": 0.46678581833839417, + "error": 0.23828125, + "gradient_norm": 0.04110230877995491, + "elapsed": 438.16989040374756 + }, + { + "group": "d3_bZ_center_5_3", + "step": 32, + "loss": 0.17910712957382202, + "error": 0.064453125, + "gradient_norm": 0.030056120827794075, + "elapsed": 442.8582558631897 + }, + { + "group": "d3_bZ_center_5_3", + "step": 48, + "loss": 0.5041052103042603, + "error": 0.27734375, + "gradient_norm": 0.045486729592084885, + "elapsed": 447.66860795021057 + }, + { + "group": "d3_bZ_center_5_3", + "step": 64, + "loss": 0.5663014054298401, + "error": 0.310546875, + "gradient_norm": 0.04649529233574867, + "elapsed": 452.51550030708313 + }, + { + "group": "d3_bZ_center_5_3", + "step": 80, + "loss": 0.5388609766960144, + "error": 0.2841796875, + "gradient_norm": 0.05346957594156265, + "elapsed": 457.18010997772217 + }, + { + "group": "d3_bZ_center_5_3", + "step": 96, + "loss": 0.6176578998565674, + "error": 0.375, + "gradient_norm": 0.08028864115476608, + "elapsed": 461.89074301719666 + }, + { + "group": "d3_bZ_center_5_3", + "step": 112, + "loss": 0.6225342750549316, + "error": 0.36328125, + "gradient_norm": 0.030471889302134514, + "elapsed": 466.5776717662811 + }, + { + "group": "d3_bZ_center_5_3", + "step": 128, + "loss": 0.2725566625595093, + "error": 0.111328125, + "gradient_norm": 0.05236189067363739, + "elapsed": 471.32313442230225 + }, + { + "group": "d3_bZ_center_5_3", + "step": 144, + "loss": 0.6361372470855713, + "error": 0.3984375, + "gradient_norm": 0.07191100716590881, + "elapsed": 478.3580629825592 + }, + { + "group": "d3_bZ_center_5_3", + "step": 160, + "loss": 0.2549514174461365, + "error": 0.1025390625, + "gradient_norm": 0.0485384576022625, + "elapsed": 484.5399954319 + }, + { + "group": "d3_bZ_center_5_3", + "step": 176, + "loss": 0.06202135607600212, + "error": 0.0205078125, + "gradient_norm": 0.01821581833064556, + "elapsed": 490.2966978549957 + }, + { + "group": "d3_bZ_center_5_3", + "step": 192, + "loss": 0.5546645522117615, + "error": 0.296875, + "gradient_norm": 0.07931670546531677, + "elapsed": 496.1227023601532 + }, + { + "group": "d3_bZ_center_5_3", + "step": 208, + "loss": 0.2724062502384186, + "error": 0.1220703125, + "gradient_norm": 0.0482773631811142, + "elapsed": 501.8398952484131 + }, + { + "group": "d3_bZ_center_5_3", + "step": 224, + "loss": 0.6230898499488831, + "error": 0.3671875, + "gradient_norm": 0.05214303359389305, + "elapsed": 508.2803044319153 + }, + { + "group": "d3_bZ_center_5_3", + "step": 240, + "loss": 0.4187527894973755, + "error": 0.2080078125, + "gradient_norm": 0.046042900532484055, + "elapsed": 513.7485942840576 + }, + { + "group": "d3_bZ_center_5_3", + "step": 256, + "loss": 0.5760256052017212, + "error": 0.3271484375, + "gradient_norm": 0.03505929186940193, + "elapsed": 519.0282807350159 + } + ] + }, + "d3_bZ_center_5_7": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bZ_center_5_7", + "parent_model": { + "weights": "weights/contextual-temporal2-4096.npz", + "training_checkpoint": "temporal2/4096" + }, + "parent_weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 163281, + "unique_rows_by_condition": { + "surface_code_bZ_d3_r01_center_5_7": 11175, + "surface_code_bZ_d3_r03_center_5_7": 13171, + "surface_code_bZ_d3_r05_center_5_7": 12697, + "surface_code_bZ_d3_r07_center_5_7": 11648, + "surface_code_bZ_d3_r09_center_5_7": 14077, + "surface_code_bZ_d3_r11_center_5_7": 13454, + "surface_code_bZ_d3_r13_center_5_7": 11564, + "surface_code_bZ_d3_r15_center_5_7": 12728, + "surface_code_bZ_d3_r17_center_5_7": 12048, + "surface_code_bZ_d3_r19_center_5_7": 14459, + "surface_code_bZ_d3_r21_center_5_7": 14010, + "surface_code_bZ_d3_r23_center_5_7": 10239, + "surface_code_bZ_d3_r25_center_5_7": 12011 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261206, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bZ_center_5_7", + "step": 1, + "loss": 0.5979939103126526, + "error": 0.357421875, + "gradient_norm": 0.0660991370677948, + "elapsed": 523.6322765350342 + }, + { + "group": "d3_bZ_center_5_7", + "step": 16, + "loss": 0.6150602102279663, + "error": 0.3701171875, + "gradient_norm": 0.04266919568181038, + "elapsed": 528.4157238006592 + }, + { + "group": "d3_bZ_center_5_7", + "step": 32, + "loss": 0.44577696919441223, + "error": 0.2099609375, + "gradient_norm": 0.06689892709255219, + "elapsed": 533.0822012424469 + }, + { + "group": "d3_bZ_center_5_7", + "step": 48, + "loss": 0.4075019657611847, + "error": 0.1884765625, + "gradient_norm": 0.05801992863416672, + "elapsed": 537.763840675354 + }, + { + "group": "d3_bZ_center_5_7", + "step": 64, + "loss": 0.5356203317642212, + "error": 0.2939453125, + "gradient_norm": 0.0543823316693306, + "elapsed": 542.4880893230438 + }, + { + "group": "d3_bZ_center_5_7", + "step": 80, + "loss": 0.45208629965782166, + "error": 0.2275390625, + "gradient_norm": 0.05819695070385933, + "elapsed": 547.1561362743378 + }, + { + "group": "d3_bZ_center_5_7", + "step": 96, + "loss": 0.4151451587677002, + "error": 0.2119140625, + "gradient_norm": 0.07201892882585526, + "elapsed": 551.8683395385742 + }, + { + "group": "d3_bZ_center_5_7", + "step": 112, + "loss": 0.5576318502426147, + "error": 0.31640625, + "gradient_norm": 0.04457806423306465, + "elapsed": 556.642165184021 + }, + { + "group": "d3_bZ_center_5_7", + "step": 128, + "loss": 0.20078304409980774, + "error": 0.08984375, + "gradient_norm": 0.040219370275735855, + "elapsed": 561.4243121147156 + }, + { + "group": "d3_bZ_center_5_7", + "step": 144, + "loss": 0.45917582511901855, + "error": 0.2236328125, + "gradient_norm": 0.0707971602678299, + "elapsed": 567.7284438610077 + }, + { + "group": "d3_bZ_center_5_7", + "step": 160, + "loss": 0.5936293601989746, + "error": 0.345703125, + "gradient_norm": 0.12180078029632568, + "elapsed": 572.3563349246979 + }, + { + "group": "d3_bZ_center_5_7", + "step": 176, + "loss": 0.24654456973075867, + "error": 0.1044921875, + "gradient_norm": 0.04859209433197975, + "elapsed": 577.008533000946 + }, + { + "group": "d3_bZ_center_5_7", + "step": 192, + "loss": 0.4809238612651825, + "error": 0.2509765625, + "gradient_norm": 0.09741280972957611, + "elapsed": 581.7403192520142 + }, + { + "group": "d3_bZ_center_5_7", + "step": 208, + "loss": 0.36378931999206543, + "error": 0.166015625, + "gradient_norm": 0.04881134256720543, + "elapsed": 586.367921590805 + }, + { + "group": "d3_bZ_center_5_7", + "step": 224, + "loss": 0.5131937265396118, + "error": 0.279296875, + "gradient_norm": 0.08562120050191879, + "elapsed": 591.1944098472595 + }, + { + "group": "d3_bZ_center_5_7", + "step": 240, + "loss": 0.4193183183670044, + "error": 0.2099609375, + "gradient_norm": 0.0680096298456192, + "elapsed": 595.8478200435638 + }, + { + "group": "d3_bZ_center_5_7", + "step": 256, + "loss": 0.467867910861969, + "error": 0.24609375, + "gradient_norm": 0.07342159003019333, + "elapsed": 600.4172458648682 + } + ] + }, + "d3_bZ_center_7_5": { + "initialization": "Continue the temporal component of the selected session-trained group decoder; no new random parameters", + "original_initialization": "Base rich network seed20261030 and temporal encoder seed20261104; all fitting occurred in this session", + "group": "d3_bZ_center_7_5", + "parent_model": { + "weights": "weights/contextual-temporal2-4096.npz", + "training_checkpoint": "temporal2/4096" + }, + "parent_weights_sha256": "5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "training": "Uniform sampling over all13 odd round counts for this geometry/basis group, supplied training labels only", + "eligible_training_shots": 258440, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 159856, + "unique_rows_by_condition": { + "surface_code_bZ_d3_r01_center_7_5": 10637, + "surface_code_bZ_d3_r03_center_7_5": 13460, + "surface_code_bZ_d3_r05_center_7_5": 12002, + "surface_code_bZ_d3_r07_center_7_5": 8000, + "surface_code_bZ_d3_r09_center_7_5": 10743, + "surface_code_bZ_d3_r11_center_7_5": 16789, + "surface_code_bZ_d3_r13_center_7_5": 12364, + "surface_code_bZ_d3_r15_center_7_5": 15213, + "surface_code_bZ_d3_r17_center_7_5": 14167, + "surface_code_bZ_d3_r19_center_7_5": 11099, + "surface_code_bZ_d3_r21_center_7_5": 13178, + "surface_code_bZ_d3_r23_center_7_5": 12014, + "surface_code_bZ_d3_r25_center_7_5": 10190 + }, + "steps": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global norm clip1", + "optimizer_restored": false, + "rng_restored": false, + "sampling_seed": 20261207, + "validation": "Fixed random screen per condition using seed20261028; full validation is used by the separate selector", + "validation_shots_requested_per_condition": 1024, + "loss": "Uniform binary conditional logical likelihood through exact frontier contraction", + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "test_data_used": false, + "log": [ + { + "group": "d3_bZ_center_7_5", + "step": 1, + "loss": 0.4038092792034149, + "error": 0.197265625, + "gradient_norm": 0.05896063148975372, + "elapsed": 603.840416431427 + }, + { + "group": "d3_bZ_center_7_5", + "step": 16, + "loss": 0.6033527851104736, + "error": 0.3515625, + "gradient_norm": 0.05784430727362633, + "elapsed": 608.1250426769257 + }, + { + "group": "d3_bZ_center_7_5", + "step": 32, + "loss": 0.5283372402191162, + "error": 0.283203125, + "gradient_norm": 0.050800539553165436, + "elapsed": 612.7134759426117 + }, + { + "group": "d3_bZ_center_7_5", + "step": 48, + "loss": 0.5995811820030212, + "error": 0.3291015625, + "gradient_norm": 0.05547967553138733, + "elapsed": 617.2784404754639 + }, + { + "group": "d3_bZ_center_7_5", + "step": 64, + "loss": 0.40154707431793213, + "error": 0.205078125, + "gradient_norm": 0.06852669268846512, + "elapsed": 621.8420352935791 + }, + { + "group": "d3_bZ_center_7_5", + "step": 80, + "loss": 0.4995174705982208, + "error": 0.2763671875, + "gradient_norm": 0.061341386288404465, + "elapsed": 626.40260887146 + }, + { + "group": "d3_bZ_center_7_5", + "step": 96, + "loss": 0.5751184225082397, + "error": 0.3251953125, + "gradient_norm": 0.07929262518882751, + "elapsed": 630.9725329875946 + }, + { + "group": "d3_bZ_center_7_5", + "step": 112, + "loss": 0.624832808971405, + "error": 0.369140625, + "gradient_norm": 0.045014865696430206, + "elapsed": 635.5494453907013 + }, + { + "group": "d3_bZ_center_7_5", + "step": 128, + "loss": 0.4616764783859253, + "error": 0.224609375, + "gradient_norm": 0.0743650421500206, + "elapsed": 640.093489408493 + }, + { + "group": "d3_bZ_center_7_5", + "step": 144, + "loss": 0.5214440822601318, + "error": 0.2724609375, + "gradient_norm": 0.05418862774968147, + "elapsed": 646.2130215167999 + }, + { + "group": "d3_bZ_center_7_5", + "step": 160, + "loss": 0.27278852462768555, + "error": 0.12109375, + "gradient_norm": 0.059856753796339035, + "elapsed": 650.7696936130524 + }, + { + "group": "d3_bZ_center_7_5", + "step": 176, + "loss": 0.5251824259757996, + "error": 0.2734375, + "gradient_norm": 0.0982872024178505, + "elapsed": 655.3179745674133 + }, + { + "group": "d3_bZ_center_7_5", + "step": 192, + "loss": 0.510776937007904, + "error": 0.2744140625, + "gradient_norm": 0.0638406053185463, + "elapsed": 659.8532302379608 + }, + { + "group": "d3_bZ_center_7_5", + "step": 208, + "loss": 0.4173796772956848, + "error": 0.20703125, + "gradient_norm": 0.0652337446808815, + "elapsed": 664.3970146179199 + }, + { + "group": "d3_bZ_center_7_5", + "step": 224, + "loss": 0.42136240005493164, + "error": 0.203125, + "gradient_norm": 0.04171523451805115, + "elapsed": 668.9384174346924 + }, + { + "group": "d3_bZ_center_7_5", + "step": 240, + "loss": 0.2494639754295349, + "error": 0.1201171875, + "gradient_norm": 0.06969694793224335, + "elapsed": 673.4954979419708 + }, + { + "group": "d3_bZ_center_7_5", + "step": 256, + "loss": 0.26821407675743103, + "error": 0.1181640625, + "gradient_norm": 0.04254033416509628, + "elapsed": 678.0544662475586 + } + ] + } + }, + "initialization": "Continue session-trained selected temporal components; no new random parameters", + "training": "Each group samples uniformly over its own13 durations; supplied training labels only", + "eligible_training_shots": 2067520, + "steps": 2048, + "steps_per_group": 256, + "batch_size": 1024, + "learning_rate": 0.0001, + "optimizer_restored": false, + "rng_restored": false, + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "run_config": { + "package": "/run-state/workspace/research/context_upgrades/short_categorical3/package", + "output": "/run-state/workspace/research/learned_exact/group_specialize1", + "steps": 256, + "eval_every": 128, + "batch": 1024, + "validation_shots": 1024, + "validation_batch": 1024, + "learning_rate": 0.0001, + "seed": 20261200, + "groups": [ + "d3_bX_center_3_5", + "d3_bX_center_5_3", + "d3_bX_center_5_7", + "d3_bX_center_7_5", + "d3_bZ_center_3_5", + "d3_bZ_center_5_3", + "d3_bZ_center_5_7", + "d3_bZ_center_7_5" + ], + "training_source_sha256": { + "learned_exact__specialize_train.py": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "learned_exact__temporal_model.py": "76fd01d5ae50f7d0b5790800898e7103ddb86db8f6a2ace883407515add2e186", + "learned_exact__data.py": "6f88582230aec7bbf35170a672ff615cac0cf18c0a690b2983874bb4c02c75e6", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "parent_config_sha256": "50123b5d6a4515814bb74a93963e83d17c2d3eb47af4d12b7757f523ac7c2f6a", + "parent_provenance_sha256": "7c76c4ba7b6bb90ddb1ac3fa9cd5d27788fdad2bf6bc6f95e8187824c971bdfb", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "validation_manifest_sha256": "482bb7268c6c827ebbf1f756ee6994750acfcd011adab08eaa2ada703e5faea1" + }, + "parent_record": "training_sources/group_specialize1/parent_training_provenance.json", + "new_random_parameters": 0, + "training_draws": 2097152, + "test_data_used": false, + "declared_plan": { + "hypothesis": "Group-specific fine-tuning may reduce conflicting updates across d3 geometries and bases", + "parents": "The temporal component selected for each of the8 groups in CURRENT after fresh2_continuation_finished.json", + "new_random_parameters": 0, + "sampling_seeds": "20261200 plus lexicographic group rank0..7", + "training": "256 updates per group,B1024,LR.0001; uniform sampling of all13 durations and all258440 training rows per group", + "optimizer": "Fresh AdamW moments for every group, weight decay1e-4, global gradient norm clip1", + "total_optimizer_updates": 2048, + "total_training_draws": 2097152, + "validation": "Screen at0/128/256. Full validation at0/128/256; step0 is a diagnostic, excluded from new checkpoint selection", + "selection": "Per-group mean failure over all13 durations: incumbent, raw128/256, or equal small-contextual blend128/256; retain incumbent on ties", + "short_model_followup": "Recheck the previously training-fitted categorical1 heads after group replacement", + "test_data_used": false + }, + "pipeline_control": { + "status": "passed", + "backend": "CPU", + "selection_eligible": false, + "submission_eligible": false, + "trainer_sha256": "5a2e7ba25969f4599cb65d60cbd53544fd77d7a6926ec0d03662b72b151acf95", + "run": "/run-state/workspace/research/learned_exact/specialize_smoke2", + "checks": [ + { + "group": "d3_bX_center_3_5", + "parent_exact": true, + "fresh_zero_optimizer": true, + "one_update_changes_parameters": true, + "sampling_replay_exact": true, + "all13_durations_evaluated": true + }, + { + "group": "d3_bZ_center_7_5", + "parent_exact": true, + "fresh_zero_optimizer": true, + "one_update_changes_parameters": true, + "sampling_replay_exact": true, + "all13_durations_evaluated": true + } + ], + "test_data_used": false + } + }, + "training_source_snapshot": "training_sources/group_specialize1", + "selected_checkpoints": { + "d3_bX_center_3_5": 128, + "d3_bX_center_5_7": 256, + "d3_bX_center_7_5": 128, + "d3_bZ_center_7_5": 128 + }, + "checkpoint_records": { + "d3_bX_center_3_5": { + "group": "d3_bX_center_3_5", + "step": 128, + "training_draws": 131072, + "unique_training_rows_seen_in_this_phase": 101608, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_3_5": 7393, + "surface_code_bX_d3_r03_center_3_5": 9191, + "surface_code_bX_d3_r05_center_3_5": 9634, + "surface_code_bX_d3_r07_center_3_5": 9218, + "surface_code_bX_d3_r09_center_3_5": 6691, + "surface_code_bX_d3_r11_center_3_5": 6028, + "surface_code_bX_d3_r13_center_3_5": 9122, + "surface_code_bX_d3_r15_center_3_5": 5301, + "surface_code_bX_d3_r17_center_3_5": 8630, + "surface_code_bX_d3_r19_center_3_5": 5276, + "surface_code_bX_d3_r21_center_3_5": 8553, + "surface_code_bX_d3_r23_center_3_5": 7977, + "surface_code_bX_d3_r25_center_3_5": 8594 + }, + "weights": "weights-128.npz", + "weights_sha256": "90c6cb7fd3be8d363318f45257de6670ba19d9336d096dc3efb309bac88b2bf9", + "complete": true + }, + "d3_bX_center_5_7": { + "group": "d3_bX_center_5_7", + "step": 256, + "training_draws": 262144, + "unique_training_rows_seen_in_this_phase": 162612, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_5_7": 13532, + "surface_code_bX_d3_r03_center_5_7": 12060, + "surface_code_bX_d3_r05_center_5_7": 14744, + "surface_code_bX_d3_r07_center_5_7": 11642, + "surface_code_bX_d3_r09_center_5_7": 13167, + "surface_code_bX_d3_r11_center_5_7": 8639, + "surface_code_bX_d3_r13_center_5_7": 14627, + "surface_code_bX_d3_r15_center_5_7": 11178, + "surface_code_bX_d3_r17_center_5_7": 10160, + "surface_code_bX_d3_r19_center_5_7": 13125, + "surface_code_bX_d3_r21_center_5_7": 13464, + "surface_code_bX_d3_r23_center_5_7": 13143, + "surface_code_bX_d3_r25_center_5_7": 13131 + }, + "weights": "weights-256.npz", + "weights_sha256": "7dc5b5ed51423bae023bb2c15de420850fef4fedb82760a7bcd993393301e038", + "complete": true + }, + "d3_bX_center_7_5": { + "group": "d3_bX_center_7_5", + "step": 128, + "training_draws": 131072, + "unique_training_rows_seen_in_this_phase": 101875, + "unique_rows_by_condition": { + "surface_code_bX_d3_r01_center_7_5": 7327, + "surface_code_bX_d3_r03_center_7_5": 6711, + "surface_code_bX_d3_r05_center_7_5": 9068, + "surface_code_bX_d3_r07_center_7_5": 9212, + "surface_code_bX_d3_r09_center_7_5": 6001, + "surface_code_bX_d3_r11_center_7_5": 7353, + "surface_code_bX_d3_r13_center_7_5": 7373, + "surface_code_bX_d3_r15_center_7_5": 8580, + "surface_code_bX_d3_r17_center_7_5": 6713, + "surface_code_bX_d3_r19_center_7_5": 9686, + "surface_code_bX_d3_r21_center_7_5": 8553, + "surface_code_bX_d3_r23_center_7_5": 7325, + "surface_code_bX_d3_r25_center_7_5": 7973 + }, + "weights": "weights-128.npz", + "weights_sha256": "1dc16b14813ebfd874acf9c907870144bc6ac98c8de8b4e8c47e41cdcfb3f1c3", + "complete": true + }, + "d3_bZ_center_7_5": { + "group": "d3_bZ_center_7_5", + "step": 128, + "training_draws": 131072, + "unique_training_rows_seen_in_this_phase": 101460, + "unique_rows_by_condition": { + "surface_code_bZ_d3_r01_center_7_5": 7386, + "surface_code_bZ_d3_r03_center_7_5": 7382, + "surface_code_bZ_d3_r05_center_7_5": 7375, + "surface_code_bZ_d3_r07_center_7_5": 4523, + "surface_code_bZ_d3_r09_center_7_5": 6016, + "surface_code_bZ_d3_r11_center_7_5": 10680, + "surface_code_bZ_d3_r13_center_7_5": 9644, + "surface_code_bZ_d3_r15_center_7_5": 7341, + "surface_code_bZ_d3_r17_center_7_5": 9210, + "surface_code_bZ_d3_r19_center_7_5": 8536, + "surface_code_bZ_d3_r21_center_7_5": 7410, + "surface_code_bZ_d3_r23_center_7_5": 8625, + "surface_code_bZ_d3_r25_center_7_5": 7332 + }, + "weights": "weights-128.npz", + "weights_sha256": "8f78092b6539927132aebd28deb0e0d1b72f43596b79e074e3206f4a784dd000", + "complete": true + } + }, + "selection": "Minimum full-validation mean failure across all13 durations per group among incumbent, specialized128/256 and equal small-contextual blends; retain incumbent on ties", + "blend_reference": "/run-state/workspace/research/context_upgrades/continuation2/predictions", + "history": [ + { + "group": "d3_bX_center_3_5", + "candidates": { + "incumbent": 0.24451622596153846, + "128": 0.2444110576923077, + "blend-128": 0.24523737980769234, + "256": 0.24468149038461534, + "blend-256": 0.24532752403846156 + }, + "selected": "128" + }, + { + "group": "d3_bX_center_5_3", + "candidates": { + "incumbent": 0.2526592548076923, + "128": 0.2528094951923077, + "blend-128": 0.25312499999999993, + "256": 0.2532001201923077, + "blend-256": 0.25318509615384616 + }, + "selected": "incumbent" + }, + { + "group": "d3_bX_center_5_7", + "candidates": { + "incumbent": 0.2333984375, + "128": 0.23329326923076926, + "blend-128": 0.23414963942307693, + "256": 0.233203125, + "blend-256": 0.2338641826923077 + }, + "selected": "256" + }, + { + "group": "d3_bX_center_7_5", + "candidates": { + "incumbent": 0.23889723557692305, + "128": 0.23933293269230768, + "blend-128": 0.23880709134615385, + "256": 0.23907752403846153, + "blend-256": 0.23888221153846154 + }, + "selected": "blend-128" + }, + { + "group": "d3_bZ_center_3_5", + "candidates": { + "incumbent": 0.24447115384615387, + "128": 0.24456129807692306, + "blend-128": 0.24534254807692307, + "256": 0.24462139423076923, + "blend-256": 0.24505709134615386 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_5_3", + "candidates": { + "incumbent": 0.23652343749999996, + "128": 0.2371394230769231, + "blend-128": 0.23753004807692307, + "256": 0.2373347355769231, + "blend-256": 0.23728966346153849 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_5_7", + "candidates": { + "incumbent": 0.2356670673076923, + "128": 0.23635817307692306, + "blend-128": 0.23662860576923073, + "256": 0.23571213942307687, + "blend-256": 0.23638822115384614 + }, + "selected": "incumbent" + }, + { + "group": "d3_bZ_center_7_5", + "candidates": { + "incumbent": 0.23294771634615385, + "128": 0.23282752403846158, + "blend-128": 0.2331280048076923, + "256": 0.23348858173076922, + "blend-256": 0.23336838942307692 + }, + "selected": "128" + }, + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23228665865384618 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.21953124999999998 + }, + "selected": "incumbent" + } + ] + } + ], + "turbo_d5_experiment": { + "method": "Three passes of extrinsic log-odds feedback between complementary exact CSS syndrome-likelihood contractions, damping 1, messages clipped to [-8,8]. Induced dependencies are approximated.", + "initialization": "Logistic coefficients randomly initialized Normal(0,.01), seed 20261103; all underlying states built in this session from permitted even-fitted DEMs.", + "training": "4096 uniformly sampled training rows per all 26 d5 conditions (sample seed 20261023); BCE plus 1e-5 L2, L-BFGS-B up to 300 iterations.", + "screen": { + "scope": "Diagnostic screen only: both d5 bases, rounds 5/13/25, 1024 uniform validation samples per condition", + "sample_seed": 20261031, + "results": [ + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "rounds": 5, + "basis": "X", + "shots": 1024, + "batch": 192, + "damping": 0.5, + "seconds": 5.466358661651611, + "elapsed": 7.00129771232605, + "first_pass_max_delta": 8.940696716308594e-07, + "failure": [ + 0.1025390625, + 0.1044921875, + 0.1025390625 + ], + "peak_gpu_bytes": 4742925056 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "rounds": 5, + "basis": "X", + "shots": 1024, + "batch": 192, + "damping": 1.0, + "seconds": 1.1764235496520996, + "elapsed": 8.178237438201904, + "first_pass_max_delta": 8.940696716308594e-07, + "failure": [ + 0.1025390625, + 0.0966796875, + 0.1005859375 + ], + "peak_gpu_bytes": 4742925056 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "rounds": 13, + "basis": "X", + "shots": 1024, + "batch": 192, + "damping": 0.5, + "seconds": 7.137438058853149, + "elapsed": 16.021901607513428, + "first_pass_max_delta": 1.1324882507324219e-06, + "failure": [ + 0.2548828125, + 0.2490234375, + 0.25 + ], + "peak_gpu_bytes": 11611887104 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "rounds": 13, + "basis": "X", + "shots": 1024, + "batch": 192, + "damping": 1.0, + "seconds": 3.088695526123047, + "elapsed": 19.11112403869629, + "first_pass_max_delta": 1.1324882507324219e-06, + "failure": [ + 0.2548828125, + 0.2490234375, + 0.2412109375 + ], + "peak_gpu_bytes": 11611887104 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "rounds": 25, + "basis": "X", + "shots": 1024, + "batch": 192, + "damping": 0.5, + "seconds": 10.504217624664307, + "elapsed": 30.677946090698242, + "first_pass_max_delta": 1.5497207641601562e-06, + "failure": [ + 0.3916015625, + 0.38671875, + 0.3896484375 + ], + "peak_gpu_bytes": 21913887488 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "rounds": 25, + "basis": "X", + "shots": 1024, + "batch": 192, + "damping": 1.0, + "seconds": 5.937381267547607, + "elapsed": 36.615668296813965, + "first_pass_max_delta": 1.5497207641601562e-06, + "failure": [ + 0.3916015625, + 0.3857421875, + 0.3896484375 + ], + "peak_gpu_bytes": 21913887488 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "rounds": 5, + "basis": "Z", + "shots": 1024, + "batch": 192, + "damping": 0.5, + "seconds": 4.611798286437988, + "elapsed": 41.71111083030701, + "first_pass_max_delta": 2.0265579223632812e-06, + "failure": [ + 0.1005859375, + 0.1015625, + 0.09765625 + ], + "peak_gpu_bytes": 21913887488 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "rounds": 5, + "basis": "Z", + "shots": 1024, + "batch": 192, + "damping": 1.0, + "seconds": 1.1570250988006592, + "elapsed": 42.86858010292053, + "first_pass_max_delta": 2.0265579223632812e-06, + "failure": [ + 0.1005859375, + 0.0986328125, + 0.095703125 + ], + "peak_gpu_bytes": 21913887488 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "rounds": 13, + "basis": "Z", + "shots": 1024, + "batch": 192, + "damping": 0.5, + "seconds": 6.715797185897827, + "elapsed": 50.234126567840576, + "first_pass_max_delta": 1.0132789611816406e-06, + "failure": [ + 0.236328125, + 0.234375, + 0.2314453125 + ], + "peak_gpu_bytes": 21913887488 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "rounds": 13, + "basis": "Z", + "shots": 1024, + "batch": 192, + "damping": 1.0, + "seconds": 3.08017635345459, + "elapsed": 53.31461310386658, + "first_pass_max_delta": 1.0132789611816406e-06, + "failure": [ + 0.236328125, + 0.23828125, + 0.234375 + ], + "peak_gpu_bytes": 21913887488 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "rounds": 25, + "basis": "Z", + "shots": 1024, + "batch": 192, + "damping": 0.5, + "seconds": 9.802945375442505, + "elapsed": 64.01536726951599, + "first_pass_max_delta": 1.4901161193847656e-06, + "failure": [ + 0.384765625, + 0.3857421875, + 0.38671875 + ], + "peak_gpu_bytes": 21913887488 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "rounds": 25, + "basis": "Z", + "shots": 1024, + "batch": 192, + "damping": 1.0, + "seconds": 5.927323341369629, + "elapsed": 69.9429976940155, + "first_pass_max_delta": 1.4901161193847656e-06, + "failure": [ + 0.384765625, + 0.3701171875, + 0.361328125 + ], + "peak_gpu_bytes": 21913887488 + } + ] + }, + "cache": { + "method": "Three extrinsic-message passes between exact CSS likelihoods, damping 1, extrinsic clipping [-8,8]", + "scope": "All 26 d5 conditions. Full validation and 4096 training shots per condition.", + "training_selection": "Same uniformly sampled training indices as d5_cache, seed 20261023; labels are only used downstream in ensemble fitting.", + "model_selection": "Damping 1 and three passes chosen from a six-condition, 1024-validation-shot diagnostic screen of .5/1 damping and 1/2/3 passes.", + "batch": 384, + "test_data_used": false, + "resume_note": "Initial dynamic allocator failed at X/r21 after saving X/r1 through r19. Those complete records are retained; remaining conditions resumed with a 90 percent preallocated pool.", + "records": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "batch": 384, + "validation": { + "seconds": 0.0023708343505859375, + "shots": 5120, + "first_pass_max_delta": 0.0, + "failure": [ + 0.0080078125, + 0.0080078125, + 0.0080078125 + ] + }, + "train": { + "seconds": 0.00203704833984375, + "shots": 4096, + "first_pass_max_delta": 0.0, + "failure": [ + 0.00830078125, + 0.00830078125, + 0.00830078125 + ] + }, + "elapsed": 0.031897783279418945, + "peak_gpu_bytes": 0 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "batch": 384, + "validation": { + "seconds": 6.5025129318237305, + "shots": 5120, + "first_pass_max_delta": 1.1622905731201172e-06, + "failure": [ + 0.05390625, + 0.05234375, + 0.0515625 + ] + }, + "train": { + "seconds": 1.8498849868774414, + "shots": 4096, + "first_pass_max_delta": 1.0728836059570312e-06, + "failure": [ + 0.056640625, + 0.056884765625, + 0.057373046875 + ] + }, + "elapsed": 9.963430881500244, + "peak_gpu_bytes": 6053389568 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "batch": 384, + "validation": { + "seconds": 7.887800455093384, + "shots": 5120, + "first_pass_max_delta": 1.1920928955078125e-06, + "failure": [ + 0.1111328125, + 0.1078125, + 0.1078125 + ] + }, + "train": { + "seconds": 3.1277287006378174, + "shots": 4096, + "first_pass_max_delta": 1.5497207641601562e-06, + "failure": [ + 0.110595703125, + 0.1044921875, + 0.106689453125 + ] + }, + "elapsed": 21.591607809066772, + "peak_gpu_bytes": 9485051136 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "batch": 384, + "validation": { + "seconds": 9.284316062927246, + "shots": 5120, + "first_pass_max_delta": 1.0728836059570312e-06, + "failure": [ + 0.1638671875, + 0.16328125, + 0.16328125 + ] + }, + "train": { + "seconds": 4.408588647842407, + "shots": 4096, + "first_pass_max_delta": 3.2186508178710938e-06, + "failure": [ + 0.165771484375, + 0.15966796875, + 0.160888671875 + ] + }, + "elapsed": 35.83207678794861, + "peak_gpu_bytes": 12921052416 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "batch": 384, + "validation": { + "seconds": 10.81107211112976, + "shots": 5120, + "first_pass_max_delta": 4.172325134277344e-06, + "failure": [ + 0.1994140625, + 0.1947265625, + 0.192578125 + ] + }, + "train": { + "seconds": 5.6971564292907715, + "shots": 4096, + "first_pass_max_delta": 1.9073486328125e-06, + "failure": [ + 0.193603515625, + 0.190185546875, + 0.1865234375 + ] + }, + "elapsed": 52.94058084487915, + "peak_gpu_bytes": 16355555584 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "batch": 384, + "validation": { + "seconds": 13.042934894561768, + "shots": 5120, + "first_pass_max_delta": 1.2516975402832031e-06, + "failure": [ + 0.2330078125, + 0.229296875, + 0.2283203125 + ] + }, + "train": { + "seconds": 6.935072898864746, + "shots": 4096, + "first_pass_max_delta": 1.043081283569336e-06, + "failure": [ + 0.237060546875, + 0.2373046875, + 0.23388671875 + ] + }, + "elapsed": 73.53631615638733, + "peak_gpu_bytes": 19787549696 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "batch": 384, + "validation": { + "seconds": 14.011132955551147, + "shots": 5120, + "first_pass_max_delta": 1.430511474609375e-06, + "failure": [ + 0.251953125, + 0.243359375, + 0.2427734375 + ] + }, + "train": { + "seconds": 8.214681386947632, + "shots": 4096, + "first_pass_max_delta": 1.6689300537109375e-06, + "failure": [ + 0.261962890625, + 0.257080078125, + 0.254150390625 + ] + }, + "elapsed": 96.39840364456177, + "peak_gpu_bytes": 23221127680 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "batch": 384, + "validation": { + "seconds": 15.821684837341309, + "shots": 5120, + "first_pass_max_delta": 2.3245811462402344e-06, + "failure": [ + 0.2822265625, + 0.286328125, + 0.2798828125 + ] + }, + "train": { + "seconds": 9.5097815990448, + "shots": 4096, + "first_pass_max_delta": 1.8477439880371094e-06, + "failure": [ + 0.294677734375, + 0.28515625, + 0.2861328125 + ] + }, + "elapsed": 122.39457035064697, + "peak_gpu_bytes": 26659319552 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "batch": 384, + "validation": { + "seconds": 18.90661311149597, + "shots": 5120, + "first_pass_max_delta": 2.3245811462402344e-06, + "failure": [ + 0.329296875, + 0.323828125, + 0.3169921875 + ] + }, + "train": { + "seconds": 11.201237440109253, + "shots": 4096, + "first_pass_max_delta": 1.0728836059570312e-06, + "failure": [ + 0.3046875, + 0.304931640625, + 0.302978515625 + ] + }, + "elapsed": 153.40053129196167, + "peak_gpu_bytes": 30096252672 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "batch": 384, + "validation": { + "seconds": 22.513427734375, + "shots": 5120, + "first_pass_max_delta": 1.4007091522216797e-06, + "failure": [ + 0.3560546875, + 0.3458984375, + 0.3455078125 + ] + }, + "train": { + "seconds": 16.373472213745117, + "shots": 4096, + "first_pass_max_delta": 1.430511474609375e-06, + "failure": [ + 0.350341796875, + 0.3447265625, + 0.339111328125 + ] + }, + "elapsed": 193.22454714775085, + "peak_gpu_bytes": 33531435520 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 20.595962524414062, + "shots": 5120, + "first_pass_max_delta": 1.1920928955078125e-06, + "failure": [ + 0.3640625, + 0.3626953125, + 0.3607421875 + ] + }, + "train": { + "seconds": 13.13056755065918, + "shots": 4096, + "first_pass_max_delta": 1.6689300537109375e-06, + "failure": [ + 0.366455078125, + 0.364013671875, + 0.3603515625 + ] + }, + "elapsed": 36.23082995414734, + "peak_gpu_bytes": 36971696384 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 21.875932693481445, + "shots": 5120, + "first_pass_max_delta": 1.2516975402832031e-06, + "failure": [ + 0.3857421875, + 0.3837890625, + 0.3794921875 + ] + }, + "train": { + "seconds": 14.333576440811157, + "shots": 4096, + "first_pass_max_delta": 1.1920928955078125e-06, + "failure": [ + 0.37841796875, + 0.380859375, + 0.378173828125 + ] + }, + "elapsed": 73.29396986961365, + "peak_gpu_bytes": 40408369664 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 23.68450117111206, + "shots": 5120, + "first_pass_max_delta": 1.7285346984863281e-06, + "failure": [ + 0.38828125, + 0.39140625, + 0.390234375 + ] + }, + "train": { + "seconds": 15.625046253204346, + "shots": 4096, + "first_pass_max_delta": 2.3543834686279297e-06, + "failure": [ + 0.401611328125, + 0.3984375, + 0.3896484375 + ] + }, + "elapsed": 113.62051224708557, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 0.0020935535430908203, + "shots": 5120, + "first_pass_max_delta": 0.0, + "failure": [ + 0.0078125, + 0.0078125, + 0.0078125 + ] + }, + "train": { + "seconds": 0.0018491744995117188, + "shots": 4096, + "first_pass_max_delta": 0.0, + "failure": [ + 0.006103515625, + 0.006103515625, + 0.006103515625 + ] + }, + "elapsed": 113.74299573898315, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 6.421818256378174, + "shots": 5120, + "first_pass_max_delta": 9.5367431640625e-07, + "failure": [ + 0.0474609375, + 0.0466796875, + 0.04609375 + ] + }, + "train": { + "seconds": 2.009964942932129, + "shots": 4096, + "first_pass_max_delta": 1.6093254089355469e-06, + "failure": [ + 0.05224609375, + 0.050537109375, + 0.050537109375 + ] + }, + "elapsed": 122.82617926597595, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 8.133492231369019, + "shots": 5120, + "first_pass_max_delta": 2.115964889526367e-06, + "failure": [ + 0.1037109375, + 0.1029296875, + 0.102734375 + ] + }, + "train": { + "seconds": 3.179387331008911, + "shots": 4096, + "first_pass_max_delta": 1.6689300537109375e-06, + "failure": [ + 0.108642578125, + 0.1044921875, + 0.10595703125 + ] + }, + "elapsed": 134.6406970024109, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 13.694931983947754, + "shots": 5120, + "first_pass_max_delta": 2.3245811462402344e-06, + "failure": [ + 0.1484375, + 0.14765625, + 0.1494140625 + ] + }, + "train": { + "seconds": 6.147953748703003, + "shots": 4096, + "first_pass_max_delta": 2.0563602447509766e-06, + "failure": [ + 0.147705078125, + 0.144775390625, + 0.143310546875 + ] + }, + "elapsed": 155.0307319164276, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 14.462661504745483, + "shots": 5120, + "first_pass_max_delta": 1.4901161193847656e-06, + "failure": [ + 0.181640625, + 0.1765625, + 0.1734375 + ] + }, + "train": { + "seconds": 6.59630274772644, + "shots": 4096, + "first_pass_max_delta": 1.7285346984863281e-06, + "failure": [ + 0.181640625, + 0.173583984375, + 0.17431640625 + ] + }, + "elapsed": 176.9893820285797, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 15.458272933959961, + "shots": 5120, + "first_pass_max_delta": 1.430511474609375e-06, + "failure": [ + 0.2208984375, + 0.2169921875, + 0.2189453125 + ] + }, + "train": { + "seconds": 8.347567081451416, + "shots": 4096, + "first_pass_max_delta": 1.7285346984863281e-06, + "failure": [ + 0.2216796875, + 0.214111328125, + 0.209716796875 + ] + }, + "elapsed": 201.48220419883728, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 16.03638219833374, + "shots": 5120, + "first_pass_max_delta": 1.0728836059570312e-06, + "failure": [ + 0.2439453125, + 0.2349609375, + 0.2333984375 + ] + }, + "train": { + "seconds": 8.29888391494751, + "shots": 4096, + "first_pass_max_delta": 8.344650268554688e-07, + "failure": [ + 0.24365234375, + 0.248046875, + 0.2451171875 + ] + }, + "elapsed": 226.75215530395508, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 16.009416103363037, + "shots": 5120, + "first_pass_max_delta": 1.341104507446289e-06, + "failure": [ + 0.271875, + 0.264453125, + 0.2638671875 + ] + }, + "train": { + "seconds": 9.500921726226807, + "shots": 4096, + "first_pass_max_delta": 1.0728836059570312e-06, + "failure": [ + 0.28076171875, + 0.267333984375, + 0.267333984375 + ] + }, + "elapsed": 252.95993447303772, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 17.426681518554688, + "shots": 5120, + "first_pass_max_delta": 1.6242265701293945e-06, + "failure": [ + 0.31484375, + 0.3056640625, + 0.3087890625 + ] + }, + "train": { + "seconds": 10.742947816848755, + "shots": 4096, + "first_pass_max_delta": 1.430511474609375e-06, + "failure": [ + 0.310791015625, + 0.309814453125, + 0.31103515625 + ] + }, + "elapsed": 281.84620356559753, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 18.49993872642517, + "shots": 5120, + "first_pass_max_delta": 1.9073486328125e-06, + "failure": [ + 0.334375, + 0.334765625, + 0.33515625 + ] + }, + "train": { + "seconds": 11.90273404121399, + "shots": 4096, + "first_pass_max_delta": 1.3113021850585938e-06, + "failure": [ + 0.327880859375, + 0.315673828125, + 0.310546875 + ] + }, + "elapsed": 313.02247071266174, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 20.121089458465576, + "shots": 5120, + "first_pass_max_delta": 1.2516975402832031e-06, + "failure": [ + 0.34609375, + 0.342578125, + 0.344140625 + ] + }, + "train": { + "seconds": 13.077136278152466, + "shots": 4096, + "first_pass_max_delta": 1.6391277313232422e-06, + "failure": [ + 0.349853515625, + 0.34765625, + 0.352294921875 + ] + }, + "elapsed": 347.0259063243866, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 22.116555213928223, + "shots": 5120, + "first_pass_max_delta": 1.6689300537109375e-06, + "failure": [ + 0.3625, + 0.3625, + 0.3564453125 + ] + }, + "train": { + "seconds": 14.53529953956604, + "shots": 4096, + "first_pass_max_delta": 1.7285346984863281e-06, + "failure": [ + 0.361572265625, + 0.36083984375, + 0.35205078125 + ] + }, + "elapsed": 384.53587651252747, + "peak_gpu_bytes": 43842280448 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "batch": 384, + "gpu_allocation": "90 percent preallocated contiguous pool", + "validation": { + "seconds": 24.039794921875, + "shots": 5120, + "first_pass_max_delta": 1.2516975402832031e-06, + "failure": [ + 0.397265625, + 0.3810546875, + 0.3755859375 + ] + }, + "train": { + "seconds": 15.72797179222107, + "shots": 4096, + "first_pass_max_delta": 1.1920928955078125e-06, + "failure": [ + 0.378662109375, + 0.370849609375, + 0.369384765625 + ] + }, + "elapsed": 425.2448420524597, + "peak_gpu_bytes": 43842280448 + } + ] + }, + "selection": "Full-validation mean failure per basis group, comparing incumbent, raw pass3, calibrated pass3, confidence ensemble, and confidence+matching ensemble.", + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": { + "failure": 0.24024939903846157 + }, + "turbo_raw": { + "failure": 0.2359375 + }, + "turbo_calibrated": { + "failure": 0.23592247596153845, + "train_loss": 0.4342440304618462, + "iterations": 8, + "optimizer_success": true + }, + "turbo_confidence": { + "failure": 0.23646334134615385, + "train_loss": 0.4325824823965761, + "iterations": 31, + "optimizer_success": true + }, + "turbo_ensemble": { + "failure": 0.23825120192307692, + "train_loss": 0.43104343457008354, + "iterations": 128, + "optimizer_success": true + } + }, + "selected": "turbo_calibrated" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": { + "failure": 0.22627704326923076 + }, + "turbo_raw": { + "failure": 0.2242938701923077 + }, + "turbo_calibrated": { + "failure": 0.22444411057692307, + "train_loss": 0.41862854651685183, + "iterations": 8, + "optimizer_success": true + }, + "turbo_confidence": { + "failure": 0.22463942307692308, + "train_loss": 0.4165407454935999, + "iterations": 28, + "optimizer_success": true + }, + "turbo_ensemble": { + "failure": 0.22291165865384616, + "train_loss": 0.4143765903988058, + "iterations": 153, + "optimizer_success": true + } + }, + "selected": "turbo_ensemble" + } + ], + "test_data_used": false, + "memory_optimization": { + "method": "Logical parity retained in forward state, marginalized out of stored histories and backward syndrome-likelihood messages; half the on-partition history size.", + "equivalence_checks": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "log_likelihood_max_delta": 0.0, + "logical_max_delta": 0.0, + "edge_posterior_max_delta": 3.2687214002180554e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "log_likelihood_max_delta": 0.0, + "logical_max_delta": 0.0, + "edge_posterior_max_delta": 3.698800981055683e-07 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "log_likelihood_max_delta": 0.0, + "logical_max_delta": 0.0, + "edge_posterior_max_delta": 4.061699030444288e-07 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "log_likelihood_max_delta": 0.0, + "logical_max_delta": 0.0, + "edge_posterior_max_delta": 4.5500107148654934e-07 + } + ], + "runtime_batch": 512, + "gpu_pool": "90 percent preallocated before JAX backend initialization" + } + }, + "neural_d5_history": [ + { + "training": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261101", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to exact complementary-CSS-conditioned relevant-edge logits; exact width-14 contraction predicts logical probability", + "training": "4096 training shots per each of all 26 d5 conditions, sampled without replacement with seed 20261023. Uniform condition and within-condition sampling for optimizer batches.", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; complementary conditioning held fixed", + "steps": 512, + "batch": 256, + "learning_rate": 0.001, + "sampling_seed": 20261101, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "starting_checkpoint": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 512, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.12617039680480957, + "error": 0.0390625, + "gradient_norm": 0.04250018671154976, + "elapsed": 18.675416231155396 + }, + { + "step": 16, + "loss": 0.6377020478248596, + "error": 0.4140625, + "gradient_norm": 0.09590183943510056, + "elapsed": 23.17981266975403 + }, + { + "step": 32, + "loss": 0.29977816343307495, + "error": 0.12109375, + "gradient_norm": 0.07157808542251587, + "elapsed": 28.000701189041138 + }, + { + "step": 48, + "loss": 0.34505343437194824, + "error": 0.1484375, + "gradient_norm": 0.07669594883918762, + "elapsed": 32.97374606132507 + }, + { + "step": 64, + "loss": 0.5405071973800659, + "error": 0.29296875, + "gradient_norm": 0.08529861271381378, + "elapsed": 37.794785499572754 + }, + { + "step": 80, + "loss": 0.5131822228431702, + "error": 0.28515625, + "gradient_norm": 0.12556222081184387, + "elapsed": 42.73275876045227 + }, + { + "step": 96, + "loss": 0.6790875196456909, + "error": 0.421875, + "gradient_norm": 0.19858981668949127, + "elapsed": 47.55139684677124 + }, + { + "step": 112, + "loss": 0.4744196832180023, + "error": 0.2421875, + "gradient_norm": 0.14321450889110565, + "elapsed": 52.42716360092163 + }, + { + "step": 128, + "loss": 0.01264211069792509, + "error": 0.00390625, + "gradient_norm": 0.007236324716359377, + "elapsed": 57.2592077255249 + }, + { + "step": 144, + "loss": 0.35788118839263916, + "error": 0.15234375, + "gradient_norm": 0.07203944772481918, + "elapsed": 64.91656231880188 + }, + { + "step": 160, + "loss": 0.6330419778823853, + "error": 0.3671875, + "gradient_norm": 0.08350329101085663, + "elapsed": 69.75011849403381 + }, + { + "step": 176, + "loss": 0.6195905208587646, + "error": 0.4140625, + "gradient_norm": 0.11415330320596695, + "elapsed": 74.56864047050476 + }, + { + "step": 192, + "loss": 0.5832147598266602, + "error": 0.37109375, + "gradient_norm": 0.3569585978984833, + "elapsed": 79.38981986045837 + }, + { + "step": 208, + "loss": 0.6469261646270752, + "error": 0.4296875, + "gradient_norm": 0.18999285995960236, + "elapsed": 84.23919153213501 + }, + { + "step": 224, + "loss": 0.5015400648117065, + "error": 0.26171875, + "gradient_norm": 0.14661277830600739, + "elapsed": 89.08856391906738 + }, + { + "step": 240, + "loss": 0.5771075487136841, + "error": 0.30859375, + "gradient_norm": 0.16081298887729645, + "elapsed": 94.75072908401489 + }, + { + "step": 256, + "loss": 0.4888438582420349, + "error": 0.265625, + "gradient_norm": 0.0695391371846199, + "elapsed": 101.01203680038452 + }, + { + "step": 272, + "loss": 0.4024130702018738, + "error": 0.171875, + "gradient_norm": 0.12405848503112793, + "elapsed": 110.68109226226807 + }, + { + "step": 288, + "loss": 0.5895810723304749, + "error": 0.34375, + "gradient_norm": 0.11818791180849075, + "elapsed": 117.13554787635803 + }, + { + "step": 304, + "loss": 0.4740591049194336, + "error": 0.23828125, + "gradient_norm": 0.12323135882616043, + "elapsed": 123.14409065246582 + }, + { + "step": 320, + "loss": 0.007106379605829716, + "error": 0.0, + "gradient_norm": 0.011303205043077469, + "elapsed": 129.3651967048645 + }, + { + "step": 336, + "loss": 0.11020991206169128, + "error": 0.046875, + "gradient_norm": 0.09031850099563599, + "elapsed": 135.01193165779114 + }, + { + "step": 352, + "loss": 0.47800248861312866, + "error": 0.23046875, + "gradient_norm": 0.09636854380369186, + "elapsed": 141.10205006599426 + }, + { + "step": 368, + "loss": 0.4062168598175049, + "error": 0.203125, + "gradient_norm": 0.17921771109104156, + "elapsed": 146.6507167816162 + }, + { + "step": 384, + "loss": 0.24366013705730438, + "error": 0.12109375, + "gradient_norm": 0.11793741583824158, + "elapsed": 152.7517864704132 + }, + { + "step": 400, + "loss": 0.4949762225151062, + "error": 0.28515625, + "gradient_norm": 0.09550267457962036, + "elapsed": 160.96661829948425 + }, + { + "step": 416, + "loss": 0.21066513657569885, + "error": 0.08984375, + "gradient_norm": 0.07445460557937622, + "elapsed": 165.83068180084229 + }, + { + "step": 432, + "loss": 0.4017776548862457, + "error": 0.18359375, + "gradient_norm": 0.1278357356786728, + "elapsed": 170.6406123638153 + }, + { + "step": 448, + "loss": 0.11823543906211853, + "error": 0.04296875, + "gradient_norm": 0.09968453645706177, + "elapsed": 175.4701704978943 + }, + { + "step": 464, + "loss": 0.47654634714126587, + "error": 0.2265625, + "gradient_norm": 0.18101797997951508, + "elapsed": 180.26738119125366 + }, + { + "step": 480, + "loss": 0.4916652739048004, + "error": 0.24609375, + "gradient_norm": 0.08958703279495239, + "elapsed": 185.08883357048035 + }, + { + "step": 496, + "loss": 0.5418418645858765, + "error": 0.3515625, + "gradient_norm": 0.08218713104724884, + "elapsed": 189.9677882194519 + }, + { + "step": 512, + "loss": 0.5470219850540161, + "error": 0.359375, + "gradient_norm": 0.07939601689577103, + "elapsed": 194.77887177467346 + } + ] + }, + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with incumbent.", + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23592247596153845, + "128": 0.23888221153846154, + "blend-128": 0.23536658653846151, + "256": 0.23865685096153846, + "blend-256": 0.23538161057692308, + "384": 0.23852163461538461, + "blend-384": 0.23487079326923077, + "512": 0.23870192307692306, + "blend-512": 0.23482572115384615 + }, + "selected": "blend-512" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22291165865384616, + "128": 0.2279897836538462, + "blend-128": 0.22366286057692308, + "256": 0.2274188701923077, + "blend-256": 0.22304687500000003, + "384": 0.22729867788461536, + "blend-384": 0.22337740384615384, + "512": 0.22662259615384617, + "blend-512": 0.22355769230769235 + }, + "selected": "incumbent" + } + ], + "checkpoints": { + "512": { + "step": 512, + "training_samples": 131072, + "weights_sha256": "86aa65455686eb06a430030bd4b8242ac78521dccf4e9b07f1e93b2aa2ec40af", + "complete": true + } + }, + "runtime": "Shared initial complementary-CSS priors between neural and physical branches in blended groups. Last-only physical branches omit logical tracking in intermediate passes when intermediate probabilities are unused.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false + }, + { + "training": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261108", + "prior_pass": 3, + "initial_seed": 20261108, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "4096 training shots per each of all 26 d5 conditions, sampled without replacement with seed 20261023. Uniform condition and within-condition sampling for optimizer batches.", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1024, + "batch": 256, + "learning_rate": 0.001, + "sampling_seed": 20261108, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "starting_checkpoint": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.011146659031510353, + "error": 0.00390625, + "gradient_norm": 0.011240893043577671, + "elapsed": 21.276997089385986 + }, + { + "step": 16, + "loss": 0.645737886428833, + "error": 0.40625, + "gradient_norm": 0.1628236621618271, + "elapsed": 25.872907638549805 + }, + { + "step": 32, + "loss": 0.574029803276062, + "error": 0.35546875, + "gradient_norm": 0.3000081777572632, + "elapsed": 30.761418342590332 + }, + { + "step": 48, + "loss": 0.574467122554779, + "error": 0.296875, + "gradient_norm": 0.24150623381137848, + "elapsed": 35.67650651931763 + }, + { + "step": 64, + "loss": 0.6003620624542236, + "error": 0.35546875, + "gradient_norm": 0.07430054992437363, + "elapsed": 40.60572576522827 + }, + { + "step": 80, + "loss": 0.5429091453552246, + "error": 0.33203125, + "gradient_norm": 0.15341751277446747, + "elapsed": 45.546849727630615 + }, + { + "step": 96, + "loss": 0.368771493434906, + "error": 0.1640625, + "gradient_norm": 0.08923184871673584, + "elapsed": 50.49156332015991 + }, + { + "step": 112, + "loss": 0.516342043876648, + "error": 0.265625, + "gradient_norm": 0.10965219140052795, + "elapsed": 55.45058846473694 + }, + { + "step": 128, + "loss": 0.5925382971763611, + "error": 0.37109375, + "gradient_norm": 0.055406324565410614, + "elapsed": 60.40891766548157 + }, + { + "step": 144, + "loss": 0.19184258580207825, + "error": 0.07421875, + "gradient_norm": 0.07042146474123001, + "elapsed": 65.33323669433594 + }, + { + "step": 160, + "loss": 0.5202382206916809, + "error": 0.25390625, + "gradient_norm": 0.14782382547855377, + "elapsed": 70.26605796813965 + }, + { + "step": 176, + "loss": 0.46083134412765503, + "error": 0.22265625, + "gradient_norm": 0.09074779599905014, + "elapsed": 75.18221640586853 + }, + { + "step": 192, + "loss": 0.3054918646812439, + "error": 0.14453125, + "gradient_norm": 0.0588168129324913, + "elapsed": 80.1186010837555 + }, + { + "step": 208, + "loss": 0.4836011230945587, + "error": 0.27734375, + "gradient_norm": 0.09208947420120239, + "elapsed": 85.05764293670654 + }, + { + "step": 224, + "loss": 0.6640600562095642, + "error": 0.38671875, + "gradient_norm": 0.22026506066322327, + "elapsed": 89.98808217048645 + }, + { + "step": 240, + "loss": 0.02421322464942932, + "error": 0.00390625, + "gradient_norm": 0.008131005801260471, + "elapsed": 94.90194272994995 + }, + { + "step": 256, + "loss": 0.6302106976509094, + "error": 0.4296875, + "gradient_norm": 0.09762304276227951, + "elapsed": 99.82612204551697 + }, + { + "step": 272, + "loss": 0.5092596411705017, + "error": 0.27734375, + "gradient_norm": 0.11407691985368729, + "elapsed": 110.44065999984741 + }, + { + "step": 288, + "loss": 0.452798455953598, + "error": 0.2265625, + "gradient_norm": 0.1105576679110527, + "elapsed": 115.36984539031982 + }, + { + "step": 304, + "loss": 0.3378596305847168, + "error": 0.18359375, + "gradient_norm": 0.0841713547706604, + "elapsed": 120.29337763786316 + }, + { + "step": 320, + "loss": 0.6271854639053345, + "error": 0.38671875, + "gradient_norm": 0.1972702294588089, + "elapsed": 125.2231035232544 + }, + { + "step": 336, + "loss": 0.04562236741185188, + "error": 0.01171875, + "gradient_norm": 0.027922745794057846, + "elapsed": 130.14725255966187 + }, + { + "step": 352, + "loss": 0.5342530608177185, + "error": 0.26953125, + "gradient_norm": 0.09031179547309875, + "elapsed": 135.08111095428467 + }, + { + "step": 368, + "loss": 0.49785488843917847, + "error": 0.2578125, + "gradient_norm": 0.19366280734539032, + "elapsed": 140.00699138641357 + }, + { + "step": 384, + "loss": 0.5673326253890991, + "error": 0.30859375, + "gradient_norm": 0.20644932985305786, + "elapsed": 144.92276740074158 + }, + { + "step": 400, + "loss": 0.5581298470497131, + "error": 0.3203125, + "gradient_norm": 0.17668266594409943, + "elapsed": 149.86573243141174 + }, + { + "step": 416, + "loss": 0.5564071536064148, + "error": 0.30078125, + "gradient_norm": 0.0821610689163208, + "elapsed": 154.7953712940216 + }, + { + "step": 432, + "loss": 0.5540086030960083, + "error": 0.34765625, + "gradient_norm": 0.1438807100057602, + "elapsed": 159.72657418251038 + }, + { + "step": 448, + "loss": 0.540939450263977, + "error": 0.29296875, + "gradient_norm": 0.17986361682415009, + "elapsed": 164.6689453125 + }, + { + "step": 464, + "loss": 0.45807865262031555, + "error": 0.25, + "gradient_norm": 0.14453186094760895, + "elapsed": 169.58739304542542 + }, + { + "step": 480, + "loss": 0.5191650390625, + "error": 0.22265625, + "gradient_norm": 0.07955105602741241, + "elapsed": 174.5444438457489 + }, + { + "step": 496, + "loss": 0.1692925989627838, + "error": 0.0703125, + "gradient_norm": 0.07875128090381622, + "elapsed": 179.48035550117493 + }, + { + "step": 512, + "loss": 0.5580664873123169, + "error": 0.3125, + "gradient_norm": 0.27090802788734436, + "elapsed": 184.42834162712097 + }, + { + "step": 528, + "loss": 0.26402050256729126, + "error": 0.13671875, + "gradient_norm": 0.13135771453380585, + "elapsed": 195.17691040039062 + }, + { + "step": 544, + "loss": 0.4352915287017822, + "error": 0.1953125, + "gradient_norm": 0.15959712862968445, + "elapsed": 200.0421543121338 + }, + { + "step": 560, + "loss": 0.22861814498901367, + "error": 0.1015625, + "gradient_norm": 0.08776932209730148, + "elapsed": 204.95144605636597 + }, + { + "step": 576, + "loss": 0.28309381008148193, + "error": 0.1328125, + "gradient_norm": 0.11050742119550705, + "elapsed": 209.8526291847229 + }, + { + "step": 592, + "loss": 0.6409220695495605, + "error": 0.41015625, + "gradient_norm": 0.19826626777648926, + "elapsed": 214.84447717666626 + }, + { + "step": 608, + "loss": 0.25090643763542175, + "error": 0.109375, + "gradient_norm": 0.05864342302083969, + "elapsed": 219.72637391090393 + }, + { + "step": 624, + "loss": 0.11423969268798828, + "error": 0.05078125, + "gradient_norm": 0.05318564549088478, + "elapsed": 224.6331377029419 + }, + { + "step": 640, + "loss": 0.32663431763648987, + "error": 0.1328125, + "gradient_norm": 0.06877780705690384, + "elapsed": 229.5065622329712 + }, + { + "step": 656, + "loss": 0.24196995794773102, + "error": 0.10546875, + "gradient_norm": 0.07683655619621277, + "elapsed": 234.4042534828186 + }, + { + "step": 672, + "loss": 0.5349344611167908, + "error": 0.296875, + "gradient_norm": 0.15214307606220245, + "elapsed": 239.26656579971313 + }, + { + "step": 688, + "loss": 0.26759713888168335, + "error": 0.1171875, + "gradient_norm": 0.14698348939418793, + "elapsed": 244.21049737930298 + }, + { + "step": 704, + "loss": 0.37338894605636597, + "error": 0.18359375, + "gradient_norm": 0.10210632532835007, + "elapsed": 249.13519072532654 + }, + { + "step": 720, + "loss": 0.36807945370674133, + "error": 0.17578125, + "gradient_norm": 0.09668388962745667, + "elapsed": 254.06281065940857 + }, + { + "step": 736, + "loss": 0.3736685514450073, + "error": 0.15625, + "gradient_norm": 0.10987236350774765, + "elapsed": 259.01695108413696 + }, + { + "step": 752, + "loss": 0.5266942977905273, + "error": 0.29296875, + "gradient_norm": 0.09041415899991989, + "elapsed": 263.9530746936798 + }, + { + "step": 768, + "loss": 0.360038161277771, + "error": 0.1640625, + "gradient_norm": 0.10391079634428024, + "elapsed": 268.9019305706024 + }, + { + "step": 784, + "loss": 0.5700286626815796, + "error": 0.34375, + "gradient_norm": 0.12206032127141953, + "elapsed": 279.4174163341522 + }, + { + "step": 800, + "loss": 0.42533689737319946, + "error": 0.20703125, + "gradient_norm": 0.06605375558137894, + "elapsed": 284.3391351699829 + }, + { + "step": 816, + "loss": 0.12355346977710724, + "error": 0.046875, + "gradient_norm": 0.06571663916110992, + "elapsed": 289.2815272808075 + }, + { + "step": 832, + "loss": 0.6411258578300476, + "error": 0.3984375, + "gradient_norm": 0.160088911652565, + "elapsed": 294.2048614025116 + }, + { + "step": 848, + "loss": 0.5756919980049133, + "error": 0.3515625, + "gradient_norm": 0.0962308868765831, + "elapsed": 299.15635418891907 + }, + { + "step": 864, + "loss": 0.2706402540206909, + "error": 0.1171875, + "gradient_norm": 0.11391306668519974, + "elapsed": 304.09321761131287 + }, + { + "step": 880, + "loss": 0.33621329069137573, + "error": 0.1640625, + "gradient_norm": 0.09049320220947266, + "elapsed": 309.0412187576294 + }, + { + "step": 896, + "loss": 0.44343245029449463, + "error": 0.23828125, + "gradient_norm": 0.12484703958034515, + "elapsed": 313.98498797416687 + }, + { + "step": 912, + "loss": 0.5987736582756042, + "error": 0.359375, + "gradient_norm": 0.07541236281394958, + "elapsed": 318.9334623813629 + }, + { + "step": 928, + "loss": 0.38585522770881653, + "error": 0.1875, + "gradient_norm": 0.09290861338376999, + "elapsed": 323.86884689331055 + }, + { + "step": 944, + "loss": 0.4820440113544464, + "error": 0.234375, + "gradient_norm": 0.22198310494422913, + "elapsed": 328.7963180541992 + }, + { + "step": 960, + "loss": 0.07455944269895554, + "error": 0.015625, + "gradient_norm": 0.055282026529312134, + "elapsed": 333.75238251686096 + }, + { + "step": 976, + "loss": 0.013475366868078709, + "error": 0.0078125, + "gradient_norm": 0.009843004867434502, + "elapsed": 338.6403331756592 + }, + { + "step": 992, + "loss": 0.4429199695587158, + "error": 0.2265625, + "gradient_norm": 0.09489083290100098, + "elapsed": 343.5606532096863 + }, + { + "step": 1008, + "loss": 0.4892328381538391, + "error": 0.234375, + "gradient_norm": 0.1342826634645462, + "elapsed": 348.5243353843689 + }, + { + "step": 1024, + "loss": 0.6096819043159485, + "error": 0.32421875, + "gradient_norm": 0.17938998341560364, + "elapsed": 353.36506962776184 + } + ] + }, + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with the recorded physical decoder.", + "physical_prediction_reference": "/run-state/workspace/research/context_upgrades/turbo1/predictions", + "prior_pass": 3, + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23482572115384615, + "256": 0.2346754807692308, + "blend-256": 0.23484074519230771, + "512": 0.23569711538461538, + "blend-512": 0.2338341346153846, + "768": 0.23470552884615387, + "blend-768": 0.23464543269230764, + "1024": 0.23653846153846153, + "blend-1024": 0.23445012019230768 + }, + "selected": "blend-512" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22291165865384616, + "256": 0.2231520432692308, + "blend-256": 0.2219951923076923, + "512": 0.22303185096153846, + "blend-512": 0.22211538461538463, + "768": 0.22279146634615382, + "blend-768": 0.2219501201923077, + "1024": 0.22291165865384616, + "blend-1024": 0.22182992788461542 + }, + "selected": "blend-1024" + } + ], + "checkpoints": { + "512": { + "step": 512, + "training_samples": 131072, + "weights_sha256": "6109f95c51d7b8803085c84b6bb34e3f199cc349bd846d6007c8f9a4f2a0c4fe", + "complete": true + }, + "1024": { + "step": 1024, + "training_samples": 262144, + "weights_sha256": "46aa01e703f38fa153206c54ff0ce7083d839de7aeb51bf14c8e732d52d5bd2d", + "complete": true + } + }, + "runtime": "Share physical priors when the conditioning pass and regime agree; otherwise recompute the neural prior independently. Last-only physical branches omit logical tracking in intermediate passes when intermediate probabilities are unused.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false + }, + { + "training": { + "initialization": "Continue from the recorded session-trained checkpoint; original random initialization seed 20261108", + "prior_pass": 3, + "initial_seed": 20261108, + "training_source_sha256": { + "learned_d5__train.py": "b73af9da21332dee9a43f653b514695b020fbc3516604b2e721d8cf0ea876d53", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "5e9420df1f6dd56518925e910096fb9bc93bd796a5933b13bf894a1a96256cdf", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "All supplied training shots per each of all26 d5 conditions; uniform condition and within-condition sampling for optimizer batches.", + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 516880, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 507282, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 19592, + "surface_code_bX_d5_r03_center_5_5": 19646, + "surface_code_bX_d5_r05_center_5_5": 19513, + "surface_code_bX_d5_r07_center_5_5": 19341, + "surface_code_bX_d5_r09_center_5_5": 19211, + "surface_code_bX_d5_r11_center_5_5": 19239, + "surface_code_bX_d5_r13_center_5_5": 19679, + "surface_code_bX_d5_r15_center_5_5": 19455, + "surface_code_bX_d5_r17_center_5_5": 19479, + "surface_code_bX_d5_r19_center_5_5": 19479, + "surface_code_bX_d5_r21_center_5_5": 19551, + "surface_code_bX_d5_r23_center_5_5": 19586, + "surface_code_bX_d5_r25_center_5_5": 19526, + "surface_code_bZ_d5_r01_center_5_5": 19652, + "surface_code_bZ_d5_r03_center_5_5": 19732, + "surface_code_bZ_d5_r05_center_5_5": 19754, + "surface_code_bZ_d5_r07_center_5_5": 19194, + "surface_code_bZ_d5_r09_center_5_5": 19641, + "surface_code_bZ_d5_r11_center_5_5": 19611, + "surface_code_bZ_d5_r13_center_5_5": 19424, + "surface_code_bZ_d5_r15_center_5_5": 19380, + "surface_code_bZ_d5_r17_center_5_5": 19384, + "surface_code_bZ_d5_r19_center_5_5": 19684, + "surface_code_bZ_d5_r21_center_5_5": 19559, + "surface_code_bZ_d5_r23_center_5_5": 19524, + "surface_code_bZ_d5_r25_center_5_5": 19446 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 2048, + "batch": 1024, + "learning_rate": 0.0005, + "sampling_seed": 20261113, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": true, + "rng_restored": true, + "sampling_state_source": "/run-state/workspace/research/learned_d5/feedback3_pilot/rng-768.json", + "starting_checkpoint": "/run-state/workspace/research/learned_d5/feedback3_pilot/weights-768.npz", + "starting_checkpoint_sha256": "bc2ba1c529317ce1b5b661efae4707eca49c6995d6f22b04193fe7642662fed8", + "starting_training_provenance": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261108", + "prior_pass": 3, + "initial_seed": 20261108, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "4096 training shots per each of all 26 d5 conditions, sampled without replacement with seed 20261023. Uniform condition and within-condition sampling for optimizer batches.", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1024, + "batch": 256, + "learning_rate": 0.001, + "sampling_seed": 20261108, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "starting_checkpoint": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.011146659031510353, + "error": 0.00390625, + "gradient_norm": 0.011240893043577671, + "elapsed": 21.276997089385986 + }, + { + "step": 16, + "loss": 0.645737886428833, + "error": 0.40625, + "gradient_norm": 0.1628236621618271, + "elapsed": 25.872907638549805 + }, + { + "step": 32, + "loss": 0.574029803276062, + "error": 0.35546875, + "gradient_norm": 0.3000081777572632, + "elapsed": 30.761418342590332 + }, + { + "step": 48, + "loss": 0.574467122554779, + "error": 0.296875, + "gradient_norm": 0.24150623381137848, + "elapsed": 35.67650651931763 + }, + { + "step": 64, + "loss": 0.6003620624542236, + "error": 0.35546875, + "gradient_norm": 0.07430054992437363, + "elapsed": 40.60572576522827 + }, + { + "step": 80, + "loss": 0.5429091453552246, + "error": 0.33203125, + "gradient_norm": 0.15341751277446747, + "elapsed": 45.546849727630615 + }, + { + "step": 96, + "loss": 0.368771493434906, + "error": 0.1640625, + "gradient_norm": 0.08923184871673584, + "elapsed": 50.49156332015991 + }, + { + "step": 112, + "loss": 0.516342043876648, + "error": 0.265625, + "gradient_norm": 0.10965219140052795, + "elapsed": 55.45058846473694 + }, + { + "step": 128, + "loss": 0.5925382971763611, + "error": 0.37109375, + "gradient_norm": 0.055406324565410614, + "elapsed": 60.40891766548157 + }, + { + "step": 144, + "loss": 0.19184258580207825, + "error": 0.07421875, + "gradient_norm": 0.07042146474123001, + "elapsed": 65.33323669433594 + }, + { + "step": 160, + "loss": 0.5202382206916809, + "error": 0.25390625, + "gradient_norm": 0.14782382547855377, + "elapsed": 70.26605796813965 + }, + { + "step": 176, + "loss": 0.46083134412765503, + "error": 0.22265625, + "gradient_norm": 0.09074779599905014, + "elapsed": 75.18221640586853 + }, + { + "step": 192, + "loss": 0.3054918646812439, + "error": 0.14453125, + "gradient_norm": 0.0588168129324913, + "elapsed": 80.1186010837555 + }, + { + "step": 208, + "loss": 0.4836011230945587, + "error": 0.27734375, + "gradient_norm": 0.09208947420120239, + "elapsed": 85.05764293670654 + }, + { + "step": 224, + "loss": 0.6640600562095642, + "error": 0.38671875, + "gradient_norm": 0.22026506066322327, + "elapsed": 89.98808217048645 + }, + { + "step": 240, + "loss": 0.02421322464942932, + "error": 0.00390625, + "gradient_norm": 0.008131005801260471, + "elapsed": 94.90194272994995 + }, + { + "step": 256, + "loss": 0.6302106976509094, + "error": 0.4296875, + "gradient_norm": 0.09762304276227951, + "elapsed": 99.82612204551697 + }, + { + "step": 272, + "loss": 0.5092596411705017, + "error": 0.27734375, + "gradient_norm": 0.11407691985368729, + "elapsed": 110.44065999984741 + }, + { + "step": 288, + "loss": 0.452798455953598, + "error": 0.2265625, + "gradient_norm": 0.1105576679110527, + "elapsed": 115.36984539031982 + }, + { + "step": 304, + "loss": 0.3378596305847168, + "error": 0.18359375, + "gradient_norm": 0.0841713547706604, + "elapsed": 120.29337763786316 + }, + { + "step": 320, + "loss": 0.6271854639053345, + "error": 0.38671875, + "gradient_norm": 0.1972702294588089, + "elapsed": 125.2231035232544 + }, + { + "step": 336, + "loss": 0.04562236741185188, + "error": 0.01171875, + "gradient_norm": 0.027922745794057846, + "elapsed": 130.14725255966187 + }, + { + "step": 352, + "loss": 0.5342530608177185, + "error": 0.26953125, + "gradient_norm": 0.09031179547309875, + "elapsed": 135.08111095428467 + }, + { + "step": 368, + "loss": 0.49785488843917847, + "error": 0.2578125, + "gradient_norm": 0.19366280734539032, + "elapsed": 140.00699138641357 + }, + { + "step": 384, + "loss": 0.5673326253890991, + "error": 0.30859375, + "gradient_norm": 0.20644932985305786, + "elapsed": 144.92276740074158 + }, + { + "step": 400, + "loss": 0.5581298470497131, + "error": 0.3203125, + "gradient_norm": 0.17668266594409943, + "elapsed": 149.86573243141174 + }, + { + "step": 416, + "loss": 0.5564071536064148, + "error": 0.30078125, + "gradient_norm": 0.0821610689163208, + "elapsed": 154.7953712940216 + }, + { + "step": 432, + "loss": 0.5540086030960083, + "error": 0.34765625, + "gradient_norm": 0.1438807100057602, + "elapsed": 159.72657418251038 + }, + { + "step": 448, + "loss": 0.540939450263977, + "error": 0.29296875, + "gradient_norm": 0.17986361682415009, + "elapsed": 164.6689453125 + }, + { + "step": 464, + "loss": 0.45807865262031555, + "error": 0.25, + "gradient_norm": 0.14453186094760895, + "elapsed": 169.58739304542542 + }, + { + "step": 480, + "loss": 0.5191650390625, + "error": 0.22265625, + "gradient_norm": 0.07955105602741241, + "elapsed": 174.5444438457489 + }, + { + "step": 496, + "loss": 0.1692925989627838, + "error": 0.0703125, + "gradient_norm": 0.07875128090381622, + "elapsed": 179.48035550117493 + }, + { + "step": 512, + "loss": 0.5580664873123169, + "error": 0.3125, + "gradient_norm": 0.27090802788734436, + "elapsed": 184.42834162712097 + }, + { + "step": 528, + "loss": 0.26402050256729126, + "error": 0.13671875, + "gradient_norm": 0.13135771453380585, + "elapsed": 195.17691040039062 + }, + { + "step": 544, + "loss": 0.4352915287017822, + "error": 0.1953125, + "gradient_norm": 0.15959712862968445, + "elapsed": 200.0421543121338 + }, + { + "step": 560, + "loss": 0.22861814498901367, + "error": 0.1015625, + "gradient_norm": 0.08776932209730148, + "elapsed": 204.95144605636597 + }, + { + "step": 576, + "loss": 0.28309381008148193, + "error": 0.1328125, + "gradient_norm": 0.11050742119550705, + "elapsed": 209.8526291847229 + }, + { + "step": 592, + "loss": 0.6409220695495605, + "error": 0.41015625, + "gradient_norm": 0.19826626777648926, + "elapsed": 214.84447717666626 + }, + { + "step": 608, + "loss": 0.25090643763542175, + "error": 0.109375, + "gradient_norm": 0.05864342302083969, + "elapsed": 219.72637391090393 + }, + { + "step": 624, + "loss": 0.11423969268798828, + "error": 0.05078125, + "gradient_norm": 0.05318564549088478, + "elapsed": 224.6331377029419 + }, + { + "step": 640, + "loss": 0.32663431763648987, + "error": 0.1328125, + "gradient_norm": 0.06877780705690384, + "elapsed": 229.5065622329712 + }, + { + "step": 656, + "loss": 0.24196995794773102, + "error": 0.10546875, + "gradient_norm": 0.07683655619621277, + "elapsed": 234.4042534828186 + }, + { + "step": 672, + "loss": 0.5349344611167908, + "error": 0.296875, + "gradient_norm": 0.15214307606220245, + "elapsed": 239.26656579971313 + }, + { + "step": 688, + "loss": 0.26759713888168335, + "error": 0.1171875, + "gradient_norm": 0.14698348939418793, + "elapsed": 244.21049737930298 + }, + { + "step": 704, + "loss": 0.37338894605636597, + "error": 0.18359375, + "gradient_norm": 0.10210632532835007, + "elapsed": 249.13519072532654 + }, + { + "step": 720, + "loss": 0.36807945370674133, + "error": 0.17578125, + "gradient_norm": 0.09668388962745667, + "elapsed": 254.06281065940857 + }, + { + "step": 736, + "loss": 0.3736685514450073, + "error": 0.15625, + "gradient_norm": 0.10987236350774765, + "elapsed": 259.01695108413696 + }, + { + "step": 752, + "loss": 0.5266942977905273, + "error": 0.29296875, + "gradient_norm": 0.09041415899991989, + "elapsed": 263.9530746936798 + }, + { + "step": 768, + "loss": 0.360038161277771, + "error": 0.1640625, + "gradient_norm": 0.10391079634428024, + "elapsed": 268.9019305706024 + }, + { + "step": 784, + "loss": 0.5700286626815796, + "error": 0.34375, + "gradient_norm": 0.12206032127141953, + "elapsed": 279.4174163341522 + }, + { + "step": 800, + "loss": 0.42533689737319946, + "error": 0.20703125, + "gradient_norm": 0.06605375558137894, + "elapsed": 284.3391351699829 + }, + { + "step": 816, + "loss": 0.12355346977710724, + "error": 0.046875, + "gradient_norm": 0.06571663916110992, + "elapsed": 289.2815272808075 + }, + { + "step": 832, + "loss": 0.6411258578300476, + "error": 0.3984375, + "gradient_norm": 0.160088911652565, + "elapsed": 294.2048614025116 + }, + { + "step": 848, + "loss": 0.5756919980049133, + "error": 0.3515625, + "gradient_norm": 0.0962308868765831, + "elapsed": 299.15635418891907 + }, + { + "step": 864, + "loss": 0.2706402540206909, + "error": 0.1171875, + "gradient_norm": 0.11391306668519974, + "elapsed": 304.09321761131287 + }, + { + "step": 880, + "loss": 0.33621329069137573, + "error": 0.1640625, + "gradient_norm": 0.09049320220947266, + "elapsed": 309.0412187576294 + }, + { + "step": 896, + "loss": 0.44343245029449463, + "error": 0.23828125, + "gradient_norm": 0.12484703958034515, + "elapsed": 313.98498797416687 + }, + { + "step": 912, + "loss": 0.5987736582756042, + "error": 0.359375, + "gradient_norm": 0.07541236281394958, + "elapsed": 318.9334623813629 + }, + { + "step": 928, + "loss": 0.38585522770881653, + "error": 0.1875, + "gradient_norm": 0.09290861338376999, + "elapsed": 323.86884689331055 + }, + { + "step": 944, + "loss": 0.4820440113544464, + "error": 0.234375, + "gradient_norm": 0.22198310494422913, + "elapsed": 328.7963180541992 + }, + { + "step": 960, + "loss": 0.07455944269895554, + "error": 0.015625, + "gradient_norm": 0.055282026529312134, + "elapsed": 333.75238251686096 + }, + { + "step": 976, + "loss": 0.013475366868078709, + "error": 0.0078125, + "gradient_norm": 0.009843004867434502, + "elapsed": 338.6403331756592 + }, + { + "step": 992, + "loss": 0.4429199695587158, + "error": 0.2265625, + "gradient_norm": 0.09489083290100098, + "elapsed": 343.5606532096863 + }, + { + "step": 1008, + "loss": 0.4892328381538391, + "error": 0.234375, + "gradient_norm": 0.1342826634645462, + "elapsed": 348.5243353843689 + }, + { + "step": 1024, + "loss": 0.6096819043159485, + "error": 0.32421875, + "gradient_norm": 0.17938998341560364, + "elapsed": 353.36506962776184 + } + ] + }, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.4341062307357788, + "objective": 0.4341062307357788, + "error": 0.208984375, + "gradient_norm": 0.07617632299661636, + "elapsed": 31.45817995071411 + }, + { + "step": 16, + "loss": 0.5996706485748291, + "objective": 0.5996706485748291, + "error": 0.359375, + "gradient_norm": 0.05249844491481781, + "elapsed": 56.34200572967529 + }, + { + "step": 32, + "loss": 0.4388691186904907, + "objective": 0.4388691186904907, + "error": 0.2041015625, + "gradient_norm": 0.0376109778881073, + "elapsed": 67.83739852905273 + }, + { + "step": 48, + "loss": 0.5373439788818359, + "objective": 0.5373439788818359, + "error": 0.2919921875, + "gradient_norm": 0.06261218339204788, + "elapsed": 76.69065475463867 + }, + { + "step": 64, + "loss": 0.24871854484081268, + "objective": 0.24871854484081268, + "error": 0.1162109375, + "gradient_norm": 0.05284671485424042, + "elapsed": 86.3852767944336 + }, + { + "step": 80, + "loss": 0.26628297567367554, + "objective": 0.26628297567367554, + "error": 0.123046875, + "gradient_norm": 0.04054367542266846, + "elapsed": 95.77356100082397 + }, + { + "step": 96, + "loss": 0.48436349630355835, + "objective": 0.48436349630355835, + "error": 0.259765625, + "gradient_norm": 0.05399860441684723, + "elapsed": 107.06293416023254 + }, + { + "step": 112, + "loss": 0.41063767671585083, + "objective": 0.41063767671585083, + "error": 0.1943359375, + "gradient_norm": 0.043602071702480316, + "elapsed": 116.78119611740112 + }, + { + "step": 128, + "loss": 0.3990316390991211, + "objective": 0.3990316390991211, + "error": 0.1865234375, + "gradient_norm": 0.0424419641494751, + "elapsed": 125.6915397644043 + }, + { + "step": 144, + "loss": 0.5119550228118896, + "objective": 0.5119550228118896, + "error": 0.2646484375, + "gradient_norm": 0.07688591629266739, + "elapsed": 136.20711088180542 + }, + { + "step": 160, + "loss": 0.3388235569000244, + "objective": 0.3388235569000244, + "error": 0.1630859375, + "gradient_norm": 0.07015731930732727, + "elapsed": 145.3505516052246 + }, + { + "step": 176, + "loss": 0.5952156186103821, + "objective": 0.5952156186103821, + "error": 0.3369140625, + "gradient_norm": 0.039373140782117844, + "elapsed": 154.77994871139526 + }, + { + "step": 192, + "loss": 0.15157413482666016, + "objective": 0.15157413482666016, + "error": 0.0634765625, + "gradient_norm": 0.029710670933127403, + "elapsed": 164.46801733970642 + }, + { + "step": 208, + "loss": 0.3120684027671814, + "objective": 0.3120684027671814, + "error": 0.1474609375, + "gradient_norm": 0.035548821091651917, + "elapsed": 173.24825358390808 + }, + { + "step": 224, + "loss": 0.5486405491828918, + "objective": 0.5486405491828918, + "error": 0.2900390625, + "gradient_norm": 0.0503678023815155, + "elapsed": 185.29849314689636 + }, + { + "step": 240, + "loss": 0.6046283841133118, + "objective": 0.6046283841133118, + "error": 0.3349609375, + "gradient_norm": 0.05043461173772812, + "elapsed": 197.54880928993225 + }, + { + "step": 256, + "loss": 0.5926339626312256, + "objective": 0.5926339626312256, + "error": 0.3359375, + "gradient_norm": 0.051241543143987656, + "elapsed": 211.79861068725586 + }, + { + "step": 272, + "loss": 0.4018518924713135, + "objective": 0.4018518924713135, + "error": 0.1943359375, + "gradient_norm": 0.0772147998213768, + "elapsed": 222.41974115371704 + }, + { + "step": 288, + "loss": 0.13863243162631989, + "objective": 0.13863243162631989, + "error": 0.0556640625, + "gradient_norm": 0.03334609419107437, + "elapsed": 234.04247426986694 + }, + { + "step": 304, + "loss": 0.562490701675415, + "objective": 0.562490701675415, + "error": 0.337890625, + "gradient_norm": 0.04585934057831764, + "elapsed": 242.65421533584595 + }, + { + "step": 320, + "loss": 0.5352796316146851, + "objective": 0.5352796316146851, + "error": 0.294921875, + "gradient_norm": 0.0837635025382042, + "elapsed": 252.10656356811523 + }, + { + "step": 336, + "loss": 0.26082637906074524, + "objective": 0.26082637906074524, + "error": 0.1220703125, + "gradient_norm": 0.048336997628211975, + "elapsed": 262.33449625968933 + }, + { + "step": 352, + "loss": 0.5959363579750061, + "objective": 0.5959363579750061, + "error": 0.3388671875, + "gradient_norm": 0.06797357648611069, + "elapsed": 271.9942307472229 + }, + { + "step": 368, + "loss": 0.48994284868240356, + "objective": 0.48994284868240356, + "error": 0.2587890625, + "gradient_norm": 0.06296153366565704, + "elapsed": 283.0493588447571 + }, + { + "step": 384, + "loss": 0.5710494518280029, + "objective": 0.5710494518280029, + "error": 0.3134765625, + "gradient_norm": 0.045333269983530045, + "elapsed": 294.64637446403503 + }, + { + "step": 400, + "loss": 0.5957783460617065, + "objective": 0.5957783460617065, + "error": 0.349609375, + "gradient_norm": 0.03918786719441414, + "elapsed": 307.6200888156891 + }, + { + "step": 416, + "loss": 0.27521568536758423, + "objective": 0.27521568536758423, + "error": 0.1220703125, + "gradient_norm": 0.038001637905836105, + "elapsed": 317.01610231399536 + }, + { + "step": 432, + "loss": 0.02379823848605156, + "objective": 0.02379823848605156, + "error": 0.0078125, + "gradient_norm": 0.007661945186555386, + "elapsed": 326.9360330104828 + }, + { + "step": 448, + "loss": 0.56734299659729, + "objective": 0.56734299659729, + "error": 0.3271484375, + "gradient_norm": 0.057416290044784546, + "elapsed": 339.6289041042328 + }, + { + "step": 464, + "loss": 0.10715995728969574, + "objective": 0.10715995728969574, + "error": 0.0380859375, + "gradient_norm": 0.02532491274178028, + "elapsed": 349.8584108352661 + }, + { + "step": 480, + "loss": 0.6143364310264587, + "objective": 0.6143364310264587, + "error": 0.36328125, + "gradient_norm": 0.08023032546043396, + "elapsed": 360.36362075805664 + }, + { + "step": 496, + "loss": 0.44069671630859375, + "objective": 0.44069671630859375, + "error": 0.2197265625, + "gradient_norm": 0.048025116324424744, + "elapsed": 369.48225808143616 + }, + { + "step": 512, + "loss": 0.019900165498256683, + "objective": 0.019900165498256683, + "error": 0.0107421875, + "gradient_norm": 0.0038635791279375553, + "elapsed": 378.59970593452454 + }, + { + "step": 528, + "loss": 0.033316534012556076, + "objective": 0.033316534012556076, + "error": 0.009765625, + "gradient_norm": 0.009174940176308155, + "elapsed": 393.4021761417389 + }, + { + "step": 544, + "loss": 0.41130945086479187, + "objective": 0.41130945086479187, + "error": 0.20703125, + "gradient_norm": 0.04695262759923935, + "elapsed": 402.8586280345917 + }, + { + "step": 560, + "loss": 0.5885373950004578, + "objective": 0.5885373950004578, + "error": 0.3544921875, + "gradient_norm": 0.08534500002861023, + "elapsed": 416.98661041259766 + }, + { + "step": 576, + "loss": 0.3804720640182495, + "objective": 0.3804720640182495, + "error": 0.19140625, + "gradient_norm": 0.05163278803229332, + "elapsed": 427.7550480365753 + }, + { + "step": 592, + "loss": 0.6101120710372925, + "objective": 0.6101120710372925, + "error": 0.3525390625, + "gradient_norm": 0.05593184754252434, + "elapsed": 441.05026268959045 + }, + { + "step": 608, + "loss": 0.5586092472076416, + "objective": 0.5586092472076416, + "error": 0.302734375, + "gradient_norm": 0.07458740472793579, + "elapsed": 452.95383286476135 + }, + { + "step": 624, + "loss": 0.5992780923843384, + "objective": 0.5992780923843384, + "error": 0.357421875, + "gradient_norm": 0.03618372976779938, + "elapsed": 466.1582691669464 + }, + { + "step": 640, + "loss": 0.3536975383758545, + "objective": 0.3536975383758545, + "error": 0.1650390625, + "gradient_norm": 0.05353165790438652, + "elapsed": 477.166255235672 + }, + { + "step": 656, + "loss": 0.4926893711090088, + "objective": 0.4926893711090088, + "error": 0.2626953125, + "gradient_norm": 0.05201377719640732, + "elapsed": 491.1417751312256 + }, + { + "step": 672, + "loss": 0.5754991173744202, + "objective": 0.5754991173744202, + "error": 0.3271484375, + "gradient_norm": 0.08167096972465515, + "elapsed": 501.630366563797 + }, + { + "step": 688, + "loss": 0.5685014724731445, + "objective": 0.5685014724731445, + "error": 0.333984375, + "gradient_norm": 0.043775107711553574, + "elapsed": 514.2880456447601 + }, + { + "step": 704, + "loss": 0.022465089336037636, + "objective": 0.022465089336037636, + "error": 0.0068359375, + "gradient_norm": 0.010172540321946144, + "elapsed": 522.9173214435577 + }, + { + "step": 720, + "loss": 0.035460107028484344, + "objective": 0.035460107028484344, + "error": 0.0107421875, + "gradient_norm": 0.010515578091144562, + "elapsed": 532.8470129966736 + }, + { + "step": 736, + "loss": 0.44765588641166687, + "objective": 0.44765588641166687, + "error": 0.2138671875, + "gradient_norm": 0.09050357341766357, + "elapsed": 541.9488840103149 + }, + { + "step": 752, + "loss": 0.5933939218521118, + "objective": 0.5933939218521118, + "error": 0.3359375, + "gradient_norm": 0.0665116235613823, + "elapsed": 552.9967355728149 + }, + { + "step": 768, + "loss": 0.6100764870643616, + "objective": 0.6100764870643616, + "error": 0.3515625, + "gradient_norm": 0.0821211114525795, + "elapsed": 563.7709202766418 + }, + { + "step": 784, + "loss": 0.02964692935347557, + "objective": 0.02964692935347557, + "error": 0.009765625, + "gradient_norm": 0.012663272209465504, + "elapsed": 573.1517221927643 + }, + { + "step": 800, + "loss": 0.38091832399368286, + "objective": 0.38091832399368286, + "error": 0.1904296875, + "gradient_norm": 0.060622021555900574, + "elapsed": 582.5687477588654 + }, + { + "step": 816, + "loss": 0.552335262298584, + "objective": 0.552335262298584, + "error": 0.3076171875, + "gradient_norm": 0.14419035613536835, + "elapsed": 594.4292685985565 + }, + { + "step": 832, + "loss": 0.5943340063095093, + "objective": 0.5943340063095093, + "error": 0.34375, + "gradient_norm": 0.0633513554930687, + "elapsed": 605.2052299976349 + }, + { + "step": 848, + "loss": 0.6074100732803345, + "objective": 0.6074100732803345, + "error": 0.3486328125, + "gradient_norm": 0.04225531220436096, + "elapsed": 614.8996202945709 + }, + { + "step": 864, + "loss": 0.6198879480361938, + "objective": 0.6198879480361938, + "error": 0.361328125, + "gradient_norm": 0.04208856821060181, + "elapsed": 625.4266908168793 + }, + { + "step": 880, + "loss": 0.6151762008666992, + "objective": 0.6151762008666992, + "error": 0.369140625, + "gradient_norm": 0.06261089444160461, + "elapsed": 636.0696911811829 + }, + { + "step": 896, + "loss": 0.49680083990097046, + "objective": 0.49680083990097046, + "error": 0.25390625, + "gradient_norm": 0.0827067643404007, + "elapsed": 644.6893246173859 + }, + { + "step": 912, + "loss": 0.4610927402973175, + "objective": 0.4610927402973175, + "error": 0.23828125, + "gradient_norm": 0.06652095168828964, + "elapsed": 655.969132900238 + }, + { + "step": 928, + "loss": 0.5218505859375, + "objective": 0.5218505859375, + "error": 0.2685546875, + "gradient_norm": 0.07188194245100021, + "elapsed": 667.5352523326874 + }, + { + "step": 944, + "loss": 0.33009427785873413, + "objective": 0.33009427785873413, + "error": 0.1533203125, + "gradient_norm": 0.05718810483813286, + "elapsed": 677.8397319316864 + }, + { + "step": 960, + "loss": 0.5703234672546387, + "objective": 0.5703234672546387, + "error": 0.3193359375, + "gradient_norm": 0.11168288439512253, + "elapsed": 687.8742904663086 + }, + { + "step": 976, + "loss": 0.025548014789819717, + "objective": 0.025548014789819717, + "error": 0.0107421875, + "gradient_norm": 0.009453393518924713, + "elapsed": 698.294285774231 + }, + { + "step": 992, + "loss": 0.45398157835006714, + "objective": 0.45398157835006714, + "error": 0.2412109375, + "gradient_norm": 0.04607952758669853, + "elapsed": 707.903199672699 + }, + { + "step": 1008, + "loss": 0.3412189781665802, + "objective": 0.3412189781665802, + "error": 0.1513671875, + "gradient_norm": 0.0432075597345829, + "elapsed": 718.5662748813629 + }, + { + "step": 1024, + "loss": 0.4376429319381714, + "objective": 0.4376429319381714, + "error": 0.2275390625, + "gradient_norm": 0.07974351197481155, + "elapsed": 728.8954858779907 + }, + { + "step": 1040, + "loss": 0.33512815833091736, + "objective": 0.33512815833091736, + "error": 0.150390625, + "gradient_norm": 0.04476875811815262, + "elapsed": 744.0822694301605 + }, + { + "step": 1056, + "loss": 0.5214208364486694, + "objective": 0.5214208364486694, + "error": 0.283203125, + "gradient_norm": 0.08898192644119263, + "elapsed": 755.1484262943268 + }, + { + "step": 1072, + "loss": 0.13849599659442902, + "objective": 0.13849599659442902, + "error": 0.052734375, + "gradient_norm": 0.028359953314065933, + "elapsed": 764.3303108215332 + }, + { + "step": 1088, + "loss": 0.323838472366333, + "objective": 0.323838472366333, + "error": 0.1435546875, + "gradient_norm": 0.04081716760993004, + "elapsed": 773.2739362716675 + }, + { + "step": 1104, + "loss": 0.5627881288528442, + "objective": 0.5627881288528442, + "error": 0.3125, + "gradient_norm": 0.08322097361087799, + "elapsed": 784.7223973274231 + }, + { + "step": 1120, + "loss": 0.44111010432243347, + "objective": 0.44111010432243347, + "error": 0.2216796875, + "gradient_norm": 0.05700977146625519, + "elapsed": 795.085648059845 + }, + { + "step": 1136, + "loss": 0.6395992040634155, + "objective": 0.6395992040634155, + "error": 0.39453125, + "gradient_norm": 0.0744553729891777, + "elapsed": 805.7942585945129 + }, + { + "step": 1152, + "loss": 0.5433304309844971, + "objective": 0.5433304309844971, + "error": 0.287109375, + "gradient_norm": 0.04814797267317772, + "elapsed": 817.3382890224457 + }, + { + "step": 1168, + "loss": 0.5708576440811157, + "objective": 0.5708576440811157, + "error": 0.3203125, + "gradient_norm": 0.051331400871276855, + "elapsed": 829.288791179657 + }, + { + "step": 1184, + "loss": 0.5447035431861877, + "objective": 0.5447035431861877, + "error": 0.2939453125, + "gradient_norm": 0.10116687417030334, + "elapsed": 839.6822843551636 + }, + { + "step": 1200, + "loss": 0.6125671863555908, + "objective": 0.6125671863555908, + "error": 0.3642578125, + "gradient_norm": 0.04368080571293831, + "elapsed": 850.2262740135193 + }, + { + "step": 1216, + "loss": 0.5002380609512329, + "objective": 0.5002380609512329, + "error": 0.259765625, + "gradient_norm": 0.04939017817378044, + "elapsed": 862.3783452510834 + }, + { + "step": 1232, + "loss": 0.5698772668838501, + "objective": 0.5698772668838501, + "error": 0.3173828125, + "gradient_norm": 0.04916854575276375, + "elapsed": 871.4622664451599 + }, + { + "step": 1248, + "loss": 0.6046518683433533, + "objective": 0.6046518683433533, + "error": 0.341796875, + "gradient_norm": 0.04919794574379921, + "elapsed": 883.3905737400055 + }, + { + "step": 1264, + "loss": 0.5913128852844238, + "objective": 0.5913128852844238, + "error": 0.357421875, + "gradient_norm": 0.046917904168367386, + "elapsed": 892.4264807701111 + }, + { + "step": 1280, + "loss": 0.5027461051940918, + "objective": 0.5027461051940918, + "error": 0.2626953125, + "gradient_norm": 0.04705750197172165, + "elapsed": 902.5875842571259 + }, + { + "step": 1296, + "loss": 0.13519814610481262, + "objective": 0.13519814610481262, + "error": 0.052734375, + "gradient_norm": 0.02625490538775921, + "elapsed": 912.4087471961975 + }, + { + "step": 1312, + "loss": 0.5862359404563904, + "objective": 0.5862359404563904, + "error": 0.3271484375, + "gradient_norm": 0.05441493168473244, + "elapsed": 923.992555141449 + }, + { + "step": 1328, + "loss": 0.6031408309936523, + "objective": 0.6031408309936523, + "error": 0.3505859375, + "gradient_norm": 0.05901554971933365, + "elapsed": 933.3936491012573 + }, + { + "step": 1344, + "loss": 0.5823733806610107, + "objective": 0.5823733806610107, + "error": 0.3310546875, + "gradient_norm": 0.0842989832162857, + "elapsed": 941.979998588562 + }, + { + "step": 1360, + "loss": 0.6241492033004761, + "objective": 0.6241492033004761, + "error": 0.3720703125, + "gradient_norm": 0.04446673393249512, + "elapsed": 954.969649553299 + }, + { + "step": 1376, + "loss": 0.5829156637191772, + "objective": 0.5829156637191772, + "error": 0.361328125, + "gradient_norm": 0.06615480780601501, + "elapsed": 966.0245676040649 + }, + { + "step": 1392, + "loss": 0.5968320369720459, + "objective": 0.5968320369720459, + "error": 0.34765625, + "gradient_norm": 0.05093541368842125, + "elapsed": 975.1022663116455 + }, + { + "step": 1408, + "loss": 0.045559000223875046, + "objective": 0.045559000223875046, + "error": 0.01171875, + "gradient_norm": 0.02514980360865593, + "elapsed": 987.2391452789307 + }, + { + "step": 1424, + "loss": 0.22601813077926636, + "objective": 0.22601813077926636, + "error": 0.09765625, + "gradient_norm": 0.04834206402301788, + "elapsed": 996.4583384990692 + }, + { + "step": 1440, + "loss": 0.23011144995689392, + "objective": 0.23011144995689392, + "error": 0.111328125, + "gradient_norm": 0.050687842071056366, + "elapsed": 1007.1440904140472 + }, + { + "step": 1456, + "loss": 0.018240466713905334, + "objective": 0.018240466713905334, + "error": 0.0078125, + "gradient_norm": 0.005604141391813755, + "elapsed": 1016.4502851963043 + }, + { + "step": 1472, + "loss": 0.4498720169067383, + "objective": 0.4498720169067383, + "error": 0.232421875, + "gradient_norm": 0.08179625123739243, + "elapsed": 1028.8303294181824 + }, + { + "step": 1488, + "loss": 0.24151627719402313, + "objective": 0.24151627719402313, + "error": 0.107421875, + "gradient_norm": 0.03838668763637543, + "elapsed": 1037.8867321014404 + }, + { + "step": 1504, + "loss": 0.46122002601623535, + "objective": 0.46122002601623535, + "error": 0.232421875, + "gradient_norm": 0.0726623386144638, + "elapsed": 1047.7258644104004 + }, + { + "step": 1520, + "loss": 0.5085602402687073, + "objective": 0.5085602402687073, + "error": 0.2705078125, + "gradient_norm": 0.06673175096511841, + "elapsed": 1059.352120399475 + }, + { + "step": 1536, + "loss": 0.6105246543884277, + "objective": 0.6105246543884277, + "error": 0.3818359375, + "gradient_norm": 0.04271261766552925, + "elapsed": 1070.1413230895996 + }, + { + "step": 1552, + "loss": 0.4792126417160034, + "objective": 0.4792126417160034, + "error": 0.2578125, + "gradient_norm": 0.05200039595365524, + "elapsed": 1086.444006204605 + }, + { + "step": 1568, + "loss": 0.5814266204833984, + "objective": 0.5814266204833984, + "error": 0.330078125, + "gradient_norm": 0.05867309868335724, + "elapsed": 1097.2902619838715 + }, + { + "step": 1584, + "loss": 0.6321226358413696, + "objective": 0.6321226358413696, + "error": 0.3798828125, + "gradient_norm": 0.05418067052960396, + "elapsed": 1107.9767682552338 + }, + { + "step": 1600, + "loss": 0.5931253433227539, + "objective": 0.5931253433227539, + "error": 0.3603515625, + "gradient_norm": 0.06396215409040451, + "elapsed": 1121.782609462738 + }, + { + "step": 1616, + "loss": 0.6411516666412354, + "objective": 0.6411516666412354, + "error": 0.38671875, + "gradient_norm": 0.05035768821835518, + "elapsed": 1132.7197887897491 + }, + { + "step": 1632, + "loss": 0.4267754852771759, + "objective": 0.4267754852771759, + "error": 0.2080078125, + "gradient_norm": 0.09109894186258316, + "elapsed": 1139.1667578220367 + }, + { + "step": 1648, + "loss": 0.21246182918548584, + "objective": 0.21246182918548584, + "error": 0.095703125, + "gradient_norm": 0.04478950425982475, + "elapsed": 1149.1183021068573 + }, + { + "step": 1664, + "loss": 0.46360665559768677, + "objective": 0.46360665559768677, + "error": 0.251953125, + "gradient_norm": 0.07668188214302063, + "elapsed": 1161.1197745800018 + }, + { + "step": 1680, + "loss": 0.46281397342681885, + "objective": 0.46281397342681885, + "error": 0.236328125, + "gradient_norm": 0.07954126596450806, + "elapsed": 1171.8474535942078 + }, + { + "step": 1696, + "loss": 0.2484058141708374, + "objective": 0.2484058141708374, + "error": 0.12109375, + "gradient_norm": 0.047261305153369904, + "elapsed": 1185.6542596817017 + }, + { + "step": 1712, + "loss": 0.24310235679149628, + "objective": 0.24310235679149628, + "error": 0.1064453125, + "gradient_norm": 0.07262872904539108, + "elapsed": 1197.8986082077026 + }, + { + "step": 1728, + "loss": 0.009729458019137383, + "objective": 0.009729458019137383, + "error": 0.001953125, + "gradient_norm": 0.01146845705807209, + "elapsed": 1208.495581150055 + }, + { + "step": 1744, + "loss": 0.24568752944469452, + "objective": 0.24568752944469452, + "error": 0.10546875, + "gradient_norm": 0.05830742046236992, + "elapsed": 1219.9394850730896 + }, + { + "step": 1760, + "loss": 0.022546378895640373, + "objective": 0.022546378895640373, + "error": 0.0068359375, + "gradient_norm": 0.007667526602745056, + "elapsed": 1229.5703229904175 + }, + { + "step": 1776, + "loss": 0.5848401784896851, + "objective": 0.5848401784896851, + "error": 0.3271484375, + "gradient_norm": 0.061901818960905075, + "elapsed": 1238.750280380249 + }, + { + "step": 1792, + "loss": 0.6031335592269897, + "objective": 0.6031335592269897, + "error": 0.3671875, + "gradient_norm": 0.0676632970571518, + "elapsed": 1247.7468683719635 + }, + { + "step": 1808, + "loss": 0.6210961937904358, + "objective": 0.6210961937904358, + "error": 0.3603515625, + "gradient_norm": 0.0718468651175499, + "elapsed": 1256.1821897029877 + }, + { + "step": 1824, + "loss": 0.570877730846405, + "objective": 0.570877730846405, + "error": 0.3212890625, + "gradient_norm": 0.05575930327177048, + "elapsed": 1266.4091975688934 + }, + { + "step": 1840, + "loss": 0.5711429119110107, + "objective": 0.5711429119110107, + "error": 0.31640625, + "gradient_norm": 0.0691002607345581, + "elapsed": 1277.4722146987915 + }, + { + "step": 1856, + "loss": 0.36046335101127625, + "objective": 0.36046335101127625, + "error": 0.16796875, + "gradient_norm": 0.04694395884871483, + "elapsed": 1287.1420249938965 + }, + { + "step": 1872, + "loss": 0.4688999652862549, + "objective": 0.4688999652862549, + "error": 0.2216796875, + "gradient_norm": 0.07401346415281296, + "elapsed": 1297.3945078849792 + }, + { + "step": 1888, + "loss": 0.46385282278060913, + "objective": 0.46385282278060913, + "error": 0.2373046875, + "gradient_norm": 0.05608939751982689, + "elapsed": 1305.9779334068298 + }, + { + "step": 1904, + "loss": 0.60875403881073, + "objective": 0.60875403881073, + "error": 0.365234375, + "gradient_norm": 0.05085878074169159, + "elapsed": 1317.3097081184387 + }, + { + "step": 1920, + "loss": 0.12223530560731888, + "objective": 0.12223530560731888, + "error": 0.0458984375, + "gradient_norm": 0.024870412424206734, + "elapsed": 1328.6486887931824 + }, + { + "step": 1936, + "loss": 0.3486189544200897, + "objective": 0.3486189544200897, + "error": 0.16796875, + "gradient_norm": 0.04780663549900055, + "elapsed": 1336.6701011657715 + }, + { + "step": 1952, + "loss": 0.5777363777160645, + "objective": 0.5777363777160645, + "error": 0.3427734375, + "gradient_norm": 0.0571451336145401, + "elapsed": 1346.9158833026886 + }, + { + "step": 1968, + "loss": 0.39320266246795654, + "objective": 0.39320266246795654, + "error": 0.1884765625, + "gradient_norm": 0.05673858895897865, + "elapsed": 1354.9182631969452 + }, + { + "step": 1984, + "loss": 0.5900611281394958, + "objective": 0.5900611281394958, + "error": 0.3349609375, + "gradient_norm": 0.06593932211399078, + "elapsed": 1364.2754452228546 + }, + { + "step": 2000, + "loss": 0.6212430000305176, + "objective": 0.6212430000305176, + "error": 0.3857421875, + "gradient_norm": 0.040818918496370316, + "elapsed": 1374.7192046642303 + }, + { + "step": 2016, + "loss": 0.15605247020721436, + "objective": 0.15605247020721436, + "error": 0.0556640625, + "gradient_norm": 0.03108786791563034, + "elapsed": 1386.2740807533264 + }, + { + "step": 2032, + "loss": 0.22049596905708313, + "objective": 0.22049596905708313, + "error": 0.1015625, + "gradient_norm": 0.042733557522296906, + "elapsed": 1396.6422457695007 + }, + { + "step": 2048, + "loss": 0.5642613172531128, + "objective": 0.5642613172531128, + "error": 0.306640625, + "gradient_norm": 0.07527482509613037, + "elapsed": 1407.6688070297241 + } + ] + }, + "training_source_snapshot": "training_sources/full3_1", + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with the recorded physical decoder.", + "physical_prediction_reference": "/run-state/workspace/research/context_upgrades/turbo1/predictions", + "prior_pass": 3, + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.2338341346153846, + "512": 0.2336688701923077, + "blend-512": 0.23399939903846154, + "1024": 0.23329326923076923, + "blend-1024": 0.23342848557692306, + "1536": 0.2330679086538462, + "blend-1536": 0.23291766826923077, + "2048": 0.2335186298076923, + "blend-2048": 0.23290264423076928 + }, + "selected": "blend-2048" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22182992788461542, + "512": 0.22143930288461539, + "blend-512": 0.22125901442307694, + "1024": 0.22104867788461538, + "blend-1024": 0.22079326923076922, + "1536": 0.22017728365384615, + "blend-1536": 0.22095853365384618, + "2048": 0.22076322115384617, + "blend-2048": 0.22025240384615385 + }, + "selected": "1536" + } + ], + "checkpoints": { + "2048": { + "step": 2048, + "training_samples": 2097152, + "unique_training_rows_seen_in_this_phase": 507282, + "weights_sha256": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5", + "complete": true + }, + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 490266, + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "complete": true + } + }, + "runtime": "Share physical priors when the conditioning pass and regime agree; otherwise recompute the neural prior independently. Last-only physical branches omit logical tracking in intermediate passes when intermediate probabilities are unused.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false, + "numerical_controls": { + "gpu_gradient_control.json": { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "data": "First1024 rows of the authorized4096 training sample; no validation labels", + "weights": "Random scratch parameters, seed20261112; gradients only, no parameter update", + "block_size": 32, + "records": [ + { + "batch": 256, + "seconds_per_gradient": 0.38611968358357746, + "shots_per_second": 663.0068625977924, + "memory_stats": { + "num_allocs": 694, + "bytes_in_use": 306432, + "peak_bytes_in_use": 3054084608, + "largest_alloc_size": 3047267584, + "bytes_limit": 76526240993, + "bytes_reserved": 0, + "peak_bytes_reserved": 0, + "largest_free_block_bytes": 0, + "pool_bytes": 76526240768, + "peak_pool_bytes": 76526240768 + } + }, + { + "batch": 512, + "seconds_per_gradient": 0.6622018814086914, + "shots_per_second": 773.178111350017, + "memory_stats": { + "num_allocs": 1332, + "bytes_in_use": 308480, + "peak_bytes_in_use": 6079704832, + "largest_alloc_size": 6069432576, + "bytes_limit": 76526240993, + "bytes_reserved": 0, + "peak_bytes_reserved": 0, + "largest_free_block_bytes": 0, + "pool_bytes": 76526240768, + "peak_pool_bytes": 76526240768 + } + }, + { + "batch": 1024, + "seconds_per_gradient": 1.117707888285319, + "shots_per_second": 916.1606630252231, + "memory_stats": { + "num_allocs": 1970, + "bytes_in_use": 312576, + "peak_bytes_in_use": 12138994176, + "largest_alloc_size": 12122019840, + "bytes_limit": 76526240993, + "bytes_reserved": 0, + "peak_bytes_reserved": 0, + "largest_free_block_bytes": 0, + "pool_bytes": 76526240768, + "peak_pool_bytes": 76526240768 + } + } + ], + "original_gradient_gpu_control": { + "loss_max_difference": 1.6689300537109375e-06, + "prediction_max_difference": 1.0132789611816406e-06, + "neural_gradient_relative_difference": 5.505155786522664e-05, + "float64_precision_audit": "/run-state/workspace/research/learned_d5/full3_1/gpu_gradient_precision.json", + "tolerance_rationale": "Original3e-5 GPU gradient threshold failed at5.51e-5. Independent float64 audits of both float32 algorithms across six X/Z durations found comparable relative rounding errors up to5.72e-5, with probability errors below6.2e-7. Use1e-4 relative for this accumulated derivative." + } + }, + "gpu_gradient_precision.json": { + "data": "First16 supplied training rows per listed condition; no parameter updates", + "weights": "full3_1/weights-1536.npz", + "reference": "Original unblocked algorithm in float64, fixed float32 neural edge probabilities", + "source_sha256": { + "gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8" + }, + "initial_gpu_control_failure": { + "relative_neural_gradient_difference": 5.505155786522664e-05, + "original_tolerance": 3e-05, + "maximum_loss_difference": 1.6689300537109375e-06, + "maximum_prediction_difference": 1.0132789611816406e-06 + }, + "records": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "training_rows": 16, + "reference_neural_gradient_norm": 0.30205945019442737, + "unblocked_float32": { + "maximum_loss_error": 2.966804864001915e-07, + "maximum_probability_error": 9.592670685565352e-08, + "neural_gradient_maximum_absolute_error": 1.6391277313232422e-07, + "neural_gradient_relative_error": 3.6604459916077934e-06, + "neural_gradient_cosine": 0.9999999999933656 + }, + "blocked_float32": { + "maximum_loss_error": 1.7747119684941026e-07, + "maximum_probability_error": 8.879568846875685e-08, + "neural_gradient_maximum_absolute_error": 1.7881393432617188e-07, + "neural_gradient_relative_error": 4.366049097416422e-06, + "neural_gradient_cosine": 0.9999999999904692 + } + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "training_rows": 16, + "reference_neural_gradient_norm": 0.22069588396473294, + "unblocked_float32": { + "maximum_loss_error": 5.498523059088711e-07, + "maximum_probability_error": 9.703680636796719e-08, + "neural_gradient_maximum_absolute_error": 6.686605047434568e-08, + "neural_gradient_relative_error": 2.392500410145668e-06, + "neural_gradient_cosine": 0.999999999997144 + }, + "blocked_float32": { + "maximum_loss_error": 8.745212829311194e-08, + "maximum_probability_error": 6.418482079162402e-08, + "neural_gradient_maximum_absolute_error": 6.705522537231445e-08, + "neural_gradient_relative_error": 1.7739189351699108e-06, + "neural_gradient_cosine": 0.9999999999984265 + } + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "training_rows": 16, + "reference_neural_gradient_norm": 0.4664494516878606, + "unblocked_float32": { + "maximum_loss_error": 3.922858555771569e-07, + "maximum_probability_error": 2.581999101192167e-07, + "neural_gradient_maximum_absolute_error": 1.7015263438224792e-06, + "neural_gradient_relative_error": 2.234804892316077e-05, + "neural_gradient_cosine": 0.9999999997509151 + }, + "blocked_float32": { + "maximum_loss_error": 3.3479861938356947e-07, + "maximum_probability_error": 1.4954284288659636e-07, + "neural_gradient_maximum_absolute_error": 1.6633421182632446e-06, + "neural_gradient_relative_error": 2.4167285966292737e-05, + "neural_gradient_cosine": 0.9999999997089409 + } + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "training_rows": 16, + "reference_neural_gradient_norm": 0.438354906018253, + "unblocked_float32": { + "maximum_loss_error": 6.361644384611509e-07, + "maximum_probability_error": 3.6173952677742705e-07, + "neural_gradient_maximum_absolute_error": 1.9436702132225037e-06, + "neural_gradient_relative_error": 5.252014500992631e-05, + "neural_gradient_cosine": 0.9999999986254251 + }, + "blocked_float32": { + "maximum_loss_error": 5.060161181180689e-07, + "maximum_probability_error": 2.589724067414423e-07, + "neural_gradient_maximum_absolute_error": 1.946929842233658e-06, + "neural_gradient_relative_error": 5.71756656511251e-05, + "neural_gradient_cosine": 0.999999998372327 + } + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "training_rows": 16, + "reference_neural_gradient_norm": 0.3057787329709659, + "unblocked_float32": { + "maximum_loss_error": 6.74491174690317e-07, + "maximum_probability_error": 4.3885854938974234e-07, + "neural_gradient_maximum_absolute_error": 8.174683898687363e-07, + "neural_gradient_relative_error": 4.090547224844183e-05, + "neural_gradient_cosine": 0.9999999991633716 + }, + "blocked_float32": { + "maximum_loss_error": 6.643292806973733e-07, + "maximum_probability_error": 4.835620329712853e-07, + "neural_gradient_maximum_absolute_error": 1.1210795491933823e-06, + "neural_gradient_relative_error": 5.584921905818847e-05, + "neural_gradient_cosine": 0.9999999984491473 + } + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "training_rows": 16, + "reference_neural_gradient_norm": 0.2501411033127809, + "unblocked_float32": { + "maximum_loss_error": 1.167099820564843e-06, + "maximum_probability_error": 4.921027032533942e-07, + "neural_gradient_maximum_absolute_error": 7.14324414730072e-07, + "neural_gradient_relative_error": 4.528117886548381e-05, + "neural_gradient_cosine": 0.9999999989770499 + }, + "blocked_float32": { + "maximum_loss_error": 1.4055183996664056e-06, + "maximum_probability_error": 6.113119928041755e-07, + "neural_gradient_maximum_absolute_error": 7.075723260641098e-07, + "neural_gradient_relative_error": 5.112087336342683e-05, + "neural_gradient_cosine": 0.9999999986947755 + } + } + ], + "status": "passed" + } + } + }, + { + "training": { + "initialization": "Uniform parameter averages of checkpoints from the same session-initialized training trajectory; no external weights", + "prior_pass": 3, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "hidden_width": 64, + "training": "No new optimizer updates; all learning comes from the recorded source trajectory and its session-trained parent", + "optimizer_updates_in_derived_run": 0, + "source_training_provenance": { + "initialization": "Continue from the recorded session-trained checkpoint; original random initialization seed 20261108", + "prior_pass": 3, + "initial_seed": 20261108, + "training_source_sha256": { + "learned_d5__train.py": "b73af9da21332dee9a43f653b514695b020fbc3516604b2e721d8cf0ea876d53", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "5e9420df1f6dd56518925e910096fb9bc93bd796a5933b13bf894a1a96256cdf", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "All supplied training shots per each of all26 d5 conditions; uniform condition and within-condition sampling for optimizer batches.", + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 516880, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 507282, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 19592, + "surface_code_bX_d5_r03_center_5_5": 19646, + "surface_code_bX_d5_r05_center_5_5": 19513, + "surface_code_bX_d5_r07_center_5_5": 19341, + "surface_code_bX_d5_r09_center_5_5": 19211, + "surface_code_bX_d5_r11_center_5_5": 19239, + "surface_code_bX_d5_r13_center_5_5": 19679, + "surface_code_bX_d5_r15_center_5_5": 19455, + "surface_code_bX_d5_r17_center_5_5": 19479, + "surface_code_bX_d5_r19_center_5_5": 19479, + "surface_code_bX_d5_r21_center_5_5": 19551, + "surface_code_bX_d5_r23_center_5_5": 19586, + "surface_code_bX_d5_r25_center_5_5": 19526, + "surface_code_bZ_d5_r01_center_5_5": 19652, + "surface_code_bZ_d5_r03_center_5_5": 19732, + "surface_code_bZ_d5_r05_center_5_5": 19754, + "surface_code_bZ_d5_r07_center_5_5": 19194, + "surface_code_bZ_d5_r09_center_5_5": 19641, + "surface_code_bZ_d5_r11_center_5_5": 19611, + "surface_code_bZ_d5_r13_center_5_5": 19424, + "surface_code_bZ_d5_r15_center_5_5": 19380, + "surface_code_bZ_d5_r17_center_5_5": 19384, + "surface_code_bZ_d5_r19_center_5_5": 19684, + "surface_code_bZ_d5_r21_center_5_5": 19559, + "surface_code_bZ_d5_r23_center_5_5": 19524, + "surface_code_bZ_d5_r25_center_5_5": 19446 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 2048, + "batch": 1024, + "learning_rate": 0.0005, + "sampling_seed": 20261113, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": true, + "rng_restored": true, + "sampling_state_source": "/run-state/workspace/research/learned_d5/feedback3_pilot/rng-768.json", + "starting_checkpoint": "/run-state/workspace/research/learned_d5/feedback3_pilot/weights-768.npz", + "starting_checkpoint_sha256": "bc2ba1c529317ce1b5b661efae4707eca49c6995d6f22b04193fe7642662fed8", + "starting_training_provenance": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261108", + "prior_pass": 3, + "initial_seed": 20261108, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "4096 training shots per each of all 26 d5 conditions, sampled without replacement with seed 20261023. Uniform condition and within-condition sampling for optimizer batches.", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1024, + "batch": 256, + "learning_rate": 0.001, + "sampling_seed": 20261108, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "starting_checkpoint": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.011146659031510353, + "error": 0.00390625, + "gradient_norm": 0.011240893043577671, + "elapsed": 21.276997089385986 + }, + { + "step": 16, + "loss": 0.645737886428833, + "error": 0.40625, + "gradient_norm": 0.1628236621618271, + "elapsed": 25.872907638549805 + }, + { + "step": 32, + "loss": 0.574029803276062, + "error": 0.35546875, + "gradient_norm": 0.3000081777572632, + "elapsed": 30.761418342590332 + }, + { + "step": 48, + "loss": 0.574467122554779, + "error": 0.296875, + "gradient_norm": 0.24150623381137848, + "elapsed": 35.67650651931763 + }, + { + "step": 64, + "loss": 0.6003620624542236, + "error": 0.35546875, + "gradient_norm": 0.07430054992437363, + "elapsed": 40.60572576522827 + }, + { + "step": 80, + "loss": 0.5429091453552246, + "error": 0.33203125, + "gradient_norm": 0.15341751277446747, + "elapsed": 45.546849727630615 + }, + { + "step": 96, + "loss": 0.368771493434906, + "error": 0.1640625, + "gradient_norm": 0.08923184871673584, + "elapsed": 50.49156332015991 + }, + { + "step": 112, + "loss": 0.516342043876648, + "error": 0.265625, + "gradient_norm": 0.10965219140052795, + "elapsed": 55.45058846473694 + }, + { + "step": 128, + "loss": 0.5925382971763611, + "error": 0.37109375, + "gradient_norm": 0.055406324565410614, + "elapsed": 60.40891766548157 + }, + { + "step": 144, + "loss": 0.19184258580207825, + "error": 0.07421875, + "gradient_norm": 0.07042146474123001, + "elapsed": 65.33323669433594 + }, + { + "step": 160, + "loss": 0.5202382206916809, + "error": 0.25390625, + "gradient_norm": 0.14782382547855377, + "elapsed": 70.26605796813965 + }, + { + "step": 176, + "loss": 0.46083134412765503, + "error": 0.22265625, + "gradient_norm": 0.09074779599905014, + "elapsed": 75.18221640586853 + }, + { + "step": 192, + "loss": 0.3054918646812439, + "error": 0.14453125, + "gradient_norm": 0.0588168129324913, + "elapsed": 80.1186010837555 + }, + { + "step": 208, + "loss": 0.4836011230945587, + "error": 0.27734375, + "gradient_norm": 0.09208947420120239, + "elapsed": 85.05764293670654 + }, + { + "step": 224, + "loss": 0.6640600562095642, + "error": 0.38671875, + "gradient_norm": 0.22026506066322327, + "elapsed": 89.98808217048645 + }, + { + "step": 240, + "loss": 0.02421322464942932, + "error": 0.00390625, + "gradient_norm": 0.008131005801260471, + "elapsed": 94.90194272994995 + }, + { + "step": 256, + "loss": 0.6302106976509094, + "error": 0.4296875, + "gradient_norm": 0.09762304276227951, + "elapsed": 99.82612204551697 + }, + { + "step": 272, + "loss": 0.5092596411705017, + "error": 0.27734375, + "gradient_norm": 0.11407691985368729, + "elapsed": 110.44065999984741 + }, + { + "step": 288, + "loss": 0.452798455953598, + "error": 0.2265625, + "gradient_norm": 0.1105576679110527, + "elapsed": 115.36984539031982 + }, + { + "step": 304, + "loss": 0.3378596305847168, + "error": 0.18359375, + "gradient_norm": 0.0841713547706604, + "elapsed": 120.29337763786316 + }, + { + "step": 320, + "loss": 0.6271854639053345, + "error": 0.38671875, + "gradient_norm": 0.1972702294588089, + "elapsed": 125.2231035232544 + }, + { + "step": 336, + "loss": 0.04562236741185188, + "error": 0.01171875, + "gradient_norm": 0.027922745794057846, + "elapsed": 130.14725255966187 + }, + { + "step": 352, + "loss": 0.5342530608177185, + "error": 0.26953125, + "gradient_norm": 0.09031179547309875, + "elapsed": 135.08111095428467 + }, + { + "step": 368, + "loss": 0.49785488843917847, + "error": 0.2578125, + "gradient_norm": 0.19366280734539032, + "elapsed": 140.00699138641357 + }, + { + "step": 384, + "loss": 0.5673326253890991, + "error": 0.30859375, + "gradient_norm": 0.20644932985305786, + "elapsed": 144.92276740074158 + }, + { + "step": 400, + "loss": 0.5581298470497131, + "error": 0.3203125, + "gradient_norm": 0.17668266594409943, + "elapsed": 149.86573243141174 + }, + { + "step": 416, + "loss": 0.5564071536064148, + "error": 0.30078125, + "gradient_norm": 0.0821610689163208, + "elapsed": 154.7953712940216 + }, + { + "step": 432, + "loss": 0.5540086030960083, + "error": 0.34765625, + "gradient_norm": 0.1438807100057602, + "elapsed": 159.72657418251038 + }, + { + "step": 448, + "loss": 0.540939450263977, + "error": 0.29296875, + "gradient_norm": 0.17986361682415009, + "elapsed": 164.6689453125 + }, + { + "step": 464, + "loss": 0.45807865262031555, + "error": 0.25, + "gradient_norm": 0.14453186094760895, + "elapsed": 169.58739304542542 + }, + { + "step": 480, + "loss": 0.5191650390625, + "error": 0.22265625, + "gradient_norm": 0.07955105602741241, + "elapsed": 174.5444438457489 + }, + { + "step": 496, + "loss": 0.1692925989627838, + "error": 0.0703125, + "gradient_norm": 0.07875128090381622, + "elapsed": 179.48035550117493 + }, + { + "step": 512, + "loss": 0.5580664873123169, + "error": 0.3125, + "gradient_norm": 0.27090802788734436, + "elapsed": 184.42834162712097 + }, + { + "step": 528, + "loss": 0.26402050256729126, + "error": 0.13671875, + "gradient_norm": 0.13135771453380585, + "elapsed": 195.17691040039062 + }, + { + "step": 544, + "loss": 0.4352915287017822, + "error": 0.1953125, + "gradient_norm": 0.15959712862968445, + "elapsed": 200.0421543121338 + }, + { + "step": 560, + "loss": 0.22861814498901367, + "error": 0.1015625, + "gradient_norm": 0.08776932209730148, + "elapsed": 204.95144605636597 + }, + { + "step": 576, + "loss": 0.28309381008148193, + "error": 0.1328125, + "gradient_norm": 0.11050742119550705, + "elapsed": 209.8526291847229 + }, + { + "step": 592, + "loss": 0.6409220695495605, + "error": 0.41015625, + "gradient_norm": 0.19826626777648926, + "elapsed": 214.84447717666626 + }, + { + "step": 608, + "loss": 0.25090643763542175, + "error": 0.109375, + "gradient_norm": 0.05864342302083969, + "elapsed": 219.72637391090393 + }, + { + "step": 624, + "loss": 0.11423969268798828, + "error": 0.05078125, + "gradient_norm": 0.05318564549088478, + "elapsed": 224.6331377029419 + }, + { + "step": 640, + "loss": 0.32663431763648987, + "error": 0.1328125, + "gradient_norm": 0.06877780705690384, + "elapsed": 229.5065622329712 + }, + { + "step": 656, + "loss": 0.24196995794773102, + "error": 0.10546875, + "gradient_norm": 0.07683655619621277, + "elapsed": 234.4042534828186 + }, + { + "step": 672, + "loss": 0.5349344611167908, + "error": 0.296875, + "gradient_norm": 0.15214307606220245, + "elapsed": 239.26656579971313 + }, + { + "step": 688, + "loss": 0.26759713888168335, + "error": 0.1171875, + "gradient_norm": 0.14698348939418793, + "elapsed": 244.21049737930298 + }, + { + "step": 704, + "loss": 0.37338894605636597, + "error": 0.18359375, + "gradient_norm": 0.10210632532835007, + "elapsed": 249.13519072532654 + }, + { + "step": 720, + "loss": 0.36807945370674133, + "error": 0.17578125, + "gradient_norm": 0.09668388962745667, + "elapsed": 254.06281065940857 + }, + { + "step": 736, + "loss": 0.3736685514450073, + "error": 0.15625, + "gradient_norm": 0.10987236350774765, + "elapsed": 259.01695108413696 + }, + { + "step": 752, + "loss": 0.5266942977905273, + "error": 0.29296875, + "gradient_norm": 0.09041415899991989, + "elapsed": 263.9530746936798 + }, + { + "step": 768, + "loss": 0.360038161277771, + "error": 0.1640625, + "gradient_norm": 0.10391079634428024, + "elapsed": 268.9019305706024 + }, + { + "step": 784, + "loss": 0.5700286626815796, + "error": 0.34375, + "gradient_norm": 0.12206032127141953, + "elapsed": 279.4174163341522 + }, + { + "step": 800, + "loss": 0.42533689737319946, + "error": 0.20703125, + "gradient_norm": 0.06605375558137894, + "elapsed": 284.3391351699829 + }, + { + "step": 816, + "loss": 0.12355346977710724, + "error": 0.046875, + "gradient_norm": 0.06571663916110992, + "elapsed": 289.2815272808075 + }, + { + "step": 832, + "loss": 0.6411258578300476, + "error": 0.3984375, + "gradient_norm": 0.160088911652565, + "elapsed": 294.2048614025116 + }, + { + "step": 848, + "loss": 0.5756919980049133, + "error": 0.3515625, + "gradient_norm": 0.0962308868765831, + "elapsed": 299.15635418891907 + }, + { + "step": 864, + "loss": 0.2706402540206909, + "error": 0.1171875, + "gradient_norm": 0.11391306668519974, + "elapsed": 304.09321761131287 + }, + { + "step": 880, + "loss": 0.33621329069137573, + "error": 0.1640625, + "gradient_norm": 0.09049320220947266, + "elapsed": 309.0412187576294 + }, + { + "step": 896, + "loss": 0.44343245029449463, + "error": 0.23828125, + "gradient_norm": 0.12484703958034515, + "elapsed": 313.98498797416687 + }, + { + "step": 912, + "loss": 0.5987736582756042, + "error": 0.359375, + "gradient_norm": 0.07541236281394958, + "elapsed": 318.9334623813629 + }, + { + "step": 928, + "loss": 0.38585522770881653, + "error": 0.1875, + "gradient_norm": 0.09290861338376999, + "elapsed": 323.86884689331055 + }, + { + "step": 944, + "loss": 0.4820440113544464, + "error": 0.234375, + "gradient_norm": 0.22198310494422913, + "elapsed": 328.7963180541992 + }, + { + "step": 960, + "loss": 0.07455944269895554, + "error": 0.015625, + "gradient_norm": 0.055282026529312134, + "elapsed": 333.75238251686096 + }, + { + "step": 976, + "loss": 0.013475366868078709, + "error": 0.0078125, + "gradient_norm": 0.009843004867434502, + "elapsed": 338.6403331756592 + }, + { + "step": 992, + "loss": 0.4429199695587158, + "error": 0.2265625, + "gradient_norm": 0.09489083290100098, + "elapsed": 343.5606532096863 + }, + { + "step": 1008, + "loss": 0.4892328381538391, + "error": 0.234375, + "gradient_norm": 0.1342826634645462, + "elapsed": 348.5243353843689 + }, + { + "step": 1024, + "loss": 0.6096819043159485, + "error": 0.32421875, + "gradient_norm": 0.17938998341560364, + "elapsed": 353.36506962776184 + } + ] + }, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.4341062307357788, + "objective": 0.4341062307357788, + "error": 0.208984375, + "gradient_norm": 0.07617632299661636, + "elapsed": 31.45817995071411 + }, + { + "step": 16, + "loss": 0.5996706485748291, + "objective": 0.5996706485748291, + "error": 0.359375, + "gradient_norm": 0.05249844491481781, + "elapsed": 56.34200572967529 + }, + { + "step": 32, + "loss": 0.4388691186904907, + "objective": 0.4388691186904907, + "error": 0.2041015625, + "gradient_norm": 0.0376109778881073, + "elapsed": 67.83739852905273 + }, + { + "step": 48, + "loss": 0.5373439788818359, + "objective": 0.5373439788818359, + "error": 0.2919921875, + "gradient_norm": 0.06261218339204788, + "elapsed": 76.69065475463867 + }, + { + "step": 64, + "loss": 0.24871854484081268, + "objective": 0.24871854484081268, + "error": 0.1162109375, + "gradient_norm": 0.05284671485424042, + "elapsed": 86.3852767944336 + }, + { + "step": 80, + "loss": 0.26628297567367554, + "objective": 0.26628297567367554, + "error": 0.123046875, + "gradient_norm": 0.04054367542266846, + "elapsed": 95.77356100082397 + }, + { + "step": 96, + "loss": 0.48436349630355835, + "objective": 0.48436349630355835, + "error": 0.259765625, + "gradient_norm": 0.05399860441684723, + "elapsed": 107.06293416023254 + }, + { + "step": 112, + "loss": 0.41063767671585083, + "objective": 0.41063767671585083, + "error": 0.1943359375, + "gradient_norm": 0.043602071702480316, + "elapsed": 116.78119611740112 + }, + { + "step": 128, + "loss": 0.3990316390991211, + "objective": 0.3990316390991211, + "error": 0.1865234375, + "gradient_norm": 0.0424419641494751, + "elapsed": 125.6915397644043 + }, + { + "step": 144, + "loss": 0.5119550228118896, + "objective": 0.5119550228118896, + "error": 0.2646484375, + "gradient_norm": 0.07688591629266739, + "elapsed": 136.20711088180542 + }, + { + "step": 160, + "loss": 0.3388235569000244, + "objective": 0.3388235569000244, + "error": 0.1630859375, + "gradient_norm": 0.07015731930732727, + "elapsed": 145.3505516052246 + }, + { + "step": 176, + "loss": 0.5952156186103821, + "objective": 0.5952156186103821, + "error": 0.3369140625, + "gradient_norm": 0.039373140782117844, + "elapsed": 154.77994871139526 + }, + { + "step": 192, + "loss": 0.15157413482666016, + "objective": 0.15157413482666016, + "error": 0.0634765625, + "gradient_norm": 0.029710670933127403, + "elapsed": 164.46801733970642 + }, + { + "step": 208, + "loss": 0.3120684027671814, + "objective": 0.3120684027671814, + "error": 0.1474609375, + "gradient_norm": 0.035548821091651917, + "elapsed": 173.24825358390808 + }, + { + "step": 224, + "loss": 0.5486405491828918, + "objective": 0.5486405491828918, + "error": 0.2900390625, + "gradient_norm": 0.0503678023815155, + "elapsed": 185.29849314689636 + }, + { + "step": 240, + "loss": 0.6046283841133118, + "objective": 0.6046283841133118, + "error": 0.3349609375, + "gradient_norm": 0.05043461173772812, + "elapsed": 197.54880928993225 + }, + { + "step": 256, + "loss": 0.5926339626312256, + "objective": 0.5926339626312256, + "error": 0.3359375, + "gradient_norm": 0.051241543143987656, + "elapsed": 211.79861068725586 + }, + { + "step": 272, + "loss": 0.4018518924713135, + "objective": 0.4018518924713135, + "error": 0.1943359375, + "gradient_norm": 0.0772147998213768, + "elapsed": 222.41974115371704 + }, + { + "step": 288, + "loss": 0.13863243162631989, + "objective": 0.13863243162631989, + "error": 0.0556640625, + "gradient_norm": 0.03334609419107437, + "elapsed": 234.04247426986694 + }, + { + "step": 304, + "loss": 0.562490701675415, + "objective": 0.562490701675415, + "error": 0.337890625, + "gradient_norm": 0.04585934057831764, + "elapsed": 242.65421533584595 + }, + { + "step": 320, + "loss": 0.5352796316146851, + "objective": 0.5352796316146851, + "error": 0.294921875, + "gradient_norm": 0.0837635025382042, + "elapsed": 252.10656356811523 + }, + { + "step": 336, + "loss": 0.26082637906074524, + "objective": 0.26082637906074524, + "error": 0.1220703125, + "gradient_norm": 0.048336997628211975, + "elapsed": 262.33449625968933 + }, + { + "step": 352, + "loss": 0.5959363579750061, + "objective": 0.5959363579750061, + "error": 0.3388671875, + "gradient_norm": 0.06797357648611069, + "elapsed": 271.9942307472229 + }, + { + "step": 368, + "loss": 0.48994284868240356, + "objective": 0.48994284868240356, + "error": 0.2587890625, + "gradient_norm": 0.06296153366565704, + "elapsed": 283.0493588447571 + }, + { + "step": 384, + "loss": 0.5710494518280029, + "objective": 0.5710494518280029, + "error": 0.3134765625, + "gradient_norm": 0.045333269983530045, + "elapsed": 294.64637446403503 + }, + { + "step": 400, + "loss": 0.5957783460617065, + "objective": 0.5957783460617065, + "error": 0.349609375, + "gradient_norm": 0.03918786719441414, + "elapsed": 307.6200888156891 + }, + { + "step": 416, + "loss": 0.27521568536758423, + "objective": 0.27521568536758423, + "error": 0.1220703125, + "gradient_norm": 0.038001637905836105, + "elapsed": 317.01610231399536 + }, + { + "step": 432, + "loss": 0.02379823848605156, + "objective": 0.02379823848605156, + "error": 0.0078125, + "gradient_norm": 0.007661945186555386, + "elapsed": 326.9360330104828 + }, + { + "step": 448, + "loss": 0.56734299659729, + "objective": 0.56734299659729, + "error": 0.3271484375, + "gradient_norm": 0.057416290044784546, + "elapsed": 339.6289041042328 + }, + { + "step": 464, + "loss": 0.10715995728969574, + "objective": 0.10715995728969574, + "error": 0.0380859375, + "gradient_norm": 0.02532491274178028, + "elapsed": 349.8584108352661 + }, + { + "step": 480, + "loss": 0.6143364310264587, + "objective": 0.6143364310264587, + "error": 0.36328125, + "gradient_norm": 0.08023032546043396, + "elapsed": 360.36362075805664 + }, + { + "step": 496, + "loss": 0.44069671630859375, + "objective": 0.44069671630859375, + "error": 0.2197265625, + "gradient_norm": 0.048025116324424744, + "elapsed": 369.48225808143616 + }, + { + "step": 512, + "loss": 0.019900165498256683, + "objective": 0.019900165498256683, + "error": 0.0107421875, + "gradient_norm": 0.0038635791279375553, + "elapsed": 378.59970593452454 + }, + { + "step": 528, + "loss": 0.033316534012556076, + "objective": 0.033316534012556076, + "error": 0.009765625, + "gradient_norm": 0.009174940176308155, + "elapsed": 393.4021761417389 + }, + { + "step": 544, + "loss": 0.41130945086479187, + "objective": 0.41130945086479187, + "error": 0.20703125, + "gradient_norm": 0.04695262759923935, + "elapsed": 402.8586280345917 + }, + { + "step": 560, + "loss": 0.5885373950004578, + "objective": 0.5885373950004578, + "error": 0.3544921875, + "gradient_norm": 0.08534500002861023, + "elapsed": 416.98661041259766 + }, + { + "step": 576, + "loss": 0.3804720640182495, + "objective": 0.3804720640182495, + "error": 0.19140625, + "gradient_norm": 0.05163278803229332, + "elapsed": 427.7550480365753 + }, + { + "step": 592, + "loss": 0.6101120710372925, + "objective": 0.6101120710372925, + "error": 0.3525390625, + "gradient_norm": 0.05593184754252434, + "elapsed": 441.05026268959045 + }, + { + "step": 608, + "loss": 0.5586092472076416, + "objective": 0.5586092472076416, + "error": 0.302734375, + "gradient_norm": 0.07458740472793579, + "elapsed": 452.95383286476135 + }, + { + "step": 624, + "loss": 0.5992780923843384, + "objective": 0.5992780923843384, + "error": 0.357421875, + "gradient_norm": 0.03618372976779938, + "elapsed": 466.1582691669464 + }, + { + "step": 640, + "loss": 0.3536975383758545, + "objective": 0.3536975383758545, + "error": 0.1650390625, + "gradient_norm": 0.05353165790438652, + "elapsed": 477.166255235672 + }, + { + "step": 656, + "loss": 0.4926893711090088, + "objective": 0.4926893711090088, + "error": 0.2626953125, + "gradient_norm": 0.05201377719640732, + "elapsed": 491.1417751312256 + }, + { + "step": 672, + "loss": 0.5754991173744202, + "objective": 0.5754991173744202, + "error": 0.3271484375, + "gradient_norm": 0.08167096972465515, + "elapsed": 501.630366563797 + }, + { + "step": 688, + "loss": 0.5685014724731445, + "objective": 0.5685014724731445, + "error": 0.333984375, + "gradient_norm": 0.043775107711553574, + "elapsed": 514.2880456447601 + }, + { + "step": 704, + "loss": 0.022465089336037636, + "objective": 0.022465089336037636, + "error": 0.0068359375, + "gradient_norm": 0.010172540321946144, + "elapsed": 522.9173214435577 + }, + { + "step": 720, + "loss": 0.035460107028484344, + "objective": 0.035460107028484344, + "error": 0.0107421875, + "gradient_norm": 0.010515578091144562, + "elapsed": 532.8470129966736 + }, + { + "step": 736, + "loss": 0.44765588641166687, + "objective": 0.44765588641166687, + "error": 0.2138671875, + "gradient_norm": 0.09050357341766357, + "elapsed": 541.9488840103149 + }, + { + "step": 752, + "loss": 0.5933939218521118, + "objective": 0.5933939218521118, + "error": 0.3359375, + "gradient_norm": 0.0665116235613823, + "elapsed": 552.9967355728149 + }, + { + "step": 768, + "loss": 0.6100764870643616, + "objective": 0.6100764870643616, + "error": 0.3515625, + "gradient_norm": 0.0821211114525795, + "elapsed": 563.7709202766418 + }, + { + "step": 784, + "loss": 0.02964692935347557, + "objective": 0.02964692935347557, + "error": 0.009765625, + "gradient_norm": 0.012663272209465504, + "elapsed": 573.1517221927643 + }, + { + "step": 800, + "loss": 0.38091832399368286, + "objective": 0.38091832399368286, + "error": 0.1904296875, + "gradient_norm": 0.060622021555900574, + "elapsed": 582.5687477588654 + }, + { + "step": 816, + "loss": 0.552335262298584, + "objective": 0.552335262298584, + "error": 0.3076171875, + "gradient_norm": 0.14419035613536835, + "elapsed": 594.4292685985565 + }, + { + "step": 832, + "loss": 0.5943340063095093, + "objective": 0.5943340063095093, + "error": 0.34375, + "gradient_norm": 0.0633513554930687, + "elapsed": 605.2052299976349 + }, + { + "step": 848, + "loss": 0.6074100732803345, + "objective": 0.6074100732803345, + "error": 0.3486328125, + "gradient_norm": 0.04225531220436096, + "elapsed": 614.8996202945709 + }, + { + "step": 864, + "loss": 0.6198879480361938, + "objective": 0.6198879480361938, + "error": 0.361328125, + "gradient_norm": 0.04208856821060181, + "elapsed": 625.4266908168793 + }, + { + "step": 880, + "loss": 0.6151762008666992, + "objective": 0.6151762008666992, + "error": 0.369140625, + "gradient_norm": 0.06261089444160461, + "elapsed": 636.0696911811829 + }, + { + "step": 896, + "loss": 0.49680083990097046, + "objective": 0.49680083990097046, + "error": 0.25390625, + "gradient_norm": 0.0827067643404007, + "elapsed": 644.6893246173859 + }, + { + "step": 912, + "loss": 0.4610927402973175, + "objective": 0.4610927402973175, + "error": 0.23828125, + "gradient_norm": 0.06652095168828964, + "elapsed": 655.969132900238 + }, + { + "step": 928, + "loss": 0.5218505859375, + "objective": 0.5218505859375, + "error": 0.2685546875, + "gradient_norm": 0.07188194245100021, + "elapsed": 667.5352523326874 + }, + { + "step": 944, + "loss": 0.33009427785873413, + "objective": 0.33009427785873413, + "error": 0.1533203125, + "gradient_norm": 0.05718810483813286, + "elapsed": 677.8397319316864 + }, + { + "step": 960, + "loss": 0.5703234672546387, + "objective": 0.5703234672546387, + "error": 0.3193359375, + "gradient_norm": 0.11168288439512253, + "elapsed": 687.8742904663086 + }, + { + "step": 976, + "loss": 0.025548014789819717, + "objective": 0.025548014789819717, + "error": 0.0107421875, + "gradient_norm": 0.009453393518924713, + "elapsed": 698.294285774231 + }, + { + "step": 992, + "loss": 0.45398157835006714, + "objective": 0.45398157835006714, + "error": 0.2412109375, + "gradient_norm": 0.04607952758669853, + "elapsed": 707.903199672699 + }, + { + "step": 1008, + "loss": 0.3412189781665802, + "objective": 0.3412189781665802, + "error": 0.1513671875, + "gradient_norm": 0.0432075597345829, + "elapsed": 718.5662748813629 + }, + { + "step": 1024, + "loss": 0.4376429319381714, + "objective": 0.4376429319381714, + "error": 0.2275390625, + "gradient_norm": 0.07974351197481155, + "elapsed": 728.8954858779907 + }, + { + "step": 1040, + "loss": 0.33512815833091736, + "objective": 0.33512815833091736, + "error": 0.150390625, + "gradient_norm": 0.04476875811815262, + "elapsed": 744.0822694301605 + }, + { + "step": 1056, + "loss": 0.5214208364486694, + "objective": 0.5214208364486694, + "error": 0.283203125, + "gradient_norm": 0.08898192644119263, + "elapsed": 755.1484262943268 + }, + { + "step": 1072, + "loss": 0.13849599659442902, + "objective": 0.13849599659442902, + "error": 0.052734375, + "gradient_norm": 0.028359953314065933, + "elapsed": 764.3303108215332 + }, + { + "step": 1088, + "loss": 0.323838472366333, + "objective": 0.323838472366333, + "error": 0.1435546875, + "gradient_norm": 0.04081716760993004, + "elapsed": 773.2739362716675 + }, + { + "step": 1104, + "loss": 0.5627881288528442, + "objective": 0.5627881288528442, + "error": 0.3125, + "gradient_norm": 0.08322097361087799, + "elapsed": 784.7223973274231 + }, + { + "step": 1120, + "loss": 0.44111010432243347, + "objective": 0.44111010432243347, + "error": 0.2216796875, + "gradient_norm": 0.05700977146625519, + "elapsed": 795.085648059845 + }, + { + "step": 1136, + "loss": 0.6395992040634155, + "objective": 0.6395992040634155, + "error": 0.39453125, + "gradient_norm": 0.0744553729891777, + "elapsed": 805.7942585945129 + }, + { + "step": 1152, + "loss": 0.5433304309844971, + "objective": 0.5433304309844971, + "error": 0.287109375, + "gradient_norm": 0.04814797267317772, + "elapsed": 817.3382890224457 + }, + { + "step": 1168, + "loss": 0.5708576440811157, + "objective": 0.5708576440811157, + "error": 0.3203125, + "gradient_norm": 0.051331400871276855, + "elapsed": 829.288791179657 + }, + { + "step": 1184, + "loss": 0.5447035431861877, + "objective": 0.5447035431861877, + "error": 0.2939453125, + "gradient_norm": 0.10116687417030334, + "elapsed": 839.6822843551636 + }, + { + "step": 1200, + "loss": 0.6125671863555908, + "objective": 0.6125671863555908, + "error": 0.3642578125, + "gradient_norm": 0.04368080571293831, + "elapsed": 850.2262740135193 + }, + { + "step": 1216, + "loss": 0.5002380609512329, + "objective": 0.5002380609512329, + "error": 0.259765625, + "gradient_norm": 0.04939017817378044, + "elapsed": 862.3783452510834 + }, + { + "step": 1232, + "loss": 0.5698772668838501, + "objective": 0.5698772668838501, + "error": 0.3173828125, + "gradient_norm": 0.04916854575276375, + "elapsed": 871.4622664451599 + }, + { + "step": 1248, + "loss": 0.6046518683433533, + "objective": 0.6046518683433533, + "error": 0.341796875, + "gradient_norm": 0.04919794574379921, + "elapsed": 883.3905737400055 + }, + { + "step": 1264, + "loss": 0.5913128852844238, + "objective": 0.5913128852844238, + "error": 0.357421875, + "gradient_norm": 0.046917904168367386, + "elapsed": 892.4264807701111 + }, + { + "step": 1280, + "loss": 0.5027461051940918, + "objective": 0.5027461051940918, + "error": 0.2626953125, + "gradient_norm": 0.04705750197172165, + "elapsed": 902.5875842571259 + }, + { + "step": 1296, + "loss": 0.13519814610481262, + "objective": 0.13519814610481262, + "error": 0.052734375, + "gradient_norm": 0.02625490538775921, + "elapsed": 912.4087471961975 + }, + { + "step": 1312, + "loss": 0.5862359404563904, + "objective": 0.5862359404563904, + "error": 0.3271484375, + "gradient_norm": 0.05441493168473244, + "elapsed": 923.992555141449 + }, + { + "step": 1328, + "loss": 0.6031408309936523, + "objective": 0.6031408309936523, + "error": 0.3505859375, + "gradient_norm": 0.05901554971933365, + "elapsed": 933.3936491012573 + }, + { + "step": 1344, + "loss": 0.5823733806610107, + "objective": 0.5823733806610107, + "error": 0.3310546875, + "gradient_norm": 0.0842989832162857, + "elapsed": 941.979998588562 + }, + { + "step": 1360, + "loss": 0.6241492033004761, + "objective": 0.6241492033004761, + "error": 0.3720703125, + "gradient_norm": 0.04446673393249512, + "elapsed": 954.969649553299 + }, + { + "step": 1376, + "loss": 0.5829156637191772, + "objective": 0.5829156637191772, + "error": 0.361328125, + "gradient_norm": 0.06615480780601501, + "elapsed": 966.0245676040649 + }, + { + "step": 1392, + "loss": 0.5968320369720459, + "objective": 0.5968320369720459, + "error": 0.34765625, + "gradient_norm": 0.05093541368842125, + "elapsed": 975.1022663116455 + }, + { + "step": 1408, + "loss": 0.045559000223875046, + "objective": 0.045559000223875046, + "error": 0.01171875, + "gradient_norm": 0.02514980360865593, + "elapsed": 987.2391452789307 + }, + { + "step": 1424, + "loss": 0.22601813077926636, + "objective": 0.22601813077926636, + "error": 0.09765625, + "gradient_norm": 0.04834206402301788, + "elapsed": 996.4583384990692 + }, + { + "step": 1440, + "loss": 0.23011144995689392, + "objective": 0.23011144995689392, + "error": 0.111328125, + "gradient_norm": 0.050687842071056366, + "elapsed": 1007.1440904140472 + }, + { + "step": 1456, + "loss": 0.018240466713905334, + "objective": 0.018240466713905334, + "error": 0.0078125, + "gradient_norm": 0.005604141391813755, + "elapsed": 1016.4502851963043 + }, + { + "step": 1472, + "loss": 0.4498720169067383, + "objective": 0.4498720169067383, + "error": 0.232421875, + "gradient_norm": 0.08179625123739243, + "elapsed": 1028.8303294181824 + }, + { + "step": 1488, + "loss": 0.24151627719402313, + "objective": 0.24151627719402313, + "error": 0.107421875, + "gradient_norm": 0.03838668763637543, + "elapsed": 1037.8867321014404 + }, + { + "step": 1504, + "loss": 0.46122002601623535, + "objective": 0.46122002601623535, + "error": 0.232421875, + "gradient_norm": 0.0726623386144638, + "elapsed": 1047.7258644104004 + }, + { + "step": 1520, + "loss": 0.5085602402687073, + "objective": 0.5085602402687073, + "error": 0.2705078125, + "gradient_norm": 0.06673175096511841, + "elapsed": 1059.352120399475 + }, + { + "step": 1536, + "loss": 0.6105246543884277, + "objective": 0.6105246543884277, + "error": 0.3818359375, + "gradient_norm": 0.04271261766552925, + "elapsed": 1070.1413230895996 + }, + { + "step": 1552, + "loss": 0.4792126417160034, + "objective": 0.4792126417160034, + "error": 0.2578125, + "gradient_norm": 0.05200039595365524, + "elapsed": 1086.444006204605 + }, + { + "step": 1568, + "loss": 0.5814266204833984, + "objective": 0.5814266204833984, + "error": 0.330078125, + "gradient_norm": 0.05867309868335724, + "elapsed": 1097.2902619838715 + }, + { + "step": 1584, + "loss": 0.6321226358413696, + "objective": 0.6321226358413696, + "error": 0.3798828125, + "gradient_norm": 0.05418067052960396, + "elapsed": 1107.9767682552338 + }, + { + "step": 1600, + "loss": 0.5931253433227539, + "objective": 0.5931253433227539, + "error": 0.3603515625, + "gradient_norm": 0.06396215409040451, + "elapsed": 1121.782609462738 + }, + { + "step": 1616, + "loss": 0.6411516666412354, + "objective": 0.6411516666412354, + "error": 0.38671875, + "gradient_norm": 0.05035768821835518, + "elapsed": 1132.7197887897491 + }, + { + "step": 1632, + "loss": 0.4267754852771759, + "objective": 0.4267754852771759, + "error": 0.2080078125, + "gradient_norm": 0.09109894186258316, + "elapsed": 1139.1667578220367 + }, + { + "step": 1648, + "loss": 0.21246182918548584, + "objective": 0.21246182918548584, + "error": 0.095703125, + "gradient_norm": 0.04478950425982475, + "elapsed": 1149.1183021068573 + }, + { + "step": 1664, + "loss": 0.46360665559768677, + "objective": 0.46360665559768677, + "error": 0.251953125, + "gradient_norm": 0.07668188214302063, + "elapsed": 1161.1197745800018 + }, + { + "step": 1680, + "loss": 0.46281397342681885, + "objective": 0.46281397342681885, + "error": 0.236328125, + "gradient_norm": 0.07954126596450806, + "elapsed": 1171.8474535942078 + }, + { + "step": 1696, + "loss": 0.2484058141708374, + "objective": 0.2484058141708374, + "error": 0.12109375, + "gradient_norm": 0.047261305153369904, + "elapsed": 1185.6542596817017 + }, + { + "step": 1712, + "loss": 0.24310235679149628, + "objective": 0.24310235679149628, + "error": 0.1064453125, + "gradient_norm": 0.07262872904539108, + "elapsed": 1197.8986082077026 + }, + { + "step": 1728, + "loss": 0.009729458019137383, + "objective": 0.009729458019137383, + "error": 0.001953125, + "gradient_norm": 0.01146845705807209, + "elapsed": 1208.495581150055 + }, + { + "step": 1744, + "loss": 0.24568752944469452, + "objective": 0.24568752944469452, + "error": 0.10546875, + "gradient_norm": 0.05830742046236992, + "elapsed": 1219.9394850730896 + }, + { + "step": 1760, + "loss": 0.022546378895640373, + "objective": 0.022546378895640373, + "error": 0.0068359375, + "gradient_norm": 0.007667526602745056, + "elapsed": 1229.5703229904175 + }, + { + "step": 1776, + "loss": 0.5848401784896851, + "objective": 0.5848401784896851, + "error": 0.3271484375, + "gradient_norm": 0.061901818960905075, + "elapsed": 1238.750280380249 + }, + { + "step": 1792, + "loss": 0.6031335592269897, + "objective": 0.6031335592269897, + "error": 0.3671875, + "gradient_norm": 0.0676632970571518, + "elapsed": 1247.7468683719635 + }, + { + "step": 1808, + "loss": 0.6210961937904358, + "objective": 0.6210961937904358, + "error": 0.3603515625, + "gradient_norm": 0.0718468651175499, + "elapsed": 1256.1821897029877 + }, + { + "step": 1824, + "loss": 0.570877730846405, + "objective": 0.570877730846405, + "error": 0.3212890625, + "gradient_norm": 0.05575930327177048, + "elapsed": 1266.4091975688934 + }, + { + "step": 1840, + "loss": 0.5711429119110107, + "objective": 0.5711429119110107, + "error": 0.31640625, + "gradient_norm": 0.0691002607345581, + "elapsed": 1277.4722146987915 + }, + { + "step": 1856, + "loss": 0.36046335101127625, + "objective": 0.36046335101127625, + "error": 0.16796875, + "gradient_norm": 0.04694395884871483, + "elapsed": 1287.1420249938965 + }, + { + "step": 1872, + "loss": 0.4688999652862549, + "objective": 0.4688999652862549, + "error": 0.2216796875, + "gradient_norm": 0.07401346415281296, + "elapsed": 1297.3945078849792 + }, + { + "step": 1888, + "loss": 0.46385282278060913, + "objective": 0.46385282278060913, + "error": 0.2373046875, + "gradient_norm": 0.05608939751982689, + "elapsed": 1305.9779334068298 + }, + { + "step": 1904, + "loss": 0.60875403881073, + "objective": 0.60875403881073, + "error": 0.365234375, + "gradient_norm": 0.05085878074169159, + "elapsed": 1317.3097081184387 + }, + { + "step": 1920, + "loss": 0.12223530560731888, + "objective": 0.12223530560731888, + "error": 0.0458984375, + "gradient_norm": 0.024870412424206734, + "elapsed": 1328.6486887931824 + }, + { + "step": 1936, + "loss": 0.3486189544200897, + "objective": 0.3486189544200897, + "error": 0.16796875, + "gradient_norm": 0.04780663549900055, + "elapsed": 1336.6701011657715 + }, + { + "step": 1952, + "loss": 0.5777363777160645, + "objective": 0.5777363777160645, + "error": 0.3427734375, + "gradient_norm": 0.0571451336145401, + "elapsed": 1346.9158833026886 + }, + { + "step": 1968, + "loss": 0.39320266246795654, + "objective": 0.39320266246795654, + "error": 0.1884765625, + "gradient_norm": 0.05673858895897865, + "elapsed": 1354.9182631969452 + }, + { + "step": 1984, + "loss": 0.5900611281394958, + "objective": 0.5900611281394958, + "error": 0.3349609375, + "gradient_norm": 0.06593932211399078, + "elapsed": 1364.2754452228546 + }, + { + "step": 2000, + "loss": 0.6212430000305176, + "objective": 0.6212430000305176, + "error": 0.3857421875, + "gradient_norm": 0.040818918496370316, + "elapsed": 1374.7192046642303 + }, + { + "step": 2016, + "loss": 0.15605247020721436, + "objective": 0.15605247020721436, + "error": 0.0556640625, + "gradient_norm": 0.03108786791563034, + "elapsed": 1386.2740807533264 + }, + { + "step": 2032, + "loss": 0.22049596905708313, + "objective": 0.22049596905708313, + "error": 0.1015625, + "gradient_norm": 0.042733557522296906, + "elapsed": 1396.6422457695007 + }, + { + "step": 2048, + "loss": 0.5642613172531128, + "objective": 0.5642613172531128, + "error": 0.306640625, + "gradient_norm": 0.07527482509613037, + "elapsed": 1407.6688070297241 + } + ] + }, + "derived_checkpoints": { + "mean3": { + "checkpoint_label": "mean3", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_run": "full3_1", + "source_optimizer_steps": [ + 1024, + 1536, + 2048 + ], + "source_weights_sha256": { + "1024": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "1536": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "2048": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5" + }, + "source_checkpoint_records": { + "1024": { + "step": 1024, + "training_samples": 1048576, + "unique_training_rows_seen_in_this_phase": 446179, + "weights_sha256": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "complete": true + }, + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 490266, + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "complete": true + }, + "2048": { + "step": 2048, + "training_samples": 2097152, + "unique_training_rows_seen_in_this_phase": 507282, + "weights_sha256": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5", + "complete": true + } + }, + "weights_sha256": "ce5951e7095a9912dc74719254f2fcf9654f219078392b7acf7a8545e6f9f3f4", + "complete": true + }, + "mean4": { + "checkpoint_label": "mean4", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_run": "full3_1", + "source_optimizer_steps": [ + 512, + 1024, + 1536, + 2048 + ], + "source_weights_sha256": { + "512": "d4194b40470453e5df9b75e12326cbbd0e6845946870bb0d53a2cbbdd6ea32dc", + "1024": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "1536": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "2048": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5" + }, + "source_checkpoint_records": { + "512": { + "step": 512, + "training_samples": 524288, + "unique_training_rows_seen_in_this_phase": 324661, + "weights_sha256": "d4194b40470453e5df9b75e12326cbbd0e6845946870bb0d53a2cbbdd6ea32dc", + "complete": true + }, + "1024": { + "step": 1024, + "training_samples": 1048576, + "unique_training_rows_seen_in_this_phase": 446179, + "weights_sha256": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "complete": true + }, + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 490266, + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "complete": true + }, + "2048": { + "step": 2048, + "training_samples": 2097152, + "unique_training_rows_seen_in_this_phase": 507282, + "weights_sha256": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5", + "complete": true + } + }, + "weights_sha256": "ff5a023ce2c18be7c29f810a3788a450e3ad3ad2237d6e9448923aa6a28c5074", + "complete": true + } + }, + "selection": "Predefined averages of the last3 or all4 saved noninitial full3_1 checkpoints; evaluate every validation condition before selecting", + "test_data_used": false, + "derivation_source_sha256": "08c498d6952b0380e001371df9a0461a483631a301f93747b821e529e72b349d" + }, + "training_source_snapshot": "training_sources/full3_swa", + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with the recorded physical decoder.", + "physical_prediction_reference": "/run-state/workspace/research/context_upgrades/turbo1/predictions", + "prior_pass": 3, + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23290264423076928, + "mean3": 0.2335186298076923, + "blend-mean3": 0.2325420673076923, + "mean4": 0.23326322115384618, + "blend-mean4": 0.23300781250000002 + }, + "selected": "blend-mean3" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22017728365384615, + "mean3": 0.22037259615384613, + "blend-mean3": 0.22091346153846153, + "mean4": 0.2205528846153846, + "blend-mean4": 0.22100360576923078 + }, + "selected": "incumbent" + } + ], + "checkpoints": { + "mean3": { + "checkpoint_label": "mean3", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_run": "full3_1", + "source_optimizer_steps": [ + 1024, + 1536, + 2048 + ], + "source_weights_sha256": { + "1024": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "1536": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "2048": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5" + }, + "source_checkpoint_records": { + "1024": { + "step": 1024, + "training_samples": 1048576, + "unique_training_rows_seen_in_this_phase": 446179, + "weights_sha256": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "complete": true + }, + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 490266, + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "complete": true + }, + "2048": { + "step": 2048, + "training_samples": 2097152, + "unique_training_rows_seen_in_this_phase": 507282, + "weights_sha256": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5", + "complete": true + } + }, + "weights_sha256": "ce5951e7095a9912dc74719254f2fcf9654f219078392b7acf7a8545e6f9f3f4", + "complete": true + } + }, + "runtime": "Share physical priors when the conditioning pass and regime agree; otherwise recompute the neural prior independently. Last-only physical branches omit logical tracking in intermediate passes when intermediate probabilities are unused.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false + }, + { + "training": { + "initialization": "Continue from the recorded session-trained checkpoint; original random initialization seed 20261134", + "prior_pass": 3, + "initial_seed": 20261134, + "training_source_sha256": { + "learned_d5__train.py": "1f66b75e34e385a6d2654021f3fd124c9d8a359da1f677369e3e774728f83168", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "All supplied training shots per each of all26 d5 conditions; uniform condition and within-condition sampling for optimizer batches.", + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 516880, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 491030, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 18670, + "surface_code_bX_d5_r03_center_5_5": 18940, + "surface_code_bX_d5_r05_center_5_5": 19128, + "surface_code_bX_d5_r07_center_5_5": 18988, + "surface_code_bX_d5_r09_center_5_5": 18523, + "surface_code_bX_d5_r11_center_5_5": 19227, + "surface_code_bX_d5_r13_center_5_5": 18816, + "surface_code_bX_d5_r15_center_5_5": 18107, + "surface_code_bX_d5_r17_center_5_5": 18728, + "surface_code_bX_d5_r19_center_5_5": 18983, + "surface_code_bX_d5_r21_center_5_5": 18959, + "surface_code_bX_d5_r23_center_5_5": 19079, + "surface_code_bX_d5_r25_center_5_5": 19193, + "surface_code_bZ_d5_r01_center_5_5": 18828, + "surface_code_bZ_d5_r03_center_5_5": 18896, + "surface_code_bZ_d5_r05_center_5_5": 19011, + "surface_code_bZ_d5_r07_center_5_5": 18806, + "surface_code_bZ_d5_r09_center_5_5": 18268, + "surface_code_bZ_d5_r11_center_5_5": 18927, + "surface_code_bZ_d5_r13_center_5_5": 19399, + "surface_code_bZ_d5_r15_center_5_5": 19358, + "surface_code_bZ_d5_r17_center_5_5": 18634, + "surface_code_bZ_d5_r19_center_5_5": 19126, + "surface_code_bZ_d5_r21_center_5_5": 18603, + "surface_code_bZ_d5_r23_center_5_5": 18626, + "surface_code_bZ_d5_r25_center_5_5": 19207 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1536, + "batch": 1024, + "learning_rate": 0.0005, + "sampling_seed": 20261135, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": true, + "rng_restored": true, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "/run-state/workspace/research/learned_d5/fresh2_warm/rng-512.json", + "starting_checkpoint": "/run-state/workspace/research/learned_d5/fresh2_warm/weights-512.npz", + "starting_checkpoint_sha256": "d3e3abba07693bd7fd3d17be2dd981d5b803a496e76ba230ed94afeb51f26f4f", + "starting_training_provenance": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261134", + "prior_pass": 3, + "initial_seed": 20261134, + "training_source_sha256": { + "learned_d5__train.py": "1f66b75e34e385a6d2654021f3fd124c9d8a359da1f677369e3e774728f83168", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "All supplied training shots per each of all26 d5 conditions; uniform condition and within-condition sampling for optimizer batches.", + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 516880, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 325678, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 11962, + "surface_code_bX_d5_r03_center_5_5": 10232, + "surface_code_bX_d5_r05_center_5_5": 14014, + "surface_code_bX_d5_r07_center_5_5": 11594, + "surface_code_bX_d5_r09_center_5_5": 12805, + "surface_code_bX_d5_r11_center_5_5": 11644, + "surface_code_bX_d5_r13_center_5_5": 13845, + "surface_code_bX_d5_r15_center_5_5": 10703, + "surface_code_bX_d5_r17_center_5_5": 15460, + "surface_code_bX_d5_r19_center_5_5": 14156, + "surface_code_bX_d5_r21_center_5_5": 11568, + "surface_code_bX_d5_r23_center_5_5": 14156, + "surface_code_bX_d5_r25_center_5_5": 12021, + "surface_code_bZ_d5_r01_center_5_5": 10601, + "surface_code_bZ_d5_r03_center_5_5": 14135, + "surface_code_bZ_d5_r05_center_5_5": 11975, + "surface_code_bZ_d5_r07_center_5_5": 13841, + "surface_code_bZ_d5_r09_center_5_5": 12024, + "surface_code_bZ_d5_r11_center_5_5": 11151, + "surface_code_bZ_d5_r13_center_5_5": 10640, + "surface_code_bZ_d5_r15_center_5_5": 11089, + "surface_code_bZ_d5_r17_center_5_5": 13788, + "surface_code_bZ_d5_r19_center_5_5": 12350, + "surface_code_bZ_d5_r21_center_5_5": 12797, + "surface_code_bZ_d5_r23_center_5_5": 12809, + "surface_code_bZ_d5_r25_center_5_5": 14318 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 512, + "batch": 1024, + "learning_rate": 0.001, + "sampling_seed": 20261135, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "rng_restored": false, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "Fresh NumPy default_rng seed 20261135", + "starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "starting_training_provenance": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.6522030830383301, + "objective": 0.6522030830383301, + "error": 0.375, + "gradient_norm": 0.11649785190820694, + "elapsed": 30.089841604232788 + }, + { + "step": 16, + "loss": 0.5927819609642029, + "objective": 0.5927819609642029, + "error": 0.3466796875, + "gradient_norm": 0.07945127785205841, + "elapsed": 48.85365080833435 + }, + { + "step": 32, + "loss": 0.3115929663181305, + "objective": 0.3115929663181305, + "error": 0.13671875, + "gradient_norm": 0.039320655167102814, + "elapsed": 63.60312819480896 + }, + { + "step": 48, + "loss": 0.2456369698047638, + "objective": 0.2456369698047638, + "error": 0.1015625, + "gradient_norm": 0.029398636892437935, + "elapsed": 73.71074151992798 + }, + { + "step": 64, + "loss": 0.6231744885444641, + "objective": 0.6231744885444641, + "error": 0.3759765625, + "gradient_norm": 0.06867238879203796, + "elapsed": 83.75580954551697 + }, + { + "step": 80, + "loss": 0.3674217164516449, + "objective": 0.3674217164516449, + "error": 0.1572265625, + "gradient_norm": 0.0557992123067379, + "elapsed": 94.6383364200592 + }, + { + "step": 96, + "loss": 0.5152362585067749, + "objective": 0.5152362585067749, + "error": 0.2568359375, + "gradient_norm": 0.08284599334001541, + "elapsed": 106.90000939369202 + }, + { + "step": 112, + "loss": 0.020773420110344887, + "objective": 0.020773420110344887, + "error": 0.0048828125, + "gradient_norm": 0.008813572116196156, + "elapsed": 117.77558088302612 + }, + { + "step": 128, + "loss": 0.02593131735920906, + "objective": 0.02593131735920906, + "error": 0.0087890625, + "gradient_norm": 0.00872033555060625, + "elapsed": 128.93439435958862 + }, + { + "step": 144, + "loss": 0.5852900743484497, + "objective": 0.5852900743484497, + "error": 0.3291015625, + "gradient_norm": 0.04771002382040024, + "elapsed": 139.5588686466217 + }, + { + "step": 160, + "loss": 0.46074625849723816, + "objective": 0.46074625849723816, + "error": 0.232421875, + "gradient_norm": 0.08834747970104218, + "elapsed": 151.5595977306366 + }, + { + "step": 176, + "loss": 0.6310865879058838, + "objective": 0.6310865879058838, + "error": 0.376953125, + "gradient_norm": 0.14084596931934357, + "elapsed": 163.7892107963562 + }, + { + "step": 192, + "loss": 0.246865376830101, + "objective": 0.246865376830101, + "error": 0.1103515625, + "gradient_norm": 0.041402049362659454, + "elapsed": 174.28971648216248 + }, + { + "step": 208, + "loss": 0.3103577196598053, + "objective": 0.3103577196598053, + "error": 0.15625, + "gradient_norm": 0.04525696486234665, + "elapsed": 187.03909611701965 + }, + { + "step": 224, + "loss": 0.4523138999938965, + "objective": 0.4523138999938965, + "error": 0.208984375, + "gradient_norm": 0.09180521965026855, + "elapsed": 199.56195068359375 + }, + { + "step": 240, + "loss": 0.02241751179099083, + "objective": 0.02241751179099083, + "error": 0.009765625, + "gradient_norm": 0.009998111054301262, + "elapsed": 212.35500597953796 + }, + { + "step": 256, + "loss": 0.5487150549888611, + "objective": 0.5487150549888611, + "error": 0.294921875, + "gradient_norm": 0.12748055160045624, + "elapsed": 223.03854608535767 + }, + { + "step": 272, + "loss": 0.023057367652654648, + "objective": 0.023057367652654648, + "error": 0.0078125, + "gradient_norm": 0.006953821517527103, + "elapsed": 244.6508972644806 + }, + { + "step": 288, + "loss": 0.5845386981964111, + "objective": 0.5845386981964111, + "error": 0.330078125, + "gradient_norm": 0.06542652100324631, + "elapsed": 256.78167748451233 + }, + { + "step": 304, + "loss": 0.442532479763031, + "objective": 0.442532479763031, + "error": 0.232421875, + "gradient_norm": 0.10874580591917038, + "elapsed": 269.1364529132843 + }, + { + "step": 320, + "loss": 0.3264174163341522, + "objective": 0.3264174163341522, + "error": 0.15625, + "gradient_norm": 0.06276191771030426, + "elapsed": 282.38969564437866 + }, + { + "step": 336, + "loss": 0.386960506439209, + "objective": 0.386960506439209, + "error": 0.177734375, + "gradient_norm": 0.06561421602964401, + "elapsed": 292.9079031944275 + }, + { + "step": 352, + "loss": 0.23919886350631714, + "objective": 0.23919886350631714, + "error": 0.107421875, + "gradient_norm": 0.02755703590810299, + "elapsed": 304.16068935394287 + }, + { + "step": 368, + "loss": 0.5029175281524658, + "objective": 0.5029175281524658, + "error": 0.259765625, + "gradient_norm": 0.0378776490688324, + "elapsed": 315.11088514328003 + }, + { + "step": 384, + "loss": 0.565666675567627, + "objective": 0.565666675567627, + "error": 0.322265625, + "gradient_norm": 0.11368246376514435, + "elapsed": 324.3651068210602 + }, + { + "step": 400, + "loss": 0.5846428275108337, + "objective": 0.5846428275108337, + "error": 0.3408203125, + "gradient_norm": 0.08116643130779266, + "elapsed": 334.70786476135254 + }, + { + "step": 416, + "loss": 0.025111017748713493, + "objective": 0.025111017748713493, + "error": 0.0078125, + "gradient_norm": 0.008838560432195663, + "elapsed": 345.56963562965393 + }, + { + "step": 432, + "loss": 0.628488302230835, + "objective": 0.628488302230835, + "error": 0.3818359375, + "gradient_norm": 0.04001976177096367, + "elapsed": 355.3310384750366 + }, + { + "step": 448, + "loss": 0.4569575786590576, + "objective": 0.4569575786590576, + "error": 0.2578125, + "gradient_norm": 0.06344135850667953, + "elapsed": 367.05255675315857 + }, + { + "step": 464, + "loss": 0.49193111062049866, + "objective": 0.49193111062049866, + "error": 0.24609375, + "gradient_norm": 0.06022385507822037, + "elapsed": 377.38399291038513 + }, + { + "step": 480, + "loss": 0.5920064449310303, + "objective": 0.5920064449310303, + "error": 0.3466796875, + "gradient_norm": 0.036063045263290405, + "elapsed": 387.7266733646393 + }, + { + "step": 496, + "loss": 0.22157302498817444, + "objective": 0.22157302498817444, + "error": 0.09375, + "gradient_norm": 0.04071022942662239, + "elapsed": 397.78643012046814 + }, + { + "step": 512, + "loss": 0.39216887950897217, + "objective": 0.39216887950897217, + "error": 0.1728515625, + "gradient_norm": 0.09079446643590927, + "elapsed": 407.0137679576874 + } + ] + }, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.6092928647994995, + "objective": 0.6092928647994995, + "error": 0.3583984375, + "gradient_norm": 0.08161187171936035, + "elapsed": 27.421262741088867 + }, + { + "step": 16, + "loss": 0.4709879755973816, + "objective": 0.4709879755973816, + "error": 0.2529296875, + "gradient_norm": 0.0541619211435318, + "elapsed": 48.74575757980347 + }, + { + "step": 32, + "loss": 0.5842419862747192, + "objective": 0.5842419862747192, + "error": 0.34375, + "gradient_norm": 0.09450904279947281, + "elapsed": 60.68022179603577 + }, + { + "step": 48, + "loss": 0.5840846300125122, + "objective": 0.5840846300125122, + "error": 0.32421875, + "gradient_norm": 0.04569687321782112, + "elapsed": 74.63272476196289 + }, + { + "step": 64, + "loss": 0.5139708518981934, + "objective": 0.5139708518981934, + "error": 0.2646484375, + "gradient_norm": 0.16111725568771362, + "elapsed": 91.88426613807678 + }, + { + "step": 80, + "loss": 0.49099838733673096, + "objective": 0.49099838733673096, + "error": 0.251953125, + "gradient_norm": 0.04431874305009842, + "elapsed": 105.08457684516907 + }, + { + "step": 96, + "loss": 0.30287861824035645, + "objective": 0.30287861824035645, + "error": 0.14453125, + "gradient_norm": 0.03792181238532066, + "elapsed": 118.16054177284241 + }, + { + "step": 112, + "loss": 0.6026535630226135, + "objective": 0.6026535630226135, + "error": 0.359375, + "gradient_norm": 0.043088704347610474, + "elapsed": 134.6414511203766 + }, + { + "step": 128, + "loss": 0.5983598828315735, + "objective": 0.5983598828315735, + "error": 0.328125, + "gradient_norm": 0.06492504477500916, + "elapsed": 148.38875198364258 + }, + { + "step": 144, + "loss": 0.616276204586029, + "objective": 0.616276204586029, + "error": 0.3857421875, + "gradient_norm": 0.05420554056763649, + "elapsed": 164.11315298080444 + }, + { + "step": 160, + "loss": 0.017882924526929855, + "objective": 0.017882924526929855, + "error": 0.0048828125, + "gradient_norm": 0.004682278726249933, + "elapsed": 178.31525373458862 + }, + { + "step": 176, + "loss": 0.5279660820960999, + "objective": 0.5279660820960999, + "error": 0.271484375, + "gradient_norm": 0.03895021602511406, + "elapsed": 192.20261907577515 + }, + { + "step": 192, + "loss": 0.5794406533241272, + "objective": 0.5794406533241272, + "error": 0.34375, + "gradient_norm": 0.041880734264850616, + "elapsed": 200.32051873207092 + }, + { + "step": 208, + "loss": 0.3353561758995056, + "objective": 0.3353561758995056, + "error": 0.1513671875, + "gradient_norm": 0.07022152841091156, + "elapsed": 212.5193521976471 + }, + { + "step": 224, + "loss": 0.47239983081817627, + "objective": 0.47239983081817627, + "error": 0.23828125, + "gradient_norm": 0.044771477580070496, + "elapsed": 223.36571788787842 + }, + { + "step": 240, + "loss": 0.6235381364822388, + "objective": 0.6235381364822388, + "error": 0.3779296875, + "gradient_norm": 0.047636937350034714, + "elapsed": 233.90032649040222 + }, + { + "step": 256, + "loss": 0.516319751739502, + "objective": 0.516319751739502, + "error": 0.271484375, + "gradient_norm": 0.087476447224617, + "elapsed": 245.52193427085876 + }, + { + "step": 272, + "loss": 0.23385891318321228, + "objective": 0.23385891318321228, + "error": 0.091796875, + "gradient_norm": 0.05921977758407593, + "elapsed": 254.38622951507568 + }, + { + "step": 288, + "loss": 0.31280556321144104, + "objective": 0.31280556321144104, + "error": 0.1318359375, + "gradient_norm": 0.03548427298665047, + "elapsed": 263.25871300697327 + }, + { + "step": 304, + "loss": 0.6208417415618896, + "objective": 0.6208417415618896, + "error": 0.361328125, + "gradient_norm": 0.10255666077136993, + "elapsed": 273.5115919113159 + }, + { + "step": 320, + "loss": 0.5985375642776489, + "objective": 0.5985375642776489, + "error": 0.3603515625, + "gradient_norm": 0.04024764895439148, + "elapsed": 285.4135670661926 + }, + { + "step": 336, + "loss": 0.028151696547865868, + "objective": 0.028151696547865868, + "error": 0.009765625, + "gradient_norm": 0.008847440592944622, + "elapsed": 295.0800693035126 + }, + { + "step": 352, + "loss": 0.6147637963294983, + "objective": 0.6147637963294983, + "error": 0.3603515625, + "gradient_norm": 0.05709920823574066, + "elapsed": 305.32019686698914 + }, + { + "step": 368, + "loss": 0.5955979824066162, + "objective": 0.5955979824066162, + "error": 0.3486328125, + "gradient_norm": 0.04276399686932564, + "elapsed": 316.3869025707245 + }, + { + "step": 384, + "loss": 0.23504304885864258, + "objective": 0.23504304885864258, + "error": 0.1025390625, + "gradient_norm": 0.03205326199531555, + "elapsed": 325.7849349975586 + }, + { + "step": 400, + "loss": 0.13460804522037506, + "objective": 0.13460804522037506, + "error": 0.0546875, + "gradient_norm": 0.03109711967408657, + "elapsed": 335.72691917419434 + }, + { + "step": 416, + "loss": 0.5798783302307129, + "objective": 0.5798783302307129, + "error": 0.322265625, + "gradient_norm": 0.053542010486125946, + "elapsed": 345.7052640914917 + }, + { + "step": 432, + "loss": 0.3892784118652344, + "objective": 0.3892784118652344, + "error": 0.19140625, + "gradient_norm": 0.052194178104400635, + "elapsed": 357.38475036621094 + }, + { + "step": 448, + "loss": 0.23582103848457336, + "objective": 0.23582103848457336, + "error": 0.1181640625, + "gradient_norm": 0.032037943601608276, + "elapsed": 369.5841510295868 + }, + { + "step": 464, + "loss": 0.5408849716186523, + "objective": 0.5408849716186523, + "error": 0.2900390625, + "gradient_norm": 0.07508285343647003, + "elapsed": 379.84099793434143 + }, + { + "step": 480, + "loss": 0.3894873559474945, + "objective": 0.3894873559474945, + "error": 0.19140625, + "gradient_norm": 0.03977999836206436, + "elapsed": 390.9687530994415 + }, + { + "step": 496, + "loss": 0.6059300899505615, + "objective": 0.6059300899505615, + "error": 0.361328125, + "gradient_norm": 0.06041429564356804, + "elapsed": 403.2380111217499 + }, + { + "step": 512, + "loss": 0.2117740511894226, + "objective": 0.2117740511894226, + "error": 0.0908203125, + "gradient_norm": 0.05693414434790611, + "elapsed": 414.4854781627655 + }, + { + "step": 528, + "loss": 0.4666211009025574, + "objective": 0.4666211009025574, + "error": 0.2470703125, + "gradient_norm": 0.0764947235584259, + "elapsed": 433.42368054389954 + }, + { + "step": 544, + "loss": 0.22636458277702332, + "objective": 0.22636458277702332, + "error": 0.1083984375, + "gradient_norm": 0.03683016076683998, + "elapsed": 442.92575907707214 + }, + { + "step": 560, + "loss": 0.23172692954540253, + "objective": 0.23172692954540253, + "error": 0.1083984375, + "gradient_norm": 0.034071482717990875, + "elapsed": 453.3129711151123 + }, + { + "step": 576, + "loss": 0.4768703579902649, + "objective": 0.4768703579902649, + "error": 0.2529296875, + "gradient_norm": 0.06308378279209137, + "elapsed": 462.4127457141876 + }, + { + "step": 592, + "loss": 0.5165150165557861, + "objective": 0.5165150165557861, + "error": 0.291015625, + "gradient_norm": 0.07674732059240341, + "elapsed": 473.8309862613678 + }, + { + "step": 608, + "loss": 0.5919064283370972, + "objective": 0.5919064283370972, + "error": 0.3359375, + "gradient_norm": 0.06379934400320053, + "elapsed": 484.3733870983124 + }, + { + "step": 624, + "loss": 0.01804366335272789, + "objective": 0.01804366335272789, + "error": 0.0068359375, + "gradient_norm": 0.005318541545420885, + "elapsed": 495.94076347351074 + }, + { + "step": 640, + "loss": 0.41747498512268066, + "objective": 0.41747498512268066, + "error": 0.1962890625, + "gradient_norm": 0.052116431295871735, + "elapsed": 506.73559165000916 + }, + { + "step": 656, + "loss": 0.6140056848526001, + "objective": 0.6140056848526001, + "error": 0.3896484375, + "gradient_norm": 0.05376415699720383, + "elapsed": 517.2397899627686 + }, + { + "step": 672, + "loss": 0.4098930358886719, + "objective": 0.4098930358886719, + "error": 0.197265625, + "gradient_norm": 0.04737741872668266, + "elapsed": 525.7957897186279 + }, + { + "step": 688, + "loss": 0.3499884009361267, + "objective": 0.3499884009361267, + "error": 0.1650390625, + "gradient_norm": 0.0714973583817482, + "elapsed": 534.9302124977112 + }, + { + "step": 704, + "loss": 0.552291989326477, + "objective": 0.552291989326477, + "error": 0.3095703125, + "gradient_norm": 0.10188189148902893, + "elapsed": 545.4470670223236 + }, + { + "step": 720, + "loss": 0.4040689468383789, + "objective": 0.4040689468383789, + "error": 0.1943359375, + "gradient_norm": 0.06630362570285797, + "elapsed": 554.2920794487 + }, + { + "step": 736, + "loss": 0.3191133439540863, + "objective": 0.3191133439540863, + "error": 0.15625, + "gradient_norm": 0.060587506741285324, + "elapsed": 562.335791349411 + }, + { + "step": 752, + "loss": 0.5949387550354004, + "objective": 0.5949387550354004, + "error": 0.330078125, + "gradient_norm": 0.051291145384311676, + "elapsed": 570.9363489151001 + }, + { + "step": 768, + "loss": 0.4783790409564972, + "objective": 0.4783790409564972, + "error": 0.244140625, + "gradient_norm": 0.08808670938014984, + "elapsed": 581.1555306911469 + }, + { + "step": 784, + "loss": 0.4414710998535156, + "objective": 0.4414710998535156, + "error": 0.20703125, + "gradient_norm": 0.06632383912801743, + "elapsed": 590.4109175205231 + }, + { + "step": 800, + "loss": 0.2536136507987976, + "objective": 0.2536136507987976, + "error": 0.1142578125, + "gradient_norm": 0.03191893920302391, + "elapsed": 601.43274974823 + }, + { + "step": 816, + "loss": 0.22448071837425232, + "objective": 0.22448071837425232, + "error": 0.1015625, + "gradient_norm": 0.04966023191809654, + "elapsed": 612.7252013683319 + }, + { + "step": 832, + "loss": 0.5342355966567993, + "objective": 0.5342355966567993, + "error": 0.2783203125, + "gradient_norm": 0.05757307633757591, + "elapsed": 623.6647284030914 + }, + { + "step": 848, + "loss": 0.2506354749202728, + "objective": 0.2506354749202728, + "error": 0.109375, + "gradient_norm": 0.03991081938147545, + "elapsed": 635.1636409759521 + }, + { + "step": 864, + "loss": 0.40698009729385376, + "objective": 0.40698009729385376, + "error": 0.1953125, + "gradient_norm": 0.09155476838350296, + "elapsed": 645.2128469944 + }, + { + "step": 880, + "loss": 0.563283383846283, + "objective": 0.563283383846283, + "error": 0.3134765625, + "gradient_norm": 0.11409252882003784, + "elapsed": 659.2946681976318 + }, + { + "step": 896, + "loss": 0.13591040670871735, + "objective": 0.13591040670871735, + "error": 0.064453125, + "gradient_norm": 0.02692740224301815, + "elapsed": 668.6167254447937 + }, + { + "step": 912, + "loss": 0.5798318982124329, + "objective": 0.5798318982124329, + "error": 0.3310546875, + "gradient_norm": 0.06674209237098694, + "elapsed": 680.6492185592651 + }, + { + "step": 928, + "loss": 0.6140691041946411, + "objective": 0.6140691041946411, + "error": 0.3857421875, + "gradient_norm": 0.06117575615644455, + "elapsed": 693.1704411506653 + }, + { + "step": 944, + "loss": 0.3964633643627167, + "objective": 0.3964633643627167, + "error": 0.1865234375, + "gradient_norm": 0.08617512136697769, + "elapsed": 708.2128443717957 + }, + { + "step": 960, + "loss": 0.5512299537658691, + "objective": 0.5512299537658691, + "error": 0.2861328125, + "gradient_norm": 0.05705108866095543, + "elapsed": 720.2417063713074 + }, + { + "step": 976, + "loss": 0.454137921333313, + "objective": 0.454137921333313, + "error": 0.216796875, + "gradient_norm": 0.07962293922901154, + "elapsed": 730.2567391395569 + }, + { + "step": 992, + "loss": 0.5681213140487671, + "objective": 0.5681213140487671, + "error": 0.3017578125, + "gradient_norm": 0.09802286326885223, + "elapsed": 742.7380962371826 + }, + { + "step": 1008, + "loss": 0.13060352206230164, + "objective": 0.13060352206230164, + "error": 0.0537109375, + "gradient_norm": 0.04271279275417328, + "elapsed": 750.8077793121338 + }, + { + "step": 1024, + "loss": 0.6129879355430603, + "objective": 0.6129879355430603, + "error": 0.3603515625, + "gradient_norm": 0.04127912223339081, + "elapsed": 761.0585849285126 + }, + { + "step": 1040, + "loss": 0.31361687183380127, + "objective": 0.31361687183380127, + "error": 0.1455078125, + "gradient_norm": 0.04341907799243927, + "elapsed": 776.3491418361664 + }, + { + "step": 1056, + "loss": 0.6326502561569214, + "objective": 0.6326502561569214, + "error": 0.365234375, + "gradient_norm": 0.07518075406551361, + "elapsed": 786.0424168109894 + }, + { + "step": 1072, + "loss": 0.537599503993988, + "objective": 0.537599503993988, + "error": 0.2958984375, + "gradient_norm": 0.08455493301153183, + "elapsed": 795.1607735157013 + }, + { + "step": 1088, + "loss": 0.5953108072280884, + "objective": 0.5953108072280884, + "error": 0.337890625, + "gradient_norm": 0.06973882764577866, + "elapsed": 804.0053510665894 + }, + { + "step": 1104, + "loss": 0.36860400438308716, + "objective": 0.36860400438308716, + "error": 0.1923828125, + "gradient_norm": 0.04828036576509476, + "elapsed": 813.4029138088226 + }, + { + "step": 1120, + "loss": 0.5423247218132019, + "objective": 0.5423247218132019, + "error": 0.28125, + "gradient_norm": 0.04841453209519386, + "elapsed": 823.626978635788 + }, + { + "step": 1136, + "loss": 0.4766136407852173, + "objective": 0.4766136407852173, + "error": 0.236328125, + "gradient_norm": 0.07564551383256912, + "elapsed": 832.4641265869141 + }, + { + "step": 1152, + "loss": 0.5473434925079346, + "objective": 0.5473434925079346, + "error": 0.2958984375, + "gradient_norm": 0.13677075505256653, + "elapsed": 844.9307618141174 + }, + { + "step": 1168, + "loss": 0.3040686249732971, + "objective": 0.3040686249732971, + "error": 0.150390625, + "gradient_norm": 0.045926257967948914, + "elapsed": 854.336992263794 + }, + { + "step": 1184, + "loss": 0.6298375129699707, + "objective": 0.6298375129699707, + "error": 0.3798828125, + "gradient_norm": 0.06807851791381836, + "elapsed": 864.5731596946716 + }, + { + "step": 1200, + "loss": 0.6272540092468262, + "objective": 0.6272540092468262, + "error": 0.37890625, + "gradient_norm": 0.139838308095932, + "elapsed": 877.8357374668121 + }, + { + "step": 1216, + "loss": 0.5224937200546265, + "objective": 0.5224937200546265, + "error": 0.287109375, + "gradient_norm": 0.0647057592868805, + "elapsed": 887.8107197284698 + }, + { + "step": 1232, + "loss": 0.02408422902226448, + "objective": 0.02408422902226448, + "error": 0.0107421875, + "gradient_norm": 0.007562167476862669, + "elapsed": 902.201171875 + }, + { + "step": 1248, + "loss": 0.01936865597963333, + "objective": 0.01936865597963333, + "error": 0.0048828125, + "gradient_norm": 0.006423021201044321, + "elapsed": 914.0247437953949 + }, + { + "step": 1264, + "loss": 0.47522181272506714, + "objective": 0.47522181272506714, + "error": 0.2490234375, + "gradient_norm": 0.04962826892733574, + "elapsed": 927.0462884902954 + }, + { + "step": 1280, + "loss": 0.019577551633119583, + "objective": 0.019577551633119583, + "error": 0.0068359375, + "gradient_norm": 0.008308992721140385, + "elapsed": 939.3647270202637 + }, + { + "step": 1296, + "loss": 0.5085430145263672, + "objective": 0.5085430145263672, + "error": 0.2734375, + "gradient_norm": 0.06214233115315437, + "elapsed": 949.4259700775146 + }, + { + "step": 1312, + "loss": 0.23232896625995636, + "objective": 0.23232896625995636, + "error": 0.1015625, + "gradient_norm": 0.05894213914871216, + "elapsed": 961.3636543750763 + }, + { + "step": 1328, + "loss": 0.5330536365509033, + "objective": 0.5330536365509033, + "error": 0.2861328125, + "gradient_norm": 0.11579663306474686, + "elapsed": 972.1607241630554 + }, + { + "step": 1344, + "loss": 0.019525721669197083, + "objective": 0.019525721669197083, + "error": 0.0087890625, + "gradient_norm": 0.008134250529110432, + "elapsed": 983.0828921794891 + }, + { + "step": 1360, + "loss": 0.22790294885635376, + "objective": 0.22790294885635376, + "error": 0.103515625, + "gradient_norm": 0.04187086224555969, + "elapsed": 991.3167304992676 + }, + { + "step": 1376, + "loss": 0.48713046312332153, + "objective": 0.48713046312332153, + "error": 0.2666015625, + "gradient_norm": 0.06267429888248444, + "elapsed": 1003.5033710002899 + }, + { + "step": 1392, + "loss": 0.6043434143066406, + "objective": 0.6043434143066406, + "error": 0.369140625, + "gradient_norm": 0.037880122661590576, + "elapsed": 1017.8567223548889 + }, + { + "step": 1408, + "loss": 0.034499723464250565, + "objective": 0.034499723464250565, + "error": 0.0068359375, + "gradient_norm": 0.013505477458238602, + "elapsed": 1027.3547134399414 + }, + { + "step": 1424, + "loss": 0.5320160388946533, + "objective": 0.5320160388946533, + "error": 0.306640625, + "gradient_norm": 0.07510018348693848, + "elapsed": 1036.9454221725464 + }, + { + "step": 1440, + "loss": 0.3451523780822754, + "objective": 0.3451523780822754, + "error": 0.171875, + "gradient_norm": 0.06453985720872879, + "elapsed": 1046.1805095672607 + }, + { + "step": 1456, + "loss": 0.21541815996170044, + "objective": 0.21541815996170044, + "error": 0.08984375, + "gradient_norm": 0.043503839522600174, + "elapsed": 1055.850379705429 + }, + { + "step": 1472, + "loss": 0.43667086958885193, + "objective": 0.43667086958885193, + "error": 0.22265625, + "gradient_norm": 0.07311506569385529, + "elapsed": 1066.6324400901794 + }, + { + "step": 1488, + "loss": 0.6163139939308167, + "objective": 0.6163139939308167, + "error": 0.3779296875, + "gradient_norm": 0.06406569480895996, + "elapsed": 1075.7883398532867 + }, + { + "step": 1504, + "loss": 0.23901250958442688, + "objective": 0.23901250958442688, + "error": 0.10546875, + "gradient_norm": 0.04792191833257675, + "elapsed": 1085.4756922721863 + }, + { + "step": 1520, + "loss": 0.3817014694213867, + "objective": 0.3817014694213867, + "error": 0.18359375, + "gradient_norm": 0.046061187982559204, + "elapsed": 1095.974383354187 + }, + { + "step": 1536, + "loss": 0.5593156814575195, + "objective": 0.5593156814575195, + "error": 0.3017578125, + "gradient_norm": 0.0735388696193695, + "elapsed": 1105.913155078888 + } + ] + }, + "training_source_snapshot": "training_sources/fresh2_full", + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with the recorded physical decoder.", + "physical_prediction_reference": "/run-state/workspace/research/context_upgrades/turbo1/predictions", + "prior_pass": 3, + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.2325420673076923, + "0": 0.23359374999999996, + "blend-0": 0.23372896634615387, + "512": 0.23342848557692306, + "blend-512": 0.23329326923076926, + "1024": 0.23315805288461536, + "blend-1024": 0.23309795673076922, + "1536": 0.2326923076923077, + "blend-1536": 0.23278245192307695 + }, + "selected": "incumbent" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22017728365384615, + "0": 0.22125901442307688, + "blend-0": 0.22125901442307694, + "512": 0.22080829326923082, + "blend-512": 0.2211838942307692, + "1024": 0.22052283653846153, + "blend-1024": 0.22031249999999997, + "1536": 0.21953124999999998, + "blend-1536": 0.21998197115384616 + }, + "selected": "1536" + } + ], + "checkpoints": { + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 491030, + "weights_sha256": "20746e71c276e720074318b0978e6ea0ddc0df206954834f13c7f36354933cea", + "complete": true + } + }, + "runtime": "Share physical priors when the conditioning pass and regime agree; otherwise recompute the neural prior independently. Last-only physical branches omit unused intermediate logical tracking; raw neural branches also omit the unused final physical readout.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false, + "numerical_controls": { + "packaged_runtime_control_cpu": { + "device": "cpu", + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 7, + "same_cpu_old_vs_new_maximum_difference": 0.0, + "old_cpu_vs_original_gpu_evaluation_maximum_difference": 4.971027374267578e-05, + "new_cpu_vs_original_gpu_evaluation_maximum_difference": 4.971027374267578e-05, + "cpu_vs_reconstructed_old_gpu_runtime_maximum_difference": 4.976987838745117e-05, + "original_gpu_evaluation_vs_reconstructed_gpu_runtime_maximum_difference": 7.748603820800781e-07, + "initial_failed_control": { + "comparison": "CPU runtime against original GPU evaluator", + "observed_maximum_difference": 4.971027374267578e-05, + "original_tolerance": 3e-06 + }, + "sources": { + "d5_base_context_model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "d5_context_model.py": "d58bcfe01767228d18ce2078d555abf13037b5df63edf38273ba66f0966ee445", + "d5_contextual.py": "59d6c85dc4bd61e26cf7243baf0e2637c3de1d35327b2c763707badd19446550", + "turbo.py": "c07dce8d7098142f5cd550d594b948290287a8cb2221f70acaeff3965c3dac0b" + }, + "scope": "Same-device compatibility check. Reconstructed GPU runtime removes the recorded equal physical blend; that reconstruction has floating-point rounding uncertainty.", + "status": "passed_same_device_compatibility" + }, + "cpu_probability_precision": { + "condition": "surface_code_bX_d5_r03_center_5_5", + "validation_syndromes": 7, + "logical_labels_used": false, + "parameter_updates": 0, + "reference": "Float64 neural forward and exact contraction from the same stored weights and fixed float32 input logits, on CPU", + "cpu_float32_vs_float64_maximum_difference": 7.624897924163321e-08, + "cpu_float32_edges_float64_contraction_vs_float64_maximum_difference": 4.725248914372315e-08, + "gpu_float32_vs_float64_maximum_difference": 4.964999121059854e-05, + "cpu_vs_gpu_float32_maximum_difference": 4.971027374267578e-05, + "maximum_neural_edge_probability_difference": 2.6330936014895556e-08, + "float32_edge_values_above_one_minus_1e6": 0, + "scope": "Precision diagnostic only; the published model is unchanged. Same-device old/new packaged-code compatibility was independently exact." + }, + "priors_only_control_cpu": { + "status": "passed", + "device": "cpu", + "source_sha256": "c07dce8d7098142f5cd550d594b948290287a8cb2221f70acaeff3965c3dac0b", + "records": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 3, + "priors_bitwise_identical": true, + "normal_seconds_including_compilation": 2.7116777896881104, + "priors_only_seconds_warm": 0.13569164276123047 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 3, + "priors_bitwise_identical": true, + "normal_seconds_including_compilation": 3.557781457901001, + "priors_only_seconds_warm": 1.7711329460144043 + } + ], + "scope": "CPU numerical equivalence on supplied training syndromes; timings are not a controlled speed comparison." + } + } + }, + { + "training": { + "initialization": "Continue from the recorded session-trained checkpoint; original random initialization seed 20261271", + "prior_pass": 3, + "initial_seed": 20261271, + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "Only the18856 declared fit rows per each of26 d5 conditions; both512-row gate and512-row audit partitions excluded from every optimizer update. Uniform condition/within-condition sampling.", + "reserved_training_partition": { + "manifest": "/run-state/workspace/research/learned_d5/reserved_split1/manifest.json", + "manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "selected_part": "fit", + "details": { + "schema": "qecbench-training-reserved-split/v1", + "seed": 20261270, + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "source_sha256": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "conditions": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "file": "surface_code_bX_d5_r01_center_5_5.npz", + "sha256": "c72d5c5ee3daf1b128e0c226f2815009daf6127e8b028004e86cebd6047ac474", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "file": "surface_code_bX_d5_r03_center_5_5.npz", + "sha256": "3a59636161c80fbbf326cf1919817ce5f60ec9e6d3e4b6223579cb6a36e12e31", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "file": "surface_code_bX_d5_r05_center_5_5.npz", + "sha256": "e808936ef0cb32869e0944ab70a3026ef96d0f31fe0fe9967c6d87a15b85abb5", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "file": "surface_code_bX_d5_r07_center_5_5.npz", + "sha256": "cd0f71459448a41af10e4399637d02e8d8193dea16ab300f839cb56ad8b08203", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "file": "surface_code_bX_d5_r09_center_5_5.npz", + "sha256": "56648e2b93499736d40f6aa5e9e8a568f150cbc8589929578f57c1e839c92d76", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "file": "surface_code_bX_d5_r11_center_5_5.npz", + "sha256": "ce2dcc2bfcb57bbfcb2291105a9a011a2a3113ad92348dfa7c76076f1fb3cacf", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "file": "surface_code_bX_d5_r13_center_5_5.npz", + "sha256": "968b14d4d948474afd0e182d9c60cd577297d4b7bb331e916058e41692d7c9d2", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "file": "surface_code_bX_d5_r15_center_5_5.npz", + "sha256": "8d73808a777d81c2acc2f6aab924cc11690a94136bc666fbf11f78292a47615d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "file": "surface_code_bX_d5_r17_center_5_5.npz", + "sha256": "0ab49c9dc61605d43f0c03427352af0ee230ecf7360927f75de60519d707c7ee", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "file": "surface_code_bX_d5_r19_center_5_5.npz", + "sha256": "27594cc6e0943860d828ebde2c76fdde64ccf2a357f896d551f3d4606e74fec4", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "file": "surface_code_bX_d5_r21_center_5_5.npz", + "sha256": "1b1fdcf280ca7c8ba94476f9c54b6ab70eee59b63b3be406a534014132295b7e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "file": "surface_code_bX_d5_r23_center_5_5.npz", + "sha256": "d31e0ca2ce6a6d04ed7bbd80113aec8cca40526b643752d8f429ece168736759", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "file": "surface_code_bX_d5_r25_center_5_5.npz", + "sha256": "f45a5978d77b1ef450f2ffd9fa19413c9d647448a3d61dfafd7590671dcace19", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "file": "surface_code_bZ_d5_r01_center_5_5.npz", + "sha256": "647e82ac0721a7245b3deb831a5a73eb555a3cb3e58b460774ffb96dc99c3b64", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "file": "surface_code_bZ_d5_r03_center_5_5.npz", + "sha256": "b64be8c7883b921bd57d5eefcc53656c2dad484833e5533e499b19b45be90158", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "file": "surface_code_bZ_d5_r05_center_5_5.npz", + "sha256": "63361e091640a4d506fc372bd0764ad248f6551d77cdf57550405b2624ca97b1", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "file": "surface_code_bZ_d5_r07_center_5_5.npz", + "sha256": "c50d26a58c1fb6b5a20f5737b94c3bac9182fe703bafa221532b8b012064f655", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "file": "surface_code_bZ_d5_r09_center_5_5.npz", + "sha256": "d62ecb975d63f13664bc6b02d30499a3fb10f0c22f1068b28bbbc31d1ec91fcc", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "file": "surface_code_bZ_d5_r11_center_5_5.npz", + "sha256": "724c7dc2c4cf2b551abf4f75e230f5aa04a74eebba79c25c845f14d15863de5e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "file": "surface_code_bZ_d5_r13_center_5_5.npz", + "sha256": "0e618a998fb591a85dd365eead741a91b6560ed1a3987046286a67a2c754fa83", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "file": "surface_code_bZ_d5_r15_center_5_5.npz", + "sha256": "e1f8c6f812dc98c48402b69a08b09b520d1374e9f2e51b3e681b67bf306e17be", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "file": "surface_code_bZ_d5_r17_center_5_5.npz", + "sha256": "aa23a51a79677a8ac43cc31b72fe07e73c827f935c632c29b09924fc88242d0d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "file": "surface_code_bZ_d5_r19_center_5_5.npz", + "sha256": "8420b79a8d7324f41dfd1cccacfd1fae9b27b370f40c60059e9de187864dba2b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "file": "surface_code_bZ_d5_r21_center_5_5.npz", + "sha256": "088b92610c90dc1a180b2eca8b16e8f225d191ec7fc11355c85e6959f35e7073", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "file": "surface_code_bZ_d5_r23_center_5_5.npz", + "sha256": "b1484c581cbd5439c74befabbd7c1c12e7cb38db099c793dfb3cf748df20fc3b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "file": "surface_code_bZ_d5_r25_center_5_5.npz", + "sha256": "92f552059b6c197b53ff1030d9ba0fe03cf22ea1f116e5280be944ad60f04be3", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + } + ], + "counts": { + "fit": 490256, + "gate": 13312, + "audit": 13312 + }, + "split_features": "Only array lengths and seeded random permutations; IDs verify alignment and are never model features", + "gate_use": "Fit a small combiner on gate labels only after experts exclude both reserved parts", + "audit_use": "Diagnostic only; no parameter fitting, checkpoint selection, or hyperparameter selection", + "validation_use": "Supplied validation selects checkpoints and candidates; no validation labels fit parameters", + "test_data_used": false + } + }, + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 490256, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 466919, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 18000, + "surface_code_bX_d5_r03_center_5_5": 18251, + "surface_code_bX_d5_r05_center_5_5": 18224, + "surface_code_bX_d5_r07_center_5_5": 17881, + "surface_code_bX_d5_r09_center_5_5": 18247, + "surface_code_bX_d5_r11_center_5_5": 17452, + "surface_code_bX_d5_r13_center_5_5": 17982, + "surface_code_bX_d5_r15_center_5_5": 17498, + "surface_code_bX_d5_r17_center_5_5": 18487, + "surface_code_bX_d5_r19_center_5_5": 18100, + "surface_code_bX_d5_r21_center_5_5": 17622, + "surface_code_bX_d5_r23_center_5_5": 17449, + "surface_code_bX_d5_r25_center_5_5": 17739, + "surface_code_bZ_d5_r01_center_5_5": 16689, + "surface_code_bZ_d5_r03_center_5_5": 18119, + "surface_code_bZ_d5_r05_center_5_5": 18146, + "surface_code_bZ_d5_r07_center_5_5": 18185, + "surface_code_bZ_d5_r09_center_5_5": 18473, + "surface_code_bZ_d5_r11_center_5_5": 18636, + "surface_code_bZ_d5_r13_center_5_5": 18474, + "surface_code_bZ_d5_r15_center_5_5": 17779, + "surface_code_bZ_d5_r17_center_5_5": 18474, + "surface_code_bZ_d5_r19_center_5_5": 17306, + "surface_code_bZ_d5_r21_center_5_5": 17165, + "surface_code_bZ_d5_r23_center_5_5": 18616, + "surface_code_bZ_d5_r25_center_5_5": 17925 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1536, + "batch": 1024, + "learning_rate": 0.0005, + "sampling_seed": 20261272, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": true, + "rng_restored": true, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "/run-state/workspace/research/learned_d5/reserved1_warm/rng-512.json", + "starting_checkpoint": "/run-state/workspace/research/learned_d5/reserved1_warm/weights-512.npz", + "starting_checkpoint_sha256": "1adc47acc35148d4260df25e25384124609d2b1e098ffcf30a1eccea55ef8712", + "starting_training_provenance": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261271", + "prior_pass": 3, + "initial_seed": 20261271, + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "Only the18856 declared fit rows per each of26 d5 conditions; both512-row gate and512-row audit partitions excluded from every optimizer update. Uniform condition/within-condition sampling.", + "reserved_training_partition": { + "manifest": "/run-state/workspace/research/learned_d5/reserved_split1/manifest.json", + "manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "selected_part": "fit", + "details": { + "schema": "qecbench-training-reserved-split/v1", + "seed": 20261270, + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "source_sha256": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "conditions": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "file": "surface_code_bX_d5_r01_center_5_5.npz", + "sha256": "c72d5c5ee3daf1b128e0c226f2815009daf6127e8b028004e86cebd6047ac474", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "file": "surface_code_bX_d5_r03_center_5_5.npz", + "sha256": "3a59636161c80fbbf326cf1919817ce5f60ec9e6d3e4b6223579cb6a36e12e31", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "file": "surface_code_bX_d5_r05_center_5_5.npz", + "sha256": "e808936ef0cb32869e0944ab70a3026ef96d0f31fe0fe9967c6d87a15b85abb5", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "file": "surface_code_bX_d5_r07_center_5_5.npz", + "sha256": "cd0f71459448a41af10e4399637d02e8d8193dea16ab300f839cb56ad8b08203", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "file": "surface_code_bX_d5_r09_center_5_5.npz", + "sha256": "56648e2b93499736d40f6aa5e9e8a568f150cbc8589929578f57c1e839c92d76", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "file": "surface_code_bX_d5_r11_center_5_5.npz", + "sha256": "ce2dcc2bfcb57bbfcb2291105a9a011a2a3113ad92348dfa7c76076f1fb3cacf", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "file": "surface_code_bX_d5_r13_center_5_5.npz", + "sha256": "968b14d4d948474afd0e182d9c60cd577297d4b7bb331e916058e41692d7c9d2", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "file": "surface_code_bX_d5_r15_center_5_5.npz", + "sha256": "8d73808a777d81c2acc2f6aab924cc11690a94136bc666fbf11f78292a47615d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "file": "surface_code_bX_d5_r17_center_5_5.npz", + "sha256": "0ab49c9dc61605d43f0c03427352af0ee230ecf7360927f75de60519d707c7ee", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "file": "surface_code_bX_d5_r19_center_5_5.npz", + "sha256": "27594cc6e0943860d828ebde2c76fdde64ccf2a357f896d551f3d4606e74fec4", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "file": "surface_code_bX_d5_r21_center_5_5.npz", + "sha256": "1b1fdcf280ca7c8ba94476f9c54b6ab70eee59b63b3be406a534014132295b7e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "file": "surface_code_bX_d5_r23_center_5_5.npz", + "sha256": "d31e0ca2ce6a6d04ed7bbd80113aec8cca40526b643752d8f429ece168736759", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "file": "surface_code_bX_d5_r25_center_5_5.npz", + "sha256": "f45a5978d77b1ef450f2ffd9fa19413c9d647448a3d61dfafd7590671dcace19", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "file": "surface_code_bZ_d5_r01_center_5_5.npz", + "sha256": "647e82ac0721a7245b3deb831a5a73eb555a3cb3e58b460774ffb96dc99c3b64", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "file": "surface_code_bZ_d5_r03_center_5_5.npz", + "sha256": "b64be8c7883b921bd57d5eefcc53656c2dad484833e5533e499b19b45be90158", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "file": "surface_code_bZ_d5_r05_center_5_5.npz", + "sha256": "63361e091640a4d506fc372bd0764ad248f6551d77cdf57550405b2624ca97b1", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "file": "surface_code_bZ_d5_r07_center_5_5.npz", + "sha256": "c50d26a58c1fb6b5a20f5737b94c3bac9182fe703bafa221532b8b012064f655", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "file": "surface_code_bZ_d5_r09_center_5_5.npz", + "sha256": "d62ecb975d63f13664bc6b02d30499a3fb10f0c22f1068b28bbbc31d1ec91fcc", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "file": "surface_code_bZ_d5_r11_center_5_5.npz", + "sha256": "724c7dc2c4cf2b551abf4f75e230f5aa04a74eebba79c25c845f14d15863de5e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "file": "surface_code_bZ_d5_r13_center_5_5.npz", + "sha256": "0e618a998fb591a85dd365eead741a91b6560ed1a3987046286a67a2c754fa83", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "file": "surface_code_bZ_d5_r15_center_5_5.npz", + "sha256": "e1f8c6f812dc98c48402b69a08b09b520d1374e9f2e51b3e681b67bf306e17be", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "file": "surface_code_bZ_d5_r17_center_5_5.npz", + "sha256": "aa23a51a79677a8ac43cc31b72fe07e73c827f935c632c29b09924fc88242d0d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "file": "surface_code_bZ_d5_r19_center_5_5.npz", + "sha256": "8420b79a8d7324f41dfd1cccacfd1fae9b27b370f40c60059e9de187864dba2b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "file": "surface_code_bZ_d5_r21_center_5_5.npz", + "sha256": "088b92610c90dc1a180b2eca8b16e8f225d191ec7fc11355c85e6959f35e7073", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "file": "surface_code_bZ_d5_r23_center_5_5.npz", + "sha256": "b1484c581cbd5439c74befabbd7c1c12e7cb38db099c793dfb3cf748df20fc3b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "file": "surface_code_bZ_d5_r25_center_5_5.npz", + "sha256": "92f552059b6c197b53ff1030d9ba0fe03cf22ea1f116e5280be944ad60f04be3", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + } + ], + "counts": { + "fit": 490256, + "gate": 13312, + "audit": 13312 + }, + "split_features": "Only array lengths and seeded random permutations; IDs verify alignment and are never model features", + "gate_use": "Fit a small combiner on gate labels only after experts exclude both reserved parts", + "audit_use": "Diagnostic only; no parameter fitting, checkpoint selection, or hyperparameter selection", + "validation_use": "Supplied validation selects checkpoints and candidates; no validation labels fit parameters", + "test_data_used": false + } + }, + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 490256, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 317613, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 14297, + "surface_code_bX_d5_r03_center_5_5": 11305, + "surface_code_bX_d5_r05_center_5_5": 12479, + "surface_code_bX_d5_r07_center_5_5": 10433, + "surface_code_bX_d5_r09_center_5_5": 10919, + "surface_code_bX_d5_r11_center_5_5": 12516, + "surface_code_bX_d5_r13_center_5_5": 12043, + "surface_code_bX_d5_r15_center_5_5": 12143, + "surface_code_bX_d5_r17_center_5_5": 11354, + "surface_code_bX_d5_r19_center_5_5": 13660, + "surface_code_bX_d5_r21_center_5_5": 13753, + "surface_code_bX_d5_r23_center_5_5": 12161, + "surface_code_bX_d5_r25_center_5_5": 12531, + "surface_code_bZ_d5_r01_center_5_5": 11397, + "surface_code_bZ_d5_r03_center_5_5": 9053, + "surface_code_bZ_d5_r05_center_5_5": 13723, + "surface_code_bZ_d5_r07_center_5_5": 14763, + "surface_code_bZ_d5_r09_center_5_5": 10969, + "surface_code_bZ_d5_r11_center_5_5": 12129, + "surface_code_bZ_d5_r13_center_5_5": 10020, + "surface_code_bZ_d5_r15_center_5_5": 13170, + "surface_code_bZ_d5_r17_center_5_5": 14946, + "surface_code_bZ_d5_r19_center_5_5": 10579, + "surface_code_bZ_d5_r21_center_5_5": 11745, + "surface_code_bZ_d5_r23_center_5_5": 12426, + "surface_code_bZ_d5_r25_center_5_5": 13099 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 512, + "batch": 1024, + "learning_rate": 0.001, + "sampling_seed": 20261272, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "rng_restored": false, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "Fresh NumPy default_rng seed 20261272", + "starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "starting_training_provenance": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.1412775069475174, + "objective": 0.1412775069475174, + "error": 0.0595703125, + "gradient_norm": 0.030735325068235397, + "elapsed": 28.457472801208496 + }, + { + "step": 16, + "loss": 0.6315727233886719, + "objective": 0.6315727233886719, + "error": 0.384765625, + "gradient_norm": 0.06563512235879898, + "elapsed": 47.886730670928955 + }, + { + "step": 32, + "loss": 0.5130410194396973, + "objective": 0.5130410194396973, + "error": 0.263671875, + "gradient_norm": 0.10626910626888275, + "elapsed": 60.16136598587036 + }, + { + "step": 48, + "loss": 0.6413166522979736, + "objective": 0.6413166522979736, + "error": 0.408203125, + "gradient_norm": 0.03790846839547157, + "elapsed": 70.9611382484436 + }, + { + "step": 64, + "loss": 0.5491592884063721, + "objective": 0.5491592884063721, + "error": 0.2939453125, + "gradient_norm": 0.093081034719944, + "elapsed": 81.46673464775085 + }, + { + "step": 80, + "loss": 0.6315242648124695, + "objective": 0.6315242648124695, + "error": 0.359375, + "gradient_norm": 0.0384257510304451, + "elapsed": 91.71172666549683 + }, + { + "step": 96, + "loss": 0.6311566829681396, + "objective": 0.6311566829681396, + "error": 0.3798828125, + "gradient_norm": 0.03731638938188553, + "elapsed": 100.83252763748169 + }, + { + "step": 112, + "loss": 0.5327925682067871, + "objective": 0.5327925682067871, + "error": 0.29296875, + "gradient_norm": 0.11202990263700485, + "elapsed": 111.35073852539062 + }, + { + "step": 128, + "loss": 0.6284654140472412, + "objective": 0.6284654140472412, + "error": 0.3740234375, + "gradient_norm": 0.03215613588690758, + "elapsed": 121.32994651794434 + }, + { + "step": 144, + "loss": 0.33964547514915466, + "objective": 0.33964547514915466, + "error": 0.1259765625, + "gradient_norm": 0.05133189633488655, + "elapsed": 131.2744882106781 + }, + { + "step": 160, + "loss": 0.14193454384803772, + "objective": 0.14193454384803772, + "error": 0.0478515625, + "gradient_norm": 0.03264402225613594, + "elapsed": 139.58473920822144 + }, + { + "step": 176, + "loss": 0.14203950762748718, + "objective": 0.14203950762748718, + "error": 0.0654296875, + "gradient_norm": 0.022548990324139595, + "elapsed": 148.9861602783203 + }, + { + "step": 192, + "loss": 0.6307225227355957, + "objective": 0.6307225227355957, + "error": 0.3955078125, + "gradient_norm": 0.08607082068920135, + "elapsed": 162.27514505386353 + }, + { + "step": 208, + "loss": 0.16193106770515442, + "objective": 0.16193106770515442, + "error": 0.064453125, + "gradient_norm": 0.023293493315577507, + "elapsed": 173.59824013710022 + }, + { + "step": 224, + "loss": 0.5426318049430847, + "objective": 0.5426318049430847, + "error": 0.3037109375, + "gradient_norm": 0.03944721072912216, + "elapsed": 182.70232272148132 + }, + { + "step": 240, + "loss": 0.6270365715026855, + "objective": 0.6270365715026855, + "error": 0.3896484375, + "gradient_norm": 0.14661568403244019, + "elapsed": 193.759183883667 + }, + { + "step": 256, + "loss": 0.4933152198791504, + "objective": 0.4933152198791504, + "error": 0.2724609375, + "gradient_norm": 0.1065438985824585, + "elapsed": 205.62959718704224 + }, + { + "step": 272, + "loss": 0.3671969473361969, + "objective": 0.3671969473361969, + "error": 0.177734375, + "gradient_norm": 0.05156548321247101, + "elapsed": 222.249596118927 + }, + { + "step": 288, + "loss": 0.5478869676589966, + "objective": 0.5478869676589966, + "error": 0.3203125, + "gradient_norm": 0.08357688039541245, + "elapsed": 232.2198715209961 + }, + { + "step": 304, + "loss": 0.21171918511390686, + "objective": 0.21171918511390686, + "error": 0.0849609375, + "gradient_norm": 0.06231697276234627, + "elapsed": 241.07631373405457 + }, + { + "step": 320, + "loss": 0.5333335995674133, + "objective": 0.5333335995674133, + "error": 0.2861328125, + "gradient_norm": 0.08931853622198105, + "elapsed": 251.28962755203247 + }, + { + "step": 336, + "loss": 0.12485946714878082, + "objective": 0.12485946714878082, + "error": 0.046875, + "gradient_norm": 0.018839582800865173, + "elapsed": 262.3605041503906 + }, + { + "step": 352, + "loss": 0.2334863245487213, + "objective": 0.2334863245487213, + "error": 0.09765625, + "gradient_norm": 0.03669576346874237, + "elapsed": 273.16373229026794 + }, + { + "step": 368, + "loss": 0.5818328857421875, + "objective": 0.5818328857421875, + "error": 0.3232421875, + "gradient_norm": 0.09833699464797974, + "elapsed": 282.8677294254303 + }, + { + "step": 384, + "loss": 0.6228232383728027, + "objective": 0.6228232383728027, + "error": 0.3671875, + "gradient_norm": 0.033418990671634674, + "elapsed": 295.04902839660645 + }, + { + "step": 400, + "loss": 0.5749450922012329, + "objective": 0.5749450922012329, + "error": 0.333984375, + "gradient_norm": 0.04644288495182991, + "elapsed": 306.67032837867737 + }, + { + "step": 416, + "loss": 0.46251457929611206, + "objective": 0.46251457929611206, + "error": 0.2216796875, + "gradient_norm": 0.06633804738521576, + "elapsed": 317.759464263916 + }, + { + "step": 432, + "loss": 0.5577508211135864, + "objective": 0.5577508211135864, + "error": 0.30859375, + "gradient_norm": 0.0970199704170227, + "elapsed": 327.4626543521881 + }, + { + "step": 448, + "loss": 0.11625733226537704, + "objective": 0.11625733226537704, + "error": 0.0419921875, + "gradient_norm": 0.020417485386133194, + "elapsed": 336.3522970676422 + }, + { + "step": 464, + "loss": 0.23657961189746857, + "objective": 0.23657961189746857, + "error": 0.1025390625, + "gradient_norm": 0.03908605873584747, + "elapsed": 344.3832321166992 + }, + { + "step": 480, + "loss": 0.011504358612000942, + "objective": 0.011504358612000942, + "error": 0.00390625, + "gradient_norm": 0.006708688102662563, + "elapsed": 355.18855381011963 + }, + { + "step": 496, + "loss": 0.3410624563694, + "objective": 0.3410624563694, + "error": 0.1533203125, + "gradient_norm": 0.05804387852549553, + "elapsed": 366.2978138923645 + }, + { + "step": 512, + "loss": 0.034005306661129, + "objective": 0.034005306661129, + "error": 0.0107421875, + "gradient_norm": 0.01019973959773779, + "elapsed": 375.73491764068604 + } + ], + "reserved_sampling_audit": { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved1_warm", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "b31e8f5ee2b5ea1b661e6bf8b5649bec45b7ab5da74fe9de46e4d06846356b87", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 256, + 512 + ], + "training_draws": 524288, + "distinct_phase_training_rows": 317613, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 14297, + "surface_code_bX_d5_r03_center_5_5": 11305, + "surface_code_bX_d5_r05_center_5_5": 12479, + "surface_code_bX_d5_r07_center_5_5": 10433, + "surface_code_bX_d5_r09_center_5_5": 10919, + "surface_code_bX_d5_r11_center_5_5": 12516, + "surface_code_bX_d5_r13_center_5_5": 12043, + "surface_code_bX_d5_r15_center_5_5": 12143, + "surface_code_bX_d5_r17_center_5_5": 11354, + "surface_code_bX_d5_r19_center_5_5": 13660, + "surface_code_bX_d5_r21_center_5_5": 13753, + "surface_code_bX_d5_r23_center_5_5": 12161, + "surface_code_bX_d5_r25_center_5_5": 12531, + "surface_code_bZ_d5_r01_center_5_5": 11397, + "surface_code_bZ_d5_r03_center_5_5": 9053, + "surface_code_bZ_d5_r05_center_5_5": 13723, + "surface_code_bZ_d5_r07_center_5_5": 14763, + "surface_code_bZ_d5_r09_center_5_5": 10969, + "surface_code_bZ_d5_r11_center_5_5": 12129, + "surface_code_bZ_d5_r13_center_5_5": 10020, + "surface_code_bZ_d5_r15_center_5_5": 13170, + "surface_code_bZ_d5_r17_center_5_5": 14946, + "surface_code_bZ_d5_r19_center_5_5": 10579, + "surface_code_bZ_d5_r21_center_5_5": 11745, + "surface_code_bZ_d5_r23_center_5_5": 12426, + "surface_code_bZ_d5_r25_center_5_5": 13099 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 512, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + "declared_study_plan": { + "hypothesis": "Fresh independent experts with an excluded training partition permit an honest combiner fit and an independent training-period diagnostic", + "experts": [ + { + "name": "reserved1", + "initial_seed": 20261271, + "sampling_seed": 20261272 + }, + { + "name": "reserved2", + "initial_seed": 20261273, + "sampling_seed": 20261274 + } + ], + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "partition": "Per26 d5 conditions:18856 fit,512 combiner,512 diagnostic rows; uniformly random partition seed20261270; sample IDs only check alignment", + "architecture": "Unchanged394-input64-unit neural correction, bound2, fixed physical pass3 priors, exact relevant-CSS contraction", + "training": "Each new expert:512 updates B1024 LR.001 from random initialization;1536 updates LR.0005 restoring own Adam/RNG state. Uniform eligible condition and row sampling, BCE, clip1,AdamW decay1e-4", + "validation_selection": "All26conditions/13durations: main-phase0/512/1024/1536, raw and equal-physical options versus incumbent, then fixed original/new ensembles with physical fractions0/.25/.5. Full replay/contract verification required before publication", + "combiner_expert_selection": "For each new expert and basis, minimum raw full-validation mean failure across0/512/1024/1536; earlier listed checkpoint wins ties. Freeze before using reserved labels", + "combiner_plan": "Fit small regularized syndrome-dependent mixtures using only the512 gate rows/condition. Diagnostic512 rows/condition must not fit or select weights/checkpoints/hyperparameters", + "holdout_prediction_generation": "Both reserved parts predicted without accessing label NPZ members; diagnostics only after final combiner selection is frozen", + "test_data_used": false + }, + "pipeline_control": { + "status": "passed", + "backend": "CPU", + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "control_sha256": "0302573e82d5113dfe1f63080b21b6976cc05b2ddb3677a640b005fc6050aa66", + "audits": [ + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke1", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ad3b3170d682b103f82456476e4a4f7c3096707269b72c242ec43d820dc06856", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 2, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 0, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 1, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke2", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ea2e649b4880641cb0c7e7b7a349d4174ce4dd276c4cdbac376e9c087f00ea1f", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 0, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 2, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 1, + "last_optimizer_count": 2, + "parent_checkpoint_sha256": "faf01476f397259640c31a761f9774af9c0592e9118c38ffdce9502acdfcfb31", + "test_data_used": false + } + ], + "initialization_exact": true, + "parameters_updated": true, + "smoke_runs_excluded_from_selection_and_submission": true, + "test_data_used": false + } + }, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.5523660182952881, + "objective": 0.5523660182952881, + "error": 0.30859375, + "gradient_norm": 0.05200070142745972, + "elapsed": 30.08410096168518 + }, + { + "step": 16, + "loss": 0.5380295515060425, + "objective": 0.5380295515060425, + "error": 0.306640625, + "gradient_norm": 0.0804876759648323, + "elapsed": 50.77648210525513 + }, + { + "step": 32, + "loss": 0.6359301805496216, + "objective": 0.6359301805496216, + "error": 0.3837890625, + "gradient_norm": 0.059380218386650085, + "elapsed": 59.453776836395264 + }, + { + "step": 48, + "loss": 0.2540435492992401, + "objective": 0.2540435492992401, + "error": 0.1083984375, + "gradient_norm": 0.04367281496524811, + "elapsed": 67.29314041137695 + }, + { + "step": 64, + "loss": 0.5867692232131958, + "objective": 0.5867692232131958, + "error": 0.3447265625, + "gradient_norm": 0.053885214030742645, + "elapsed": 78.74847197532654 + }, + { + "step": 80, + "loss": 0.6015321016311646, + "objective": 0.6015321016311646, + "error": 0.365234375, + "gradient_norm": 0.04807985574007034, + "elapsed": 90.48145818710327 + }, + { + "step": 96, + "loss": 0.49287766218185425, + "objective": 0.49287766218185425, + "error": 0.271484375, + "gradient_norm": 0.07899080961942673, + "elapsed": 101.65468978881836 + }, + { + "step": 112, + "loss": 0.3271353542804718, + "objective": 0.3271353542804718, + "error": 0.15234375, + "gradient_norm": 0.049542222172021866, + "elapsed": 111.14713263511658 + }, + { + "step": 128, + "loss": 0.50013667345047, + "objective": 0.50013667345047, + "error": 0.271484375, + "gradient_norm": 0.06454745680093765, + "elapsed": 121.21207547187805 + }, + { + "step": 144, + "loss": 0.028576843440532684, + "objective": 0.028576843440532684, + "error": 0.0087890625, + "gradient_norm": 0.010781333781778812, + "elapsed": 130.69302248954773 + }, + { + "step": 160, + "loss": 0.5668779015541077, + "objective": 0.5668779015541077, + "error": 0.330078125, + "gradient_norm": 0.06098390743136406, + "elapsed": 142.14290237426758 + }, + { + "step": 176, + "loss": 0.3986494839191437, + "objective": 0.3986494839191437, + "error": 0.1884765625, + "gradient_norm": 0.042795032262802124, + "elapsed": 152.75753688812256 + }, + { + "step": 192, + "loss": 0.31897079944610596, + "objective": 0.31897079944610596, + "error": 0.142578125, + "gradient_norm": 0.040675707161426544, + "elapsed": 160.04981398582458 + }, + { + "step": 208, + "loss": 0.5092275142669678, + "objective": 0.5092275142669678, + "error": 0.255859375, + "gradient_norm": 0.07929783314466476, + "elapsed": 169.85345673561096 + }, + { + "step": 224, + "loss": 0.35782667994499207, + "objective": 0.35782667994499207, + "error": 0.1748046875, + "gradient_norm": 0.05785144120454788, + "elapsed": 179.90323066711426 + }, + { + "step": 240, + "loss": 0.5660895109176636, + "objective": 0.5660895109176636, + "error": 0.3349609375, + "gradient_norm": 0.10684454441070557, + "elapsed": 191.3668942451477 + }, + { + "step": 256, + "loss": 0.6265910863876343, + "objective": 0.6265910863876343, + "error": 0.3779296875, + "gradient_norm": 0.034383758902549744, + "elapsed": 200.3055775165558 + }, + { + "step": 272, + "loss": 0.6210677623748779, + "objective": 0.6210677623748779, + "error": 0.369140625, + "gradient_norm": 0.04434216767549515, + "elapsed": 210.09376430511475 + }, + { + "step": 288, + "loss": 0.4892377257347107, + "objective": 0.4892377257347107, + "error": 0.2490234375, + "gradient_norm": 0.1040654331445694, + "elapsed": 220.45881819725037 + }, + { + "step": 304, + "loss": 0.6407739520072937, + "objective": 0.6407739520072937, + "error": 0.3916015625, + "gradient_norm": 0.07782924920320511, + "elapsed": 233.3719048500061 + }, + { + "step": 320, + "loss": 0.4752756953239441, + "objective": 0.4752756953239441, + "error": 0.263671875, + "gradient_norm": 0.051829319447278976, + "elapsed": 244.25844407081604 + }, + { + "step": 336, + "loss": 0.6482080221176147, + "objective": 0.6482080221176147, + "error": 0.41015625, + "gradient_norm": 0.04979892820119858, + "elapsed": 253.1897099018097 + }, + { + "step": 352, + "loss": 0.34022292494773865, + "objective": 0.34022292494773865, + "error": 0.1708984375, + "gradient_norm": 0.09951864182949066, + "elapsed": 264.0781395435333 + }, + { + "step": 368, + "loss": 0.3494992256164551, + "objective": 0.3494992256164551, + "error": 0.15625, + "gradient_norm": 0.10392706841230392, + "elapsed": 275.8111581802368 + }, + { + "step": 384, + "loss": 0.47191378474235535, + "objective": 0.47191378474235535, + "error": 0.25, + "gradient_norm": 0.07366786152124405, + "elapsed": 283.9459602832794 + }, + { + "step": 400, + "loss": 0.583655595779419, + "objective": 0.583655595779419, + "error": 0.3623046875, + "gradient_norm": 0.10394527018070221, + "elapsed": 294.3349726200104 + }, + { + "step": 416, + "loss": 0.6212975978851318, + "objective": 0.6212975978851318, + "error": 0.37109375, + "gradient_norm": 0.054796766489744186, + "elapsed": 304.7477548122406 + }, + { + "step": 432, + "loss": 0.4719577431678772, + "objective": 0.4719577431678772, + "error": 0.2431640625, + "gradient_norm": 0.05418012663722038, + "elapsed": 315.91914200782776 + }, + { + "step": 448, + "loss": 0.5696494579315186, + "objective": 0.5696494579315186, + "error": 0.3330078125, + "gradient_norm": 0.047046076506376266, + "elapsed": 324.96326184272766 + }, + { + "step": 464, + "loss": 0.613875687122345, + "objective": 0.613875687122345, + "error": 0.34765625, + "gradient_norm": 0.05237002298235893, + "elapsed": 334.7670781612396 + }, + { + "step": 480, + "loss": 0.28741705417633057, + "objective": 0.28741705417633057, + "error": 0.1240234375, + "gradient_norm": 0.05365394428372383, + "elapsed": 344.03080439567566 + }, + { + "step": 496, + "loss": 0.3729455769062042, + "objective": 0.3729455769062042, + "error": 0.1875, + "gradient_norm": 0.05905403569340706, + "elapsed": 356.01581716537476 + }, + { + "step": 512, + "loss": 0.38685142993927, + "objective": 0.38685142993927, + "error": 0.17578125, + "gradient_norm": 0.048455506563186646, + "elapsed": 367.7296392917633 + }, + { + "step": 528, + "loss": 0.6062720417976379, + "objective": 0.6062720417976379, + "error": 0.369140625, + "gradient_norm": 0.07544548809528351, + "elapsed": 385.4480962753296 + }, + { + "step": 544, + "loss": 0.520085871219635, + "objective": 0.520085871219635, + "error": 0.279296875, + "gradient_norm": 0.08394371718168259, + "elapsed": 397.71993708610535 + }, + { + "step": 560, + "loss": 0.5944540500640869, + "objective": 0.5944540500640869, + "error": 0.3544921875, + "gradient_norm": 0.05468091368675232, + "elapsed": 406.9417428970337 + }, + { + "step": 576, + "loss": 0.34102559089660645, + "objective": 0.34102559089660645, + "error": 0.1611328125, + "gradient_norm": 0.07333917915821075, + "elapsed": 417.0068130493164 + }, + { + "step": 592, + "loss": 0.47373664379119873, + "objective": 0.47373664379119873, + "error": 0.2412109375, + "gradient_norm": 0.05662858858704567, + "elapsed": 425.1176447868347 + }, + { + "step": 608, + "loss": 0.48517894744873047, + "objective": 0.48517894744873047, + "error": 0.25, + "gradient_norm": 0.08127480745315552, + "elapsed": 434.92080903053284 + }, + { + "step": 624, + "loss": 0.39865612983703613, + "objective": 0.39865612983703613, + "error": 0.1904296875, + "gradient_norm": 0.07332058995962143, + "elapsed": 446.6602101325989 + }, + { + "step": 640, + "loss": 0.41867297887802124, + "objective": 0.41867297887802124, + "error": 0.2177734375, + "gradient_norm": 0.07386308163404465, + "elapsed": 457.0243580341339 + }, + { + "step": 656, + "loss": 0.5108687877655029, + "objective": 0.5108687877655029, + "error": 0.2822265625, + "gradient_norm": 0.052080318331718445, + "elapsed": 469.5842761993408 + }, + { + "step": 672, + "loss": 0.5043742656707764, + "objective": 0.5043742656707764, + "error": 0.2734375, + "gradient_norm": 0.047204963862895966, + "elapsed": 479.356397151947 + }, + { + "step": 688, + "loss": 0.5550935864448547, + "objective": 0.5550935864448547, + "error": 0.30078125, + "gradient_norm": 0.04080262407660484, + "elapsed": 489.9912152290344 + }, + { + "step": 704, + "loss": 0.5698974132537842, + "objective": 0.5698974132537842, + "error": 0.322265625, + "gradient_norm": 0.10692963004112244, + "elapsed": 500.3283371925354 + }, + { + "step": 720, + "loss": 0.45870622992515564, + "objective": 0.45870622992515564, + "error": 0.2255859375, + "gradient_norm": 0.06705734878778458, + "elapsed": 509.82279753685 + }, + { + "step": 736, + "loss": 0.555386483669281, + "objective": 0.555386483669281, + "error": 0.31640625, + "gradient_norm": 0.05112688988447189, + "elapsed": 518.507036447525 + }, + { + "step": 752, + "loss": 0.14282986521720886, + "objective": 0.14282986521720886, + "error": 0.056640625, + "gradient_norm": 0.03209136053919792, + "elapsed": 529.1373023986816 + }, + { + "step": 768, + "loss": 0.5362129807472229, + "objective": 0.5362129807472229, + "error": 0.2841796875, + "gradient_norm": 0.049996186047792435, + "elapsed": 538.9186007976532 + }, + { + "step": 784, + "loss": 0.5071826577186584, + "objective": 0.5071826577186584, + "error": 0.2744140625, + "gradient_norm": 0.04826078191399574, + "elapsed": 549.5225830078125 + }, + { + "step": 800, + "loss": 0.24775367975234985, + "objective": 0.24775367975234985, + "error": 0.107421875, + "gradient_norm": 0.06889795511960983, + "elapsed": 560.7170543670654 + }, + { + "step": 816, + "loss": 0.17432856559753418, + "objective": 0.17432856559753418, + "error": 0.06640625, + "gradient_norm": 0.05147368833422661, + "elapsed": 570.7887880802155 + }, + { + "step": 832, + "loss": 0.5410823822021484, + "objective": 0.5410823822021484, + "error": 0.3115234375, + "gradient_norm": 0.11862928420305252, + "elapsed": 581.9721121788025 + }, + { + "step": 848, + "loss": 0.5555508732795715, + "objective": 0.5555508732795715, + "error": 0.296875, + "gradient_norm": 0.060369592159986496, + "elapsed": 592.2823219299316 + }, + { + "step": 864, + "loss": 0.31839215755462646, + "objective": 0.31839215755462646, + "error": 0.1552734375, + "gradient_norm": 0.063877172768116, + "elapsed": 603.1910541057587 + }, + { + "step": 880, + "loss": 0.481766939163208, + "objective": 0.481766939163208, + "error": 0.2470703125, + "gradient_norm": 0.1623816341161728, + "elapsed": 614.4277107715607 + }, + { + "step": 896, + "loss": 0.5780366659164429, + "objective": 0.5780366659164429, + "error": 0.3037109375, + "gradient_norm": 0.06694691628217697, + "elapsed": 623.9365792274475 + }, + { + "step": 912, + "loss": 0.4794909358024597, + "objective": 0.4794909358024597, + "error": 0.2314453125, + "gradient_norm": 0.07813122123479843, + "elapsed": 633.9845306873322 + }, + { + "step": 928, + "loss": 0.6279138922691345, + "objective": 0.6279138922691345, + "error": 0.380859375, + "gradient_norm": 0.047679927200078964, + "elapsed": 643.7766675949097 + }, + { + "step": 944, + "loss": 0.6401606798171997, + "objective": 0.6401606798171997, + "error": 0.3994140625, + "gradient_norm": 0.07329051941633224, + "elapsed": 655.2369928359985 + }, + { + "step": 960, + "loss": 0.4340277910232544, + "objective": 0.4340277910232544, + "error": 0.2158203125, + "gradient_norm": 0.11762503534555435, + "elapsed": 666.9884371757507 + }, + { + "step": 976, + "loss": 0.44496864080429077, + "objective": 0.44496864080429077, + "error": 0.2236328125, + "gradient_norm": 0.05260347202420235, + "elapsed": 677.3464586734772 + }, + { + "step": 992, + "loss": 0.13230293989181519, + "objective": 0.13230293989181519, + "error": 0.05078125, + "gradient_norm": 0.030240925028920174, + "elapsed": 685.7275724411011 + }, + { + "step": 1008, + "loss": 0.2971688508987427, + "objective": 0.2971688508987427, + "error": 0.1171875, + "gradient_norm": 0.05503479763865471, + "elapsed": 694.1270356178284 + }, + { + "step": 1024, + "loss": 0.5688735246658325, + "objective": 0.5688735246658325, + "error": 0.314453125, + "gradient_norm": 0.06526188552379608, + "elapsed": 703.9192817211151 + }, + { + "step": 1040, + "loss": 0.42805811762809753, + "objective": 0.42805811762809753, + "error": 0.2080078125, + "gradient_norm": 0.13000032305717468, + "elapsed": 720.145961523056 + }, + { + "step": 1056, + "loss": 0.5543602705001831, + "objective": 0.5543602705001831, + "error": 0.298828125, + "gradient_norm": 0.15922385454177856, + "elapsed": 733.5112845897675 + }, + { + "step": 1072, + "loss": 0.031130114570260048, + "objective": 0.031130114570260048, + "error": 0.013671875, + "gradient_norm": 0.008926023729145527, + "elapsed": 742.4467866420746 + }, + { + "step": 1088, + "loss": 0.14947748184204102, + "objective": 0.14947748184204102, + "error": 0.056640625, + "gradient_norm": 0.03975249081850052, + "elapsed": 751.8575854301453 + }, + { + "step": 1104, + "loss": 0.6275734901428223, + "objective": 0.6275734901428223, + "error": 0.3671875, + "gradient_norm": 0.08096148073673248, + "elapsed": 761.5625903606415 + }, + { + "step": 1120, + "loss": 0.23923414945602417, + "objective": 0.23923414945602417, + "error": 0.0966796875, + "gradient_norm": 0.03325376287102699, + "elapsed": 773.9633615016937 + }, + { + "step": 1136, + "loss": 0.570243239402771, + "objective": 0.570243239402771, + "error": 0.31640625, + "gradient_norm": 0.07534287869930267, + "elapsed": 783.1533136367798 + }, + { + "step": 1152, + "loss": 0.4264270067214966, + "objective": 0.4264270067214966, + "error": 0.2119140625, + "gradient_norm": 0.08900073170661926, + "elapsed": 792.1710996627808 + }, + { + "step": 1168, + "loss": 0.5958121418952942, + "objective": 0.5958121418952942, + "error": 0.3583984375, + "gradient_norm": 0.08239343762397766, + "elapsed": 803.1175289154053 + }, + { + "step": 1184, + "loss": 0.2909137010574341, + "objective": 0.2909137010574341, + "error": 0.1416015625, + "gradient_norm": 0.05281354859471321, + "elapsed": 812.6055159568787 + }, + { + "step": 1200, + "loss": 0.6119058728218079, + "objective": 0.6119058728218079, + "error": 0.36328125, + "gradient_norm": 0.056254416704177856, + "elapsed": 823.2276427745819 + }, + { + "step": 1216, + "loss": 0.13595536351203918, + "objective": 0.13595536351203918, + "error": 0.0556640625, + "gradient_norm": 0.04057573154568672, + "elapsed": 834.1696293354034 + }, + { + "step": 1232, + "loss": 0.5840731263160706, + "objective": 0.5840731263160706, + "error": 0.328125, + "gradient_norm": 0.054566267877817154, + "elapsed": 845.3501887321472 + }, + { + "step": 1248, + "loss": 0.3053072690963745, + "objective": 0.3053072690963745, + "error": 0.1337890625, + "gradient_norm": 0.04617297649383545, + "elapsed": 854.9564871788025 + }, + { + "step": 1264, + "loss": 0.6288673281669617, + "objective": 0.6288673281669617, + "error": 0.3994140625, + "gradient_norm": 0.08229745179414749, + "elapsed": 864.8914043903351 + }, + { + "step": 1280, + "loss": 0.5586361289024353, + "objective": 0.5586361289024353, + "error": 0.2958984375, + "gradient_norm": 0.05713959410786629, + "elapsed": 877.0349607467651 + }, + { + "step": 1296, + "loss": 0.3648858666419983, + "objective": 0.3648858666419983, + "error": 0.16796875, + "gradient_norm": 0.08502963185310364, + "elapsed": 888.5764675140381 + }, + { + "step": 1312, + "loss": 0.4747084081172943, + "objective": 0.4747084081172943, + "error": 0.244140625, + "gradient_norm": 0.08609883487224579, + "elapsed": 899.7598609924316 + }, + { + "step": 1328, + "loss": 0.15583917498588562, + "objective": 0.15583917498588562, + "error": 0.05859375, + "gradient_norm": 0.027793049812316895, + "elapsed": 909.47514295578 + }, + { + "step": 1344, + "loss": 0.47515708208084106, + "objective": 0.47515708208084106, + "error": 0.263671875, + "gradient_norm": 0.07668807357549667, + "elapsed": 919.7640328407288 + }, + { + "step": 1360, + "loss": 0.5173689126968384, + "objective": 0.5173689126968384, + "error": 0.2744140625, + "gradient_norm": 0.05054212734103203, + "elapsed": 930.6309463977814 + }, + { + "step": 1376, + "loss": 0.46629998087882996, + "objective": 0.46629998087882996, + "error": 0.24609375, + "gradient_norm": 0.051172077655792236, + "elapsed": 939.0202586650848 + }, + { + "step": 1392, + "loss": 0.11312969774007797, + "objective": 0.11312969774007797, + "error": 0.044921875, + "gradient_norm": 0.05863805115222931, + "elapsed": 949.1451416015625 + }, + { + "step": 1408, + "loss": 0.5750841498374939, + "objective": 0.5750841498374939, + "error": 0.322265625, + "gradient_norm": 0.051106806844472885, + "elapsed": 959.94162940979 + }, + { + "step": 1424, + "loss": 0.5937192440032959, + "objective": 0.5937192440032959, + "error": 0.3408203125, + "gradient_norm": 0.05014815554022789, + "elapsed": 969.5868306159973 + }, + { + "step": 1440, + "loss": 0.5292985439300537, + "objective": 0.5292985439300537, + "error": 0.2958984375, + "gradient_norm": 0.057068243622779846, + "elapsed": 982.6692054271698 + }, + { + "step": 1456, + "loss": 0.5959951877593994, + "objective": 0.5959951877593994, + "error": 0.3408203125, + "gradient_norm": 0.0703694075345993, + "elapsed": 995.0066986083984 + }, + { + "step": 1472, + "loss": 0.018453411757946014, + "objective": 0.018453411757946014, + "error": 0.00390625, + "gradient_norm": 0.012016087770462036, + "elapsed": 1004.0057821273804 + }, + { + "step": 1488, + "loss": 0.5711684823036194, + "objective": 0.5711684823036194, + "error": 0.3095703125, + "gradient_norm": 0.07746906578540802, + "elapsed": 1016.1701967716217 + }, + { + "step": 1504, + "loss": 0.3114882707595825, + "objective": 0.3114882707595825, + "error": 0.1455078125, + "gradient_norm": 0.05321609228849411, + "elapsed": 1026.6053586006165 + }, + { + "step": 1520, + "loss": 0.6433392763137817, + "objective": 0.6433392763137817, + "error": 0.4072265625, + "gradient_norm": 0.05683734640479088, + "elapsed": 1036.1535296440125 + }, + { + "step": 1536, + "loss": 0.38409170508384705, + "objective": 0.38409170508384705, + "error": 0.19140625, + "gradient_norm": 0.07577994465827942, + "elapsed": 1046.9508447647095 + } + ], + "reserved_sampling_audit": { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved1_full", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "7b45252d6bb77a39c003c8f34f040d0d672e9dd1a1338a14126e1fe07a02c8c9", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 512, + 1024, + 1536 + ], + "training_draws": 1572864, + "distinct_phase_training_rows": 466919, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 18000, + "surface_code_bX_d5_r03_center_5_5": 18251, + "surface_code_bX_d5_r05_center_5_5": 18224, + "surface_code_bX_d5_r07_center_5_5": 17881, + "surface_code_bX_d5_r09_center_5_5": 18247, + "surface_code_bX_d5_r11_center_5_5": 17452, + "surface_code_bX_d5_r13_center_5_5": 17982, + "surface_code_bX_d5_r15_center_5_5": 17498, + "surface_code_bX_d5_r17_center_5_5": 18487, + "surface_code_bX_d5_r19_center_5_5": 18100, + "surface_code_bX_d5_r21_center_5_5": 17622, + "surface_code_bX_d5_r23_center_5_5": 17449, + "surface_code_bX_d5_r25_center_5_5": 17739, + "surface_code_bZ_d5_r01_center_5_5": 16689, + "surface_code_bZ_d5_r03_center_5_5": 18119, + "surface_code_bZ_d5_r05_center_5_5": 18146, + "surface_code_bZ_d5_r07_center_5_5": 18185, + "surface_code_bZ_d5_r09_center_5_5": 18473, + "surface_code_bZ_d5_r11_center_5_5": 18636, + "surface_code_bZ_d5_r13_center_5_5": 18474, + "surface_code_bZ_d5_r15_center_5_5": 17779, + "surface_code_bZ_d5_r17_center_5_5": 18474, + "surface_code_bZ_d5_r19_center_5_5": 17306, + "surface_code_bZ_d5_r21_center_5_5": 17165, + "surface_code_bZ_d5_r23_center_5_5": 18616, + "surface_code_bZ_d5_r25_center_5_5": 17925 + }, + "initial_optimizer_count": 512, + "last_optimizer_count": 2048, + "parent_checkpoint_sha256": "1adc47acc35148d4260df25e25384124609d2b1e098ffcf30a1eccea55ef8712", + "test_data_used": false + }, + "declared_study_plan": { + "hypothesis": "Fresh independent experts with an excluded training partition permit an honest combiner fit and an independent training-period diagnostic", + "experts": [ + { + "name": "reserved1", + "initial_seed": 20261271, + "sampling_seed": 20261272 + }, + { + "name": "reserved2", + "initial_seed": 20261273, + "sampling_seed": 20261274 + } + ], + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "partition": "Per26 d5 conditions:18856 fit,512 combiner,512 diagnostic rows; uniformly random partition seed20261270; sample IDs only check alignment", + "architecture": "Unchanged394-input64-unit neural correction, bound2, fixed physical pass3 priors, exact relevant-CSS contraction", + "training": "Each new expert:512 updates B1024 LR.001 from random initialization;1536 updates LR.0005 restoring own Adam/RNG state. Uniform eligible condition and row sampling, BCE, clip1,AdamW decay1e-4", + "validation_selection": "All26conditions/13durations: main-phase0/512/1024/1536, raw and equal-physical options versus incumbent, then fixed original/new ensembles with physical fractions0/.25/.5. Full replay/contract verification required before publication", + "combiner_expert_selection": "For each new expert and basis, minimum raw full-validation mean failure across0/512/1024/1536; earlier listed checkpoint wins ties. Freeze before using reserved labels", + "combiner_plan": "Fit small regularized syndrome-dependent mixtures using only the512 gate rows/condition. Diagnostic512 rows/condition must not fit or select weights/checkpoints/hyperparameters", + "holdout_prediction_generation": "Both reserved parts predicted without accessing label NPZ members; diagnostics only after final combiner selection is frozen", + "test_data_used": false + }, + "pipeline_control": { + "status": "passed", + "backend": "CPU", + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "control_sha256": "0302573e82d5113dfe1f63080b21b6976cc05b2ddb3677a640b005fc6050aa66", + "audits": [ + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke1", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ad3b3170d682b103f82456476e4a4f7c3096707269b72c242ec43d820dc06856", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 2, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 0, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 1, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke2", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ea2e649b4880641cb0c7e7b7a349d4174ce4dd276c4cdbac376e9c087f00ea1f", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 0, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 2, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 1, + "last_optimizer_count": 2, + "parent_checkpoint_sha256": "faf01476f397259640c31a761f9774af9c0592e9118c38ffdce9502acdfcfb31", + "test_data_used": false + } + ], + "initialization_exact": true, + "parameters_updated": true, + "smoke_runs_excluded_from_selection_and_submission": true, + "test_data_used": false + } + }, + "training_source_snapshot": "training_sources/reserved1_full", + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with the recorded physical decoder.", + "physical_prediction_reference": "/run-state/workspace/research/context_upgrades/turbo1/predictions", + "prior_pass": 3, + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23228665865384618, + "0": 0.2337439903846154, + "blend-0": 0.23366887019230773, + "512": 0.23284254807692306, + "blend-512": 0.23275240384615387, + "1024": 0.23356370192307693, + "blend-1024": 0.23315805288461536, + "1536": 0.23218149038461539, + "blend-1536": 0.2330378605769231 + }, + "selected": "1536" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.21953124999999998, + "0": 0.2206580528846154, + "blend-0": 0.2208683894230769, + "512": 0.22100360576923078, + "blend-512": 0.2208984375, + "1024": 0.22104867788461538, + "blend-1024": 0.22019230769230771, + "1536": 0.22264122596153849, + "blend-1536": 0.22032752403846154 + }, + "selected": "incumbent" + } + ], + "checkpoints": { + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 466919, + "weights_sha256": "65a762bc0623024c3fbc416ff5df00d8ea275f6c7d691a54c6e0492f459a362f", + "complete": true + } + }, + "runtime": "Share physical priors when the conditioning pass and regime agree; otherwise recompute the neural prior independently. Last-only physical branches omit unused intermediate logical tracking; raw neural branches also omit the unused final physical readout.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false, + "numerical_controls": { + "packaged_runtime_control_cpu": { + "device": "cpu", + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 7, + "same_cpu_old_vs_new_maximum_difference": 0.0, + "old_cpu_vs_original_gpu_evaluation_maximum_difference": 4.971027374267578e-05, + "new_cpu_vs_original_gpu_evaluation_maximum_difference": 4.971027374267578e-05, + "cpu_vs_reconstructed_old_gpu_runtime_maximum_difference": 4.976987838745117e-05, + "original_gpu_evaluation_vs_reconstructed_gpu_runtime_maximum_difference": 7.748603820800781e-07, + "initial_failed_control": { + "comparison": "CPU runtime against original GPU evaluator", + "observed_maximum_difference": 4.971027374267578e-05, + "original_tolerance": 3e-06 + }, + "sources": { + "d5_base_context_model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "d5_context_model.py": "53342e15dcbb8bc2dd0b288d75ea115fb504be99a33bc283a518b9d76232cd99", + "d5_temporal_context_model.py": "d58bcfe01767228d18ce2078d555abf13037b5df63edf38273ba66f0966ee445", + "d5_history_context_model.py": "4cc383b4909ff740bccfd20b687f8ee46866e67f93f82fe6c4bace162149ffb4", + "d5_history_features.py": "d709cd54225aa1b14707afa436314c8392f59f748a0007d988c6d18dedd275ee", + "d5_contextual.py": "59d6c85dc4bd61e26cf7243baf0e2637c3de1d35327b2c763707badd19446550", + "turbo.py": "c07dce8d7098142f5cd550d594b948290287a8cb2221f70acaeff3965c3dac0b" + }, + "scope": "Same-device compatibility check. Reconstructed GPU runtime removes the recorded equal physical blend; that reconstruction has floating-point rounding uncertainty.", + "status": "passed_same_device_compatibility" + }, + "dispatcher_control_cpu": { + "status": "passed", + "device": "cpu", + "sources": { + "d5_context_model.py": "53342e15dcbb8bc2dd0b288d75ea115fb504be99a33bc283a518b9d76232cd99", + "d5_base_context_model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "d5_temporal_context_model.py": "d58bcfe01767228d18ce2078d555abf13037b5df63edf38273ba66f0966ee445", + "d5_history_context_model.py": "4cc383b4909ff740bccfd20b687f8ee46866e67f93f82fe6c4bace162149ffb4", + "d5_history_features.py": "d709cd54225aa1b14707afa436314c8392f59f748a0007d988c6d18dedd275ee" + }, + "cases": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "base64", + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "base128", + "weights_sha256": "2a21869e7669492fac8252131434b2e09c97f1def2714988382ab7f127371bd8", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "temporal", + "weights_sha256": "9446a1e6dc46e1bcae540531e4f124930bb151ebfa600746ca77bc8f5b2aaa7c", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "history", + "weights_sha256": "c508d8968ffa143be4219a207fb54ece3e1bfe144b8a880e4ed4f3d13f092c1e", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "base64", + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "base128", + "weights_sha256": "2a21869e7669492fac8252131434b2e09c97f1def2714988382ab7f127371bd8", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "temporal", + "weights_sha256": "9446a1e6dc46e1bcae540531e4f124930bb151ebfa600746ca77bc8f5b2aaa7c", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "history", + "weights_sha256": "c508d8968ffa143be4219a207fb54ece3e1bfe144b8a880e4ed4f3d13f092c1e", + "maximum_edge_probability_difference": 0.0 + } + ], + "scope": "Routing and code-copy check against each direct model implementation, using training detector inputs without labels. Tiny trained temporal/history smoke weights test nonzero feature couplings; they are excluded from model selection and submission.", + "test_data_used": false + }, + "cpu_probability_precision": { + "condition": "surface_code_bX_d5_r03_center_5_5", + "validation_syndromes": 7, + "logical_labels_used": false, + "parameter_updates": 0, + "reference": "Float64 neural forward and exact contraction from the same stored weights and fixed float32 input logits, on CPU", + "cpu_float32_vs_float64_maximum_difference": 7.624897924163321e-08, + "cpu_float32_edges_float64_contraction_vs_float64_maximum_difference": 4.725248914372315e-08, + "gpu_float32_vs_float64_maximum_difference": 4.964999121059854e-05, + "cpu_vs_gpu_float32_maximum_difference": 4.971027374267578e-05, + "maximum_neural_edge_probability_difference": 2.6330936014895556e-08, + "float32_edge_values_above_one_minus_1e6": 0, + "scope": "Precision diagnostic only; the published model is unchanged. Same-device old/new packaged-code compatibility was independently exact." + }, + "priors_only_control_cpu": { + "status": "passed", + "device": "cpu", + "source_sha256": "c07dce8d7098142f5cd550d594b948290287a8cb2221f70acaeff3965c3dac0b", + "records": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 3, + "priors_bitwise_identical": true, + "normal_seconds_including_compilation": 2.7116777896881104, + "priors_only_seconds_warm": 0.13569164276123047 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 3, + "priors_bitwise_identical": true, + "normal_seconds_including_compilation": 3.557781457901001, + "priors_only_seconds_warm": 1.7711329460144043 + } + ], + "scope": "CPU numerical equivalence on supplied training syndromes; timings are not a controlled speed comparison." + } + } + } + ], + "short_syndrome_updates": [ + { + "training": { + "initialization": "256 residual logits per condition initialized independently Normal(0,.01), seeds20261126 through20261133; optimized in this session", + "architecture": "One categorical residual per possible8-bit detection syndrome, added to an exact physical DEM logit; no sample IDs or row indices are model features", + "loss": "Binomial logical BCE sufficient statistics plus strength times cross entropy to the fixed physical prior; damped Newton optimization from random residual initialization", + "fixed_prior": "Exact full-DEM probabilities for all256 possible input syndromes, computed now from the authorized packaged even-fitted DEM plans; no external trained weights or decoder answers", + "training": "All19880 supplied training labels for each of eight d3 one-round conditions; only aggregate counts by detection syndrome enter fitting", + "data_scope": "This is a finite categorical classifier, indexed by detection events, not a per-shot answer table. Other122 conditions retain the incumbent in any candidate benchmark.", + "selection": "One common strength and optional equal probability blend for all eight geometries/bases, minimizing full validation mean; all other conditions unchanged", + "base_package": { + "package": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/package", + "predictions": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/predictions", + "score": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/score.json", + "P": 0.7663217397836538 + }, + "test_data_used": false, + "training_records": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "training_shots": 19880, + "observed_syndromes": 149, + "initial_seed": 20261126, + "physical_plan_sha256": "640c371577096ba08c799b70fd16d03a06a37004feaa15c85c4cb6ef87529080", + "training_arrays_sha256": "a7acd6f6e5372873cf2d34946876a791996238efdea39f7fa33f7d2eabc1c10f" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "training_shots": 19880, + "observed_syndromes": 157, + "initial_seed": 20261127, + "physical_plan_sha256": "4a0f8f630b7f34fba620a4e03bd77e14fb80149e70b7da80b6176dbd24d9ddc8", + "training_arrays_sha256": "0e2267afc5dc4e761d3b9e09288875f2077215fac2f902ce4151699c38c24531" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "training_shots": 19880, + "observed_syndromes": 152, + "initial_seed": 20261128, + "physical_plan_sha256": "de8914194be7689d70e9424540923197a5c0465fb42ec96556df97b73ba250c1", + "training_arrays_sha256": "0542609248a5d2c8b410666bb901361b60c39cb8b32b3b46fdd24a6c7913db56" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "training_shots": 19880, + "observed_syndromes": 147, + "initial_seed": 20261129, + "physical_plan_sha256": "bc1a6888cc5a854f0348cab463b8879c2d176d9509176b944b7f4265e0772ab3", + "training_arrays_sha256": "ccd43f09fba55b2138a5401e6f5c89cc7b4c4ec470a07cd037d9f715acaa1188" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "training_shots": 19880, + "observed_syndromes": 153, + "initial_seed": 20261130, + "physical_plan_sha256": "1931b5b85d0014c2a928a40c3ec502316ff30ea1632a25c5f64e2694f828434b", + "training_arrays_sha256": "aa27eee730c88b2071b5fd97f9d47a0f3ad010e29202415f786babc073d405e4" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "training_shots": 19880, + "observed_syndromes": 159, + "initial_seed": 20261131, + "physical_plan_sha256": "6d231f857bbe85040c91af1160c2dda16557a67851deaedc8092412f6abeb294", + "training_arrays_sha256": "569131ce49a2c1060ebd472c0290fc0c1de6e522cd7cd7aa92b10e17cdd1783c" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "training_shots": 19880, + "observed_syndromes": 158, + "initial_seed": 20261132, + "physical_plan_sha256": "ef285cea44ad63e0452596d4be65c8844ea8a7dcc49fb31b6a6241d367ed63eb", + "training_arrays_sha256": "6928ade685b05f76b7a3a9dc6423504d0bdce09742603c24978aa21fcf106f88" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "training_shots": 19880, + "observed_syndromes": 160, + "initial_seed": 20261133, + "physical_plan_sha256": "82bee01cf3e00079270a27cb79472322867548df5c9dc4db3252e4c6ec89e6a6", + "training_arrays_sha256": "afbc73fc5ca8e3b8e996377ab3df5a5b9397f36362e72c01feea7848ea1995f3" + } + ], + "records": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 16, + "seed": 20261126, + "iterations": 8, + "failure": 0.0134765625, + "blended_failure": 0.013671875, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.04649575086997129, + "weights_sha256": "d985985dedbe644bfae165330f4f46da14d04efbc4cad1af81c5510115380701" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 64, + "seed": 20261126, + "iterations": 6, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.04591998541695955, + "weights_sha256": "17383d153dd1dfef62b3d4f6c5b7549c3209150faf0714e78fede09b941ecc3a" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 256, + "seed": 20261126, + "iterations": 5, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.0458401737684183, + "weights_sha256": "f863a64ca698135f6fac6ac184d3c689db684a15d73bf0565418b240d76b5c58" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 1024, + "seed": 20261126, + "iterations": 5, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.045887733186657405, + "weights_sha256": "ded1a941e0dfc58e55ced6523720445fb70032d2d15c9929b0c93544f7c567f8" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 16, + "seed": 20261127, + "iterations": 8, + "failure": 0.0177734375, + "blended_failure": 0.0177734375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.05532273244895745, + "weights_sha256": "02950043334a38d3e7980cc97685904338553746653bd2d6a4c9be88ae845270" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 64, + "seed": 20261127, + "iterations": 6, + "failure": 0.01875, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.055166841080990084, + "weights_sha256": "412ee1f453695e4f3534dbe8d7eb1ca565d06fd7c718b52fe9a306b35e845d9d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 256, + "seed": 20261127, + "iterations": 5, + "failure": 0.01953125, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.055186840974757456, + "weights_sha256": "12d8f72c2ee5cb837145aaf9a1b485d8517e4374721eebcbea9803d3bfdc8fcd" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 1024, + "seed": 20261127, + "iterations": 4, + "failure": 0.01953125, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.05544033886527203, + "weights_sha256": "d1daa90794c1c3c8cd00134d9b22a7173aee4dd9b139b86f6d3f9b8f2131056d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 16, + "seed": 20261128, + "iterations": 7, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.049592331750930654, + "weights_sha256": "ad21a8640e2fe7bbd550225e354dedcbad8cb70433b892f45d28fa2346ab88de" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 64, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04900882633372332, + "weights_sha256": "4664564f60149b00b1754a3f9e91c8b04b29ef819b231bf17ea7588346433a57" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 256, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04861554683295004, + "weights_sha256": "cad51322361a95020501afa64e356f2a49dd02afa0cd91294d4498f7eb0c5a8d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 1024, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04843255984360956, + "weights_sha256": "5fe850e6313cb9ed6631697684afeeb7b7c5857a5c74fad66189cfcf8a08218b" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 16, + "seed": 20261129, + "iterations": 7, + "failure": 0.0158203125, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05156220348280275, + "weights_sha256": "56c2fd4a7c35033084020cd1f5c9dcc2ab1cf2c631d0e88cc87ac4c715c6af17" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 64, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05139675960346585, + "weights_sha256": "0bf66368e18c8d1baecaa614d4c0cec16304ac14bcd29d22d1cdb2a0ff6c0173" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 256, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05135569004239689, + "weights_sha256": "d9581a6f29f9d3ea54d482c17995a37b55e3b4253d36e1d49cfce95b398eb5c2" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 1024, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05141882723288258, + "weights_sha256": "2c4e4592067fcbbe69d6ede68c4494209652a2d510e74aa2ea3b4420c3cdd741" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 16, + "seed": 20261130, + "iterations": 7, + "failure": 0.0173828125, + "blended_failure": 0.0173828125, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.054216247940585036, + "weights_sha256": "7b12f028f764293a9496d9fd2ddbf92ba9c23653d7889a602a9ec23f8cde3d6b" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 64, + "seed": 20261130, + "iterations": 6, + "failure": 0.017578125, + "blended_failure": 0.0171875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05364509063427466, + "weights_sha256": "1ad2ffaafa33009129a0953d79fe2d30ad62308eb9dbf8da0b76eca018a5b55a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 256, + "seed": 20261130, + "iterations": 5, + "failure": 0.0171875, + "blended_failure": 0.016796875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05368896256105915, + "weights_sha256": "64619c9b7bd40a14651bcd056d58f5b55e79eb334a4e5105ff12cb7ff6f2400a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 1024, + "seed": 20261130, + "iterations": 6, + "failure": 0.0171875, + "blended_failure": 0.016796875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05387292464104988, + "weights_sha256": "b1490702e212d7cdcc936f55186b15411ced3a8928a1a32f2d4ac1212706fabf" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 16, + "seed": 20261131, + "iterations": 8, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04709647994869577, + "weights_sha256": "eb56715dfc5e8c6b8866ceeb2636422acad9992dd2c625355dc21b94c25351f0" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 64, + "seed": 20261131, + "iterations": 6, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.046679107084477436, + "weights_sha256": "320cd10cc8cd9d13d20d9ce0ea90413ed8343587f0c77abb0e1c8c84503aa2d8" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 256, + "seed": 20261131, + "iterations": 5, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04621785858320204, + "weights_sha256": "c7e63309de0668bd4d5c05169ecd6af1879c88be10947d0fdb958ca37068d433" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 1024, + "seed": 20261131, + "iterations": 4, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04577880173787941, + "weights_sha256": "494824e979e52fbf0302e706ff6786d89ce60b607afd6b376cad9700f328feda" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 16, + "seed": 20261132, + "iterations": 7, + "failure": 0.01484375, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.05068038016752655, + "weights_sha256": "0b4c35df1d44c9353a2ea505205f3def95bb28de0c7052ded18cf599bef2709b" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 64, + "seed": 20261132, + "iterations": 6, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.049663607204405706, + "weights_sha256": "b18deed32b51a58789873a1b45718f5c40d1d9500b57e113520b700a66902f1a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 256, + "seed": 20261132, + "iterations": 5, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.04918133832768282, + "weights_sha256": "12e71625e223602cbc9f7ae150473a1dad2c32f2d9221a4b88ccb93babc2c41d" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 1024, + "seed": 20261132, + "iterations": 6, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.049002647954447996, + "weights_sha256": "e909b83698caba60ad01e28027b28005544cd8e795f88574fc6f81bcf56b2add" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 16, + "seed": 20261133, + "iterations": 7, + "failure": 0.016015625, + "blended_failure": 0.016015625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05204562159505248, + "weights_sha256": "b03b071238dda333574a4da2d9b2bb999cf362a83b9194b1c53871e9438f9f45" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 64, + "seed": 20261133, + "iterations": 6, + "failure": 0.016015625, + "blended_failure": 0.016015625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05177096705064832, + "weights_sha256": "2a4c8113ee9a1dadcfc0f1b7ff8d164e7c8771d5764b0512ee1a5de2a8aaa395" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 256, + "seed": 20261133, + "iterations": 6, + "failure": 0.016015625, + "blended_failure": 0.01640625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.051861030681133645, + "weights_sha256": "f201491af84870ffa8c1b59e16dea1fea910e7fda32f0e3d82863943222b57ee" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 1024, + "seed": 20261133, + "iterations": 6, + "failure": 0.01640625, + "blended_failure": 0.01640625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05206536190640361, + "weights_sha256": "b7cfd76b6574457626306868e31ab5327a1950cbbca41f6384eb2c4bc759e800" + } + ], + "choices": { + "incumbent": 0.0154541015625, + "16": 0.015380859375, + "blend-16": 0.015429687499999999, + "64": 0.0155029296875, + "blend-64": 0.015600585937500001, + "256": 0.0155517578125, + "blend-256": 0.015600585937500001, + "1024": 0.0156005859375, + "blend-1024": 0.015600585937500001 + }, + "selected": "16", + "expected_full_P": 0.7663245567908653, + "validation_P_gain": 2.817007211538435e-06, + "source_sha256": "7e75f14190b18b05e9af540a8ef0f75522060e78c30b05475686ea18faf0035f", + "seconds": 3.316046953201294 + }, + "packaging_selection": { + "incumbent": 0.0154541015625, + "16": 0.015380859375, + "64": 0.0155029296875, + "256": 0.0155517578125, + "1024": 0.0156005859375 + }, + "selected": "16", + "selection_scope": "One common prior strength for all eight short conditions; other122 condition predictions retained", + "runtime_source_sha256": "451ce740551f9e13348064f2e726e7e31a611b64bcf5d95def601deb78e854af" + }, + { + "training": { + "initialization": "256 residual logits per condition initialized independently Normal(0,.01), seeds20261126 through20261133; optimized in this session", + "architecture": "One categorical residual per possible8-bit detection syndrome, added to an exact physical DEM logit; no sample IDs or row indices are model features", + "loss": "Binomial logical BCE sufficient statistics plus strength times cross entropy to the fixed physical prior; damped Newton optimization from random residual initialization", + "fixed_prior": "Exact full-DEM probabilities for all256 possible input syndromes, computed now from the authorized packaged even-fitted DEM plans; no external trained weights or decoder answers", + "training": "All19880 supplied training labels for each of eight d3 one-round conditions; only aggregate counts by detection syndrome enter fitting", + "data_scope": "This is a finite categorical classifier, indexed by detection events, not a per-shot answer table. Other122 conditions retain the incumbent in any candidate benchmark.", + "selection": "One common strength and optional equal probability blend for all eight geometries/bases, minimizing full validation mean; all other conditions unchanged", + "base_package": { + "package": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/package", + "predictions": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/predictions", + "score": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/score.json", + "P": 0.7663217397836538 + }, + "test_data_used": false, + "training_records": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "training_shots": 19880, + "observed_syndromes": 149, + "initial_seed": 20261126, + "physical_plan_sha256": "640c371577096ba08c799b70fd16d03a06a37004feaa15c85c4cb6ef87529080", + "training_arrays_sha256": "a7acd6f6e5372873cf2d34946876a791996238efdea39f7fa33f7d2eabc1c10f" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "training_shots": 19880, + "observed_syndromes": 157, + "initial_seed": 20261127, + "physical_plan_sha256": "4a0f8f630b7f34fba620a4e03bd77e14fb80149e70b7da80b6176dbd24d9ddc8", + "training_arrays_sha256": "0e2267afc5dc4e761d3b9e09288875f2077215fac2f902ce4151699c38c24531" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "training_shots": 19880, + "observed_syndromes": 152, + "initial_seed": 20261128, + "physical_plan_sha256": "de8914194be7689d70e9424540923197a5c0465fb42ec96556df97b73ba250c1", + "training_arrays_sha256": "0542609248a5d2c8b410666bb901361b60c39cb8b32b3b46fdd24a6c7913db56" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "training_shots": 19880, + "observed_syndromes": 147, + "initial_seed": 20261129, + "physical_plan_sha256": "bc1a6888cc5a854f0348cab463b8879c2d176d9509176b944b7f4265e0772ab3", + "training_arrays_sha256": "ccd43f09fba55b2138a5401e6f5c89cc7b4c4ec470a07cd037d9f715acaa1188" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "training_shots": 19880, + "observed_syndromes": 153, + "initial_seed": 20261130, + "physical_plan_sha256": "1931b5b85d0014c2a928a40c3ec502316ff30ea1632a25c5f64e2694f828434b", + "training_arrays_sha256": "aa27eee730c88b2071b5fd97f9d47a0f3ad010e29202415f786babc073d405e4" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "training_shots": 19880, + "observed_syndromes": 159, + "initial_seed": 20261131, + "physical_plan_sha256": "6d231f857bbe85040c91af1160c2dda16557a67851deaedc8092412f6abeb294", + "training_arrays_sha256": "569131ce49a2c1060ebd472c0290fc0c1de6e522cd7cd7aa92b10e17cdd1783c" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "training_shots": 19880, + "observed_syndromes": 158, + "initial_seed": 20261132, + "physical_plan_sha256": "ef285cea44ad63e0452596d4be65c8844ea8a7dcc49fb31b6a6241d367ed63eb", + "training_arrays_sha256": "6928ade685b05f76b7a3a9dc6423504d0bdce09742603c24978aa21fcf106f88" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "training_shots": 19880, + "observed_syndromes": 160, + "initial_seed": 20261133, + "physical_plan_sha256": "82bee01cf3e00079270a27cb79472322867548df5c9dc4db3252e4c6ec89e6a6", + "training_arrays_sha256": "afbc73fc5ca8e3b8e996377ab3df5a5b9397f36362e72c01feea7848ea1995f3" + } + ], + "records": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 16, + "seed": 20261126, + "iterations": 8, + "failure": 0.0134765625, + "blended_failure": 0.013671875, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.04649575086997129, + "weights_sha256": "d985985dedbe644bfae165330f4f46da14d04efbc4cad1af81c5510115380701" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 64, + "seed": 20261126, + "iterations": 6, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.04591998541695955, + "weights_sha256": "17383d153dd1dfef62b3d4f6c5b7549c3209150faf0714e78fede09b941ecc3a" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 256, + "seed": 20261126, + "iterations": 5, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.0458401737684183, + "weights_sha256": "f863a64ca698135f6fac6ac184d3c689db684a15d73bf0565418b240d76b5c58" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 1024, + "seed": 20261126, + "iterations": 5, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.045887733186657405, + "weights_sha256": "ded1a941e0dfc58e55ced6523720445fb70032d2d15c9929b0c93544f7c567f8" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 16, + "seed": 20261127, + "iterations": 8, + "failure": 0.0177734375, + "blended_failure": 0.0177734375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.05532273244895745, + "weights_sha256": "02950043334a38d3e7980cc97685904338553746653bd2d6a4c9be88ae845270" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 64, + "seed": 20261127, + "iterations": 6, + "failure": 0.01875, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.055166841080990084, + "weights_sha256": "412ee1f453695e4f3534dbe8d7eb1ca565d06fd7c718b52fe9a306b35e845d9d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 256, + "seed": 20261127, + "iterations": 5, + "failure": 0.01953125, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.055186840974757456, + "weights_sha256": "12d8f72c2ee5cb837145aaf9a1b485d8517e4374721eebcbea9803d3bfdc8fcd" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 1024, + "seed": 20261127, + "iterations": 4, + "failure": 0.01953125, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.05544033886527203, + "weights_sha256": "d1daa90794c1c3c8cd00134d9b22a7173aee4dd9b139b86f6d3f9b8f2131056d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 16, + "seed": 20261128, + "iterations": 7, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.049592331750930654, + "weights_sha256": "ad21a8640e2fe7bbd550225e354dedcbad8cb70433b892f45d28fa2346ab88de" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 64, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04900882633372332, + "weights_sha256": "4664564f60149b00b1754a3f9e91c8b04b29ef819b231bf17ea7588346433a57" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 256, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04861554683295004, + "weights_sha256": "cad51322361a95020501afa64e356f2a49dd02afa0cd91294d4498f7eb0c5a8d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 1024, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04843255984360956, + "weights_sha256": "5fe850e6313cb9ed6631697684afeeb7b7c5857a5c74fad66189cfcf8a08218b" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 16, + "seed": 20261129, + "iterations": 7, + "failure": 0.0158203125, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05156220348280275, + "weights_sha256": "56c2fd4a7c35033084020cd1f5c9dcc2ab1cf2c631d0e88cc87ac4c715c6af17" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 64, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05139675960346585, + "weights_sha256": "0bf66368e18c8d1baecaa614d4c0cec16304ac14bcd29d22d1cdb2a0ff6c0173" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 256, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05135569004239689, + "weights_sha256": "d9581a6f29f9d3ea54d482c17995a37b55e3b4253d36e1d49cfce95b398eb5c2" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 1024, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05141882723288258, + "weights_sha256": "2c4e4592067fcbbe69d6ede68c4494209652a2d510e74aa2ea3b4420c3cdd741" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 16, + "seed": 20261130, + "iterations": 7, + "failure": 0.0173828125, + "blended_failure": 0.0173828125, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.054216247940585036, + "weights_sha256": "7b12f028f764293a9496d9fd2ddbf92ba9c23653d7889a602a9ec23f8cde3d6b" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 64, + "seed": 20261130, + "iterations": 6, + "failure": 0.017578125, + "blended_failure": 0.0171875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05364509063427466, + "weights_sha256": "1ad2ffaafa33009129a0953d79fe2d30ad62308eb9dbf8da0b76eca018a5b55a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 256, + "seed": 20261130, + "iterations": 5, + "failure": 0.0171875, + "blended_failure": 0.016796875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05368896256105915, + "weights_sha256": "64619c9b7bd40a14651bcd056d58f5b55e79eb334a4e5105ff12cb7ff6f2400a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 1024, + "seed": 20261130, + "iterations": 6, + "failure": 0.0171875, + "blended_failure": 0.016796875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05387292464104988, + "weights_sha256": "b1490702e212d7cdcc936f55186b15411ced3a8928a1a32f2d4ac1212706fabf" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 16, + "seed": 20261131, + "iterations": 8, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04709647994869577, + "weights_sha256": "eb56715dfc5e8c6b8866ceeb2636422acad9992dd2c625355dc21b94c25351f0" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 64, + "seed": 20261131, + "iterations": 6, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.046679107084477436, + "weights_sha256": "320cd10cc8cd9d13d20d9ce0ea90413ed8343587f0c77abb0e1c8c84503aa2d8" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 256, + "seed": 20261131, + "iterations": 5, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04621785858320204, + "weights_sha256": "c7e63309de0668bd4d5c05169ecd6af1879c88be10947d0fdb958ca37068d433" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 1024, + "seed": 20261131, + "iterations": 4, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04577880173787941, + "weights_sha256": "494824e979e52fbf0302e706ff6786d89ce60b607afd6b376cad9700f328feda" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 16, + "seed": 20261132, + "iterations": 7, + "failure": 0.01484375, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.05068038016752655, + "weights_sha256": "0b4c35df1d44c9353a2ea505205f3def95bb28de0c7052ded18cf599bef2709b" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 64, + "seed": 20261132, + "iterations": 6, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.049663607204405706, + "weights_sha256": "b18deed32b51a58789873a1b45718f5c40d1d9500b57e113520b700a66902f1a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 256, + "seed": 20261132, + "iterations": 5, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.04918133832768282, + "weights_sha256": "12e71625e223602cbc9f7ae150473a1dad2c32f2d9221a4b88ccb93babc2c41d" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 1024, + "seed": 20261132, + "iterations": 6, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.049002647954447996, + "weights_sha256": "e909b83698caba60ad01e28027b28005544cd8e795f88574fc6f81bcf56b2add" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 16, + "seed": 20261133, + "iterations": 7, + "failure": 0.016015625, + "blended_failure": 0.016015625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05204562159505248, + "weights_sha256": "b03b071238dda333574a4da2d9b2bb999cf362a83b9194b1c53871e9438f9f45" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 64, + "seed": 20261133, + "iterations": 6, + "failure": 0.016015625, + "blended_failure": 0.016015625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05177096705064832, + "weights_sha256": "2a4c8113ee9a1dadcfc0f1b7ff8d164e7c8771d5764b0512ee1a5de2a8aaa395" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 256, + "seed": 20261133, + "iterations": 6, + "failure": 0.016015625, + "blended_failure": 0.01640625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.051861030681133645, + "weights_sha256": "f201491af84870ffa8c1b59e16dea1fea910e7fda32f0e3d82863943222b57ee" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 1024, + "seed": 20261133, + "iterations": 6, + "failure": 0.01640625, + "blended_failure": 0.01640625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05206536190640361, + "weights_sha256": "b7cfd76b6574457626306868e31ab5327a1950cbbca41f6384eb2c4bc759e800" + } + ], + "choices": { + "incumbent": 0.0154541015625, + "16": 0.015380859375, + "blend-16": 0.015429687499999999, + "64": 0.0155029296875, + "blend-64": 0.015600585937500001, + "256": 0.0155517578125, + "blend-256": 0.015600585937500001, + "1024": 0.0156005859375, + "blend-1024": 0.015600585937500001 + }, + "selected": "16", + "expected_full_P": 0.7663245567908653, + "validation_P_gain": 2.817007211538435e-06, + "source_sha256": "7e75f14190b18b05e9af540a8ef0f75522060e78c30b05475686ea18faf0035f", + "seconds": 3.316046953201294 + }, + "packaging_selection": { + "incumbent": 0.0154296875, + "16": 0.015380859375, + "64": 0.0155029296875, + "256": 0.0155517578125, + "1024": 0.0156005859375 + }, + "selected": "16", + "new_optimizer_updates": 0, + "selection_scope": "One common prior strength for all eight short conditions; other122 condition predictions retained", + "runtime_source_sha256": "451ce740551f9e13348064f2e726e7e31a611b64bcf5d95def601deb78e854af" + }, + { + "training": { + "initialization": "256 residual logits per condition initialized independently Normal(0,.01), seeds20261126 through20261133; optimized in this session", + "architecture": "One categorical residual per possible8-bit detection syndrome, added to an exact physical DEM logit; no sample IDs or row indices are model features", + "loss": "Binomial logical BCE sufficient statistics plus strength times cross entropy to the fixed physical prior; damped Newton optimization from random residual initialization", + "fixed_prior": "Exact full-DEM probabilities for all256 possible input syndromes, computed now from the authorized packaged even-fitted DEM plans; no external trained weights or decoder answers", + "training": "All19880 supplied training labels for each of eight d3 one-round conditions; only aggregate counts by detection syndrome enter fitting", + "data_scope": "This is a finite categorical classifier, indexed by detection events, not a per-shot answer table. Other122 conditions retain the incumbent in any candidate benchmark.", + "selection": "One common strength and optional equal probability blend for all eight geometries/bases, minimizing full validation mean; all other conditions unchanged", + "base_package": { + "package": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/package", + "predictions": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/predictions", + "score": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/score.json", + "P": 0.7663217397836538 + }, + "test_data_used": false, + "training_records": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "training_shots": 19880, + "observed_syndromes": 149, + "initial_seed": 20261126, + "physical_plan_sha256": "640c371577096ba08c799b70fd16d03a06a37004feaa15c85c4cb6ef87529080", + "training_arrays_sha256": "a7acd6f6e5372873cf2d34946876a791996238efdea39f7fa33f7d2eabc1c10f" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "training_shots": 19880, + "observed_syndromes": 157, + "initial_seed": 20261127, + "physical_plan_sha256": "4a0f8f630b7f34fba620a4e03bd77e14fb80149e70b7da80b6176dbd24d9ddc8", + "training_arrays_sha256": "0e2267afc5dc4e761d3b9e09288875f2077215fac2f902ce4151699c38c24531" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "training_shots": 19880, + "observed_syndromes": 152, + "initial_seed": 20261128, + "physical_plan_sha256": "de8914194be7689d70e9424540923197a5c0465fb42ec96556df97b73ba250c1", + "training_arrays_sha256": "0542609248a5d2c8b410666bb901361b60c39cb8b32b3b46fdd24a6c7913db56" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "training_shots": 19880, + "observed_syndromes": 147, + "initial_seed": 20261129, + "physical_plan_sha256": "bc1a6888cc5a854f0348cab463b8879c2d176d9509176b944b7f4265e0772ab3", + "training_arrays_sha256": "ccd43f09fba55b2138a5401e6f5c89cc7b4c4ec470a07cd037d9f715acaa1188" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "training_shots": 19880, + "observed_syndromes": 153, + "initial_seed": 20261130, + "physical_plan_sha256": "1931b5b85d0014c2a928a40c3ec502316ff30ea1632a25c5f64e2694f828434b", + "training_arrays_sha256": "aa27eee730c88b2071b5fd97f9d47a0f3ad010e29202415f786babc073d405e4" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "training_shots": 19880, + "observed_syndromes": 159, + "initial_seed": 20261131, + "physical_plan_sha256": "6d231f857bbe85040c91af1160c2dda16557a67851deaedc8092412f6abeb294", + "training_arrays_sha256": "569131ce49a2c1060ebd472c0290fc0c1de6e522cd7cd7aa92b10e17cdd1783c" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "training_shots": 19880, + "observed_syndromes": 158, + "initial_seed": 20261132, + "physical_plan_sha256": "ef285cea44ad63e0452596d4be65c8844ea8a7dcc49fb31b6a6241d367ed63eb", + "training_arrays_sha256": "6928ade685b05f76b7a3a9dc6423504d0bdce09742603c24978aa21fcf106f88" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "training_shots": 19880, + "observed_syndromes": 160, + "initial_seed": 20261133, + "physical_plan_sha256": "82bee01cf3e00079270a27cb79472322867548df5c9dc4db3252e4c6ec89e6a6", + "training_arrays_sha256": "afbc73fc5ca8e3b8e996377ab3df5a5b9397f36362e72c01feea7848ea1995f3" + } + ], + "records": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 16, + "seed": 20261126, + "iterations": 8, + "failure": 0.0134765625, + "blended_failure": 0.013671875, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.04649575086997129, + "weights_sha256": "d985985dedbe644bfae165330f4f46da14d04efbc4cad1af81c5510115380701" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 64, + "seed": 20261126, + "iterations": 6, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.04591998541695955, + "weights_sha256": "17383d153dd1dfef62b3d4f6c5b7549c3209150faf0714e78fede09b941ecc3a" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 256, + "seed": 20261126, + "iterations": 5, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.0458401737684183, + "weights_sha256": "f863a64ca698135f6fac6ac184d3c689db684a15d73bf0565418b240d76b5c58" + }, + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "prior_strength": 1024, + "seed": 20261126, + "iterations": 5, + "failure": 0.0140625, + "blended_failure": 0.0140625, + "incumbent_failure": 0.0134765625, + "negative_log_likelihood": 0.045887733186657405, + "weights_sha256": "ded1a941e0dfc58e55ced6523720445fb70032d2d15c9929b0c93544f7c567f8" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 16, + "seed": 20261127, + "iterations": 8, + "failure": 0.0177734375, + "blended_failure": 0.0177734375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.05532273244895745, + "weights_sha256": "02950043334a38d3e7980cc97685904338553746653bd2d6a4c9be88ae845270" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 64, + "seed": 20261127, + "iterations": 6, + "failure": 0.01875, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.055166841080990084, + "weights_sha256": "412ee1f453695e4f3534dbe8d7eb1ca565d06fd7c718b52fe9a306b35e845d9d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 256, + "seed": 20261127, + "iterations": 5, + "failure": 0.01953125, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.055186840974757456, + "weights_sha256": "12d8f72c2ee5cb837145aaf9a1b485d8517e4374721eebcbea9803d3bfdc8fcd" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_3", + "prior_strength": 1024, + "seed": 20261127, + "iterations": 4, + "failure": 0.01953125, + "blended_failure": 0.0193359375, + "incumbent_failure": 0.0193359375, + "negative_log_likelihood": 0.05544033886527203, + "weights_sha256": "d1daa90794c1c3c8cd00134d9b22a7173aee4dd9b139b86f6d3f9b8f2131056d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 16, + "seed": 20261128, + "iterations": 7, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.049592331750930654, + "weights_sha256": "ad21a8640e2fe7bbd550225e354dedcbad8cb70433b892f45d28fa2346ab88de" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 64, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04900882633372332, + "weights_sha256": "4664564f60149b00b1754a3f9e91c8b04b29ef819b231bf17ea7588346433a57" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 256, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04861554683295004, + "weights_sha256": "cad51322361a95020501afa64e356f2a49dd02afa0cd91294d4498f7eb0c5a8d" + }, + { + "condition": "surface_code_bX_d3_r01_center_5_7", + "prior_strength": 1024, + "seed": 20261128, + "iterations": 6, + "failure": 0.015234375, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.0158203125, + "negative_log_likelihood": 0.04843255984360956, + "weights_sha256": "5fe850e6313cb9ed6631697684afeeb7b7c5857a5c74fad66189cfcf8a08218b" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 16, + "seed": 20261129, + "iterations": 7, + "failure": 0.0158203125, + "blended_failure": 0.0158203125, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05156220348280275, + "weights_sha256": "56c2fd4a7c35033084020cd1f5c9dcc2ab1cf2c631d0e88cc87ac4c715c6af17" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 64, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05139675960346585, + "weights_sha256": "0bf66368e18c8d1baecaa614d4c0cec16304ac14bcd29d22d1cdb2a0ff6c0173" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 256, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05135569004239689, + "weights_sha256": "d9581a6f29f9d3ea54d482c17995a37b55e3b4253d36e1d49cfce95b398eb5c2" + }, + { + "condition": "surface_code_bX_d3_r01_center_7_5", + "prior_strength": 1024, + "seed": 20261129, + "iterations": 6, + "failure": 0.0154296875, + "blended_failure": 0.0154296875, + "incumbent_failure": 0.01484375, + "negative_log_likelihood": 0.05141882723288258, + "weights_sha256": "2c4e4592067fcbbe69d6ede68c4494209652a2d510e74aa2ea3b4420c3cdd741" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 16, + "seed": 20261130, + "iterations": 7, + "failure": 0.0173828125, + "blended_failure": 0.0173828125, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.054216247940585036, + "weights_sha256": "7b12f028f764293a9496d9fd2ddbf92ba9c23653d7889a602a9ec23f8cde3d6b" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 64, + "seed": 20261130, + "iterations": 6, + "failure": 0.017578125, + "blended_failure": 0.0171875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05364509063427466, + "weights_sha256": "1ad2ffaafa33009129a0953d79fe2d30ad62308eb9dbf8da0b76eca018a5b55a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 256, + "seed": 20261130, + "iterations": 5, + "failure": 0.0171875, + "blended_failure": 0.016796875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05368896256105915, + "weights_sha256": "64619c9b7bd40a14651bcd056d58f5b55e79eb334a4e5105ff12cb7ff6f2400a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_3_5", + "prior_strength": 1024, + "seed": 20261130, + "iterations": 6, + "failure": 0.0171875, + "blended_failure": 0.016796875, + "incumbent_failure": 0.016796875, + "negative_log_likelihood": 0.05387292464104988, + "weights_sha256": "b1490702e212d7cdcc936f55186b15411ced3a8928a1a32f2d4ac1212706fabf" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 16, + "seed": 20261131, + "iterations": 8, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04709647994869577, + "weights_sha256": "eb56715dfc5e8c6b8866ceeb2636422acad9992dd2c625355dc21b94c25351f0" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 64, + "seed": 20261131, + "iterations": 6, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.046679107084477436, + "weights_sha256": "320cd10cc8cd9d13d20d9ce0ea90413ed8343587f0c77abb0e1c8c84503aa2d8" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 256, + "seed": 20261131, + "iterations": 5, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04621785858320204, + "weights_sha256": "c7e63309de0668bd4d5c05169ecd6af1879c88be10947d0fdb958ca37068d433" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_3", + "prior_strength": 1024, + "seed": 20261131, + "iterations": 4, + "failure": 0.0125, + "blended_failure": 0.0125, + "incumbent_failure": 0.0125, + "negative_log_likelihood": 0.04577880173787941, + "weights_sha256": "494824e979e52fbf0302e706ff6786d89ce60b607afd6b376cad9700f328feda" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 16, + "seed": 20261132, + "iterations": 7, + "failure": 0.01484375, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.05068038016752655, + "weights_sha256": "0b4c35df1d44c9353a2ea505205f3def95bb28de0c7052ded18cf599bef2709b" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 64, + "seed": 20261132, + "iterations": 6, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.049663607204405706, + "weights_sha256": "b18deed32b51a58789873a1b45718f5c40d1d9500b57e113520b700a66902f1a" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 256, + "seed": 20261132, + "iterations": 5, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.04918133832768282, + "weights_sha256": "12e71625e223602cbc9f7ae150473a1dad2c32f2d9221a4b88ccb93babc2c41d" + }, + { + "condition": "surface_code_bZ_d3_r01_center_5_7", + "prior_strength": 1024, + "seed": 20261132, + "iterations": 6, + "failure": 0.014453125, + "blended_failure": 0.014453125, + "incumbent_failure": 0.014453125, + "negative_log_likelihood": 0.049002647954447996, + "weights_sha256": "e909b83698caba60ad01e28027b28005544cd8e795f88574fc6f81bcf56b2add" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 16, + "seed": 20261133, + "iterations": 7, + "failure": 0.016015625, + "blended_failure": 0.016015625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05204562159505248, + "weights_sha256": "b03b071238dda333574a4da2d9b2bb999cf362a83b9194b1c53871e9438f9f45" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 64, + "seed": 20261133, + "iterations": 6, + "failure": 0.016015625, + "blended_failure": 0.016015625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05177096705064832, + "weights_sha256": "2a4c8113ee9a1dadcfc0f1b7ff8d164e7c8771d5764b0512ee1a5de2a8aaa395" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 256, + "seed": 20261133, + "iterations": 6, + "failure": 0.016015625, + "blended_failure": 0.01640625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.051861030681133645, + "weights_sha256": "f201491af84870ffa8c1b59e16dea1fea910e7fda32f0e3d82863943222b57ee" + }, + { + "condition": "surface_code_bZ_d3_r01_center_7_5", + "prior_strength": 1024, + "seed": 20261133, + "iterations": 6, + "failure": 0.01640625, + "blended_failure": 0.01640625, + "incumbent_failure": 0.01640625, + "negative_log_likelihood": 0.05206536190640361, + "weights_sha256": "b7cfd76b6574457626306868e31ab5327a1950cbbca41f6384eb2c4bc759e800" + } + ], + "choices": { + "incumbent": 0.0154541015625, + "16": 0.015380859375, + "blend-16": 0.015429687499999999, + "64": 0.0155029296875, + "blend-64": 0.015600585937500001, + "256": 0.0155517578125, + "blend-256": 0.015600585937500001, + "1024": 0.0156005859375, + "blend-1024": 0.015600585937500001 + }, + "selected": "16", + "expected_full_P": 0.7663245567908653, + "validation_P_gain": 2.817007211538435e-06, + "source_sha256": "7e75f14190b18b05e9af540a8ef0f75522060e78c30b05475686ea18faf0035f", + "seconds": 3.316046953201294 + }, + "packaging_selection": { + "incumbent": 0.0155517578125, + "16": 0.015380859375, + "64": 0.0155029296875, + "256": 0.0155517578125, + "1024": 0.0156005859375 + }, + "selected": "16", + "new_optimizer_updates": 0, + "selection_scope": "One common prior strength for all eight short conditions; other122 condition predictions retained", + "runtime_source_sha256": "451ce740551f9e13348064f2e726e7e31a611b64bcf5d95def601deb78e854af" + } + ], + "research_selection_history": { + "path": "selection_history.json", + "sha256": "843e686c59c2f32d1081c1786edaf534d7aebe52ffc452150eed62c921c71f25", + "completed_training_runs": 50, + "assembled_candidates": 38 + }, + "runtime_projection": { + "measured_full_validation_seconds_by_distance": { + "d3": 68.0347409248352, + "d5": 312.38163661956787 + }, + "validation_shots_per_condition": 5120, + "benchmark_shots_per_condition": 25000, + "workload_source": "Supplied data/README.md declares 25000 benchmark rows per condition; no benchmark examples accessed", + "linear_scale": 4.8828125, + "projected_total_seconds": 1857.5018434785306, + "limit_seconds": 3600, + "interpretation": "Projection from complete validation replays, scaling startup/compilation overhead as well as shot work. Retained-path timings are inherited; one-round categorical replacements only remove contractions. This is not a timed benchmark-split run." + }, + "neural_probability_ensemble": { + "new_optimizer_updates": 0, + "new_trainable_parameters": 0, + "initialization": "Constituents trained from random initialization in this session; this step only averages their predicted probabilities.", + "new_training": { + "initialization": "Continue from the recorded session-trained checkpoint; original random initialization seed 20261271", + "prior_pass": 3, + "initial_seed": 20261271, + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "Only the18856 declared fit rows per each of26 d5 conditions; both512-row gate and512-row audit partitions excluded from every optimizer update. Uniform condition/within-condition sampling.", + "reserved_training_partition": { + "manifest": "/run-state/workspace/research/learned_d5/reserved_split1/manifest.json", + "manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "selected_part": "fit", + "details": { + "schema": "qecbench-training-reserved-split/v1", + "seed": 20261270, + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "source_sha256": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "conditions": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "file": "surface_code_bX_d5_r01_center_5_5.npz", + "sha256": "c72d5c5ee3daf1b128e0c226f2815009daf6127e8b028004e86cebd6047ac474", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "file": "surface_code_bX_d5_r03_center_5_5.npz", + "sha256": "3a59636161c80fbbf326cf1919817ce5f60ec9e6d3e4b6223579cb6a36e12e31", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "file": "surface_code_bX_d5_r05_center_5_5.npz", + "sha256": "e808936ef0cb32869e0944ab70a3026ef96d0f31fe0fe9967c6d87a15b85abb5", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "file": "surface_code_bX_d5_r07_center_5_5.npz", + "sha256": "cd0f71459448a41af10e4399637d02e8d8193dea16ab300f839cb56ad8b08203", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "file": "surface_code_bX_d5_r09_center_5_5.npz", + "sha256": "56648e2b93499736d40f6aa5e9e8a568f150cbc8589929578f57c1e839c92d76", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "file": "surface_code_bX_d5_r11_center_5_5.npz", + "sha256": "ce2dcc2bfcb57bbfcb2291105a9a011a2a3113ad92348dfa7c76076f1fb3cacf", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "file": "surface_code_bX_d5_r13_center_5_5.npz", + "sha256": "968b14d4d948474afd0e182d9c60cd577297d4b7bb331e916058e41692d7c9d2", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "file": "surface_code_bX_d5_r15_center_5_5.npz", + "sha256": "8d73808a777d81c2acc2f6aab924cc11690a94136bc666fbf11f78292a47615d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "file": "surface_code_bX_d5_r17_center_5_5.npz", + "sha256": "0ab49c9dc61605d43f0c03427352af0ee230ecf7360927f75de60519d707c7ee", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "file": "surface_code_bX_d5_r19_center_5_5.npz", + "sha256": "27594cc6e0943860d828ebde2c76fdde64ccf2a357f896d551f3d4606e74fec4", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "file": "surface_code_bX_d5_r21_center_5_5.npz", + "sha256": "1b1fdcf280ca7c8ba94476f9c54b6ab70eee59b63b3be406a534014132295b7e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "file": "surface_code_bX_d5_r23_center_5_5.npz", + "sha256": "d31e0ca2ce6a6d04ed7bbd80113aec8cca40526b643752d8f429ece168736759", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "file": "surface_code_bX_d5_r25_center_5_5.npz", + "sha256": "f45a5978d77b1ef450f2ffd9fa19413c9d647448a3d61dfafd7590671dcace19", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "file": "surface_code_bZ_d5_r01_center_5_5.npz", + "sha256": "647e82ac0721a7245b3deb831a5a73eb555a3cb3e58b460774ffb96dc99c3b64", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "file": "surface_code_bZ_d5_r03_center_5_5.npz", + "sha256": "b64be8c7883b921bd57d5eefcc53656c2dad484833e5533e499b19b45be90158", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "file": "surface_code_bZ_d5_r05_center_5_5.npz", + "sha256": "63361e091640a4d506fc372bd0764ad248f6551d77cdf57550405b2624ca97b1", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "file": "surface_code_bZ_d5_r07_center_5_5.npz", + "sha256": "c50d26a58c1fb6b5a20f5737b94c3bac9182fe703bafa221532b8b012064f655", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "file": "surface_code_bZ_d5_r09_center_5_5.npz", + "sha256": "d62ecb975d63f13664bc6b02d30499a3fb10f0c22f1068b28bbbc31d1ec91fcc", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "file": "surface_code_bZ_d5_r11_center_5_5.npz", + "sha256": "724c7dc2c4cf2b551abf4f75e230f5aa04a74eebba79c25c845f14d15863de5e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "file": "surface_code_bZ_d5_r13_center_5_5.npz", + "sha256": "0e618a998fb591a85dd365eead741a91b6560ed1a3987046286a67a2c754fa83", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "file": "surface_code_bZ_d5_r15_center_5_5.npz", + "sha256": "e1f8c6f812dc98c48402b69a08b09b520d1374e9f2e51b3e681b67bf306e17be", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "file": "surface_code_bZ_d5_r17_center_5_5.npz", + "sha256": "aa23a51a79677a8ac43cc31b72fe07e73c827f935c632c29b09924fc88242d0d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "file": "surface_code_bZ_d5_r19_center_5_5.npz", + "sha256": "8420b79a8d7324f41dfd1cccacfd1fae9b27b370f40c60059e9de187864dba2b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "file": "surface_code_bZ_d5_r21_center_5_5.npz", + "sha256": "088b92610c90dc1a180b2eca8b16e8f225d191ec7fc11355c85e6959f35e7073", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "file": "surface_code_bZ_d5_r23_center_5_5.npz", + "sha256": "b1484c581cbd5439c74befabbd7c1c12e7cb38db099c793dfb3cf748df20fc3b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "file": "surface_code_bZ_d5_r25_center_5_5.npz", + "sha256": "92f552059b6c197b53ff1030d9ba0fe03cf22ea1f116e5280be944ad60f04be3", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + } + ], + "counts": { + "fit": 490256, + "gate": 13312, + "audit": 13312 + }, + "split_features": "Only array lengths and seeded random permutations; IDs verify alignment and are never model features", + "gate_use": "Fit a small combiner on gate labels only after experts exclude both reserved parts", + "audit_use": "Diagnostic only; no parameter fitting, checkpoint selection, or hyperparameter selection", + "validation_use": "Supplied validation selects checkpoints and candidates; no validation labels fit parameters", + "test_data_used": false + } + }, + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 490256, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 466919, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 18000, + "surface_code_bX_d5_r03_center_5_5": 18251, + "surface_code_bX_d5_r05_center_5_5": 18224, + "surface_code_bX_d5_r07_center_5_5": 17881, + "surface_code_bX_d5_r09_center_5_5": 18247, + "surface_code_bX_d5_r11_center_5_5": 17452, + "surface_code_bX_d5_r13_center_5_5": 17982, + "surface_code_bX_d5_r15_center_5_5": 17498, + "surface_code_bX_d5_r17_center_5_5": 18487, + "surface_code_bX_d5_r19_center_5_5": 18100, + "surface_code_bX_d5_r21_center_5_5": 17622, + "surface_code_bX_d5_r23_center_5_5": 17449, + "surface_code_bX_d5_r25_center_5_5": 17739, + "surface_code_bZ_d5_r01_center_5_5": 16689, + "surface_code_bZ_d5_r03_center_5_5": 18119, + "surface_code_bZ_d5_r05_center_5_5": 18146, + "surface_code_bZ_d5_r07_center_5_5": 18185, + "surface_code_bZ_d5_r09_center_5_5": 18473, + "surface_code_bZ_d5_r11_center_5_5": 18636, + "surface_code_bZ_d5_r13_center_5_5": 18474, + "surface_code_bZ_d5_r15_center_5_5": 17779, + "surface_code_bZ_d5_r17_center_5_5": 18474, + "surface_code_bZ_d5_r19_center_5_5": 17306, + "surface_code_bZ_d5_r21_center_5_5": 17165, + "surface_code_bZ_d5_r23_center_5_5": 18616, + "surface_code_bZ_d5_r25_center_5_5": 17925 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1536, + "batch": 1024, + "learning_rate": 0.0005, + "sampling_seed": 20261272, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": true, + "rng_restored": true, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "/run-state/workspace/research/learned_d5/reserved1_warm/rng-512.json", + "starting_checkpoint": "/run-state/workspace/research/learned_d5/reserved1_warm/weights-512.npz", + "starting_checkpoint_sha256": "1adc47acc35148d4260df25e25384124609d2b1e098ffcf30a1eccea55ef8712", + "starting_training_provenance": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261271", + "prior_pass": 3, + "initial_seed": 20261271, + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "Only the18856 declared fit rows per each of26 d5 conditions; both512-row gate and512-row audit partitions excluded from every optimizer update. Uniform condition/within-condition sampling.", + "reserved_training_partition": { + "manifest": "/run-state/workspace/research/learned_d5/reserved_split1/manifest.json", + "manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "selected_part": "fit", + "details": { + "schema": "qecbench-training-reserved-split/v1", + "seed": 20261270, + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "source_sha256": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "conditions": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "file": "surface_code_bX_d5_r01_center_5_5.npz", + "sha256": "c72d5c5ee3daf1b128e0c226f2815009daf6127e8b028004e86cebd6047ac474", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "file": "surface_code_bX_d5_r03_center_5_5.npz", + "sha256": "3a59636161c80fbbf326cf1919817ce5f60ec9e6d3e4b6223579cb6a36e12e31", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "file": "surface_code_bX_d5_r05_center_5_5.npz", + "sha256": "e808936ef0cb32869e0944ab70a3026ef96d0f31fe0fe9967c6d87a15b85abb5", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "file": "surface_code_bX_d5_r07_center_5_5.npz", + "sha256": "cd0f71459448a41af10e4399637d02e8d8193dea16ab300f839cb56ad8b08203", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "file": "surface_code_bX_d5_r09_center_5_5.npz", + "sha256": "56648e2b93499736d40f6aa5e9e8a568f150cbc8589929578f57c1e839c92d76", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "file": "surface_code_bX_d5_r11_center_5_5.npz", + "sha256": "ce2dcc2bfcb57bbfcb2291105a9a011a2a3113ad92348dfa7c76076f1fb3cacf", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "file": "surface_code_bX_d5_r13_center_5_5.npz", + "sha256": "968b14d4d948474afd0e182d9c60cd577297d4b7bb331e916058e41692d7c9d2", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "file": "surface_code_bX_d5_r15_center_5_5.npz", + "sha256": "8d73808a777d81c2acc2f6aab924cc11690a94136bc666fbf11f78292a47615d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "file": "surface_code_bX_d5_r17_center_5_5.npz", + "sha256": "0ab49c9dc61605d43f0c03427352af0ee230ecf7360927f75de60519d707c7ee", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "file": "surface_code_bX_d5_r19_center_5_5.npz", + "sha256": "27594cc6e0943860d828ebde2c76fdde64ccf2a357f896d551f3d4606e74fec4", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "file": "surface_code_bX_d5_r21_center_5_5.npz", + "sha256": "1b1fdcf280ca7c8ba94476f9c54b6ab70eee59b63b3be406a534014132295b7e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "file": "surface_code_bX_d5_r23_center_5_5.npz", + "sha256": "d31e0ca2ce6a6d04ed7bbd80113aec8cca40526b643752d8f429ece168736759", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "file": "surface_code_bX_d5_r25_center_5_5.npz", + "sha256": "f45a5978d77b1ef450f2ffd9fa19413c9d647448a3d61dfafd7590671dcace19", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "file": "surface_code_bZ_d5_r01_center_5_5.npz", + "sha256": "647e82ac0721a7245b3deb831a5a73eb555a3cb3e58b460774ffb96dc99c3b64", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "file": "surface_code_bZ_d5_r03_center_5_5.npz", + "sha256": "b64be8c7883b921bd57d5eefcc53656c2dad484833e5533e499b19b45be90158", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "file": "surface_code_bZ_d5_r05_center_5_5.npz", + "sha256": "63361e091640a4d506fc372bd0764ad248f6551d77cdf57550405b2624ca97b1", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "file": "surface_code_bZ_d5_r07_center_5_5.npz", + "sha256": "c50d26a58c1fb6b5a20f5737b94c3bac9182fe703bafa221532b8b012064f655", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "file": "surface_code_bZ_d5_r09_center_5_5.npz", + "sha256": "d62ecb975d63f13664bc6b02d30499a3fb10f0c22f1068b28bbbc31d1ec91fcc", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "file": "surface_code_bZ_d5_r11_center_5_5.npz", + "sha256": "724c7dc2c4cf2b551abf4f75e230f5aa04a74eebba79c25c845f14d15863de5e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "file": "surface_code_bZ_d5_r13_center_5_5.npz", + "sha256": "0e618a998fb591a85dd365eead741a91b6560ed1a3987046286a67a2c754fa83", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "file": "surface_code_bZ_d5_r15_center_5_5.npz", + "sha256": "e1f8c6f812dc98c48402b69a08b09b520d1374e9f2e51b3e681b67bf306e17be", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "file": "surface_code_bZ_d5_r17_center_5_5.npz", + "sha256": "aa23a51a79677a8ac43cc31b72fe07e73c827f935c632c29b09924fc88242d0d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "file": "surface_code_bZ_d5_r19_center_5_5.npz", + "sha256": "8420b79a8d7324f41dfd1cccacfd1fae9b27b370f40c60059e9de187864dba2b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "file": "surface_code_bZ_d5_r21_center_5_5.npz", + "sha256": "088b92610c90dc1a180b2eca8b16e8f225d191ec7fc11355c85e6959f35e7073", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "file": "surface_code_bZ_d5_r23_center_5_5.npz", + "sha256": "b1484c581cbd5439c74befabbd7c1c12e7cb38db099c793dfb3cf748df20fc3b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "file": "surface_code_bZ_d5_r25_center_5_5.npz", + "sha256": "92f552059b6c197b53ff1030d9ba0fe03cf22ea1f116e5280be944ad60f04be3", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + } + ], + "counts": { + "fit": 490256, + "gate": 13312, + "audit": 13312 + }, + "split_features": "Only array lengths and seeded random permutations; IDs verify alignment and are never model features", + "gate_use": "Fit a small combiner on gate labels only after experts exclude both reserved parts", + "audit_use": "Diagnostic only; no parameter fitting, checkpoint selection, or hyperparameter selection", + "validation_use": "Supplied validation selects checkpoints and candidates; no validation labels fit parameters", + "test_data_used": false + } + }, + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 490256, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 317613, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 14297, + "surface_code_bX_d5_r03_center_5_5": 11305, + "surface_code_bX_d5_r05_center_5_5": 12479, + "surface_code_bX_d5_r07_center_5_5": 10433, + "surface_code_bX_d5_r09_center_5_5": 10919, + "surface_code_bX_d5_r11_center_5_5": 12516, + "surface_code_bX_d5_r13_center_5_5": 12043, + "surface_code_bX_d5_r15_center_5_5": 12143, + "surface_code_bX_d5_r17_center_5_5": 11354, + "surface_code_bX_d5_r19_center_5_5": 13660, + "surface_code_bX_d5_r21_center_5_5": 13753, + "surface_code_bX_d5_r23_center_5_5": 12161, + "surface_code_bX_d5_r25_center_5_5": 12531, + "surface_code_bZ_d5_r01_center_5_5": 11397, + "surface_code_bZ_d5_r03_center_5_5": 9053, + "surface_code_bZ_d5_r05_center_5_5": 13723, + "surface_code_bZ_d5_r07_center_5_5": 14763, + "surface_code_bZ_d5_r09_center_5_5": 10969, + "surface_code_bZ_d5_r11_center_5_5": 12129, + "surface_code_bZ_d5_r13_center_5_5": 10020, + "surface_code_bZ_d5_r15_center_5_5": 13170, + "surface_code_bZ_d5_r17_center_5_5": 14946, + "surface_code_bZ_d5_r19_center_5_5": 10579, + "surface_code_bZ_d5_r21_center_5_5": 11745, + "surface_code_bZ_d5_r23_center_5_5": 12426, + "surface_code_bZ_d5_r25_center_5_5": 13099 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 512, + "batch": 1024, + "learning_rate": 0.001, + "sampling_seed": 20261272, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "rng_restored": false, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "Fresh NumPy default_rng seed 20261272", + "starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "starting_training_provenance": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.1412775069475174, + "objective": 0.1412775069475174, + "error": 0.0595703125, + "gradient_norm": 0.030735325068235397, + "elapsed": 28.457472801208496 + }, + { + "step": 16, + "loss": 0.6315727233886719, + "objective": 0.6315727233886719, + "error": 0.384765625, + "gradient_norm": 0.06563512235879898, + "elapsed": 47.886730670928955 + }, + { + "step": 32, + "loss": 0.5130410194396973, + "objective": 0.5130410194396973, + "error": 0.263671875, + "gradient_norm": 0.10626910626888275, + "elapsed": 60.16136598587036 + }, + { + "step": 48, + "loss": 0.6413166522979736, + "objective": 0.6413166522979736, + "error": 0.408203125, + "gradient_norm": 0.03790846839547157, + "elapsed": 70.9611382484436 + }, + { + "step": 64, + "loss": 0.5491592884063721, + "objective": 0.5491592884063721, + "error": 0.2939453125, + "gradient_norm": 0.093081034719944, + "elapsed": 81.46673464775085 + }, + { + "step": 80, + "loss": 0.6315242648124695, + "objective": 0.6315242648124695, + "error": 0.359375, + "gradient_norm": 0.0384257510304451, + "elapsed": 91.71172666549683 + }, + { + "step": 96, + "loss": 0.6311566829681396, + "objective": 0.6311566829681396, + "error": 0.3798828125, + "gradient_norm": 0.03731638938188553, + "elapsed": 100.83252763748169 + }, + { + "step": 112, + "loss": 0.5327925682067871, + "objective": 0.5327925682067871, + "error": 0.29296875, + "gradient_norm": 0.11202990263700485, + "elapsed": 111.35073852539062 + }, + { + "step": 128, + "loss": 0.6284654140472412, + "objective": 0.6284654140472412, + "error": 0.3740234375, + "gradient_norm": 0.03215613588690758, + "elapsed": 121.32994651794434 + }, + { + "step": 144, + "loss": 0.33964547514915466, + "objective": 0.33964547514915466, + "error": 0.1259765625, + "gradient_norm": 0.05133189633488655, + "elapsed": 131.2744882106781 + }, + { + "step": 160, + "loss": 0.14193454384803772, + "objective": 0.14193454384803772, + "error": 0.0478515625, + "gradient_norm": 0.03264402225613594, + "elapsed": 139.58473920822144 + }, + { + "step": 176, + "loss": 0.14203950762748718, + "objective": 0.14203950762748718, + "error": 0.0654296875, + "gradient_norm": 0.022548990324139595, + "elapsed": 148.9861602783203 + }, + { + "step": 192, + "loss": 0.6307225227355957, + "objective": 0.6307225227355957, + "error": 0.3955078125, + "gradient_norm": 0.08607082068920135, + "elapsed": 162.27514505386353 + }, + { + "step": 208, + "loss": 0.16193106770515442, + "objective": 0.16193106770515442, + "error": 0.064453125, + "gradient_norm": 0.023293493315577507, + "elapsed": 173.59824013710022 + }, + { + "step": 224, + "loss": 0.5426318049430847, + "objective": 0.5426318049430847, + "error": 0.3037109375, + "gradient_norm": 0.03944721072912216, + "elapsed": 182.70232272148132 + }, + { + "step": 240, + "loss": 0.6270365715026855, + "objective": 0.6270365715026855, + "error": 0.3896484375, + "gradient_norm": 0.14661568403244019, + "elapsed": 193.759183883667 + }, + { + "step": 256, + "loss": 0.4933152198791504, + "objective": 0.4933152198791504, + "error": 0.2724609375, + "gradient_norm": 0.1065438985824585, + "elapsed": 205.62959718704224 + }, + { + "step": 272, + "loss": 0.3671969473361969, + "objective": 0.3671969473361969, + "error": 0.177734375, + "gradient_norm": 0.05156548321247101, + "elapsed": 222.249596118927 + }, + { + "step": 288, + "loss": 0.5478869676589966, + "objective": 0.5478869676589966, + "error": 0.3203125, + "gradient_norm": 0.08357688039541245, + "elapsed": 232.2198715209961 + }, + { + "step": 304, + "loss": 0.21171918511390686, + "objective": 0.21171918511390686, + "error": 0.0849609375, + "gradient_norm": 0.06231697276234627, + "elapsed": 241.07631373405457 + }, + { + "step": 320, + "loss": 0.5333335995674133, + "objective": 0.5333335995674133, + "error": 0.2861328125, + "gradient_norm": 0.08931853622198105, + "elapsed": 251.28962755203247 + }, + { + "step": 336, + "loss": 0.12485946714878082, + "objective": 0.12485946714878082, + "error": 0.046875, + "gradient_norm": 0.018839582800865173, + "elapsed": 262.3605041503906 + }, + { + "step": 352, + "loss": 0.2334863245487213, + "objective": 0.2334863245487213, + "error": 0.09765625, + "gradient_norm": 0.03669576346874237, + "elapsed": 273.16373229026794 + }, + { + "step": 368, + "loss": 0.5818328857421875, + "objective": 0.5818328857421875, + "error": 0.3232421875, + "gradient_norm": 0.09833699464797974, + "elapsed": 282.8677294254303 + }, + { + "step": 384, + "loss": 0.6228232383728027, + "objective": 0.6228232383728027, + "error": 0.3671875, + "gradient_norm": 0.033418990671634674, + "elapsed": 295.04902839660645 + }, + { + "step": 400, + "loss": 0.5749450922012329, + "objective": 0.5749450922012329, + "error": 0.333984375, + "gradient_norm": 0.04644288495182991, + "elapsed": 306.67032837867737 + }, + { + "step": 416, + "loss": 0.46251457929611206, + "objective": 0.46251457929611206, + "error": 0.2216796875, + "gradient_norm": 0.06633804738521576, + "elapsed": 317.759464263916 + }, + { + "step": 432, + "loss": 0.5577508211135864, + "objective": 0.5577508211135864, + "error": 0.30859375, + "gradient_norm": 0.0970199704170227, + "elapsed": 327.4626543521881 + }, + { + "step": 448, + "loss": 0.11625733226537704, + "objective": 0.11625733226537704, + "error": 0.0419921875, + "gradient_norm": 0.020417485386133194, + "elapsed": 336.3522970676422 + }, + { + "step": 464, + "loss": 0.23657961189746857, + "objective": 0.23657961189746857, + "error": 0.1025390625, + "gradient_norm": 0.03908605873584747, + "elapsed": 344.3832321166992 + }, + { + "step": 480, + "loss": 0.011504358612000942, + "objective": 0.011504358612000942, + "error": 0.00390625, + "gradient_norm": 0.006708688102662563, + "elapsed": 355.18855381011963 + }, + { + "step": 496, + "loss": 0.3410624563694, + "objective": 0.3410624563694, + "error": 0.1533203125, + "gradient_norm": 0.05804387852549553, + "elapsed": 366.2978138923645 + }, + { + "step": 512, + "loss": 0.034005306661129, + "objective": 0.034005306661129, + "error": 0.0107421875, + "gradient_norm": 0.01019973959773779, + "elapsed": 375.73491764068604 + } + ], + "reserved_sampling_audit": { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved1_warm", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "b31e8f5ee2b5ea1b661e6bf8b5649bec45b7ab5da74fe9de46e4d06846356b87", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 256, + 512 + ], + "training_draws": 524288, + "distinct_phase_training_rows": 317613, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 14297, + "surface_code_bX_d5_r03_center_5_5": 11305, + "surface_code_bX_d5_r05_center_5_5": 12479, + "surface_code_bX_d5_r07_center_5_5": 10433, + "surface_code_bX_d5_r09_center_5_5": 10919, + "surface_code_bX_d5_r11_center_5_5": 12516, + "surface_code_bX_d5_r13_center_5_5": 12043, + "surface_code_bX_d5_r15_center_5_5": 12143, + "surface_code_bX_d5_r17_center_5_5": 11354, + "surface_code_bX_d5_r19_center_5_5": 13660, + "surface_code_bX_d5_r21_center_5_5": 13753, + "surface_code_bX_d5_r23_center_5_5": 12161, + "surface_code_bX_d5_r25_center_5_5": 12531, + "surface_code_bZ_d5_r01_center_5_5": 11397, + "surface_code_bZ_d5_r03_center_5_5": 9053, + "surface_code_bZ_d5_r05_center_5_5": 13723, + "surface_code_bZ_d5_r07_center_5_5": 14763, + "surface_code_bZ_d5_r09_center_5_5": 10969, + "surface_code_bZ_d5_r11_center_5_5": 12129, + "surface_code_bZ_d5_r13_center_5_5": 10020, + "surface_code_bZ_d5_r15_center_5_5": 13170, + "surface_code_bZ_d5_r17_center_5_5": 14946, + "surface_code_bZ_d5_r19_center_5_5": 10579, + "surface_code_bZ_d5_r21_center_5_5": 11745, + "surface_code_bZ_d5_r23_center_5_5": 12426, + "surface_code_bZ_d5_r25_center_5_5": 13099 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 512, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + "declared_study_plan": { + "hypothesis": "Fresh independent experts with an excluded training partition permit an honest combiner fit and an independent training-period diagnostic", + "experts": [ + { + "name": "reserved1", + "initial_seed": 20261271, + "sampling_seed": 20261272 + }, + { + "name": "reserved2", + "initial_seed": 20261273, + "sampling_seed": 20261274 + } + ], + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "partition": "Per26 d5 conditions:18856 fit,512 combiner,512 diagnostic rows; uniformly random partition seed20261270; sample IDs only check alignment", + "architecture": "Unchanged394-input64-unit neural correction, bound2, fixed physical pass3 priors, exact relevant-CSS contraction", + "training": "Each new expert:512 updates B1024 LR.001 from random initialization;1536 updates LR.0005 restoring own Adam/RNG state. Uniform eligible condition and row sampling, BCE, clip1,AdamW decay1e-4", + "validation_selection": "All26conditions/13durations: main-phase0/512/1024/1536, raw and equal-physical options versus incumbent, then fixed original/new ensembles with physical fractions0/.25/.5. Full replay/contract verification required before publication", + "combiner_expert_selection": "For each new expert and basis, minimum raw full-validation mean failure across0/512/1024/1536; earlier listed checkpoint wins ties. Freeze before using reserved labels", + "combiner_plan": "Fit small regularized syndrome-dependent mixtures using only the512 gate rows/condition. Diagnostic512 rows/condition must not fit or select weights/checkpoints/hyperparameters", + "holdout_prediction_generation": "Both reserved parts predicted without accessing label NPZ members; diagnostics only after final combiner selection is frozen", + "test_data_used": false + }, + "pipeline_control": { + "status": "passed", + "backend": "CPU", + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "control_sha256": "0302573e82d5113dfe1f63080b21b6976cc05b2ddb3677a640b005fc6050aa66", + "audits": [ + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke1", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ad3b3170d682b103f82456476e4a4f7c3096707269b72c242ec43d820dc06856", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 2, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 0, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 1, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke2", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ea2e649b4880641cb0c7e7b7a349d4174ce4dd276c4cdbac376e9c087f00ea1f", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 0, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 2, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 1, + "last_optimizer_count": 2, + "parent_checkpoint_sha256": "faf01476f397259640c31a761f9774af9c0592e9118c38ffdce9502acdfcfb31", + "test_data_used": false + } + ], + "initialization_exact": true, + "parameters_updated": true, + "smoke_runs_excluded_from_selection_and_submission": true, + "test_data_used": false + } + }, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.5523660182952881, + "objective": 0.5523660182952881, + "error": 0.30859375, + "gradient_norm": 0.05200070142745972, + "elapsed": 30.08410096168518 + }, + { + "step": 16, + "loss": 0.5380295515060425, + "objective": 0.5380295515060425, + "error": 0.306640625, + "gradient_norm": 0.0804876759648323, + "elapsed": 50.77648210525513 + }, + { + "step": 32, + "loss": 0.6359301805496216, + "objective": 0.6359301805496216, + "error": 0.3837890625, + "gradient_norm": 0.059380218386650085, + "elapsed": 59.453776836395264 + }, + { + "step": 48, + "loss": 0.2540435492992401, + "objective": 0.2540435492992401, + "error": 0.1083984375, + "gradient_norm": 0.04367281496524811, + "elapsed": 67.29314041137695 + }, + { + "step": 64, + "loss": 0.5867692232131958, + "objective": 0.5867692232131958, + "error": 0.3447265625, + "gradient_norm": 0.053885214030742645, + "elapsed": 78.74847197532654 + }, + { + "step": 80, + "loss": 0.6015321016311646, + "objective": 0.6015321016311646, + "error": 0.365234375, + "gradient_norm": 0.04807985574007034, + "elapsed": 90.48145818710327 + }, + { + "step": 96, + "loss": 0.49287766218185425, + "objective": 0.49287766218185425, + "error": 0.271484375, + "gradient_norm": 0.07899080961942673, + "elapsed": 101.65468978881836 + }, + { + "step": 112, + "loss": 0.3271353542804718, + "objective": 0.3271353542804718, + "error": 0.15234375, + "gradient_norm": 0.049542222172021866, + "elapsed": 111.14713263511658 + }, + { + "step": 128, + "loss": 0.50013667345047, + "objective": 0.50013667345047, + "error": 0.271484375, + "gradient_norm": 0.06454745680093765, + "elapsed": 121.21207547187805 + }, + { + "step": 144, + "loss": 0.028576843440532684, + "objective": 0.028576843440532684, + "error": 0.0087890625, + "gradient_norm": 0.010781333781778812, + "elapsed": 130.69302248954773 + }, + { + "step": 160, + "loss": 0.5668779015541077, + "objective": 0.5668779015541077, + "error": 0.330078125, + "gradient_norm": 0.06098390743136406, + "elapsed": 142.14290237426758 + }, + { + "step": 176, + "loss": 0.3986494839191437, + "objective": 0.3986494839191437, + "error": 0.1884765625, + "gradient_norm": 0.042795032262802124, + "elapsed": 152.75753688812256 + }, + { + "step": 192, + "loss": 0.31897079944610596, + "objective": 0.31897079944610596, + "error": 0.142578125, + "gradient_norm": 0.040675707161426544, + "elapsed": 160.04981398582458 + }, + { + "step": 208, + "loss": 0.5092275142669678, + "objective": 0.5092275142669678, + "error": 0.255859375, + "gradient_norm": 0.07929783314466476, + "elapsed": 169.85345673561096 + }, + { + "step": 224, + "loss": 0.35782667994499207, + "objective": 0.35782667994499207, + "error": 0.1748046875, + "gradient_norm": 0.05785144120454788, + "elapsed": 179.90323066711426 + }, + { + "step": 240, + "loss": 0.5660895109176636, + "objective": 0.5660895109176636, + "error": 0.3349609375, + "gradient_norm": 0.10684454441070557, + "elapsed": 191.3668942451477 + }, + { + "step": 256, + "loss": 0.6265910863876343, + "objective": 0.6265910863876343, + "error": 0.3779296875, + "gradient_norm": 0.034383758902549744, + "elapsed": 200.3055775165558 + }, + { + "step": 272, + "loss": 0.6210677623748779, + "objective": 0.6210677623748779, + "error": 0.369140625, + "gradient_norm": 0.04434216767549515, + "elapsed": 210.09376430511475 + }, + { + "step": 288, + "loss": 0.4892377257347107, + "objective": 0.4892377257347107, + "error": 0.2490234375, + "gradient_norm": 0.1040654331445694, + "elapsed": 220.45881819725037 + }, + { + "step": 304, + "loss": 0.6407739520072937, + "objective": 0.6407739520072937, + "error": 0.3916015625, + "gradient_norm": 0.07782924920320511, + "elapsed": 233.3719048500061 + }, + { + "step": 320, + "loss": 0.4752756953239441, + "objective": 0.4752756953239441, + "error": 0.263671875, + "gradient_norm": 0.051829319447278976, + "elapsed": 244.25844407081604 + }, + { + "step": 336, + "loss": 0.6482080221176147, + "objective": 0.6482080221176147, + "error": 0.41015625, + "gradient_norm": 0.04979892820119858, + "elapsed": 253.1897099018097 + }, + { + "step": 352, + "loss": 0.34022292494773865, + "objective": 0.34022292494773865, + "error": 0.1708984375, + "gradient_norm": 0.09951864182949066, + "elapsed": 264.0781395435333 + }, + { + "step": 368, + "loss": 0.3494992256164551, + "objective": 0.3494992256164551, + "error": 0.15625, + "gradient_norm": 0.10392706841230392, + "elapsed": 275.8111581802368 + }, + { + "step": 384, + "loss": 0.47191378474235535, + "objective": 0.47191378474235535, + "error": 0.25, + "gradient_norm": 0.07366786152124405, + "elapsed": 283.9459602832794 + }, + { + "step": 400, + "loss": 0.583655595779419, + "objective": 0.583655595779419, + "error": 0.3623046875, + "gradient_norm": 0.10394527018070221, + "elapsed": 294.3349726200104 + }, + { + "step": 416, + "loss": 0.6212975978851318, + "objective": 0.6212975978851318, + "error": 0.37109375, + "gradient_norm": 0.054796766489744186, + "elapsed": 304.7477548122406 + }, + { + "step": 432, + "loss": 0.4719577431678772, + "objective": 0.4719577431678772, + "error": 0.2431640625, + "gradient_norm": 0.05418012663722038, + "elapsed": 315.91914200782776 + }, + { + "step": 448, + "loss": 0.5696494579315186, + "objective": 0.5696494579315186, + "error": 0.3330078125, + "gradient_norm": 0.047046076506376266, + "elapsed": 324.96326184272766 + }, + { + "step": 464, + "loss": 0.613875687122345, + "objective": 0.613875687122345, + "error": 0.34765625, + "gradient_norm": 0.05237002298235893, + "elapsed": 334.7670781612396 + }, + { + "step": 480, + "loss": 0.28741705417633057, + "objective": 0.28741705417633057, + "error": 0.1240234375, + "gradient_norm": 0.05365394428372383, + "elapsed": 344.03080439567566 + }, + { + "step": 496, + "loss": 0.3729455769062042, + "objective": 0.3729455769062042, + "error": 0.1875, + "gradient_norm": 0.05905403569340706, + "elapsed": 356.01581716537476 + }, + { + "step": 512, + "loss": 0.38685142993927, + "objective": 0.38685142993927, + "error": 0.17578125, + "gradient_norm": 0.048455506563186646, + "elapsed": 367.7296392917633 + }, + { + "step": 528, + "loss": 0.6062720417976379, + "objective": 0.6062720417976379, + "error": 0.369140625, + "gradient_norm": 0.07544548809528351, + "elapsed": 385.4480962753296 + }, + { + "step": 544, + "loss": 0.520085871219635, + "objective": 0.520085871219635, + "error": 0.279296875, + "gradient_norm": 0.08394371718168259, + "elapsed": 397.71993708610535 + }, + { + "step": 560, + "loss": 0.5944540500640869, + "objective": 0.5944540500640869, + "error": 0.3544921875, + "gradient_norm": 0.05468091368675232, + "elapsed": 406.9417428970337 + }, + { + "step": 576, + "loss": 0.34102559089660645, + "objective": 0.34102559089660645, + "error": 0.1611328125, + "gradient_norm": 0.07333917915821075, + "elapsed": 417.0068130493164 + }, + { + "step": 592, + "loss": 0.47373664379119873, + "objective": 0.47373664379119873, + "error": 0.2412109375, + "gradient_norm": 0.05662858858704567, + "elapsed": 425.1176447868347 + }, + { + "step": 608, + "loss": 0.48517894744873047, + "objective": 0.48517894744873047, + "error": 0.25, + "gradient_norm": 0.08127480745315552, + "elapsed": 434.92080903053284 + }, + { + "step": 624, + "loss": 0.39865612983703613, + "objective": 0.39865612983703613, + "error": 0.1904296875, + "gradient_norm": 0.07332058995962143, + "elapsed": 446.6602101325989 + }, + { + "step": 640, + "loss": 0.41867297887802124, + "objective": 0.41867297887802124, + "error": 0.2177734375, + "gradient_norm": 0.07386308163404465, + "elapsed": 457.0243580341339 + }, + { + "step": 656, + "loss": 0.5108687877655029, + "objective": 0.5108687877655029, + "error": 0.2822265625, + "gradient_norm": 0.052080318331718445, + "elapsed": 469.5842761993408 + }, + { + "step": 672, + "loss": 0.5043742656707764, + "objective": 0.5043742656707764, + "error": 0.2734375, + "gradient_norm": 0.047204963862895966, + "elapsed": 479.356397151947 + }, + { + "step": 688, + "loss": 0.5550935864448547, + "objective": 0.5550935864448547, + "error": 0.30078125, + "gradient_norm": 0.04080262407660484, + "elapsed": 489.9912152290344 + }, + { + "step": 704, + "loss": 0.5698974132537842, + "objective": 0.5698974132537842, + "error": 0.322265625, + "gradient_norm": 0.10692963004112244, + "elapsed": 500.3283371925354 + }, + { + "step": 720, + "loss": 0.45870622992515564, + "objective": 0.45870622992515564, + "error": 0.2255859375, + "gradient_norm": 0.06705734878778458, + "elapsed": 509.82279753685 + }, + { + "step": 736, + "loss": 0.555386483669281, + "objective": 0.555386483669281, + "error": 0.31640625, + "gradient_norm": 0.05112688988447189, + "elapsed": 518.507036447525 + }, + { + "step": 752, + "loss": 0.14282986521720886, + "objective": 0.14282986521720886, + "error": 0.056640625, + "gradient_norm": 0.03209136053919792, + "elapsed": 529.1373023986816 + }, + { + "step": 768, + "loss": 0.5362129807472229, + "objective": 0.5362129807472229, + "error": 0.2841796875, + "gradient_norm": 0.049996186047792435, + "elapsed": 538.9186007976532 + }, + { + "step": 784, + "loss": 0.5071826577186584, + "objective": 0.5071826577186584, + "error": 0.2744140625, + "gradient_norm": 0.04826078191399574, + "elapsed": 549.5225830078125 + }, + { + "step": 800, + "loss": 0.24775367975234985, + "objective": 0.24775367975234985, + "error": 0.107421875, + "gradient_norm": 0.06889795511960983, + "elapsed": 560.7170543670654 + }, + { + "step": 816, + "loss": 0.17432856559753418, + "objective": 0.17432856559753418, + "error": 0.06640625, + "gradient_norm": 0.05147368833422661, + "elapsed": 570.7887880802155 + }, + { + "step": 832, + "loss": 0.5410823822021484, + "objective": 0.5410823822021484, + "error": 0.3115234375, + "gradient_norm": 0.11862928420305252, + "elapsed": 581.9721121788025 + }, + { + "step": 848, + "loss": 0.5555508732795715, + "objective": 0.5555508732795715, + "error": 0.296875, + "gradient_norm": 0.060369592159986496, + "elapsed": 592.2823219299316 + }, + { + "step": 864, + "loss": 0.31839215755462646, + "objective": 0.31839215755462646, + "error": 0.1552734375, + "gradient_norm": 0.063877172768116, + "elapsed": 603.1910541057587 + }, + { + "step": 880, + "loss": 0.481766939163208, + "objective": 0.481766939163208, + "error": 0.2470703125, + "gradient_norm": 0.1623816341161728, + "elapsed": 614.4277107715607 + }, + { + "step": 896, + "loss": 0.5780366659164429, + "objective": 0.5780366659164429, + "error": 0.3037109375, + "gradient_norm": 0.06694691628217697, + "elapsed": 623.9365792274475 + }, + { + "step": 912, + "loss": 0.4794909358024597, + "objective": 0.4794909358024597, + "error": 0.2314453125, + "gradient_norm": 0.07813122123479843, + "elapsed": 633.9845306873322 + }, + { + "step": 928, + "loss": 0.6279138922691345, + "objective": 0.6279138922691345, + "error": 0.380859375, + "gradient_norm": 0.047679927200078964, + "elapsed": 643.7766675949097 + }, + { + "step": 944, + "loss": 0.6401606798171997, + "objective": 0.6401606798171997, + "error": 0.3994140625, + "gradient_norm": 0.07329051941633224, + "elapsed": 655.2369928359985 + }, + { + "step": 960, + "loss": 0.4340277910232544, + "objective": 0.4340277910232544, + "error": 0.2158203125, + "gradient_norm": 0.11762503534555435, + "elapsed": 666.9884371757507 + }, + { + "step": 976, + "loss": 0.44496864080429077, + "objective": 0.44496864080429077, + "error": 0.2236328125, + "gradient_norm": 0.05260347202420235, + "elapsed": 677.3464586734772 + }, + { + "step": 992, + "loss": 0.13230293989181519, + "objective": 0.13230293989181519, + "error": 0.05078125, + "gradient_norm": 0.030240925028920174, + "elapsed": 685.7275724411011 + }, + { + "step": 1008, + "loss": 0.2971688508987427, + "objective": 0.2971688508987427, + "error": 0.1171875, + "gradient_norm": 0.05503479763865471, + "elapsed": 694.1270356178284 + }, + { + "step": 1024, + "loss": 0.5688735246658325, + "objective": 0.5688735246658325, + "error": 0.314453125, + "gradient_norm": 0.06526188552379608, + "elapsed": 703.9192817211151 + }, + { + "step": 1040, + "loss": 0.42805811762809753, + "objective": 0.42805811762809753, + "error": 0.2080078125, + "gradient_norm": 0.13000032305717468, + "elapsed": 720.145961523056 + }, + { + "step": 1056, + "loss": 0.5543602705001831, + "objective": 0.5543602705001831, + "error": 0.298828125, + "gradient_norm": 0.15922385454177856, + "elapsed": 733.5112845897675 + }, + { + "step": 1072, + "loss": 0.031130114570260048, + "objective": 0.031130114570260048, + "error": 0.013671875, + "gradient_norm": 0.008926023729145527, + "elapsed": 742.4467866420746 + }, + { + "step": 1088, + "loss": 0.14947748184204102, + "objective": 0.14947748184204102, + "error": 0.056640625, + "gradient_norm": 0.03975249081850052, + "elapsed": 751.8575854301453 + }, + { + "step": 1104, + "loss": 0.6275734901428223, + "objective": 0.6275734901428223, + "error": 0.3671875, + "gradient_norm": 0.08096148073673248, + "elapsed": 761.5625903606415 + }, + { + "step": 1120, + "loss": 0.23923414945602417, + "objective": 0.23923414945602417, + "error": 0.0966796875, + "gradient_norm": 0.03325376287102699, + "elapsed": 773.9633615016937 + }, + { + "step": 1136, + "loss": 0.570243239402771, + "objective": 0.570243239402771, + "error": 0.31640625, + "gradient_norm": 0.07534287869930267, + "elapsed": 783.1533136367798 + }, + { + "step": 1152, + "loss": 0.4264270067214966, + "objective": 0.4264270067214966, + "error": 0.2119140625, + "gradient_norm": 0.08900073170661926, + "elapsed": 792.1710996627808 + }, + { + "step": 1168, + "loss": 0.5958121418952942, + "objective": 0.5958121418952942, + "error": 0.3583984375, + "gradient_norm": 0.08239343762397766, + "elapsed": 803.1175289154053 + }, + { + "step": 1184, + "loss": 0.2909137010574341, + "objective": 0.2909137010574341, + "error": 0.1416015625, + "gradient_norm": 0.05281354859471321, + "elapsed": 812.6055159568787 + }, + { + "step": 1200, + "loss": 0.6119058728218079, + "objective": 0.6119058728218079, + "error": 0.36328125, + "gradient_norm": 0.056254416704177856, + "elapsed": 823.2276427745819 + }, + { + "step": 1216, + "loss": 0.13595536351203918, + "objective": 0.13595536351203918, + "error": 0.0556640625, + "gradient_norm": 0.04057573154568672, + "elapsed": 834.1696293354034 + }, + { + "step": 1232, + "loss": 0.5840731263160706, + "objective": 0.5840731263160706, + "error": 0.328125, + "gradient_norm": 0.054566267877817154, + "elapsed": 845.3501887321472 + }, + { + "step": 1248, + "loss": 0.3053072690963745, + "objective": 0.3053072690963745, + "error": 0.1337890625, + "gradient_norm": 0.04617297649383545, + "elapsed": 854.9564871788025 + }, + { + "step": 1264, + "loss": 0.6288673281669617, + "objective": 0.6288673281669617, + "error": 0.3994140625, + "gradient_norm": 0.08229745179414749, + "elapsed": 864.8914043903351 + }, + { + "step": 1280, + "loss": 0.5586361289024353, + "objective": 0.5586361289024353, + "error": 0.2958984375, + "gradient_norm": 0.05713959410786629, + "elapsed": 877.0349607467651 + }, + { + "step": 1296, + "loss": 0.3648858666419983, + "objective": 0.3648858666419983, + "error": 0.16796875, + "gradient_norm": 0.08502963185310364, + "elapsed": 888.5764675140381 + }, + { + "step": 1312, + "loss": 0.4747084081172943, + "objective": 0.4747084081172943, + "error": 0.244140625, + "gradient_norm": 0.08609883487224579, + "elapsed": 899.7598609924316 + }, + { + "step": 1328, + "loss": 0.15583917498588562, + "objective": 0.15583917498588562, + "error": 0.05859375, + "gradient_norm": 0.027793049812316895, + "elapsed": 909.47514295578 + }, + { + "step": 1344, + "loss": 0.47515708208084106, + "objective": 0.47515708208084106, + "error": 0.263671875, + "gradient_norm": 0.07668807357549667, + "elapsed": 919.7640328407288 + }, + { + "step": 1360, + "loss": 0.5173689126968384, + "objective": 0.5173689126968384, + "error": 0.2744140625, + "gradient_norm": 0.05054212734103203, + "elapsed": 930.6309463977814 + }, + { + "step": 1376, + "loss": 0.46629998087882996, + "objective": 0.46629998087882996, + "error": 0.24609375, + "gradient_norm": 0.051172077655792236, + "elapsed": 939.0202586650848 + }, + { + "step": 1392, + "loss": 0.11312969774007797, + "objective": 0.11312969774007797, + "error": 0.044921875, + "gradient_norm": 0.05863805115222931, + "elapsed": 949.1451416015625 + }, + { + "step": 1408, + "loss": 0.5750841498374939, + "objective": 0.5750841498374939, + "error": 0.322265625, + "gradient_norm": 0.051106806844472885, + "elapsed": 959.94162940979 + }, + { + "step": 1424, + "loss": 0.5937192440032959, + "objective": 0.5937192440032959, + "error": 0.3408203125, + "gradient_norm": 0.05014815554022789, + "elapsed": 969.5868306159973 + }, + { + "step": 1440, + "loss": 0.5292985439300537, + "objective": 0.5292985439300537, + "error": 0.2958984375, + "gradient_norm": 0.057068243622779846, + "elapsed": 982.6692054271698 + }, + { + "step": 1456, + "loss": 0.5959951877593994, + "objective": 0.5959951877593994, + "error": 0.3408203125, + "gradient_norm": 0.0703694075345993, + "elapsed": 995.0066986083984 + }, + { + "step": 1472, + "loss": 0.018453411757946014, + "objective": 0.018453411757946014, + "error": 0.00390625, + "gradient_norm": 0.012016087770462036, + "elapsed": 1004.0057821273804 + }, + { + "step": 1488, + "loss": 0.5711684823036194, + "objective": 0.5711684823036194, + "error": 0.3095703125, + "gradient_norm": 0.07746906578540802, + "elapsed": 1016.1701967716217 + }, + { + "step": 1504, + "loss": 0.3114882707595825, + "objective": 0.3114882707595825, + "error": 0.1455078125, + "gradient_norm": 0.05321609228849411, + "elapsed": 1026.6053586006165 + }, + { + "step": 1520, + "loss": 0.6433392763137817, + "objective": 0.6433392763137817, + "error": 0.4072265625, + "gradient_norm": 0.05683734640479088, + "elapsed": 1036.1535296440125 + }, + { + "step": 1536, + "loss": 0.38409170508384705, + "objective": 0.38409170508384705, + "error": 0.19140625, + "gradient_norm": 0.07577994465827942, + "elapsed": 1046.9508447647095 + } + ], + "reserved_sampling_audit": { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved1_full", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "7b45252d6bb77a39c003c8f34f040d0d672e9dd1a1338a14126e1fe07a02c8c9", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 512, + 1024, + 1536 + ], + "training_draws": 1572864, + "distinct_phase_training_rows": 466919, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 18000, + "surface_code_bX_d5_r03_center_5_5": 18251, + "surface_code_bX_d5_r05_center_5_5": 18224, + "surface_code_bX_d5_r07_center_5_5": 17881, + "surface_code_bX_d5_r09_center_5_5": 18247, + "surface_code_bX_d5_r11_center_5_5": 17452, + "surface_code_bX_d5_r13_center_5_5": 17982, + "surface_code_bX_d5_r15_center_5_5": 17498, + "surface_code_bX_d5_r17_center_5_5": 18487, + "surface_code_bX_d5_r19_center_5_5": 18100, + "surface_code_bX_d5_r21_center_5_5": 17622, + "surface_code_bX_d5_r23_center_5_5": 17449, + "surface_code_bX_d5_r25_center_5_5": 17739, + "surface_code_bZ_d5_r01_center_5_5": 16689, + "surface_code_bZ_d5_r03_center_5_5": 18119, + "surface_code_bZ_d5_r05_center_5_5": 18146, + "surface_code_bZ_d5_r07_center_5_5": 18185, + "surface_code_bZ_d5_r09_center_5_5": 18473, + "surface_code_bZ_d5_r11_center_5_5": 18636, + "surface_code_bZ_d5_r13_center_5_5": 18474, + "surface_code_bZ_d5_r15_center_5_5": 17779, + "surface_code_bZ_d5_r17_center_5_5": 18474, + "surface_code_bZ_d5_r19_center_5_5": 17306, + "surface_code_bZ_d5_r21_center_5_5": 17165, + "surface_code_bZ_d5_r23_center_5_5": 18616, + "surface_code_bZ_d5_r25_center_5_5": 17925 + }, + "initial_optimizer_count": 512, + "last_optimizer_count": 2048, + "parent_checkpoint_sha256": "1adc47acc35148d4260df25e25384124609d2b1e098ffcf30a1eccea55ef8712", + "test_data_used": false + }, + "declared_study_plan": { + "hypothesis": "Fresh independent experts with an excluded training partition permit an honest combiner fit and an independent training-period diagnostic", + "experts": [ + { + "name": "reserved1", + "initial_seed": 20261271, + "sampling_seed": 20261272 + }, + { + "name": "reserved2", + "initial_seed": 20261273, + "sampling_seed": 20261274 + } + ], + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "partition": "Per26 d5 conditions:18856 fit,512 combiner,512 diagnostic rows; uniformly random partition seed20261270; sample IDs only check alignment", + "architecture": "Unchanged394-input64-unit neural correction, bound2, fixed physical pass3 priors, exact relevant-CSS contraction", + "training": "Each new expert:512 updates B1024 LR.001 from random initialization;1536 updates LR.0005 restoring own Adam/RNG state. Uniform eligible condition and row sampling, BCE, clip1,AdamW decay1e-4", + "validation_selection": "All26conditions/13durations: main-phase0/512/1024/1536, raw and equal-physical options versus incumbent, then fixed original/new ensembles with physical fractions0/.25/.5. Full replay/contract verification required before publication", + "combiner_expert_selection": "For each new expert and basis, minimum raw full-validation mean failure across0/512/1024/1536; earlier listed checkpoint wins ties. Freeze before using reserved labels", + "combiner_plan": "Fit small regularized syndrome-dependent mixtures using only the512 gate rows/condition. Diagnostic512 rows/condition must not fit or select weights/checkpoints/hyperparameters", + "holdout_prediction_generation": "Both reserved parts predicted without accessing label NPZ members; diagnostics only after final combiner selection is frozen", + "test_data_used": false + }, + "pipeline_control": { + "status": "passed", + "backend": "CPU", + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "control_sha256": "0302573e82d5113dfe1f63080b21b6976cc05b2ddb3677a640b005fc6050aa66", + "audits": [ + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke1", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ad3b3170d682b103f82456476e4a4f7c3096707269b72c242ec43d820dc06856", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 2, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 0, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 1, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke2", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ea2e649b4880641cb0c7e7b7a349d4174ce4dd276c4cdbac376e9c087f00ea1f", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 0, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 2, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 1, + "last_optimizer_count": 2, + "parent_checkpoint_sha256": "faf01476f397259640c31a761f9774af9c0592e9118c38ffdce9502acdfcfb31", + "test_data_used": false + } + ], + "initialization_exact": true, + "parameters_updated": true, + "smoke_runs_excluded_from_selection_and_submission": true, + "test_data_used": false + } + }, + "source_reference_package": "/run-state/workspace/research/context_upgrades/neural_d5_full3_swa/package", + "original_training_provenance": { + "training": { + "initialization": "Uniform parameter averages of checkpoints from the same session-initialized training trajectory; no external weights", + "prior_pass": 3, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "hidden_width": 64, + "training": "No new optimizer updates; all learning comes from the recorded source trajectory and its session-trained parent", + "optimizer_updates_in_derived_run": 0, + "source_training_provenance": { + "initialization": "Continue from the recorded session-trained checkpoint; original random initialization seed 20261108", + "prior_pass": 3, + "initial_seed": 20261108, + "training_source_sha256": { + "learned_d5__train.py": "b73af9da21332dee9a43f653b514695b020fbc3516604b2e721d8cf0ea876d53", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "5e9420df1f6dd56518925e910096fb9bc93bd796a5933b13bf894a1a96256cdf", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "All supplied training shots per each of all26 d5 conditions; uniform condition and within-condition sampling for optimizer batches.", + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 516880, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 507282, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 19592, + "surface_code_bX_d5_r03_center_5_5": 19646, + "surface_code_bX_d5_r05_center_5_5": 19513, + "surface_code_bX_d5_r07_center_5_5": 19341, + "surface_code_bX_d5_r09_center_5_5": 19211, + "surface_code_bX_d5_r11_center_5_5": 19239, + "surface_code_bX_d5_r13_center_5_5": 19679, + "surface_code_bX_d5_r15_center_5_5": 19455, + "surface_code_bX_d5_r17_center_5_5": 19479, + "surface_code_bX_d5_r19_center_5_5": 19479, + "surface_code_bX_d5_r21_center_5_5": 19551, + "surface_code_bX_d5_r23_center_5_5": 19586, + "surface_code_bX_d5_r25_center_5_5": 19526, + "surface_code_bZ_d5_r01_center_5_5": 19652, + "surface_code_bZ_d5_r03_center_5_5": 19732, + "surface_code_bZ_d5_r05_center_5_5": 19754, + "surface_code_bZ_d5_r07_center_5_5": 19194, + "surface_code_bZ_d5_r09_center_5_5": 19641, + "surface_code_bZ_d5_r11_center_5_5": 19611, + "surface_code_bZ_d5_r13_center_5_5": 19424, + "surface_code_bZ_d5_r15_center_5_5": 19380, + "surface_code_bZ_d5_r17_center_5_5": 19384, + "surface_code_bZ_d5_r19_center_5_5": 19684, + "surface_code_bZ_d5_r21_center_5_5": 19559, + "surface_code_bZ_d5_r23_center_5_5": 19524, + "surface_code_bZ_d5_r25_center_5_5": 19446 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 2048, + "batch": 1024, + "learning_rate": 0.0005, + "sampling_seed": 20261113, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": true, + "rng_restored": true, + "sampling_state_source": "/run-state/workspace/research/learned_d5/feedback3_pilot/rng-768.json", + "starting_checkpoint": "/run-state/workspace/research/learned_d5/feedback3_pilot/weights-768.npz", + "starting_checkpoint_sha256": "bc2ba1c529317ce1b5b661efae4707eca49c6995d6f22b04193fe7642662fed8", + "starting_training_provenance": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261108", + "prior_pass": 3, + "initial_seed": 20261108, + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "4096 training shots per each of all 26 d5 conditions, sampled without replacement with seed 20261023. Uniform condition and within-condition sampling for optimizer batches.", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1024, + "batch": 256, + "learning_rate": 0.001, + "sampling_seed": 20261108, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "starting_checkpoint": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.011146659031510353, + "error": 0.00390625, + "gradient_norm": 0.011240893043577671, + "elapsed": 21.276997089385986 + }, + { + "step": 16, + "loss": 0.645737886428833, + "error": 0.40625, + "gradient_norm": 0.1628236621618271, + "elapsed": 25.872907638549805 + }, + { + "step": 32, + "loss": 0.574029803276062, + "error": 0.35546875, + "gradient_norm": 0.3000081777572632, + "elapsed": 30.761418342590332 + }, + { + "step": 48, + "loss": 0.574467122554779, + "error": 0.296875, + "gradient_norm": 0.24150623381137848, + "elapsed": 35.67650651931763 + }, + { + "step": 64, + "loss": 0.6003620624542236, + "error": 0.35546875, + "gradient_norm": 0.07430054992437363, + "elapsed": 40.60572576522827 + }, + { + "step": 80, + "loss": 0.5429091453552246, + "error": 0.33203125, + "gradient_norm": 0.15341751277446747, + "elapsed": 45.546849727630615 + }, + { + "step": 96, + "loss": 0.368771493434906, + "error": 0.1640625, + "gradient_norm": 0.08923184871673584, + "elapsed": 50.49156332015991 + }, + { + "step": 112, + "loss": 0.516342043876648, + "error": 0.265625, + "gradient_norm": 0.10965219140052795, + "elapsed": 55.45058846473694 + }, + { + "step": 128, + "loss": 0.5925382971763611, + "error": 0.37109375, + "gradient_norm": 0.055406324565410614, + "elapsed": 60.40891766548157 + }, + { + "step": 144, + "loss": 0.19184258580207825, + "error": 0.07421875, + "gradient_norm": 0.07042146474123001, + "elapsed": 65.33323669433594 + }, + { + "step": 160, + "loss": 0.5202382206916809, + "error": 0.25390625, + "gradient_norm": 0.14782382547855377, + "elapsed": 70.26605796813965 + }, + { + "step": 176, + "loss": 0.46083134412765503, + "error": 0.22265625, + "gradient_norm": 0.09074779599905014, + "elapsed": 75.18221640586853 + }, + { + "step": 192, + "loss": 0.3054918646812439, + "error": 0.14453125, + "gradient_norm": 0.0588168129324913, + "elapsed": 80.1186010837555 + }, + { + "step": 208, + "loss": 0.4836011230945587, + "error": 0.27734375, + "gradient_norm": 0.09208947420120239, + "elapsed": 85.05764293670654 + }, + { + "step": 224, + "loss": 0.6640600562095642, + "error": 0.38671875, + "gradient_norm": 0.22026506066322327, + "elapsed": 89.98808217048645 + }, + { + "step": 240, + "loss": 0.02421322464942932, + "error": 0.00390625, + "gradient_norm": 0.008131005801260471, + "elapsed": 94.90194272994995 + }, + { + "step": 256, + "loss": 0.6302106976509094, + "error": 0.4296875, + "gradient_norm": 0.09762304276227951, + "elapsed": 99.82612204551697 + }, + { + "step": 272, + "loss": 0.5092596411705017, + "error": 0.27734375, + "gradient_norm": 0.11407691985368729, + "elapsed": 110.44065999984741 + }, + { + "step": 288, + "loss": 0.452798455953598, + "error": 0.2265625, + "gradient_norm": 0.1105576679110527, + "elapsed": 115.36984539031982 + }, + { + "step": 304, + "loss": 0.3378596305847168, + "error": 0.18359375, + "gradient_norm": 0.0841713547706604, + "elapsed": 120.29337763786316 + }, + { + "step": 320, + "loss": 0.6271854639053345, + "error": 0.38671875, + "gradient_norm": 0.1972702294588089, + "elapsed": 125.2231035232544 + }, + { + "step": 336, + "loss": 0.04562236741185188, + "error": 0.01171875, + "gradient_norm": 0.027922745794057846, + "elapsed": 130.14725255966187 + }, + { + "step": 352, + "loss": 0.5342530608177185, + "error": 0.26953125, + "gradient_norm": 0.09031179547309875, + "elapsed": 135.08111095428467 + }, + { + "step": 368, + "loss": 0.49785488843917847, + "error": 0.2578125, + "gradient_norm": 0.19366280734539032, + "elapsed": 140.00699138641357 + }, + { + "step": 384, + "loss": 0.5673326253890991, + "error": 0.30859375, + "gradient_norm": 0.20644932985305786, + "elapsed": 144.92276740074158 + }, + { + "step": 400, + "loss": 0.5581298470497131, + "error": 0.3203125, + "gradient_norm": 0.17668266594409943, + "elapsed": 149.86573243141174 + }, + { + "step": 416, + "loss": 0.5564071536064148, + "error": 0.30078125, + "gradient_norm": 0.0821610689163208, + "elapsed": 154.7953712940216 + }, + { + "step": 432, + "loss": 0.5540086030960083, + "error": 0.34765625, + "gradient_norm": 0.1438807100057602, + "elapsed": 159.72657418251038 + }, + { + "step": 448, + "loss": 0.540939450263977, + "error": 0.29296875, + "gradient_norm": 0.17986361682415009, + "elapsed": 164.6689453125 + }, + { + "step": 464, + "loss": 0.45807865262031555, + "error": 0.25, + "gradient_norm": 0.14453186094760895, + "elapsed": 169.58739304542542 + }, + { + "step": 480, + "loss": 0.5191650390625, + "error": 0.22265625, + "gradient_norm": 0.07955105602741241, + "elapsed": 174.5444438457489 + }, + { + "step": 496, + "loss": 0.1692925989627838, + "error": 0.0703125, + "gradient_norm": 0.07875128090381622, + "elapsed": 179.48035550117493 + }, + { + "step": 512, + "loss": 0.5580664873123169, + "error": 0.3125, + "gradient_norm": 0.27090802788734436, + "elapsed": 184.42834162712097 + }, + { + "step": 528, + "loss": 0.26402050256729126, + "error": 0.13671875, + "gradient_norm": 0.13135771453380585, + "elapsed": 195.17691040039062 + }, + { + "step": 544, + "loss": 0.4352915287017822, + "error": 0.1953125, + "gradient_norm": 0.15959712862968445, + "elapsed": 200.0421543121338 + }, + { + "step": 560, + "loss": 0.22861814498901367, + "error": 0.1015625, + "gradient_norm": 0.08776932209730148, + "elapsed": 204.95144605636597 + }, + { + "step": 576, + "loss": 0.28309381008148193, + "error": 0.1328125, + "gradient_norm": 0.11050742119550705, + "elapsed": 209.8526291847229 + }, + { + "step": 592, + "loss": 0.6409220695495605, + "error": 0.41015625, + "gradient_norm": 0.19826626777648926, + "elapsed": 214.84447717666626 + }, + { + "step": 608, + "loss": 0.25090643763542175, + "error": 0.109375, + "gradient_norm": 0.05864342302083969, + "elapsed": 219.72637391090393 + }, + { + "step": 624, + "loss": 0.11423969268798828, + "error": 0.05078125, + "gradient_norm": 0.05318564549088478, + "elapsed": 224.6331377029419 + }, + { + "step": 640, + "loss": 0.32663431763648987, + "error": 0.1328125, + "gradient_norm": 0.06877780705690384, + "elapsed": 229.5065622329712 + }, + { + "step": 656, + "loss": 0.24196995794773102, + "error": 0.10546875, + "gradient_norm": 0.07683655619621277, + "elapsed": 234.4042534828186 + }, + { + "step": 672, + "loss": 0.5349344611167908, + "error": 0.296875, + "gradient_norm": 0.15214307606220245, + "elapsed": 239.26656579971313 + }, + { + "step": 688, + "loss": 0.26759713888168335, + "error": 0.1171875, + "gradient_norm": 0.14698348939418793, + "elapsed": 244.21049737930298 + }, + { + "step": 704, + "loss": 0.37338894605636597, + "error": 0.18359375, + "gradient_norm": 0.10210632532835007, + "elapsed": 249.13519072532654 + }, + { + "step": 720, + "loss": 0.36807945370674133, + "error": 0.17578125, + "gradient_norm": 0.09668388962745667, + "elapsed": 254.06281065940857 + }, + { + "step": 736, + "loss": 0.3736685514450073, + "error": 0.15625, + "gradient_norm": 0.10987236350774765, + "elapsed": 259.01695108413696 + }, + { + "step": 752, + "loss": 0.5266942977905273, + "error": 0.29296875, + "gradient_norm": 0.09041415899991989, + "elapsed": 263.9530746936798 + }, + { + "step": 768, + "loss": 0.360038161277771, + "error": 0.1640625, + "gradient_norm": 0.10391079634428024, + "elapsed": 268.9019305706024 + }, + { + "step": 784, + "loss": 0.5700286626815796, + "error": 0.34375, + "gradient_norm": 0.12206032127141953, + "elapsed": 279.4174163341522 + }, + { + "step": 800, + "loss": 0.42533689737319946, + "error": 0.20703125, + "gradient_norm": 0.06605375558137894, + "elapsed": 284.3391351699829 + }, + { + "step": 816, + "loss": 0.12355346977710724, + "error": 0.046875, + "gradient_norm": 0.06571663916110992, + "elapsed": 289.2815272808075 + }, + { + "step": 832, + "loss": 0.6411258578300476, + "error": 0.3984375, + "gradient_norm": 0.160088911652565, + "elapsed": 294.2048614025116 + }, + { + "step": 848, + "loss": 0.5756919980049133, + "error": 0.3515625, + "gradient_norm": 0.0962308868765831, + "elapsed": 299.15635418891907 + }, + { + "step": 864, + "loss": 0.2706402540206909, + "error": 0.1171875, + "gradient_norm": 0.11391306668519974, + "elapsed": 304.09321761131287 + }, + { + "step": 880, + "loss": 0.33621329069137573, + "error": 0.1640625, + "gradient_norm": 0.09049320220947266, + "elapsed": 309.0412187576294 + }, + { + "step": 896, + "loss": 0.44343245029449463, + "error": 0.23828125, + "gradient_norm": 0.12484703958034515, + "elapsed": 313.98498797416687 + }, + { + "step": 912, + "loss": 0.5987736582756042, + "error": 0.359375, + "gradient_norm": 0.07541236281394958, + "elapsed": 318.9334623813629 + }, + { + "step": 928, + "loss": 0.38585522770881653, + "error": 0.1875, + "gradient_norm": 0.09290861338376999, + "elapsed": 323.86884689331055 + }, + { + "step": 944, + "loss": 0.4820440113544464, + "error": 0.234375, + "gradient_norm": 0.22198310494422913, + "elapsed": 328.7963180541992 + }, + { + "step": 960, + "loss": 0.07455944269895554, + "error": 0.015625, + "gradient_norm": 0.055282026529312134, + "elapsed": 333.75238251686096 + }, + { + "step": 976, + "loss": 0.013475366868078709, + "error": 0.0078125, + "gradient_norm": 0.009843004867434502, + "elapsed": 338.6403331756592 + }, + { + "step": 992, + "loss": 0.4429199695587158, + "error": 0.2265625, + "gradient_norm": 0.09489083290100098, + "elapsed": 343.5606532096863 + }, + { + "step": 1008, + "loss": 0.4892328381538391, + "error": 0.234375, + "gradient_norm": 0.1342826634645462, + "elapsed": 348.5243353843689 + }, + { + "step": 1024, + "loss": 0.6096819043159485, + "error": 0.32421875, + "gradient_norm": 0.17938998341560364, + "elapsed": 353.36506962776184 + } + ] + }, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.4341062307357788, + "objective": 0.4341062307357788, + "error": 0.208984375, + "gradient_norm": 0.07617632299661636, + "elapsed": 31.45817995071411 + }, + { + "step": 16, + "loss": 0.5996706485748291, + "objective": 0.5996706485748291, + "error": 0.359375, + "gradient_norm": 0.05249844491481781, + "elapsed": 56.34200572967529 + }, + { + "step": 32, + "loss": 0.4388691186904907, + "objective": 0.4388691186904907, + "error": 0.2041015625, + "gradient_norm": 0.0376109778881073, + "elapsed": 67.83739852905273 + }, + { + "step": 48, + "loss": 0.5373439788818359, + "objective": 0.5373439788818359, + "error": 0.2919921875, + "gradient_norm": 0.06261218339204788, + "elapsed": 76.69065475463867 + }, + { + "step": 64, + "loss": 0.24871854484081268, + "objective": 0.24871854484081268, + "error": 0.1162109375, + "gradient_norm": 0.05284671485424042, + "elapsed": 86.3852767944336 + }, + { + "step": 80, + "loss": 0.26628297567367554, + "objective": 0.26628297567367554, + "error": 0.123046875, + "gradient_norm": 0.04054367542266846, + "elapsed": 95.77356100082397 + }, + { + "step": 96, + "loss": 0.48436349630355835, + "objective": 0.48436349630355835, + "error": 0.259765625, + "gradient_norm": 0.05399860441684723, + "elapsed": 107.06293416023254 + }, + { + "step": 112, + "loss": 0.41063767671585083, + "objective": 0.41063767671585083, + "error": 0.1943359375, + "gradient_norm": 0.043602071702480316, + "elapsed": 116.78119611740112 + }, + { + "step": 128, + "loss": 0.3990316390991211, + "objective": 0.3990316390991211, + "error": 0.1865234375, + "gradient_norm": 0.0424419641494751, + "elapsed": 125.6915397644043 + }, + { + "step": 144, + "loss": 0.5119550228118896, + "objective": 0.5119550228118896, + "error": 0.2646484375, + "gradient_norm": 0.07688591629266739, + "elapsed": 136.20711088180542 + }, + { + "step": 160, + "loss": 0.3388235569000244, + "objective": 0.3388235569000244, + "error": 0.1630859375, + "gradient_norm": 0.07015731930732727, + "elapsed": 145.3505516052246 + }, + { + "step": 176, + "loss": 0.5952156186103821, + "objective": 0.5952156186103821, + "error": 0.3369140625, + "gradient_norm": 0.039373140782117844, + "elapsed": 154.77994871139526 + }, + { + "step": 192, + "loss": 0.15157413482666016, + "objective": 0.15157413482666016, + "error": 0.0634765625, + "gradient_norm": 0.029710670933127403, + "elapsed": 164.46801733970642 + }, + { + "step": 208, + "loss": 0.3120684027671814, + "objective": 0.3120684027671814, + "error": 0.1474609375, + "gradient_norm": 0.035548821091651917, + "elapsed": 173.24825358390808 + }, + { + "step": 224, + "loss": 0.5486405491828918, + "objective": 0.5486405491828918, + "error": 0.2900390625, + "gradient_norm": 0.0503678023815155, + "elapsed": 185.29849314689636 + }, + { + "step": 240, + "loss": 0.6046283841133118, + "objective": 0.6046283841133118, + "error": 0.3349609375, + "gradient_norm": 0.05043461173772812, + "elapsed": 197.54880928993225 + }, + { + "step": 256, + "loss": 0.5926339626312256, + "objective": 0.5926339626312256, + "error": 0.3359375, + "gradient_norm": 0.051241543143987656, + "elapsed": 211.79861068725586 + }, + { + "step": 272, + "loss": 0.4018518924713135, + "objective": 0.4018518924713135, + "error": 0.1943359375, + "gradient_norm": 0.0772147998213768, + "elapsed": 222.41974115371704 + }, + { + "step": 288, + "loss": 0.13863243162631989, + "objective": 0.13863243162631989, + "error": 0.0556640625, + "gradient_norm": 0.03334609419107437, + "elapsed": 234.04247426986694 + }, + { + "step": 304, + "loss": 0.562490701675415, + "objective": 0.562490701675415, + "error": 0.337890625, + "gradient_norm": 0.04585934057831764, + "elapsed": 242.65421533584595 + }, + { + "step": 320, + "loss": 0.5352796316146851, + "objective": 0.5352796316146851, + "error": 0.294921875, + "gradient_norm": 0.0837635025382042, + "elapsed": 252.10656356811523 + }, + { + "step": 336, + "loss": 0.26082637906074524, + "objective": 0.26082637906074524, + "error": 0.1220703125, + "gradient_norm": 0.048336997628211975, + "elapsed": 262.33449625968933 + }, + { + "step": 352, + "loss": 0.5959363579750061, + "objective": 0.5959363579750061, + "error": 0.3388671875, + "gradient_norm": 0.06797357648611069, + "elapsed": 271.9942307472229 + }, + { + "step": 368, + "loss": 0.48994284868240356, + "objective": 0.48994284868240356, + "error": 0.2587890625, + "gradient_norm": 0.06296153366565704, + "elapsed": 283.0493588447571 + }, + { + "step": 384, + "loss": 0.5710494518280029, + "objective": 0.5710494518280029, + "error": 0.3134765625, + "gradient_norm": 0.045333269983530045, + "elapsed": 294.64637446403503 + }, + { + "step": 400, + "loss": 0.5957783460617065, + "objective": 0.5957783460617065, + "error": 0.349609375, + "gradient_norm": 0.03918786719441414, + "elapsed": 307.6200888156891 + }, + { + "step": 416, + "loss": 0.27521568536758423, + "objective": 0.27521568536758423, + "error": 0.1220703125, + "gradient_norm": 0.038001637905836105, + "elapsed": 317.01610231399536 + }, + { + "step": 432, + "loss": 0.02379823848605156, + "objective": 0.02379823848605156, + "error": 0.0078125, + "gradient_norm": 0.007661945186555386, + "elapsed": 326.9360330104828 + }, + { + "step": 448, + "loss": 0.56734299659729, + "objective": 0.56734299659729, + "error": 0.3271484375, + "gradient_norm": 0.057416290044784546, + "elapsed": 339.6289041042328 + }, + { + "step": 464, + "loss": 0.10715995728969574, + "objective": 0.10715995728969574, + "error": 0.0380859375, + "gradient_norm": 0.02532491274178028, + "elapsed": 349.8584108352661 + }, + { + "step": 480, + "loss": 0.6143364310264587, + "objective": 0.6143364310264587, + "error": 0.36328125, + "gradient_norm": 0.08023032546043396, + "elapsed": 360.36362075805664 + }, + { + "step": 496, + "loss": 0.44069671630859375, + "objective": 0.44069671630859375, + "error": 0.2197265625, + "gradient_norm": 0.048025116324424744, + "elapsed": 369.48225808143616 + }, + { + "step": 512, + "loss": 0.019900165498256683, + "objective": 0.019900165498256683, + "error": 0.0107421875, + "gradient_norm": 0.0038635791279375553, + "elapsed": 378.59970593452454 + }, + { + "step": 528, + "loss": 0.033316534012556076, + "objective": 0.033316534012556076, + "error": 0.009765625, + "gradient_norm": 0.009174940176308155, + "elapsed": 393.4021761417389 + }, + { + "step": 544, + "loss": 0.41130945086479187, + "objective": 0.41130945086479187, + "error": 0.20703125, + "gradient_norm": 0.04695262759923935, + "elapsed": 402.8586280345917 + }, + { + "step": 560, + "loss": 0.5885373950004578, + "objective": 0.5885373950004578, + "error": 0.3544921875, + "gradient_norm": 0.08534500002861023, + "elapsed": 416.98661041259766 + }, + { + "step": 576, + "loss": 0.3804720640182495, + "objective": 0.3804720640182495, + "error": 0.19140625, + "gradient_norm": 0.05163278803229332, + "elapsed": 427.7550480365753 + }, + { + "step": 592, + "loss": 0.6101120710372925, + "objective": 0.6101120710372925, + "error": 0.3525390625, + "gradient_norm": 0.05593184754252434, + "elapsed": 441.05026268959045 + }, + { + "step": 608, + "loss": 0.5586092472076416, + "objective": 0.5586092472076416, + "error": 0.302734375, + "gradient_norm": 0.07458740472793579, + "elapsed": 452.95383286476135 + }, + { + "step": 624, + "loss": 0.5992780923843384, + "objective": 0.5992780923843384, + "error": 0.357421875, + "gradient_norm": 0.03618372976779938, + "elapsed": 466.1582691669464 + }, + { + "step": 640, + "loss": 0.3536975383758545, + "objective": 0.3536975383758545, + "error": 0.1650390625, + "gradient_norm": 0.05353165790438652, + "elapsed": 477.166255235672 + }, + { + "step": 656, + "loss": 0.4926893711090088, + "objective": 0.4926893711090088, + "error": 0.2626953125, + "gradient_norm": 0.05201377719640732, + "elapsed": 491.1417751312256 + }, + { + "step": 672, + "loss": 0.5754991173744202, + "objective": 0.5754991173744202, + "error": 0.3271484375, + "gradient_norm": 0.08167096972465515, + "elapsed": 501.630366563797 + }, + { + "step": 688, + "loss": 0.5685014724731445, + "objective": 0.5685014724731445, + "error": 0.333984375, + "gradient_norm": 0.043775107711553574, + "elapsed": 514.2880456447601 + }, + { + "step": 704, + "loss": 0.022465089336037636, + "objective": 0.022465089336037636, + "error": 0.0068359375, + "gradient_norm": 0.010172540321946144, + "elapsed": 522.9173214435577 + }, + { + "step": 720, + "loss": 0.035460107028484344, + "objective": 0.035460107028484344, + "error": 0.0107421875, + "gradient_norm": 0.010515578091144562, + "elapsed": 532.8470129966736 + }, + { + "step": 736, + "loss": 0.44765588641166687, + "objective": 0.44765588641166687, + "error": 0.2138671875, + "gradient_norm": 0.09050357341766357, + "elapsed": 541.9488840103149 + }, + { + "step": 752, + "loss": 0.5933939218521118, + "objective": 0.5933939218521118, + "error": 0.3359375, + "gradient_norm": 0.0665116235613823, + "elapsed": 552.9967355728149 + }, + { + "step": 768, + "loss": 0.6100764870643616, + "objective": 0.6100764870643616, + "error": 0.3515625, + "gradient_norm": 0.0821211114525795, + "elapsed": 563.7709202766418 + }, + { + "step": 784, + "loss": 0.02964692935347557, + "objective": 0.02964692935347557, + "error": 0.009765625, + "gradient_norm": 0.012663272209465504, + "elapsed": 573.1517221927643 + }, + { + "step": 800, + "loss": 0.38091832399368286, + "objective": 0.38091832399368286, + "error": 0.1904296875, + "gradient_norm": 0.060622021555900574, + "elapsed": 582.5687477588654 + }, + { + "step": 816, + "loss": 0.552335262298584, + "objective": 0.552335262298584, + "error": 0.3076171875, + "gradient_norm": 0.14419035613536835, + "elapsed": 594.4292685985565 + }, + { + "step": 832, + "loss": 0.5943340063095093, + "objective": 0.5943340063095093, + "error": 0.34375, + "gradient_norm": 0.0633513554930687, + "elapsed": 605.2052299976349 + }, + { + "step": 848, + "loss": 0.6074100732803345, + "objective": 0.6074100732803345, + "error": 0.3486328125, + "gradient_norm": 0.04225531220436096, + "elapsed": 614.8996202945709 + }, + { + "step": 864, + "loss": 0.6198879480361938, + "objective": 0.6198879480361938, + "error": 0.361328125, + "gradient_norm": 0.04208856821060181, + "elapsed": 625.4266908168793 + }, + { + "step": 880, + "loss": 0.6151762008666992, + "objective": 0.6151762008666992, + "error": 0.369140625, + "gradient_norm": 0.06261089444160461, + "elapsed": 636.0696911811829 + }, + { + "step": 896, + "loss": 0.49680083990097046, + "objective": 0.49680083990097046, + "error": 0.25390625, + "gradient_norm": 0.0827067643404007, + "elapsed": 644.6893246173859 + }, + { + "step": 912, + "loss": 0.4610927402973175, + "objective": 0.4610927402973175, + "error": 0.23828125, + "gradient_norm": 0.06652095168828964, + "elapsed": 655.969132900238 + }, + { + "step": 928, + "loss": 0.5218505859375, + "objective": 0.5218505859375, + "error": 0.2685546875, + "gradient_norm": 0.07188194245100021, + "elapsed": 667.5352523326874 + }, + { + "step": 944, + "loss": 0.33009427785873413, + "objective": 0.33009427785873413, + "error": 0.1533203125, + "gradient_norm": 0.05718810483813286, + "elapsed": 677.8397319316864 + }, + { + "step": 960, + "loss": 0.5703234672546387, + "objective": 0.5703234672546387, + "error": 0.3193359375, + "gradient_norm": 0.11168288439512253, + "elapsed": 687.8742904663086 + }, + { + "step": 976, + "loss": 0.025548014789819717, + "objective": 0.025548014789819717, + "error": 0.0107421875, + "gradient_norm": 0.009453393518924713, + "elapsed": 698.294285774231 + }, + { + "step": 992, + "loss": 0.45398157835006714, + "objective": 0.45398157835006714, + "error": 0.2412109375, + "gradient_norm": 0.04607952758669853, + "elapsed": 707.903199672699 + }, + { + "step": 1008, + "loss": 0.3412189781665802, + "objective": 0.3412189781665802, + "error": 0.1513671875, + "gradient_norm": 0.0432075597345829, + "elapsed": 718.5662748813629 + }, + { + "step": 1024, + "loss": 0.4376429319381714, + "objective": 0.4376429319381714, + "error": 0.2275390625, + "gradient_norm": 0.07974351197481155, + "elapsed": 728.8954858779907 + }, + { + "step": 1040, + "loss": 0.33512815833091736, + "objective": 0.33512815833091736, + "error": 0.150390625, + "gradient_norm": 0.04476875811815262, + "elapsed": 744.0822694301605 + }, + { + "step": 1056, + "loss": 0.5214208364486694, + "objective": 0.5214208364486694, + "error": 0.283203125, + "gradient_norm": 0.08898192644119263, + "elapsed": 755.1484262943268 + }, + { + "step": 1072, + "loss": 0.13849599659442902, + "objective": 0.13849599659442902, + "error": 0.052734375, + "gradient_norm": 0.028359953314065933, + "elapsed": 764.3303108215332 + }, + { + "step": 1088, + "loss": 0.323838472366333, + "objective": 0.323838472366333, + "error": 0.1435546875, + "gradient_norm": 0.04081716760993004, + "elapsed": 773.2739362716675 + }, + { + "step": 1104, + "loss": 0.5627881288528442, + "objective": 0.5627881288528442, + "error": 0.3125, + "gradient_norm": 0.08322097361087799, + "elapsed": 784.7223973274231 + }, + { + "step": 1120, + "loss": 0.44111010432243347, + "objective": 0.44111010432243347, + "error": 0.2216796875, + "gradient_norm": 0.05700977146625519, + "elapsed": 795.085648059845 + }, + { + "step": 1136, + "loss": 0.6395992040634155, + "objective": 0.6395992040634155, + "error": 0.39453125, + "gradient_norm": 0.0744553729891777, + "elapsed": 805.7942585945129 + }, + { + "step": 1152, + "loss": 0.5433304309844971, + "objective": 0.5433304309844971, + "error": 0.287109375, + "gradient_norm": 0.04814797267317772, + "elapsed": 817.3382890224457 + }, + { + "step": 1168, + "loss": 0.5708576440811157, + "objective": 0.5708576440811157, + "error": 0.3203125, + "gradient_norm": 0.051331400871276855, + "elapsed": 829.288791179657 + }, + { + "step": 1184, + "loss": 0.5447035431861877, + "objective": 0.5447035431861877, + "error": 0.2939453125, + "gradient_norm": 0.10116687417030334, + "elapsed": 839.6822843551636 + }, + { + "step": 1200, + "loss": 0.6125671863555908, + "objective": 0.6125671863555908, + "error": 0.3642578125, + "gradient_norm": 0.04368080571293831, + "elapsed": 850.2262740135193 + }, + { + "step": 1216, + "loss": 0.5002380609512329, + "objective": 0.5002380609512329, + "error": 0.259765625, + "gradient_norm": 0.04939017817378044, + "elapsed": 862.3783452510834 + }, + { + "step": 1232, + "loss": 0.5698772668838501, + "objective": 0.5698772668838501, + "error": 0.3173828125, + "gradient_norm": 0.04916854575276375, + "elapsed": 871.4622664451599 + }, + { + "step": 1248, + "loss": 0.6046518683433533, + "objective": 0.6046518683433533, + "error": 0.341796875, + "gradient_norm": 0.04919794574379921, + "elapsed": 883.3905737400055 + }, + { + "step": 1264, + "loss": 0.5913128852844238, + "objective": 0.5913128852844238, + "error": 0.357421875, + "gradient_norm": 0.046917904168367386, + "elapsed": 892.4264807701111 + }, + { + "step": 1280, + "loss": 0.5027461051940918, + "objective": 0.5027461051940918, + "error": 0.2626953125, + "gradient_norm": 0.04705750197172165, + "elapsed": 902.5875842571259 + }, + { + "step": 1296, + "loss": 0.13519814610481262, + "objective": 0.13519814610481262, + "error": 0.052734375, + "gradient_norm": 0.02625490538775921, + "elapsed": 912.4087471961975 + }, + { + "step": 1312, + "loss": 0.5862359404563904, + "objective": 0.5862359404563904, + "error": 0.3271484375, + "gradient_norm": 0.05441493168473244, + "elapsed": 923.992555141449 + }, + { + "step": 1328, + "loss": 0.6031408309936523, + "objective": 0.6031408309936523, + "error": 0.3505859375, + "gradient_norm": 0.05901554971933365, + "elapsed": 933.3936491012573 + }, + { + "step": 1344, + "loss": 0.5823733806610107, + "objective": 0.5823733806610107, + "error": 0.3310546875, + "gradient_norm": 0.0842989832162857, + "elapsed": 941.979998588562 + }, + { + "step": 1360, + "loss": 0.6241492033004761, + "objective": 0.6241492033004761, + "error": 0.3720703125, + "gradient_norm": 0.04446673393249512, + "elapsed": 954.969649553299 + }, + { + "step": 1376, + "loss": 0.5829156637191772, + "objective": 0.5829156637191772, + "error": 0.361328125, + "gradient_norm": 0.06615480780601501, + "elapsed": 966.0245676040649 + }, + { + "step": 1392, + "loss": 0.5968320369720459, + "objective": 0.5968320369720459, + "error": 0.34765625, + "gradient_norm": 0.05093541368842125, + "elapsed": 975.1022663116455 + }, + { + "step": 1408, + "loss": 0.045559000223875046, + "objective": 0.045559000223875046, + "error": 0.01171875, + "gradient_norm": 0.02514980360865593, + "elapsed": 987.2391452789307 + }, + { + "step": 1424, + "loss": 0.22601813077926636, + "objective": 0.22601813077926636, + "error": 0.09765625, + "gradient_norm": 0.04834206402301788, + "elapsed": 996.4583384990692 + }, + { + "step": 1440, + "loss": 0.23011144995689392, + "objective": 0.23011144995689392, + "error": 0.111328125, + "gradient_norm": 0.050687842071056366, + "elapsed": 1007.1440904140472 + }, + { + "step": 1456, + "loss": 0.018240466713905334, + "objective": 0.018240466713905334, + "error": 0.0078125, + "gradient_norm": 0.005604141391813755, + "elapsed": 1016.4502851963043 + }, + { + "step": 1472, + "loss": 0.4498720169067383, + "objective": 0.4498720169067383, + "error": 0.232421875, + "gradient_norm": 0.08179625123739243, + "elapsed": 1028.8303294181824 + }, + { + "step": 1488, + "loss": 0.24151627719402313, + "objective": 0.24151627719402313, + "error": 0.107421875, + "gradient_norm": 0.03838668763637543, + "elapsed": 1037.8867321014404 + }, + { + "step": 1504, + "loss": 0.46122002601623535, + "objective": 0.46122002601623535, + "error": 0.232421875, + "gradient_norm": 0.0726623386144638, + "elapsed": 1047.7258644104004 + }, + { + "step": 1520, + "loss": 0.5085602402687073, + "objective": 0.5085602402687073, + "error": 0.2705078125, + "gradient_norm": 0.06673175096511841, + "elapsed": 1059.352120399475 + }, + { + "step": 1536, + "loss": 0.6105246543884277, + "objective": 0.6105246543884277, + "error": 0.3818359375, + "gradient_norm": 0.04271261766552925, + "elapsed": 1070.1413230895996 + }, + { + "step": 1552, + "loss": 0.4792126417160034, + "objective": 0.4792126417160034, + "error": 0.2578125, + "gradient_norm": 0.05200039595365524, + "elapsed": 1086.444006204605 + }, + { + "step": 1568, + "loss": 0.5814266204833984, + "objective": 0.5814266204833984, + "error": 0.330078125, + "gradient_norm": 0.05867309868335724, + "elapsed": 1097.2902619838715 + }, + { + "step": 1584, + "loss": 0.6321226358413696, + "objective": 0.6321226358413696, + "error": 0.3798828125, + "gradient_norm": 0.05418067052960396, + "elapsed": 1107.9767682552338 + }, + { + "step": 1600, + "loss": 0.5931253433227539, + "objective": 0.5931253433227539, + "error": 0.3603515625, + "gradient_norm": 0.06396215409040451, + "elapsed": 1121.782609462738 + }, + { + "step": 1616, + "loss": 0.6411516666412354, + "objective": 0.6411516666412354, + "error": 0.38671875, + "gradient_norm": 0.05035768821835518, + "elapsed": 1132.7197887897491 + }, + { + "step": 1632, + "loss": 0.4267754852771759, + "objective": 0.4267754852771759, + "error": 0.2080078125, + "gradient_norm": 0.09109894186258316, + "elapsed": 1139.1667578220367 + }, + { + "step": 1648, + "loss": 0.21246182918548584, + "objective": 0.21246182918548584, + "error": 0.095703125, + "gradient_norm": 0.04478950425982475, + "elapsed": 1149.1183021068573 + }, + { + "step": 1664, + "loss": 0.46360665559768677, + "objective": 0.46360665559768677, + "error": 0.251953125, + "gradient_norm": 0.07668188214302063, + "elapsed": 1161.1197745800018 + }, + { + "step": 1680, + "loss": 0.46281397342681885, + "objective": 0.46281397342681885, + "error": 0.236328125, + "gradient_norm": 0.07954126596450806, + "elapsed": 1171.8474535942078 + }, + { + "step": 1696, + "loss": 0.2484058141708374, + "objective": 0.2484058141708374, + "error": 0.12109375, + "gradient_norm": 0.047261305153369904, + "elapsed": 1185.6542596817017 + }, + { + "step": 1712, + "loss": 0.24310235679149628, + "objective": 0.24310235679149628, + "error": 0.1064453125, + "gradient_norm": 0.07262872904539108, + "elapsed": 1197.8986082077026 + }, + { + "step": 1728, + "loss": 0.009729458019137383, + "objective": 0.009729458019137383, + "error": 0.001953125, + "gradient_norm": 0.01146845705807209, + "elapsed": 1208.495581150055 + }, + { + "step": 1744, + "loss": 0.24568752944469452, + "objective": 0.24568752944469452, + "error": 0.10546875, + "gradient_norm": 0.05830742046236992, + "elapsed": 1219.9394850730896 + }, + { + "step": 1760, + "loss": 0.022546378895640373, + "objective": 0.022546378895640373, + "error": 0.0068359375, + "gradient_norm": 0.007667526602745056, + "elapsed": 1229.5703229904175 + }, + { + "step": 1776, + "loss": 0.5848401784896851, + "objective": 0.5848401784896851, + "error": 0.3271484375, + "gradient_norm": 0.061901818960905075, + "elapsed": 1238.750280380249 + }, + { + "step": 1792, + "loss": 0.6031335592269897, + "objective": 0.6031335592269897, + "error": 0.3671875, + "gradient_norm": 0.0676632970571518, + "elapsed": 1247.7468683719635 + }, + { + "step": 1808, + "loss": 0.6210961937904358, + "objective": 0.6210961937904358, + "error": 0.3603515625, + "gradient_norm": 0.0718468651175499, + "elapsed": 1256.1821897029877 + }, + { + "step": 1824, + "loss": 0.570877730846405, + "objective": 0.570877730846405, + "error": 0.3212890625, + "gradient_norm": 0.05575930327177048, + "elapsed": 1266.4091975688934 + }, + { + "step": 1840, + "loss": 0.5711429119110107, + "objective": 0.5711429119110107, + "error": 0.31640625, + "gradient_norm": 0.0691002607345581, + "elapsed": 1277.4722146987915 + }, + { + "step": 1856, + "loss": 0.36046335101127625, + "objective": 0.36046335101127625, + "error": 0.16796875, + "gradient_norm": 0.04694395884871483, + "elapsed": 1287.1420249938965 + }, + { + "step": 1872, + "loss": 0.4688999652862549, + "objective": 0.4688999652862549, + "error": 0.2216796875, + "gradient_norm": 0.07401346415281296, + "elapsed": 1297.3945078849792 + }, + { + "step": 1888, + "loss": 0.46385282278060913, + "objective": 0.46385282278060913, + "error": 0.2373046875, + "gradient_norm": 0.05608939751982689, + "elapsed": 1305.9779334068298 + }, + { + "step": 1904, + "loss": 0.60875403881073, + "objective": 0.60875403881073, + "error": 0.365234375, + "gradient_norm": 0.05085878074169159, + "elapsed": 1317.3097081184387 + }, + { + "step": 1920, + "loss": 0.12223530560731888, + "objective": 0.12223530560731888, + "error": 0.0458984375, + "gradient_norm": 0.024870412424206734, + "elapsed": 1328.6486887931824 + }, + { + "step": 1936, + "loss": 0.3486189544200897, + "objective": 0.3486189544200897, + "error": 0.16796875, + "gradient_norm": 0.04780663549900055, + "elapsed": 1336.6701011657715 + }, + { + "step": 1952, + "loss": 0.5777363777160645, + "objective": 0.5777363777160645, + "error": 0.3427734375, + "gradient_norm": 0.0571451336145401, + "elapsed": 1346.9158833026886 + }, + { + "step": 1968, + "loss": 0.39320266246795654, + "objective": 0.39320266246795654, + "error": 0.1884765625, + "gradient_norm": 0.05673858895897865, + "elapsed": 1354.9182631969452 + }, + { + "step": 1984, + "loss": 0.5900611281394958, + "objective": 0.5900611281394958, + "error": 0.3349609375, + "gradient_norm": 0.06593932211399078, + "elapsed": 1364.2754452228546 + }, + { + "step": 2000, + "loss": 0.6212430000305176, + "objective": 0.6212430000305176, + "error": 0.3857421875, + "gradient_norm": 0.040818918496370316, + "elapsed": 1374.7192046642303 + }, + { + "step": 2016, + "loss": 0.15605247020721436, + "objective": 0.15605247020721436, + "error": 0.0556640625, + "gradient_norm": 0.03108786791563034, + "elapsed": 1386.2740807533264 + }, + { + "step": 2032, + "loss": 0.22049596905708313, + "objective": 0.22049596905708313, + "error": 0.1015625, + "gradient_norm": 0.042733557522296906, + "elapsed": 1396.6422457695007 + }, + { + "step": 2048, + "loss": 0.5642613172531128, + "objective": 0.5642613172531128, + "error": 0.306640625, + "gradient_norm": 0.07527482509613037, + "elapsed": 1407.6688070297241 + } + ] + }, + "derived_checkpoints": { + "mean3": { + "checkpoint_label": "mean3", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_run": "full3_1", + "source_optimizer_steps": [ + 1024, + 1536, + 2048 + ], + "source_weights_sha256": { + "1024": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "1536": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "2048": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5" + }, + "source_checkpoint_records": { + "1024": { + "step": 1024, + "training_samples": 1048576, + "unique_training_rows_seen_in_this_phase": 446179, + "weights_sha256": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "complete": true + }, + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 490266, + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "complete": true + }, + "2048": { + "step": 2048, + "training_samples": 2097152, + "unique_training_rows_seen_in_this_phase": 507282, + "weights_sha256": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5", + "complete": true + } + }, + "weights_sha256": "ce5951e7095a9912dc74719254f2fcf9654f219078392b7acf7a8545e6f9f3f4", + "complete": true + }, + "mean4": { + "checkpoint_label": "mean4", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_run": "full3_1", + "source_optimizer_steps": [ + 512, + 1024, + 1536, + 2048 + ], + "source_weights_sha256": { + "512": "d4194b40470453e5df9b75e12326cbbd0e6845946870bb0d53a2cbbdd6ea32dc", + "1024": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "1536": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "2048": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5" + }, + "source_checkpoint_records": { + "512": { + "step": 512, + "training_samples": 524288, + "unique_training_rows_seen_in_this_phase": 324661, + "weights_sha256": "d4194b40470453e5df9b75e12326cbbd0e6845946870bb0d53a2cbbdd6ea32dc", + "complete": true + }, + "1024": { + "step": 1024, + "training_samples": 1048576, + "unique_training_rows_seen_in_this_phase": 446179, + "weights_sha256": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "complete": true + }, + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 490266, + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "complete": true + }, + "2048": { + "step": 2048, + "training_samples": 2097152, + "unique_training_rows_seen_in_this_phase": 507282, + "weights_sha256": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5", + "complete": true + } + }, + "weights_sha256": "ff5a023ce2c18be7c29f810a3788a450e3ad3ad2237d6e9448923aa6a28c5074", + "complete": true + } + }, + "selection": "Predefined averages of the last3 or all4 saved noninitial full3_1 checkpoints; evaluate every validation condition before selecting", + "test_data_used": false, + "derivation_source_sha256": "08c498d6952b0380e001371df9a0461a483631a301f93747b821e529e72b349d" + }, + "training_source_snapshot": "training_sources/full3_swa", + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with the recorded physical decoder.", + "physical_prediction_reference": "/run-state/workspace/research/context_upgrades/turbo1/predictions", + "prior_pass": 3, + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23290264423076928, + "mean3": 0.2335186298076923, + "blend-mean3": 0.2325420673076923, + "mean4": 0.23326322115384618, + "blend-mean4": 0.23300781250000002 + }, + "selected": "blend-mean3" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.22017728365384615, + "mean3": 0.22037259615384613, + "blend-mean3": 0.22091346153846153, + "mean4": 0.2205528846153846, + "blend-mean4": 0.22100360576923078 + }, + "selected": "incumbent" + } + ], + "checkpoints": { + "mean3": { + "checkpoint_label": "mean3", + "kind": "uniform_parameter_average", + "optimizer_updates_in_derived_run": 0, + "source_run": "full3_1", + "source_optimizer_steps": [ + 1024, + 1536, + 2048 + ], + "source_weights_sha256": { + "1024": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "1536": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "2048": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5" + }, + "source_checkpoint_records": { + "1024": { + "step": 1024, + "training_samples": 1048576, + "unique_training_rows_seen_in_this_phase": 446179, + "weights_sha256": "22adf2425bbfb872e814227799b725f78618bccf68410935470e6c37d159a6b7", + "complete": true + }, + "1536": { + "step": 1536, + "training_samples": 1572864, + "unique_training_rows_seen_in_this_phase": 490266, + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "complete": true + }, + "2048": { + "step": 2048, + "training_samples": 2097152, + "unique_training_rows_seen_in_this_phase": 507282, + "weights_sha256": "b93c1367dfeb0e32b2add76b1abeb3f12d4d9f8145d0f13d8d5b17ca882ba3b5", + "complete": true + } + }, + "weights_sha256": "ce5951e7095a9912dc74719254f2fcf9654f219078392b7acf7a8545e6f9f3f4", + "complete": true + } + }, + "runtime": "Share physical priors when the conditioning pass and regime agree; otherwise recompute the neural prior independently. Last-only physical branches omit logical tracking in intermediate passes when intermediate probabilities are unused.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false + }, + "checkpoints": { + "512": { + "step": 512, + "training_samples": 524288, + "unique_training_rows_seen_in_this_phase": 317630, + "weights_sha256": "82246691e00fc2a3a621ad268bf2ed753376f4abfb39240f64814b5f6cb00f5b", + "complete": true + } + }, + "selection": "Per-basis minimum full-validation mean over the incumbent and equal old/new neural probability averages, optionally blended with physical probability at fractions 0, .25, or .5. All 13 durations included.", + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23216646634615384, + "0-physical-0": 0.232421875, + "0-physical-0.25": 0.2330228365384615, + "0-physical-0.5": 0.23330829326923078, + "512-physical-0": 0.2321364182692308, + "512-physical-0.25": 0.23296274038461537, + "512-physical-0.5": 0.2327674278846154, + "1024-physical-0": 0.23255709134615382, + "1024-physical-0.25": 0.23302283653846154, + "1024-physical-0.5": 0.23284254807692306, + "1536-physical-0": 0.23224158653846155, + "1536-physical-0.25": 0.2330228365384615, + "1536-physical-0.5": 0.2332481971153846 + }, + "selected": "512-physical-0", + "original_checkpoint": "full3_swa/mean3" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.21953124999999998, + "0-physical-0": 0.22059795673076923, + "0-physical-0.25": 0.22046274038461539, + "0-physical-0.5": 0.2205829326923077, + "512-physical-0": 0.22013221153846155, + "512-physical-0.25": 0.22046274038461539, + "512-physical-0.5": 0.22061298076923078, + "1024-physical-0": 0.22013221153846155, + "1024-physical-0.25": 0.2209885817307692, + "1024-physical-0.5": 0.22049278846153844, + "1536-physical-0": 0.22064302884615383, + "1536-physical-0.25": 0.2205078125, + "1536-physical-0.5": 0.22095853365384616 + }, + "selected": "incumbent", + "original_checkpoint": "full3_1/1536" + } + ], + "control": { + "status": "passed", + "device": "cpu", + "source_sha256": "59d6c85dc4bd61e26cf7243baf0e2637c3de1d35327b2c763707badd19446550", + "reference_package": "/run-state/workspace/research/context_upgrades/short_categorical2/package", + "members": [ + { + "weights": "weights/neural-d5-neural_d5_full3_swa-mean3.npz", + "coefficient": 1.0 + }, + { + "weights": "weights/neural-d5-neural_d5_full3_1-1536.npz", + "coefficient": 3.0 + } + ], + "cases": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 1, + "single_path_exact": true, + "shared_mixture_exact": true, + "cpu_recomputed_vs_gpu_cached_prior_max_difference": null + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 7, + "single_path_exact": true, + "shared_mixture_exact": true, + "cpu_recomputed_vs_gpu_cached_prior_max_difference": 1.7881393432617188e-07 + } + ], + "seconds": 4.879673480987549, + "scope": "Runtime probability aggregation and prior reuse; no model fitting or validation selection." + }, + "test_data_used": false + }, + "neural_d5": { + "training": { + "initialization": "Continue from the recorded session-trained checkpoint; original random initialization seed 20261273", + "prior_pass": 3, + "initial_seed": 20261273, + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "Only the18856 declared fit rows per each of26 d5 conditions; both512-row gate and512-row audit partitions excluded from every optimizer update. Uniform condition/within-condition sampling.", + "reserved_training_partition": { + "manifest": "/run-state/workspace/research/learned_d5/reserved_split1/manifest.json", + "manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "selected_part": "fit", + "details": { + "schema": "qecbench-training-reserved-split/v1", + "seed": 20261270, + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "source_sha256": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "conditions": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "file": "surface_code_bX_d5_r01_center_5_5.npz", + "sha256": "c72d5c5ee3daf1b128e0c226f2815009daf6127e8b028004e86cebd6047ac474", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "file": "surface_code_bX_d5_r03_center_5_5.npz", + "sha256": "3a59636161c80fbbf326cf1919817ce5f60ec9e6d3e4b6223579cb6a36e12e31", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "file": "surface_code_bX_d5_r05_center_5_5.npz", + "sha256": "e808936ef0cb32869e0944ab70a3026ef96d0f31fe0fe9967c6d87a15b85abb5", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "file": "surface_code_bX_d5_r07_center_5_5.npz", + "sha256": "cd0f71459448a41af10e4399637d02e8d8193dea16ab300f839cb56ad8b08203", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "file": "surface_code_bX_d5_r09_center_5_5.npz", + "sha256": "56648e2b93499736d40f6aa5e9e8a568f150cbc8589929578f57c1e839c92d76", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "file": "surface_code_bX_d5_r11_center_5_5.npz", + "sha256": "ce2dcc2bfcb57bbfcb2291105a9a011a2a3113ad92348dfa7c76076f1fb3cacf", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "file": "surface_code_bX_d5_r13_center_5_5.npz", + "sha256": "968b14d4d948474afd0e182d9c60cd577297d4b7bb331e916058e41692d7c9d2", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "file": "surface_code_bX_d5_r15_center_5_5.npz", + "sha256": "8d73808a777d81c2acc2f6aab924cc11690a94136bc666fbf11f78292a47615d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "file": "surface_code_bX_d5_r17_center_5_5.npz", + "sha256": "0ab49c9dc61605d43f0c03427352af0ee230ecf7360927f75de60519d707c7ee", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "file": "surface_code_bX_d5_r19_center_5_5.npz", + "sha256": "27594cc6e0943860d828ebde2c76fdde64ccf2a357f896d551f3d4606e74fec4", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "file": "surface_code_bX_d5_r21_center_5_5.npz", + "sha256": "1b1fdcf280ca7c8ba94476f9c54b6ab70eee59b63b3be406a534014132295b7e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "file": "surface_code_bX_d5_r23_center_5_5.npz", + "sha256": "d31e0ca2ce6a6d04ed7bbd80113aec8cca40526b643752d8f429ece168736759", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "file": "surface_code_bX_d5_r25_center_5_5.npz", + "sha256": "f45a5978d77b1ef450f2ffd9fa19413c9d647448a3d61dfafd7590671dcace19", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "file": "surface_code_bZ_d5_r01_center_5_5.npz", + "sha256": "647e82ac0721a7245b3deb831a5a73eb555a3cb3e58b460774ffb96dc99c3b64", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "file": "surface_code_bZ_d5_r03_center_5_5.npz", + "sha256": "b64be8c7883b921bd57d5eefcc53656c2dad484833e5533e499b19b45be90158", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "file": "surface_code_bZ_d5_r05_center_5_5.npz", + "sha256": "63361e091640a4d506fc372bd0764ad248f6551d77cdf57550405b2624ca97b1", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "file": "surface_code_bZ_d5_r07_center_5_5.npz", + "sha256": "c50d26a58c1fb6b5a20f5737b94c3bac9182fe703bafa221532b8b012064f655", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "file": "surface_code_bZ_d5_r09_center_5_5.npz", + "sha256": "d62ecb975d63f13664bc6b02d30499a3fb10f0c22f1068b28bbbc31d1ec91fcc", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "file": "surface_code_bZ_d5_r11_center_5_5.npz", + "sha256": "724c7dc2c4cf2b551abf4f75e230f5aa04a74eebba79c25c845f14d15863de5e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "file": "surface_code_bZ_d5_r13_center_5_5.npz", + "sha256": "0e618a998fb591a85dd365eead741a91b6560ed1a3987046286a67a2c754fa83", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "file": "surface_code_bZ_d5_r15_center_5_5.npz", + "sha256": "e1f8c6f812dc98c48402b69a08b09b520d1374e9f2e51b3e681b67bf306e17be", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "file": "surface_code_bZ_d5_r17_center_5_5.npz", + "sha256": "aa23a51a79677a8ac43cc31b72fe07e73c827f935c632c29b09924fc88242d0d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "file": "surface_code_bZ_d5_r19_center_5_5.npz", + "sha256": "8420b79a8d7324f41dfd1cccacfd1fae9b27b370f40c60059e9de187864dba2b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "file": "surface_code_bZ_d5_r21_center_5_5.npz", + "sha256": "088b92610c90dc1a180b2eca8b16e8f225d191ec7fc11355c85e6959f35e7073", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "file": "surface_code_bZ_d5_r23_center_5_5.npz", + "sha256": "b1484c581cbd5439c74befabbd7c1c12e7cb38db099c793dfb3cf748df20fc3b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "file": "surface_code_bZ_d5_r25_center_5_5.npz", + "sha256": "92f552059b6c197b53ff1030d9ba0fe03cf22ea1f116e5280be944ad60f04be3", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + } + ], + "counts": { + "fit": 490256, + "gate": 13312, + "audit": 13312 + }, + "split_features": "Only array lengths and seeded random permutations; IDs verify alignment and are never model features", + "gate_use": "Fit a small combiner on gate labels only after experts exclude both reserved parts", + "audit_use": "Diagnostic only; no parameter fitting, checkpoint selection, or hyperparameter selection", + "validation_use": "Supplied validation selects checkpoints and candidates; no validation labels fit parameters", + "test_data_used": false + } + }, + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 490256, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 467790, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 18254, + "surface_code_bX_d5_r03_center_5_5": 18525, + "surface_code_bX_d5_r05_center_5_5": 18175, + "surface_code_bX_d5_r07_center_5_5": 18005, + "surface_code_bX_d5_r09_center_5_5": 18067, + "surface_code_bX_d5_r11_center_5_5": 18445, + "surface_code_bX_d5_r13_center_5_5": 18673, + "surface_code_bX_d5_r15_center_5_5": 17345, + "surface_code_bX_d5_r17_center_5_5": 17898, + "surface_code_bX_d5_r19_center_5_5": 18359, + "surface_code_bX_d5_r21_center_5_5": 18036, + "surface_code_bX_d5_r23_center_5_5": 17255, + "surface_code_bX_d5_r25_center_5_5": 18057, + "surface_code_bZ_d5_r01_center_5_5": 17596, + "surface_code_bZ_d5_r03_center_5_5": 18333, + "surface_code_bZ_d5_r05_center_5_5": 18250, + "surface_code_bZ_d5_r07_center_5_5": 18210, + "surface_code_bZ_d5_r09_center_5_5": 17447, + "surface_code_bZ_d5_r11_center_5_5": 18120, + "surface_code_bZ_d5_r13_center_5_5": 18224, + "surface_code_bZ_d5_r15_center_5_5": 17857, + "surface_code_bZ_d5_r17_center_5_5": 18359, + "surface_code_bZ_d5_r19_center_5_5": 17398, + "surface_code_bZ_d5_r21_center_5_5": 18235, + "surface_code_bZ_d5_r23_center_5_5": 16653, + "surface_code_bZ_d5_r25_center_5_5": 18014 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 1536, + "batch": 1024, + "learning_rate": 0.0005, + "sampling_seed": 20261274, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": true, + "rng_restored": true, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "/run-state/workspace/research/learned_d5/reserved2_warm/rng-512.json", + "starting_checkpoint": "/run-state/workspace/research/learned_d5/reserved2_warm/weights-512.npz", + "starting_checkpoint_sha256": "2b00e3f258886b5c4ecf69f36fd5463a205eefc84bd10c550acc391e84515c24", + "starting_training_provenance": { + "initialization": "All parameters initialized in this session: variance-scaled normal hidden layers, Normal(0,.001) output weights, zero biases, seed 20261273", + "prior_pass": 3, + "initial_seed": 20261273, + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "runtime_versions": { + "jax": "0.7.2", + "numpy": "2.3.3", + "optax": "0.2.6" + }, + "hidden_width": 64, + "input_features": 394, + "feature_mode": "local events, reconstructed measurements, shot densities, physical edge support and conditioned prior", + "architecture": "Two 64-unit SiLU layers; 394 features; bounded 2*tanh correction to relevant-CSS edge logits from the recorded physical feedback pass; exact width-14 contraction predicts logical probability. D5 joint conditioning remains approximate.", + "training": "Only the18856 declared fit rows per each of26 d5 conditions; both512-row gate and512-row audit partitions excluded from every optimizer update. Uniform condition/within-condition sampling.", + "reserved_training_partition": { + "manifest": "/run-state/workspace/research/learned_d5/reserved_split1/manifest.json", + "manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "selected_part": "fit", + "details": { + "schema": "qecbench-training-reserved-split/v1", + "seed": 20261270, + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "source_sha256": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "conditions": [ + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "file": "surface_code_bX_d5_r01_center_5_5.npz", + "sha256": "c72d5c5ee3daf1b128e0c226f2815009daf6127e8b028004e86cebd6047ac474", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "file": "surface_code_bX_d5_r03_center_5_5.npz", + "sha256": "3a59636161c80fbbf326cf1919817ce5f60ec9e6d3e4b6223579cb6a36e12e31", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "file": "surface_code_bX_d5_r05_center_5_5.npz", + "sha256": "e808936ef0cb32869e0944ab70a3026ef96d0f31fe0fe9967c6d87a15b85abb5", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "file": "surface_code_bX_d5_r07_center_5_5.npz", + "sha256": "cd0f71459448a41af10e4399637d02e8d8193dea16ab300f839cb56ad8b08203", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "file": "surface_code_bX_d5_r09_center_5_5.npz", + "sha256": "56648e2b93499736d40f6aa5e9e8a568f150cbc8589929578f57c1e839c92d76", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "file": "surface_code_bX_d5_r11_center_5_5.npz", + "sha256": "ce2dcc2bfcb57bbfcb2291105a9a011a2a3113ad92348dfa7c76076f1fb3cacf", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "file": "surface_code_bX_d5_r13_center_5_5.npz", + "sha256": "968b14d4d948474afd0e182d9c60cd577297d4b7bb331e916058e41692d7c9d2", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "file": "surface_code_bX_d5_r15_center_5_5.npz", + "sha256": "8d73808a777d81c2acc2f6aab924cc11690a94136bc666fbf11f78292a47615d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "file": "surface_code_bX_d5_r17_center_5_5.npz", + "sha256": "0ab49c9dc61605d43f0c03427352af0ee230ecf7360927f75de60519d707c7ee", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "file": "surface_code_bX_d5_r19_center_5_5.npz", + "sha256": "27594cc6e0943860d828ebde2c76fdde64ccf2a357f896d551f3d4606e74fec4", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "file": "surface_code_bX_d5_r21_center_5_5.npz", + "sha256": "1b1fdcf280ca7c8ba94476f9c54b6ab70eee59b63b3be406a534014132295b7e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "file": "surface_code_bX_d5_r23_center_5_5.npz", + "sha256": "d31e0ca2ce6a6d04ed7bbd80113aec8cca40526b643752d8f429ece168736759", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "file": "surface_code_bX_d5_r25_center_5_5.npz", + "sha256": "f45a5978d77b1ef450f2ffd9fa19413c9d647448a3d61dfafd7590671dcace19", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "file": "surface_code_bZ_d5_r01_center_5_5.npz", + "sha256": "647e82ac0721a7245b3deb831a5a73eb555a3cb3e58b460774ffb96dc99c3b64", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "file": "surface_code_bZ_d5_r03_center_5_5.npz", + "sha256": "b64be8c7883b921bd57d5eefcc53656c2dad484833e5533e499b19b45be90158", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "file": "surface_code_bZ_d5_r05_center_5_5.npz", + "sha256": "63361e091640a4d506fc372bd0764ad248f6551d77cdf57550405b2624ca97b1", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "file": "surface_code_bZ_d5_r07_center_5_5.npz", + "sha256": "c50d26a58c1fb6b5a20f5737b94c3bac9182fe703bafa221532b8b012064f655", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "file": "surface_code_bZ_d5_r09_center_5_5.npz", + "sha256": "d62ecb975d63f13664bc6b02d30499a3fb10f0c22f1068b28bbbc31d1ec91fcc", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "file": "surface_code_bZ_d5_r11_center_5_5.npz", + "sha256": "724c7dc2c4cf2b551abf4f75e230f5aa04a74eebba79c25c845f14d15863de5e", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "file": "surface_code_bZ_d5_r13_center_5_5.npz", + "sha256": "0e618a998fb591a85dd365eead741a91b6560ed1a3987046286a67a2c754fa83", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "file": "surface_code_bZ_d5_r15_center_5_5.npz", + "sha256": "e1f8c6f812dc98c48402b69a08b09b520d1374e9f2e51b3e681b67bf306e17be", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "file": "surface_code_bZ_d5_r17_center_5_5.npz", + "sha256": "aa23a51a79677a8ac43cc31b72fe07e73c827f935c632c29b09924fc88242d0d", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "file": "surface_code_bZ_d5_r19_center_5_5.npz", + "sha256": "8420b79a8d7324f41dfd1cccacfd1fae9b27b370f40c60059e9de187864dba2b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "file": "surface_code_bZ_d5_r21_center_5_5.npz", + "sha256": "088b92610c90dc1a180b2eca8b16e8f225d191ec7fc11355c85e6959f35e7073", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "file": "surface_code_bZ_d5_r23_center_5_5.npz", + "sha256": "b1484c581cbd5439c74befabbd7c1c12e7cb38db099c793dfb3cf748df20fc3b", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "file": "surface_code_bZ_d5_r25_center_5_5.npz", + "sha256": "92f552059b6c197b53ff1030d9ba0fe03cf22ea1f116e5280be944ad60f04be3", + "counts": { + "fit": 18856, + "gate": 512, + "audit": 512 + } + } + ], + "counts": { + "fit": 490256, + "gate": 13312, + "audit": 13312 + }, + "split_features": "Only array lengths and seeded random permutations; IDs verify alignment and are never model features", + "gate_use": "Fit a small combiner on gate labels only after experts exclude both reserved parts", + "audit_use": "Diagnostic only; no parameter fitting, checkpoint selection, or hyperparameter selection", + "validation_use": "Supplied validation selects checkpoints and candidates; no validation labels fit parameters", + "test_data_used": false + } + }, + "training_cache": "/run-state/workspace/research/learned_d5/full_training_priors3", + "training_cache_provenance": { + "method": "Three undamped physical CSS extrinsic-message passes, clipping8, pass1/pass3 priors captured before logical readout", + "scope": "All supplied training rows in all26 d5 conditions; no validation or test labels used in cache generation", + "reused_rows": "4096 rows per condition from feedback5_cache, sampled with seed20261023; same first three passes", + "remaining_rows": "Computed now with last-only logical tracking; previously controlled against full logical tracking", + "train_manifest_sha256": "ce46c21e3595cfc5885bbe2b6481105317d2e6267498ec4572601469825914b8", + "records": [ + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 44.93641114234924, + "elapsed": 45.15474009513855, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.11551070213318, + "elapsed": 88.52458453178406, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 39.70699763298035, + "elapsed": 128.4802794456482, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r23_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.178571701049805, + "elapsed": 169.95510387420654, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 41.53053879737854, + "elapsed": 211.7576286792755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r21_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 43.43117809295654, + "elapsed": 255.62733364105225, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 33.84876799583435, + "elapsed": 289.70106053352356, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r19_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 32.88018870353699, + "elapsed": 322.7981607913971, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.585307836532593, + "elapsed": 352.58776783943176, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r17_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.854028463363647, + "elapsed": 382.6393291950226, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 26.721288919448853, + "elapsed": 409.54919600486755, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r15_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.810269832611084, + "elapsed": 439.6440734863281, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 29.79407238960266, + "elapsed": 469.7887041568756, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r13_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 28.757604837417603, + "elapsed": 498.71140813827515, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.38013219833374, + "elapsed": 524.2447266578674, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r11_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 25.378958225250244, + "elapsed": 549.8600506782532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 21.241567850112915, + "elapsed": 571.2600774765015, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 18.780335664749146, + "elapsed": 590.304051399231, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.346807956695557, + "elapsed": 604.8041462898254, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r07_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 14.03441047668457, + "elapsed": 618.9537570476532, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.811666488647461, + "elapsed": 629.8610434532166, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r05_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 10.982703924179077, + "elapsed": 640.9919559955597, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.846271991729736, + "elapsed": 648.9624857902527, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 7.83586859703064, + "elapsed": 656.9065537452698, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.7685718536376953, + "elapsed": 657.7747800350189, + "peak_gpu_bytes": 58661028096 + }, + { + "condition": "surface_code_bZ_d5_r01_center_5_5", + "shots": 19880, + "reused_training_rows": 4096, + "new_rows": 15784, + "seconds": 0.748960018157959, + "elapsed": 658.5666444301605, + "peak_gpu_bytes": 58661028096 + } + ], + "test_data_used": false + }, + "training_shots": 490256, + "training_pool_interpretation": "Eligible training rows; optimizer samples conditions and rows with replacement. Distinct rows used in this phase are recorded separately.", + "unique_training_rows_seen_in_this_phase": 317635, + "unique_rows_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 13700, + "surface_code_bX_d5_r03_center_5_5": 10036, + "surface_code_bX_d5_r05_center_5_5": 11768, + "surface_code_bX_d5_r07_center_5_5": 10917, + "surface_code_bX_d5_r09_center_5_5": 13458, + "surface_code_bX_d5_r11_center_5_5": 11764, + "surface_code_bX_d5_r13_center_5_5": 14018, + "surface_code_bX_d5_r15_center_5_5": 10968, + "surface_code_bX_d5_r17_center_5_5": 13469, + "surface_code_bX_d5_r19_center_5_5": 11340, + "surface_code_bX_d5_r21_center_5_5": 11327, + "surface_code_bX_d5_r23_center_5_5": 13970, + "surface_code_bX_d5_r25_center_5_5": 10500, + "surface_code_bZ_d5_r01_center_5_5": 12079, + "surface_code_bZ_d5_r03_center_5_5": 12160, + "surface_code_bZ_d5_r05_center_5_5": 9494, + "surface_code_bZ_d5_r07_center_5_5": 10910, + "surface_code_bZ_d5_r09_center_5_5": 10064, + "surface_code_bZ_d5_r11_center_5_5": 10969, + "surface_code_bZ_d5_r13_center_5_5": 13419, + "surface_code_bZ_d5_r15_center_5_5": 12842, + "surface_code_bZ_d5_r17_center_5_5": 13694, + "surface_code_bZ_d5_r19_center_5_5": 13449, + "surface_code_bZ_d5_r21_center_5_5": 13799, + "surface_code_bZ_d5_r23_center_5_5": 12754, + "surface_code_bZ_d5_r25_center_5_5": 14767 + }, + "gradient_block_size": 32, + "bucket_operations": true, + "accumulate_conditions": 1, + "effective_batch_size": 1024, + "uncertainty_weight_floor": 1.0, + "example_weighting": "Uniform BCE", + "loss": "Conditional logical binary cross entropy, differentiated through exact relevant-CSS contraction; physical CSS feedback prior held fixed", + "steps": 512, + "batch": 1024, + "learning_rate": 0.001, + "sampling_seed": 20261274, + "optimizer": "AdamW, weight decay 1e-4, global gradient norm clip 1", + "optimizer_restored": false, + "rng_restored": false, + "explicit_optimizer_reset": false, + "explicit_rng_reset": false, + "sampling_state_source": "Fresh NumPy default_rng seed 20261274", + "starting_checkpoint": null, + "starting_checkpoint_sha256": null, + "starting_training_provenance": null, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.2600052058696747, + "objective": 0.2600052058696747, + "error": 0.1123046875, + "gradient_norm": 0.06799795478582382, + "elapsed": 27.333195447921753 + }, + { + "step": 16, + "loss": 0.0312246885150671, + "objective": 0.0312246885150671, + "error": 0.01171875, + "gradient_norm": 0.004962741397321224, + "elapsed": 48.383540868759155 + }, + { + "step": 32, + "loss": 0.22698244452476501, + "objective": 0.22698244452476501, + "error": 0.08984375, + "gradient_norm": 0.06353150308132172, + "elapsed": 57.04609966278076 + }, + { + "step": 48, + "loss": 0.5861443281173706, + "objective": 0.5861443281173706, + "error": 0.3486328125, + "gradient_norm": 0.04095375910401344, + "elapsed": 69.08654689788818 + }, + { + "step": 64, + "loss": 0.6103856563568115, + "objective": 0.6103856563568115, + "error": 0.3662109375, + "gradient_norm": 0.04155975207686424, + "elapsed": 81.63970494270325 + }, + { + "step": 80, + "loss": 0.5673234462738037, + "objective": 0.5673234462738037, + "error": 0.3125, + "gradient_norm": 0.1773851364850998, + "elapsed": 92.5357596874237 + }, + { + "step": 96, + "loss": 0.3763846755027771, + "objective": 0.3763846755027771, + "error": 0.1875, + "gradient_norm": 0.0951203852891922, + "elapsed": 103.12279391288757 + }, + { + "step": 112, + "loss": 0.45539408922195435, + "objective": 0.45539408922195435, + "error": 0.22265625, + "gradient_norm": 0.056369006633758545, + "elapsed": 112.61882042884827 + }, + { + "step": 128, + "loss": 0.015473627485334873, + "objective": 0.015473627485334873, + "error": 0.005859375, + "gradient_norm": 0.005696057807654142, + "elapsed": 125.16960310935974 + }, + { + "step": 144, + "loss": 0.03449750319123268, + "objective": 0.03449750319123268, + "error": 0.0107421875, + "gradient_norm": 0.008358650840818882, + "elapsed": 135.8080232143402 + }, + { + "step": 160, + "loss": 0.5731935501098633, + "objective": 0.5731935501098633, + "error": 0.31640625, + "gradient_norm": 0.056162577122449875, + "elapsed": 145.0349259376526 + }, + { + "step": 176, + "loss": 0.5626271963119507, + "objective": 0.5626271963119507, + "error": 0.314453125, + "gradient_norm": 0.048817526549100876, + "elapsed": 154.84093379974365 + }, + { + "step": 192, + "loss": 0.5507581233978271, + "objective": 0.5507581233978271, + "error": 0.3173828125, + "gradient_norm": 0.06503377854824066, + "elapsed": 164.7195086479187 + }, + { + "step": 208, + "loss": 0.5725968480110168, + "objective": 0.5725968480110168, + "error": 0.3251953125, + "gradient_norm": 0.047704510390758514, + "elapsed": 175.38803815841675 + }, + { + "step": 224, + "loss": 0.5249365568161011, + "objective": 0.5249365568161011, + "error": 0.2802734375, + "gradient_norm": 0.10021239519119263, + "elapsed": 187.0162854194641 + }, + { + "step": 240, + "loss": 0.2526492476463318, + "objective": 0.2526492476463318, + "error": 0.1103515625, + "gradient_norm": 0.06751289963722229, + "elapsed": 196.51696944236755 + }, + { + "step": 256, + "loss": 0.5214780569076538, + "objective": 0.5214780569076538, + "error": 0.275390625, + "gradient_norm": 0.14627203345298767, + "elapsed": 208.2405219078064 + }, + { + "step": 272, + "loss": 0.59315025806427, + "objective": 0.59315025806427, + "error": 0.341796875, + "gradient_norm": 0.03693874180316925, + "elapsed": 224.87874341011047 + }, + { + "step": 288, + "loss": 0.37350377440452576, + "objective": 0.37350377440452576, + "error": 0.169921875, + "gradient_norm": 0.05035478249192238, + "elapsed": 235.2427306175232 + }, + { + "step": 304, + "loss": 0.6201726198196411, + "objective": 0.6201726198196411, + "error": 0.3798828125, + "gradient_norm": 0.04230104014277458, + "elapsed": 244.4733214378357 + }, + { + "step": 320, + "loss": 0.5781067609786987, + "objective": 0.5781067609786987, + "error": 0.3291015625, + "gradient_norm": 0.06764703243970871, + "elapsed": 256.96991300582886 + }, + { + "step": 336, + "loss": 0.13824111223220825, + "objective": 0.13824111223220825, + "error": 0.0556640625, + "gradient_norm": 0.02330971322953701, + "elapsed": 268.097412109375 + }, + { + "step": 352, + "loss": 0.6141752004623413, + "objective": 0.6141752004623413, + "error": 0.37890625, + "gradient_norm": 0.08660273998975754, + "elapsed": 282.79302310943604 + }, + { + "step": 368, + "loss": 0.3470626473426819, + "objective": 0.3470626473426819, + "error": 0.1611328125, + "gradient_norm": 0.05711895599961281, + "elapsed": 293.79467129707336 + }, + { + "step": 384, + "loss": 0.6023644208908081, + "objective": 0.6023644208908081, + "error": 0.3466796875, + "gradient_norm": 0.08649417012929916, + "elapsed": 305.9786322116852 + }, + { + "step": 400, + "loss": 0.03022841364145279, + "objective": 0.03022841364145279, + "error": 0.0087890625, + "gradient_norm": 0.009741511195898056, + "elapsed": 315.06104922294617 + }, + { + "step": 416, + "loss": 0.23827238380908966, + "objective": 0.23827238380908966, + "error": 0.1015625, + "gradient_norm": 0.03526044636964798, + "elapsed": 325.6410942077637 + }, + { + "step": 432, + "loss": 0.43375664949417114, + "objective": 0.43375664949417114, + "error": 0.201171875, + "gradient_norm": 0.03940205276012421, + "elapsed": 336.9890570640564 + }, + { + "step": 448, + "loss": 0.5915575623512268, + "objective": 0.5915575623512268, + "error": 0.3359375, + "gradient_norm": 0.04364592209458351, + "elapsed": 346.9254243373871 + }, + { + "step": 464, + "loss": 0.5641118288040161, + "objective": 0.5641118288040161, + "error": 0.3076171875, + "gradient_norm": 0.052896615117788315, + "elapsed": 356.9816539287567 + }, + { + "step": 480, + "loss": 0.5682889223098755, + "objective": 0.5682889223098755, + "error": 0.322265625, + "gradient_norm": 0.07130409777164459, + "elapsed": 369.16103172302246 + }, + { + "step": 496, + "loss": 0.37034764885902405, + "objective": 0.37034764885902405, + "error": 0.181640625, + "gradient_norm": 0.11464523524045944, + "elapsed": 381.041054725647 + }, + { + "step": 512, + "loss": 0.5398496389389038, + "objective": 0.5398496389389038, + "error": 0.3076171875, + "gradient_norm": 0.05673467367887497, + "elapsed": 394.5030150413513 + } + ], + "reserved_sampling_audit": { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved2_warm", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "db182d721768f832e1c83f6258b31bef0d8bf2ded239a8ab5a45cbb76378fd30", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 256, + 512 + ], + "training_draws": 524288, + "distinct_phase_training_rows": 317635, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 13700, + "surface_code_bX_d5_r03_center_5_5": 10036, + "surface_code_bX_d5_r05_center_5_5": 11768, + "surface_code_bX_d5_r07_center_5_5": 10917, + "surface_code_bX_d5_r09_center_5_5": 13458, + "surface_code_bX_d5_r11_center_5_5": 11764, + "surface_code_bX_d5_r13_center_5_5": 14018, + "surface_code_bX_d5_r15_center_5_5": 10968, + "surface_code_bX_d5_r17_center_5_5": 13469, + "surface_code_bX_d5_r19_center_5_5": 11340, + "surface_code_bX_d5_r21_center_5_5": 11327, + "surface_code_bX_d5_r23_center_5_5": 13970, + "surface_code_bX_d5_r25_center_5_5": 10500, + "surface_code_bZ_d5_r01_center_5_5": 12079, + "surface_code_bZ_d5_r03_center_5_5": 12160, + "surface_code_bZ_d5_r05_center_5_5": 9494, + "surface_code_bZ_d5_r07_center_5_5": 10910, + "surface_code_bZ_d5_r09_center_5_5": 10064, + "surface_code_bZ_d5_r11_center_5_5": 10969, + "surface_code_bZ_d5_r13_center_5_5": 13419, + "surface_code_bZ_d5_r15_center_5_5": 12842, + "surface_code_bZ_d5_r17_center_5_5": 13694, + "surface_code_bZ_d5_r19_center_5_5": 13449, + "surface_code_bZ_d5_r21_center_5_5": 13799, + "surface_code_bZ_d5_r23_center_5_5": 12754, + "surface_code_bZ_d5_r25_center_5_5": 14767 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 512, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + "declared_study_plan": { + "hypothesis": "Fresh independent experts with an excluded training partition permit an honest combiner fit and an independent training-period diagnostic", + "experts": [ + { + "name": "reserved1", + "initial_seed": 20261271, + "sampling_seed": 20261272 + }, + { + "name": "reserved2", + "initial_seed": 20261273, + "sampling_seed": 20261274 + } + ], + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "partition": "Per26 d5 conditions:18856 fit,512 combiner,512 diagnostic rows; uniformly random partition seed20261270; sample IDs only check alignment", + "architecture": "Unchanged394-input64-unit neural correction, bound2, fixed physical pass3 priors, exact relevant-CSS contraction", + "training": "Each new expert:512 updates B1024 LR.001 from random initialization;1536 updates LR.0005 restoring own Adam/RNG state. Uniform eligible condition and row sampling, BCE, clip1,AdamW decay1e-4", + "validation_selection": "All26conditions/13durations: main-phase0/512/1024/1536, raw and equal-physical options versus incumbent, then fixed original/new ensembles with physical fractions0/.25/.5. Full replay/contract verification required before publication", + "combiner_expert_selection": "For each new expert and basis, minimum raw full-validation mean failure across0/512/1024/1536; earlier listed checkpoint wins ties. Freeze before using reserved labels", + "combiner_plan": "Fit small regularized syndrome-dependent mixtures using only the512 gate rows/condition. Diagnostic512 rows/condition must not fit or select weights/checkpoints/hyperparameters", + "holdout_prediction_generation": "Both reserved parts predicted without accessing label NPZ members; diagnostics only after final combiner selection is frozen", + "test_data_used": false + }, + "pipeline_control": { + "status": "passed", + "backend": "CPU", + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "control_sha256": "0302573e82d5113dfe1f63080b21b6976cc05b2ddb3677a640b005fc6050aa66", + "audits": [ + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke1", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ad3b3170d682b103f82456476e4a4f7c3096707269b72c242ec43d820dc06856", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 2, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 0, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 1, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke2", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ea2e649b4880641cb0c7e7b7a349d4174ce4dd276c4cdbac376e9c087f00ea1f", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 0, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 2, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 1, + "last_optimizer_count": 2, + "parent_checkpoint_sha256": "faf01476f397259640c31a761f9774af9c0592e9118c38ffdce9502acdfcfb31", + "test_data_used": false + } + ], + "initialization_exact": true, + "parameters_updated": true, + "smoke_runs_excluded_from_selection_and_submission": true, + "test_data_used": false + } + }, + "validation": "Uniform subset per all 26 conditions, sample seed 20261102; full validation required before publication", + "validation_shots_per_condition": 1024, + "test_data_used": false, + "records": [ + { + "step": 1, + "loss": 0.30839407444000244, + "objective": 0.30839407444000244, + "error": 0.130859375, + "gradient_norm": 0.053425733000040054, + "elapsed": 28.537403345108032 + }, + { + "step": 16, + "loss": 0.021987520158290863, + "objective": 0.021987520158290863, + "error": 0.0078125, + "gradient_norm": 0.01397851575165987, + "elapsed": 48.18276286125183 + }, + { + "step": 32, + "loss": 0.5041587352752686, + "objective": 0.5041587352752686, + "error": 0.2724609375, + "gradient_norm": 0.0528741292655468, + "elapsed": 58.27348470687866 + }, + { + "step": 48, + "loss": 0.4326452612876892, + "objective": 0.4326452612876892, + "error": 0.21484375, + "gradient_norm": 0.0559566393494606, + "elapsed": 68.90473222732544 + }, + { + "step": 64, + "loss": 0.4804917275905609, + "objective": 0.4804917275905609, + "error": 0.248046875, + "gradient_norm": 0.0669105276465416, + "elapsed": 77.87249231338501 + }, + { + "step": 80, + "loss": 0.2889654338359833, + "objective": 0.2889654338359833, + "error": 0.1328125, + "gradient_norm": 0.08293467015028, + "elapsed": 86.87973022460938 + }, + { + "step": 96, + "loss": 0.5135385990142822, + "objective": 0.5135385990142822, + "error": 0.271484375, + "gradient_norm": 0.06412295252084732, + "elapsed": 95.98773431777954 + }, + { + "step": 112, + "loss": 0.31248384714126587, + "objective": 0.31248384714126587, + "error": 0.1357421875, + "gradient_norm": 0.03881710395216942, + "elapsed": 106.47444081306458 + }, + { + "step": 128, + "loss": 0.23868557810783386, + "objective": 0.23868557810783386, + "error": 0.091796875, + "gradient_norm": 0.03896595537662506, + "elapsed": 117.72143626213074 + }, + { + "step": 144, + "loss": 0.5315916538238525, + "objective": 0.5315916538238525, + "error": 0.2890625, + "gradient_norm": 0.09184520691633224, + "elapsed": 126.97882843017578 + }, + { + "step": 160, + "loss": 0.604732096195221, + "objective": 0.604732096195221, + "error": 0.3603515625, + "gradient_norm": 0.044600710272789, + "elapsed": 137.403742313385 + }, + { + "step": 176, + "loss": 0.032417282462120056, + "objective": 0.032417282462120056, + "error": 0.0107421875, + "gradient_norm": 0.010968778282403946, + "elapsed": 147.58081603050232 + }, + { + "step": 192, + "loss": 0.24050910770893097, + "objective": 0.24050910770893097, + "error": 0.087890625, + "gradient_norm": 0.052534136921167374, + "elapsed": 156.545964717865 + }, + { + "step": 208, + "loss": 0.3183761537075043, + "objective": 0.3183761537075043, + "error": 0.1435546875, + "gradient_norm": 0.05253623053431511, + "elapsed": 166.62695455551147 + }, + { + "step": 224, + "loss": 0.6407097578048706, + "objective": 0.6407097578048706, + "error": 0.3837890625, + "gradient_norm": 0.08772490173578262, + "elapsed": 174.46970582008362 + }, + { + "step": 240, + "loss": 0.597212553024292, + "objective": 0.597212553024292, + "error": 0.36328125, + "gradient_norm": 0.13039150834083557, + "elapsed": 184.2768793106079 + }, + { + "step": 256, + "loss": 0.3317721486091614, + "objective": 0.3317721486091614, + "error": 0.14453125, + "gradient_norm": 0.03749232366681099, + "elapsed": 194.6345317363739 + }, + { + "step": 272, + "loss": 0.6330116987228394, + "objective": 0.6330116987228394, + "error": 0.3955078125, + "gradient_norm": 0.06468097865581512, + "elapsed": 205.8717017173767 + }, + { + "step": 288, + "loss": 0.3141757845878601, + "objective": 0.3141757845878601, + "error": 0.138671875, + "gradient_norm": 0.046496689319610596, + "elapsed": 215.2117359638214 + }, + { + "step": 304, + "loss": 0.5782994031906128, + "objective": 0.5782994031906128, + "error": 0.345703125, + "gradient_norm": 0.06487675756216049, + "elapsed": 225.47403240203857 + }, + { + "step": 320, + "loss": 0.45729100704193115, + "objective": 0.45729100704193115, + "error": 0.2255859375, + "gradient_norm": 0.04169687256217003, + "elapsed": 233.03686332702637 + }, + { + "step": 336, + "loss": 0.49350813031196594, + "objective": 0.49350813031196594, + "error": 0.24609375, + "gradient_norm": 0.08623651415109634, + "elapsed": 244.53246903419495 + }, + { + "step": 352, + "loss": 0.25660067796707153, + "objective": 0.25660067796707153, + "error": 0.1103515625, + "gradient_norm": 0.03029652312397957, + "elapsed": 254.88137793540955 + }, + { + "step": 368, + "loss": 0.2295728325843811, + "objective": 0.2295728325843811, + "error": 0.0966796875, + "gradient_norm": 0.042884912341833115, + "elapsed": 262.7415475845337 + }, + { + "step": 384, + "loss": 0.6214326620101929, + "objective": 0.6214326620101929, + "error": 0.3759765625, + "gradient_norm": 0.08176509290933609, + "elapsed": 271.72958397865295 + }, + { + "step": 400, + "loss": 0.6463049650192261, + "objective": 0.6463049650192261, + "error": 0.3984375, + "gradient_norm": 0.08226390928030014, + "elapsed": 281.51069259643555 + }, + { + "step": 416, + "loss": 0.024987798184156418, + "objective": 0.024987798184156418, + "error": 0.0078125, + "gradient_norm": 0.0075854891911149025, + "elapsed": 291.0118627548218 + }, + { + "step": 432, + "loss": 0.5520929098129272, + "objective": 0.5520929098129272, + "error": 0.3125, + "gradient_norm": 0.09755270183086395, + "elapsed": 301.23231768608093 + }, + { + "step": 448, + "loss": 0.6077401638031006, + "objective": 0.6077401638031006, + "error": 0.361328125, + "gradient_norm": 0.04908076301217079, + "elapsed": 312.93572759628296 + }, + { + "step": 464, + "loss": 0.016434211283922195, + "objective": 0.016434211283922195, + "error": 0.005859375, + "gradient_norm": 0.007213531993329525, + "elapsed": 323.8330478668213 + }, + { + "step": 480, + "loss": 0.1582300364971161, + "objective": 0.1582300364971161, + "error": 0.064453125, + "gradient_norm": 0.028335656970739365, + "elapsed": 334.6112554073334 + }, + { + "step": 496, + "loss": 0.5916742086410522, + "objective": 0.5916742086410522, + "error": 0.35546875, + "gradient_norm": 0.08213689178228378, + "elapsed": 345.8490369319916 + }, + { + "step": 512, + "loss": 0.11447565257549286, + "objective": 0.11447565257549286, + "error": 0.04296875, + "gradient_norm": 0.028994916006922722, + "elapsed": 358.71793270111084 + }, + { + "step": 528, + "loss": 0.3011414408683777, + "objective": 0.3011414408683777, + "error": 0.1435546875, + "gradient_norm": 0.04305516928434372, + "elapsed": 373.143226146698 + }, + { + "step": 544, + "loss": 0.3099900782108307, + "objective": 0.3099900782108307, + "error": 0.130859375, + "gradient_norm": 0.06152835488319397, + "elapsed": 380.42762184143066 + }, + { + "step": 560, + "loss": 0.42917633056640625, + "objective": 0.42917633056640625, + "error": 0.203125, + "gradient_norm": 0.051812849938869476, + "elapsed": 390.78397703170776 + }, + { + "step": 576, + "loss": 0.4895544648170471, + "objective": 0.4895544648170471, + "error": 0.2451171875, + "gradient_norm": 0.059052009135484695, + "elapsed": 400.29374146461487 + }, + { + "step": 592, + "loss": 0.5950886011123657, + "objective": 0.5950886011123657, + "error": 0.328125, + "gradient_norm": 0.1449151188135147, + "elapsed": 410.06920647621155 + }, + { + "step": 608, + "loss": 0.3282078504562378, + "objective": 0.3282078504562378, + "error": 0.1484375, + "gradient_norm": 0.06495015323162079, + "elapsed": 420.5240683555603 + }, + { + "step": 624, + "loss": 0.6034166812896729, + "objective": 0.6034166812896729, + "error": 0.3388671875, + "gradient_norm": 0.05658626928925514, + "elapsed": 430.7997169494629 + }, + { + "step": 640, + "loss": 0.590431809425354, + "objective": 0.590431809425354, + "error": 0.3447265625, + "gradient_norm": 0.046094730496406555, + "elapsed": 441.8197224140167 + }, + { + "step": 656, + "loss": 0.2260439246892929, + "objective": 0.2260439246892929, + "error": 0.1015625, + "gradient_norm": 0.06323576718568802, + "elapsed": 450.76086831092834 + }, + { + "step": 672, + "loss": 0.26158156991004944, + "objective": 0.26158156991004944, + "error": 0.1162109375, + "gradient_norm": 0.08324819058179855, + "elapsed": 459.1986529827118 + }, + { + "step": 688, + "loss": 0.4871026873588562, + "objective": 0.4871026873588562, + "error": 0.244140625, + "gradient_norm": 0.051720812916755676, + "elapsed": 470.4437210559845 + }, + { + "step": 704, + "loss": 0.5861694812774658, + "objective": 0.5861694812774658, + "error": 0.341796875, + "gradient_norm": 0.05766218528151512, + "elapsed": 483.85575103759766 + }, + { + "step": 720, + "loss": 0.4168863296508789, + "objective": 0.4168863296508789, + "error": 0.21484375, + "gradient_norm": 0.05056491494178772, + "elapsed": 494.63891077041626 + }, + { + "step": 736, + "loss": 0.42054638266563416, + "objective": 0.42054638266563416, + "error": 0.21875, + "gradient_norm": 0.07021808624267578, + "elapsed": 505.4899232387543 + }, + { + "step": 752, + "loss": 0.2022928148508072, + "objective": 0.2022928148508072, + "error": 0.0849609375, + "gradient_norm": 0.0765448734164238, + "elapsed": 516.2925503253937 + }, + { + "step": 768, + "loss": 0.026398655027151108, + "objective": 0.026398655027151108, + "error": 0.0068359375, + "gradient_norm": 0.00973521638661623, + "elapsed": 524.7940125465393 + }, + { + "step": 784, + "loss": 0.5843480825424194, + "objective": 0.5843480825424194, + "error": 0.345703125, + "gradient_norm": 0.04805552959442139, + "elapsed": 535.345025062561 + }, + { + "step": 800, + "loss": 0.3102012872695923, + "objective": 0.3102012872695923, + "error": 0.134765625, + "gradient_norm": 0.09761057049036026, + "elapsed": 544.4683487415314 + }, + { + "step": 816, + "loss": 0.5332639217376709, + "objective": 0.5332639217376709, + "error": 0.30078125, + "gradient_norm": 0.10398133844137192, + "elapsed": 554.8217175006866 + }, + { + "step": 832, + "loss": 0.4870310425758362, + "objective": 0.4870310425758362, + "error": 0.2685546875, + "gradient_norm": 0.05754273384809494, + "elapsed": 564.9130115509033 + }, + { + "step": 848, + "loss": 0.1336989849805832, + "objective": 0.1336989849805832, + "error": 0.0498046875, + "gradient_norm": 0.02862304449081421, + "elapsed": 573.6143791675568 + }, + { + "step": 864, + "loss": 0.5794297456741333, + "objective": 0.5794297456741333, + "error": 0.3427734375, + "gradient_norm": 0.05002075806260109, + "elapsed": 584.2565310001373 + }, + { + "step": 880, + "loss": 0.6150081753730774, + "objective": 0.6150081753730774, + "error": 0.341796875, + "gradient_norm": 0.0605069138109684, + "elapsed": 596.845867395401 + }, + { + "step": 896, + "loss": 0.3804032504558563, + "objective": 0.3804032504558563, + "error": 0.18359375, + "gradient_norm": 0.057405781000852585, + "elapsed": 606.0786938667297 + }, + { + "step": 912, + "loss": 0.5734928846359253, + "objective": 0.5734928846359253, + "error": 0.2958984375, + "gradient_norm": 0.06807747483253479, + "elapsed": 616.9755277633667 + }, + { + "step": 928, + "loss": 0.23615539073944092, + "objective": 0.23615539073944092, + "error": 0.107421875, + "gradient_norm": 0.04033413156867027, + "elapsed": 625.9104406833649 + }, + { + "step": 944, + "loss": 0.5668450593948364, + "objective": 0.5668450593948364, + "error": 0.3134765625, + "gradient_norm": 0.04825817048549652, + "elapsed": 635.4241654872894 + }, + { + "step": 960, + "loss": 0.1369795948266983, + "objective": 0.1369795948266983, + "error": 0.0537109375, + "gradient_norm": 0.029475854709744453, + "elapsed": 646.0763671398163 + }, + { + "step": 976, + "loss": 0.026218727231025696, + "objective": 0.026218727231025696, + "error": 0.009765625, + "gradient_norm": 0.0067830472253263, + "elapsed": 656.7150173187256 + }, + { + "step": 992, + "loss": 0.6016548871994019, + "objective": 0.6016548871994019, + "error": 0.3564453125, + "gradient_norm": 0.04935981705784798, + "elapsed": 668.9989516735077 + }, + { + "step": 1008, + "loss": 0.1370980143547058, + "objective": 0.1370980143547058, + "error": 0.0546875, + "gradient_norm": 0.04418199881911278, + "elapsed": 677.3821382522583 + }, + { + "step": 1024, + "loss": 0.4085504412651062, + "objective": 0.4085504412651062, + "error": 0.19921875, + "gradient_norm": 0.07943295687437057, + "elapsed": 688.8395888805389 + }, + { + "step": 1040, + "loss": 0.34129297733306885, + "objective": 0.34129297733306885, + "error": 0.15625, + "gradient_norm": 0.04551500454545021, + "elapsed": 703.4613966941833 + }, + { + "step": 1056, + "loss": 0.5297085046768188, + "objective": 0.5297085046768188, + "error": 0.2705078125, + "gradient_norm": 0.06177444010972977, + "elapsed": 714.0862259864807 + }, + { + "step": 1072, + "loss": 0.3833361268043518, + "objective": 0.3833361268043518, + "error": 0.185546875, + "gradient_norm": 0.053057629615068436, + "elapsed": 724.1480000019073 + }, + { + "step": 1088, + "loss": 0.6497273445129395, + "objective": 0.6497273445129395, + "error": 0.421875, + "gradient_norm": 0.10790837556123734, + "elapsed": 735.8740057945251 + }, + { + "step": 1104, + "loss": 0.5393906831741333, + "objective": 0.5393906831741333, + "error": 0.2998046875, + "gradient_norm": 0.06015805900096893, + "elapsed": 743.9961709976196 + }, + { + "step": 1120, + "loss": 0.38553956151008606, + "objective": 0.38553956151008606, + "error": 0.1875, + "gradient_norm": 0.05357081815600395, + "elapsed": 753.2208635807037 + }, + { + "step": 1136, + "loss": 0.5478834509849548, + "objective": 0.5478834509849548, + "error": 0.2900390625, + "gradient_norm": 0.05761478468775749, + "elapsed": 761.3359644412994 + }, + { + "step": 1152, + "loss": 0.5732287168502808, + "objective": 0.5732287168502808, + "error": 0.341796875, + "gradient_norm": 0.07881136238574982, + "elapsed": 771.133172750473 + }, + { + "step": 1168, + "loss": 0.5174047946929932, + "objective": 0.5174047946929932, + "error": 0.29296875, + "gradient_norm": 0.07794999331235886, + "elapsed": 783.7084786891937 + }, + { + "step": 1184, + "loss": 0.5022754669189453, + "objective": 0.5022754669189453, + "error": 0.265625, + "gradient_norm": 0.05175226181745529, + "elapsed": 793.499255657196 + }, + { + "step": 1200, + "loss": 0.5698775053024292, + "objective": 0.5698775053024292, + "error": 0.34375, + "gradient_norm": 0.06385946273803711, + "elapsed": 804.970814704895 + }, + { + "step": 1216, + "loss": 0.6203033924102783, + "objective": 0.6203033924102783, + "error": 0.37109375, + "gradient_norm": 0.07393646240234375, + "elapsed": 816.1773698329926 + }, + { + "step": 1232, + "loss": 0.6154648065567017, + "objective": 0.6154648065567017, + "error": 0.3857421875, + "gradient_norm": 0.04278155043721199, + "elapsed": 827.3619928359985 + }, + { + "step": 1248, + "loss": 0.5948328971862793, + "objective": 0.5948328971862793, + "error": 0.3291015625, + "gradient_norm": 0.062024734914302826, + "elapsed": 838.8370804786682 + }, + { + "step": 1264, + "loss": 0.5644958019256592, + "objective": 0.5644958019256592, + "error": 0.3212890625, + "gradient_norm": 0.12030917406082153, + "elapsed": 849.5000331401825 + }, + { + "step": 1280, + "loss": 0.028782427310943604, + "objective": 0.028782427310943604, + "error": 0.0087890625, + "gradient_norm": 0.009096251800656319, + "elapsed": 857.8837285041809 + }, + { + "step": 1296, + "loss": 0.5129679441452026, + "objective": 0.5129679441452026, + "error": 0.2626953125, + "gradient_norm": 0.12833116948604584, + "elapsed": 868.5195860862732 + }, + { + "step": 1312, + "loss": 0.4095553159713745, + "objective": 0.4095553159713745, + "error": 0.193359375, + "gradient_norm": 0.09977155178785324, + "elapsed": 877.4712297916412 + }, + { + "step": 1328, + "loss": 0.2850862741470337, + "objective": 0.2850862741470337, + "error": 0.1240234375, + "gradient_norm": 0.05365074798464775, + "elapsed": 887.5133347511292 + }, + { + "step": 1344, + "loss": 0.41809165477752686, + "objective": 0.41809165477752686, + "error": 0.19140625, + "gradient_norm": 0.10622142255306244, + "elapsed": 895.0828025341034 + }, + { + "step": 1360, + "loss": 0.3627069890499115, + "objective": 0.3627069890499115, + "error": 0.1650390625, + "gradient_norm": 0.049557290971279144, + "elapsed": 906.2595431804657 + }, + { + "step": 1376, + "loss": 0.023341629654169083, + "objective": 0.023341629654169083, + "error": 0.0068359375, + "gradient_norm": 0.008970360271632671, + "elapsed": 916.6110022068024 + }, + { + "step": 1392, + "loss": 0.519214391708374, + "objective": 0.519214391708374, + "error": 0.26953125, + "gradient_norm": 0.052287619560956955, + "elapsed": 926.660523891449 + }, + { + "step": 1408, + "loss": 0.6152850389480591, + "objective": 0.6152850389480591, + "error": 0.3662109375, + "gradient_norm": 0.049617987126111984, + "elapsed": 936.7533056735992 + }, + { + "step": 1424, + "loss": 0.020841240882873535, + "objective": 0.020841240882873535, + "error": 0.0068359375, + "gradient_norm": 0.008459246717393398, + "elapsed": 946.8231542110443 + }, + { + "step": 1440, + "loss": 0.5963407754898071, + "objective": 0.5963407754898071, + "error": 0.3525390625, + "gradient_norm": 0.08714025467634201, + "elapsed": 956.0344398021698 + }, + { + "step": 1456, + "loss": 0.44305220246315, + "objective": 0.44305220246315, + "error": 0.2099609375, + "gradient_norm": 0.061915796250104904, + "elapsed": 967.506050825119 + }, + { + "step": 1472, + "loss": 0.5292993783950806, + "objective": 0.5292993783950806, + "error": 0.2939453125, + "gradient_norm": 0.10089804977178574, + "elapsed": 977.855934381485 + }, + { + "step": 1488, + "loss": 0.6087026596069336, + "objective": 0.6087026596069336, + "error": 0.345703125, + "gradient_norm": 0.05276322737336159, + "elapsed": 986.2705359458923 + }, + { + "step": 1504, + "loss": 0.3670162558555603, + "objective": 0.3670162558555603, + "error": 0.1796875, + "gradient_norm": 0.0575372576713562, + "elapsed": 995.2220902442932 + }, + { + "step": 1520, + "loss": 0.33479321002960205, + "objective": 0.33479321002960205, + "error": 0.1435546875, + "gradient_norm": 0.056317709386348724, + "elapsed": 1005.2168045043945 + }, + { + "step": 1536, + "loss": 0.5869293212890625, + "objective": 0.5869293212890625, + "error": 0.337890625, + "gradient_norm": 0.07419256865978241, + "elapsed": 1016.8691458702087 + } + ], + "reserved_sampling_audit": { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved2_full", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "0f5926c94bb1aa83840c6d257757b80c081835affc2cb34bf9246ba18e00266a", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 512, + 1024, + 1536 + ], + "training_draws": 1572864, + "distinct_phase_training_rows": 467790, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 18254, + "surface_code_bX_d5_r03_center_5_5": 18525, + "surface_code_bX_d5_r05_center_5_5": 18175, + "surface_code_bX_d5_r07_center_5_5": 18005, + "surface_code_bX_d5_r09_center_5_5": 18067, + "surface_code_bX_d5_r11_center_5_5": 18445, + "surface_code_bX_d5_r13_center_5_5": 18673, + "surface_code_bX_d5_r15_center_5_5": 17345, + "surface_code_bX_d5_r17_center_5_5": 17898, + "surface_code_bX_d5_r19_center_5_5": 18359, + "surface_code_bX_d5_r21_center_5_5": 18036, + "surface_code_bX_d5_r23_center_5_5": 17255, + "surface_code_bX_d5_r25_center_5_5": 18057, + "surface_code_bZ_d5_r01_center_5_5": 17596, + "surface_code_bZ_d5_r03_center_5_5": 18333, + "surface_code_bZ_d5_r05_center_5_5": 18250, + "surface_code_bZ_d5_r07_center_5_5": 18210, + "surface_code_bZ_d5_r09_center_5_5": 17447, + "surface_code_bZ_d5_r11_center_5_5": 18120, + "surface_code_bZ_d5_r13_center_5_5": 18224, + "surface_code_bZ_d5_r15_center_5_5": 17857, + "surface_code_bZ_d5_r17_center_5_5": 18359, + "surface_code_bZ_d5_r19_center_5_5": 17398, + "surface_code_bZ_d5_r21_center_5_5": 18235, + "surface_code_bZ_d5_r23_center_5_5": 16653, + "surface_code_bZ_d5_r25_center_5_5": 18014 + }, + "initial_optimizer_count": 512, + "last_optimizer_count": 2048, + "parent_checkpoint_sha256": "2b00e3f258886b5c4ecf69f36fd5463a205eefc84bd10c550acc391e84515c24", + "test_data_used": false + }, + "declared_study_plan": { + "hypothesis": "Fresh independent experts with an excluded training partition permit an honest combiner fit and an independent training-period diagnostic", + "experts": [ + { + "name": "reserved1", + "initial_seed": 20261271, + "sampling_seed": 20261272 + }, + { + "name": "reserved2", + "initial_seed": 20261273, + "sampling_seed": 20261274 + } + ], + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "partition": "Per26 d5 conditions:18856 fit,512 combiner,512 diagnostic rows; uniformly random partition seed20261270; sample IDs only check alignment", + "architecture": "Unchanged394-input64-unit neural correction, bound2, fixed physical pass3 priors, exact relevant-CSS contraction", + "training": "Each new expert:512 updates B1024 LR.001 from random initialization;1536 updates LR.0005 restoring own Adam/RNG state. Uniform eligible condition and row sampling, BCE, clip1,AdamW decay1e-4", + "validation_selection": "All26conditions/13durations: main-phase0/512/1024/1536, raw and equal-physical options versus incumbent, then fixed original/new ensembles with physical fractions0/.25/.5. Full replay/contract verification required before publication", + "combiner_expert_selection": "For each new expert and basis, minimum raw full-validation mean failure across0/512/1024/1536; earlier listed checkpoint wins ties. Freeze before using reserved labels", + "combiner_plan": "Fit small regularized syndrome-dependent mixtures using only the512 gate rows/condition. Diagnostic512 rows/condition must not fit or select weights/checkpoints/hyperparameters", + "holdout_prediction_generation": "Both reserved parts predicted without accessing label NPZ members; diagnostics only after final combiner selection is frozen", + "test_data_used": false + }, + "pipeline_control": { + "status": "passed", + "backend": "CPU", + "training_source_sha256": { + "learned_d5__reserved_train.py": "f1789039eb1500b30f716864237b9c564887ccb615f117fb9fb1a0ff15f54ff0", + "learned_d5__reserved_split.py": "69f3d3741a9625b1d70490f45202f101b6cd61b6bf332977559ec14307597456", + "learned_d5__data.py": "9e3bcfe9d45f6af60b86a580cdc9374043758a1a6f10564aef9eb344f7a6b364", + "learned_d5__model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "learned_exact__gradient.py": "ecb6b45698480386fa124fe878db7dbfa246d1969fd720ec26daff9547da2001", + "learned_exact__checkpoint_gradient.py": "7ece6b3f45e009727fd104a3d39e2816a8c3437f737c3d98131d3a5d7d60e9b8", + "exact_d3__exact.py": "869dfacb295c419c156d1070fc2afdd6e20d02ac1840e45e72346b2b289f4825" + }, + "control_sha256": "0302573e82d5113dfe1f63080b21b6976cc05b2ddb3677a640b005fc6050aa66", + "audits": [ + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke1", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ad3b3170d682b103f82456476e4a4f7c3096707269b72c242ec43d820dc06856", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 2, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 0, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 0, + "last_optimizer_count": 1, + "parent_checkpoint_sha256": null, + "test_data_used": false + }, + { + "status": "passed", + "run": "/run-state/workspace/research/learned_d5/reserved_smoke2", + "partition_manifest_sha256": "241221ce16d1d4fc634bdfef691aa2a40d888f6cb75e981485c570905056257b", + "source_sha256": "0b474c57cd4d84ef86c631af7473eac8a956f03b7e4c9859efc1fbf2dbd0bca6", + "training_config_sha256": "ea2e649b4880641cb0c7e7b7a349d4174ce4dd276c4cdbac376e9c087f00ea1f", + "fit_pool": 490256, + "gate_rows_excluded": 13312, + "audit_rows_excluded": 13312, + "sampling_replayed_checkpoints": [ + 1 + ], + "training_draws": 2, + "distinct_phase_training_rows": 2, + "distinct_by_condition": { + "surface_code_bX_d5_r01_center_5_5": 0, + "surface_code_bX_d5_r03_center_5_5": 0, + "surface_code_bX_d5_r05_center_5_5": 0, + "surface_code_bX_d5_r07_center_5_5": 0, + "surface_code_bX_d5_r09_center_5_5": 0, + "surface_code_bX_d5_r11_center_5_5": 0, + "surface_code_bX_d5_r13_center_5_5": 0, + "surface_code_bX_d5_r15_center_5_5": 0, + "surface_code_bX_d5_r17_center_5_5": 0, + "surface_code_bX_d5_r19_center_5_5": 0, + "surface_code_bX_d5_r21_center_5_5": 0, + "surface_code_bX_d5_r23_center_5_5": 0, + "surface_code_bX_d5_r25_center_5_5": 0, + "surface_code_bZ_d5_r01_center_5_5": 0, + "surface_code_bZ_d5_r03_center_5_5": 0, + "surface_code_bZ_d5_r05_center_5_5": 0, + "surface_code_bZ_d5_r07_center_5_5": 0, + "surface_code_bZ_d5_r09_center_5_5": 0, + "surface_code_bZ_d5_r11_center_5_5": 0, + "surface_code_bZ_d5_r13_center_5_5": 0, + "surface_code_bZ_d5_r15_center_5_5": 0, + "surface_code_bZ_d5_r17_center_5_5": 0, + "surface_code_bZ_d5_r19_center_5_5": 0, + "surface_code_bZ_d5_r21_center_5_5": 2, + "surface_code_bZ_d5_r23_center_5_5": 0, + "surface_code_bZ_d5_r25_center_5_5": 0 + }, + "initial_optimizer_count": 1, + "last_optimizer_count": 2, + "parent_checkpoint_sha256": "faf01476f397259640c31a761f9774af9c0592e9118c38ffdce9502acdfcfb31", + "test_data_used": false + } + ], + "initialization_exact": true, + "parameters_updated": true, + "smoke_runs_excluded_from_selection_and_submission": true, + "test_data_used": false + } + }, + "training_source_snapshot": "training_sources/reserved2_full", + "selection": "Minimum full-validation condition-mean failure per basis group over incumbent, listed neural checkpoints and equal probability averages with the recorded physical decoder.", + "physical_prediction_reference": "/run-state/workspace/research/context_upgrades/turbo1/predictions", + "prior_pass": 3, + "history": [ + { + "group": "d5_bX_center_5_5", + "candidates": { + "incumbent": 0.23212139423076927, + "0": 0.23353365384615382, + "blend-0": 0.23306790865384613, + "512": 0.23380408653846152, + "blend-512": 0.23366887019230773, + "1024": 0.23197115384615388, + "blend-1024": 0.23299278846153842, + "1536": 0.23206129807692305, + "blend-1536": 0.2329326923076923 + }, + "selected": "1024" + }, + { + "group": "d5_bZ_center_5_5", + "candidates": { + "incumbent": 0.21953124999999998, + "0": 0.22103365384615387, + "blend-0": 0.2211388221153846, + "512": 0.22092848557692304, + "blend-512": 0.22094350961538464, + "1024": 0.2204326923076923, + "blend-1024": 0.22046274038461539, + "1536": 0.22086838942307688, + "blend-1536": 0.22059795673076926 + }, + "selected": "incumbent" + } + ], + "checkpoints": { + "1024": { + "step": 1024, + "training_samples": 1048576, + "unique_training_rows_seen_in_this_phase": 428858, + "weights_sha256": "a346f535004381e2e0b628fac8ff7c58282a2447b9704638e46232dff46e511f", + "complete": true + } + }, + "runtime": "Share physical priors when the conditioning pass and regime agree; otherwise recompute the neural prior independently. Last-only physical branches omit unused intermediate logical tracking; raw neural branches also omit the unused final physical readout.", + "last_only_equivalence_controls": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "maximum_probability_difference": 7.450580596923828e-07 + }, + { + "condition": "surface_code_bZ_d5_r03_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "maximum_probability_difference": 5.960464477539063e-08 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "maximum_probability_difference": 1.7881393432617188e-07 + } + ], + "test_data_used": false, + "numerical_controls": { + "packaged_runtime_control_cpu": { + "device": "cpu", + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 7, + "same_cpu_old_vs_new_maximum_difference": 0.0, + "old_cpu_vs_original_gpu_evaluation_maximum_difference": 4.971027374267578e-05, + "new_cpu_vs_original_gpu_evaluation_maximum_difference": 4.971027374267578e-05, + "cpu_vs_reconstructed_old_gpu_runtime_maximum_difference": 4.976987838745117e-05, + "original_gpu_evaluation_vs_reconstructed_gpu_runtime_maximum_difference": 7.748603820800781e-07, + "initial_failed_control": { + "comparison": "CPU runtime against original GPU evaluator", + "observed_maximum_difference": 4.971027374267578e-05, + "original_tolerance": 3e-06 + }, + "sources": { + "d5_base_context_model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "d5_context_model.py": "53342e15dcbb8bc2dd0b288d75ea115fb504be99a33bc283a518b9d76232cd99", + "d5_temporal_context_model.py": "d58bcfe01767228d18ce2078d555abf13037b5df63edf38273ba66f0966ee445", + "d5_history_context_model.py": "4cc383b4909ff740bccfd20b687f8ee46866e67f93f82fe6c4bace162149ffb4", + "d5_history_features.py": "d709cd54225aa1b14707afa436314c8392f59f748a0007d988c6d18dedd275ee", + "d5_contextual.py": "59d6c85dc4bd61e26cf7243baf0e2637c3de1d35327b2c763707badd19446550", + "turbo.py": "c07dce8d7098142f5cd550d594b948290287a8cb2221f70acaeff3965c3dac0b" + }, + "scope": "Same-device compatibility check. Reconstructed GPU runtime removes the recorded equal physical blend; that reconstruction has floating-point rounding uncertainty.", + "status": "passed_same_device_compatibility" + }, + "dispatcher_control_cpu": { + "status": "passed", + "device": "cpu", + "sources": { + "d5_context_model.py": "53342e15dcbb8bc2dd0b288d75ea115fb504be99a33bc283a518b9d76232cd99", + "d5_base_context_model.py": "3b2d4b34a8945ddfe82d76e28b4aa917f11933ed885c0cdcd2bc389448a871fb", + "d5_temporal_context_model.py": "d58bcfe01767228d18ce2078d555abf13037b5df63edf38273ba66f0966ee445", + "d5_history_context_model.py": "4cc383b4909ff740bccfd20b687f8ee46866e67f93f82fe6c4bace162149ffb4", + "d5_history_features.py": "d709cd54225aa1b14707afa436314c8392f59f748a0007d988c6d18dedd275ee" + }, + "cases": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "base64", + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "base128", + "weights_sha256": "2a21869e7669492fac8252131434b2e09c97f1def2714988382ab7f127371bd8", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "temporal", + "weights_sha256": "9446a1e6dc46e1bcae540531e4f124930bb151ebfa600746ca77bc8f5b2aaa7c", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "architecture": "history", + "weights_sha256": "c508d8968ffa143be4219a207fb54ece3e1bfe144b8a880e4ed4f3d13f092c1e", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "base64", + "weights_sha256": "fb250c19cf7bb00741b6d862b8f646a2c8ab88397bb03c7bafc9085f9347eca5", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "base128", + "weights_sha256": "2a21869e7669492fac8252131434b2e09c97f1def2714988382ab7f127371bd8", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "temporal", + "weights_sha256": "9446a1e6dc46e1bcae540531e4f124930bb151ebfa600746ca77bc8f5b2aaa7c", + "maximum_edge_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "architecture": "history", + "weights_sha256": "c508d8968ffa143be4219a207fb54ece3e1bfe144b8a880e4ed4f3d13f092c1e", + "maximum_edge_probability_difference": 0.0 + } + ], + "scope": "Routing and code-copy check against each direct model implementation, using training detector inputs without labels. Tiny trained temporal/history smoke weights test nonzero feature couplings; they are excluded from model selection and submission.", + "test_data_used": false + }, + "cpu_probability_precision": { + "condition": "surface_code_bX_d5_r03_center_5_5", + "validation_syndromes": 7, + "logical_labels_used": false, + "parameter_updates": 0, + "reference": "Float64 neural forward and exact contraction from the same stored weights and fixed float32 input logits, on CPU", + "cpu_float32_vs_float64_maximum_difference": 7.624897924163321e-08, + "cpu_float32_edges_float64_contraction_vs_float64_maximum_difference": 4.725248914372315e-08, + "gpu_float32_vs_float64_maximum_difference": 4.964999121059854e-05, + "cpu_vs_gpu_float32_maximum_difference": 4.971027374267578e-05, + "maximum_neural_edge_probability_difference": 2.6330936014895556e-08, + "float32_edge_values_above_one_minus_1e6": 0, + "scope": "Precision diagnostic only; the published model is unchanged. Same-device old/new packaged-code compatibility was independently exact." + }, + "priors_only_control_cpu": { + "status": "passed", + "device": "cpu", + "source_sha256": "c07dce8d7098142f5cd550d594b948290287a8cb2221f70acaeff3965c3dac0b", + "records": [ + { + "condition": "surface_code_bX_d5_r03_center_5_5", + "shots": 3, + "priors_bitwise_identical": true, + "normal_seconds_including_compilation": 2.7116777896881104, + "priors_only_seconds_warm": 0.13569164276123047 + }, + { + "condition": "surface_code_bZ_d5_r25_center_5_5", + "shots": 3, + "priors_bitwise_identical": true, + "normal_seconds_including_compilation": 3.557781457901001, + "priors_only_seconds_warm": 1.7711329460144043 + } + ], + "scope": "CPU numerical equivalence on supplied training syndromes; timings are not a controlled speed comparison." + } + } + }, + "package_validation": { + "performance": 0.7672100360576923, + "failure_by_distance": { + "d3": 0.2398212139423077, + "d5": 0.2257587139423077 + }, + "scorer": "Supplied qecbench.scoring on all 130 validation conditions and 665600 shots", + "contract_checks": [ + { + "condition": "surface_code_bX_d3_r01_center_3_5", + "shots": 1, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d3_r25_center_5_3", + "shots": 37, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d3_r13_center_5_7", + "shots": 1025, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r01_center_5_5", + "shots": 7, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bZ_d5_r09_center_5_5", + "shots": 257, + "maximum_probability_difference": 0.0 + }, + { + "condition": "surface_code_bX_d5_r25_center_5_5", + "shots": 17, + "maximum_probability_difference": 0.0 + } + ], + "prediction_generation": "All26 d5 conditions replayed from the assembled package; unchanged d3 predictions retained. Trusted scoring covers all130 conditions.", + "runtime_evidence": "Full133120-shot d5 replay took 312.38s on one H100; compatible physical/neural priors are shared. D3 paths unchanged from the recorded incumbent.", + "d5_validation_runtime_seconds": 312.38163661956787, + "contract_execution": { + "requested_verifier_uid": 10001, + "effective_uid": 1000, + "effective_gid": 1000, + "supplementary_groups": [], + "identity_status": "Development process is already unprivileged and cannot change UID; verifier UID10001 was not executed", + "model_and_input_copy": "Owned by development UID 1000,directories0555,files0444,relocated under a fresh accessible temporary parent", + "output_directory": "Owned by execution UID 1000,mode0700", + "PYTHONPATH": "", + "backend": "Runtime default; full selected subset cases", + "scope": "Local contract check; not a Docker/network/mount-isolation test" + } + } +} diff --git a/shared/package-files/06/06e2ecaf4175380e08780f35e81cee2c5892346a693e800ba62795dbff0d7e0f/test_scalar.py b/shared/package-files/06/06e2ecaf4175380e08780f35e81cee2c5892346a693e800ba62795dbff0d7e0f/test_scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..29e3dc0aebe9551ae94566904372dde3563fbef9 --- /dev/null +++ b/shared/package-files/06/06e2ecaf4175380e08780f35e81cee2c5892346a693e800ba62795dbff0d7e0f/test_scalar.py @@ -0,0 +1,303 @@ +""" test scalar indexing, including at and iat """ +from datetime import ( + datetime, + timedelta, +) +import itertools + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Series, + Timedelta, + Timestamp, + date_range, +) +import pandas._testing as tm + + +def generate_indices(f, values=False): + """ + generate the indices + if values is True , use the axis values + is False, use the range + """ + axes = f.axes + if values: + axes = (list(range(len(ax))) for ax in axes) + + return itertools.product(*axes) + + +class TestScalar: + @pytest.mark.parametrize("kind", ["series", "frame"]) + @pytest.mark.parametrize("col", ["ints", "uints"]) + def test_iat_set_ints(self, kind, col, request): + f = request.getfixturevalue(f"{kind}_{col}") + indices = generate_indices(f, True) + for i in indices: + f.iat[i] = 1 + expected = f.values[i] + tm.assert_almost_equal(expected, 1) + + @pytest.mark.parametrize("kind", ["series", "frame"]) + @pytest.mark.parametrize("col", ["labels", "ts", "floats"]) + def test_iat_set_other(self, kind, col, request): + f = request.getfixturevalue(f"{kind}_{col}") + msg = "iAt based indexing can only have integer indexers" + with pytest.raises(ValueError, match=msg): + idx = next(generate_indices(f, False)) + f.iat[idx] = 1 + + @pytest.mark.parametrize("kind", ["series", "frame"]) + @pytest.mark.parametrize("col", ["ints", "uints", "labels", "ts", "floats"]) + def test_at_set_ints_other(self, kind, col, request): + f = request.getfixturevalue(f"{kind}_{col}") + indices = generate_indices(f, False) + for i in indices: + f.at[i] = 1 + expected = f.loc[i] + tm.assert_almost_equal(expected, 1) + + +class TestAtAndiAT: + # at and iat tests that don't need Base class + + def test_float_index_at_iat(self): + ser = Series([1, 2, 3], index=[0.1, 0.2, 0.3]) + for el, item in ser.items(): + assert ser.at[el] == item + for i in range(len(ser)): + assert ser.iat[i] == i + 1 + + def test_at_iat_coercion(self): + # as timestamp is not a tuple! + dates = date_range("1/1/2000", periods=8) + df = DataFrame( + np.random.default_rng(2).standard_normal((8, 4)), + index=dates, + columns=["A", "B", "C", "D"], + ) + s = df["A"] + + result = s.at[dates[5]] + xp = s.values[5] + assert result == xp + + @pytest.mark.parametrize( + "ser, expected", + [ + [ + Series(["2014-01-01", "2014-02-02"], dtype="datetime64[ns]"), + Timestamp("2014-02-02"), + ], + [ + Series(["1 days", "2 days"], dtype="timedelta64[ns]"), + Timedelta("2 days"), + ], + ], + ) + def test_iloc_iat_coercion_datelike(self, indexer_ial, ser, expected): + # GH 7729 + # make sure we are boxing the returns + result = indexer_ial(ser)[1] + assert result == expected + + def test_imethods_with_dups(self): + # GH6493 + # iat/iloc with dups + + s = Series(range(5), index=[1, 1, 2, 2, 3], dtype="int64") + result = s.iloc[2] + assert result == 2 + result = s.iat[2] + assert result == 2 + + msg = "index 10 is out of bounds for axis 0 with size 5" + with pytest.raises(IndexError, match=msg): + s.iat[10] + msg = "index -10 is out of bounds for axis 0 with size 5" + with pytest.raises(IndexError, match=msg): + s.iat[-10] + + result = s.iloc[[2, 3]] + expected = Series([2, 3], [2, 2], dtype="int64") + tm.assert_series_equal(result, expected) + + df = s.to_frame() + result = df.iloc[2] + expected = Series(2, index=[0], name=2) + tm.assert_series_equal(result, expected) + + result = df.iat[2, 0] + assert result == 2 + + def test_frame_at_with_duplicate_axes(self): + # GH#33041 + arr = np.random.default_rng(2).standard_normal(6).reshape(3, 2) + df = DataFrame(arr, columns=["A", "A"]) + + result = df.at[0, "A"] + expected = df.iloc[0].copy() + + tm.assert_series_equal(result, expected) + + result = df.T.at["A", 0] + tm.assert_series_equal(result, expected) + + # setter + df.at[1, "A"] = 2 + expected = Series([2.0, 2.0], index=["A", "A"], name=1) + tm.assert_series_equal(df.iloc[1], expected) + + def test_at_getitem_dt64tz_values(self): + # gh-15822 + df = DataFrame( + { + "name": ["John", "Anderson"], + "date": [ + Timestamp(2017, 3, 13, 13, 32, 56), + Timestamp(2017, 2, 16, 12, 10, 3), + ], + } + ) + df["date"] = df["date"].dt.tz_localize("Asia/Shanghai") + + expected = Timestamp("2017-03-13 13:32:56+0800", tz="Asia/Shanghai") + + result = df.loc[0, "date"] + assert result == expected + + result = df.at[0, "date"] + assert result == expected + + def test_mixed_index_at_iat_loc_iloc_series(self): + # GH 19860 + s = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2]) + for el, item in s.items(): + assert s.at[el] == s.loc[el] == item + for i in range(len(s)): + assert s.iat[i] == s.iloc[i] == i + 1 + + with pytest.raises(KeyError, match="^4$"): + s.at[4] + with pytest.raises(KeyError, match="^4$"): + s.loc[4] + + def test_mixed_index_at_iat_loc_iloc_dataframe(self): + # GH 19860 + df = DataFrame( + [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], columns=["a", "b", "c", 1, 2] + ) + for rowIdx, row in df.iterrows(): + for el, item in row.items(): + assert df.at[rowIdx, el] == df.loc[rowIdx, el] == item + + for row in range(2): + for i in range(5): + assert df.iat[row, i] == df.iloc[row, i] == row * 5 + i + + with pytest.raises(KeyError, match="^3$"): + df.at[0, 3] + with pytest.raises(KeyError, match="^3$"): + df.loc[0, 3] + + def test_iat_setter_incompatible_assignment(self): + # GH 23236 + result = DataFrame({"a": [0.0, 1.0], "b": [4, 5]}) + result.iat[0, 0] = None + expected = DataFrame({"a": [None, 1], "b": [4, 5]}) + tm.assert_frame_equal(result, expected) + + +def test_iat_dont_wrap_object_datetimelike(): + # GH#32809 .iat calls go through DataFrame._get_value, should not + # call maybe_box_datetimelike + dti = date_range("2016-01-01", periods=3) + tdi = dti - dti + ser = Series(dti.to_pydatetime(), dtype=object) + ser2 = Series(tdi.to_pytimedelta(), dtype=object) + df = DataFrame({"A": ser, "B": ser2}) + assert (df.dtypes == object).all() + + for result in [df.at[0, "A"], df.iat[0, 0], df.loc[0, "A"], df.iloc[0, 0]]: + assert result is ser[0] + assert isinstance(result, datetime) + assert not isinstance(result, Timestamp) + + for result in [df.at[1, "B"], df.iat[1, 1], df.loc[1, "B"], df.iloc[1, 1]]: + assert result is ser2[1] + assert isinstance(result, timedelta) + assert not isinstance(result, Timedelta) + + +def test_at_with_tuple_index_get(): + # GH 26989 + # DataFrame.at getter works with Index of tuples + df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)]) + assert df.index.nlevels == 1 + assert df.at[(1, 2), "a"] == 1 + + # Series.at getter works with Index of tuples + series = df["a"] + assert series.index.nlevels == 1 + assert series.at[(1, 2)] == 1 + + +@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") +def test_at_with_tuple_index_set(): + # GH 26989 + # DataFrame.at setter works with Index of tuples + df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)]) + assert df.index.nlevels == 1 + df.at[(1, 2), "a"] = 2 + assert df.at[(1, 2), "a"] == 2 + + # Series.at setter works with Index of tuples + series = df["a"] + assert series.index.nlevels == 1 + series.at[1, 2] = 3 + assert series.at[1, 2] == 3 + + +class TestMultiIndexScalar: + def test_multiindex_at_get(self): + # GH 26989 + # DataFrame.at and DataFrame.loc getter works with MultiIndex + df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]]) + assert df.index.nlevels == 2 + assert df.at[(1, 3), "a"] == 1 + assert df.loc[(1, 3), "a"] == 1 + + # Series.at and Series.loc getter works with MultiIndex + series = df["a"] + assert series.index.nlevels == 2 + assert series.at[1, 3] == 1 + assert series.loc[1, 3] == 1 + + @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") + def test_multiindex_at_set(self): + # GH 26989 + # DataFrame.at and DataFrame.loc setter works with MultiIndex + df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]]) + assert df.index.nlevels == 2 + df.at[(1, 3), "a"] = 3 + assert df.at[(1, 3), "a"] == 3 + df.loc[(1, 3), "a"] = 4 + assert df.loc[(1, 3), "a"] == 4 + + # Series.at and Series.loc setter works with MultiIndex + series = df["a"] + assert series.index.nlevels == 2 + series.at[1, 3] = 5 + assert series.at[1, 3] == 5 + series.loc[1, 3] = 6 + assert series.loc[1, 3] == 6 + + def test_multiindex_at_get_one_level(self): + # GH#38053 + s2 = Series((0, 1), index=[[False, True]]) + result = s2.at[False] + assert result == 0 diff --git a/shared/package-files/06/06e4113c5d11f4cadb2f31b2338e39475c67e2f79bdca96cd05181611f54afda/linalg_tensorinv_native.h b/shared/package-files/06/06e4113c5d11f4cadb2f31b2338e39475c67e2f79bdca96cd05181611f54afda/linalg_tensorinv_native.h new file mode 100644 index 0000000000000000000000000000000000000000..f9b90dd08988f112132f24d9723c62605e032662 --- /dev/null +++ b/shared/package-files/06/06e4113c5d11f4cadb2f31b2338e39475c67e2f79bdca96cd05181611f54afda/linalg_tensorinv_native.h @@ -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 linalg_tensorinv(const at::Tensor & self, int64_t ind=2); +TORCH_API at::Tensor & linalg_tensorinv_out(const at::Tensor & self, int64_t ind, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/ct82 b/shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/ct82 new file mode 100644 index 0000000000000000000000000000000000000000..3e68f869ea34a85fcf46e8b90d1a40c332889f3f Binary files /dev/null and b/shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/ct82 differ diff --git a/shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/swtp b/shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/swtp new file mode 100644 index 0000000000000000000000000000000000000000..3e68f869ea34a85fcf46e8b90d1a40c332889f3f Binary files /dev/null and b/shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/swtp differ diff --git a/shared/package-files/06/06e66db70bc400c63502c3f4101850917ac8015607eaa8373fc99997281bff9e/ne_cuda_dispatch.h b/shared/package-files/06/06e66db70bc400c63502c3f4101850917ac8015607eaa8373fc99997281bff9e/ne_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f4847a150f978cc90217b44533e962d4567a7aac --- /dev/null +++ b/shared/package-files/06/06e66db70bc400c63502c3f4101850917ac8015607eaa8373fc99997281bff9e/ne_cuda_dispatch.h @@ -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 at::Tensor ne(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & ne_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & ne_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & ne_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor ne(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & ne_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & ne_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & ne_(at::Tensor & self, const at::Tensor & other); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/06/06eb1ab5790017b7fd3eb3c6a87d7ac941a8ac223d5d8a42deb6d53a7d646de1/stride_native.h b/shared/package-files/06/06eb1ab5790017b7fd3eb3c6a87d7ac941a8ac223d5d8a42deb6d53a7d646de1/stride_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e55695a411cdbc6683a602b0717a5429a339123c --- /dev/null +++ b/shared/package-files/06/06eb1ab5790017b7fd3eb3c6a87d7ac941a8ac223d5d8a42deb6d53a7d646de1/stride_native.h @@ -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 int64_t stride(const at::Tensor & self, int64_t dim); +TORCH_API int64_t stride(const at::Tensor & self, at::Dimname dim); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06eb7dafd9b888bec41aafe168c5bc222438562bc7d13814a33c57e293ef7691/.f2py_f2cmap b/shared/package-files/06/06eb7dafd9b888bec41aafe168c5bc222438562bc7d13814a33c57e293ef7691/.f2py_f2cmap new file mode 100644 index 0000000000000000000000000000000000000000..2665f89b52d2f17ce7b0a857bea73ec5fab2df88 --- /dev/null +++ b/shared/package-files/06/06eb7dafd9b888bec41aafe168c5bc222438562bc7d13814a33c57e293ef7691/.f2py_f2cmap @@ -0,0 +1 @@ +dict(real=dict(rk="double")) diff --git a/shared/package-files/06/06ec96e9078fc6835997e0a0c69e562da87f7be9122b686c37c1ae77f8346a87/test_iteration.py b/shared/package-files/06/06ec96e9078fc6835997e0a0c69e562da87f7be9122b686c37c1ae77f8346a87/test_iteration.py new file mode 100644 index 0000000000000000000000000000000000000000..a1c23ff05f3e19aca490444216ec295453483e80 --- /dev/null +++ b/shared/package-files/06/06ec96e9078fc6835997e0a0c69e562da87f7be9122b686c37c1ae77f8346a87/test_iteration.py @@ -0,0 +1,160 @@ +import datetime + +import numpy as np +import pytest + +from pandas.compat import ( + IS64, + is_platform_windows, +) + +from pandas import ( + Categorical, + DataFrame, + Series, + date_range, +) +import pandas._testing as tm + + +class TestIteration: + def test_keys(self, float_frame): + assert float_frame.keys() is float_frame.columns + + def test_iteritems(self): + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) + for k, v in df.items(): + assert isinstance(v, DataFrame._constructor_sliced) + + def test_items(self): + # GH#17213, GH#13918 + cols = ["a", "b", "c"] + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=cols) + for c, (k, v) in zip(cols, df.items()): + assert c == k + assert isinstance(v, Series) + assert (df[k] == v).all() + + def test_items_names(self, float_string_frame): + for k, v in float_string_frame.items(): + assert v.name == k + + def test_iter(self, float_frame): + assert list(float_frame) == list(float_frame.columns) + + def test_iterrows(self, float_frame, float_string_frame): + for k, v in float_frame.iterrows(): + exp = float_frame.loc[k] + tm.assert_series_equal(v, exp) + + for k, v in float_string_frame.iterrows(): + exp = float_string_frame.loc[k] + tm.assert_series_equal(v, exp) + + def test_iterrows_iso8601(self): + # GH#19671 + s = DataFrame( + { + "non_iso8601": ["M1701", "M1802", "M1903", "M2004"], + "iso8601": date_range("2000-01-01", periods=4, freq="ME"), + } + ) + for k, v in s.iterrows(): + exp = s.loc[k] + tm.assert_series_equal(v, exp) + + def test_iterrows_corner(self): + # GH#12222 + df = DataFrame( + { + "a": [datetime.datetime(2015, 1, 1)], + "b": [None], + "c": [None], + "d": [""], + "e": [[]], + "f": [set()], + "g": [{}], + } + ) + expected = Series( + [datetime.datetime(2015, 1, 1), None, None, "", [], set(), {}], + index=list("abcdefg"), + name=0, + dtype="object", + ) + _, result = next(df.iterrows()) + tm.assert_series_equal(result, expected) + + def test_itertuples(self, float_frame): + for i, tup in enumerate(float_frame.itertuples()): + ser = DataFrame._constructor_sliced(tup[1:]) + ser.name = tup[0] + expected = float_frame.iloc[i, :].reset_index(drop=True) + tm.assert_series_equal(ser, expected) + + def test_itertuples_index_false(self): + df = DataFrame( + {"floats": np.random.default_rng(2).standard_normal(5), "ints": range(5)}, + columns=["floats", "ints"], + ) + + for tup in df.itertuples(index=False): + assert isinstance(tup[1], int) + + def test_itertuples_duplicate_cols(self): + df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) + dfaa = df[["a", "a"]] + + assert list(dfaa.itertuples()) == [(0, 1, 1), (1, 2, 2), (2, 3, 3)] + + # repr with int on 32-bit/windows + if not (is_platform_windows() or not IS64): + assert ( + repr(list(df.itertuples(name=None))) + == "[(0, 1, 4), (1, 2, 5), (2, 3, 6)]" + ) + + def test_itertuples_tuple_name(self): + df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) + tup = next(df.itertuples(name="TestName")) + assert tup._fields == ("Index", "a", "b") + assert (tup.Index, tup.a, tup.b) == tup + assert type(tup).__name__ == "TestName" + + def test_itertuples_disallowed_col_labels(self): + df = DataFrame(data={"def": [1, 2, 3], "return": [4, 5, 6]}) + tup2 = next(df.itertuples(name="TestName")) + assert tup2 == (0, 1, 4) + assert tup2._fields == ("Index", "_1", "_2") + + @pytest.mark.parametrize("limit", [254, 255, 1024]) + @pytest.mark.parametrize("index", [True, False]) + def test_itertuples_py2_3_field_limit_namedtuple(self, limit, index): + # GH#28282 + df = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(limit)}]) + result = next(df.itertuples(index=index)) + assert isinstance(result, tuple) + assert hasattr(result, "_fields") + + def test_sequence_like_with_categorical(self): + # GH#7839 + # make sure can iterate + df = DataFrame( + {"id": [1, 2, 3, 4, 5, 6], "raw_grade": ["a", "b", "b", "a", "a", "e"]} + ) + df["grade"] = Categorical(df["raw_grade"]) + + # basic sequencing testing + result = list(df.grade.values) + expected = np.array(df.grade.values).tolist() + tm.assert_almost_equal(result, expected) + + # iteration + for t in df.itertuples(index=False): + str(t) + + for row, s in df.iterrows(): + str(s) + + for c, col in df.items(): + str(col) diff --git a/shared/package-files/06/06ecf92c25953c6884a271c4f9c5c85df6e406135cd2ac55adac6435dc4aa7ca/_transforms_video.py b/shared/package-files/06/06ecf92c25953c6884a271c4f9c5c85df6e406135cd2ac55adac6435dc4aa7ca/_transforms_video.py new file mode 100644 index 0000000000000000000000000000000000000000..a04da4f74849805641e4c470f6b6b8d5f7000e3a --- /dev/null +++ b/shared/package-files/06/06ecf92c25953c6884a271c4f9c5c85df6e406135cd2ac55adac6435dc4aa7ca/_transforms_video.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 + +import numbers +import random +import warnings + +from torchvision.transforms import RandomCrop, RandomResizedCrop + +from . import _functional_video as F + + +__all__ = [ + "RandomCropVideo", + "RandomResizedCropVideo", + "CenterCropVideo", + "NormalizeVideo", + "ToTensorVideo", + "RandomHorizontalFlipVideo", +] + + +warnings.warn( + "The 'torchvision.transforms._transforms_video' module is deprecated since 0.12 and will be removed in the future. " + "Please use the 'torchvision.transforms' module instead." +) + + +class RandomCropVideo(RandomCrop): + def __init__(self, size): + if isinstance(size, numbers.Number): + self.size = (int(size), int(size)) + else: + self.size = size + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: randomly cropped/resized video clip. + size is (C, T, OH, OW) + """ + i, j, h, w = self.get_params(clip, self.size) + return F.crop(clip, i, j, h, w) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size})" + + +class RandomResizedCropVideo(RandomResizedCrop): + def __init__( + self, + size, + scale=(0.08, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), + interpolation_mode="bilinear", + ): + if isinstance(size, tuple): + if len(size) != 2: + raise ValueError(f"size should be tuple (height, width), instead got {size}") + self.size = size + else: + self.size = (size, size) + + self.interpolation_mode = interpolation_mode + self.scale = scale + self.ratio = ratio + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: randomly cropped/resized video clip. + size is (C, T, H, W) + """ + i, j, h, w = self.get_params(clip, self.scale, self.ratio) + return F.resized_crop(clip, i, j, h, w, self.size, self.interpolation_mode) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}, scale={self.scale}, ratio={self.ratio})" + + +class CenterCropVideo: + def __init__(self, crop_size): + if isinstance(crop_size, numbers.Number): + self.crop_size = (int(crop_size), int(crop_size)) + else: + self.crop_size = crop_size + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: central cropping of video clip. Size is + (C, T, crop_size, crop_size) + """ + return F.center_crop(clip, self.crop_size) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(crop_size={self.crop_size})" + + +class NormalizeVideo: + """ + Normalize the video clip by mean subtraction and division by standard deviation + Args: + mean (3-tuple): pixel RGB mean + std (3-tuple): pixel RGB standard deviation + inplace (boolean): whether do in-place normalization + """ + + def __init__(self, mean, std, inplace=False): + self.mean = mean + self.std = std + self.inplace = inplace + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): video clip to be normalized. Size is (C, T, H, W) + """ + return F.normalize(clip, self.mean, self.std, self.inplace) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})" + + +class ToTensorVideo: + """ + Convert tensor data type from uint8 to float, divide value by 255.0 and + permute the dimensions of clip tensor + """ + + def __init__(self): + pass + + def __call__(self, clip): + """ + Args: + clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C) + Return: + clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) + """ + return F.to_tensor(clip) + + def __repr__(self) -> str: + return self.__class__.__name__ + + +class RandomHorizontalFlipVideo: + """ + Flip the video clip along the horizontal direction with a given probability + Args: + p (float): probability of the clip being flipped. Default value is 0.5 + """ + + def __init__(self, p=0.5): + self.p = p + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Size is (C, T, H, W) + Return: + clip (torch.tensor): Size is (C, T, H, W) + """ + if random.random() < self.p: + clip = F.hflip(clip) + return clip + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" diff --git a/shared/package-files/06/06ed11b7397fa6e6832c433bb3be627fceac193837153ac6c0ebba3abddec8da/direct_url.json b/shared/package-files/06/06ed11b7397fa6e6832c433bb3be627fceac193837153ac6c0ebba3abddec8da/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..935365821c027c35927e00d511be94393a741df2 --- /dev/null +++ b/shared/package-files/06/06ed11b7397fa6e6832c433bb3be627fceac193837153ac6c0ebba3abddec8da/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/builder/ci_310/chardet_1640804867535/work"} \ No newline at end of file diff --git a/shared/package-files/06/06f59c12f8dab0108c06df6a5485ba40dbc7c540ed41ad1fb3b0fcfb9d4b6df7/dataframe.py b/shared/package-files/06/06f59c12f8dab0108c06df6a5485ba40dbc7c540ed41ad1fb3b0fcfb9d4b6df7/dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..612b574304fc102a1991274981772f91b65da93b --- /dev/null +++ b/shared/package-files/06/06f59c12f8dab0108c06df6a5485ba40dbc7c540ed41ad1fb3b0fcfb9d4b6df7/dataframe.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import enum +from typing import TYPE_CHECKING, Any, NoReturn + +from narwhals._utils import Version, _hasattr_static, parse_version + +if TYPE_CHECKING: + import pandas as pd + import pyarrow as pa + from typing_extensions import Self, TypeIs + + from narwhals._interchange.series import InterchangeSeries + from narwhals.dtypes import DType + from narwhals.stable.v1.typing import DataFrameLike + + +class DtypeKind(enum.IntEnum): + # https://data-apis.org/dataframe-protocol/latest/API.html + INT = 0 + UINT = 1 + FLOAT = 2 + BOOL = 20 + STRING = 21 # UTF-8 + DATETIME = 22 + CATEGORICAL = 23 + + +def map_interchange_dtype_to_narwhals_dtype( # noqa: C901, PLR0911, PLR0912 + interchange_dtype: tuple[DtypeKind, int, Any, Any], +) -> DType: + dtypes = Version.V1.dtypes + if interchange_dtype[0] == DtypeKind.INT: + if interchange_dtype[1] == 64: + return dtypes.Int64() + if interchange_dtype[1] == 32: + return dtypes.Int32() + if interchange_dtype[1] == 16: + return dtypes.Int16() + if interchange_dtype[1] == 8: + return dtypes.Int8() + msg = "Invalid bit width for INT" # pragma: no cover + raise AssertionError(msg) + if interchange_dtype[0] == DtypeKind.UINT: + if interchange_dtype[1] == 64: + return dtypes.UInt64() + if interchange_dtype[1] == 32: + return dtypes.UInt32() + if interchange_dtype[1] == 16: + return dtypes.UInt16() + if interchange_dtype[1] == 8: + return dtypes.UInt8() + msg = "Invalid bit width for UINT" # pragma: no cover + raise AssertionError(msg) + if interchange_dtype[0] == DtypeKind.FLOAT: + if interchange_dtype[1] == 64: + return dtypes.Float64() + if interchange_dtype[1] == 32: + return dtypes.Float32() + if interchange_dtype[1] == 16: + return dtypes.Float16() + msg = "Invalid bit width for FLOAT" # pragma: no cover + raise AssertionError(msg) + if interchange_dtype[0] == DtypeKind.BOOL: + return dtypes.Boolean() + if interchange_dtype[0] == DtypeKind.STRING: + return dtypes.String() + if interchange_dtype[0] == DtypeKind.DATETIME: + return dtypes.Datetime() + if interchange_dtype[0] == DtypeKind.CATEGORICAL: # pragma: no cover + # upstream issue: https://github.com/ibis-project/ibis/issues/9570 + return dtypes.Categorical() + msg = f"Invalid dtype, got: {interchange_dtype}" # pragma: no cover + raise AssertionError(msg) + + +class InterchangeFrame: + _version = Version.V1 + + def __init__(self, df: DataFrameLike) -> None: + self._interchange_frame = df.__dataframe__() + + def __narwhals_dataframe__(self) -> Self: + return self + + def __native_namespace__(self) -> NoReturn: + msg = ( + "Cannot access native namespace for interchange-level dataframes with unknown backend." + "If you would like to see this kind of object supported in Narwhals, please " + "open a feature request at https://github.com/narwhals-dev/narwhals/issues." + ) + raise NotImplementedError(msg) + + def get_column(self, name: str) -> InterchangeSeries: + from narwhals._interchange.series import InterchangeSeries + + return InterchangeSeries(self._interchange_frame.get_column_by_name(name)) + + def to_pandas(self) -> pd.DataFrame: + import pandas as pd # ignore-banned-import() + + if parse_version(pd) < (1, 5, 0): # pragma: no cover + msg = ( + "Conversion to pandas is achieved via interchange protocol which requires" + f" 'pandas>=1.5.0' to be installed, found {pd.__version__}" + ) + raise NotImplementedError(msg) + return pd.api.interchange.from_dataframe(self._interchange_frame) + + def to_arrow(self) -> pa.Table: + from pyarrow.interchange.from_dataframe import ( # ignore-banned-import() + from_dataframe, + ) + + return from_dataframe(self._interchange_frame) + + @property + def schema(self) -> dict[str, DType]: + return { + column_name: map_interchange_dtype_to_narwhals_dtype( + self._interchange_frame.get_column_by_name(column_name).dtype + ) + for column_name in self._interchange_frame.column_names() + } + + @property + def columns(self) -> list[str]: + return list(self._interchange_frame.column_names()) + + def __getattr__(self, attr: str) -> NoReturn: + msg = ( + f"Attribute {attr} is not supported for interchange-level dataframes.\n\n" + "Hint: you probably called `nw.from_native` on an object which isn't fully " + "supported by Narwhals, yet implements `__dataframe__`. If you would like to " + "see this kind of object supported in Narwhals, please open a feature request " + "at https://github.com/narwhals-dev/narwhals/issues." + ) + raise NotImplementedError(msg) + + def simple_select(self, *column_names: str) -> Self: + frame = self._interchange_frame.select_columns_by_name(list(column_names)) + if not hasattr(frame, "_df"): # pragma: no cover + msg = ( + "Expected interchange object to implement `_df` property to allow for recovering original object.\n" + "See https://github.com/data-apis/dataframe-api/issues/360." + ) + raise NotImplementedError(msg) + return self.__class__(frame._df) + + def select(self, *exprs: str) -> Self: # pragma: no cover + msg = ( + "`select`-ing not by name is not supported for interchange-only level.\n\n" + "If you would like to see this kind of object better supported in " + "Narwhals, please open a feature request " + "at https://github.com/narwhals-dev/narwhals/issues." + ) + raise NotImplementedError(msg) + + +def supports_dataframe_interchange(obj: Any) -> TypeIs[DataFrameLike]: + return _hasattr_static(obj, "__dataframe__") diff --git a/shared/package-files/06/06f7ccb74a31ab9d3c900d87c814b7ce81b8acbd938ad74fe9cc674075f07869/pipeline.py b/shared/package-files/06/06f7ccb74a31ab9d3c900d87c814b7ce81b8acbd938ad74fe9cc674075f07869/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..4b843563bdce395b49e9dbb9121ff6c50b9262a8 --- /dev/null +++ b/shared/package-files/06/06f7ccb74a31ab9d3c900d87c814b7ce81b8acbd938ad74fe9cc674075f07869/pipeline.py @@ -0,0 +1,2196 @@ +"""Utilities to build a composite estimator as a chain of transforms and estimators.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from collections import Counter, defaultdict +from contextlib import contextmanager +from copy import deepcopy +from itertools import chain, islice + +import numpy as np +from scipy import sparse + +from .base import TransformerMixin, _fit_context, clone +from .exceptions import NotFittedError +from .preprocessing import FunctionTransformer +from .utils import Bunch +from .utils._metadata_requests import METHODS +from .utils._param_validation import HasMethods, Hidden +from .utils._repr_html.estimator import _VisualBlock +from .utils._set_output import ( + _get_container_adapter, + _safe_set_output, +) +from .utils._tags import get_tags +from .utils._user_interface import _print_elapsed_time +from .utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + get_routing_for_object, + process_routing, +) +from .utils.metaestimators import _BaseComposition, available_if +from .utils.parallel import Parallel, delayed +from .utils.validation import check_is_fitted, check_memory + +__all__ = ["FeatureUnion", "Pipeline", "make_pipeline", "make_union"] + + +@contextmanager +def _raise_or_warn_if_not_fitted(estimator): + """A context manager to make sure a NotFittedError is raised, if a sub-estimator + raises the error. + + Otherwise, we raise a warning if the pipeline is not fitted, with the deprecation. + + TODO(1.8): remove this context manager and replace with check_is_fitted. + """ + try: + yield + except NotFittedError as exc: + raise NotFittedError("Pipeline is not fitted yet.") from exc + + # we only get here if the above didn't raise + try: + check_is_fitted(estimator) + except NotFittedError: + warnings.warn( + "This Pipeline instance is not fitted yet. Call 'fit' with " + "appropriate arguments before using other methods such as transform, " + "predict, etc. This will raise an error in 1.8 instead of the current " + "warning.", + FutureWarning, + ) + + +def _final_estimator_has(attr): + """Check that final_estimator has `attr`. + + Used together with `available_if` in `Pipeline`.""" + + def check(self): + # raise original `AttributeError` if `attr` does not exist + getattr(self._final_estimator, attr) + return True + + return check + + +def _cached_transform( + sub_pipeline, *, cache, param_name, param_value, transform_params +): + """Transform a parameter value using a sub-pipeline and cache the result. + + Parameters + ---------- + sub_pipeline : Pipeline + The sub-pipeline to be used for transformation. + cache : dict + The cache dictionary to store the transformed values. + param_name : str + The name of the parameter to be transformed. + param_value : object + The value of the parameter to be transformed. + transform_params : dict + The metadata to be used for transformation. This passed to the + `transform` method of the sub-pipeline. + + Returns + ------- + transformed_value : object + The transformed value of the parameter. + """ + if param_name not in cache: + # If the parameter is a tuple, transform each element of the + # tuple. This is needed to support the pattern present in + # `lightgbm` and `xgboost` where users can pass multiple + # validation sets. + if isinstance(param_value, tuple): + cache[param_name] = tuple( + sub_pipeline.transform(element, **transform_params) + for element in param_value + ) + else: + cache[param_name] = sub_pipeline.transform(param_value, **transform_params) + + return cache[param_name] + + +class Pipeline(_BaseComposition): + """ + A sequence of data transformers with an optional final predictor. + + `Pipeline` allows you to sequentially apply a list of transformers to + preprocess the data and, if desired, conclude the sequence with a final + :term:`predictor` for predictive modeling. + + Intermediate steps of the pipeline must be transformers, that is, they + must implement `fit` and `transform` methods. + The final :term:`estimator` only needs to implement `fit`. + The transformers in the pipeline can be cached using ``memory`` argument. + + The purpose of the pipeline is to assemble several steps that can be + cross-validated together while setting different parameters. For this, it + enables setting parameters of the various steps using their names and the + parameter name separated by a `'__'`, as in the example below. A step's + estimator may be replaced entirely by setting the parameter with its name + to another estimator, or a transformer removed by setting it to + `'passthrough'` or `None`. + + For an example use case of `Pipeline` combined with + :class:`~sklearn.model_selection.GridSearchCV`, refer to + :ref:`sphx_glr_auto_examples_compose_plot_compare_reduction.py`. The + example :ref:`sphx_glr_auto_examples_compose_plot_digits_pipe.py` shows how + to grid search on a pipeline using `'__'` as a separator in the parameter names. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.5 + + Parameters + ---------- + steps : list of tuples + List of (name of step, estimator) tuples that are to be chained in + sequential order. To be compatible with the scikit-learn API, all steps + must define `fit`. All non-last steps must also define `transform`. See + :ref:`Combining Estimators ` for more details. + + transform_input : list of str, default=None + The names of the :term:`metadata` parameters that should be transformed by the + pipeline before passing it to the step consuming it. + + This enables transforming some input arguments to ``fit`` (other than ``X``) + to be transformed by the steps of the pipeline up to the step which requires + them. Requirement is defined via :ref:`metadata routing `. + For instance, this can be used to pass a validation set through the pipeline. + + You can only set this if metadata routing is enabled, which you + can enable using ``sklearn.set_config(enable_metadata_routing=True)``. + + .. versionadded:: 1.6 + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the fitted transformers of the pipeline. The last step + will never be cached, even if it is a transformer. By default, no + caching is performed. If a string is given, it is the path to the + caching directory. Enabling caching triggers a clone of the transformers + before fitting. Therefore, the transformer instance given to the + pipeline cannot be inspected directly. Use the attribute ``named_steps`` + or ``steps`` to inspect estimators within the pipeline. Caching the + transformers is advantageous when fitting is time consuming. See + :ref:`sphx_glr_auto_examples_neighbors_plot_caching_nearest_neighbors.py` + for an example on how to enable caching. + + verbose : bool, default=False + If True, the time elapsed while fitting each step will be printed as it + is completed. + + Attributes + ---------- + named_steps : :class:`~sklearn.utils.Bunch` + Dictionary-like object, with the following attributes. + Read-only attribute to access any step parameter by user given name. + Keys are step names and values are steps parameters. + + classes_ : ndarray of shape (n_classes,) + The classes labels. Only exist if the last step of the pipeline is a + classifier. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying first estimator in `steps` exposes such an attribute + when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + .. versionadded:: 1.0 + + See Also + -------- + make_pipeline : Convenience function for simplified pipeline construction. + + Examples + -------- + >>> from sklearn.svm import SVC + >>> from sklearn.preprocessing import StandardScaler + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.pipeline import Pipeline + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, + ... random_state=0) + >>> pipe = Pipeline([('scaler', StandardScaler()), ('svc', SVC())]) + >>> # The pipeline can be used as any other estimator + >>> # and avoids leaking the test set into the train set + >>> pipe.fit(X_train, y_train).score(X_test, y_test) + 0.88 + >>> # An estimator's parameter can be set using '__' syntax + >>> pipe.set_params(svc__C=10).fit(X_train, y_train).score(X_test, y_test) + 0.76 + """ + + # BaseEstimator interface + _parameter_constraints: dict = { + "steps": [list, Hidden(tuple)], + "transform_input": [list, None], + "memory": [None, str, HasMethods(["cache"])], + "verbose": ["boolean"], + } + + def __init__(self, steps, *, transform_input=None, memory=None, verbose=False): + self.steps = steps + self.transform_input = transform_input + self.memory = memory + self.verbose = verbose + + def set_output(self, *, transform=None): + """Set the output container when `"transform"` and `"fit_transform"` are called. + + Calling `set_output` will set the output of all estimators in `steps`. + + Parameters + ---------- + transform : {"default", "pandas", "polars"}, default=None + Configure output of `transform` and `fit_transform`. + + - `"default"`: Default output format of a transformer + - `"pandas"`: DataFrame output + - `"polars"`: Polars output + - `None`: Transform configuration is unchanged + + .. versionadded:: 1.4 + `"polars"` option was added. + + Returns + ------- + self : estimator instance + Estimator instance. + """ + for _, _, step in self._iter(): + _safe_set_output(step, transform=transform) + return self + + def get_params(self, deep=True): + """Get parameters for this estimator. + + Returns the parameters given in the constructor as well as the + estimators contained within the `steps` of the `Pipeline`. + + Parameters + ---------- + deep : bool, default=True + If True, will return the parameters for this estimator and + contained subobjects that are estimators. + + Returns + ------- + params : mapping of string to any + Parameter names mapped to their values. + """ + return self._get_params("steps", deep=deep) + + def set_params(self, **kwargs): + """Set the parameters of this estimator. + + Valid parameter keys can be listed with ``get_params()``. Note that + you can directly set the parameters of the estimators contained in + `steps`. + + Parameters + ---------- + **kwargs : dict + Parameters of this estimator or parameters of estimators contained + in `steps`. Parameters of the steps may be set using its name and + the parameter name separated by a '__'. + + Returns + ------- + self : object + Pipeline class instance. + """ + self._set_params("steps", **kwargs) + return self + + def _validate_steps(self): + if not self.steps: + raise ValueError("The pipeline is empty. Please add steps.") + names, estimators = zip(*self.steps) + + # validate names + self._validate_names(names) + + # validate estimators + transformers = estimators[:-1] + estimator = estimators[-1] + + for t in transformers: + if t is None or t == "passthrough": + continue + if not (hasattr(t, "fit") or hasattr(t, "fit_transform")) or not hasattr( + t, "transform" + ): + raise TypeError( + "All intermediate steps should be " + "transformers and implement fit and transform " + "or be the string 'passthrough' " + "'%s' (type %s) doesn't" % (t, type(t)) + ) + + # We allow last estimator to be None as an identity transformation + if ( + estimator is not None + and estimator != "passthrough" + and not hasattr(estimator, "fit") + ): + raise TypeError( + "Last step of Pipeline should implement fit " + "or be the string 'passthrough'. " + "'%s' (type %s) doesn't" % (estimator, type(estimator)) + ) + + def _iter(self, with_final=True, filter_passthrough=True): + """ + Generate (idx, (name, trans)) tuples from self.steps + + When filter_passthrough is True, 'passthrough' and None transformers + are filtered out. + """ + stop = len(self.steps) + if not with_final: + stop -= 1 + + for idx, (name, trans) in enumerate(islice(self.steps, 0, stop)): + if not filter_passthrough: + yield idx, name, trans + elif trans is not None and trans != "passthrough": + yield idx, name, trans + + def __len__(self): + """ + Returns the length of the Pipeline + """ + return len(self.steps) + + def __getitem__(self, ind): + """Returns a sub-pipeline or a single estimator in the pipeline + + Indexing with an integer will return an estimator; using a slice + returns another Pipeline instance which copies a slice of this + Pipeline. This copy is shallow: modifying (or fitting) estimators in + the sub-pipeline will affect the larger pipeline and vice-versa. + However, replacing a value in `step` will not affect a copy. + + See + :ref:`sphx_glr_auto_examples_feature_selection_plot_feature_selection_pipeline.py` + for an example of how to use slicing to inspect part of a pipeline. + """ + if isinstance(ind, slice): + if ind.step not in (1, None): + raise ValueError("Pipeline slicing only supports a step of 1") + return self.__class__( + self.steps[ind], memory=self.memory, verbose=self.verbose + ) + try: + name, est = self.steps[ind] + except TypeError: + # Not an int, try get step by name + return self.named_steps[ind] + return est + + # TODO(1.8): Remove this property + @property + def _estimator_type(self): + """Return the estimator type of the last step in the pipeline.""" + + if not self.steps: + return None + + return self.steps[-1][1]._estimator_type + + @property + def named_steps(self): + """Access the steps by name. + + Read-only attribute to access any step by given name. + Keys are steps names and values are the steps objects.""" + # Use Bunch object to improve autocomplete + return Bunch(**dict(self.steps)) + + @property + def _final_estimator(self): + try: + estimator = self.steps[-1][1] + return "passthrough" if estimator is None else estimator + except (ValueError, AttributeError, TypeError): + # This condition happens when a call to a method is first calling + # `_available_if` and `fit` did not validate `steps` yet. We + # return `None` and an `InvalidParameterError` will be raised + # right after. + return None + + def _log_message(self, step_idx): + if not self.verbose: + return None + name, _ = self.steps[step_idx] + + return "(step %d of %d) Processing %s" % (step_idx + 1, len(self.steps), name) + + def _check_method_params(self, method, props, **kwargs): + if _routing_enabled(): + routed_params = process_routing(self, method, **props, **kwargs) + return routed_params + else: + fit_params_steps = Bunch( + **{ + name: Bunch(**{method: {} for method in METHODS}) + for name, step in self.steps + if step is not None + } + ) + for pname, pval in props.items(): + if "__" not in pname: + raise ValueError( + "Pipeline.fit does not accept the {} parameter. " + "You can pass parameters to specific steps of your " + "pipeline using the stepname__parameter format, e.g. " + "`Pipeline.fit(X, y, logisticregression__sample_weight" + "=sample_weight)`.".format(pname) + ) + step, param = pname.split("__", 1) + fit_params_steps[step]["fit"][param] = pval + # without metadata routing, fit_transform and fit_predict + # get all the same params and pass it to the last fit. + fit_params_steps[step]["fit_transform"][param] = pval + fit_params_steps[step]["fit_predict"][param] = pval + return fit_params_steps + + def _get_metadata_for_step(self, *, step_idx, step_params, all_params): + """Get params (metadata) for step `name`. + + This transforms the metadata up to this step if required, which is + indicated by the `transform_input` parameter. + + If a param in `step_params` is included in the `transform_input` list, + it will be transformed. + + Parameters + ---------- + step_idx : int + Index of the step in the pipeline. + + step_params : dict + Parameters specific to the step. These are routed parameters, e.g. + `routed_params[name]`. If a parameter name here is included in the + `pipeline.transform_input`, then it will be transformed. Note that + these parameters are *after* routing, so the aliases are already + resolved. + + all_params : dict + All parameters passed by the user. Here this is used to call + `transform` on the slice of the pipeline itself. + + Returns + ------- + dict + Parameters to be passed to the step. The ones which should be + transformed are transformed. + """ + if ( + self.transform_input is None + or not all_params + or not step_params + or step_idx == 0 + ): + # we only need to process step_params if transform_input is set + # and metadata is given by the user. + return step_params + + sub_pipeline = self[:step_idx] + sub_metadata_routing = get_routing_for_object(sub_pipeline) + # here we get the metadata required by sub_pipeline.transform + transform_params = { + key: value + for key, value in all_params.items() + if key + in sub_metadata_routing.consumes( + method="transform", params=all_params.keys() + ) + } + transformed_params = dict() # this is to be returned + transformed_cache = dict() # used to transform each param once + # `step_params` is the output of `process_routing`, so it has a dict for each + # method (e.g. fit, transform, predict), which are the args to be passed to + # those methods. We need to transform the parameters which are in the + # `transform_input`, before returning these dicts. + for method, method_params in step_params.items(): + transformed_params[method] = Bunch() + for param_name, param_value in method_params.items(): + # An example of `(param_name, param_value)` is + # `('sample_weight', array([0.5, 0.5, ...]))` + if param_name in self.transform_input: + # This parameter now needs to be transformed by the sub_pipeline, to + # this step. We cache these computations to avoid repeating them. + transformed_params[method][param_name] = _cached_transform( + sub_pipeline, + cache=transformed_cache, + param_name=param_name, + param_value=param_value, + transform_params=transform_params, + ) + else: + transformed_params[method][param_name] = param_value + return transformed_params + + # Estimator interface + + def _fit(self, X, y=None, routed_params=None, raw_params=None): + """Fit the pipeline except the last step. + + routed_params is the output of `process_routing` + raw_params is the parameters passed by the user, used when `transform_input` + is set by the user, to transform metadata using a sub-pipeline. + """ + # shallow copy of steps - this should really be steps_ + self.steps = list(self.steps) + self._validate_steps() + # Setup the memory + memory = check_memory(self.memory) + + fit_transform_one_cached = memory.cache(_fit_transform_one) + + for step_idx, name, transformer in self._iter( + with_final=False, filter_passthrough=False + ): + if transformer is None or transformer == "passthrough": + with _print_elapsed_time("Pipeline", self._log_message(step_idx)): + continue + + if hasattr(memory, "location") and memory.location is None: + # we do not clone when caching is disabled to + # preserve backward compatibility + cloned_transformer = transformer + else: + cloned_transformer = clone(transformer) + # Fit or load from cache the current transformer + step_params = self._get_metadata_for_step( + step_idx=step_idx, + step_params=routed_params[name], + all_params=raw_params, + ) + + X, fitted_transformer = fit_transform_one_cached( + cloned_transformer, + X, + y, + weight=None, + message_clsname="Pipeline", + message=self._log_message(step_idx), + params=step_params, + ) + # Replace the transformer of the step with the fitted + # transformer. This is necessary when loading the transformer + # from the cache. + self.steps[step_idx] = (name, fitted_transformer) + return X + + @_fit_context( + # estimators in Pipeline.steps are not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None, **params): + """Fit the model. + + Fit all the transformers one after the other and sequentially transform the + data. Finally, fit the transformed data using the final estimator. + + Parameters + ---------- + X : iterable + Training data. Must fulfill input requirements of first step of the + pipeline. + + y : iterable, default=None + Training targets. Must fulfill label requirements for all steps of + the pipeline. + + **params : dict of str -> object + - If `enable_metadata_routing=False` (default): Parameters passed to the + ``fit`` method of each step, where each parameter name is prefixed such + that parameter ``p`` for step ``s`` has key ``s__p``. + + - If `enable_metadata_routing=True`: Parameters requested and accepted by + steps. Each step must have requested certain metadata for these parameters + to be forwarded to them. + + .. versionchanged:: 1.4 + Parameters are now passed to the ``transform`` method of the + intermediate steps as well, if requested, and if + `enable_metadata_routing=True` is set via + :func:`~sklearn.set_config`. + + See :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + self : object + Pipeline with fitted steps. + """ + if not _routing_enabled() and self.transform_input is not None: + raise ValueError( + "The `transform_input` parameter can only be set if metadata " + "routing is enabled. You can enable metadata routing using " + "`sklearn.set_config(enable_metadata_routing=True)`." + ) + + routed_params = self._check_method_params(method="fit", props=params) + Xt = self._fit(X, y, routed_params, raw_params=params) + with _print_elapsed_time("Pipeline", self._log_message(len(self.steps) - 1)): + if self._final_estimator != "passthrough": + last_step_params = self._get_metadata_for_step( + step_idx=len(self) - 1, + step_params=routed_params[self.steps[-1][0]], + all_params=params, + ) + self._final_estimator.fit(Xt, y, **last_step_params["fit"]) + + return self + + def _can_fit_transform(self): + return ( + self._final_estimator == "passthrough" + or hasattr(self._final_estimator, "transform") + or hasattr(self._final_estimator, "fit_transform") + ) + + @available_if(_can_fit_transform) + @_fit_context( + # estimators in Pipeline.steps are not validated yet + prefer_skip_nested_validation=False + ) + def fit_transform(self, X, y=None, **params): + """Fit the model and transform with the final estimator. + + Fit all the transformers one after the other and sequentially transform + the data. Only valid if the final estimator either implements + `fit_transform` or `fit` and `transform`. + + Parameters + ---------- + X : iterable + Training data. Must fulfill input requirements of first step of the + pipeline. + + y : iterable, default=None + Training targets. Must fulfill label requirements for all steps of + the pipeline. + + **params : dict of str -> object + - If `enable_metadata_routing=False` (default): Parameters passed to the + ``fit`` method of each step, where each parameter name is prefixed such + that parameter ``p`` for step ``s`` has key ``s__p``. + + - If `enable_metadata_routing=True`: Parameters requested and accepted by + steps. Each step must have requested certain metadata for these parameters + to be forwarded to them. + + .. versionchanged:: 1.4 + Parameters are now passed to the ``transform`` method of the + intermediate steps as well, if requested, and if + `enable_metadata_routing=True`. + + See :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + Xt : ndarray of shape (n_samples, n_transformed_features) + Transformed samples. + """ + routed_params = self._check_method_params(method="fit_transform", props=params) + Xt = self._fit(X, y, routed_params) + + last_step = self._final_estimator + with _print_elapsed_time("Pipeline", self._log_message(len(self.steps) - 1)): + if last_step == "passthrough": + return Xt + last_step_params = self._get_metadata_for_step( + step_idx=len(self) - 1, + step_params=routed_params[self.steps[-1][0]], + all_params=params, + ) + if hasattr(last_step, "fit_transform"): + return last_step.fit_transform( + Xt, y, **last_step_params["fit_transform"] + ) + else: + return last_step.fit(Xt, y, **last_step_params["fit"]).transform( + Xt, **last_step_params["transform"] + ) + + @available_if(_final_estimator_has("predict")) + def predict(self, X, **params): + """Transform the data, and apply `predict` with the final estimator. + + Call `transform` of each transformer in the pipeline. The transformed + data are finally passed to the final estimator that calls `predict` + method. Only valid if the final estimator implements `predict`. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step + of the pipeline. + + **params : dict of str -> object + - If `enable_metadata_routing=False` (default): Parameters to the + ``predict`` called at the end of all transformations in the pipeline. + + - If `enable_metadata_routing=True`: Parameters requested and accepted by + steps. Each step must have requested certain metadata for these parameters + to be forwarded to them. + + .. versionadded:: 0.20 + + .. versionchanged:: 1.4 + Parameters are now passed to the ``transform`` method of the + intermediate steps as well, if requested, and if + `enable_metadata_routing=True` is set via + :func:`~sklearn.set_config`. + + See :ref:`Metadata Routing User Guide ` for more + details. + + Note that while this may be used to return uncertainties from some + models with ``return_std`` or ``return_cov``, uncertainties that are + generated by the transformations in the pipeline are not propagated + to the final estimator. + + Returns + ------- + y_pred : ndarray + Result of calling `predict` on the final estimator. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + Xt = X + + if not _routing_enabled(): + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt) + return self.steps[-1][1].predict(Xt, **params) + + # metadata routing enabled + routed_params = process_routing(self, "predict", **params) + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt, **routed_params[name].transform) + return self.steps[-1][1].predict( + Xt, **routed_params[self.steps[-1][0]].predict + ) + + @available_if(_final_estimator_has("fit_predict")) + @_fit_context( + # estimators in Pipeline.steps are not validated yet + prefer_skip_nested_validation=False + ) + def fit_predict(self, X, y=None, **params): + """Transform the data, and apply `fit_predict` with the final estimator. + + Call `fit_transform` of each transformer in the pipeline. The + transformed data are finally passed to the final estimator that calls + `fit_predict` method. Only valid if the final estimator implements + `fit_predict`. + + Parameters + ---------- + X : iterable + Training data. Must fulfill input requirements of first step of + the pipeline. + + y : iterable, default=None + Training targets. Must fulfill label requirements for all steps + of the pipeline. + + **params : dict of str -> object + - If `enable_metadata_routing=False` (default): Parameters to the + ``predict`` called at the end of all transformations in the pipeline. + + - If `enable_metadata_routing=True`: Parameters requested and accepted by + steps. Each step must have requested certain metadata for these parameters + to be forwarded to them. + + .. versionadded:: 0.20 + + .. versionchanged:: 1.4 + Parameters are now passed to the ``transform`` method of the + intermediate steps as well, if requested, and if + `enable_metadata_routing=True`. + + See :ref:`Metadata Routing User Guide ` for more + details. + + Note that while this may be used to return uncertainties from some + models with ``return_std`` or ``return_cov``, uncertainties that are + generated by the transformations in the pipeline are not propagated + to the final estimator. + + Returns + ------- + y_pred : ndarray + Result of calling `fit_predict` on the final estimator. + """ + routed_params = self._check_method_params(method="fit_predict", props=params) + Xt = self._fit(X, y, routed_params) + + params_last_step = routed_params[self.steps[-1][0]] + with _print_elapsed_time("Pipeline", self._log_message(len(self.steps) - 1)): + y_pred = self.steps[-1][1].fit_predict( + Xt, y, **params_last_step.get("fit_predict", {}) + ) + return y_pred + + @available_if(_final_estimator_has("predict_proba")) + def predict_proba(self, X, **params): + """Transform the data, and apply `predict_proba` with the final estimator. + + Call `transform` of each transformer in the pipeline. The transformed + data are finally passed to the final estimator that calls + `predict_proba` method. Only valid if the final estimator implements + `predict_proba`. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step + of the pipeline. + + **params : dict of str -> object + - If `enable_metadata_routing=False` (default): Parameters to the + `predict_proba` called at the end of all transformations in the pipeline. + + - If `enable_metadata_routing=True`: Parameters requested and accepted by + steps. Each step must have requested certain metadata for these parameters + to be forwarded to them. + + .. versionadded:: 0.20 + + .. versionchanged:: 1.4 + Parameters are now passed to the ``transform`` method of the + intermediate steps as well, if requested, and if + `enable_metadata_routing=True`. + + See :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + y_proba : ndarray of shape (n_samples, n_classes) + Result of calling `predict_proba` on the final estimator. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + Xt = X + + if not _routing_enabled(): + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt) + return self.steps[-1][1].predict_proba(Xt, **params) + + # metadata routing enabled + routed_params = process_routing(self, "predict_proba", **params) + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt, **routed_params[name].transform) + return self.steps[-1][1].predict_proba( + Xt, **routed_params[self.steps[-1][0]].predict_proba + ) + + @available_if(_final_estimator_has("decision_function")) + def decision_function(self, X, **params): + """Transform the data, and apply `decision_function` with the final estimator. + + Call `transform` of each transformer in the pipeline. The transformed + data are finally passed to the final estimator that calls + `decision_function` method. Only valid if the final estimator + implements `decision_function`. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step + of the pipeline. + + **params : dict of string -> object + Parameters requested and accepted by steps. Each step must have + requested certain metadata for these parameters to be forwarded to + them. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + y_score : ndarray of shape (n_samples, n_classes) + Result of calling `decision_function` on the final estimator. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + _raise_for_params(params, self, "decision_function") + + # not branching here since params is only available if + # enable_metadata_routing=True + routed_params = process_routing(self, "decision_function", **params) + + Xt = X + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform( + Xt, **routed_params.get(name, {}).get("transform", {}) + ) + return self.steps[-1][1].decision_function( + Xt, + **routed_params.get(self.steps[-1][0], {}).get("decision_function", {}), + ) + + @available_if(_final_estimator_has("score_samples")) + def score_samples(self, X): + """Transform the data, and apply `score_samples` with the final estimator. + + Call `transform` of each transformer in the pipeline. The transformed + data are finally passed to the final estimator that calls + `score_samples` method. Only valid if the final estimator implements + `score_samples`. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step + of the pipeline. + + Returns + ------- + y_score : ndarray of shape (n_samples,) + Result of calling `score_samples` on the final estimator. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + Xt = X + for _, _, transformer in self._iter(with_final=False): + Xt = transformer.transform(Xt) + return self.steps[-1][1].score_samples(Xt) + + @available_if(_final_estimator_has("predict_log_proba")) + def predict_log_proba(self, X, **params): + """Transform the data, and apply `predict_log_proba` with the final estimator. + + Call `transform` of each transformer in the pipeline. The transformed + data are finally passed to the final estimator that calls + `predict_log_proba` method. Only valid if the final estimator + implements `predict_log_proba`. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step + of the pipeline. + + **params : dict of str -> object + - If `enable_metadata_routing=False` (default): Parameters to the + `predict_log_proba` called at the end of all transformations in the + pipeline. + + - If `enable_metadata_routing=True`: Parameters requested and accepted by + steps. Each step must have requested certain metadata for these parameters + to be forwarded to them. + + .. versionadded:: 0.20 + + .. versionchanged:: 1.4 + Parameters are now passed to the ``transform`` method of the + intermediate steps as well, if requested, and if + `enable_metadata_routing=True`. + + See :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + y_log_proba : ndarray of shape (n_samples, n_classes) + Result of calling `predict_log_proba` on the final estimator. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + Xt = X + + if not _routing_enabled(): + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt) + return self.steps[-1][1].predict_log_proba(Xt, **params) + + # metadata routing enabled + routed_params = process_routing(self, "predict_log_proba", **params) + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt, **routed_params[name].transform) + return self.steps[-1][1].predict_log_proba( + Xt, **routed_params[self.steps[-1][0]].predict_log_proba + ) + + def _can_transform(self): + return self._final_estimator == "passthrough" or hasattr( + self._final_estimator, "transform" + ) + + @available_if(_can_transform) + def transform(self, X, **params): + """Transform the data, and apply `transform` with the final estimator. + + Call `transform` of each transformer in the pipeline. The transformed + data are finally passed to the final estimator that calls + `transform` method. Only valid if the final estimator + implements `transform`. + + This also works where final estimator is `None` in which case all prior + transformations are applied. + + Parameters + ---------- + X : iterable + Data to transform. Must fulfill input requirements of first step + of the pipeline. + + **params : dict of str -> object + Parameters requested and accepted by steps. Each step must have + requested certain metadata for these parameters to be forwarded to + them. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + Xt : ndarray of shape (n_samples, n_transformed_features) + Transformed data. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + _raise_for_params(params, self, "transform") + + # not branching here since params is only available if + # enable_metadata_routing=True + routed_params = process_routing(self, "transform", **params) + Xt = X + for _, name, transform in self._iter(): + Xt = transform.transform(Xt, **routed_params[name].transform) + return Xt + + def _can_inverse_transform(self): + return all(hasattr(t, "inverse_transform") for _, _, t in self._iter()) + + @available_if(_can_inverse_transform) + def inverse_transform(self, X, **params): + """Apply `inverse_transform` for each step in a reverse order. + + All estimators in the pipeline must support `inverse_transform`. + + Parameters + ---------- + X : array-like of shape (n_samples, n_transformed_features) + Data samples, where ``n_samples`` is the number of samples and + ``n_features`` is the number of features. Must fulfill + input requirements of last step of pipeline's + ``inverse_transform`` method. + + **params : dict of str -> object + Parameters requested and accepted by steps. Each step must have + requested certain metadata for these parameters to be forwarded to + them. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + X_original : ndarray of shape (n_samples, n_features) + Inverse transformed data, that is, data in the original feature + space. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + _raise_for_params(params, self, "inverse_transform") + + # we don't have to branch here, since params is only non-empty if + # enable_metadata_routing=True. + routed_params = process_routing(self, "inverse_transform", **params) + reverse_iter = reversed(list(self._iter())) + for _, name, transform in reverse_iter: + X = transform.inverse_transform( + X, **routed_params[name].inverse_transform + ) + return X + + @available_if(_final_estimator_has("score")) + def score(self, X, y=None, sample_weight=None, **params): + """Transform the data, and apply `score` with the final estimator. + + Call `transform` of each transformer in the pipeline. The transformed + data are finally passed to the final estimator that calls + `score` method. Only valid if the final estimator implements `score`. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step + of the pipeline. + + y : iterable, default=None + Targets used for scoring. Must fulfill label requirements for all + steps of the pipeline. + + sample_weight : array-like, default=None + If not None, this argument is passed as ``sample_weight`` keyword + argument to the ``score`` method of the final estimator. + + **params : dict of str -> object + Parameters requested and accepted by steps. Each step must have + requested certain metadata for these parameters to be forwarded to + them. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + score : float + Result of calling `score` on the final estimator. + """ + # TODO(1.8): Remove the context manager and use check_is_fitted(self) + with _raise_or_warn_if_not_fitted(self): + Xt = X + if not _routing_enabled(): + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt) + score_params = {} + if sample_weight is not None: + score_params["sample_weight"] = sample_weight + return self.steps[-1][1].score(Xt, y, **score_params) + + # metadata routing is enabled. + routed_params = process_routing( + self, "score", sample_weight=sample_weight, **params + ) + + Xt = X + for _, name, transform in self._iter(with_final=False): + Xt = transform.transform(Xt, **routed_params[name].transform) + return self.steps[-1][1].score( + Xt, y, **routed_params[self.steps[-1][0]].score + ) + + @property + def classes_(self): + """The classes labels. Only exist if the last step is a classifier.""" + return self.steps[-1][1].classes_ + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + + if not self.steps: + return tags + + try: + if self.steps[0][1] is not None and self.steps[0][1] != "passthrough": + tags.input_tags.pairwise = get_tags( + self.steps[0][1] + ).input_tags.pairwise + # WARNING: the sparse tag can be incorrect. + # Some Pipelines accepting sparse data are wrongly tagged sparse=False. + # For example Pipeline([PCA(), estimator]) accepts sparse data + # even if the estimator doesn't as PCA outputs a dense array. + tags.input_tags.sparse = all( + get_tags(step).input_tags.sparse + for name, step in self.steps + if step is not None and step != "passthrough" + ) + except (ValueError, AttributeError, TypeError): + # This happens when the `steps` is not a list of (name, estimator) + # tuples and `fit` is not called yet to validate the steps. + pass + + try: + if self.steps[-1][1] is not None and self.steps[-1][1] != "passthrough": + last_step_tags = get_tags(self.steps[-1][1]) + tags.estimator_type = last_step_tags.estimator_type + tags.target_tags.multi_output = last_step_tags.target_tags.multi_output + tags.classifier_tags = deepcopy(last_step_tags.classifier_tags) + tags.regressor_tags = deepcopy(last_step_tags.regressor_tags) + tags.transformer_tags = deepcopy(last_step_tags.transformer_tags) + except (ValueError, AttributeError, TypeError): + # This happens when the `steps` is not a list of (name, estimator) + # tuples and `fit` is not called yet to validate the steps. + pass + + return tags + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Transform input features using the pipeline. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + feature_names_out = input_features + for _, name, transform in self._iter(): + if not hasattr(transform, "get_feature_names_out"): + raise AttributeError( + "Estimator {} does not provide get_feature_names_out. " + "Did you mean to call pipeline[:-1].get_feature_names_out" + "()?".format(name) + ) + feature_names_out = transform.get_feature_names_out(feature_names_out) + return feature_names_out + + @property + def n_features_in_(self): + """Number of features seen during first step `fit` method.""" + # delegate to first step (which will call check_is_fitted) + return self.steps[0][1].n_features_in_ + + @property + def feature_names_in_(self): + """Names of features seen during first step `fit` method.""" + # delegate to first step (which will call check_is_fitted) + return self.steps[0][1].feature_names_in_ + + def __sklearn_is_fitted__(self): + """Indicate whether pipeline has been fit. + + This is done by checking whether the last non-`passthrough` step of the + pipeline is fitted. + + An empty pipeline is considered fitted. + """ + # First find the last step that is not 'passthrough' + last_step = None + for _, estimator in reversed(self.steps): + if estimator != "passthrough": + last_step = estimator + break + + if last_step is None: + # All steps are 'passthrough', so the pipeline is considered fitted + return True + + try: + # check if the last step of the pipeline is fitted + # we only check the last step since if the last step is fit, it + # means the previous steps should also be fit. This is faster than + # checking if every step of the pipeline is fit. + check_is_fitted(last_step) + return True + except NotFittedError: + return False + + def _sk_visual_block_(self): + _, estimators = zip(*self.steps) + + def _get_name(name, est): + if est is None or est == "passthrough": + return f"{name}: passthrough" + # Is an estimator + return f"{name}: {est.__class__.__name__}" + + names = [_get_name(name, est) for name, est in self.steps] + name_details = [str(est) for est in estimators] + return _VisualBlock( + "serial", + estimators, + names=names, + name_details=name_details, + dash_wrapped=False, + ) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__) + + # first we add all steps except the last one + for _, name, trans in self._iter(with_final=False, filter_passthrough=True): + method_mapping = MethodMapping() + # fit, fit_predict, and fit_transform call fit_transform if it + # exists, or else fit and transform + if hasattr(trans, "fit_transform"): + ( + method_mapping.add(caller="fit", callee="fit_transform") + .add(caller="fit_transform", callee="fit_transform") + .add(caller="fit_predict", callee="fit_transform") + ) + else: + ( + method_mapping.add(caller="fit", callee="fit") + .add(caller="fit", callee="transform") + .add(caller="fit_transform", callee="fit") + .add(caller="fit_transform", callee="transform") + .add(caller="fit_predict", callee="fit") + .add(caller="fit_predict", callee="transform") + ) + + ( + method_mapping.add(caller="predict", callee="transform") + .add(caller="predict", callee="transform") + .add(caller="predict_proba", callee="transform") + .add(caller="decision_function", callee="transform") + .add(caller="predict_log_proba", callee="transform") + .add(caller="transform", callee="transform") + .add(caller="inverse_transform", callee="inverse_transform") + .add(caller="score", callee="transform") + ) + + router.add(method_mapping=method_mapping, **{name: trans}) + + final_name, final_est = self.steps[-1] + if final_est is None or final_est == "passthrough": + return router + + # then we add the last step + method_mapping = MethodMapping() + if hasattr(final_est, "fit_transform"): + method_mapping.add(caller="fit_transform", callee="fit_transform") + else: + method_mapping.add(caller="fit", callee="fit").add( + caller="fit", callee="transform" + ) + ( + method_mapping.add(caller="fit", callee="fit") + .add(caller="predict", callee="predict") + .add(caller="fit_predict", callee="fit_predict") + .add(caller="predict_proba", callee="predict_proba") + .add(caller="decision_function", callee="decision_function") + .add(caller="predict_log_proba", callee="predict_log_proba") + .add(caller="transform", callee="transform") + .add(caller="inverse_transform", callee="inverse_transform") + .add(caller="score", callee="score") + ) + + router.add(method_mapping=method_mapping, **{final_name: final_est}) + return router + + +def _name_estimators(estimators): + """Generate names for estimators.""" + + names = [ + estimator if isinstance(estimator, str) else type(estimator).__name__.lower() + for estimator in estimators + ] + namecount = defaultdict(int) + for est, name in zip(estimators, names): + namecount[name] += 1 + + for k, v in list(namecount.items()): + if v == 1: + del namecount[k] + + for i in reversed(range(len(estimators))): + name = names[i] + if name in namecount: + names[i] += "-%d" % namecount[name] + namecount[name] -= 1 + + return list(zip(names, estimators)) + + +def make_pipeline(*steps, memory=None, transform_input=None, verbose=False): + """Construct a :class:`Pipeline` from the given estimators. + + This is a shorthand for the :class:`Pipeline` constructor; it does not + require, and does not permit, naming the estimators. Instead, their names + will be set to the lowercase of their types automatically. + + Parameters + ---------- + *steps : list of Estimator objects + List of the scikit-learn estimators that are chained together. + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the fitted transformers of the pipeline. The last step + will never be cached, even if it is a transformer. By default, no + caching is performed. If a string is given, it is the path to the + caching directory. Enabling caching triggers a clone of the transformers + before fitting. Therefore, the transformer instance given to the + pipeline cannot be inspected directly. Use the attribute ``named_steps`` + or ``steps`` to inspect estimators within the pipeline. Caching the + transformers is advantageous when fitting is time consuming. + + transform_input : list of str, default=None + This enables transforming some input arguments to ``fit`` (other than ``X``) + to be transformed by the steps of the pipeline up to the step which requires + them. Requirement is defined via :ref:`metadata routing `. + This can be used to pass a validation set through the pipeline for instance. + + You can only set this if metadata routing is enabled, which you + can enable using ``sklearn.set_config(enable_metadata_routing=True)``. + + .. versionadded:: 1.6 + + verbose : bool, default=False + If True, the time elapsed while fitting each step will be printed as it + is completed. + + Returns + ------- + p : Pipeline + Returns a scikit-learn :class:`Pipeline` object. + + See Also + -------- + Pipeline : Class for creating a pipeline of transforms with a final + estimator. + + Examples + -------- + >>> from sklearn.naive_bayes import GaussianNB + >>> from sklearn.preprocessing import StandardScaler + >>> from sklearn.pipeline import make_pipeline + >>> make_pipeline(StandardScaler(), GaussianNB(priors=None)) + Pipeline(steps=[('standardscaler', StandardScaler()), + ('gaussiannb', GaussianNB())]) + """ + return Pipeline( + _name_estimators(steps), + transform_input=transform_input, + memory=memory, + verbose=verbose, + ) + + +def _transform_one(transformer, X, y, weight, params): + """Call transform and apply weight to output. + + Parameters + ---------- + transformer : estimator + Estimator to be used for transformation. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data to be transformed. + + y : ndarray of shape (n_samples,) + Ignored. + + weight : float + Weight to be applied to the output of the transformation. + + params : dict + Parameters to be passed to the transformer's ``transform`` method. + + This should be of the form ``process_routing()["step_name"]``. + """ + res = transformer.transform(X, **params.transform) + # if we have a weight for this transformer, multiply output + if weight is None: + return res + return res * weight + + +def _fit_transform_one( + transformer, X, y, weight, message_clsname="", message=None, params=None +): + """ + Fits ``transformer`` to ``X`` and ``y``. The transformed result is returned + with the fitted transformer. If ``weight`` is not ``None``, the result will + be multiplied by ``weight``. + + ``params`` needs to be of the form ``process_routing()["step_name"]``. + """ + params = params or {} + with _print_elapsed_time(message_clsname, message): + if hasattr(transformer, "fit_transform"): + res = transformer.fit_transform(X, y, **params.get("fit_transform", {})) + else: + res = transformer.fit(X, y, **params.get("fit", {})).transform( + X, **params.get("transform", {}) + ) + + if weight is None: + return res, transformer + return res * weight, transformer + + +def _fit_one(transformer, X, y, weight, message_clsname="", message=None, params=None): + """ + Fits ``transformer`` to ``X`` and ``y``. + """ + with _print_elapsed_time(message_clsname, message): + return transformer.fit(X, y, **params["fit"]) + + +class FeatureUnion(TransformerMixin, _BaseComposition): + """Concatenates results of multiple transformer objects. + + This estimator applies a list of transformer objects in parallel to the + input data, then concatenates the results. This is useful to combine + several feature extraction mechanisms into a single transformer. + + Parameters of the transformers may be set using its name and the parameter + name separated by a '__'. A transformer may be replaced entirely by + setting the parameter with its name to another transformer, removed by + setting to 'drop' or disabled by setting to 'passthrough' (features are + passed without transformation). + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.13 + + Parameters + ---------- + transformer_list : list of (str, transformer) tuples + List of transformer objects to be applied to the data. The first + half of each tuple is the name of the transformer. The transformer can + be 'drop' for it to be ignored or can be 'passthrough' for features to + be passed unchanged. + + .. versionadded:: 1.1 + Added the option `"passthrough"`. + + .. versionchanged:: 0.22 + Deprecated `None` as a transformer in favor of 'drop'. + + n_jobs : int, default=None + Number of jobs to run in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionchanged:: v0.20 + `n_jobs` default changed from 1 to None + + transformer_weights : dict, default=None + Multiplicative weights for features per transformer. + Keys are transformer names, values the weights. + Raises ValueError if key not present in ``transformer_list``. + + verbose : bool, default=False + If True, the time elapsed while fitting each transformer will be + printed as it is completed. + + verbose_feature_names_out : bool, default=True + If True, :meth:`get_feature_names_out` will prefix all feature names + with the name of the transformer that generated that feature. + If False, :meth:`get_feature_names_out` will not prefix any feature + names and will error if feature names are not unique. + + .. versionadded:: 1.5 + + Attributes + ---------- + named_transformers : :class:`~sklearn.utils.Bunch` + Dictionary-like object, with the following attributes. + Read-only attribute to access any transformer parameter by user + given name. Keys are transformer names and values are + transformer parameters. + + .. versionadded:: 1.2 + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying first transformer in `transformer_list` exposes such an + attribute when 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.3 + + See Also + -------- + make_union : Convenience function for simplified feature union + construction. + + Examples + -------- + >>> from sklearn.pipeline import FeatureUnion + >>> from sklearn.decomposition import PCA, TruncatedSVD + >>> union = FeatureUnion([("pca", PCA(n_components=1)), + ... ("svd", TruncatedSVD(n_components=2))]) + >>> X = [[0., 1., 3], [2., 2., 5]] + >>> union.fit_transform(X) + array([[-1.5 , 3.04, -0.872], + [ 1.5 , 5.72, 0.463]]) + >>> # An estimator's parameter can be set using '__' syntax + >>> union.set_params(svd__n_components=1).fit_transform(X) + array([[-1.5 , 3.04], + [ 1.5 , 5.72]]) + + For a more detailed example of usage, see + :ref:`sphx_glr_auto_examples_compose_plot_feature_union.py`. + """ + + def __init__( + self, + transformer_list, + *, + n_jobs=None, + transformer_weights=None, + verbose=False, + verbose_feature_names_out=True, + ): + self.transformer_list = transformer_list + self.n_jobs = n_jobs + self.transformer_weights = transformer_weights + self.verbose = verbose + self.verbose_feature_names_out = verbose_feature_names_out + + def set_output(self, *, transform=None): + """Set the output container when `"transform"` and `"fit_transform"` are called. + + `set_output` will set the output of all estimators in `transformer_list`. + + Parameters + ---------- + transform : {"default", "pandas", "polars"}, default=None + Configure output of `transform` and `fit_transform`. + + - `"default"`: Default output format of a transformer + - `"pandas"`: DataFrame output + - `"polars"`: Polars output + - `None`: Transform configuration is unchanged + + Returns + ------- + self : estimator instance + Estimator instance. + """ + super().set_output(transform=transform) + for _, step, _ in self._iter(): + _safe_set_output(step, transform=transform) + return self + + @property + def named_transformers(self): + # Use Bunch object to improve autocomplete + return Bunch(**dict(self.transformer_list)) + + def get_params(self, deep=True): + """Get parameters for this estimator. + + Returns the parameters given in the constructor as well as the + estimators contained within the `transformer_list` of the + `FeatureUnion`. + + Parameters + ---------- + deep : bool, default=True + If True, will return the parameters for this estimator and + contained subobjects that are estimators. + + Returns + ------- + params : mapping of string to any + Parameter names mapped to their values. + """ + return self._get_params("transformer_list", deep=deep) + + def set_params(self, **kwargs): + """Set the parameters of this estimator. + + Valid parameter keys can be listed with ``get_params()``. Note that + you can directly set the parameters of the estimators contained in + `transformer_list`. + + Parameters + ---------- + **kwargs : dict + Parameters of this estimator or parameters of estimators contained + in `transform_list`. Parameters of the transformers may be set + using its name and the parameter name separated by a '__'. + + Returns + ------- + self : object + FeatureUnion class instance. + """ + self._set_params("transformer_list", **kwargs) + return self + + def _validate_transformers(self): + names, transformers = zip(*self.transformer_list) + + # validate names + self._validate_names(names) + + # validate estimators + for t in transformers: + if t in ("drop", "passthrough"): + continue + if not (hasattr(t, "fit") or hasattr(t, "fit_transform")) or not hasattr( + t, "transform" + ): + raise TypeError( + "All estimators should implement fit and " + "transform. '%s' (type %s) doesn't" % (t, type(t)) + ) + + def _validate_transformer_weights(self): + if not self.transformer_weights: + return + + transformer_names = set(name for name, _ in self.transformer_list) + for name in self.transformer_weights: + if name not in transformer_names: + raise ValueError( + f'Attempting to weight transformer "{name}", ' + "but it is not present in transformer_list." + ) + + def _iter(self): + """ + Generate (name, trans, weight) tuples excluding None and + 'drop' transformers. + """ + + get_weight = (self.transformer_weights or {}).get + + for name, trans in self.transformer_list: + if trans == "drop": + continue + if trans == "passthrough": + trans = FunctionTransformer(feature_names_out="one-to-one") + yield (name, trans, get_weight(name)) + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + # List of tuples (name, feature_names_out) + transformer_with_feature_names_out = [] + for name, trans, _ in self._iter(): + if not hasattr(trans, "get_feature_names_out"): + raise AttributeError( + "Transformer %s (type %s) does not provide get_feature_names_out." + % (str(name), type(trans).__name__) + ) + feature_names_out = trans.get_feature_names_out(input_features) + transformer_with_feature_names_out.append((name, feature_names_out)) + + return self._add_prefix_for_feature_names_out( + transformer_with_feature_names_out + ) + + def _add_prefix_for_feature_names_out(self, transformer_with_feature_names_out): + """Add prefix for feature names out that includes the transformer names. + + Parameters + ---------- + transformer_with_feature_names_out : list of tuples of (str, array-like of str) + The tuple consistent of the transformer's name and its feature names out. + + Returns + ------- + feature_names_out : ndarray of shape (n_features,), dtype=str + Transformed feature names. + """ + if self.verbose_feature_names_out: + # Prefix the feature names out with the transformers name + names = list( + chain.from_iterable( + (f"{name}__{i}" for i in feature_names_out) + for name, feature_names_out in transformer_with_feature_names_out + ) + ) + return np.asarray(names, dtype=object) + + # verbose_feature_names_out is False + # Check that names are all unique without a prefix + feature_names_count = Counter( + chain.from_iterable(s for _, s in transformer_with_feature_names_out) + ) + top_6_overlap = [ + name for name, count in feature_names_count.most_common(6) if count > 1 + ] + top_6_overlap.sort() + if top_6_overlap: + if len(top_6_overlap) == 6: + # There are more than 5 overlapping names, we only show the 5 + # of the feature names + names_repr = str(top_6_overlap[:5])[:-1] + ", ...]" + else: + names_repr = str(top_6_overlap) + raise ValueError( + f"Output feature names: {names_repr} are not unique. Please set " + "verbose_feature_names_out=True to add prefixes to feature names" + ) + + return np.concatenate( + [name for _, name in transformer_with_feature_names_out], + ) + + def fit(self, X, y=None, **fit_params): + """Fit all transformers using X. + + Parameters + ---------- + X : iterable or array-like, depending on transformers + Input data, used to fit transformers. + + y : array-like of shape (n_samples, n_outputs), default=None + Targets for supervised learning. + + **fit_params : dict, default=None + - If `enable_metadata_routing=False` (default): + Parameters directly passed to the `fit` methods of the + sub-transformers. + + - If `enable_metadata_routing=True`: + Parameters safely routed to the `fit` methods of the + sub-transformers. See :ref:`Metadata Routing User Guide + ` for more details. + + .. versionchanged:: 1.5 + `**fit_params` can be routed via metadata routing API. + + Returns + ------- + self : object + FeatureUnion class instance. + """ + if _routing_enabled(): + routed_params = process_routing(self, "fit", **fit_params) + else: + # TODO(SLEP6): remove when metadata routing cannot be disabled. + routed_params = Bunch() + for name, _ in self.transformer_list: + routed_params[name] = Bunch(fit={}) + routed_params[name].fit = fit_params + + transformers = self._parallel_func(X, y, _fit_one, routed_params) + + if not transformers: + # All transformers are None + return self + + self._update_transformer_list(transformers) + return self + + def fit_transform(self, X, y=None, **params): + """Fit all transformers, transform the data and concatenate results. + + Parameters + ---------- + X : iterable or array-like, depending on transformers + Input data to be transformed. + + y : array-like of shape (n_samples, n_outputs), default=None + Targets for supervised learning. + + **params : dict, default=None + - If `enable_metadata_routing=False` (default): + Parameters directly passed to the `fit` methods of the + sub-transformers. + + - If `enable_metadata_routing=True`: + Parameters safely routed to the `fit` methods of the + sub-transformers. See :ref:`Metadata Routing User Guide + ` for more details. + + .. versionchanged:: 1.5 + `**params` can now be routed via metadata routing API. + + Returns + ------- + X_t : array-like or sparse matrix of \ + shape (n_samples, sum_n_components) + The `hstack` of results of transformers. `sum_n_components` is the + sum of `n_components` (output dimension) over transformers. + """ + if _routing_enabled(): + routed_params = process_routing(self, "fit_transform", **params) + else: + # TODO(SLEP6): remove when metadata routing cannot be disabled. + routed_params = Bunch() + for name, obj in self.transformer_list: + if hasattr(obj, "fit_transform"): + routed_params[name] = Bunch(fit_transform={}) + routed_params[name].fit_transform = params + else: + routed_params[name] = Bunch(fit={}) + routed_params[name] = Bunch(transform={}) + routed_params[name].fit = params + + results = self._parallel_func(X, y, _fit_transform_one, routed_params) + if not results: + # All transformers are None + return np.zeros((X.shape[0], 0)) + + Xs, transformers = zip(*results) + self._update_transformer_list(transformers) + + return self._hstack(Xs) + + def _log_message(self, name, idx, total): + if not self.verbose: + return None + return "(step %d of %d) Processing %s" % (idx, total, name) + + def _parallel_func(self, X, y, func, routed_params): + """Runs func in parallel on X and y""" + self.transformer_list = list(self.transformer_list) + self._validate_transformers() + self._validate_transformer_weights() + transformers = list(self._iter()) + + return Parallel(n_jobs=self.n_jobs)( + delayed(func)( + transformer, + X, + y, + weight, + message_clsname="FeatureUnion", + message=self._log_message(name, idx, len(transformers)), + params=routed_params[name], + ) + for idx, (name, transformer, weight) in enumerate(transformers, 1) + ) + + def transform(self, X, **params): + """Transform X separately by each transformer, concatenate results. + + Parameters + ---------- + X : iterable or array-like, depending on transformers + Input data to be transformed. + + **params : dict, default=None + + Parameters routed to the `transform` method of the sub-transformers via the + metadata routing API. See :ref:`Metadata Routing User Guide + ` for more details. + + .. versionadded:: 1.5 + + Returns + ------- + X_t : array-like or sparse matrix of shape (n_samples, sum_n_components) + The `hstack` of results of transformers. `sum_n_components` is the + sum of `n_components` (output dimension) over transformers. + """ + _raise_for_params(params, self, "transform") + + if _routing_enabled(): + routed_params = process_routing(self, "transform", **params) + else: + # TODO(SLEP6): remove when metadata routing cannot be disabled. + routed_params = Bunch() + for name, _ in self.transformer_list: + routed_params[name] = Bunch(transform={}) + + Xs = Parallel(n_jobs=self.n_jobs)( + delayed(_transform_one)(trans, X, None, weight, params=routed_params[name]) + for name, trans, weight in self._iter() + ) + if not Xs: + # All transformers are None + return np.zeros((X.shape[0], 0)) + + return self._hstack(Xs) + + def _hstack(self, Xs): + # Check if Xs dimensions are valid + for X, (name, _) in zip(Xs, self.transformer_list): + if hasattr(X, "shape") and len(X.shape) != 2: + raise ValueError( + f"Transformer '{name}' returned an array or dataframe with " + f"{len(X.shape)} dimensions, but expected 2 dimensions " + "(n_samples, n_features)." + ) + + adapter = _get_container_adapter("transform", self) + if adapter and all(adapter.is_supported_container(X) for X in Xs): + return adapter.hstack(Xs) + + if any(sparse.issparse(f) for f in Xs): + return sparse.hstack(Xs).tocsr() + + return np.hstack(Xs) + + def _update_transformer_list(self, transformers): + transformers = iter(transformers) + self.transformer_list[:] = [ + (name, old if old == "drop" else next(transformers)) + for name, old in self.transformer_list + ] + + @property + def n_features_in_(self): + """Number of features seen during :term:`fit`.""" + + # X is passed to all transformers so we just delegate to the first one + return self.transformer_list[0][1].n_features_in_ + + @property + def feature_names_in_(self): + """Names of features seen during :term:`fit`.""" + # X is passed to all transformers -- delegate to the first one + return self.transformer_list[0][1].feature_names_in_ + + def __sklearn_is_fitted__(self): + # Delegate whether feature union was fitted + for _, transformer, _ in self._iter(): + check_is_fitted(transformer) + return True + + def _sk_visual_block_(self): + names, transformers = zip(*self.transformer_list) + return _VisualBlock("parallel", transformers, names=names) + + def __getitem__(self, name): + """Return transformer with name.""" + if not isinstance(name, str): + raise KeyError("Only string keys are supported") + return self.named_transformers[name] + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.5 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__) + + for name, transformer in self.transformer_list: + router.add( + **{name: transformer}, + method_mapping=MethodMapping() + .add(caller="fit", callee="fit") + .add(caller="fit_transform", callee="fit_transform") + .add(caller="fit_transform", callee="fit") + .add(caller="fit_transform", callee="transform") + .add(caller="transform", callee="transform"), + ) + + return router + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + try: + tags.input_tags.sparse = all( + get_tags(trans).input_tags.sparse + for name, trans in self.transformer_list + if trans not in {"passthrough", "drop"} + ) + except Exception: + # If `transformer_list` does not comply with our API (list of tuples) + # then it will fail. In this case, we assume that `sparse` is False + # but the parameter validation will raise an error during `fit`. + pass # pragma: no cover + return tags + + +def make_union( + *transformers, n_jobs=None, verbose=False, verbose_feature_names_out=True +): + """Construct a :class:`FeatureUnion` from the given transformers. + + This is a shorthand for the :class:`FeatureUnion` constructor; it does not + require, and does not permit, naming the transformers. Instead, they will + be given names automatically based on their types. It also does not allow + weighting. + + Parameters + ---------- + *transformers : list of estimators + One or more estimators. + + n_jobs : int, default=None + Number of jobs to run in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionchanged:: v0.20 + `n_jobs` default changed from 1 to None. + + verbose : bool, default=False + If True, the time elapsed while fitting each transformer will be + printed as it is completed. + + verbose_feature_names_out : bool, default=True + If True, the feature names generated by `get_feature_names_out` will + include prefixes derived from the transformer names. + + Returns + ------- + f : FeatureUnion + A :class:`FeatureUnion` object for concatenating the results of multiple + transformer objects. + + See Also + -------- + FeatureUnion : Class for concatenating the results of multiple transformer + objects. + + Examples + -------- + >>> from sklearn.decomposition import PCA, TruncatedSVD + >>> from sklearn.pipeline import make_union + >>> make_union(PCA(), TruncatedSVD()) + FeatureUnion(transformer_list=[('pca', PCA()), + ('truncatedsvd', TruncatedSVD())]) + """ + return FeatureUnion( + _name_estimators(transformers), + n_jobs=n_jobs, + verbose=verbose, + verbose_feature_names_out=verbose_feature_names_out, + ) diff --git a/shared/package-files/06/06f8846a9e982ef773a1d4876ee584f017be8184d1e678bceb3fef1ae8597f98/test_random_panel.py b/shared/package-files/06/06f8846a9e982ef773a1d4876ee584f017be8184d1e678bceb3fef1ae8597f98/test_random_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..2cbee828e4ba91e9dde557b02ef63343b491d5e1 --- /dev/null +++ b/shared/package-files/06/06f8846a9e982ef773a1d4876ee584f017be8184d1e678bceb3fef1ae8597f98/test_random_panel.py @@ -0,0 +1,189 @@ +"""Test for short_panel and panel sandwich + +Created on Fri May 18 13:05:47 2012 + +Author: Josef Perktold + +moved example from main of random_panel +""" + +import numpy as np +import numpy.testing as npt +from numpy.testing import assert_almost_equal + +from statsmodels.regression.linear_model import OLS +import statsmodels.sandbox.panel.correlation_structures as cs +from statsmodels.sandbox.panel.panel_short import ShortPanelGLS, ShortPanelGLS2 +from statsmodels.sandbox.panel.random_panel import PanelSample +from statsmodels.stats.moment_helpers import cov2corr, se_cov +import statsmodels.stats.sandwich_covariance as sw +import statsmodels.tools.eval_measures as em + + +def assert_maxabs(actual, expected, value): + npt.assert_array_less(em.maxabs(actual, expected, None), value) + + +def test_panel_sample_rng_default_is_generator(): + # GH: rng=None used to be pre-converted to a random int before being + # handed to check_random_state(deprecated=True), so the default case + # always produced a legacy RandomState instead of a fresh Generator + # like every other canonical rng-accepting constructor in the + # library. + dgp = PanelSample(20, 2, 4, rng=None) + assert isinstance(dgp.random_state, np.random.Generator) + + +def test_panel_sample_rng_types(): + for rng in (0, np.random.RandomState(0), np.random.default_rng(0)): + dgp = PanelSample(20, 2, 4, rng=rng) + dgp.generate_panel() + + +def test_panel_sample_rng_reproducible(): + dgp1 = PanelSample(20, 2, 4, rng=0) + dgp2 = PanelSample(20, 2, 4, rng=0) + y1 = dgp1.generate_panel() + y2 = dgp2.generate_panel() + assert_almost_equal(y1, y2, decimal=13) + + +def test_short_panel(): + # this checks that some basic statistical properties are satisfied by the + # results, not verified results against other packages + # Note: the ranking of robust bse is different if within=True + # I added within keyword to PanelSample to be able to use old example + # if within is False, then there is no within group variation in exog. + nobs = 100 + nobs_i = 5 + n_groups = nobs // nobs_i + k_vars = 3 + + dgp = PanelSample( + nobs, + k_vars, + n_groups, + corr_structure=cs.corr_arma, + corr_args=( + [1], + [1.0, -0.9], + ), + rng=377769, + within=False, + ) + # print 'rng', dgp.rng + y = dgp.generate_panel() + noise = y - dgp.y_true + + # test dgp + + dgp_cov_e = np.array( + [ + [1.0, 0.9, 0.81, 0.729, 0.6561], + [0.9, 1.0, 0.9, 0.81, 0.729], + [0.81, 0.9, 1.0, 0.9, 0.81], + [0.729, 0.81, 0.9, 1.0, 0.9], + [0.6561, 0.729, 0.81, 0.9, 1.0], + ] + ) + + npt.assert_almost_equal(dgp.cov, dgp_cov_e, 13) + + cov_noise = np.cov(noise.reshape(-1, n_groups, order="F")) + corr_noise = cov2corr(cov_noise) + npt.assert_almost_equal(corr_noise, dgp.cov, 1) + + # estimate panel model + mod2 = ShortPanelGLS(y, dgp.exog, dgp.groups) + res2 = mod2.fit_iterative(2) + + # whitened residual should be uncorrelated + corr_wresid = np.corrcoef(res2.wresid.reshape(-1, n_groups, order="F")) + assert_maxabs(corr_wresid, np.eye(5), 0.1) + + # residual should have same correlation as dgp + corr_resid = np.corrcoef(res2.resid.reshape(-1, n_groups, order="F")) + assert_maxabs(corr_resid, dgp.cov, 0.1) + + assert_almost_equal(res2.resid.std(), 1, decimal=0) + + y_pred = np.dot(mod2.exog, res2.params) + assert_almost_equal(res2.fittedvalues, y_pred, 13) + + # compare with OLS + + res2_ols = mod2._fit_ols() + assert mod2.res_pooled is res2_ols + + res2_ols = mod2.res_pooled # TODO: BUG: requires call to _fit_ols + + # fitting once is the same as OLS + # note: I need to create new instance, otherwise it continuous fitting + mod1 = ShortPanelGLS(y, dgp.exog, dgp.groups) + res1 = mod1.fit_iterative(1) + + assert_almost_equal(res1.params, res2_ols.params, decimal=13) + assert_almost_equal(res1.bse, res2_ols.bse, decimal=13) + + res_ols = OLS(y, dgp.exog).fit() + assert_almost_equal(res1.params, res_ols.params, decimal=13) + assert_almost_equal(res1.bse, res_ols.bse, decimal=13) + + # compare with old version + mod_old = ShortPanelGLS2(y, dgp.exog, dgp.groups) + res_old = mod_old.fit() + + assert_almost_equal(res2.params, res_old.params, decimal=13) + assert_almost_equal(res2.bse, res_old.bse, decimal=13) + + mod5 = ShortPanelGLS(y, dgp.exog, dgp.groups) + res5 = mod5.fit_iterative(5) + + # make sure it's different + # npt.assert_array_less(0.009, em.maxabs(res5.bse, res2.bse)) + + cov_clu = sw.cov_cluster(mod2.res_pooled, dgp.groups.astype(int)) + clubse = se_cov(cov_clu) + pnwbse = se_cov(sw.cov_nw_panel(mod2.res_pooled, 4, mod2.group.groupidx)) + bser = np.vstack((res2.bse, res5.bse, clubse, pnwbse)) + bser_mean = np.mean(bser, axis=0) + + # cov_cluster close to robust and PanelGLS + # is up to 24% larger than mean of bser + # npt.assert_array_less(0, clubse / bser_mean - 1) + npt.assert_array_less(clubse / bser_mean - 1, 0.25) + # cov_nw_panel close to robust and PanelGLS + npt.assert_array_less(pnwbse / bser_mean - 1, 0.1) + # OLS underestimates bse, robust at least 60% larger + npt.assert_array_less(0.6, bser_mean / res_ols.bse - 1) + + # cov_hac_panel with uniform_kernel is the same as cov_cluster for balanced + # panel with full length kernel + # I fixe default correction to be equal + cov_uni = sw.cov_nw_panel( + mod2.res_pooled, + 4, + mod2.group.groupidx, + weights_func=sw.weights_uniform, + use_correction="c", + ) + assert_almost_equal(cov_uni, cov_clu, decimal=13) + + # without correction + cov_clu2 = sw.cov_cluster( + mod2.res_pooled, dgp.groups.astype(int), use_correction=False + ) + cov_uni2 = sw.cov_nw_panel( + mod2.res_pooled, + 4, + mod2.group.groupidx, + weights_func=sw.weights_uniform, + use_correction=False, + ) + assert_almost_equal(cov_uni2, cov_clu2, decimal=13) + + cov_white = sw.cov_white_simple(mod2.res_pooled) + cov_pnw0 = sw.cov_nw_panel( + mod2.res_pooled, 0, mod2.group.groupidx, use_correction="hac" + ) + assert_almost_equal(cov_pnw0, cov_white, decimal=13) diff --git a/shared/package-files/06/06fa9070cf676ade84535bc2fbdb2d80f026a64a0c82c2807bbee2795ac87484/ExpandUtils.h b/shared/package-files/06/06fa9070cf676ade84535bc2fbdb2d80f026a64a0c82c2807bbee2795ac87484/ExpandUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..82db1f8b6517cb9253dff2f25b13ab8a98d4bfd4 --- /dev/null +++ b/shared/package-files/06/06fa9070cf676ade84535bc2fbdb2d80f026a64a0c82c2807bbee2795ac87484/ExpandUtils.h @@ -0,0 +1,527 @@ +#pragma once + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace at { + +TORCH_API std::vector infer_size(IntArrayRef a, IntArrayRef b); +TORCH_API std::vector infer_size_symint( + SymIntArrayRef a, + SymIntArrayRef b); +TORCH_API DimVector infer_size_dimvector(IntArrayRef a, IntArrayRef b); +TORCH_API SymDimVector +infer_size_symdimvector(SymIntArrayRef a, SymIntArrayRef b); + +// Named type instead of a pair/tuple so that we can be sure to +// construct the vectors in place and get NRVO. +template +struct InferExpandGeometryResult { + Container sizes; + Container strides; + explicit InferExpandGeometryResult(size_t ndim) + : sizes(ndim), strides(ndim) {} + explicit InferExpandGeometryResult(IntArrayRef sizes_, size_t ndim) + : sizes(sizes_.begin(), sizes_.end()), strides(ndim) {} +}; + +TORCH_API std::tuple, std::vector> +inferExpandGeometry( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides, + IntArrayRef sizes); + +TORCH_API InferExpandGeometryResult inferExpandGeometry_dimvector( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides, + IntArrayRef sizes); + +TORCH_API std::vector infer_dense_strides( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides); + +// True if input shapes are expandable +// NOTE: infer_size did a similar check, please keep them sync if change is +// needed +inline bool are_expandable(IntArrayRef shape1, IntArrayRef shape2) { + size_t ndim1 = shape1.size(); + size_t ndim2 = shape2.size(); + size_t ndim = ndim1 < ndim2 ? ndim1 : ndim2; + + for (int64_t i = static_cast(ndim) - 1; i >= 0; --i) { + if (shape1[--ndim1] == shape2[--ndim2] || shape1[ndim1] == 1 || + shape2[ndim2] == 1) { + continue; + } + return false; + } + return true; +} + +// avoid copy-construction of Tensor by using a reference_wrapper. +inline void check_defined( + std::initializer_list> tensors, + const char* api_name) { + for (auto& t : tensors) { + if (!t.get().defined()) { + AT_ERROR(api_name, "(...) called with an undefined Tensor"); + } + } +} + +// NOTE [ ExpandUtils Borrowing ] +// +// Functions in ExpandUtils return `c10::MaybeOwned` because +// expansion may not actually be needed, in which case we can improve +// efficiency by returning +// `c10::MaybeOwned::borrowed(to_expand)`. However, this means +// that you need to be careful: the returned `c10::MaybeOwned` +// must not outlive the original `Tensor` object that `to_expand` +// referred to! The deleted rvalue reference overloads of these +// functions help with this by preventing trivial use of a temporary +// resulting from a function call, but it is still possible to make a +// mistake. + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + const Tensor& to_expand) { + if (tensor.sym_sizes().equals(to_expand.sym_sizes())) { + return c10::MaybeOwned::borrowed(to_expand); + } + return c10::MaybeOwned::owned( + to_expand.expand_symint(tensor.sym_sizes())); +} + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + Tensor&& to_expand) = delete; + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + const Tensor& to_expand, + const char* api_name) { + check_defined({tensor, to_expand}, api_name); + return expand_inplace(tensor, to_expand); +} + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + Tensor&& to_expand, + const char* api_name) = delete; + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + const Tensor& to_expand2) { + if (tensor.sizes().equals(to_expand1.sizes()) && + tensor.sizes().equals((to_expand2.sizes()))) { + return std::make_tuple( + c10::MaybeOwned::borrowed(to_expand1), + c10::MaybeOwned::borrowed(to_expand2)); + } + + return std::make_tuple( + c10::MaybeOwned::owned(to_expand1.expand(tensor.sizes())), + c10::MaybeOwned::owned(to_expand2.expand(tensor.sizes()))); +} + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + Tensor&& to_expand1, + const Tensor& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + Tensor&& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace(const Tensor& tensor, Tensor&& to_expand1, Tensor&& to_expand2) = + delete; + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + const Tensor& to_expand2, + const char* api_name) { + check_defined({tensor, to_expand1, to_expand2}, api_name); + return expand_inplace(tensor, to_expand1, to_expand2); +} + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + Tensor&& to_expand1, + const Tensor& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + Tensor&& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; + +// See NOTE [ ExpandUtils Borrowing ] above for `MaybeOwned` explanation. +inline std::tuple, c10::MaybeOwned> +expand_outplace(const Tensor& to_expand1, const Tensor& to_expand2) { + auto s1 = to_expand1.sym_sizes(); + auto s2 = to_expand2.sym_sizes(); + if (s1.equals(s2)) { + return std::make_tuple( + c10::MaybeOwned::borrowed(to_expand1), + c10::MaybeOwned::borrowed(to_expand2)); + } + + auto expanded_size = infer_size_symdimvector(s1, s2); + return std::make_tuple( + c10::MaybeOwned::owned(to_expand1.expand_symint(expanded_size)), + c10::MaybeOwned::owned(to_expand2.expand_symint(expanded_size))); +} + +inline std::tuple, c10::MaybeOwned> +expand_outplace(Tensor&& to_expand1, const Tensor& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace(const Tensor& to_expand1, Tensor&& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace(Tensor&& to_expand1, Tensor&& to_expand2) = delete; + +inline std::tuple, c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + const char* api_name) { + check_defined({to_expand1, to_expand2}, api_name); + return expand_outplace(to_expand1, to_expand2); +} + +inline std::tuple, c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3) { + if (to_expand1.sizes().equals(to_expand2.sizes()) && + to_expand1.sizes().equals(to_expand3.sizes())) { + return std::make_tuple( + c10::MaybeOwned::borrowed(to_expand1), + c10::MaybeOwned::borrowed(to_expand2), + c10::MaybeOwned::borrowed(to_expand3)); + } + + auto expanded_size12 = + infer_size_dimvector(to_expand1.sizes(), to_expand2.sizes()); + auto expanded_size = + infer_size_dimvector(expanded_size12, to_expand3.sizes()); + return std::make_tuple( + c10::MaybeOwned::owned(to_expand1.expand(expanded_size)), + c10::MaybeOwned::owned(to_expand2.expand(expanded_size)), + c10::MaybeOwned::owned(to_expand3.expand(expanded_size))); +} + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + Tensor&& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace(Tensor&& to_expand1, Tensor&& to_expand2, Tensor&& to_expand3) = + delete; + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3, + const char* api_name) { + check_defined({to_expand1, to_expand2, to_expand3}, api_name); + return expand_outplace(to_expand1, to_expand2, to_expand3); +} + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; + +inline c10::MaybeOwned expand_size( + const Tensor& to_expand, + IntArrayRef sizes) { + if (to_expand.sizes().equals(sizes)) { + return c10::MaybeOwned::borrowed(to_expand); + } + + return c10::MaybeOwned::owned(to_expand.expand(sizes)); +} + +inline c10::MaybeOwned expand_size( + Tensor&& to_expand, + IntArrayRef sizes) = delete; + +inline c10::MaybeOwned expand_size( + const Tensor& to_expand, + IntArrayRef sizes, + const char* api_name) { + check_defined({to_expand}, api_name); + return expand_size(to_expand, sizes); +} + +inline c10::MaybeOwned expand_size( + Tensor&& to_expand, + IntArrayRef sizes, + const char* api_name) = delete; + +inline std::vector expand_outplace(TensorList to_expand) { + // expands a list of Tensors; ignores undefined (null) tensors + bool first = true; + DimVector sizes; + for (const auto i : c10::irange(to_expand.size())) { + if (!to_expand[i].defined()) { + continue; + } else if (first) { + sizes = to_expand[i].sizes(); + first = false; + } else { + sizes = infer_size_dimvector(sizes, to_expand[i].sizes()); + } + } + + std::vector result(to_expand.size()); + for (const auto i : c10::irange(to_expand.size())) { + if (!to_expand[i].defined()) { + continue; + } else if (to_expand[i].sizes().equals(sizes)) { + result[i] = to_expand[i]; + } else { + result[i] = to_expand[i].expand(sizes); + } + } + return result; +} + +template +inline Tensor _sum_to( + Tensor tensor, + const c10::ArrayRef shape, + bool always_return_non_view = false) { + if (shape.size() == 0) { + return tensor.sum(); + } + + auto sizes = at::symint::sizes(tensor); + c10::SmallVector reduce_dims; + const int64_t leading_dims = sizes.size() - shape.size(); + for (const auto i : c10::irange(leading_dims)) { + reduce_dims.push_back(i); + } + for (int64_t i = leading_dims; i < static_cast(sizes.size()); ++i) { + if (shape[i - leading_dims] == 1 && sizes[i] != 1) { + reduce_dims.push_back(i); + } + } + + if (!reduce_dims.empty()) { + tensor = tensor.sum(reduce_dims, /*keepdim=*/true); + } + + if (always_return_non_view) { + // This is only actually used by the functionalization pass. + // We want to be able to guarantee that this function doesn't return a view + // of the input. + return leading_dims > 0 ? at::symint::view_copy(tensor, shape) + : tensor.clone(); + } else { + return leading_dims > 0 ? at::symint::view(tensor, shape) : tensor; + } +} + +inline Tensor sum_to( + Tensor tensor, + const c10::SymIntArrayRef shape, + bool always_return_non_view = false) { + return _sum_to(std::move(tensor), shape, always_return_non_view); +} + +// Sums `tensor` repeatedly to produce a tensor of shape `shape`. +// Precondition: is_expandable_to(shape, tensor.sizes()) must be true +inline Tensor sum_to( + Tensor tensor, + const IntArrayRef shape, + bool always_return_non_view = false) { + return _sum_to(std::move(tensor), shape, always_return_non_view); +} + +static inline bool is_expandable_to( + SymIntArrayRef shape, + c10::SymIntArrayRef desired) { + size_t ndim = shape.size(); + size_t target_dim = desired.size(); + if (ndim > target_dim) { + return false; + } + for (const auto i : c10::irange(ndim)) { + const auto& size = shape[ndim - i - 1]; + const auto& target = desired[target_dim - i - 1]; + if (size != target && size != 1) { + return false; + } + } + return true; +} + +static inline bool is_expandable_to(IntArrayRef shape, IntArrayRef desired) { + auto sym_shape = c10::SymIntArrayRef( + reinterpret_cast(shape.data()), shape.size()); + auto sym_desired = c10::SymIntArrayRef( + reinterpret_cast(desired.data()), desired.size()); + return is_expandable_to(sym_shape, sym_desired); +} + +} // namespace at diff --git a/shared/package-files/06/06fdaf8c6162d41911403a8a68d81e4e013184a34a9a2bad0bf9db88a934ff89/hp2397 b/shared/package-files/06/06fdaf8c6162d41911403a8a68d81e4e013184a34a9a2bad0bf9db88a934ff89/hp2397 new file mode 100644 index 0000000000000000000000000000000000000000..70ea75de59c7d50e6776d9b677fef950a18046ea Binary files /dev/null and b/shared/package-files/06/06fdaf8c6162d41911403a8a68d81e4e013184a34a9a2bad0bf9db88a934ff89/hp2397 differ diff --git a/shared/package-files/06/06fdaf8c6162d41911403a8a68d81e4e013184a34a9a2bad0bf9db88a934ff89/hp2397a b/shared/package-files/06/06fdaf8c6162d41911403a8a68d81e4e013184a34a9a2bad0bf9db88a934ff89/hp2397a new file mode 100644 index 0000000000000000000000000000000000000000..70ea75de59c7d50e6776d9b677fef950a18046ea Binary files /dev/null and b/shared/package-files/06/06fdaf8c6162d41911403a8a68d81e4e013184a34a9a2bad0bf9db88a934ff89/hp2397a differ diff --git a/shared/package-files/06/06feb038863e48f6227e5eaba30364824da21277ec5163ecd0fd7338533cefd9/cudnn_convolution_relu.h b/shared/package-files/06/06feb038863e48f6227e5eaba30364824da21277ec5163ecd0fd7338533cefd9/cudnn_convolution_relu.h new file mode 100644 index 0000000000000000000000000000000000000000..874f8b146d77e2ff2cf921680ef3ee115708924d --- /dev/null +++ b/shared/package-files/06/06feb038863e48f6227e5eaba30364824da21277ec5163ecd0fd7338533cefd9/cudnn_convolution_relu.h @@ -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::cudnn_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor +inline at::Tensor cudnn_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) { + return at::_ops::cudnn_convolution_relu::call(self, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups); +} +namespace symint { + template ::value>> + at::Tensor cudnn_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) { + return at::_ops::cudnn_convolution_relu::call(self, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups); + } +} + +// aten::cudnn_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor +inline at::Tensor cudnn_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) { + return at::_ops::cudnn_convolution_relu::call(self, weight, bias, stride, padding, dilation, groups); +} +namespace symint { + template ::value>> + at::Tensor cudnn_convolution_relu(const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::cudnn_convolution_relu::call(self, weight, bias, stride, padding, dilation, groups); + } +} + +// aten::cudnn_convolution_relu.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); + } +} + +// aten::cudnn_convolution_relu.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_relu_outf(const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_relu_outf(const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); + } +} + +// aten::cudnn_convolution_relu.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_relu_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, stride, padding, dilation, groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, stride, padding, dilation, groups, out); + } +} + +// aten::cudnn_convolution_relu.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_relu_symint_outf(const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, stride, padding, dilation, groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_relu_outf(const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_relu_out::call(self, weight, bias, stride, padding, dilation, groups, out); + } +} + +} diff --git a/shared/package-files/0b/0b0054161e1f225245e0a9bcd1aa45787f6c3d5062fb738f4ce9f1a8abde6794/_axes.py b/shared/package-files/0b/0b0054161e1f225245e0a9bcd1aa45787f6c3d5062fb738f4ce9f1a8abde6794/_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..9d419430b088879b8d0ea439a341c88bc5c8ebc8 --- /dev/null +++ b/shared/package-files/0b/0b0054161e1f225245e0a9bcd1aa45787f6c3d5062fb738f4ce9f1a8abde6794/_axes.py @@ -0,0 +1,8871 @@ +import functools +import itertools +import logging +import math +from numbers import Integral, Number, Real + +import re +import numpy as np + +import matplotlib as mpl +import matplotlib.category # Register category unit converter as side effect. +import matplotlib.cbook as cbook +import matplotlib.collections as mcoll +import matplotlib.colorizer as mcolorizer +import matplotlib.colors as mcolors +import matplotlib.contour as mcontour +import matplotlib.dates # noqa: F401, Register date unit converter as side effect. +import matplotlib.image as mimage +import matplotlib.inset as minset +import matplotlib.legend as mlegend +import matplotlib.lines as mlines +import matplotlib.markers as mmarkers +import matplotlib.mlab as mlab +import matplotlib.patches as mpatches +import matplotlib.path as mpath +import matplotlib.quiver as mquiver +import matplotlib.stackplot as mstack +import matplotlib.streamplot as mstream +import matplotlib.table as mtable +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms +import matplotlib.tri as mtri +import matplotlib.units as munits +from matplotlib import _api, _docstring, _preprocess_data +from matplotlib.axes._base import ( + _AxesBase, _TransformedBoundsLocator, _process_plot_format) +from matplotlib.axes._secondary_axes import SecondaryAxis +from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer +from matplotlib.transforms import _ScaledRotation + +_log = logging.getLogger(__name__) + + +# The axes module contains all the wrappers to plotting functions. +# All the other methods should go in the _AxesBase class. + + +def _make_axes_method(func): + """ + Patch the qualname for functions that are directly added to Axes. + + Some Axes functionality is defined in functions in other submodules. + These are simply added as attributes to Axes. As a result, their + ``__qualname__`` is e.g. only "table" and not "Axes.table". This + function fixes that. + + Note that the function itself is patched, so that + ``matplotlib.table.table.__qualname__` will also show "Axes.table". + However, since these functions are not intended to be standalone, + this is bearable. + """ + func.__qualname__ = f"Axes.{func.__name__}" + return func + + +@_docstring.interpd +class Axes(_AxesBase): + """ + An Axes object encapsulates all the elements of an individual (sub-)plot in + a figure. + + It contains most of the (sub-)plot elements: `~.axis.Axis`, + `~.axis.Tick`, `~.lines.Line2D`, `~.text.Text`, `~.patches.Polygon`, etc., + and sets the coordinate system. + + Like all visible elements in a figure, Axes is an `.Artist` subclass. + + The `Axes` instance supports callbacks through a callbacks attribute which + is a `~.cbook.CallbackRegistry` instance. The events you can connect to + are 'xlim_changed' and 'ylim_changed' and the callback will be called with + func(*ax*) where *ax* is the `Axes` instance. + + .. note:: + + As a user, you do not instantiate Axes directly, but use Axes creation + methods instead; e.g. from `.pyplot` or `.Figure`: + `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` or `.Figure.add_axes`. + + """ + ### Labelling, legend and texts + + def get_title(self, loc="center"): + """ + Get an Axes title. + + Get one of the three available Axes titles. The available titles + are positioned above the Axes in the center, flush with the left + edge, and flush with the right edge. + + Parameters + ---------- + loc : {'center', 'left', 'right'}, str, default: 'center' + Which title to return. + + Returns + ------- + str + The title text string. + + """ + titles = {'left': self._left_title, + 'center': self.title, + 'right': self._right_title} + title = _api.check_getitem(titles, loc=loc.lower()) + return title.get_text() + + def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, + **kwargs): + """ + Set a title for the Axes. + + Set one of the three available Axes titles. The available titles + are positioned above the Axes in the center, flush with the left + edge, and flush with the right edge. + + Parameters + ---------- + label : str + Text to use for the title + + fontdict : dict + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``set_title(..., **fontdict)``. + + A dictionary controlling the appearance of the title text, + the default *fontdict* is:: + + {'fontsize': rcParams['axes.titlesize'], + 'fontweight': rcParams['axes.titleweight'], + 'color': rcParams['axes.titlecolor'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc} + + loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation` + Which title to set. + + y : float, default: :rc:`axes.titley` + Vertical Axes location for the title (1.0 is the top). If + None (the default) and :rc:`axes.titley` is also None, y is + determined automatically to avoid decorators on the Axes. + + pad : float, default: :rc:`axes.titlepad` + The offset of the title from the top of the Axes, in points. + + Returns + ------- + `.Text` + The matplotlib text instance representing the title + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + Other keyword arguments are text properties, see `.Text` for a list + of valid text properties. + """ + if loc is None: + loc = mpl.rcParams['axes.titlelocation'] + + if y is None: + y = mpl.rcParams['axes.titley'] + if y is None: + y = 1.0 + else: + self._autotitlepos = False + kwargs['y'] = y + + titles = {'left': self._left_title, + 'center': self.title, + 'right': self._right_title} + title = _api.check_getitem(titles, loc=loc.lower()) + default = { + 'fontsize': mpl.rcParams['axes.titlesize'], + 'fontweight': mpl.rcParams['axes.titleweight'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc.lower()} + titlecolor = mpl.rcParams['axes.titlecolor'] + if not cbook._str_lower_equal(titlecolor, 'auto'): + default["color"] = titlecolor + if pad is None: + pad = mpl.rcParams['axes.titlepad'] + self._set_title_offset_trans(float(pad)) + title.set_text(label) + title.update(default) + if fontdict is not None: + title.update(fontdict) + title._internal_update(kwargs) + return title + + def get_legend_handles_labels(self, legend_handler_map=None): + """ + Return handles and labels for legend + + ``ax.legend()`` is equivalent to :: + + h, l = ax.get_legend_handles_labels() + ax.legend(h, l) + """ + # pass through to legend. + handles, labels = mlegend._get_legend_handles_labels( + [self], legend_handler_map) + return handles, labels + + @_docstring.interpd + def legend(self, *args, **kwargs): + """ + Place a legend on the Axes. + + Call signatures:: + + legend() + legend(handles, labels) + legend(handles=handles) + legend(labels) + + The call signatures correspond to the following different ways to use + this method: + + **1. Automatic detection of elements to be shown in the legend** + + The elements to be added to the legend are automatically determined, + when you do not pass in any extra arguments. + + In this case, the labels are taken from the artist. You can specify + them either at artist creation or by calling the + :meth:`~.Artist.set_label` method on the artist:: + + ax.plot([1, 2, 3], label='Inline label') + ax.legend() + + or:: + + line, = ax.plot([1, 2, 3]) + line.set_label('Label via method') + ax.legend() + + .. note:: + Specific artists can be excluded from the automatic legend element + selection by using a label starting with an underscore, "_". + A string starting with an underscore is the default label for all + artists, so calling `.Axes.legend` without any arguments and + without setting the labels manually will result in a ``UserWarning`` + and an empty legend being drawn. + + + **2. Explicitly listing the artists and labels in the legend** + + For full control of which artists have a legend entry, it is possible + to pass an iterable of legend artists followed by an iterable of + legend labels respectively:: + + ax.legend([line1, line2, line3], ['label1', 'label2', 'label3']) + + + **3. Explicitly listing the artists in the legend** + + This is similar to 2, but the labels are taken from the artists' + label properties. Example:: + + line1, = ax.plot([1, 2, 3], label='label1') + line2, = ax.plot([1, 2, 3], label='label2') + ax.legend(handles=[line1, line2]) + + + **4. Labeling existing plot elements** + + .. admonition:: Discouraged + + This call signature is discouraged, because the relation between + plot elements and labels is only implicit by their order and can + easily be mixed up. + + To make a legend for all artists on an Axes, call this function with + an iterable of strings, one for each legend item. For example:: + + ax.plot([1, 2, 3]) + ax.plot([5, 6, 7]) + ax.legend(['First line', 'Second line']) + + + Parameters + ---------- + handles : list of (`.Artist` or tuple of `.Artist`), optional + A list of Artists (lines, patches) to be added to the legend. + Use this together with *labels*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + The length of handles and labels should be the same in this + case. If they are not, they are truncated to the smaller length. + + If an entry contains a tuple, then the legend handler for all Artists in the + tuple will be placed alongside a single label. + + labels : list of str, optional + A list of labels to show next to the artists. + Use this together with *handles*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + Returns + ------- + `~matplotlib.legend.Legend` + + Other Parameters + ---------------- + %(_legend_kw_axes)s + + See Also + -------- + .Figure.legend + + Notes + ----- + Some artists are not supported by this function. See + :ref:`legend_guide` for details. + + Examples + -------- + .. plot:: gallery/text_labels_and_annotations/legend.py + """ + handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs) + self.legend_ = mlegend.Legend(self, handles, labels, **kwargs) + self.legend_._remove_method = self._remove_legend + return self.legend_ + + def _remove_legend(self, legend): + self.legend_ = None + + def inset_axes(self, bounds, *, transform=None, zorder=5, **kwargs): + """ + Add a child inset Axes to this existing Axes. + + + Parameters + ---------- + bounds : [x0, y0, width, height] + Lower-left corner of inset Axes, and its width and height. + + transform : `.Transform` + Defaults to `ax.transAxes`, i.e. the units of *rect* are in + Axes-relative coordinates. + + projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ +'polar', 'rectilinear', str}, optional + The projection type of the inset `~.axes.Axes`. *str* is the name + of a custom projection, see `~matplotlib.projections`. The default + None results in a 'rectilinear' projection. + + polar : bool, default: False + If True, equivalent to projection='polar'. + + axes_class : subclass type of `~.axes.Axes`, optional + The `.axes.Axes` subclass that is instantiated. This parameter + is incompatible with *projection* and *polar*. See + :ref:`axisartist_users-guide-index` for examples. + + zorder : number + Defaults to 5 (same as `.Axes.legend`). Adjust higher or lower + to change whether it is above or below data plotted on the + parent Axes. + + **kwargs + Other keyword arguments are passed on to the inset Axes class. + + Returns + ------- + ax + The created `~.axes.Axes` instance. + + Examples + -------- + This example makes two inset Axes, the first is in Axes-relative + coordinates, and the second in data-coordinates:: + + fig, ax = plt.subplots() + ax.plot(range(10)) + axin1 = ax.inset_axes([0.8, 0.1, 0.15, 0.15]) + axin2 = ax.inset_axes( + [5, 7, 2.3, 2.3], transform=ax.transData) + + """ + if transform is None: + transform = self.transAxes + kwargs.setdefault('label', 'inset_axes') + + # This puts the rectangle into figure-relative coordinates. + inset_locator = _TransformedBoundsLocator(bounds, transform) + bounds = inset_locator(self, None).bounds + fig = self.get_figure(root=False) + projection_class, pkw = fig._process_projection_requirements(**kwargs) + inset_ax = projection_class(fig, bounds, zorder=zorder, **pkw) + + # this locator lets the axes move if in data coordinates. + # it gets called in `ax.apply_aspect() (of all places) + inset_ax.set_axes_locator(inset_locator) + + self.add_child_axes(inset_ax) + + return inset_ax + + @_docstring.interpd + def indicate_inset(self, bounds=None, inset_ax=None, *, transform=None, + facecolor='none', edgecolor='0.5', alpha=0.5, + zorder=None, **kwargs): + """ + Add an inset indicator to the Axes. This is a rectangle on the plot + at the position indicated by *bounds* that optionally has lines that + connect the rectangle to an inset Axes (`.Axes.inset_axes`). + + Warnings + -------- + This method is experimental as of 3.0, and the API may change. + + Parameters + ---------- + bounds : [x0, y0, width, height], optional + Lower-left corner of rectangle to be marked, and its width + and height. If not set, the bounds will be calculated from the + data limits of *inset_ax*, which must be supplied. + + inset_ax : `.Axes`, optional + An optional inset Axes to draw connecting lines to. Two lines are + drawn connecting the indicator box to the inset Axes on corners + chosen so as to not overlap with the indicator box. + + transform : `.Transform` + Transform for the rectangle coordinates. Defaults to + ``ax.transAxes``, i.e. the units of *rect* are in Axes-relative + coordinates. + + facecolor : :mpltype:`color`, default: 'none' + Facecolor of the rectangle. + + edgecolor : :mpltype:`color`, default: '0.5' + Color of the rectangle and color of the connecting lines. + + alpha : float or None, default: 0.5 + Transparency of the rectangle and connector lines. If not + ``None``, this overrides any alpha value included in the + *facecolor* and *edgecolor* parameters. + + zorder : float, default: 4.99 + Drawing order of the rectangle and connector lines. The default, + 4.99, is just below the default level of inset Axes. + + **kwargs + Other keyword arguments are passed on to the `.Rectangle` patch: + + %(Rectangle:kwdoc)s + + Returns + ------- + inset_indicator : `.inset.InsetIndicator` + An artist which contains + + inset_indicator.rectangle : `.Rectangle` + The indicator frame. + + inset_indicator.connectors : 4-tuple of `.patches.ConnectionPatch` + The four connector lines connecting to (lower_left, upper_left, + lower_right upper_right) corners of *inset_ax*. Two lines are + set with visibility to *False*, but the user can set the + visibility to True if the automatic choice is not deemed correct. + + .. versionchanged:: 3.10 + Previously the rectangle and connectors tuple were returned. + """ + # to make the Axes connectors work, we need to apply the aspect to + # the parent Axes. + self.apply_aspect() + + if transform is None: + transform = self.transData + kwargs.setdefault('label', '_indicate_inset') + + indicator_patch = minset.InsetIndicator( + bounds, inset_ax=inset_ax, + facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, + zorder=zorder, transform=transform, **kwargs) + self.add_artist(indicator_patch) + + return indicator_patch + + def indicate_inset_zoom(self, inset_ax, **kwargs): + """ + Add an inset indicator rectangle to the Axes based on the axis + limits for an *inset_ax* and draw connectors between *inset_ax* + and the rectangle. + + Warnings + -------- + This method is experimental as of 3.0, and the API may change. + + Parameters + ---------- + inset_ax : `.Axes` + Inset Axes to draw connecting lines to. Two lines are + drawn connecting the indicator box to the inset Axes on corners + chosen so as to not overlap with the indicator box. + + **kwargs + Other keyword arguments are passed on to `.Axes.indicate_inset` + + Returns + ------- + inset_indicator : `.inset.InsetIndicator` + An artist which contains + + inset_indicator.rectangle : `.Rectangle` + The indicator frame. + + inset_indicator.connectors : 4-tuple of `.patches.ConnectionPatch` + The four connector lines connecting to (lower_left, upper_left, + lower_right upper_right) corners of *inset_ax*. Two lines are + set with visibility to *False*, but the user can set the + visibility to True if the automatic choice is not deemed correct. + + .. versionchanged:: 3.10 + Previously the rectangle and connectors tuple were returned. + """ + + return self.indicate_inset(None, inset_ax, **kwargs) + + @_docstring.interpd + def secondary_xaxis(self, location, functions=None, *, transform=None, **kwargs): + """ + Add a second x-axis to this `~.axes.Axes`. + + For example if we want to have a second scale for the data plotted on + the xaxis. + + %(_secax_docstring)s + + Examples + -------- + The main axis shows frequency, and the secondary axis shows period. + + .. plot:: + + fig, ax = plt.subplots() + ax.loglog(range(1, 360, 5), range(1, 360, 5)) + ax.set_xlabel('frequency [Hz]') + + def invert(x): + # 1/x with special treatment of x == 0 + x = np.array(x).astype(float) + near_zero = np.isclose(x, 0) + x[near_zero] = np.inf + x[~near_zero] = 1 / x[~near_zero] + return x + + # the inverse of 1/x is itself + secax = ax.secondary_xaxis('top', functions=(invert, invert)) + secax.set_xlabel('Period [s]') + plt.show() + + To add a secondary axis relative to your data, you can pass a transform + to the new axis. + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(0, 5), range(-1, 4)) + + # Pass 'ax.transData' as a transform to place the axis + # relative to your data at y=0 + secax = ax.secondary_xaxis(0, transform=ax.transData) + """ + if not (location in ['top', 'bottom'] or isinstance(location, Real)): + raise ValueError('secondary_xaxis location must be either ' + 'a float or "top"/"bottom"') + + secondary_ax = SecondaryAxis(self, 'x', location, functions, + transform, **kwargs) + self.add_child_axes(secondary_ax) + return secondary_ax + + @_docstring.interpd + def secondary_yaxis(self, location, functions=None, *, transform=None, **kwargs): + """ + Add a second y-axis to this `~.axes.Axes`. + + For example if we want to have a second scale for the data plotted on + the yaxis. + + %(_secax_docstring)s + + Examples + -------- + Add a secondary Axes that converts from radians to degrees + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(1, 360, 5), range(1, 360, 5)) + ax.set_ylabel('degrees') + secax = ax.secondary_yaxis('right', functions=(np.deg2rad, + np.rad2deg)) + secax.set_ylabel('radians') + + To add a secondary axis relative to your data, you can pass a transform + to the new axis. + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(0, 5), range(-1, 4)) + + # Pass 'ax.transData' as a transform to place the axis + # relative to your data at x=3 + secax = ax.secondary_yaxis(3, transform=ax.transData) + """ + if not (location in ['left', 'right'] or isinstance(location, Real)): + raise ValueError('secondary_yaxis location must be either ' + 'a float or "left"/"right"') + + secondary_ax = SecondaryAxis(self, 'y', location, functions, + transform, **kwargs) + self.add_child_axes(secondary_ax) + return secondary_ax + + @_docstring.interpd + def text(self, x, y, s, fontdict=None, **kwargs): + """ + Add text to the Axes. + + Add the text *s* to the Axes at location *x*, *y* in data coordinates, + with a default ``horizontalalignment`` on the ``left`` and + ``verticalalignment`` at the ``baseline``. See + :doc:`/gallery/text_labels_and_annotations/text_alignment`. + + Parameters + ---------- + x, y : float + The position to place the text. By default, this is in data + coordinates. The coordinate system can be changed using the + *transform* parameter. + + s : str + The text. + + fontdict : dict, default: None + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``text(..., **fontdict)``. + + A dictionary to override the default text properties. If fontdict + is None, the defaults are determined by `.rcParams`. + + Returns + ------- + `.Text` + The created `.Text` instance. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties. + Other miscellaneous text parameters. + + %(Text:kwdoc)s + + Examples + -------- + Individual keyword arguments can be used to override any given + parameter:: + + >>> text(x, y, s, fontsize=12) + + The default transform specifies that text is in data coords, + alternatively, you can specify text in axis coords ((0, 0) is + lower-left and (1, 1) is upper-right). The example below places + text in the center of the Axes:: + + >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center', + ... verticalalignment='center', transform=ax.transAxes) + + You can put a rectangular box around the text instance (e.g., to + set a background color) by using the keyword *bbox*. *bbox* is + a dictionary of `~matplotlib.patches.Rectangle` + properties. For example:: + + >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5)) + """ + effective_kwargs = { + 'verticalalignment': 'baseline', + 'horizontalalignment': 'left', + 'transform': self.transData, + 'clip_on': False, + **(fontdict if fontdict is not None else {}), + **kwargs, + } + t = mtext.Text(x, y, text=s, **effective_kwargs) + if t.get_clip_path() is None: + t.set_clip_path(self.patch) + self._add_text(t) + return t + + @_docstring.interpd + def annotate(self, text, xy, xytext=None, xycoords='data', textcoords=None, + arrowprops=None, annotation_clip=None, **kwargs): + # Signature must match Annotation. This is verified in + # test_annotate_signature(). + a = mtext.Annotation(text, xy, xytext=xytext, xycoords=xycoords, + textcoords=textcoords, arrowprops=arrowprops, + annotation_clip=annotation_clip, **kwargs) + a.set_transform(mtransforms.IdentityTransform()) + if kwargs.get('clip_on', False) and a.get_clip_path() is None: + a.set_clip_path(self.patch) + self._add_text(a) + return a + annotate.__doc__ = mtext.Annotation.__init__.__doc__ + #### Lines and spans + + @_docstring.interpd + def axhline(self, y=0, xmin=0, xmax=1, **kwargs): + """ + Add a horizontal line spanning the whole or fraction of the Axes. + + Note: If you want to set x-limits in data coordinates, use + `~.Axes.hlines` instead. + + Parameters + ---------- + y : float, default: 0 + y position in :ref:`data coordinates `. + + xmin : float, default: 0 + The start x-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the far left of the plot, + 1 the far right of the plot. + + xmax : float, default: 1 + The end x-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the far left of the plot, + 1 the far right of the plot. + + Returns + ------- + `~matplotlib.lines.Line2D` + A `.Line2D` specified via two points ``(xmin, y)``, ``(xmax, y)``. + Its transform is set such that *x* is in + :ref:`axes coordinates ` and *y* is in + :ref:`data coordinates `. + + This is still a generic line and the horizontal character is only + realized through using identical *y* values for both points. Thus, + if you want to change the *y* value later, you have to provide two + values ``line.set_ydata([3, 3])``. + + Other Parameters + ---------------- + **kwargs + Valid keyword arguments are `.Line2D` properties, except for + 'transform': + + %(Line2D:kwdoc)s + + See Also + -------- + hlines : Add horizontal lines in data coordinates. + axhspan : Add a horizontal span (rectangle) across the axis. + axline : Add a line with an arbitrary slope. + + Examples + -------- + * draw a thick red hline at 'y' = 0 that spans the xrange:: + + >>> axhline(linewidth=4, color='r') + + * draw a default hline at 'y' = 1 that spans the xrange:: + + >>> axhline(y=1) + + * draw a default hline at 'y' = .5 that spans the middle half of + the xrange:: + + >>> axhline(y=.5, xmin=0.25, xmax=0.75) + """ + self._check_no_units([xmin, xmax], ['xmin', 'xmax']) + if "transform" in kwargs: + raise ValueError("'transform' is not allowed as a keyword " + "argument; axhline generates its own transform.") + ymin, ymax = self.get_ybound() + + # Strip away the units for comparison with non-unitized bounds. + yy, = self._process_unit_info([("y", y)], kwargs) + scaley = (yy < ymin) or (yy > ymax) + + trans = self.get_yaxis_transform(which='grid') + l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs) + self.add_line(l) + l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + if scaley: + self._request_autoscale_view("y") + return l + + @_docstring.interpd + def axvline(self, x=0, ymin=0, ymax=1, **kwargs): + """ + Add a vertical line spanning the whole or fraction of the Axes. + + Note: If you want to set y-limits in data coordinates, use + `~.Axes.vlines` instead. + + Parameters + ---------- + x : float, default: 0 + x position in :ref:`data coordinates `. + + ymin : float, default: 0 + The start y-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the bottom of the plot, 1 the + top of the plot. + + ymax : float, default: 1 + The end y-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the bottom of the plot, 1 the + top of the plot. + + Returns + ------- + `~matplotlib.lines.Line2D` + A `.Line2D` specified via two points ``(x, ymin)``, ``(x, ymax)``. + Its transform is set such that *x* is in + :ref:`data coordinates ` and *y* is in + :ref:`axes coordinates `. + + This is still a generic line and the vertical character is only + realized through using identical *x* values for both points. Thus, + if you want to change the *x* value later, you have to provide two + values ``line.set_xdata([3, 3])``. + + Other Parameters + ---------------- + **kwargs + Valid keyword arguments are `.Line2D` properties, except for + 'transform': + + %(Line2D:kwdoc)s + + See Also + -------- + vlines : Add vertical lines in data coordinates. + axvspan : Add a vertical span (rectangle) across the axis. + axline : Add a line with an arbitrary slope. + + Examples + -------- + * draw a thick red vline at *x* = 0 that spans the yrange:: + + >>> axvline(linewidth=4, color='r') + + * draw a default vline at *x* = 1 that spans the yrange:: + + >>> axvline(x=1) + + * draw a default vline at *x* = .5 that spans the middle half of + the yrange:: + + >>> axvline(x=.5, ymin=0.25, ymax=0.75) + """ + self._check_no_units([ymin, ymax], ['ymin', 'ymax']) + if "transform" in kwargs: + raise ValueError("'transform' is not allowed as a keyword " + "argument; axvline generates its own transform.") + xmin, xmax = self.get_xbound() + + # Strip away the units for comparison with non-unitized bounds. + xx, = self._process_unit_info([("x", x)], kwargs) + scalex = (xx < xmin) or (xx > xmax) + + trans = self.get_xaxis_transform(which='grid') + l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs) + self.add_line(l) + l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + if scalex: + self._request_autoscale_view("x") + return l + + @staticmethod + def _check_no_units(vals, names): + # Helper method to check that vals are not unitized + for val, name in zip(vals, names): + if not munits._is_natively_supported(val): + raise ValueError(f"{name} must be a single scalar value, " + f"but got {val}") + + @_docstring.interpd + def axline(self, xy1, xy2=None, *, slope=None, **kwargs): + """ + Add an infinitely long straight line. + + The line can be defined either by two points *xy1* and *xy2*, or + by one point *xy1* and a *slope*. + + This draws a straight line "on the screen", regardless of the x and y + scales, and is thus also suitable for drawing exponential decays in + semilog plots, power laws in loglog plots, etc. However, *slope* + should only be used with linear scales; It has no clear meaning for + all other scales, and thus the behavior is undefined. Please specify + the line using the points *xy1*, *xy2* for non-linear scales. + + The *transform* keyword argument only applies to the points *xy1*, + *xy2*. The *slope* (if given) is always in data coordinates. This can + be used e.g. with ``ax.transAxes`` for drawing grid lines with a fixed + slope. + + Parameters + ---------- + xy1, xy2 : (float, float) + Points for the line to pass through. + Either *xy2* or *slope* has to be given. + slope : float, optional + The slope of the line. Either *xy2* or *slope* has to be given. + + Returns + ------- + `.AxLine` + + Other Parameters + ---------------- + **kwargs + Valid kwargs are `.Line2D` properties + + %(Line2D:kwdoc)s + + See Also + -------- + axhline : for horizontal lines + axvline : for vertical lines + + Examples + -------- + Draw a thick red line passing through (0, 0) and (1, 1):: + + >>> axline((0, 0), (1, 1), linewidth=4, color='r') + """ + if slope is not None and (self.get_xscale() != 'linear' or + self.get_yscale() != 'linear'): + raise TypeError("'slope' cannot be used with non-linear scales") + + datalim = [xy1] if xy2 is None else [xy1, xy2] + if "transform" in kwargs: + # if a transform is passed (i.e. line points not in data space), + # data limits should not be adjusted. + datalim = [] + + line = mlines.AxLine(xy1, xy2, slope, **kwargs) + # Like add_line, but correctly handling data limits. + self._set_artist_props(line) + if line.get_clip_path() is None: + line.set_clip_path(self.patch) + if not line.get_label(): + line.set_label(f"_child{len(self._children)}") + self._children.append(line) + line._remove_method = self._children.remove + self.update_datalim(datalim) + + self._request_autoscale_view() + return line + + @_docstring.interpd + def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs): + """ + Add a horizontal span (rectangle) across the Axes. + + The rectangle spans from *ymin* to *ymax* vertically, and, by default, + the whole x-axis horizontally. The x-span can be set using *xmin* + (default: 0) and *xmax* (default: 1) which are in axis units; e.g. + ``xmin = 0.5`` always refers to the middle of the x-axis regardless of + the limits set by `~.Axes.set_xlim`. + + Parameters + ---------- + ymin : float + Lower y-coordinate of the span, in data units. + ymax : float + Upper y-coordinate of the span, in data units. + xmin : float, default: 0 + Lower x-coordinate of the span, in x-axis (0-1) units. + xmax : float, default: 1 + Upper x-coordinate of the span, in x-axis (0-1) units. + + Returns + ------- + `~matplotlib.patches.Rectangle` + Horizontal span (rectangle) from (xmin, ymin) to (xmax, ymax). + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + axvspan : Add a vertical span across the Axes. + """ + # Strip units away. + self._check_no_units([xmin, xmax], ['xmin', 'xmax']) + (ymin, ymax), = self._process_unit_info([("y", [ymin, ymax])], kwargs) + + p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) + p.set_transform(self.get_yaxis_transform(which="grid")) + # For Rectangles and non-separable transforms, add_patch can be buggy + # and update the x limits even though it shouldn't do so for an + # yaxis_transformed patch, so undo that update. + ix = self.dataLim.intervalx.copy() + mx = self.dataLim.minposx + self.add_patch(p) + self.dataLim.intervalx = ix + self.dataLim.minposx = mx + p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + self._request_autoscale_view("y") + return p + + @_docstring.interpd + def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs): + """ + Add a vertical span (rectangle) across the Axes. + + The rectangle spans from *xmin* to *xmax* horizontally, and, by + default, the whole y-axis vertically. The y-span can be set using + *ymin* (default: 0) and *ymax* (default: 1) which are in axis units; + e.g. ``ymin = 0.5`` always refers to the middle of the y-axis + regardless of the limits set by `~.Axes.set_ylim`. + + Parameters + ---------- + xmin : float + Lower x-coordinate of the span, in data units. + xmax : float + Upper x-coordinate of the span, in data units. + ymin : float, default: 0 + Lower y-coordinate of the span, in y-axis units (0-1). + ymax : float, default: 1 + Upper y-coordinate of the span, in y-axis units (0-1). + + Returns + ------- + `~matplotlib.patches.Rectangle` + Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax). + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + axhspan : Add a horizontal span across the Axes. + + Examples + -------- + Draw a vertical, green, translucent rectangle from x = 1.25 to + x = 1.55 that spans the yrange of the Axes. + + >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5) + + """ + # Strip units away. + self._check_no_units([ymin, ymax], ['ymin', 'ymax']) + (xmin, xmax), = self._process_unit_info([("x", [xmin, xmax])], kwargs) + + p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) + p.set_transform(self.get_xaxis_transform(which="grid")) + # For Rectangles and non-separable transforms, add_patch can be buggy + # and update the y limits even though it shouldn't do so for an + # xaxis_transformed patch, so undo that update. + iy = self.dataLim.intervaly.copy() + my = self.dataLim.minposy + self.add_patch(p) + self.dataLim.intervaly = iy + self.dataLim.minposy = my + p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + self._request_autoscale_view("x") + return p + + @_api.make_keyword_only("3.10", "label") + @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], + label_namer="y") + def hlines(self, y, xmin, xmax, colors=None, linestyles='solid', + label='', **kwargs): + """ + Plot horizontal lines at each *y* from *xmin* to *xmax*. + + Parameters + ---------- + y : float or array-like + y-indexes where to plot the lines. + + xmin, xmax : float or array-like + Respective beginning and end of each line. If scalars are + provided, all lines will have the same length. + + colors : :mpltype:`color` or list of color , default: :rc:`lines.color` + + linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid' + + label : str, default: '' + + Returns + ------- + `~matplotlib.collections.LineCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.LineCollection` properties. + + See Also + -------- + vlines : vertical lines + axhline : horizontal line across the Axes + """ + + # We do the conversion first since not all unitized data is uniform + xmin, xmax, y = self._process_unit_info( + [("x", xmin), ("x", xmax), ("y", y)], kwargs) + + if not np.iterable(y): + y = [y] + if not np.iterable(xmin): + xmin = [xmin] + if not np.iterable(xmax): + xmax = [xmax] + + # Create and combine masked_arrays from input + y, xmin, xmax = cbook._combine_masks(y, xmin, xmax) + y = np.ravel(y) + xmin = np.ravel(xmin) + xmax = np.ravel(xmax) + + masked_verts = np.ma.empty((len(y), 2, 2)) + masked_verts[:, 0, 0] = xmin + masked_verts[:, 0, 1] = y + masked_verts[:, 1, 0] = xmax + masked_verts[:, 1, 1] = y + + lines = mcoll.LineCollection(masked_verts, colors=colors, + linestyles=linestyles, label=label) + self.add_collection(lines, autolim=False) + lines._internal_update(kwargs) + + if len(y) > 0: + # Extreme values of xmin/xmax/y. Using masked_verts here handles + # the case of y being a masked *object* array (as can be generated + # e.g. by errorbar()), which would make nanmin/nanmax stumble. + updatex = True + updatey = True + if self.name == "rectilinear": + datalim = lines.get_datalim(self.transData) + t = lines.get_transform() + updatex, updatey = t.contains_branch_seperately(self.transData) + minx = np.nanmin(datalim.xmin) + maxx = np.nanmax(datalim.xmax) + miny = np.nanmin(datalim.ymin) + maxy = np.nanmax(datalim.ymax) + else: + minx = np.nanmin(masked_verts[..., 0]) + maxx = np.nanmax(masked_verts[..., 0]) + miny = np.nanmin(masked_verts[..., 1]) + maxy = np.nanmax(masked_verts[..., 1]) + + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners, updatex, updatey) + self._request_autoscale_view() + return lines + + @_api.make_keyword_only("3.10", "label") + @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], + label_namer="x") + def vlines(self, x, ymin, ymax, colors=None, linestyles='solid', + label='', **kwargs): + """ + Plot vertical lines at each *x* from *ymin* to *ymax*. + + Parameters + ---------- + x : float or array-like + x-indexes where to plot the lines. + + ymin, ymax : float or array-like + Respective beginning and end of each line. If scalars are + provided, all lines will have the same length. + + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + + linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid' + + label : str, default: '' + + Returns + ------- + `~matplotlib.collections.LineCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.LineCollection` properties. + + See Also + -------- + hlines : horizontal lines + axvline : vertical line across the Axes + """ + + # We do the conversion first since not all unitized data is uniform + x, ymin, ymax = self._process_unit_info( + [("x", x), ("y", ymin), ("y", ymax)], kwargs) + + if not np.iterable(x): + x = [x] + if not np.iterable(ymin): + ymin = [ymin] + if not np.iterable(ymax): + ymax = [ymax] + + # Create and combine masked_arrays from input + x, ymin, ymax = cbook._combine_masks(x, ymin, ymax) + x = np.ravel(x) + ymin = np.ravel(ymin) + ymax = np.ravel(ymax) + + masked_verts = np.ma.empty((len(x), 2, 2)) + masked_verts[:, 0, 0] = x + masked_verts[:, 0, 1] = ymin + masked_verts[:, 1, 0] = x + masked_verts[:, 1, 1] = ymax + + lines = mcoll.LineCollection(masked_verts, colors=colors, + linestyles=linestyles, label=label) + self.add_collection(lines, autolim=False) + lines._internal_update(kwargs) + + if len(x) > 0: + # Extreme values of x/ymin/ymax. Using masked_verts here handles + # the case of x being a masked *object* array (as can be generated + # e.g. by errorbar()), which would make nanmin/nanmax stumble. + updatex = True + updatey = True + if self.name == "rectilinear": + datalim = lines.get_datalim(self.transData) + t = lines.get_transform() + updatex, updatey = t.contains_branch_seperately(self.transData) + minx = np.nanmin(datalim.xmin) + maxx = np.nanmax(datalim.xmax) + miny = np.nanmin(datalim.ymin) + maxy = np.nanmax(datalim.ymax) + else: + minx = np.nanmin(masked_verts[..., 0]) + maxx = np.nanmax(masked_verts[..., 0]) + miny = np.nanmin(masked_verts[..., 1]) + maxy = np.nanmax(masked_verts[..., 1]) + + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners, updatex, updatey) + self._request_autoscale_view() + return lines + + @_api.make_keyword_only("3.10", "orientation") + @_preprocess_data(replace_names=["positions", "lineoffsets", + "linelengths", "linewidths", + "colors", "linestyles"]) + @_docstring.interpd + def eventplot(self, positions, orientation='horizontal', lineoffsets=1, + linelengths=1, linewidths=None, colors=None, alpha=None, + linestyles='solid', **kwargs): + """ + Plot identical parallel lines at the given positions. + + This type of plot is commonly used in neuroscience for representing + neural events, where it is usually called a spike raster, dot raster, + or raster plot. + + However, it is useful in any situation where you wish to show the + timing or position of multiple sets of discrete events, such as the + arrival times of people to a business on each day of the month or the + date of hurricanes each year of the last century. + + Parameters + ---------- + positions : array-like or list of array-like + A 1D array-like defines the positions of one sequence of events. + + Multiple groups of events may be passed as a list of array-likes. + Each group can be styled independently by passing lists of values + to *lineoffsets*, *linelengths*, *linewidths*, *colors* and + *linestyles*. + + Note that *positions* can be a 2D array, but in practice different + event groups usually have different counts so that one will use a + list of different-length arrays rather than a 2D array. + + orientation : {'horizontal', 'vertical'}, default: 'horizontal' + The direction of the event sequence: + + - 'horizontal': the events are arranged horizontally. + The indicator lines are vertical. + - 'vertical': the events are arranged vertically. + The indicator lines are horizontal. + + lineoffsets : float or array-like, default: 1 + The offset of the center of the lines from the origin, in the + direction orthogonal to *orientation*. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linelengths : float or array-like, default: 1 + The total height of the lines (i.e. the lines stretches from + ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``). + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linewidths : float or array-like, default: :rc:`lines.linewidth` + The line width(s) of the event lines, in points. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + The color(s) of the event lines. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + alpha : float or array-like, default: 1 + The alpha blending value(s), between 0 (transparent) and 1 + (opaque). + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linestyles : str or tuple or list of such values, default: 'solid' + Default is 'solid'. Valid strings are ['solid', 'dashed', + 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples + should be of the form:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink + in points. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Other keyword arguments are line collection properties. See + `.LineCollection` for a list of the valid properties. + + Returns + ------- + list of `.EventCollection` + The `.EventCollection` that were added. + + Notes + ----- + For *linelengths*, *linewidths*, *colors*, *alpha* and *linestyles*, if + only a single value is given, that value is applied to all lines. If an + array-like is given, it must have the same length as *positions*, and + each value will be applied to the corresponding row of the array. + + Examples + -------- + .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py + """ + + lineoffsets, linelengths = self._process_unit_info( + [("y", lineoffsets), ("y", linelengths)], kwargs) + + # fix positions, noting that it can be a list of lists: + if not np.iterable(positions): + positions = [positions] + elif any(np.iterable(position) for position in positions): + positions = [np.asanyarray(position) for position in positions] + else: + positions = [np.asanyarray(positions)] + + poss = [] + for position in positions: + poss += self._process_unit_info([("x", position)], kwargs) + positions = poss + + # prevent 'singular' keys from **kwargs dict from overriding the effect + # of 'plural' keyword arguments (e.g. 'color' overriding 'colors') + colors = cbook._local_over_kwdict(colors, kwargs, 'color') + linewidths = cbook._local_over_kwdict(linewidths, kwargs, 'linewidth') + linestyles = cbook._local_over_kwdict(linestyles, kwargs, 'linestyle') + + if not np.iterable(lineoffsets): + lineoffsets = [lineoffsets] + if not np.iterable(linelengths): + linelengths = [linelengths] + if not np.iterable(linewidths): + linewidths = [linewidths] + if not np.iterable(colors): + colors = [colors] + if not np.iterable(alpha): + alpha = [alpha] + if hasattr(linestyles, 'lower') or not np.iterable(linestyles): + linestyles = [linestyles] + + lineoffsets = np.asarray(lineoffsets) + linelengths = np.asarray(linelengths) + linewidths = np.asarray(linewidths) + + if len(lineoffsets) == 0: + raise ValueError('lineoffsets cannot be empty') + if len(linelengths) == 0: + raise ValueError('linelengths cannot be empty') + if len(linestyles) == 0: + raise ValueError('linestyles cannot be empty') + if len(linewidths) == 0: + raise ValueError('linewidths cannot be empty') + if len(alpha) == 0: + raise ValueError('alpha cannot be empty') + if len(colors) == 0: + colors = [None] + try: + # Early conversion of the colors into RGBA values to take care + # of cases like colors='0.5' or colors='C1'. (Issue #8193) + colors = mcolors.to_rgba_array(colors) + except ValueError: + # Will fail if any element of *colors* is None. But as long + # as len(colors) == 1 or len(positions), the rest of the + # code should process *colors* properly. + pass + + if len(lineoffsets) == 1 and len(positions) != 1: + lineoffsets = np.tile(lineoffsets, len(positions)) + lineoffsets[0] = 0 + lineoffsets = np.cumsum(lineoffsets) + if len(linelengths) == 1: + linelengths = np.tile(linelengths, len(positions)) + if len(linewidths) == 1: + linewidths = np.tile(linewidths, len(positions)) + if len(colors) == 1: + colors = list(colors) * len(positions) + if len(alpha) == 1: + alpha = list(alpha) * len(positions) + if len(linestyles) == 1: + linestyles = [linestyles] * len(positions) + + if len(lineoffsets) != len(positions): + raise ValueError('lineoffsets and positions are unequal sized ' + 'sequences') + if len(linelengths) != len(positions): + raise ValueError('linelengths and positions are unequal sized ' + 'sequences') + if len(linewidths) != len(positions): + raise ValueError('linewidths and positions are unequal sized ' + 'sequences') + if len(colors) != len(positions): + raise ValueError('colors and positions are unequal sized ' + 'sequences') + if len(alpha) != len(positions): + raise ValueError('alpha and positions are unequal sized ' + 'sequences') + if len(linestyles) != len(positions): + raise ValueError('linestyles and positions are unequal sized ' + 'sequences') + + colls = [] + for position, lineoffset, linelength, linewidth, color, alpha_, \ + linestyle in \ + zip(positions, lineoffsets, linelengths, linewidths, + colors, alpha, linestyles): + coll = mcoll.EventCollection(position, + orientation=orientation, + lineoffset=lineoffset, + linelength=linelength, + linewidth=linewidth, + color=color, + alpha=alpha_, + linestyle=linestyle) + self.add_collection(coll, autolim=False) + coll._internal_update(kwargs) + colls.append(coll) + + if len(positions) > 0: + # try to get min/max + min_max = [(np.min(_p), np.max(_p)) for _p in positions + if len(_p) > 0] + # if we have any non-empty positions, try to autoscale + if len(min_max) > 0: + mins, maxes = zip(*min_max) + minpos = np.min(mins) + maxpos = np.max(maxes) + + minline = (lineoffsets - linelengths).min() + maxline = (lineoffsets + linelengths).max() + + if orientation == "vertical": + corners = (minline, minpos), (maxline, maxpos) + else: # "horizontal" + corners = (minpos, minline), (maxpos, maxline) + self.update_datalim(corners) + self._request_autoscale_view() + + return colls + + #### Basic plotting + + # Uses a custom implementation of data-kwarg handling in + # _process_plot_var_args. + @_docstring.interpd + def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs): + """ + Plot y versus x as lines and/or markers. + + Call signatures:: + + plot([x], y, [fmt], *, data=None, **kwargs) + plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + The coordinates of the points or line nodes are given by *x*, *y*. + + The optional parameter *fmt* is a convenient way for defining basic + formatting like color, marker and linestyle. It's a shortcut string + notation described in the *Notes* section below. + + >>> plot(x, y) # plot x and y using default line style and color + >>> plot(x, y, 'bo') # plot x and y using blue circle markers + >>> plot(y) # plot y using x as index array 0..N-1 + >>> plot(y, 'r+') # ditto, but with red plusses + + You can use `.Line2D` properties as keyword arguments for more + control on the appearance. Line properties and *fmt* can be mixed. + The following two calls yield identical results: + + >>> plot(x, y, 'go--', linewidth=2, markersize=12) + >>> plot(x, y, color='green', marker='o', linestyle='dashed', + ... linewidth=2, markersize=12) + + When conflicting with *fmt*, keyword arguments take precedence. + + + **Plotting labelled data** + + There's a convenient way for plotting objects with labelled data (i.e. + data that can be accessed by index ``obj['y']``). Instead of giving + the data in *x* and *y*, you can provide the object in the *data* + parameter and just give the labels for *x* and *y*:: + + >>> plot('xlabel', 'ylabel', data=obj) + + All indexable objects are supported. This could e.g. be a `dict`, a + `pandas.DataFrame` or a structured numpy array. + + + **Plotting multiple sets of data** + + There are various ways to plot multiple sets of data. + + - The most straight forward way is just to call `plot` multiple times. + Example: + + >>> plot(x1, y1, 'bo') + >>> plot(x2, y2, 'go') + + - If *x* and/or *y* are 2D arrays, a separate data set will be drawn + for every column. If both *x* and *y* are 2D, they must have the + same shape. If only one of them is 2D with shape (N, m) the other + must have length N and will be used for every data set m. + + Example: + + >>> x = [1, 2, 3] + >>> y = np.array([[1, 2], [3, 4], [5, 6]]) + >>> plot(x, y) + + is equivalent to: + + >>> for col in range(y.shape[1]): + ... plot(x, y[:, col]) + + - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]* + groups:: + + >>> plot(x1, y1, 'g^', x2, y2, 'g-') + + In this case, any additional keyword argument applies to all + datasets. Also, this syntax cannot be combined with the *data* + parameter. + + By default, each line is assigned a different style specified by a + 'style cycle'. The *fmt* and line property parameters are only + necessary if you want explicit deviations from these defaults. + Alternatively, you can also change the style cycle using + :rc:`axes.prop_cycle`. + + + Parameters + ---------- + x, y : array-like or float + The horizontal / vertical coordinates of the data points. + *x* values are optional and default to ``range(len(y))``. + + Commonly, these parameters are 1D arrays. + + They can also be scalars, or two-dimensional (in that case, the + columns represent separate data sets). + + These arguments cannot be passed as keywords. + + fmt : str, optional + A format string, e.g. 'ro' for red circles. See the *Notes* + section for a full description of the format strings. + + Format strings are just an abbreviation for quickly setting + basic line properties. All of these and more can also be + controlled by keyword arguments. + + This argument cannot be passed as keyword. + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*. + + .. note:: + Technically there's a slight ambiguity in calls where the + second label is a valid *fmt*. ``plot('n', 'o', data=obj)`` + could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases, + the former interpretation is chosen, but a warning is issued. + You may suppress the warning by adding an empty format string + ``plot('n', 'o', '', data=obj)``. + + Returns + ------- + list of `.Line2D` + A list of lines representing the plotted data. + + Other Parameters + ---------------- + scalex, scaley : bool, default: True + These parameters determine if the view limits are adapted to the + data limits. The values are passed on to + `~.axes.Axes.autoscale_view`. + + **kwargs : `~matplotlib.lines.Line2D` properties, optional + *kwargs* are used to specify properties like a line label (for + auto legends), linewidth, antialiasing, marker face color. + Example:: + + >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) + >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2') + + If you specify multiple lines with one plot call, the kwargs apply + to all those lines. In case the label object is iterable, each + element is used as labels for each set of data. + + Here is a list of available `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + scatter : XY scatter plot with markers of varying size and/or color ( + sometimes also called bubble chart). + + Notes + ----- + **Format Strings** + + A format string consists of a part for color, marker and line:: + + fmt = '[marker][line][color]' + + Each of them is optional. If not provided, the value from the style + cycle is used. Exception: If ``line`` is given, but no ``marker``, + the data will be a line without markers. + + Other combinations such as ``[color][marker][line]`` are also + supported, but note that their parsing may be ambiguous. + + **Markers** + + ============= =============================== + character description + ============= =============================== + ``'.'`` point marker + ``','`` pixel marker + ``'o'`` circle marker + ``'v'`` triangle_down marker + ``'^'`` triangle_up marker + ``'<'`` triangle_left marker + ``'>'`` triangle_right marker + ``'1'`` tri_down marker + ``'2'`` tri_up marker + ``'3'`` tri_left marker + ``'4'`` tri_right marker + ``'8'`` octagon marker + ``'s'`` square marker + ``'p'`` pentagon marker + ``'P'`` plus (filled) marker + ``'*'`` star marker + ``'h'`` hexagon1 marker + ``'H'`` hexagon2 marker + ``'+'`` plus marker + ``'x'`` x marker + ``'X'`` x (filled) marker + ``'D'`` diamond marker + ``'d'`` thin_diamond marker + ``'|'`` vline marker + ``'_'`` hline marker + ============= =============================== + + **Line Styles** + + ============= =============================== + character description + ============= =============================== + ``'-'`` solid line style + ``'--'`` dashed line style + ``'-.'`` dash-dot line style + ``':'`` dotted line style + ============= =============================== + + Example format strings:: + + 'b' # blue markers with default shape + 'or' # red circles + '-g' # green solid line + '--' # dashed line with default color + '^k:' # black triangle_up markers connected by a dotted line + + **Colors** + + The supported color abbreviations are the single letter codes + + ============= =============================== + character color + ============= =============================== + ``'b'`` blue + ``'g'`` green + ``'r'`` red + ``'c'`` cyan + ``'m'`` magenta + ``'y'`` yellow + ``'k'`` black + ``'w'`` white + ============= =============================== + + and the ``'CN'`` colors that index into the default property cycle. + + If the color is the only part of the format string, you can + additionally use any `matplotlib.colors` spec, e.g. full names + (``'green'``) or hex strings (``'#008000'``). + """ + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + lines = [*self._get_lines(self, *args, data=data, **kwargs)] + for line in lines: + self.add_line(line) + if scalex: + self._request_autoscale_view("x") + if scaley: + self._request_autoscale_view("y") + return lines + + @_api.deprecated("3.9", alternative="plot") + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + @_docstring.interpd + def plot_date(self, x, y, fmt='o', tz=None, xdate=True, ydate=False, + **kwargs): + """ + Plot coercing the axis to treat floats as dates. + + .. deprecated:: 3.9 + + This method exists for historic reasons and will be removed in version 3.11. + + - ``datetime``-like data should directly be plotted using + `~.Axes.plot`. + - If you need to plot plain numeric data as :ref:`date-format` or + need to set a timezone, call ``ax.xaxis.axis_date`` / + ``ax.yaxis.axis_date`` before `~.Axes.plot`. See + `.Axis.axis_date`. + + Similar to `.plot`, this plots *y* vs. *x* as lines or markers. + However, the axis labels are formatted as dates depending on *xdate* + and *ydate*. Note that `.plot` will work with `datetime` and + `numpy.datetime64` objects without resorting to this method. + + Parameters + ---------- + x, y : array-like + The coordinates of the data points. If *xdate* or *ydate* is + *True*, the respective values *x* or *y* are interpreted as + :ref:`Matplotlib dates `. + + fmt : str, optional + The plot format string. For details, see the corresponding + parameter in `.plot`. + + tz : timezone string or `datetime.tzinfo`, default: :rc:`timezone` + The time zone to use in labeling dates. + + xdate : bool, default: True + If *True*, the *x*-axis will be interpreted as Matplotlib dates. + + ydate : bool, default: False + If *True*, the *y*-axis will be interpreted as Matplotlib dates. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + matplotlib.dates : Helper functions on dates. + matplotlib.dates.date2num : Convert dates to num. + matplotlib.dates.num2date : Convert num to dates. + matplotlib.dates.drange : Create an equally spaced sequence of dates. + + Notes + ----- + If you are using custom date tickers and formatters, it may be + necessary to set the formatters/locators after the call to + `.plot_date`. `.plot_date` will set the default tick locator to + `.AutoDateLocator` (if the tick locator is not already set to a + `.DateLocator` instance) and the default tick formatter to + `.AutoDateFormatter` (if the tick formatter is not already set to a + `.DateFormatter` instance). + """ + if xdate: + self.xaxis_date(tz) + if ydate: + self.yaxis_date(tz) + return self.plot(x, y, fmt, **kwargs) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.interpd + def loglog(self, *args, **kwargs): + """ + Make a plot with log scaling on both the x- and y-axis. + + Call signatures:: + + loglog([x], y, [fmt], data=None, **kwargs) + loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + both the x-axis and the y-axis to log scaling. All the concepts and + parameters of plot can be used here as well. + + The additional parameters *base*, *subs* and *nonpositive* control the + x/y-axis properties. They are just forwarded to `.Axes.set_xscale` and + `.Axes.set_yscale`. To use different properties on the x-axis and the + y-axis, use e.g. + ``ax.set_xscale("log", base=10); ax.set_yscale("log", base=2)``. + + Parameters + ---------- + base : float, default: 10 + Base of the logarithm. + + subs : sequence, optional + The location of the minor ticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_xscale`/`.Axes.set_yscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values can be masked as invalid, or clipped to a very + small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + dx = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basex', 'subsx', 'nonposx']} + self.set_xscale('log', **dx) + dy = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basey', 'subsy', 'nonposy']} + self.set_yscale('log', **dy) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in {*dx, *dy}}) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.interpd + def semilogx(self, *args, **kwargs): + """ + Make a plot with log scaling on the x-axis. + + Call signatures:: + + semilogx([x], y, [fmt], data=None, **kwargs) + semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + the x-axis to log scaling. All the concepts and parameters of plot can + be used here as well. + + The additional parameters *base*, *subs*, and *nonpositive* control the + x-axis properties. They are just forwarded to `.Axes.set_xscale`. + + Parameters + ---------- + base : float, default: 10 + Base of the x logarithm. + + subs : array-like, optional + The location of the minor xticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_xscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values in x can be masked as invalid, or clipped to a + very small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + d = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basex', 'subsx', 'nonposx']} + self.set_xscale('log', **d) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in d}) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.interpd + def semilogy(self, *args, **kwargs): + """ + Make a plot with log scaling on the y-axis. + + Call signatures:: + + semilogy([x], y, [fmt], data=None, **kwargs) + semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + the y-axis to log scaling. All the concepts and parameters of plot can + be used here as well. + + The additional parameters *base*, *subs*, and *nonpositive* control the + y-axis properties. They are just forwarded to `.Axes.set_yscale`. + + Parameters + ---------- + base : float, default: 10 + Base of the y logarithm. + + subs : array-like, optional + The location of the minor yticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_yscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values in y can be masked as invalid, or clipped to a + very small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + d = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basey', 'subsy', 'nonposy']} + self.set_yscale('log', **d) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in d}) + + @_preprocess_data(replace_names=["x"], label_namer="x") + def acorr(self, x, **kwargs): + """ + Plot the autocorrelation of *x*. + + Parameters + ---------- + x : array-like + Not run through Matplotlib's unit conversion, so this should + be a unit-less array. + + detrend : callable, default: `.mlab.detrend_none` (no detrending) + A detrending function applied to *x*. It must have the + signature :: + + detrend(x: np.ndarray) -> np.ndarray + + normed : bool, default: True + If ``True``, input vectors are normalised to unit length. + + usevlines : bool, default: True + Determines the plot style. + + If ``True``, vertical lines are plotted from 0 to the acorr value + using `.Axes.vlines`. Additionally, a horizontal line is plotted + at y=0 using `.Axes.axhline`. + + If ``False``, markers are plotted at the acorr values using + `.Axes.plot`. + + maxlags : int, default: 10 + Number of lags to show. If ``None``, will return all + ``2 * len(x) - 1`` lags. + + Returns + ------- + lags : array (length ``2*maxlags+1``) + The lag vector. + c : array (length ``2*maxlags+1``) + The auto correlation vector. + line : `.LineCollection` or `.Line2D` + `.Artist` added to the Axes of the correlation: + + - `.LineCollection` if *usevlines* is True. + - `.Line2D` if *usevlines* is False. + b : `~matplotlib.lines.Line2D` or None + Horizontal line at 0 if *usevlines* is True + None *usevlines* is False. + + Other Parameters + ---------------- + linestyle : `~matplotlib.lines.Line2D` property, optional + The linestyle for plotting the data points. + Only used if *usevlines* is ``False``. + + marker : str, default: 'o' + The marker for plotting the data points. + Only used if *usevlines* is ``False``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed to `.Axes.vlines` and + `.Axes.axhline` if *usevlines* is ``True``; otherwise they are + passed to `.Axes.plot`. + + Notes + ----- + The cross correlation is performed with `numpy.correlate` with + ``mode = "full"``. + """ + return self.xcorr(x, x, **kwargs) + + @_api.make_keyword_only("3.10", "normed") + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, + usevlines=True, maxlags=10, **kwargs): + r""" + Plot the cross correlation between *x* and *y*. + + The correlation with lag k is defined as + :math:`\sum_n x[n+k] \cdot y^*[n]`, where :math:`y^*` is the complex + conjugate of :math:`y`. + + Parameters + ---------- + x, y : array-like of length n + Neither *x* nor *y* are run through Matplotlib's unit conversion, so + these should be unit-less arrays. + + detrend : callable, default: `.mlab.detrend_none` (no detrending) + A detrending function applied to *x* and *y*. It must have the + signature :: + + detrend(x: np.ndarray) -> np.ndarray + + normed : bool, default: True + If ``True``, input vectors are normalised to unit length. + + usevlines : bool, default: True + Determines the plot style. + + If ``True``, vertical lines are plotted from 0 to the xcorr value + using `.Axes.vlines`. Additionally, a horizontal line is plotted + at y=0 using `.Axes.axhline`. + + If ``False``, markers are plotted at the xcorr values using + `.Axes.plot`. + + maxlags : int, default: 10 + Number of lags to show. If None, will return all ``2 * len(x) - 1`` + lags. + + Returns + ------- + lags : array (length ``2*maxlags+1``) + The lag vector. + c : array (length ``2*maxlags+1``) + The auto correlation vector. + line : `.LineCollection` or `.Line2D` + `.Artist` added to the Axes of the correlation: + + - `.LineCollection` if *usevlines* is True. + - `.Line2D` if *usevlines* is False. + b : `~matplotlib.lines.Line2D` or None + Horizontal line at 0 if *usevlines* is True + None *usevlines* is False. + + Other Parameters + ---------------- + linestyle : `~matplotlib.lines.Line2D` property, optional + The linestyle for plotting the data points. + Only used if *usevlines* is ``False``. + + marker : str, default: 'o' + The marker for plotting the data points. + Only used if *usevlines* is ``False``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed to `.Axes.vlines` and + `.Axes.axhline` if *usevlines* is ``True``; otherwise they are + passed to `.Axes.plot`. + + Notes + ----- + The cross correlation is performed with `numpy.correlate` with + ``mode = "full"``. + """ + Nx = len(x) + if Nx != len(y): + raise ValueError('x and y must be equal length') + + x = detrend(np.asarray(x)) + y = detrend(np.asarray(y)) + + correls = np.correlate(x, y, mode="full") + + if normed: + correls = correls / np.sqrt(np.dot(x, x) * np.dot(y, y)) + + if maxlags is None: + maxlags = Nx - 1 + + if maxlags >= Nx or maxlags < 1: + raise ValueError('maxlags must be None or strictly ' + 'positive < %d' % Nx) + + lags = np.arange(-maxlags, maxlags + 1) + correls = correls[Nx - 1 - maxlags:Nx + maxlags] + + if usevlines: + a = self.vlines(lags, [0], correls, **kwargs) + # Make label empty so only vertical lines get a legend entry + kwargs.pop('label', '') + b = self.axhline(**kwargs) + else: + kwargs.setdefault('marker', 'o') + kwargs.setdefault('linestyle', 'None') + a, = self.plot(lags, correls, **kwargs) + b = None + return lags, correls, a, b + + #### Specialized plotting + + # @_preprocess_data() # let 'plot' do the unpacking.. + def step(self, x, y, *args, where='pre', data=None, **kwargs): + """ + Make a step plot. + + Call signatures:: + + step(x, y, [fmt], *, data=None, where='pre', **kwargs) + step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs) + + This is just a thin wrapper around `.plot` which changes some + formatting options. Most of the concepts and parameters of plot can be + used here as well. + + .. note:: + + This method uses a standard plot with a step drawstyle: The *x* + values are the reference positions and steps extend left/right/both + directions depending on *where*. + + For the common case where you know the values and edges of the + steps, use `~.Axes.stairs` instead. + + Parameters + ---------- + x : array-like + 1D sequence of x positions. It is assumed, but not checked, that + it is uniformly increasing. + + y : array-like + 1D sequence of y levels. + + fmt : str, optional + A format string, e.g. 'g' for a green line. See `.plot` for a more + detailed description. + + Note: While full format strings are accepted, it is recommended to + only specify the color. Line styles are currently ignored (use + the keyword argument *linestyle* instead). Markers are accepted + and plotted on the given positions, however, this is a rarely + needed feature for step plots. + + where : {'pre', 'post', 'mid'}, default: 'pre' + Define where the steps should be placed: + + - 'pre': The y value is continued constantly to the left from + every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the + value ``y[i]``. + - 'post': The y value is continued constantly to the right from + every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the + value ``y[i]``. + - 'mid': Steps occur half-way between the *x* positions. + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*. + + **kwargs + Additional parameters are the same as those for `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + _api.check_in_list(('pre', 'post', 'mid'), where=where) + kwargs['drawstyle'] = 'steps-' + where + return self.plot(x, y, *args, data=data, **kwargs) + + @staticmethod + def _convert_dx(dx, x0, xconv, convert): + """ + Small helper to do logic of width conversion flexibly. + + *dx* and *x0* have units, but *xconv* has already been converted + to unitless (and is an ndarray). This allows the *dx* to have units + that are different from *x0*, but are still accepted by the + ``__add__`` operator of *x0*. + """ + + # x should be an array... + assert type(xconv) is np.ndarray + + if xconv.size == 0: + # xconv has already been converted, but maybe empty... + return convert(dx) + + try: + # attempt to add the width to x0; this works for + # datetime+timedelta, for instance + + # only use the first element of x and x0. This saves + # having to be sure addition works across the whole + # vector. This is particularly an issue if + # x0 and dx are lists so x0 + dx just concatenates the lists. + # We can't just cast x0 and dx to numpy arrays because that + # removes the units from unit packages like `pint` that + # wrap numpy arrays. + try: + x0 = cbook._safe_first_finite(x0) + except (TypeError, IndexError, KeyError): + pass + + try: + x = cbook._safe_first_finite(xconv) + except (TypeError, IndexError, KeyError): + x = xconv + + delist = False + if not np.iterable(dx): + dx = [dx] + delist = True + dx = [convert(x0 + ddx) - x for ddx in dx] + if delist: + dx = dx[0] + except (ValueError, TypeError, AttributeError): + # if the above fails (for any reason) just fallback to what + # we do by default and convert dx by itself. + dx = convert(dx) + return dx + + def _parse_bar_color_args(self, kwargs): + """ + Helper function to process color-related arguments of `.Axes.bar`. + + Argument precedence for facecolors: + + - kwargs['facecolor'] + - kwargs['color'] + - 'Result of ``self._get_patches_for_fill.get_next_color`` + + Argument precedence for edgecolors: + + - kwargs['edgecolor'] + - None + + Parameters + ---------- + self : Axes + + kwargs : dict + Additional kwargs. If these keys exist, we pop and process them: + 'facecolor', 'edgecolor', 'color' + Note: The dict is modified by this function. + + + Returns + ------- + facecolor + The facecolor. One or more colors as (N, 4) rgba array. + edgecolor + The edgecolor. Not normalized; may be any valid color spec or None. + """ + color = kwargs.pop('color', None) + + facecolor = kwargs.pop('facecolor', color) + edgecolor = kwargs.pop('edgecolor', None) + + facecolor = (facecolor if facecolor is not None + else self._get_patches_for_fill.get_next_color()) + + try: + facecolor = mcolors.to_rgba_array(facecolor) + except ValueError as err: + raise ValueError( + "'facecolor' or 'color' argument must be a valid color or " + "sequence of colors." + ) from err + + return facecolor, edgecolor + + @_preprocess_data() + @_docstring.interpd + def bar(self, x, height, width=0.8, bottom=None, *, align="center", + **kwargs): + r""" + Make a bar plot. + + The bars are positioned at *x* with the given *align*\ment. Their + dimensions are given by *height* and *width*. The vertical baseline + is *bottom* (default 0). + + Many parameters can take either a single value applying to all bars + or a sequence of values, one for each bar. + + Parameters + ---------- + x : float or array-like + The x coordinates of the bars. See also *align* for the + alignment of the bars to the coordinates. + + Bars are often used for categorical data, i.e. string labels below + the bars. You can provide a list of strings directly to *x*. + ``bar(['A', 'B', 'C'], [1, 2, 3])`` is often a shorter and more + convenient notation compared to + ``bar(range(3), [1, 2, 3], tick_label=['A', 'B', 'C'])``. They are + equivalent as long as the names are unique. The explicit *tick_label* + notation draws the names in the sequence given. However, when having + duplicate values in categorical *x* data, these values map to the same + numerical x coordinate, and hence the corresponding bars are drawn on + top of each other. + + height : float or array-like + The height(s) of the bars. + + Note that if *bottom* has units (e.g. datetime), *height* should be in + units that are a difference from the value of *bottom* (e.g. timedelta). + + width : float or array-like, default: 0.8 + The width(s) of the bars. + + Note that if *x* has units (e.g. datetime), then *width* should be in + units that are a difference (e.g. timedelta) around the *x* values. + + bottom : float or array-like, default: 0 + The y coordinate(s) of the bottom side(s) of the bars. + + Note that if *bottom* has units, then the y-axis will get a Locator and + Formatter appropriate for the units (e.g. dates, or categorical). + + align : {'center', 'edge'}, default: 'center' + Alignment of the bars to the *x* coordinates: + + - 'center': Center the base on the *x* positions. + - 'edge': Align the left edges of the bars with the *x* positions. + + To align the bars on the right edge pass a negative *width* and + ``align='edge'``. + + Returns + ------- + `.BarContainer` + Container with all the bars and optionally errorbars. + + Other Parameters + ---------------- + color : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. This is an alias for *facecolor*. + If both are given, *facecolor* takes precedence. + + facecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. + If both *color* and *facecolor are given, *facecolor* takes precedence. + + edgecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar edges. + + linewidth : float or array-like, optional + Width of the bar edge(s). If 0, don't draw edges. + + tick_label : str or list of str, optional + The tick labels of the bars. + Default: None (Use default numeric labels.) + + label : str or list of str, optional + A single label is attached to the resulting `.BarContainer` as a + label for the whole dataset. + If a list is provided, it must be the same length as *x* and + labels the individual bars. Repeated labels are not de-duplicated + and will cause repeated label entries, so this is best used when + bars also differ in style (e.g., by passing a list to *color*.) + + xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional + If not *None*, add horizontal / vertical errorbars to the bar tips. + The values are +/- sizes relative to the data: + + - scalar: symmetric +/- values for all bars + - shape(N,): symmetric +/- values for each bar + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. (Default) + + See :doc:`/gallery/statistics/errorbar_features` for an example on + the usage of *xerr* and *yerr*. + + ecolor : :mpltype:`color` or list of :mpltype:`color`, default: 'black' + The line color of the errorbars. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + error_kw : dict, optional + Dictionary of keyword arguments to be passed to the + `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined + here take precedence over the independent keyword arguments. + + log : bool, default: False + If *True*, set the y-axis to be log scale. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + barh : Plot a horizontal bar plot. + + Notes + ----- + Stacked bars can be achieved by passing individual *bottom* values per + bar. See :doc:`/gallery/lines_bars_and_markers/bar_stacked`. + """ + kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch) + facecolor, edgecolor = self._parse_bar_color_args(kwargs) + + linewidth = kwargs.pop('linewidth', None) + hatch = kwargs.pop('hatch', None) + + # Because xerr and yerr will be passed to errorbar, most dimension + # checking and processing will be left to the errorbar method. + xerr = kwargs.pop('xerr', None) + yerr = kwargs.pop('yerr', None) + error_kw = kwargs.pop('error_kw', None) + error_kw = {} if error_kw is None else error_kw.copy() + ezorder = error_kw.pop('zorder', None) + if ezorder is None: + ezorder = kwargs.get('zorder', None) + if ezorder is not None: + # If using the bar zorder, increment slightly to make sure + # errorbars are drawn on top of bars + ezorder += 0.01 + error_kw.setdefault('zorder', ezorder) + ecolor = kwargs.pop('ecolor', 'k') + capsize = kwargs.pop('capsize', mpl.rcParams["errorbar.capsize"]) + error_kw.setdefault('ecolor', ecolor) + error_kw.setdefault('capsize', capsize) + + # The keyword argument *orientation* is used by barh() to defer all + # logic and drawing to bar(). It is considered internal and is + # intentionally not mentioned in the docstring. + orientation = kwargs.pop('orientation', 'vertical') + _api.check_in_list(['vertical', 'horizontal'], orientation=orientation) + log = kwargs.pop('log', False) + label = kwargs.pop('label', '') + tick_labels = kwargs.pop('tick_label', None) + + y = bottom # Matches barh call signature. + if orientation == 'vertical': + if y is None: + y = 0 + else: # horizontal + if x is None: + x = 0 + + if orientation == 'vertical': + # It is possible for y (bottom) to contain unit information. + # However, it is also possible for y=0 for the default and height + # to contain unit information. This will prioritize the units of y. + self._process_unit_info( + [("x", x), ("y", y), ("y", height)], kwargs, convert=False) + if log: + self.set_yscale('log', nonpositive='clip') + else: # horizontal + # It is possible for x (left) to contain unit information. + # However, it is also possible for x=0 for the default and width + # to contain unit information. This will prioritize the units of x. + self._process_unit_info( + [("x", x), ("x", width), ("y", y)], kwargs, convert=False) + if log: + self.set_xscale('log', nonpositive='clip') + + # lets do some conversions now since some types cannot be + # subtracted uniformly + if self.xaxis is not None: + x0 = x + x = np.asarray(self.convert_xunits(x)) + width = self._convert_dx(width, x0, x, self.convert_xunits) + if xerr is not None: + xerr = self._convert_dx(xerr, x0, x, self.convert_xunits) + if self.yaxis is not None: + y0 = y + y = np.asarray(self.convert_yunits(y)) + height = self._convert_dx(height, y0, y, self.convert_yunits) + if yerr is not None: + yerr = self._convert_dx(yerr, y0, y, self.convert_yunits) + + x, height, width, y, linewidth, hatch = np.broadcast_arrays( + # Make args iterable too. + np.atleast_1d(x), height, width, y, linewidth, hatch) + + # Now that units have been converted, set the tick locations. + if orientation == 'vertical': + tick_label_axis = self.xaxis + tick_label_position = x + else: # horizontal + tick_label_axis = self.yaxis + tick_label_position = y + + if not isinstance(label, str) and np.iterable(label): + bar_container_label = '_nolegend_' + patch_labels = label + else: + bar_container_label = label + patch_labels = ['_nolegend_'] * len(x) + if len(patch_labels) != len(x): + raise ValueError(f'number of labels ({len(patch_labels)}) ' + f'does not match number of bars ({len(x)}).') + + linewidth = itertools.cycle(np.atleast_1d(linewidth)) + hatch = itertools.cycle(np.atleast_1d(hatch)) + facecolor = itertools.chain(itertools.cycle(facecolor), + # Fallback if color == "none". + itertools.repeat('none')) + if edgecolor is None: + edgecolor = itertools.repeat(None) + else: + edgecolor = itertools.chain( + itertools.cycle(mcolors.to_rgba_array(edgecolor)), + # Fallback if edgecolor == "none". + itertools.repeat('none')) + + # We will now resolve the alignment and really have + # left, bottom, width, height vectors + _api.check_in_list(['center', 'edge'], align=align) + if align == 'center': + if orientation == 'vertical': + try: + left = x - width / 2 + except TypeError as e: + raise TypeError(f'the dtypes of parameters x ({x.dtype}) ' + f'and width ({width.dtype}) ' + f'are incompatible') from e + bottom = y + else: # horizontal + try: + bottom = y - height / 2 + except TypeError as e: + raise TypeError(f'the dtypes of parameters y ({y.dtype}) ' + f'and height ({height.dtype}) ' + f'are incompatible') from e + left = x + else: # edge + left = x + bottom = y + + patches = [] + args = zip(left, bottom, width, height, facecolor, edgecolor, linewidth, + hatch, patch_labels) + for l, b, w, h, c, e, lw, htch, lbl in args: + r = mpatches.Rectangle( + xy=(l, b), width=w, height=h, + facecolor=c, + edgecolor=e, + linewidth=lw, + label=lbl, + hatch=htch, + ) + r._internal_update(kwargs) + r.get_path()._interpolation_steps = 100 + if orientation == 'vertical': + r.sticky_edges.y.append(b) + else: # horizontal + r.sticky_edges.x.append(l) + self.add_patch(r) + patches.append(r) + + if xerr is not None or yerr is not None: + if orientation == 'vertical': + # using list comps rather than arrays to preserve unit info + ex = [l + 0.5 * w for l, w in zip(left, width)] + ey = [b + h for b, h in zip(bottom, height)] + + else: # horizontal + # using list comps rather than arrays to preserve unit info + ex = [l + w for l, w in zip(left, width)] + ey = [b + 0.5 * h for b, h in zip(bottom, height)] + + error_kw.setdefault("label", '_nolegend_') + + errorbar = self.errorbar(ex, ey, yerr=yerr, xerr=xerr, fmt='none', + **error_kw) + else: + errorbar = None + + self._request_autoscale_view() + + if orientation == 'vertical': + datavalues = height + else: # horizontal + datavalues = width + + bar_container = BarContainer(patches, errorbar, datavalues=datavalues, + orientation=orientation, + label=bar_container_label) + self.add_container(bar_container) + + if tick_labels is not None: + tick_labels = np.broadcast_to(tick_labels, len(patches)) + tick_label_axis.set_ticks(tick_label_position) + tick_label_axis.set_ticklabels(tick_labels) + + return bar_container + + # @_preprocess_data() # let 'bar' do the unpacking.. + @_docstring.interpd + def barh(self, y, width, height=0.8, left=None, *, align="center", + data=None, **kwargs): + r""" + Make a horizontal bar plot. + + The bars are positioned at *y* with the given *align*\ment. Their + dimensions are given by *width* and *height*. The horizontal baseline + is *left* (default 0). + + Many parameters can take either a single value applying to all bars + or a sequence of values, one for each bar. + + Parameters + ---------- + y : float or array-like + The y coordinates of the bars. See also *align* for the + alignment of the bars to the coordinates. + + Bars are often used for categorical data, i.e. string labels below + the bars. You can provide a list of strings directly to *y*. + ``barh(['A', 'B', 'C'], [1, 2, 3])`` is often a shorter and more + convenient notation compared to + ``barh(range(3), [1, 2, 3], tick_label=['A', 'B', 'C'])``. They are + equivalent as long as the names are unique. The explicit *tick_label* + notation draws the names in the sequence given. However, when having + duplicate values in categorical *y* data, these values map to the same + numerical y coordinate, and hence the corresponding bars are drawn on + top of each other. + + width : float or array-like + The width(s) of the bars. + + Note that if *left* has units (e.g. datetime), *width* should be in + units that are a difference from the value of *left* (e.g. timedelta). + + height : float or array-like, default: 0.8 + The heights of the bars. + + Note that if *y* has units (e.g. datetime), then *height* should be in + units that are a difference (e.g. timedelta) around the *y* values. + + left : float or array-like, default: 0 + The x coordinates of the left side(s) of the bars. + + Note that if *left* has units, then the x-axis will get a Locator and + Formatter appropriate for the units (e.g. dates, or categorical). + + align : {'center', 'edge'}, default: 'center' + Alignment of the base to the *y* coordinates*: + + - 'center': Center the bars on the *y* positions. + - 'edge': Align the bottom edges of the bars with the *y* + positions. + + To align the bars on the top edge pass a negative *height* and + ``align='edge'``. + + Returns + ------- + `.BarContainer` + Container with all the bars and optionally errorbars. + + Other Parameters + ---------------- + color : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. + + edgecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar edges. + + linewidth : float or array-like, optional + Width of the bar edge(s). If 0, don't draw edges. + + tick_label : str or list of str, optional + The tick labels of the bars. + Default: None (Use default numeric labels.) + + label : str or list of str, optional + A single label is attached to the resulting `.BarContainer` as a + label for the whole dataset. + If a list is provided, it must be the same length as *y* and + labels the individual bars. Repeated labels are not de-duplicated + and will cause repeated label entries, so this is best used when + bars also differ in style (e.g., by passing a list to *color*.) + + xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional + If not *None*, add horizontal / vertical errorbars to the bar tips. + The values are +/- sizes relative to the data: + + - scalar: symmetric +/- values for all bars + - shape(N,): symmetric +/- values for each bar + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. (default) + + See :doc:`/gallery/statistics/errorbar_features` for an example on + the usage of *xerr* and *yerr*. + + ecolor : :mpltype:`color` or list of :mpltype:`color`, default: 'black' + The line color of the errorbars. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + error_kw : dict, optional + Dictionary of keyword arguments to be passed to the + `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined + here take precedence over the independent keyword arguments. + + log : bool, default: False + If ``True``, set the x-axis to be log scale. + + data : indexable object, optional + If given, all parameters also accept a string ``s``, which is + interpreted as ``data[s]`` if ``s`` is a key in ``data``. + + **kwargs : `.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + bar : Plot a vertical bar plot. + + Notes + ----- + Stacked bars can be achieved by passing individual *left* values per + bar. See + :doc:`/gallery/lines_bars_and_markers/horizontal_barchart_distribution`. + """ + kwargs.setdefault('orientation', 'horizontal') + patches = self.bar(x=left, height=height, width=width, bottom=y, + align=align, data=data, **kwargs) + return patches + + def bar_label(self, container, labels=None, *, fmt="%g", label_type="edge", + padding=0, **kwargs): + """ + Label a bar plot. + + Adds labels to bars in the given `.BarContainer`. + You may need to adjust the axis limits to fit the labels. + + Parameters + ---------- + container : `.BarContainer` + Container with all the bars and optionally errorbars, likely + returned from `.bar` or `.barh`. + + labels : array-like, optional + A list of label texts, that should be displayed. If not given, the + label texts will be the data values formatted with *fmt*. + + fmt : str or callable, default: '%g' + An unnamed %-style or {}-style format string for the label or a + function to call with the value as the first argument. + When *fmt* is a string and can be interpreted in both formats, + %-style takes precedence over {}-style. + + .. versionadded:: 3.7 + Support for {}-style format string and callables. + + label_type : {'edge', 'center'}, default: 'edge' + The label type. Possible values: + + - 'edge': label placed at the end-point of the bar segment, and the + value displayed will be the position of that end-point. + - 'center': label placed in the center of the bar segment, and the + value displayed will be the length of that segment. + (useful for stacked bars, i.e., + :doc:`/gallery/lines_bars_and_markers/bar_label_demo`) + + padding : float, default: 0 + Distance of label from the end of the bar, in points. + + **kwargs + Any remaining keyword arguments are passed through to + `.Axes.annotate`. The alignment parameters ( + *horizontalalignment* / *ha*, *verticalalignment* / *va*) are + not supported because the labels are automatically aligned to + the bars. + + Returns + ------- + list of `.Annotation` + A list of `.Annotation` instances for the labels. + """ + for key in ['horizontalalignment', 'ha', 'verticalalignment', 'va']: + if key in kwargs: + raise ValueError( + f"Passing {key!r} to bar_label() is not supported.") + + a, b = self.yaxis.get_view_interval() + y_inverted = a > b + c, d = self.xaxis.get_view_interval() + x_inverted = c > d + + # want to know whether to put label on positive or negative direction + # cannot use np.sign here because it will return 0 if x == 0 + def sign(x): + return 1 if x >= 0 else -1 + + _api.check_in_list(['edge', 'center'], label_type=label_type) + + bars = container.patches + errorbar = container.errorbar + datavalues = container.datavalues + orientation = container.orientation + + if errorbar: + # check "ErrorbarContainer" for the definition of these elements + lines = errorbar.lines # attribute of "ErrorbarContainer" (tuple) + barlinecols = lines[2] # 0: data_line, 1: caplines, 2: barlinecols + barlinecol = barlinecols[0] # the "LineCollection" of error bars + errs = barlinecol.get_segments() + else: + errs = [] + + if labels is None: + labels = [] + + annotations = [] + + for bar, err, dat, lbl in itertools.zip_longest( + bars, errs, datavalues, labels + ): + (x0, y0), (x1, y1) = bar.get_bbox().get_points() + xc, yc = (x0 + x1) / 2, (y0 + y1) / 2 + + if orientation == "vertical": + extrema = max(y0, y1) if dat >= 0 else min(y0, y1) + length = abs(y0 - y1) + else: # horizontal + extrema = max(x0, x1) if dat >= 0 else min(x0, x1) + length = abs(x0 - x1) + + if err is None or np.size(err) == 0: + endpt = extrema + elif orientation == "vertical": + endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min() + else: # horizontal + endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min() + + if label_type == "center": + value = sign(dat) * length + else: # edge + value = extrema + + if label_type == "center": + xy = (0.5, 0.5) + kwargs["xycoords"] = ( + lambda r, b=bar: + mtransforms.Bbox.intersection( + b.get_window_extent(r), b.get_clip_box() + ) or mtransforms.Bbox.null() + ) + else: # edge + if orientation == "vertical": + xy = xc, endpt + else: # horizontal + xy = endpt, yc + + if orientation == "vertical": + y_direction = -1 if y_inverted else 1 + xytext = 0, y_direction * sign(dat) * padding + else: # horizontal + x_direction = -1 if x_inverted else 1 + xytext = x_direction * sign(dat) * padding, 0 + + if label_type == "center": + ha, va = "center", "center" + else: # edge + if orientation == "vertical": + ha = 'center' + if y_inverted: + va = 'top' if dat > 0 else 'bottom' # also handles NaN + else: + va = 'top' if dat < 0 else 'bottom' # also handles NaN + else: # horizontal + if x_inverted: + ha = 'right' if dat > 0 else 'left' # also handles NaN + else: + ha = 'right' if dat < 0 else 'left' # also handles NaN + va = 'center' + + if np.isnan(dat): + lbl = '' + + if lbl is None: + if isinstance(fmt, str): + lbl = cbook._auto_format_str(fmt, value) + elif callable(fmt): + lbl = fmt(value) + else: + raise TypeError("fmt must be a str or callable") + annotation = self.annotate(lbl, + xy, xytext, textcoords="offset points", + ha=ha, va=va, **kwargs) + annotations.append(annotation) + + return annotations + + @_preprocess_data() + @_docstring.interpd + def broken_barh(self, xranges, yrange, **kwargs): + """ + Plot a horizontal sequence of rectangles. + + A rectangle is drawn for each element of *xranges*. All rectangles + have the same vertical position and size defined by *yrange*. + + Parameters + ---------- + xranges : sequence of tuples (*xmin*, *xwidth*) + The x-positions and extents of the rectangles. For each tuple + (*xmin*, *xwidth*) a rectangle is drawn from *xmin* to *xmin* + + *xwidth*. + yrange : (*ymin*, *yheight*) + The y-position and extent for all the rectangles. + + Returns + ------- + `~.collections.PolyCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `.PolyCollection` properties + + Each *kwarg* can be either a single argument applying to all + rectangles, e.g.:: + + facecolors='black' + + or a sequence of arguments over which is cycled, e.g.:: + + facecolors=('black', 'blue') + + would create interleaving black and blue rectangles. + + Supported keywords: + + %(PolyCollection:kwdoc)s + """ + # process the unit information + xdata = cbook._safe_first_finite(xranges) if len(xranges) else None + ydata = cbook._safe_first_finite(yrange) if len(yrange) else None + self._process_unit_info( + [("x", xdata), ("y", ydata)], kwargs, convert=False) + + vertices = [] + y0, dy = yrange + y0, y1 = self.convert_yunits((y0, y0 + dy)) + for xr in xranges: # convert the absolute values, not the x and dx + try: + x0, dx = xr + except Exception: + raise ValueError( + "each range in xrange must be a sequence with two " + "elements (i.e. xrange must be an (N, 2) array)") from None + x0, x1 = self.convert_xunits((x0, x0 + dx)) + vertices.append([(x0, y0), (x0, y1), (x1, y1), (x1, y0)]) + + col = mcoll.PolyCollection(np.array(vertices), **kwargs) + self.add_collection(col, autolim=True) + self._request_autoscale_view() + + return col + + @_preprocess_data() + def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, + label=None, orientation='vertical'): + """ + Create a stem plot. + + A stem plot draws lines perpendicular to a baseline at each location + *locs* from the baseline to *heads*, and places a marker there. For + vertical stem plots (the default), the *locs* are *x* positions, and + the *heads* are *y* values. For horizontal stem plots, the *locs* are + *y* positions, and the *heads* are *x* values. + + Call signature:: + + stem([locs,] heads, linefmt=None, markerfmt=None, basefmt=None) + + The *locs*-positions are optional. *linefmt* may be provided as + positional, but all other formats must be provided as keyword + arguments. + + Parameters + ---------- + locs : array-like, default: (0, 1, ..., len(heads) - 1) + For vertical stem plots, the x-positions of the stems. + For horizontal stem plots, the y-positions of the stems. + + heads : array-like + For vertical stem plots, the y-values of the stem heads. + For horizontal stem plots, the x-values of the stem heads. + + linefmt : str, optional + A string defining the color and/or linestyle of the vertical lines: + + ========= ============= + Character Line Style + ========= ============= + ``'-'`` solid line + ``'--'`` dashed line + ``'-.'`` dash-dot line + ``':'`` dotted line + ========= ============= + + Default: 'C0-', i.e. solid line with the first color of the color + cycle. + + Note: Markers specified through this parameter (e.g. 'x') will be + silently ignored. Instead, markers should be specified using + *markerfmt*. + + markerfmt : str, optional + A string defining the color and/or shape of the markers at the stem + heads. If the marker is not given, use the marker 'o', i.e. filled + circles. If the color is not given, use the color from *linefmt*. + + basefmt : str, default: 'C3-' ('C2-' in classic mode) + A format string defining the properties of the baseline. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + The orientation of the stems. + + bottom : float, default: 0 + The y/x-position of the baseline (depending on *orientation*). + + label : str, optional + The label to use for the stems in legends. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + `.StemContainer` + The container may be treated like a tuple + (*markerline*, *stemlines*, *baseline*) + + Notes + ----- + .. seealso:: + The MATLAB function + `stem `_ + which inspired this method. + """ + if not 1 <= len(args) <= 3: + raise _api.nargs_error('stem', '1-3', len(args)) + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if len(args) == 1: + heads, = args + locs = np.arange(len(heads)) + args = () + elif isinstance(args[1], str): + heads, *args = args + locs = np.arange(len(heads)) + else: + locs, heads, *args = args + + if orientation == 'vertical': + locs, heads = self._process_unit_info([("x", locs), ("y", heads)]) + else: # horizontal + heads, locs = self._process_unit_info([("x", heads), ("y", locs)]) + + heads = cbook._check_1d(heads) + locs = cbook._check_1d(locs) + + # resolve line format + if linefmt is None: + linefmt = args[0] if len(args) > 0 else "C0-" + linestyle, linemarker, linecolor = _process_plot_format(linefmt) + + # resolve marker format + if markerfmt is None: + # if not given as kwarg, fall back to 'o' + markerfmt = "o" + if markerfmt == '': + markerfmt = ' ' # = empty line style; '' would resolve rcParams + markerstyle, markermarker, markercolor = \ + _process_plot_format(markerfmt) + if markermarker is None: + markermarker = 'o' + if markerstyle is None: + markerstyle = 'None' + if markercolor is None: + markercolor = linecolor + + # resolve baseline format + if basefmt is None: + basefmt = ("C2-" if mpl.rcParams["_internal.classic_mode"] else + "C3-") + basestyle, basemarker, basecolor = _process_plot_format(basefmt) + + # New behaviour in 3.1 is to use a LineCollection for the stemlines + if linestyle is None: + linestyle = mpl.rcParams['lines.linestyle'] + xlines = self.vlines if orientation == "vertical" else self.hlines + stemlines = xlines( + locs, bottom, heads, + colors=linecolor, linestyles=linestyle, label="_nolegend_") + + if orientation == 'horizontal': + marker_x = heads + marker_y = locs + baseline_x = [bottom, bottom] + baseline_y = [np.min(locs), np.max(locs)] + else: + marker_x = locs + marker_y = heads + baseline_x = [np.min(locs), np.max(locs)] + baseline_y = [bottom, bottom] + + markerline, = self.plot(marker_x, marker_y, + color=markercolor, linestyle=markerstyle, + marker=markermarker, label="_nolegend_") + + baseline, = self.plot(baseline_x, baseline_y, + color=basecolor, linestyle=basestyle, + marker=basemarker, label="_nolegend_") + + stem_container = StemContainer((markerline, stemlines, baseline), + label=label) + self.add_container(stem_container) + return stem_container + + @_api.make_keyword_only("3.10", "explode") + @_preprocess_data(replace_names=["x", "explode", "labels", "colors"]) + def pie(self, x, explode=None, labels=None, colors=None, + autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, + startangle=0, radius=1, counterclock=True, + wedgeprops=None, textprops=None, center=(0, 0), + frame=False, rotatelabels=False, *, normalize=True, hatch=None): + """ + Plot a pie chart. + + Make a pie chart of array *x*. The fractional area of each wedge is + given by ``x/sum(x)``. + + The wedges are plotted counterclockwise, by default starting from the + x-axis. + + Parameters + ---------- + x : 1D array-like + The wedge sizes. + + explode : array-like, default: None + If not *None*, is a ``len(x)`` array which specifies the fraction + of the radius with which to offset each wedge. + + labels : list, default: None + A sequence of strings providing the labels for each wedge + + colors : :mpltype:`color` or list of :mpltype:`color`, default: None + A sequence of colors through which the pie chart will cycle. If + *None*, will use the colors in the currently active cycle. + + hatch : str or list, default: None + Hatching pattern applied to all pie wedges or sequence of patterns + through which the chart will cycle. For a list of valid patterns, + see :doc:`/gallery/shapes_and_collections/hatch_style_reference`. + + .. versionadded:: 3.7 + + autopct : None or str or callable, default: None + If not *None*, *autopct* is a string or function used to label the + wedges with their numeric value. The label will be placed inside + the wedge. If *autopct* is a format string, the label will be + ``fmt % pct``. If *autopct* is a function, then it will be called. + + pctdistance : float, default: 0.6 + The relative distance along the radius at which the text + generated by *autopct* is drawn. To draw the text outside the pie, + set *pctdistance* > 1. This parameter is ignored if *autopct* is + ``None``. + + labeldistance : float or None, default: 1.1 + The relative distance along the radius at which the labels are + drawn. To draw the labels inside the pie, set *labeldistance* < 1. + If set to ``None``, labels are not drawn but are still stored for + use in `.legend`. + + shadow : bool or dict, default: False + If bool, whether to draw a shadow beneath the pie. If dict, draw a shadow + passing the properties in the dict to `.Shadow`. + + .. versionadded:: 3.8 + *shadow* can be a dict. + + startangle : float, default: 0 degrees + The angle by which the start of the pie is rotated, + counterclockwise from the x-axis. + + radius : float, default: 1 + The radius of the pie. + + counterclock : bool, default: True + Specify fractions direction, clockwise or counterclockwise. + + wedgeprops : dict, default: None + Dict of arguments passed to each `.patches.Wedge` of the pie. + For example, ``wedgeprops = {'linewidth': 3}`` sets the width of + the wedge border lines equal to 3. By default, ``clip_on=False``. + When there is a conflict between these properties and other + keywords, properties passed to *wedgeprops* take precedence. + + textprops : dict, default: None + Dict of arguments to pass to the text objects. + + center : (float, float), default: (0, 0) + The coordinates of the center of the chart. + + frame : bool, default: False + Plot Axes frame with the chart if true. + + rotatelabels : bool, default: False + Rotate each label to the angle of the corresponding slice if true. + + normalize : bool, default: True + When *True*, always make a full pie by normalizing x so that + ``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1`` + and raises a `ValueError` for ``sum(x) > 1``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + patches : list + A sequence of `matplotlib.patches.Wedge` instances + + texts : list + A list of the label `.Text` instances. + + autotexts : list + A list of `.Text` instances for the numeric labels. This will only + be returned if the parameter *autopct* is not *None*. + + Notes + ----- + The pie chart will probably look best if the figure and Axes are + square, or the Axes aspect is equal. + This method sets the aspect ratio of the axis to "equal". + The Axes aspect ratio can be controlled with `.Axes.set_aspect`. + """ + self.set_aspect('equal') + # The use of float32 is "historical", but can't be changed without + # regenerating the test baselines. + x = np.asarray(x, np.float32) + if x.ndim > 1: + raise ValueError("x must be 1D") + + if np.any(x < 0): + raise ValueError("Wedge sizes 'x' must be non negative values") + + sx = x.sum() + + if normalize: + x = x / sx + elif sx > 1: + raise ValueError('Cannot plot an unnormalized pie with sum(x) > 1') + if labels is None: + labels = [''] * len(x) + if explode is None: + explode = [0] * len(x) + if len(x) != len(labels): + raise ValueError(f"'labels' must be of length 'x', not {len(labels)}") + if len(x) != len(explode): + raise ValueError(f"'explode' must be of length 'x', not {len(explode)}") + if colors is None: + get_next_color = self._get_patches_for_fill.get_next_color + else: + color_cycle = itertools.cycle(colors) + + def get_next_color(): + return next(color_cycle) + + hatch_cycle = itertools.cycle(np.atleast_1d(hatch)) + + _api.check_isinstance(Real, radius=radius, startangle=startangle) + if radius <= 0: + raise ValueError(f"'radius' must be a positive number, not {radius}") + + # Starting theta1 is the start fraction of the circle + theta1 = startangle / 360 + + if wedgeprops is None: + wedgeprops = {} + if textprops is None: + textprops = {} + + texts = [] + slices = [] + autotexts = [] + + for frac, label, expl in zip(x, labels, explode): + x, y = center + theta2 = (theta1 + frac) if counterclock else (theta1 - frac) + thetam = 2 * np.pi * 0.5 * (theta1 + theta2) + x += expl * math.cos(thetam) + y += expl * math.sin(thetam) + + w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2), + 360. * max(theta1, theta2), + facecolor=get_next_color(), + hatch=next(hatch_cycle), + clip_on=False, + label=label) + w.set(**wedgeprops) + slices.append(w) + self.add_patch(w) + + if shadow: + # Make sure to add a shadow after the call to add_patch so the + # figure and transform props will be set. + shadow_dict = {'ox': -0.02, 'oy': -0.02, 'label': '_nolegend_'} + if isinstance(shadow, dict): + shadow_dict.update(shadow) + self.add_patch(mpatches.Shadow(w, **shadow_dict)) + + if labeldistance is not None: + xt = x + labeldistance * radius * math.cos(thetam) + yt = y + labeldistance * radius * math.sin(thetam) + label_alignment_h = 'left' if xt > 0 else 'right' + label_alignment_v = 'center' + label_rotation = 'horizontal' + if rotatelabels: + label_alignment_v = 'bottom' if yt > 0 else 'top' + label_rotation = (np.rad2deg(thetam) + + (0 if xt > 0 else 180)) + t = self.text(xt, yt, label, + clip_on=False, + horizontalalignment=label_alignment_h, + verticalalignment=label_alignment_v, + rotation=label_rotation, + size=mpl.rcParams['xtick.labelsize']) + t.set(**textprops) + texts.append(t) + + if autopct is not None: + xt = x + pctdistance * radius * math.cos(thetam) + yt = y + pctdistance * radius * math.sin(thetam) + if isinstance(autopct, str): + s = autopct % (100. * frac) + elif callable(autopct): + s = autopct(100. * frac) + else: + raise TypeError( + 'autopct must be callable or a format string') + if mpl._val_or_rc(textprops.get("usetex"), "text.usetex"): + # escape % (i.e. \%) if it is not already escaped + s = re.sub(r"([^\\])%", r"\1\\%", s) + t = self.text(xt, yt, s, + clip_on=False, + horizontalalignment='center', + verticalalignment='center') + t.set(**textprops) + autotexts.append(t) + + theta1 = theta2 + + if frame: + self._request_autoscale_view() + else: + self.set(frame_on=False, xticks=[], yticks=[], + xlim=(-1.25 + center[0], 1.25 + center[0]), + ylim=(-1.25 + center[1], 1.25 + center[1])) + + if autopct is None: + return slices, texts + else: + return slices, texts, autotexts + + @staticmethod + def _errorevery_to_mask(x, errorevery): + """ + Normalize `errorbar`'s *errorevery* to be a boolean mask for data *x*. + + This function is split out to be usable both by 2D and 3D errorbars. + """ + if isinstance(errorevery, Integral): + errorevery = (0, errorevery) + if isinstance(errorevery, tuple): + if (len(errorevery) == 2 and + isinstance(errorevery[0], Integral) and + isinstance(errorevery[1], Integral)): + errorevery = slice(errorevery[0], None, errorevery[1]) + else: + raise ValueError( + f'{errorevery=!r} is a not a tuple of two integers') + elif isinstance(errorevery, slice): + pass + elif not isinstance(errorevery, str) and np.iterable(errorevery): + try: + x[errorevery] # fancy indexing + except (ValueError, IndexError) as err: + raise ValueError( + f"{errorevery=!r} is iterable but not a valid NumPy fancy " + "index to match 'xerr'/'yerr'") from err + else: + raise ValueError(f"{errorevery=!r} is not a recognized value") + everymask = np.zeros(len(x), bool) + everymask[errorevery] = True + return everymask + + @_api.make_keyword_only("3.10", "ecolor") + @_preprocess_data(replace_names=["x", "y", "xerr", "yerr"], + label_namer="y") + @_docstring.interpd + def errorbar(self, x, y, yerr=None, xerr=None, + fmt='', ecolor=None, elinewidth=None, capsize=None, + barsabove=False, lolims=False, uplims=False, + xlolims=False, xuplims=False, errorevery=1, capthick=None, + **kwargs): + """ + Plot y versus x as lines and/or markers with attached errorbars. + + *x*, *y* define the data locations, *xerr*, *yerr* define the errorbar + sizes. By default, this draws the data markers/lines as well as the + errorbars. Use fmt='none' to draw errorbars without any data markers. + + .. versionadded:: 3.7 + Caps and error lines are drawn in polar coordinates on polar plots. + + + Parameters + ---------- + x, y : float or array-like + The data positions. + + xerr, yerr : float or array-like, shape(N,) or shape(2, N), optional + The errorbar sizes: + + - scalar: Symmetric +/- values for all data points. + - shape(N,): Symmetric +/-values for each data point. + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. + + All values must be >= 0. + + See :doc:`/gallery/statistics/errorbar_features` + for an example on the usage of ``xerr`` and ``yerr``. + + fmt : str, default: '' + The format for the data points / data lines. See `.plot` for + details. + + Use 'none' (case-insensitive) to plot errorbars without any data + markers. + + ecolor : :mpltype:`color`, default: None + The color of the errorbar lines. If None, use the color of the + line connecting the markers. + + elinewidth : float, default: None + The linewidth of the errorbar lines. If None, the linewidth of + the current style is used. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + capthick : float, default: None + An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*). + This setting is a more sensible name for the property that + controls the thickness of the error bar cap in points. For + backwards compatibility, if *mew* or *markeredgewidth* are given, + then they will over-ride *capthick*. This may change in future + releases. + + barsabove : bool, default: False + If True, will plot the errorbars above the plot + symbols. Default is below. + + lolims, uplims, xlolims, xuplims : bool or array-like, default: False + These arguments can be used to indicate that a value gives only + upper/lower limits. In that case a caret symbol is used to + indicate this. *lims*-arguments may be scalars, or array-likes of + the same length as *xerr* and *yerr*. To use limits with inverted + axes, `~.Axes.set_xlim` or `~.Axes.set_ylim` must be called before + :meth:`errorbar`. Note the tricky parameter names: setting e.g. + *lolims* to True means that the y-value is a *lower* limit of the + True value, so, only an *upward*-pointing arrow will be drawn! + + errorevery : int or (int, int), default: 1 + draws error bars on a subset of the data. *errorevery* =N draws + error bars on the points (x[::N], y[::N]). + *errorevery* =(start, N) draws error bars on the points + (x[start::N], y[start::N]). e.g. errorevery=(6, 3) + adds error bars to the data at (x[6], x[9], x[12], x[15], ...). + Used to avoid overlapping error bars when two series share x-axis + values. + + Returns + ------- + `.ErrorbarContainer` + The container contains: + + - data_line : A `~matplotlib.lines.Line2D` instance of x, y plot markers + and/or line. + - caplines : A tuple of `~matplotlib.lines.Line2D` instances of the error + bar caps. + - barlinecols : A tuple of `.LineCollection` with the horizontal and + vertical error ranges. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments are passed on to the `~.Axes.plot` call + drawing the markers. For example, this code makes big red squares + with thick green edges:: + + x, y, yerr = rand(3, 10) + errorbar(x, y, yerr, marker='s', mfc='red', + mec='green', ms=20, mew=4) + + where *mfc*, *mec*, *ms* and *mew* are aliases for the longer + property names, *markerfacecolor*, *markeredgecolor*, *markersize* + and *markeredgewidth*. + + Valid kwargs for the marker properties are: + + - *dashes* + - *dash_capstyle* + - *dash_joinstyle* + - *drawstyle* + - *fillstyle* + - *linestyle* + - *marker* + - *markeredgecolor* + - *markeredgewidth* + - *markerfacecolor* + - *markerfacecoloralt* + - *markersize* + - *markevery* + - *solid_capstyle* + - *solid_joinstyle* + + Refer to the corresponding `.Line2D` property for more details: + + %(Line2D:kwdoc)s + """ + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + # Drop anything that comes in as None to use the default instead. + kwargs = {k: v for k, v in kwargs.items() if v is not None} + kwargs.setdefault('zorder', 2) + + # Casting to object arrays preserves units. + if not isinstance(x, np.ndarray): + x = np.asarray(x, dtype=object) + if not isinstance(y, np.ndarray): + y = np.asarray(y, dtype=object) + + def _upcast_err(err): + """ + Safely handle tuple of containers that carry units. + + This function covers the case where the input to the xerr/yerr is a + length 2 tuple of equal length ndarray-subclasses that carry the + unit information in the container. + + If we have a tuple of nested numpy array (subclasses), we defer + coercing the units to be consistent to the underlying unit + library (and implicitly the broadcasting). + + Otherwise, fallback to casting to an object array. + """ + + if ( + # make sure it is not a scalar + np.iterable(err) and + # and it is not empty + len(err) > 0 and + # and the first element is an array sub-class use + # safe_first_element because getitem is index-first not + # location first on pandas objects so err[0] almost always + # fails. + isinstance(cbook._safe_first_finite(err), np.ndarray) + ): + # Get the type of the first element + atype = type(cbook._safe_first_finite(err)) + # Promote the outer container to match the inner container + if atype is np.ndarray: + # Converts using np.asarray, because data cannot + # be directly passed to init of np.ndarray + return np.asarray(err, dtype=object) + # If atype is not np.ndarray, directly pass data to init. + # This works for types such as unyts and astropy units + return atype(err) + # Otherwise wrap it in an object array + return np.asarray(err, dtype=object) + + if xerr is not None and not isinstance(xerr, np.ndarray): + xerr = _upcast_err(xerr) + if yerr is not None and not isinstance(yerr, np.ndarray): + yerr = _upcast_err(yerr) + x, y = np.atleast_1d(x, y) # Make sure all the args are iterable. + if len(x) != len(y): + raise ValueError("'x' and 'y' must have the same size") + + everymask = self._errorevery_to_mask(x, errorevery) + + label = kwargs.pop("label", None) + kwargs['label'] = '_nolegend_' + + # Create the main line and determine overall kwargs for child artists. + # We avoid calling self.plot() directly, or self._get_lines(), because + # that would call self._process_unit_info again, and do other indirect + # data processing. + (data_line, base_style), = self._get_lines._plot_args( + self, (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True) + + # Do this after creating `data_line` to avoid modifying `base_style`. + if barsabove: + data_line.set_zorder(kwargs['zorder'] - .1) + else: + data_line.set_zorder(kwargs['zorder'] + .1) + + # Add line to plot, or throw it away and use it to determine kwargs. + if fmt.lower() != 'none': + self.add_line(data_line) + else: + data_line = None + # Remove alpha=0 color that _get_lines._plot_args returns for + # 'none' format, and replace it with user-specified color, if + # supplied. + base_style.pop('color') + if 'color' in kwargs: + base_style['color'] = kwargs.pop('color') + + if 'color' not in base_style: + base_style['color'] = 'C0' + if ecolor is None: + ecolor = base_style['color'] + + # Eject any line-specific information from format string, as it's not + # needed for bars or caps. + for key in ['marker', 'markersize', 'markerfacecolor', + 'markerfacecoloralt', + 'markeredgewidth', 'markeredgecolor', 'markevery', + 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle', + 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle', + 'dashes']: + base_style.pop(key, None) + + # Make the style dict for the line collections (the bars). + eb_lines_style = {**base_style, 'color': ecolor} + + if elinewidth is not None: + eb_lines_style['linewidth'] = elinewidth + elif 'linewidth' in kwargs: + eb_lines_style['linewidth'] = kwargs['linewidth'] + + for key in ('transform', 'alpha', 'zorder', 'rasterized'): + if key in kwargs: + eb_lines_style[key] = kwargs[key] + + # Make the style dict for caps (the "hats"). + eb_cap_style = {**base_style, 'linestyle': 'none'} + if capsize is None: + capsize = mpl.rcParams["errorbar.capsize"] + if capsize > 0: + eb_cap_style['markersize'] = 2. * capsize + if capthick is not None: + eb_cap_style['markeredgewidth'] = capthick + + # For backwards-compat, allow explicit setting of + # 'markeredgewidth' to over-ride capthick. + for key in ('markeredgewidth', 'transform', 'alpha', + 'zorder', 'rasterized'): + if key in kwargs: + eb_cap_style[key] = kwargs[key] + eb_cap_style["markeredgecolor"] = ecolor + + barcols = [] + caplines = {'x': [], 'y': []} + + # Vectorized fancy-indexer. + def apply_mask(arrays, mask): + return [array[mask] for array in arrays] + + # dep: dependent dataset, indep: independent dataset + for (dep_axis, dep, err, lolims, uplims, indep, lines_func, + marker, lomarker, himarker) in [ + ("x", x, xerr, xlolims, xuplims, y, self.hlines, + "|", mlines.CARETRIGHTBASE, mlines.CARETLEFTBASE), + ("y", y, yerr, lolims, uplims, x, self.vlines, + "_", mlines.CARETUPBASE, mlines.CARETDOWNBASE), + ]: + if err is None: + continue + lolims = np.broadcast_to(lolims, len(dep)).astype(bool) + uplims = np.broadcast_to(uplims, len(dep)).astype(bool) + try: + np.broadcast_to(err, (2, len(dep))) + except ValueError: + raise ValueError( + f"'{dep_axis}err' (shape: {np.shape(err)}) must be a " + f"scalar or a 1D or (2, n) array-like whose shape matches " + f"'{dep_axis}' (shape: {np.shape(dep)})") from None + if err.dtype is np.dtype(object) and np.any(err == None): # noqa: E711 + raise ValueError( + f"'{dep_axis}err' must not contain None. " + "Use NaN if you want to skip a value.") + + # Raise if any errors are negative, but not if they are nan. + # To avoid nan comparisons (which lead to warnings on some + # platforms), we select with `err==err` (which is False for nan). + # Also, since datetime.timedelta cannot be compared with 0, + # we compare with the negative error instead. + if np.any((check := err[err == err]) < -check): + raise ValueError( + f"'{dep_axis}err' must not contain negative values") + # This is like + # elow, ehigh = np.broadcast_to(...) + # return dep - elow * ~lolims, dep + ehigh * ~uplims + # except that broadcast_to would strip units. + low, high = dep + np.vstack([-(1 - lolims), 1 - uplims]) * err + barcols.append(lines_func( + *apply_mask([indep, low, high], everymask), **eb_lines_style)) + if self.name == "polar" and dep_axis == "x": + for b in barcols: + for p in b.get_paths(): + p._interpolation_steps = 2 + # Normal errorbars for points without upper/lower limits. + nolims = ~(lolims | uplims) + if nolims.any() and capsize > 0: + indep_masked, lo_masked, hi_masked = apply_mask( + [indep, low, high], nolims & everymask) + for lh_masked in [lo_masked, hi_masked]: + # Since this has to work for x and y as dependent data, we + # first set both x and y to the independent variable and + # overwrite the respective dependent data in a second step. + line = mlines.Line2D(indep_masked, indep_masked, + marker=marker, **eb_cap_style) + line.set(**{f"{dep_axis}data": lh_masked}) + caplines[dep_axis].append(line) + for idx, (lims, hl) in enumerate([(lolims, high), (uplims, low)]): + if not lims.any(): + continue + hlmarker = ( + himarker + if self._axis_map[dep_axis].get_inverted() ^ idx + else lomarker) + x_masked, y_masked, hl_masked = apply_mask( + [x, y, hl], lims & everymask) + # As above, we set the dependent data in a second step. + line = mlines.Line2D(x_masked, y_masked, + marker=hlmarker, **eb_cap_style) + line.set(**{f"{dep_axis}data": hl_masked}) + caplines[dep_axis].append(line) + if capsize > 0: + caplines[dep_axis].append(mlines.Line2D( + x_masked, y_masked, marker=marker, **eb_cap_style)) + if self.name == 'polar': + trans_shift = self.transShift + for axis in caplines: + for l in caplines[axis]: + # Rotate caps to be perpendicular to the error bars + for theta, r in zip(l.get_xdata(), l.get_ydata()): + rotation = _ScaledRotation(theta=theta, trans_shift=trans_shift) + if axis == 'y': + rotation += mtransforms.Affine2D().rotate(np.pi / 2) + ms = mmarkers.MarkerStyle(marker=marker, + transform=rotation) + self.add_line(mlines.Line2D([theta], [r], marker=ms, + **eb_cap_style)) + else: + for axis in caplines: + for l in caplines[axis]: + self.add_line(l) + + self._request_autoscale_view() + caplines = caplines['x'] + caplines['y'] + errorbar_container = ErrorbarContainer( + (data_line, tuple(caplines), tuple(barcols)), + has_xerr=(xerr is not None), has_yerr=(yerr is not None), + label=label) + self.add_container(errorbar_container) + + return errorbar_container # (l0, caplines, barcols) + + @_api.make_keyword_only("3.10", "notch") + @_preprocess_data() + @_api.rename_parameter("3.9", "labels", "tick_labels") + def boxplot(self, x, notch=None, sym=None, vert=None, + orientation='vertical', whis=None, positions=None, + widths=None, patch_artist=None, bootstrap=None, + usermedians=None, conf_intervals=None, + meanline=None, showmeans=None, showcaps=None, + showbox=None, showfliers=None, boxprops=None, + tick_labels=None, flierprops=None, medianprops=None, + meanprops=None, capprops=None, whiskerprops=None, + manage_ticks=True, autorange=False, zorder=None, + capwidths=None, label=None): + """ + Draw a box and whisker plot. + + The box extends from the first quartile (Q1) to the third + quartile (Q3) of the data, with a line at the median. + The whiskers extend from the box to the farthest data point + lying within 1.5x the inter-quartile range (IQR) from the box. + Flier points are those past the end of the whiskers. + See https://en.wikipedia.org/wiki/Box_plot for reference. + + .. code-block:: none + + Q1-1.5IQR Q1 median Q3 Q3+1.5IQR + |-----:-----| + o |--------| : |--------| o o + |-----:-----| + flier <-----------> fliers + IQR + + + Parameters + ---------- + x : Array or a sequence of vectors. + The input data. If a 2D array, a boxplot is drawn for each column + in *x*. If a sequence of 1D arrays, a boxplot is drawn for each + array in *x*. + + notch : bool, default: :rc:`boxplot.notch` + Whether to draw a notched boxplot (`True`), or a rectangular + boxplot (`False`). The notches represent the confidence interval + (CI) around the median. The documentation for *bootstrap* + describes how the locations of the notches are computed by + default, but their locations may also be overridden by setting the + *conf_intervals* parameter. + + .. note:: + + In cases where the values of the CI are less than the + lower quartile or greater than the upper quartile, the + notches will extend beyond the box, giving it a + distinctive "flipped" appearance. This is expected + behavior and consistent with other statistical + visualization packages. + + sym : str, optional + The default symbol for flier points. An empty string ('') hides + the fliers. If `None`, then the fliers default to 'b+'. More + control is provided by the *flierprops* parameter. + + vert : bool, optional + .. deprecated:: 3.11 + Use *orientation* instead. + + This is a pending deprecation for 3.10, with full deprecation + in 3.11 and removal in 3.13. + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the boxes vertically. + If False, plots the boxes horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the boxes horizontally. + Otherwise, plots the boxes vertically. + + .. versionadded:: 3.10 + + whis : float or (float, float), default: 1.5 + The position of the whiskers. + + If a float, the lower whisker is at the lowest datum above + ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum + below ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and + third quartiles. The default value of ``whis = 1.5`` corresponds + to Tukey's original definition of boxplots. + + If a pair of floats, they indicate the percentiles at which to + draw the whiskers (e.g., (5, 95)). In particular, setting this to + (0, 100) results in whiskers covering the whole range of the data. + + In the edge case where ``Q1 == Q3``, *whis* is automatically set + to (0, 100) (cover the whole range of the data) if *autorange* is + True. + + Beyond the whiskers, data are considered outliers and are plotted + as individual points. + + bootstrap : int, optional + Specifies whether to bootstrap the confidence intervals + around the median for notched boxplots. If *bootstrap* is + None, no bootstrapping is performed, and notches are + calculated using a Gaussian-based asymptotic approximation + (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and + Kendall and Stuart, 1967). Otherwise, bootstrap specifies + the number of times to bootstrap the median to determine its + 95% confidence intervals. Values between 1000 and 10000 are + recommended. + + usermedians : 1D array-like, optional + A 1D array-like of length ``len(x)``. Each entry that is not + `None` forces the value of the median for the corresponding + dataset. For entries that are `None`, the medians are computed + by Matplotlib as normal. + + conf_intervals : array-like, optional + A 2D array-like of shape ``(len(x), 2)``. Each entry that is not + None forces the location of the corresponding notch (which is + only drawn if *notch* is `True`). For entries that are `None`, + the notches are computed by the method specified by the other + parameters (e.g., *bootstrap*). + + positions : array-like, optional + The positions of the boxes. The ticks and limits are + automatically set to match the positions. Defaults to + ``range(1, N+1)`` where N is the number of boxes to be drawn. + + widths : float or array-like + The widths of the boxes. The default is 0.5, or ``0.15*(distance + between extreme positions)``, if that is smaller. + + patch_artist : bool, default: :rc:`boxplot.patchartist` + If `False` produces boxes with the Line2D artist. Otherwise, + boxes are drawn with Patch artists. + + tick_labels : list of str, optional + The tick labels of each boxplot. + Ticks are always placed at the box *positions*. If *tick_labels* is given, + the ticks are labelled accordingly. Otherwise, they keep their numeric + values. + + .. versionchanged:: 3.9 + Renamed from *labels*, which is deprecated since 3.9 + and will be removed in 3.11. + + manage_ticks : bool, default: True + If True, the tick locations and labels will be adjusted to match + the boxplot positions. + + autorange : bool, default: False + When `True` and the data are distributed such that the 25th and + 75th percentiles are equal, *whis* is set to (0, 100) such + that the whisker ends are at the minimum and maximum of the data. + + meanline : bool, default: :rc:`boxplot.meanline` + If `True` (and *showmeans* is `True`), will try to render the + mean as a line spanning the full width of the box according to + *meanprops* (see below). Not recommended if *shownotches* is also + True. Otherwise, means will be shown as points. + + zorder : float, default: ``Line2D.zorder = 2`` + The zorder of the boxplot. + + Returns + ------- + dict + A dictionary mapping each component of the boxplot to a list + of the `.Line2D` instances created. That dictionary has the + following keys (assuming vertical boxplots): + + - ``boxes``: the main body of the boxplot showing the + quartiles and the median's confidence intervals if + enabled. + + - ``medians``: horizontal lines at the median of each box. + + - ``whiskers``: the vertical lines extending to the most + extreme, non-outlier data points. + + - ``caps``: the horizontal lines at the ends of the + whiskers. + + - ``fliers``: points representing data that extend beyond + the whiskers (fliers). + + - ``means``: points or lines representing the means. + + Other Parameters + ---------------- + showcaps : bool, default: :rc:`boxplot.showcaps` + Show the caps on the ends of whiskers. + showbox : bool, default: :rc:`boxplot.showbox` + Show the central box. + showfliers : bool, default: :rc:`boxplot.showfliers` + Show the outliers beyond the caps. + showmeans : bool, default: :rc:`boxplot.showmeans` + Show the arithmetic means. + capprops : dict, default: None + The style of the caps. + capwidths : float or array, default: None + The widths of the caps. + boxprops : dict, default: None + The style of the box. + whiskerprops : dict, default: None + The style of the whiskers. + flierprops : dict, default: None + The style of the fliers. + medianprops : dict, default: None + The style of the median. + meanprops : dict, default: None + The style of the mean. + label : str or list of str, optional + Legend labels. Use a single string when all boxes have the same style and + you only want a single legend entry for them. Use a list of strings to + label all boxes individually. To be distinguishable, the boxes should be + styled individually, which is currently only possible by modifying the + returned artists, see e.g. :doc:`/gallery/statistics/boxplot_demo`. + + In the case of a single string, the legend entry will technically be + associated with the first box only. By default, the legend will show the + median line (``result["medians"]``); if *patch_artist* is True, the legend + will show the box `.Patch` artists (``result["boxes"]``) instead. + + .. versionadded:: 3.9 + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + See Also + -------- + .Axes.bxp : Draw a boxplot from pre-computed statistics. + violinplot : Draw an estimate of the probability density function. + """ + + # Missing arguments default to rcParams. + if whis is None: + whis = mpl.rcParams['boxplot.whiskers'] + if bootstrap is None: + bootstrap = mpl.rcParams['boxplot.bootstrap'] + + bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap, + labels=tick_labels, autorange=autorange) + if notch is None: + notch = mpl.rcParams['boxplot.notch'] + if patch_artist is None: + patch_artist = mpl.rcParams['boxplot.patchartist'] + if meanline is None: + meanline = mpl.rcParams['boxplot.meanline'] + if showmeans is None: + showmeans = mpl.rcParams['boxplot.showmeans'] + if showcaps is None: + showcaps = mpl.rcParams['boxplot.showcaps'] + if showbox is None: + showbox = mpl.rcParams['boxplot.showbox'] + if showfliers is None: + showfliers = mpl.rcParams['boxplot.showfliers'] + + if boxprops is None: + boxprops = {} + if whiskerprops is None: + whiskerprops = {} + if capprops is None: + capprops = {} + if medianprops is None: + medianprops = {} + if meanprops is None: + meanprops = {} + if flierprops is None: + flierprops = {} + + if patch_artist: + boxprops['linestyle'] = 'solid' # Not consistent with bxp. + if 'color' in boxprops: + boxprops['edgecolor'] = boxprops.pop('color') + + # if non-default sym value, put it into the flier dictionary + # the logic for providing the default symbol ('b+') now lives + # in bxp in the initial value of flierkw + # handle all of the *sym* related logic here so we only have to pass + # on the flierprops dict. + if sym is not None: + # no-flier case, which should really be done with + # 'showfliers=False' but none-the-less deal with it to keep back + # compatibility + if sym == '': + # blow away existing dict and make one for invisible markers + flierprops = dict(linestyle='none', marker='', color='none') + # turn the fliers off just to be safe + showfliers = False + # now process the symbol string + else: + # process the symbol string + # discarded linestyle + _, marker, color = _process_plot_format(sym) + # if we have a marker, use it + if marker is not None: + flierprops['marker'] = marker + # if we have a color, use it + if color is not None: + # assume that if color is passed in the user want + # filled symbol, if the users want more control use + # flierprops + flierprops['color'] = color + flierprops['markerfacecolor'] = color + flierprops['markeredgecolor'] = color + + # replace medians if necessary: + if usermedians is not None: + if (len(np.ravel(usermedians)) != len(bxpstats) or + np.shape(usermedians)[0] != len(bxpstats)): + raise ValueError( + "'usermedians' and 'x' have different lengths") + else: + # reassign medians as necessary + for stats, med in zip(bxpstats, usermedians): + if med is not None: + stats['med'] = med + + if conf_intervals is not None: + if len(conf_intervals) != len(bxpstats): + raise ValueError( + "'conf_intervals' and 'x' have different lengths") + else: + for stats, ci in zip(bxpstats, conf_intervals): + if ci is not None: + if len(ci) != 2: + raise ValueError('each confidence interval must ' + 'have two values') + else: + if ci[0] is not None: + stats['cilo'] = ci[0] + if ci[1] is not None: + stats['cihi'] = ci[1] + + artists = self.bxp(bxpstats, positions=positions, widths=widths, + vert=vert, patch_artist=patch_artist, + shownotches=notch, showmeans=showmeans, + showcaps=showcaps, showbox=showbox, + boxprops=boxprops, flierprops=flierprops, + medianprops=medianprops, meanprops=meanprops, + meanline=meanline, showfliers=showfliers, + capprops=capprops, whiskerprops=whiskerprops, + manage_ticks=manage_ticks, zorder=zorder, + capwidths=capwidths, label=label, + orientation=orientation) + return artists + + @_api.make_keyword_only("3.10", "widths") + def bxp(self, bxpstats, positions=None, widths=None, vert=None, + orientation='vertical', patch_artist=False, shownotches=False, + showmeans=False, showcaps=True, showbox=True, showfliers=True, + boxprops=None, whiskerprops=None, flierprops=None, + medianprops=None, capprops=None, meanprops=None, + meanline=False, manage_ticks=True, zorder=None, + capwidths=None, label=None): + """ + Draw a box and whisker plot from pre-computed statistics. + + The box extends from the first quartile *q1* to the third + quartile *q3* of the data, with a line at the median (*med*). + The whiskers extend from *whislow* to *whishi*. + Flier points are markers past the end of the whiskers. + See https://en.wikipedia.org/wiki/Box_plot for reference. + + .. code-block:: none + + whislow q1 med q3 whishi + |-----:-----| + o |--------| : |--------| o o + |-----:-----| + flier fliers + + .. note:: + This is a low-level drawing function for when you already + have the statistical parameters. If you want a boxplot based + on a dataset, use `~.Axes.boxplot` instead. + + Parameters + ---------- + bxpstats : list of dicts + A list of dictionaries containing stats for each boxplot. + Required keys are: + + - ``med``: Median (float). + - ``q1``, ``q3``: First & third quartiles (float). + - ``whislo``, ``whishi``: Lower & upper whisker positions (float). + + Optional keys are: + + - ``mean``: Mean (float). Needed if ``showmeans=True``. + - ``fliers``: Data beyond the whiskers (array-like). + Needed if ``showfliers=True``. + - ``cilo``, ``cihi``: Lower & upper confidence intervals + about the median. Needed if ``shownotches=True``. + - ``label``: Name of the dataset (str). If available, + this will be used a tick label for the boxplot + + positions : array-like, default: [1, 2, ..., n] + The positions of the boxes. The ticks and limits + are automatically set to match the positions. + + widths : float or array-like, default: None + The widths of the boxes. The default is + ``clip(0.15*(distance between extreme positions), 0.15, 0.5)``. + + capwidths : float or array-like, default: None + Either a scalar or a vector and sets the width of each cap. + The default is ``0.5*(width of the box)``, see *widths*. + + vert : bool, optional + .. deprecated:: 3.11 + Use *orientation* instead. + + This is a pending deprecation for 3.10, with full deprecation + in 3.11 and removal in 3.13. + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the boxes vertically. + If False, plots the boxes horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the boxes horizontally. + Otherwise, plots the boxes vertically. + + .. versionadded:: 3.10 + + patch_artist : bool, default: False + If `False` produces boxes with the `.Line2D` artist. + If `True` produces boxes with the `~matplotlib.patches.Patch` artist. + + shownotches, showmeans, showcaps, showbox, showfliers : bool + Whether to draw the CI notches, the mean value (both default to + False), the caps, the box, and the fliers (all three default to + True). + + boxprops, whiskerprops, capprops, flierprops, medianprops, meanprops :\ + dict, optional + Artist properties for the boxes, whiskers, caps, fliers, medians, and + means. + + meanline : bool, default: False + If `True` (and *showmeans* is `True`), will try to render the mean + as a line spanning the full width of the box according to + *meanprops*. Not recommended if *shownotches* is also True. + Otherwise, means will be shown as points. + + manage_ticks : bool, default: True + If True, the tick locations and labels will be adjusted to match the + boxplot positions. + + label : str or list of str, optional + Legend labels. Use a single string when all boxes have the same style and + you only want a single legend entry for them. Use a list of strings to + label all boxes individually. To be distinguishable, the boxes should be + styled individually, which is currently only possible by modifying the + returned artists, see e.g. :doc:`/gallery/statistics/boxplot_demo`. + + In the case of a single string, the legend entry will technically be + associated with the first box only. By default, the legend will show the + median line (``result["medians"]``); if *patch_artist* is True, the legend + will show the box `.Patch` artists (``result["boxes"]``) instead. + + .. versionadded:: 3.9 + + zorder : float, default: ``Line2D.zorder = 2`` + The zorder of the resulting boxplot. + + Returns + ------- + dict + A dictionary mapping each component of the boxplot to a list + of the `.Line2D` instances created. That dictionary has the + following keys (assuming vertical boxplots): + + - ``boxes``: main bodies of the boxplot showing the quartiles, and + the median's confidence intervals if enabled. + - ``medians``: horizontal lines at the median of each box. + - ``whiskers``: vertical lines up to the last non-outlier data. + - ``caps``: horizontal lines at the ends of the whiskers. + - ``fliers``: points representing data beyond the whiskers (fliers). + - ``means``: points or lines representing the means. + + See Also + -------- + boxplot : Draw a boxplot from data instead of pre-computed statistics. + """ + # Clamp median line to edge of box by default. + medianprops = { + "solid_capstyle": "butt", + "dash_capstyle": "butt", + **(medianprops or {}), + } + meanprops = { + "solid_capstyle": "butt", + "dash_capstyle": "butt", + **(meanprops or {}), + } + + # lists of artists to be output + whiskers = [] + caps = [] + boxes = [] + medians = [] + means = [] + fliers = [] + + # empty list of xticklabels + datalabels = [] + + # Use default zorder if none specified + if zorder is None: + zorder = mlines.Line2D.zorder + + zdelta = 0.1 + + def merge_kw_rc(subkey, explicit, zdelta=0, usemarker=True): + d = {k.split('.')[-1]: v for k, v in mpl.rcParams.items() + if k.startswith(f'boxplot.{subkey}props')} + d['zorder'] = zorder + zdelta + if not usemarker: + d['marker'] = '' + d.update(cbook.normalize_kwargs(explicit, mlines.Line2D)) + return d + + box_kw = { + 'linestyle': mpl.rcParams['boxplot.boxprops.linestyle'], + 'linewidth': mpl.rcParams['boxplot.boxprops.linewidth'], + 'edgecolor': mpl.rcParams['boxplot.boxprops.color'], + 'facecolor': ('white' if mpl.rcParams['_internal.classic_mode'] + else mpl.rcParams['patch.facecolor']), + 'zorder': zorder, + **cbook.normalize_kwargs(boxprops, mpatches.PathPatch) + } if patch_artist else merge_kw_rc('box', boxprops, usemarker=False) + whisker_kw = merge_kw_rc('whisker', whiskerprops, usemarker=False) + cap_kw = merge_kw_rc('cap', capprops, usemarker=False) + flier_kw = merge_kw_rc('flier', flierprops) + median_kw = merge_kw_rc('median', medianprops, zdelta, usemarker=False) + mean_kw = merge_kw_rc('mean', meanprops, zdelta) + removed_prop = 'marker' if meanline else 'linestyle' + # Only remove the property if it's not set explicitly as a parameter. + if meanprops is None or removed_prop not in meanprops: + mean_kw[removed_prop] = '' + + # vert and orientation parameters are linked until vert's + # deprecation period expires. vert only takes precedence + # if set to False. + if vert is None: + vert = mpl.rcParams['boxplot.vertical'] + else: + _api.warn_deprecated( + "3.11", + name="vert: bool", + alternative="orientation: {'vertical', 'horizontal'}", + pending=True, + ) + if vert is False: + orientation = 'horizontal' + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if not mpl.rcParams['boxplot.vertical']: + _api.warn_deprecated( + "3.10", + name='boxplot.vertical', obj_type="rcparam" + ) + + # vertical or horizontal plot? + maybe_swap = slice(None) if orientation == 'vertical' else slice(None, None, -1) + + def do_plot(xs, ys, **kwargs): + return self.plot(*[xs, ys][maybe_swap], **kwargs)[0] + + def do_patch(xs, ys, **kwargs): + path = mpath.Path._create_closed( + np.column_stack([xs, ys][maybe_swap])) + patch = mpatches.PathPatch(path, **kwargs) + self.add_artist(patch) + return patch + + # input validation + N = len(bxpstats) + datashape_message = ("List of boxplot statistics and `{0}` " + "values must have same the length") + # check position + if positions is None: + positions = list(range(1, N + 1)) + elif len(positions) != N: + raise ValueError(datashape_message.format("positions")) + + positions = np.array(positions) + if len(positions) > 0 and not all(isinstance(p, Real) for p in positions): + raise TypeError("positions should be an iterable of numbers") + + # width + if widths is None: + widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N + elif np.isscalar(widths): + widths = [widths] * N + elif len(widths) != N: + raise ValueError(datashape_message.format("widths")) + + # capwidth + if capwidths is None: + capwidths = 0.5 * np.array(widths) + elif np.isscalar(capwidths): + capwidths = [capwidths] * N + elif len(capwidths) != N: + raise ValueError(datashape_message.format("capwidths")) + + for pos, width, stats, capwidth in zip(positions, widths, bxpstats, + capwidths): + # try to find a new label + datalabels.append(stats.get('label', pos)) + + # whisker coords + whis_x = [pos, pos] + whislo_y = [stats['q1'], stats['whislo']] + whishi_y = [stats['q3'], stats['whishi']] + # cap coords + cap_left = pos - capwidth * 0.5 + cap_right = pos + capwidth * 0.5 + cap_x = [cap_left, cap_right] + cap_lo = np.full(2, stats['whislo']) + cap_hi = np.full(2, stats['whishi']) + # box and median coords + box_left = pos - width * 0.5 + box_right = pos + width * 0.5 + med_y = [stats['med'], stats['med']] + # notched boxes + if shownotches: + notch_left = pos - width * 0.25 + notch_right = pos + width * 0.25 + box_x = [box_left, box_right, box_right, notch_right, + box_right, box_right, box_left, box_left, notch_left, + box_left, box_left] + box_y = [stats['q1'], stats['q1'], stats['cilo'], + stats['med'], stats['cihi'], stats['q3'], + stats['q3'], stats['cihi'], stats['med'], + stats['cilo'], stats['q1']] + med_x = [notch_left, notch_right] + # plain boxes + else: + box_x = [box_left, box_right, box_right, box_left, box_left] + box_y = [stats['q1'], stats['q1'], stats['q3'], stats['q3'], + stats['q1']] + med_x = [box_left, box_right] + + # maybe draw the box + if showbox: + do_box = do_patch if patch_artist else do_plot + boxes.append(do_box(box_x, box_y, **box_kw)) + median_kw.setdefault('label', '_nolegend_') + # draw the whiskers + whisker_kw.setdefault('label', '_nolegend_') + whiskers.append(do_plot(whis_x, whislo_y, **whisker_kw)) + whiskers.append(do_plot(whis_x, whishi_y, **whisker_kw)) + # maybe draw the caps + if showcaps: + cap_kw.setdefault('label', '_nolegend_') + caps.append(do_plot(cap_x, cap_lo, **cap_kw)) + caps.append(do_plot(cap_x, cap_hi, **cap_kw)) + # draw the medians + medians.append(do_plot(med_x, med_y, **median_kw)) + # maybe draw the means + if showmeans: + if meanline: + means.append(do_plot( + [box_left, box_right], [stats['mean'], stats['mean']], + **mean_kw + )) + else: + means.append(do_plot([pos], [stats['mean']], **mean_kw)) + # maybe draw the fliers + if showfliers: + flier_kw.setdefault('label', '_nolegend_') + flier_x = np.full(len(stats['fliers']), pos, dtype=np.float64) + flier_y = stats['fliers'] + fliers.append(do_plot(flier_x, flier_y, **flier_kw)) + + # Set legend labels + if label: + box_or_med = boxes if showbox and patch_artist else medians + if cbook.is_scalar_or_string(label): + # assign the label only to the first box + box_or_med[0].set_label(label) + else: # label is a sequence + if len(box_or_med) != len(label): + raise ValueError(datashape_message.format("label")) + for artist, lbl in zip(box_or_med, label): + artist.set_label(lbl) + + if manage_ticks: + axis_name = "x" if orientation == 'vertical' else "y" + interval = getattr(self.dataLim, f"interval{axis_name}") + axis = self._axis_map[axis_name] + positions = axis.convert_units(positions) + # The 0.5 additional padding ensures reasonable-looking boxes + # even when drawing a single box. We set the sticky edge to + # prevent margins expansion, in order to match old behavior (back + # when separate calls to boxplot() would completely reset the axis + # limits regardless of what was drawn before). The sticky edges + # are attached to the median lines, as they are always present. + interval[:] = (min(interval[0], min(positions) - .5), + max(interval[1], max(positions) + .5)) + for median, position in zip(medians, positions): + getattr(median.sticky_edges, axis_name).extend( + [position - .5, position + .5]) + # Modified from Axis.set_ticks and Axis.set_ticklabels. + locator = axis.get_major_locator() + if not isinstance(axis.get_major_locator(), + mticker.FixedLocator): + locator = mticker.FixedLocator([]) + axis.set_major_locator(locator) + locator.locs = np.array([*locator.locs, *positions]) + formatter = axis.get_major_formatter() + if not isinstance(axis.get_major_formatter(), + mticker.FixedFormatter): + formatter = mticker.FixedFormatter([]) + axis.set_major_formatter(formatter) + formatter.seq = [*formatter.seq, *datalabels] + + self._request_autoscale_view() + + return dict(whiskers=whiskers, caps=caps, boxes=boxes, + medians=medians, fliers=fliers, means=means) + + @staticmethod + def _parse_scatter_color_args(c, edgecolors, kwargs, xsize, + get_next_color_func): + """ + Helper function to process color related arguments of `.Axes.scatter`. + + Argument precedence for facecolors: + + - c (if not None) + - kwargs['facecolor'] + - kwargs['facecolors'] + - kwargs['color'] (==kwcolor) + - 'b' if in classic mode else the result of ``get_next_color_func()`` + + Argument precedence for edgecolors: + + - kwargs['edgecolor'] + - edgecolors (is an explicit kw argument in scatter()) + - kwargs['color'] (==kwcolor) + - 'face' if not in classic mode else None + + Parameters + ---------- + c : :mpltype:`color` or array-like or list of :mpltype:`color` or None + See argument description of `.Axes.scatter`. + edgecolors : :mpltype:`color` or sequence of color or {'face', 'none'} or None + See argument description of `.Axes.scatter`. + kwargs : dict + Additional kwargs. If these keys exist, we pop and process them: + 'facecolors', 'facecolor', 'edgecolor', 'color' + Note: The dict is modified by this function. + xsize : int + The size of the x and y arrays passed to `.Axes.scatter`. + get_next_color_func : callable + A callable that returns a color. This color is used as facecolor + if no other color is provided. + + Note, that this is a function rather than a fixed color value to + support conditional evaluation of the next color. As of the + current implementation obtaining the next color from the + property cycle advances the cycle. This must only happen if we + actually use the color, which will only be decided within this + method. + + Returns + ------- + c + The input *c* if it was not *None*, else a color derived from the + other inputs or defaults. + colors : array(N, 4) or None + The facecolors as RGBA values, or *None* if a colormap is used. + edgecolors + The edgecolor. + + """ + facecolors = kwargs.pop('facecolors', None) + facecolors = kwargs.pop('facecolor', facecolors) + edgecolors = kwargs.pop('edgecolor', edgecolors) + + kwcolor = kwargs.pop('color', None) + + if kwcolor is not None and c is not None: + raise ValueError("Supply a 'c' argument or a 'color'" + " kwarg but not both; they differ but" + " their functionalities overlap.") + + if kwcolor is not None: + try: + mcolors.to_rgba_array(kwcolor) + except ValueError as err: + raise ValueError( + "'color' kwarg must be a color or sequence of color " + "specs. For a sequence of values to be color-mapped, use " + "the 'c' argument instead.") from err + if edgecolors is None: + edgecolors = kwcolor + if facecolors is None: + facecolors = kwcolor + + if edgecolors is None and not mpl.rcParams['_internal.classic_mode']: + edgecolors = mpl.rcParams['scatter.edgecolors'] + + # Raise a warning if both `c` and `facecolor` are set (issue #24404). + if c is not None and facecolors is not None: + _api.warn_external( + "You passed both c and facecolor/facecolors for the markers. " + "c has precedence over facecolor/facecolors. " + "This behavior may change in the future." + ) + + c_was_none = c is None + if c is None: + c = (facecolors if facecolors is not None + else "b" if mpl.rcParams['_internal.classic_mode'] + else get_next_color_func()) + c_is_string_or_strings = ( + isinstance(c, str) + or (np.iterable(c) and len(c) > 0 + and isinstance(cbook._safe_first_finite(c), str))) + + def invalid_shape_exception(csize, xsize): + return ValueError( + f"'c' argument has {csize} elements, which is inconsistent " + f"with 'x' and 'y' with size {xsize}.") + + c_is_mapped = False # Unless proven otherwise below. + valid_shape = True # Unless proven otherwise below. + if not c_was_none and kwcolor is None and not c_is_string_or_strings: + try: # First, does 'c' look suitable for value-mapping? + c = np.asanyarray(c, dtype=float) + except ValueError: + pass # Failed to convert to float array; must be color specs. + else: + # handle the documented special case of a 2D array with 1 + # row which as RGB(A) to broadcast. + if c.shape == (1, 4) or c.shape == (1, 3): + c_is_mapped = False + if c.size != xsize: + valid_shape = False + # If c can be either mapped values or an RGB(A) color, prefer + # the former if shapes match, the latter otherwise. + elif c.size == xsize: + c = c.ravel() + c_is_mapped = True + else: # Wrong size; it must not be intended for mapping. + if c.shape in ((3,), (4,)): + _api.warn_external( + "*c* argument looks like a single numeric RGB or " + "RGBA sequence, which should be avoided as value-" + "mapping will have precedence in case its length " + "matches with *x* & *y*. Please use the *color* " + "keyword-argument or provide a 2D array " + "with a single row if you intend to specify " + "the same RGB or RGBA value for all points.") + valid_shape = False + if not c_is_mapped: + try: # Is 'c' acceptable as PathCollection facecolors? + colors = mcolors.to_rgba_array(c) + except (TypeError, ValueError) as err: + if "RGBA values should be within 0-1 range" in str(err): + raise + else: + if not valid_shape: + raise invalid_shape_exception(c.size, xsize) from err + # Both the mapping *and* the RGBA conversion failed: pretty + # severe failure => one may appreciate a verbose feedback. + raise ValueError( + f"'c' argument must be a color, a sequence of colors, " + f"or a sequence of numbers, not {c!r}") from err + else: + if len(colors) not in (0, 1, xsize): + # NB: remember that a single color is also acceptable. + # Besides *colors* will be an empty array if c == 'none'. + raise invalid_shape_exception(len(colors), xsize) + else: + colors = None # use cmap, norm after collection is created + return c, colors, edgecolors + + @_api.make_keyword_only("3.10", "marker") + @_preprocess_data(replace_names=["x", "y", "s", "linewidths", + "edgecolors", "c", "facecolor", + "facecolors", "color"], + label_namer="y") + @_docstring.interpd + def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, + vmin=None, vmax=None, alpha=None, linewidths=None, *, + edgecolors=None, colorizer=None, plotnonfinite=False, **kwargs): + """ + A scatter plot of *y* vs. *x* with varying marker size and/or color. + + Parameters + ---------- + x, y : float or array-like, shape (n, ) + The data positions. + + s : float or array-like, shape (n, ), optional + The marker size in points**2 (typographic points are 1/72 in.). + Default is ``rcParams['lines.markersize'] ** 2``. + + The linewidth and edgecolor can visually interact with the marker + size, and can lead to artifacts if the marker size is smaller than + the linewidth. + + If the linewidth is greater than 0 and the edgecolor is anything + but *'none'*, then the effective size of the marker will be + increased by half the linewidth because the stroke will be centered + on the edge of the shape. + + To eliminate the marker edge either set *linewidth=0* or + *edgecolor='none'*. + + c : array-like or list of :mpltype:`color` or :mpltype:`color`, optional + The marker colors. Possible values: + + - A scalar or sequence of n numbers to be mapped to colors using + *cmap* and *norm*. + - A 2D array in which the rows are RGB or RGBA. + - A sequence of colors of length n. + - A single color format string. + + Note that *c* should not be a single numeric RGB or RGBA sequence + because that is indistinguishable from an array of values to be + colormapped. If you want to specify the same RGB or RGBA value for + all points, use a 2D array with a single row. Otherwise, + value-matching will have precedence in case of a size matching with + *x* and *y*. + + If you wish to specify a single color for all points + prefer the *color* keyword argument. + + Defaults to `None`. In that case the marker color is determined + by the value of *color*, *facecolor* or *facecolors*. In case + those are not specified or `None`, the marker color is determined + by the next color of the ``Axes``' current "shape and fill" color + cycle. This cycle defaults to :rc:`axes.prop_cycle`. + + marker : `~.markers.MarkerStyle`, default: :rc:`scatter.marker` + The marker style. *marker* can be either an instance of the class + or the text shorthand for a particular marker. + See :mod:`matplotlib.markers` for more information about marker + styles. + + %(cmap_doc)s + + This parameter is ignored if *c* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *c* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *c* is RGB(A). + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + linewidths : float or array-like, default: :rc:`lines.linewidth` + The linewidth of the marker edges. Note: The default *edgecolors* + is 'face'. You may want to change this as well. + + edgecolors : {'face', 'none', *None*} or :mpltype:`color` or list of \ +:mpltype:`color`, default: :rc:`scatter.edgecolors` + The edge color of the marker. Possible values: + + - 'face': The edge color will always be the same as the face color. + - 'none': No patch boundary will be drawn. + - A color or sequence of colors. + + For non-filled markers, *edgecolors* is ignored. Instead, the color + is determined like with 'face', i.e. from *c*, *colors*, or + *facecolors*. + + %(colorizer_doc)s + + This parameter is ignored if *c* is RGB(A). + + plotnonfinite : bool, default: False + Whether to plot points with nonfinite *c* (i.e. ``inf``, ``-inf`` + or ``nan``). If ``True`` the points are drawn with the *bad* + colormap color (see `.Colormap.set_bad`). + + Returns + ------- + `~matplotlib.collections.PathCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.PathCollection` properties + %(PathCollection:kwdoc)s + + See Also + -------- + plot : To plot scatter plots when markers are identical in size and + color. + + Notes + ----- + * The `.plot` function will be faster for scatterplots where markers + don't vary in size or color. + + * Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which + case all masks will be combined and only unmasked points will be + plotted. + + * Fundamentally, scatter works with 1D arrays; *x*, *y*, *s*, and *c* + may be input as N-D arrays, but within scatter they will be + flattened. The exception is *c*, which will be flattened only if its + size matches the size of *x* and *y*. + + """ + # add edgecolors and linewidths to kwargs so they + # can be processed by normailze_kwargs + if edgecolors is not None: + kwargs.update({'edgecolors': edgecolors}) + if linewidths is not None: + kwargs.update({'linewidths': linewidths}) + + kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) + # re direct linewidth and edgecolor so it can be + # further processed by the rest of the function + linewidths = kwargs.pop('linewidth', None) + edgecolors = kwargs.pop('edgecolor', None) + # Process **kwargs to handle aliases, conflicts with explicit kwargs: + x, y = self._process_unit_info([("x", x), ("y", y)], kwargs) + # np.ma.ravel yields an ndarray, not a masked array, + # unless its argument is a masked array. + x = np.ma.ravel(x) + y = np.ma.ravel(y) + if x.size != y.size: + raise ValueError("x and y must be the same size") + + if s is None: + s = (20 if mpl.rcParams['_internal.classic_mode'] else + mpl.rcParams['lines.markersize'] ** 2.0) + s = np.ma.ravel(s) + if (len(s) not in (1, x.size) or + (not np.issubdtype(s.dtype, np.floating) and + not np.issubdtype(s.dtype, np.integer))): + raise ValueError( + "s must be a scalar, " + "or float array-like with the same size as x and y") + + # get the original edgecolor the user passed before we normalize + orig_edgecolor = edgecolors + if edgecolors is None: + orig_edgecolor = kwargs.get('edgecolor', None) + c, colors, edgecolors = \ + self._parse_scatter_color_args( + c, edgecolors, kwargs, x.size, + get_next_color_func=self._get_patches_for_fill.get_next_color) + + if plotnonfinite and colors is None: + c = np.ma.masked_invalid(c) + x, y, s, edgecolors, linewidths = \ + cbook._combine_masks(x, y, s, edgecolors, linewidths) + else: + x, y, s, c, colors, edgecolors, linewidths = \ + cbook._combine_masks( + x, y, s, c, colors, edgecolors, linewidths) + # Unmask edgecolors if it was actually a single RGB or RGBA. + if (x.size in (3, 4) + and np.ma.is_masked(edgecolors) + and not np.ma.is_masked(orig_edgecolor)): + edgecolors = edgecolors.data + + scales = s # Renamed for readability below. + + # load default marker from rcParams + if marker is None: + marker = mpl.rcParams['scatter.marker'] + + if isinstance(marker, mmarkers.MarkerStyle): + marker_obj = marker + else: + marker_obj = mmarkers.MarkerStyle(marker) + + path = marker_obj.get_path().transformed( + marker_obj.get_transform()) + if not marker_obj.is_filled(): + if orig_edgecolor is not None: + _api.warn_external( + f"You passed a edgecolor/edgecolors ({orig_edgecolor!r}) " + f"for an unfilled marker ({marker!r}). Matplotlib is " + "ignoring the edgecolor in favor of the facecolor. This " + "behavior may change in the future." + ) + # We need to handle markers that cannot be filled (like + # '+' and 'x') differently than markers that can be + # filled, but have their fillstyle set to 'none'. This is + # to get: + # + # - respecting the fillestyle if set + # - maintaining back-compatibility for querying the facecolor of + # the un-fillable markers. + # + # While not an ideal situation, but is better than the + # alternatives. + if marker_obj.get_fillstyle() == 'none': + # promote the facecolor to be the edgecolor + edgecolors = colors + # set the facecolor to 'none' (at the last chance) because + # we cannot fill a path if the facecolor is non-null + # (which is defendable at the renderer level). + colors = 'none' + else: + # if we are not nulling the face color we can do this + # simpler + edgecolors = 'face' + + if linewidths is None: + linewidths = mpl.rcParams['lines.linewidth'] + elif np.iterable(linewidths): + linewidths = [ + lw if lw is not None else mpl.rcParams['lines.linewidth'] + for lw in linewidths] + + offsets = np.ma.column_stack([x, y]) + + collection = mcoll.PathCollection( + (path,), scales, + facecolors=colors, + edgecolors=edgecolors, + linewidths=linewidths, + offsets=offsets, + offset_transform=kwargs.pop('transform', self.transData), + alpha=alpha, + ) + collection.set_transform(mtransforms.IdentityTransform()) + if colors is None: + if colorizer: + collection._set_colorizer_check_keywords(colorizer, cmap=cmap, + norm=norm, vmin=vmin, + vmax=vmax) + else: + collection.set_cmap(cmap) + collection.set_norm(norm) + collection.set_array(c) + collection._scale_norm(norm, vmin, vmax) + else: + extra_kwargs = { + 'cmap': cmap, 'norm': norm, 'vmin': vmin, 'vmax': vmax + } + extra_keys = [k for k, v in extra_kwargs.items() if v is not None] + if any(extra_keys): + keys_str = ", ".join(f"'{k}'" for k in extra_keys) + _api.warn_external( + "No data for colormapping provided via 'c'. " + f"Parameters {keys_str} will be ignored") + collection._internal_update(kwargs) + + # Classic mode only: + # ensure there are margins to allow for the + # finite size of the symbols. In v2.x, margins + # are present by default, so we disable this + # scatter-specific override. + if mpl.rcParams['_internal.classic_mode']: + if self._xmargin < 0.05 and x.size > 0: + self.set_xmargin(0.05) + if self._ymargin < 0.05 and x.size > 0: + self.set_ymargin(0.05) + + self.add_collection(collection) + self._request_autoscale_view() + + return collection + + @_api.make_keyword_only("3.10", "gridsize") + @_preprocess_data(replace_names=["x", "y", "C"], label_namer="y") + @_docstring.interpd + def hexbin(self, x, y, C=None, gridsize=100, bins=None, + xscale='linear', yscale='linear', extent=None, + cmap=None, norm=None, vmin=None, vmax=None, + alpha=None, linewidths=None, edgecolors='face', + reduce_C_function=np.mean, mincnt=None, marginals=False, + colorizer=None, **kwargs): + """ + Make a 2D hexagonal binning plot of points *x*, *y*. + + If *C* is *None*, the value of the hexagon is determined by the number + of points in the hexagon. Otherwise, *C* specifies values at the + coordinate (x[i], y[i]). For each hexagon, these values are reduced + using *reduce_C_function*. + + Parameters + ---------- + x, y : array-like + The data positions. *x* and *y* must be of the same length. + + C : array-like, optional + If given, these values are accumulated in the bins. Otherwise, + every point has a value of 1. Must be of the same length as *x* + and *y*. + + gridsize : int or (int, int), default: 100 + If a single int, the number of hexagons in the *x*-direction. + The number of hexagons in the *y*-direction is chosen such that + the hexagons are approximately regular. + + Alternatively, if a tuple (*nx*, *ny*), the number of hexagons + in the *x*-direction and the *y*-direction. In the + *y*-direction, counting is done along vertically aligned + hexagons, not along the zig-zag chains of hexagons; see the + following illustration. + + .. plot:: + + import numpy + import matplotlib.pyplot as plt + + np.random.seed(19680801) + n= 300 + x = np.random.standard_normal(n) + y = np.random.standard_normal(n) + + fig, ax = plt.subplots(figsize=(4, 4)) + h = ax.hexbin(x, y, gridsize=(5, 3)) + hx, hy = h.get_offsets().T + ax.plot(hx[24::3], hy[24::3], 'ro-') + ax.plot(hx[-3:], hy[-3:], 'ro-') + ax.set_title('gridsize=(5, 3)') + ax.axis('off') + + To get approximately regular hexagons, choose + :math:`n_x = \\sqrt{3}\\,n_y`. + + bins : 'log' or int or sequence, default: None + Discretization of the hexagon values. + + - If *None*, no binning is applied; the color of each hexagon + directly corresponds to its count value. + - If 'log', use a logarithmic scale for the colormap. + Internally, :math:`log_{10}(i+1)` is used to determine the + hexagon color. This is equivalent to ``norm=LogNorm()``. + - If an integer, divide the counts in the specified number + of bins, and color the hexagons accordingly. + - If a sequence of values, the values of the lower bound of + the bins to be used. + + xscale : {'linear', 'log'}, default: 'linear' + Use a linear or log10 scale on the horizontal axis. + + yscale : {'linear', 'log'}, default: 'linear' + Use a linear or log10 scale on the vertical axis. + + mincnt : int >= 0, default: *None* + If not *None*, only display cells with at least *mincnt* + number of points in the cell. + + marginals : bool, default: *False* + If marginals is *True*, plot the marginal density as + colormapped rectangles along the bottom of the x-axis and + left of the y-axis. + + extent : 4-tuple of float, default: *None* + The limits of the bins (xmin, xmax, ymin, ymax). + The default assigns the limits based on + *gridsize*, *x*, *y*, *xscale* and *yscale*. + + If *xscale* or *yscale* is set to 'log', the limits are + expected to be the exponent for a power of 10. E.g. for + x-limits of 1 and 50 in 'linear' scale and y-limits + of 10 and 1000 in 'log' scale, enter (1, 50, 1, 3). + + Returns + ------- + `~matplotlib.collections.PolyCollection` + A `.PolyCollection` defining the hexagonal bins. + + - `.PolyCollection.get_offsets` contains a Mx2 array containing + the x, y positions of the M hexagon centers in data coordinates. + - `.PolyCollection.get_array` contains the values of the M + hexagons. + + If *marginals* is *True*, horizontal + bar and vertical bar (both PolyCollections) will be attached + to the return collection as attributes *hbar* and *vbar*. + + Other Parameters + ---------------- + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + alpha : float between 0 and 1, optional + The alpha blending value, between 0 (transparent) and 1 (opaque). + + linewidths : float, default: *None* + If *None*, defaults to :rc:`patch.linewidth`. + + edgecolors : {'face', 'none', *None*} or color, default: 'face' + The color of the hexagon edges. Possible values are: + + - 'face': Draw the edges in the same color as the fill color. + - 'none': No edges are drawn. This can sometimes lead to unsightly + unpainted pixels between the hexagons. + - *None*: Draw outlines in the default color. + - An explicit color. + + reduce_C_function : callable, default: `numpy.mean` + The function to aggregate *C* within the bins. It is ignored if + *C* is not given. This must have the signature:: + + def reduce_C_function(C: array) -> float + + Commonly used functions are: + + - `numpy.mean`: average of the points + - `numpy.sum`: integral of the point values + - `numpy.amax`: value taken from the largest point + + By default will only reduce cells with at least 1 point because some + reduction functions (such as `numpy.amax`) will error/warn with empty + input. Changing *mincnt* will adjust the cutoff, and if set to 0 will + pass empty input to the reduction function. + + %(colorizer_doc)s + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `~matplotlib.collections.PolyCollection` properties + All other keyword arguments are passed on to `.PolyCollection`: + + %(PolyCollection:kwdoc)s + + See Also + -------- + hist2d : 2D histogram rectangular bins + """ + self._process_unit_info([("x", x), ("y", y)], kwargs, convert=False) + + x, y, C = cbook.delete_masked_points(x, y, C) + + # Set the size of the hexagon grid + if np.iterable(gridsize): + nx, ny = gridsize + else: + nx = gridsize + ny = int(nx / math.sqrt(3)) + # Count the number of data in each hexagon + x = np.asarray(x, float) + y = np.asarray(y, float) + + # Will be log()'d if necessary, and then rescaled. + tx = x + ty = y + + if xscale == 'log': + if np.any(x <= 0.0): + raise ValueError( + "x contains non-positive values, so cannot be log-scaled") + tx = np.log10(tx) + if yscale == 'log': + if np.any(y <= 0.0): + raise ValueError( + "y contains non-positive values, so cannot be log-scaled") + ty = np.log10(ty) + if extent is not None: + xmin, xmax, ymin, ymax = extent + if xmin > xmax: + raise ValueError("In extent, xmax must be greater than xmin") + if ymin > ymax: + raise ValueError("In extent, ymax must be greater than ymin") + else: + xmin, xmax = (tx.min(), tx.max()) if len(x) else (0, 1) + ymin, ymax = (ty.min(), ty.max()) if len(y) else (0, 1) + + # to avoid issues with singular data, expand the min/max pairs + xmin, xmax = mtransforms.nonsingular(xmin, xmax, expander=0.1) + ymin, ymax = mtransforms.nonsingular(ymin, ymax, expander=0.1) + + nx1 = nx + 1 + ny1 = ny + 1 + nx2 = nx + ny2 = ny + n = nx1 * ny1 + nx2 * ny2 + + # In the x-direction, the hexagons exactly cover the region from + # xmin to xmax. Need some padding to avoid roundoff errors. + padding = 1.e-9 * (xmax - xmin) + xmin -= padding + xmax += padding + sx = (xmax - xmin) / nx + sy = (ymax - ymin) / ny + # Positions in hexagon index coordinates. + ix = (tx - xmin) / sx + iy = (ty - ymin) / sy + ix1 = np.round(ix).astype(int) + iy1 = np.round(iy).astype(int) + ix2 = np.floor(ix).astype(int) + iy2 = np.floor(iy).astype(int) + # flat indices, plus one so that out-of-range points go to position 0. + i1 = np.where((0 <= ix1) & (ix1 < nx1) & (0 <= iy1) & (iy1 < ny1), + ix1 * ny1 + iy1 + 1, 0) + i2 = np.where((0 <= ix2) & (ix2 < nx2) & (0 <= iy2) & (iy2 < ny2), + ix2 * ny2 + iy2 + 1, 0) + + d1 = (ix - ix1) ** 2 + 3.0 * (iy - iy1) ** 2 + d2 = (ix - ix2 - 0.5) ** 2 + 3.0 * (iy - iy2 - 0.5) ** 2 + bdist = (d1 < d2) + + if C is None: # [1:] drops out-of-range points. + counts1 = np.bincount(i1[bdist], minlength=1 + nx1 * ny1)[1:] + counts2 = np.bincount(i2[~bdist], minlength=1 + nx2 * ny2)[1:] + accum = np.concatenate([counts1, counts2]).astype(float) + if mincnt is not None: + accum[accum < mincnt] = np.nan + C = np.ones(len(x)) + else: + # store the C values in a list per hexagon index + Cs_at_i1 = [[] for _ in range(1 + nx1 * ny1)] + Cs_at_i2 = [[] for _ in range(1 + nx2 * ny2)] + for i in range(len(x)): + if bdist[i]: + Cs_at_i1[i1[i]].append(C[i]) + else: + Cs_at_i2[i2[i]].append(C[i]) + if mincnt is None: + mincnt = 1 + accum = np.array( + [reduce_C_function(acc) if len(acc) >= mincnt else np.nan + for Cs_at_i in [Cs_at_i1, Cs_at_i2] + for acc in Cs_at_i[1:]], # [1:] drops out-of-range points. + float) + + good_idxs = ~np.isnan(accum) + + offsets = np.zeros((n, 2), float) + offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1) + offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1) + offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2) + offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5 + offsets[:, 0] *= sx + offsets[:, 1] *= sy + offsets[:, 0] += xmin + offsets[:, 1] += ymin + # remove accumulation bins with no data + offsets = offsets[good_idxs, :] + accum = accum[good_idxs] + + polygon = [sx, sy / 3] * np.array( + [[.5, -.5], [.5, .5], [0., 1.], [-.5, .5], [-.5, -.5], [0., -1.]]) + + if linewidths is None: + linewidths = [mpl.rcParams['patch.linewidth']] + + if xscale == 'log' or yscale == 'log': + polygons = np.expand_dims(polygon, 0) + if xscale == 'log': + polygons[:, :, 0] = 10.0 ** polygons[:, :, 0] + xmin = 10.0 ** xmin + xmax = 10.0 ** xmax + self.set_xscale(xscale) + if yscale == 'log': + polygons[:, :, 1] = 10.0 ** polygons[:, :, 1] + ymin = 10.0 ** ymin + ymax = 10.0 ** ymax + self.set_yscale(yscale) + else: + polygons = [polygon] + + collection = mcoll.PolyCollection( + polygons, + edgecolors=edgecolors, + linewidths=linewidths, + offsets=offsets, + offset_transform=mtransforms.AffineDeltaTransform(self.transData) + ) + + # Set normalizer if bins is 'log' + if cbook._str_equal(bins, 'log'): + if norm is not None: + _api.warn_external("Only one of 'bins' and 'norm' arguments " + f"can be supplied, ignoring {bins=}") + else: + norm = mcolors.LogNorm(vmin=vmin, vmax=vmax) + vmin = vmax = None + bins = None + + if bins is not None: + if not np.iterable(bins): + minimum, maximum = min(accum), max(accum) + bins -= 1 # one less edge than bins + bins = minimum + (maximum - minimum) * np.arange(bins) / bins + bins = np.sort(bins) + accum = bins.searchsorted(accum) + + if colorizer: + collection._set_colorizer_check_keywords(colorizer, cmap=cmap, + norm=norm, vmin=vmin, + vmax=vmax) + else: + collection.set_cmap(cmap) + collection.set_norm(norm) + collection.set_array(accum) + collection.set_alpha(alpha) + collection._internal_update(kwargs) + collection._scale_norm(norm, vmin, vmax) + + # autoscale the norm with current accum values if it hasn't been set + if norm is not None: + if collection.norm.vmin is None and collection.norm.vmax is None: + collection.norm.autoscale() + + corners = ((xmin, ymin), (xmax, ymax)) + self.update_datalim(corners) + self._request_autoscale_view(tight=True) + + # add the collection last + self.add_collection(collection, autolim=False) + if not marginals: + return collection + + # Process marginals + bars = [] + for zname, z, zmin, zmax, zscale, nbins in [ + ("x", x, xmin, xmax, xscale, nx), + ("y", y, ymin, ymax, yscale, 2 * ny), + ]: + + if zscale == "log": + bin_edges = np.geomspace(zmin, zmax, nbins + 1) + else: + bin_edges = np.linspace(zmin, zmax, nbins + 1) + + verts = np.empty((nbins, 4, 2)) + verts[:, 0, 0] = verts[:, 1, 0] = bin_edges[:-1] + verts[:, 2, 0] = verts[:, 3, 0] = bin_edges[1:] + verts[:, 0, 1] = verts[:, 3, 1] = .00 + verts[:, 1, 1] = verts[:, 2, 1] = .05 + if zname == "y": + verts = verts[:, :, ::-1] # Swap x and y. + + # Sort z-values into bins defined by bin_edges. + bin_idxs = np.searchsorted(bin_edges, z) - 1 + values = np.empty(nbins) + for i in range(nbins): + # Get C-values for each bin, and compute bin value with + # reduce_C_function. + ci = C[bin_idxs == i] + values[i] = reduce_C_function(ci) if len(ci) > 0 else np.nan + + mask = ~np.isnan(values) + verts = verts[mask] + values = values[mask] + + trans = getattr(self, f"get_{zname}axis_transform")(which="grid") + bar = mcoll.PolyCollection( + verts, transform=trans, edgecolors="face") + bar.set_array(values) + bar.set_cmap(cmap) + bar.set_norm(norm) + bar.set_alpha(alpha) + bar._internal_update(kwargs) + bars.append(self.add_collection(bar, autolim=False)) + + collection.hbar, collection.vbar = bars + + def on_changed(collection): + collection.hbar.set_cmap(collection.get_cmap()) + collection.hbar.set_cmap(collection.get_cmap()) + collection.vbar.set_clim(collection.get_clim()) + collection.vbar.set_clim(collection.get_clim()) + + collection.callbacks.connect('changed', on_changed) + + return collection + + @_docstring.interpd + def arrow(self, x, y, dx, dy, **kwargs): + """ + [*Discouraged*] Add an arrow to the Axes. + + This draws an arrow from ``(x, y)`` to ``(x+dx, y+dy)``. + + .. admonition:: Discouraged + + The use of this method is discouraged because it is not guaranteed + that the arrow renders reasonably. For example, the resulting arrow + is affected by the Axes aspect ratio and limits, which may distort + the arrow. + + Consider using `~.Axes.annotate` without a text instead, e.g. :: + + ax.annotate("", xytext=(0, 0), xy=(0.5, 0.5), + arrowprops=dict(arrowstyle="->")) + + Parameters + ---------- + %(FancyArrow)s + + Returns + ------- + `.FancyArrow` + The created `.FancyArrow` object. + """ + # Strip away units for the underlying patch since units + # do not make sense to most patch-like code + x = self.convert_xunits(x) + y = self.convert_yunits(y) + dx = self.convert_xunits(dx) + dy = self.convert_yunits(dy) + + a = mpatches.FancyArrow(x, y, dx, dy, **kwargs) + self.add_patch(a) + self._request_autoscale_view() + return a + + @_docstring.copy(mquiver.QuiverKey.__init__) + def quiverkey(self, Q, X, Y, U, label, **kwargs): + qk = mquiver.QuiverKey(Q, X, Y, U, label, **kwargs) + self.add_artist(qk) + return qk + + # Handle units for x and y, if they've been passed + def _quiver_units(self, args, kwargs): + if len(args) > 3: + x, y = args[0:2] + x, y = self._process_unit_info([("x", x), ("y", y)], kwargs) + return (x, y) + args[2:] + return args + + # args can be a combination of X, Y, U, V, C and all should be replaced + @_preprocess_data() + @_docstring.interpd + def quiver(self, *args, **kwargs): + """%(quiver_doc)s""" + # Make sure units are handled for x and y values + args = self._quiver_units(args, kwargs) + q = mquiver.Quiver(self, *args, **kwargs) + self.add_collection(q, autolim=True) + self._request_autoscale_view() + return q + + # args can be some combination of X, Y, U, V, C and all should be replaced + @_preprocess_data() + @_docstring.interpd + def barbs(self, *args, **kwargs): + """%(barbs_doc)s""" + # Make sure units are handled for x and y values + args = self._quiver_units(args, kwargs) + b = mquiver.Barbs(self, *args, **kwargs) + self.add_collection(b, autolim=True) + self._request_autoscale_view() + return b + + # Uses a custom implementation of data-kwarg handling in + # _process_plot_var_args. + def fill(self, *args, data=None, **kwargs): + """ + Plot filled polygons. + + Parameters + ---------- + *args : sequence of x, y, [color] + Each polygon is defined by the lists of *x* and *y* positions of + its nodes, optionally followed by a *color* specifier. See + :mod:`matplotlib.colors` for supported color specifiers. The + standard color cycle is used for polygons without a color + specifier. + + You can plot multiple polygons by providing multiple *x*, *y*, + *[color]* groups. + + For example, each of the following is legal:: + + ax.fill(x, y) # a polygon with default color + ax.fill(x, y, "b") # a blue polygon + ax.fill(x, y, x2, y2) # two polygons + ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*, e.g.:: + + ax.fill("time", "signal", + data={"time": [0, 1, 2], "signal": [0, 1, 0]}) + + Returns + ------- + list of `~matplotlib.patches.Polygon` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Polygon` properties + + Notes + ----- + Use :meth:`fill_between` if you would like to fill the region between + two curves. + """ + # For compatibility(!), get aliases from Line2D rather than Patch. + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + # _get_patches_for_fill returns a generator, convert it to a list. + patches = [*self._get_patches_for_fill(self, *args, data=data, **kwargs)] + for poly in patches: + self.add_patch(poly) + self._request_autoscale_view() + return patches + + def _fill_between_x_or_y( + self, ind_dir, ind, dep1, dep2=0, *, + where=None, interpolate=False, step=None, **kwargs): + # Common implementation between fill_between (*ind_dir*="x") and + # fill_betweenx (*ind_dir*="y"). *ind* is the independent variable, + # *dep* the dependent variable. The docstring below is interpolated + # to generate both methods' docstrings. + """ + Fill the area between two {dir} curves. + + The curves are defined by the points (*{ind}*, *{dep}1*) and (*{ind}*, + *{dep}2*). This creates one or multiple polygons describing the filled + area. + + You may exclude some {dir} sections from filling using *where*. + + By default, the edges connect the given points directly. Use *step* + if the filling should be a step function, i.e. constant in between + *{ind}*. + + Parameters + ---------- + {ind} : array-like + The {ind} coordinates of the nodes defining the curves. + + {dep}1 : array-like or float + The {dep} coordinates of the nodes defining the first curve. + + {dep}2 : array-like or float, default: 0 + The {dep} coordinates of the nodes defining the second curve. + + where : array-like of bool, optional + Define *where* to exclude some {dir} regions from being filled. + The filled regions are defined by the coordinates ``{ind}[where]``. + More precisely, fill between ``{ind}[i]`` and ``{ind}[i+1]`` if + ``where[i] and where[i+1]``. Note that this definition implies + that an isolated *True* value between two *False* values in *where* + will not result in filling. Both sides of the *True* position + remain unfilled due to the adjacent *False* values. + + interpolate : bool, default: False + This option is only relevant if *where* is used and the two curves + are crossing each other. + + Semantically, *where* is often used for *{dep}1* > *{dep}2* or + similar. By default, the nodes of the polygon defining the filled + region will only be placed at the positions in the *{ind}* array. + Such a polygon cannot describe the above semantics close to the + intersection. The {ind}-sections containing the intersection are + simply clipped. + + Setting *interpolate* to *True* will calculate the actual + intersection point and extend the filled region up to this point. + + step : {{'pre', 'post', 'mid'}}, optional + Define *step* if the filling should be a step function, + i.e. constant in between *{ind}*. The value determines where the + step will occur: + + - 'pre': The {dep} value is continued constantly to the left from + every *{ind}* position, i.e. the interval ``({ind}[i-1], {ind}[i]]`` + has the value ``{dep}[i]``. + - 'post': The y value is continued constantly to the right from + every *{ind}* position, i.e. the interval ``[{ind}[i], {ind}[i+1])`` + has the value ``{dep}[i]``. + - 'mid': Steps occur half-way between the *{ind}* positions. + + Returns + ------- + `.FillBetweenPolyCollection` + A `.FillBetweenPolyCollection` containing the plotted polygons. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments are passed on to + `.FillBetweenPolyCollection`. They control the `.Polygon` properties: + + %(FillBetweenPolyCollection:kwdoc)s + + See Also + -------- + fill_between : Fill between two sets of y-values. + fill_betweenx : Fill between two sets of x-values. + """ + dep_dir = mcoll.FillBetweenPolyCollection._f_dir_from_t(ind_dir) + + if not mpl.rcParams["_internal.classic_mode"]: + kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) + if not any(c in kwargs for c in ("color", "facecolor")): + kwargs["facecolor"] = self._get_patches_for_fill.get_next_color() + + ind, dep1, dep2 = self._fill_between_process_units( + ind_dir, dep_dir, ind, dep1, dep2, **kwargs) + + collection = mcoll.FillBetweenPolyCollection( + ind_dir, ind, dep1, dep2, + where=where, interpolate=interpolate, step=step, **kwargs) + + self.add_collection(collection) + self._request_autoscale_view() + return collection + + def _fill_between_process_units(self, ind_dir, dep_dir, ind, dep1, dep2, **kwargs): + """Handle united data, such as dates.""" + return map(np.ma.masked_invalid, self._process_unit_info( + [(ind_dir, ind), (dep_dir, dep1), (dep_dir, dep2)], kwargs)) + + def fill_between(self, x, y1, y2=0, where=None, interpolate=False, + step=None, **kwargs): + return self._fill_between_x_or_y( + "x", x, y1, y2, + where=where, interpolate=interpolate, step=step, **kwargs) + + if _fill_between_x_or_y.__doc__: + fill_between.__doc__ = _fill_between_x_or_y.__doc__.format( + dir="horizontal", ind="x", dep="y" + ) + fill_between = _preprocess_data( + _docstring.interpd(fill_between), + replace_names=["x", "y1", "y2", "where"]) + + def fill_betweenx(self, y, x1, x2=0, where=None, + step=None, interpolate=False, **kwargs): + return self._fill_between_x_or_y( + "y", y, x1, x2, + where=where, interpolate=interpolate, step=step, **kwargs) + + if _fill_between_x_or_y.__doc__: + fill_betweenx.__doc__ = _fill_between_x_or_y.__doc__.format( + dir="vertical", ind="y", dep="x" + ) + fill_betweenx = _preprocess_data( + _docstring.interpd(fill_betweenx), + replace_names=["y", "x1", "x2", "where"]) + + #### plotting z(x, y): imshow, pcolor and relatives, contour + + @_preprocess_data() + @_docstring.interpd + def imshow(self, X, cmap=None, norm=None, *, aspect=None, + interpolation=None, alpha=None, + vmin=None, vmax=None, colorizer=None, origin=None, extent=None, + interpolation_stage=None, filternorm=True, filterrad=4.0, + resample=None, url=None, **kwargs): + """ + Display data as an image, i.e., on a 2D regular raster. + + The input may either be actual RGB(A) data, or 2D scalar data, which + will be rendered as a pseudocolor image. For displaying a grayscale + image, set up the colormapping using the parameters + ``cmap='gray', vmin=0, vmax=255``. + + The number of pixels used to render an image is set by the Axes size + and the figure *dpi*. This can lead to aliasing artifacts when + the image is resampled, because the displayed image size will usually + not match the size of *X* (see + :doc:`/gallery/images_contours_and_fields/image_antialiasing`). + The resampling can be controlled via the *interpolation* parameter + and/or :rc:`image.interpolation`. + + Parameters + ---------- + X : array-like or PIL image + The image data. Supported array shapes are: + + - (M, N): an image with scalar data. The values are mapped to + colors using normalization and a colormap. See parameters *norm*, + *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the image. + + Out-of-range RGB(A) values are clipped. + + %(cmap_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(colorizer_doc)s + + This parameter is ignored if *X* is RGB(A). + + aspect : {'equal', 'auto'} or float or None, default: None + The aspect ratio of the Axes. This parameter is particularly + relevant for images since it determines whether data pixels are + square. + + This parameter is a shortcut for explicitly calling + `.Axes.set_aspect`. See there for further details. + + - 'equal': Ensures an aspect ratio of 1. Pixels will be square + (unless pixel sizes are explicitly made non-square in data + coordinates using *extent*). + - 'auto': The Axes is kept fixed and the aspect is adjusted so + that the data fit in the Axes. In general, this will result in + non-square pixels. + + Normally, None (the default) means to use :rc:`image.aspect`. However, if + the image uses a transform that does not contain the axes data transform, + then None means to not modify the axes aspect at all (in that case, directly + call `.Axes.set_aspect` if desired). + + interpolation : str, default: :rc:`image.interpolation` + The interpolation method used. + + Supported values are 'none', 'auto', 'nearest', 'bilinear', + 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', + 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', + 'sinc', 'lanczos', 'blackman'. + + The data *X* is resampled to the pixel size of the image on the + figure canvas, using the interpolation method to either up- or + downsample the data. + + If *interpolation* is 'none', then for the ps, pdf, and svg + backends no down- or upsampling occurs, and the image data is + passed to the backend as a native image. Note that different ps, + pdf, and svg viewers may display these raw pixels differently. On + other backends, 'none' is the same as 'nearest'. + + If *interpolation* is the default 'auto', then 'nearest' + interpolation is used if the image is upsampled by more than a + factor of three (i.e. the number of display pixels is at least + three times the size of the data array). If the upsampling rate is + smaller than 3, or the image is downsampled, then 'hanning' + interpolation is used to act as an anti-aliasing filter, unless the + image happens to be upsampled by exactly a factor of two or one. + + See + :doc:`/gallery/images_contours_and_fields/interpolation_methods` + for an overview of the supported interpolation methods, and + :doc:`/gallery/images_contours_and_fields/image_antialiasing` for + a discussion of image antialiasing. + + Some interpolation methods require an additional radius parameter, + which can be set by *filterrad*. Additionally, the antigrain image + resize filter is controlled by the parameter *filternorm*. + + interpolation_stage : {'auto', 'data', 'rgba'}, default: 'auto' + Supported values: + + - 'data': Interpolation is carried out on the data provided by the user + This is useful if interpolating between pixels during upsampling. + - 'rgba': The interpolation is carried out in RGBA-space after the + color-mapping has been applied. This is useful if downsampling and + combining pixels visually. + - 'auto': Select a suitable interpolation stage automatically. This uses + 'rgba' when downsampling, or upsampling at a rate less than 3, and + 'data' when upsampling at a higher rate. + + See :doc:`/gallery/images_contours_and_fields/image_antialiasing` for + a discussion of image antialiasing. + + alpha : float or array-like, optional + The alpha blending value, between 0 (transparent) and 1 (opaque). + If *alpha* is an array, the alpha blending values are applied pixel + by pixel, and *alpha* must have the same shape as *X*. + + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Place the [0, 0] index of the array in the upper left or lower + left corner of the Axes. The convention (the default) 'upper' is + typically used for matrices and images. + + Note that the vertical axis points upward for 'lower' + but downward for 'upper'. + + See the :ref:`imshow_extent` tutorial for + examples and a more detailed description. + + extent : floats (left, right, bottom, top), optional + The bounding box in data coordinates that the image will fill. + These values may be unitful and match the units of the Axes. + The image is stretched individually along x and y to fill the box. + + The default extent is determined by the following conditions. + Pixels have unit size in data coordinates. Their centers are on + integer coordinates, and their center coordinates range from 0 to + columns-1 horizontally and from 0 to rows-1 vertically. + + Note that the direction of the vertical axis and thus the default + values for top and bottom depend on *origin*: + + - For ``origin == 'upper'`` the default is + ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``. + - For ``origin == 'lower'`` the default is + ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``. + + See the :ref:`imshow_extent` tutorial for + examples and a more detailed description. + + filternorm : bool, default: True + A parameter for the antigrain image resize filter (see the + antigrain documentation). If *filternorm* is set, the filter + normalizes integer values and corrects the rounding errors. It + doesn't do anything with the source floating point values, it + corrects only integers according to the rule of 1.0 which means + that any sum of pixel weights must be equal to 1.0. So, the + filter function must produce a graph of the proper shape. + + filterrad : float > 0, default: 4.0 + The filter radius for filters that have a radius parameter, i.e. + when interpolation is one of: 'sinc', 'lanczos' or 'blackman'. + + resample : bool, default: :rc:`image.resample` + When *True*, use a full resampling method. When *False*, only + resample when the output image is larger than the input image. + + url : str, optional + Set the url of the created `.AxesImage`. See `.Artist.set_url`. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `~matplotlib.artist.Artist` properties + These parameters are passed on to the constructor of the + `.AxesImage` artist. + + See Also + -------- + matshow : Plot a matrix or an array as an image. + + Notes + ----- + Unless *extent* is used, pixel centers will be located at integer + coordinates. In other words: the origin will coincide with the center + of pixel (0, 0). + + There are two common representations for RGB images with an alpha + channel: + + - Straight (unassociated) alpha: R, G, and B channels represent the + color of the pixel, disregarding its opacity. + - Premultiplied (associated) alpha: R, G, and B channels represent + the color of the pixel, adjusted for its opacity by multiplication. + + `~matplotlib.pyplot.imshow` expects RGB images adopting the straight + (unassociated) alpha representation. + """ + im = mimage.AxesImage(self, cmap=cmap, norm=norm, colorizer=colorizer, + interpolation=interpolation, origin=origin, + extent=extent, filternorm=filternorm, + filterrad=filterrad, resample=resample, + interpolation_stage=interpolation_stage, + **kwargs) + + if aspect is None and not ( + im.is_transform_set() + and not im.get_transform().contains_branch(self.transData)): + aspect = mpl.rcParams['image.aspect'] + if aspect is not None: + self.set_aspect(aspect) + + im.set_data(X) + im.set_alpha(alpha) + if im.get_clip_path() is None: + # image does not already have clipping set, clip to Axes patch + im.set_clip_path(self.patch) + im._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax) + im._scale_norm(norm, vmin, vmax) + im.set_url(url) + + # update ax.dataLim, and, if autoscaling, set viewLim + # to tightly fit the image, regardless of dataLim. + im.set_extent(im.get_extent()) + + self.add_image(im) + return im + + def _pcolorargs(self, funcname, *args, shading='auto', **kwargs): + # - create X and Y if not present; + # - reshape X and Y as needed if they are 1-D; + # - check for proper sizes based on `shading` kwarg; + # - reset shading if shading='auto' to flat or nearest + # depending on size; + + _valid_shading = ['gouraud', 'nearest', 'flat', 'auto'] + try: + _api.check_in_list(_valid_shading, shading=shading) + except ValueError: + _api.warn_external(f"shading value '{shading}' not in list of " + f"valid values {_valid_shading}. Setting " + "shading='auto'.") + shading = 'auto' + + if len(args) == 1: + C = np.asanyarray(args[0]) + nrows, ncols = C.shape[:2] + if shading in ['gouraud', 'nearest']: + X, Y = np.meshgrid(np.arange(ncols), np.arange(nrows)) + else: + X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1)) + shading = 'flat' + elif len(args) == 3: + # Check x and y for bad data... + C = np.asanyarray(args[2]) + # unit conversion allows e.g. datetime objects as axis values + X, Y = args[:2] + X, Y = self._process_unit_info([("x", X), ("y", Y)], kwargs) + X, Y = (cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]) + + if funcname == 'pcolormesh': + if np.ma.is_masked(X) or np.ma.is_masked(Y): + raise ValueError( + 'x and y arguments to pcolormesh cannot have ' + 'non-finite values or be of type ' + 'numpy.ma.MaskedArray with masked values') + nrows, ncols = C.shape[:2] + else: + raise _api.nargs_error(funcname, takes="1 or 3", given=len(args)) + + Nx = X.shape[-1] + Ny = Y.shape[0] + if X.ndim != 2 or X.shape[0] == 1: + x = X.reshape(1, Nx) + X = x.repeat(Ny, axis=0) + if Y.ndim != 2 or Y.shape[1] == 1: + y = Y.reshape(Ny, 1) + Y = y.repeat(Nx, axis=1) + if X.shape != Y.shape: + raise TypeError(f'Incompatible X, Y inputs to {funcname}; ' + f'see help({funcname})') + + if shading == 'auto': + if ncols == Nx and nrows == Ny: + shading = 'nearest' + else: + shading = 'flat' + + if shading == 'flat': + if (Nx, Ny) != (ncols + 1, nrows + 1): + raise TypeError(f"Dimensions of C {C.shape} should" + f" be one smaller than X({Nx}) and Y({Ny})" + f" while using shading='flat'" + f" see help({funcname})") + else: # ['nearest', 'gouraud']: + if (Nx, Ny) != (ncols, nrows): + raise TypeError('Dimensions of C %s are incompatible with' + ' X (%d) and/or Y (%d); see help(%s)' % ( + C.shape, Nx, Ny, funcname)) + if shading == 'nearest': + # grid is specified at the center, so define corners + # at the midpoints between the grid centers and then use the + # flat algorithm. + def _interp_grid(X, require_monotonicity=False): + # helper for below. To ensure the cell edges are calculated + # correctly, when expanding columns, the monotonicity of + # X coords needs to be checked. When expanding rows, the + # monotonicity of Y coords needs to be checked. + if np.shape(X)[1] > 1: + dX = np.diff(X, axis=1) * 0.5 + if (require_monotonicity and + not (np.all(dX >= 0) or np.all(dX <= 0))): + _api.warn_external( + f"The input coordinates to {funcname} are " + "interpreted as cell centers, but are not " + "monotonically increasing or decreasing. " + "This may lead to incorrectly calculated cell " + "edges, in which case, please supply " + f"explicit cell edges to {funcname}.") + + hstack = np.ma.hstack if np.ma.isMA(X) else np.hstack + X = hstack((X[:, [0]] - dX[:, [0]], + X[:, :-1] + dX, + X[:, [-1]] + dX[:, [-1]])) + else: + # This is just degenerate, but we can't reliably guess + # a dX if there is just one value. + X = np.hstack((X, X)) + return X + + if ncols == Nx: + X = _interp_grid(X, require_monotonicity=True) + Y = _interp_grid(Y) + if nrows == Ny: + X = _interp_grid(X.T).T + Y = _interp_grid(Y.T, require_monotonicity=True).T + shading = 'flat' + + C = cbook.safe_masked_invalid(C, copy=True) + return X, Y, C, shading + + @_preprocess_data() + @_docstring.interpd + def pcolor(self, *args, shading=None, alpha=None, norm=None, cmap=None, + vmin=None, vmax=None, colorizer=None, **kwargs): + r""" + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + pcolor([X, Y,] C, /, **kwargs) + + *X* and *Y* can be used to specify the corners of the quadrilaterals. + + The arguments *X*, *Y*, *C* are positional-only. + + .. hint:: + + ``pcolor()`` can be very slow for large arrays. In most + cases you should use the similar but much faster + `~.Axes.pcolormesh` instead. See + :ref:`Differences between pcolor() and pcolormesh() + ` for a discussion of the + differences. + + Parameters + ---------- + C : 2D array-like + The color-mapped values. Color-mapping is controlled by *cmap*, + *norm*, *vmin*, and *vmax*. + + X, Y : array-like, optional + The coordinates of the corners of quadrilaterals of a pcolormesh:: + + (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) + ●╶───╴● + │ │ + ●╶───╴● + (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1]) + + Note that the column index corresponds to the x-coordinate, and + the row index corresponds to y. For details, see the + :ref:`Notes ` section below. + + If ``shading='flat'`` the dimensions of *X* and *Y* should be one + greater than those of *C*, and the quadrilateral is colored due + to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal + dimensions, a warning will be raised and the last row and column + of *C* will be ignored. + + If ``shading='nearest'``, the dimensions of *X* and *Y* should be + the same as those of *C* (if not, a ValueError will be raised). The + color ``C[i, j]`` will be centered on ``(X[i, j], Y[i, j])``. + + If *X* and/or *Y* are 1-D arrays or column vectors they will be + expanded as needed into the appropriate 2D arrays, making a + rectangular grid. + + shading : {'flat', 'nearest', 'auto'}, default: :rc:`pcolor.shading` + The fill style for the quadrilateral. Possible values: + + - 'flat': A solid color is used for each quad. The color of the + quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by + ``C[i, j]``. The dimensions of *X* and *Y* should be + one greater than those of *C*; if they are the same as *C*, + then a deprecation warning is raised, and the last row + and column of *C* are dropped. + - 'nearest': Each grid point will have a color centered on it, + extending halfway between the adjacent grid centers. The + dimensions of *X* and *Y* must be the same as *C*. + - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one + larger than *C*. Choose 'nearest' if dimensions are the same. + + See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids` + for more description. + + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + %(colorizer_doc)s + + edgecolors : {'none', None, 'face', color, color sequence}, optional + The color of the edges. Defaults to 'none'. Possible values: + + - 'none' or '': No edge. + - *None*: :rc:`patch.edgecolor` will be used. Note that currently + :rc:`patch.force_edgecolor` has to be True for this to work. + - 'face': Use the adjacent face color. + - A color or sequence of colors will set the edge color. + + The singular form *edgecolor* works as an alias. + + alpha : float, default: None + The alpha blending value of the face color, between 0 (transparent) + and 1 (opaque). Note: The edgecolor is currently not affected by + this. + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + Returns + ------- + `matplotlib.collections.PolyQuadMesh` + + Other Parameters + ---------------- + antialiaseds : bool, default: False + The default *antialiaseds* is False if the default + *edgecolors*\ ="none" is used. This eliminates artificial lines + at patch boundaries, and works regardless of the value of alpha. + If *edgecolors* is not "none", then the default *antialiaseds* + is taken from :rc:`patch.antialiased`. + Stroking the edges may be preferred if *alpha* is 1, but will + cause artifacts otherwise. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additionally, the following arguments are allowed. They are passed + along to the `~matplotlib.collections.PolyQuadMesh` constructor: + + %(PolyCollection:kwdoc)s + + See Also + -------- + pcolormesh : for an explanation of the differences between + pcolor and pcolormesh. + imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a + faster alternative. + + Notes + ----- + **Masked arrays** + + *X*, *Y* and *C* may be masked arrays. If either ``C[i, j]``, or one + of the vertices surrounding ``C[i, j]`` (*X* or *Y* at + ``[i, j], [i+1, j], [i, j+1], [i+1, j+1]``) is masked, nothing is + plotted. + + .. _axes-pcolor-grid-orientation: + + **Grid orientation** + + The grid orientation follows the standard matrix convention: An array + *C* with shape (nrows, ncolumns) is plotted with the column number as + *X* and the row number as *Y*. + """ + + if shading is None: + shading = mpl.rcParams['pcolor.shading'] + shading = shading.lower() + X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading, + kwargs=kwargs) + linewidths = (0.25,) + if 'linewidth' in kwargs: + kwargs['linewidths'] = kwargs.pop('linewidth') + kwargs.setdefault('linewidths', linewidths) + + if 'edgecolor' in kwargs: + kwargs['edgecolors'] = kwargs.pop('edgecolor') + ec = kwargs.setdefault('edgecolors', 'none') + + # aa setting will default via collections to patch.antialiased + # unless the boundary is not stroked, in which case the + # default will be False; with unstroked boundaries, aa + # makes artifacts that are often disturbing. + if 'antialiaseds' in kwargs: + kwargs['antialiased'] = kwargs.pop('antialiaseds') + if 'antialiased' not in kwargs and cbook._str_lower_equal(ec, "none"): + kwargs['antialiased'] = False + + kwargs.setdefault('snap', False) + + if np.ma.isMaskedArray(X) or np.ma.isMaskedArray(Y): + stack = np.ma.stack + X = np.ma.asarray(X) + Y = np.ma.asarray(Y) + # For bounds collections later + x = X.compressed() + y = Y.compressed() + else: + stack = np.stack + x = X + y = Y + coords = stack([X, Y], axis=-1) + + collection = mcoll.PolyQuadMesh( + coords, array=C, cmap=cmap, norm=norm, colorizer=colorizer, + alpha=alpha, **kwargs) + collection._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax) + collection._scale_norm(norm, vmin, vmax) + + # Transform from native to data coordinates? + t = collection._transform + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): + t = t._as_mpl_transform(self.axes) + + if t and any(t.contains_branch_seperately(self.transData)): + trans_to_data = t - self.transData + pts = np.vstack([x, y]).T.astype(float) + transformed_pts = trans_to_data.transform(pts) + x = transformed_pts[..., 0] + y = transformed_pts[..., 1] + + self.add_collection(collection, autolim=False) + + minx = np.min(x) + maxx = np.max(x) + miny = np.min(y) + maxy = np.max(y) + collection.sticky_edges.x[:] = [minx, maxx] + collection.sticky_edges.y[:] = [miny, maxy] + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners) + self._request_autoscale_view() + return collection + + @_preprocess_data() + @_docstring.interpd + def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None, + vmax=None, colorizer=None, shading=None, antialiased=False, + **kwargs): + """ + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + pcolormesh([X, Y,] C, /, **kwargs) + + *X* and *Y* can be used to specify the corners of the quadrilaterals. + + The arguments *X*, *Y*, *C* are positional-only. + + .. hint:: + + `~.Axes.pcolormesh` is similar to `~.Axes.pcolor`. It is much faster + and preferred in most cases. For a detailed discussion on the + differences see :ref:`Differences between pcolor() and pcolormesh() + `. + + Parameters + ---------- + C : array-like + The mesh data. Supported array shapes are: + + - (M, N) or M*N: a mesh with scalar data. The values are mapped to + colors using normalization and a colormap. See parameters *norm*, + *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the mesh data. + + X, Y : array-like, optional + The coordinates of the corners of quadrilaterals of a pcolormesh:: + + (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) + ●╶───╴● + │ │ + ●╶───╴● + (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1]) + + Note that the column index corresponds to the x-coordinate, and + the row index corresponds to y. For details, see the + :ref:`Notes ` section below. + + If ``shading='flat'`` the dimensions of *X* and *Y* should be one + greater than those of *C*, and the quadrilateral is colored due + to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal + dimensions, a warning will be raised and the last row and column + of *C* will be ignored. + + If ``shading='nearest'`` or ``'gouraud'``, the dimensions of *X* + and *Y* should be the same as those of *C* (if not, a ValueError + will be raised). For ``'nearest'`` the color ``C[i, j]`` is + centered on ``(X[i, j], Y[i, j])``. For ``'gouraud'``, a smooth + interpolation is carried out between the quadrilateral corners. + + If *X* and/or *Y* are 1-D arrays or column vectors they will be + expanded as needed into the appropriate 2D arrays, making a + rectangular grid. + + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + %(colorizer_doc)s + + edgecolors : {'none', None, 'face', color, color sequence}, optional + The color of the edges. Defaults to 'none'. Possible values: + + - 'none' or '': No edge. + - *None*: :rc:`patch.edgecolor` will be used. Note that currently + :rc:`patch.force_edgecolor` has to be True for this to work. + - 'face': Use the adjacent face color. + - A color or sequence of colors will set the edge color. + + The singular form *edgecolor* works as an alias. + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + shading : {'flat', 'nearest', 'gouraud', 'auto'}, optional + The fill style for the quadrilateral; defaults to + :rc:`pcolor.shading`. Possible values: + + - 'flat': A solid color is used for each quad. The color of the + quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by + ``C[i, j]``. The dimensions of *X* and *Y* should be + one greater than those of *C*; if they are the same as *C*, + then a deprecation warning is raised, and the last row + and column of *C* are dropped. + - 'nearest': Each grid point will have a color centered on it, + extending halfway between the adjacent grid centers. The + dimensions of *X* and *Y* must be the same as *C*. + - 'gouraud': Each quad will be Gouraud shaded: The color of the + corners (i', j') are given by ``C[i', j']``. The color values of + the area in between is interpolated from the corner values. + The dimensions of *X* and *Y* must be the same as *C*. When + Gouraud shading is used, *edgecolors* is ignored. + - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one + larger than *C*. Choose 'nearest' if dimensions are the same. + + See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids` + for more description. + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + rasterized : bool, optional + Rasterize the pcolormesh when drawing vector graphics. This can + speed up rendering and produce smaller files for large data sets. + See also :doc:`/gallery/misc/rasterization_demo`. + + Returns + ------- + `matplotlib.collections.QuadMesh` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additionally, the following arguments are allowed. They are passed + along to the `~matplotlib.collections.QuadMesh` constructor: + + %(QuadMesh:kwdoc)s + + See Also + -------- + pcolor : An alternative implementation with slightly different + features. For a detailed discussion on the differences see + :ref:`Differences between pcolor() and pcolormesh() + `. + imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a + faster alternative. + + Notes + ----- + **Masked arrays** + + *C* may be a masked array. If ``C[i, j]`` is masked, the corresponding + quadrilateral will be transparent. Masking of *X* and *Y* is not + supported. Use `~.Axes.pcolor` if you need this functionality. + + .. _axes-pcolormesh-grid-orientation: + + **Grid orientation** + + The grid orientation follows the standard matrix convention: An array + *C* with shape (nrows, ncolumns) is plotted with the column number as + *X* and the row number as *Y*. + + .. _differences-pcolor-pcolormesh: + + **Differences between pcolor() and pcolormesh()** + + Both methods are used to create a pseudocolor plot of a 2D array + using quadrilaterals. + + The main difference lies in the created object and internal data + handling: + While `~.Axes.pcolor` returns a `.PolyQuadMesh`, `~.Axes.pcolormesh` + returns a `.QuadMesh`. The latter is more specialized for the given + purpose and thus is faster. It should almost always be preferred. + + There is also a slight difference in the handling of masked arrays. + Both `~.Axes.pcolor` and `~.Axes.pcolormesh` support masked arrays + for *C*. However, only `~.Axes.pcolor` supports masked arrays for *X* + and *Y*. The reason lies in the internal handling of the masked values. + `~.Axes.pcolor` leaves out the respective polygons from the + PolyQuadMesh. `~.Axes.pcolormesh` sets the facecolor of the masked + elements to transparent. You can see the difference when using + edgecolors. While all edges are drawn irrespective of masking in a + QuadMesh, the edge between two adjacent masked quadrilaterals in + `~.Axes.pcolor` is not drawn as the corresponding polygons do not + exist in the PolyQuadMesh. Because PolyQuadMesh draws each individual + polygon, it also supports applying hatches and linestyles to the collection. + + Another difference is the support of Gouraud shading in + `~.Axes.pcolormesh`, which is not available with `~.Axes.pcolor`. + + """ + if shading is None: + shading = mpl.rcParams['pcolor.shading'] + shading = shading.lower() + kwargs.setdefault('edgecolors', 'none') + + X, Y, C, shading = self._pcolorargs('pcolormesh', *args, + shading=shading, kwargs=kwargs) + coords = np.stack([X, Y], axis=-1) + + kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap']) + + collection = mcoll.QuadMesh( + coords, antialiased=antialiased, shading=shading, + array=C, cmap=cmap, norm=norm, colorizer=colorizer, alpha=alpha, **kwargs) + collection._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax) + collection._scale_norm(norm, vmin, vmax) + + coords = coords.reshape(-1, 2) # flatten the grid structure; keep x, y + + # Transform from native to data coordinates? + t = collection._transform + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): + t = t._as_mpl_transform(self.axes) + + if t and any(t.contains_branch_seperately(self.transData)): + trans_to_data = t - self.transData + coords = trans_to_data.transform(coords) + + self.add_collection(collection, autolim=False) + + minx, miny = np.min(coords, axis=0) + maxx, maxy = np.max(coords, axis=0) + collection.sticky_edges.x[:] = [minx, maxx] + collection.sticky_edges.y[:] = [miny, maxy] + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners) + self._request_autoscale_view() + return collection + + @_preprocess_data() + @_docstring.interpd + def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None, + vmax=None, colorizer=None, **kwargs): + """ + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + ax.pcolorfast([X, Y], C, /, **kwargs) + + The arguments *X*, *Y*, *C* are positional-only. + + This method is similar to `~.Axes.pcolor` and `~.Axes.pcolormesh`. + It's designed to provide the fastest pcolor-type plotting with the + Agg backend. To achieve this, it uses different algorithms internally + depending on the complexity of the input grid (regular rectangular, + non-regular rectangular or arbitrary quadrilateral). + + .. warning:: + + This method is experimental. Compared to `~.Axes.pcolor` or + `~.Axes.pcolormesh` it has some limitations: + + - It supports only flat shading (no outlines) + - It lacks support for log scaling of the axes. + - It does not have a pyplot wrapper. + + Parameters + ---------- + C : array-like + The image data. Supported array shapes are: + + - (M, N): an image with scalar data. Color-mapping is controlled + by *cmap*, *norm*, *vmin*, and *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the image. + + This parameter can only be passed positionally. + + X, Y : tuple or array-like, default: ``(0, N)``, ``(0, M)`` + *X* and *Y* are used to specify the coordinates of the + quadrilaterals. There are different ways to do this: + + - Use tuples ``X=(xmin, xmax)`` and ``Y=(ymin, ymax)`` to define + a *uniform rectangular grid*. + + The tuples define the outer edges of the grid. All individual + quadrilaterals will be of the same size. This is the fastest + version. + + - Use 1D arrays *X*, *Y* to specify a *non-uniform rectangular + grid*. + + In this case *X* and *Y* have to be monotonic 1D arrays of length + *N+1* and *M+1*, specifying the x and y boundaries of the cells. + + The speed is intermediate. Note: The grid is checked, and if + found to be uniform the fast version is used. + + - Use 2D arrays *X*, *Y* if you need an *arbitrary quadrilateral + grid* (i.e. if the quadrilaterals are not rectangular). + + In this case *X* and *Y* are 2D arrays with shape (M + 1, N + 1), + specifying the x and y coordinates of the corners of the colored + quadrilaterals. + + This is the most general, but the slowest to render. It may + produce faster and more compact output using ps, pdf, and + svg backends, however. + + These arguments can only be passed positionally. + + %(cmap_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(colorizer_doc)s + + This parameter is ignored if *C* is RGB(A). + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + Returns + ------- + `.AxesImage` or `.PcolorImage` or `.QuadMesh` + The return type depends on the type of grid: + + - `.AxesImage` for a regular rectangular grid. + - `.PcolorImage` for a non-regular rectangular grid. + - `.QuadMesh` for a non-rectangular grid. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Supported additional parameters depend on the type of grid. + See return types of *image* for further description. + """ + + C = args[-1] + nr, nc = np.shape(C)[:2] + if len(args) == 1: + style = "image" + x = [0, nc] + y = [0, nr] + elif len(args) == 3: + x, y = args[:2] + x = np.asarray(x) + y = np.asarray(y) + if x.ndim == 1 and y.ndim == 1: + if x.size == 2 and y.size == 2: + style = "image" + else: + if x.size != nc + 1: + raise ValueError( + f"Length of X ({x.size}) must be one larger than the " + f"number of columns in C ({nc})") + if y.size != nr + 1: + raise ValueError( + f"Length of Y ({y.size}) must be one larger than the " + f"number of rows in C ({nr})" + ) + dx = np.diff(x) + dy = np.diff(y) + if (np.ptp(dx) < 0.01 * abs(dx.mean()) and + np.ptp(dy) < 0.01 * abs(dy.mean())): + style = "image" + else: + style = "pcolorimage" + elif x.ndim == 2 and y.ndim == 2: + style = "quadmesh" + else: + raise TypeError( + f"When 3 positional parameters are passed to pcolorfast, the first " + f"two (X and Y) must be both 1D or both 2D; the given X was " + f"{x.ndim}D and the given Y was {y.ndim}D") + else: + raise _api.nargs_error('pcolorfast', '1 or 3', len(args)) + + mcolorizer.ColorizingArtist._check_exclusionary_keywords(colorizer, vmin=vmin, + vmax=vmax) + if style == "quadmesh": + # data point in each cell is value at lower left corner + coords = np.stack([x, y], axis=-1) + if np.ndim(C) not in {2, 3}: + raise ValueError("C must be 2D or 3D") + collection = mcoll.QuadMesh( + coords, array=C, + alpha=alpha, cmap=cmap, norm=norm, colorizer=colorizer, + antialiased=False, edgecolors="none") + self.add_collection(collection, autolim=False) + xl, xr, yb, yt = x.min(), x.max(), y.min(), y.max() + ret = collection + + else: # It's one of the two image styles. + extent = xl, xr, yb, yt = x[0], x[-1], y[0], y[-1] + if style == "image": + im = mimage.AxesImage( + self, cmap=cmap, norm=norm, colorizer=colorizer, + data=C, alpha=alpha, extent=extent, + interpolation='nearest', origin='lower', + **kwargs) + elif style == "pcolorimage": + im = mimage.PcolorImage( + self, x, y, C, + cmap=cmap, norm=norm, colorizer=colorizer, alpha=alpha, + extent=extent, **kwargs) + self.add_image(im) + ret = im + + if np.ndim(C) == 2: # C.ndim == 3 is RGB(A) so doesn't need scaling. + ret._scale_norm(norm, vmin, vmax) + + if ret.get_clip_path() is None: + # image does not already have clipping set, clip to Axes patch + ret.set_clip_path(self.patch) + + ret.sticky_edges.x[:] = [xl, xr] + ret.sticky_edges.y[:] = [yb, yt] + self.update_datalim(np.array([[xl, yb], [xr, yt]])) + self._request_autoscale_view(tight=True) + return ret + + @_preprocess_data() + @_docstring.interpd + def contour(self, *args, **kwargs): + """ + Plot contour lines. + + Call signature:: + + contour([X, Y,] Z, /, [levels], **kwargs) + + The arguments *X*, *Y*, *Z* are positional-only. + %(contour_doc)s + """ + kwargs['filled'] = False + contours = mcontour.QuadContourSet(self, *args, **kwargs) + self._request_autoscale_view() + return contours + + @_preprocess_data() + @_docstring.interpd + def contourf(self, *args, **kwargs): + """ + Plot filled contours. + + Call signature:: + + contourf([X, Y,] Z, /, [levels], **kwargs) + + The arguments *X*, *Y*, *Z* are positional-only. + %(contour_doc)s + """ + kwargs['filled'] = True + contours = mcontour.QuadContourSet(self, *args, **kwargs) + self._request_autoscale_view() + return contours + + def clabel(self, CS, levels=None, **kwargs): + """ + Label a contour plot. + + Adds labels to line contours in given `.ContourSet`. + + Parameters + ---------- + CS : `.ContourSet` instance + Line contours to label. + + levels : array-like, optional + A list of level values, that should be labeled. The list must be + a subset of ``CS.levels``. If not given, all levels are labeled. + + **kwargs + All other parameters are documented in `~.ContourLabeler.clabel`. + """ + return CS.clabel(levels, **kwargs) + + #### Data analysis + + @_api.make_keyword_only("3.10", "range") + @_preprocess_data(replace_names=["x", 'weights'], label_namer="x") + def hist(self, x, bins=None, range=None, density=False, weights=None, + cumulative=False, bottom=None, histtype='bar', align='mid', + orientation='vertical', rwidth=None, log=False, + color=None, label=None, stacked=False, **kwargs): + """ + Compute and plot a histogram. + + This method uses `numpy.histogram` to bin the data in *x* and count the + number of values in each bin, then draws the distribution either as a + `.BarContainer` or `.Polygon`. The *bins*, *range*, *density*, and + *weights* parameters are forwarded to `numpy.histogram`. + + If the data has already been binned and counted, use `~.bar` or + `~.stairs` to plot the distribution:: + + counts, bins = np.histogram(x) + plt.stairs(counts, bins) + + Alternatively, plot pre-computed bins and counts using ``hist()`` by + treating each bin as a single point with a weight equal to its count:: + + plt.hist(bins[:-1], bins, weights=counts) + + The data input *x* can be a singular array, a list of datasets of + potentially different lengths ([*x0*, *x1*, ...]), or a 2D ndarray in + which each column is a dataset. Note that the ndarray form is + transposed relative to the list form. If the input is an array, then + the return value is a tuple (*n*, *bins*, *patches*); if the input is a + sequence of arrays, then the return value is a tuple + ([*n0*, *n1*, ...], *bins*, [*patches0*, *patches1*, ...]). + + Masked arrays are not supported. + + Parameters + ---------- + x : (n,) array or sequence of (n,) arrays + Input values, this takes either a single array or a sequence of + arrays which are not required to be of the same length. + + bins : int or sequence or str, default: :rc:`hist.bins` + If *bins* is an integer, it defines the number of equal-width bins + in the range. + + If *bins* is a sequence, it defines the bin edges, including the + left edge of the first bin and the right edge of the last bin; + in this case, bins may be unequally spaced. All but the last + (righthand-most) bin is half-open. In other words, if *bins* is:: + + [1, 2, 3, 4] + + then the first bin is ``[1, 2)`` (including 1, but excluding 2) and + the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which + *includes* 4. + + If *bins* is a string, it is one of the binning strategies + supported by `numpy.histogram_bin_edges`: 'auto', 'fd', 'doane', + 'scott', 'stone', 'rice', 'sturges', or 'sqrt'. + + range : tuple or None, default: None + The lower and upper range of the bins. Lower and upper outliers + are ignored. If not provided, *range* is ``(x.min(), x.max())``. + Range has no effect if *bins* is a sequence. + + If *bins* is a sequence or *range* is specified, autoscaling + is based on the specified bin range instead of the + range of x. + + density : bool, default: False + If ``True``, draw and return a probability density: each bin + will display the bin's raw count divided by the total number of + counts *and the bin width* + (``density = counts / (sum(counts) * np.diff(bins))``), + so that the area under the histogram integrates to 1 + (``np.sum(density * np.diff(bins)) == 1``). + + If *stacked* is also ``True``, the sum of the histograms is + normalized to 1. + + weights : (n,) array-like or None, default: None + An array of weights, of the same shape as *x*. Each value in + *x* only contributes its associated weight towards the bin count + (instead of 1). If *density* is ``True``, the weights are + normalized, so that the integral of the density over the range + remains 1. + + cumulative : bool or -1, default: False + If ``True``, then a histogram is computed where each bin gives the + counts in that bin plus all bins for smaller values. The last bin + gives the total number of datapoints. + + If *density* is also ``True`` then the histogram is normalized such + that the last bin equals 1. + + If *cumulative* is a number less than 0 (e.g., -1), the direction + of accumulation is reversed. In this case, if *density* is also + ``True``, then the histogram is normalized such that the first bin + equals 1. + + bottom : array-like or float, default: 0 + Location of the bottom of each bin, i.e. bins are drawn from + ``bottom`` to ``bottom + hist(x, bins)`` If a scalar, the bottom + of each bin is shifted by the same amount. If an array, each bin + is shifted independently and the length of bottom must match the + number of bins. If None, defaults to 0. + + histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar' + The type of histogram to draw. + + - 'bar' is a traditional bar-type histogram. If multiple data + are given the bars are arranged side by side. + - 'barstacked' is a bar-type histogram where multiple + data are stacked on top of each other. + - 'step' generates a lineplot that is by default unfilled. + - 'stepfilled' generates a lineplot that is by default filled. + + align : {'left', 'mid', 'right'}, default: 'mid' + The horizontal alignment of the histogram bars. + + - 'left': bars are centered on the left bin edges. + - 'mid': bars are centered between the bin edges. + - 'right': bars are centered on the right bin edges. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', `~.Axes.barh` will be used for bar-type histograms + and the *bottom* kwarg will be the left edges. + + rwidth : float or None, default: None + The relative width of the bars as a fraction of the bin width. If + ``None``, automatically compute the width. + + Ignored if *histtype* is 'step' or 'stepfilled'. + + log : bool, default: False + If ``True``, the histogram axis will be set to a log scale. + + color : :mpltype:`color` or list of :mpltype:`color` or None, default: None + Color or sequence of colors, one per dataset. Default (``None``) + uses the standard line color sequence. + + label : str or list of str, optional + String, or sequence of strings to match multiple datasets. Bar + charts yield multiple patches per dataset, but only the first gets + the label, so that `~.Axes.legend` will work as expected. + + stacked : bool, default: False + If ``True``, multiple data are stacked on top of each other If + ``False`` multiple data are arranged side by side if histtype is + 'bar' or on top of each other if histtype is 'step' + + Returns + ------- + n : array or list of arrays + The values of the histogram bins. See *density* and *weights* for a + description of the possible semantics. If input *x* is an array, + then this is an array of length *nbins*. If input is a sequence of + arrays ``[data1, data2, ...]``, then this is a list of arrays with + the values of the histograms for each of the arrays in the same + order. The dtype of the array *n* (or of its element arrays) will + always be float even if no weighting or normalization is used. + + bins : array + The edges of the bins. Length nbins + 1 (nbins left edges and right + edge of last bin). Always a single array even when multiple data + sets are passed in. + + patches : `.BarContainer` or list of a single `.Polygon` or list of \ +such objects + Container of individual artists used to create the histogram + or list of such containers if there are multiple input datasets. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + `~matplotlib.patches.Patch` properties. The following properties + additionally accept a sequence of values corresponding to the + datasets in *x*: + *edgecolor*, *facecolor*, *linewidth*, *linestyle*, *hatch*. + + .. versionadded:: 3.10 + Allowing sequences of values in above listed Patch properties. + + See Also + -------- + hist2d : 2D histogram with rectangular bins + hexbin : 2D histogram with hexagonal bins + stairs : Plot a pre-computed histogram + bar : Plot a pre-computed histogram + + Notes + ----- + For large numbers of bins (>1000), plotting can be significantly + accelerated by using `~.Axes.stairs` to plot a pre-computed histogram + (``plt.stairs(*np.histogram(data))``), or by setting *histtype* to + 'step' or 'stepfilled' rather than 'bar' or 'barstacked'. + """ + # Avoid shadowing the builtin. + bin_range = range + from builtins import range + + kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch) + + if np.isscalar(x): + x = [x] + + if bins is None: + bins = mpl.rcParams['hist.bins'] + + # Validate string inputs here to avoid cluttering subsequent code. + _api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'], + histtype=histtype) + _api.check_in_list(['left', 'mid', 'right'], align=align) + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if histtype == 'barstacked' and not stacked: + stacked = True + + # Massage 'x' for processing. + x = cbook._reshape_2D(x, 'x') + nx = len(x) # number of datasets + + # Process unit information. _process_unit_info sets the unit and + # converts the first dataset; then we convert each following dataset + # one at a time. + if orientation == "vertical": + convert_units = self.convert_xunits + x = [*self._process_unit_info([("x", x[0])], kwargs), + *map(convert_units, x[1:])] + else: # horizontal + convert_units = self.convert_yunits + x = [*self._process_unit_info([("y", x[0])], kwargs), + *map(convert_units, x[1:])] + + if bin_range is not None: + bin_range = convert_units(bin_range) + + if not cbook.is_scalar_or_string(bins): + bins = convert_units(bins) + + # We need to do to 'weights' what was done to 'x' + if weights is not None: + w = cbook._reshape_2D(weights, 'weights') + else: + w = [None] * nx + + if len(w) != nx: + raise ValueError('weights should have the same shape as x') + + input_empty = True + for xi, wi in zip(x, w): + len_xi = len(xi) + if wi is not None and len(wi) != len_xi: + raise ValueError('weights should have the same shape as x') + if len_xi: + input_empty = False + + if color is None: + colors = [self._get_lines.get_next_color() for i in range(nx)] + else: + colors = mcolors.to_rgba_array(color) + if len(colors) != nx: + raise ValueError(f"The 'color' keyword argument must have one " + f"color per dataset, but {nx} datasets and " + f"{len(colors)} colors were provided") + + hist_kwargs = dict() + + # if the bin_range is not given, compute without nan numpy + # does not do this for us when guessing the range (but will + # happily ignore nans when computing the histogram). + if bin_range is None: + xmin = np.inf + xmax = -np.inf + for xi in x: + if len(xi): + # python's min/max ignore nan, + # np.minnan returns nan for all nan input + xmin = min(xmin, np.nanmin(xi)) + xmax = max(xmax, np.nanmax(xi)) + if xmin <= xmax: # Only happens if we have seen a finite value. + bin_range = (xmin, xmax) + + # If bins are not specified either explicitly or via range, + # we need to figure out the range required for all datasets, + # and supply that to np.histogram. + if not input_empty and len(x) > 1: + if weights is not None: + _w = np.concatenate(w) + else: + _w = None + bins = np.histogram_bin_edges( + np.concatenate(x), bins, bin_range, _w) + else: + hist_kwargs['range'] = bin_range + + density = bool(density) + if density and not stacked: + hist_kwargs['density'] = density + + # List to store all the top coordinates of the histograms + tops = [] # Will have shape (n_datasets, n_bins). + # Loop through datasets + for i in range(nx): + # this will automatically overwrite bins, + # so that each histogram uses the same bins + m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) + tops.append(m) + tops = np.array(tops, float) # causes problems later if it's an int + bins = np.array(bins, float) # causes problems if float16 + if stacked: + tops = tops.cumsum(axis=0) + # If a stacked density plot, normalize so the area of all the + # stacked histograms together is 1 + if density: + tops = (tops / np.diff(bins)) / tops[-1].sum() + if cumulative: + slc = slice(None) + if isinstance(cumulative, Number) and cumulative < 0: + slc = slice(None, None, -1) + if density: + tops = (tops * np.diff(bins))[:, slc].cumsum(axis=1)[:, slc] + else: + tops = tops[:, slc].cumsum(axis=1)[:, slc] + + patches = [] + + if histtype.startswith('bar'): + + totwidth = np.diff(bins) + + if rwidth is not None: + dr = np.clip(rwidth, 0, 1) + elif (len(tops) > 1 and + ((not stacked) or mpl.rcParams['_internal.classic_mode'])): + dr = 0.8 + else: + dr = 1.0 + + if histtype == 'bar' and not stacked: + width = dr * totwidth / nx + dw = width + boffset = -0.5 * dr * totwidth * (1 - 1 / nx) + elif histtype == 'barstacked' or stacked: + width = dr * totwidth + boffset, dw = 0.0, 0.0 + + if align == 'mid': + boffset += 0.5 * totwidth + elif align == 'right': + boffset += totwidth + + if orientation == 'horizontal': + _barfunc = self.barh + bottom_kwarg = 'left' + else: # orientation == 'vertical' + _barfunc = self.bar + bottom_kwarg = 'bottom' + + for top, color in zip(tops, colors): + if bottom is None: + bottom = np.zeros(len(top)) + if stacked: + height = top - bottom + else: + height = top + bars = _barfunc(bins[:-1]+boffset, height, width, + align='center', log=log, + color=color, **{bottom_kwarg: bottom}) + patches.append(bars) + if stacked: + bottom = top + boffset += dw + # Remove stickies from all bars but the lowest ones, as otherwise + # margin expansion would be unable to cross the stickies in the + # middle of the bars. + for bars in patches[1:]: + for patch in bars: + patch.sticky_edges.x[:] = patch.sticky_edges.y[:] = [] + + elif histtype.startswith('step'): + # these define the perimeter of the polygon + x = np.zeros(4 * len(bins) - 3) + y = np.zeros(4 * len(bins) - 3) + + x[0:2*len(bins)-1:2], x[1:2*len(bins)-1:2] = bins, bins[:-1] + x[2*len(bins)-1:] = x[1:2*len(bins)-1][::-1] + + if bottom is None: + bottom = 0 + + y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = bottom + y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1] + + if log: + if orientation == 'horizontal': + self.set_xscale('log', nonpositive='clip') + else: # orientation == 'vertical' + self.set_yscale('log', nonpositive='clip') + + if align == 'left': + x -= 0.5*(bins[1]-bins[0]) + elif align == 'right': + x += 0.5*(bins[1]-bins[0]) + + # If fill kwarg is set, it will be passed to the patch collection, + # overriding this + fill = (histtype == 'stepfilled') + + xvals, yvals = [], [] + for top in tops: + if stacked: + # top of the previous polygon becomes the bottom + y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1] + # set the top of this polygon + y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = top + bottom + + # The starting point of the polygon has not yet been + # updated. So far only the endpoint was adjusted. This + # assignment closes the polygon. The redundant endpoint is + # later discarded (for step and stepfilled). + y[0] = y[-1] + + if orientation == 'horizontal': + xvals.append(y.copy()) + yvals.append(x.copy()) + else: + xvals.append(x.copy()) + yvals.append(y.copy()) + + # stepfill is closed, step is not + split = -1 if fill else 2 * len(bins) + # add patches in reverse order so that when stacking, + # items lower in the stack are plotted on top of + # items higher in the stack + for x, y, color in reversed(list(zip(xvals, yvals, colors))): + patches.append(self.fill( + x[:split], y[:split], + closed=True if fill else None, + facecolor=color, + edgecolor=None if fill else color, + fill=fill if fill else None, + zorder=None if fill else mlines.Line2D.zorder)) + for patch_list in patches: + for patch in patch_list: + if orientation == 'vertical': + patch.sticky_edges.y.append(0) + elif orientation == 'horizontal': + patch.sticky_edges.x.append(0) + + # we return patches, so put it back in the expected order + patches.reverse() + + # If None, make all labels None (via zip_longest below); otherwise, + # cast each element to str, but keep a single str as it. + labels = [] if label is None else np.atleast_1d(np.asarray(label, str)) + + if histtype == "step": + ec = kwargs.get('edgecolor', colors) + else: + ec = kwargs.get('edgecolor', None) + if ec is None or cbook._str_lower_equal(ec, 'none'): + edgecolors = itertools.repeat(ec) + else: + edgecolors = itertools.cycle(mcolors.to_rgba_array(ec)) + + fc = kwargs.get('facecolor', colors) + if cbook._str_lower_equal(fc, 'none'): + facecolors = itertools.repeat(fc) + else: + facecolors = itertools.cycle(mcolors.to_rgba_array(fc)) + + hatches = itertools.cycle(np.atleast_1d(kwargs.get('hatch', None))) + linewidths = itertools.cycle(np.atleast_1d(kwargs.get('linewidth', None))) + if 'linestyle' in kwargs: + linestyles = itertools.cycle(mlines._get_dash_patterns(kwargs['linestyle'])) + else: + linestyles = itertools.repeat(None) + + for patch, lbl in itertools.zip_longest(patches, labels): + if not patch: + continue + p = patch[0] + kwargs.update({ + 'hatch': next(hatches), + 'linewidth': next(linewidths), + 'linestyle': next(linestyles), + 'edgecolor': next(edgecolors), + 'facecolor': next(facecolors), + }) + p._internal_update(kwargs) + if lbl is not None: + p.set_label(lbl) + for p in patch[1:]: + p._internal_update(kwargs) + p.set_label('_nolegend_') + + if nx == 1: + return tops[0], bins, patches[0] + else: + patch_type = ("BarContainer" if histtype.startswith("bar") + else "list[Polygon]") + return tops, bins, cbook.silent_list(patch_type, patches) + + @_preprocess_data() + def stairs(self, values, edges=None, *, + orientation='vertical', baseline=0, fill=False, **kwargs): + """ + Draw a stepwise constant function as a line or a filled plot. + + *edges* define the x-axis positions of the steps. *values* the function values + between these steps. Depending on *fill*, the function is drawn either as a + continuous line with vertical segments at the edges, or as a filled area. + + Parameters + ---------- + values : array-like + The step heights. + + edges : array-like + The step positions, with ``len(edges) == len(vals) + 1``, + between which the curve takes on vals values. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + The direction of the steps. Vertical means that *values* are along + the y-axis, and edges are along the x-axis. + + baseline : float, array-like or None, default: 0 + The bottom value of the bounding edges or when + ``fill=True``, position of lower edge. If *fill* is + True or an array is passed to *baseline*, a closed + path is drawn. + + If None, then drawn as an unclosed Path. + + fill : bool, default: False + Whether the area under the step curve should be filled. + + Passing both ``fill=True` and ``baseline=None`` will likely result in + undesired filling: the first and last points will be connected + with a straight line and the fill will be between this line and the stairs. + + + Returns + ------- + StepPatch : `~matplotlib.patches.StepPatch` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + `~matplotlib.patches.StepPatch` properties + + """ + + if 'color' in kwargs: + _color = kwargs.pop('color') + else: + _color = self._get_lines.get_next_color() + if fill: + kwargs.setdefault('linewidth', 0) + kwargs.setdefault('facecolor', _color) + else: + kwargs.setdefault('edgecolor', _color) + + if edges is None: + edges = np.arange(len(values) + 1) + + edges, values, baseline = self._process_unit_info( + [("x", edges), ("y", values), ("y", baseline)], kwargs) + + patch = mpatches.StepPatch(values, + edges, + baseline=baseline, + orientation=orientation, + fill=fill, + **kwargs) + self.add_patch(patch) + if baseline is None and fill: + _api.warn_external( + f"Both {baseline=} and {fill=} have been passed. " + "baseline=None is only intended for unfilled stair plots. " + "Because baseline is None, the Path used to draw the stairs will " + "not be closed, thus because fill is True the polygon will be closed " + "by drawing an (unstroked) edge from the first to last point. It is " + "very likely that the resulting fill patterns is not the desired " + "result." + ) + + if baseline is not None: + if orientation == 'vertical': + patch.sticky_edges.y.append(np.min(baseline)) + self.update_datalim([(edges[0], np.min(baseline))]) + else: + patch.sticky_edges.x.append(np.min(baseline)) + self.update_datalim([(np.min(baseline), edges[0])]) + self._request_autoscale_view() + return patch + + @_api.make_keyword_only("3.10", "range") + @_preprocess_data(replace_names=["x", "y", "weights"]) + @_docstring.interpd + def hist2d(self, x, y, bins=10, range=None, density=False, weights=None, + cmin=None, cmax=None, **kwargs): + """ + Make a 2D histogram plot. + + Parameters + ---------- + x, y : array-like, shape (n, ) + Input values + + bins : None or int or [int, int] or array-like or [array, array] + + The bin specification: + + - If int, the number of bins for the two dimensions + (``nx = ny = bins``). + - If ``[int, int]``, the number of bins in each dimension + (``nx, ny = bins``). + - If array-like, the bin edges for the two dimensions + (``x_edges = y_edges = bins``). + - If ``[array, array]``, the bin edges in each dimension + (``x_edges, y_edges = bins``). + + The default value is 10. + + range : array-like shape(2, 2), optional + The leftmost and rightmost edges of the bins along each dimension + (if not specified explicitly in the bins parameters): ``[[xmin, + xmax], [ymin, ymax]]``. All values outside of this range will be + considered outliers and not tallied in the histogram. + + density : bool, default: False + Normalize histogram. See the documentation for the *density* + parameter of `~.Axes.hist` for more details. + + weights : array-like, shape (n, ), optional + An array of values w_i weighing each sample (x_i, y_i). + + cmin, cmax : float, default: None + All bins that has count less than *cmin* or more than *cmax* will not be + displayed (set to NaN before passing to `~.Axes.pcolormesh`) and these count + values in the return value count histogram will also be set to nan upon + return. + + Returns + ------- + h : 2D array + The bi-dimensional histogram of samples x and y. Values in x are + histogrammed along the first dimension and values in y are + histogrammed along the second dimension. + xedges : 1D array + The bin edges along the x-axis. + yedges : 1D array + The bin edges along the y-axis. + image : `~.matplotlib.collections.QuadMesh` + + Other Parameters + ---------------- + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + %(colorizer_doc)s + + alpha : ``0 <= scalar <= 1`` or ``None``, optional + The alpha blending value. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed along to the + `~.Axes.pcolormesh` method and `~matplotlib.collections.QuadMesh` + constructor. + + See Also + -------- + hist : 1D histogram plotting + hexbin : 2D histogram with hexagonal bins + + Notes + ----- + - Currently ``hist2d`` calculates its own axis limits, and any limits + previously set are ignored. + - Rendering the histogram with a logarithmic color scale is + accomplished by passing a `.colors.LogNorm` instance to the *norm* + keyword argument. Likewise, power-law normalization (similar + in effect to gamma correction) can be accomplished with + `.colors.PowerNorm`. + """ + + h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range, + density=density, weights=weights) + + if cmin is not None: + h[h < cmin] = None + if cmax is not None: + h[h > cmax] = None + + pc = self.pcolormesh(xedges, yedges, h.T, **kwargs) + self.set_xlim(xedges[0], xedges[-1]) + self.set_ylim(yedges[0], yedges[-1]) + + return h, xedges, yedges, pc + + @_preprocess_data(replace_names=["x", "weights"], label_namer="x") + @_docstring.interpd + def ecdf(self, x, weights=None, *, complementary=False, + orientation="vertical", compress=False, **kwargs): + """ + Compute and plot the empirical cumulative distribution function of *x*. + + .. versionadded:: 3.8 + + Parameters + ---------- + x : 1d array-like + The input data. Infinite entries are kept (and move the relevant + end of the ecdf from 0/1), but NaNs and masked values are errors. + + weights : 1d array-like or None, default: None + The weights of the entries; must have the same shape as *x*. + Weights corresponding to NaN data points are dropped, and then the + remaining weights are normalized to sum to 1. If unset, all + entries have the same weight. + + complementary : bool, default: False + Whether to plot a cumulative distribution function, which increases + from 0 to 1 (the default), or a complementary cumulative + distribution function, which decreases from 1 to 0. + + orientation : {"vertical", "horizontal"}, default: "vertical" + Whether the entries are plotted along the x-axis ("vertical", the + default) or the y-axis ("horizontal"). This parameter takes the + same values as in `~.Axes.hist`. + + compress : bool, default: False + Whether multiple entries with the same values are grouped together + (with a summed weight) before plotting. This is mainly useful if + *x* contains many identical data points, to decrease the rendering + complexity of the plot. If *x* contains no duplicate points, this + has no effect and just uses some time and memory. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + Returns + ------- + `.Line2D` + + Notes + ----- + The ecdf plot can be thought of as a cumulative histogram with one bin + per data entry; i.e. it reports on the entire dataset without any + arbitrary binning. + + If *x* contains NaNs or masked entries, either remove them first from + the array (if they should not taken into account), or replace them by + -inf or +inf (if they should be sorted at the beginning or the end of + the array). + """ + _api.check_in_list(["horizontal", "vertical"], orientation=orientation) + if "drawstyle" in kwargs or "ds" in kwargs: + raise TypeError("Cannot pass 'drawstyle' or 'ds' to ecdf()") + if np.ma.getmask(x).any(): + raise ValueError("ecdf() does not support masked entries") + x = np.asarray(x) + if np.isnan(x).any(): + raise ValueError("ecdf() does not support NaNs") + argsort = np.argsort(x) + x = x[argsort] + if weights is None: + # Ensure that we end at exactly 1, avoiding floating point errors. + cum_weights = (1 + np.arange(len(x))) / len(x) + else: + weights = np.take(weights, argsort) # Reorder weights like we reordered x. + cum_weights = np.cumsum(weights / np.sum(weights)) + if compress: + # Get indices of unique x values. + compress_idxs = [0, *(x[:-1] != x[1:]).nonzero()[0] + 1] + x = x[compress_idxs] + cum_weights = cum_weights[compress_idxs] + if orientation == "vertical": + if not complementary: + line, = self.plot([x[0], *x], [0, *cum_weights], + drawstyle="steps-post", **kwargs) + else: + line, = self.plot([*x, x[-1]], [1, *1 - cum_weights], + drawstyle="steps-pre", **kwargs) + line.sticky_edges.y[:] = [0, 1] + else: # orientation == "horizontal": + if not complementary: + line, = self.plot([0, *cum_weights], [x[0], *x], + drawstyle="steps-pre", **kwargs) + else: + line, = self.plot([1, *1 - cum_weights], [*x, x[-1]], + drawstyle="steps-post", **kwargs) + line.sticky_edges.x[:] = [0, 1] + return line + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, pad_to=None, + sides=None, scale_by_freq=None, return_line=None, **kwargs): + r""" + Plot the power spectral density. + + The power spectral density :math:`P_{xx}` by Welch's average + periodogram method. The vector *x* is divided into *NFFT* length + segments. Each segment is detrended by function *detrend* and + windowed by function *window*. *noverlap* gives the length of + the overlap between segments. The :math:`|\mathrm{fft}(i)|^2` + of each segment :math:`i` are averaged to compute :math:`P_{xx}`, + with a scaling to correct for power loss due to windowing. + + If len(*x*) < *NFFT*, it will be zero padded to *NFFT*. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data + + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between segments. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + return_line : bool, default: False + Whether to include the line object plotted in the returned values. + + Returns + ------- + Pxx : 1-D array + The values for the power spectrum :math:`P_{xx}` before scaling + (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *Pxx*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + Only returned if *return_line* is True. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + specgram + Differs in the default overlap; in not returning the mean of the + segment periodograms; in returning the times of the segments; and + in plotting a colormap instead of a line. + magnitude_spectrum + Plots the magnitude spectrum. + csd + Plots the spectral density between two signals. + + Notes + ----- + For plotting, the power is plotted as + :math:`10\log_{10}(P_{xx})` for decibels, though *Pxx* itself + is returned. + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + if Fc is None: + Fc = 0 + + pxx, freqs = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, pad_to=pad_to, + sides=sides, scale_by_freq=scale_by_freq) + freqs += Fc + + if scale_by_freq in (None, True): + psd_units = 'dB/Hz' + else: + psd_units = 'dB' + + line = self.plot(freqs, 10 * np.log10(pxx), **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Power Spectral Density (%s)' % psd_units) + self.grid(True) + + vmin, vmax = self.get_ybound() + step = max(10 * int(np.log10(vmax - vmin)), 1) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) + self.set_yticks(ticks) + + if return_line is None or not return_line: + return pxx, freqs + else: + return pxx, freqs, line + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + @_docstring.interpd + def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, pad_to=None, + sides=None, scale_by_freq=None, return_line=None, **kwargs): + r""" + Plot the cross-spectral density. + + The cross spectral density :math:`P_{xy}` by Welch's average + periodogram method. The vectors *x* and *y* are divided into + *NFFT* length segments. Each segment is detrended by function + *detrend* and windowed by function *window*. *noverlap* gives + the length of the overlap between segments. The product of + the direct FFTs of *x* and *y* are averaged over each segment + to compute :math:`P_{xy}`, with a scaling to correct for power + loss due to windowing. + + If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero + padded to *NFFT*. + + Parameters + ---------- + x, y : 1-D arrays or sequences + Arrays or sequences containing the data. + + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between segments. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + return_line : bool, default: False + Whether to include the line object plotted in the returned values. + + Returns + ------- + Pxy : 1-D array + The values for the cross spectrum :math:`P_{xy}` before scaling + (complex valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *Pxy*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + Only returned if *return_line* is True. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + psd : is equivalent to setting ``y = x``. + + Notes + ----- + For plotting, the power is plotted as + :math:`10 \log_{10}(P_{xy})` for decibels, though :math:`P_{xy}` itself + is returned. + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + if Fc is None: + Fc = 0 + + pxy, freqs = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, pad_to=pad_to, + sides=sides, scale_by_freq=scale_by_freq) + # pxy is complex + freqs += Fc + + line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Cross Spectrum Magnitude (dB)') + self.grid(True) + + vmin, vmax = self.get_ybound() + step = max(10 * int(np.log10(vmax - vmin)), 1) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) + self.set_yticks(ticks) + + if return_line is None or not return_line: + return pxy, freqs + else: + return pxy, freqs, line + + @_api.make_keyword_only("3.10", "Fs") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, scale=None, + **kwargs): + """ + Plot the magnitude spectrum. + + Compute the magnitude spectrum of *x*. Data is padded to a + length of *pad_to* and the windowing function *window* is applied to + the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(Single_Spectrum)s + + scale : {'default', 'linear', 'dB'} + The scaling of the values in the *spec*. 'linear' is no scaling. + 'dB' returns the values in dB scale, i.e., the dB amplitude + (20 * log10). 'default' is 'linear'. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the magnitude spectrum before scaling (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + psd + Plots the power spectral density. + angle_spectrum + Plots the angles of the corresponding frequencies. + phase_spectrum + Plots the phase (unwrapped angle) of the corresponding frequencies. + specgram + Can plot the magnitude spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.magnitude_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + yunits = _api.check_getitem( + {None: 'energy', 'default': 'energy', 'linear': 'energy', + 'dB': 'dB'}, + scale=scale) + if yunits == 'energy': + Z = spec + else: # yunits == 'dB' + Z = 20. * np.log10(spec) + + line, = self.plot(freqs, Z, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Magnitude (%s)' % yunits) + + return spec, freqs, line + + @_api.make_keyword_only("3.10", "Fs") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def angle_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, **kwargs): + """ + Plot the angle spectrum. + + Compute the angle spectrum (wrapped phase spectrum) of *x*. + Data is padded to a length of *pad_to* and the windowing function + *window* is applied to the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(Single_Spectrum)s + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the angle spectrum in radians (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + magnitude_spectrum + Plots the magnitudes of the corresponding frequencies. + phase_spectrum + Plots the unwrapped version of this function. + specgram + Can plot the angle spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.angle_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + lines = self.plot(freqs, spec, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Angle (radians)') + + return spec, freqs, lines[0] + + @_api.make_keyword_only("3.10", "Fs") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def phase_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, **kwargs): + """ + Plot the phase spectrum. + + Compute the phase spectrum (unwrapped angle spectrum) of *x*. + Data is padded to a length of *pad_to* and the windowing function + *window* is applied to the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data + + %(Spectral)s + + %(Single_Spectrum)s + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the phase spectrum in radians (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + magnitude_spectrum + Plots the magnitudes of the corresponding frequencies. + angle_spectrum + Plots the wrapped version of this function. + specgram + Can plot the phase spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.phase_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + lines = self.plot(freqs, spec, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Phase (radians)') + + return spec, freqs, lines[0] + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x", "y"]) + @_docstring.interpd + def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, + window=mlab.window_hanning, noverlap=0, pad_to=None, + sides='default', scale_by_freq=None, **kwargs): + r""" + Plot the coherence between *x* and *y*. + + Coherence is the normalized cross spectral density: + + .. math:: + + C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}} + + Parameters + ---------- + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between blocks. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + Cxy : 1-D array + The coherence vector. + + freqs : 1-D array + The frequencies for the elements in *Cxy*. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + cxy, freqs = mlab.cohere(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, + scale_by_freq=scale_by_freq, sides=sides, + pad_to=pad_to) + freqs += Fc + + self.plot(freqs, cxy, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Coherence') + self.grid(True) + + return cxy, freqs + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, + cmap=None, xextent=None, pad_to=None, sides=None, + scale_by_freq=None, mode=None, scale=None, + vmin=None, vmax=None, **kwargs): + """ + Plot a spectrogram. + + Compute and plot a spectrogram of data in *x*. Data are split into + *NFFT* length segments and the spectrum of each section is + computed. The windowing function *window* is applied to each + segment, and the amount of overlap of each segment is + specified with *noverlap*. The spectrogram is plotted as a colormap + (using imshow). + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(PSD)s + + mode : {'default', 'psd', 'magnitude', 'angle', 'phase'} + What sort of spectrum to use. Default is 'psd', which takes the + power spectral density. 'magnitude' returns the magnitude + spectrum. 'angle' returns the phase spectrum without unwrapping. + 'phase' returns the phase spectrum with unwrapping. + + noverlap : int, default: 128 + The number of points of overlap between blocks. + + scale : {'default', 'linear', 'dB'} + The scaling of the values in the *spec*. 'linear' is no scaling. + 'dB' returns the values in dB scale. When *mode* is 'psd', + this is dB power (10 * log10). Otherwise, this is dB amplitude + (20 * log10). 'default' is 'dB' if *mode* is 'psd' or + 'magnitude' and 'linear' otherwise. This must be 'linear' + if *mode* is 'angle' or 'phase'. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + cmap : `.Colormap`, default: :rc:`image.cmap` + + xextent : *None* or (xmin, xmax) + The image extent along the x-axis. The default sets *xmin* to the + left border of the first bin (*spectrum* column) and *xmax* to the + right border of the last bin. Note that for *noverlap>0* the width + of the bins is smaller than those of the segments. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + vmin, vmax : float, optional + vmin and vmax define the data range that the colormap covers. + By default, the colormap covers the complete value range of the + data. + + **kwargs + Additional keyword arguments are passed on to `~.axes.Axes.imshow` + which makes the specgram image. The origin keyword argument + is not supported. + + Returns + ------- + spectrum : 2D array + Columns are the periodograms of successive segments. + + freqs : 1-D array + The frequencies corresponding to the rows in *spectrum*. + + t : 1-D array + The times corresponding to midpoints of segments (i.e., the columns + in *spectrum*). + + im : `.AxesImage` + The image created by imshow containing the spectrogram. + + See Also + -------- + psd + Differs in the default overlap; in returning the mean of the + segment periodograms; in not returning times; and in generating a + line plot instead of colormap. + magnitude_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'magnitude'. Plots a line instead of a colormap. + angle_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'angle'. Plots a line instead of a colormap. + phase_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'phase'. Plots a line instead of a colormap. + + Notes + ----- + The parameters *detrend* and *scale_by_freq* do only apply when *mode* + is set to 'psd'. + """ + if NFFT is None: + NFFT = 256 # same default as in mlab.specgram() + if Fc is None: + Fc = 0 # same default as in mlab._spectral_helper() + if noverlap is None: + noverlap = 128 # same default as in mlab.specgram() + if Fs is None: + Fs = 2 # same default as in mlab._spectral_helper() + + if mode == 'complex': + raise ValueError('Cannot plot a complex specgram') + + if scale is None or scale == 'default': + if mode in ['angle', 'phase']: + scale = 'linear' + else: + scale = 'dB' + elif mode in ['angle', 'phase'] and scale == 'dB': + raise ValueError('Cannot use dB scale with angle or phase mode') + + spec, freqs, t = mlab.specgram(x=x, NFFT=NFFT, Fs=Fs, + detrend=detrend, window=window, + noverlap=noverlap, pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + mode=mode) + + if scale == 'linear': + Z = spec + elif scale == 'dB': + if mode is None or mode == 'default' or mode == 'psd': + Z = 10. * np.log10(spec) + else: + Z = 20. * np.log10(spec) + else: + raise ValueError(f'Unknown scale {scale!r}') + + Z = np.flipud(Z) + + if xextent is None: + # padding is needed for first and last segment: + pad_xextent = (NFFT-noverlap) / Fs / 2 + xextent = np.min(t) - pad_xextent, np.max(t) + pad_xextent + xmin, xmax = xextent + freqs += Fc + extent = xmin, xmax, freqs[0], freqs[-1] + + if 'origin' in kwargs: + raise _api.kwarg_error("specgram", "origin") + + im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax, + origin='upper', **kwargs) + self.axis('auto') + + return spec, freqs, t, im + + @_api.make_keyword_only("3.10", "precision") + @_docstring.interpd + def spy(self, Z, precision=0, marker=None, markersize=None, + aspect='equal', origin="upper", **kwargs): + """ + Plot the sparsity pattern of a 2D array. + + This visualizes the non-zero values of the array. + + Two plotting styles are available: image and marker. Both + are available for full arrays, but only the marker style + works for `scipy.sparse.spmatrix` instances. + + **Image style** + + If *marker* and *markersize* are *None*, `~.Axes.imshow` is used. Any + extra remaining keyword arguments are passed to this method. + + **Marker style** + + If *Z* is a `scipy.sparse.spmatrix` or *marker* or *markersize* are + *None*, a `.Line2D` object will be returned with the value of marker + determining the marker type, and any remaining keyword arguments + passed to `~.Axes.plot`. + + Parameters + ---------- + Z : (M, N) array-like + The array to be plotted. + + precision : float or 'present', default: 0 + If *precision* is 0, any non-zero value will be plotted. Otherwise, + values of :math:`|Z| > precision` will be plotted. + + For `scipy.sparse.spmatrix` instances, you can also + pass 'present'. In this case any value present in the array + will be plotted, even if it is identically zero. + + aspect : {'equal', 'auto', None} or float, default: 'equal' + The aspect ratio of the Axes. This parameter is particularly + relevant for images since it determines whether data pixels are + square. + + This parameter is a shortcut for explicitly calling + `.Axes.set_aspect`. See there for further details. + + - 'equal': Ensures an aspect ratio of 1. Pixels will be square. + - 'auto': The Axes is kept fixed and the aspect is adjusted so + that the data fit in the Axes. In general, this will result in + non-square pixels. + - *None*: Use :rc:`image.aspect`. + + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Place the [0, 0] index of the array in the upper left or lower left + corner of the Axes. The convention 'upper' is typically used for + matrices and images. + + Returns + ------- + `~matplotlib.image.AxesImage` or `.Line2D` + The return type depends on the plotting style (see above). + + Other Parameters + ---------------- + **kwargs + The supported additional parameters depend on the plotting style. + + For the image style, you can pass the following additional + parameters of `~.Axes.imshow`: + + - *cmap* + - *alpha* + - *url* + - any `.Artist` properties (passed on to the `.AxesImage`) + + For the marker style, you can pass any `.Line2D` property except + for *linestyle*: + + %(Line2D:kwdoc)s + """ + if marker is None and markersize is None and hasattr(Z, 'tocoo'): + marker = 's' + _api.check_in_list(["upper", "lower"], origin=origin) + if marker is None and markersize is None: + Z = np.asarray(Z) + mask = np.abs(Z) > precision + + if 'cmap' not in kwargs: + kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], + name='binary') + if 'interpolation' in kwargs: + raise _api.kwarg_error("spy", "interpolation") + if 'norm' not in kwargs: + kwargs['norm'] = mcolors.NoNorm() + ret = self.imshow(mask, interpolation='nearest', + aspect=aspect, origin=origin, + **kwargs) + else: + if hasattr(Z, 'tocoo'): + c = Z.tocoo() + if precision == 'present': + y = c.row + x = c.col + else: + nonzero = np.abs(c.data) > precision + y = c.row[nonzero] + x = c.col[nonzero] + else: + Z = np.asarray(Z) + nonzero = np.abs(Z) > precision + y, x = np.nonzero(nonzero) + if marker is None: + marker = 's' + if markersize is None: + markersize = 10 + if 'linestyle' in kwargs: + raise _api.kwarg_error("spy", "linestyle") + ret = mlines.Line2D( + x, y, linestyle='None', marker=marker, markersize=markersize, + **kwargs) + self.add_line(ret) + nr, nc = Z.shape + self.set_xlim(-0.5, nc - 0.5) + if origin == "upper": + self.set_ylim(nr - 0.5, -0.5) + else: + self.set_ylim(-0.5, nr - 0.5) + self.set_aspect(aspect) + self.title.set_y(1.05) + if origin == "upper": + self.xaxis.tick_top() + else: # lower + self.xaxis.tick_bottom() + self.xaxis.set_ticks_position('both') + self.xaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + self.yaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + return ret + + def matshow(self, Z, **kwargs): + """ + Plot the values of a 2D matrix or array as color-coded image. + + The matrix will be shown the way it would be printed, with the first + row at the top. Row and column numbering is zero-based. + + Parameters + ---------- + Z : (M, N) array-like + The matrix to be displayed. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.axes.Axes.imshow` arguments + + See Also + -------- + imshow : More general function to plot data on a 2D regular raster. + + Notes + ----- + This is just a convenience function wrapping `.imshow` to set useful + defaults for displaying a matrix. In particular: + + - Set ``origin='upper'``. + - Set ``interpolation='nearest'``. + - Set ``aspect='equal'``. + - Ticks are placed to the left and above. + - Ticks are formatted to show integer indices. + + """ + Z = np.asanyarray(Z) + kw = {'origin': 'upper', + 'interpolation': 'nearest', + 'aspect': 'equal', # (already the imshow default) + **kwargs} + im = self.imshow(Z, **kw) + self.title.set_y(1.05) + self.xaxis.tick_top() + self.xaxis.set_ticks_position('both') + self.xaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + self.yaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + return im + + @_api.make_keyword_only("3.10", "vert") + @_preprocess_data(replace_names=["dataset"]) + def violinplot(self, dataset, positions=None, vert=None, + orientation='vertical', widths=0.5, showmeans=False, + showextrema=True, showmedians=False, quantiles=None, + points=100, bw_method=None, side='both',): + """ + Make a violin plot. + + Make a violin plot for each column of *dataset* or each vector in + sequence *dataset*. Each filled area extends to represent the + entire data range, with optional lines at the mean, the median, + the minimum, the maximum, and user-specified quantiles. + + Parameters + ---------- + dataset : Array or a sequence of vectors. + The input data. + + positions : array-like, default: [1, 2, ..., n] + The positions of the violins; i.e. coordinates on the x-axis for + vertical violins (or y-axis for horizontal violins). + + vert : bool, optional + .. deprecated:: 3.10 + Use *orientation* instead. + + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the violins vertically. + If False, plots the violins horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the violins horizontally. + Otherwise, plots the violins vertically. + + .. versionadded:: 3.10 + + widths : float or array-like, default: 0.5 + The maximum width of each violin in units of the *positions* axis. + The default is 0.5, which is half the available space when using default + *positions*. + + showmeans : bool, default: False + Whether to show the mean with a line. + + showextrema : bool, default: True + Whether to show extrema with a line. + + showmedians : bool, default: False + Whether to show the median with a line. + + quantiles : array-like, default: None + If not None, set a list of floats in interval [0, 1] for each violin, + which stands for the quantiles that will be rendered for that + violin. + + points : int, default: 100 + The number of points to evaluate each of the gaussian kernel density + estimations at. + + bw_method : {'scott', 'silverman'} or float or callable, default: 'scott' + The method used to calculate the estimator bandwidth. If a + float, this will be used directly as `kde.factor`. If a + callable, it should take a `matplotlib.mlab.GaussianKDE` instance as + its only parameter and return a float. + + side : {'both', 'low', 'high'}, default: 'both' + 'both' plots standard violins. 'low'/'high' only + plots the side below/above the positions value. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + dict + A dictionary mapping each component of the violinplot to a + list of the corresponding collection instances created. The + dictionary has the following keys: + + - ``bodies``: A list of the `~.collections.PolyCollection` + instances containing the filled area of each violin. + + - ``cmeans``: A `~.collections.LineCollection` instance that marks + the mean values of each of the violin's distribution. + + - ``cmins``: A `~.collections.LineCollection` instance that marks + the bottom of each violin's distribution. + + - ``cmaxes``: A `~.collections.LineCollection` instance that marks + the top of each violin's distribution. + + - ``cbars``: A `~.collections.LineCollection` instance that marks + the centers of each violin's distribution. + + - ``cmedians``: A `~.collections.LineCollection` instance that + marks the median values of each of the violin's distribution. + + - ``cquantiles``: A `~.collections.LineCollection` instance created + to identify the quantile values of each of the violin's + distribution. + + See Also + -------- + .Axes.violin : Draw a violin from pre-computed statistics. + boxplot : Draw a box and whisker plot. + """ + + def _kde_method(X, coords): + # Unpack in case of e.g. Pandas or xarray object + X = cbook._unpack_to_numpy(X) + # fallback gracefully if the vector contains only one value + if np.all(X[0] == X): + return (X[0] == coords).astype(float) + kde = mlab.GaussianKDE(X, bw_method) + return kde.evaluate(coords) + + vpstats = cbook.violin_stats(dataset, _kde_method, points=points, + quantiles=quantiles) + return self.violin(vpstats, positions=positions, vert=vert, + orientation=orientation, widths=widths, + showmeans=showmeans, showextrema=showextrema, + showmedians=showmedians, side=side) + + @_api.make_keyword_only("3.10", "vert") + def violin(self, vpstats, positions=None, vert=None, + orientation='vertical', widths=0.5, showmeans=False, + showextrema=True, showmedians=False, side='both'): + """ + Draw a violin plot from pre-computed statistics. + + Draw a violin plot for each column of *vpstats*. Each filled area + extends to represent the entire data range, with optional lines at the + mean, the median, the minimum, the maximum, and the quantiles values. + + Parameters + ---------- + vpstats : list of dicts + A list of dictionaries containing stats for each violin plot. + Required keys are: + + - ``coords``: A list of scalars containing the coordinates that + the violin's kernel density estimate were evaluated at. + + - ``vals``: A list of scalars containing the values of the + kernel density estimate at each of the coordinates given + in *coords*. + + - ``mean``: The mean value for this violin's dataset. + + - ``median``: The median value for this violin's dataset. + + - ``min``: The minimum value for this violin's dataset. + + - ``max``: The maximum value for this violin's dataset. + + Optional keys are: + + - ``quantiles``: A list of scalars containing the quantile values + for this violin's dataset. + + positions : array-like, default: [1, 2, ..., n] + The positions of the violins; i.e. coordinates on the x-axis for + vertical violins (or y-axis for horizontal violins). + + vert : bool, optional + .. deprecated:: 3.10 + Use *orientation* instead. + + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the violins vertically. + If False, plots the violins horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the violins horizontally. + Otherwise, plots the violins vertically. + + .. versionadded:: 3.10 + + widths : float or array-like, default: 0.5 + The maximum width of each violin in units of the *positions* axis. + The default is 0.5, which is half available space when using default + *positions*. + + showmeans : bool, default: False + Whether to show the mean with a line. + + showextrema : bool, default: True + Whether to show extrema with a line. + + showmedians : bool, default: False + Whether to show the median with a line. + + side : {'both', 'low', 'high'}, default: 'both' + 'both' plots standard violins. 'low'/'high' only + plots the side below/above the positions value. + + Returns + ------- + dict + A dictionary mapping each component of the violinplot to a + list of the corresponding collection instances created. The + dictionary has the following keys: + + - ``bodies``: A list of the `~.collections.PolyCollection` + instances containing the filled area of each violin. + + - ``cmeans``: A `~.collections.LineCollection` instance that marks + the mean values of each of the violin's distribution. + + - ``cmins``: A `~.collections.LineCollection` instance that marks + the bottom of each violin's distribution. + + - ``cmaxes``: A `~.collections.LineCollection` instance that marks + the top of each violin's distribution. + + - ``cbars``: A `~.collections.LineCollection` instance that marks + the centers of each violin's distribution. + + - ``cmedians``: A `~.collections.LineCollection` instance that + marks the median values of each of the violin's distribution. + + - ``cquantiles``: A `~.collections.LineCollection` instance created + to identify the quantiles values of each of the violin's + distribution. + + See Also + -------- + violinplot : + Draw a violin plot from data instead of pre-computed statistics. + """ + + # Statistical quantities to be plotted on the violins + means = [] + mins = [] + maxes = [] + medians = [] + quantiles = [] + + qlens = [] # Number of quantiles in each dataset. + + artists = {} # Collections to be returned + + N = len(vpstats) + datashape_message = ("List of violinplot statistics and `{0}` " + "values must have the same length") + + # vert and orientation parameters are linked until vert's + # deprecation period expires. If both are selected, + # vert takes precedence. + if vert is not None: + _api.warn_deprecated( + "3.11", + name="vert: bool", + alternative="orientation: {'vertical', 'horizontal'}", + pending=True, + ) + orientation = 'vertical' if vert else 'horizontal' + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + # Validate positions + if positions is None: + positions = range(1, N + 1) + elif len(positions) != N: + raise ValueError(datashape_message.format("positions")) + + # Validate widths + if np.isscalar(widths): + widths = [widths] * N + elif len(widths) != N: + raise ValueError(datashape_message.format("widths")) + + # Validate side + _api.check_in_list(["both", "low", "high"], side=side) + + # Calculate ranges for statistics lines (shape (2, N)). + line_ends = [[-0.25 if side in ['both', 'low'] else 0], + [0.25 if side in ['both', 'high'] else 0]] \ + * np.array(widths) + positions + + # Colors. + if mpl.rcParams['_internal.classic_mode']: + fillcolor = 'y' + linecolor = 'r' + else: + fillcolor = linecolor = self._get_lines.get_next_color() + + # Check whether we are rendering vertically or horizontally + if orientation == 'vertical': + fill = self.fill_betweenx + if side in ['low', 'high']: + perp_lines = functools.partial(self.hlines, colors=linecolor, + capstyle='projecting') + par_lines = functools.partial(self.vlines, colors=linecolor, + capstyle='projecting') + else: + perp_lines = functools.partial(self.hlines, colors=linecolor) + par_lines = functools.partial(self.vlines, colors=linecolor) + else: + fill = self.fill_between + if side in ['low', 'high']: + perp_lines = functools.partial(self.vlines, colors=linecolor, + capstyle='projecting') + par_lines = functools.partial(self.hlines, colors=linecolor, + capstyle='projecting') + else: + perp_lines = functools.partial(self.vlines, colors=linecolor) + par_lines = functools.partial(self.hlines, colors=linecolor) + + # Render violins + bodies = [] + for stats, pos, width in zip(vpstats, positions, widths): + # The 0.5 factor reflects the fact that we plot from v-p to v+p. + vals = np.array(stats['vals']) + vals = 0.5 * width * vals / vals.max() + bodies += [fill(stats['coords'], + -vals + pos if side in ['both', 'low'] else pos, + vals + pos if side in ['both', 'high'] else pos, + facecolor=fillcolor, alpha=0.3)] + means.append(stats['mean']) + mins.append(stats['min']) + maxes.append(stats['max']) + medians.append(stats['median']) + q = stats.get('quantiles') # a list of floats, or None + if q is None: + q = [] + quantiles.extend(q) + qlens.append(len(q)) + artists['bodies'] = bodies + + if showmeans: # Render means + artists['cmeans'] = perp_lines(means, *line_ends) + if showextrema: # Render extrema + artists['cmaxes'] = perp_lines(maxes, *line_ends) + artists['cmins'] = perp_lines(mins, *line_ends) + artists['cbars'] = par_lines(positions, mins, maxes) + if showmedians: # Render medians + artists['cmedians'] = perp_lines(medians, *line_ends) + if quantiles: # Render quantiles: each width is repeated qlen times. + artists['cquantiles'] = perp_lines( + quantiles, *np.repeat(line_ends, qlens, axis=1)) + + return artists + + # Methods that are entirely implemented in other modules. + + table = _make_axes_method(mtable.table) + + # args can be either Y or y1, y2, ... and all should be replaced + stackplot = _preprocess_data()(_make_axes_method(mstack.stackplot)) + + streamplot = _preprocess_data( + replace_names=["x", "y", "u", "v", "start_points"])( + _make_axes_method(mstream.streamplot)) + + tricontour = _make_axes_method(mtri.tricontour) + tricontourf = _make_axes_method(mtri.tricontourf) + tripcolor = _make_axes_method(mtri.tripcolor) + triplot = _make_axes_method(mtri.triplot) + + def _get_aspect_ratio(self): + """ + Convenience method to calculate the aspect ratio of the Axes in + the display coordinate system. + """ + figure_size = self.get_figure().get_size_inches() + ll, ur = self.get_position() * figure_size + width, height = ur - ll + return height / (width * self.get_data_ratio()) diff --git a/shared/package-files/0b/0b037aa7ff6a50ec27b41fcc6af78f8d08280dc7f29253e5ee22fda4c8c6ba63/_functional_sym_constrain_range_compositeexplicitautograd_dispatch.h b/shared/package-files/0b/0b037aa7ff6a50ec27b41fcc6af78f8d08280dc7f29253e5ee22fda4c8c6ba63/_functional_sym_constrain_range_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b86b9b93db45e8d9b69718734ad2e9316a01ea35 --- /dev/null +++ b/shared/package-files/0b/0b037aa7ff6a50ec27b41fcc6af78f8d08280dc7f29253e5ee22fda4c8c6ba63/_functional_sym_constrain_range_compositeexplicitautograd_dispatch.h @@ -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 _functional_sym_constrain_range(const at::Scalar & size, c10::optional min, c10::optional max, const at::Tensor & dep_token); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/0b/0b06f83f70673fb41a55be48d7c7542730695032a84c657c14f1f481e03dbbc8/type_as_ops.h b/shared/package-files/0b/0b06f83f70673fb41a55be48d7c7542730695032a84c657c14f1f481e03dbbc8/type_as_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f050ef49a8fbc74d978fbf0e748b2946fdab7555 --- /dev/null +++ b/shared/package-files/0b/0b06f83f70673fb41a55be48d7c7542730695032a84c657c14f1f481e03dbbc8/type_as_ops.h @@ -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 type_as { + 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::type_as") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "type_as(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); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/0b/0b0965c52e13f5c3f6bad63ec6eba2dc6860b63441900efbe7d6f24b82dd4375/test_neighbors_pipeline.py b/shared/package-files/0b/0b0965c52e13f5c3f6bad63ec6eba2dc6860b63441900efbe7d6f24b82dd4375/test_neighbors_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..6ad78824489cada3ad56ccff34d806ba6cf1278a --- /dev/null +++ b/shared/package-files/0b/0b0965c52e13f5c3f6bad63ec6eba2dc6860b63441900efbe7d6f24b82dd4375/test_neighbors_pipeline.py @@ -0,0 +1,256 @@ +""" +This is testing the equivalence between some estimators with internal nearest +neighbors computations, and the corresponding pipeline versions with +KNeighborsTransformer or RadiusNeighborsTransformer to precompute the +neighbors. +""" + +import numpy as np + +from sklearn.base import clone +from sklearn.cluster import DBSCAN, SpectralClustering +from sklearn.cluster.tests.common import generate_clustered_data +from sklearn.datasets import make_blobs +from sklearn.manifold import TSNE, Isomap, SpectralEmbedding +from sklearn.neighbors import ( + KNeighborsRegressor, + KNeighborsTransformer, + LocalOutlierFactor, + RadiusNeighborsRegressor, + RadiusNeighborsTransformer, +) +from sklearn.pipeline import make_pipeline +from sklearn.utils._testing import assert_array_almost_equal + + +def test_spectral_clustering(): + # Test chaining KNeighborsTransformer and SpectralClustering + n_neighbors = 5 + X, _ = make_blobs(random_state=0) + + # compare the chained version and the compact version + est_chain = make_pipeline( + KNeighborsTransformer(n_neighbors=n_neighbors, mode="connectivity"), + SpectralClustering( + n_neighbors=n_neighbors, affinity="precomputed", random_state=42 + ), + ) + est_compact = SpectralClustering( + n_neighbors=n_neighbors, affinity="nearest_neighbors", random_state=42 + ) + labels_compact = est_compact.fit_predict(X) + labels_chain = est_chain.fit_predict(X) + assert_array_almost_equal(labels_chain, labels_compact) + + +def test_spectral_embedding(): + # Test chaining KNeighborsTransformer and SpectralEmbedding + n_neighbors = 5 + + n_samples = 1000 + centers = np.array( + [ + [0.0, 5.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 4.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 5.0, 1.0], + ] + ) + S, true_labels = make_blobs( + n_samples=n_samples, centers=centers, cluster_std=1.0, random_state=42 + ) + + # compare the chained version and the compact version + est_chain = make_pipeline( + KNeighborsTransformer(n_neighbors=n_neighbors, mode="connectivity"), + SpectralEmbedding( + n_neighbors=n_neighbors, affinity="precomputed", random_state=42 + ), + ) + est_compact = SpectralEmbedding( + n_neighbors=n_neighbors, affinity="nearest_neighbors", random_state=42 + ) + St_compact = est_compact.fit_transform(S) + St_chain = est_chain.fit_transform(S) + assert_array_almost_equal(St_chain, St_compact) + + +def test_dbscan(): + # Test chaining RadiusNeighborsTransformer and DBSCAN + radius = 0.3 + n_clusters = 3 + X = generate_clustered_data(n_clusters=n_clusters) + + # compare the chained version and the compact version + est_chain = make_pipeline( + RadiusNeighborsTransformer(radius=radius, mode="distance"), + DBSCAN(metric="precomputed", eps=radius), + ) + est_compact = DBSCAN(eps=radius) + + labels_chain = est_chain.fit_predict(X) + labels_compact = est_compact.fit_predict(X) + assert_array_almost_equal(labels_chain, labels_compact) + + +def test_isomap(): + # Test chaining KNeighborsTransformer and Isomap with + # neighbors_algorithm='precomputed' + algorithm = "auto" + n_neighbors = 10 + + X, _ = make_blobs(random_state=0) + X2, _ = make_blobs(random_state=1) + + # compare the chained version and the compact version + est_chain = make_pipeline( + KNeighborsTransformer( + n_neighbors=n_neighbors, algorithm=algorithm, mode="distance" + ), + Isomap(n_neighbors=n_neighbors, metric="precomputed"), + ) + est_compact = Isomap(n_neighbors=n_neighbors, neighbors_algorithm=algorithm) + + Xt_chain = est_chain.fit_transform(X) + Xt_compact = est_compact.fit_transform(X) + assert_array_almost_equal(Xt_chain, Xt_compact) + + Xt_chain = est_chain.transform(X2) + Xt_compact = est_compact.transform(X2) + assert_array_almost_equal(Xt_chain, Xt_compact) + + +def test_tsne(): + # Test chaining KNeighborsTransformer and TSNE + max_iter = 250 + perplexity = 5 + n_neighbors = int(3.0 * perplexity + 1) + + rng = np.random.RandomState(0) + X = rng.randn(20, 2) + + for metric in ["minkowski", "sqeuclidean"]: + # compare the chained version and the compact version + est_chain = make_pipeline( + KNeighborsTransformer( + n_neighbors=n_neighbors, mode="distance", metric=metric + ), + TSNE( + init="random", + metric="precomputed", + perplexity=perplexity, + method="barnes_hut", + random_state=42, + max_iter=max_iter, + ), + ) + est_compact = TSNE( + init="random", + metric=metric, + perplexity=perplexity, + max_iter=max_iter, + method="barnes_hut", + random_state=42, + ) + + Xt_chain = est_chain.fit_transform(X) + Xt_compact = est_compact.fit_transform(X) + assert_array_almost_equal(Xt_chain, Xt_compact) + + +def test_lof_novelty_false(): + # Test chaining KNeighborsTransformer and LocalOutlierFactor + n_neighbors = 4 + + rng = np.random.RandomState(0) + X = rng.randn(40, 2) + + # compare the chained version and the compact version + est_chain = make_pipeline( + KNeighborsTransformer(n_neighbors=n_neighbors, mode="distance"), + LocalOutlierFactor( + metric="precomputed", + n_neighbors=n_neighbors, + novelty=False, + contamination="auto", + ), + ) + est_compact = LocalOutlierFactor( + n_neighbors=n_neighbors, novelty=False, contamination="auto" + ) + + pred_chain = est_chain.fit_predict(X) + pred_compact = est_compact.fit_predict(X) + assert_array_almost_equal(pred_chain, pred_compact) + + +def test_lof_novelty_true(): + # Test chaining KNeighborsTransformer and LocalOutlierFactor + n_neighbors = 4 + + rng = np.random.RandomState(0) + X1 = rng.randn(40, 2) + X2 = rng.randn(40, 2) + + # compare the chained version and the compact version + est_chain = make_pipeline( + KNeighborsTransformer(n_neighbors=n_neighbors, mode="distance"), + LocalOutlierFactor( + metric="precomputed", + n_neighbors=n_neighbors, + novelty=True, + contamination="auto", + ), + ) + est_compact = LocalOutlierFactor( + n_neighbors=n_neighbors, novelty=True, contamination="auto" + ) + + pred_chain = est_chain.fit(X1).predict(X2) + pred_compact = est_compact.fit(X1).predict(X2) + assert_array_almost_equal(pred_chain, pred_compact) + + +def test_kneighbors_regressor(): + # Test chaining KNeighborsTransformer and classifiers/regressors + rng = np.random.RandomState(0) + X = 2 * rng.rand(40, 5) - 1 + X2 = 2 * rng.rand(40, 5) - 1 + y = rng.rand(40, 1) + + n_neighbors = 12 + radius = 1.5 + # We precompute more neighbors than necessary, to have equivalence between + # k-neighbors estimator after radius-neighbors transformer, and vice-versa. + factor = 2 + + k_trans = KNeighborsTransformer(n_neighbors=n_neighbors, mode="distance") + k_trans_factor = KNeighborsTransformer( + n_neighbors=int(n_neighbors * factor), mode="distance" + ) + + r_trans = RadiusNeighborsTransformer(radius=radius, mode="distance") + r_trans_factor = RadiusNeighborsTransformer( + radius=int(radius * factor), mode="distance" + ) + + k_reg = KNeighborsRegressor(n_neighbors=n_neighbors) + r_reg = RadiusNeighborsRegressor(radius=radius) + + test_list = [ + (k_trans, k_reg), + (k_trans_factor, r_reg), + (r_trans, r_reg), + (r_trans_factor, k_reg), + ] + + for trans, reg in test_list: + # compare the chained version and the compact version + reg_compact = clone(reg) + reg_precomp = clone(reg) + reg_precomp.set_params(metric="precomputed") + + reg_chain = make_pipeline(clone(trans), reg_precomp) + + y_pred_chain = reg_chain.fit(X, y).predict(X2) + y_pred_compact = reg_compact.fit(X, y).predict(X2) + assert_array_almost_equal(y_pred_chain, y_pred_compact) diff --git a/shared/package-files/0b/0b0970183b6286c2e0edde29dc2622ba5680f3eaef225c277b818843020a0e91/loss.py b/shared/package-files/0b/0b0970183b6286c2e0edde29dc2622ba5680f3eaef225c277b818843020a0e91/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..f7144a38e92328fc69883af815e0e7bbc6a83d8c --- /dev/null +++ b/shared/package-files/0b/0b0970183b6286c2e0edde29dc2622ba5680f3eaef225c277b818843020a0e91/loss.py @@ -0,0 +1,484 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates +import contextlib +from typing import cast, Dict, Optional, Tuple + +import torch +import torch._prims_common as utils +import torch.distributed._functional_collectives as funcol +import torch.distributed.distributed_c10d as c10d +from torch import Tensor +from torch.distributed._tensor import DTensor, Replicate, Shard +from torch.distributed._tensor.ops.embedding_ops import _MaskPartial +from torch.distributed._tensor.ops.math_ops import ( + _skip_dim, + Reduction, + replicate_reduction_dims, +) +from torch.distributed._tensor.placement_types import Placement, TensorMeta +from torch.distributed.device_mesh import DeviceMesh + +aten = torch.ops.aten + + +__all__ = ["loss_parallel"] + + +@contextlib.contextmanager +def loss_parallel(): + """ + A context manager that enables loss parallelism, where efficient parallelized loss computation + can be performed when the input is sharded on the class dimension. Currently only the cross-entropy + loss is supported. + + Within this context manager, one can use :func:`~torch.nn.functional.cross_entropy` or + :class:`~torch.nn.CrossEntropyLoss` as usual, with the following assumptions on the input parameters. + The corresponding ``backward()`` call, if any, also needs to happen under this context manager. + + Args: + input (:class:`DTensor`): + Input logits. Assumed to be sharded on the class dimension. + target (Union[:class:`torch.Tensor`, :class:`DTensor`]): + Must be ground truth class indices (class probabilities currently not supported). + Assumed to be replicated across the ``DeviceMesh``. + weight (Union[:class:`torch.Tensor`, :class:`DTensor`], optional): + If given, assumed to be replicated across the ``DeviceMesh``. + label_smoothing: + Currently not supported. + + Returns: + A replicated :class:`DTensor`. + + Example: + A sharded DTensor is manually created here to showcase the usage. + In practice, it is usually the output of a TP module. + + >>> # xdoctest: +SKIP("distributed") + >>> from torch.distributed.tensor.parallel import loss_parallel + >>> from torch.distributed.device_mesh import init_device_mesh + >>> ... + >>> device_mesh = init_device_mesh("cuda", (8,)) + >>> input = torch.randn(4, 16, device="cuda", requires_grad=True) + >>> dist_input = distribute_tensor(input, device_mesh, placements=[Shard(1)]) + >>> target = torch.randint(16, (4,), device="cuda") + >>> with loss_parallel(): + >>> loss = F.cross_entropy(dist_input, target, reduction="mean") + >>> loss.backward() + >>> ... + """ + _enable_custom_loss_ops() + + yield + + _disable_custom_loss_ops() + + +# Currently only needs to support one dimensional DeviceMesh; in general return +# the mesh_dim with placements[mesh_dim].is_shard(dim) +def _find_all_reduce_mesh_dim(placements: Tuple[Placement, ...], dim: int) -> int: + if not len(placements) == 1: + raise ValueError( + "Currently loss_parallel() only supports input on one-dimensional DeviceMesh." + ) + if not placements[0].is_shard(dim): + raise ValueError( + f"loss_parallel() should be enabled only when the input tensor is sharded on dimension {dim}." + ) + return 0 + + +def _cast_to_dtensor( + tensor, placements: Tuple[Placement, ...], mesh: DeviceMesh +) -> DTensor: + if isinstance(tensor, DTensor): + if tensor.placements == placements: + return tensor + else: + raise RuntimeError(f"Expected {placements} but got {tensor.placements}.") + elif isinstance(tensor, torch.Tensor): + return DTensor.from_local( + tensor, device_mesh=mesh, placements=placements, run_check=False + ) + else: + raise TypeError(f"Unsupported type {type(tensor)}") + + +def _propagate_tensor_meta( + op_call: torch._ops.OpOverload, + args: Tuple[object, ...], + kwargs: Dict[str, object], +) -> TensorMeta: + op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs) + tensor_meta = DTensor._op_dispatcher.sharding_propagator._propagate_tensor_meta( + op_info.schema + ) + if isinstance(tensor_meta, TensorMeta): + return tensor_meta + elif isinstance(tensor_meta, tuple): + return tensor_meta[0] + else: + raise RuntimeError(f"Unexpected tensor meta type: {type(tensor_meta)}.") + + +# NOTE: The implementation follows torch._decomp.decomposition._log_softmax, +# with all_reduce manually inserted to perform distributed computation. +def _log_softmax(x, dim, half_to_float, mesh, mesh_dim): + x = x.contiguous() + if half_to_float: + assert x.dtype == torch.half + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + x = x.to(computation_dtype) + if x.numel() == 0: + shifted = x + else: + x_max = torch.amax(x, dim, keepdim=True) + x_max = funcol.all_reduce( + x_max, reduceOp=c10d.ReduceOp.MAX.name, group=(mesh, mesh_dim) + ) + shifted = x - x_max + shifted_sumexp = torch.sum(torch.exp(shifted), dim, keepdim=True) + shifted_sumexp = funcol.all_reduce( + shifted_sumexp, reduceOp=c10d.ReduceOp.SUM.name, group=(mesh, mesh_dim) + ) + shifted_logsumexp = torch.log(shifted_sumexp) + result = shifted - shifted_logsumexp + if not half_to_float: + result = result.to(result_dtype) + return result + + +def _log_softmax_handler( + op_call: torch._ops.OpOverload, + args: Tuple[object, ...], + kwargs: Dict[str, object], +) -> object: + x = cast(DTensor, args[0]) + dim = cast(int, args[1]) + half_to_float = cast(bool, args[2]) + + spec = x._spec + mesh_dim = _find_all_reduce_mesh_dim(spec.placements, dim) + + output_tensor_meta = _propagate_tensor_meta(op_call, args, kwargs) + + res = _log_softmax(x._local_tensor, dim, half_to_float, spec.mesh, mesh_dim) + + return DTensor( + res, + spec.mesh, + spec.placements, + shape=output_tensor_meta.shape, + dtype=output_tensor_meta.dtype, + requires_grad=res.requires_grad, + stride=output_tensor_meta.stride, + ) + + +# NOTE: As explained below at _nll_loss_and_log_softmax_backward, the +# _log_softmax_backward_handler does not actually do any computation. +def _log_softmax_backward_handler( + op_call: torch._ops.OpOverload, + args: Tuple[object, ...], + kwargs: Dict[str, object], +) -> object: + grad_output = cast(DTensor, args[0]) + input_dtype = cast(torch.dtype, args[3]) + return grad_output.to(input_dtype) + + +# NOTE: The implementation follows torch._decomp.decomposition._nll_loss_forward, +# with customized communication inserted to perform distributed computation. +def _nll_loss_forward( + x: Tensor, + target: Tensor, + weight: Optional[Tensor], + local_weight: Optional[Tensor], + reduction: int, + ignore_index: int, + channel_dim_size: int, + mesh: DeviceMesh, + mesh_dim: int, +) -> Tuple[Tensor, Tensor]: + n_dims = x.dim() + channel_dim = 1 + if n_dims < 2: + channel_dim = 0 + + def _weight_view(weight: Tensor) -> Tensor: + if n_dims > 1: + shape = [ + 1, + ] * n_dims + shape[channel_dim] = weight.shape[0] + w = weight.view(shape) + else: + w = weight + return w + + if weight is not None: + w = _weight_view(weight) + assert local_weight is not None + local_w = _weight_view(local_weight) + x = x * local_w + safe_target = torch.where(target != ignore_index, target, 0) + safe_target_ = safe_target.unsqueeze(channel_dim) + + # The following code block is a distributed version of + # result = -torch.gather(self, channel_dim, safe_target_).squeeze(channel_dim) + partial_placement = _MaskPartial(logical_dim_size=channel_dim_size) + safe_target_partial_ = partial_placement._partition_value( + safe_target_, mesh, mesh_dim + ) + result_partial = torch.gather(x, channel_dim, safe_target_partial_) + # an all_reduce happens here + result_reduced = partial_placement._reduce_value(result_partial, mesh, mesh_dim) + result = -result_reduced.squeeze(channel_dim) + + result = torch.where(target != ignore_index, result, 0) + + if reduction == Reduction.NONE.value and n_dims > 1: + total_weight = x.new_full((), 0.0) + return result, total_weight + + if weight is not None: + new_shape = list(x.shape) + new_shape[channel_dim] = -1 + w = w.expand(new_shape) + wsum = torch.gather(w, channel_dim, safe_target_).squeeze(channel_dim) + wsum = torch.where(target != ignore_index, wsum, 0) + total_weight = wsum.sum() + else: + total_weight = (target != ignore_index).sum().to(x) + + # NOTE: this is correct only on 1D DeviceMesh; o/w additional + # all-reduce on result and total_weight is needed + if reduction == Reduction.SUM.value: + result = result.sum() + elif reduction == Reduction.MEAN.value: + result = result.sum() / total_weight + + return result, total_weight + + +def _nll_loss_forward_handler( + op_call: torch._ops.OpOverload, + args: Tuple[object, ...], + kwargs: Dict[str, object], +) -> object: + x = cast(DTensor, args[0]) + target = args[1] + weight = args[2] + reduction = cast(int, args[3]) + ignore_index = cast(int, args[4]) + + channel_dim = 1 if x.dim() >= 2 else 0 + channel_dim_size = x.shape[channel_dim] + spec = x._spec + mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim) + + # Check user input: if target and weight are not DTensors, convert them to DTensors; + # if they are DTensors, check that they have the desired placements. + target_placements = _skip_dim( + replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim + ) + all_replicate_placements = (Replicate(),) * spec.mesh.ndim + target = _cast_to_dtensor(target, target_placements, spec.mesh) + local_weight = None + if weight is not None: + weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh) + # For local computation, both (replicated) weight and (sharded) local_weight + # are needed in _nll_loss_forward(). local_weight is generated here using + # DTensor API, without incurring any communication. + sharded_placements = [ + Shard(0) if i == mesh_dim else Replicate() for i in range(spec.mesh.ndim) + ] + local_weight = weight.redistribute(spec.mesh, sharded_placements)._local_tensor + assert local_weight.shape[0] == x._local_tensor.shape[channel_dim] + + if reduction == Reduction.NONE.value: + output_placements = target_placements + else: + output_placements = all_replicate_placements + + # tensor inputs to _propagate_tensor_meta need to be DTensors + args = list(args) + args[1], args[2] = target, weight + output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs) + + result, total_weight = _nll_loss_forward( + x._local_tensor, + target._local_tensor, + weight._local_tensor if weight is not None else None, + local_weight, + reduction, + ignore_index, + channel_dim_size, + spec.mesh, + mesh_dim, + ) + + return ( + DTensor( + result, + spec.mesh, + output_placements, + shape=output_tensor_meta.shape, + dtype=output_tensor_meta.dtype, + requires_grad=result.requires_grad, + stride=output_tensor_meta.stride, + ), + total_weight, + ) + + +# NOTE: The backward computation of cross_entropy goes through two steps: +# backward for nll_loss and then backward for log_softmax. In loss parallel, +# the two steps are fused into the following function (called by _nll_loss_backward_handler) +# to avoid communication when target contains class indices not class probabilities. +# Also note that the _log_softmax_backward_handler does not perform computation. +# The implementation resembles _nll_loss_backward and _log_softmax_backward_data +# from torch._decomp.decomposition. +def _nll_loss_and_log_softmax_backward( + grad_output: Tensor, + x: Tensor, + target: Tensor, + weight: Optional[Tensor], + reduction: int, + ignore_index: int, + total_weight: Tensor, + channel_dim_size: int, + mesh: DeviceMesh, + mesh_dim: int, +) -> Tensor: + channel_dim = 0 if x.dim() < 2 else 1 + if reduction == Reduction.MEAN.value: + grad_output = grad_output / total_weight + + target = target.unsqueeze(channel_dim) + safe_target = torch.where(target != ignore_index, target, 0) + grad_input = torch.zeros_like(x) + + # The following code block is a distributed version of + # grad_input = torch.scatter(grad_input, channel_dim, safe_target, -1.0) + partial_placement = _MaskPartial(logical_dim_size=channel_dim_size) + safe_target = safe_target.squeeze(channel_dim).flatten() + masked_safe_target = partial_placement._partition_value(safe_target, mesh, mesh_dim) + # only update grad_input to -1 if not masked + assert partial_placement.mask_buffer.data is not None + grad_update = partial_placement.mask_buffer.data.float() - 1.0 + arange_1d = torch.arange( + masked_safe_target.shape[0], device=masked_safe_target.device + ) + # The first two cases with x.dim() <= 2 are for aten.nll_loss_backward.default; + # the last case is for aten.nll_loss2d_backward.default. + if x.dim() == 1: + grad_input[masked_safe_target] = grad_update + elif x.dim() == 2: + grad_input[arange_1d, masked_safe_target] = grad_update + else: + grad_input_t = grad_input.transpose(channel_dim, -1) + intermidate_shape = grad_input_t.shape + grad_input_2d = grad_input_t.reshape(-1, x.shape[channel_dim]) + grad_input_2d[arange_1d, masked_safe_target] = grad_update + grad_input = grad_input_2d.view(intermidate_shape).transpose(channel_dim, -1) + + if grad_input.dim() > grad_output.dim() > 0: + grad_output = grad_output.unsqueeze(channel_dim) + + if weight is not None: + new_shape = [1 for _ in range(x.dim())] + new_shape[channel_dim] = weight.shape[0] + weight = weight.reshape(new_shape) + # In order for fused computation to work, the following line is rewritten. + # grad_output = grad_output * weight + new_shape = list(x.shape) + new_shape[channel_dim] = -1 + w = weight.expand(new_shape) + w_target = torch.gather(w, channel_dim, target) + grad_output = grad_output * w_target + + grad_output = torch.where(target != ignore_index, grad_output, 0) + + # NOTE: Instead of directly returning the grad_input as grad_output for log_softmax, + # here we perform backward computation for log_softmax altogether to avoid the + # otherwise extra all_gather communication. + # return grad_input * grad_output + return (grad_input + torch.exp(x)) * grad_output + + +def _nll_loss_backward_handler( + op_call: torch._ops.OpOverload, + args: Tuple[object, ...], + kwargs: Dict[str, object], +) -> object: + grad_output = cast(DTensor, args[0]) + x = cast(DTensor, args[1]) + target = args[2] + weight = args[3] + reduction = cast(int, args[4]) + ignore_index = cast(int, args[5]) + total_weight = cast(Tensor, args[6]) + + channel_dim = 1 if x.dim() >= 2 else 0 + channel_dim_size = x.shape[channel_dim] + spec = x._spec + mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim) + + # if target and weight are not DTensors, convert them to DTensors + target_placements = _skip_dim( + replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim + ) + all_replicate_placements = (Replicate(),) * spec.mesh.ndim + target = _cast_to_dtensor(target, target_placements, spec.mesh) + if weight is not None: + weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh) + + # tensor inputs to _propagate_tensor_meta need to be DTensors + args = list(args) + args[2], args[3] = target, weight + args[6] = _cast_to_dtensor(total_weight, all_replicate_placements, spec.mesh) + output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs) + + result = _nll_loss_and_log_softmax_backward( + grad_output._local_tensor, + x._local_tensor, + target._local_tensor, + weight._local_tensor if weight is not None else None, + reduction, + ignore_index, + total_weight, + channel_dim_size, + spec.mesh, + mesh_dim, + ) + + return DTensor( + result, + spec.mesh, + # the output sharding is the same as input sharding: Shard(channel_dim) on mesh_dim + spec.placements, + shape=output_tensor_meta.shape, + dtype=output_tensor_meta.dtype, + requires_grad=result.requires_grad, + stride=output_tensor_meta.stride, + ) + + +customized_loss_ops = { + aten._log_softmax.default: _log_softmax_handler, + aten._log_softmax_backward_data.default: _log_softmax_backward_handler, + aten.nll_loss_forward.default: _nll_loss_forward_handler, + aten.nll_loss2d_forward.default: _nll_loss_forward_handler, + aten.nll_loss_backward.default: _nll_loss_backward_handler, + aten.nll_loss2d_backward.default: _nll_loss_backward_handler, +} + + +def _enable_custom_loss_ops(): + DTensor._op_dispatcher._custom_op_handlers.update(customized_loss_ops) + + +def _disable_custom_loss_ops(): + for custom_op in customized_loss_ops: + DTensor._op_dispatcher._custom_op_handlers.pop(custom_op) diff --git a/shared/package-files/0b/0b0fb6fe714319b37c5aa22c56971abb2668a165fc8f72a6c763e70b47c7badf/Ceuta b/shared/package-files/0b/0b0fb6fe714319b37c5aa22c56971abb2668a165fc8f72a6c763e70b47c7badf/Ceuta new file mode 100644 index 0000000000000000000000000000000000000000..b41ec4f81ab104943e84105246f0e5d0157e6e2e Binary files /dev/null and b/shared/package-files/0b/0b0fb6fe714319b37c5aa22c56971abb2668a165fc8f72a6c763e70b47c7badf/Ceuta differ diff --git a/shared/package-files/0b/0b15584e5cfcfc043ba3dd3287971abe94a73412e8cc82fc521b1c4584a15153/test_backend_pdf.py b/shared/package-files/0b/0b15584e5cfcfc043ba3dd3287971abe94a73412e8cc82fc521b1c4584a15153/test_backend_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..c816c4715ae2123eb792ef3278fe0ea87e6705a1 --- /dev/null +++ b/shared/package-files/0b/0b15584e5cfcfc043ba3dd3287971abe94a73412e8cc82fc521b1c4584a15153/test_backend_pdf.py @@ -0,0 +1,448 @@ +import datetime +import decimal +import io +import os +from pathlib import Path + +import numpy as np +import pytest + +import matplotlib as mpl +from matplotlib import ( + pyplot as plt, rcParams, font_manager as fm +) +from matplotlib.cbook import _get_data_path +from matplotlib.ft2font import FT2Font +from matplotlib.font_manager import findfont, FontProperties +from matplotlib.backends._backend_pdf_ps import get_glyphs_subset, font_as_file +from matplotlib.backends.backend_pdf import PdfPages +from matplotlib.patches import Rectangle +from matplotlib.testing.decorators import check_figures_equal, image_comparison +from matplotlib.testing._markers import needs_usetex + + +@image_comparison(['pdf_use14corefonts.pdf']) +def test_use14corefonts(): + rcParams['pdf.use14corefonts'] = True + rcParams['font.family'] = 'sans-serif' + rcParams['font.size'] = 8 + rcParams['font.sans-serif'] = ['Helvetica'] + rcParams['pdf.compression'] = 0 + + text = '''A three-line text positioned just above a blue line +and containing some French characters and the euro symbol: +"Merci pépé pour les 10 €"''' + + fig, ax = plt.subplots() + ax.set_title('Test PDF backend with option use14corefonts=True') + ax.text(0.5, 0.5, text, horizontalalignment='center', + verticalalignment='bottom', + fontsize=14) + ax.axhline(0.5, linewidth=0.5) + + +@pytest.mark.parametrize('fontname, fontfile', [ + ('DejaVu Sans', 'DejaVuSans.ttf'), + ('WenQuanYi Zen Hei', 'wqy-zenhei.ttc'), +]) +@pytest.mark.parametrize('fonttype', [3, 42]) +def test_embed_fonts(fontname, fontfile, fonttype): + if Path(findfont(FontProperties(family=[fontname]))).name != fontfile: + pytest.skip(f'Font {fontname!r} may be missing') + + rcParams['pdf.fonttype'] = fonttype + fig, ax = plt.subplots() + ax.plot([1, 2, 3]) + ax.set_title('Axes Title', font=fontname) + fig.savefig(io.BytesIO(), format='pdf') + + +def test_multipage_pagecount(): + with PdfPages(io.BytesIO()) as pdf: + assert pdf.get_pagecount() == 0 + fig, ax = plt.subplots() + ax.plot([1, 2, 3]) + fig.savefig(pdf, format="pdf") + assert pdf.get_pagecount() == 1 + pdf.savefig() + assert pdf.get_pagecount() == 2 + + +def test_multipage_properfinalize(): + pdfio = io.BytesIO() + with PdfPages(pdfio) as pdf: + for i in range(10): + fig, ax = plt.subplots() + ax.set_title('This is a long title') + fig.savefig(pdf, format="pdf") + s = pdfio.getvalue() + assert s.count(b'startxref') == 1 + assert len(s) < 40000 + + +def test_multipage_keep_empty(tmp_path): + # An empty pdf deletes itself afterwards. + fn = tmp_path / "a.pdf" + with PdfPages(fn) as pdf: + pass + assert not fn.exists() + + # Test pdf files with content, they should never be deleted. + fn = tmp_path / "b.pdf" + with PdfPages(fn) as pdf: + pdf.savefig(plt.figure()) + assert fn.exists() + + +def test_composite_image(): + # Test that figures can be saved with and without combining multiple images + # (on a single set of axes) into a single composite image. + X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) + Z = np.sin(Y ** 2) + fig, ax = plt.subplots() + ax.set_xlim(0, 3) + ax.imshow(Z, extent=[0, 1, 0, 1]) + ax.imshow(Z[::-1], extent=[2, 3, 0, 1]) + plt.rcParams['image.composite_image'] = True + with PdfPages(io.BytesIO()) as pdf: + fig.savefig(pdf, format="pdf") + assert len(pdf._file._images) == 1 + plt.rcParams['image.composite_image'] = False + with PdfPages(io.BytesIO()) as pdf: + fig.savefig(pdf, format="pdf") + assert len(pdf._file._images) == 2 + + +def test_indexed_image(): + # An image with low color count should compress to a palette-indexed format. + pikepdf = pytest.importorskip('pikepdf') + + data = np.zeros((256, 1, 3), dtype=np.uint8) + data[:, 0, 0] = np.arange(256) # Maximum unique colours for an indexed image. + + rcParams['pdf.compression'] = True + fig = plt.figure() + fig.figimage(data, resize=True) + buf = io.BytesIO() + fig.savefig(buf, format='pdf', dpi='figure') + + with pikepdf.Pdf.open(buf) as pdf: + page, = pdf.pages + image, = page.images.values() + pdf_image = pikepdf.PdfImage(image) + assert pdf_image.indexed + pil_image = pdf_image.as_pil_image() + rgb = np.asarray(pil_image.convert('RGB')) + + np.testing.assert_array_equal(data, rgb) + + +def test_savefig_metadata(monkeypatch): + pikepdf = pytest.importorskip('pikepdf') + monkeypatch.setenv('SOURCE_DATE_EPOCH', '0') + + fig, ax = plt.subplots() + ax.plot(range(5)) + + md = { + 'Author': 'me', + 'Title': 'Multipage PDF', + 'Subject': 'Test page', + 'Keywords': 'test,pdf,multipage', + 'ModDate': datetime.datetime( + 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))), + 'Trapped': 'True' + } + buf = io.BytesIO() + fig.savefig(buf, metadata=md, format='pdf') + + with pikepdf.Pdf.open(buf) as pdf: + info = {k: str(v) for k, v in pdf.docinfo.items()} + + assert info == { + '/Author': 'me', + '/CreationDate': 'D:19700101000000Z', + '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', + '/Keywords': 'test,pdf,multipage', + '/ModDate': 'D:19680801000000Z', + '/Producer': f'Matplotlib pdf backend v{mpl.__version__}', + '/Subject': 'Test page', + '/Title': 'Multipage PDF', + '/Trapped': '/True', + } + + +def test_invalid_metadata(): + fig, ax = plt.subplots() + + with pytest.warns(UserWarning, + match="Unknown infodict keyword: 'foobar'."): + fig.savefig(io.BytesIO(), format='pdf', metadata={'foobar': 'invalid'}) + + with pytest.warns(UserWarning, + match='not an instance of datetime.datetime.'): + fig.savefig(io.BytesIO(), format='pdf', + metadata={'ModDate': '1968-08-01'}) + + with pytest.warns(UserWarning, + match='not one of {"True", "False", "Unknown"}'): + fig.savefig(io.BytesIO(), format='pdf', metadata={'Trapped': 'foo'}) + + with pytest.warns(UserWarning, match='not an instance of str.'): + fig.savefig(io.BytesIO(), format='pdf', metadata={'Title': 1234}) + + +def test_multipage_metadata(monkeypatch): + pikepdf = pytest.importorskip('pikepdf') + monkeypatch.setenv('SOURCE_DATE_EPOCH', '0') + + fig, ax = plt.subplots() + ax.plot(range(5)) + + md = { + 'Author': 'me', + 'Title': 'Multipage PDF', + 'Subject': 'Test page', + 'Keywords': 'test,pdf,multipage', + 'ModDate': datetime.datetime( + 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))), + 'Trapped': 'True' + } + buf = io.BytesIO() + with PdfPages(buf, metadata=md) as pdf: + pdf.savefig(fig) + pdf.savefig(fig) + + with pikepdf.Pdf.open(buf) as pdf: + info = {k: str(v) for k, v in pdf.docinfo.items()} + + assert info == { + '/Author': 'me', + '/CreationDate': 'D:19700101000000Z', + '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', + '/Keywords': 'test,pdf,multipage', + '/ModDate': 'D:19680801000000Z', + '/Producer': f'Matplotlib pdf backend v{mpl.__version__}', + '/Subject': 'Test page', + '/Title': 'Multipage PDF', + '/Trapped': '/True', + } + + +def test_text_urls(): + pikepdf = pytest.importorskip('pikepdf') + + test_url = 'https://test_text_urls.matplotlib.org/' + + fig = plt.figure(figsize=(2, 1)) + fig.text(0.1, 0.1, 'test plain 123', url=f'{test_url}plain') + fig.text(0.1, 0.4, 'test mathtext $123$', url=f'{test_url}mathtext') + + with io.BytesIO() as fd: + fig.savefig(fd, format='pdf') + + with pikepdf.Pdf.open(fd) as pdf: + annots = pdf.pages[0].Annots + + # Iteration over Annots must occur within the context manager, + # otherwise it may fail depending on the pdf structure. + for y, fragment in [('0.1', 'plain'), ('0.4', 'mathtext')]: + annot = next( + (a for a in annots if a.A.URI == f'{test_url}{fragment}'), + None) + assert annot is not None + assert getattr(annot, 'QuadPoints', None) is None + # Positions in points (72 per inch.) + assert annot.Rect[1] == decimal.Decimal(y) * 72 + + +def test_text_rotated_urls(): + pikepdf = pytest.importorskip('pikepdf') + + test_url = 'https://test_text_urls.matplotlib.org/' + + fig = plt.figure(figsize=(1, 1)) + fig.text(0.1, 0.1, 'N', rotation=45, url=f'{test_url}') + + with io.BytesIO() as fd: + fig.savefig(fd, format='pdf') + + with pikepdf.Pdf.open(fd) as pdf: + annots = pdf.pages[0].Annots + + # Iteration over Annots must occur within the context manager, + # otherwise it may fail depending on the pdf structure. + annot = next( + (a for a in annots if a.A.URI == f'{test_url}'), + None) + assert annot is not None + assert getattr(annot, 'QuadPoints', None) is not None + # Positions in points (72 per inch) + assert annot.Rect[0] == \ + annot.QuadPoints[6] - decimal.Decimal('0.00001') + + +@needs_usetex +def test_text_urls_tex(): + pikepdf = pytest.importorskip('pikepdf') + + test_url = 'https://test_text_urls.matplotlib.org/' + + fig = plt.figure(figsize=(2, 1)) + fig.text(0.1, 0.7, 'test tex $123$', usetex=True, url=f'{test_url}tex') + + with io.BytesIO() as fd: + fig.savefig(fd, format='pdf') + + with pikepdf.Pdf.open(fd) as pdf: + annots = pdf.pages[0].Annots + + # Iteration over Annots must occur within the context manager, + # otherwise it may fail depending on the pdf structure. + annot = next( + (a for a in annots if a.A.URI == f'{test_url}tex'), + None) + assert annot is not None + # Positions in points (72 per inch.) + assert annot.Rect[1] == decimal.Decimal('0.7') * 72 + + +def test_pdfpages_fspath(): + with PdfPages(Path(os.devnull)) as pdf: + pdf.savefig(plt.figure()) + + +@image_comparison(['hatching_legend.pdf']) +def test_hatching_legend(): + """Test for correct hatching on patches in legend""" + fig = plt.figure(figsize=(1, 2)) + + a = Rectangle([0, 0], 0, 0, facecolor="green", hatch="XXXX") + b = Rectangle([0, 0], 0, 0, facecolor="blue", hatch="XXXX") + + fig.legend([a, b, a, b], ["", "", "", ""]) + + +@image_comparison(['grayscale_alpha.pdf']) +def test_grayscale_alpha(): + """Masking images with NaN did not work for grayscale images""" + x, y = np.ogrid[-2:2:.1, -2:2:.1] + dd = np.exp(-(x**2 + y**2)) + dd[dd < .1] = np.nan + fig, ax = plt.subplots() + ax.imshow(dd, interpolation='none', cmap='gray_r') + ax.set_xticks([]) + ax.set_yticks([]) + + +@mpl.style.context('default') +@check_figures_equal(extensions=["pdf", "eps"]) +def test_pdf_eps_savefig_when_color_is_none(fig_test, fig_ref): + ax_test = fig_test.add_subplot() + ax_test.set_axis_off() + ax_test.plot(np.sin(np.linspace(-5, 5, 100)), "v", c="none") + ax_ref = fig_ref.add_subplot() + ax_ref.set_axis_off() + + +@needs_usetex +def test_failing_latex(): + """Test failing latex subprocess call""" + plt.xlabel("$22_2_2$", usetex=True) # This fails with "Double subscript" + with pytest.raises(RuntimeError): + plt.savefig(io.BytesIO(), format="pdf") + + +def test_empty_rasterized(): + # Check that empty figures that are rasterised save to pdf files fine + fig, ax = plt.subplots() + ax.plot([], [], rasterized=True) + fig.savefig(io.BytesIO(), format="pdf") + + +@image_comparison(['kerning.pdf']) +def test_kerning(): + fig = plt.figure() + s = "AVAVAVAVAVAVAVAV€AAVV" + fig.text(0, .25, s, size=5) + fig.text(0, .75, s, size=20) + + +def test_glyphs_subset(): + fpath = str(_get_data_path("fonts/ttf/DejaVuSerif.ttf")) + chars = "these should be subsetted! 1234567890" + + # non-subsetted FT2Font + nosubfont = FT2Font(fpath) + nosubfont.set_text(chars) + + # subsetted FT2Font + with get_glyphs_subset(fpath, chars) as subset: + subfont = FT2Font(font_as_file(subset)) + subfont.set_text(chars) + + nosubcmap = nosubfont.get_charmap() + subcmap = subfont.get_charmap() + + # all unique chars must be available in subsetted font + assert {*chars} == {chr(key) for key in subcmap} + + # subsetted font's charmap should have less entries + assert len(subcmap) < len(nosubcmap) + + # since both objects are assigned same characters + assert subfont.get_num_glyphs() == nosubfont.get_num_glyphs() + + +@image_comparison(["multi_font_type3.pdf"], tol=4.6) +def test_multi_font_type3(): + fp = fm.FontProperties(family=["WenQuanYi Zen Hei"]) + if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc": + pytest.skip("Font may be missing") + + plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27) + plt.rc('pdf', fonttype=3) + + fig = plt.figure() + fig.text(0.15, 0.475, "There are 几个汉字 in between!") + + +@image_comparison(["multi_font_type42.pdf"], tol=2.2) +def test_multi_font_type42(): + fp = fm.FontProperties(family=["WenQuanYi Zen Hei"]) + if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc": + pytest.skip("Font may be missing") + + plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27) + plt.rc('pdf', fonttype=42) + + fig = plt.figure() + fig.text(0.15, 0.475, "There are 几个汉字 in between!") + + +@pytest.mark.parametrize('family_name, file_name', + [("Noto Sans", "NotoSans-Regular.otf"), + ("FreeMono", "FreeMono.otf")]) +def test_otf_font_smoke(family_name, file_name): + # checks that there's no segfault + fp = fm.FontProperties(family=[family_name]) + if Path(fm.findfont(fp)).name != file_name: + pytest.skip(f"Font {family_name} may be missing") + + plt.rc('font', family=[family_name], size=27) + + fig = plt.figure() + fig.text(0.15, 0.475, "Привет мир!") + fig.savefig(io.BytesIO(), format="pdf") + + +@image_comparison(["truetype-conversion.pdf"]) +# mpltest.ttf does not have "l"/"p" glyphs so we get a warning when trying to +# get the font extents. +def test_truetype_conversion(recwarn): + mpl.rcParams['pdf.fonttype'] = 3 + fig, ax = plt.subplots() + ax.text(0, 0, "ABCDE", + font=Path(__file__).with_name("mpltest.ttf"), fontsize=80) + ax.set_xticks([]) + ax.set_yticks([]) diff --git a/shared/package-files/0b/0b1868143f39318e91501e877ac7dc3c66b83701959176804d301942b2987399/adaptive_max_pool3d_meta.h b/shared/package-files/0b/0b1868143f39318e91501e877ac7dc3c66b83701959176804d301942b2987399/adaptive_max_pool3d_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..d99cae2da8a555fb2d4b5df5e52f46267f2662b5 --- /dev/null +++ b/shared/package-files/0b/0b1868143f39318e91501e877ac7dc3c66b83701959176804d301942b2987399/adaptive_max_pool3d_meta.h @@ -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_adaptive_max_pool3d : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, at::IntArrayRef output_size); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0b19a5eeff022bedd89336e1360f2b80396601e830e924405299e796f118f0f4/cfa_tvpvar_invP.csv b/shared/package-files/0b/0b19a5eeff022bedd89336e1360f2b80396601e830e924405299e796f118f0f4/cfa_tvpvar_invP.csv new file mode 100644 index 0000000000000000000000000000000000000000..3d40212b60ebb132111fe06cfd305a26fbb1892c --- /dev/null +++ b/shared/package-files/0b/0b19a5eeff022bedd89336e1360f2b80396601e830e924405299e796f118f0f4/cfa_tvpvar_invP.csv @@ -0,0 +1,108 @@ +100.368849325795,0.0732138069722595,0.236019793064346,-0.056220923168912,-0.0243776384495469,-0.0785863407490821,-100,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.0732138069722595,100.23174582727,0.102339215686181,-0.0243776384495469,-0.0105702507692978,-0.0340753814393669,0,-100,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.236019793064346,0.102339215686181,100.529911549577,-0.0785863407490821,-0.0340753814393669,-0.109849013574111,0,0,-100,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.056220923168912,-0.0243776384495469,-0.0785863407490821,100.260800648817,0.0263634275429295,0.0849879410792929,0,0,0,-100,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.0243776384495469,-0.0105702507692978,-0.0340753814393669,0.0263634275429295,100.211431297615,0.0368511433719755,0,0,0,0,-100,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.0785863407490821,-0.0340753814393669,-0.109849013574111,0.0849879410792929,0.0368511433719755,100.318797254132,0,0,0,0,0,-100,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 +-100,0,0,0,0,0,200.168849325795,0.643933979025891,1.49871874010728,-0.056220923168912,-0.214407505568165,-0.499020951030981,-100,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,-100,0,0,0,0,0.643933979025891,202.45574548427,5.71560423597509,-0.214407505568165,-0.817677402874498,-1.90309641510777,0,-100,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,-100,0,0,0,1.49871874010728,5.71560423597509,213.302735153766,-0.499020951030981,-1.90309641510777,-4.42934579390835,0,0,-100,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,-100,0,0,-0.056220923168912,-0.214407505568165,-0.499020951030981,200.060800648817,0.23187302368953,0.53967092473445,0,0,0,-100,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,-100,0,-0.214407505568165,-0.817677402874498,-1.90309641510777,0.23187302368953,200.884284956838,2.05812160807706,0,0,0,0,-100,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,-100,-0.499020951030981,-1.90309641510777,-4.42934579390835,0.53967092473445,2.05812160807707,204.790157879401,0,0,0,0,0,-100,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,-100,0,0,0,0,0,200.168849325795,0.849138399902697,-0.316393465376947,-0.056220923168912,-0.282733404565315,0.105347964075695,-100,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,-100,0,0,0,0,0.849138399902697,204.270292574712,-1.59113363150371,-0.282733404565315,-1.42185815442634,0.52979187939795,0,-100,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,-100,0,0,0,-0.316393465376947,-1.59113363150371,200.592864818747,0.105347964075695,0.52979187939795,-0.197403260376036,0,0,-100,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,-100,0,0,-0.056220923168912,-0.282733404565315,0.105347964075695,200.060800648817,0.305764713044303,-0.11392955160332,0,0,0,-100,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,-100,0,-0.282733404565315,-1.42185815442634,0.52979187939795,0.305764713044303,201.537681941921,-0.572948436094306,0,0,0,0,-100,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,-100,0.105347964075695,0.52979187939795,-0.197403260376036,-0.11392955160332,-0.572948436094306,200.213483621985,0,0,0,0,0,-100,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,-100,0,0,0,0,0,200.168849325795,-0.267992686966019,0.110284287601537,-0.056220923168912,0.0892321967693272,-0.0367208126581201,-100,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,-100,0,0,0,0,-0.267992686966019,200.425350115726,-0.175039979728882,0.0892321967693272,-0.141626719937655,0.0582821945273721,0,-100,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,-100,0,0,0,0.110284287601537,-0.175039979728882,200.072032411349,-0.0367208126581201,0.0582821945273721,-0.0239842750041923,0,0,-100,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,-100,0,0,-0.056220923168912,0.0892321967693272,-0.0367208126581201,200.060800648817,-0.0965010027075988,0.0397120699707412,0,0,0,-100,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,-100,0,0.0892321967693272,-0.141626719937655,0.0582821945273721,-0.0965010027075988,200.153163555073,-0.0630298302128547,0,0,0,0,-100,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,-100,-0.0367208126581201,0.0582821945273721,-0.0239842750041923,0.0397120699707412,-0.0630298302128547,200.025938020926,0,0,0,0,0,-100,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,-100,0,0,0,0,0,200.168849325795,0.0907081013589849,-0.871692070147434,-0.056220923168912,-0.0302026269472918,0.290242988367518,-100,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,-100,0,0,0,0,0.0907081013589849,200.04872959731,-0.468284562465768,-0.0302026269472918,-0.0162252525056666,0.15592238987955,0,-100,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,-100,0,0,0,-0.871692070147434,-0.468284562465768,204.500148647786,0.290242988367518,0.15592238987955,-1.49839219187865,0,0,-100,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,-100,0,0,-0.056220923168912,-0.0302026269472918,0.290242988367518,200.060800648817,0.0326629164173964,-0.313886023435245,0,0,0,-100,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,-100,0,-0.0302026269472918,-0.0162252525056666,0.15592238987955,0.0326629164173964,200.017546952699,-0.168623742468636,0,0,0,0,-100,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,-100,0.290242988367518,0.15592238987955,-1.49839219187865,-0.313886023435245,-0.168623742468636,201.620450400199,0,0,0,0,0,-100,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,-100,0,0,0,0,0,200.168849325795,-0.0188874774905546,0.400010216177632,-0.056220923168912,0.00628886977101397,-0.133189419173328,-100,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,-100,0,0,0,0,-0.0188874774905546,200.002112752327,-0.0447451236091994,0.00628886977101397,-0.000703472671161025,0.0148985620449793,0,-100,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,-100,0,0,0,0.400010216177632,-0.0447451236091994,200.947638803369,-0.133189419173328,0.0148985620449793,-0.315530595725573,0,0,-100,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,-100,0,0,-0.056220923168912,0.00628886977101397,-0.133189419173328,200.060800648817,-0.00680115766251051,0.14403895640376,0,0,0,-100,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,-100,0,0.00628886977101397,-0.000703472671161025,0.0148985620449793,-0.00680115766251051,200.00076077717,-0.0161121907595587,0,0,0,0,-100,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,-100,-0.133189419173328,0.0148985620449793,-0.315530595725573,0.14403895640376,-0.0161121907595587,200.341233545456,0,0,0,0,0,-100,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,-100,0,0,0,0,0,200.168849325795,0.997551074948089,1.25181743832697,-0.056220923168912,-0.332149637420922,-0.416811448255046,-100,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,-100,0,0,0,0,0.997551074948089,205.893468288619,7.39565778755137,-0.332149637420922,-1.9623189271971,-2.46249551959256,0,-100,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,-100,0,0,0,1.25181743832697,7.39565778755137,209.280741226044,-0.416811448255046,-2.46249551959256,-3.09016240936677,0,0,-100,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,-100,0,0,-0.056220923168912,-0.332149637420922,-0.416811448255046,200.060800648817,0.359206365197346,0.450764680831489,0,0,0,-100,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,-100,0,-0.332149637420922,-1.9623189271971,-2.46249551959256,0.359206365197346,202.122168353606,2.66308905761844,0,0,0,0,-100,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,-100,-0.416811448255046,-2.46249551959256,-3.09016240936677,0.450764680831489,2.66308905761844,203.341885348896,0,0,0,0,0,-100,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,-100,0,0,0,0,0,200.168849325795,0.326799794574497,1.08277258554704,-0.056220923168912,-0.10881290793336,-0.360525421435168,-100,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,-100,0,0,0,0,0.326799794574497,200.63250537265,2.09565455390897,-0.10881290793336,-0.210602179144955,-0.697779710454015,0,-100,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,-100,0,0,0,1.08277258554704,2.09565455390897,206.943447754317,-0.360525421435168,-0.697779710454015,-2.31192538604343,0,0,-100,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,-100,0,0,-0.056220923168912,-0.10881290793336,-0.360525421435168,200.060800648817,0.117676747892285,0.389893625055664,0,0,0,-100,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,-100,0,-0.10881290793336,-0.210602179144955,-0.697779710454015,0.117676747892285,200.227757717457,0.754620463977826,0,0,0,0,-100,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,-100,-0.360525421435168,-0.697779710454015,-2.31192538604343,0.389893625055664,0.754620463977826,202.500253563353,0,0,0,0,0,-100 +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,-100,0,0,0,0,0,100.168849325795,1.33884426203398,1.36111576095929,-0.056220923168912,-0.445788338427493,-0.453203969043948 +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,-100,0,0,0,0,1.33884426203398,110.615997129612,10.7925928512863,-0.445788338427493,-3.5347559498602,-3.59355615207263 +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,-100,0,0,0,1.36111576095929,10.7925928512863,110.972126219658,-0.453203969043948,-3.59355615207263,-3.6533344879467 +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,-100,0,0,-0.056220923168912,-0.445788338427493,-0.453203969043948,100.060800648817,0.482102012626847,0.490121716456923 +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,-100,0,-0.445788338427493,-3.5347559498602,-3.59355615207263,0.482102012626847,103.822695236003,3.88628527052326 +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,-100,-0.453203969043948,-3.59355615207263,-3.6533344879467,0.490121716456923,3.88628527052325,103.950933116939 +380.176256034162,0.317222605150652,1.02263243395277,-0.0800019999906426,-0.0346892174849764,-0.111827840552949,-379.244661472674,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.317222605150652,163.60708102858,0.443417900961571,-0.0346892174849764,-0.0150413965883446,-0.0484890413023456,0,-163.269531918026,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.02263243395277,0.443417900961571,78.9963170737937,-0.111827840552949,-0.0484890413023456,-0.156314416192077,0,0,-77.3668681002465,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.0800019999906426,-0.0346892174849764,-0.111827840552949,293.341903927158,0.0203493388443068,0.0656002869083059,0,0,0,-293.094973269044,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.0346892174849764,-0.0150413965883446,-0.0484890413023456,0.0203493388443068,134.363276306781,0.0284445716345247,0,0,0,0,-134.154452744359,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.111827840552949,-0.0484890413023456,-0.156314416192077,0.0656002869083059,0.0284445716345247,346.815692256624,0,0,0,0,0,-346.523995318729,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 +-379.244661472674,0,0,0,0,0,759.220917506837,2.79005317192447,6.49368586044257,-0.0800019999906426,-0.305100455339784,-0.710103496517942,-379.244661472674,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,-163.269531918026,0,0,0,0,2.79005317192447,337.179378994122,24.7647122957711,-0.305100455339784,-1.16354950950515,-2.70809354955298,0,-163.269531918026,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,-77.3668681002465,0,0,0,6.49368586044257,24.7647122957711,212.372158181553,-0.710103496517942,-2.70809354955298,-6.30292962458421,0,0,-77.3668681002465,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,-293.094973269044,0,0,-0.0800019999906426,-0.305100455339784,-0.710103496517942,586.236877196202,0.178977590081137,0.416559891309997,0,0,0,-293.094973269044,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,-134.154452744359,0,-0.305100455339784,-1.16354950950515,-2.70809354955298,0.178977590081137,268.991465227671,1.58861794117442,0,0,0,0,-134.154452744359,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,-346.523995318729,-0.710103496517942,-2.70809354955298,-6.30292962458421,0.416559891309997,1.58861794117442,696.745406144107,0,0,0,0,0,-346.523995318729,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,-379.244661472674,0,0,0,0,0,759.220917506837,3.67916799426442,-1.37087748186004,-0.0800019999906426,-0.402327755476919,0.149909452672565,-379.244661472674,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,-163.269531918026,0,0,0,0,3.67916799426442,345.041493791904,-6.89410340210382,-0.402327755476919,-2.02329470320777,0.753890323061687,0,-163.269531918026,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,-77.3668681002465,0,0,0,-1.37087748186004,-6.89410340210382,157.302515643642,0.149909452672565,0.753890323061687,-0.280903527452022,0,0,-77.3668681002465,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,-293.094973269044,0,0,-0.0800019999906426,-0.402327755476919,0.149909452672565,586.236877196202,0.236012928980453,-0.0879396674116321,0,0,0,-293.094973269044,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,-134.154452744359,0,-0.402327755476919,-2.02329470320777,0.753890323061687,0.236012928980453,269.495807716053,-0.442246056489175,0,0,0,0,-134.154452744359,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,-346.523995318729,0.149909452672565,0.753890323061687,-0.280903527452022,-0.0879396674116321,-0.442246056489175,693.21277386052,0,0,0,0,0,-346.523995318729,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,-379.244661472674,0,0,0,0,0,759.220917506837,-1.16116538445945,0.477842506310303,-0.0800019999906426,0.126976822910873,-0.0522534723434738,-379.244661472674,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,-163.269531918026,0,0,0,0,-1.16116538445945,328.382031404488,-0.758417580937325,0.126976822910873,-0.201533881133284,0.0829351754332583,0,-163.269531918026,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,-77.3668681002465,0,0,0,0.477842506310303,-0.758417580937325,155.045840025284,-0.0522534723434738,0.0829351754332583,-0.0341294639167714,0,0,-77.3668681002465,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,-293.094973269044,0,0,-0.0800019999906426,0.126976822910873,-0.0522534723434738,586.236877196202,-0.0744869611401857,0.0306528567549694,0,0,0,-293.094973269044,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,-134.154452744359,0,0.126976822910873,-0.201533881133284,0.0829351754332583,-0.0744869611401857,268.427129004067,-0.0486513132714601,0,0,0,0,-134.154452744359,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,-346.523995318729,-0.0522534723434738,0.0829351754332583,-0.0341294639167714,0.0306528567549694,-0.0486513132714601,693.068011614469,0,0,0,0,0,-346.523995318729,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,-379.244661472674,0,0,0,0,0,759.220917506837,0.393022319304735,-3.77688909806462,-0.0800019999906426,-0.0429781374008232,0.413013843314157,-379.244661472674,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,-163.269531918026,0,0,0,0,0.393022319304735,326.750200648165,-2.02899500791578,-0.0429781374008232,-0.0230884264725892,0.221876524442815,0,-163.269531918026,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,-77.3668681002465,0,0,0,-3.77688909806462,-2.02899500791578,174.23209227091,0.413013843314157,0.221876524442815,-2.13220212981029,0,0,-77.3668681002465,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,-293.094973269044,0,0,-0.0800019999906426,-0.0429781374008232,0.413013843314157,586.236877196202,0.0252117731178368,-0.242281586450577,0,0,0,-293.094973269044,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,-134.154452744359,0,-0.0429781374008232,-0.0230884264725892,0.221876524442815,0.0252117731178368,268.322449588231,-0.130156887495066,0,0,0,0,-134.154452744359,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,-346.523995318729,0.413013843314157,0.221876524442815,-2.13220212981029,-0.242281586450577,-0.130156887495066,694.298779982673,0,0,0,0,0,-346.523995318729,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,-379.244661472674,0,0,0,0,0,759.220917506837,-0.0818361325828638,1.73317422096112,-0.0800019999906426,0.00894901988446926,-0.18952765822512,-379.244661472674,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,-163.269531918026,0,0,0,0,-0.0818361325828638,326.54821802192,-0.193872785285927,0.00894901988446926,-0.00100103693535153,0.0212005547650293,0,-163.269531918026,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,-77.3668681002465,0,0,0,1.73317422096112,-0.193872785285927,158.839689194585,-0.18952765822512,0.0212005547650293,-0.448997940507729,0,0,-77.3668681002465,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,-293.094973269044,0,0,-0.0800019999906426,0.00894901988446926,-0.18952765822512,586.236877196202,-0.00524966116725961,0.111180442143478,0,0,0,-293.094973269044,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,-134.154452744359,0,0.00894901988446926,-0.00100103693535153,0.0212005547650293,-0.00524966116725961,268.309492715564,-0.0124366389293073,0,0,0,0,-134.154452744359,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,-346.523995318729,-0.18952765822512,0.0212005547650293,-0.448997940507729,0.111180442143478,-0.0124366389293073,693.311381163224,0,0,0,0,0,-346.523995318729,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,-379.244661472674,0,0,0,0,0,759.220917506837,4.32221412671202,5.42390575468313,-0.0800019999906426,-0.472646726379872,-0.593119920482538,-379.244661472674,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,-163.269531918026,0,0,0,0,4.32221412671202,352.074429926177,32.0440901407937,-0.472646726379872,-2.79236679062697,-3.50411475712546,0,-163.269531918026,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,-77.3668681002465,0,0,0,5.42390575468313,32.0440901407937,194.945562783562,-0.593119920482538,-3.50411475712546,-4.39728056941525,0,0,-77.3668681002465,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,-293.094973269044,0,0,-0.0800019999906426,-0.472646726379872,-0.593119920482538,586.236877196202,0.27726334250468,0.34793515427192,0,0,0,-293.094973269044,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,-134.154452744359,0,-0.472646726379872,-2.79236679062697,-3.50411475712546,0.27726334250468,269.946959677304,2.05557875651026,0,0,0,0,-134.154452744359,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,-346.523995318729,-0.593119920482538,-3.50411475712546,-4.39728056941525,0.34793515427192,2.05557875651026,695.627517037535,0,0,0,0,0,-346.523995318729,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,-379.244661472674,0,0,0,0,0,759.220917506837,1.41596628402208,4.69146400900972,-0.0800019999906426,-0.154840044751883,-0.513025278429288,-379.244661472674,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,-163.269531918026,0,0,0,0,1.41596628402208,329.279598857811,9.08010421229316,-0.154840044751883,-0.299685501132088,-0.992935890104364,0,-163.269531918026,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,-77.3668681002465,0,0,0,4.69146400900972,9.08010421229316,184.818479453721,-0.513025278429288,-0.992935890104364,-3.28985445786647,0,0,-77.3668681002465,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,-293.094973269044,0,0,-0.0800019999906426,-0.154840044751883,-0.513025278429288,586.236877196202,0.090832044242229,0.300950150604399,0,0,0,-293.094973269044,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,-134.154452744359,0,-0.154840044751883,-0.299685501132088,-0.992935890104364,0.090832044242229,268.484706566153,0.582474623048441,0,0,0,0,-134.154452744359,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,-346.523995318729,-0.513025278429288,-0.992935890104364,-3.28985445786647,0.300950150604399,0.582474623048441,694.977880325531,0,0,0,0,0,-346.523995318729 +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,-379.244661472674,0,0,0,0,0,379.976256034162,5.80097774254989,5.89747624743401,-0.0800019999906426,-0.634353842599754,-0.644906235678143 +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,-163.269531918026,0,0,0,0,5.80097774254989,209.266788514768,46.762414935103,-0.634353842599754,-5.02993422249619,-5.11360651942229 +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,-77.3668681002465,0,0,0,5.89747624743401,46.762414935103,124.907169682442,-0.644906235678143,-5.11360651942229,-5.19867069404762 +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,-293.094973269044,0,0,-0.0800019999906426,-0.634353842599754,-0.644906235678143,293.141903927158,0.37212373832996,0.378313967973031 +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,-134.154452744359,0,-0.634353842599754,-5.02993422249619,-5.11360651942229,0.37212373832996,137.105105520037,2.99973649809907 +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,-346.523995318729,-0.644906235678143,-5.11360651942229,-5.19867069404762,0.378313967973031,2.99973649809907,349.573632040542 diff --git a/shared/package-files/0b/0b1abd84144515cbc4b416d91a8fffc0258361fea0cb008111fc7ec3747ef868/rmsprop.py b/shared/package-files/0b/0b1abd84144515cbc4b416d91a8fffc0258361fea0cb008111fc7ec3747ef868/rmsprop.py new file mode 100644 index 0000000000000000000000000000000000000000..62d28ae51a047256dcadecdc491144ec603e266a --- /dev/null +++ b/shared/package-files/0b/0b1abd84144515cbc4b416d91a8fffc0258361fea0cb008111fc7ec3747ef868/rmsprop.py @@ -0,0 +1,374 @@ +import torch +from torch import Tensor +from .optimizer import (Optimizer, _default_to_fused_or_foreach, _use_grad_for_differentiable, + _differentiable_doc, _foreach_doc, _maximize_doc, _view_as_real) +from typing import List, Optional + +__all__ = ["RMSprop", "rmsprop"] + + +class RMSprop(Optimizer): + def __init__( + self, + params, + lr=1e-2, + alpha=0.99, + eps=1e-8, + weight_decay=0, + momentum=0, + centered=False, + foreach: Optional[bool] = None, + maximize: bool = False, + differentiable: bool = False, + ): + if not 0.0 <= lr: + raise ValueError(f"Invalid learning rate: {lr}") + if not 0.0 <= eps: + raise ValueError(f"Invalid epsilon value: {eps}") + if not 0.0 <= momentum: + raise ValueError(f"Invalid momentum value: {momentum}") + if not 0.0 <= weight_decay: + raise ValueError(f"Invalid weight_decay value: {weight_decay}") + if not 0.0 <= alpha: + raise ValueError(f"Invalid alpha value: {alpha}") + + defaults = dict( + lr=lr, + momentum=momentum, + alpha=alpha, + eps=eps, + centered=centered, + weight_decay=weight_decay, + foreach=foreach, + maximize=maximize, + differentiable=differentiable, + ) + super().__init__(params, defaults) + + def __setstate__(self, state): + super().__setstate__(state) + for group in self.param_groups: + group.setdefault("momentum", 0) + group.setdefault("centered", False) + group.setdefault("foreach", None) + group.setdefault("maximize", False) + group.setdefault("differentiable", False) + + def _init_group(self, group, params_with_grad, grads, square_avgs, momentum_buffer_list, grad_avgs): + has_complex = False + for p in group["params"]: + if p.grad is None: + continue + has_complex |= torch.is_complex(p) + params_with_grad.append(p) + + if p.grad.is_sparse: + raise RuntimeError("RMSprop does not support sparse gradients") + grads.append(p.grad) + + state = self.state[p] + + # State initialization + if len(state) == 0: + state["step"] = 0 + state["square_avg"] = torch.zeros_like( + p, memory_format=torch.preserve_format + ) + if group["momentum"] > 0: + state["momentum_buffer"] = torch.zeros_like( + p, memory_format=torch.preserve_format + ) + if group["centered"]: + state["grad_avg"] = torch.zeros_like( + p, memory_format=torch.preserve_format + ) + square_avgs.append(state["square_avg"]) + + if group["momentum"] > 0: + momentum_buffer_list.append(state["momentum_buffer"]) + if group["centered"]: + grad_avgs.append(state["grad_avg"]) + + if group["differentiable"] and isinstance(state["step"], Tensor): + raise RuntimeError("`step` can't be a tensor") + + state["step"] += 1 + return has_complex + + @_use_grad_for_differentiable + def step(self, closure=None): + """Performs a single optimization step. + + Args: + closure (Callable, optional): A closure that reevaluates the model + and returns the loss. + """ + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + params_with_grad = [] + grads = [] + square_avgs = [] + grad_avgs = [] + momentum_buffer_list = [] + + has_complex = self._init_group(group, params_with_grad, grads, square_avgs, momentum_buffer_list, grad_avgs) + + rmsprop( + params_with_grad, + grads, + square_avgs, + grad_avgs, + momentum_buffer_list, + lr=group["lr"], + alpha=group["alpha"], + eps=group["eps"], + weight_decay=group["weight_decay"], + momentum=group["momentum"], + centered=group["centered"], + foreach=group["foreach"], + maximize=group["maximize"], + differentiable=group["differentiable"], + has_complex=has_complex, + ) + + return loss + + +RMSprop.__doc__ = r"""Implements RMSprop algorithm. + + .. math:: + \begin{aligned} + &\rule{110mm}{0.4pt} \\ + &\textbf{input} : \alpha \text{ (alpha)},\: \gamma \text{ (lr)}, + \: \theta_0 \text{ (params)}, \: f(\theta) \text{ (objective)} \\ + &\hspace{13mm} \lambda \text{ (weight decay)},\: \mu \text{ (momentum)},\: centered\\ + &\textbf{initialize} : v_0 \leftarrow 0 \text{ (square average)}, \: + \textbf{b}_0 \leftarrow 0 \text{ (buffer)}, \: g^{ave}_0 \leftarrow 0 \\[-1.ex] + &\rule{110mm}{0.4pt} \\ + &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\ + &\hspace{5mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\ + &\hspace{5mm}if \: \lambda \neq 0 \\ + &\hspace{10mm} g_t \leftarrow g_t + \lambda \theta_{t-1} \\ + &\hspace{5mm}v_t \leftarrow \alpha v_{t-1} + (1 - \alpha) g^2_t + \hspace{8mm} \\ + &\hspace{5mm} \tilde{v_t} \leftarrow v_t \\ + &\hspace{5mm}if \: centered \\ + &\hspace{10mm} g^{ave}_t \leftarrow g^{ave}_{t-1} \alpha + (1-\alpha) g_t \\ + &\hspace{10mm} \tilde{v_t} \leftarrow \tilde{v_t} - \big(g^{ave}_{t} \big)^2 \\ + &\hspace{5mm}if \: \mu > 0 \\ + &\hspace{10mm} \textbf{b}_t\leftarrow \mu \textbf{b}_{t-1} + + g_t/ \big(\sqrt{\tilde{v_t}} + \epsilon \big) \\ + &\hspace{10mm} \theta_t \leftarrow \theta_{t-1} - \gamma \textbf{b}_t \\ + &\hspace{5mm} else \\ + &\hspace{10mm}\theta_t \leftarrow \theta_{t-1} - + \gamma g_t/ \big(\sqrt{\tilde{v_t}} + \epsilon \big) \hspace{3mm} \\ + &\rule{110mm}{0.4pt} \\[-1.ex] + &\bf{return} \: \theta_t \\[-1.ex] + &\rule{110mm}{0.4pt} \\[-1.ex] + \end{aligned} + + For further details regarding the algorithm we refer to + `lecture notes `_ by G. Hinton. + and centered version `Generating Sequences + With Recurrent Neural Networks `_. + The implementation here takes the square root of the gradient average before + adding epsilon (note that TensorFlow interchanges these two operations). The effective + learning rate is thus :math:`\gamma/(\sqrt{v} + \epsilon)` where :math:`\gamma` + is the scheduled learning rate and :math:`v` is the weighted moving average + of the squared gradient. + """ + fr""" + Args: + params (iterable): iterable of parameters to optimize or dicts defining + parameter groups + lr (float, optional): learning rate (default: 1e-2) + momentum (float, optional): momentum factor (default: 0) + alpha (float, optional): smoothing constant (default: 0.99) + eps (float, optional): term added to the denominator to improve + numerical stability (default: 1e-8) + centered (bool, optional) : if ``True``, compute the centered RMSProp, + the gradient is normalized by an estimation of its variance + weight_decay (float, optional): weight decay (L2 penalty) (default: 0) + {_foreach_doc} + {_maximize_doc} + {_differentiable_doc} + + """ + + +def rmsprop( + params: List[Tensor], + grads: List[Tensor], + square_avgs: List[Tensor], + grad_avgs: List[Tensor], + momentum_buffer_list: List[Tensor], + # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627 + # setting this as kwarg for now as functional API is compiled by torch/distributed/optim + foreach: Optional[bool] = None, + maximize: bool = False, + differentiable: bool = False, + has_complex: bool = False, + *, + lr: float, + alpha: float, + eps: float, + weight_decay: float, + momentum: float, + centered: bool, +): + r"""Functional API that performs rmsprop algorithm computation. + See :class:`~torch.optim.RMSProp` for details. + """ + + if foreach is None: + _, foreach = _default_to_fused_or_foreach(params, differentiable, use_fused=False) + + if foreach and torch.jit.is_scripting(): + raise RuntimeError("torch.jit.script not supported with foreach optimizers") + + if foreach and not torch.jit.is_scripting(): + func = _multi_tensor_rmsprop + else: + func = _single_tensor_rmsprop + + func( + params, + grads, + square_avgs, + grad_avgs, + momentum_buffer_list, + lr=lr, + alpha=alpha, + eps=eps, + weight_decay=weight_decay, + momentum=momentum, + centered=centered, + maximize=maximize, + differentiable=differentiable, + has_complex=has_complex, + ) + + +def _single_tensor_rmsprop( + params: List[Tensor], + grads: List[Tensor], + square_avgs: List[Tensor], + grad_avgs: List[Tensor], + momentum_buffer_list: List[Tensor], + *, + lr: float, + alpha: float, + eps: float, + weight_decay: float, + momentum: float, + centered: bool, + maximize: bool, + differentiable: bool, + has_complex: bool, +): + + for i, param in enumerate(params): + grad = grads[i] + grad = grad if not maximize else -grad + square_avg = square_avgs[i] + + if weight_decay != 0: + grad = grad.add(param, alpha=weight_decay) + + is_complex_param = torch.is_complex(param) + if is_complex_param: + param = torch.view_as_real(param) + grad = torch.view_as_real(grad) + square_avg = torch.view_as_real(square_avg) + + square_avg.mul_(alpha).addcmul_(grad, grad, value=1 - alpha) + + if centered: + grad_avg = grad_avgs[i] + if is_complex_param: + grad_avg = torch.view_as_real(grad_avg) + grad_avg.lerp_(grad, 1 - alpha) + avg = square_avg.addcmul(grad_avg, grad_avg, value=-1).sqrt_() + else: + avg = square_avg.sqrt() + + if differentiable: + avg = avg.add(eps) + else: + avg = avg.add_(eps) + + if momentum > 0: + buf = momentum_buffer_list[i] + if is_complex_param: + buf = torch.view_as_real(buf) + buf.mul_(momentum).addcdiv_(grad, avg) + param.add_(buf, alpha=-lr) + else: + param.addcdiv_(grad, avg, value=-lr) + + +def _multi_tensor_rmsprop( + params: List[Tensor], + grads: List[Tensor], + square_avgs: List[Tensor], + grad_avgs: List[Tensor], + momentum_buffer_list: List[Tensor], + *, + lr: float, + alpha: float, + eps: float, + weight_decay: float, + momentum: float, + centered: bool, + maximize: bool, + differentiable: bool, + has_complex: bool, +): + + if len(params) == 0: + return + + assert not differentiable, "_foreach ops don't support autograd" + + grouped_tensors = Optimizer._group_tensors_by_device_and_dtype([params, grads, square_avgs, grad_avgs, momentum_buffer_list]) + for (((grouped_params, grouped_grads, grouped_square_avgs, grouped_grad_avgs, + grouped_momentum_buffer_list)), _) in grouped_tensors.values(): + if has_complex: + state_and_grads = [grouped_grads, grouped_square_avgs] + if momentum > 0: + state_and_grads.append(grouped_momentum_buffer_list) + if centered: + state_and_grads.append(grouped_grad_avgs) + _view_as_real(grouped_params, *state_and_grads) + + if maximize: + grouped_grads = torch._foreach_neg(grouped_grads) + + if weight_decay != 0: + # Re-use the intermediate memory (grouped_grads) already allocated for maximize + if maximize: + torch._foreach_add_(grouped_grads, grouped_params, alpha=weight_decay) + else: + grouped_grads = torch._foreach_add(grouped_grads, grouped_params, alpha=weight_decay) + + torch._foreach_mul_(grouped_square_avgs, alpha) + torch._foreach_addcmul_(grouped_square_avgs, grouped_grads, grouped_grads, value=1 - alpha) + + if centered: + torch._foreach_lerp_(grouped_grad_avgs, grouped_grads, 1 - alpha) + avg = torch._foreach_addcmul(grouped_square_avgs, grouped_grad_avgs, grouped_grad_avgs, value=-1) + torch._foreach_sqrt_(avg) + torch._foreach_add_(avg, eps) + else: + avg = torch._foreach_sqrt(grouped_square_avgs) + torch._foreach_add_(avg, eps) + + if momentum > 0: + torch._foreach_mul_(grouped_momentum_buffer_list, momentum) + torch._foreach_addcdiv_(grouped_momentum_buffer_list, grouped_grads, avg) + torch._foreach_add_(grouped_params, grouped_momentum_buffer_list, alpha=-lr) + else: + torch._foreach_addcdiv_(grouped_params, grouped_grads, avg, value=-lr) diff --git a/shared/package-files/0b/0b20c7f08b612c2ab140c77b869fc78dc966cfcc978c855dade2a3c7631543e4/random.h b/shared/package-files/0b/0b20c7f08b612c2ab140c77b869fc78dc966cfcc978c855dade2a3c7631543e4/random.h new file mode 100644 index 0000000000000000000000000000000000000000..a1415e5ac6587903ac0aaf0f579d6f75610f229a --- /dev/null +++ b/shared/package-files/0b/0b20c7f08b612c2ab140c77b869fc78dc966cfcc978c855dade2a3c7631543e4/random.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch { +namespace serialize { +class OutputArchive; +class InputArchive; +} // namespace serialize +} // namespace torch + +namespace torch { +namespace data { +namespace samplers { + +/// A `Sampler` that returns random indices. +class TORCH_API RandomSampler : public Sampler<> { + public: + /// Constructs a `RandomSampler` with a size and dtype for the stored indices. + /// + /// The constructor will eagerly allocate all required indices, which is the + /// sequence `0 ... size - 1`. `index_dtype` is the data type of the stored + /// indices. You can change it to influence memory usage. + explicit RandomSampler(int64_t size, Dtype index_dtype = torch::kInt64); + + ~RandomSampler() override; + + /// Resets the `RandomSampler` to a new set of indices. + void reset(optional new_size = nullopt) override; + + /// Returns the next batch of indices. + optional> next(size_t batch_size) override; + + /// Serializes the `RandomSampler` to the `archive`. + void save(serialize::OutputArchive& archive) const override; + + /// Deserializes the `RandomSampler` from the `archive`. + void load(serialize::InputArchive& archive) override; + + /// Returns the current index of the `RandomSampler`. + size_t index() const noexcept; + + private: + at::Tensor indices_; + int64_t index_ = 0; +}; +} // namespace samplers +} // namespace data +} // namespace torch diff --git a/shared/package-files/0b/0b22ada953eddf5e7e05ef6c3b430a88cb5674c51d51ec9b0c01c0bde87a2611/putty-noapp b/shared/package-files/0b/0b22ada953eddf5e7e05ef6c3b430a88cb5674c51d51ec9b0c01c0bde87a2611/putty-noapp new file mode 100644 index 0000000000000000000000000000000000000000..c67bf882bf52d45a9f5cdf6e52fa2e21ee377030 Binary files /dev/null and b/shared/package-files/0b/0b22ada953eddf5e7e05ef6c3b430a88cb5674c51d51ec9b0c01c0bde87a2611/putty-noapp differ diff --git a/shared/package-files/0b/0b2587f5b6d51a880af840b29a7872c6880c0c431e382d8137d0365c3620f9e1/test_special_matrices.py b/shared/package-files/0b/0b2587f5b6d51a880af840b29a7872c6880c0c431e382d8137d0365c3620f9e1/test_special_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..d32e7ed4b4016924c60b3ed6287888a0372e8791 --- /dev/null +++ b/shared/package-files/0b/0b2587f5b6d51a880af840b29a7872c6880c0c431e382d8137d0365c3620f9e1/test_special_matrices.py @@ -0,0 +1,640 @@ +import pytest +import numpy as np +from numpy import arange, array, eye, copy, sqrt +from numpy.testing import (assert_equal, assert_array_equal, + assert_array_almost_equal, assert_allclose) +from pytest import raises as assert_raises + +from scipy.fft import fft +from scipy.special import comb +from scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft, + companion, kron, block_diag, + helmert, hilbert, invhilbert, pascal, invpascal, + fiedler, fiedler_companion, eigvals, + convolution_matrix) +from numpy.linalg import cond + + +class TestToeplitz: + + def test_basic(self): + y = toeplitz([1, 2, 3]) + assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]]) + y = toeplitz([1, 2, 3], [1, 4, 5]) + assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]]) + + def test_complex_01(self): + data = (1.0 + arange(3.0)) * (1.0 + 1.0j) + x = copy(data) + t = toeplitz(x) + # Calling toeplitz should not change x. + assert_array_equal(x, data) + # According to the docstring, x should be the first column of t. + col0 = t[:, 0] + assert_array_equal(col0, data) + assert_array_equal(t[0, 1:], data[1:].conj()) + + def test_scalar_00(self): + """Scalar arguments still produce a 2D array.""" + t = toeplitz(10) + assert_array_equal(t, [[10]]) + t = toeplitz(10, 20) + assert_array_equal(t, [[10]]) + + def test_scalar_01(self): + c = array([1, 2, 3]) + t = toeplitz(c, 1) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_02(self): + c = array([1, 2, 3]) + t = toeplitz(c, array(1)) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_03(self): + c = array([1, 2, 3]) + t = toeplitz(c, array([1])) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_04(self): + r = array([10, 2, 3]) + t = toeplitz(1, r) + assert_array_equal(t, [[1, 2, 3]]) + + +class TestHankel: + def test_basic(self): + y = hankel([1, 2, 3]) + assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]]) + y = hankel([1, 2, 3], [3, 4, 5]) + assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]]) + + +class TestCirculant: + def test_basic(self): + y = circulant([1, 2, 3]) + assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]]) + + +class TestHadamard: + + def test_basic(self): + + y = hadamard(1) + assert_array_equal(y, [[1]]) + + y = hadamard(2, dtype=float) + assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]]) + + y = hadamard(4) + assert_array_equal(y, [[1, 1, 1, 1], + [1, -1, 1, -1], + [1, 1, -1, -1], + [1, -1, -1, 1]]) + + assert_raises(ValueError, hadamard, 0) + assert_raises(ValueError, hadamard, 5) + + +class TestLeslie: + + def test_bad_shapes(self): + assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5]) + assert_raises(ValueError, leslie, [1, 2], [1, 2]) + assert_raises(ValueError, leslie, [1], []) + + def test_basic(self): + a = leslie([1, 2, 3], [0.25, 0.5]) + expected = array([[1.0, 2.0, 3.0], + [0.25, 0.0, 0.0], + [0.0, 0.5, 0.0]]) + assert_array_equal(a, expected) + + +class TestCompanion: + + def test_bad_shapes(self): + assert_raises(ValueError, companion, [0, 4, 5]) + assert_raises(ValueError, companion, [1]) + assert_raises(ValueError, companion, []) + + def test_basic(self): + c = companion([1, 2, 3]) + expected = array([ + [-2.0, -3.0], + [1.0, 0.0]]) + assert_array_equal(c, expected) + + c = companion([2.0, 5.0, -10.0]) + expected = array([ + [-2.5, 5.0], + [1.0, 0.0]]) + assert_array_equal(c, expected) + + c = companion([(1.0, 2.0, 3.0), + (4.0, 5.0, 6.0)]) + expected = array([ + ([-2.00, -3.00], + [+1.00, +0.00]), + ([-1.25, -1.50], + [+1.00, +0.00]) + ]) + assert_array_equal(c, expected) + + +class TestBlockDiag: + def test_basic(self): + x = block_diag(eye(2), [[1, 2], [3, 4], [5, 6]], [[1, 2, 3]]) + assert_array_equal(x, [[1, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 2, 0, 0, 0], + [0, 0, 3, 4, 0, 0, 0], + [0, 0, 5, 6, 0, 0, 0], + [0, 0, 0, 0, 1, 2, 3]]) + + def test_dtype(self): + x = block_diag([[1.5]]) + assert_equal(x.dtype, float) + + x = block_diag([[True]]) + assert_equal(x.dtype, bool) + + def test_mixed_dtypes(self): + actual = block_diag([[1]], [[1j]]) + desired = np.array([[1, 0], [0, 1j]]) + assert_array_equal(actual, desired) + + def test_scalar_and_1d_args(self): + a = block_diag(1) + assert_equal(a.shape, (1, 1)) + assert_array_equal(a, [[1]]) + + a = block_diag([2, 3], 4) + assert_array_equal(a, [[2, 3, 0], [0, 0, 4]]) + + def test_bad_arg(self): + assert_raises(ValueError, block_diag, [[[1]]]) + + def test_no_args(self): + a = block_diag() + assert_equal(a.ndim, 2) + assert_equal(a.nbytes, 0) + + def test_empty_matrix_arg(self): + # regression test for gh-4596: check the shape of the result + # for empty matrix inputs. Empty matrices are no longer ignored + # (gh-4908) it is viewed as a shape (1, 0) matrix. + a = block_diag([[1, 0], [0, 1]], + [], + [[2, 3], [4, 5], [6, 7]]) + assert_array_equal(a, [[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0], + [0, 0, 2, 3], + [0, 0, 4, 5], + [0, 0, 6, 7]]) + + def test_zerosized_matrix_arg(self): + # test for gh-4908: check the shape of the result for + # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0). + # note that [[]] takes shape (1,0) + a = block_diag([[1, 0], [0, 1]], + [[]], + [[2, 3], [4, 5], [6, 7]], + np.zeros([0, 2], dtype='int32')) + assert_array_equal(a, [[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 2, 3, 0, 0], + [0, 0, 4, 5, 0, 0], + [0, 0, 6, 7, 0, 0]]) + + +class TestKron: + @pytest.mark.thread_unsafe + def test_dep(self): + with pytest.deprecated_call(match="`kron`"): + kron(np.array([[1, 2],[3, 4]]),np.array([[1, 1, 1]])) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_basic(self): + + a = kron(array([[1, 2], [3, 4]]), array([[1, 1, 1]])) + assert_array_equal(a, array([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]])) + + m1 = array([[1, 2], [3, 4]]) + m2 = array([[10], [11]]) + a = kron(m1, m2) + expected = array([[10, 20], + [11, 22], + [30, 40], + [33, 44]]) + assert_array_equal(a, expected) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_empty(self): + m1 = np.empty((0, 2)) + m2 = np.empty((1, 3)) + a = kron(m1, m2) + assert_allclose(a, np.empty((0, 6))) + + +class TestHelmert: + + def test_orthogonality(self): + for n in range(1, 7): + H = helmert(n, full=True) + Id = np.eye(n) + assert_allclose(H.dot(H.T), Id, atol=1e-12) + assert_allclose(H.T.dot(H), Id, atol=1e-12) + + def test_subspace(self): + for n in range(2, 7): + H_full = helmert(n, full=True) + H_partial = helmert(n) + for U in H_full[1:, :].T, H_partial.T: + C = np.eye(n) - np.full((n, n), 1 / n) + assert_allclose(U.dot(U.T), C) + assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12) + + +class TestHilbert: + + def test_basic(self): + h3 = array([[1.0, 1/2., 1/3.], + [1/2., 1/3., 1/4.], + [1/3., 1/4., 1/5.]]) + assert_array_almost_equal(hilbert(3), h3) + + assert_array_equal(hilbert(1), [[1.0]]) + + h0 = hilbert(0) + assert_equal(h0.shape, (0, 0)) + + +class TestInvHilbert: + + def test_basic(self): + invh1 = array([[1]]) + assert_array_equal(invhilbert(1, exact=True), invh1) + assert_array_equal(invhilbert(1), invh1) + + invh2 = array([[4, -6], + [-6, 12]]) + assert_array_equal(invhilbert(2, exact=True), invh2) + assert_array_almost_equal(invhilbert(2), invh2) + + invh3 = array([[9, -36, 30], + [-36, 192, -180], + [30, -180, 180]]) + assert_array_equal(invhilbert(3, exact=True), invh3) + assert_array_almost_equal(invhilbert(3), invh3) + + invh4 = array([[16, -120, 240, -140], + [-120, 1200, -2700, 1680], + [240, -2700, 6480, -4200], + [-140, 1680, -4200, 2800]]) + assert_array_equal(invhilbert(4, exact=True), invh4) + assert_array_almost_equal(invhilbert(4), invh4) + + invh5 = array([[25, -300, 1050, -1400, 630], + [-300, 4800, -18900, 26880, -12600], + [1050, -18900, 79380, -117600, 56700], + [-1400, 26880, -117600, 179200, -88200], + [630, -12600, 56700, -88200, 44100]]) + assert_array_equal(invhilbert(5, exact=True), invh5) + assert_array_almost_equal(invhilbert(5), invh5) + + invh17 = array([ + [289, -41616, 1976760, -46124400, 629598060, -5540462928, + 33374693352, -143034400080, 446982500250, -1033026222800, + 1774926873720, -2258997839280, 2099709530100, -1384423866000, + 613101997800, -163493866080, 19835652870], + [-41616, 7990272, -426980160, 10627061760, -151103534400, + 1367702848512, -8410422724704, 36616806420480, -115857864064800, + 270465047424000, -468580694662080, 600545887119360, + -561522320049600, 372133135180800, -165537539406000, + 44316454993920, -5395297580640], + [1976760, -426980160, 24337869120, -630981792000, 9228108708000, + -85267724461920, 532660105897920, -2348052711713280, + 7504429831470000, -17664748409880000, 30818191841236800, + -39732544853164800, 37341234283298400, -24857330514030000, + 11100752642520000, -2982128117299200, 364182586693200], + [-46124400, 10627061760, -630981792000, 16826181120000, + -251209625940000, 2358021022156800, -14914482965141760, + 66409571644416000, -214015221119700000, 507295338950400000, + -890303319857952000, 1153715376477081600, -1089119333262870000, + 727848632044800000, -326170262829600000, 87894302404608000, + -10763618673376800], + [629598060, -151103534400, 9228108708000, + -251209625940000, 3810012660090000, -36210360321495360, + 231343968720664800, -1038687206500944000, 3370739732635275000, + -8037460526495400000, 14178080368737885600, -18454939322943942000, + 17489975175339030000, -11728977435138600000, 5272370630081100000, + -1424711708039692800, 174908803442373000], + [-5540462928, 1367702848512, -85267724461920, 2358021022156800, + -36210360321495360, 347619459086355456, -2239409617216035264, + 10124803292907663360, -33052510749726468000, + 79217210949138662400, -140362995650505067440, + 183420385176741672960, -174433352415381259200, + 117339159519533952000, -52892422160973595200, + 14328529177999196160, -1763080738699119840], + [33374693352, -8410422724704, 532660105897920, + -14914482965141760, 231343968720664800, -2239409617216035264, + 14527452132196331328, -66072377044391477760, + 216799987176909536400, -521925895055522958000, + 928414062734059661760, -1217424500995626443520, + 1161358898976091015200, -783401860847777371200, + 354015418167362952000, -96120549902411274240, + 11851820521255194480], + [-143034400080, 36616806420480, -2348052711713280, + 66409571644416000, -1038687206500944000, 10124803292907663360, + -66072377044391477760, 302045152202932469760, + -995510145200094810000, 2405996923185123840000, + -4294704507885446054400, 5649058909023744614400, + -5403874060541811254400, 3654352703663101440000, + -1655137020003255360000, 450325202737117593600, + -55630994283442749600], + [446982500250, -115857864064800, 7504429831470000, + -214015221119700000, 3370739732635275000, -33052510749726468000, + 216799987176909536400, -995510145200094810000, + 3293967392206196062500, -7988661659013106500000, + 14303908928401362270000, -18866974090684772052000, + 18093328327706957325000, -12263364009096700500000, + 5565847995255512250000, -1517208935002984080000, + 187754605706619279900], + [-1033026222800, 270465047424000, -17664748409880000, + 507295338950400000, -8037460526495400000, 79217210949138662400, + -521925895055522958000, 2405996923185123840000, + -7988661659013106500000, 19434404971634224000000, + -34894474126569249192000, 46141453390504792320000, + -44349976506971935800000, 30121928988527376000000, + -13697025107665828500000, 3740200989399948902400, + -463591619028689580000], + [1774926873720, -468580694662080, + 30818191841236800, -890303319857952000, 14178080368737885600, + -140362995650505067440, 928414062734059661760, + -4294704507885446054400, 14303908928401362270000, + -34894474126569249192000, 62810053427824648545600, + -83243376594051600326400, 80177044485212743068000, + -54558343880470209780000, 24851882355348879230400, + -6797096028813368678400, 843736746632215035600], + [-2258997839280, 600545887119360, -39732544853164800, + 1153715376477081600, -18454939322943942000, 183420385176741672960, + -1217424500995626443520, 5649058909023744614400, + -18866974090684772052000, 46141453390504792320000, + -83243376594051600326400, 110552468520163390156800, + -106681852579497947388000, 72720410752415168870400, + -33177973900974346080000, 9087761081682520473600, + -1129631016152221783200], + [2099709530100, -561522320049600, 37341234283298400, + -1089119333262870000, 17489975175339030000, + -174433352415381259200, 1161358898976091015200, + -5403874060541811254400, 18093328327706957325000, + -44349976506971935800000, 80177044485212743068000, + -106681852579497947388000, 103125790826848015808400, + -70409051543137015800000, 32171029219823375700000, + -8824053728865840192000, 1098252376814660067000], + [-1384423866000, 372133135180800, + -24857330514030000, 727848632044800000, -11728977435138600000, + 117339159519533952000, -783401860847777371200, + 3654352703663101440000, -12263364009096700500000, + 30121928988527376000000, -54558343880470209780000, + 72720410752415168870400, -70409051543137015800000, + 48142941226076592000000, -22027500987368499000000, + 6049545098753157120000, -753830033789944188000], + [613101997800, -165537539406000, + 11100752642520000, -326170262829600000, 5272370630081100000, + -52892422160973595200, 354015418167362952000, + -1655137020003255360000, 5565847995255512250000, + -13697025107665828500000, 24851882355348879230400, + -33177973900974346080000, 32171029219823375700000, + -22027500987368499000000, 10091416708498869000000, + -2774765838662800128000, 346146444087219270000], + [-163493866080, 44316454993920, -2982128117299200, + 87894302404608000, -1424711708039692800, + 14328529177999196160, -96120549902411274240, + 450325202737117593600, -1517208935002984080000, + 3740200989399948902400, -6797096028813368678400, + 9087761081682520473600, -8824053728865840192000, + 6049545098753157120000, -2774765838662800128000, + 763806510427609497600, -95382575704033754400], + [19835652870, -5395297580640, 364182586693200, -10763618673376800, + 174908803442373000, -1763080738699119840, 11851820521255194480, + -55630994283442749600, 187754605706619279900, + -463591619028689580000, 843736746632215035600, + -1129631016152221783200, 1098252376814660067000, + -753830033789944188000, 346146444087219270000, + -95382575704033754400, 11922821963004219300] + ]) + assert_array_equal(invhilbert(17, exact=True), invh17) + assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12) + + def test_inverse(self): + for n in range(1, 10): + a = hilbert(n) + b = invhilbert(n) + # The Hilbert matrix is increasingly badly conditioned, + # so take that into account in the test + c = cond(a) + assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c) + + +class TestPascal: + + cases = [ + (1, array([[1]]), array([[1]])), + (2, array([[1, 1], + [1, 2]]), + array([[1, 0], + [1, 1]])), + (3, array([[1, 1, 1], + [1, 2, 3], + [1, 3, 6]]), + array([[1, 0, 0], + [1, 1, 0], + [1, 2, 1]])), + (4, array([[1, 1, 1, 1], + [1, 2, 3, 4], + [1, 3, 6, 10], + [1, 4, 10, 20]]), + array([[1, 0, 0, 0], + [1, 1, 0, 0], + [1, 2, 1, 0], + [1, 3, 3, 1]])), + ] + + def check_case(self, n, sym, low): + assert_array_equal(pascal(n), sym) + assert_array_equal(pascal(n, kind='lower'), low) + assert_array_equal(pascal(n, kind='upper'), low.T) + assert_array_almost_equal(pascal(n, exact=False), sym) + assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low) + assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T) + + def test_cases(self): + for n, sym, low in self.cases: + self.check_case(n, sym, low) + + def test_big(self): + p = pascal(50) + assert p[-1, -1] == comb(98, 49, exact=True) + + def test_threshold(self): + # Regression test. An early version of `pascal` returned an + # array of type np.uint64 for n=35, but that data type is too small + # to hold p[-1, -1]. The second assert_equal below would fail + # because p[-1, -1] overflowed. + p = pascal(34) + assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34") + p = pascal(35) + assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35") + + +def test_invpascal(): + + def check_invpascal(n, kind, exact): + ip = invpascal(n, kind=kind, exact=exact) + p = pascal(n, kind=kind, exact=exact) + # Matrix-multiply ip and p, and check that we get the identity matrix. + # We can't use the simple expression e = ip.dot(p), because when + # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is + # np.int64. The product of those dtypes is np.float64, which loses + # precision when n is greater than 18. Instead we'll cast both to + # object arrays, and then multiply. + e = ip.astype(object).dot(p.astype(object)) + assert_array_equal(e, eye(n), err_msg="n=%d kind=%r exact=%r" % + (n, kind, exact)) + + kinds = ['symmetric', 'lower', 'upper'] + + ns = [1, 2, 5, 18] + for n in ns: + for kind in kinds: + for exact in [True, False]: + check_invpascal(n, kind, exact) + + ns = [19, 34, 35, 50] + for n in ns: + for kind in kinds: + check_invpascal(n, kind, True) + + +def test_dft(): + m = dft(2) + expected = array([[1.0, 1.0], [1.0, -1.0]]) + assert_array_almost_equal(m, expected) + m = dft(2, scale='n') + assert_array_almost_equal(m, expected/2.0) + m = dft(2, scale='sqrtn') + assert_array_almost_equal(m, expected/sqrt(2.0)) + + x = array([0, 1, 2, 3, 4, 5, 0, 1]) + m = dft(8) + mx = m.dot(x) + fx = fft(x) + assert_array_almost_equal(mx, fx) + + +def test_fiedler(): + f = fiedler([]) + assert_equal(f.size, 0) + f = fiedler([123.]) + assert_array_equal(f, np.array([[0.]])) + f = fiedler(np.arange(1, 7)) + des = np.array([[0, 1, 2, 3, 4, 5], + [1, 0, 1, 2, 3, 4], + [2, 1, 0, 1, 2, 3], + [3, 2, 1, 0, 1, 2], + [4, 3, 2, 1, 0, 1], + [5, 4, 3, 2, 1, 0]]) + assert_array_equal(f, des) + + +def test_fiedler_companion(): + fc = fiedler_companion([]) + assert_equal(fc.size, 0) + fc = fiedler_companion([1.]) + assert_equal(fc.size, 0) + fc = fiedler_companion([1., 2.]) + assert_array_equal(fc, np.array([[-2.]])) + fc = fiedler_companion([1e-12, 2., 3.]) + assert_array_almost_equal(fc, companion([1e-12, 2., 3.])) + with assert_raises(ValueError): + fiedler_companion([0, 1, 2]) + fc = fiedler_companion([1., -16., 86., -176., 105.]) + assert_array_almost_equal(eigvals(fc), + np.array([7., 5., 3., 1.])) + + +class TestConvolutionMatrix: + """ + Test convolution_matrix vs. numpy.convolve for various parameters. + """ + + def create_vector(self, n, cpx): + """Make a complex or real test vector of length n.""" + x = np.linspace(-2.5, 2.2, n) + if cpx: + x = x + 1j*np.linspace(-1.5, 3.1, n) + return x + + def test_bad_n(self): + # n must be a positive integer + with pytest.raises(ValueError, match='n must be a positive integer'): + convolution_matrix([1, 2, 3], 0) + + def test_empty_first_arg(self): + # first arg must have at least one value + with pytest.raises(ValueError, match=r'len\(a\)'): + convolution_matrix([], 4) + + def test_bad_mode(self): + # mode must be in ('full', 'valid', 'same') + with pytest.raises(ValueError, match='mode.*must be one of'): + convolution_matrix((1, 1), 4, mode='invalid argument') + + @pytest.mark.parametrize('cpx', [False, True]) + @pytest.mark.parametrize('na', [1, 2, 9]) + @pytest.mark.parametrize('nv', [1, 2, 9]) + @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same']) + def test_against_numpy_convolve(self, cpx, na, nv, mode): + a = self.create_vector(na, cpx) + v = self.create_vector(nv, cpx) + if mode is None: + y1 = np.convolve(v, a) + A = convolution_matrix(a, nv) + else: + y1 = np.convolve(v, a, mode) + A = convolution_matrix(a, nv, mode) + y2 = A @ v + assert_array_almost_equal(y1, y2) + + +@pytest.mark.thread_unsafe +@pytest.mark.fail_slow(5) # `leslie` has an import in the function +@pytest.mark.parametrize('f, args', [(circulant, ()), + (companion, ()), + (convolution_matrix, (5, 'same')), + (fiedler, ()), + (fiedler_companion, ()), + (leslie, (np.arange(9),)), + (toeplitz, (np.arange(9),)), + ]) +def test_batch(f, args): + rng = np.random.default_rng(283592436523456) + batch_shape = (2, 3) + m = 10 + A = rng.random(batch_shape + (m,)) + + if f in {toeplitz}: + message = "Beginning in SciPy 1.17, multidimensional input will be..." + with pytest.warns(FutureWarning, match=message): + f(A, *args) + return + + res = f(A, *args) + ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)]) + ref = ref.reshape(A.shape[:-1] + ref.shape[-2:]) + assert_allclose(res, ref) diff --git a/shared/package-files/0b/0b2be73597d781db5a92cbb33bba9c80fa58f0aa55be96e3153400ea99b9affe/linalg_det.h b/shared/package-files/0b/0b2be73597d781db5a92cbb33bba9c80fa58f0aa55be96e3153400ea99b9affe/linalg_det.h new file mode 100644 index 0000000000000000000000000000000000000000..4fd277012a00807f630a5e1944b63f1d21c75f99 --- /dev/null +++ b/shared/package-files/0b/0b2be73597d781db5a92cbb33bba9c80fa58f0aa55be96e3153400ea99b9affe/linalg_det.h @@ -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_det(Tensor A) -> Tensor +inline at::Tensor linalg_det(const at::Tensor & A) { + return at::_ops::linalg_det::call(A); +} + +// aten::linalg_det.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_det_out(at::Tensor & out, const at::Tensor & A) { + return at::_ops::linalg_det_out::call(A, out); +} +// aten::linalg_det.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_det_outf(const at::Tensor & A, at::Tensor & out) { + return at::_ops::linalg_det_out::call(A, out); +} + +} diff --git a/shared/package-files/0b/0b2ea3ab5b3d29f4fe78517bb2fd46079cf0b8b588d756d5acf0a83a7045b1ff/T_S_I__1.py b/shared/package-files/0b/0b2ea3ab5b3d29f4fe78517bb2fd46079cf0b8b588d756d5acf0a83a7045b1ff/T_S_I__1.py new file mode 100644 index 0000000000000000000000000000000000000000..6cdce17faaf11652e1b21cb17460f232e417bd16 --- /dev/null +++ b/shared/package-files/0b/0b2ea3ab5b3d29f4fe78517bb2fd46079cf0b8b588d756d5acf0a83a7045b1ff/T_S_I__1.py @@ -0,0 +1,163 @@ +"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its hinting source data. + +TSI1 contains the text of the glyph programs in the form of low-level assembly +code, as well as the 'extra' programs 'fpgm', 'ppgm' (i.e. 'prep'), and 'cvt'. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from . import DefaultTable +from fontTools.misc.loggingTools import LogMixin +from fontTools.misc.textTools import strjoin, tobytes, tostr + + +class table_T_S_I__1(LogMixin, DefaultTable.DefaultTable): + extras = {0xFFFA: "ppgm", 0xFFFB: "cvt", 0xFFFC: "reserved", 0xFFFD: "fpgm"} + + indextable = "TSI0" + + def decompile(self, data, ttFont): + totalLength = len(data) + indextable = ttFont[self.indextable] + for indices, isExtra in zip( + (indextable.indices, indextable.extra_indices), (False, True) + ): + programs = {} + for i, (glyphID, textLength, textOffset) in enumerate(indices): + if isExtra: + name = self.extras[glyphID] + else: + name = ttFont.getGlyphName(glyphID) + if textOffset > totalLength: + self.log.warning("textOffset > totalLength; %r skipped" % name) + continue + if textLength < 0x8000: + # If the length stored in the record is less than 32768, then use + # that as the length of the record. + pass + elif textLength == 0x8000: + # If the length is 32768, compute the actual length as follows: + isLast = i == (len(indices) - 1) + if isLast: + if isExtra: + # For the last "extra" record (the very last record of the + # table), the length is the difference between the total + # length of the TSI1 table and the textOffset of the final + # record. + nextTextOffset = totalLength + else: + # For the last "normal" record (the last record just prior + # to the record containing the "magic number"), the length + # is the difference between the textOffset of the record + # following the "magic number" (0xFFFE) record (i.e. the + # first "extra" record), and the textOffset of the last + # "normal" record. + nextTextOffset = indextable.extra_indices[0][2] + else: + # For all other records with a length of 0x8000, the length is + # the difference between the textOffset of the record in + # question and the textOffset of the next record. + nextTextOffset = indices[i + 1][2] + assert nextTextOffset >= textOffset, "entries not sorted by offset" + if nextTextOffset > totalLength: + self.log.warning( + "nextTextOffset > totalLength; %r truncated" % name + ) + nextTextOffset = totalLength + textLength = nextTextOffset - textOffset + else: + from fontTools import ttLib + + raise ttLib.TTLibError( + "%r textLength (%d) must not be > 32768" % (name, textLength) + ) + text = data[textOffset : textOffset + textLength] + assert len(text) == textLength + text = tostr(text, encoding="utf-8") + if text: + programs[name] = text + if isExtra: + self.extraPrograms = programs + else: + self.glyphPrograms = programs + + def compile(self, ttFont): + if not hasattr(self, "glyphPrograms"): + self.glyphPrograms = {} + self.extraPrograms = {} + data = b"" + indextable = ttFont[self.indextable] + glyphNames = ttFont.getGlyphOrder() + + indices = [] + for i, name in enumerate(glyphNames): + if len(data) % 2: + data = ( + data + b"\015" + ) # align on 2-byte boundaries, fill with return chars. Yum. + if name in self.glyphPrograms: + text = tobytes(self.glyphPrograms[name], encoding="utf-8") + else: + text = b"" + textLength = len(text) + if textLength >= 0x8000: + textLength = 0x8000 + indices.append((i, textLength, len(data))) + data = data + text + + extra_indices = [] + for code, name in sorted(self.extras.items()): + if len(data) % 2: + data = ( + data + b"\015" + ) # align on 2-byte boundaries, fill with return chars. + if name in self.extraPrograms: + text = tobytes(self.extraPrograms[name], encoding="utf-8") + else: + text = b"" + textLength = len(text) + if textLength >= 0x8000: + textLength = 0x8000 + extra_indices.append((code, textLength, len(data))) + data = data + text + indextable.set(indices, extra_indices) + return data + + def toXML(self, writer, ttFont): + names = sorted(self.glyphPrograms.keys()) + writer.newline() + for name in names: + text = self.glyphPrograms[name] + if not text: + continue + writer.begintag("glyphProgram", name=name) + writer.newline() + writer.write_noindent(text.replace("\r", "\n")) + writer.newline() + writer.endtag("glyphProgram") + writer.newline() + writer.newline() + extra_names = sorted(self.extraPrograms.keys()) + for name in extra_names: + text = self.extraPrograms[name] + if not text: + continue + writer.begintag("extraProgram", name=name) + writer.newline() + writer.write_noindent(text.replace("\r", "\n")) + writer.newline() + writer.endtag("extraProgram") + writer.newline() + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "glyphPrograms"): + self.glyphPrograms = {} + self.extraPrograms = {} + lines = strjoin(content).replace("\r", "\n").split("\n") + text = "\r".join(lines[1:-1]) + if name == "glyphProgram": + self.glyphPrograms[attrs["name"]] = text + elif name == "extraProgram": + self.extraPrograms[attrs["name"]] = text diff --git a/shared/package-files/0b/0b31409125f86466ac3478ebda1ba854dc6e41877437844205f1910bb6b43dec/dim.py b/shared/package-files/0b/0b31409125f86466ac3478ebda1ba854dc6e41877437844205f1910bb6b43dec/dim.py new file mode 100644 index 0000000000000000000000000000000000000000..f8e34af96225f38ce59a4b9b400e399b30c42641 --- /dev/null +++ b/shared/package-files/0b/0b31409125f86466ac3478ebda1ba854dc6e41877437844205f1910bb6b43dec/dim.py @@ -0,0 +1,121 @@ +# 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 dis +import inspect + +from dataclasses import dataclass +from typing import Union + +from . import DimList + +_vmap_levels = [] + + +@dataclass +class LevelInfo: + level: int + alive: bool = True + + +class Dim: + def __init__(self, name: str, size: Union[None, int] = None): + self.name = name + self._size = None + self._vmap_level = None + if size is not None: + self.size = size + + def __del__(self): + if self._vmap_level is not None: + _vmap_active_levels[self._vmap_stack].alive = False # noqa: F821 + while ( + not _vmap_levels[-1].alive + and current_level() == _vmap_levels[-1].level # noqa: F821 + ): + _vmap_decrement_nesting() # noqa: F821 + _vmap_levels.pop() + + @property + def size(self): + assert self.is_bound + return self._size + + @size.setter + def size(self, size: int): + from . import DimensionBindError + + if self._size is None: + self._size = size + self._vmap_level = _vmap_increment_nesting(size, "same") # noqa: F821 + self._vmap_stack = len(_vmap_levels) + _vmap_levels.append(LevelInfo(self._vmap_level)) + + elif self._size != size: + raise DimensionBindError( + f"Dim '{self}' previously bound to a dimension of size {self._size} cannot bind to a dimension of size {size}" + ) + + @property + def is_bound(self): + return self._size is not None + + def __repr__(self): + return self.name + + +def extract_name(inst): + assert inst.opname == "STORE_FAST" or inst.opname == "STORE_NAME" + return inst.argval + + +_cache = {} + + +def dims(lists=0): + frame = inspect.currentframe() + assert frame is not None + calling_frame = frame.f_back + assert calling_frame is not None + code, lasti = calling_frame.f_code, calling_frame.f_lasti + key = (code, lasti) + if key not in _cache: + first = lasti // 2 + 1 + instructions = list(dis.get_instructions(calling_frame.f_code)) + unpack = instructions[first] + + if unpack.opname == "STORE_FAST" or unpack.opname == "STORE_NAME": + # just a single dim, not a list + name = unpack.argval + ctor = Dim if lists == 0 else DimList + _cache[key] = lambda: ctor(name=name) + else: + assert unpack.opname == "UNPACK_SEQUENCE" + ndims = unpack.argval + names = tuple( + extract_name(instructions[first + 1 + i]) for i in range(ndims) + ) + first_list = len(names) - lists + _cache[key] = lambda: tuple( + Dim(n) if i < first_list else DimList(name=n) + for i, n in enumerate(names) + ) + return _cache[key]() + + +def _dim_set(positional, arg): + def convert(a): + if isinstance(a, Dim): + return a + else: + assert isinstance(a, int) + return positional[a] + + if arg is None: + return positional + elif not isinstance(arg, (Dim, int)): + return tuple(convert(a) for a in arg) + else: + return (convert(arg),) diff --git a/shared/package-files/0b/0b356362197f2f5339b6100b8747b6e466476d3017bd3c6c7313533537220ceb/xterm-pcolor b/shared/package-files/0b/0b356362197f2f5339b6100b8747b6e466476d3017bd3c6c7313533537220ceb/xterm-pcolor new file mode 100644 index 0000000000000000000000000000000000000000..af19a92e24902110f5e241cf01abf561bfdf5e6b Binary files /dev/null and b/shared/package-files/0b/0b356362197f2f5339b6100b8747b6e466476d3017bd3c6c7313533537220ceb/xterm-pcolor differ diff --git a/shared/package-files/0b/0b39bec5e8d3d63c133395fdd9a5305bc9f1cab14032a4f66d93a3e41f74604e/__init__.py b/shared/package-files/0b/0b39bec5e8d3d63c133395fdd9a5305bc9f1cab14032a4f66d93a3e41f74604e/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..556e77461ed3ace1f987b29c2c5aca4eb9311e1f --- /dev/null +++ b/shared/package-files/0b/0b39bec5e8d3d63c133395fdd9a5305bc9f1cab14032a4f66d93a3e41f74604e/__init__.py @@ -0,0 +1,16 @@ +# 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 hypothesis.internal.conjecture.shrinking.floats import Float +from hypothesis.internal.conjecture.shrinking.integer import Integer +from hypothesis.internal.conjecture.shrinking.lexical import Lexical +from hypothesis.internal.conjecture.shrinking.ordering import Ordering + +__all__ = ["Lexical", "Integer", "Ordering", "Float"] diff --git a/shared/package-files/0b/0b3bb2c034d6437c538bfff835ddfaaa0731ea60ecdada5852c573b5db950bdb/test_downcast.py b/shared/package-files/0b/0b3bb2c034d6437c538bfff835ddfaaa0731ea60ecdada5852c573b5db950bdb/test_downcast.py new file mode 100644 index 0000000000000000000000000000000000000000..9430ba2c478ae40a4a21bcc6dc034783cdf9543c --- /dev/null +++ b/shared/package-files/0b/0b3bb2c034d6437c538bfff835ddfaaa0731ea60ecdada5852c573b5db950bdb/test_downcast.py @@ -0,0 +1,97 @@ +import decimal + +import numpy as np +import pytest + +from pandas.core.dtypes.cast import maybe_downcast_to_dtype + +from pandas import ( + Series, + Timedelta, +) +import pandas._testing as tm + + +@pytest.mark.parametrize( + "arr,dtype,expected", + [ + ( + np.array([8.5, 8.6, 8.7, 8.8, 8.9999999999995]), + "infer", + np.array([8.5, 8.6, 8.7, 8.8, 8.9999999999995]), + ), + ( + np.array([8.0, 8.0, 8.0, 8.0, 8.9999999999995]), + "infer", + np.array([8, 8, 8, 8, 9], dtype=np.int64), + ), + ( + np.array([8.0, 8.0, 8.0, 8.0, 9.0000000000005]), + "infer", + np.array([8, 8, 8, 8, 9], dtype=np.int64), + ), + ( + # This is a judgement call, but we do _not_ downcast Decimal + # objects + np.array([decimal.Decimal(0.0)]), + "int64", + np.array([decimal.Decimal(0.0)]), + ), + ( + # GH#45837 + np.array([Timedelta(days=1), Timedelta(days=2)], dtype=object), + "infer", + np.array([1, 2], dtype="m8[D]").astype("m8[ns]"), + ), + # TODO: similar for dt64, dt64tz, Period, Interval? + ], +) +def test_downcast(arr, expected, dtype): + result = maybe_downcast_to_dtype(arr, dtype) + tm.assert_numpy_array_equal(result, expected) + + +def test_downcast_booleans(): + # see gh-16875: coercing of booleans. + ser = Series([True, True, False]) + result = maybe_downcast_to_dtype(ser, np.dtype(np.float64)) + + expected = ser.values + tm.assert_numpy_array_equal(result, expected) + + +def test_downcast_conversion_no_nan(any_real_numpy_dtype): + dtype = any_real_numpy_dtype + expected = np.array([1, 2]) + arr = np.array([1.0, 2.0], dtype=dtype) + + result = maybe_downcast_to_dtype(arr, "infer") + tm.assert_almost_equal(result, expected, check_dtype=False) + + +def test_downcast_conversion_nan(float_numpy_dtype): + dtype = float_numpy_dtype + data = [1.0, 2.0, np.nan] + + expected = np.array(data, dtype=dtype) + arr = np.array(data, dtype=dtype) + + result = maybe_downcast_to_dtype(arr, "infer") + tm.assert_almost_equal(result, expected) + + +def test_downcast_conversion_empty(any_real_numpy_dtype): + dtype = any_real_numpy_dtype + arr = np.array([], dtype=dtype) + result = maybe_downcast_to_dtype(arr, np.dtype("int64")) + tm.assert_numpy_array_equal(result, np.array([], dtype=np.int64)) + + +@pytest.mark.parametrize("klass", [np.datetime64, np.timedelta64]) +def test_datetime_likes_nan(klass): + dtype = klass.__name__ + "[ns]" + arr = np.array([1, 2, np.nan]) + + exp = np.array([1, 2, klass("NaT")], dtype) + res = maybe_downcast_to_dtype(arr, dtype) + tm.assert_numpy_array_equal(res, exp) diff --git a/shared/package-files/0b/0b42a26dc923f1b579ea7723977b004e40f9ef945fbf63ffd4a1890c87cb145b/array.py b/shared/package-files/0b/0b42a26dc923f1b579ea7723977b004e40f9ef945fbf63ffd4a1890c87cb145b/array.py new file mode 100644 index 0000000000000000000000000000000000000000..e16a126ac10ee3ee3a00d8d967ad2a038e37ff5c --- /dev/null +++ b/shared/package-files/0b/0b42a26dc923f1b579ea7723977b004e40f9ef945fbf63ffd4a1890c87cb145b/array.py @@ -0,0 +1,2969 @@ +from __future__ import annotations + +import functools +import operator +from pathlib import Path +import re +import textwrap +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Literal, + cast, +) +import unicodedata +import warnings + +import numpy as np + +from pandas._libs import lib +from pandas._libs.tslibs import ( + NaT, + Timedelta, + Timestamp, + timezones, +) +from pandas.compat import ( + pa_version_under10p1, + pa_version_under11p0, + pa_version_under13p0, +) +from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level +from pandas.util._validators import validate_fillna_kwargs + +from pandas.core.dtypes.cast import ( + can_hold_element, + infer_dtype_from_scalar, +) +from pandas.core.dtypes.common import ( + is_array_like, + is_bool_dtype, + is_float_dtype, + is_integer, + is_list_like, + is_numeric_dtype, + is_scalar, + is_string_dtype, +) +from pandas.core.dtypes.dtypes import DatetimeTZDtype +from pandas.core.dtypes.missing import isna + +from pandas.core import ( + algorithms as algos, + missing, + ops, + roperator, +) +from pandas.core.algorithms import map_array +from pandas.core.arraylike import OpsMixin +from pandas.core.arrays._arrow_string_mixins import ArrowStringArrayMixin +from pandas.core.arrays._utils import to_numpy_dtype_inference +from pandas.core.arrays.base import ( + ExtensionArray, + ExtensionArraySupportsAnyAll, +) +from pandas.core.arrays.masked import BaseMaskedArray +from pandas.core.arrays.string_ import StringDtype +import pandas.core.common as com +from pandas.core.indexers import ( + check_array_indexer, + unpack_tuple_and_ellipses, + validate_indices, +) +from pandas.core.nanops import check_below_min_count +from pandas.core.strings.base import BaseStringArrayMethods + +from pandas.io._util import _arrow_dtype_mapping +from pandas.tseries.frequencies import to_offset + +if not pa_version_under10p1: + import pyarrow as pa + import pyarrow.compute as pc + + from pandas.core.dtypes.dtypes import ArrowDtype + + ARROW_CMP_FUNCS = { + "eq": pc.equal, + "ne": pc.not_equal, + "lt": pc.less, + "gt": pc.greater, + "le": pc.less_equal, + "ge": pc.greater_equal, + } + + ARROW_LOGICAL_FUNCS = { + "and_": pc.and_kleene, + "rand_": lambda x, y: pc.and_kleene(y, x), + "or_": pc.or_kleene, + "ror_": lambda x, y: pc.or_kleene(y, x), + "xor": pc.xor, + "rxor": lambda x, y: pc.xor(y, x), + } + + ARROW_BIT_WISE_FUNCS = { + "and_": pc.bit_wise_and, + "rand_": lambda x, y: pc.bit_wise_and(y, x), + "or_": pc.bit_wise_or, + "ror_": lambda x, y: pc.bit_wise_or(y, x), + "xor": pc.bit_wise_xor, + "rxor": lambda x, y: pc.bit_wise_xor(y, x), + } + + def cast_for_truediv( + arrow_array: pa.ChunkedArray, pa_object: pa.Array | pa.Scalar + ) -> tuple[pa.ChunkedArray, pa.Array | pa.Scalar]: + # Ensure int / int -> float mirroring Python/Numpy behavior + # as pc.divide_checked(int, int) -> int + if pa.types.is_integer(arrow_array.type) and pa.types.is_integer( + pa_object.type + ): + # GH: 56645. + # https://github.com/apache/arrow/issues/35563 + return pc.cast(arrow_array, pa.float64(), safe=False), pc.cast( + pa_object, pa.float64(), safe=False + ) + + return arrow_array, pa_object + + def floordiv_compat( + left: pa.ChunkedArray | pa.Array | pa.Scalar, + right: pa.ChunkedArray | pa.Array | pa.Scalar, + ) -> pa.ChunkedArray: + # TODO: Replace with pyarrow floordiv kernel. + # https://github.com/apache/arrow/issues/39386 + if pa.types.is_integer(left.type) and pa.types.is_integer(right.type): + divided = pc.divide_checked(left, right) + if pa.types.is_signed_integer(divided.type): + # GH 56676 + has_remainder = pc.not_equal(pc.multiply(divided, right), left) + has_one_negative_operand = pc.less( + pc.bit_wise_xor(left, right), + pa.scalar(0, type=divided.type), + ) + result = pc.if_else( + pc.and_( + has_remainder, + has_one_negative_operand, + ), + # GH: 55561 + pc.subtract(divided, pa.scalar(1, type=divided.type)), + divided, + ) + else: + result = divided + result = result.cast(left.type) + else: + divided = pc.divide(left, right) + result = pc.floor(divided) + return result + + ARROW_ARITHMETIC_FUNCS = { + "add": pc.add_checked, + "radd": lambda x, y: pc.add_checked(y, x), + "sub": pc.subtract_checked, + "rsub": lambda x, y: pc.subtract_checked(y, x), + "mul": pc.multiply_checked, + "rmul": lambda x, y: pc.multiply_checked(y, x), + "truediv": lambda x, y: pc.divide(*cast_for_truediv(x, y)), + "rtruediv": lambda x, y: pc.divide(*cast_for_truediv(y, x)), + "floordiv": lambda x, y: floordiv_compat(x, y), + "rfloordiv": lambda x, y: floordiv_compat(y, x), + "mod": NotImplemented, + "rmod": NotImplemented, + "divmod": NotImplemented, + "rdivmod": NotImplemented, + "pow": pc.power_checked, + "rpow": lambda x, y: pc.power_checked(y, x), + } + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pandas._typing import ( + ArrayLike, + AxisInt, + Dtype, + FillnaOptions, + InterpolateOptions, + Iterator, + NpDtype, + NumpySorter, + NumpyValueArrayLike, + PositionalIndexer, + Scalar, + Self, + SortKind, + TakeIndexer, + TimeAmbiguous, + TimeNonexistent, + npt, + ) + + from pandas import Series + from pandas.core.arrays.datetimes import DatetimeArray + from pandas.core.arrays.timedeltas import TimedeltaArray + + +def get_unit_from_pa_dtype(pa_dtype): + # https://github.com/pandas-dev/pandas/pull/50998#discussion_r1100344804 + if pa_version_under11p0: + unit = str(pa_dtype).split("[", 1)[-1][:-1] + if unit not in ["s", "ms", "us", "ns"]: + raise ValueError(pa_dtype) + return unit + return pa_dtype.unit + + +def to_pyarrow_type( + dtype: ArrowDtype | pa.DataType | Dtype | None, +) -> pa.DataType | None: + """ + Convert dtype to a pyarrow type instance. + """ + if isinstance(dtype, ArrowDtype): + return dtype.pyarrow_dtype + elif isinstance(dtype, pa.DataType): + return dtype + elif isinstance(dtype, DatetimeTZDtype): + return pa.timestamp(dtype.unit, dtype.tz) + elif dtype: + try: + # Accepts python types too + # Doesn't handle all numpy types + return pa.from_numpy_dtype(dtype) + except pa.ArrowNotImplementedError: + pass + return None + + +class ArrowExtensionArray( # type: ignore[misc] + OpsMixin, + ExtensionArraySupportsAnyAll, + ArrowStringArrayMixin, + BaseStringArrayMethods, +): + """ + Pandas ExtensionArray backed by a PyArrow ChunkedArray. + + .. warning:: + + ArrowExtensionArray is considered experimental. The implementation and + parts of the API may change without warning. + + Parameters + ---------- + values : pyarrow.Array or pyarrow.ChunkedArray + + Attributes + ---------- + None + + Methods + ------- + None + + Returns + ------- + ArrowExtensionArray + + Notes + ----- + Most methods are implemented using `pyarrow compute functions. `__ + Some methods may either raise an exception or raise a ``PerformanceWarning`` if an + associated compute function is not available based on the installed version of PyArrow. + + Please install the latest version of PyArrow to enable the best functionality and avoid + potential bugs in prior versions of PyArrow. + + Examples + -------- + Create an ArrowExtensionArray with :func:`pandas.array`: + + >>> pd.array([1, 1, None], dtype="int64[pyarrow]") + + [1, 1, ] + Length: 3, dtype: int64[pyarrow] + """ # noqa: E501 (http link too long) + + _pa_array: pa.ChunkedArray + _dtype: ArrowDtype + + def __init__(self, values: pa.Array | pa.ChunkedArray) -> None: + if pa_version_under10p1: + msg = "pyarrow>=10.0.1 is required for PyArrow backed ArrowExtensionArray." + raise ImportError(msg) + if isinstance(values, pa.Array): + self._pa_array = pa.chunked_array([values]) + elif isinstance(values, pa.ChunkedArray): + self._pa_array = values + else: + raise ValueError( + f"Unsupported type '{type(values)}' for ArrowExtensionArray" + ) + self._dtype = ArrowDtype(self._pa_array.type) + + @classmethod + def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False): + """ + Construct a new ExtensionArray from a sequence of scalars. + """ + pa_type = to_pyarrow_type(dtype) + pa_array = cls._box_pa_array(scalars, pa_type=pa_type, copy=copy) + arr = cls(pa_array) + return arr + + @classmethod + def _from_sequence_of_strings( + cls, strings, *, dtype: Dtype | None = None, copy: bool = False + ): + """ + Construct a new ExtensionArray from a sequence of strings. + """ + pa_type = to_pyarrow_type(dtype) + if ( + pa_type is None + or pa.types.is_binary(pa_type) + or pa.types.is_string(pa_type) + or pa.types.is_large_string(pa_type) + ): + # pa_type is None: Let pa.array infer + # pa_type is string/binary: scalars already correct type + scalars = strings + elif pa.types.is_timestamp(pa_type): + from pandas.core.tools.datetimes import to_datetime + + scalars = to_datetime(strings, errors="raise") + elif pa.types.is_date(pa_type): + from pandas.core.tools.datetimes import to_datetime + + scalars = to_datetime(strings, errors="raise").date + elif pa.types.is_duration(pa_type): + from pandas.core.tools.timedeltas import to_timedelta + + scalars = to_timedelta(strings, errors="raise") + if pa_type.unit != "ns": + # GH51175: test_from_sequence_of_strings_pa_array + # attempt to parse as int64 reflecting pyarrow's + # duration to string casting behavior + mask = isna(scalars) + if not isinstance(strings, (pa.Array, pa.ChunkedArray)): + strings = pa.array(strings, type=pa.string(), from_pandas=True) + strings = pc.if_else(mask, None, strings) + try: + scalars = strings.cast(pa.int64()) + except pa.ArrowInvalid: + pass + elif pa.types.is_time(pa_type): + from pandas.core.tools.times import to_time + + # "coerce" to allow "null times" (None) to not raise + scalars = to_time(strings, errors="coerce") + elif pa.types.is_boolean(pa_type): + # pyarrow string->bool casting is case-insensitive: + # "true" or "1" -> True + # "false" or "0" -> False + # Note: BooleanArray was previously used to parse these strings + # and allows "1.0" and "0.0". Pyarrow casting does not support + # this, but we allow it here. + if isinstance(strings, (pa.Array, pa.ChunkedArray)): + scalars = strings + else: + scalars = pa.array(strings, type=pa.string(), from_pandas=True) + scalars = pc.if_else(pc.equal(scalars, "1.0"), "1", scalars) + scalars = pc.if_else(pc.equal(scalars, "0.0"), "0", scalars) + scalars = scalars.cast(pa.bool_()) + elif ( + pa.types.is_integer(pa_type) + or pa.types.is_floating(pa_type) + or pa.types.is_decimal(pa_type) + ): + from pandas.core.tools.numeric import to_numeric + + scalars = to_numeric(strings, errors="raise") + else: + raise NotImplementedError( + f"Converting strings to {pa_type} is not implemented." + ) + return cls._from_sequence(scalars, dtype=pa_type, copy=copy) + + @classmethod + def _box_pa( + cls, value, pa_type: pa.DataType | None = None + ) -> pa.Array | pa.ChunkedArray | pa.Scalar: + """ + Box value into a pyarrow Array, ChunkedArray or Scalar. + + Parameters + ---------- + value : any + pa_type : pa.DataType | None + + Returns + ------- + pa.Array or pa.ChunkedArray or pa.Scalar + """ + if isinstance(value, pa.Scalar) or not is_list_like(value): + return cls._box_pa_scalar(value, pa_type) + return cls._box_pa_array(value, pa_type) + + @classmethod + def _box_pa_scalar(cls, value, pa_type: pa.DataType | None = None) -> pa.Scalar: + """ + Box value into a pyarrow Scalar. + + Parameters + ---------- + value : any + pa_type : pa.DataType | None + + Returns + ------- + pa.Scalar + """ + if isinstance(value, pa.Scalar): + pa_scalar = value + elif isna(value): + pa_scalar = pa.scalar(None, type=pa_type) + else: + # Workaround https://github.com/apache/arrow/issues/37291 + if isinstance(value, Timedelta): + if pa_type is None: + pa_type = pa.duration(value.unit) + elif value.unit != pa_type.unit: + value = value.as_unit(pa_type.unit) + value = value._value + elif isinstance(value, Timestamp): + if pa_type is None: + pa_type = pa.timestamp(value.unit, tz=value.tz) + elif value.unit != pa_type.unit: + value = value.as_unit(pa_type.unit) + value = value._value + + pa_scalar = pa.scalar(value, type=pa_type, from_pandas=True) + + if pa_type is not None and pa_scalar.type != pa_type: + pa_scalar = pa_scalar.cast(pa_type) + + return pa_scalar + + @classmethod + def _box_pa_array( + cls, value, pa_type: pa.DataType | None = None, copy: bool = False + ) -> pa.Array | pa.ChunkedArray: + """ + Box value into a pyarrow Array or ChunkedArray. + + Parameters + ---------- + value : Sequence + pa_type : pa.DataType | None + + Returns + ------- + pa.Array or pa.ChunkedArray + """ + if isinstance(value, cls): + pa_array = value._pa_array + elif isinstance(value, (pa.Array, pa.ChunkedArray)): + pa_array = value + elif isinstance(value, BaseMaskedArray): + # GH 52625 + if copy: + value = value.copy() + pa_array = value.__arrow_array__() + else: + if ( + isinstance(value, np.ndarray) + and pa_type is not None + and ( + pa.types.is_large_binary(pa_type) + or pa.types.is_large_string(pa_type) + ) + ): + # See https://github.com/apache/arrow/issues/35289 + value = value.tolist() + elif copy and is_array_like(value): + # pa array should not get updated when numpy array is updated + value = value.copy() + + if ( + pa_type is not None + and pa.types.is_duration(pa_type) + and (not isinstance(value, np.ndarray) or value.dtype.kind not in "mi") + ): + # Workaround https://github.com/apache/arrow/issues/37291 + from pandas.core.tools.timedeltas import to_timedelta + + value = to_timedelta(value, unit=pa_type.unit).as_unit(pa_type.unit) + value = value.to_numpy() + + try: + pa_array = pa.array(value, type=pa_type, from_pandas=True) + except (pa.ArrowInvalid, pa.ArrowTypeError): + # GH50430: let pyarrow infer type, then cast + pa_array = pa.array(value, from_pandas=True) + + if pa_type is None and pa.types.is_duration(pa_array.type): + # Workaround https://github.com/apache/arrow/issues/37291 + from pandas.core.tools.timedeltas import to_timedelta + + value = to_timedelta(value) + value = value.to_numpy() + pa_array = pa.array(value, type=pa_type, from_pandas=True) + + if pa.types.is_duration(pa_array.type) and pa_array.null_count > 0: + # GH52843: upstream bug for duration types when originally + # constructed with data containing numpy NaT. + # https://github.com/apache/arrow/issues/35088 + arr = cls(pa_array) + arr = arr.fillna(arr.dtype.na_value) + pa_array = arr._pa_array + + if pa_type is not None and pa_array.type != pa_type: + if pa.types.is_dictionary(pa_type): + pa_array = pa_array.dictionary_encode() + else: + try: + pa_array = pa_array.cast(pa_type) + except ( + pa.ArrowInvalid, + pa.ArrowTypeError, + pa.ArrowNotImplementedError, + ): + if pa.types.is_string(pa_array.type) or pa.types.is_large_string( + pa_array.type + ): + # TODO: Move logic in _from_sequence_of_strings into + # _box_pa_array + return cls._from_sequence_of_strings( + value, dtype=pa_type + )._pa_array + else: + raise + + return pa_array + + def __getitem__(self, item: PositionalIndexer): + """Select a subset of self. + + Parameters + ---------- + item : int, slice, or ndarray + * int: The position in 'self' to get. + * slice: A slice object, where 'start', 'stop', and 'step' are + integers or None + * ndarray: A 1-d boolean NumPy ndarray the same length as 'self' + + Returns + ------- + item : scalar or ExtensionArray + + Notes + ----- + For scalar ``item``, return a scalar value suitable for the array's + type. This should be an instance of ``self.dtype.type``. + For slice ``key``, return an instance of ``ExtensionArray``, even + if the slice is length 0 or 1. + For a boolean mask, return an instance of ``ExtensionArray``, filtered + to the values where ``item`` is True. + """ + item = check_array_indexer(self, item) + + if isinstance(item, np.ndarray): + if not len(item): + # Removable once we migrate StringDtype[pyarrow] to ArrowDtype[string] + if ( + isinstance(self._dtype, StringDtype) + and self._dtype.storage == "pyarrow" + ): + # TODO(infer_string) should this be large_string? + pa_dtype = pa.string() + else: + pa_dtype = self._dtype.pyarrow_dtype + return type(self)(pa.chunked_array([], type=pa_dtype)) + elif item.dtype.kind in "iu": + return self.take(item) + elif item.dtype.kind == "b": + return type(self)(self._pa_array.filter(item)) + else: + raise IndexError( + "Only integers, slices and integer or " + "boolean arrays are valid indices." + ) + elif isinstance(item, tuple): + item = unpack_tuple_and_ellipses(item) + + if item is Ellipsis: + # TODO: should be handled by pyarrow? + item = slice(None) + + if is_scalar(item) and not is_integer(item): + # e.g. "foo" or 2.5 + # exception message copied from numpy + raise IndexError( + r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis " + r"(`None`) and integer or boolean arrays are valid indices" + ) + # We are not an array indexer, so maybe e.g. a slice or integer + # indexer. We dispatch to pyarrow. + if isinstance(item, slice): + # Arrow bug https://github.com/apache/arrow/issues/38768 + if item.start == item.stop: + pass + elif ( + item.stop is not None + and item.stop < -len(self) + and item.step is not None + and item.step < 0 + ): + item = slice(item.start, None, item.step) + + value = self._pa_array[item] + if isinstance(value, pa.ChunkedArray): + return type(self)(value) + else: + pa_type = self._pa_array.type + scalar = value.as_py() + if scalar is None: + return self._dtype.na_value + elif pa.types.is_timestamp(pa_type) and pa_type.unit != "ns": + # GH 53326 + return Timestamp(scalar).as_unit(pa_type.unit) + elif pa.types.is_duration(pa_type) and pa_type.unit != "ns": + # GH 53326 + return Timedelta(scalar).as_unit(pa_type.unit) + else: + return scalar + + def __iter__(self) -> Iterator[Any]: + """ + Iterate over elements of the array. + """ + na_value = self._dtype.na_value + # GH 53326 + pa_type = self._pa_array.type + box_timestamp = pa.types.is_timestamp(pa_type) and pa_type.unit != "ns" + box_timedelta = pa.types.is_duration(pa_type) and pa_type.unit != "ns" + for value in self._pa_array: + val = value.as_py() + if val is None: + yield na_value + elif box_timestamp: + yield Timestamp(val).as_unit(pa_type.unit) + elif box_timedelta: + yield Timedelta(val).as_unit(pa_type.unit) + else: + yield val + + def __arrow_array__(self, type=None): + """Convert myself to a pyarrow ChunkedArray.""" + return self._pa_array + + def __array__( + self, dtype: NpDtype | None = None, copy: bool | None = None + ) -> np.ndarray: + """Correctly construct numpy arrays when passed to `np.asarray()`.""" + if copy is False: + warnings.warn( + "Starting with NumPy 2.0, the behavior of the 'copy' keyword has " + "changed and passing 'copy=False' raises an error when returning " + "a zero-copy NumPy array is not possible. pandas will follow " + "this behavior starting with pandas 3.0.\nThis conversion to " + "NumPy requires a copy, but 'copy=False' was passed. Consider " + "using 'np.asarray(..)' instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + elif copy is None: + # `to_numpy(copy=False)` has the meaning of NumPy `copy=None`. + copy = False + + return self.to_numpy(dtype=dtype, copy=copy) + + def __invert__(self) -> Self: + # This is a bit wise op for integer types + if pa.types.is_integer(self._pa_array.type): + return type(self)(pc.bit_wise_not(self._pa_array)) + elif pa.types.is_string(self._pa_array.type) or pa.types.is_large_string( + self._pa_array.type + ): + # Raise TypeError instead of pa.ArrowNotImplementedError + raise TypeError("__invert__ is not supported for string dtypes") + else: + return type(self)(pc.invert(self._pa_array)) + + def __neg__(self) -> Self: + try: + return type(self)(pc.negate_checked(self._pa_array)) + except pa.ArrowNotImplementedError as err: + raise TypeError( + f"unary '-' not supported for dtype '{self.dtype}'" + ) from err + + def __pos__(self) -> Self: + return type(self)(self._pa_array) + + def __abs__(self) -> Self: + return type(self)(pc.abs_checked(self._pa_array)) + + # GH 42600: __getstate__/__setstate__ not necessary once + # https://issues.apache.org/jira/browse/ARROW-10739 is addressed + def __getstate__(self): + state = self.__dict__.copy() + state["_pa_array"] = self._pa_array.combine_chunks() + return state + + def __setstate__(self, state) -> None: + if "_data" in state: + data = state.pop("_data") + else: + data = state["_pa_array"] + state["_pa_array"] = pa.chunked_array(data) + self.__dict__.update(state) + + def _cmp_method(self, other, op): + pc_func = ARROW_CMP_FUNCS[op.__name__] + if isinstance(other, (ExtensionArray, np.ndarray, list)): + try: + boxed = self._box_pa(other) + except pa.lib.ArrowInvalid: + # e.g. GH#60228 [1, "b"] we have to operate pointwise + res_values = [op(x, y) for x, y in zip(self, other)] + result = pa.array(res_values, type=pa.bool_(), from_pandas=True) + else: + try: + result = pc_func(self._pa_array, boxed) + except pa.ArrowNotImplementedError: + result = ops.invalid_comparison(self, other, op) + result = pa.array(result, type=pa.bool_()) + + elif is_scalar(other): + try: + result = pc_func(self._pa_array, self._box_pa(other)) + except (pa.lib.ArrowNotImplementedError, pa.lib.ArrowInvalid): + mask = isna(self) | isna(other) + valid = ~mask + result = np.zeros(len(self), dtype="bool") + np_array = np.array(self) + try: + result[valid] = op(np_array[valid], other) + except TypeError: + result = ops.invalid_comparison(self, other, op) + result = pa.array(result, type=pa.bool_()) + result = pc.if_else(valid, result, None) + else: + raise NotImplementedError( + f"{op.__name__} not implemented for {type(other)}" + ) + return ArrowExtensionArray(result) + + def _op_method_error_message(self, other, op) -> str: + if hasattr(other, "dtype"): + other_type = f"dtype '{other.dtype}'" + else: + other_type = f"object of type {type(other)}" + return ( + f"operation '{op.__name__}' not supported for " + f"dtype '{self.dtype}' with {other_type}" + ) + + def _evaluate_op_method(self, other, op, arrow_funcs) -> Self: + pa_type = self._pa_array.type + other_original = other + other = self._box_pa(other) + + if ( + pa.types.is_string(pa_type) + or pa.types.is_large_string(pa_type) + or pa.types.is_binary(pa_type) + ): + if op in [operator.add, roperator.radd]: + sep = pa.scalar("", type=pa_type) + try: + if op is operator.add: + result = pc.binary_join_element_wise(self._pa_array, other, sep) + elif op is roperator.radd: + result = pc.binary_join_element_wise(other, self._pa_array, sep) + except pa.ArrowNotImplementedError as err: + raise TypeError( + self._op_method_error_message(other_original, op) + ) from err + return type(self)(result) + elif op in [operator.mul, roperator.rmul]: + binary = self._pa_array + integral = other + if not pa.types.is_integer(integral.type): + raise TypeError("Can only string multiply by an integer.") + pa_integral = pc.if_else(pc.less(integral, 0), 0, integral) + result = pc.binary_repeat(binary, pa_integral) + return type(self)(result) + elif ( + pa.types.is_string(other.type) + or pa.types.is_binary(other.type) + or pa.types.is_large_string(other.type) + ) and op in [operator.mul, roperator.rmul]: + binary = other + integral = self._pa_array + if not pa.types.is_integer(integral.type): + raise TypeError("Can only string multiply by an integer.") + pa_integral = pc.if_else(pc.less(integral, 0), 0, integral) + result = pc.binary_repeat(binary, pa_integral) + return type(self)(result) + if ( + isinstance(other, pa.Scalar) + and pc.is_null(other).as_py() + and op.__name__ in ARROW_LOGICAL_FUNCS + ): + # pyarrow kleene ops require null to be typed + other = other.cast(pa_type) + + pc_func = arrow_funcs[op.__name__] + if pc_func is NotImplemented: + if pa.types.is_string(pa_type) or pa.types.is_large_string(pa_type): + raise TypeError(self._op_method_error_message(other_original, op)) + raise NotImplementedError(f"{op.__name__} not implemented.") + + try: + result = pc_func(self._pa_array, other) + except pa.ArrowNotImplementedError as err: + raise TypeError(self._op_method_error_message(other_original, op)) from err + return type(self)(result) + + def _logical_method(self, other, op): + # For integer types `^`, `|`, `&` are bitwise operators and return + # integer types. Otherwise these are boolean ops. + if pa.types.is_integer(self._pa_array.type): + return self._evaluate_op_method(other, op, ARROW_BIT_WISE_FUNCS) + elif ( + ( + pa.types.is_string(self._pa_array.type) + or pa.types.is_large_string(self._pa_array.type) + ) + and op in (roperator.ror_, roperator.rand_, roperator.rxor) + and isinstance(other, np.ndarray) + and other.dtype == bool + ): + # GH#60234 backward compatibility for the move to StringDtype in 3.0 + op_name = op.__name__[1:].strip("_") + warnings.warn( + f"'{op_name}' operations between boolean dtype and {self.dtype} are " + "deprecated and will raise in a future version. Explicitly " + "cast the strings to a boolean dtype before operating instead.", + DeprecationWarning, + stacklevel=find_stack_level(), + ) + return op(other, self.astype(bool)) + else: + return self._evaluate_op_method(other, op, ARROW_LOGICAL_FUNCS) + + def _arith_method(self, other, op) -> Self | npt.NDArray[np.object_]: + if ( + op in [operator.truediv, roperator.rtruediv] + and isinstance(other, Path) + and ( + pa.types.is_string(self._pa_array.type) + or pa.types.is_large_string(self._pa_array.type) + ) + ): + # GH#61940 + return np.array( + [ + op(x, other) if isinstance(x, str) else self.dtype.na_value + for x in self + ], + dtype=object, + ) + return self._evaluate_op_method(other, op, ARROW_ARITHMETIC_FUNCS) + + def equals(self, other) -> bool: + if not isinstance(other, ArrowExtensionArray): + return False + # I'm told that pyarrow makes __eq__ behave like pandas' equals; + # TODO: is this documented somewhere? + return self._pa_array == other._pa_array + + @property + def dtype(self) -> ArrowDtype: + """ + An instance of 'ExtensionDtype'. + """ + return self._dtype + + @property + def nbytes(self) -> int: + """ + The number of bytes needed to store this object in memory. + """ + return self._pa_array.nbytes + + def __len__(self) -> int: + """ + Length of this array. + + Returns + ------- + length : int + """ + return len(self._pa_array) + + def __contains__(self, key) -> bool: + # https://github.com/pandas-dev/pandas/pull/51307#issuecomment-1426372604 + if isna(key) and key is not self.dtype.na_value: + if self.dtype.kind == "f" and lib.is_float(key): + return pc.any(pc.is_nan(self._pa_array)).as_py() + + # e.g. date or timestamp types we do not allow None here to match pd.NA + return False + # TODO: maybe complex? object? + + return bool(super().__contains__(key)) + + @property + def _hasna(self) -> bool: + return self._pa_array.null_count > 0 + + def isna(self) -> npt.NDArray[np.bool_]: + """ + Boolean NumPy array indicating if each value is missing. + + This should return a 1-D array the same length as 'self'. + """ + # GH51630: fast paths + null_count = self._pa_array.null_count + if null_count == 0: + return np.zeros(len(self), dtype=np.bool_) + elif null_count == len(self): + return np.ones(len(self), dtype=np.bool_) + + return self._pa_array.is_null().to_numpy() + + def any(self, *, skipna: bool = True, **kwargs): + """ + Return whether any element is truthy. + + Returns False unless there is at least one element that is truthy. + By default, NAs are skipped. If ``skipna=False`` is specified and + missing values are present, similar :ref:`Kleene logic ` + is used as for logical operations. + + Parameters + ---------- + skipna : bool, default True + Exclude NA values. If the entire array is NA and `skipna` is + True, then the result will be False, as for an empty array. + If `skipna` is False, the result will still be True if there is + at least one element that is truthy, otherwise NA will be returned + if there are NA's present. + + Returns + ------- + bool or :attr:`pandas.NA` + + See Also + -------- + ArrowExtensionArray.all : Return whether all elements are truthy. + + Examples + -------- + The result indicates whether any element is truthy (and by default + skips NAs): + + >>> pd.array([True, False, True], dtype="boolean[pyarrow]").any() + True + >>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any() + True + >>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any() + False + >>> pd.array([], dtype="boolean[pyarrow]").any() + False + >>> pd.array([pd.NA], dtype="boolean[pyarrow]").any() + False + >>> pd.array([pd.NA], dtype="float64[pyarrow]").any() + False + + With ``skipna=False``, the result can be NA if this is logically + required (whether ``pd.NA`` is True or False influences the result): + + >>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False) + True + >>> pd.array([1, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False) + True + >>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False) + + >>> pd.array([0, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False) + + """ + return self._reduce("any", skipna=skipna, **kwargs) + + def all(self, *, skipna: bool = True, **kwargs): + """ + Return whether all elements are truthy. + + Returns True unless there is at least one element that is falsey. + By default, NAs are skipped. If ``skipna=False`` is specified and + missing values are present, similar :ref:`Kleene logic ` + is used as for logical operations. + + Parameters + ---------- + skipna : bool, default True + Exclude NA values. If the entire array is NA and `skipna` is + True, then the result will be True, as for an empty array. + If `skipna` is False, the result will still be False if there is + at least one element that is falsey, otherwise NA will be returned + if there are NA's present. + + Returns + ------- + bool or :attr:`pandas.NA` + + See Also + -------- + ArrowExtensionArray.any : Return whether any element is truthy. + + Examples + -------- + The result indicates whether all elements are truthy (and by default + skips NAs): + + >>> pd.array([True, True, pd.NA], dtype="boolean[pyarrow]").all() + True + >>> pd.array([1, 1, pd.NA], dtype="boolean[pyarrow]").all() + True + >>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").all() + False + >>> pd.array([], dtype="boolean[pyarrow]").all() + True + >>> pd.array([pd.NA], dtype="boolean[pyarrow]").all() + True + >>> pd.array([pd.NA], dtype="float64[pyarrow]").all() + True + + With ``skipna=False``, the result can be NA if this is logically + required (whether ``pd.NA`` is True or False influences the result): + + >>> pd.array([True, True, pd.NA], dtype="boolean[pyarrow]").all(skipna=False) + + >>> pd.array([1, 1, pd.NA], dtype="boolean[pyarrow]").all(skipna=False) + + >>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").all(skipna=False) + False + >>> pd.array([1, 0, pd.NA], dtype="boolean[pyarrow]").all(skipna=False) + False + """ + return self._reduce("all", skipna=skipna, **kwargs) + + def argsort( + self, + *, + ascending: bool = True, + kind: SortKind = "quicksort", + na_position: str = "last", + **kwargs, + ) -> np.ndarray: + order = "ascending" if ascending else "descending" + null_placement = {"last": "at_end", "first": "at_start"}.get(na_position, None) + if null_placement is None: + raise ValueError(f"invalid na_position: {na_position}") + + result = pc.array_sort_indices( + self._pa_array, order=order, null_placement=null_placement + ) + np_result = result.to_numpy() + return np_result.astype(np.intp, copy=False) + + def _argmin_max(self, skipna: bool, method: str) -> int: + if self._pa_array.length() in (0, self._pa_array.null_count) or ( + self._hasna and not skipna + ): + # For empty or all null, pyarrow returns -1 but pandas expects TypeError + # For skipna=False and data w/ null, pandas expects NotImplementedError + # let ExtensionArray.arg{max|min} raise + return getattr(super(), f"arg{method}")(skipna=skipna) + + data = self._pa_array + if pa.types.is_duration(data.type): + data = data.cast(pa.int64()) + + value = getattr(pc, method)(data, skip_nulls=skipna) + return pc.index(data, value).as_py() + + def argmin(self, skipna: bool = True) -> int: + return self._argmin_max(skipna, "min") + + def argmax(self, skipna: bool = True) -> int: + return self._argmin_max(skipna, "max") + + def copy(self) -> Self: + """ + Return a shallow copy of the array. + + Underlying ChunkedArray is immutable, so a deep copy is unnecessary. + + Returns + ------- + type(self) + """ + return type(self)(self._pa_array) + + def dropna(self) -> Self: + """ + Return ArrowExtensionArray without NA values. + + Returns + ------- + ArrowExtensionArray + """ + return type(self)(pc.drop_null(self._pa_array)) + + def _pad_or_backfill( + self, + *, + method: FillnaOptions, + limit: int | None = None, + limit_area: Literal["inside", "outside"] | None = None, + copy: bool = True, + ) -> Self: + if not self._hasna: + # TODO(CoW): Not necessary anymore when CoW is the default + return self.copy() + + if limit is None and limit_area is None: + method = missing.clean_fill_method(method) + try: + if method == "pad": + return type(self)(pc.fill_null_forward(self._pa_array)) + elif method == "backfill": + return type(self)(pc.fill_null_backward(self._pa_array)) + except pa.ArrowNotImplementedError: + # ArrowNotImplementedError: Function 'coalesce' has no kernel + # matching input types (duration[ns], duration[ns]) + # TODO: remove try/except wrapper if/when pyarrow implements + # a kernel for duration types. + pass + + # TODO(3.0): after EA.fillna 'method' deprecation is enforced, we can remove + # this method entirely. + return super()._pad_or_backfill( + method=method, limit=limit, limit_area=limit_area, copy=copy + ) + + @doc(ExtensionArray.fillna) + def fillna( + self, + value: object | ArrayLike | None = None, + method: FillnaOptions | None = None, + limit: int | None = None, + copy: bool = True, + ) -> Self: + value, method = validate_fillna_kwargs(value, method) + + if not self._hasna: + # TODO(CoW): Not necessary anymore when CoW is the default + return self.copy() + + if limit is not None: + return super().fillna(value=value, method=method, limit=limit, copy=copy) + + if method is not None: + return super().fillna(method=method, limit=limit, copy=copy) + + if isinstance(value, (np.ndarray, ExtensionArray)): + # Similar to check_value_size, but we do not mask here since we may + # end up passing it to the super() method. + if len(value) != len(self): + raise ValueError( + f"Length of 'value' does not match. Got ({len(value)}) " + f" expected {len(self)}" + ) + + try: + fill_value = self._box_pa(value, pa_type=self._pa_array.type) + except pa.ArrowTypeError as err: + msg = f"Invalid value '{value!s}' for dtype '{self.dtype}'" + raise TypeError(msg) from err + + try: + return type(self)(pc.fill_null(self._pa_array, fill_value=fill_value)) + except pa.ArrowNotImplementedError: + # ArrowNotImplementedError: Function 'coalesce' has no kernel + # matching input types (duration[ns], duration[ns]) + # TODO: remove try/except wrapper if/when pyarrow implements + # a kernel for duration types. + pass + + return super().fillna(value=value, method=method, limit=limit, copy=copy) + + def isin(self, values: ArrayLike) -> npt.NDArray[np.bool_]: + # short-circuit to return all False array. + if not len(values): + return np.zeros(len(self), dtype=bool) + + result = pc.is_in(self._pa_array, value_set=pa.array(values, from_pandas=True)) + # pyarrow 2.0.0 returned nulls, so we explicitly specify dtype to convert nulls + # to False + return np.array(result, dtype=np.bool_) + + def _values_for_factorize(self) -> tuple[np.ndarray, Any]: + """ + Return an array and missing value suitable for factorization. + + Returns + ------- + values : ndarray + na_value : pd.NA + + Notes + ----- + The values returned by this method are also used in + :func:`pandas.util.hash_pandas_object`. + """ + values = self._pa_array.to_numpy() + return values, self.dtype.na_value + + @doc(ExtensionArray.factorize) + def factorize( + self, + use_na_sentinel: bool = True, + ) -> tuple[np.ndarray, ExtensionArray]: + null_encoding = "mask" if use_na_sentinel else "encode" + + data = self._pa_array + pa_type = data.type + if pa_version_under11p0 and pa.types.is_duration(pa_type): + # https://github.com/apache/arrow/issues/15226#issuecomment-1376578323 + data = data.cast(pa.int64()) + + if pa.types.is_dictionary(data.type): + encoded = data + else: + encoded = data.dictionary_encode(null_encoding=null_encoding) + if encoded.length() == 0: + indices = np.array([], dtype=np.intp) + uniques = type(self)(pa.chunked_array([], type=encoded.type.value_type)) + else: + # GH 54844 + combined = encoded.combine_chunks() + pa_indices = combined.indices + if pa_indices.null_count > 0: + pa_indices = pc.fill_null(pa_indices, -1) + indices = pa_indices.to_numpy(zero_copy_only=False, writable=True).astype( + np.intp, copy=False + ) + uniques = type(self)(combined.dictionary) + + if pa_version_under11p0 and pa.types.is_duration(pa_type): + uniques = cast(ArrowExtensionArray, uniques.astype(self.dtype)) + return indices, uniques + + def reshape(self, *args, **kwargs): + raise NotImplementedError( + f"{type(self)} does not support reshape " + f"as backed by a 1D pyarrow.ChunkedArray." + ) + + def round(self, decimals: int = 0, *args, **kwargs) -> Self: + """ + Round each value in the array a to the given number of decimals. + + Parameters + ---------- + decimals : int, default 0 + Number of decimal places to round to. If decimals is negative, + it specifies the number of positions to the left of the decimal point. + *args, **kwargs + Additional arguments and keywords have no effect. + + Returns + ------- + ArrowExtensionArray + Rounded values of the ArrowExtensionArray. + + See Also + -------- + DataFrame.round : Round values of a DataFrame. + Series.round : Round values of a Series. + """ + return type(self)(pc.round(self._pa_array, ndigits=decimals)) + + @doc(ExtensionArray.searchsorted) + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter | None = None, + ) -> npt.NDArray[np.intp] | np.intp: + if self._hasna: + raise ValueError( + "searchsorted requires array to be sorted, which is impossible " + "with NAs present." + ) + if isinstance(value, ExtensionArray): + value = value.astype(object) + # Base class searchsorted would cast to object, which is *much* slower. + dtype = None + if isinstance(self.dtype, ArrowDtype): + pa_dtype = self.dtype.pyarrow_dtype + if ( + pa.types.is_timestamp(pa_dtype) or pa.types.is_duration(pa_dtype) + ) and pa_dtype.unit == "ns": + # np.array[datetime/timedelta].searchsorted(datetime/timedelta) + # erroneously fails when numpy type resolution is nanoseconds + dtype = object + return self.to_numpy(dtype=dtype).searchsorted(value, side=side, sorter=sorter) + + def take( + self, + indices: TakeIndexer, + allow_fill: bool = False, + fill_value: Any = None, + ) -> ArrowExtensionArray: + """ + Take elements from an array. + + Parameters + ---------- + indices : sequence of int or one-dimensional np.ndarray of int + Indices to be taken. + allow_fill : bool, default False + How to handle negative values in `indices`. + + * False: negative values in `indices` indicate positional indices + from the right (the default). This is similar to + :func:`numpy.take`. + + * True: negative values in `indices` indicate + missing values. These values are set to `fill_value`. Any other + other negative values raise a ``ValueError``. + + fill_value : any, optional + Fill value to use for NA-indices when `allow_fill` is True. + This may be ``None``, in which case the default NA value for + the type, ``self.dtype.na_value``, is used. + + For many ExtensionArrays, there will be two representations of + `fill_value`: a user-facing "boxed" scalar, and a low-level + physical NA value. `fill_value` should be the user-facing version, + and the implementation should handle translating that to the + physical version for processing the take if necessary. + + Returns + ------- + ExtensionArray + + Raises + ------ + IndexError + When the indices are out of bounds for the array. + ValueError + When `indices` contains negative values other than ``-1`` + and `allow_fill` is True. + + See Also + -------- + numpy.take + api.extensions.take + + Notes + ----- + ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``, + ``iloc``, when `indices` is a sequence of values. Additionally, + it's called by :meth:`Series.reindex`, or any other method + that causes realignment, with a `fill_value`. + """ + indices_array = np.asanyarray(indices) + + if len(self._pa_array) == 0 and (indices_array >= 0).any(): + raise IndexError("cannot do a non-empty take") + if indices_array.size > 0 and indices_array.max() >= len(self._pa_array): + raise IndexError("out of bounds value in 'indices'.") + + if allow_fill: + fill_mask = indices_array < 0 + if fill_mask.any(): + validate_indices(indices_array, len(self._pa_array)) + # TODO(ARROW-9433): Treat negative indices as NULL + indices_array = pa.array(indices_array, mask=fill_mask) + result = self._pa_array.take(indices_array) + if isna(fill_value): + return type(self)(result) + # TODO: ArrowNotImplementedError: Function fill_null has no + # kernel matching input types (array[string], scalar[string]) + result = type(self)(result) + result[fill_mask] = fill_value + return result + # return type(self)(pc.fill_null(result, pa.scalar(fill_value))) + else: + # Nothing to fill + return type(self)(self._pa_array.take(indices)) + else: # allow_fill=False + # TODO(ARROW-9432): Treat negative indices as indices from the right. + if (indices_array < 0).any(): + # Don't modify in-place + indices_array = np.copy(indices_array) + indices_array[indices_array < 0] += len(self._pa_array) + return type(self)(self._pa_array.take(indices_array)) + + def _maybe_convert_datelike_array(self): + """Maybe convert to a datelike array.""" + pa_type = self._pa_array.type + if pa.types.is_timestamp(pa_type): + return self._to_datetimearray() + elif pa.types.is_duration(pa_type): + return self._to_timedeltaarray() + return self + + def _to_datetimearray(self) -> DatetimeArray: + """Convert a pyarrow timestamp typed array to a DatetimeArray.""" + from pandas.core.arrays.datetimes import ( + DatetimeArray, + tz_to_dtype, + ) + + pa_type = self._pa_array.type + assert pa.types.is_timestamp(pa_type) + np_dtype = np.dtype(f"M8[{pa_type.unit}]") + dtype = tz_to_dtype(pa_type.tz, pa_type.unit) + np_array = self._pa_array.to_numpy() + np_array = np_array.astype(np_dtype) + return DatetimeArray._simple_new(np_array, dtype=dtype) + + def _to_timedeltaarray(self) -> TimedeltaArray: + """Convert a pyarrow duration typed array to a TimedeltaArray.""" + from pandas.core.arrays.timedeltas import TimedeltaArray + + pa_type = self._pa_array.type + assert pa.types.is_duration(pa_type) + np_dtype = np.dtype(f"m8[{pa_type.unit}]") + np_array = self._pa_array.to_numpy() + np_array = np_array.astype(np_dtype) + return TimedeltaArray._simple_new(np_array, dtype=np_dtype) + + def _values_for_json(self) -> np.ndarray: + if is_numeric_dtype(self.dtype): + return np.asarray(self, dtype=object) + return super()._values_for_json() + + @doc(ExtensionArray.to_numpy) + def to_numpy( + self, + dtype: npt.DTypeLike | None = None, + copy: bool = False, + na_value: object = lib.no_default, + ) -> np.ndarray: + original_na_value = na_value + dtype, na_value = to_numpy_dtype_inference(self, dtype, na_value, self._hasna) + pa_type = self._pa_array.type + if not self._hasna or isna(na_value) or pa.types.is_null(pa_type): + data = self + else: + data = self.fillna(na_value) + copy = False + + if pa.types.is_timestamp(pa_type) or pa.types.is_duration(pa_type): + # GH 55997 + if dtype != object and na_value is self.dtype.na_value: + na_value = lib.no_default + result = data._maybe_convert_datelike_array().to_numpy( + dtype=dtype, na_value=na_value + ) + elif pa.types.is_time(pa_type) or pa.types.is_date(pa_type): + # convert to list of python datetime.time objects before + # wrapping in ndarray + result = np.array(list(data), dtype=dtype) + if data._hasna: + result[data.isna()] = na_value + elif pa.types.is_null(pa_type): + if dtype is not None and isna(na_value): + na_value = None + result = np.full(len(data), fill_value=na_value, dtype=dtype) + elif not data._hasna or ( + pa.types.is_floating(pa_type) + and ( + na_value is np.nan + or original_na_value is lib.no_default + and is_float_dtype(dtype) + ) + ): + result = data._pa_array.to_numpy() + if dtype is not None: + result = result.astype(dtype, copy=False) + if copy: + result = result.copy() + else: + if dtype is None: + empty = pa.array([], type=pa_type).to_numpy(zero_copy_only=False) + if can_hold_element(empty, na_value): + dtype = empty.dtype + else: + dtype = np.object_ + result = np.empty(len(data), dtype=dtype) + mask = data.isna() + result[mask] = na_value + result[~mask] = data[~mask]._pa_array.to_numpy() + return result + + def map(self, mapper, na_action=None): + if is_numeric_dtype(self.dtype): + return map_array(self.to_numpy(), mapper, na_action=na_action) + else: + return super().map(mapper, na_action) + + @doc(ExtensionArray.duplicated) + def duplicated( + self, keep: Literal["first", "last", False] = "first" + ) -> npt.NDArray[np.bool_]: + pa_type = self._pa_array.type + if pa.types.is_floating(pa_type) or pa.types.is_integer(pa_type): + values = self.to_numpy(na_value=0) + elif pa.types.is_boolean(pa_type): + values = self.to_numpy(na_value=False) + elif pa.types.is_temporal(pa_type): + if pa_type.bit_width == 32: + pa_type = pa.int32() + else: + pa_type = pa.int64() + arr = self.astype(ArrowDtype(pa_type)) + values = arr.to_numpy(na_value=0) + else: + # factorize the values to avoid the performance penalty of + # converting to object dtype + values = self.factorize()[0] + + mask = self.isna() if self._hasna else None + return algos.duplicated(values, keep=keep, mask=mask) + + def unique(self) -> Self: + """ + Compute the ArrowExtensionArray of unique values. + + Returns + ------- + ArrowExtensionArray + """ + pa_type = self._pa_array.type + + if pa_version_under11p0 and pa.types.is_duration(pa_type): + # https://github.com/apache/arrow/issues/15226#issuecomment-1376578323 + data = self._pa_array.cast(pa.int64()) + else: + data = self._pa_array + + pa_result = pc.unique(data) + + if pa_version_under11p0 and pa.types.is_duration(pa_type): + pa_result = pa_result.cast(pa_type) + + return type(self)(pa_result) + + def value_counts(self, dropna: bool = True) -> Series: + """ + Return a Series containing counts of each unique value. + + Parameters + ---------- + dropna : bool, default True + Don't include counts of missing values. + + Returns + ------- + counts : Series + + See Also + -------- + Series.value_counts + """ + pa_type = self._pa_array.type + if pa_version_under11p0 and pa.types.is_duration(pa_type): + # https://github.com/apache/arrow/issues/15226#issuecomment-1376578323 + data = self._pa_array.cast(pa.int64()) + else: + data = self._pa_array + + from pandas import ( + Index, + Series, + ) + + vc = data.value_counts() + + values = vc.field(0) + counts = vc.field(1) + if dropna and data.null_count > 0: + mask = values.is_valid() + values = values.filter(mask) + counts = counts.filter(mask) + + if pa_version_under11p0 and pa.types.is_duration(pa_type): + values = values.cast(pa_type) + + counts = ArrowExtensionArray(counts) + + index = Index(type(self)(values)) + + return Series(counts, index=index, name="count", copy=False) + + @classmethod + def _concat_same_type(cls, to_concat) -> Self: + """ + Concatenate multiple ArrowExtensionArrays. + + Parameters + ---------- + to_concat : sequence of ArrowExtensionArrays + + Returns + ------- + ArrowExtensionArray + """ + chunks = [array for ea in to_concat for array in ea._pa_array.iterchunks()] + if to_concat[0].dtype == "string": + # StringDtype has no attribute pyarrow_dtype + pa_dtype = pa.large_string() + else: + pa_dtype = to_concat[0].dtype.pyarrow_dtype + arr = pa.chunked_array(chunks, type=pa_dtype) + return cls(arr) + + def _accumulate( + self, name: str, *, skipna: bool = True, **kwargs + ) -> ArrowExtensionArray | ExtensionArray: + """ + Return an ExtensionArray performing an accumulation operation. + + The underlying data type might change. + + Parameters + ---------- + name : str + Name of the function, supported values are: + - cummin + - cummax + - cumsum + - cumprod + skipna : bool, default True + If True, skip NA values. + **kwargs + Additional keyword arguments passed to the accumulation function. + Currently, there is no supported kwarg. + + Returns + ------- + array + + Raises + ------ + NotImplementedError : subclass does not define accumulations + """ + if is_string_dtype(self): + return self._str_accumulate(name=name, skipna=skipna, **kwargs) + + pyarrow_name = { + "cummax": "cumulative_max", + "cummin": "cumulative_min", + "cumprod": "cumulative_prod_checked", + "cumsum": "cumulative_sum_checked", + }.get(name, name) + pyarrow_meth = getattr(pc, pyarrow_name, None) + if pyarrow_meth is None: + return super()._accumulate(name, skipna=skipna, **kwargs) + + data_to_accum = self._pa_array + + pa_dtype = data_to_accum.type + + convert_to_int = ( + pa.types.is_temporal(pa_dtype) and name in ["cummax", "cummin"] + ) or (pa.types.is_duration(pa_dtype) and name == "cumsum") + + if convert_to_int: + if pa_dtype.bit_width == 32: + data_to_accum = data_to_accum.cast(pa.int32()) + else: + data_to_accum = data_to_accum.cast(pa.int64()) + + try: + result = pyarrow_meth(data_to_accum, skip_nulls=skipna, **kwargs) + except pa.ArrowNotImplementedError as err: + msg = f"operation '{name}' not supported for dtype '{self.dtype}'" + raise TypeError(msg) from err + + if convert_to_int: + result = result.cast(pa_dtype) + + return type(self)(result) + + def _str_accumulate( + self, name: str, *, skipna: bool = True, **kwargs + ) -> ArrowExtensionArray | ExtensionArray: + """ + Accumulate implementation for strings, see `_accumulate` docstring for details. + + pyarrow.compute does not implement these methods for strings. + """ + if name == "cumprod": + msg = f"operation '{name}' not supported for dtype '{self.dtype}'" + raise TypeError(msg) + + # We may need to strip out trailing NA values + tail: pa.array | None = None + na_mask: pa.array | None = None + pa_array = self._pa_array + np_func = { + "cumsum": np.cumsum, + "cummin": np.minimum.accumulate, + "cummax": np.maximum.accumulate, + }[name] + + if self._hasna: + na_mask = pc.is_null(pa_array) + if pc.all(na_mask) == pa.scalar(True): + return type(self)(pa_array) + if skipna: + if name == "cumsum": + pa_array = pc.fill_null(pa_array, "") + else: + # We can retain the running min/max by forward/backward filling. + pa_array = pc.fill_null_forward(pa_array) + pa_array = pc.fill_null_backward(pa_array) + else: + # When not skipping NA values, the result should be null from + # the first NA value onward. + idx = pc.index(na_mask, True).as_py() + tail = pa.nulls(len(pa_array) - idx, type=pa_array.type) + pa_array = pa_array[:idx] + + # error: Cannot call function of unknown type + pa_result = pa.array(np_func(pa_array), type=pa_array.type) # type: ignore[operator] + + if tail is not None: + pa_result = pa.concat_arrays([pa_result, tail]) + elif na_mask is not None: + pa_result = pc.if_else(na_mask, None, pa_result) + + result = type(self)(pa_result) + return result + + def _reduce_pyarrow(self, name: str, *, skipna: bool = True, **kwargs) -> pa.Scalar: + """ + Return a pyarrow scalar result of performing the reduction operation. + + Parameters + ---------- + name : str + Name of the function, supported values are: + { any, all, min, max, sum, mean, median, prod, + std, var, sem, kurt, skew }. + skipna : bool, default True + If True, skip NaN values. + **kwargs + Additional keyword arguments passed to the reduction function. + Currently, `ddof` is the only supported kwarg. + + Returns + ------- + pyarrow scalar + + Raises + ------ + TypeError : subclass does not define reductions + """ + pa_type = self._pa_array.type + + data_to_reduce = self._pa_array + + cast_kwargs = {} if pa_version_under13p0 else {"safe": False} + + if name in ["any", "all"] and ( + pa.types.is_integer(pa_type) + or pa.types.is_floating(pa_type) + or pa.types.is_duration(pa_type) + or pa.types.is_decimal(pa_type) + ): + # pyarrow only supports any/all for boolean dtype, we allow + # for other dtypes, matching our non-pyarrow behavior + + if pa.types.is_duration(pa_type): + data_to_cmp = self._pa_array.cast(pa.int64()) + else: + data_to_cmp = self._pa_array + + not_eq = pc.not_equal(data_to_cmp, 0) + data_to_reduce = not_eq + + elif name in ["min", "max", "sum"] and pa.types.is_duration(pa_type): + data_to_reduce = self._pa_array.cast(pa.int64()) + + elif name in ["median", "mean", "std", "sem"] and pa.types.is_temporal(pa_type): + nbits = pa_type.bit_width + if nbits == 32: + data_to_reduce = self._pa_array.cast(pa.int32()) + else: + data_to_reduce = self._pa_array.cast(pa.int64()) + + if name == "sem": + + def pyarrow_meth(data, skip_nulls, **kwargs): + numerator = pc.stddev(data, skip_nulls=skip_nulls, **kwargs) + denominator = pc.sqrt_checked(pc.count(self._pa_array)) + return pc.divide_checked(numerator, denominator) + + elif name == "sum" and ( + pa.types.is_string(pa_type) or pa.types.is_large_string(pa_type) + ): + + def pyarrow_meth(data, skip_nulls, min_count=0): # type: ignore[misc] + mask = pc.is_null(data) if data.null_count > 0 else None + if skip_nulls: + if min_count > 0 and check_below_min_count( + (len(data),), + None if mask is None else mask.to_numpy(), + min_count, + ): + return pa.scalar(None, type=data.type) + if data.null_count > 0: + # binary_join returns null if there is any null -> + # have to filter out any nulls + data = data.filter(pc.invert(mask)) + else: + if mask is not None or check_below_min_count( + (len(data),), None, min_count + ): + return pa.scalar(None, type=data.type) + + if pa.types.is_large_string(data.type): + # binary_join only supports string, not large_string + data = data.cast(pa.string()) + data_list = pa.ListArray.from_arrays( + [0, len(data)], data.combine_chunks() + )[0] + return pc.binary_join(data_list, "") + + else: + pyarrow_name = { + "median": "quantile", + "prod": "product", + "std": "stddev", + "var": "variance", + }.get(name, name) + # error: Incompatible types in assignment + # (expression has type "Optional[Any]", variable has type + # "Callable[[Any, Any, KwArg(Any)], Any]") + pyarrow_meth = getattr(pc, pyarrow_name, None) # type: ignore[assignment] + if pyarrow_meth is None: + # Let ExtensionArray._reduce raise the TypeError + return super()._reduce(name, skipna=skipna, **kwargs) + + # GH51624: pyarrow defaults to min_count=1, pandas behavior is min_count=0 + if name in ["any", "all"] and "min_count" not in kwargs: + kwargs["min_count"] = 0 + elif name == "median": + # GH 52679: Use quantile instead of approximate_median + kwargs["q"] = 0.5 + + try: + result = pyarrow_meth(data_to_reduce, skip_nulls=skipna, **kwargs) + except (AttributeError, NotImplementedError, TypeError) as err: + msg = ( + f"'{type(self).__name__}' with dtype {self.dtype} " + f"does not support reduction '{name}' with pyarrow " + f"version {pa.__version__}. '{name}' may be supported by " + f"upgrading pyarrow." + ) + raise TypeError(msg) from err + if name == "median": + # GH 52679: Use quantile instead of approximate_median; returns array + result = result[0] + if pc.is_null(result).as_py(): + return result + + if name in ["min", "max", "sum"] and pa.types.is_duration(pa_type): + result = result.cast(pa_type) + if name in ["median", "mean"] and pa.types.is_temporal(pa_type): + if not pa_version_under13p0: + nbits = pa_type.bit_width + if nbits == 32: + result = result.cast(pa.int32(), **cast_kwargs) + else: + result = result.cast(pa.int64(), **cast_kwargs) + result = result.cast(pa_type) + if name in ["std", "sem"] and pa.types.is_temporal(pa_type): + result = result.cast(pa.int64(), **cast_kwargs) + if pa.types.is_duration(pa_type): + result = result.cast(pa_type) + elif pa.types.is_time(pa_type): + unit = get_unit_from_pa_dtype(pa_type) + result = result.cast(pa.duration(unit)) + elif pa.types.is_date(pa_type): + # go with closest available unit, i.e. "s" + result = result.cast(pa.duration("s")) + else: + # i.e. timestamp + result = result.cast(pa.duration(pa_type.unit)) + + return result + + def _reduce( + self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs + ): + """ + Return a scalar result of performing the reduction operation. + + Parameters + ---------- + name : str + Name of the function, supported values are: + { any, all, min, max, sum, mean, median, prod, + std, var, sem, kurt, skew }. + skipna : bool, default True + If True, skip NaN values. + **kwargs + Additional keyword arguments passed to the reduction function. + Currently, `ddof` is the only supported kwarg. + + Returns + ------- + scalar + + Raises + ------ + TypeError : subclass does not define reductions + """ + result = self._reduce_calc(name, skipna=skipna, keepdims=keepdims, **kwargs) + if isinstance(result, pa.Array): + return type(self)(result) + else: + return result + + def _reduce_calc( + self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs + ): + pa_result = self._reduce_pyarrow(name, skipna=skipna, **kwargs) + + if keepdims: + if isinstance(pa_result, pa.Scalar): + result = pa.array([pa_result.as_py()], type=pa_result.type) + else: + result = pa.array( + [pa_result], + type=to_pyarrow_type(infer_dtype_from_scalar(pa_result)[0]), + ) + return result + + if pc.is_null(pa_result).as_py(): + return self.dtype.na_value + elif isinstance(pa_result, pa.Scalar): + return pa_result.as_py() + else: + return pa_result + + def _explode(self): + """ + See Series.explode.__doc__. + """ + # child class explode method supports only list types; return + # default implementation for non list types. + if not hasattr(self.dtype, "pyarrow_dtype") or ( + not pa.types.is_list(self.dtype.pyarrow_dtype) + ): + return super()._explode() + values = self + counts = pa.compute.list_value_length(values._pa_array) + counts = counts.fill_null(1).to_numpy() + fill_value = pa.scalar([None], type=self._pa_array.type) + mask = counts == 0 + if mask.any(): + values = values.copy() + values[mask] = fill_value + counts = counts.copy() + counts[mask] = 1 + values = values.fillna(fill_value) + values = type(self)(pa.compute.list_flatten(values._pa_array)) + return values, counts + + def __setitem__(self, key, value) -> None: + """Set one or more values inplace. + + Parameters + ---------- + key : int, ndarray, or slice + When called from, e.g. ``Series.__setitem__``, ``key`` will be + one of + + * scalar int + * ndarray of integers. + * boolean ndarray + * slice object + + value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object + value or values to be set of ``key``. + + Returns + ------- + None + """ + # GH50085: unwrap 1D indexers + if isinstance(key, tuple) and len(key) == 1: + key = key[0] + + key = check_array_indexer(self, key) + value = self._maybe_convert_setitem_value(value) + + if com.is_null_slice(key): + # fast path (GH50248) + data = self._if_else(True, value, self._pa_array) + + elif is_integer(key): + # fast path + key = cast(int, key) + n = len(self) + if key < 0: + key += n + if not 0 <= key < n: + raise IndexError( + f"index {key} is out of bounds for axis 0 with size {n}" + ) + if isinstance(value, pa.Scalar): + value = value.as_py() + elif is_list_like(value): + raise ValueError("Length of indexer and values mismatch") + chunks = [ + *self._pa_array[:key].chunks, + pa.array([value], type=self._pa_array.type, from_pandas=True), + *self._pa_array[key + 1 :].chunks, + ] + data = pa.chunked_array(chunks).combine_chunks() + + elif is_bool_dtype(key): + key = np.asarray(key, dtype=np.bool_) + data = self._replace_with_mask(self._pa_array, key, value) + + elif is_scalar(value) or isinstance(value, pa.Scalar): + mask = np.zeros(len(self), dtype=np.bool_) + mask[key] = True + data = self._if_else(mask, value, self._pa_array) + + else: + indices = np.arange(len(self))[key] + if len(indices) != len(value): + raise ValueError("Length of indexer and values mismatch") + if len(indices) == 0: + return + argsort = np.argsort(indices) + indices = indices[argsort] + value = value.take(argsort) + mask = np.zeros(len(self), dtype=np.bool_) + mask[indices] = True + data = self._replace_with_mask(self._pa_array, mask, value) + + if isinstance(data, pa.Array): + data = pa.chunked_array([data]) + self._pa_array = data + + def _rank_calc( + self, + *, + axis: AxisInt = 0, + method: str = "average", + na_option: str = "keep", + ascending: bool = True, + pct: bool = False, + ): + if axis != 0: + ranked = super()._rank( + axis=axis, + method=method, + na_option=na_option, + ascending=ascending, + pct=pct, + ) + # keep dtypes consistent with the implementation below + if method == "average" or pct: + pa_type = pa.float64() + else: + pa_type = pa.uint64() + result = pa.array(ranked, type=pa_type, from_pandas=True) + return result + + data = self._pa_array.combine_chunks() + sort_keys = "ascending" if ascending else "descending" + null_placement = "at_start" if na_option == "top" else "at_end" + tiebreaker = "min" if method == "average" else method + + result = pc.rank( + data, + sort_keys=sort_keys, + null_placement=null_placement, + tiebreaker=tiebreaker, + ) + + if na_option == "keep": + mask = pc.is_null(self._pa_array) + null = pa.scalar(None, type=result.type) + result = pc.if_else(mask, null, result) + + if method == "average": + result_max = pc.rank( + data, + sort_keys=sort_keys, + null_placement=null_placement, + tiebreaker="max", + ) + result_max = result_max.cast(pa.float64()) + result_min = result.cast(pa.float64()) + result = pc.divide(pc.add(result_min, result_max), 2) + + if pct: + if not pa.types.is_floating(result.type): + result = result.cast(pa.float64()) + if method == "dense": + divisor = pc.max(result) + else: + divisor = pc.count(result) + result = pc.divide(result, divisor) + + return result + + def _rank( + self, + *, + axis: AxisInt = 0, + method: str = "average", + na_option: str = "keep", + ascending: bool = True, + pct: bool = False, + ): + """ + See Series.rank.__doc__. + """ + return self._convert_rank_result( + self._rank_calc( + axis=axis, + method=method, + na_option=na_option, + ascending=ascending, + pct=pct, + ) + ) + + def _quantile(self, qs: npt.NDArray[np.float64], interpolation: str) -> Self: + """ + Compute the quantiles of self for each quantile in `qs`. + + Parameters + ---------- + qs : np.ndarray[float64] + interpolation: str + + Returns + ------- + same type as self + """ + pa_dtype = self._pa_array.type + + data = self._pa_array + if pa.types.is_temporal(pa_dtype): + # https://github.com/apache/arrow/issues/33769 in these cases + # we can cast to ints and back + nbits = pa_dtype.bit_width + if nbits == 32: + data = data.cast(pa.int32()) + else: + data = data.cast(pa.int64()) + + result = pc.quantile(data, q=qs, interpolation=interpolation) + + if pa.types.is_temporal(pa_dtype): + if pa.types.is_floating(result.type): + result = pc.floor(result) + nbits = pa_dtype.bit_width + if nbits == 32: + result = result.cast(pa.int32()) + else: + result = result.cast(pa.int64()) + result = result.cast(pa_dtype) + + return type(self)(result) + + def _mode(self, dropna: bool = True) -> Self: + """ + Returns the mode(s) of the ExtensionArray. + + Always returns `ExtensionArray` even if only one value. + + Parameters + ---------- + dropna : bool, default True + Don't consider counts of NA values. + + Returns + ------- + same type as self + Sorted, if possible. + """ + pa_type = self._pa_array.type + if pa.types.is_temporal(pa_type): + nbits = pa_type.bit_width + if nbits == 32: + data = self._pa_array.cast(pa.int32()) + elif nbits == 64: + data = self._pa_array.cast(pa.int64()) + else: + raise NotImplementedError(pa_type) + else: + data = self._pa_array + + if dropna: + data = data.drop_null() + + res = pc.value_counts(data) + most_common = res.field("values").filter( + pc.equal(res.field("counts"), pc.max(res.field("counts"))) + ) + + if pa.types.is_temporal(pa_type): + most_common = most_common.cast(pa_type) + + most_common = most_common.take(pc.array_sort_indices(most_common)) + return type(self)(most_common) + + def _maybe_convert_setitem_value(self, value): + """Maybe convert value to be pyarrow compatible.""" + try: + value = self._box_pa(value, self._pa_array.type) + except pa.ArrowTypeError as err: + msg = f"Invalid value '{value!s}' for dtype '{self.dtype}'" + raise TypeError(msg) from err + return value + + def interpolate( + self, + *, + method: InterpolateOptions, + axis: int, + index, + limit, + limit_direction, + limit_area, + copy: bool, + **kwargs, + ) -> Self: + """ + See NDFrame.interpolate.__doc__. + """ + # NB: we return type(self) even if copy=False + if not self.dtype._is_numeric: + raise TypeError(f"Cannot interpolate with {self.dtype} dtype") + + mask = self.isna() + if self.dtype.kind == "f": + data = self._pa_array.to_numpy() + elif self.dtype.kind in "iu": + data = self.to_numpy(dtype="f8", na_value=0.0) + else: + raise NotImplementedError( + f"interpolate is not implemented for dtype={self.dtype}" + ) + + missing.interpolate_2d_inplace( + data, + method=method, + axis=0, + index=index, + limit=limit, + limit_direction=limit_direction, + limit_area=limit_area, + mask=mask, + **kwargs, + ) + return type(self)(self._box_pa_array(pa.array(data, mask=mask))) + + @classmethod + def _if_else( + cls, + cond: npt.NDArray[np.bool_] | bool, + left: ArrayLike | Scalar, + right: ArrayLike | Scalar, + ): + """ + Choose values based on a condition. + + Analogous to pyarrow.compute.if_else, with logic + to fallback to numpy for unsupported types. + + Parameters + ---------- + cond : npt.NDArray[np.bool_] or bool + left : ArrayLike | Scalar + right : ArrayLike | Scalar + + Returns + ------- + pa.Array + """ + try: + return pc.if_else(cond, left, right) + except pa.ArrowNotImplementedError: + pass + + def _to_numpy_and_type(value) -> tuple[np.ndarray, pa.DataType | None]: + if isinstance(value, (pa.Array, pa.ChunkedArray)): + pa_type = value.type + elif isinstance(value, pa.Scalar): + pa_type = value.type + value = value.as_py() + else: + pa_type = None + return np.array(value, dtype=object), pa_type + + left, left_type = _to_numpy_and_type(left) + right, right_type = _to_numpy_and_type(right) + pa_type = left_type or right_type + result = np.where(cond, left, right) + return pa.array(result, type=pa_type, from_pandas=True) + + @classmethod + def _replace_with_mask( + cls, + values: pa.Array | pa.ChunkedArray, + mask: npt.NDArray[np.bool_] | bool, + replacements: ArrayLike | Scalar, + ): + """ + Replace items selected with a mask. + + Analogous to pyarrow.compute.replace_with_mask, with logic + to fallback to numpy for unsupported types. + + Parameters + ---------- + values : pa.Array or pa.ChunkedArray + mask : npt.NDArray[np.bool_] or bool + replacements : ArrayLike or Scalar + Replacement value(s) + + Returns + ------- + pa.Array or pa.ChunkedArray + """ + if isinstance(replacements, pa.ChunkedArray): + # replacements must be array or scalar, not ChunkedArray + replacements = replacements.combine_chunks() + if isinstance(values, pa.ChunkedArray) and pa.types.is_boolean(values.type): + # GH#52059 replace_with_mask segfaults for chunked array + # https://github.com/apache/arrow/issues/34634 + values = values.combine_chunks() + try: + return pc.replace_with_mask(values, mask, replacements) + except pa.ArrowNotImplementedError: + pass + if isinstance(replacements, pa.Array): + replacements = np.array(replacements, dtype=object) + elif isinstance(replacements, pa.Scalar): + replacements = replacements.as_py() + result = np.array(values, dtype=object) + result[mask] = replacements + return pa.array(result, type=values.type, from_pandas=True) + + # ------------------------------------------------------------------ + # GroupBy Methods + + def _to_masked(self): + pa_dtype = self._pa_array.type + + if pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype): + na_value = 1 + elif pa.types.is_boolean(pa_dtype): + na_value = True + else: + raise NotImplementedError + + dtype = _arrow_dtype_mapping()[pa_dtype] + mask = self.isna() + arr = self.to_numpy(dtype=dtype.numpy_dtype, na_value=na_value) + return dtype.construct_array_type()(arr, mask) + + def _groupby_op( + self, + *, + how: str, + has_dropped_na: bool, + min_count: int, + ngroups: int, + ids: npt.NDArray[np.intp], + **kwargs, + ): + if isinstance(self.dtype, StringDtype): + if how in [ + "prod", + "mean", + "median", + "cumsum", + "cumprod", + "std", + "sem", + "var", + "skew", + ]: + raise TypeError( + f"dtype '{self.dtype}' does not support operation '{how}'" + ) + return super()._groupby_op( + how=how, + has_dropped_na=has_dropped_na, + min_count=min_count, + ngroups=ngroups, + ids=ids, + **kwargs, + ) + + # maybe convert to a compatible dtype optimized for groupby + values: ExtensionArray + pa_type = self._pa_array.type + if pa.types.is_timestamp(pa_type): + values = self._to_datetimearray() + elif pa.types.is_duration(pa_type): + values = self._to_timedeltaarray() + else: + values = self._to_masked() + + result = values._groupby_op( + how=how, + has_dropped_na=has_dropped_na, + min_count=min_count, + ngroups=ngroups, + ids=ids, + **kwargs, + ) + if isinstance(result, np.ndarray): + return result + return type(self)._from_sequence(result, copy=False) + + def _apply_elementwise(self, func: Callable) -> list[list[Any]]: + """Apply a callable to each element while maintaining the chunking structure.""" + return [ + [ + None if val is None else func(val) + for val in chunk.to_numpy(zero_copy_only=False) + ] + for chunk in self._pa_array.iterchunks() + ] + + def _convert_bool_result(self, result, na=lib.no_default, method_name=None): + if na is not lib.no_default and not isna( + na + ): # pyright: ignore [reportGeneralTypeIssues] + result = result.fill_null(na) + return type(self)(result) + + def _convert_int_result(self, result): + return type(self)(result) + + def _convert_rank_result(self, result): + return type(self)(result) + + def _str_count(self, pat: str, flags: int = 0): + if flags: + raise NotImplementedError(f"count not implemented with {flags=}") + return type(self)(pc.count_substring_regex(self._pa_array, pat)) + + def _str_repeat(self, repeats: int | Sequence[int]): + if not isinstance(repeats, int): + raise NotImplementedError( + f"repeat is not implemented when repeats is {type(repeats).__name__}" + ) + else: + return type(self)(pc.binary_repeat(self._pa_array, repeats)) + + def _str_join(self, sep: str): + if pa.types.is_string(self._pa_array.type) or pa.types.is_large_string( + self._pa_array.type + ): + result = self._apply_elementwise(list) + result = pa.chunked_array(result, type=pa.list_(pa.string())) + else: + result = self._pa_array + return type(self)(pc.binary_join(result, sep)) + + def _str_partition(self, sep: str, expand: bool): + predicate = lambda val: val.partition(sep) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_rpartition(self, sep: str, expand: bool): + predicate = lambda val: val.rpartition(sep) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_casefold(self): + predicate = lambda val: val.casefold() + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_encode(self, encoding: str, errors: str = "strict"): + predicate = lambda val: val.encode(encoding, errors) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_extract(self, pat: str, flags: int = 0, expand: bool = True): + if flags: + raise NotImplementedError("Only flags=0 is implemented.") + groups = re.compile(pat).groupindex.keys() + if len(groups) == 0: + raise ValueError(f"{pat=} must contain a symbolic group name.") + result = pc.extract_regex(self._pa_array, pat) + if expand: + return { + col: type(self)(pc.struct_field(result, [i])) + for col, i in zip(groups, range(result.type.num_fields)) + } + else: + return type(self)(pc.struct_field(result, [0])) + + def _str_findall(self, pat: str, flags: int = 0): + regex = re.compile(pat, flags=flags) + predicate = lambda val: regex.findall(val) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_get_dummies(self, sep: str = "|"): + split = pc.split_pattern(self._pa_array, sep) + flattened_values = pc.list_flatten(split) + uniques = flattened_values.unique() + uniques_sorted = uniques.take(pa.compute.array_sort_indices(uniques)) + lengths = pc.list_value_length(split).fill_null(0).to_numpy() + n_rows = len(self) + n_cols = len(uniques) + indices = pc.index_in(flattened_values, uniques_sorted).to_numpy() + indices = indices + np.arange(n_rows).repeat(lengths) * n_cols + dummies = np.zeros(n_rows * n_cols, dtype=np.bool_) + dummies[indices] = True + dummies = dummies.reshape((n_rows, n_cols)) + result = type(self)(pa.array(list(dummies))) + return result, uniques_sorted.to_pylist() + + def _str_index(self, sub: str, start: int = 0, end: int | None = None): + predicate = lambda val: val.index(sub, start, end) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_rindex(self, sub: str, start: int = 0, end: int | None = None): + predicate = lambda val: val.rindex(sub, start, end) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_normalize(self, form: str): + predicate = lambda val: unicodedata.normalize(form, val) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_rfind(self, sub: str, start: int = 0, end=None): + predicate = lambda val: val.rfind(sub, start, end) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_split( + self, + pat: str | None = None, + n: int | None = -1, + expand: bool = False, + regex: bool | None = None, + ): + if n in {-1, 0}: + n = None + if pat is None: + split_func = pc.utf8_split_whitespace + elif regex: + split_func = functools.partial(pc.split_pattern_regex, pattern=pat) + else: + split_func = functools.partial(pc.split_pattern, pattern=pat) + return type(self)(split_func(self._pa_array, max_splits=n)) + + def _str_rsplit(self, pat: str | None = None, n: int | None = -1): + if n in {-1, 0}: + n = None + if pat is None: + return type(self)( + pc.utf8_split_whitespace(self._pa_array, max_splits=n, reverse=True) + ) + else: + return type(self)( + pc.split_pattern(self._pa_array, pat, max_splits=n, reverse=True) + ) + + def _str_translate(self, table: dict[int, str]): + predicate = lambda val: val.translate(table) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + def _str_wrap(self, width: int, **kwargs): + kwargs["width"] = width + tw = textwrap.TextWrapper(**kwargs) + predicate = lambda val: "\n".join(tw.wrap(val)) + result = self._apply_elementwise(predicate) + return type(self)(pa.chunked_array(result)) + + @property + def _dt_days(self): + return type(self)( + pa.array(self._to_timedeltaarray().days, from_pandas=True, type=pa.int32()) + ) + + @property + def _dt_hours(self): + return type(self)( + pa.array( + [ + td.components.hours if td is not NaT else None + for td in self._to_timedeltaarray() + ], + type=pa.int32(), + ) + ) + + @property + def _dt_minutes(self): + return type(self)( + pa.array( + [ + td.components.minutes if td is not NaT else None + for td in self._to_timedeltaarray() + ], + type=pa.int32(), + ) + ) + + @property + def _dt_seconds(self): + return type(self)( + pa.array( + self._to_timedeltaarray().seconds, from_pandas=True, type=pa.int32() + ) + ) + + @property + def _dt_milliseconds(self): + return type(self)( + pa.array( + [ + td.components.milliseconds if td is not NaT else None + for td in self._to_timedeltaarray() + ], + type=pa.int32(), + ) + ) + + @property + def _dt_microseconds(self): + return type(self)( + pa.array( + self._to_timedeltaarray().microseconds, + from_pandas=True, + type=pa.int32(), + ) + ) + + @property + def _dt_nanoseconds(self): + return type(self)( + pa.array( + self._to_timedeltaarray().nanoseconds, from_pandas=True, type=pa.int32() + ) + ) + + def _dt_to_pytimedelta(self): + data = self._pa_array.to_pylist() + if self._dtype.pyarrow_dtype.unit == "ns": + data = [None if ts is None else ts.to_pytimedelta() for ts in data] + return np.array(data, dtype=object) + + def _dt_total_seconds(self): + return type(self)( + pa.array(self._to_timedeltaarray().total_seconds(), from_pandas=True) + ) + + def _dt_as_unit(self, unit: str): + if pa.types.is_date(self.dtype.pyarrow_dtype): + raise NotImplementedError("as_unit not implemented for date types") + pd_array = self._maybe_convert_datelike_array() + # Don't just cast _pa_array in order to follow pandas unit conversion rules + return type(self)(pa.array(pd_array.as_unit(unit), from_pandas=True)) + + @property + def _dt_year(self): + return type(self)(pc.year(self._pa_array)) + + @property + def _dt_day(self): + return type(self)(pc.day(self._pa_array)) + + @property + def _dt_day_of_week(self): + return type(self)(pc.day_of_week(self._pa_array)) + + _dt_dayofweek = _dt_day_of_week + _dt_weekday = _dt_day_of_week + + @property + def _dt_day_of_year(self): + return type(self)(pc.day_of_year(self._pa_array)) + + _dt_dayofyear = _dt_day_of_year + + @property + def _dt_hour(self): + return type(self)(pc.hour(self._pa_array)) + + def _dt_isocalendar(self): + return type(self)(pc.iso_calendar(self._pa_array)) + + @property + def _dt_is_leap_year(self): + return type(self)(pc.is_leap_year(self._pa_array)) + + @property + def _dt_is_month_start(self): + return type(self)(pc.equal(pc.day(self._pa_array), 1)) + + @property + def _dt_is_month_end(self): + result = pc.equal( + pc.days_between( + pc.floor_temporal(self._pa_array, unit="day"), + pc.ceil_temporal(self._pa_array, unit="month"), + ), + 1, + ) + return type(self)(result) + + @property + def _dt_is_year_start(self): + return type(self)( + pc.and_( + pc.equal(pc.month(self._pa_array), 1), + pc.equal(pc.day(self._pa_array), 1), + ) + ) + + @property + def _dt_is_year_end(self): + return type(self)( + pc.and_( + pc.equal(pc.month(self._pa_array), 12), + pc.equal(pc.day(self._pa_array), 31), + ) + ) + + @property + def _dt_is_quarter_start(self): + result = pc.equal( + pc.floor_temporal(self._pa_array, unit="quarter"), + pc.floor_temporal(self._pa_array, unit="day"), + ) + return type(self)(result) + + @property + def _dt_is_quarter_end(self): + result = pc.equal( + pc.days_between( + pc.floor_temporal(self._pa_array, unit="day"), + pc.ceil_temporal(self._pa_array, unit="quarter"), + ), + 1, + ) + return type(self)(result) + + @property + def _dt_days_in_month(self): + result = pc.days_between( + pc.floor_temporal(self._pa_array, unit="month"), + pc.ceil_temporal(self._pa_array, unit="month"), + ) + return type(self)(result) + + _dt_daysinmonth = _dt_days_in_month + + @property + def _dt_microsecond(self): + return type(self)(pc.microsecond(self._pa_array)) + + @property + def _dt_minute(self): + return type(self)(pc.minute(self._pa_array)) + + @property + def _dt_month(self): + return type(self)(pc.month(self._pa_array)) + + @property + def _dt_nanosecond(self): + return type(self)(pc.nanosecond(self._pa_array)) + + @property + def _dt_quarter(self): + return type(self)(pc.quarter(self._pa_array)) + + @property + def _dt_second(self): + return type(self)(pc.second(self._pa_array)) + + @property + def _dt_date(self): + return type(self)(self._pa_array.cast(pa.date32())) + + @property + def _dt_time(self): + unit = ( + self.dtype.pyarrow_dtype.unit + if self.dtype.pyarrow_dtype.unit in {"us", "ns"} + else "ns" + ) + return type(self)(self._pa_array.cast(pa.time64(unit))) + + @property + def _dt_tz(self): + return timezones.maybe_get_tz(self.dtype.pyarrow_dtype.tz) + + @property + def _dt_unit(self): + return self.dtype.pyarrow_dtype.unit + + def _dt_normalize(self): + return type(self)(pc.floor_temporal(self._pa_array, 1, "day")) + + def _dt_strftime(self, format: str): + return type(self)(pc.strftime(self._pa_array, format=format)) + + def _round_temporally( + self, + method: Literal["ceil", "floor", "round"], + freq, + ambiguous: TimeAmbiguous = "raise", + nonexistent: TimeNonexistent = "raise", + ): + if ambiguous != "raise": + raise NotImplementedError("ambiguous is not supported.") + if nonexistent != "raise": + raise NotImplementedError("nonexistent is not supported.") + offset = to_offset(freq) + if offset is None: + raise ValueError(f"Must specify a valid frequency: {freq}") + pa_supported_unit = { + "Y": "year", + "YS": "year", + "Q": "quarter", + "QS": "quarter", + "M": "month", + "MS": "month", + "W": "week", + "D": "day", + "h": "hour", + "min": "minute", + "s": "second", + "ms": "millisecond", + "us": "microsecond", + "ns": "nanosecond", + } + unit = pa_supported_unit.get(offset._prefix, None) + if unit is None: + raise ValueError(f"{freq=} is not supported") + multiple = offset.n + rounding_method = getattr(pc, f"{method}_temporal") + return type(self)(rounding_method(self._pa_array, multiple=multiple, unit=unit)) + + def _dt_ceil( + self, + freq, + ambiguous: TimeAmbiguous = "raise", + nonexistent: TimeNonexistent = "raise", + ): + return self._round_temporally("ceil", freq, ambiguous, nonexistent) + + def _dt_floor( + self, + freq, + ambiguous: TimeAmbiguous = "raise", + nonexistent: TimeNonexistent = "raise", + ): + return self._round_temporally("floor", freq, ambiguous, nonexistent) + + def _dt_round( + self, + freq, + ambiguous: TimeAmbiguous = "raise", + nonexistent: TimeNonexistent = "raise", + ): + return self._round_temporally("round", freq, ambiguous, nonexistent) + + def _dt_day_name(self, locale: str | None = None): + if locale is None: + locale = "C" + return type(self)(pc.strftime(self._pa_array, format="%A", locale=locale)) + + def _dt_month_name(self, locale: str | None = None): + if locale is None: + locale = "C" + return type(self)(pc.strftime(self._pa_array, format="%B", locale=locale)) + + def _dt_to_pydatetime(self): + if pa.types.is_date(self.dtype.pyarrow_dtype): + raise ValueError( + f"to_pydatetime cannot be called with {self.dtype.pyarrow_dtype} type. " + "Convert to pyarrow timestamp type." + ) + data = self._pa_array.to_pylist() + if self._dtype.pyarrow_dtype.unit == "ns": + data = [None if ts is None else ts.to_pydatetime(warn=False) for ts in data] + return np.array(data, dtype=object) + + def _dt_tz_localize( + self, + tz, + ambiguous: TimeAmbiguous = "raise", + nonexistent: TimeNonexistent = "raise", + ): + if ambiguous != "raise": + raise NotImplementedError(f"{ambiguous=} is not supported") + nonexistent_pa = { + "raise": "raise", + "shift_backward": "earliest", + "shift_forward": "latest", + }.get( + nonexistent, None # type: ignore[arg-type] + ) + if nonexistent_pa is None: + raise NotImplementedError(f"{nonexistent=} is not supported") + if tz is None: + result = self._pa_array.cast(pa.timestamp(self.dtype.pyarrow_dtype.unit)) + else: + result = pc.assume_timezone( + self._pa_array, str(tz), ambiguous=ambiguous, nonexistent=nonexistent_pa + ) + return type(self)(result) + + def _dt_tz_convert(self, tz): + if self.dtype.pyarrow_dtype.tz is None: + raise TypeError( + "Cannot convert tz-naive timestamps, use tz_localize to localize" + ) + current_unit = self.dtype.pyarrow_dtype.unit + result = self._pa_array.cast(pa.timestamp(current_unit, tz)) + return type(self)(result) + + +def transpose_homogeneous_pyarrow( + arrays: Sequence[ArrowExtensionArray], +) -> list[ArrowExtensionArray]: + """Transpose arrow extension arrays in a list, but faster. + + Input should be a list of arrays of equal length and all have the same + dtype. The caller is responsible for ensuring validity of input data. + """ + arrays = list(arrays) + nrows, ncols = len(arrays[0]), len(arrays) + indices = np.arange(nrows * ncols).reshape(ncols, nrows).T.flatten() + arr = pa.chunked_array([chunk for arr in arrays for chunk in arr._pa_array.chunks]) + arr = arr.take(indices) + return [ArrowExtensionArray(arr.slice(i * ncols, ncols)) for i in range(nrows)] diff --git a/shared/package-files/0b/0b4aa24176a1f4609efbf3a3c48fc8e2a9c783b7703d322243e7f89f97f4b30b/histc_cpu_dispatch.h b/shared/package-files/0b/0b4aa24176a1f4609efbf3a3c48fc8e2a9c783b7703d322243e7f89f97f4b30b/histc_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d1328d6bab03f8e24f8256931f04997facbbde84 --- /dev/null +++ b/shared/package-files/0b/0b4aa24176a1f4609efbf3a3c48fc8e2a9c783b7703d322243e7f89f97f4b30b/histc_cpu_dispatch.h @@ -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 histc(const at::Tensor & self, int64_t bins=100, const at::Scalar & min=0, const at::Scalar & max=0); +TORCH_API at::Tensor & histc_out(at::Tensor & out, const at::Tensor & self, int64_t bins=100, const at::Scalar & min=0, const at::Scalar & max=0); +TORCH_API at::Tensor & histc_outf(const at::Tensor & self, int64_t bins, const at::Scalar & min, const at::Scalar & max, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/0b/0b4abdb730e6c730b52295a234a638965cdca29c7a761a2d18e2e92b537d9b7b/plot_surface.py b/shared/package-files/0b/0b4abdb730e6c730b52295a234a638965cdca29c7a761a2d18e2e92b537d9b7b/plot_surface.py new file mode 100644 index 0000000000000000000000000000000000000000..ed421eebb441d193f4d9b763f56e146c11e5a42c --- /dev/null +++ b/shared/package-files/0b/0b4abdb730e6c730b52295a234a638965cdca29c7a761a2d18e2e92b537d9b7b/plot_surface.py @@ -0,0 +1,102 @@ +import pyglet.gl as pgl + +from sympy.core import S +from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase + + +class PlotSurface(PlotModeBase): + + default_rot_preset = 'perspective' + + def _on_calculate_verts(self): + self.u_interval = self.intervals[0] + self.u_set = list(self.u_interval.frange()) + self.v_interval = self.intervals[1] + self.v_set = list(self.v_interval.frange()) + self.bounds = [[S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0]] + evaluate = self._get_evaluator() + + self._calculating_verts_pos = 0.0 + self._calculating_verts_len = float( + self.u_interval.v_len*self.v_interval.v_len) + + verts = [] + b = self.bounds + for u in self.u_set: + column = [] + for v in self.v_set: + try: + _e = evaluate(u, v) # calculate vertex + except ZeroDivisionError: + _e = None + if _e is not None: # update bounding box + for axis in range(3): + b[axis][0] = min([b[axis][0], _e[axis]]) + b[axis][1] = max([b[axis][1], _e[axis]]) + column.append(_e) + self._calculating_verts_pos += 1.0 + + verts.append(column) + for axis in range(3): + b[axis][2] = b[axis][1] - b[axis][0] + if b[axis][2] == 0.0: + b[axis][2] = 1.0 + + self.verts = verts + self.push_wireframe(self.draw_verts(False, False)) + self.push_solid(self.draw_verts(False, True)) + + def _on_calculate_cverts(self): + if not self.verts or not self.color: + return + + def set_work_len(n): + self._calculating_cverts_len = float(n) + + def inc_work_pos(): + self._calculating_cverts_pos += 1.0 + set_work_len(1) + self._calculating_cverts_pos = 0 + self.cverts = self.color.apply_to_surface(self.verts, + self.u_set, + self.v_set, + set_len=set_work_len, + inc_pos=inc_work_pos) + self.push_solid(self.draw_verts(True, True)) + + def calculate_one_cvert(self, u, v): + vert = self.verts[u][v] + return self.color(vert[0], vert[1], vert[2], + self.u_set[u], self.v_set[v]) + + def draw_verts(self, use_cverts, use_solid_color): + def f(): + for u in range(1, len(self.u_set)): + pgl.glBegin(pgl.GL_QUAD_STRIP) + for v in range(len(self.v_set)): + pa = self.verts[u - 1][v] + pb = self.verts[u][v] + if pa is None or pb is None: + pgl.glEnd() + pgl.glBegin(pgl.GL_QUAD_STRIP) + continue + if use_cverts: + ca = self.cverts[u - 1][v] + cb = self.cverts[u][v] + if ca is None: + ca = (0, 0, 0) + if cb is None: + cb = (0, 0, 0) + else: + if use_solid_color: + ca = cb = self.default_solid_color + else: + ca = cb = self.default_wireframe_color + pgl.glColor3f(*ca) + pgl.glVertex3f(*pa) + pgl.glColor3f(*cb) + pgl.glVertex3f(*pb) + pgl.glEnd() + return f diff --git a/shared/package-files/0b/0b4b0bdd9badc77279e0eec724d8bca9f2fe2352269149107f56a95ae86405f2/lu_unpack_ops.h b/shared/package-files/0b/0b4b0bdd9badc77279e0eec724d8bca9f2fe2352269149107f56a95ae86405f2/lu_unpack_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..87e98c03f6048f6e24c9378434ad3c4243273d37 --- /dev/null +++ b/shared/package-files/0b/0b4b0bdd9badc77279e0eec724d8bca9f2fe2352269149107f56a95ae86405f2/lu_unpack_ops.h @@ -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 lu_unpack { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::lu_unpack") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U)") + static ::std::tuple call(const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots); +}; + +struct TORCH_API lu_unpack_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, bool, at::Tensor &, 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::lu_unpack") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lu_unpack.out(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True, *, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U)") + static ::std::tuple call(const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots, at::Tensor & P, at::Tensor & L, at::Tensor & U); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots, at::Tensor & P, at::Tensor & L, at::Tensor & U); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/0b/0b4bfed8d871fec60bee61d26e6c380ade88bc0f76a0f2eafcf1d386537386c2/_prelu_kernel_backward_cuda_dispatch.h b/shared/package-files/0b/0b4bfed8d871fec60bee61d26e6c380ade88bc0f76a0f2eafcf1d386537386c2/_prelu_kernel_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b3d3acc88549936300923dee53ded8cd81acea0c --- /dev/null +++ b/shared/package-files/0b/0b4bfed8d871fec60bee61d26e6c380ade88bc0f76a0f2eafcf1d386537386c2/_prelu_kernel_backward_cuda_dispatch.h @@ -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 _prelu_kernel_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/0b/0b502a332ddc2f87a46222999afb4e23a9f35200c394484ea154250496f2bf3e/softplus_backward_ops.h b/shared/package-files/0b/0b502a332ddc2f87a46222999afb4e23a9f35200c394484ea154250496f2bf3e/softplus_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7378f288894ebe7be61f5a0854fde530604862e9 --- /dev/null +++ b/shared/package-files/0b/0b502a332ddc2f87a46222999afb4e23a9f35200c394484ea154250496f2bf3e/softplus_backward_ops.h @@ -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 softplus_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Scalar &, 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::softplus_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold, at::Tensor & grad_input); +}; + +struct TORCH_API softplus_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, 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::softplus_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/0b/0b53738cc5852a6d35acf514af5e588f3d56074a466a425079ab493bb1b498db/colorbar.pyi b/shared/package-files/0b/0b53738cc5852a6d35acf514af5e588f3d56074a466a425079ab493bb1b498db/colorbar.pyi new file mode 100644 index 0000000000000000000000000000000000000000..07467ca74f3d5a528f8c1c0859fc25a2eb285664 --- /dev/null +++ b/shared/package-files/0b/0b53738cc5852a6d35acf514af5e588f3d56074a466a425079ab493bb1b498db/colorbar.pyi @@ -0,0 +1,139 @@ +import matplotlib.spines as mspines +from matplotlib import cm, collections, colors, contour, colorizer +from matplotlib.axes import Axes +from matplotlib.axis import Axis +from matplotlib.backend_bases import RendererBase +from matplotlib.patches import Patch +from matplotlib.ticker import Locator, Formatter +from matplotlib.transforms import Bbox + +import numpy as np +from numpy.typing import ArrayLike +from collections.abc import Sequence +from typing import Any, Literal, overload +from .typing import ColorType + +class _ColorbarSpine(mspines.Spines): + def __init__(self, axes: Axes): ... + def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox:... + def set_xy(self, xy: ArrayLike) -> None: ... + def draw(self, renderer: RendererBase | None) -> None:... + + +class Colorbar: + n_rasterize: int + mappable: cm.ScalarMappable | colorizer.ColorizingArtist + ax: Axes + alpha: float | None + cmap: colors.Colormap + norm: colors.Normalize + values: Sequence[float] | None + boundaries: Sequence[float] | None + extend: Literal["neither", "both", "min", "max"] + spacing: Literal["uniform", "proportional"] + orientation: Literal["vertical", "horizontal"] + drawedges: bool + extendfrac: Literal["auto"] | float | Sequence[float] | None + extendrect: bool + solids: None | collections.QuadMesh + solids_patches: list[Patch] + lines: list[collections.LineCollection] + outline: _ColorbarSpine + dividers: collections.LineCollection + ticklocation: Literal["left", "right", "top", "bottom"] + def __init__( + self, + ax: Axes, + mappable: cm.ScalarMappable | colorizer.ColorizingArtist | None = ..., + *, + cmap: str | colors.Colormap | None = ..., + norm: colors.Normalize | None = ..., + alpha: float | None = ..., + values: Sequence[float] | None = ..., + boundaries: Sequence[float] | None = ..., + orientation: Literal["vertical", "horizontal"] | None = ..., + ticklocation: Literal["auto", "left", "right", "top", "bottom"] = ..., + extend: Literal["neither", "both", "min", "max"] | None = ..., + spacing: Literal["uniform", "proportional"] = ..., + ticks: Sequence[float] | Locator | None = ..., + format: str | Formatter | None = ..., + drawedges: bool = ..., + extendfrac: Literal["auto"] | float | Sequence[float] | None = ..., + extendrect: bool = ..., + label: str = ..., + location: Literal["left", "right", "top", "bottom"] | None = ... + ) -> None: ... + @property + def long_axis(self) -> Axis: ... + @property + def locator(self) -> Locator: ... + @locator.setter + def locator(self, loc: Locator) -> None: ... + @property + def minorlocator(self) -> Locator: ... + @minorlocator.setter + def minorlocator(self, loc: Locator) -> None: ... + @property + def formatter(self) -> Formatter: ... + @formatter.setter + def formatter(self, fmt: Formatter) -> None: ... + @property + def minorformatter(self) -> Formatter: ... + @minorformatter.setter + def minorformatter(self, fmt: Formatter) -> None: ... + def update_normal(self, mappable: cm.ScalarMappable | None = ...) -> None: ... + @overload + def add_lines(self, CS: contour.ContourSet, erase: bool = ...) -> None: ... + @overload + def add_lines( + self, + levels: ArrayLike, + colors: ColorType | Sequence[ColorType], + linewidths: float | ArrayLike, + erase: bool = ..., + ) -> None: ... + def update_ticks(self) -> None: ... + def set_ticks( + self, + ticks: Sequence[float] | Locator, + *, + labels: Sequence[str] | None = ..., + minor: bool = ..., + **kwargs + ) -> None: ... + def get_ticks(self, minor: bool = ...) -> np.ndarray: ... + def set_ticklabels( + self, + ticklabels: Sequence[str], + *, + minor: bool = ..., + **kwargs + ) -> None: ... + def minorticks_on(self) -> None: ... + def minorticks_off(self) -> None: ... + def set_label(self, label: str, *, loc: str | None = ..., **kwargs) -> None: ... + def set_alpha(self, alpha: float | np.ndarray) -> None: ... + def remove(self) -> None: ... + def drag_pan(self, button: Any, key: Any, x: float, y: float) -> None: ... + +ColorbarBase = Colorbar + +def make_axes( + parents: Axes | list[Axes] | np.ndarray, + location: Literal["left", "right", "top", "bottom"] | None = ..., + orientation: Literal["vertical", "horizontal"] | None = ..., + fraction: float = ..., + shrink: float = ..., + aspect: float = ..., + **kwargs +) -> tuple[Axes, dict[str, Any]]: ... +def make_axes_gridspec( + parent: Axes, + *, + location: Literal["left", "right", "top", "bottom"] | None = ..., + orientation: Literal["vertical", "horizontal"] | None = ..., + fraction: float = ..., + shrink: float = ..., + aspect: float = ..., + **kwargs +) -> tuple[Axes, dict[str, Any]]: ... diff --git a/shared/package-files/0b/0b54f872eb6a3ea5622bc27f1b484e1bc85c89118611b3a1b33d30845b028fd9/simple_paths.py b/shared/package-files/0b/0b54f872eb6a3ea5622bc27f1b484e1bc85c89118611b3a1b33d30845b028fd9/simple_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..f88b03afffe28cd4f6d1a3b2a157f994c6f7749b --- /dev/null +++ b/shared/package-files/0b/0b54f872eb6a3ea5622bc27f1b484e1bc85c89118611b3a1b33d30845b028fd9/simple_paths.py @@ -0,0 +1,975 @@ +from heapq import heappop, heappush +from itertools import count + +import networkx as nx +from networkx.algorithms.shortest_paths.weighted import _weight_function +from networkx.utils import not_implemented_for, pairwise + +__all__ = [ + "all_simple_paths", + "is_simple_path", + "shortest_simple_paths", + "all_simple_edge_paths", +] + + +@nx._dispatch +def is_simple_path(G, nodes): + """Returns True if and only if `nodes` form a simple path in `G`. + + A *simple path* in a graph is a nonempty sequence of nodes in which + no node appears more than once in the sequence, and each adjacent + pair of nodes in the sequence is adjacent in the graph. + + Parameters + ---------- + G : graph + A NetworkX graph. + nodes : list + A list of one or more nodes in the graph `G`. + + Returns + ------- + bool + Whether the given list of nodes represents a simple path in `G`. + + Notes + ----- + An empty list of nodes is not a path but a list of one node is a + path. Here's an explanation why. + + This function operates on *node paths*. One could also consider + *edge paths*. There is a bijection between node paths and edge + paths. + + The *length of a path* is the number of edges in the path, so a list + of nodes of length *n* corresponds to a path of length *n* - 1. + Thus the smallest edge path would be a list of zero edges, the empty + path. This corresponds to a list of one node. + + To convert between a node path and an edge path, you can use code + like the following:: + + >>> from networkx.utils import pairwise + >>> nodes = [0, 1, 2, 3] + >>> edges = list(pairwise(nodes)) + >>> edges + [(0, 1), (1, 2), (2, 3)] + >>> nodes = [edges[0][0]] + [v for u, v in edges] + >>> nodes + [0, 1, 2, 3] + + Examples + -------- + >>> G = nx.cycle_graph(4) + >>> nx.is_simple_path(G, [2, 3, 0]) + True + >>> nx.is_simple_path(G, [0, 2]) + False + + """ + # The empty list is not a valid path. Could also return + # NetworkXPointlessConcept here. + if len(nodes) == 0: + return False + + # If the list is a single node, just check that the node is actually + # in the graph. + if len(nodes) == 1: + return nodes[0] in G + + # check that all nodes in the list are in the graph, if at least one + # is not in the graph, then this is not a simple path + if not all(n in G for n in nodes): + return False + + # If the list contains repeated nodes, then it's not a simple path + if len(set(nodes)) != len(nodes): + return False + + # Test that each adjacent pair of nodes is adjacent. + return all(v in G[u] for u, v in pairwise(nodes)) + + +def all_simple_paths(G, source, target, cutoff=None): + """Generate all simple paths in the graph G from source to target. + + A simple path is a path with no repeated nodes. + + Parameters + ---------- + G : NetworkX graph + + source : node + Starting node for path + + target : nodes + Single node or iterable of nodes at which to end path + + cutoff : integer, optional + Depth to stop the search. Only paths of length <= cutoff are returned. + + Returns + ------- + path_generator: generator + A generator that produces lists of simple paths. If there are no paths + between the source and target within the given cutoff the generator + produces no output. If it is possible to traverse the same sequence of + nodes in multiple ways, namely through parallel edges, then it will be + returned multiple times (once for each viable edge combination). + + Examples + -------- + This iterator generates lists of nodes:: + + >>> G = nx.complete_graph(4) + >>> for path in nx.all_simple_paths(G, source=0, target=3): + ... print(path) + ... + [0, 1, 2, 3] + [0, 1, 3] + [0, 2, 1, 3] + [0, 2, 3] + [0, 3] + + You can generate only those paths that are shorter than a certain + length by using the `cutoff` keyword argument:: + + >>> paths = nx.all_simple_paths(G, source=0, target=3, cutoff=2) + >>> print(list(paths)) + [[0, 1, 3], [0, 2, 3], [0, 3]] + + To get each path as the corresponding list of edges, you can use the + :func:`networkx.utils.pairwise` helper function:: + + >>> paths = nx.all_simple_paths(G, source=0, target=3) + >>> for path in map(nx.utils.pairwise, paths): + ... print(list(path)) + [(0, 1), (1, 2), (2, 3)] + [(0, 1), (1, 3)] + [(0, 2), (2, 1), (1, 3)] + [(0, 2), (2, 3)] + [(0, 3)] + + Pass an iterable of nodes as target to generate all paths ending in any of several nodes:: + + >>> G = nx.complete_graph(4) + >>> for path in nx.all_simple_paths(G, source=0, target=[3, 2]): + ... print(path) + ... + [0, 1, 2] + [0, 1, 2, 3] + [0, 1, 3] + [0, 1, 3, 2] + [0, 2] + [0, 2, 1, 3] + [0, 2, 3] + [0, 3] + [0, 3, 1, 2] + [0, 3, 2] + + Iterate over each path from the root nodes to the leaf nodes in a + directed acyclic graph using a functional programming approach:: + + >>> from itertools import chain + >>> from itertools import product + >>> from itertools import starmap + >>> from functools import partial + >>> + >>> chaini = chain.from_iterable + >>> + >>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)]) + >>> roots = (v for v, d in G.in_degree() if d == 0) + >>> leaves = (v for v, d in G.out_degree() if d == 0) + >>> all_paths = partial(nx.all_simple_paths, G) + >>> list(chaini(starmap(all_paths, product(roots, leaves)))) + [[0, 1, 2], [0, 3, 2]] + + The same list computed using an iterative approach:: + + >>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)]) + >>> roots = (v for v, d in G.in_degree() if d == 0) + >>> leaves = (v for v, d in G.out_degree() if d == 0) + >>> all_paths = [] + >>> for root in roots: + ... for leaf in leaves: + ... paths = nx.all_simple_paths(G, root, leaf) + ... all_paths.extend(paths) + >>> all_paths + [[0, 1, 2], [0, 3, 2]] + + Iterate over each path from the root nodes to the leaf nodes in a + directed acyclic graph passing all leaves together to avoid unnecessary + compute:: + + >>> G = nx.DiGraph([(0, 1), (2, 1), (1, 3), (1, 4)]) + >>> roots = (v for v, d in G.in_degree() if d == 0) + >>> leaves = [v for v, d in G.out_degree() if d == 0] + >>> all_paths = [] + >>> for root in roots: + ... paths = nx.all_simple_paths(G, root, leaves) + ... all_paths.extend(paths) + >>> all_paths + [[0, 1, 3], [0, 1, 4], [2, 1, 3], [2, 1, 4]] + + If parallel edges offer multiple ways to traverse a given sequence of + nodes, this sequence of nodes will be returned multiple times: + + >>> G = nx.MultiDiGraph([(0, 1), (0, 1), (1, 2)]) + >>> list(nx.all_simple_paths(G, 0, 2)) + [[0, 1, 2], [0, 1, 2]] + + Notes + ----- + This algorithm uses a modified depth-first search to generate the + paths [1]_. A single path can be found in $O(V+E)$ time but the + number of simple paths in a graph can be very large, e.g. $O(n!)$ in + the complete graph of order $n$. + + This function does not check that a path exists between `source` and + `target`. For large graphs, this may result in very long runtimes. + Consider using `has_path` to check that a path exists between `source` and + `target` before calling this function on large graphs. + + References + ---------- + .. [1] R. Sedgewick, "Algorithms in C, Part 5: Graph Algorithms", + Addison Wesley Professional, 3rd ed., 2001. + + See Also + -------- + all_shortest_paths, shortest_path, has_path + + """ + if source not in G: + raise nx.NodeNotFound(f"source node {source} not in graph") + if target in G: + targets = {target} + else: + try: + targets = set(target) + except TypeError as err: + raise nx.NodeNotFound(f"target node {target} not in graph") from err + if source in targets: + return _empty_generator() + if cutoff is None: + cutoff = len(G) - 1 + if cutoff < 1: + return _empty_generator() + if G.is_multigraph(): + return _all_simple_paths_multigraph(G, source, targets, cutoff) + else: + return _all_simple_paths_graph(G, source, targets, cutoff) + + +def _empty_generator(): + yield from () + + +def _all_simple_paths_graph(G, source, targets, cutoff): + visited = {source: True} + stack = [iter(G[source])] + while stack: + children = stack[-1] + child = next(children, None) + if child is None: + stack.pop() + visited.popitem() + elif len(visited) < cutoff: + if child in visited: + continue + if child in targets: + yield list(visited) + [child] + visited[child] = True + if targets - set(visited.keys()): # expand stack until find all targets + stack.append(iter(G[child])) + else: + visited.popitem() # maybe other ways to child + else: # len(visited) == cutoff: + for target in (targets & (set(children) | {child})) - set(visited.keys()): + yield list(visited) + [target] + stack.pop() + visited.popitem() + + +def _all_simple_paths_multigraph(G, source, targets, cutoff): + visited = {source: True} + stack = [(v for u, v in G.edges(source))] + while stack: + children = stack[-1] + child = next(children, None) + if child is None: + stack.pop() + visited.popitem() + elif len(visited) < cutoff: + if child in visited: + continue + if child in targets: + yield list(visited) + [child] + visited[child] = True + if targets - set(visited.keys()): + stack.append((v for u, v in G.edges(child))) + else: + visited.popitem() + else: # len(visited) == cutoff: + for target in targets - set(visited.keys()): + count = ([child] + list(children)).count(target) + for i in range(count): + yield list(visited) + [target] + stack.pop() + visited.popitem() + + +def all_simple_edge_paths(G, source, target, cutoff=None): + """Generate lists of edges for all simple paths in G from source to target. + + A simple path is a path with no repeated nodes. + + Parameters + ---------- + G : NetworkX graph + + source : node + Starting node for path + + target : nodes + Single node or iterable of nodes at which to end path + + cutoff : integer, optional + Depth to stop the search. Only paths of length <= cutoff are returned. + + Returns + ------- + path_generator: generator + A generator that produces lists of simple paths. If there are no paths + between the source and target within the given cutoff the generator + produces no output. + For multigraphs, the list of edges have elements of the form `(u,v,k)`. + Where `k` corresponds to the edge key. + + Examples + -------- + + Print the simple path edges of a Graph:: + + >>> g = nx.Graph([(1, 2), (2, 4), (1, 3), (3, 4)]) + >>> for path in sorted(nx.all_simple_edge_paths(g, 1, 4)): + ... print(path) + [(1, 2), (2, 4)] + [(1, 3), (3, 4)] + + Print the simple path edges of a MultiGraph. Returned edges come with + their associated keys:: + + >>> mg = nx.MultiGraph() + >>> mg.add_edge(1, 2, key="k0") + 'k0' + >>> mg.add_edge(1, 2, key="k1") + 'k1' + >>> mg.add_edge(2, 3, key="k0") + 'k0' + >>> for path in sorted(nx.all_simple_edge_paths(mg, 1, 3)): + ... print(path) + [(1, 2, 'k0'), (2, 3, 'k0')] + [(1, 2, 'k1'), (2, 3, 'k0')] + + + Notes + ----- + This algorithm uses a modified depth-first search to generate the + paths [1]_. A single path can be found in $O(V+E)$ time but the + number of simple paths in a graph can be very large, e.g. $O(n!)$ in + the complete graph of order $n$. + + References + ---------- + .. [1] R. Sedgewick, "Algorithms in C, Part 5: Graph Algorithms", + Addison Wesley Professional, 3rd ed., 2001. + + See Also + -------- + all_shortest_paths, shortest_path, all_simple_paths + + """ + if source not in G: + raise nx.NodeNotFound("source node %s not in graph" % source) + if target in G: + targets = {target} + else: + try: + targets = set(target) + except TypeError: + raise nx.NodeNotFound("target node %s not in graph" % target) + if source in targets: + return [] + if cutoff is None: + cutoff = len(G) - 1 + if cutoff < 1: + return [] + if G.is_multigraph(): + for simp_path in _all_simple_edge_paths_multigraph(G, source, targets, cutoff): + yield simp_path + else: + for simp_path in _all_simple_paths_graph(G, source, targets, cutoff): + yield list(zip(simp_path[:-1], simp_path[1:])) + + +def _all_simple_edge_paths_multigraph(G, source, targets, cutoff): + if not cutoff or cutoff < 1: + return [] + visited = [source] + stack = [iter(G.edges(source, keys=True))] + + while stack: + children = stack[-1] + child = next(children, None) + if child is None: + stack.pop() + visited.pop() + elif len(visited) < cutoff: + if child[1] in targets: + yield visited[1:] + [child] + elif child[1] not in [v[0] for v in visited[1:]]: + visited.append(child) + stack.append(iter(G.edges(child[1], keys=True))) + else: # len(visited) == cutoff: + for u, v, k in [child] + list(children): + if v in targets: + yield visited[1:] + [(u, v, k)] + stack.pop() + visited.pop() + + +@not_implemented_for("multigraph") +def shortest_simple_paths(G, source, target, weight=None): + """Generate all simple paths in the graph G from source to target, + starting from shortest ones. + + A simple path is a path with no repeated nodes. + + If a weighted shortest path search is to be used, no negative weights + are allowed. + + Parameters + ---------- + G : NetworkX graph + + source : node + Starting node for path + + target : node + Ending node for path + + weight : string or function + If it is a string, it is the name of the edge attribute to be + used as a weight. + + If it is a function, the weight of an edge is the value returned + by the function. The function must accept exactly three positional + arguments: the two endpoints of an edge and the dictionary of edge + attributes for that edge. The function must return a number. + + If None all edges are considered to have unit weight. Default + value None. + + Returns + ------- + path_generator: generator + A generator that produces lists of simple paths, in order from + shortest to longest. + + Raises + ------ + NetworkXNoPath + If no path exists between source and target. + + NetworkXError + If source or target nodes are not in the input graph. + + NetworkXNotImplemented + If the input graph is a Multi[Di]Graph. + + Examples + -------- + + >>> G = nx.cycle_graph(7) + >>> paths = list(nx.shortest_simple_paths(G, 0, 3)) + >>> print(paths) + [[0, 1, 2, 3], [0, 6, 5, 4, 3]] + + You can use this function to efficiently compute the k shortest/best + paths between two nodes. + + >>> from itertools import islice + >>> def k_shortest_paths(G, source, target, k, weight=None): + ... return list( + ... islice(nx.shortest_simple_paths(G, source, target, weight=weight), k) + ... ) + >>> for path in k_shortest_paths(G, 0, 3, 2): + ... print(path) + [0, 1, 2, 3] + [0, 6, 5, 4, 3] + + Notes + ----- + This procedure is based on algorithm by Jin Y. Yen [1]_. Finding + the first $K$ paths requires $O(KN^3)$ operations. + + See Also + -------- + all_shortest_paths + shortest_path + all_simple_paths + + References + ---------- + .. [1] Jin Y. Yen, "Finding the K Shortest Loopless Paths in a + Network", Management Science, Vol. 17, No. 11, Theory Series + (Jul., 1971), pp. 712-716. + + """ + if source not in G: + raise nx.NodeNotFound(f"source node {source} not in graph") + + if target not in G: + raise nx.NodeNotFound(f"target node {target} not in graph") + + if weight is None: + length_func = len + shortest_path_func = _bidirectional_shortest_path + else: + wt = _weight_function(G, weight) + + def length_func(path): + return sum( + wt(u, v, G.get_edge_data(u, v)) for (u, v) in zip(path, path[1:]) + ) + + shortest_path_func = _bidirectional_dijkstra + + listA = [] + listB = PathBuffer() + prev_path = None + while True: + if not prev_path: + length, path = shortest_path_func(G, source, target, weight=weight) + listB.push(length, path) + else: + ignore_nodes = set() + ignore_edges = set() + for i in range(1, len(prev_path)): + root = prev_path[:i] + root_length = length_func(root) + for path in listA: + if path[:i] == root: + ignore_edges.add((path[i - 1], path[i])) + try: + length, spur = shortest_path_func( + G, + root[-1], + target, + ignore_nodes=ignore_nodes, + ignore_edges=ignore_edges, + weight=weight, + ) + path = root[:-1] + spur + listB.push(root_length + length, path) + except nx.NetworkXNoPath: + pass + ignore_nodes.add(root[-1]) + + if listB: + path = listB.pop() + yield path + listA.append(path) + prev_path = path + else: + break + + +class PathBuffer: + def __init__(self): + self.paths = set() + self.sortedpaths = [] + self.counter = count() + + def __len__(self): + return len(self.sortedpaths) + + def push(self, cost, path): + hashable_path = tuple(path) + if hashable_path not in self.paths: + heappush(self.sortedpaths, (cost, next(self.counter), path)) + self.paths.add(hashable_path) + + def pop(self): + (cost, num, path) = heappop(self.sortedpaths) + hashable_path = tuple(path) + self.paths.remove(hashable_path) + return path + + +def _bidirectional_shortest_path( + G, source, target, ignore_nodes=None, ignore_edges=None, weight=None +): + """Returns the shortest path between source and target ignoring + nodes and edges in the containers ignore_nodes and ignore_edges. + + This is a custom modification of the standard bidirectional shortest + path implementation at networkx.algorithms.unweighted + + Parameters + ---------- + G : NetworkX graph + + source : node + starting node for path + + target : node + ending node for path + + ignore_nodes : container of nodes + nodes to ignore, optional + + ignore_edges : container of edges + edges to ignore, optional + + weight : None + This function accepts a weight argument for convenience of + shortest_simple_paths function. It will be ignored. + + Returns + ------- + path: list + List of nodes in a path from source to target. + + Raises + ------ + NetworkXNoPath + If no path exists between source and target. + + See Also + -------- + shortest_path + + """ + # call helper to do the real work + results = _bidirectional_pred_succ(G, source, target, ignore_nodes, ignore_edges) + pred, succ, w = results + + # build path from pred+w+succ + path = [] + # from w to target + while w is not None: + path.append(w) + w = succ[w] + # from source to w + w = pred[path[0]] + while w is not None: + path.insert(0, w) + w = pred[w] + + return len(path), path + + +def _bidirectional_pred_succ(G, source, target, ignore_nodes=None, ignore_edges=None): + """Bidirectional shortest path helper. + Returns (pred,succ,w) where + pred is a dictionary of predecessors from w to the source, and + succ is a dictionary of successors from w to the target. + """ + # does BFS from both source and target and meets in the middle + if ignore_nodes and (source in ignore_nodes or target in ignore_nodes): + raise nx.NetworkXNoPath(f"No path between {source} and {target}.") + if target == source: + return ({target: None}, {source: None}, source) + + # handle either directed or undirected + if G.is_directed(): + Gpred = G.predecessors + Gsucc = G.successors + else: + Gpred = G.neighbors + Gsucc = G.neighbors + + # support optional nodes filter + if ignore_nodes: + + def filter_iter(nodes): + def iterate(v): + for w in nodes(v): + if w not in ignore_nodes: + yield w + + return iterate + + Gpred = filter_iter(Gpred) + Gsucc = filter_iter(Gsucc) + + # support optional edges filter + if ignore_edges: + if G.is_directed(): + + def filter_pred_iter(pred_iter): + def iterate(v): + for w in pred_iter(v): + if (w, v) not in ignore_edges: + yield w + + return iterate + + def filter_succ_iter(succ_iter): + def iterate(v): + for w in succ_iter(v): + if (v, w) not in ignore_edges: + yield w + + return iterate + + Gpred = filter_pred_iter(Gpred) + Gsucc = filter_succ_iter(Gsucc) + + else: + + def filter_iter(nodes): + def iterate(v): + for w in nodes(v): + if (v, w) not in ignore_edges and (w, v) not in ignore_edges: + yield w + + return iterate + + Gpred = filter_iter(Gpred) + Gsucc = filter_iter(Gsucc) + + # predecesssor and successors in search + pred = {source: None} + succ = {target: None} + + # initialize fringes, start with forward + forward_fringe = [source] + reverse_fringe = [target] + + while forward_fringe and reverse_fringe: + if len(forward_fringe) <= len(reverse_fringe): + this_level = forward_fringe + forward_fringe = [] + for v in this_level: + for w in Gsucc(v): + if w not in pred: + forward_fringe.append(w) + pred[w] = v + if w in succ: + # found path + return pred, succ, w + else: + this_level = reverse_fringe + reverse_fringe = [] + for v in this_level: + for w in Gpred(v): + if w not in succ: + succ[w] = v + reverse_fringe.append(w) + if w in pred: + # found path + return pred, succ, w + + raise nx.NetworkXNoPath(f"No path between {source} and {target}.") + + +def _bidirectional_dijkstra( + G, source, target, weight="weight", ignore_nodes=None, ignore_edges=None +): + """Dijkstra's algorithm for shortest paths using bidirectional search. + + This function returns the shortest path between source and target + ignoring nodes and edges in the containers ignore_nodes and + ignore_edges. + + This is a custom modification of the standard Dijkstra bidirectional + shortest path implementation at networkx.algorithms.weighted + + Parameters + ---------- + G : NetworkX graph + + source : node + Starting node. + + target : node + Ending node. + + weight: string, function, optional (default='weight') + Edge data key or weight function corresponding to the edge weight + + ignore_nodes : container of nodes + nodes to ignore, optional + + ignore_edges : container of edges + edges to ignore, optional + + Returns + ------- + length : number + Shortest path length. + + Returns a tuple of two dictionaries keyed by node. + The first dictionary stores distance from the source. + The second stores the path from the source to that node. + + Raises + ------ + NetworkXNoPath + If no path exists between source and target. + + Notes + ----- + Edge weight attributes must be numerical. + Distances are calculated as sums of weighted edges traversed. + + In practice bidirectional Dijkstra is much more than twice as fast as + ordinary Dijkstra. + + Ordinary Dijkstra expands nodes in a sphere-like manner from the + source. The radius of this sphere will eventually be the length + of the shortest path. Bidirectional Dijkstra will expand nodes + from both the source and the target, making two spheres of half + this radius. Volume of the first sphere is pi*r*r while the + others are 2*pi*r/2*r/2, making up half the volume. + + This algorithm is not guaranteed to work if edge weights + are negative or are floating point numbers + (overflows and roundoff errors can cause problems). + + See Also + -------- + shortest_path + shortest_path_length + """ + if ignore_nodes and (source in ignore_nodes or target in ignore_nodes): + raise nx.NetworkXNoPath(f"No path between {source} and {target}.") + if source == target: + if source not in G: + raise nx.NodeNotFound(f"Node {source} not in graph") + return (0, [source]) + + # handle either directed or undirected + if G.is_directed(): + Gpred = G.predecessors + Gsucc = G.successors + else: + Gpred = G.neighbors + Gsucc = G.neighbors + + # support optional nodes filter + if ignore_nodes: + + def filter_iter(nodes): + def iterate(v): + for w in nodes(v): + if w not in ignore_nodes: + yield w + + return iterate + + Gpred = filter_iter(Gpred) + Gsucc = filter_iter(Gsucc) + + # support optional edges filter + if ignore_edges: + if G.is_directed(): + + def filter_pred_iter(pred_iter): + def iterate(v): + for w in pred_iter(v): + if (w, v) not in ignore_edges: + yield w + + return iterate + + def filter_succ_iter(succ_iter): + def iterate(v): + for w in succ_iter(v): + if (v, w) not in ignore_edges: + yield w + + return iterate + + Gpred = filter_pred_iter(Gpred) + Gsucc = filter_succ_iter(Gsucc) + + else: + + def filter_iter(nodes): + def iterate(v): + for w in nodes(v): + if (v, w) not in ignore_edges and (w, v) not in ignore_edges: + yield w + + return iterate + + Gpred = filter_iter(Gpred) + Gsucc = filter_iter(Gsucc) + + push = heappush + pop = heappop + # Init: Forward Backward + dists = [{}, {}] # dictionary of final distances + paths = [{source: [source]}, {target: [target]}] # dictionary of paths + fringe = [[], []] # heap of (distance, node) tuples for + # extracting next node to expand + seen = [{source: 0}, {target: 0}] # dictionary of distances to + # nodes seen + c = count() + # initialize fringe heap + push(fringe[0], (0, next(c), source)) + push(fringe[1], (0, next(c), target)) + # neighs for extracting correct neighbor information + neighs = [Gsucc, Gpred] + # variables to hold shortest discovered path + # finaldist = 1e30000 + finalpath = [] + dir = 1 + while fringe[0] and fringe[1]: + # choose direction + # dir == 0 is forward direction and dir == 1 is back + dir = 1 - dir + # extract closest to expand + (dist, _, v) = pop(fringe[dir]) + if v in dists[dir]: + # Shortest path to v has already been found + continue + # update distance + dists[dir][v] = dist # equal to seen[dir][v] + if v in dists[1 - dir]: + # if we have scanned v in both directions we are done + # we have now discovered the shortest path + return (finaldist, finalpath) + + wt = _weight_function(G, weight) + for w in neighs[dir](v): + if dir == 0: # forward + minweight = wt(v, w, G.get_edge_data(v, w)) + vwLength = dists[dir][v] + minweight + else: # back, must remember to change v,w->w,v + minweight = wt(w, v, G.get_edge_data(w, v)) + vwLength = dists[dir][v] + minweight + + if w in dists[dir]: + if vwLength < dists[dir][w]: + raise ValueError("Contradictory paths found: negative weights?") + elif w not in seen[dir] or vwLength < seen[dir][w]: + # relaxing + seen[dir][w] = vwLength + push(fringe[dir], (vwLength, next(c), w)) + paths[dir][w] = paths[dir][v] + [w] + if w in seen[0] and w in seen[1]: + # see if this path is better than the already + # discovered shortest path + totaldist = seen[0][w] + seen[1][w] + if finalpath == [] or finaldist > totaldist: + finaldist = totaldist + revpath = paths[1][w][:] + revpath.reverse() + finalpath = paths[0][w] + revpath[1:] + raise nx.NetworkXNoPath(f"No path between {source} and {target}.") diff --git a/shared/package-files/0b/0b5a65cf6a321d0f010c93b98dec5c37eacc087c441739a9c6de5b861a897b40/TensorImpl.h b/shared/package-files/0b/0b5a65cf6a321d0f010c93b98dec5c37eacc087c441739a9c6de5b861a897b40/TensorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..228d8b29f7015b2e548772e435e0a89ec49953da --- /dev/null +++ b/shared/package-files/0b/0b5a65cf6a321d0f010c93b98dec5c37eacc087c441739a9c6de5b861a897b40/TensorImpl.h @@ -0,0 +1,3249 @@ +#pragma once + +#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 +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// A global boolean variable to control whether we free memory when a Tensor +// is shrunk to a smaller size. As a result, a Tensor is always going to +// keep the memory allocated for its maximum capacity reshaped to so far. +// +// This parameter is respected "upper-case" methods which call Resize() +// (e.g., CopyFrom, ResizeLike); it is NOT respected by Tensor::resize_ +// or ShrinkTo, both of which guarantee to never to free memory. +C10_DECLARE_bool(caffe2_keep_on_shrink); + +// Since we can have high variance in blob memory allocated across different +// inputs in the same run, we will shrink the blob only if the memory gain +// is larger than this flag in bytes. This only applies to functions which +// respect caffe2_keep_on_shrink. +C10_DECLARE_int64(caffe2_max_keep_on_shrink_memory); + +namespace at { +class Tensor; +class TensorBase; +} // namespace at + +namespace c10 { + +/** + * A utility function to convert vector to vector. + */ +inline std::vector ToVectorint64_t(const ArrayRef& src) { + return std::vector(src.begin(), src.end()); +} + +/** + * Return product of all dimensions starting from k + */ +inline int64_t size_from_dim_(int k, IntArrayRef dims) { + int64_t r = 1; + for (const auto i : c10::irange(k, dims.size())) { + r *= dims[i]; + } + return r; +} + +// Product of all dims up to k (not including dims[k]) +inline int64_t size_to_dim_(int k, IntArrayRef dims) { + TORCH_CHECK(k >= 0 && static_cast(k) <= dims.size()); + int64_t r = 1; + for (const auto i : c10::irange(k)) { + r *= dims[i]; + } + return r; +} + +// Product of all dims between k and l (not including dims[k] and dims[l]) +inline int64_t size_between_dim_(int k, int l, IntArrayRef dims) { + TORCH_CHECK((unsigned)l < dims.size() && (unsigned)k < dims.size()); + int64_t r = 1; + if (k < l) { + for (int i = k + 1; i < l; ++i) { + r *= dims[i]; + } + } else { + for (int i = l + 1; i < k; ++i) { + r *= dims[i]; + } + } + return r; +} + +// Wrap around axis_index if it is negative, s.t., -1 is the last dim +inline int canonical_axis_index_(int axis_index, int ndims) { + TORCH_CHECK(axis_index >= -ndims); + TORCH_CHECK(axis_index < ndims); + if (axis_index < 0) { + return axis_index + ndims; + } + return axis_index; +} + +using PlacementDtor = void (*)(void*, size_t); + +/* + * A Context that will call extra placement deleter during + * deconstruction. + * + * Accept a already constructed DataPtr and store it as member + * during destruction, we'll call extra deleter on the underlying + * data pointer before the DataPtr is destructed. + * `data_ptr_` owns the memory. + */ +struct C10_API PlacementDeleteContext { + DataPtr data_ptr_; + PlacementDtor placement_dtor_; + size_t size_; + PlacementDeleteContext( + DataPtr&& data_ptr, + PlacementDtor placement_dtor, + size_t size) + : data_ptr_(std::move(data_ptr)), + placement_dtor_(placement_dtor), + size_(size) {} + static DataPtr makeDataPtr( + DataPtr&& data_ptr, + PlacementDtor placement_dtor, + size_t size, + Device device); + ~PlacementDeleteContext() { + placement_dtor_(data_ptr_.get(), size_); + // original memory will be freed when data_ptr_ is destructed + } +}; + +struct C10_API AutogradMetaInterface { + virtual void set_requires_grad( + bool requires_grad, + at::TensorImpl* self_impl) = 0; + virtual bool requires_grad() const = 0; + virtual at::Tensor& mutable_grad() = 0; + virtual const at::Tensor& grad() const = 0; + virtual const at::Tensor& fw_grad(uint64_t level, const at::TensorBase& self) + const = 0; + virtual void set_fw_grad( + const at::TensorBase& new_grad, + const at::TensorBase& self, + uint64_t level, + bool is_inplace_op) = 0; + virtual ~AutogradMetaInterface(); +}; + +namespace impl { + +// Unfortunately, the definition of AutogradMeta lives in a separate +// compilation unit than TensorImpl (libtorch.so versus libc10.so) +// which means that we cannot construct an AutogradMeta from TensorImpl, +// not even from the cpp file. So we have to indirect it through a factory +// function which will be initialized when we load libtorch.so. + +struct C10_API AutogradMetaFactory { + virtual ~AutogradMetaFactory() = default; + virtual std::unique_ptr make() const = 0; + // This method is the dumbest method. But I don't have access + // to Tensor (not TensorImpl) which is undefined in this header. + virtual const at::Tensor& undefined_tensor() const = 0; +}; + +C10_API void SetAutogradMetaFactory(AutogradMetaFactory* factory); +C10_API AutogradMetaFactory* GetAutogradMetaFactory(); + +struct C10_API AutogradMetaFactoryRegisterer { + explicit AutogradMetaFactoryRegisterer(AutogradMetaFactory* factory) { + SetAutogradMetaFactory(factory); + } +}; + +} // namespace impl + +struct C10_API NamedTensorMetaInterface { + virtual ~NamedTensorMetaInterface() = default; + virtual std::unique_ptr clone() const { + TORCH_INTERNAL_ASSERT( + false, "Not implemented: NamedTensorMetaInterface::clone"); + }; + virtual int64_t slow_dim() const { + TORCH_INTERNAL_ASSERT( + false, "Not implemented: NamedTensorMetaInterface::slow_dim"); + }; +}; + +// For ease of copy pasting +#if 0 +is_contiguous +is_channels_last_contiguous +is_channels_last_3d_contiguous +is_channels_last +is_channels_last_3d +is_non_overlapping_and_dense +#endif + +/** + * This structure is intended to hold additional metadata of the specific device + * backend. + **/ +struct C10_API BackendMeta : intrusive_ptr_target { + ~BackendMeta() override = default; + virtual intrusive_ptr clone( + const intrusive_ptr& ptr) const { + return ptr; + } +}; + +struct C10_API ExtraMeta { + std::unique_ptr symbolic_shape_meta_ = nullptr; + std::unique_ptr named_tensor_meta_ = nullptr; + intrusive_ptr backend_meta_ = nullptr; + c10::optional custom_data_ptr_error_msg_ = c10::nullopt; + c10::optional custom_storage_error_msg_ = c10::nullopt; + + ExtraMeta() = default; + ExtraMeta(const ExtraMeta& other) { + if (other.symbolic_shape_meta_) { + symbolic_shape_meta_ = + std::make_unique(*other.symbolic_shape_meta_); + } + if (other.named_tensor_meta_) { + named_tensor_meta_ = other.named_tensor_meta_->clone(); + } + if (other.backend_meta_) { + backend_meta_ = other.backend_meta_->clone(other.backend_meta_); + } + if (other.custom_data_ptr_error_msg_) { + custom_data_ptr_error_msg_ = other.custom_data_ptr_error_msg_; + } + if (other.custom_storage_error_msg_) { + custom_storage_error_msg_ = other.custom_storage_error_msg_; + } + } + + ExtraMeta( + std::unique_ptr symbolic_shape_meta, + std::unique_ptr named_tensor_meta, + intrusive_ptr backend_meta, + c10::optional custom_data_ptr_error_msg = c10::nullopt, + c10::optional custom_storage_access_error_msg = c10::nullopt) + : symbolic_shape_meta_(std::move(symbolic_shape_meta)), + named_tensor_meta_(std::move(named_tensor_meta)), + backend_meta_(std::move(backend_meta)), + custom_data_ptr_error_msg_(std::move(custom_data_ptr_error_msg)), + custom_storage_error_msg_(std::move(custom_storage_access_error_msg)) {} + + std::unique_ptr clone() const { + return std::make_unique(*this); + } +}; + +// NOTE [ Version Counter Sharing ] +// +// Every Tensor has a version counter. Version counters are incremented whenever +// the data or size of a tensor changes through in-place Variable operations. +// Version counters are used to detect modifications to saved variables which +// would result in incorrect gradient calculations. Version counters may be +// shared between Variables: +// +// 1. A view shares the version counter of the base Variable, +// 2. `x.detach()` shares the version counter of `x`, +// 3. Unpacked saved variables share the version counter of the source. +// +// Version counters are not shared in these scenarios: +// +// 1. When we replace a `Variable`'s underlying `Tensor` by calling +// `set_data(...)`, +// 2. `x.data` does not share the version counter of `x`. (See discussion at +// https://github.com/pytorch/pytorch/issues/5396) +// +// Question: Why do we put the version counter in TensorImpl instead of +// AutogradMeta? +// +// Answer: After the Variable/Tensor merge, a tensor will not have AutogradMeta +// when its `requires_grad_` is false, but when we use this tensor in the +// forward pass of a function that requires saving this tensor for backward, we +// need to keep track of this tensor's version to make sure it's always valid in +// the autograd graph. +// +// To achieve this goal, we put the version counter in TensorImpl instead of +// AutogradMeta, and have it always be available. This allows us to have the +// optimization of not carrying AutogradMeta when a tensor doesn't require +// gradient. +// +// A hypothetical alternative way to achieve this goal is to initialize +// AutogradMeta and create the version counter for the non-requires-grad tensor +// only when it's saved for backward. However, since saving a tensor for +// backward happens in the forward pass, and our invariant is that forward pass +// needs to be thread-safe, lazy-initializing AutogradMeta when saving a tensor +// can introduce race conditions when we are running the forward pass in +// multi-thread scenarios, thus making the forward pass not thread-safe anymore, +// which breaks the invariant. +struct C10_API VariableVersion { + private: + struct VersionCounter : intrusive_ptr_target { + VersionCounter(uint32_t version) : version_(version) {} + std::atomic version_; + }; + c10::intrusive_ptr version_counter_; + + public: + // Note [Disabled VariableVersion] + // VariableVersion struct has an intrusive_ptr pointing VersionCounter struct + // with an atomic variable. Thus `VariableVersion(/*version=*/0)` is not as + // cheap as we expected. In some cases constructing a VariableVersion with + // version 0 is not necessary so we add a cheap constructor which + // doesn't allocate the intrusive_ptr. + // Example use cases are: + // - Inference tensors don't track version counter, so they'll just always + // have disabled VariableVersion. + // - In SavedVariable class we override version_counter_ inside its + // constructor + // so that we can use the cheap constructor there. + enum Disabled { DISABLED }; + // It's okay to return true even for inference tensor which + // doesn't have version counter enabled. + // We want to be permissive here since in many cases (e.g. make_variable) + // we can std::move a TensorImpl if there's no other uses which saves us + // an additional TensorImpl allocation. + bool unique() const { + return version_counter_ ? 1 == version_counter_.use_count() : true; + } + // NOTE: As of C++11 and 14, default-constructing a std::atomic variable + // leaves it in a persistently undefined state. See + // https://cplusplus.github.io/LWG/issue2334. + VariableVersion(uint32_t version) + : version_counter_(c10::make_intrusive(version)) {} + VariableVersion(Disabled = DISABLED) {} + + bool enabled() const { + return version_counter_; + } + + // Note [Inplace update inference tensor] + // 1. Inplace update to inference tensor is forbidden in normal mode. + // For example: + // inference_tensor.copy_(normal_tensor_requires_grad) + // This inplace makes inference_tensor have requires_grad=True and + // have a grad_fn. This is bad because views of `inference_tensor` + // created in InferenceMode won't be able to know the grad_fn since + // their ViewMeta were not recorded. To match NoGradMode behavior + // that "inplace update to a view created in NoGradMode raise an error", + // we just ban inplace update to inference tensor since we can't tell + // if an inference tensor is a view created in InferenceMode. + // + // Note that views of normal tensor created in InferenceMode has proper + // ViewMeta so that they're aware of the grad_fn correctly. + // + // 2. Inplace update to inference tensor in inference tensor doesn't bump + // version counter. + // * It either doesn't call bump() by skipping ADInplaceOrView kernel, + // - e.g. inference_tensor.add_(1) + // * or bump() is a no-op for inference tensor. + // - e.g. inference_tensor.add_(normal_tensor) + void bump() { + // TODO: Replace the link to the documentation once it's available. + TORCH_CHECK( + version_counter_ || InferenceMode::is_enabled(), + "Inplace update to inference tensor outside InferenceMode is not allowed." + "You can make a clone to get a normal tensor before doing inplace update." + "See https://github.com/pytorch/rfcs/pull/17 for more details."); + if (version_counter_) { + ++version_counter_->version_; + } + } + + void set_version(int64_t i) { + TORCH_CHECK( + version_counter_, + "Tried to call torch.autograd._unsafe_set_version() on a tensor " + "that does not have a version counter. Was it created in inference mode?"); + TORCH_CHECK(i >= 0, "Cannot set a version_counter to a value below 0: ", i); + version_counter_->version_ = i; + } + + // Inference tensor doesn't have version counter so it shouldn't be + // accessed. + uint32_t current_version() const { + TORCH_CHECK( + version_counter_, "Inference tensors do not track version counter."); + return version_counter_->version_; + } +}; + +// Forward declaration of TensorImpl needed for forward declaration of +// C10_TensorImpl_Size_Check_Dummy_Class +struct C10_API TensorImpl; + +/** + * NOTE: Some TensorImpl methods are small and not overridden in the + * PyTorch codebase itself, but may theoretically need to be + * overridden by third-party TensorImpl subclasses. This macro allows + * users that need maximum performance and don't need these extension + * points to disable them with a build-time flag. (In particular, + * XLA's XLATensorImpl currently overrides these methods, so we can't + * enable this flag by default.) + */ +#ifdef C10_DISABLE_TENSORIMPL_EXTENSIBILITY +#define TENSORIMPL_MAYBE_VIRTUAL +#else +#define TENSORIMPL_MAYBE_VIRTUAL virtual +#endif + +/** + * The low-level representation of a tensor, which contains a pointer + * to a storage (which contains the actual data) and metadata (e.g., sizes and + * strides) describing this particular view of the data as a tensor. + * + * Some basic characteristics about our in-memory representation of + * tensors: + * + * - It contains a pointer to a storage struct (Storage/StorageImpl) + * which contains the pointer to the actual data and records the + * data type and device of the view. This allows multiple tensors + * to alias the same underlying data, which allows to efficiently + * implement differing *views* on a tensor. + * + * - The tensor struct itself records view-specific metadata about + * the tensor, e.g., sizes, strides and offset into storage. + * Each view of a storage can have a different size or offset. + * + * - This class is intrusively refcounted. It is refcounted so that + * we can support prompt deallocation of large tensors; it is + * intrusively refcounted so that we can still perform reference + * counted operations on raw pointers, which is often more convenient + * when passing tensors across language boundaries. + * + * - For backwards-compatibility reasons, a tensor may be in an + * uninitialized state. A tensor may be uninitialized in the following + * two ways: + * + * - A tensor may be DTYPE UNINITIALIZED. A tensor of this + * form has an uninitialized dtype. This situation most + * frequently arises when a user writes Tensor x(CPU). The dtype + * is subsequently initialized when mutable_data() is + * invoked for the first time. + * + * - A tensor may be STORAGE UNINITIALIZED. A tensor of this form + * has non-zero size, but has a storage with a null data pointer. + * This situation most frequently arises when a user calls + * Resize() or FreeMemory(). This is because Caffe2 historically + * does lazy allocation: allocation of data doesn't occur until + * mutable_data() is invoked. A tensor with zero size is + * always storage initialized, because no allocation is necessary + * in this case. + * + * All combinations of these two uninitialized states are possible. + * Consider the following transcript in idiomatic Caffe2 API: + * + * Tensor x(CPU); // x is storage-initialized, dtype-UNINITIALIZED + * x.Resize(4); // x is storage-UNINITIALIZED, dtype-UNINITIALIZED + * x.mutable_data(); // x is storage-initialized, dtype-initialized + * x.FreeMemory(); // x is storage-UNINITIALIZED, dtype-initialized. + * + * All other fields on tensor are always initialized. In particular, + * size is always valid. (Historically, a tensor declared as Tensor x(CPU) + * also had uninitialized size, encoded as numel == -1, but we have now + * decided to default to zero size, resulting in numel == 0). + * + * Uninitialized storages MUST be uniquely owned, to keep our model + * simple. Thus, we will reject operations which could cause an + * uninitialized storage to become shared (or a shared storage to + * become uninitialized, e.g., from FreeMemory). + * + * In practice, tensors which are storage-UNINITIALIZED and + * dtype-UNINITIALIZED are *extremely* ephemeral: essentially, + * after you do a Resize(), you basically always call mutable_data() + * immediately afterwards. Most functions are not designed to + * work if given a storage-UNINITIALIZED, dtype-UNINITIALIZED tensor. + * + * We intend to eliminate all uninitialized states, so that every + * tensor is fully initialized in all fields. Please do not write new code + * that depends on these uninitialized states. + */ +struct C10_API TensorImpl : public c10::intrusive_ptr_target { + TensorImpl() = delete; + ~TensorImpl() override; + // Note [Enum ImplType] + // This enum is temporary. In the followup refactor we should + // think about how to specialize TensorImpl creation for view + // tensors. Currently we only special case its key_set_ but + // there's also potential to share version_counter_ directly + // without creating first and then override in as_view. + enum ImplType { VIEW }; + + /** + * Construct a 1-dim 0-size tensor backed by the given storage. + */ + TensorImpl( + Storage&& storage, + DispatchKeySet, + const caffe2::TypeMeta data_type); + + // See Note [Enum ImplType] + TensorImpl( + ImplType, + Storage&& storage, + DispatchKeySet, + const caffe2::TypeMeta data_type); + + /** + * Construct a 1-dim 0 size tensor that doesn't have a storage. + */ + TensorImpl( + DispatchKeySet, + const caffe2::TypeMeta data_type, + c10::optional device_opt); + + // Legacy constructors so I don't have to go update call sites. + // TODO: When Variable is added, delete these constructors + TensorImpl( + Storage&& storage, + DispatchKey dispatch_key, + const caffe2::TypeMeta data_type) + : TensorImpl( + std::move(storage), + DispatchKeySet(dispatch_key), + data_type) {} + TensorImpl( + DispatchKey dispatch_key, + const caffe2::TypeMeta data_type, + c10::optional device_opt) + : TensorImpl(DispatchKeySet(dispatch_key), data_type, device_opt) {} + + private: + // This constructor is private, because the data_type is redundant with + // storage. Still, we pass it in separately because it's easier to write + // the initializer list if we're not worried about storage being moved out + // from under us. + TensorImpl( + Storage&& storage, + DispatchKeySet, + const caffe2::TypeMeta data_type, + c10::optional); + + public: + TensorImpl(const TensorImpl&) = delete; + TensorImpl& operator=(const TensorImpl&) = delete; + TensorImpl(TensorImpl&&) = delete; + TensorImpl& operator=(TensorImpl&&) = delete; + + /** + * Release (decref) storage, and any other external allocations. This + * override is for `intrusive_ptr_target` and is used to implement weak + * tensors. + */ + void release_resources() override; + + public: + /** + * Return the DispatchKeySet corresponding to this Tensor, specifying + * all of the DispatchKeys that this Tensor identifies as. This is the + * information used to dispatch operations on this tensor. + */ + DispatchKeySet key_set() const { + return key_set_; + } + + private: + [[noreturn]] void throw_cannot_call_with_symbolic(const char* meth) const; + + // NOTE: The general recipe for customizable methods is that the fastpath + // function (e.g., sizes()) does an unlikely policy test, and if doesn't + // trigger, it does the fast path implementation with no checks and going + // directly to on-TensorImpl fields. In particular, you never need to + // check ExtraMeta if the policy doesn't trigger, as non-trivial ExtraMeta + // implies the policy will always match. + // + // The default implementations of methods are "safe": they do extra tests + // to make sure the internal state is consistent no matter if you are + // doing symbolic shapes or not. If you don't want the tests, directly + // override the custom method (e.g., custom_sizes()) to do your preferred + // behavior. + + public: + /** + * Return a reference to the sizes of this tensor. This reference remains + * valid as long as the tensor is live and not resized. + */ + IntArrayRef sizes() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return sizes_custom(); + } + return sizes_and_strides_.sizes_arrayref(); + } + + SymIntArrayRef sym_sizes() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return sym_sizes_custom(); + } + // Sizes guaranteed to be non-negative, so unchecked cast is OK + return c10::fromIntArrayRefKnownNonNegative( + sizes_and_strides_.sizes_arrayref()); + } + + IntArrayRef sizes_default() const { + if (C10_UNLIKELY(has_symbolic_sizes_strides_)) { + throw_cannot_call_with_symbolic("sizes"); + } + return sizes_and_strides_.sizes_arrayref(); + } + + SymIntArrayRef sym_sizes_default() const { + if (has_symbolic_sizes_strides_) { + return symbolic_shape_meta().sizes_; + } else { + // Sizes guaranteed to be non-negative, so unchecked cast is OK + return c10::fromIntArrayRefKnownNonNegative(sizes_default()); + } + } + + // From https://stackoverflow.com/a/3057522/23845 + // TODO: does C++14 have a stdlib template for this? + template + struct identity { + typedef T type; + }; + + template + ArrayRef generic_sizes() { + return _generic_sizes(identity()); + } + + ArrayRef _generic_sizes(identity) { + return sizes(); + } + ArrayRef _generic_sizes(identity) { + return sym_sizes(); + } + + template + ArrayRef generic_strides() { + return _generic_strides(identity()); + } + + ArrayRef _generic_strides(identity) { + return strides(); + } + ArrayRef _generic_strides(identity) { + return sym_strides(); + } + + template + T generic_storage_offset() { + return _generic_storage_offset(identity()); + } + + int64_t _generic_storage_offset(identity) { + return storage_offset(); + } + c10::SymInt _generic_storage_offset(identity) { + return sym_storage_offset(); + } + + /** + * The number of elements in a tensor. + * + * WARNING: Previously, if you were using the Caffe2 API, you could + * test numel() == -1 to see if a tensor was uninitialized. This + * is no longer true; numel always accurately reports the product + * of sizes of a tensor. + */ + int64_t numel() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return numel_custom(); + } + return numel_; + } + + c10::SymInt sym_numel() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return sym_numel_custom(); + } + return c10::SymInt(SymInt::UNCHECKED, numel_); + } + + int64_t numel_default() const { + if (C10_UNLIKELY(has_symbolic_sizes_strides_)) { + throw_cannot_call_with_symbolic("numel"); + } + return numel_; + } + + c10::SymInt sym_numel_default() const { + if (has_symbolic_sizes_strides_) { + return symbolic_shape_meta().numel(); + } else { + return c10::SymInt(SymInt::UNCHECKED, numel_); + } + } + + /** + * Return the number of dimensions of this tensor. Note that 0-dimension + * represents a Tensor that is a Scalar, e.g., one that has a single element. + */ + int64_t dim() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return dim_custom(); + } + return static_cast(sizes_and_strides_.size()); + } + + int64_t dim_default() const { + if (has_symbolic_sizes_strides_) { + return static_cast(symbolic_shape_meta().sizes_.size()); + } else { + return static_cast(sizes_and_strides_.size()); + } + } + + /** + * Return the offset in number of elements into the storage that this + * tensor points to. Most tensors have storage_offset() == 0, but, + * for example, an index into a tensor will have a non-zero storage_offset(). + * + * WARNING: This is NOT computed in bytes. + */ + int64_t storage_offset() const { + // TODO: maybe this should be toggled by strides + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return storage_offset_custom(); + } + return storage_offset_; + } + + c10::SymInt sym_storage_offset() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return sym_storage_offset_custom(); + } + return c10::SymInt(SymInt::UNCHECKED, storage_offset_); + } + + int64_t storage_offset_default() const { + if (C10_UNLIKELY(has_symbolic_sizes_strides_)) { + throw_cannot_call_with_symbolic("storage_offset"); + } + return storage_offset_; + } + + c10::SymInt sym_storage_offset_default() const { + if (has_symbolic_sizes_strides_) { + return symbolic_shape_meta().storage_offset_; + } else { + return c10::SymInt(SymInt::UNCHECKED, storage_offset_); + } + } + + /** + * Return a reference to the strides of this tensor. This reference remains + * valid as long as the tensor is live and not restrided. + */ + IntArrayRef strides() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomStrides))) { + return strides_custom(); + } + return sizes_and_strides_.strides_arrayref(); + } + + c10::SymIntArrayRef sym_strides() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomStrides))) { + return sym_strides_custom(); + } + return c10::fromIntArrayRefKnownNonNegative(strides_default()); + } + + IntArrayRef strides_default() const { + if (C10_UNLIKELY(has_symbolic_sizes_strides_)) { + throw_cannot_call_with_symbolic("strides"); + } + return sizes_and_strides_.strides_arrayref(); + } + + c10::SymIntArrayRef sym_strides_default() const { + if (has_symbolic_sizes_strides_) { + return symbolic_shape_meta().strides_; + } else { + return c10::fromIntArrayRefKnownNonNegative(strides_default()); + } + } + + /** + * Whether or not a tensor is laid out in contiguous memory. + * + * Tensors with non-trivial strides are not contiguous. See + * compute_contiguous() for the exact definition of whether or not + * a tensor is contiguous or not. + */ + bool is_contiguous( + at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomStrides))) { + return is_contiguous_custom(memory_format); + } + return is_contiguous_default(memory_format); + } + + // These are factored into separate functions in case subclasses + // want to use them + bool is_contiguous_default(at::MemoryFormat memory_format) const { + if (has_symbolic_sizes_strides_) { + if (memory_format == at::MemoryFormat::ChannelsLast) { + return symbolic_shape_meta().is_channels_last_contiguous().guard_bool( + __FILE__, __LINE__); + } else if (memory_format == at::MemoryFormat::ChannelsLast3d) { + return symbolic_shape_meta() + .is_channels_last_3d_contiguous() + .guard_bool(__FILE__, __LINE__); + } + return symbolic_shape_meta().is_contiguous().guard_bool( + __FILE__, __LINE__); + } + + if (memory_format == at::MemoryFormat::ChannelsLast) { + return is_channels_last_contiguous_; + } else if (memory_format == at::MemoryFormat::ChannelsLast3d) { + return is_channels_last_3d_contiguous_; + } + return is_contiguous_; + } + + bool is_strides_like_default(at::MemoryFormat memory_format) const { + if (has_symbolic_sizes_strides_) { + if (memory_format == at::MemoryFormat::ChannelsLast) { + return symbolic_shape_meta().is_channels_last().guard_bool( + __FILE__, __LINE__); + } else if (memory_format == at::MemoryFormat::ChannelsLast3d) { + return symbolic_shape_meta().is_channels_last_3d().guard_bool( + __FILE__, __LINE__); + } else { + return false; + } + } + + if (memory_format == at::MemoryFormat::ChannelsLast) { + return is_channels_last_; + } else if (memory_format == at::MemoryFormat::ChannelsLast3d) { + return is_channels_last_3d_; + } else { + return false; + } + } + + bool is_non_overlapping_and_dense_default() const { + if (has_symbolic_sizes_strides_) { + return symbolic_shape_meta().is_non_overlapping_and_dense().guard_bool( + __FILE__, __LINE__); + } else { + return is_non_overlapping_and_dense_; + } + } + + // NB: these dim accessor functions don't have _default(), as you can use + // sizes_default/strides_default + /** + * Return the size of a tensor at some dimension, wrapping the dimension if + * necessary. + * + * NOTE: if you know wrapping is unnecessary, do sizes()[d] instead; it will + * be faster + */ + int64_t size(int64_t d) const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return size_custom(d); + } + d = maybe_wrap_dim(d, dim(), /*wrap_scalar=*/false); + return sizes_and_strides_.size_at_unchecked(d); + } + + c10::SymInt sym_size(int64_t d) const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomSizes))) { + return sym_size_custom(d); + } + d = maybe_wrap_dim(d, dim(), /*wrap_scalar=*/false); + const auto sizes = this->sym_sizes(); + return sizes[d]; + } + + /** + * Return the stride of a tensor at some dimension, wrapping the dimension + * if necessary. + * + * NOTE: if you know wrapping is unnecessary, do sizes()[d] instead; it will + * be faster + */ + int64_t stride(int64_t d) const { + d = maybe_wrap_dim(d, dim(), false); + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomStrides))) { + // TODO: provide stride_custom, symmetrically with size_custom. + // There is presently no user for it; only NestedTensor is using + // size_custom overrideability + return strides_custom()[d]; // unchecked (maybe_wrap_dim enforces bounds) + } + // Intentionally don't call default, which also handles symbolic + return sizes_and_strides_.stride_at_unchecked(d); + } + + enum class SizesStridesPolicy : uint8_t { + // Default behavior, e.g., dense tensor. + // + // Can override: nothing + Default = 0, + // Customizable strides behavior, e.g., sparse tensor, + // mkldnn tensor. + // + // Can override: strides(), is_contiguous() + CustomStrides = 1, + // Customizable sizes behavior, e.g., nested tensor + // + // Can override: strides(), is_contiguous(), sizes(), dim(), numel() + CustomSizes = 2 + }; + + protected: + inline bool matches_policy(SizesStridesPolicy policy) const { + return sizes_strides_policy_ >= static_cast(policy); + } + + inline bool matches_custom(SizesStridesPolicy policy) const { + return custom_sizes_strides_ >= static_cast(policy); + } + + inline bool matches_python_custom(SizesStridesPolicy policy) const { + auto r = python_custom_sizes_strides_ >= static_cast(policy); + if (r) { + TORCH_INTERNAL_ASSERT(is_python_dispatch()) + } + return r; + } + + /** + * Customization points for the functions above. sizes_strides_policy_ + * must be set to enable these. + * + * NB: dim is overrideable separately from sizes because it is possible + * for a tensor to have rank, but not well defined sizes. + */ + // sizes_strides_policy_ >= CustomStrides + virtual bool is_contiguous_custom(at::MemoryFormat memory_format) const; + virtual bool is_strides_like_custom(at::MemoryFormat memory_format) const; + virtual bool is_non_overlapping_and_dense_custom() const; + // sizes_strides_policy_ >= CustomSizes + // Currently this method only exists to be overwritten by subclasses such as + // NestedTensorImpl. + virtual int64_t size_custom(int64_t d) const { + // TODO: We could add support to Python dispatch here. + // TODO: We could call into aten::size.int instead of + // sizes_custom()[d] and enable use of the dispatcher. + d = maybe_wrap_dim(d, dim(), /*wrap_scalar=*/false); + return sizes_custom()[d]; // unchecked (maybe_wrap_dim enforces bounds) + } + + virtual c10::SymInt sym_size_custom(int64_t d) const { + // TODO: We could add support to Python dispatch here. + // TODO: We could call into aten::size.int instead of + // sym_sizes_custom()[d] and enable use of the dispatcher. + d = maybe_wrap_dim(d, dim(), /*wrap_scalar=*/false); + return sym_sizes_custom()[d]; // unchecked (maybe_wrap_dim enforces bounds) + } + + virtual IntArrayRef sizes_custom() const; + virtual IntArrayRef strides_custom() const; + virtual int64_t numel_custom() const; + virtual int64_t storage_offset_custom() const; + virtual int64_t dim_custom() const; + virtual Device device_custom() const; + virtual Layout layout_custom() const; + + virtual c10::SymIntArrayRef sym_sizes_custom() const; + virtual c10::SymIntArrayRef sym_strides_custom() const; + virtual c10::SymInt sym_numel_custom() const; + virtual c10::SymInt sym_storage_offset_custom() const; + + public: + /** + * True if this tensor has storage. See storage() for details. + */ +#ifdef DEBUG + // Allow subclasses to check that their storage_ is never getting set in debug + // builds. + virtual +#else + TENSORIMPL_MAYBE_VIRTUAL +#endif + bool + has_storage() const + // NOTE: we devirtualize this because it arguably shouldn't be an + // error just to ask subclasses if they have storage. + // This used to throw for most subclasses, but OpaqueTensorImpl + // wanted it to successfully return false, so we went ahead and made + // it a non-error. +#ifdef C10_DISABLE_TENSORIMPL_EXTENSIBILITY + { + return storage_; + } +#else + ; +#endif + + /** + * Return the underlying storage of a Tensor. Multiple tensors may share + * a single storage. A Storage is an impoverished, Tensor-like class + * which supports far less operations than Tensor. + * + * Avoid using this method if possible; try to use only Tensor APIs to perform + * operations. + */ + TENSORIMPL_MAYBE_VIRTUAL const Storage& storage() const { + if (C10_UNLIKELY(storage_access_should_throw_)) { + throw_storage_access_error(); + } + return storage_; + } + + /** + * Return the underlying storage, unsafely assuming this is a basic strided + * tensor. In cases where `storage` access would throw, this returns a + * default-constructed Storage. + */ + inline const Storage& unsafe_storage() const { + return storage_; + } + + bool unique_version() const { + return version_counter_.unique(); + } + + protected: + virtual Layout layout_impl() const { + TORCH_CHECK( + false, "layout_impl is only implemented for TensorImpl subclasses."); + } + + public: + // Whether a tensor is sparse COO or not. + bool is_sparse() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + return key_set_.has_all(c10::sparse_ks); + } + + // Whether a tensor is sparse CSR or not. + bool is_sparse_csr() const { + return layout() == kSparseCsr; + } + + // Whether a tensor is sparse CSR/CSC/BSR/BSC or not. + bool is_sparse_compressed() const { + return key_set_.has_all(c10::sparse_csr_ks); + } + + bool is_quantized() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + constexpr auto quantized_ks = DispatchKeySet(DispatchKey::Quantized); + return key_set_.has_all(quantized_ks); + } + + bool is_meta() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_meta(); + } + return device_opt_.has_value() && device_opt_->type() == kMeta; + } + + bool is_cpu() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_cpu(); + } + // Note: we cannot rely on dispatch keys to determine the device type + // of a tensor, because "wrapper" tensors (like FunctionalTensorWrapper) + // don't include backend dispatch keys. + return device_opt_.has_value() && device_opt_->type() == kCPU; + } + + bool is_cuda() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_cuda(); + } + return device_opt_.has_value() && device_opt_->type() == kCUDA; + } + + bool is_xpu() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_xpu(); + } + return device_opt_.has_value() && device_opt_->type() == kXPU; + } + + bool is_ipu() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_ipu(); + } + return device_opt_.has_value() && device_opt_->type() == kIPU; + } + + bool is_xla() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_xla(); + } + return device_opt_.has_value() && device_opt_->type() == kXLA; + } + + bool is_mtia() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_mtia(); + } + return device_opt_.has_value() && device_opt_->type() == kMTIA; + } + + bool is_hpu() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_hpu(); + } + return device_opt_.has_value() && device_opt_->type() == kHPU; + } + + bool is_lazy() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_lazy(); + } + return device_opt_.has_value() && device_opt_->type() == kLazy; + } + + bool is_hip() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_hip(); + } + return device_opt_.has_value() && device_opt_->type() == kHIP; + } + + bool is_ve() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_ve(); + } + return device_opt_.has_value() && device_opt_->type() == kVE; + } + + bool is_privateuseone() const { + // NB: This method is not virtual and avoid dispatches for performance + // reasons. + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_privateuseone(); + } + return device_opt_.has_value() && device_opt_->type() == kPrivateUse1; + } + + bool is_mkldnn() const { + return key_set_.has_all(c10::mkldnn_ks); + } + + bool is_vulkan() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_vulkan(); + } + return device_opt_.has_value() && device_opt_->type() == kVulkan; + } + + bool is_metal() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_metal(); + } + return device_opt_.has_value() && device_opt_->type() == kMetal; + } + + bool is_mps() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_mps(); + } + return device_opt_.has_value() && device_opt_->type() == kMPS; + } + + bool is_ort() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().is_ort(); + } + return device_opt_.has_value() && device_opt_->type() == kORT; + } + + bool is_nested() const { + return key_set_.has(DispatchKey::NestedTensor); + } + + // TODO: remove this once we don't automatically enabled Autograd dispatch + // keys + // in TensorImpl constructor. + // DON'T USE THIS API!! It's only created for testing purpose in + // file aten/src/ATen/core/boxing/impl/test_helpers.h + void remove_autograd_key() { + key_set_ = key_set_ - autograd_dispatch_keyset; + } + + // Inference tensor doesn't have autograd or ADInplaceOrView key. + // Invariant: + // Inference tensor has version_counter_.enabled() == false + bool is_inference() { + bool no_ADInplaceOrView = !key_set_.has_any(c10::inplace_or_view_ks); + bool no_Autograd = !key_set_.has_any(c10::autograd_dispatch_keyset); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + no_ADInplaceOrView == no_Autograd, + "ADInplaceOrView and Autograd keys must be on/off at the same time."); + return no_ADInplaceOrView && no_Autograd; + } + + DeviceIndex get_device() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom().index(); + } + return device_default().index(); + } + + Device device() const { + if (C10_UNLIKELY(device_policy_)) { + return device_custom(); + } + return device_default(); + } + + protected: + c10::Device device_default() const { + TORCH_CHECK(device_opt_.has_value(), "tensor does not have a device"); + // See NOTE [c10::optional operator usage in CUDA] + return *device_opt_; + } + + public: + Layout layout() const { + if (C10_UNLIKELY(layout_policy_)) { + return layout_custom(); + } + + // NB: This method is not virtual and avoid dispatches for perf. + // strided is also the most common layout type, so we check for + // strided case first. + // This keyset must also be kept in sync with the logic in + // is_sparse() / is_sparse_csr() / is_mkldnn() + constexpr auto sparse_and_sparsecsr_and_mkldnn_ks = + c10::sparse_ks | c10::sparse_csr_ks | c10::mkldnn_ks; + if (!key_set_.has_any(sparse_and_sparsecsr_and_mkldnn_ks)) { + return kStrided; + } else if (is_sparse()) { + return kSparse; + } else if (is_sparse_compressed()) { + // Typically, the tensor dispatch keys define the tensor layout + // uniquely. This allows using non-virtual layout method for + // better performance. However, when tensor's layout depends, + // say, on tensor attributes, one must use this execution path + // where the corresponding tensor impl class overwrites virtual + // layout_impl() method. + // + // TODO: implement layout() as native function/method so that + // __torch_dispatch__ users will be able to redefine the + // layout() method. + return layout_impl(); + } else { + TORCH_INTERNAL_ASSERT( + is_mkldnn(), "There is an error in the layout calculation logic."); + return kMkldnn; + } + } + + /** + * True if a tensor was auto-wrapped from a C++ or Python number. + * For example, when you write 't + 2', 2 is auto-wrapped into a Tensor + * with `is_wrapped_number_` set to true. + * + * Wrapped numbers do not participate in the result type computation for + * mixed-type operations if there are any Tensors that are not wrapped + * numbers. This is useful, because we want 't + 2' to work with + * any type of tensor, not just LongTensor (which is what integers + * in Python represent). + * + * Otherwise, they behave like their non-wrapped equivalents. + * See [Result type computation] in TensorIterator.h. + * + * Why did we opt for wrapped numbers, as opposed to just having + * an extra function add(Tensor, Scalar)? This helps greatly reduce + * the amount of code we have to write for add, when actually + * a Tensor-Scalar addition is really just a Tensor-Tensor + * addition when the RHS is 0-dim (except for promotion behavior.) + */ + bool is_wrapped_number() const { + return is_wrapped_number_; + } + + /** + * Set whether or not a tensor was auto-wrapped from a C++ or Python + * number. You probably don't want to call this, unless you are + * writing binding code. + */ + void set_wrapped_number(bool value) { + TORCH_INTERNAL_ASSERT(dim() == 0); + is_wrapped_number_ = value; + } + + /** + * Returns true if Tensor supports as_strided and as_strided_backward. + * This is used in autograd to perform inplace update on view Tensors. + * See Note [View + Inplace update for base tensor] and + * [View + Inplace update for view tensor] for details. + * Note this method only returns true for XLA backend, where it + * simulates strided Tensor to support most view ops, but it cannot + * fully support general `as_strided` case. + * It can be expanded as needed in the future, e.g sparse Tensor. + */ + inline bool support_as_strided() const { + if (is_nested()) { + return false; + } + if (key_set_.has(DispatchKey::Functionalize)) { + return false; + } + return device().supports_as_strided(); + } + + // ~~~~~ Autograd API ~~~~~ + // Some methods below are defined in TensorImpl.cpp because Tensor is an + // incomplete type. + + /** + * Set whether or not a tensor requires gradient. + */ + void set_requires_grad(bool requires_grad); + + /** + * True if a tensor requires gradient. Tensors which require gradient + * have history tracked for any operations performed on them, so that + * we can automatically differentiate back to them. A tensor that + * requires gradient and has no history is a "leaf" tensor, which we + * accumulate gradients into. + */ + bool requires_grad() const; + + /** + * Return a mutable reference to the gradient. This is conventionally + * used as `t.grad() = x` to set a gradient to a completely new tensor. + */ + at::Tensor& mutable_grad(); + + /** + * Return the accumulated gradient of a tensor. This gradient is written + * into when performing backwards, when this tensor is a leaf tensor. + */ + const at::Tensor& grad() const; + + /** + * Whether or not the imaginary part of the tensor should be negated + */ + inline bool is_conj() const { + constexpr auto conjugate_ks = DispatchKeySet(DispatchKey::Conjugate); + return key_set_.has_all(conjugate_ks); + } + + /** + * Set whether or not to take the conjugate of the tensor (flip the imaginary + * bit). + */ + void _set_conj(bool value) { + if (value) { + key_set_ = key_set_.add(DispatchKey::Conjugate); + TORCH_INTERNAL_ASSERT(isComplexType(typeMetaToScalarType(dtype()))); + } else { + key_set_ = key_set_.remove(DispatchKey::Conjugate); + } + } + + /** + * XXX: do not use, private api! + * Update the backend component related keys to the backend component + * corresponding to this device. + */ + void _change_backend_component_keys(c10::Device device); + + /** + * Whether or not the tensor is a zerotensor + */ + inline bool _is_zerotensor() const { + constexpr auto zerotensor_ks = DispatchKeySet(DispatchKey::ZeroTensor); + return key_set_.has_all(zerotensor_ks); + } + + /** + Set whether or not the tensor is a zero tensor + */ + void _set_zero(bool value) { + if (value) { + TORCH_INTERNAL_ASSERT( + false, + "Please call `torch._efficientzerotensor` if you want to create a tensor with no storage."); + } else { + key_set_ = key_set_.remove(DispatchKey::ZeroTensor); + } + } + + /** + * Whether or not the tensor should be negated + */ + inline bool is_neg() const { + constexpr auto negative_ks = DispatchKeySet(DispatchKey::Negative); + return key_set_.has_all(negative_ks); + } + + /** + * Set whether or not to take the conjugate of the tensor (flip the imaginary + * bit). + */ + void _set_neg(bool value) { + if (value) { + key_set_ = key_set_.add(DispatchKey::Negative); + } else { + key_set_ = key_set_.remove(DispatchKey::Negative); + } + } + + /** + * Return the accumulated gradient of a tensor. This gradient is computed + * using forward mode AD. + * + * This is an internal API that should never be used by end users. + * + * The API is as follows: + * - "level" allows to specify the level of forward AD nesting for which the + * gradient should be returned. Note that since levels are not fully + * supported yet, this argument should be 0. See documentation for + * torch::autograd::enter_dual_level for more details about forward AD + * nesting. + * - "self" should represent the Tensor whose forward grad is accessed. It + * is required when dealing with view. + */ + const at::Tensor& _fw_grad(uint64_t level, const at::TensorBase& self) const; + + /** + * Sets the forward gradient for this Tensor. + * The given Tensor might not be used directly and its content will be copied. + * + * This is an internal API that should never be used by end users. + * + * The API is as follows: + * - "new_grad" is a Tensor containing the new value of the gradient that + * should be set + * - "self" should represent the Tensor whose forward grad is accessed. It + * is required when dealing with view. + * - "level" allows to specify the level of forward AD nesting for which the + * gradient should be set. Note that since levels are not fully supported + * yet, this argument should be 0. See documentation for + * torch::autograd::enter_dual_level for more details about forward AD + * nesting. + * - "is_inplace_op" is a boolean flag that tells if this gradient was + * generated by an inplace operation or an out of place one. This allows + * better error checking. + */ + void _set_fw_grad( + const at::TensorBase& new_grad, + const at::TensorBase& self, + uint64_t level, + bool is_inplace_op); + + /** + * Return a typed data pointer to the actual data which this tensor refers to. + * This checks that the requested type (from the template parameter) matches + * the internal type of the tensor. + * + * It is invalid to call data() on a dtype-uninitialized tensor, even if + * the size is 0. + * + * WARNING: If a tensor is not contiguous, you MUST use strides when + * performing index calculations to determine the location of elements in + * the tensor. We recommend using 'TensorAccessor' to handle this computation + * for you; this class is available from 'Tensor'. + */ + template + const T* data_dtype_initialized() const { + return data_dtype_initialized_impl( + [this] { return static_cast(storage_.data()); }); + } + + /** + * Return a mutable typed data pointer to the actual data which this + * tensor refers to. This checks that the requested type (from the + * template parameter) matches the internal type of the tensor. + * + * It is invalid to call data() on a dtype-uninitialized tensor, even if + * the size is 0. + * + * WARNING: If a tensor is not contiguous, you MUST use strides when + * performing index calculations to determine the location of elements in + * the tensor. We recommend using 'TensorAccessor' to handle this computation + * for you; this class is available from 'Tensor'. + */ + template + T* mutable_data_dtype_initialized() { + return data_dtype_initialized_impl( + [this] { return static_cast(storage_.mutable_data()); }); + } + + private: + // Shared implementation of data_dtype_initialized() and + // mutable_data_dtype_initialized(). + template + T* data_dtype_initialized_impl(const Func& get_data) const { + TORCH_CHECK( + data_type_.Match>(), + "Tensor type mismatch, caller expects elements to be ", + caffe2::TypeMeta::TypeName>(), + ", while tensor contains ", + data_type_.name(), + ". "); + return data_ptr_impl_impl(get_data); + } + + public: + /** + * More efficient helper for Tensor::data_ptr(). Like data(), but + * does not do a type check. Unlike the untemplated data(), does + * check has_storage() and storage_initialized(). + */ + template + inline const T* data_ptr_impl() const { + return data_ptr_impl_impl( + [this] { return static_cast(storage_.data()); }); + } + + /** + * More efficient helper for Tensor::data_ptr(). Like data(), but + * does not do a type check. Unlike the untemplated data(), does + * check has_storage() and storage_initialized(). + */ + template + inline T* mutable_data_ptr_impl() { + return data_ptr_impl_impl( + [this] { return static_cast(storage_.mutable_data()); }); + } + + private: + // Shared implementation of mutable_data_ptr_impl() and the future + // mutable_data_ptr_impl(). + template + __ubsan_ignore_pointer_overflow__ T* data_ptr_impl_impl( + const Func& get_data) const { + if (C10_UNLIKELY(!has_storage())) { + throw_data_ptr_access_error(); + } + TORCH_CHECK( + storage_initialized(), + "The tensor has a non-zero number of elements, but its data is not allocated yet. " + "Caffe2 uses a lazy allocation, so you will need to call " + "mutable_data() or raw_mutable_data() to actually allocate memory."); + // Caller does the type check. + // Note: storage_offset_ can be non-null even for zero-elements tensors + // (for example if created as `torch.empty(5)[10:]`) that triggers + // applying non-zero offset to null pointer in UBSan + return get_data() + storage_offset_; + } + + public: + /** + * Return a const void* data pointer to the actual data which this + * tensor refers to. + * + * It is invalid to call data() on a dtype-uninitialized tensor, even if the + * size is 0. + * + * WARNING: The data pointed to by this tensor may not contiguous; do NOT + * assume that itemsize() * numel() is sufficient to compute the bytes that + * can be validly read from this tensor. + */ + inline const void* data() const { + return data_impl( + [this] { return static_cast(storage_.data()); }); + } + + /** + * Return a void* data pointer to the actual data which this tensor refers to. + * + * It is invalid to call mutable_data() on a dtype-uninitialized + * tensor, even if the size is 0. + * + * WARNING: The data pointed to by this tensor may not contiguous; do NOT + * assume that itemsize() * numel() is sufficient to compute the bytes that + * can be validly read from this tensor. + */ + inline void* mutable_data() { + return data_impl( + [this] { return static_cast(storage_.mutable_data()); }); + } + + private: + /// Shared implementation of data() and mutable_data(). + /// + /// get_data must return a byte-addressed pointer, e.g. char*, + /// std::byte const*, etc. + template + Void* data_impl(const Func& get_data) const { + if (C10_UNLIKELY(!has_storage())) { + throw_data_ptr_access_error(); + } + TORCH_CHECK( + dtype_initialized(), + "Cannot access data pointer of Tensor that doesn't have initialized dtype " + "(e.g., caffe2::Tensor x(CPU), prior to calling mutable_data() on x)"); + auto* data = get_data(); + static_assert( + sizeof(*data) == 1, "get_data must return a byte-addressed pointer."); + // Computing an offset into an empty tensor would be UB, since an empty + // tensor's storage will be nullptr, and adding a nonzero offset to nullptr + // is UB. So we skip the offset computation in this case. + if (is_empty()) { + return nullptr; + } + return data + data_type_.itemsize() * storage_offset_; + } + + public: + /** + * Returns the TypeMeta of a tensor, which describes what data type + * it is (e.g., int, float, ...) + */ + const caffe2::TypeMeta dtype() const { + return data_type_; + } + + /** + * Return the size of a single element of this tensor in bytes. + */ + size_t itemsize() const { + TORCH_CHECK( + dtype_initialized(), + "Cannot report itemsize of Tensor that doesn't have initialized dtype " + "(e.g., caffe2::Tensor x(CPU), prior to calling mutable_data() on x)"); + return data_type_.itemsize(); + } + + void set_backend_meta(intrusive_ptr backend_meta) { + get_extra_meta().backend_meta_ = std::move(backend_meta); + } + + c10::BackendMeta* get_backend_meta() { + if (!extra_meta_) { + return nullptr; + } + return extra_meta_->backend_meta_.get(); + } + + intrusive_ptr get_backend_meta_intrusive_ptr() const { + if (!extra_meta_) { + return nullptr; + } + return extra_meta_->backend_meta_; + } + + void release_storage_and_set_meta_custom_data_ptr_error_msg_( + c10::optional s) { + storage_ = {}; + set_storage_access_should_throw(); + get_extra_meta().custom_data_ptr_error_msg_ = s; + get_extra_meta().custom_storage_error_msg_ = std::move(s); + } + + protected: + /** + * Returns the human-readable name of the actual type of this object (e.g., + * TensorImpl, BatchedTensorImpl, etc.). Used for error messages. + */ + virtual const char* tensorimpl_type_name() const { + return "TensorImpl"; + } + + private: + [[noreturn]] void throw_storage_access_error() const; + [[noreturn]] void throw_data_ptr_access_error() const; + + ExtraMeta& get_extra_meta() { + if (!extra_meta_) { + extra_meta_ = std::make_unique(); + } + return *extra_meta_; + } + + c10::SymbolicShapeMeta& symbolic_shape_meta() { + TORCH_INTERNAL_ASSERT(extra_meta_ && extra_meta_->symbolic_shape_meta_); + return *extra_meta_->symbolic_shape_meta_; + } + + const c10::SymbolicShapeMeta& symbolic_shape_meta() const { + TORCH_INTERNAL_ASSERT(extra_meta_ && extra_meta_->symbolic_shape_meta_); + return *extra_meta_->symbolic_shape_meta_; + } + + public: + /** + * True if a tensor has no elements (e.g., numel() == 0). + */ + inline bool is_empty() const { + return numel() == 0; + } + + // if we are going to use sym sizes, we should be setting sym strides at the + // same time, otherwise it's very easy to misuse this API + void set_sizes_and_strides( + c10::SymIntArrayRef sizes, + c10::SymIntArrayRef strides, + c10::optional storage_offset = c10::nullopt); + // This is renamed to avoid breaking overload BC + void generic_set_sizes_contiguous(c10::SymIntArrayRef sizes); + void generic_set_sizes_contiguous(c10::IntArrayRef sizes) { + set_sizes_contiguous(sizes); + } + + /** + * Change the size at some dimension. This DOES NOT update strides; + * thus, most changes to size will not preserve contiguity. You probably + * also want to call set_stride() when you call this. + * + * TODO: This should be jettisoned in favor of `set_sizes_and_strides`, + * which is harder to misuse. + */ + virtual void set_size(int64_t dim, int64_t new_size) { + TORCH_CHECK( + allow_tensor_metadata_change(), + "set_size ", + err_msg_tensor_metadata_change_not_allowed); + TORCH_CHECK( + !matches_policy(SizesStridesPolicy::CustomSizes), + "set_size() called on tensor with dynamic shapes or customized size behavior") + sizes_and_strides_.size_at(dim) = new_size; + refresh_numel(); + refresh_contiguous(); + } + + /** + * Change the stride at some dimension. + * + * TODO: This should be jettisoned in favor of `set_sizes_and_strides`, + * which is harder to misuse. + */ + virtual void set_stride(int64_t dim, int64_t new_stride) { + TORCH_CHECK( + allow_tensor_metadata_change(), + "set_stride ", + err_msg_tensor_metadata_change_not_allowed); + TORCH_CHECK( + !has_symbolic_sizes_strides_, + "set_stride() called on tensor with symbolic shape") + sizes_and_strides_.stride_at_unchecked(dim) = new_stride; + refresh_contiguous(); + } + + /** + * Set the offset into the storage of this tensor. + * + * WARNING: This does NOT check if the tensor is in bounds for the new + * location at the storage; the caller is responsible for checking this + * (and resizing if necessary.) + */ + virtual void set_storage_offset(int64_t storage_offset) { + TORCH_CHECK( + allow_tensor_metadata_change(), + "set_storage_offset ", + err_msg_tensor_metadata_change_not_allowed); + // TODO: this should probably consult policy + TORCH_CHECK( + !has_symbolic_sizes_strides_, + "set_storage_offset() called on tensor with symbolic shape") + storage_offset_ = storage_offset; + } + + /** + * Like set_sizes_and_strides but assumes contiguous strides. + * + * WARNING: This function does not check if the requested + * sizes/strides are in bounds for the storage that is allocated; + * this is the responsibility of the caller + */ + void set_sizes_contiguous(IntArrayRef new_size) { + TORCH_CHECK( + allow_tensor_metadata_change(), + "set_sizes_contiguous ", + err_msg_tensor_metadata_change_not_allowed); + TORCH_CHECK( + !matches_policy(SizesStridesPolicy::CustomStrides), + "tried to directly modify sizes for customized tensor"); + sizes_and_strides_.set_sizes(new_size); + + refresh_numel(); + empty_tensor_restride( + MemoryFormat::Contiguous); // calls refresh_contiguous() + } + + /** + * Set the sizes and strides of a tensor. + * + * WARNING: This function does not check if the requested + * sizes/strides are in bounds for the storage that is allocated; + * this is the responsibility of the caller + */ + void set_sizes_and_strides( + IntArrayRef new_size, + IntArrayRef new_stride, + c10::optional storage_offset = c10::nullopt) { + TORCH_CHECK( + allow_tensor_metadata_change(), + "set_sizes_and_strides ", + err_msg_tensor_metadata_change_not_allowed); + TORCH_CHECK( + !has_symbolic_sizes_strides_, + "set_sizes_and_strides() called on tensor with symbolic shape") + TORCH_CHECK( + new_size.size() == new_stride.size(), + "dimensionality of sizes (", + new_size.size(), + ") must match dimensionality of strides (", + new_stride.size(), + ")"); + const auto new_dim = new_size.size(); + bool overflowed = false; + sizes_and_strides_.set_sizes(new_size); + + if (new_dim > 0) { + for (size_t dim = new_dim - 1;; dim--) { + if (new_stride[dim] >= 0) { + sizes_and_strides_.stride_at_unchecked(dim) = new_stride[dim]; + } else { + // XXX: This behavior is surprising and may need to be removed to + // support negative strides. Some pytorch functions rely on it: + // for example, torch.cat (run TestTorch.test_cat_empty). + if (dim == new_dim - 1) { + sizes_and_strides_.stride_at_unchecked(dim) = 1; + } else { + // Keep stride monotonically increasing to match NumPy. + overflowed |= c10::mul_overflows( + sizes_and_strides_.stride_at_unchecked(dim + 1), + std::max( + sizes_and_strides_.size_at_unchecked(dim + 1), 1), + std::addressof(sizes_and_strides_.stride_at_unchecked(dim))); + } + } + if (dim == 0) + break; + } + TORCH_CHECK(!overflowed, "Stride calculation overflowed"); + } + + refresh_numel(); + refresh_contiguous(); + + if (storage_offset.has_value()) { + storage_offset_ = *storage_offset; + } + } + + /** + * Set whether a tensor allows changes to its metadata (e.g. sizes / strides / + * storage / storage_offset). See NOTE [ Metadata Change for a Detached Tensor + * ] for details. + */ + void set_allow_tensor_metadata_change(bool value) { + // TODO: at some point, we should kill this field completely. + allow_tensor_metadata_change_ = true; + } + + /** + * True if a tensor allows changes to its metadata (e.g. sizes / strides / + * storage / storage_offset). See NOTE [ Metadata Change for a Detached Tensor + * ] for details. + */ + bool allow_tensor_metadata_change() const { + return allow_tensor_metadata_change_; + } + + /** + * Set the pointer to autograd metadata. + */ + void set_autograd_meta( + std::unique_ptr autograd_meta); + + /** + * Return the pointer to autograd metadata. May return nullptr if the + * tensor does not track gradients. + */ + c10::AutogradMetaInterface* autograd_meta() const; + + /** + * Set the pointer to named tensor metadata. + */ + void set_named_tensor_meta( + std::unique_ptr named_tensor_meta) { + TORCH_WARN_ONCE( + "Named tensors and all their associated APIs are an experimental feature ", + "and subject to change. Please do not use them for anything important ", + "until they are released as stable."); +#ifdef DEBUG + if (named_tensor_meta) { + TORCH_INTERNAL_ASSERT(named_tensor_meta->slow_dim() == dim()); + } +#endif + if (named_tensor_meta) { + get_extra_meta().named_tensor_meta_ = std::move(named_tensor_meta); + key_set_ = key_set_.add(DispatchKey::Named); + } else { + if (extra_meta_) { + extra_meta_->named_tensor_meta_ = nullptr; + } + key_set_ = key_set_.remove(DispatchKey::Named); + } + } + + void set_python_dispatch(bool k) { + if (k) { + key_set_ = key_set_.add(c10::python_ks); + } else { + key_set_ = key_set_ - c10::python_ks; + } + } + + bool is_python_dispatch() const { + return key_set_.has_all(c10::python_ks); + } + + /** + * Return the pointer to named tensor metadata. + */ + const c10::NamedTensorMetaInterface* named_tensor_meta() const { + if (!extra_meta_) { + return nullptr; + } + return extra_meta_->named_tensor_meta_.get(); + } + + c10::NamedTensorMetaInterface* named_tensor_meta() { + if (!extra_meta_) { + return nullptr; + } + return extra_meta_->named_tensor_meta_.get(); + } + + bool has_named_tensor_meta() const { + if (!extra_meta_) { + return false; + } + return extra_meta_->named_tensor_meta_ != nullptr; + } + + // NOTE [ TensorImpl Shallow-Copying ] + // + // TensorImpl shallow-copying is used when we want to have two Variables share + // the same tensor metadata (e.g. sizes / strides / storage pointer / + // storage_offset), but each with a different autograd history. Example call + // sites: + // + // 1. `var_detached = var.detach()` uses `shallow_copy_and_detach()` to create + // `var_detached` that shares the same tensor metadata with `var`, but with a + // completely new autograd history. + // 2. `var.set_data(tensor)` uses `shallow_copy_from()` to copy tensor + // metadata from `tensor` into `var`, while keeping `var`'s original + // AutogradMeta. + // + // Functions that shallow-copy a TensorImpl (such as + // `shallow_copy_and_detach()` / `shallow_copy_from()` / + // `copy_tensor_metadata()`) copy the tensor metadata fields (e.g. sizes / + // strides / storage pointer / storage_offset) by value. However, the + // following fields are not copied: + // + // 1. the AutogradMeta pointer, because it is unique for each Variable. + // 2. the version counter, because the destination TensorImpl's version + // counter is either set to the passed-in `version_counter` (in + // `shallow_copy_and_detach()` and `copy_tensor_metadata()`), or it is kept + // intact (in `shallow_copy_from()`). See NOTE [ Version Counter Sharing ] for + // details. + // + // In `shallow_copy_and_detach()` and `copy_tensor_metadata()`, the passed-in + // `allow_tensor_metadata_change` determines whether the TensorImpl + // shallow-copy allows changes to its metadata (e.g. sizes / strides / storage + // / storage_offset). See NOTE [ Metadata Change for a Detached Tensor ] for + // details. + // + // In `shallow_copy_from()`, we don't check the destination TensorImpl's + // `allow_tensor_metadata_change_`, because `shallow_copy_from()` is used for + // implementing functions such as `var.set_data(tensor)`, which changes + // `var`'s tensor metadata and expects its `allow_tensor_metadata_change_` to + // be ignored. + + /** + * One TensorImpl can be copied to another TensorImpl if they have the same + * DispatchKeySet. The only two special cases (for legacy reason) are: + * CPU is compatible with CUDA and SparseCPU is + * compatible with SparseCUDA. + */ + inline bool has_compatible_shallow_copy_type(DispatchKeySet from) { + auto is_dense = [](DispatchKeySet ts) { + constexpr auto dense_backends = DispatchKeySet( + {BackendComponent::CPUBit, + BackendComponent::CUDABit, + BackendComponent::MPSBit, + BackendComponent::HIPBit, + BackendComponent::XPUBit, + BackendComponent::HPUBit}); + constexpr auto dense_k = DispatchKeySet(DispatchKey::Dense); + return ts.has_any(dense_k) && ts.has_any(dense_backends); + }; + auto is_sparse = [](DispatchKeySet ts) { + constexpr auto sparse_backends = DispatchKeySet( + {BackendComponent::CPUBit, + BackendComponent::CUDABit, + BackendComponent::HIPBit, + BackendComponent::XPUBit}); + constexpr auto sparse_k = DispatchKeySet(DispatchKey::Sparse); + return ts.has_any(sparse_k) && ts.has_any(sparse_backends); + }; + auto is_sparse_compressed = [](DispatchKeySet ts) { + constexpr auto sparse_compressed_k = + DispatchKeySet(DispatchKey::SparseCsr); + return ts.has_any(sparse_compressed_k); + }; + return (key_set_ == from) || (is_dense(key_set_) && is_dense(from)) || + (is_sparse(key_set_) && is_sparse(from)) || + (is_sparse_compressed(key_set_) && is_sparse_compressed(from)); + ; + } + + private: + template + c10::intrusive_ptr shallow_copy_and_detach_core( + VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const; + + public: + /** + * Return a TensorImpl that is a shallow-copy of this TensorImpl. + * + * For usage of `version_counter` and `allow_tensor_metadata_change`, + * see NOTE [ TensorImpl Shallow-Copying ]. + */ + virtual c10::intrusive_ptr shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const; + + /** + * Return a TensorImpl that is a shallow-copy of this TensorImpl. + * + * For usage of `version_counter` and `allow_tensor_metadata_change`, + * see NOTE [ TensorImpl Shallow-Copying ]. + */ + virtual c10::intrusive_ptr shallow_copy_and_detach( + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const; + + /** + * Shallow-copies data from another TensorImpl into this TensorImpl. + * + * For why this function doesn't check this TensorImpl's + * `allow_tensor_metadata_change_`, see NOTE [ TensorImpl Shallow-Copying ]. + */ + virtual void shallow_copy_from(const c10::intrusive_ptr& impl) { + copy_tensor_metadata( + /*src_impl=*/impl.get(), + /*dest_impl=*/this, + /*version_counter=*/version_counter(), + /*allow_tensor_metadata_change=*/allow_tensor_metadata_change()); + } + + // Inference tensor doesn't have version counter, + // set_version_counter is no-op for them. + void set_version_counter(const c10::VariableVersion& version_counter) { + TORCH_CHECK( + !(is_inference() && version_counter.enabled()), + "Cannot set version_counter for inference tensor"); + version_counter_ = version_counter; + } + + void set_version_counter(c10::VariableVersion&& version_counter) { + TORCH_CHECK( + !(is_inference() && version_counter.enabled()), + "Cannot set version_counter for inference tensor"); + version_counter_ = std::move(version_counter); + } + + const c10::VariableVersion& version_counter() const noexcept { + return version_counter_; + } + + void bump_version() { + version_counter_.bump(); + } + + impl::PyObjectSlot* pyobj_slot() { + return &pyobj_slot_; + } + + const impl::PyObjectSlot* pyobj_slot() const { + return &pyobj_slot_; + } + + private: + // See NOTE [c10::optional operator usage in CUDA] + // We probably don't want to expose this publicly until + // the note is addressed. + c10::optional device_opt() const { + return device_opt_; + } + + public: + /** + * The device type of a Tensor, e.g., DeviceType::CPU or DeviceType::CUDA. + */ + DeviceType device_type() const { + // TODO: A useful internal assert would be to show that device_opt_ is null + // only if you are an undefined tensor + TORCH_CHECK( + device_opt_.has_value(), + "device_type cannot be run on undefined Tensor"); + // See NOTE [c10::optional operator usage in CUDA] + return (*device_opt_).type(); + } + + /** + * @brief Extends the outer-most dimension of this tensor by num elements, + * preserving the existing data. + * + * The underlying data may be reallocated in order to accommodate the new + * elements, in which case this tensors' capacity is grown at a factor of + * growthPct. This ensures that Extend runs on an amortized O(1) time + * complexity. + * + * This op is auto-asynchronous if the underlying device (CUDA) supports it. + */ + void Extend(int64_t num, float growthPct); + + /** + * @brief Reserve space for the underlying tensor. + * + * This must be called after Resize(), since we only specify the first + * dimension This does not copy over the old data to the newly allocated space + */ + void ReserveSpace(int64_t outer_dim); + + /** + * @brief Resizes a tensor. + * + * Resize takes in a vector of ints specifying the dimensions of the tensor. + * You can pass in an empty vector to specify that it is a scalar (i.e. + * containing one single item). + * + * The underlying storage may be deleted after calling Resize: if the new + * shape leads to a different number of items in the tensor, the old memory + * is deleted and new memory will be allocated next time you call + * mutable_data(). However, if the shape is different but the total number of + * items is the same, the underlying storage is kept. + * + * This method respects caffe2_keep_on_shrink. Consult the internal logic + * of this method to see exactly under what circumstances this flag matters. + */ + template + void Resize(Ts... dim_source) { + bool size_changed = SetDims(dim_source...); + if (size_changed) { + HandleResize(); + } + } + + template + void Resize(const std::vector& dim_source) { + Resize(ArrayRef(dim_source)); + } + + /** + * Resizes the tensor without touching underlying storage. + * This requires the total size of the tensor to remains constant. + */ + void Reshape(const std::vector& dims); + + /** + * Release whatever memory the tensor was holding but keep size and type + * information. Subsequent call to mutable_data will trigger new memory + * allocation. + */ + void FreeMemory(); + + /** + * @brief Shares the data with another tensor. + * + * To share data between two tensors, the sizes of the two tensors must be + * equal already. The reason we do not implicitly do a Resize to make the two + * tensors have the same shape is that we want to allow tensors of different + * shapes but the same number of items to still be able to share data. This + * allows one to e.g. have a n-dimensional Tensor and a flattened version + * sharing the same underlying storage. + * + * The source tensor should already have its data allocated. + */ + // To be deprecated + void ShareData(const TensorImpl& src); + + void ShareExternalPointer( + DataPtr&& data_ptr, + const caffe2::TypeMeta data_type, + size_t size_bytes); + + /** + * Returns a mutable raw pointer of the underlying storage. Since we will need + * to know the type of the data for allocation, a TypeMeta object is passed in + * to specify the necessary information. This is conceptually equivalent of + * calling mutable_data() where the TypeMeta parameter meta is derived from + * the type T. This function differs from mutable_data() in the sense that + * the type T can be specified during runtime via the TypeMeta object. + * + * If the existing data does not match the desired type, it will be deleted + * and a new storage will be created. + */ + inline void* raw_mutable_data(const caffe2::TypeMeta& meta) { + // For 0-size tensors it's fine to return any pointer (including nullptr) + if (data_type_ == meta && storage_initialized()) { + return static_cast( + static_cast(storage_.mutable_data()) + + storage_offset_ * meta.itemsize()); + } else { + bool had_special_dtor = data_type_.placementDelete() != nullptr; + storage_offset_ = 0; + data_type_ = meta; + // NB: device is not changed + + // We can reuse the existing buffer if the current data does not have + // a special destructor and the new data doesn't have a special + // constructor. + if (numel_ == 0 || + (meta.placementNew() == nullptr && !had_special_dtor && + (storage_.nbytes() >= (numel_ * data_type_.itemsize())))) { + TORCH_INTERNAL_ASSERT( + storage_offset_ == 0); // because we just reallocated + return storage_.mutable_data(); + } + Allocator* allocator = storage_.allocator(); + // Storage might have nullptr allocator in rare cases, for example, if + // an external memory segment has been wrapped with Tensor and we don't + // know how to reallocate it. However, in order to preserve legacy C2 + // behavior, we allow reallocating the memory using default allocator. + if (allocator == nullptr) { + allocator = GetAllocator(storage_.device_type()); + } + if (meta.placementNew()) { + // For types that need placement new, we will call it, as well as + // making sure that when the data is freed, it calls the right + // destruction procedure. + auto size = numel_; + auto dtor = data_type_.placementDelete(); + auto data_ptr = allocator->allocate(numel_ * data_type_.itemsize()); + storage_.set_data_ptr_noswap(PlacementDeleteContext::makeDataPtr( + std::move(data_ptr), dtor, size, storage_.device())); + data_type_.placementNew()(storage_.mutable_data(), numel_); + } else { + // For fundamental type, new and delete is easier. + storage_.set_data_ptr_noswap( + allocator->allocate(numel_ * data_type_.itemsize())); + } + storage_.set_nbytes(numel_ * data_type_.itemsize()); + TORCH_INTERNAL_ASSERT( + storage_offset_ == 0); // because we just reallocated + device_opt_ = storage_.device(); + return storage_.mutable_data(); + } + } + + /** + * Returns a typed pointer of the underlying storage. + * + * For fundamental types, we reuse possible existing storage if there + * is sufficient capacity. + */ + template + inline T* mutable_data() { + if (storage_initialized() && data_type_.Match()) { + return static_cast(storage_.mutable_data()) + storage_offset_; + } + // Check it here statically - otherwise TypeMeta would throw the runtime + // error in attempt to invoke TypeMeta::ctor() + static_assert( + std::is_default_constructible::value, + "Tensor can't hold non-default-constructable types"); + return static_cast(raw_mutable_data(caffe2::TypeMeta::Make())); + } + + /** + * True if a tensor is storage initialized. A tensor may become + * storage UNINITIALIZED after a Resize() or FreeMemory() + */ + bool storage_initialized() const { + TORCH_CHECK( + has_storage(), + "cannot call storage_initialized on tensor that does not have storage"); + return storage_.data() || numel_ == 0; + } + + /** + * True if a tensor is dtype initialized. A tensor allocated with + * Caffe2-style constructors is dtype uninitialized until the + * first time mutable_data() is called. + */ + bool dtype_initialized() const noexcept { + return data_type_ != caffe2::TypeMeta(); + } + + void set_storage_keep_dtype(at::Storage storage) { + TORCH_CHECK( + allow_tensor_metadata_change(), + "set_storage ", + err_msg_tensor_metadata_change_not_allowed); + storage_ = std::move(storage); + device_opt_ = storage_.device(); + } + + void set_storage_and_dtype( + at::Storage storage, + const caffe2::TypeMeta data_type) { + set_storage_keep_dtype(std::move(storage)); + data_type_ = data_type; + } + + void empty_tensor_restride_symint(MemoryFormat memory_format); + + /** + * Set the strides of the tensor to match memory_format + * + * WARNING: This function doesn't rearrange data and assumes tensor is a + * memory contiguous + */ + void empty_tensor_restride(MemoryFormat memory_format) { + if (has_symbolic_sizes_strides_) { + empty_tensor_restride_symint(memory_format); + return; + } +#ifdef DEBUG + TORCH_INTERNAL_ASSERT( + compute_numel() == numel_, + "If you are seeing this error, that means empty_tensor_restride was " + "called before setting correct numel"); +#endif + switch (memory_format) { + case MemoryFormat::Contiguous: { + // dim_ is a virtual call, don't repeat it + const auto dim_ = dim(); + sizes_and_strides_.resize(dim_); + if (dim_ > 0) { + bool overflowed = false; + const auto last_idx = dim_ - 1; + sizes_and_strides_.stride_at_unchecked(last_idx) = 1; + for (auto i = last_idx - 1; i >= 0; --i) { + overflowed |= c10::mul_overflows( + sizes_and_strides_.stride_at_unchecked(i + 1), + std::max( + sizes_and_strides_.size_at_unchecked(i + 1), 1), + std::addressof(sizes_and_strides_.stride_at_unchecked(i))); + } + TORCH_CHECK(!overflowed, "Stride calculation overflowed"); + } + break; + } + case MemoryFormat::ChannelsLast: { + TORCH_CHECK( + dim() == 4, "required rank 4 tensor to use channels_last format"); + set_sizes_and_strides(sizes(), get_channels_last_strides_2d(sizes())); + break; + } + case MemoryFormat::ChannelsLast3d: { + TORCH_CHECK( + dim() == 5, + "required rank 5 tensor to use channels_last_3d format"); + set_sizes_and_strides(sizes(), get_channels_last_strides_3d(sizes())); + break; + } + case MemoryFormat::Preserve: + TORCH_CHECK(false, "unsupported memory format ", memory_format); + // Cleaning warning messages, no need to break as TORCH_CHECK(false) + // terminates flow. + // break; + case MemoryFormat::NumOptions: + TORCH_INTERNAL_ASSERT(false, "invalid memory format ", memory_format); + } + // recompute contiguous flag, as currently NHWC/NCHW flags are not mutually + // exclusive see #24090 + refresh_contiguous(); + } + + bool is_strides_like(at::MemoryFormat memory_format) const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomStrides))) { + return is_strides_like_custom(memory_format); + } + return is_strides_like_default(memory_format); + } + + bool is_strides_like_channels_last() const { + return is_strides_like(at::MemoryFormat::ChannelsLast); + } + + bool is_strides_like_channels_last_3d() const { + return is_strides_like(at::MemoryFormat::ChannelsLast3d); + } + + bool is_non_overlapping_and_dense() const { + if (C10_UNLIKELY(matches_policy(SizesStridesPolicy::CustomStrides))) { + return is_non_overlapping_and_dense_custom(); + } + return is_non_overlapping_and_dense_default(); + } + + bool has_symbolic_sizes_strides() const { + return has_symbolic_sizes_strides_; + } + + private: + void HandleResize(); + + // The Caffe2 Resize() method supports being called both as Resize({2,2}) as + // well as variadic with Resize(2, 2). These overloads provide all of the + // supported calling configurations, while being overloads (and not templates) + // so that implicit conversions still work. + // + // SetDims on ArrayRef is internally implemented as a template, so we can + // handle both ArrayRefs of different types (there are some uses of + // Resize in Caffe2 which pass in int, not int64_t.) + + template < + typename T, + typename = typename std::enable_if_t>> + bool SetDimsTemplate(ArrayRef src) { + TORCH_CHECK( + !has_symbolic_sizes_strides_, + "SetDims() called on tensor with symbolic shape") + + auto old_numel = numel_; + sizes_and_strides_.resize(src.size()); + int64_t new_numel = 1; + for (const auto i : c10::irange(src.size())) { + new_numel *= src[i]; + sizes_and_strides_.size_at_unchecked(i) = src[i]; + } + numel_ = new_numel; + empty_tensor_restride(MemoryFormat::Contiguous); + return numel_ != old_numel; + } + + bool SetDims(ArrayRef s) { + return SetDimsTemplate(s); + } + + bool SetDims(ArrayRef s) { + return SetDimsTemplate(s); + } + + bool SetDims(ArrayRef s) { + return SetDimsTemplate(s); + } + + bool SetDims() { + return SetDims(IntArrayRef{}); + } + + bool SetDims(const int64_t d0) { + return SetDims(IntArrayRef{d0}); + } + + bool SetDims(const int64_t d0, const int64_t d1) { + return SetDims(IntArrayRef{d0, d1}); + } + + bool SetDims(const int64_t d0, const int64_t d1, const int64_t d2) { + return SetDims(IntArrayRef{d0, d1, d2}); + } + + bool SetDims( + const int64_t d0, + const int64_t d1, + const int64_t d2, + const int64_t d3) { + return SetDims(IntArrayRef{d0, d1, d2, d3}); + } + + /** + * Compute the number of elements based on the sizes of a tensor. + */ + // NB: This is ONLY called when sizes_and_strides_ is used directly; if + // we are virtualizing, then numel calls are virtualized as well, and this + // should never get called + int64_t compute_numel() const { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!has_symbolic_sizes_strides_); +#if C10_HAS_BUILTIN_OVERFLOW() && !defined(C10_MOBILE) + // Use overflow checks if supported by the compiler + return safe_compute_numel(); +#else + return c10::multiply_integers(sizes_and_strides_.sizes_arrayref()); +#endif + } + + /** + * Compute the number of elements based on the sizes of a + * tensor. Catches integer overflow that may occur when a tensor + * using a sparse layout has multiple dimensions with large sizes. + */ + int64_t safe_compute_numel() const { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!has_symbolic_sizes_strides_); + uint64_t n = 1; + bool overflows = + c10::safe_multiplies_u64(sizes_and_strides_.sizes_arrayref(), &n); + constexpr auto numel_max = std::min( + static_cast(std::numeric_limits::max()), + static_cast(std::numeric_limits::max())); + + overflows |= (n > numel_max); + TORCH_CHECK(!overflows, "numel: integer multiplication overflow"); + return static_cast(n); + } + + /** + * Compute whether or not a tensor is contiguous based on the sizes and + * strides of a tensor. + */ + bool compute_contiguous(identity) const; + + bool compute_channels_last_contiguous_2d(identity) const; + + bool compute_channels_last_contiguous_3d(identity) const; + + bool compute_strides_like_channels_last_2d(identity) const; + + bool compute_strides_like_channels_last_3d(identity) const; + + bool compute_non_overlapping_and_dense(identity) const; + + protected: + /** + * Recompute the cached numel of a tensor. Call this if you modify + * sizes. + * + * For tensors with sparse layouts, use safe_refresh_numel() instead + * because it will catch integer overflow that may occur for tensors + * with sparse layouts and large dimensions. + * + * NB: We may uselessly recompute cached numel even in situations where + * it is completely never used (e.g., if CustomSizes for Python). However, + * we still must keep it up to date in case the Python overload + * returns None (in which case we will consult the field here). This also + * implies that sizes/strides will never be complete garbage; in the + * very worst case scenario, it will reflect a 1-dim zero size tensor. + */ + void refresh_numel() { + if (has_symbolic_sizes_strides_) { + symbolic_shape_meta().refresh_numel(); + } else { + numel_ = compute_numel(); + } + } + + /** + * Recompute the cached numel of a tensor. Call this if you modify + * sizes. Use only for tensors with sparse layouts because only + * sparse tensor are likely to have sizes that may lead to integer + * overflow when computing numel. + */ + void safe_refresh_numel() { + if (has_symbolic_sizes_strides_) { + // NB: sym numel is done with symbolic integers, which handle overflow + // checking + symbolic_shape_meta().refresh_numel(); + } else { + numel_ = safe_compute_numel(); + } + } + + private: + // NB: the TypeId argument prevents confusion where you pass a true/false + // literal and pick the wrong overload + + void _set_is_contiguous(identity, bool b) { + is_contiguous_ = b; + } + + void _set_is_channels_last_contiguous(identity, bool b) { + is_channels_last_contiguous_ = b; + } + + void _set_is_channels_last_3d_contiguous(identity, bool b) { + is_channels_last_3d_contiguous_ = b; + } + + void _set_is_channels_last(identity, bool b) { + is_channels_last_ = b; + } + + void _set_is_channels_last_3d(identity, bool b) { + is_channels_last_3d_ = b; + } + + void _set_is_non_overlapping_and_dense(identity, bool b) { + is_non_overlapping_and_dense_ = b; + } + + // These are little wrappers over the real compute_ functions that + // can make use of other contiguity fields to short circuit. + + bool compute_is_non_overlapping_and_dense_dim4(identity type_id) { + return is_contiguous_ || is_channels_last_contiguous_ || + compute_non_overlapping_and_dense(type_id); + } + + bool compute_channels_last_contiguous_3d_dim5(identity type_id) { + return !is_channels_last_contiguous_ && + compute_channels_last_contiguous_3d(type_id); + } + + bool compute_channels_last_2d_dim5(identity type_id) { + return !is_channels_last_3d_contiguous_ && + compute_strides_like_channels_last_2d(type_id); + } + + bool compute_channels_last_3d_dim5(identity type_id) { + return !is_channels_last_ && compute_strides_like_channels_last_3d(type_id); + } + + bool compute_is_non_overlapping_and_dense_dim5(identity type_id) { + return is_contiguous_ || is_channels_last_contiguous_ || + is_channels_last_3d_contiguous_ || + compute_non_overlapping_and_dense(type_id); + } + + bool compute_is_non_overlapping_and_dense_anydim(identity type_id) { + return is_contiguous_ || compute_non_overlapping_and_dense(type_id); + } + + template + void _refresh_contiguous() { + auto type_id = identity(); + // Note: + // Dim 0, 1, 2 will never be a channels last 2d/3d format + // Dim 3+ is possibly be a channels last 2d format (Dim 4 only at this + // point) Dim 4+ is possibly be a channels last 3d format (Dim 5 only at + // this point) + switch (dim()) { + case 4: { + _set_is_contiguous(type_id, compute_contiguous(type_id)); + _set_is_channels_last_contiguous( + type_id, compute_channels_last_contiguous_2d(type_id)); + _set_is_channels_last_3d_contiguous(type_id, false); + _set_is_channels_last( + type_id, compute_strides_like_channels_last_2d(type_id)); + _set_is_channels_last_3d(type_id, false); + _set_is_non_overlapping_and_dense( + type_id, compute_is_non_overlapping_and_dense_dim4(type_id)); + break; + } + case 5: { + _set_is_contiguous(type_id, compute_contiguous(type_id)); + _set_is_channels_last_contiguous( + type_id, compute_channels_last_contiguous_2d(type_id)); + _set_is_channels_last_3d_contiguous( + type_id, compute_channels_last_contiguous_3d_dim5(type_id)); + _set_is_channels_last(type_id, compute_channels_last_2d_dim5(type_id)); + _set_is_channels_last_3d( + type_id, compute_channels_last_3d_dim5(type_id)); + _set_is_non_overlapping_and_dense( + type_id, compute_is_non_overlapping_and_dense_dim5(type_id)); + break; + } + default: + // is_channels_last_ and is_channels_last_3d_ are suggested + // memory_format. Being channels_last_contiguous doesn't necessarily + // mean the tensor is strided like channels_last: for strides on channel + // dimension could suggest desired memory_layout, but it doesn't affect + // memory storage + _set_is_contiguous(type_id, compute_contiguous(type_id)); + _set_is_channels_last_contiguous(type_id, false); + _set_is_channels_last_3d_contiguous(type_id, false); + _set_is_channels_last(type_id, false); + _set_is_channels_last_3d(type_id, false); + _set_is_non_overlapping_and_dense( + type_id, compute_is_non_overlapping_and_dense_anydim(type_id)); + break; + } + } + + protected: + /** + * Recompute the cached contiguity of a tensor. Call this if you modify sizes + * or strides. + */ + void refresh_contiguous() { + if (has_symbolic_sizes_strides_) { + symbolic_shape_meta().refresh_contiguous(); + } else { + _refresh_contiguous(); + } + } + + /** + * Copy the tensor metadata fields (e.g. sizes / strides / storage pointer / + * storage_offset) from one TensorImpl to another TensorImpl. + * + * For usage of `version_counter` and `allow_tensor_metadata_change`, see NOTE + * [ TensorImpl Shallow-Copying ]. + */ + static void copy_tensor_metadata( + const TensorImpl* src_impl, + TensorImpl* dest_impl, + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change); + + /** + * Copy the tensor metadata fields (e.g. sizes / strides / storage pointer / + * storage_offset) from one TensorImpl to another TensorImpl. + * + * For usage of `version_counter` and `allow_tensor_metadata_change`, see NOTE + * [ TensorImpl Shallow-Copying ]. + */ + static void copy_tensor_metadata( + const TensorImpl* src_impl, + TensorImpl* dest_impl, + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change); + + private: + static void copy_tensor_metadata_except_version_counter( + const TensorImpl* src_impl, + TensorImpl* dest_impl, + bool allow_tensor_metadata_change); + + protected: + // Error message to show when the user tries to change tensor metadata on + // Tensor created from .data or .detach(). + // + // See NOTE [ Metadata Change for a Detached Tensor ] for details. + static const char* const err_msg_tensor_metadata_change_not_allowed; + + static void copy_generic_tensor_metadata( + const TensorImpl* src_impl, + TensorImpl* dest_impl); + + public: + void set_storage_access_should_throw() { + storage_access_should_throw_ = true; + } + + public: + void set_custom_sizes_strides(SizesStridesPolicy policy) { + custom_sizes_strides_ = static_cast(policy); + refresh_sizes_strides_policy(); + } + + void set_python_custom_sizes_strides(SizesStridesPolicy policy) { + python_custom_sizes_strides_ = static_cast(policy); + refresh_sizes_strides_policy(); + } + + void set_custom_device(bool custom_device) { + custom_device_ = custom_device; + refresh_device_policy(); + } + + void set_custom_layout(bool custom_layout) { + custom_layout_ = custom_layout; + refresh_layout_policy(); + } + + void set_python_custom_device(bool custom_device) { + python_custom_device_ = custom_device; + refresh_device_policy(); + } + + void set_python_custom_layout(bool custom_layout) { + python_custom_layout_ = custom_layout; + refresh_layout_policy(); + } + + protected: + void refresh_sizes_strides_policy() { + if (has_symbolic_sizes_strides_) { + sizes_strides_policy_ = + static_cast(SizesStridesPolicy::CustomSizes); + } else { + sizes_strides_policy_ = + std::max(custom_sizes_strides_, python_custom_sizes_strides_); + } + } + + void refresh_device_policy() { + device_policy_ = custom_device_ || python_custom_device_; + } + + void refresh_layout_policy() { + layout_policy_ = custom_layout_ || python_custom_layout_; + } + + protected: + Storage storage_; + + private: + // This pointer points to an AutogradMeta struct that stores autograd-specific + // fields (such as grad_ / grad_fn_ / grad_accumulator_). This pointer always + // has unique ownership (meaning only one TensorImpl can own it at a time). + // + // autograd_meta_ can be nullptr, as an optimization. When this occurs, it is + // equivalent to having an autograd_meta_ pointing to a default constructed + // AutogradMeta; intuitively, tensors which don't require grad will have this + // field set to null. + // + // This means accessors on autograd_meta_ have to be careful to test if they + // got a nullptr, and handle default behavior appropriately in that case. + // + // Note that we don't enforce the invariant that if the AutogradMeta is + // default constructed, it is nullptr (to do this, we'd have to continuously + // check if an AutogradMeta became, by mutation, equal to the default + // constructed form. (This might be useful, but it seems rare enough that + // a requires_grad=True variable will turn back into the requires_grad=False + // version.) So there are three representable states: + // + // 1. autograd_meta_ == nullptr + // 2. autograd_meta_ is default constructed (semantically, same as (1)) + // 3. autograd_meta_ has nontrivial information content + // + std::unique_ptr autograd_meta_ = nullptr; + + protected: + std::unique_ptr extra_meta_ = nullptr; + + c10::VariableVersion version_counter_; + + impl::PyObjectSlot pyobj_slot_; + + c10::impl::SizesAndStrides sizes_and_strides_; + + int64_t storage_offset_ = 0; + // If sizes and strides are empty, the numel is 1!! However, most of the + // time, we will immediately set sizes to {0} and reset numel to 0. + // (Can't do that in the default initializers, because there's no way to + // spell "allocate a one-element array" for strides_). + int64_t numel_ = 1; + + // INVARIANT: When storage is non-null, this type meta must + // agree with the type meta in storage + caffe2::TypeMeta data_type_; + + // NOTE [c10::optional operator usage in CUDA] + // Our optional definition doesn't compile in .cu file if `value()` or + // `operator->` are used. Instead, we always use `operator*`. + // See https://github.com/pytorch/pytorch/issues/18496 for more info. + // If this is too burdensome to maintain, we can just + // manually implement this with an additional bool. + + // INVARIANT: When storage is non-null, this Device must + // agree with the type meta in storage. + // + // INVARIANT: device_opt_ is only nullopt for undefined tensors + // (which do not have a device.) + c10::optional device_opt_; + + // default member initializers for bit-fields only available with -std=c++2a + // or -std=gnu++2a + inline void init_bitfields() { + is_contiguous_ = true; + is_channels_last_ = false; + is_channels_last_contiguous_ = false; + is_channels_last_3d_ = false; + is_channels_last_3d_contiguous_ = false; + is_non_overlapping_and_dense_ = true; + is_wrapped_number_ = false; + allow_tensor_metadata_change_ = true; + reserved_ = false; + sizes_strides_policy_ = static_cast(SizesStridesPolicy::Default); + custom_sizes_strides_ = static_cast(SizesStridesPolicy::Default); + python_custom_sizes_strides_ = + static_cast(SizesStridesPolicy::Default); + python_custom_device_ = false; + python_custom_layout_ = false; + custom_device_ = false; + custom_layout_ = false; + device_policy_ = false; + layout_policy_ = false; + storage_access_should_throw_ = false; + has_symbolic_sizes_strides_ = false; + } + + // Tensor is contiguous + bool is_contiguous_ : 1; + + // Tensor is a subclass that does not permit storage access. + bool storage_access_should_throw_ : 1; + + // Tensor is stored in the channels last 2d memory format, when dimensions + // order is (N)CHW and C-strides < W-strides < H-strides (< N-strides) + // (If size of any dimension is equal to 1, this dimension strides value + // is not taken into account). + bool is_channels_last_ : 1; + + // Channels last contiguous tensor is channel last tensor which occupies + // contiguous memory block. + bool is_channels_last_contiguous_ : 1; + + // Tensor is stored in the channels last 3d memory format, when dimensions + // order is (N)CDHW and C-strides < W-strides < H-strides < D - strides (< + // N-strides) (If size of any dimension is equal to 1, this dimension strides + // value is not taken into account). + bool is_channels_last_3d_ : 1; + + // Channels last 3d contiguous tensor is channel last 3d tensor which occupies + // contiguous memory block. + bool is_channels_last_3d_contiguous_ : 1; + + // Dense tensor is the tensor that store values in a contiguous block of + // memory. Non-overlapping tensor is the tensor in which elements occupy + // individual non-repetitive memory. + bool is_non_overlapping_and_dense_ : 1; + + bool is_wrapped_number_ : 1; + + // NOTE [ Metadata Change for a Detached Tensor ] + // + // Normally, a user is allowed to change the tensor metadata + // (e.g. sizes / strides / storage / storage_offset) of a tensor. + // However, if the tensor is created by `t1_detached = t1.data` in Python + // or `t1_detached = t1.detach()` in Python/C++, those changes to the + // tensor metadata of `t1_detached` will not be propagated back to the + // original tensor `t1`. In order to make such changes explicitly illegal, + // we created the `allow_tensor_metadata_change_` flag, to prevent users + // from changing metadata of the detached tensor and expecting the original + // tensor to also be updated. + // + // NOTE: For a full list of tensor metadata fields, please see + // `copy_tensor_metadata()` in TensorImpl and its subclasses to find + // which fields are copied by value. + bool allow_tensor_metadata_change_ : 1; + + // we decide to keep reserved_ and it will + // live in Tensor after the split + // The logic is that if Extend() or ReserveSpace() were ever called, + // then subsequent Resize()s will not free up Storage. + bool reserved_ : 1; + + // Call _custom() virtual methods for + // strides()/is_contiguous()/sizes()/dim()/numel() + // This is a combination of sizes_strides_custom_dispatch_ + // and has_symbolic_sizes_strides_ + uint8_t sizes_strides_policy_ : 2; + + // Whether or not sizes_and_strides_ contains a symbolic value. + bool has_symbolic_sizes_strides_ : 1; + + // Call _custom() virtual method for + // strides()/is_contiguous()/sizes()/dim()/numel() + uint8_t custom_sizes_strides_ : 2; + + // Combo of custom_ and python_custom_ + bool device_policy_ : 1; + bool layout_policy_ : 1; + + // Call _custom() virtual method for device() + bool custom_device_ : 1; + + // Call _custom() virtual method for layout() + bool custom_layout_ : 1; + + // Call into Python for + // strides()/is_contiguous()/sizes()/dim()/numel() + uint8_t python_custom_sizes_strides_ : 2; + + // Call into Python for device() + bool python_custom_device_ : 1; + + // Call into Python for layout() + bool python_custom_layout_ : 1; + + // The set of DispatchKeys which describe this tensor. NB: this + // does NOT include Autograd (historically, it did, but + // not anymore!) + // + // INVARIANT: extra_meta_->named_tensor_meta_ != nullptr <==> + // key_set_.has(DispatchKey::Named) + DispatchKeySet key_set_; + + private: + // C10_TensorImpl_Size_Check_Dummy_Class needs to be friends with + // TensorImpl so it can inspect the size of private fields + template < + size_t cplusplus, + size_t clang_ver_major, + size_t gcc_ver, + size_t gcc_ver_minor, + size_t nvcc, + size_t cuda_version, + size_t cuda_version_major, + size_t ptr_size> + friend class C10_TensorImpl_Size_Check_Dummy_Class; +}; + +// Note [TensorImpl size constraints] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Changed the size of TensorImpl? If the size went down, good for +// you! Adjust the documentation below and the expected size. +// Did it go up? Read on... +// +// Struct size matters. In some production systems at Facebook, we have +// 400M live tensors during a training run. Do the math: every 64-bit +// word you add to Tensor is an extra 3.2 gigabytes in RAM. +// +// If you are a Facebook employee, you can check if the run in question +// has tipped you over the point using the command here: +// https://fburl.com/q5enpv98 +// +// For reference, we OOMed at 160 bytes (20 words) per TensorImpl. +// This is not counting overhead from strides out-of-line allocation and +// StorageImpl space and this is from before we inlined sizes and strides +// directly into TensorImpl as SmallVectors. +// +// Our memory usage on 32-bit systems is suboptimal, but we're not checking +// for it at the moment (to help avoid rage inducing cycles when the +// 32-bit number is wrong). +// +// Current breakdown: +// +// vtable pointer +// strong refcount TODO: pack these into one word +// weak refcount +// storage pointer +// autograd metadata pointer +// named tensor metadata pointer +// version counter pointer +// PyObjectSlot +// SizesAndStrides size/pointer +// SizesAndStrides sizes (pre-allocated 0) +// SizesAndStrides sizes (pre-allocated 1) +// SizesAndStrides sizes (pre-allocated 2) +// SizesAndStrides sizes (pre-allocated 3) +// SizesAndStrides sizes (pre-allocated 4) +// SizesAndStrides strides (pre-allocated 0) +// SizesAndStrides strides (pre-allocated 1) +// SizesAndStrides strides (pre-allocated 2) +// SizesAndStrides strides (pre-allocated 3) +// SizesAndStrides strides (pre-allocated 4) +// storage offset +// numel +// data type, device, is_contiguous, storage_access_should_throw_, bitfields +// DispatchKeySet +// + +// Various preprocessor macros we use to check that the +// TensorImpl size hasn't changed unexpectedly. We undef +// these later. +#ifndef __NVCC__ +#define C10_NVCC 0 +#else +#define C10_NVCC __NVCC__ +#endif + +#ifndef __CUDA_VER_MAJOR__ +#define C10_CUDA_VERSION_MAJOR 0 +#else +#define C10_CUDA_VERSION_MAJOR __CUDA_VER_MAJOR__ +#endif + +#ifndef CUDA_VERSION +#define C10_CUDA_VERSION 0 +#else +#define C10_CUDA_VERSION CUDA_VERSION +#endif + +#ifndef __clang_major__ +#define C10_CLANG_MAJOR_VERSION 0 +#else +#define C10_CLANG_MAJOR_VERSION __clang_major__ +#endif + +#ifndef __GNUC__ +#define C10_GCC_VERSION 0 +#else +#define C10_GCC_VERSION __GNUC__ +#endif + +#ifndef __GNUC_MINOR__ +#define C10_GCC_VERSION_MINOR 0 +#else +#define C10_GCC_VERSION_MINOR __GNUC_MINOR__ +#endif + +// We use a templatized class to both contain the logic of checking the sizes +// as well as to provide compile-time information that might be useful in +// figuring out why sizes may have changed. +// All the compile time information is given by the template fields that are +// always printed by the compiler when the static_assert fails. +template < + size_t cplusplus = __cplusplus, + size_t clang_ver_major = C10_CLANG_MAJOR_VERSION, + size_t gcc_ver = C10_GCC_VERSION, + size_t gcc_ver_minor = C10_GCC_VERSION_MINOR, + size_t nvcc = C10_NVCC, + size_t cuda_version = C10_CUDA_VERSION, + size_t cuda_version_major = C10_CUDA_VERSION_MAJOR, + size_t ptr_size = sizeof(void*)> +class C10_TensorImpl_Size_Check_Dummy_Class : private TensorImpl { + // Names of (non-bitfield) fields in TensorImpl; used to provide + // compile-time info about fields whose size changes unexpectedly. + enum class FieldNameEnum { + storage_, + autograd_meta_, + extra_meta_, + version_counter_, + pyobj_slot_, + sizes_and_strides_, + storage_offset_, + numel_, + data_type_, + device_opt_, + key_set_, + TOTAL_SIZE + }; + + // Provides compile-time equality check that reveals what numbers + // were used and on which quantity + template + constexpr static bool are_equal() { + static_assert( + Actual == Expected, + "Actual and Expected sizes of a field did not match!"); + return true; + } + + // Provides compile-time <= check that reveals what numbers + // were used and on which quantity + template + constexpr static bool is_le() { + static_assert( + Actual <= Expected, + "Actual and Expected sizes of a field did not match!"); + return true; + } + + public: + // Compile-time check that TensorImpl field sizes are as expected + // + // Observed total sizes and associated versions + // If you find a flag that predicts when unique_ptr has 16 bytes + // on 64-bit systems or when sizes_and_strides_ is 84 vs 88 bytes + // on 32-bit systems you get a cookie! + // Length | LLVM | GCC | C++ | CUDA + // 192 | ? | 11.2 | 201703 | 11040 + // 208 | ? | 11.2 | 201703 | 11040 + // 208 | ? | 11.2 | 201402 | 11040 + // 192 | ? | 11.2 | 201402 | 11040 + // 160 | 12 | 4.2 | 201703 | 0 + // + // To keep things clean, we split on systems here. + +#if UINTPTR_MAX == 0xFFFFFFFF + // This is a 32-bit system + static constexpr bool check_sizes() { + constexpr size_t tsize = 20 * sizeof(int64_t); + + // clang-format off + are_equal(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + is_le(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + is_le(); + // clang-format on + + return true; + } +#else + // This is a 64-bit system + static constexpr bool check_sizes() { + constexpr size_t tsize = 26 * sizeof(int64_t); + + // clang-format off + are_equal(); + // On some systems involving NVCC the size of unique_ptr is 16 bytes. We haven't + // figured out how to detect those via macro preprocessors yet, so we use <= + // comparisons for the relevant fields. + is_le(); + is_le(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + are_equal(); + is_le(); + // clang-format on + + return true; + } +#endif +}; + +// We use a class to encapsulate size-checking logic with +// templates to capture sizes and flags. We call this within +// a static assert to prove there is no run-time behaviour. +// Since the methods we call return either true or fail their +// own static_asserts, we should never see the error messages +// below. We have to provide it though for c++ <17. +static_assert( + C10_TensorImpl_Size_Check_Dummy_Class<>::check_sizes(), + "You should not see this message."); + +// Clean up after ourselves +#undef C10_NVCC +#undef C10_CUDA_VERSION_MAJOR +#undef C10_CUDA_VERSION +#undef C10_CLANG_MAJOR_VERSION +#undef C10_GCC_VERSION +#undef C10_GCC_VERSION_MINOR + +} // namespace c10 diff --git a/shared/package-files/0b/0b5a736f5d775e1d0657b279ff0946b6b49c6d4db963fa68845139ca74015ac2/indices_copy_compositeexplicitautograd_dispatch.h b/shared/package-files/0b/0b5a736f5d775e1d0657b279ff0946b6b49c6d4db963fa68845139ca74015ac2/indices_copy_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..da83e3f3323c418188451db8e403a7d2ce4f8855 --- /dev/null +++ b/shared/package-files/0b/0b5a736f5d775e1d0657b279ff0946b6b49c6d4db963fa68845139ca74015ac2/indices_copy_compositeexplicitautograd_dispatch.h @@ -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 & indices_copy_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & indices_copy_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/0b/0b5b76842c70b59fab0f43a69c5aa48303241d677c1242f5d230b8d51ed96a56/RECORD b/shared/package-files/0b/0b5b76842c70b59fab0f43a69c5aa48303241d677c1242f5d230b8d51ed96a56/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4f9b2c210b06f2ce142d100104aa7a4122879c6b --- /dev/null +++ b/shared/package-files/0b/0b5b76842c70b59fab0f43a69c5aa48303241d677c1242f5d230b8d51ed96a56/RECORD @@ -0,0 +1,208 @@ +PIL/BdfFontFile.py,sha256=CgWJtLCciuqgkpRedO-0xvIYsEe-AGUxs5k9AGbllPg,3469 +PIL/BlpImagePlugin.py,sha256=AuzKyME8-lGusxhWNw-Gy4i5OiK58BUf341GrJwIvac,15569 +PIL/BmpImagePlugin.py,sha256=rBG0UMmwEH7sneMLRdZXLqZbiPFWbGDLzhgUDq2y3GI,17699 +PIL/BufrStubImagePlugin.py,sha256=6b85Pu28dcbLAaCCZHWfhRkAU5-_J7lMWVRi-C6QnPc,1592 +PIL/ContainerIO.py,sha256=0lHPzJmOqWx2XK_oBQeiwBbr8Y6xT182Y72q_yj6wIo,3181 +PIL/CurImagePlugin.py,sha256=9aIXiNuTVkA0WlcPb5q5C5ZiDVcGBeI-EfsP5FjtP8U,1741 +PIL/DcxImagePlugin.py,sha256=A3Av_UXMGR51I8TmBQTJIQUyLbLUwUho0gHKDEQIIp0,1993 +PIL/DdsImagePlugin.py,sha256=8EpTFrYKy49zm1c8rhf-Ts5quzSXDhG0f7JVeUEobg0,16539 +PIL/EpsImagePlugin.py,sha256=2RktUZljG27e5eLZAXA6tRIRFpshdcWD6_JXHCl4wNc,15919 +PIL/ExifTags.py,sha256=zuMaexyJLTtuVZlOv43_P7qR7YMgjHffu7SOpPdvN3E,9753 +PIL/FitsImagePlugin.py,sha256=kzGddPcFZ-wjZhv48mHv-zA8SVG9rlyIytzQ6zOdGyA,2000 +PIL/FliImagePlugin.py,sha256=Ce4lhNCfrzlleWOGs7vGmLX3wul7uLIOrVxHI_ufsbU,4523 +PIL/FontFile.py,sha256=cEA7RQKpMcsXTbTLraBYNWEz2N3x47rz0VeYnlj5Uyw,3591 +PIL/FpxImagePlugin.py,sha256=mXaNTmqTRx8v2YrA5ujT31Ph92pdQo082fqStGLLQTg,6983 +PIL/FtexImagePlugin.py,sha256=USOGJE-qbbz2i2kqsgbhNe5MkesOrCYDNDkB-MDCoOg,3465 +PIL/GbrImagePlugin.py,sha256=eMCpGbv7k1kO-o0LxfWbPivVOW85sxzhj80m79KQqlY,2945 +PIL/GdImageFile.py,sha256=SNBzEAyZIeYYue_gIue4Ngr0G93WEScsiWM5hxdYvk8,2642 +PIL/GifImagePlugin.py,sha256=s34iS6fV0kz4tD73nCABbSuono7vk2S0VdTJl22TAHE,37203 +PIL/GimpGradientFile.py,sha256=tsjtwjYF66-bf1XNsTM5wI6Ix_wDODDO4TsDAhVhA4U,3430 +PIL/GimpPaletteFile.py,sha256=cEgzwxWE7Un4ecteOuKQtOCzXKnDZB1XBUPr8eOFymw,1380 +PIL/GribStubImagePlugin.py,sha256=_RF5KKShDil6f1ZBppBxZ9ZDzLzA4SfF8NU0O3sxqWk,1586 +PIL/Hdf5StubImagePlugin.py,sha256=Ryc2pROK1Zv67JOsNqWNc69qjX4EefdnLZolryEW4ZI,1589 +PIL/IcnsImagePlugin.py,sha256=KvI7GUIPjUHvjgFib08Xnr-S95jJE47flrpEaKGGfCk,11996 +PIL/IcoImagePlugin.py,sha256=Hi5jh3H6H-1fc8q4CrhNxLqXzZu4BjWZMdFrTCH5p0g,11574 +PIL/ImImagePlugin.py,sha256=l7PD_fbTEDfbqzGbo8Pir6EudzTvnFGOVWXyYkZAYCY,10904 +PIL/Image.py,sha256=bdqvPbFUqfwuymWqnhr47-bJ-hka5jolRj8J15q9lsA,134480 +PIL/ImageChops.py,sha256=GEjlymcoDtA5OOeIxQVIX96BD-s6AXhb7TmSLYn2tUg,7946 +PIL/ImageCms.py,sha256=6uJ1DXxJYstDSckcgFetzAKDQwkGCjrQ8uLy5iz7vnU,37181 +PIL/ImageColor.py,sha256=0FcbJ8P79HwEZeD82hZQ888KMtW5CWDteuuvLaptuB8,9173 +PIL/ImageDraw.py,sha256=HvxImwYIAyIPnyLADiU1DMNDcR9jdtTYBD-6RUS4Yyk,36435 +PIL/ImageDraw2.py,sha256=mbG4zwC6tCpMwea4fzXLCO2dT7D4FS5Qu4C5n1XupE0,5535 +PIL/ImageEnhance.py,sha256=2sC99It-If3s69RzTdDVV0lLscdE0P5ZbNflOzm6FPE,3225 +PIL/ImageFile.py,sha256=FHWA782rQqbbOjoNo4uW8q3FA6HLriarpZpAuEBtAL4,24345 +PIL/ImageFilter.py,sha256=HbRCGz_ErSUs4bT9qP0eg5gfr8fB_4nGnEjPP8nRcNM,17143 +PIL/ImageFont.py,sha256=W2uoXRPwSr9Gh_2kR5Iyc2rQfwu4Gxo2ejPkZcWPrLg,60840 +PIL/ImageGrab.py,sha256=5DDhN0PhU-JIDBrjooXUnPlTAIxgcE9iNh5C3oWex0c,5630 +PIL/ImageMath.py,sha256=TqzLP2bwj6FU6vel8nqoV64190dBgr5gqw73vgG-KQg,7509 +PIL/ImageMode.py,sha256=aqTBqT_GqrlBo0azaCmEPzHj6pasdtk2aWDGGna0meA,2770 +PIL/ImageMorph.py,sha256=jUIZZMjfvxI2lsE5GeNJaFvl7rIzCRY_XxuVs7f6Lm8,8012 +PIL/ImageOps.py,sha256=uS6DkoM9laNqNZm0rAZt2bofnb4P-16GjkpU0Az1KKo,22458 +PIL/ImagePalette.py,sha256=RBsDBC1kJHEc5OuDaIup48NuLxFSOIZWtqGOAZJvj7g,7763 +PIL/ImagePath.py,sha256=5yUG5XCUil1KKTTA_8PgGhcmg-mnue-GK0FwTBlhjw4,371 +PIL/ImageQt.py,sha256=DhUBqFaQr8TGHZAYPONY_dgaOC7vxnUzUzsVJRQaKYo,5745 +PIL/ImageSequence.py,sha256=j-i3HxuBqkVFPPZSRerCeRlkAYG0orFkWc9mG5IhYSM,2192 +PIL/ImageShow.py,sha256=IjMLpgJ50pRYc-f7-xZlzqrrwGBGf-P_v8HoX4IYBNY,8392 +PIL/ImageStat.py,sha256=ImYsQY6lIdht8_pNmofHXHMz_tWlsV3ct2eHDbx0DEA,3724 +PIL/ImageTk.py,sha256=v7UpqgvLscTrc3woG_q0HQLlAX1JZMgj3nmXVi2rJb0,8496 +PIL/ImageTransform.py,sha256=QbNygcTyHzCfSpNK7wFZQJ2dEJ1d2uIUJUYjLlsvkBE,3164 +PIL/ImageWin.py,sha256=AeO3qPyeQzEOagNb9AWOiWX2ZyRK4qTyEXgdttF-YzI,7226 +PIL/ImtImagePlugin.py,sha256=Kb3yzGSr4GuN_Dp-vQI1ob7HW_s8agqp0-gKG8Lqt7U,2614 +PIL/IptcImagePlugin.py,sha256=ZCydfUtpgPeMz1o9Fg9mkE0HUrU-wUUt9ijge7g7pH4,6135 +PIL/Jpeg2KImagePlugin.py,sha256=wXem0GpIymfqrSNmA5o2-H2q0YIeBPxGT9F4q5H9GrQ,11573 +PIL/JpegImagePlugin.py,sha256=HsFU08YvgKbveI17n-Xr-ROGhYXrq8YBD62FDp2jMrg,29578 +PIL/JpegPresets.py,sha256=9TUIdnpWJQHtew5Mh__t7GE5jyLZVnilWJ28BZvhlC4,12378 +PIL/McIdasImagePlugin.py,sha256=qMFakL7l4YCbb4GaiZt2rxLceS5Dwj-PMtFrmF3JzGM,1832 +PIL/MicImagePlugin.py,sha256=ghIjl4yl-ifdH7ykjkokhd2dMCOc5Bpn2wi0FJ4gpM8,2615 +PIL/MpegImagePlugin.py,sha256=4XlVZbLjYUDLQUiJXUuoPcZKbCsjrLb4j89Ue-Mptnw,1858 +PIL/MpoImagePlugin.py,sha256=_NELKSFJqmCNLhgnAA7RjLkWUooKq2gHdgHDwXnEibw,6255 +PIL/MspImagePlugin.py,sha256=WSm2IvKq0s7k9054-LmOz6rsXZCejMSfnrZXrcBOKDw,5648 +PIL/PSDraw.py,sha256=n-UXRnVJAALbmL3aVYJz9_D_CAkpDulXCnHs2Esfn7c,6560 +PIL/PaletteFile.py,sha256=ZMuQqDZ7X9d_c9LRMV7Wku1U7v_rVIHlT0Zipu4W4Eg,1163 +PIL/PalmImagePlugin.py,sha256=Txc8OcCjyJiR80npQKgw06-JgX_pFnEv8BHsF3co64M,9179 +PIL/PcdImagePlugin.py,sha256=0fIQ-vUvMcD13NqhYk4UNCTajxsZSFqdQnSqBP4VrSw,1531 +PIL/PcfFontFile.py,sha256=NPZQ0XkbGB8uTlGqgmIPGkwuLMYBdykDeVuvFgIC7JU,7147 +PIL/PcxImagePlugin.py,sha256=Z7INEBrZt3JdYFT73H741A1P7FHd6N_lrMGdxCI_gp4,6057 +PIL/PdfImagePlugin.py,sha256=6bQN-R47u-fGMVLtBirn8sV9ENFfD13IptJzAEJqEcc,8841 +PIL/PdfParser.py,sha256=de45wTgum1mNNzBURVxbnyIE9TWhFB4lapJWT0ScVcw,34483 +PIL/PixarImagePlugin.py,sha256=_kySXXNkfkPgVLd5H_xXi7vHfEy_fY42W4fBo2cXRoY,1687 +PIL/PngImagePlugin.py,sha256=tZr5QSRYbeZmMuHGW7Z0HZ4tj_7Og2OYWPWKFk803yY,46481 +PIL/PpmImagePlugin.py,sha256=o9Nm2Y7R2uw5HtYx-cJKRMsmeof2zXA2fazB13eCz1E,11359 +PIL/PsdImagePlugin.py,sha256=IDHRQQrP--TaqNf45rM-oWnDrSNrPUBPAYzw2A38358,7697 +PIL/PyAccess.py,sha256=l0v6Sd0ha80QM4TULXuK7t_Ph2VwNG_MzGOuwhQj2S8,9909 +PIL/QoiImagePlugin.py,sha256=R3EQMRD4N-jy1mquob4xtLyzlSF6CiljiKc7cx83Vqs,3670 +PIL/SgiImagePlugin.py,sha256=irpZprRXEM01GjcWgwO5hlbWw1RuYGMG9QlxDeB2eMo,6184 +PIL/SpiderImagePlugin.py,sha256=WoiSQ-PX30v5ZR8oECFEo_z5tLobeVS1MZQWp8uEL2Y,9467 +PIL/SunImagePlugin.py,sha256=Zyzd_n8OVaD_ECUPMdg7YViGVfRLhR-2b8z6vPYCTL4,4440 +PIL/TarIO.py,sha256=p2NKGZ9-rKCVdLT5Bc3K_mpNc7SRaZ_b9g86y8WGZuo,1739 +PIL/TgaImagePlugin.py,sha256=Sgd8Zm7sLSZC1xp-35Ve2gEXgaZBPv0s1YpUN5ZyM3k,6615 +PIL/TiffImagePlugin.py,sha256=xibeBz2VQESXEgj8p876nSI6PY53q3cr76G8Cl5NlCM,76701 +PIL/TiffTags.py,sha256=ZmHL4R5_xkb_PwH0Kz7Pu6wlX80gn0800ysaAd79JSw,16567 +PIL/WalImageFile.py,sha256=HUnZ08FnSpFyLS8QEUAX3HdhS0FiVrEfweczbGmVyYM,5555 +PIL/WebPImagePlugin.py,sha256=u8vPrNJXiaA0yLIv6Qtpxv3YgN0T0vveUfF7SIGH-2g,11320 +PIL/WmfImagePlugin.py,sha256=zfqPQqk0rGPQYmoP_g0euoOYdBjQZr0RtCGk3n2Oxjg,4726 +PIL/XVThumbImagePlugin.py,sha256=QydC-4ISyYMIWWCYEVXZRBqgouv7S8cG7Sq222wNk8A,2022 +PIL/XbmImagePlugin.py,sha256=JrNSE9gesB7jEb9_iBLu3xIYHozoPbQEKQNleETJXtQ,2523 +PIL/XpmImagePlugin.py,sha256=P6RNrQQlko-1hKtKRAzad6RVUQ7JrjUizD__6zZeT1M,3219 +PIL/__init__.py,sha256=xJm_loI9xcfcm1_sa9l8mXH7l1f9573QnhcW_ngX9y8,2014 +PIL/__main__.py,sha256=LiJGDPwg067ZaSwzvYXzXsusvNCvOT3SgZp9_YwGLpI,77 +PIL/__pycache__/BdfFontFile.cpython-310.pyc,, +PIL/__pycache__/BlpImagePlugin.cpython-310.pyc,, +PIL/__pycache__/BmpImagePlugin.cpython-310.pyc,, +PIL/__pycache__/BufrStubImagePlugin.cpython-310.pyc,, +PIL/__pycache__/ContainerIO.cpython-310.pyc,, +PIL/__pycache__/CurImagePlugin.cpython-310.pyc,, +PIL/__pycache__/DcxImagePlugin.cpython-310.pyc,, +PIL/__pycache__/DdsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/EpsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/ExifTags.cpython-310.pyc,, +PIL/__pycache__/FitsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/FliImagePlugin.cpython-310.pyc,, +PIL/__pycache__/FontFile.cpython-310.pyc,, +PIL/__pycache__/FpxImagePlugin.cpython-310.pyc,, +PIL/__pycache__/FtexImagePlugin.cpython-310.pyc,, +PIL/__pycache__/GbrImagePlugin.cpython-310.pyc,, +PIL/__pycache__/GdImageFile.cpython-310.pyc,, +PIL/__pycache__/GifImagePlugin.cpython-310.pyc,, +PIL/__pycache__/GimpGradientFile.cpython-310.pyc,, +PIL/__pycache__/GimpPaletteFile.cpython-310.pyc,, +PIL/__pycache__/GribStubImagePlugin.cpython-310.pyc,, +PIL/__pycache__/Hdf5StubImagePlugin.cpython-310.pyc,, +PIL/__pycache__/IcnsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/IcoImagePlugin.cpython-310.pyc,, +PIL/__pycache__/ImImagePlugin.cpython-310.pyc,, +PIL/__pycache__/Image.cpython-310.pyc,, +PIL/__pycache__/ImageChops.cpython-310.pyc,, +PIL/__pycache__/ImageCms.cpython-310.pyc,, +PIL/__pycache__/ImageColor.cpython-310.pyc,, +PIL/__pycache__/ImageDraw.cpython-310.pyc,, +PIL/__pycache__/ImageDraw2.cpython-310.pyc,, +PIL/__pycache__/ImageEnhance.cpython-310.pyc,, +PIL/__pycache__/ImageFile.cpython-310.pyc,, +PIL/__pycache__/ImageFilter.cpython-310.pyc,, +PIL/__pycache__/ImageFont.cpython-310.pyc,, +PIL/__pycache__/ImageGrab.cpython-310.pyc,, +PIL/__pycache__/ImageMath.cpython-310.pyc,, +PIL/__pycache__/ImageMode.cpython-310.pyc,, +PIL/__pycache__/ImageMorph.cpython-310.pyc,, +PIL/__pycache__/ImageOps.cpython-310.pyc,, +PIL/__pycache__/ImagePalette.cpython-310.pyc,, +PIL/__pycache__/ImagePath.cpython-310.pyc,, +PIL/__pycache__/ImageQt.cpython-310.pyc,, +PIL/__pycache__/ImageSequence.cpython-310.pyc,, +PIL/__pycache__/ImageShow.cpython-310.pyc,, +PIL/__pycache__/ImageStat.cpython-310.pyc,, +PIL/__pycache__/ImageTk.cpython-310.pyc,, +PIL/__pycache__/ImageTransform.cpython-310.pyc,, +PIL/__pycache__/ImageWin.cpython-310.pyc,, +PIL/__pycache__/ImtImagePlugin.cpython-310.pyc,, +PIL/__pycache__/IptcImagePlugin.cpython-310.pyc,, +PIL/__pycache__/Jpeg2KImagePlugin.cpython-310.pyc,, +PIL/__pycache__/JpegImagePlugin.cpython-310.pyc,, +PIL/__pycache__/JpegPresets.cpython-310.pyc,, +PIL/__pycache__/McIdasImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MicImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MpegImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MpoImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MspImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PSDraw.cpython-310.pyc,, +PIL/__pycache__/PaletteFile.cpython-310.pyc,, +PIL/__pycache__/PalmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PcdImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PcfFontFile.cpython-310.pyc,, +PIL/__pycache__/PcxImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PdfImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PdfParser.cpython-310.pyc,, +PIL/__pycache__/PixarImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PngImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PpmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PsdImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PyAccess.cpython-310.pyc,, +PIL/__pycache__/QoiImagePlugin.cpython-310.pyc,, +PIL/__pycache__/SgiImagePlugin.cpython-310.pyc,, +PIL/__pycache__/SpiderImagePlugin.cpython-310.pyc,, +PIL/__pycache__/SunImagePlugin.cpython-310.pyc,, +PIL/__pycache__/TarIO.cpython-310.pyc,, +PIL/__pycache__/TgaImagePlugin.cpython-310.pyc,, +PIL/__pycache__/TiffImagePlugin.cpython-310.pyc,, +PIL/__pycache__/TiffTags.cpython-310.pyc,, +PIL/__pycache__/WalImageFile.cpython-310.pyc,, +PIL/__pycache__/WebPImagePlugin.cpython-310.pyc,, +PIL/__pycache__/WmfImagePlugin.cpython-310.pyc,, +PIL/__pycache__/XVThumbImagePlugin.cpython-310.pyc,, +PIL/__pycache__/XbmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/XpmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/__init__.cpython-310.pyc,, +PIL/__pycache__/__main__.cpython-310.pyc,, +PIL/__pycache__/_binary.cpython-310.pyc,, +PIL/__pycache__/_deprecate.cpython-310.pyc,, +PIL/__pycache__/_tkinter_finder.cpython-310.pyc,, +PIL/__pycache__/_typing.cpython-310.pyc,, +PIL/__pycache__/_util.cpython-310.pyc,, +PIL/__pycache__/_version.cpython-310.pyc,, +PIL/__pycache__/features.cpython-310.pyc,, +PIL/_binary.py,sha256=2qsiRyxBrHwPBm9OeqgSBN0bW_kwsiF8-OmAxzgP-Sw,2279 +PIL/_deprecate.py,sha256=Kt1jv0PTNdqqZksTO2g6XIXgnglkUv3ILRQ8nlP1IKc,2000 +PIL/_imaging.cpython-310-x86_64-linux-gnu.so,sha256=ZYMzFN85Ok4bLdOV3S7CS8C1lqfRu6RyDQLT49h0msI,591968 +PIL/_imagingcms.cpython-310-x86_64-linux-gnu.so,sha256=G_0BoZiTVTHmSQoYMXjhWW5Y4o-vaem7y2wjWD1AE7Y,46016 +PIL/_imagingcms.pyi,sha256=uN4MUZ6avvQ7ZRsGS9neyFpi76OYlxLv7SOrmwS0TtQ,99 +PIL/_imagingft.cpython-310-x86_64-linux-gnu.so,sha256=0E9dsl9HFzuptCvRanc8ZfTmkVCUPqS5ZgEUa9SkDh4,42896 +PIL/_imagingft.pyi,sha256=uN4MUZ6avvQ7ZRsGS9neyFpi76OYlxLv7SOrmwS0TtQ,99 +PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so,sha256=qkjhf3YWzxBbqpcN0zlHYERcnn3GmS2S9ev_zpbju8U,29696 +PIL/_imagingmorph.cpython-310-x86_64-linux-gnu.so,sha256=z_AVzULjm6HPtAQaqGtgGkFJhNAVyE5OTyGtC9tvH_g,16224 +PIL/_imagingtk.cpython-310-x86_64-linux-gnu.so,sha256=_jHubm8XmdPKYe5ET_BA0KOFbe1LyynxbE7tgBC2y6Y,16848 +PIL/_tkinter_finder.py,sha256=T9mPJn0kOMBd449ks26RgIVcoJdV0Pq-hI96Jmir3pQ,539 +PIL/_typing.py,sha256=EOvAj7Z7yFQGe4CQzCdXrcH1aCNwDmD-ig1p3Y-LPLg,402 +PIL/_util.py,sha256=kYai_kiMPzmVmoHOsqtNg516QcsuGymoUE3xBh41nL4,823 +PIL/_version.py,sha256=wTAXIDScPCi6rN3xG3UOqezq0mqLgFmsKxU1U8M5iNs,87 +PIL/_webp.cpython-310-x86_64-linux-gnu.so,sha256=uZH42uawGzdKvPNqvVjyeJKAGKPp435AYR0Q2BJnE_Y,33376 +PIL/features.py,sha256=ZtIUwxcwRTf_MVzQ9LLbd6lDhKkU5SQ1BSxv61auazo,9654 +pillow-10.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pillow-10.2.0.dist-info/LICENSE,sha256=5wY4TG8pnRtvp4KuZXdAs3K0vXk4oaMYv5SsJJEUdYo,1446 +pillow-10.2.0.dist-info/METADATA,sha256=fZlKCvuFmrHk6sj1aII6g7Kv2q3uD3qzvp3_iYa-4p4,9708 +pillow-10.2.0.dist-info/RECORD,, +pillow-10.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pillow-10.2.0.dist-info/WHEEL,sha256=9l1ndzONx4ZaWPkwijf7Cfj4e86OKtajPx-bu9J08f4,105 +pillow-10.2.0.dist-info/direct_url.json,sha256=TUrXMWaNZyT-haBOg2qSfw1fTplHzsgJUKYc2_-mLyg,66 +pillow-10.2.0.dist-info/top_level.txt,sha256=riZqrk-hyZqh5f1Z0Zwii3dKfxEsByhu9cU9IODF-NY,4 +pillow-10.2.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 diff --git a/shared/package-files/0b/0b5c3286b69a388e0b11a1e33a50304c25a6d7ece04076fe46a6d70abfe36452/__init__.py b/shared/package-files/0b/0b5c3286b69a388e0b11a1e33a50304c25a6d7ece04076fe46a6d70abfe36452/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75a139ca431c060a35e4456de4b3b6a3800ba7fb --- /dev/null +++ b/shared/package-files/0b/0b5c3286b69a388e0b11a1e33a50304c25a6d7ece04076fe46a6d70abfe36452/__init__.py @@ -0,0 +1,396 @@ +import ast +import os +import re +import string +import sys +import traceback +import unittest +import difflib +from typing import Any, Callable, Dict, List, Match, Tuple, Optional + +# NB: We do not internally use this property for anything, but it +# is preserved for BC reasons +ACCEPT = os.getenv('EXPECTTEST_ACCEPT') + +LINENO_AT_START = sys.version_info >= (3, 8) + + +def nth_line(src: str, lineno: int) -> int: + """ + Compute the starting index of the n-th line (where n is 1-indexed) + + >>> nth_line("aaa\\nbb\\nc", 2) + 4 + """ + assert lineno >= 1 + pos = 0 + for _ in range(lineno - 1): + pos = src.find("\n", pos) + 1 + return pos + + +def nth_eol(src: str, lineno: int) -> int: + """ + Compute the ending index of the n-th line (before the newline, + where n is 1-indexed) + + >>> nth_eol("aaa\\nbb\\nc", 2) + 6 + """ + assert lineno >= 1 + pos = -1 + for _ in range(lineno): + pos = src.find("\n", pos + 1) + if pos == -1: + return len(src) + return pos + + +def normalize_nl(t: str) -> str: + return t.replace("\r\n", "\n").replace("\r", "\n") + + +def escape_trailing_quote(s: str, quote: str) -> str: + if s and s[-1] == quote: + return s[:-1] + "\\" + quote + else: + return s + + +class EditHistory: + state: Dict[str, List[Tuple[int, int]]] + seen: Dict[str, Dict[int, str]] + + def __init__(self) -> None: + self.state = {} + self.seen = {} + + def reload_file(self, fn: str) -> None: + """ + The idea is that if you reload a file, the line numbers + from traceback are now up to date, but we do NOT want to clear + out seen list as it will tell us if we are expecting the + same line multiple times. Instead, we need to adjust + the seen list for the new world order. + """ + new_seen = {} + for seen_loc, seen_str in self.seen.get(fn, {}).items(): + new_seen[self.adjust_lineno(fn, seen_loc)] = seen_str + + self.seen[fn] = new_seen + self.state.pop(fn, None) + + def adjust_lineno(self, fn: str, lineno: int) -> int: + if fn not in self.state: + return lineno + for edit_loc, edit_diff in self.state[fn]: + if lineno > edit_loc: + lineno += edit_diff + return lineno + + def seen_file(self, fn: str) -> bool: + return fn in self.state + + def seen_edit(self, fn: str, lineno: int) -> Optional[str]: + return self.seen.get(fn, {}).get(lineno, None) + + def record_edit(self, fn: str, lineno: int, delta: int, expect: str) -> None: + self.state.setdefault(fn, []).append((lineno, delta)) + self.seen.setdefault(fn, {})[lineno] = expect + + +EDIT_HISTORY = EditHistory() + + +def ok_for_raw_triple_quoted_string(s: str, quote: str) -> bool: + """ + Is this string representable inside a raw triple-quoted string? + Due to the fact that backslashes are always treated literally, + some strings are not representable. + + >>> ok_for_raw_triple_quoted_string("blah", quote="'") + True + >>> ok_for_raw_triple_quoted_string("'", quote="'") + False + >>> ok_for_raw_triple_quoted_string("a ''' b", quote="'") + False + """ + return quote * 3 not in s and (not s or s[-1] not in [quote, "\\"]) + + +RE_EXPECT = re.compile( + (r"(?Pr?)" r"(?P'''|" r'""")' r"(?P.*?)" r"(?P=quote)"), re.DOTALL +) + + +def replace_string_literal( + src: str, start_lineno: int, end_lineno: int, new_string: str +) -> Tuple[str, int]: + r""" + Replace a triple quoted string literal with new contents. + Only handles printable ASCII correctly at the moment. This + will preserve the quote style of the original string, and + makes a best effort to preserve raw-ness (unless it is impossible + to do so.) + + Returns a tuple of the replaced string, as well as a delta of + number of lines added/removed. + + >>> replace_string_literal("'''arf'''", 1, 1, "barf") + ("'''barf'''", 0) + >>> r = replace_string_literal(" moo = '''arf'''", 1, 1, "'a'\n\\b\n") + >>> print(r[0]) + moo = '''\ + 'a' + \\b + ''' + >>> r[1] + 3 + >>> replace_string_literal(" moo = '''\\\narf'''", 1, 2, "'a'\n\\b\n")[1] + 2 + >>> print(replace_string_literal(" f('''\"\"\"''')", 1, 1, "a ''' b")[0]) + f('''a \'\'\' b''') + """ + # Haven't implemented correct escaping for non-printable characters + assert all(c in string.printable for c in new_string), repr(new_string) + + new_string = normalize_nl(new_string) + + delta = [new_string.count("\n")] + if delta[0] > 0: + delta[0] += 1 # handle the extra \\\n + + assert start_lineno <= end_lineno + start = nth_line(src, start_lineno) + end = nth_eol(src, end_lineno) + assert start <= end + + def replace(m: Match[str]) -> str: + s = new_string + raw = m.group("raw") == "r" + if not raw or not ok_for_raw_triple_quoted_string(s, quote=m.group("quote")[0]): + raw = False + s = s.replace("\\", "\\\\") + if m.group("quote") == "'''": + s = escape_trailing_quote(s, "'").replace("'''", r"\'\'\'") + else: + s = escape_trailing_quote(s, '"').replace('"""', r"\"\"\"") + + new_body = "\\\n" + s if "\n" in s and not raw else s + delta[0] -= m.group("body").count("\n") + return "".join( + [ + "r" if raw else "", + m.group("quote"), + new_body, + m.group("quote"), + ] + ) + + return ( + src[:start] + RE_EXPECT.sub(replace, src[start:end], count=1) + src[end:], + delta[0], + ) + + +def replace_many(rep: Dict[str, str], text: str) -> str: + rep = {re.escape(k): v for k, v in rep.items()} + pattern = re.compile("|".join(rep.keys())) + return pattern.sub(lambda m: rep[re.escape(m.group(0))], text) + + +def assert_eq(expect: str, actual: str, *, msg: str) -> None: + # TODO: improve this + if actual != expect: + diff = "".join( + difflib.unified_diff( + expect.splitlines(True), + actual.splitlines(True), + fromfile="expect.txt", + tofile="actual.txt", + ) + ) + raise AssertionError( + f"Mismatch between actual and expect strings:\n\n{diff}\n\n{msg}" + ) + + +def assert_expected_inline( + actual: str, + expect: str, + skip: int = 0, + *, + expect_filters: Optional[Dict[str, str]] = None, + assert_eq: Any = assert_eq, + debug_id: str = "", +) -> None: + """ + Assert that actual is equal to expect. The expect argument + MUST be a string literal (triple-quoted strings OK), and will + get updated directly in source when you run the test suite + with EXPECTTEST_ACCEPT=1. + + If you want to write a helper function that makes use of + assertExpectedInline (e.g., expect is not a string literal), + set the skip argument to how many function calls we should + skip to find the string literal to update. + """ + if expect_filters is not None: + actual = replace_many(expect_filters, actual) + + # NB: Intentionally do not use ACCEPT global variable; + # reaccessing environment here allows for modification + # of os.environ to be picked up + if os.getenv("EXPECTTEST_ACCEPT"): + if actual != expect: + # current frame and parent frame, plus any requested skip + tb = traceback.extract_stack(limit=2 + skip) + fn, lineno, _, _ = tb[0] + debug_suffix = "" if not debug_id else f" for {debug_id}" + if (prev_actual := EDIT_HISTORY.seen_edit(fn, lineno)) is not None: + assert_eq( + actual, + prev_actual, + msg=f"Uh oh, accepting different values{debug_suffix} at {fn}:{lineno}. Are you running a parametrized test? If so, you need a separate assertExpectedInline invocation per distinct output.", + ) + print( + "Skipping already accepted output{} at {}:{}".format( + debug_suffix, fn, lineno + ) + ) + return + print("Accepting new output{} at {}:{}".format(debug_suffix, fn, lineno)) + with open(fn, "r+") as f: + old = f.read() + old_ast = ast.parse(old) + + # NB: it's only the traceback line numbers that are wrong; + # we reread the file every time we write to it, so AST's + # line numbers are correct + lineno = EDIT_HISTORY.adjust_lineno(fn, lineno) + + # Conservative assumption to start + start_lineno = lineno + end_lineno = lineno + # Try to give a more accurate bounds based on AST + # NB: this walk is in no specified order (in practice it's + # breadth first) + for n in ast.walk(old_ast): + if isinstance(n, ast.Expr): + if hasattr(n, "end_lineno"): + assert LINENO_AT_START + if n.lineno == start_lineno: + end_lineno = n.end_lineno # type: ignore[attr-defined] + else: + if n.lineno == end_lineno: + start_lineno = n.lineno + + new, delta = replace_string_literal( + old, start_lineno, end_lineno, actual + ) + + assert old != new, ( + f"Failed to substitute string at {fn}:{lineno}; did you use triple quotes? " + "If this is unexpected, please file a bug report at " + "https://github.com/ezyang/expecttest/issues/new " + f"with the contents of the source file near {fn}:{lineno}" + ) + + # Only write the backup file the first time we hit the + # file + if not EDIT_HISTORY.seen_file(fn): + with open(fn + ".bak", "w") as f_bak: + f_bak.write(old) + f.seek(0) + f.truncate(0) + + f.write(new) + + EDIT_HISTORY.record_edit(fn, lineno, delta, actual) + else: + help_text = ( + "To accept the new output, re-run test with " + "envvar EXPECTTEST_ACCEPT=1 (we recommend " + "staging/committing your changes before doing this)" + ) + assert_eq(expect, actual, msg=help_text) + + +class TestCase(unittest.TestCase): + longMessage = True + _expect_filters: Dict[str, str] + + def substituteExpected(self, pattern: str, replacement: str) -> None: + if not hasattr(self, "_expect_filters"): + self._expect_filters = {} + + def expect_filters_cleanup() -> None: + del self._expect_filters + + self.addCleanup(expect_filters_cleanup) + if pattern in self._expect_filters: + raise RuntimeError( + "Cannot remap {} to {} (existing mapping is {})".format( + pattern, replacement, self._expect_filters[pattern] + ) + ) + self._expect_filters[pattern] = replacement + + def assertExpectedInline(self, actual: str, expect: str, skip: int = 0) -> None: + """ + Assert that actual is equal to expect. The expect argument + MUST be a string literal (triple-quoted strings OK), and will + get updated directly in source when you run the test suite + with EXPECTTEST_ACCEPT=1. + + If you want to write a helper function that makes use of + assertExpectedInline (e.g., expect is not a string literal), + set the skip argument to how many function calls we should + skip to find the string literal to update. + """ + assert_expected_inline( + actual, + expect, + skip=skip + 1, + expect_filters=getattr(self, "_expect_filters", None), + debug_id=self.id(), + assert_eq=self.assertMultiLineEqualMaybeCppStack, + ) + + def assertExpectedRaisesInline( + self, + exc_type: Any, + callable: Callable[..., Any], + expect: str, + *args: Any, + **kwargs: Any, + ) -> None: + """ + Like assertExpectedInline, but tests the str() representation of + the raised exception from callable. The raised exeption must + be exc_type. + """ + try: + callable(*args, **kwargs) + except exc_type as e: + self.assertExpectedInline(str(e), expect, skip=1) + return + # Don't put this in the try block; the AssertionError will catch it + self.fail(msg="Did not raise when expected to") + + def assertMultiLineEqualMaybeCppStack( + self, expect: str, actual: str, *args: Any, **kwargs: Any + ) -> None: + cpp_stack_header = "\nException raised from" + if cpp_stack_header in actual: + actual = actual.rsplit(cpp_stack_header, maxsplit=1)[0] + if hasattr(self, "assertMultiLineEqual"): + self.assertMultiLineEqual(expect, actual, *args, **kwargs) + else: + self.assertEqual(expect, actual, *args, **kwargs) + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/shared/package-files/0b/0b62cbfe81666913e812d1510d39fc44d6c9cdcc74e25e58140783696e285eee/data.py b/shared/package-files/0b/0b62cbfe81666913e812d1510d39fc44d6c9cdcc74e25e58140783696e285eee/data.py new file mode 100644 index 0000000000000000000000000000000000000000..d972d7e3a34b11b3b45c6ddcd714f31d89dbb22b --- /dev/null +++ b/shared/package-files/0b/0b62cbfe81666913e812d1510d39fc44d6c9cdcc74e25e58140783696e285eee/data.py @@ -0,0 +1,86 @@ +"""Taxation Powers Vote for the Scottish Parliament 1997 dataset""" +from statsmodels.datasets import utils as du + +__docformat__ = "restructuredtext" + +COPYRIGHT = """Used with express permission from the original author, +who retains all rights.""" +TITLE = "Taxation Powers Vote for the Scottish Parliament 1997" +SOURCE = """ +Jeff Gill's *Generalized Linear Models: A Unified Approach* + +http://jgill.wustl.edu/research/books.html +""" +DESCRSHORT = """Taxation Powers' Yes Vote for Scottish Parliament-1997""" + +DESCRLONG = """ +This data is based on the example in Gill and describes the proportion of +voters who voted Yes to grant the Scottish Parliament taxation powers. +The data are divided into 32 council districts. This example's explanatory +variables include the amount of council tax collected in pounds sterling as +of April 1997 per two adults before adjustments, the female percentage of +total claims for unemployment benefits as of January, 1998, the standardized +mortality rate (UK is 100), the percentage of labor force participation, +regional GDP, the percentage of children aged 5 to 15, and an interaction term +between female unemployment and the council tax. + +The original source files and variable information are included in +/scotland/src/ +""" + +NOTE = """:: + + Number of Observations - 32 (1 for each Scottish district) + + Number of Variables - 8 + + Variable name definitions:: + + YES - Proportion voting yes to granting taxation powers to the + Scottish parliament. + COUTAX - Amount of council tax collected in pounds sterling as of + April '97 + UNEMPF - Female percentage of total unemployment benefits claims as of + January 1998 + MOR - The standardized mortality rate (UK is 100) + ACT - Labor force participation (Short for active) + GDP - GDP per county + AGE - Percentage of children aged 5 to 15 in the county + COUTAX_FEMALEUNEMP - Interaction between COUTAX and UNEMPF + + Council district names are included in the data file, though are not + returned by load. +""" + + +def load(): + """ + Load the Scotvote data and returns a Dataset instance. + + Returns + ------- + Dataset + A `Dataset` instance with ``data``, ``names``, ``endog``, ``exog``, + ``endog_name`` and ``exog_name`` attributes. + """ + return load_pandas() + + +def load_pandas(): + """ + Load the Scotvote data and returns a Dataset instance. + + Returns + ------- + Dataset + A `Dataset` instance with ``data``, ``names``, ``endog``, ``exog``, + ``endog_name`` and ``exog_name`` attributes. + """ + data = _get_data() + return du.process_pandas(data, endog_idx=0) + + +def _get_data(): + data = du.load_csv(__file__, "scotvote.csv") + data = data.iloc[:, 1:9] + return data.astype(float) diff --git a/shared/package-files/0b/0b6310817eee6cbfdcb3963389b59af26d18c5d32ae7fdc2877755233b0b3be6/validators.py b/shared/package-files/0b/0b6310817eee6cbfdcb3963389b59af26d18c5d32ae7fdc2877755233b0b3be6/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..1488554f789526d8d85eb467250a64a64489362d --- /dev/null +++ b/shared/package-files/0b/0b6310817eee6cbfdcb3963389b59af26d18c5d32ae7fdc2877755233b0b3be6/validators.py @@ -0,0 +1,720 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful validators. +""" + + +import operator +import re + +from contextlib import contextmanager +from re import Pattern + +from ._config import get_run_validators, set_run_validators +from ._make import _AndValidator, and_, attrib, attrs +from .converters import default_if_none +from .exceptions import NotCallableError + + +__all__ = [ + "and_", + "deep_iterable", + "deep_mapping", + "disabled", + "ge", + "get_disabled", + "gt", + "in_", + "instance_of", + "is_callable", + "le", + "lt", + "matches_re", + "max_len", + "min_len", + "not_", + "optional", + "provides", + "set_disabled", +] + + +def set_disabled(disabled): + """ + Globally disable or enable running validators. + + By default, they are run. + + :param disabled: If ``True``, disable running all validators. + :type disabled: bool + + .. warning:: + + This function is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(not disabled) + + +def get_disabled(): + """ + Return a bool indicating whether validators are currently disabled or not. + + :return: ``True`` if validators are currently disabled. + :rtype: bool + + .. versionadded:: 21.3.0 + """ + return not get_run_validators() + + +@contextmanager +def disabled(): + """ + Context manager that disables running validators within its context. + + .. warning:: + + This context manager is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(False) + try: + yield + finally: + set_run_validators(True) + + +@attrs(repr=False, slots=True, hash=True) +class _InstanceOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not isinstance(value, self.type): + raise TypeError( + "'{name}' must be {type!r} (got {value!r} that is a " + "{actual!r}).".format( + name=attr.name, + type=self.type, + actual=value.__class__, + value=value, + ), + attr, + self.type, + value, + ) + + def __repr__(self): + return "".format( + type=self.type + ) + + +def instance_of(type): + """ + A validator that raises a `TypeError` if the initializer is called + with a wrong type for this particular attribute (checks are performed using + `isinstance` therefore it's also valid to pass a tuple of types). + + :param type: The type to check for. + :type type: type or tuple of type + + :raises TypeError: With a human readable error message, the attribute + (of type `attrs.Attribute`), the expected type, and the value it + got. + """ + return _InstanceOfValidator(type) + + +@attrs(repr=False, frozen=True, slots=True) +class _MatchesReValidator: + pattern = attrib() + match_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.match_func(value): + raise ValueError( + "'{name}' must match regex {pattern!r}" + " ({value!r} doesn't)".format( + name=attr.name, pattern=self.pattern.pattern, value=value + ), + attr, + self.pattern, + value, + ) + + def __repr__(self): + return "".format( + pattern=self.pattern + ) + + +def matches_re(regex, flags=0, func=None): + r""" + A validator that raises `ValueError` if the initializer is called + with a string that doesn't match *regex*. + + :param regex: a regex string or precompiled pattern to match against + :param int flags: flags that will be passed to the underlying re function + (default 0) + :param callable func: which underlying `re` function to call. Valid options + are `re.fullmatch`, `re.search`, and `re.match`; the default ``None`` + means `re.fullmatch`. For performance reasons, the pattern is always + precompiled using `re.compile`. + + .. versionadded:: 19.2.0 + .. versionchanged:: 21.3.0 *regex* can be a pre-compiled pattern. + """ + valid_funcs = (re.fullmatch, None, re.search, re.match) + if func not in valid_funcs: + raise ValueError( + "'func' must be one of {}.".format( + ", ".join( + sorted( + e and e.__name__ or "None" for e in set(valid_funcs) + ) + ) + ) + ) + + if isinstance(regex, Pattern): + if flags: + raise TypeError( + "'flags' can only be used with a string pattern; " + "pass flags to re.compile() instead" + ) + pattern = regex + else: + pattern = re.compile(regex, flags) + + if func is re.match: + match_func = pattern.match + elif func is re.search: + match_func = pattern.search + else: + match_func = pattern.fullmatch + + return _MatchesReValidator(pattern, match_func) + + +@attrs(repr=False, slots=True, hash=True) +class _ProvidesValidator: + interface = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.interface.providedBy(value): + raise TypeError( + "'{name}' must provide {interface!r} which {value!r} " + "doesn't.".format( + name=attr.name, interface=self.interface, value=value + ), + attr, + self.interface, + value, + ) + + def __repr__(self): + return "".format( + interface=self.interface + ) + + +def provides(interface): + """ + A validator that raises a `TypeError` if the initializer is called + with an object that does not provide the requested *interface* (checks are + performed using ``interface.providedBy(value)`` (see `zope.interface + `_). + + :param interface: The interface to check for. + :type interface: ``zope.interface.Interface`` + + :raises TypeError: With a human readable error message, the attribute + (of type `attrs.Attribute`), the expected interface, and the + value it got. + + .. deprecated:: 23.1.0 + """ + import warnings + + warnings.warn( + "attrs's zope-interface support is deprecated and will be removed in, " + "or after, April 2024.", + DeprecationWarning, + stacklevel=2, + ) + return _ProvidesValidator(interface) + + +@attrs(repr=False, slots=True, hash=True) +class _OptionalValidator: + validator = attrib() + + def __call__(self, inst, attr, value): + if value is None: + return + + self.validator(inst, attr, value) + + def __repr__(self): + return "".format( + what=repr(self.validator) + ) + + +def optional(validator): + """ + A validator that makes an attribute optional. An optional attribute is one + which can be set to ``None`` in addition to satisfying the requirements of + the sub-validator. + + :param Callable | tuple[Callable] | list[Callable] validator: A validator + (or validators) that is used for non-``None`` values. + + .. versionadded:: 15.1.0 + .. versionchanged:: 17.1.0 *validator* can be a list of validators. + .. versionchanged:: 23.1.0 *validator* can also be a tuple of validators. + """ + if isinstance(validator, (list, tuple)): + return _OptionalValidator(_AndValidator(validator)) + + return _OptionalValidator(validator) + + +@attrs(repr=False, slots=True, hash=True) +class _InValidator: + options = attrib() + + def __call__(self, inst, attr, value): + try: + in_options = value in self.options + except TypeError: # e.g. `1 in "abc"` + in_options = False + + if not in_options: + raise ValueError( + "'{name}' must be in {options!r} (got {value!r})".format( + name=attr.name, options=self.options, value=value + ), + attr, + self.options, + value, + ) + + def __repr__(self): + return "".format( + options=self.options + ) + + +def in_(options): + """ + A validator that raises a `ValueError` if the initializer is called + with a value that does not belong in the options provided. The check is + performed using ``value in options``. + + :param options: Allowed options. + :type options: list, tuple, `enum.Enum`, ... + + :raises ValueError: With a human readable error message, the attribute (of + type `attrs.Attribute`), the expected options, and the value it + got. + + .. versionadded:: 17.1.0 + .. versionchanged:: 22.1.0 + The ValueError was incomplete until now and only contained the human + readable error message. Now it contains all the information that has + been promised since 17.1.0. + """ + return _InValidator(options) + + +@attrs(repr=False, slots=False, hash=True) +class _IsCallableValidator: + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not callable(value): + message = ( + "'{name}' must be callable " + "(got {value!r} that is a {actual!r})." + ) + raise NotCallableError( + msg=message.format( + name=attr.name, value=value, actual=value.__class__ + ), + value=value, + ) + + def __repr__(self): + return "" + + +def is_callable(): + """ + A validator that raises a `attrs.exceptions.NotCallableError` if the + initializer is called with a value for this particular attribute + that is not callable. + + .. versionadded:: 19.1.0 + + :raises attrs.exceptions.NotCallableError: With a human readable error + message containing the attribute (`attrs.Attribute`) name, + and the value it got. + """ + return _IsCallableValidator() + + +@attrs(repr=False, slots=True, hash=True) +class _DeepIterable: + member_validator = attrib(validator=is_callable()) + iterable_validator = attrib( + default=None, validator=optional(is_callable()) + ) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.iterable_validator is not None: + self.iterable_validator(inst, attr, value) + + for member in value: + self.member_validator(inst, attr, member) + + def __repr__(self): + iterable_identifier = ( + "" + if self.iterable_validator is None + else f" {self.iterable_validator!r}" + ) + return ( + "" + ).format( + iterable_identifier=iterable_identifier, + member=self.member_validator, + ) + + +def deep_iterable(member_validator, iterable_validator=None): + """ + A validator that performs deep validation of an iterable. + + :param member_validator: Validator(s) to apply to iterable members + :param iterable_validator: Validator to apply to iterable itself + (optional) + + .. versionadded:: 19.1.0 + + :raises TypeError: if any sub-validators fail + """ + if isinstance(member_validator, (list, tuple)): + member_validator = and_(*member_validator) + return _DeepIterable(member_validator, iterable_validator) + + +@attrs(repr=False, slots=True, hash=True) +class _DeepMapping: + key_validator = attrib(validator=is_callable()) + value_validator = attrib(validator=is_callable()) + mapping_validator = attrib(default=None, validator=optional(is_callable())) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.mapping_validator is not None: + self.mapping_validator(inst, attr, value) + + for key in value: + self.key_validator(inst, attr, key) + self.value_validator(inst, attr, value[key]) + + def __repr__(self): + return ( + "" + ).format(key=self.key_validator, value=self.value_validator) + + +def deep_mapping(key_validator, value_validator, mapping_validator=None): + """ + A validator that performs deep validation of a dictionary. + + :param key_validator: Validator to apply to dictionary keys + :param value_validator: Validator to apply to dictionary values + :param mapping_validator: Validator to apply to top-level mapping + attribute (optional) + + .. versionadded:: 19.1.0 + + :raises TypeError: if any sub-validators fail + """ + return _DeepMapping(key_validator, value_validator, mapping_validator) + + +@attrs(repr=False, frozen=True, slots=True) +class _NumberValidator: + bound = attrib() + compare_op = attrib() + compare_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.compare_func(value, self.bound): + raise ValueError( + "'{name}' must be {op} {bound}: {value}".format( + name=attr.name, + op=self.compare_op, + bound=self.bound, + value=value, + ) + ) + + def __repr__(self): + return "".format( + op=self.compare_op, bound=self.bound + ) + + +def lt(val): + """ + A validator that raises `ValueError` if the initializer is called + with a number larger or equal to *val*. + + :param val: Exclusive upper bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<", operator.lt) + + +def le(val): + """ + A validator that raises `ValueError` if the initializer is called + with a number greater than *val*. + + :param val: Inclusive upper bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<=", operator.le) + + +def ge(val): + """ + A validator that raises `ValueError` if the initializer is called + with a number smaller than *val*. + + :param val: Inclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">=", operator.ge) + + +def gt(val): + """ + A validator that raises `ValueError` if the initializer is called + with a number smaller or equal to *val*. + + :param val: Exclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">", operator.gt) + + +@attrs(repr=False, frozen=True, slots=True) +class _MaxLengthValidator: + max_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) > self.max_length: + raise ValueError( + "Length of '{name}' must be <= {max}: {len}".format( + name=attr.name, max=self.max_length, len=len(value) + ) + ) + + def __repr__(self): + return f"" + + +def max_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is longer than *length*. + + :param int length: Maximum length of the string or iterable + + .. versionadded:: 21.3.0 + """ + return _MaxLengthValidator(length) + + +@attrs(repr=False, frozen=True, slots=True) +class _MinLengthValidator: + min_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) < self.min_length: + raise ValueError( + "Length of '{name}' must be => {min}: {len}".format( + name=attr.name, min=self.min_length, len=len(value) + ) + ) + + def __repr__(self): + return f"" + + +def min_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is shorter than *length*. + + :param int length: Minimum length of the string or iterable + + .. versionadded:: 22.1.0 + """ + return _MinLengthValidator(length) + + +@attrs(repr=False, slots=True, hash=True) +class _SubclassOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not issubclass(value, self.type): + raise TypeError( + "'{name}' must be a subclass of {type!r} " + "(got {value!r}).".format( + name=attr.name, + type=self.type, + value=value, + ), + attr, + self.type, + value, + ) + + def __repr__(self): + return "".format( + type=self.type + ) + + +def _subclass_of(type): + """ + A validator that raises a `TypeError` if the initializer is called + with a wrong type for this particular attribute (checks are performed using + `issubclass` therefore it's also valid to pass a tuple of types). + + :param type: The type to check for. + :type type: type or tuple of types + + :raises TypeError: With a human readable error message, the attribute + (of type `attrs.Attribute`), the expected type, and the value it + got. + """ + return _SubclassOfValidator(type) + + +@attrs(repr=False, slots=True, hash=True) +class _NotValidator: + validator = attrib() + msg = attrib( + converter=default_if_none( + "not_ validator child '{validator!r}' " + "did not raise a captured error" + ) + ) + exc_types = attrib( + validator=deep_iterable( + member_validator=_subclass_of(Exception), + iterable_validator=instance_of(tuple), + ), + ) + + def __call__(self, inst, attr, value): + try: + self.validator(inst, attr, value) + except self.exc_types: + pass # suppress error to invert validity + else: + raise ValueError( + self.msg.format( + validator=self.validator, + exc_types=self.exc_types, + ), + attr, + self.validator, + value, + self.exc_types, + ) + + def __repr__(self): + return ( + "" + ).format( + what=self.validator, + exc_types=self.exc_types, + ) + + +def not_(validator, *, msg=None, exc_types=(ValueError, TypeError)): + """ + A validator that wraps and logically 'inverts' the validator passed to it. + It will raise a `ValueError` if the provided validator *doesn't* raise a + `ValueError` or `TypeError` (by default), and will suppress the exception + if the provided validator *does*. + + Intended to be used with existing validators to compose logic without + needing to create inverted variants, for example, ``not_(in_(...))``. + + :param validator: A validator to be logically inverted. + :param msg: Message to raise if validator fails. + Formatted with keys ``exc_types`` and ``validator``. + :type msg: str + :param exc_types: Exception type(s) to capture. + Other types raised by child validators will not be intercepted and + pass through. + + :raises ValueError: With a human readable error message, + the attribute (of type `attrs.Attribute`), + the validator that failed to raise an exception, + the value it got, + and the expected exception types. + + .. versionadded:: 22.2.0 + """ + try: + exc_types = tuple(exc_types) + except TypeError: + exc_types = (exc_types,) + return _NotValidator(validator, msg, exc_types) diff --git a/shared/package-files/0b/0b662ccc42b06c4f8d5299be4c78167bdc1ca0285994300e3c7dabde4d3b9e9a/backward_compatibility.py b/shared/package-files/0b/0b662ccc42b06c4f8d5299be4c78167bdc1ca0285994300e3c7dabde4d3b9e9a/backward_compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..be97f016a0917a771970843a4ba70deb68cdd60d --- /dev/null +++ b/shared/package-files/0b/0b662ccc42b06c4f8d5299be4c78167bdc1ca0285994300e3c7dabde4d3b9e9a/backward_compatibility.py @@ -0,0 +1,5 @@ +import warnings + +def worker_init_fn(worker_id): + warnings.warn("Usage of backward_compatibility.worker_init_fn is deprecated" + " as DataLoader automatically applies sharding in every worker") diff --git a/shared/package-files/0b/0b6bfdb51ea7a39e024440960c5840353978d14b00e00847b1d9c6a0d09be3f4/Paramaribo b/shared/package-files/0b/0b6bfdb51ea7a39e024440960c5840353978d14b00e00847b1d9c6a0d09be3f4/Paramaribo new file mode 100644 index 0000000000000000000000000000000000000000..24f925a2dd33d487e41cb38b9c3b4c420af69c1d Binary files /dev/null and b/shared/package-files/0b/0b6bfdb51ea7a39e024440960c5840353978d14b00e00847b1d9c6a0d09be3f4/Paramaribo differ diff --git a/shared/package-files/0b/0b77f10e07e282fda3f0bbd1a2a58b9c33afe33c58bec6eb2ffa13c9c4fafbfa/sparse_resize_and_clear_native.h b/shared/package-files/0b/0b77f10e07e282fda3f0bbd1a2a58b9c33afe33c58bec6eb2ffa13c9c4fafbfa/sparse_resize_and_clear_native.h new file mode 100644 index 0000000000000000000000000000000000000000..718cd921048c9b2c2e9c092dc1b8edc13cc1263a --- /dev/null +++ b/shared/package-files/0b/0b77f10e07e282fda3f0bbd1a2a58b9c33afe33c58bec6eb2ffa13c9c4fafbfa/sparse_resize_and_clear_native.h @@ -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 sparse_resize_and_clear(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim); +TORCH_API const at::Tensor & sparse_resize_and_clear_out(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim, const at::Tensor & out); +TORCH_API const at::Tensor & sparse_resize_and_clear_(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim); +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0b7acd051878adeb94a7c62e45d19053de563dcf2f9786c063ecf92d78038ae0/launder.h b/shared/package-files/0b/0b7acd051878adeb94a7c62e45d19053de563dcf2f9786c063ecf92d78038ae0/launder.h new file mode 100644 index 0000000000000000000000000000000000000000..9e4533c4b4760a416b0aca4b91c32ffd324d7f08 --- /dev/null +++ b/shared/package-files/0b/0b7acd051878adeb94a7c62e45d19053de563dcf2f9786c063ecf92d78038ae0/launder.h @@ -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 + +namespace arrow { +namespace internal { + +#if __cpp_lib_launder +using std::launder; +#else +template +constexpr T* launder(T* p) noexcept { + return p; +} +#endif + +} // namespace internal +} // namespace arrow diff --git a/shared/package-files/0b/0b88dbbc0abdb7bc1cb1763ed121faeba68fdadf30e1dc8ef27467bbb4d17587/test_collections.py b/shared/package-files/0b/0b88dbbc0abdb7bc1cb1763ed121faeba68fdadf30e1dc8ef27467bbb4d17587/test_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..5c2f66a7a5cca8dbfe85b089de3a17ded0301009 --- /dev/null +++ b/shared/package-files/0b/0b88dbbc0abdb7bc1cb1763ed121faeba68fdadf30e1dc8ef27467bbb4d17587/test_collections.py @@ -0,0 +1,1393 @@ +from datetime import datetime +import io +import itertools +import platform +import re +from types import SimpleNamespace + +import numpy as np +from numpy.testing import assert_array_equal, assert_array_almost_equal +import pytest + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.collections as mcollections +import matplotlib.colors as mcolors +import matplotlib.path as mpath +import matplotlib.transforms as mtransforms +from matplotlib.collections import (Collection, LineCollection, + EventCollection, PolyCollection) +from matplotlib.collections import FillBetweenPolyCollection +from matplotlib.testing.decorators import check_figures_equal, image_comparison + + +@pytest.fixture(params=["pcolormesh", "pcolor"]) +def pcfunc(request): + return request.param + + +def generate_EventCollection_plot(): + """Generate the initial collection and plot it.""" + positions = np.array([0., 1., 2., 3., 5., 8., 13., 21.]) + extra_positions = np.array([34., 55., 89.]) + orientation = 'horizontal' + lineoffset = 1 + linelength = .5 + linewidth = 2 + color = [1, 0, 0, 1] + linestyle = 'solid' + antialiased = True + + coll = EventCollection(positions, + orientation=orientation, + lineoffset=lineoffset, + linelength=linelength, + linewidth=linewidth, + color=color, + linestyle=linestyle, + antialiased=antialiased + ) + + fig, ax = plt.subplots() + ax.add_collection(coll) + ax.set_title('EventCollection: default') + props = {'positions': positions, + 'extra_positions': extra_positions, + 'orientation': orientation, + 'lineoffset': lineoffset, + 'linelength': linelength, + 'linewidth': linewidth, + 'color': color, + 'linestyle': linestyle, + 'antialiased': antialiased + } + ax.set_xlim(-1, 22) + ax.set_ylim(0, 2) + return ax, coll, props + + +@image_comparison(['EventCollection_plot__default.png']) +def test__EventCollection__get_props(): + _, coll, props = generate_EventCollection_plot() + # check that the default segments have the correct coordinates + check_segments(coll, + props['positions'], + props['linelength'], + props['lineoffset'], + props['orientation']) + # check that the default positions match the input positions + np.testing.assert_array_equal(props['positions'], coll.get_positions()) + # check that the default orientation matches the input orientation + assert props['orientation'] == coll.get_orientation() + # check that the default orientation matches the input orientation + assert coll.is_horizontal() + # check that the default linelength matches the input linelength + assert props['linelength'] == coll.get_linelength() + # check that the default lineoffset matches the input lineoffset + assert props['lineoffset'] == coll.get_lineoffset() + # check that the default linestyle matches the input linestyle + assert coll.get_linestyle() == [(0, None)] + # check that the default color matches the input color + for color in [coll.get_color(), *coll.get_colors()]: + np.testing.assert_array_equal(color, props['color']) + + +@image_comparison(['EventCollection_plot__set_positions.png']) +def test__EventCollection__set_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], props['extra_positions']]) + coll.set_positions(new_positions) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: set_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__add_positions.png']) +def test__EventCollection__add_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][0]]) + coll.switch_orientation() # Test adding in the vertical orientation, too. + coll.add_positions(props['extra_positions'][0]) + coll.switch_orientation() + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: add_positions') + splt.set_xlim(-1, 35) + + +@image_comparison(['EventCollection_plot__append_positions.png']) +def test__EventCollection__append_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][2]]) + coll.append_positions(props['extra_positions'][2]) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: append_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__extend_positions.png']) +def test__EventCollection__extend_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][1:]]) + coll.extend_positions(props['extra_positions'][1:]) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: extend_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__switch_orientation.png']) +def test__EventCollection__switch_orientation(): + splt, coll, props = generate_EventCollection_plot() + new_orientation = 'vertical' + coll.switch_orientation() + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() + new_positions = coll.get_positions() + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], new_orientation) + splt.set_title('EventCollection: switch_orientation') + splt.set_ylim(-1, 22) + splt.set_xlim(0, 2) + + +@image_comparison(['EventCollection_plot__switch_orientation__2x.png']) +def test__EventCollection__switch_orientation_2x(): + """ + Check that calling switch_orientation twice sets the orientation back to + the default. + """ + splt, coll, props = generate_EventCollection_plot() + coll.switch_orientation() + coll.switch_orientation() + new_positions = coll.get_positions() + assert props['orientation'] == coll.get_orientation() + assert coll.is_horizontal() + np.testing.assert_array_equal(props['positions'], new_positions) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: switch_orientation 2x') + + +@image_comparison(['EventCollection_plot__set_orientation.png']) +def test__EventCollection__set_orientation(): + splt, coll, props = generate_EventCollection_plot() + new_orientation = 'vertical' + coll.set_orientation(new_orientation) + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() + check_segments(coll, + props['positions'], + props['linelength'], + props['lineoffset'], + new_orientation) + splt.set_title('EventCollection: set_orientation') + splt.set_ylim(-1, 22) + splt.set_xlim(0, 2) + + +@image_comparison(['EventCollection_plot__set_linelength.png']) +def test__EventCollection__set_linelength(): + splt, coll, props = generate_EventCollection_plot() + new_linelength = 15 + coll.set_linelength(new_linelength) + assert new_linelength == coll.get_linelength() + check_segments(coll, + props['positions'], + new_linelength, + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: set_linelength') + splt.set_ylim(-20, 20) + + +@image_comparison(['EventCollection_plot__set_lineoffset.png']) +def test__EventCollection__set_lineoffset(): + splt, coll, props = generate_EventCollection_plot() + new_lineoffset = -5. + coll.set_lineoffset(new_lineoffset) + assert new_lineoffset == coll.get_lineoffset() + check_segments(coll, + props['positions'], + props['linelength'], + new_lineoffset, + props['orientation']) + splt.set_title('EventCollection: set_lineoffset') + splt.set_ylim(-6, -4) + + +@image_comparison([ + 'EventCollection_plot__set_linestyle.png', + 'EventCollection_plot__set_linestyle.png', + 'EventCollection_plot__set_linewidth.png', +]) +def test__EventCollection__set_prop(): + for prop, value, expected in [ + ('linestyle', 'dashed', [(0, (6.0, 6.0))]), + ('linestyle', (0, (6., 6.)), [(0, (6.0, 6.0))]), + ('linewidth', 5, 5), + ]: + splt, coll, _ = generate_EventCollection_plot() + coll.set(**{prop: value}) + assert plt.getp(coll, prop) == expected + splt.set_title(f'EventCollection: set_{prop}') + + +@image_comparison(['EventCollection_plot__set_color.png']) +def test__EventCollection__set_color(): + splt, coll, _ = generate_EventCollection_plot() + new_color = np.array([0, 1, 1, 1]) + coll.set_color(new_color) + for color in [coll.get_color(), *coll.get_colors()]: + np.testing.assert_array_equal(color, new_color) + splt.set_title('EventCollection: set_color') + + +def check_segments(coll, positions, linelength, lineoffset, orientation): + """ + Test helper checking that all values in the segment are correct, given a + particular set of inputs. + """ + segments = coll.get_segments() + if (orientation.lower() == 'horizontal' + or orientation.lower() == 'none' or orientation is None): + # if horizontal, the position in is in the y-axis + pos1 = 1 + pos2 = 0 + elif orientation.lower() == 'vertical': + # if vertical, the position in is in the x-axis + pos1 = 0 + pos2 = 1 + else: + raise ValueError("orientation must be 'horizontal' or 'vertical'") + + # test to make sure each segment is correct + for i, segment in enumerate(segments): + assert segment[0, pos1] == lineoffset + linelength / 2 + assert segment[1, pos1] == lineoffset - linelength / 2 + assert segment[0, pos2] == positions[i] + assert segment[1, pos2] == positions[i] + + +def test_collection_norm_autoscale(): + # norm should be autoscaled when array is set, not deferred to draw time + lines = np.arange(24).reshape((4, 3, 2)) + coll = mcollections.LineCollection(lines, array=np.arange(4)) + assert coll.norm(2) == 2 / 3 + # setting a new array shouldn't update the already scaled limits + coll.set_array(np.arange(4) + 5) + assert coll.norm(2) == 2 / 3 + + +def test_null_collection_datalim(): + col = mcollections.PathCollection([]) + col_data_lim = col.get_datalim(mtransforms.IdentityTransform()) + assert_array_equal(col_data_lim.get_points(), + mtransforms.Bbox.null().get_points()) + + +def test_no_offsets_datalim(): + # A collection with no offsets and a non transData + # transform should return a null bbox + ax = plt.axes() + coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])]) + ax.add_collection(coll) + coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform()) + assert_array_equal(coll_data_lim.get_points(), + mtransforms.Bbox.null().get_points()) + + +def test_add_collection(): + # Test if data limits are unchanged by adding an empty collection. + # GitHub issue #1490, pull #1497. + plt.figure() + ax = plt.axes() + ax.scatter([0, 1], [0, 1]) + bounds = ax.dataLim.bounds + ax.scatter([], []) + assert ax.dataLim.bounds == bounds + + +@mpl.style.context('mpl20') +@check_figures_equal(extensions=['png']) +def test_collection_log_datalim(fig_test, fig_ref): + # Data limits should respect the minimum x/y when using log scale. + x_vals = [4.38462e-6, 5.54929e-6, 7.02332e-6, 8.88889e-6, 1.12500e-5, + 1.42383e-5, 1.80203e-5, 2.28070e-5, 2.88651e-5, 3.65324e-5, + 4.62363e-5, 5.85178e-5, 7.40616e-5, 9.37342e-5, 1.18632e-4] + y_vals = [0.0, 0.1, 0.182, 0.332, 0.604, 1.1, 2.0, 3.64, 6.64, 12.1, 22.0, + 39.6, 71.3] + + x, y = np.meshgrid(x_vals, y_vals) + x = x.flatten() + y = y.flatten() + + ax_test = fig_test.subplots() + ax_test.set_xscale('log') + ax_test.set_yscale('log') + ax_test.margins = 0 + ax_test.scatter(x, y) + + ax_ref = fig_ref.subplots() + ax_ref.set_xscale('log') + ax_ref.set_yscale('log') + ax_ref.plot(x, y, marker="o", ls="") + + +def test_quiver_limits(): + ax = plt.axes() + x, y = np.arange(8), np.arange(10) + u = v = np.linspace(0, 10, 80).reshape(10, 8) + q = plt.quiver(x, y, u, v) + assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.) + + plt.figure() + ax = plt.axes() + x = np.linspace(-5, 10, 20) + y = np.linspace(-2, 4, 10) + y, x = np.meshgrid(y, x) + trans = mtransforms.Affine2D().translate(25, 32) + ax.transData + plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans) + assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) + + +def test_barb_limits(): + ax = plt.axes() + x = np.linspace(-5, 10, 20) + y = np.linspace(-2, 4, 10) + y, x = np.meshgrid(y, x) + trans = mtransforms.Affine2D().translate(25, 32) + ax.transData + plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans) + # The calculated bounds are approximately the bounds of the original data, + # this is because the entire path is taken into account when updating the + # datalim. + assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6), + decimal=1) + + +@image_comparison(['EllipseCollection_test_image.png'], remove_text=True, + tol=0 if platform.machine() == 'x86_64' else 0.021) +def test_EllipseCollection(): + # Test basic functionality + fig, ax = plt.subplots() + x = np.arange(4) + y = np.arange(3) + X, Y = np.meshgrid(x, y) + XY = np.vstack((X.ravel(), Y.ravel())).T + + ww = X / x[-1] + hh = Y / y[-1] + aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis + + ec = mcollections.EllipseCollection( + ww, hh, aa, units='x', offsets=XY, offset_transform=ax.transData, + facecolors='none') + ax.add_collection(ec) + ax.autoscale_view() + + +def test_EllipseCollection_setter_getter(): + # Test widths, heights and angle setter + rng = np.random.default_rng(0) + + widths = (2, ) + heights = (3, ) + angles = (45, ) + offsets = rng.random((10, 2)) * 10 + + fig, ax = plt.subplots() + + ec = mcollections.EllipseCollection( + widths=widths, + heights=heights, + angles=angles, + offsets=offsets, + units='x', + offset_transform=ax.transData, + ) + + assert_array_almost_equal(ec._widths, np.array(widths).ravel() * 0.5) + assert_array_almost_equal(ec._heights, np.array(heights).ravel() * 0.5) + assert_array_almost_equal(ec._angles, np.deg2rad(angles).ravel()) + + assert_array_almost_equal(ec.get_widths(), widths) + assert_array_almost_equal(ec.get_heights(), heights) + assert_array_almost_equal(ec.get_angles(), angles) + + ax.add_collection(ec) + ax.set_xlim(-2, 12) + ax.set_ylim(-2, 12) + + new_widths = rng.random((10, 2)) * 2 + new_heights = rng.random((10, 2)) * 3 + new_angles = rng.random((10, 2)) * 180 + + ec.set(widths=new_widths, heights=new_heights, angles=new_angles) + + assert_array_almost_equal(ec.get_widths(), new_widths.ravel()) + assert_array_almost_equal(ec.get_heights(), new_heights.ravel()) + assert_array_almost_equal(ec.get_angles(), new_angles.ravel()) + + +@image_comparison(['polycollection_close.png'], remove_text=True, style='mpl20') +def test_polycollection_close(): + from mpl_toolkits.mplot3d import Axes3D # type: ignore[import] + plt.rcParams['axes3d.automargin'] = True + + vertsQuad = [ + [[0., 0.], [0., 1.], [1., 1.], [1., 0.]], + [[0., 1.], [2., 3.], [2., 2.], [1., 1.]], + [[2., 2.], [2., 3.], [4., 1.], [3., 1.]], + [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]] + + fig = plt.figure() + ax = fig.add_axes(Axes3D(fig)) + + colors = ['r', 'g', 'b', 'y', 'k'] + zpos = list(range(5)) + + poly = mcollections.PolyCollection( + vertsQuad * len(zpos), linewidth=0.25) + poly.set_alpha(0.7) + + # need to have a z-value for *each* polygon = element! + zs = [] + cs = [] + for z, c in zip(zpos, colors): + zs.extend([z] * len(vertsQuad)) + cs.extend([c] * len(vertsQuad)) + + poly.set_color(cs) + + ax.add_collection3d(poly, zs=zs, zdir='y') + + # axis limit settings: + ax.set_xlim3d(0, 4) + ax.set_zlim3d(0, 3) + ax.set_ylim3d(0, 4) + + +@image_comparison(['regularpolycollection_rotate.png'], remove_text=True) +def test_regularpolycollection_rotate(): + xx, yy = np.mgrid[:10, :10] + xy_points = np.transpose([xx.flatten(), yy.flatten()]) + rotations = np.linspace(0, 2*np.pi, len(xy_points)) + + fig, ax = plt.subplots() + for xy, alpha in zip(xy_points, rotations): + col = mcollections.RegularPolyCollection( + 4, sizes=(100,), rotation=alpha, + offsets=[xy], offset_transform=ax.transData) + ax.add_collection(col, autolim=True) + ax.autoscale_view() + + +@image_comparison(['regularpolycollection_scale.png'], remove_text=True) +def test_regularpolycollection_scale(): + # See issue #3860 + + class SquareCollection(mcollections.RegularPolyCollection): + def __init__(self, **kwargs): + super().__init__(4, rotation=np.pi/4., **kwargs) + + def get_transform(self): + """Return transform scaling circle areas to data space.""" + ax = self.axes + + pts2pixels = 72.0 / ax.get_figure(root=True).dpi + + scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width + scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height + return mtransforms.Affine2D().scale(scale_x, scale_y) + + fig, ax = plt.subplots() + + xy = [(0, 0)] + # Unit square has a half-diagonal of `1/sqrt(2)`, so `pi * r**2` equals... + circle_areas = [np.pi / 2] + squares = SquareCollection( + sizes=circle_areas, offsets=xy, offset_transform=ax.transData) + ax.add_collection(squares, autolim=True) + ax.axis([-1, 1, -1, 1]) + + +def test_picking(): + fig, ax = plt.subplots() + col = ax.scatter([0], [0], [1000], picker=True) + fig.savefig(io.BytesIO(), dpi=fig.dpi) + mouse_event = SimpleNamespace(x=325, y=240) + found, indices = col.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + +def test_quadmesh_contains(): + x = np.arange(4) + X = x[:, None] * x[None, :] + + fig, ax = plt.subplots() + mesh = ax.pcolormesh(X) + fig.draw_without_rendering() + xdata, ydata = 0.5, 0.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + xdata, ydata = 1.5, 1.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [5]) + + +def test_quadmesh_contains_concave(): + # Test a concave polygon, V-like shape + x = [[0, -1], [1, 0]] + y = [[0, 1], [1, -1]] + fig, ax = plt.subplots() + mesh = ax.pcolormesh(x, y, [[0]]) + fig.draw_without_rendering() + # xdata, ydata, expected + points = [(-0.5, 0.25, True), # left wing + (0, 0.25, False), # between the two wings + (0.5, 0.25, True), # right wing + (0, -0.25, True), # main body + ] + for point in points: + xdata, ydata, expected = point + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found is expected + + +def test_quadmesh_cursor_data(): + x = np.arange(4) + X = x[:, None] * x[None, :] + + fig, ax = plt.subplots() + mesh = ax.pcolormesh(X) + # Empty array data + mesh._A = None + fig.draw_without_rendering() + xdata, ydata = 0.5, 0.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + # Empty collection should return None + assert mesh.get_cursor_data(mouse_event) is None + + # Now test adding the array data, to make sure we do get a value + mesh.set_array(np.ones(X.shape)) + assert_array_equal(mesh.get_cursor_data(mouse_event), [1]) + + +def test_quadmesh_cursor_data_multiple_points(): + x = [1, 2, 1, 2] + fig, ax = plt.subplots() + mesh = ax.pcolormesh(x, x, np.ones((3, 3))) + fig.draw_without_rendering() + xdata, ydata = 1.5, 1.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + # All quads are covering the same square + assert_array_equal(mesh.get_cursor_data(mouse_event), np.ones(9)) + + +def test_linestyle_single_dashes(): + plt.scatter([0, 1, 2], [0, 1, 2], linestyle=(0., [2., 2.])) + plt.draw() + + +@image_comparison(['size_in_xy.png'], remove_text=True) +def test_size_in_xy(): + fig, ax = plt.subplots() + + widths, heights, angles = (10, 10), 10, 0 + widths = 10, 10 + coords = [(10, 10), (15, 15)] + e = mcollections.EllipseCollection( + widths, heights, angles, units='xy', + offsets=coords, offset_transform=ax.transData) + + ax.add_collection(e) + + ax.set_xlim(0, 30) + ax.set_ylim(0, 30) + + +def test_pandas_indexing(pd): + + # Should not fail break when faced with a + # non-zero indexed series + index = [11, 12, 13] + ec = fc = pd.Series(['red', 'blue', 'green'], index=index) + lw = pd.Series([1, 2, 3], index=index) + ls = pd.Series(['solid', 'dashed', 'dashdot'], index=index) + aa = pd.Series([True, False, True], index=index) + + Collection(edgecolors=ec) + Collection(facecolors=fc) + Collection(linewidths=lw) + Collection(linestyles=ls) + Collection(antialiaseds=aa) + + +@mpl.style.context('default') +def test_lslw_bcast(): + col = mcollections.PathCollection([]) + col.set_linestyles(['-', '-']) + col.set_linewidths([1, 2, 3]) + + assert col.get_linestyles() == [(0, None)] * 6 + assert col.get_linewidths() == [1, 2, 3] * 2 + + col.set_linestyles(['-', '-', '-']) + assert col.get_linestyles() == [(0, None)] * 3 + assert (col.get_linewidths() == [1, 2, 3]).all() + + +def test_set_wrong_linestyle(): + c = Collection() + with pytest.raises(ValueError, match="Do not know how to convert 'fuzzy'"): + c.set_linestyle('fuzzy') + + +@mpl.style.context('default') +def test_capstyle(): + col = mcollections.PathCollection([]) + assert col.get_capstyle() is None + col = mcollections.PathCollection([], capstyle='round') + assert col.get_capstyle() == 'round' + col.set_capstyle('butt') + assert col.get_capstyle() == 'butt' + + +@mpl.style.context('default') +def test_joinstyle(): + col = mcollections.PathCollection([]) + assert col.get_joinstyle() is None + col = mcollections.PathCollection([], joinstyle='round') + assert col.get_joinstyle() == 'round' + col.set_joinstyle('miter') + assert col.get_joinstyle() == 'miter' + + +@image_comparison(['cap_and_joinstyle.png']) +def test_cap_and_joinstyle_image(): + fig, ax = plt.subplots() + ax.set_xlim([-0.5, 1.5]) + ax.set_ylim([-0.5, 2.5]) + + x = np.array([0.0, 1.0, 0.5]) + ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]]) + + segs = np.zeros((3, 3, 2)) + segs[:, :, 0] = x + segs[:, :, 1] = ys + line_segments = LineCollection(segs, linewidth=[10, 15, 20]) + line_segments.set_capstyle("round") + line_segments.set_joinstyle("miter") + + ax.add_collection(line_segments) + ax.set_title('Line collection with customized caps and joinstyle') + + +@image_comparison(['scatter_post_alpha.png'], + remove_text=True, style='default') +def test_scatter_post_alpha(): + fig, ax = plt.subplots() + sc = ax.scatter(range(5), range(5), c=range(5)) + sc.set_alpha(.1) + + +def test_scatter_alpha_array(): + x = np.arange(5) + alpha = x / 5 + # With colormapping. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, c=x, alpha=alpha) + sc1 = ax1.scatter(x, x, c=x) + sc1.set_alpha(alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + # Without colormapping. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'], alpha=alpha) + sc1 = ax1.scatter(x, x, color='r', alpha=alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + # Without colormapping, and set alpha afterward. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm']) + sc0.set_alpha(alpha) + sc1 = ax1.scatter(x, x, color='r') + sc1.set_alpha(alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + + +def test_pathcollection_legend_elements(): + np.random.seed(19680801) + x, y = np.random.rand(2, 10) + y = np.random.rand(10) + c = np.random.randint(0, 5, size=10) + s = np.random.randint(10, 300, size=10) + + fig, ax = plt.subplots() + sc = ax.scatter(x, y, c=c, s=s, cmap="jet", marker="o", linewidths=0) + + h, l = sc.legend_elements(fmt="{x:g}") + assert len(h) == 5 + assert l == ["0", "1", "2", "3", "4"] + colors = np.array([line.get_color() for line in h]) + colors2 = sc.cmap(np.arange(5)/4) + assert_array_equal(colors, colors2) + l1 = ax.legend(h, l, loc=1) + + h2, lab2 = sc.legend_elements(num=9) + assert len(h2) == 9 + l2 = ax.legend(h2, lab2, loc=2) + + h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red") + assert all(line.get_alpha() == 0.5 for line in h) + assert all(line.get_markerfacecolor() == "red" for line in h) + l3 = ax.legend(h, l, loc=4) + + h, l = sc.legend_elements(prop="sizes", num=4, fmt="{x:.2f}", + func=lambda x: 2*x) + actsizes = [line.get_markersize() for line in h] + labeledsizes = np.sqrt(np.array(l, float) / 2) + assert_array_almost_equal(actsizes, labeledsizes) + l4 = ax.legend(h, l, loc=3) + + loc = mpl.ticker.MaxNLocator(nbins=9, min_n_ticks=9-1, + steps=[1, 2, 2.5, 3, 5, 6, 8, 10]) + h5, lab5 = sc.legend_elements(num=loc) + assert len(h2) == len(h5) + + levels = [-1, 0, 55.4, 260] + h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}") + assert [float(l) for l in lab6] == levels[2:] + + for l in [l1, l2, l3, l4]: + ax.add_artist(l) + + fig.canvas.draw() + + +def test_EventCollection_nosort(): + # Check that EventCollection doesn't modify input in place + arr = np.array([3, 2, 1, 10]) + coll = EventCollection(arr) + np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10])) + + +def test_collection_set_verts_array(): + verts = np.arange(80, dtype=np.double).reshape(10, 4, 2) + col_arr = PolyCollection(verts) + col_list = PolyCollection(list(verts)) + assert len(col_arr._paths) == len(col_list._paths) + for ap, lp in zip(col_arr._paths, col_list._paths): + assert np.array_equal(ap._vertices, lp._vertices) + assert np.array_equal(ap._codes, lp._codes) + + verts_tuple = np.empty(10, dtype=object) + verts_tuple[:] = [tuple(tuple(y) for y in x) for x in verts] + col_arr_tuple = PolyCollection(verts_tuple) + assert len(col_arr._paths) == len(col_arr_tuple._paths) + for ap, atp in zip(col_arr._paths, col_arr_tuple._paths): + assert np.array_equal(ap._vertices, atp._vertices) + assert np.array_equal(ap._codes, atp._codes) + + +@check_figures_equal(extensions=["png"]) +@pytest.mark.parametrize("kwargs", [{}, {"step": "pre"}]) +def test_fill_between_poly_collection_set_data(fig_test, fig_ref, kwargs): + t = np.linspace(0, 16) + f1 = np.sin(t) + f2 = f1 + 0.2 + + fig_ref.subplots().fill_between(t, f1, f2, **kwargs) + + coll = fig_test.subplots().fill_between(t, -1, 1.2, **kwargs) + coll.set_data(t, f1, f2) + + +@pytest.mark.parametrize(("t_direction", "f1", "shape", "where", "msg"), [ + ("z", None, None, None, r"t_direction must be 'x' or 'y', got 'z'"), + ("x", None, (-1, 1), None, r"'x' is not 1-dimensional"), + ("x", None, None, [False] * 3, r"where size \(3\) does not match 'x' size \(\d+\)"), + ("y", [1, 2], None, None, r"'y' has size \d+, but 'x1' has an unequal size of \d+"), +]) +def test_fill_between_poly_collection_raise(t_direction, f1, shape, where, msg): + t = np.linspace(0, 16) + f1 = np.sin(t) if f1 is None else np.asarray(f1) + f2 = f1 + 0.2 + if shape: + t = t.reshape(*shape) + with pytest.raises(ValueError, match=msg): + FillBetweenPolyCollection(t_direction, t, f1, f2, where=where) + + +def test_collection_set_array(): + vals = [*range(10)] + + # Test set_array with list + c = Collection() + c.set_array(vals) + + # Test set_array with wrong dtype + with pytest.raises(TypeError, match="^Image data of dtype"): + c.set_array("wrong_input") + + # Test if array kwarg is copied + vals[5] = 45 + assert np.not_equal(vals, c.get_array()).any() + + +def test_blended_collection_autolim(): + f, ax = plt.subplots() + + # sample data to give initial data limits + ax.plot([2, 3, 4], [0.4, 0.6, 0.5]) + np.testing.assert_allclose((ax.dataLim.xmin, ax.dataLim.xmax), (2, 4)) + data_ymin, data_ymax = ax.dataLim.ymin, ax.dataLim.ymax + + # LineCollection with vertical lines spanning the Axes vertical, using transAxes + x = [1, 2, 3, 4, 5] + vertical_lines = [np.array([[xi, 0], [xi, 1]]) for xi in x] + trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) + ax.add_collection(LineCollection(vertical_lines, transform=trans)) + + # check that the x data limits are updated to include the LineCollection + np.testing.assert_allclose((ax.dataLim.xmin, ax.dataLim.xmax), (1, 5)) + # check that the y data limits are not updated (because they are not transData) + np.testing.assert_allclose((ax.dataLim.ymin, ax.dataLim.ymax), + (data_ymin, data_ymax)) + + +def test_singleton_autolim(): + fig, ax = plt.subplots() + ax.scatter(0, 0) + np.testing.assert_allclose(ax.get_ylim(), [-0.06, 0.06]) + np.testing.assert_allclose(ax.get_xlim(), [-0.06, 0.06]) + + +@pytest.mark.parametrize("transform, expected", [ + ("transData", (-0.5, 3.5)), + ("transAxes", (2.8, 3.2)), +]) +def test_autolim_with_zeros(transform, expected): + # 1) Test that a scatter at (0, 0) data coordinates contributes to + # autoscaling even though any(offsets) would be False in that situation. + # 2) Test that specifying transAxes for the transform does not contribute + # to the autoscaling. + fig, ax = plt.subplots() + ax.scatter(0, 0, transform=getattr(ax, transform)) + ax.scatter(3, 3) + np.testing.assert_allclose(ax.get_ylim(), expected) + np.testing.assert_allclose(ax.get_xlim(), expected) + + +def test_quadmesh_set_array_validation(pcfunc): + x = np.arange(11) + y = np.arange(8) + z = np.random.random((7, 10)) + fig, ax = plt.subplots() + coll = getattr(ax, pcfunc)(x, y, z) + + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (10, 7)")): + coll.set_array(z.reshape(10, 7)) + + z = np.arange(54).reshape((6, 9)) + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (6, 9)")): + coll.set_array(z) + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (54,)")): + coll.set_array(z.ravel()) + + # RGB(A) tests + z = np.ones((9, 6, 3)) # RGB with wrong X/Y dims + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 3)")): + coll.set_array(z) + + z = np.ones((9, 6, 4)) # RGBA with wrong X/Y dims + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 4)")): + coll.set_array(z) + + z = np.ones((7, 10, 2)) # Right X/Y dims, bad 3rd dim + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (7, 10, 2)")): + coll.set_array(z) + + x = np.arange(10) + y = np.arange(7) + z = np.random.random((7, 10)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, z, shading='gouraud') + + +def test_polyquadmesh_masked_vertices_array(): + xx, yy = np.meshgrid([0, 1, 2], [0, 1, 2, 3]) + # 2 x 3 mesh data + zz = (xx*yy)[:-1, :-1] + quadmesh = plt.pcolormesh(xx, yy, zz) + quadmesh.update_scalarmappable() + quadmesh_fc = quadmesh.get_facecolor()[1:, :] + # Mask the origin vertex in x + xx = np.ma.masked_where((xx == 0) & (yy == 0), xx) + polymesh = plt.pcolor(xx, yy, zz) + polymesh.update_scalarmappable() + # One cell should be left out + assert len(polymesh.get_paths()) == 5 + # Poly version should have the same facecolors as the end of the quadmesh + assert_array_equal(quadmesh_fc, polymesh.get_facecolor()) + + # Mask the origin vertex in y + yy = np.ma.masked_where((xx == 0) & (yy == 0), yy) + polymesh = plt.pcolor(xx, yy, zz) + polymesh.update_scalarmappable() + # One cell should be left out + assert len(polymesh.get_paths()) == 5 + # Poly version should have the same facecolors as the end of the quadmesh + assert_array_equal(quadmesh_fc, polymesh.get_facecolor()) + + # Mask the origin cell data + zz = np.ma.masked_where((xx[:-1, :-1] == 0) & (yy[:-1, :-1] == 0), zz) + polymesh = plt.pcolor(zz) + polymesh.update_scalarmappable() + # One cell should be left out + assert len(polymesh.get_paths()) == 5 + # Poly version should have the same facecolors as the end of the quadmesh + assert_array_equal(quadmesh_fc, polymesh.get_facecolor()) + + # We should also be able to call set_array with a new mask and get + # updated polys + # Remove mask, should add all polys back + zz = np.arange(6).reshape((3, 2)) + polymesh.set_array(zz) + polymesh.update_scalarmappable() + assert len(polymesh.get_paths()) == 6 + # Add mask should remove polys + zz = np.ma.masked_less(zz, 2) + polymesh.set_array(zz) + polymesh.update_scalarmappable() + assert len(polymesh.get_paths()) == 4 + + +def test_quadmesh_get_coordinates(pcfunc): + x = [0, 1, 2] + y = [2, 4, 6] + z = np.ones(shape=(2, 2)) + xx, yy = np.meshgrid(x, y) + coll = getattr(plt, pcfunc)(xx, yy, z) + + # shape (3, 3, 2) + coords = np.stack([xx.T, yy.T]).T + assert_array_equal(coll.get_coordinates(), coords) + + +def test_quadmesh_set_array(): + x = np.arange(4) + y = np.arange(4) + z = np.arange(9).reshape((3, 3)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, np.ones(z.shape)) + # Test that the collection is able to update with a 2d array + coll.set_array(z) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), z) + + # Check that pre-flattened arrays work too + coll.set_array(np.ones(9)) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), np.ones(9)) + + z = np.arange(16).reshape((4, 4)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, np.ones(z.shape), shading='gouraud') + # Test that the collection is able to update with a 2d array + coll.set_array(z) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), z) + + # Check that pre-flattened arrays work too + coll.set_array(np.ones(16)) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), np.ones(16)) + + +def test_quadmesh_vmin_vmax(pcfunc): + # test when vmin/vmax on the norm changes, the quadmesh gets updated + fig, ax = plt.subplots() + cmap = mpl.colormaps['plasma'] + norm = mpl.colors.Normalize(vmin=0, vmax=1) + coll = getattr(ax, pcfunc)([[1]], cmap=cmap, norm=norm) + fig.canvas.draw() + assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1))) + + # Change the vmin/vmax of the norm so that the color is from + # the bottom of the colormap now + norm.vmin, norm.vmax = 1, 2 + fig.canvas.draw() + assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1))) + + +def test_quadmesh_alpha_array(pcfunc): + x = np.arange(4) + y = np.arange(4) + z = np.arange(9).reshape((3, 3)) + alpha = z / z.max() + alpha_flat = alpha.ravel() + # Provide 2-D alpha: + fig, (ax0, ax1) = plt.subplots(2) + coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha) + coll2 = getattr(ax0, pcfunc)(x, y, z) + coll2.set_alpha(alpha) + plt.draw() + assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat) + assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat) + # Or provide 1-D alpha: + fig, (ax0, ax1) = plt.subplots(2) + coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha) + coll2 = getattr(ax1, pcfunc)(x, y, z) + coll2.set_alpha(alpha) + plt.draw() + assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat) + assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat) + + +def test_alpha_validation(pcfunc): + # Most of the relevant testing is in test_artist and test_colors. + fig, ax = plt.subplots() + pc = getattr(ax, pcfunc)(np.arange(12).reshape((3, 4))) + with pytest.raises(ValueError, match="^Data array shape"): + pc.set_alpha([0.5, 0.6]) + pc.update_scalarmappable() + + +def test_legend_inverse_size_label_relationship(): + """ + Ensure legend markers scale appropriately when label and size are + inversely related. + Here label = 5 / size + """ + + np.random.seed(19680801) + X = np.random.random(50) + Y = np.random.random(50) + C = 1 - np.random.random(50) + S = 5 / C + + legend_sizes = [0.2, 0.4, 0.6, 0.8] + fig, ax = plt.subplots() + sc = ax.scatter(X, Y, s=S) + handles, labels = sc.legend_elements( + prop='sizes', num=legend_sizes, func=lambda s: 5 / s + ) + + # Convert markersize scale to 's' scale + handle_sizes = [x.get_markersize() for x in handles] + handle_sizes = [5 / x**2 for x in handle_sizes] + + assert_array_almost_equal(handle_sizes, legend_sizes, decimal=1) + + +@mpl.style.context('default') +def test_color_logic(pcfunc): + pcfunc = getattr(plt, pcfunc) + z = np.arange(12).reshape(3, 4) + # Explicitly set an edgecolor. + pc = pcfunc(z, edgecolors='red', facecolors='none') + pc.update_scalarmappable() # This is called in draw(). + # Define 2 reference "colors" here for multiple use. + face_default = mcolors.to_rgba_array(pc._get_default_facecolor()) + mapped = pc.get_cmap()(pc.norm(z.ravel())) + # GitHub issue #1302: + assert mcolors.same_color(pc.get_edgecolor(), 'red') + # Check setting attributes after initialization: + pc = pcfunc(z) + pc.set_facecolor('none') + pc.set_edgecolor('red') + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), 'none') + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + pc.set_alpha(0.5) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]]) + pc.set_alpha(None) # restore default alpha + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Reset edgecolor to default. + pc.set_edgecolor(None) + pc.update_scalarmappable() + assert np.array_equal(pc.get_edgecolor(), mapped) + pc.set_facecolor(None) # restore default for facecolor + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), 'none') + # Turn off colormapping entirely: + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), 'none') + assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped + # Turn it back on by restoring the array (must be 1D!): + pc.set_array(z) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), 'none') + # Give color via tuple rather than string. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0)) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Provide an RGB array; mapping overrides it. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3))) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Turn off the mapping. + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3))) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # And an RGBA array. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4))) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Turn off the mapping. + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4))) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + + +def test_LineCollection_args(): + lc = LineCollection(None, linewidth=2.2, edgecolor='r', + zorder=3, facecolors=[0, 1, 0, 1]) + assert lc.get_linewidth()[0] == 2.2 + assert mcolors.same_color(lc.get_edgecolor(), 'r') + assert lc.get_zorder() == 3 + assert mcolors.same_color(lc.get_facecolor(), [[0, 1, 0, 1]]) + # To avoid breaking mplot3d, LineCollection internally sets the facecolor + # kwarg if it has not been specified. Hence we need the following test + # for LineCollection._set_default(). + lc = LineCollection(None, facecolor=None) + assert mcolors.same_color(lc.get_facecolor(), 'none') + + +def test_array_dimensions(pcfunc): + # Make sure we can set the 1D, 2D, and 3D array shapes + z = np.arange(12).reshape(3, 4) + pc = getattr(plt, pcfunc)(z) + # 1D + pc.set_array(z.ravel()) + pc.update_scalarmappable() + # 2D + pc.set_array(z) + pc.update_scalarmappable() + # 3D RGB is OK as well + z = np.arange(36, dtype=np.uint8).reshape(3, 4, 3) + pc.set_array(z) + pc.update_scalarmappable() + + +def test_get_segments(): + segments = np.tile(np.linspace(0, 1, 256), (2, 1)).T + lc = LineCollection([segments]) + + readback, = lc.get_segments() + # these should comeback un-changed! + assert np.all(segments == readback) + + +def test_set_offsets_late(): + identity = mtransforms.IdentityTransform() + sizes = [2] + + null = mcollections.CircleCollection(sizes=sizes) + + init = mcollections.CircleCollection(sizes=sizes, offsets=(10, 10)) + + late = mcollections.CircleCollection(sizes=sizes) + late.set_offsets((10, 10)) + + # Bbox.__eq__ doesn't compare bounds + null_bounds = null.get_datalim(identity).bounds + init_bounds = init.get_datalim(identity).bounds + late_bounds = late.get_datalim(identity).bounds + + # offsets and transform are applied when set after initialization + assert null_bounds != init_bounds + assert init_bounds == late_bounds + + +def test_set_offset_transform(): + skew = mtransforms.Affine2D().skew(2, 2) + init = mcollections.Collection(offset_transform=skew) + + late = mcollections.Collection() + late.set_offset_transform(skew) + + assert skew == init.get_offset_transform() == late.get_offset_transform() + + +def test_set_offset_units(): + # passing the offsets in initially (i.e. via scatter) + # should yield the same results as `set_offsets` + x = np.linspace(0, 10, 5) + y = np.sin(x) + d = x * np.timedelta64(24, 'h') + np.datetime64('2021-11-29') + + sc = plt.scatter(d, y) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(d, y))) + np.testing.assert_allclose(off0, sc.get_offsets()) + + # try the other way around + fig, ax = plt.subplots() + sc = ax.scatter(y, d) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(y, d))) + np.testing.assert_allclose(off0, sc.get_offsets()) + + +@image_comparison(baseline_images=["test_check_masked_offsets"], + extensions=["png"], remove_text=True, style="mpl20") +def test_check_masked_offsets(): + # Check if masked data is respected by scatter + # Ref: Issue #24545 + unmasked_x = [ + datetime(2022, 12, 15, 4, 49, 52), + datetime(2022, 12, 15, 4, 49, 53), + datetime(2022, 12, 15, 4, 49, 54), + datetime(2022, 12, 15, 4, 49, 55), + datetime(2022, 12, 15, 4, 49, 56), + ] + + masked_y = np.ma.array([1, 2, 3, 4, 5], mask=[0, 1, 1, 0, 0]) + + fig, ax = plt.subplots() + ax.scatter(unmasked_x, masked_y) + + +@check_figures_equal(extensions=["png"]) +def test_masked_set_offsets(fig_ref, fig_test): + x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0]) + y = np.arange(1, 6) + + ax_test = fig_test.add_subplot() + scat = ax_test.scatter(x, y) + scat.set_offsets(np.ma.column_stack([x, y])) + ax_test.set_xticks([]) + ax_test.set_yticks([]) + + ax_ref = fig_ref.add_subplot() + ax_ref.scatter([1, 2, 5], [1, 2, 5]) + ax_ref.set_xticks([]) + ax_ref.set_yticks([]) + + +def test_check_offsets_dtype(): + # Check that setting offsets doesn't change dtype + x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0]) + y = np.arange(1, 6) + + fig, ax = plt.subplots() + scat = ax.scatter(x, y) + masked_offsets = np.ma.column_stack([x, y]) + scat.set_offsets(masked_offsets) + assert isinstance(scat.get_offsets(), type(masked_offsets)) + + unmasked_offsets = np.column_stack([x, y]) + scat.set_offsets(unmasked_offsets) + assert isinstance(scat.get_offsets(), type(unmasked_offsets)) + + +@pytest.mark.parametrize('gapcolor', ['orange', ['r', 'k']]) +@check_figures_equal(extensions=['png']) +def test_striped_lines(fig_test, fig_ref, gapcolor): + ax_test = fig_test.add_subplot(111) + ax_ref = fig_ref.add_subplot(111) + + for ax in [ax_test, ax_ref]: + ax.set_xlim(0, 6) + ax.set_ylim(0, 1) + + x = range(1, 6) + linestyles = [':', '-', '--'] + + ax_test.vlines(x, 0, 1, linewidth=20, linestyle=linestyles, gapcolor=gapcolor, + alpha=0.5) + + if isinstance(gapcolor, str): + gapcolor = [gapcolor] + + for x, gcol, ls in zip(x, itertools.cycle(gapcolor), + itertools.cycle(linestyles)): + ax_ref.axvline(x, 0, 1, linewidth=20, linestyle=ls, gapcolor=gcol, alpha=0.5) + + +@check_figures_equal(extensions=['png', 'pdf', 'svg', 'eps']) +def test_hatch_linewidth(fig_test, fig_ref): + ax_test = fig_test.add_subplot() + ax_ref = fig_ref.add_subplot() + + lw = 2.0 + + polygons = [ + [(0.1, 0.1), (0.1, 0.4), (0.4, 0.4), (0.4, 0.1)], + [(0.6, 0.6), (0.6, 0.9), (0.9, 0.9), (0.9, 0.6)], + ] + ref = PolyCollection(polygons, hatch="x") + ref.set_hatch_linewidth(lw) + + with mpl.rc_context({"hatch.linewidth": lw}): + test = PolyCollection(polygons, hatch="x") + + ax_ref.add_collection(ref) + ax_test.add_collection(test) + + assert test.get_hatch_linewidth() == ref.get_hatch_linewidth() == lw diff --git a/shared/package-files/0b/0b8ab2a09ad44e4abe395de23bef15cf752d598a49c124dd879fef94608674d4/style.py b/shared/package-files/0b/0b8ab2a09ad44e4abe395de23bef15cf752d598a49c124dd879fef94608674d4/style.py new file mode 100644 index 0000000000000000000000000000000000000000..edc19627dba6835339768ccbaf726db21d8ac212 --- /dev/null +++ b/shared/package-files/0b/0b8ab2a09ad44e4abe395de23bef15cf752d598a49c124dd879fef94608674d4/style.py @@ -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 pip._vendor.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/0b/0b8e1198b935a517c0771d3a22e74f2e1da1ed77ad6f4bf3e905257ccd437cb4/_foreach_log2_native.h b/shared/package-files/0b/0b8e1198b935a517c0771d3a22e74f2e1da1ed77ad6f4bf3e905257ccd437cb4/_foreach_log2_native.h new file mode 100644 index 0000000000000000000000000000000000000000..0b64f1804ede7042c313f091a017dc65adda2083 --- /dev/null +++ b/shared/package-files/0b/0b8e1198b935a517c0771d3a22e74f2e1da1ed77ad6f4bf3e905257ccd437cb4/_foreach_log2_native.h @@ -0,0 +1,25 @@ +#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_log2_out(at::TensorList self, at::TensorList out); +TORCH_API ::std::vector foreach_tensor_log2_slow(at::TensorList self); +TORCH_API void foreach_tensor_log2_slow_(at::TensorList self); +TORCH_API ::std::vector foreach_tensor_log2_cuda(at::TensorList self); +TORCH_API void foreach_tensor_log2_cuda_(at::TensorList self); +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0b8e297950dcf124e01794e55b79dacf7da98ed561c6f5d6b92c03aa0fd881ed/is_set_to_cpu_dispatch.h b/shared/package-files/0b/0b8e297950dcf124e01794e55b79dacf7da98ed561c6f5d6b92c03aa0fd881ed/is_set_to_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e06a867a3f36a53486cbb1c50d2a9a72ab62924d --- /dev/null +++ b/shared/package-files/0b/0b8e297950dcf124e01794e55b79dacf7da98ed561c6f5d6b92c03aa0fd881ed/is_set_to_cpu_dispatch.h @@ -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 bool is_set_to(const at::Tensor & self, const at::Tensor & tensor); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/0b/0b9000b2d96087709121b8760b242e3e37fb731d4b39fcd2d7038fb920fc2de9/log10_cpu_dispatch.h b/shared/package-files/0b/0b9000b2d96087709121b8760b242e3e37fb731d4b39fcd2d7038fb920fc2de9/log10_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4215f0e104c345a1363ec643aa122701470e4385 --- /dev/null +++ b/shared/package-files/0b/0b9000b2d96087709121b8760b242e3e37fb731d4b39fcd2d7038fb920fc2de9/log10_cpu_dispatch.h @@ -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 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 cpu +} // namespace at diff --git a/shared/package-files/0b/0b930af0985560660558fbf1b0e46ca99027bce5de7d8439ee6d589b496e5b93/ext.py b/shared/package-files/0b/0b930af0985560660558fbf1b0e46ca99027bce5de7d8439ee6d589b496e5b93/ext.py new file mode 100644 index 0000000000000000000000000000000000000000..23e0d6b41ce6a36a2bc1a9657ff68aeb99d8b32f --- /dev/null +++ b/shared/package-files/0b/0b930af0985560660558fbf1b0e46ca99027bce5de7d8439ee6d589b496e5b93/ext.py @@ -0,0 +1,193 @@ +# coding: utf-8 +from collections import namedtuple +import datetime +import sys +import struct + + +PY2 = sys.version_info[0] == 2 + +if PY2: + int_types = (int, long) + _utc = None +else: + int_types = int + try: + _utc = datetime.timezone.utc + except AttributeError: + _utc = datetime.timezone(datetime.timedelta(0)) + + +class ExtType(namedtuple("ExtType", "code data")): + """ExtType represents ext type in msgpack.""" + + def __new__(cls, code, data): + if not isinstance(code, int): + raise TypeError("code must be int") + if not isinstance(data, bytes): + raise TypeError("data must be bytes") + if not 0 <= code <= 127: + raise ValueError("code must be 0~127") + return super(ExtType, cls).__new__(cls, code, data) + + +class Timestamp(object): + """Timestamp represents the Timestamp extension type in msgpack. + + When built with Cython, msgpack uses C methods to pack and unpack `Timestamp`. When using pure-Python + msgpack, :func:`to_bytes` and :func:`from_bytes` are used to pack and unpack `Timestamp`. + + This class is immutable: Do not override seconds and nanoseconds. + """ + + __slots__ = ["seconds", "nanoseconds"] + + def __init__(self, seconds, nanoseconds=0): + """Initialize a Timestamp object. + + :param int seconds: + Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds). + May be negative. + + :param int nanoseconds: + Number of nanoseconds to add to `seconds` to get fractional time. + Maximum is 999_999_999. Default is 0. + + Note: Negative times (before the UNIX epoch) are represented as negative seconds + positive ns. + """ + if not isinstance(seconds, int_types): + raise TypeError("seconds must be an integer") + if not isinstance(nanoseconds, int_types): + raise TypeError("nanoseconds must be an integer") + if not (0 <= nanoseconds < 10**9): + raise ValueError( + "nanoseconds must be a non-negative integer less than 999999999." + ) + self.seconds = seconds + self.nanoseconds = nanoseconds + + def __repr__(self): + """String representation of Timestamp.""" + return "Timestamp(seconds={0}, nanoseconds={1})".format( + self.seconds, self.nanoseconds + ) + + def __eq__(self, other): + """Check for equality with another Timestamp object""" + if type(other) is self.__class__: + return ( + self.seconds == other.seconds and self.nanoseconds == other.nanoseconds + ) + return False + + def __ne__(self, other): + """not-equals method (see :func:`__eq__()`)""" + return not self.__eq__(other) + + def __hash__(self): + return hash((self.seconds, self.nanoseconds)) + + @staticmethod + def from_bytes(b): + """Unpack bytes into a `Timestamp` object. + + Used for pure-Python msgpack unpacking. + + :param b: Payload from msgpack ext message with code -1 + :type b: bytes + + :returns: Timestamp object unpacked from msgpack ext payload + :rtype: Timestamp + """ + if len(b) == 4: + seconds = struct.unpack("!L", b)[0] + nanoseconds = 0 + elif len(b) == 8: + data64 = struct.unpack("!Q", b)[0] + seconds = data64 & 0x00000003FFFFFFFF + nanoseconds = data64 >> 34 + elif len(b) == 12: + nanoseconds, seconds = struct.unpack("!Iq", b) + else: + raise ValueError( + "Timestamp type can only be created from 32, 64, or 96-bit byte objects" + ) + return Timestamp(seconds, nanoseconds) + + def to_bytes(self): + """Pack this Timestamp object into bytes. + + Used for pure-Python msgpack packing. + + :returns data: Payload for EXT message with code -1 (timestamp type) + :rtype: bytes + """ + if (self.seconds >> 34) == 0: # seconds is non-negative and fits in 34 bits + data64 = self.nanoseconds << 34 | self.seconds + if data64 & 0xFFFFFFFF00000000 == 0: + # nanoseconds is zero and seconds < 2**32, so timestamp 32 + data = struct.pack("!L", data64) + else: + # timestamp 64 + data = struct.pack("!Q", data64) + else: + # timestamp 96 + data = struct.pack("!Iq", self.nanoseconds, self.seconds) + return data + + @staticmethod + def from_unix(unix_sec): + """Create a Timestamp from posix timestamp in seconds. + + :param unix_float: Posix timestamp in seconds. + :type unix_float: int or float. + """ + seconds = int(unix_sec // 1) + nanoseconds = int((unix_sec % 1) * 10**9) + return Timestamp(seconds, nanoseconds) + + def to_unix(self): + """Get the timestamp as a floating-point value. + + :returns: posix timestamp + :rtype: float + """ + return self.seconds + self.nanoseconds / 1e9 + + @staticmethod + def from_unix_nano(unix_ns): + """Create a Timestamp from posix timestamp in nanoseconds. + + :param int unix_ns: Posix timestamp in nanoseconds. + :rtype: Timestamp + """ + return Timestamp(*divmod(unix_ns, 10**9)) + + def to_unix_nano(self): + """Get the timestamp as a unixtime in nanoseconds. + + :returns: posix timestamp in nanoseconds + :rtype: int + """ + return self.seconds * 10**9 + self.nanoseconds + + def to_datetime(self): + """Get the timestamp as a UTC datetime. + + Python 2 is not supported. + + :rtype: datetime. + """ + return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta( + seconds=self.to_unix() + ) + + @staticmethod + def from_datetime(dt): + """Create a Timestamp from datetime with tzinfo. + + Python 2 is not supported. + + :rtype: Timestamp + """ + return Timestamp.from_unix(dt.timestamp()) diff --git a/shared/package-files/0b/0b972fd3e9f0a052343f72ee6b58427c94fc53547be83fdba1ffb3e20db64c9c/blob.h b/shared/package-files/0b/0b972fd3e9f0a052343f72ee6b58427c94fc53547be83fdba1ffb3e20db64c9c/blob.h new file mode 100644 index 0000000000000000000000000000000000000000..3e8da3e4e7a67e4920b8dd89350a157eddc7edbf --- /dev/null +++ b/shared/package-files/0b/0b972fd3e9f0a052343f72ee6b58427c94fc53547be83fdba1ffb3e20db64c9c/blob.h @@ -0,0 +1,208 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace caffe2 { + +class Tensor; + +/** + * @brief Blob is a general container that hosts a typed pointer. + * + * A Blob hosts a pointer as well as its type, and takes charge of deleting it + * properly when the blob is deallocated or re-allocated with a new type. A blob + * could contain anything, although the most common case is to contain a Tensor. + */ +class TORCH_API Blob final : public c10::intrusive_ptr_target { + public: + /** + * Initializes an empty Blob. + */ + Blob() noexcept : meta_(), pointer_(nullptr), has_ownership_(false) {} + ~Blob() override { + Reset(); + } + + Blob(Blob&& other) noexcept : Blob() { + swap(other); + } + + Blob& operator=(Blob&& other) noexcept { + Blob(std::move(other)).swap(*this); + return *this; + } + + /** + * Checks if the content stored in the blob is of type T. + */ + template + bool IsType() const noexcept { + return meta_.Match(); + } + + /** + * Returns the meta info of the blob. + */ + const TypeMeta meta() const noexcept { + return meta_; + } + + /** + * Returns a printable typename of the blob. + */ + c10::string_view TypeName() const noexcept { + return meta_.name(); + } + + /** + * @brief Gets the const reference of the stored object. The code checks if + * the stored object is of the desired type. + */ + // TODO(jerryzh): add a Get(c10::DeviceType) function? + template + const T& Get() const { + TORCH_INTERNAL_ASSERT( + IsType(), + "wrong type for the Blob instance. Blob contains ", + meta_.name(), + " while caller expects ", + TypeMeta::TypeName()); + // TODO: after we add Get(c10::DeviceType) + // and changed all the callsites, we can add + // a static assert here to enforce T != Tensor + return *static_cast(pointer_); + } + + const void* GetRaw() const noexcept { + return pointer_; + } + void* GetRaw() noexcept { + return pointer_; + } + + /** + * @brief Gets a mutable pointer to the stored object. + * + * If the current object is not of the right type, a new object is created + * and the old object is freed. Note that type T should have a default + * constructor. Otherwise, create the object yourself first, and use + * Reset(). + */ + template + T* GetMutable() { + static_assert( + std::is_default_constructible::value, + "GetMutable can't be called with non-default-constructible types. " + "Try using specialized methods"); + if (IsType()) { + return static_cast(pointer_); + } else { + // TODO Re-enable logging + // VLOG(1) << "Create new mutable object " << TypeMeta::TypeName(); + return Reset(new T()); + } + } + + template + T* GetMutableOrNull() { + if (IsType()) { + return static_cast(pointer_); + } else { + return nullptr; + } + } + + /** + * Sets the underlying object to the allocated one. The Blob then takes over + * the ownership of the passed in pointer. If there is already an object in + * the Blob, the old object is freed. + * + * This is used when the underlying class T does not have a default ctor, or + * complex initializations needs to be done outside the blob. + */ + template + T* Reset(T* allocated) { + free_(); + meta_ = TypeMeta::Make(); + pointer_ = static_cast(allocated); + has_ownership_ = true; + return allocated; + } + + /** + * Sets the underlying object to the allocated one, but does not take over + * the ownership of the passed in pointer. If there is already an object in + * the Blob, the old object is freed. + * + * Unlike Reset, this does not take over the ownership of the pointer and the + * caller is responsible for making sure that the lifetime of the allocated + * blob outlasts the lifetime of any access to this blob, until another Reset + * call is made or the blob is destructed. + */ + template + typename std::remove_const::type* ShareExternal( + typename std::remove_const::type* allocated) { + return static_cast(ShareExternal( + static_cast(allocated), + TypeMeta::Make::type>())); + } + + void* ShareExternal(void* allocated, const TypeMeta meta) { + free_(); + meta_ = meta; + pointer_ = allocated; + has_ownership_ = false; + return allocated; + } + + /** + * Resets the Blob to an empty one. + */ + void Reset() { + free_(); + pointer_ = nullptr; + meta_ = TypeMeta(); + has_ownership_ = false; + } + + /** + * @brief Swaps the underlying storage of two blobs. + */ + void swap(Blob& rhs) { + using std::swap; + swap(meta_, rhs.meta_); + swap(pointer_, rhs.pointer_); + swap(has_ownership_, rhs.has_ownership_); + } + + private: + void free_() { + if (has_ownership_ && pointer_ != nullptr) { + (*meta_.deleteFn())(pointer_); + } + } + + TypeMeta meta_; + void* pointer_; + bool has_ownership_; + + C10_DISABLE_COPY_AND_ASSIGN(Blob); +}; + +inline void swap(Blob& lhs, Blob& rhs) { + lhs.swap(rhs); +} + +inline std::ostream& operator<<(std::ostream& out, const Blob& v) { + return out << "Blob[" << v.TypeName() << "]"; +} + +} // namespace caffe2 diff --git a/shared/package-files/0b/0b9923922f700dd4a59e269a7e01ccef4b80a6d5c307f376d0b53bba3605f5cc/max_pool1d_with_indices_compositeimplicitautograd_dispatch.h b/shared/package-files/0b/0b9923922f700dd4a59e269a7e01ccef4b80a6d5c307f376d0b53bba3605f5cc/max_pool1d_with_indices_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9921979cc2be89f4db4f8a6cb9ac6b396db3b50c --- /dev/null +++ b/shared/package-files/0b/0b9923922f700dd4a59e269a7e01ccef4b80a6d5c307f376d0b53bba3605f5cc/max_pool1d_with_indices_compositeimplicitautograd_dispatch.h @@ -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 max_pool1d_with_indices(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/0b/0b99b4eef22c0a2af6026aefd102b4021d476d372304e07031d17ec76affffa1/agile.py b/shared/package-files/0b/0b99b4eef22c0a2af6026aefd102b4021d476d372304e07031d17ec76affffa1/agile.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c1a457a45acfc6801067b9a387c59a7cf0d998 --- /dev/null +++ b/shared/package-files/0b/0b99b4eef22c0a2af6026aefd102b4021d476d372304e07031d17ec76affffa1/agile.py @@ -0,0 +1,23 @@ +""" + pygments.lexers.agile + ~~~~~~~~~~~~~~~~~~~~~ + + Just export lexer classes previously contained in this module. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexers.lisp import SchemeLexer +from pygments.lexers.jvm import IokeLexer, ClojureLexer +from pygments.lexers.python import PythonLexer, PythonConsoleLexer, \ + PythonTracebackLexer, Python3Lexer, Python3TracebackLexer, DgLexer +from pygments.lexers.ruby import RubyLexer, RubyConsoleLexer, FancyLexer +from pygments.lexers.perl import PerlLexer, Perl6Lexer +from pygments.lexers.d import CrocLexer, MiniDLexer +from pygments.lexers.iolang import IoLexer +from pygments.lexers.tcl import TclLexer +from pygments.lexers.factor import FactorLexer +from pygments.lexers.scripting import LuaLexer, MoonScriptLexer + +__all__ = [] diff --git a/shared/package-files/0b/0b9b402c82d647c1850b9770e9fe2684cf545de23d0d178eafa276e10b2e6811/arma_forecast.inp b/shared/package-files/0b/0b9b402c82d647c1850b9770e9fe2684cf545de23d0d178eafa276e10b2e6811/arma_forecast.inp new file mode 100644 index 0000000000000000000000000000000000000000..27dc74ccb9d219ba2b74d7b9d0120fe2811d83f6 --- /dev/null +++ b/shared/package-files/0b/0b9b402c82d647c1850b9770e9fe2684cf545de23d0d178eafa276e10b2e6811/arma_forecast.inp @@ -0,0 +1,32 @@ +open \ + /home/skipper/statsmodels/statsmodels/statsmodels/tsa/tests/results/y_arma_data.csv +setobs 12 1980:01 --time-series +dataset addobs 10 + +# (0,0) +arima 1 0 1 ; 1 --nc +fcast 2000:11 2001:08 + +# (4,1) +arima 4 0 1 ; 3 --nc +fcast 2000:11 2001:08 + +# (5,0) +arima 5 0 0 ; 5 --nc +fcast 2000:11 2001:08 + +# (1,1) c +arima 1 0 1 ; 7 +fcast 2000:11 2001:08 + +# (4,1) c +arima 4 0 1 ; 9 +fcast 2000:11 2001:08 + +# (5,0) c +arima 5 0 0 ; 11 +fcast 2000:11 2001:08 + +smpl 2000:11 2001:08 +#store '/home/skipper/statsmodels/statsmodels-git/scikits/statsmodels/tsa/tests/results/results_arma_forecasts.csv' fc11 fe11 fc41 fe41 fc50 fe50 fc11c fe11c fc41c fe41c fc50c fe50c --omit-obs +# no way to capture errors as far as I can tell diff --git a/shared/package-files/0b/0ba0e67338ad8ed9eb3be5e10888bc5aa353d2e3e06273d6358b4ac094f0727e/covtype.rst b/shared/package-files/0b/0ba0e67338ad8ed9eb3be5e10888bc5aa353d2e3e06273d6358b4ac094f0727e/covtype.rst new file mode 100644 index 0000000000000000000000000000000000000000..f4b752ade17a7f9325ae1e29297fa8b45097075d --- /dev/null +++ b/shared/package-files/0b/0ba0e67338ad8ed9eb3be5e10888bc5aa353d2e3e06273d6358b4ac094f0727e/covtype.rst @@ -0,0 +1,30 @@ +.. _covtype_dataset: + +Forest covertypes +----------------- + +The samples in this dataset correspond to 30×30m patches of forest in the US, +collected for the task of predicting each patch's cover type, +i.e. the dominant species of tree. +There are seven covertypes, making this a multiclass classification problem. +Each sample has 54 features, described on the +`dataset's homepage `__. +Some of the features are boolean indicators, +while others are discrete or continuous measurements. + +**Data Set Characteristics:** + +================= ============ +Classes 7 +Samples total 581012 +Dimensionality 54 +Features int +================= ============ + +:func:`sklearn.datasets.fetch_covtype` will load the covertype dataset; +it returns a dictionary-like 'Bunch' object +with the feature matrix in the ``data`` member +and the target values in ``target``. If optional argument 'as_frame' is +set to 'True', it will return ``data`` and ``target`` as pandas +data frame, and there will be an additional member ``frame`` as well. +The dataset will be downloaded from the web if necessary. diff --git a/shared/package-files/0b/0ba2749e629148ae67c848daefe81981fe6d099a4f034699f65bb1fb3ea01f10/test_constructors.py b/shared/package-files/0b/0ba2749e629148ae67c848daefe81981fe6d099a4f034699f65bb1fb3ea01f10/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..d034162f1b46e11bd06204de7707c7343fd9b1b2 --- /dev/null +++ b/shared/package-files/0b/0ba2749e629148ae67c848daefe81981fe6d099a4f034699f65bb1fb3ea01f10/test_constructors.py @@ -0,0 +1,156 @@ +import numpy as np +import pytest + +from pandas._libs.tslibs import iNaT +from pandas._libs.tslibs.offsets import MonthEnd +from pandas._libs.tslibs.period import IncompatibleFrequency + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import ( + PeriodArray, + period_array, +) + + +@pytest.mark.parametrize( + "data, freq, expected", + [ + ([pd.Period("2017", "D")], None, [17167]), + ([pd.Period("2017", "D")], "D", [17167]), + ([2017], "D", [17167]), + (["2017"], "D", [17167]), + ([pd.Period("2017", "D")], pd.tseries.offsets.Day(), [17167]), + ([pd.Period("2017", "D"), None], None, [17167, iNaT]), + (pd.Series(pd.date_range("2017", periods=3)), None, [17167, 17168, 17169]), + (pd.date_range("2017", periods=3), None, [17167, 17168, 17169]), + (pd.period_range("2017", periods=4, freq="Q"), None, [188, 189, 190, 191]), + ], +) +def test_period_array_ok(data, freq, expected): + result = period_array(data, freq=freq).asi8 + expected = np.asarray(expected, dtype=np.int64) + tm.assert_numpy_array_equal(result, expected) + + +def test_period_array_readonly_object(): + # https://github.com/pandas-dev/pandas/issues/25403 + pa = period_array([pd.Period("2019-01-01")]) + arr = np.asarray(pa, dtype="object") + arr.setflags(write=False) + + result = period_array(arr) + tm.assert_period_array_equal(result, pa) + + result = pd.Series(arr) + tm.assert_series_equal(result, pd.Series(pa)) + + result = pd.DataFrame({"A": arr}) + tm.assert_frame_equal(result, pd.DataFrame({"A": pa})) + + +def test_from_datetime64_freq_changes(): + # https://github.com/pandas-dev/pandas/issues/23438 + arr = pd.date_range("2017", periods=3, freq="D") + result = PeriodArray._from_datetime64(arr, freq="M") + expected = period_array(["2017-01-01", "2017-01-01", "2017-01-01"], freq="M") + tm.assert_period_array_equal(result, expected) + + +@pytest.mark.parametrize("freq", ["2M", MonthEnd(2)]) +def test_from_datetime64_freq_2M(freq): + arr = np.array( + ["2020-01-01T00:00:00", "2020-01-02T00:00:00"], dtype="datetime64[ns]" + ) + result = PeriodArray._from_datetime64(arr, freq) + expected = period_array(["2020-01", "2020-01"], freq=freq) + tm.assert_period_array_equal(result, expected) + + +@pytest.mark.parametrize( + "data, freq, msg", + [ + ( + [pd.Period("2017", "D"), pd.Period("2017", "Y")], + None, + "Input has different freq", + ), + ([pd.Period("2017", "D")], "Y", "Input has different freq"), + ], +) +def test_period_array_raises(data, freq, msg): + with pytest.raises(IncompatibleFrequency, match=msg): + period_array(data, freq) + + +def test_period_array_non_period_series_raies(): + ser = pd.Series([1, 2, 3]) + with pytest.raises(TypeError, match="dtype"): + PeriodArray(ser, dtype="period[D]") + + +def test_period_array_freq_mismatch(): + arr = period_array(["2000", "2001"], freq="D") + with pytest.raises(IncompatibleFrequency, match="freq"): + PeriodArray(arr, dtype="period[M]") + + dtype = pd.PeriodDtype(pd.tseries.offsets.MonthEnd()) + with pytest.raises(IncompatibleFrequency, match="freq"): + PeriodArray(arr, dtype=dtype) + + +def test_from_sequence_disallows_i8(): + arr = period_array(["2000", "2001"], freq="D") + + msg = str(arr[0].ordinal) + with pytest.raises(TypeError, match=msg): + PeriodArray._from_sequence(arr.asi8, dtype=arr.dtype) + + with pytest.raises(TypeError, match=msg): + PeriodArray._from_sequence(list(arr.asi8), dtype=arr.dtype) + + +def test_from_td64nat_sequence_raises(): + # GH#44507 + td = pd.NaT.to_numpy("m8[ns]") + + dtype = pd.period_range("2005-01-01", periods=3, freq="D").dtype + + arr = np.array([None], dtype=object) + arr[0] = td + + msg = "Value must be Period, string, integer, or datetime" + with pytest.raises(ValueError, match=msg): + PeriodArray._from_sequence(arr, dtype=dtype) + + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(arr, dtype=dtype) + with pytest.raises(ValueError, match=msg): + pd.Index(arr, dtype=dtype) + with pytest.raises(ValueError, match=msg): + pd.array(arr, dtype=dtype) + with pytest.raises(ValueError, match=msg): + pd.Series(arr, dtype=dtype) + with pytest.raises(ValueError, match=msg): + pd.DataFrame(arr, dtype=dtype) + + +def test_freq_deprecated(): + # GH#52462 + data = np.arange(5).astype(np.int64) + msg = "The 'freq' keyword in the PeriodArray constructor is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = PeriodArray(data, freq="M") + + expected = PeriodArray(data, dtype="period[M]") + tm.assert_equal(res, expected) + + +def test_period_array_from_datetime64(): + arr = np.array( + ["2020-01-01T00:00:00", "2020-02-02T00:00:00"], dtype="datetime64[ns]" + ) + result = PeriodArray._from_datetime64(arr, freq=MonthEnd(2)) + + expected = period_array(["2020-01-01", "2020-02-01"], freq=MonthEnd(2)) + tm.assert_period_array_equal(result, expected) diff --git a/shared/package-files/0b/0ba37ca796ae9697a1b0e041987d5c3c8635c6239201265505f9e55e01af47fb/__init__.py b/shared/package-files/0b/0ba37ca796ae9697a1b0e041987d5c3c8635c6239201265505f9e55e01af47fb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba47f60a36ad3be8cb2f557adb57f1d2f1ba470 --- /dev/null +++ b/shared/package-files/0b/0ba37ca796ae9697a1b0e041987d5c3c8635c6239201265505f9e55e01af47fb/__init__.py @@ -0,0 +1,35 @@ +import torch + +from ._bounding_boxes import BoundingBoxes, BoundingBoxFormat +from ._image import Image +from ._mask import Mask +from ._torch_function_helpers import set_return_type +from ._tv_tensor import TVTensor +from ._video import Video + + +# TODO: Fix this. We skip this method as it leads to +# RecursionError: maximum recursion depth exceeded while calling a Python object +# Until `disable` is removed, there will be graph breaks after all calls to functional transforms +@torch.compiler.disable +def wrap(wrappee, *, like, **kwargs): + """Convert a :class:`torch.Tensor` (``wrappee``) into the same :class:`~torchvision.tv_tensors.TVTensor` subclass as ``like``. + + If ``like`` is a :class:`~torchvision.tv_tensors.BoundingBoxes`, the ``format`` and ``canvas_size`` of + ``like`` are assigned to ``wrappee``, unless they are passed as ``kwargs``. + + Args: + wrappee (Tensor): The tensor to convert. + like (:class:`~torchvision.tv_tensors.TVTensor`): The reference. + ``wrappee`` will be converted into the same subclass as ``like``. + kwargs: Can contain "format" and "canvas_size" if ``like`` is a :class:`~torchvision.tv_tensor.BoundingBoxes`. + Ignored otherwise. + """ + if isinstance(like, BoundingBoxes): + return BoundingBoxes._wrap( + wrappee, + format=kwargs.get("format", like.format), + canvas_size=kwargs.get("canvas_size", like.canvas_size), + ) + else: + return wrappee.as_subclass(type(like)) diff --git a/shared/package-files/0b/0ba825c867714acfa1303412b7d8e47ed99195318f30219d21095f0a147d8869/test_to_frame.py b/shared/package-files/0b/0ba825c867714acfa1303412b7d8e47ed99195318f30219d21095f0a147d8869/test_to_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..c829109d4e06c14dca160f1de8903432f844f4ef --- /dev/null +++ b/shared/package-files/0b/0ba825c867714acfa1303412b7d8e47ed99195318f30219d21095f0a147d8869/test_to_frame.py @@ -0,0 +1,28 @@ +from pandas import ( + DataFrame, + Index, + date_range, +) +import pandas._testing as tm + + +class TestToFrame: + def test_to_frame_datetime_tz(self): + # GH#25809 + idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC") + result = idx.to_frame() + expected = DataFrame(idx, index=idx) + tm.assert_frame_equal(result, expected) + + def test_to_frame_respects_none_name(self): + # GH#44212 if we explicitly pass name=None, then that should be respected, + # not changed to 0 + # GH-45448 this is first deprecated to only change in the future + idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC") + result = idx.to_frame(name=None) + exp_idx = Index([None], dtype=object) + tm.assert_index_equal(exp_idx, result.columns) + + result = idx.rename("foo").to_frame(name=None) + exp_idx = Index([None], dtype=object) + tm.assert_index_equal(exp_idx, result.columns) diff --git a/shared/package-files/0b/0bb386010413cf4619c5909aee0d26f3fd01aaaf2368f45adb6247552a8aeed6/test_slice.py b/shared/package-files/0b/0bb386010413cf4619c5909aee0d26f3fd01aaaf2368f45adb6247552a8aeed6/test_slice.py new file mode 100644 index 0000000000000000000000000000000000000000..36490719e26908b9e913ed99b7673d602647c492 --- /dev/null +++ b/shared/package-files/0b/0bb386010413cf4619c5909aee0d26f3fd01aaaf2368f45adb6247552a8aeed6/test_slice.py @@ -0,0 +1,65 @@ +from sympy.matrices.expressions.slice import MatrixSlice +from sympy.matrices.expressions import MatrixSymbol +from sympy.abc import a, b, c, d, k, l, m, n +from sympy.testing.pytest import raises, XFAIL +from sympy.functions.elementary.integers import floor +from sympy.assumptions import assuming, Q + + +X = MatrixSymbol('X', n, m) +Y = MatrixSymbol('Y', m, k) + +def test_shape(): + B = MatrixSlice(X, (a, b), (c, d)) + assert B.shape == (b - a, d - c) + +def test_entry(): + B = MatrixSlice(X, (a, b), (c, d)) + assert B[0,0] == X[a, c] + assert B[k,l] == X[a+k, c+l] + raises(IndexError, lambda : MatrixSlice(X, 1, (2, 5))[1, 0]) + + assert X[1::2, :][1, 3] == X[1+2, 3] + assert X[:, 1::2][3, 1] == X[3, 1+2] + +def test_on_diag(): + assert not MatrixSlice(X, (a, b), (c, d)).on_diag + assert MatrixSlice(X, (a, b), (a, b)).on_diag + +def test_inputs(): + assert MatrixSlice(X, 1, (2, 5)) == MatrixSlice(X, (1, 2), (2, 5)) + assert MatrixSlice(X, 1, (2, 5)).shape == (1, 3) + +def test_slicing(): + assert X[1:5, 2:4] == MatrixSlice(X, (1, 5), (2, 4)) + assert X[1, 2:4] == MatrixSlice(X, 1, (2, 4)) + assert X[1:5, :].shape == (4, X.shape[1]) + assert X[:, 1:5].shape == (X.shape[0], 4) + + assert X[::2, ::2].shape == (floor(n/2), floor(m/2)) + assert X[2, :] == MatrixSlice(X, 2, (0, m)) + assert X[k, :] == MatrixSlice(X, k, (0, m)) + +def test_exceptions(): + X = MatrixSymbol('x', 10, 20) + raises(IndexError, lambda: X[0:12, 2]) + raises(IndexError, lambda: X[0:9, 22]) + raises(IndexError, lambda: X[-1:5, 2]) + +@XFAIL +def test_symmetry(): + X = MatrixSymbol('x', 10, 10) + Y = X[:5, 5:] + with assuming(Q.symmetric(X)): + assert Y.T == X[5:, :5] + +def test_slice_of_slice(): + X = MatrixSymbol('x', 10, 10) + assert X[2, :][:, 3][0, 0] == X[2, 3] + assert X[:5, :5][:4, :4] == X[:4, :4] + assert X[1:5, 2:6][1:3, 2] == X[2:4, 4] + assert X[1:9:2, 2:6][1:3, 2] == X[3:7:2, 4] + +def test_negative_index(): + X = MatrixSymbol('x', 10, 10) + assert X[-1, :] == X[9, :] diff --git a/shared/package-files/0b/0bb44267abb55c60eccdfb20f6a65c786b817d62efaea9835260514a3628e639/test_runtests.py b/shared/package-files/0b/0bb44267abb55c60eccdfb20f6a65c786b817d62efaea9835260514a3628e639/test_runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..099582c3c4d67786a3af2a9863c6db29c7c47428 --- /dev/null +++ b/shared/package-files/0b/0bb44267abb55c60eccdfb20f6a65c786b817d62efaea9835260514a3628e639/test_runtests.py @@ -0,0 +1,284 @@ +import os +import sys +import subprocess + +from numba import cuda +import unittest +import itertools + +try: + import git # noqa: F401 from gitpython package +except ImportError: + has_gitpython = False +else: + has_gitpython = True + +try: + import yaml # from pyyaml package +except ImportError: + has_pyyaml = False +else: + has_pyyaml = True + + +class TestCase(unittest.TestCase): + """These test cases are meant to test the Numba test infrastructure itself. + Therefore, the logic used here shouldn't use numba.testing, but only the + upstream unittest, and run the numba test suite only in a subprocess.""" + + def get_testsuite_listing(self, args, *, subp_kwargs=None): + """ + Use `subp_kwargs` to pass extra argument to `subprocess.check_output`. + """ + subp_kwargs = subp_kwargs or {} + cmd = [sys.executable, '-m', 'numba.runtests', '-l'] + list(args) + out_bytes = subprocess.check_output(cmd, **subp_kwargs) + lines = out_bytes.decode('UTF-8').splitlines() + lines = [line for line in lines if line.strip()] + return lines + + def check_listing_prefix(self, prefix): + listing = self.get_testsuite_listing([prefix]) + for ln in listing[:-1]: + errmsg = '{!r} not startswith {!r}'.format(ln, prefix) + self.assertTrue(ln.startswith(prefix), msg=errmsg) + + def check_testsuite_size(self, args, minsize): + """ + Check that the reported numbers of tests are at least *minsize*. + """ + lines = self.get_testsuite_listing(args) + last_line = lines[-1] + self.assertTrue('tests found' in last_line) + number = int(last_line.split(' ')[0]) + # There may be some "skipped" messages at the beginning, + # so do an approximate check. + self.assertIn(len(lines), range(number + 1, number + 20)) + self.assertGreaterEqual(number, minsize) + return lines + + def check_all(self, ids): + lines = self.check_testsuite_size(ids, 5000) + # CUDA should be included by default + self.assertTrue(any('numba.cuda.tests.' in line for line in lines)) + # As well as subpackage + self.assertTrue(any('numba.tests.npyufunc.test_' in line + for line in lines),) + + def _get_numba_tests_from_listing(self, listing): + """returns a filter on strings starting with 'numba.', useful for + selecting the 'numba' test names from a test listing.""" + return filter(lambda x: x.startswith('numba.'), listing) + + def test_default(self): + self.check_all([]) + + def test_all(self): + self.check_all(['numba.tests']) + + def test_cuda(self): + # Even without CUDA enabled, there is at least one test + # (in numba.cuda.tests.nocuda) + minsize = 100 if cuda.is_available() else 1 + self.check_testsuite_size(['numba.cuda.tests'], minsize) + + @unittest.skipIf(not cuda.is_available(), "NO CUDA") + def test_cuda_submodules(self): + self.check_listing_prefix('numba.cuda.tests.cudadrv') + self.check_listing_prefix('numba.cuda.tests.cudapy') + self.check_listing_prefix('numba.cuda.tests.nocuda') + self.check_listing_prefix('numba.cuda.tests.cudasim') + + def test_module(self): + self.check_testsuite_size(['numba.tests.test_storeslice'], 2) + self.check_testsuite_size(['numba.tests.test_nested_calls'], 10) + # Several modules + self.check_testsuite_size(['numba.tests.test_nested_calls', + 'numba.tests.test_storeslice'], 12) + + def test_subpackage(self): + self.check_testsuite_size(['numba.tests.npyufunc'], 50) + + def test_random(self): + self.check_testsuite_size( + ['--random', '0.1', 'numba.tests.npyufunc'], 5) + + def test_include_exclude_tags(self): + def get_count(arg_list): + lines = self.get_testsuite_listing(arg_list) + self.assertIn('tests found', lines[-1]) + count = int(lines[-1].split()[0]) + self.assertTrue(count > 0) + return count + + tags = ['long_running', 'long_running, important'] + + total = get_count(['numba.tests']) + + for tag in tags: + included = get_count(['--tags', tag, 'numba.tests']) + excluded = get_count(['--exclude-tags', tag, 'numba.tests']) + self.assertEqual(total, included + excluded) + + # check syntax with `=` sign in + included = get_count(['--tags=%s' % tag, 'numba.tests']) + excluded = get_count(['--exclude-tags=%s' % tag, 'numba.tests']) + self.assertEqual(total, included + excluded) + + def test_check_shard(self): + tmpAll = self.get_testsuite_listing([]) + tmp1 = self.get_testsuite_listing(['-j', '0:2']) + tmp2 = self.get_testsuite_listing(['-j', '1:2']) + + lAll = set(self._get_numba_tests_from_listing(tmpAll)) + l1 = set(self._get_numba_tests_from_listing(tmp1)) + l2 = set(self._get_numba_tests_from_listing(tmp2)) + + # The difference between two adjacent shards should be less than 5% of + # the total + self.assertLess(abs(len(l2) - len(l1)), len(lAll) / 20) + self.assertLess(len(l1), len(lAll)) + self.assertLess(len(l2), len(lAll)) + + def test_check_sharding_equivalent(self): + # get some shards + sharded = list() + for i in range(3): + subset = self.get_testsuite_listing(['-j', '{}:3'.format(i)]) + slist = [*self._get_numba_tests_from_listing(subset)] + sharded.append(slist) + + # get the always running tests + tmp = self.get_testsuite_listing(['--tag', 'always_test']) + always_running = set(self._get_numba_tests_from_listing(tmp)) + + # make sure there is at least one test that always runs + self.assertGreaterEqual(len(always_running), 1) + + # check that each shard contains no repeats + sharded_sets = [set(x) for x in sharded] + for i in range(len(sharded)): + self.assertEqual(len(sharded_sets[i]), len(sharded[i])) + + # check that the always running tests are in every shard, and then + # remove them from the shards + for shard in sharded_sets: + for test in always_running: + self.assertIn(test, shard) + shard.remove(test) + self.assertNotIn(test, shard) + + # check that there is no overlap between the shards + for a, b in itertools.combinations(sharded_sets, 2): + self.assertFalse(a & b) + + # check that the sum of the shards and the always running tests is the + # same as the full listing + + sum_of_parts = set() + for x in sharded_sets: + sum_of_parts.update(x) + sum_of_parts.update(always_running) + + full_listing = set(self._get_numba_tests_from_listing( + self.get_testsuite_listing([]))) + + self.assertEqual(sum_of_parts, full_listing) + + @unittest.skipUnless(has_gitpython, "Requires gitpython") + def test_gitdiff(self): + # Check for git + try: + subprocess.call("git", + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + except FileNotFoundError: + self.skipTest("no git available") + + # default + outs = self.get_testsuite_listing(['-g']) + self.assertNotIn("Git diff by common ancestor", outs) + # using ancestor + outs = self.get_testsuite_listing(['-g=ancestor']) + self.assertIn("Git diff by common ancestor", outs) + # misspelled ancestor + subp_kwargs = dict(stderr=subprocess.DEVNULL) + with self.assertRaises(subprocess.CalledProcessError): + self.get_testsuite_listing(['-g=ancest'], subp_kwargs=subp_kwargs) + + @unittest.skipUnless(has_pyyaml, "Requires pyyaml") + def test_azure_config(self): + from yaml import Loader + base_path = os.path.dirname(os.path.abspath(__file__)) + azure_pipe = os.path.join(base_path, '..', '..', 'azure-pipelines.yml') + if not os.path.isfile(azure_pipe): + self.skipTest("'azure-pipelines.yml' is not available") + with open(os.path.abspath(azure_pipe), 'rt') as f: + data = f.read() + pipe_yml = yaml.load(data, Loader=Loader) + + templates = pipe_yml['jobs'] + # first look at the items in the first template, this is linux. + start_indexes = [] + tmplt = templates[0] + matrix = tmplt['parameters']['matrix'] + for setup in matrix.values(): + start_indexes.append(setup['TEST_START_INDEX']) + + # next look at the items in the windows only template + winpath = ['..', '..', 'buildscripts', 'azure', 'azure-windows.yml'] + azure_windows = os.path.join(base_path, *winpath) + if not os.path.isfile(azure_windows): + self.skipTest("'azure-windows.yml' is not available") + with open(os.path.abspath(azure_windows), 'rt') as f: + data = f.read() + windows_yml = yaml.load(data, Loader=Loader) + + # There's only one template in windows and its keyed differently to the + # above, get its matrix. + matrix = windows_yml['jobs'][0]['strategy']['matrix'] + for setup in matrix.values(): + start_indexes.append(setup['TEST_START_INDEX']) + + # sanity checks + # 1. That the TEST_START_INDEX is unique + self.assertEqual(len(start_indexes), len(set(start_indexes))) + # 2. That the TEST_START_INDEX is a complete range + lim_start_index = max(start_indexes) + 1 + expected = [*range(lim_start_index)] + self.assertEqual(sorted(start_indexes), expected) + # 3. That the number of indexes matches the declared test count + self.assertEqual(lim_start_index, pipe_yml['variables']['TEST_COUNT']) + + def test_no_compilation_on_list(self): + # Checks that the test suite doesn't do any CPU-side compilation on + # listing of tests. + code = """if 1: + from unittest import mock + from llvmlite import binding as llvm + error = RuntimeError("Detected compilation during test listing") + with mock.patch.object(llvm.ExecutionEngine, 'finalize_object', + side_effect=error): + import numba + {0} + """ + + # Run with a jit function in the test to demonstrate failure + with self.assertRaises(subprocess.CalledProcessError) as raises: + cmd = [sys.executable, "-c", code.format("numba.njit(lambda:0)()")] + subprocess.check_output(cmd, + stderr=subprocess.STDOUT, + timeout=60) + self.assertIn("Detected compilation during test listing", + raises.exception.stdout.decode('UTF-8')) + + # Run to validate the test suite does not trigger compilation during + # listing. + cmd = [sys.executable, "-c", code.format("numba.test('-l')")] + subprocess.check_call(cmd, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL,) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/0b/0bb5451907acb1e3df272a2036ce62b716cecbc60bf4e1146cadca0db40cddf2/fake_quantize_per_channel_affine_cachemask_backward.h b/shared/package-files/0b/0bb5451907acb1e3df272a2036ce62b716cecbc60bf4e1146cadca0db40cddf2/fake_quantize_per_channel_affine_cachemask_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..c5f7d5e08b040725fdfee137dd092c4cfe68587f --- /dev/null +++ b/shared/package-files/0b/0bb5451907acb1e3df272a2036ce62b716cecbc60bf4e1146cadca0db40cddf2/fake_quantize_per_channel_affine_cachemask_backward.h @@ -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::fake_quantize_per_channel_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor +inline at::Tensor fake_quantize_per_channel_affine_cachemask_backward(const at::Tensor & grad, const at::Tensor & mask) { + return at::_ops::fake_quantize_per_channel_affine_cachemask_backward::call(grad, mask); +} + +} diff --git a/shared/package-files/0b/0bbb177df1d35ccdcffa268b3cf7ea7e60e8c4e7e540c24b70cede77da778da9/__init__.py b/shared/package-files/0b/0bbb177df1d35ccdcffa268b3cf7ea7e60e8c4e7e540c24b70cede77da778da9/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19a169fc30183db91f931ad6ad04fbc0e16559b3 --- /dev/null +++ b/shared/package-files/0b/0bbb177df1d35ccdcffa268b3cf7ea7e60e8c4e7e540c24b70cede77da778da9/__init__.py @@ -0,0 +1,4 @@ +from .more import * # noqa +from .recipes import * # noqa + +__version__ = '8.8.0' diff --git a/shared/package-files/0b/0bc1609acc21e2e9bea9882a3d93411295d569e7d15e2e9ed36ea9623a272c78/animation.pyi b/shared/package-files/0b/0bc1609acc21e2e9bea9882a3d93411295d569e7d15e2e9ed36ea9623a272c78/animation.pyi new file mode 100644 index 0000000000000000000000000000000000000000..345e3c6dbe61f1b3c99eba4c9e77edb0c51cff3e --- /dev/null +++ b/shared/package-files/0b/0bc1609acc21e2e9bea9882a3d93411295d569e7d15e2e9ed36ea9623a272c78/animation.pyi @@ -0,0 +1,217 @@ +import abc +from collections.abc import Callable, Collection, Iterable, Sequence, Generator +import contextlib +from pathlib import Path +from matplotlib.artist import Artist +from matplotlib.backend_bases import TimerBase +from matplotlib.figure import Figure + +from typing import Any + +subprocess_creation_flags: int + +def adjusted_figsize(w: float, h: float, dpi: float, n: int) -> tuple[float, float]: ... + +class MovieWriterRegistry: + def __init__(self) -> None: ... + def register( + self, name: str + ) -> Callable[[type[AbstractMovieWriter]], type[AbstractMovieWriter]]: ... + def is_available(self, name: str) -> bool: ... + def __iter__(self) -> Generator[str, None, None]: ... + def list(self) -> list[str]: ... + def __getitem__(self, name: str) -> type[AbstractMovieWriter]: ... + +writers: MovieWriterRegistry + +class AbstractMovieWriter(abc.ABC, metaclass=abc.ABCMeta): + fps: int + metadata: dict[str, str] + codec: str + bitrate: int + def __init__( + self, + fps: int = ..., + metadata: dict[str, str] | None = ..., + codec: str | None = ..., + bitrate: int | None = ..., + ) -> None: ... + outfile: str | Path + fig: Figure + dpi: float + + @abc.abstractmethod + def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ... + @property + def frame_size(self) -> tuple[int, int]: ... + @abc.abstractmethod + def grab_frame(self, **savefig_kwargs) -> None: ... + @abc.abstractmethod + def finish(self) -> None: ... + @contextlib.contextmanager + def saving( + self, fig: Figure, outfile: str | Path, dpi: float | None, *args, **kwargs + ) -> Generator[AbstractMovieWriter, None, None]: ... + +class MovieWriter(AbstractMovieWriter): + supported_formats: list[str] + frame_format: str + extra_args: list[str] | None + def __init__( + self, + fps: int = ..., + codec: str | None = ..., + bitrate: int | None = ..., + extra_args: list[str] | None = ..., + metadata: dict[str, str] | None = ..., + ) -> None: ... + def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ... + def grab_frame(self, **savefig_kwargs) -> None: ... + def finish(self) -> None: ... + @classmethod + def bin_path(cls) -> str: ... + @classmethod + def isAvailable(cls) -> bool: ... + +class FileMovieWriter(MovieWriter): + fig: Figure + outfile: str | Path + dpi: float + temp_prefix: str + fname_format_str: str + def setup( + self, + fig: Figure, + outfile: str | Path, + dpi: float | None = ..., + frame_prefix: str | Path | None = ..., + ) -> None: ... + def __del__(self) -> None: ... + @property + def frame_format(self) -> str: ... + @frame_format.setter + def frame_format(self, frame_format: str) -> None: ... + +class PillowWriter(AbstractMovieWriter): + @classmethod + def isAvailable(cls) -> bool: ... + def setup( + self, fig: Figure, outfile: str | Path, dpi: float | None = ... + ) -> None: ... + def grab_frame(self, **savefig_kwargs) -> None: ... + def finish(self) -> None: ... + +class FFMpegBase: + codec: str + @property + def output_args(self) -> list[str]: ... + +class FFMpegWriter(FFMpegBase, MovieWriter): ... + +class FFMpegFileWriter(FFMpegBase, FileMovieWriter): + supported_formats: list[str] + +class ImageMagickBase: + @classmethod + def bin_path(cls) -> str: ... + @classmethod + def isAvailable(cls) -> bool: ... + +class ImageMagickWriter(ImageMagickBase, MovieWriter): + input_names: str + +class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter): + supported_formats: list[str] + @property + def input_names(self) -> str: ... + +class HTMLWriter(FileMovieWriter): + supported_formats: list[str] + @classmethod + def isAvailable(cls) -> bool: ... + embed_frames: bool + default_mode: str + def __init__( + self, + fps: int = ..., + codec: str | None = ..., + bitrate: int | None = ..., + extra_args: list[str] | None = ..., + metadata: dict[str, str] | None = ..., + embed_frames: bool = ..., + default_mode: str = ..., + embed_limit: float | None = ..., + ) -> None: ... + def setup( + self, + fig: Figure, + outfile: str | Path, + dpi: float | None = ..., + frame_dir: str | Path | None = ..., + ) -> None: ... + def grab_frame(self, **savefig_kwargs): ... + def finish(self) -> None: ... + +class Animation: + frame_seq: Iterable[Artist] + event_source: Any + def __init__( + self, fig: Figure, event_source: Any | None = ..., blit: bool = ... + ) -> None: ... + def __del__(self) -> None: ... + def save( + self, + filename: str | Path, + writer: AbstractMovieWriter | str | None = ..., + fps: int | None = ..., + dpi: float | None = ..., + codec: str | None = ..., + bitrate: int | None = ..., + extra_args: list[str] | None = ..., + metadata: dict[str, str] | None = ..., + extra_anim: list[Animation] | None = ..., + savefig_kwargs: dict[str, Any] | None = ..., + *, + progress_callback: Callable[[int, int], Any] | None = ... + ) -> None: ... + def new_frame_seq(self) -> Iterable[Artist]: ... + def new_saved_frame_seq(self) -> Iterable[Artist]: ... + def to_html5_video(self, embed_limit: float | None = ...) -> str: ... + def to_jshtml( + self, + fps: int | None = ..., + embed_frames: bool = ..., + default_mode: str | None = ..., + ) -> str: ... + def _repr_html_(self) -> str: ... + def pause(self) -> None: ... + def resume(self) -> None: ... + +class TimedAnimation(Animation): + def __init__( + self, + fig: Figure, + interval: int = ..., + repeat_delay: int = ..., + repeat: bool = ..., + event_source: TimerBase | None = ..., + *args, + **kwargs + ) -> None: ... + +class ArtistAnimation(TimedAnimation): + def __init__(self, fig: Figure, artists: Sequence[Collection[Artist]], *args, **kwargs) -> None: ... + +class FuncAnimation(TimedAnimation): + def __init__( + self, + fig: Figure, + func: Callable[..., Iterable[Artist]], + frames: Iterable | int | Callable[[], Generator] | None = ..., + init_func: Callable[[], Iterable[Artist]] | None = ..., + fargs: tuple[Any, ...] | None = ..., + save_count: int | None = ..., + *, + cache_frame_data: bool = ..., + **kwargs + ) -> None: ... diff --git a/shared/package-files/0b/0bc174193943142a49e58c782d8bc3af9537ffea36ea5921d78f6e442a118513/fit_ets_results_nonseasonal.json b/shared/package-files/0b/0bc174193943142a49e58c782d8bc3af9537ffea36ea5921d78f6e442a118513/fit_ets_results_nonseasonal.json new file mode 100644 index 0000000000000000000000000000000000000000..0131b2a210c8fbc198d968f1f7ac7ac9f595529d --- /dev/null +++ b/shared/package-files/0b/0bc174193943142a49e58c782d8bc3af9537ffea36ea5921d78f6e442a118513/fit_ets_results_nonseasonal.json @@ -0,0 +1,428 @@ +{ + "TRUE": { + "AAN": { + "alpha": [0.99989969], + "beta": [0.11886985], + "gamma": ["NaN"], + "phi": [0.80000197], + "initstate": [36.46466837, 34.72584983], + "states": [ + [36.46466837, 34.72584983], + [111.00444391, 33.33954414], + [130.82912094, 25.8577145], + [141.28811387, 19.47039125], + [154.2280392, 15.26292828], + [162.74123627, 11.77084583], + [192.16447653, 11.79511278], + [240.79579335, 14.09570863], + [304.21215963, 17.47506305], + [383.99796591, 21.80318555], + [429.65932578, 20.7972885], + [359.32565463, 6.29854055], + [437.24454332, 13.70295357], + [468.39876426, 13.36283045], + [424.44081866, 4.19361146], + [487.97339313, 10.50892629], + [509.82709889, 10.00571067], + [506.34840471, 6.63943524], + [340.20143754, -15.07173243], + [240.26773648, -22.50430409], + [219.03311171, -18.38761082], + [172.07789796, -18.5434781], + [252.58052824, -3.50093403], + [221.07395708, -6.2133525], + [276.51271342, 2.21088831], + [271.14866728, 0.92075971], + [342.61150544, 9.14466896], + [428.3479688, 16.63854612], + [442.39447955, 13.39832392], + [432.78718725, 8.30229721], + [437.24993723, 6.38279833], + [437.20967621, 4.49442471], + [445.36364081, 4.13746117], + [453.1945569, 3.84743431], + [454.40982787, 2.85651583], + [422.38234791, -1.79393609], + [456.03360198, 2.73598177], + [440.38839372, 0.06865339], + [425.19590209, -1.75771681], + [486.19891284, 6.01313791], + [500.42814122, 5.93023463], + [521.27429388, 6.6584281], + [508.9493878, 3.22829475], + [488.89112899, -0.10894828], + [509.86846186, 2.41702526], + [456.72843715, -4.6136281], + [473.81451864, -1.2209058], + [525.94554298, 5.33681655], + [549.8318397, 6.60154759], + [542.341751, 3.76297155] + ], + "residuals": [46.76371814, -6.84771067, -10.22825544, -2.63669041, -3.69754643, 20.00854745, 39.19913535, 52.14500216, 65.8123229, 28.2215994, -86.98026751, 72.88735495, 20.19385673, -54.65371834, 60.18371387, 13.44789299, -11.48443434, -171.47572853, -87.88510094, -3.23146141, -32.24832368, 95.34701313, -28.70869673, 60.41551062, -7.13347667, 70.73332359, 78.42857712, 0.73571495, -20.3280168, -2.17932271, -5.1470285, 4.55887328, 4.52139255, -1.8628709, -34.31614037, 35.08992621, -17.8357881, -15.24894404, 62.41544832, 9.41965109, 16.10356859, -17.6534324, -22.64317221, 21.06660483, -55.07917447, 20.77907732, 53.11307896, 19.61880089, -12.77262092], + "fitted": [64.24541648, 137.67614474, 151.51534335, 156.86446514, 166.43841182, 172.15793607, 201.60058993, 252.07238795, 318.19224441, 401.44055719, 446.29719745, 364.36449945, 448.20693311, 479.08905488, 427.79571607, 496.38055481, 517.83168709, 511.65996595, 328.14402198, 222.26424899, 204.32298692, 157.24307904, 249.77977414, 216.10326287, 278.28142841, 271.88527686, 349.92725858, 441.6588384, 453.11316502, 439.42904133, 442.35618843, 440.80522481, 448.67361788, 456.27251191, 456.69504615, 420.94719551, 458.22239278, 440.44331656, 423.78972519, 491.00943498, 505.17234058, 526.60104944, 511.53202994, 488.80397015, 511.80208682, 453.0375256, 472.8377916, 530.21500671, 555.11309075], + "sigma2": [2524.87915822], + "loglik": [-284.64438385], + "forecast": [545.35213563, 547.76044926, 549.68710489, 551.22843318], + "simulation": [547.11618798, 550.09223639, 553.1698472, 557.1828509] + }, + "MAN": { + "alpha": [0.92024781], + "beta": [0.00010003], + "gamma": ["NaN"], + "phi": [0.96360848], + "initstate": [36.95199158, 35.03197857], + "states": [ + [36.95199158, 35.03197857], + [107.79511867, 33.7611429], + [131.58601678, 32.5315735], + [143.01345409, 31.3455349], + [155.742309, 30.20292373], + [164.50380656, 29.10158235], + [192.19677776, 28.04249363], + [239.07859613, 27.02414347], + [301.09923081, 26.04460484], + [379.39420981, 25.10258469], + [427.58230842, 24.1916722], + [366.62037109, 23.30214022], + [433.40960553, 22.45895912], + [467.33613466, 21.64297887], + [429.52002993, 20.84898057], + [484.91940638, 20.09409257], + [509.38612591, 19.36339284], + [508.07768419, 18.65655921], + [355.00786285, 17.95902621], + [250.79055022, 17.29226073], + [222.89444721, 16.65812565], + [177.4078277, 16.04522208], + [247.82721514, 15.46728594], + [224.39359737, 14.90024067], + [273.50675816, 14.36177613], + [272.43977267, 13.83750904], + [338.08509597, 13.33962724], + [422.18169498, 12.86192187], + [441.77097083, 12.39463915], + [434.45431397, 11.94148588], + [437.94448086, 11.50604569], + [438.15204175, 11.08614062], + [445.64088947, 10.68235198], + [453.41349029, 10.29333096], + [455.12123717, 9.91784851], + [425.75236415, 9.55269181], + [454.35596917, 9.20716344], + [442.20826166, 8.86981599], + [427.23291192, 8.5444731], + [482.15864804, 8.2386021], + [499.60511422, 7.93982034], + [520.15779004, 7.65228063], + [510.42972988, 7.3719436], + [491.17332263, 7.1008021], + [508.92512394, 6.84357897], + [461.4120816, 6.58864937], + [473.3336521, 6.34948416], + [522.24248908, 6.12306803], + [548.1038965, 5.90241003], + [543.25371532, 5.68646694] + ], + "residuals": [0.5699412, -0.06769307, -0.13285543, -0.10963337, -0.11958725, -0.0019728, 0.09844487, 0.14747361, 0.17722022, 0.06461835, -0.20310041, 0.12382549, 0.02933635, -0.13059661, 0.08533867, 0.01099821, -0.04109045, -0.3533299, -0.35468623, -0.18104354, -0.2798607, 0.30964494, -0.15856693, 0.15818607, -0.05637086, 0.19891573, 0.22059817, 0.01799227, -0.04612901, -0.01953424, -0.02632919, -0.00773256, -0.0060085, -0.01925743, -0.09102914, 0.04846383, -0.04930933, -0.05670686, 0.11651583, 0.02108081, 0.02763874, -0.03522818, -0.0553482, 0.02380419, -0.11405335, 0.01294602, 0.09698321, 0.04107049, -0.02067753], + "fitted": [70.70910331, 140.32764236, 162.93371697, 173.21827742, 184.84610252, 192.54633819, 219.21876251, 265.11929002, 326.19603297, 403.58327337, 450.89360896, 389.07451108, 455.05124905, 488.19149269, 449.61028447, 504.28224444, 528.04485551, 526.05530291, 372.31333285, 267.45351935, 238.9463584, 192.86913981, 262.73162307, 238.75159568, 287.34588747, 285.77371377, 350.93927394, 434.575552, 453.71455026, 445.96123106, 449.03180409, 448.8347409, 455.93449446, 463.33223132, 464.67816013, 434.95741902, 463.22806997, 450.75529159, 435.46643868, 490.09743492, 507.25599245, 527.53159257, 517.53339727, 498.01571577, 515.51965468, 467.76096002, 479.4520689, 528.14272937, 553.79150888], + "sigma2": [0.02699609], + "loglik": [-292.23998794], + "forecast": [548.73324311, 554.01336256, 559.10133046, 564.00413949], + "simulation": [1516.72741014, 2023.08879651, 3922.27554037, 12227.18112316] + }, + "AMN": [], + "MMN": { + "alpha": [0.99989195], + "beta": [0.0001004], + "gamma": ["NaN"], + "phi": [0.80000008], + "initstate": [49.59586353, 1.94518873], + "states": [ + [49.59586353, 1.94518873], + [111.00626531, 1.70287641], + [130.83265987, 1.53086356], + [141.29169592, 1.40585035], + [154.23115931, 1.31323946], + [162.74400507, 1.24356515], + [192.16665452, 1.19051394], + [240.79757902, 1.14971849], + [304.21360996, 1.11809546], + [383.99901648, 1.09342713], + [429.66029592, 1.07407275], + [359.32726149, 1.05880942], + [437.24525098, 1.04679424], + [468.39918401, 1.03726683], + [424.44158998, 1.02969158], + [487.97365101, 1.02369621], + [509.8270836, 1.01891507], + [506.34846072, 1.01510145], + [340.20285088, 1.01202887], + [240.27007295, 1.00958111], + [219.03528099, 1.00764793], + [172.07988187, 1.00609154], + [252.58148385, 1.00491676], + [221.0745893, 1.00391856], + [276.51285777, 1.00315848], + [271.14860687, 1.00252379], + [342.61093749, 1.00204478], + [428.34663178, 1.00166046], + [442.39309699, 1.0013313], + [432.78623723, 1.00106261], + [437.24927611, 1.00085095], + [437.20919642, 1.00068063], + [445.3632427, 1.00054628], + [453.19418526, 1.00043872], + [454.40952687, 1.0003512], + [422.38238038, 1.00027384], + [456.03349544, 1.00022705], + [440.38830422, 1.00017817], + [425.19602096, 1.00013905], + [486.19858678, 1.00012564], + [500.42755379, 1.00010344], + [521.27366105, 1.00008692], + [508.94895275, 1.00006716], + [488.89102811, 1.00004976], + [509.86831031, 1.00004411], + [456.72865648, 1.00002482], + [473.8147576, 1.00002361], + [525.9452384, 1.00002994], + [549.83122788, 1.00002851], + [542.34128053, 1.00002143] + ], + "residuals": [0.31444931, -0.23014643, -0.2318658, -0.1688208, -0.15150488, -0.00816872, 0.08990931, 0.12994864, 0.1544487, 0.04175385, -0.21018479, 0.16248472, 0.03276962, -0.11999931, 0.12309851, 0.0253941, -0.02160288, -0.3361696, -0.30050075, -0.0953169, -0.21917124, 0.46075107, -0.12818097, 0.24688675, -0.02187275, 0.26103694, 0.24822754, 0.0314258, -0.02275879, 0.00945532, -0.00077192, 0.01809786, 0.01714063, 0.00233019, -0.07074952, 0.0794419, -0.03448621, -0.03463881, 0.14335758, 0.02916546, 0.0415749, -0.0237139, -0.03946635, 0.04287101, -0.10426519, 0.03739318, 0.11001383, 0.04539522, -0.01364623], + "fitted": [84.45295975, 169.93937366, 183.93542271, 185.5529762, 191.79941262, 193.74916611, 220.93556124, 269.23116678, 332.63025613, 412.4411519, 454.93797007, 376.13557184, 453.53850332, 482.3125063, 434.49387893, 497.2024395, 517.52733348, 512.45655482, 343.47273561, 242.10995914, 220.37439289, 172.91795779, 253.574502, 221.76735281, 277.21132665, 271.6959264, 343.17127523, 428.91553799, 442.86420204, 433.15410596, 437.54691303, 437.44724083, 445.55786703, 453.35323968, 454.53719225, 422.47491085, 456.11632597, 440.45107411, 425.24332074, 486.24745386, 500.46896355, 521.30990939, 508.97629614, 488.91049078, 509.88630422, 456.7377262, 473.8237079, 525.95783395, 549.84376674], + "sigma2": [0.02636346], + "loglik": [-291.19968724], + "forecast": [542.3505805, 542.35988062, 542.36732084, 542.37327309], + "simulation": [1499.08539655, 2099.13666096, 4154.16307236, 13465.2229351] + }, + "ANN": [], + "MNN": [] + }, + "FALSE": { + "AAN": { + "alpha": [0.99770564], + "beta": [0.0001001], + "gamma": ["NaN"], + "phi": ["NaN"], + "initstate": [21.3150686, 11.71213626], + "states": [ + [21.3150686, 11.71213626], + [110.83021567, 11.71994255], + [130.80944069, 11.72077123], + [141.28994009, 11.72064679], + [154.22498205, 11.72076864], + [162.74821856, 11.72044781], + [192.12587828, 11.72221943], + [240.71494479, 11.72591843], + [304.09859591, 11.73110146], + [383.84814933, 11.73792602], + [429.58397366, 11.74133716], + [359.50508703, 11.73312781], + [437.10039507, 11.73973603], + [468.35591056, 11.74169413], + [424.56304605, 11.73612212], + [487.86085661, 11.74129551], + [509.80498496, 11.7423192], + [506.3821272, 11.74079762], + [340.59249355, 11.72298528], + [240.51601958, 11.711768], + [219.10894899, 11.70844505], + [172.20944045, 11.70256469], + [252.43251963, 11.70943962], + [221.1698977, 11.70512806], + [276.41863884, 11.70949697], + [271.18691047, 11.70779719], + [342.4815721, 11.71377577], + [428.18568454, 11.72119952], + [442.38884573, 11.72144854], + [432.83407587, 11.71931382], + [437.26647591, 11.71858269], + [437.23617813, 11.71740388], + [445.37233368, 11.71704456], + [453.20394552, 11.71665472], + [454.43375698, 11.71560253], + [422.47933114, 11.71122094], + [455.98699774, 11.71340787], + [440.44927248, 11.71067365], + [425.25624136, 11.7079743], + [486.09219682, 11.7129035], + [500.42306569, 11.71316617], + [521.25493942, 11.71408109], + [509.00273089, 11.71167646], + [488.96187713, 11.7084906], + [509.84946635, 11.70941157], + [456.87166966, 11.70292125], + [473.80457583, 11.70344599], + [525.85807994, 11.70749448], + [549.8056598, 11.70872257], + [542.38446176, 11.70680319] + ], + "residuals": [77.98192976, 8.27827585, -1.24312401, 1.21718784, -3.2048853, 17.69781714, 36.95162756, 51.77652689, 68.17486995, 34.07608124, -82.00838087, 66.01363955, 19.56065873, -55.66226815, 51.68026178, 10.22629568, -15.20005141, -177.9386874, -112.0565578, -33.19500001, -58.74273081, 68.67808703, -43.07088184, 43.64374773, -16.98018406, 59.72389279, 74.16048783, 2.4876693, -21.32514606, -7.30367106, -11.77589867, -3.58948392, -3.89436781, -10.51095923, -43.77045373, 21.84656965, -27.31380094, -26.96557361, 49.24095785, 2.62398575, 9.1396773, -24.02140347, -31.82554962, 9.20020725, -64.83596558, 5.24201201, 40.44284874, 12.26823318, -19.17391255], + "fitted": [33.02720486, 122.55015822, 142.53021192, 153.01058688, 165.94575069, 174.46866637, 203.84809771, 252.44086322, 315.82969736, 395.58607535, 441.32531082, 371.23821484, 448.8401311, 480.09760469, 436.29916817, 499.60215212, 521.54730416, 518.12292482, 352.31547884, 252.22778758, 230.81739405, 183.91200514, 264.14195925, 232.87502576, 288.1281358, 282.89470766, 354.19534787, 439.90688405, 454.11029428, 444.55338969, 448.9850586, 448.95358201, 457.08937823, 464.92060024, 466.14935951, 434.19055208, 467.70040561, 452.15994613, 436.96421566, 497.80510033, 512.13623187, 532.96902051, 520.71440735, 500.67036773, 521.55887793, 468.57459091, 485.50802183, 537.56557442, 561.51438238], + "sigma2": [2571.94347286], + "loglik": [-285.64745013], + "forecast": [554.09126495, 565.79806815, 577.50487134, 589.21167453], + "simulation": [555.8553173, 567.95840692, 580.64324663, 594.58901206] + }, + "MAN": { + "alpha": [0.9998996], + "beta": [0.02781619], + "gamma": ["NaN"], + "phi": ["NaN"], + "initstate": [37.8545175, 32.60926576], + "states": [ + [37.8545175, 32.60926576], + [111.00506374, 33.73708288], + [130.82983105, 33.35005644], + [141.28938642, 32.71326602], + [154.22976018, 32.1632043], + [162.74324013, 31.50529307], + [192.16669256, 31.44737838], + [240.79799978, 31.92541777], + [304.21422802, 32.80146004], + [383.99984948, 34.10851154], + [429.66099656, 34.42989409], + [359.32744957, 31.51548189], + [437.2471948, 32.80640122], + [468.40095578, 32.76042645], + [424.44304007, 30.62620034], + [487.97612566, 31.54163636], + [509.82942064, 31.27211657], + [506.35074218, 30.30538486], + [340.2039638, 24.84028583], + [240.27144987, 21.36923367], + [219.03706554, 20.18404442], + [172.08140495, 18.31628623], + [252.58384786, 20.04624175], + [221.07625409, 18.61206657], + [276.51507559, 19.63654937], + [271.15046219, 18.9410425], + [342.61332657, 20.40214607], + [428.34927532, 22.2196659], + [442.39537408, 21.99228559], + [432.78832121, 21.11322419], + [437.25139052, 20.65003384], + [437.2112375, 20.07445392], + [445.36529506, 19.74284064], + [453.19620654, 19.41146291], + [454.41146815, 18.90526313], + [422.38402009, 17.48836699], + [456.03549874, 17.93800829], + [440.3899769, 17.0037487], + [425.19760543, 16.10808544], + [486.20066546, 17.35701789], + [500.42940019, 17.26999224], + [521.27555008, 17.3694773], + [508.95059876, 16.54340855], + [488.892533, 15.52519283], + [509.8700275, 15.67687031], + [456.72982249, 13.76244938], + [473.81626914, 13.8549196], + [525.94702717, 14.91971443], + [549.83290728, 15.16914402], + [542.34274512, 14.53878521] + ], + "residuals": [0.57540696, -0.09612758, -0.1394373, -0.11364699, -0.12689373, -0.01071848, 0.07685408, 0.11547953, 0.13942639, 0.0276335, -0.22576173, 0.1187406, -0.00351621, -0.15309648, 0.07231908, -0.01865059, -0.06422877, -0.36610388, -0.34183617, -0.16284889, -0.2806878, 0.32664472, -0.1891171, 0.15365977, -0.08442862, 0.18107078, 0.17999333, -0.01814237, -0.06805201, -0.03668599, -0.04518934, -0.02607034, -0.02561367, -0.03850557, -0.1076189, 0.03674869, -0.0708624, -0.07039745, 0.10174236, -0.00621299, 0.00690848, -0.05513355, -0.06965855, 0.01081019, -0.13095689, 0.00706564, 0.07849486, 0.01657907, -0.04010885], + "fitted": [70.46378327, 144.74214662, 164.17988748, 174.00265244, 186.39296449, 194.24853319, 223.61407094, 272.72341756, 337.01568805, 418.10836102, 464.09089064, 390.84293147, 470.05359602, 501.16138224, 455.06924041, 519.51776202, 541.10153721, 536.65612705, 365.04424963, 261.64068354, 239.22110996, 190.39769118, 272.63008961, 239.68832067, 296.15162497, 290.09150469, 363.01547264, 450.56894122, 464.38765967, 453.90154539, 457.90142436, 457.28569142, 465.1081357, 472.60766945, 473.31673128, 439.87238709, 473.97350703, 457.3937256, 441.30569087, 503.55768336, 517.69939244, 538.64502738, 525.49400731, 504.41772583, 525.5468978, 470.49227187, 487.67118874, 540.8667416, 565.0020513], + "sigma2": [0.02664264], + "loglik": [-293.30311473], + "forecast": [556.88153033, 571.42031554, 585.95910076, 600.49788597], + "simulation": [1539.24970258, 2213.6703814, 4497.80880936, 14969.46458166] + }, + "AMN": [], + "MMN": { + "alpha": [0.99989999], + "beta": [0.1233809], + "gamma": ["NaN"], + "phi": ["NaN"], + "initstate": [67.17844939, 1.22353509], + "states": [ + [67.17844939, 1.22353509], + [111.00625294, 1.27645519], + [130.82952078, 1.2643778], + [141.28950123, 1.24162081], + [154.22989495, 1.22310775], + [162.74345553, 1.20238912], + [192.166835, 1.19972469], + [240.79869993, 1.20630727], + [304.21601596, 1.21334748], + [384.00307868, 1.21938432], + [429.66601549, 1.20698683], + [359.33285993, 1.16124749], + [437.24985645, 1.16810698], + [468.40502563, 1.1561558], + [424.44704907, 1.12530726], + [487.97839524, 1.12831472], + [509.83252468, 1.11800772], + [506.35361831, 1.10260438], + [340.2060519, 1.04945521], + [240.27059939, 1.00710604], + [219.03508232, 0.9953235], + [172.0792573, 0.96944802], + [252.58151451, 1.03094385], + [221.07501042, 1.01173377], + [276.513488, 1.04122894], + [271.1496285, 1.03374797], + [342.61236802, 1.06210456], + [428.3493885, 1.08531981], + [442.39680372, 1.07883852], + [432.78959761, 1.06643074], + [437.25214791, 1.05950596], + [437.21176639, 1.05215193], + [445.36556315, 1.04801796], + [453.19636617, 1.04426247], + [454.41152583, 1.03913164], + [422.38388772, 1.02560611], + [456.03483774, 1.03227712], + [440.38964174, 1.02406109], + [425.19695192, 1.01683526], + [486.19978799, 1.03246108], + [500.42924142, 1.03206691], + [521.27542918, 1.03325021], + [508.95058337, 1.0262299], + [488.8921992, 1.01813022], + [509.86936339, 1.02118758], + [456.72930791, 1.00571277], + [473.81515496, 1.00962389], + [525.94611252, 1.02201256], + [549.83257645, 1.02490041], + [542.34258835, 1.02014697] + ], + "residuals": [0.35055512, -0.07668663, -0.14587809, -0.12084851, -0.13729296, -0.01796024, 0.04446996, 0.04730205, 0.04032521, -0.08240341, -0.30714215, 0.0478761, -0.08292401, -0.21625709, 0.02166115, -0.07403789, -0.11166634, -0.39068684, -0.32706429, -0.09482344, -0.21070566, 0.51413034, -0.15102412, 0.23628535, -0.05823233, 0.22232658, 0.17715697, -0.04840119, -0.09321584, -0.05262903, -0.05625666, -0.03184497, -0.02904353, -0.03982267, -0.10549594, 0.0527185, -0.06450865, -0.0571892, 0.12455018, -0.00309427, 0.00929268, -0.0550685, -0.0639698, 0.02433854, -0.12282073, 0.03151947, 0.09945286, 0.02290183, -0.03759055], + "fitted": [82.19518997, 141.69450778, 165.41794158, 175.42798446, 188.63977927, 195.68096055, 230.54729592, 290.47722207, 369.11973715, 468.24733444, 518.60122396, 417.27438345, 510.75460932, 541.54918638, 477.63334402, 550.5932065, 569.99669928, 558.3077158, 357.03101466, 241.977971, 218.01076443, 166.82189526, 260.39736003, 223.66905368, 287.91384725, 280.3003771, 363.89015689, 464.89607731, 477.27471161, 461.54012927, 463.27125513, 460.01320283, 466.75110851, 473.25595865, 472.19339384, 433.19949604, 470.75432865, 450.98589507, 432.35525113, 501.98235696, 516.47646103, 538.60794926, 522.30030546, 497.75592377, 520.67225984, 459.33849909, 478.37509996, 537.52353504, 563.52363429], + "sigma2": [0.02662895], + "loglik": [-293.74307293], + "forecast": [553.2691477, 564.41584411, 575.78711267, 587.38747782], + "simulation": [1529.26488789, 2659.60503193, 6859.74137563, 32477.11031692] + }, + "ANN": { + "alpha": [0.99989996], + "beta": ["NaN"], + "gamma": ["NaN"], + "phi": ["NaN"], + "initstate": [110.88321179], + "states": [110.88321179, 111.00912202, 130.82645142, 141.28604147, 154.22648008, 162.74001364, 192.1635398, 240.79485989, 304.21104556, 383.99658506, 429.65758838, 359.32396656, 437.24405878, 468.39767303, 424.43973437, 487.97307367, 509.82626147, 506.34760077, 340.20085978, 240.26891886, 219.03491196, 172.07936097, 252.58203817, 221.07422965, 276.51322702, 271.14848847, 342.61145085, 428.34725815, 442.39314811, 432.78610937, 437.24927211, 437.20916394, 445.3632823, 453.19422697, 454.40951943, 422.38211, 456.03375501, 440.38816996, 425.19589245, 486.19907037, 500.42766256, 521.27382359, 508.94885011, 488.89086446, 509.86847625, 456.72822883, 473.81489346, 525.94565508, 549.83141792, 542.34121919], + "residuals": [0.12592282, 19.81931205, 10.4606365, 12.94173326, 8.5143853, 29.42646988, 48.63618547, 63.42253022, 79.79352175, 45.66557153, -70.34065844, 77.92788783, 31.15673105, -43.96233649, 63.53969558, 21.85537413, -3.47900873, -166.16336336, -99.94193874, -21.23613128, -46.96024872, 80.5107312, -31.51096076, 55.44454384, -5.36527527, 71.47011198, 85.74438485, 14.0472952, -9.60799989, 4.46360926, -0.04011218, 8.15493415, 7.83172812, 1.21541404, -32.03061365, 33.65501173, -15.64715033, -15.19379744, 61.00928106, 14.2300157, 20.84824661, -12.32620654, -20.05999238, 20.97971052, -53.1455639, 17.08837408, 52.13597711, 23.88815252, -7.49094809], + "fitted": [110.88321179, 111.00912202, 130.82645142, 141.28604147, 154.22648008, 162.74001364, 192.1635398, 240.79485989, 304.21104556, 383.99658506, 429.65758838, 359.32396656, 437.24405878, 468.39767303, 424.43973437, 487.97307367, 509.82626147, 506.34760077, 340.20085978, 240.26891886, 219.03491196, 172.07936097, 252.58203817, 221.07422965, 276.51322702, 271.14848847, 342.61145085, 428.34725815, 442.39314811, 432.78610937, 437.24927211, 437.20916394, 445.3632823, 453.19422697, 454.40951943, 422.38211, 456.03375501, 440.38816996, 425.19589245, 486.19907037, 500.42766256, 521.27382359, 508.94885011, 488.89086446, 509.86847625, 456.72822883, 473.81489346, 525.94565508, 549.83141792], + "sigma2": [2405.9689539], + "loglik": [-285.07846207], + "forecast": [542.34121919, 542.34121919, 542.34121919, 542.34121919], + "simulation": [544.10527154, 544.50525228, 545.48395023, 547.72474552] + }, + "MNN": { + "alpha": [0.99989932], + "beta": ["NaN"], + "gamma": ["NaN"], + "phi": ["NaN"], + "initstate": [108.50797841], + "states": [108.50797841, 111.0088828, 130.82643863, 141.28603473, 154.22647175, 162.74000816, 192.16352086, 240.79482858, 304.21100472, 383.99653369, 429.65755898, 359.32401184, 437.24400862, 468.39765297, 424.43976267, 487.97303277, 509.8262474, 506.34760301, 340.20096675, 240.26898321, 219.03492564, 172.0793912, 252.58198634, 221.07424993, 276.51319133, 271.14849192, 342.61140484, 428.34720294, 442.39313906, 432.78611555, 437.24926923, 437.20916397, 445.36327705, 453.19422193, 454.40951864, 422.38213062, 456.03373334, 440.38818003, 425.19590223, 486.19903109, 500.42765339, 521.27381017, 508.94885805, 488.89087737, 509.86846274, 456.72826304, 473.81488246, 525.94562151, 549.83140253, 542.34122401], + "residuals": [0.02305044, 0.17854023, 0.07995822, 0.09159957, 0.05520708, 0.18081894, 0.25309801, 0.26338839, 0.26229677, 0.11892197, -0.16371324, 0.21687346, 0.07125719, -0.09385682, 0.14970244, 0.04478816, -0.00682388, -0.32816066, -0.29377355, -0.08838509, -0.21439623, 0.46786951, -0.12475517, 0.25079594, -0.0194032, 0.26358291, 0.2502673, 0.03279431, -0.02171822, 0.01031365, -0.00009173, 0.01865225, 0.01758505, 0.00268189, -0.07048843, 0.07967901, -0.03431134, -0.03450094, 0.14348509, 0.02926796, 0.04166088, -0.02364629, -0.03941457, 0.04291284, -0.10423385, 0.03741468, 0.11003451, 0.0454195, -0.01362405], + "fitted": [108.50797841, 111.0088828, 130.82643863, 141.28603473, 154.22647175, 162.74000816, 192.16352086, 240.79482858, 304.21100472, 383.99653369, 429.65755898, 359.32401184, 437.24400862, 468.39765297, 424.43976267, 487.97303277, 509.8262474, 506.34760301, 340.20096675, 240.26898321, 219.03492564, 172.0793912, 252.58198634, 221.07424993, 276.51319133, 271.14849192, 342.61140484, 428.34720294, 442.39313906, 432.78611555, 437.24926923, 437.20916397, 445.36327705, 453.19422193, 454.40951864, 422.38213062, 456.03373334, 440.38818003, 425.19590223, 486.19903109, 500.42765339, 521.27381017, 508.94885805, 488.89087737, 509.86846274, 456.72826304, 473.81488246, 525.94562151, 549.83140253], + "sigma2": [0.02465689], + "loglik": [-289.29728569], + "forecast": [542.34122401, 542.34122401, 542.34122401, 542.34122401], + "simulation": [1499.05953474, 2098.78414921, 4152.82441187, 13458.19015798] + } + } +} \ No newline at end of file diff --git a/shared/package-files/0b/0bc1b9aea78d01eb3434760585dc5cc3e64c838c838a9ab348d73834847bba87/__init__.py b/shared/package-files/0b/0bc1b9aea78d01eb3434760585dc5cc3e64c838c838a9ab348d73834847bba87/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ce4d601f1188a41df7812c320395800a64e1bee --- /dev/null +++ b/shared/package-files/0b/0bc1b9aea78d01eb3434760585dc5cc3e64c838c838a9ab348d73834847bba87/__init__.py @@ -0,0 +1,70 @@ +from importlib.metadata import entry_points + +from . import _version, caching +from .callbacks import Callback +from .compression import available_compressions +from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs +from .exceptions import FSTimeoutError +from .mapping import FSMap, get_mapper +from .registry import ( + available_protocols, + filesystem, + get_filesystem_class, + register_implementation, + registry, +) +from .spec import AbstractFileSystem + +__version__ = _version.get_versions()["version"] + +__all__ = [ + "AbstractFileSystem", + "FSTimeoutError", + "FSMap", + "filesystem", + "register_implementation", + "get_filesystem_class", + "get_fs_token_paths", + "get_mapper", + "open", + "open_files", + "open_local", + "registry", + "caching", + "Callback", + "available_protocols", + "available_compressions", + "url_to_fs", +] + + +def process_entries(): + if entry_points is not None: + try: + eps = entry_points() + except TypeError: + pass # importlib-metadata < 0.8 + else: + if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0 + specs = eps.select(group="fsspec.specs") + else: + specs = eps.get("fsspec.specs", []) + registered_names = {} + for spec in specs: + err_msg = f"Unable to load filesystem from {spec}" + name = spec.name + if name in registered_names: + continue + registered_names[name] = True + register_implementation( + name, + spec.value.replace(":", "."), + errtxt=err_msg, + # We take our implementations as the ones to overload with if + # for some reason we encounter some, may be the same, already + # registered + clobber=True, + ) + + +process_entries() diff --git a/shared/package-files/0b/0bc2876df83d9c6ca17db35ae7a4575cfd2fd6b94891352f630d73926bf76ce9/autoreload.pyi b/shared/package-files/0b/0bc2876df83d9c6ca17db35ae7a4575cfd2fd6b94891352f630d73926bf76ce9/autoreload.pyi new file mode 100644 index 0000000000000000000000000000000000000000..edb684167c3e4ddc2b9c55713dc0bd84585e8b77 --- /dev/null +++ b/shared/package-files/0b/0bc2876df83d9c6ca17db35ae7a4575cfd2fd6b94891352f630d73926bf76ce9/autoreload.pyi @@ -0,0 +1,67 @@ +import threading +import types +from pathlib import Path +from typing import Any, Callable, List, Optional, Set, Dict, Union, Iterator, Tuple, Iterable + +from django.apps.registry import Apps + +USE_INOTIFY: bool +fd: Any +RUN_RELOADER: bool +FILE_MODIFIED: int +I18N_MODIFIED: int + +def gen_filenames(only_new: bool = ...) -> List[str]: ... +def clean_files(filelist: List[Optional[str]]) -> List[str]: ... +def reset_translations() -> None: ... +def inotify_code_changed(): ... +def code_changed(): ... +def check_errors(fn: Callable) -> Callable: ... +def raise_last_exception() -> None: ... +def ensure_echo_on() -> None: ... +def reloader_thread() -> None: ... +def restart_with_reloader() -> int: ... +def python_reloader(main_func: Any, args: Any, kwargs: Any) -> None: ... +def main(main_func: Any, args: Optional[Any] = ..., kwargs: Optional[Any] = ...) -> None: ... +def iter_all_python_module_files() -> Set[Path]: ... +def iter_modules_and_files( + modules: Iterable[types.ModuleType], extra_files: Iterable[Union[str, Path]] +) -> Set[Path]: ... +def common_roots(paths: Iterable[Path]) -> Iterator[Path]: ... +def sys_path_directories() -> Iterator[Path]: ... + +class BaseReloader: + extra_files: Set[Path] + directory_globs: Dict[Path, Set[str]] + def __init__(self) -> None: ... + def watch_dir(self, path: Union[str, Path], glob: str) -> None: ... + def watch_file(self, path: Union[str, Path]) -> None: ... + def watched_files(self, include_globs: bool = ...) -> Iterator[Path]: ... + def wait_for_apps_ready(self, app_reg: Apps, django_main_thread: threading.Thread) -> bool: ... + def run(self, django_main_thread: threading.Thread) -> None: ... + def run_loop(self) -> None: ... + def tick(self) -> Iterator[None]: ... + @classmethod + def check_availability(cls) -> bool: ... + def notify_file_changed(self, path: Union[str, Path]) -> None: ... + @property + def should_stop(self) -> bool: ... + def stop(self) -> None: ... + +class StatReloader(BaseReloader): + SLEEP_TIME: int = ... + def snapshot_files(self) -> Iterator[Tuple[Path, int]]: ... + +class WatchmanUnavailable(RuntimeError): ... + +class WatchmanReloader(BaseReloader): + @property + def client(self) -> Any: ... + def watched_roots(self, watched_files: Iterable[Path]) -> Set[Path]: ... + def update_watches(self) -> None: ... + def request_processed(self, **kwargs: Any) -> None: ... + def check_server_status(self, inner_ex: Optional[BaseException] = ...) -> bool: ... + +def get_reloader() -> BaseReloader: ... +def start_django(reloader: BaseReloader, main_func: Callable, *args: Any, **kwargs: Any) -> None: ... +def run_with_reloader(main_func: Callable, *args: Any, **kwargs: Any) -> None: ... diff --git a/shared/package-files/0b/0bca6e522f4103d97ef192ee03c93f459879244ce4895e1bf10da46e1947bf1d/log_sigmoid_forward.h b/shared/package-files/0b/0bca6e522f4103d97ef192ee03c93f459879244ce4895e1bf10da46e1947bf1d/log_sigmoid_forward.h new file mode 100644 index 0000000000000000000000000000000000000000..e6d37ec8fbccd41e8cdf382ef41a60e7ef3821ed --- /dev/null +++ b/shared/package-files/0b/0bca6e522f4103d97ef192ee03c93f459879244ce4895e1bf10da46e1947bf1d/log_sigmoid_forward.h @@ -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::log_sigmoid_forward.output(Tensor self, *, Tensor(a!) output, Tensor(b!) buffer) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple log_sigmoid_forward_out(at::Tensor & output, at::Tensor & buffer, const at::Tensor & self) { + return at::_ops::log_sigmoid_forward_output::call(self, output, buffer); +} +// aten::log_sigmoid_forward.output(Tensor self, *, Tensor(a!) output, Tensor(b!) buffer) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple log_sigmoid_forward_outf(const at::Tensor & self, at::Tensor & output, at::Tensor & buffer) { + return at::_ops::log_sigmoid_forward_output::call(self, output, buffer); +} + +// aten::log_sigmoid_forward(Tensor self) -> (Tensor output, Tensor buffer) +inline ::std::tuple log_sigmoid_forward(const at::Tensor & self) { + return at::_ops::log_sigmoid_forward::call(self); +} + +} diff --git a/shared/package-files/0b/0bcfa5cb4fd3aa49a940d666c0f1f0a36215d8c047d234048c0869a87ae0f18e/test_abstract_interface.py b/shared/package-files/0b/0bcfa5cb4fd3aa49a940d666c0f1f0a36215d8c047d234048c0869a87ae0f18e/test_abstract_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..42902913ed755122011587f7834a8babd86ff27e --- /dev/null +++ b/shared/package-files/0b/0bcfa5cb4fd3aa49a940d666c0f1f0a36215d8c047d234048c0869a87ae0f18e/test_abstract_interface.py @@ -0,0 +1,25 @@ +from pathlib import Path +import pytest +import textwrap +from . import util +from numpy.f2py import crackfortran +from numpy.testing import IS_WASM + + +@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess") +class TestAbstractInterface(util.F2PyTest): + sources = [util.getpath("tests", "src", "abstract_interface", "foo.f90")] + + skip = ["add1", "add2"] + + def test_abstract_interface(self): + assert self.module.ops_module.foo(3, 5) == (8, 13) + + def test_parse_abstract_interface(self): + # Test gh18403 + fpath = util.getpath("tests", "src", "abstract_interface", + "gh18403_mod.f90") + mod = crackfortran.crackfortran([str(fpath)]) + assert len(mod) == 1 + assert len(mod[0]["body"]) == 1 + assert mod[0]["body"][0]["block"] == "abstract interface" diff --git a/shared/package-files/0b/0bd24f483bad5c14b840599da9cb029450ad74df6d7466ae3c3f13610e3f345d/truss.py b/shared/package-files/0b/0bd24f483bad5c14b840599da9cb029450ad74df6d7466ae3c3f13610e3f345d/truss.py new file mode 100644 index 0000000000000000000000000000000000000000..8384a673f03b13d1e50333b23e221d15d9ede4eb --- /dev/null +++ b/shared/package-files/0b/0bd24f483bad5c14b840599da9cb029450ad74df6d7466ae3c3f13610e3f345d/truss.py @@ -0,0 +1,735 @@ +""" +This module can be used to solve problems related +to 2D Trusses. +""" + +from cmath import inf +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy import Matrix, pi +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.matrices.dense import zeros +from sympy import sin, cos + + + +class Truss: + """ + A Truss is an assembly of members such as beams, + connected by nodes, that create a rigid structure. + In engineering, a truss is a structure that + consists of two-force members only. + + Trusses are extremely important in engineering applications + and can be seen in numerous real-world applications like bridges. + + Examples + ======== + + There is a Truss consisting of four nodes and five + members connecting the nodes. A force P acts + downward on the node D and there also exist pinned + and roller joints on the nodes A and B respectively. + + .. image:: truss_example.png + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node("node_1", 0, 0) + >>> t.add_node("node_2", 6, 0) + >>> t.add_node("node_3", 2, 2) + >>> t.add_node("node_4", 2, 0) + >>> t.add_member("member_1", "node_1", "node_4") + >>> t.add_member("member_2", "node_2", "node_4") + >>> t.add_member("member_3", "node_1", "node_3") + >>> t.add_member("member_4", "node_2", "node_3") + >>> t.add_member("member_5", "node_3", "node_4") + >>> t.apply_load("node_4", magnitude=10, direction=270) + >>> t.apply_support("node_1", type="fixed") + >>> t.apply_support("node_2", type="roller") + """ + + def __init__(self): + """ + Initializes the class + """ + self._nodes = [] + self._members = {} + self._loads = {} + self._supports = {} + self._node_labels = [] + self._node_positions = [] + self._node_position_x = [] + self._node_position_y = [] + self._nodes_occupied = {} + self._reaction_loads = {} + self._internal_forces = {} + self._node_coordinates = {} + + @property + def nodes(self): + """ + Returns the nodes of the truss along with their positions. + """ + return self._nodes + + @property + def node_labels(self): + """ + Returns the node labels of the truss. + """ + return self._node_labels + + @property + def node_positions(self): + """ + Returns the positions of the nodes of the truss. + """ + return self._node_positions + + @property + def members(self): + """ + Returns the members of the truss along with the start and end points. + """ + return self._members + + @property + def member_labels(self): + """ + Returns the members of the truss along with the start and end points. + """ + return self._member_labels + + @property + def supports(self): + """ + Returns the nodes with provided supports along with the kind of support provided i.e. + pinned or roller. + """ + return self._supports + + @property + def loads(self): + """ + Returns the loads acting on the truss. + """ + return self._loads + + @property + def reaction_loads(self): + """ + Returns the reaction forces for all supports which are all initialized to 0. + """ + return self._reaction_loads + + @property + def internal_forces(self): + """ + Returns the internal forces for all members which are all initialized to 0. + """ + return self._internal_forces + + def add_node(self, label, x, y): + """ + This method adds a node to the truss along with its name/label and its location. + + Parameters + ========== + label: String or a Symbol + The label for a node. It is the only way to identify a particular node. + + x: Sympifyable + The x-coordinate of the position of the node. + + y: Sympifyable + The y-coordinate of the position of the node. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.nodes + [('A', 0, 0)] + >>> t.add_node('B', 3, 0) + >>> t.nodes + [('A', 0, 0), ('B', 3, 0)] + """ + x = sympify(x) + y = sympify(y) + + if label in self._node_labels: + raise ValueError("Node needs to have a unique label") + + elif x in self._node_position_x and y in self._node_position_y and self._node_position_x.index(x)==self._node_position_y.index(y): + raise ValueError("A node already exists at the given position") + + else : + self._nodes.append((label, x, y)) + self._node_labels.append(label) + self._node_positions.append((x, y)) + self._node_position_x.append(x) + self._node_position_y.append(y) + self._node_coordinates[label] = [x, y] + + def remove_node(self, label): + """ + This method removes a node from the truss. + + Parameters + ========== + label: String or Symbol + The label of the node to be removed. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.nodes + [('A', 0, 0)] + >>> t.add_node('B', 3, 0) + >>> t.nodes + [('A', 0, 0), ('B', 3, 0)] + >>> t.remove_node('A') + >>> t.nodes + [('B', 3, 0)] + """ + for i in range(len(self.nodes)): + if self._node_labels[i] == label: + x = self._node_position_x[i] + y = self._node_position_y[i] + + if label not in self._node_labels: + raise ValueError("No such node exists in the truss") + + else: + members_duplicate = self._members.copy() + for member in members_duplicate: + if label == self._members[member][0] or label == self._members[member][1]: + raise ValueError("The node given has members already attached to it") + self._nodes.remove((label, x, y)) + self._node_labels.remove(label) + self._node_positions.remove((x, y)) + self._node_position_x.remove(x) + self._node_position_y.remove(y) + if label in list(self._loads): + self._loads.pop(label) + if label in list(self._supports): + self._supports.pop(label) + self._node_coordinates.pop(label) + + def add_member(self, label, start, end): + """ + This method adds a member between any two nodes in the given truss. + + Parameters + ========== + label: String or Symbol + The label for a member. It is the only way to identify a particular member. + + start: String or Symbol + The label of the starting point/node of the member. + + end: String or Symbol + The label of the ending point/node of the member. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> t.add_node('C', 2, 2) + >>> t.add_member('AB', 'A', 'B') + >>> t.members + {'AB': ['A', 'B']} + """ + + if start not in self._node_labels or end not in self._node_labels or start==end: + raise ValueError("The start and end points of the member must be unique nodes") + + elif label in list(self._members): + raise ValueError("A member with the same label already exists for the truss") + + elif self._nodes_occupied.get((start, end)): + raise ValueError("A member already exists between the two nodes") + + else: + self._members[label] = [start, end] + self._nodes_occupied[start, end] = True + self._nodes_occupied[end, start] = True + self._internal_forces[label] = 0 + + def remove_member(self, label): + """ + This method removes a member from the given truss. + + Parameters + ========== + label: String or Symbol + The label for the member to be removed. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> t.add_node('C', 2, 2) + >>> t.add_member('AB', 'A', 'B') + >>> t.add_member('AC', 'A', 'C') + >>> t.add_member('BC', 'B', 'C') + >>> t.members + {'AB': ['A', 'B'], 'AC': ['A', 'C'], 'BC': ['B', 'C']} + >>> t.remove_member('AC') + >>> t.members + {'AB': ['A', 'B'], 'BC': ['B', 'C']} + """ + if label not in list(self._members): + raise ValueError("No such member exists in the Truss") + + else: + self._nodes_occupied.pop((self._members[label][0], self._members[label][1])) + self._nodes_occupied.pop((self._members[label][1], self._members[label][0])) + self._members.pop(label) + self._internal_forces.pop(label) + + def change_node_label(self, label, new_label): + """ + This method changes the label of a node. + + Parameters + ========== + label: String or Symbol + The label of the node for which the label has + to be changed. + + new_label: String or Symbol + The new label of the node. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> t.nodes + [('A', 0, 0), ('B', 3, 0)] + >>> t.change_node_label('A', 'C') + >>> t.nodes + [('C', 0, 0), ('B', 3, 0)] + """ + if label not in self._node_labels: + raise ValueError("No such node exists for the Truss") + elif new_label in self._node_labels: + raise ValueError("A node with the given label already exists") + else: + for node in self._nodes: + if node[0] == label: + self._nodes[self._nodes.index((label, node[1], node[2]))] = (new_label, node[1], node[2]) + self._node_labels[self._node_labels.index(node[0])] = new_label + self._node_coordinates[new_label] = self._node_coordinates[label] + self._node_coordinates.pop(label) + if node[0] in list(self._supports): + self._supports[new_label] = self._supports[node[0]] + self._supports.pop(node[0]) + if new_label in list(self._supports): + if self._supports[new_label] == 'pinned': + if 'R_'+str(label)+'_x' in list(self._reaction_loads) and 'R_'+str(label)+'_y' in list(self._reaction_loads): + self._reaction_loads['R_'+str(new_label)+'_x'] = self._reaction_loads['R_'+str(label)+'_x'] + self._reaction_loads['R_'+str(new_label)+'_y'] = self._reaction_loads['R_'+str(label)+'_y'] + self._reaction_loads.pop('R_'+str(label)+'_x') + self._reaction_loads.pop('R_'+str(label)+'_y') + self._loads[new_label] = self._loads[label] + for load in self._loads[new_label]: + if load[1] == 90: + load[0] -= Symbol('R_'+str(label)+'_y') + if load[0] == 0: + self._loads[label].remove(load) + break + for load in self._loads[new_label]: + if load[1] == 0: + load[0] -= Symbol('R_'+str(label)+'_x') + if load[0] == 0: + self._loads[label].remove(load) + break + self.apply_load(new_label, Symbol('R_'+str(new_label)+'_x'), 0) + self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90) + self._loads.pop(label) + elif self._supports[new_label] == 'roller': + self._loads[new_label] = self._loads[label] + for load in self._loads[label]: + if load[1] == 90: + load[0] -= Symbol('R_'+str(label)+'_y') + if load[0] == 0: + self._loads[label].remove(load) + break + self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90) + self._loads.pop(label) + else: + if label in list(self._loads): + self._loads[new_label] = self._loads[label] + self._loads.pop(label) + for member in list(self._members): + if self._members[member][0] == node[0]: + self._members[member][0] = new_label + self._nodes_occupied[(new_label, self._members[member][1])] = True + self._nodes_occupied[(self._members[member][1], new_label)] = True + self._nodes_occupied.pop((label, self._members[member][1])) + self._nodes_occupied.pop((self._members[member][1], label)) + elif self._members[member][1] == node[0]: + self._members[member][1] = new_label + self._nodes_occupied[(self._members[member][0], new_label)] = True + self._nodes_occupied[(new_label, self._members[member][0])] = True + self._nodes_occupied.pop((self._members[member][0], label)) + self._nodes_occupied.pop((label, self._members[member][0])) + + def change_member_label(self, label, new_label): + """ + This method changes the label of a member. + + Parameters + ========== + label: String or Symbol + The label of the member for which the label has + to be changed. + + new_label: String or Symbol + The new label of the member. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> t.nodes + [('A', 0, 0), ('B', 3, 0)] + >>> t.change_node_label('A', 'C') + >>> t.nodes + [('C', 0, 0), ('B', 3, 0)] + >>> t.add_member('BC', 'B', 'C') + >>> t.members + {'BC': ['B', 'C']} + >>> t.change_member_label('BC', 'BC_new') + >>> t.members + {'BC_new': ['B', 'C']} + """ + if label not in list(self._members): + raise ValueError("No such member exists for the Truss") + + else: + members_duplicate = list(self._members).copy() + for member in members_duplicate: + if member == label: + self._members[new_label] = [self._members[member][0], self._members[member][1]] + self._members.pop(label) + self._internal_forces[new_label] = self._internal_forces[label] + self._internal_forces.pop(label) + + def apply_load(self, location, magnitude, direction): + """ + This method applies an external load at a particular node + + Parameters + ========== + location: String or Symbol + Label of the Node at which load is applied. + + magnitude: Sympifyable + Magnitude of the load applied. It must always be positive and any changes in + the direction of the load are not reflected here. + + direction: Sympifyable + The angle, in degrees, that the load vector makes with the horizontal + in the counter-clockwise direction. It takes the values 0 to 360, + inclusive. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> from sympy import symbols + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> P = symbols('P') + >>> t.apply_load('A', P, 90) + >>> t.apply_load('A', P/2, 45) + >>> t.apply_load('A', P/4, 90) + >>> t.loads + {'A': [[P, 90], [P/2, 45], [P/4, 90]]} + """ + magnitude = sympify(magnitude) + direction = sympify(direction) + + if location not in self.node_labels: + raise ValueError("Load must be applied at a known node") + + else: + if location in list(self._loads): + self._loads[location].append([magnitude, direction]) + else: + self._loads[location] = [[magnitude, direction]] + + def remove_load(self, location, magnitude, direction): + """ + This method removes an already + present external load at a particular node + + Parameters + ========== + location: String or Symbol + Label of the Node at which load is applied and is to be removed. + + magnitude: Sympifyable + Magnitude of the load applied. + + direction: Sympifyable + The angle, in degrees, that the load vector makes with the horizontal + in the counter-clockwise direction. It takes the values 0 to 360, + inclusive. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> from sympy import symbols + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> P = symbols('P') + >>> t.apply_load('A', P, 90) + >>> t.apply_load('A', P/2, 45) + >>> t.apply_load('A', P/4, 90) + >>> t.loads + {'A': [[P, 90], [P/2, 45], [P/4, 90]]} + >>> t.remove_load('A', P/4, 90) + >>> t.loads + {'A': [[P, 90], [P/2, 45]]} + """ + magnitude = sympify(magnitude) + direction = sympify(direction) + + if location not in self.node_labels: + raise ValueError("Load must be removed from a known node") + + else: + if [magnitude, direction] not in self._loads[location]: + raise ValueError("No load of this magnitude and direction has been applied at this node") + else: + self._loads[location].remove([magnitude, direction]) + if self._loads[location] == []: + self._loads.pop(location) + + def apply_support(self, location, type): + """ + This method adds a pinned or roller support at a particular node + + Parameters + ========== + + location: String or Symbol + Label of the Node at which support is added. + + type: String + Type of the support being provided at the node. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> t.apply_support('A', 'pinned') + >>> t.supports + {'A': 'pinned'} + """ + if location not in self._node_labels: + raise ValueError("Support must be added on a known node") + + else: + if location not in list(self._supports): + if type == 'pinned': + self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0) + self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90) + elif type == 'roller': + self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90) + elif self._supports[location] == 'pinned': + if type == 'roller': + self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0) + elif self._supports[location] == 'roller': + if type == 'pinned': + self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0) + self._supports[location] = type + + def remove_support(self, location): + """ + This method removes support from a particular node + + Parameters + ========== + + location: String or Symbol + Label of the Node at which support is to be removed. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node('A', 0, 0) + >>> t.add_node('B', 3, 0) + >>> t.apply_support('A', 'pinned') + >>> t.supports + {'A': 'pinned'} + >>> t.remove_support('A') + >>> t.supports + {} + """ + if location not in self._node_labels: + raise ValueError("No such node exists in the Truss") + + elif location not in list(self._supports): + raise ValueError("No support has been added to the given node") + + else: + if self._supports[location] == 'pinned': + self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0) + self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90) + elif self._supports[location] == 'roller': + self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90) + self._supports.pop(location) + + def solve(self): + """ + This method solves for all reaction forces of all supports and all internal forces + of all the members in the truss, provided the Truss is solvable. + + A Truss is solvable if the following condition is met, + + 2n >= r + m + + Where n is the number of nodes, r is the number of reaction forces, where each pinned + support has 2 reaction forces and each roller has 1, and m is the number of members. + + The given condition is derived from the fact that a system of equations is solvable + only when the number of variables is lesser than or equal to the number of equations. + Equilibrium Equations in x and y directions give two equations per node giving 2n number + equations. However, the truss needs to be stable as well and may be unstable if 2n > r + m. + The number of variables is simply the sum of the number of reaction forces and member + forces. + + .. note:: + The sign convention for the internal forces present in a member revolves around whether each + force is compressive or tensile. While forming equations for each node, internal force due + to a member on the node is assumed to be away from the node i.e. each force is assumed to + be compressive by default. Hence, a positive value for an internal force implies the + presence of compressive force in the member and a negative value implies a tensile force. + + Examples + ======== + + >>> from sympy.physics.continuum_mechanics.truss import Truss + >>> t = Truss() + >>> t.add_node("node_1", 0, 0) + >>> t.add_node("node_2", 6, 0) + >>> t.add_node("node_3", 2, 2) + >>> t.add_node("node_4", 2, 0) + >>> t.add_member("member_1", "node_1", "node_4") + >>> t.add_member("member_2", "node_2", "node_4") + >>> t.add_member("member_3", "node_1", "node_3") + >>> t.add_member("member_4", "node_2", "node_3") + >>> t.add_member("member_5", "node_3", "node_4") + >>> t.apply_load("node_4", magnitude=10, direction=270) + >>> t.apply_support("node_1", type="pinned") + >>> t.apply_support("node_2", type="roller") + >>> t.solve() + >>> t.reaction_loads + {'R_node_1_x': 0, 'R_node_1_y': 20/3, 'R_node_2_y': 10/3} + >>> t.internal_forces + {'member_1': 20/3, 'member_2': 20/3, 'member_3': -20*sqrt(2)/3, 'member_4': -10*sqrt(5)/3, 'member_5': 10} + """ + count_reaction_loads = 0 + for node in self._nodes: + if node[0] in list(self._supports): + if self._supports[node[0]]=='pinned': + count_reaction_loads += 2 + elif self._supports[node[0]]=='roller': + count_reaction_loads += 1 + if 2*len(self._nodes) != len(self._members) + count_reaction_loads: + raise ValueError("The given truss cannot be solved") + coefficients_matrix = [[0 for i in range(2*len(self._nodes))] for j in range(2*len(self._nodes))] + load_matrix = zeros(2*len(self.nodes), 1) + load_matrix_row = 0 + for node in self._nodes: + if node[0] in list(self._loads): + for load in self._loads[node[0]]: + if load[0]!=Symbol('R_'+str(node[0])+'_x') and load[0]!=Symbol('R_'+str(node[0])+'_y'): + load_matrix[load_matrix_row] -= load[0]*cos(pi*load[1]/180) + load_matrix[load_matrix_row + 1] -= load[0]*sin(pi*load[1]/180) + load_matrix_row += 2 + cols = 0 + row = 0 + for node in self._nodes: + if node[0] in list(self._supports): + if self._supports[node[0]]=='pinned': + coefficients_matrix[row][cols] += 1 + coefficients_matrix[row+1][cols+1] += 1 + cols += 2 + elif self._supports[node[0]]=='roller': + coefficients_matrix[row+1][cols] += 1 + cols += 1 + row += 2 + for member in list(self._members): + start = self._members[member][0] + end = self._members[member][1] + length = sqrt((self._node_coordinates[start][0]-self._node_coordinates[end][0])**2 + (self._node_coordinates[start][1]-self._node_coordinates[end][1])**2) + start_index = self._node_labels.index(start) + end_index = self._node_labels.index(end) + horizontal_component_start = (self._node_coordinates[end][0]-self._node_coordinates[start][0])/length + vertical_component_start = (self._node_coordinates[end][1]-self._node_coordinates[start][1])/length + horizontal_component_end = (self._node_coordinates[start][0]-self._node_coordinates[end][0])/length + vertical_component_end = (self._node_coordinates[start][1]-self._node_coordinates[end][1])/length + coefficients_matrix[start_index*2][cols] += horizontal_component_start + coefficients_matrix[start_index*2+1][cols] += vertical_component_start + coefficients_matrix[end_index*2][cols] += horizontal_component_end + coefficients_matrix[end_index*2+1][cols] += vertical_component_end + cols += 1 + forces_matrix = (Matrix(coefficients_matrix)**-1)*load_matrix + self._reaction_loads = {} + i = 0 + min_load = inf + for node in self._nodes: + if node[0] in list(self._loads): + for load in self._loads[node[0]]: + if type(load[0]) not in [Symbol, Mul, Add]: + min_load = min(min_load, load[0]) + for j in range(len(forces_matrix)): + if type(forces_matrix[j]) not in [Symbol, Mul, Add]: + if abs(forces_matrix[j]/min_load) <1E-10: + forces_matrix[j] = 0 + for node in self._nodes: + if node[0] in list(self._supports): + if self._supports[node[0]]=='pinned': + self._reaction_loads['R_'+str(node[0])+'_x'] = forces_matrix[i] + self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i+1] + i += 2 + elif self._supports[node[0]]=='roller': + self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i] + i += 1 + for member in list(self._members): + self._internal_forces[member] = forces_matrix[i] + i += 1 + return diff --git a/shared/package-files/0b/0bd2e0399c39668018cdb5cdfb2f415dd4b7d626848b0c28f90a729e42d2fd03/server.pyi b/shared/package-files/0b/0bd2e0399c39668018cdb5cdfb2f415dd4b7d626848b0c28f90a729e42d2fd03/server.pyi new file mode 100644 index 0000000000000000000000000000000000000000..995a089add96fb2ca79ea6fa74b33bf0ac15bbc5 --- /dev/null +++ b/shared/package-files/0b/0bd2e0399c39668018cdb5cdfb2f415dd4b7d626848b0c28f90a729e42d2fd03/server.pyi @@ -0,0 +1,72 @@ +import email.message +import socketserver +import sys +from typing import Any, Callable, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union + +if sys.version_info >= (3, 7): + from builtins import _PathLike + +class HTTPServer(socketserver.TCPServer): + server_name: str + server_port: int + def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... + +if sys.version_info >= (3, 7): + class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): + daemon_threads: bool # undocumented + +class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): + client_address: Tuple[str, int] + server: socketserver.BaseServer + close_connection: bool + requestline: str + command: str + path: str + request_version: str + headers: email.message.Message + server_version: str + sys_version: str + error_message_format: str + error_content_type: str + protocol_version: str + MessageClass: type + responses: Mapping[int, Tuple[str, str]] + weekdayname: ClassVar[Sequence[str]] = ... # Undocumented + monthname: ClassVar[Sequence[Optional[str]]] = ... # Undocumented + def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer) -> None: ... + def handle(self) -> None: ... + def handle_one_request(self) -> None: ... + def handle_expect_100(self) -> bool: ... + def send_error(self, code: int, message: Optional[str] = ..., explain: Optional[str] = ...) -> None: ... + def send_response(self, code: int, message: Optional[str] = ...) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def send_response_only(self, code: int, message: Optional[str] = ...) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., size: Union[int, str] = ...) -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... + def parse_request(self) -> bool: ... # Undocumented + +class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): + extensions_map: Dict[str, str] + if sys.version_info >= (3, 7): + def __init__( + self, + request: bytes, + client_address: Tuple[str, int], + server: socketserver.BaseServer, + directory: Optional[Union[str, _PathLike[str]]] = ..., + ) -> None: ... + else: + def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer) -> None: ... + def do_GET(self) -> None: ... + def do_HEAD(self) -> None: ... + +class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): + cgi_directories: List[str] + def do_POST(self) -> None: ... diff --git a/shared/package-files/0b/0bd678f5d21ff3feed7631243867ef41093d4cee8639096f3daa2426dfc21421/fmax_native.h b/shared/package-files/0b/0bd678f5d21ff3feed7631243867ef41093d4cee8639096f3daa2426dfc21421/fmax_native.h new file mode 100644 index 0000000000000000000000000000000000000000..8c931bc50701c49b699a8ff3fabd974e8d5e14a8 --- /dev/null +++ b/shared/package-files/0b/0bd678f5d21ff3feed7631243867ef41093d4cee8639096f3daa2426dfc21421/fmax_native.h @@ -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_fmax_out : public at::meta::structured_fmax { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0bd850160eb02e0f15f3cc612717cd475fb4079acbbefb9590f1b5b7070156fb/one_hot.h b/shared/package-files/0b/0bd850160eb02e0f15f3cc612717cd475fb4079acbbefb9590f1b5b7070156fb/one_hot.h new file mode 100644 index 0000000000000000000000000000000000000000..6617cfa53c19f659054645b55cd13feaed9dd610 --- /dev/null +++ b/shared/package-files/0b/0bd850160eb02e0f15f3cc612717cd475fb4079acbbefb9590f1b5b7070156fb/one_hot.h @@ -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::one_hot(Tensor self, int num_classes=-1) -> Tensor +inline at::Tensor one_hot(const at::Tensor & self, int64_t num_classes=-1) { + return at::_ops::one_hot::call(self, num_classes); +} + +} diff --git a/shared/package-files/0b/0bd8faaee920408d67fc97902e8646b8375f530cc25d287221d3d3a7a79d6cc4/wheel_legacy.py b/shared/package-files/0b/0bd8faaee920408d67fc97902e8646b8375f530cc25d287221d3d3a7a79d6cc4/wheel_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f0492ccbe9c727c835c12c84a1d8340366fa1e --- /dev/null +++ b/shared/package-files/0b/0bd8faaee920408d67fc97902e8646b8375f530cc25d287221d3d3a7a79d6cc4/wheel_legacy.py @@ -0,0 +1,102 @@ +import logging +import os.path +from typing import List, Optional + +from pip._internal.cli.spinners import open_spinner +from pip._internal.utils.setuptools_build import make_setuptools_bdist_wheel_args +from pip._internal.utils.subprocess import call_subprocess, format_command_args + +logger = logging.getLogger(__name__) + + +def format_command_result( + command_args: List[str], + command_output: str, +) -> str: + """Format command information for logging.""" + command_desc = format_command_args(command_args) + text = f"Command arguments: {command_desc}\n" + + if not command_output: + text += "Command output: None" + elif logger.getEffectiveLevel() > logging.DEBUG: + text += "Command output: [use --verbose to show]" + else: + if not command_output.endswith("\n"): + command_output += "\n" + text += f"Command output:\n{command_output}" + + return text + + +def get_legacy_build_wheel_path( + names: List[str], + temp_dir: str, + name: str, + command_args: List[str], + command_output: str, +) -> Optional[str]: + """Return the path to the wheel in the temporary build directory.""" + # Sort for determinism. + names = sorted(names) + if not names: + msg = ("Legacy build of wheel for {!r} created no files.\n").format(name) + msg += format_command_result(command_args, command_output) + logger.warning(msg) + return None + + if len(names) > 1: + msg = ( + "Legacy build of wheel for {!r} created more than one file.\n" + "Filenames (choosing first): {}\n" + ).format(name, names) + msg += format_command_result(command_args, command_output) + logger.warning(msg) + + return os.path.join(temp_dir, names[0]) + + +def build_wheel_legacy( + name: str, + setup_py_path: str, + source_dir: str, + global_options: List[str], + build_options: List[str], + tempd: str, +) -> Optional[str]: + """Build one unpacked package using the "legacy" build process. + + Returns path to wheel if successfully built. Otherwise, returns None. + """ + wheel_args = make_setuptools_bdist_wheel_args( + setup_py_path, + global_options=global_options, + build_options=build_options, + destination_dir=tempd, + ) + + spin_message = f"Building wheel for {name} (setup.py)" + with open_spinner(spin_message) as spinner: + logger.debug("Destination directory: %s", tempd) + + try: + output = call_subprocess( + wheel_args, + command_desc="python setup.py bdist_wheel", + cwd=source_dir, + spinner=spinner, + ) + except Exception: + spinner.finish("error") + logger.error("Failed building wheel for %s", name) + return None + + names = os.listdir(tempd) + wheel_path = get_legacy_build_wheel_path( + names=names, + temp_dir=tempd, + name=name, + command_args=wheel_args, + command_output=output, + ) + return wheel_path diff --git a/shared/package-files/0b/0bda397b55d26a9e521dfc03e49cae13a5171ea81f6fc23349694c336604ab40/resize_as.h b/shared/package-files/0b/0bda397b55d26a9e521dfc03e49cae13a5171ea81f6fc23349694c336604ab40/resize_as.h new file mode 100644 index 0000000000000000000000000000000000000000..bdbb9557d6bee17a38b30784d4f31d31d5701383 --- /dev/null +++ b/shared/package-files/0b/0bda397b55d26a9e521dfc03e49cae13a5171ea81f6fc23349694c336604ab40/resize_as.h @@ -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::resize_as_(Tensor(a!) self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor(a!) +inline const at::Tensor & resize_as_(const at::Tensor & self, const at::Tensor & the_template, c10::optional memory_format=c10::nullopt) { + return at::_ops::resize_as_::call(self, the_template, memory_format); +} + +// aten::resize_as.out(Tensor self, Tensor the_template, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline const at::Tensor & resize_as_out(const at::Tensor & out, const at::Tensor & self, const at::Tensor & the_template, c10::optional memory_format=c10::nullopt) { + return at::_ops::resize_as_out::call(self, the_template, memory_format, out); +} +// aten::resize_as.out(Tensor self, Tensor the_template, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline const at::Tensor & resize_as_outf(const at::Tensor & self, const at::Tensor & the_template, c10::optional memory_format, const at::Tensor & out) { + return at::_ops::resize_as_out::call(self, the_template, memory_format, out); +} + +// aten::resize_as(Tensor self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor resize_as(const at::Tensor & self, const at::Tensor & the_template, c10::optional memory_format=c10::nullopt) { + return at::_ops::resize_as::call(self, the_template, memory_format); +} + +} diff --git a/shared/package-files/0b/0bdc91f78eb90d9a8c228c070a5416535dfaa8fd1564b0f4fc7d47c1e7979918/_g_a_s_p.py b/shared/package-files/0b/0bdc91f78eb90d9a8c228c070a5416535dfaa8fd1564b0f4fc7d47c1e7979918/_g_a_s_p.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d6d837dd94927180e1be757f788b0cd1de8ac6 --- /dev/null +++ b/shared/package-files/0b/0bdc91f78eb90d9a8c228c070a5416535dfaa8fd1564b0f4fc7d47c1e7979918/_g_a_s_p.py @@ -0,0 +1,62 @@ +from fontTools.misc.textTools import safeEval +from . import DefaultTable +import struct + +GASP_SYMMETRIC_GRIDFIT = 0x0004 +GASP_SYMMETRIC_SMOOTHING = 0x0008 +GASP_DOGRAY = 0x0002 +GASP_GRIDFIT = 0x0001 + + +class table__g_a_s_p(DefaultTable.DefaultTable): + """Grid-fitting and Scan-conversion Procedure table + + The ``gasp`` table defines the preferred rasterization settings for + the font when rendered on monochrome and greyscale output devices. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/gasp + """ + + def decompile(self, data, ttFont): + self.version, numRanges = struct.unpack(">HH", data[:4]) + assert 0 <= self.version <= 1, "unknown 'gasp' format: %s" % self.version + data = data[4:] + self.gaspRange = {} + for i in range(numRanges): + rangeMaxPPEM, rangeGaspBehavior = struct.unpack(">HH", data[:4]) + self.gaspRange[int(rangeMaxPPEM)] = int(rangeGaspBehavior) + data = data[4:] + assert not data, "too much data" + + def compile(self, ttFont): + version = 0 # ignore self.version + numRanges = len(self.gaspRange) + data = b"" + items = sorted(self.gaspRange.items()) + for rangeMaxPPEM, rangeGaspBehavior in items: + data = data + struct.pack(">HH", rangeMaxPPEM, rangeGaspBehavior) + if rangeGaspBehavior & ~(GASP_GRIDFIT | GASP_DOGRAY): + version = 1 + data = struct.pack(">HH", version, numRanges) + data + return data + + def toXML(self, writer, ttFont): + items = sorted(self.gaspRange.items()) + for rangeMaxPPEM, rangeGaspBehavior in items: + writer.simpletag( + "gaspRange", + [ + ("rangeMaxPPEM", rangeMaxPPEM), + ("rangeGaspBehavior", rangeGaspBehavior), + ], + ) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name != "gaspRange": + return + if not hasattr(self, "gaspRange"): + self.gaspRange = {} + self.gaspRange[safeEval(attrs["rangeMaxPPEM"])] = safeEval( + attrs["rangeGaspBehavior"] + ) diff --git a/shared/package-files/0b/0be07b3429325ac4392b34049c8e417b5e83b001c764953d3f9bfdfbec2c17ea/test_backend_tools.py b/shared/package-files/0b/0be07b3429325ac4392b34049c8e417b5e83b001c764953d3f9bfdfbec2c17ea/test_backend_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..cc05a1a98f78f6b7267cf3d861013b3cf4416624 --- /dev/null +++ b/shared/package-files/0b/0be07b3429325ac4392b34049c8e417b5e83b001c764953d3f9bfdfbec2c17ea/test_backend_tools.py @@ -0,0 +1,20 @@ +import pytest + +from matplotlib.backend_tools import ToolHelpBase + + +@pytest.mark.parametrize('rc_shortcut,expected', [ + ('home', 'Home'), + ('backspace', 'Backspace'), + ('f1', 'F1'), + ('ctrl+a', 'Ctrl+A'), + ('ctrl+A', 'Ctrl+Shift+A'), + ('a', 'a'), + ('A', 'A'), + ('ctrl+shift+f1', 'Ctrl+Shift+F1'), + ('1', '1'), + ('cmd+p', 'Cmd+P'), + ('cmd+1', 'Cmd+1'), +]) +def test_format_shortcut(rc_shortcut, expected): + assert ToolHelpBase.format_shortcut(rc_shortcut) == expected diff --git a/shared/package-files/0b/0be65b223d754afc5f9a66befe2b9f72a5926772a88458d1f197a35621b55d57/absolute b/shared/package-files/0b/0be65b223d754afc5f9a66befe2b9f72a5926772a88458d1f197a35621b55d57/absolute new file mode 100644 index 0000000000000000000000000000000000000000..e8732ce2c67a59bfec3558f2bd3d71acc6530a36 Binary files /dev/null and b/shared/package-files/0b/0be65b223d754afc5f9a66befe2b9f72a5926772a88458d1f197a35621b55d57/absolute differ diff --git a/shared/package-files/0b/0be8e146d11424f48931e88e174bcff0ef8cc7c6e19cd89a3746441482c7c130/_softmax_cuda_dispatch.h b/shared/package-files/0b/0be8e146d11424f48931e88e174bcff0ef8cc7c6e19cd89a3746441482c7c130/_softmax_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..156e618d581416743636150a9d44c665f20ccaea --- /dev/null +++ b/shared/package-files/0b/0be8e146d11424f48931e88e174bcff0ef8cc7c6e19cd89a3746441482c7c130/_softmax_cuda_dispatch.h @@ -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 _softmax(const at::Tensor & self, int64_t dim, bool half_to_float); +TORCH_API at::Tensor & _softmax_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool half_to_float); +TORCH_API at::Tensor & _softmax_outf(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/0b/0beaf0353bf916d52fa37a1607c5cdaae08e6bf5d01dfe91f494585fa255006d/test_comparison.py b/shared/package-files/0b/0beaf0353bf916d52fa37a1607c5cdaae08e6bf5d01dfe91f494585fa255006d/test_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..a429649f1ce1dc10fc9610faa73a81dd94255b37 --- /dev/null +++ b/shared/package-files/0b/0beaf0353bf916d52fa37a1607c5cdaae08e6bf5d01dfe91f494585fa255006d/test_comparison.py @@ -0,0 +1,65 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import FloatingArray +from pandas.tests.arrays.masked_shared import ( + ComparisonOps, + NumericOps, +) + + +class TestComparisonOps(NumericOps, ComparisonOps): + @pytest.mark.parametrize("other", [True, False, pd.NA, -1.0, 0.0, 1]) + def test_scalar(self, other, comparison_op, dtype): + ComparisonOps.test_scalar(self, other, comparison_op, dtype) + + def test_compare_with_integerarray(self, comparison_op): + op = comparison_op + a = pd.array([0, 1, None] * 3, dtype="Int64") + b = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype="Float64") + other = b.astype("Int64") + expected = op(a, other) + result = op(a, b) + tm.assert_extension_array_equal(result, expected) + expected = op(other, a) + result = op(b, a) + tm.assert_extension_array_equal(result, expected) + + +def test_equals(): + # GH-30652 + # equals is generally tested in /tests/extension/base/methods, but this + # specifically tests that two arrays of the same class but different dtype + # do not evaluate equal + a1 = pd.array([1, 2, None], dtype="Float64") + a2 = pd.array([1, 2, None], dtype="Float32") + assert a1.equals(a2) is False + + +def test_equals_nan_vs_na(): + # GH#44382 + + mask = np.zeros(3, dtype=bool) + data = np.array([1.0, np.nan, 3.0], dtype=np.float64) + + left = FloatingArray(data, mask) + assert left.equals(left) + tm.assert_extension_array_equal(left, left) + + assert left.equals(left.copy()) + assert left.equals(FloatingArray(data.copy(), mask.copy())) + + mask2 = np.array([False, True, False], dtype=bool) + data2 = np.array([1.0, 2.0, 3.0], dtype=np.float64) + right = FloatingArray(data2, mask2) + assert right.equals(right) + tm.assert_extension_array_equal(right, right) + + assert not left.equals(right) + + # with mask[1] = True, the only difference is data[1], which should + # not matter for equals + mask[1] = True + assert left.equals(right) diff --git a/shared/package-files/0b/0beb4a462d08b8bc9c5e04ba082d68885902ae83a8ffe00ed153a399f7b4b651/double-to-string.h b/shared/package-files/0b/0beb4a462d08b8bc9c5e04ba082d68885902ae83a8ffe00ed153a399f7b4b651/double-to-string.h new file mode 100644 index 0000000000000000000000000000000000000000..90a88b902d6ea12d3adf917cdbf9e63b818d71ee --- /dev/null +++ b/shared/package-files/0b/0beb4a462d08b8bc9c5e04ba082d68885902ae83a8ffe00ed153a399f7b4b651/double-to-string.h @@ -0,0 +1,472 @@ +// Copyright 2012 the V8 project authors. 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 Google Inc. 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 +// 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. + +#ifndef DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_ +#define DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_ + +#include "utils.h" + +namespace arrow_vendored { +namespace double_conversion { + +class DoubleToStringConverter { + public: + // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint + // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the + // function returns false. + static const int kMaxFixedDigitsBeforePoint = 60; + static const int kMaxFixedDigitsAfterPoint = 100; + + // When calling ToExponential with a requested_digits + // parameter > kMaxExponentialDigits then the function returns false. + static const int kMaxExponentialDigits = 120; + + // When calling ToPrecision with a requested_digits + // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits + // then the function returns false. + static const int kMinPrecisionDigits = 1; + static const int kMaxPrecisionDigits = 120; + + // The maximal number of digits that are needed to emit a double in base 10. + // A higher precision can be achieved by using more digits, but the shortest + // accurate representation of any double will never use more digits than + // kBase10MaximalLength. + // Note that DoubleToAscii null-terminates its input. So the given buffer + // should be at least kBase10MaximalLength + 1 characters long. + static const int kBase10MaximalLength = 17; + + // The maximal number of digits that are needed to emit a single in base 10. + // A higher precision can be achieved by using more digits, but the shortest + // accurate representation of any single will never use more digits than + // kBase10MaximalLengthSingle. + static const int kBase10MaximalLengthSingle = 9; + + // The length of the longest string that 'ToShortest' can produce when the + // converter is instantiated with EcmaScript defaults (see + // 'EcmaScriptConverter') + // This value does not include the trailing '\0' character. + // This amount of characters is needed for negative values that hit the + // 'decimal_in_shortest_low' limit. For example: "-0.0000033333333333333333" + static const int kMaxCharsEcmaScriptShortest = 25; + + enum Flags { + NO_FLAGS = 0, + EMIT_POSITIVE_EXPONENT_SIGN = 1, + EMIT_TRAILING_DECIMAL_POINT = 2, + EMIT_TRAILING_ZERO_AFTER_POINT = 4, + UNIQUE_ZERO = 8, + NO_TRAILING_ZERO = 16, + EMIT_TRAILING_DECIMAL_POINT_IN_EXPONENTIAL = 32, + EMIT_TRAILING_ZERO_AFTER_POINT_IN_EXPONENTIAL = 64 + }; + + // Flags should be a bit-or combination of the possible Flags-enum. + // - NO_FLAGS: no special flags. + // - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent + // form, emits a '+' for positive exponents. Example: 1.2e+2. + // - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is + // converted into decimal format then a trailing decimal point is appended. + // Example: 2345.0 is converted to "2345.". + // - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point + // emits a trailing '0'-character. This flag requires the + // EMIT_TRAILING_DECIMAL_POINT flag. + // Example: 2345.0 is converted to "2345.0". + // - UNIQUE_ZERO: "-0.0" is converted to "0.0". + // - NO_TRAILING_ZERO: Trailing zeros are removed from the fractional portion + // of the result in precision mode. Matches printf's %g. + // When EMIT_TRAILING_ZERO_AFTER_POINT is also given, one trailing zero is + // preserved. + // - EMIT_TRAILING_DECIMAL_POINT_IN_EXPONENTIAL: when the input number has + // exactly one significant digit and is converted into exponent form then a + // trailing decimal point is appended to the significand in shortest mode + // or in precision mode with one requested digit. + // - EMIT_TRAILING_ZERO_AFTER_POINT_IN_EXPONENTIAL: in addition to a trailing + // decimal point emits a trailing '0'-character. This flag requires the + // EMIT_TRAILING_DECIMAL_POINT_IN_EXPONENTIAL flag. + // + // Infinity symbol and nan_symbol provide the string representation for these + // special values. If the string is NULL and the special value is encountered + // then the conversion functions return false. + // + // The exponent_character is used in exponential representations. It is + // usually 'e' or 'E'. + // + // When converting to the shortest representation the converter will + // represent input numbers in decimal format if they are in the interval + // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[ + // (lower boundary included, greater boundary excluded). + // Example: with decimal_in_shortest_low = -6 and + // decimal_in_shortest_high = 21: + // ToShortest(0.000001) -> "0.000001" + // ToShortest(0.0000001) -> "1e-7" + // ToShortest(111111111111111111111.0) -> "111111111111111110000" + // ToShortest(100000000000000000000.0) -> "100000000000000000000" + // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" + // + // When converting to precision mode the converter may add + // max_leading_padding_zeroes before returning the number in exponential + // format. + // Example with max_leading_padding_zeroes_in_precision_mode = 6. + // ToPrecision(0.0000012345, 2) -> "0.0000012" + // ToPrecision(0.00000012345, 2) -> "1.2e-7" + // Similarly the converter may add up to + // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid + // returning an exponential representation. A zero added by the + // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. + // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: + // ToPrecision(230.0, 2) -> "230" + // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. + // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. + // + // When converting numbers with exactly one significant digit to exponent + // form in shortest mode or in precision mode with one requested digit, the + // EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT flags have + // no effect. Use the EMIT_TRAILING_DECIMAL_POINT_IN_EXPONENTIAL flag to + // append a decimal point in this case and the + // EMIT_TRAILING_ZERO_AFTER_POINT_IN_EXPONENTIAL flag to also append a + // '0'-character in this case. + // Example with decimal_in_shortest_low = 0: + // ToShortest(0.0009) -> "9e-4" + // with EMIT_TRAILING_DECIMAL_POINT_IN_EXPONENTIAL deactivated. + // ToShortest(0.0009) -> "9.e-4" + // with EMIT_TRAILING_DECIMAL_POINT_IN_EXPONENTIAL activated. + // ToShortest(0.0009) -> "9.0e-4" + // with EMIT_TRAILING_DECIMAL_POINT_IN_EXPONENTIAL activated and + // EMIT_TRAILING_ZERO_AFTER_POINT_IN_EXPONENTIAL activated. + // + // The min_exponent_width is used for exponential representations. + // The converter adds leading '0's to the exponent until the exponent + // is at least min_exponent_width digits long. + // The min_exponent_width is clamped to 5. + // As such, the exponent may never have more than 5 digits in total. + DoubleToStringConverter(int flags, + const char* infinity_symbol, + const char* nan_symbol, + char exponent_character, + int decimal_in_shortest_low, + int decimal_in_shortest_high, + int max_leading_padding_zeroes_in_precision_mode, + int max_trailing_padding_zeroes_in_precision_mode, + int min_exponent_width = 0) + : flags_(flags), + infinity_symbol_(infinity_symbol), + nan_symbol_(nan_symbol), + exponent_character_(exponent_character), + decimal_in_shortest_low_(decimal_in_shortest_low), + decimal_in_shortest_high_(decimal_in_shortest_high), + max_leading_padding_zeroes_in_precision_mode_( + max_leading_padding_zeroes_in_precision_mode), + max_trailing_padding_zeroes_in_precision_mode_( + max_trailing_padding_zeroes_in_precision_mode), + min_exponent_width_(min_exponent_width) { + // When 'trailing zero after the point' is set, then 'trailing point' + // must be set too. + DOUBLE_CONVERSION_ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) || + !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0)); + } + + // Returns a converter following the EcmaScript specification. + // + // Flags: UNIQUE_ZERO and EMIT_POSITIVE_EXPONENT_SIGN. + // Special values: "Infinity" and "NaN". + // Lower case 'e' for exponential values. + // decimal_in_shortest_low: -6 + // decimal_in_shortest_high: 21 + // max_leading_padding_zeroes_in_precision_mode: 6 + // max_trailing_padding_zeroes_in_precision_mode: 0 + static const DoubleToStringConverter& EcmaScriptConverter(); + + // Computes the shortest string of digits that correctly represent the input + // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high + // (see constructor) it then either returns a decimal representation, or an + // exponential representation. + // Example with decimal_in_shortest_low = -6, + // decimal_in_shortest_high = 21, + // EMIT_POSITIVE_EXPONENT_SIGN activated, and + // EMIT_TRAILING_DECIMAL_POINT deactivated: + // ToShortest(0.000001) -> "0.000001" + // ToShortest(0.0000001) -> "1e-7" + // ToShortest(111111111111111111111.0) -> "111111111111111110000" + // ToShortest(100000000000000000000.0) -> "100000000000000000000" + // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" + // + // Note: the conversion may round the output if the returned string + // is accurate enough to uniquely identify the input-number. + // For example the most precise representation of the double 9e59 equals + // "899999999999999918767229449717619953810131273674690656206848", but + // the converter will return the shorter (but still correct) "9e59". + // + // Returns true if the conversion succeeds. The conversion always succeeds + // except when the input value is special and no infinity_symbol or + // nan_symbol has been given to the constructor. + // + // The length of the longest result is the maximum of the length of the + // following string representations (each with possible examples): + // - NaN and negative infinity: "NaN", "-Infinity", "-inf". + // - -10^(decimal_in_shortest_high - 1): + // "-100000000000000000000", "-1000000000000000.0" + // - the longest string in range [0; -10^decimal_in_shortest_low]. Generally, + // this string is 3 + kBase10MaximalLength - decimal_in_shortest_low. + // (Sign, '0', decimal point, padding zeroes for decimal_in_shortest_low, + // and the significant digits). + // "-0.0000033333333333333333", "-0.0012345678901234567" + // - the longest exponential representation. (A negative number with + // kBase10MaximalLength significant digits). + // "-1.7976931348623157e+308", "-1.7976931348623157E308" + // In addition, the buffer must be able to hold the trailing '\0' character. + bool ToShortest(double value, StringBuilder* result_builder) const { + return ToShortestIeeeNumber(value, result_builder, SHORTEST); + } + + // Same as ToShortest, but for single-precision floats. + bool ToShortestSingle(float value, StringBuilder* result_builder) const { + return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE); + } + + + // Computes a decimal representation with a fixed number of digits after the + // decimal point. The last emitted digit is rounded. + // + // Examples: + // ToFixed(3.12, 1) -> "3.1" + // ToFixed(3.1415, 3) -> "3.142" + // ToFixed(1234.56789, 4) -> "1234.5679" + // ToFixed(1.23, 5) -> "1.23000" + // ToFixed(0.1, 4) -> "0.1000" + // ToFixed(1e30, 2) -> "1000000000000000019884624838656.00" + // ToFixed(0.1, 30) -> "0.100000000000000005551115123126" + // ToFixed(0.1, 17) -> "0.10000000000000001" + // + // If requested_digits equals 0, then the tail of the result depends on + // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT. + // Examples, for requested_digits == 0, + // let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be + // - false and false: then 123.45 -> 123 + // 0.678 -> 1 + // - true and false: then 123.45 -> 123. + // 0.678 -> 1. + // - true and true: then 123.45 -> 123.0 + // 0.678 -> 1.0 + // + // Returns true if the conversion succeeds. The conversion always succeeds + // except for the following cases: + // - the input value is special and no infinity_symbol or nan_symbol has + // been provided to the constructor, + // - 'value' > 10^kMaxFixedDigitsBeforePoint, or + // - 'requested_digits' > kMaxFixedDigitsAfterPoint. + // The last two conditions imply that the result for non-special values never + // contains more than + // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters + // (one additional character for the sign, and one for the decimal point). + // In addition, the buffer must be able to hold the trailing '\0' character. + bool ToFixed(double value, + int requested_digits, + StringBuilder* result_builder) const; + + // Computes a representation in exponential format with requested_digits + // after the decimal point. The last emitted digit is rounded. + // If requested_digits equals -1, then the shortest exponential representation + // is computed. + // + // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and + // exponent_character set to 'e'. + // ToExponential(3.12, 1) -> "3.1e0" + // ToExponential(5.0, 3) -> "5.000e0" + // ToExponential(0.001, 2) -> "1.00e-3" + // ToExponential(3.1415, -1) -> "3.1415e0" + // ToExponential(3.1415, 4) -> "3.1415e0" + // ToExponential(3.1415, 3) -> "3.142e0" + // ToExponential(123456789000000, 3) -> "1.235e14" + // ToExponential(1000000000000000019884624838656.0, -1) -> "1e30" + // ToExponential(1000000000000000019884624838656.0, 32) -> + // "1.00000000000000001988462483865600e30" + // ToExponential(1234, 0) -> "1e3" + // + // Returns true if the conversion succeeds. The conversion always succeeds + // except for the following cases: + // - the input value is special and no infinity_symbol or nan_symbol has + // been provided to the constructor, + // - 'requested_digits' > kMaxExponentialDigits. + // + // The last condition implies that the result never contains more than + // kMaxExponentialDigits + 8 characters (the sign, the digit before the + // decimal point, the decimal point, the exponent character, the + // exponent's sign, and at most 3 exponent digits). + // In addition, the buffer must be able to hold the trailing '\0' character. + bool ToExponential(double value, + int requested_digits, + StringBuilder* result_builder) const; + + + // Computes 'precision' leading digits of the given 'value' and returns them + // either in exponential or decimal format, depending on + // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the + // constructor). + // The last computed digit is rounded. + // + // Example with max_leading_padding_zeroes_in_precision_mode = 6. + // ToPrecision(0.0000012345, 2) -> "0.0000012" + // ToPrecision(0.00000012345, 2) -> "1.2e-7" + // Similarly the converter may add up to + // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid + // returning an exponential representation. A zero added by the + // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. + // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: + // ToPrecision(230.0, 2) -> "230" + // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. + // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. + // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no + // EMIT_TRAILING_ZERO_AFTER_POINT: + // ToPrecision(123450.0, 6) -> "123450" + // ToPrecision(123450.0, 5) -> "123450" + // ToPrecision(123450.0, 4) -> "123500" + // ToPrecision(123450.0, 3) -> "123000" + // ToPrecision(123450.0, 2) -> "1.2e5" + // + // Returns true if the conversion succeeds. The conversion always succeeds + // except for the following cases: + // - the input value is special and no infinity_symbol or nan_symbol has + // been provided to the constructor, + // - precision < kMinPericisionDigits + // - precision > kMaxPrecisionDigits + // + // The last condition implies that the result never contains more than + // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the + // exponent character, the exponent's sign, and at most 3 exponent digits). + // In addition, the buffer must be able to hold the trailing '\0' character. + bool ToPrecision(double value, + int precision, + StringBuilder* result_builder) const; + + enum DtoaMode { + // Produce the shortest correct representation. + // For example the output of 0.299999999999999988897 is (the less accurate + // but correct) 0.3. + SHORTEST, + // Same as SHORTEST, but for single-precision floats. + SHORTEST_SINGLE, + // Produce a fixed number of digits after the decimal point. + // For instance fixed(0.1, 4) becomes 0.1000 + // If the input number is big, the output will be big. + FIXED, + // Fixed number of digits (independent of the decimal point). + PRECISION + }; + + // Converts the given double 'v' to digit characters. 'v' must not be NaN, + // +Infinity, or -Infinity. In SHORTEST_SINGLE-mode this restriction also + // applies to 'v' after it has been casted to a single-precision float. That + // is, in this mode static_cast(v) must not be NaN, +Infinity or + // -Infinity. + // + // The result should be interpreted as buffer * 10^(point-length). + // + // The digits are written to the buffer in the platform's charset, which is + // often UTF-8 (with ASCII-range digits) but may be another charset, such + // as EBCDIC. + // + // The output depends on the given mode: + // - SHORTEST: produce the least amount of digits for which the internal + // identity requirement is still satisfied. If the digits are printed + // (together with the correct exponent) then reading this number will give + // 'v' again. The buffer will choose the representation that is closest to + // 'v'. If there are two at the same distance, than the one farther away + // from 0 is chosen (halfway cases - ending with 5 - are rounded up). + // In this mode the 'requested_digits' parameter is ignored. + // - SHORTEST_SINGLE: same as SHORTEST but with single-precision. + // - FIXED: produces digits necessary to print a given number with + // 'requested_digits' digits after the decimal point. The produced digits + // might be too short in which case the caller has to fill the remainder + // with '0's. + // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2. + // Halfway cases are rounded towards +/-Infinity (away from 0). The call + // toFixed(0.15, 2) thus returns buffer="2", point=0. + // The returned buffer may contain digits that would be truncated from the + // shortest representation of the input. + // - PRECISION: produces 'requested_digits' where the first digit is not '0'. + // Even though the length of produced digits usually equals + // 'requested_digits', the function is allowed to return fewer digits, in + // which case the caller has to fill the missing digits with '0's. + // Halfway cases are again rounded away from 0. + // DoubleToAscii expects the given buffer to be big enough to hold all + // digits and a terminating null-character. In SHORTEST-mode it expects a + // buffer of at least kBase10MaximalLength + 1. In all other modes the + // requested_digits parameter and the padding-zeroes limit the size of the + // output. Don't forget the decimal point, the exponent character and the + // terminating null-character when computing the maximal output size. + // The given length is only used in debug mode to ensure the buffer is big + // enough. + static void DoubleToAscii(double v, + DtoaMode mode, + int requested_digits, + char* buffer, + int buffer_length, + bool* sign, + int* length, + int* point); + + private: + // Implementation for ToShortest and ToShortestSingle. + bool ToShortestIeeeNumber(double value, + StringBuilder* result_builder, + DtoaMode mode) const; + + // If the value is a special value (NaN or Infinity) constructs the + // corresponding string using the configured infinity/nan-symbol. + // If either of them is NULL or the value is not special then the + // function returns false. + bool HandleSpecialValues(double value, StringBuilder* result_builder) const; + // Constructs an exponential representation (i.e. 1.234e56). + // The given exponent assumes a decimal point after the first decimal digit. + void CreateExponentialRepresentation(const char* decimal_digits, + int length, + int exponent, + StringBuilder* result_builder) const; + // Creates a decimal representation (i.e 1234.5678). + void CreateDecimalRepresentation(const char* decimal_digits, + int length, + int decimal_point, + int digits_after_point, + StringBuilder* result_builder) const; + + const int flags_; + const char* const infinity_symbol_; + const char* const nan_symbol_; + const char exponent_character_; + const int decimal_in_shortest_low_; + const int decimal_in_shortest_high_; + const int max_leading_padding_zeroes_in_precision_mode_; + const int max_trailing_padding_zeroes_in_precision_mode_; + const int min_exponent_width_; + + DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter); +}; + +} // namespace double_conversion +} // namespace arrow_vendored + +#endif // DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_ diff --git a/shared/package-files/0b/0becb812cf5929286cd552087852e11b6c63d9d232edffec5ea82c4d43744551/lower_to_qnnpack.py b/shared/package-files/0b/0becb812cf5929286cd552087852e11b6c63d9d232edffec5ea82c4d43744551/lower_to_qnnpack.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a82179789dc392132a791632f0397a2dcf7595 --- /dev/null +++ b/shared/package-files/0b/0becb812cf5929286cd552087852e11b6c63d9d232edffec5ea82c4d43744551/lower_to_qnnpack.py @@ -0,0 +1,18 @@ +from ._lower_to_native_backend import _lower_to_native_backend +from ..qconfig import QConfigAny +from torch.fx import GraphModule +from typing import Dict, Tuple + +__all__ = [ + "lower_to_qnnpack" +] + +def lower_to_qnnpack( + model: GraphModule, + qconfig_map: Dict[str, QConfigAny], + node_name_to_scope: Dict[str, Tuple[str, type]] +) -> GraphModule: + """ Lower a quantized reference model (with reference quantized operator patterns) + to qnnpack + """ + return _lower_to_native_backend(model, qconfig_map, node_name_to_scope) diff --git a/shared/package-files/0b/0befdc306a6bb072d734c68f834c4e1cbc873f86bb438cb358c02c52a350c676/special_modified_bessel_i1_meta_dispatch.h b/shared/package-files/0b/0befdc306a6bb072d734c68f834c4e1cbc873f86bb438cb358c02c52a350c676/special_modified_bessel_i1_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7cc4edf25667439e005b2ce200a34c8f75926f67 --- /dev/null +++ b/shared/package-files/0b/0befdc306a6bb072d734c68f834c4e1cbc873f86bb438cb358c02c52a350c676/special_modified_bessel_i1_meta_dispatch.h @@ -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 at::Tensor special_modified_bessel_i1(const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_i1_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_i1_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/0b/0beff3eeb38313fd76a25cf4770b652aac1f6922d7115de46750b20c932c421f/core.py b/shared/package-files/0b/0beff3eeb38313fd76a25cf4770b652aac1f6922d7115de46750b20c932c421f/core.py new file mode 100644 index 0000000000000000000000000000000000000000..1cdc739731bfb073a580202f0cd0a36c5d3cb5aa --- /dev/null +++ b/shared/package-files/0b/0beff3eeb38313fd76a25cf4770b652aac1f6922d7115de46750b20c932c421f/core.py @@ -0,0 +1,216 @@ +import sys +from distutils.core import Distribution + +if 'setuptools' in sys.modules: + have_setuptools = True + from setuptools import setup as old_setup + # easy_install imports math, it may be picked up from cwd + from setuptools.command import easy_install + try: + # very old versions of setuptools don't have this + from setuptools.command import bdist_egg + except ImportError: + have_setuptools = False +else: + from distutils.core import setup as old_setup + have_setuptools = False + +import warnings +import distutils.core +import distutils.dist + +from numpy.distutils.extension import Extension # noqa: F401 +from numpy.distutils.numpy_distribution import NumpyDistribution +from numpy.distutils.command import config, config_compiler, \ + build, build_py, build_ext, build_clib, build_src, build_scripts, \ + sdist, install_data, install_headers, install, bdist_rpm, \ + install_clib +from numpy.distutils.misc_util import is_sequence, is_string + +numpy_cmdclass = {'build': build.build, + 'build_src': build_src.build_src, + 'build_scripts': build_scripts.build_scripts, + 'config_cc': config_compiler.config_cc, + 'config_fc': config_compiler.config_fc, + 'config': config.config, + 'build_ext': build_ext.build_ext, + 'build_py': build_py.build_py, + 'build_clib': build_clib.build_clib, + 'sdist': sdist.sdist, + 'install_data': install_data.install_data, + 'install_headers': install_headers.install_headers, + 'install_clib': install_clib.install_clib, + 'install': install.install, + 'bdist_rpm': bdist_rpm.bdist_rpm, + } +if have_setuptools: + # Use our own versions of develop and egg_info to ensure that build_src is + # handled appropriately. + from numpy.distutils.command import develop, egg_info + numpy_cmdclass['bdist_egg'] = bdist_egg.bdist_egg + numpy_cmdclass['develop'] = develop.develop + numpy_cmdclass['easy_install'] = easy_install.easy_install + numpy_cmdclass['egg_info'] = egg_info.egg_info + +def _dict_append(d, **kws): + for k, v in kws.items(): + if k not in d: + d[k] = v + continue + dv = d[k] + if isinstance(dv, tuple): + d[k] = dv + tuple(v) + elif isinstance(dv, list): + d[k] = dv + list(v) + elif isinstance(dv, dict): + _dict_append(dv, **v) + elif is_string(dv): + assert is_string(v) + d[k] = v + else: + raise TypeError(repr(type(dv))) + +def _command_line_ok(_cache=None): + """ Return True if command line does not contain any + help or display requests. + """ + if _cache: + return _cache[0] + elif _cache is None: + _cache = [] + ok = True + display_opts = ['--'+n for n in Distribution.display_option_names] + for o in Distribution.display_options: + if o[1]: + display_opts.append('-'+o[1]) + for arg in sys.argv: + if arg.startswith('--help') or arg=='-h' or arg in display_opts: + ok = False + break + _cache.append(ok) + return ok + +def get_distribution(always=False): + dist = distutils.core._setup_distribution + # XXX Hack to get numpy installable with easy_install. + # The problem is easy_install runs it's own setup(), which + # sets up distutils.core._setup_distribution. However, + # when our setup() runs, that gets overwritten and lost. + # We can't use isinstance, as the DistributionWithoutHelpCommands + # class is local to a function in setuptools.command.easy_install + if dist is not None and \ + 'DistributionWithoutHelpCommands' in repr(dist): + dist = None + if always and dist is None: + dist = NumpyDistribution() + return dist + +def setup(**attr): + + cmdclass = numpy_cmdclass.copy() + + new_attr = attr.copy() + if 'cmdclass' in new_attr: + cmdclass.update(new_attr['cmdclass']) + new_attr['cmdclass'] = cmdclass + + if 'configuration' in new_attr: + # To avoid calling configuration if there are any errors + # or help request in command in the line. + configuration = new_attr.pop('configuration') + + old_dist = distutils.core._setup_distribution + old_stop = distutils.core._setup_stop_after + distutils.core._setup_distribution = None + distutils.core._setup_stop_after = "commandline" + try: + dist = setup(**new_attr) + finally: + distutils.core._setup_distribution = old_dist + distutils.core._setup_stop_after = old_stop + if dist.help or not _command_line_ok(): + # probably displayed help, skip running any commands + return dist + + # create setup dictionary and append to new_attr + config = configuration() + if hasattr(config, 'todict'): + config = config.todict() + _dict_append(new_attr, **config) + + # Move extension source libraries to libraries + libraries = [] + for ext in new_attr.get('ext_modules', []): + new_libraries = [] + for item in ext.libraries: + if is_sequence(item): + lib_name, build_info = item + _check_append_ext_library(libraries, lib_name, build_info) + new_libraries.append(lib_name) + elif is_string(item): + new_libraries.append(item) + else: + raise TypeError("invalid description of extension module " + "library %r" % (item,)) + ext.libraries = new_libraries + if libraries: + if 'libraries' not in new_attr: + new_attr['libraries'] = [] + for item in libraries: + _check_append_library(new_attr['libraries'], item) + + # sources in ext_modules or libraries may contain header files + if ('ext_modules' in new_attr or 'libraries' in new_attr) \ + and 'headers' not in new_attr: + new_attr['headers'] = [] + + # Use our custom NumpyDistribution class instead of distutils' one + new_attr['distclass'] = NumpyDistribution + + return old_setup(**new_attr) + +def _check_append_library(libraries, item): + for libitem in libraries: + if is_sequence(libitem): + if is_sequence(item): + if item[0]==libitem[0]: + if item[1] is libitem[1]: + return + warnings.warn("[0] libraries list contains %r with" + " different build_info" % (item[0],), + stacklevel=2) + break + else: + if item==libitem[0]: + warnings.warn("[1] libraries list contains %r with" + " no build_info" % (item[0],), + stacklevel=2) + break + else: + if is_sequence(item): + if item[0]==libitem: + warnings.warn("[2] libraries list contains %r with" + " no build_info" % (item[0],), + stacklevel=2) + break + else: + if item==libitem: + return + libraries.append(item) + +def _check_append_ext_library(libraries, lib_name, build_info): + for item in libraries: + if is_sequence(item): + if item[0]==lib_name: + if item[1] is build_info: + return + warnings.warn("[3] libraries list contains %r with" + " different build_info" % (lib_name,), + stacklevel=2) + break + elif item==lib_name: + warnings.warn("[4] libraries list contains %r with" + " no build_info" % (lib_name,), + stacklevel=2) + break + libraries.append((lib_name, build_info)) diff --git a/shared/package-files/0b/0bf4d396c8bd71f2a6c43048c12d8107b4b8142a55a81b45450bd81a73a9bd41/functional_adadelta.py b/shared/package-files/0b/0bf4d396c8bd71f2a6c43048c12d8107b4b8142a55a81b45450bd81a73a9bd41/functional_adadelta.py new file mode 100644 index 0000000000000000000000000000000000000000..803132e5d7a42ecab2f51835d69b4b272a2cb012 --- /dev/null +++ b/shared/package-files/0b/0bf4d396c8bd71f2a6c43048c12d8107b4b8142a55a81b45450bd81a73a9bd41/functional_adadelta.py @@ -0,0 +1,102 @@ +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 Adadelta 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 _FunctionalAdadelta: + def __init__( + self, + params: List[Tensor], + lr: float = 1.0, + rho: float = 0.9, + eps: float = 1e-6, + weight_decay: float = 0.0, + foreach: bool = False, + maximize: bool = False, + _allow_empty_param_list: bool = False, + ): + self.defaults = { + "lr": lr, + "rho": rho, + "eps": eps, + "weight_decay": weight_decay, + } + self.foreach = foreach + self.maximize = maximize + + 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} + + self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {}) + + def step(self, gradients: List[Optional[Tensor]]): + params = self.param_group["params"] + params_with_grad = [] + grads = [] + square_avgs = [] + acc_deltas = [] + lr = self.defaults["lr"] + rho = self.defaults["rho"] + eps = self.defaults["eps"] + weight_decay = self.defaults["weight_decay"] + + 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_complex = False + for param, gradient in zip(params, gradients): + if gradient is not None: + has_complex |= torch.is_complex(param) + params_with_grad.append(param) + grads.append(gradient) + # Lazy state initialization + if param not in self.state: + self.state[param] = {} + state = self.state[param] + state["step"] = torch.tensor(0.0) + state["square_avg"] = torch.zeros_like( + param, memory_format=torch.preserve_format + ) + state["acc_delta"] = torch.zeros_like( + param, memory_format=torch.preserve_format + ) + + state = self.state[param] + square_avgs.append(state["square_avg"]) + acc_deltas.append(state["acc_delta"]) + + with torch.no_grad(): + F.adadelta( + params_with_grad, + grads, + square_avgs, + acc_deltas, + lr=lr, + rho=rho, + eps=eps, + weight_decay=weight_decay, + foreach=self.foreach, + maximize=self.maximize, + has_complex=has_complex + ) diff --git a/shared/package-files/0b/0bf7b81d0234e27e7e2ad231180b4b62df178aeb13ccdd727506992bd2942905/_config.py b/shared/package-files/0b/0bf7b81d0234e27e7e2ad231180b4b62df178aeb13ccdd727506992bd2942905/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ead0037c9e1855d9b5fb17a31acbf54eae1253cb --- /dev/null +++ b/shared/package-files/0b/0bf7b81d0234e27e7e2ad231180b4b62df178aeb13ccdd727506992bd2942905/_config.py @@ -0,0 +1,76 @@ +import os +import sys + +from typing import Optional + +# [@compile_ignored: debug] Uses z3 for validating the guard optimizations transformations. +translation_validation = ( + os.environ.get("TORCHDYNAMO_TRANSLATION_VALIDATION", "0") == "1" +) +# Timeout (in milliseconds) for z3 finding a solution. +# [@compile_ignored: debug] +translation_validation_timeout = int( + os.environ.get("TORCHDYNAMO_TRANSLATION_VALIDATION_TIMEOUT", "600000") +) +# Disables bisection for translation validation. +# +# Translation validation bisection is enabled by default, if translation validation +# is also enabled. This should help finding guard simplification issues. However, +# since validation uses Z3 for bisecting, it might take a lot of time. +# +# Set this configuration option so as to avoid bisecting. +# [@compile_ignored: debug] +translation_validation_no_bisect = ( + os.environ.get("TORCHDYNAMO_TRANSLATION_NO_BISECT", "0") == "1" +) +# Checks whether replaying ShapeEnv events on a freshly constructed one yields +# the a ShapeEnv with the same state. This should be used only in testing. +check_shape_env_recorded_events = False + +# TODO: Perhaps consider allowing unions for the configs below (so you can hit +# multiple reps at the same time) + +# Give extended debug information if the string representation of a guard +# matches this. For example, set this to "Ne(s0, 10)" and whenever we issue +# this guard, we will generate full Python and C++ backtrace +# [@compile_ignored: debug] +extended_debug_guard_added = os.environ.get( + "TORCHDYNAMO_EXTENDED_DEBUG_GUARD_ADDED", None +) + +# Give extended debug information when a particular symbol is allocated. For +# example, set this to "u2" and whenever we create this symbol, we will +# generate full Python and C++ backtrace +# [@compile_ignored: debug] +extended_debug_create_symbol = os.environ.get( + "TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL", None +) + +# Give extended debug information (C++ backtrace) for all extended debug +# settings as well as errors. The C++ backtrace is slow and very spammy so we +# don't include it by default even when you're requesting extended debug. +# [@compile_ignored: debug] +extended_debug_cpp = os.environ.get("TORCHDYNAMO_EXTENDED_DEBUG_CPP", "") != "" + +# [@compile_ignored: debug] Show a warning for every specialization +print_specializations = False + +# wraps (un)equalities with 'Not' class after recording the correct expression +# in the FX graph. This should incorrectly construct the divisible and replacement +# lists, and incorrectly issue guards. +inject_EVALUATE_EXPR_flip_equality_TESTING_ONLY = False + +# [@compile_ignored: debug] Validate that ShapeEnv's version key is updated correctly +validate_shape_env_version_key = False + +# If we produce more than this many guards on a symbol, force the symbol to +# get specialized and bail out if this many guards mention this particular +# symbol. This may be slightly more aggressive than the true number of guards +# issued (as we test if we've hit the limit on-the-fly, whereas we may +# do further simplifications at final guard issuance time that make guards +# irrelevant.) +symbol_guard_limit_before_specialize: Optional[int] = None + +from torch.utils._config_module import install_config_module + +install_config_module(sys.modules[__name__]) diff --git a/shared/package-files/0b/0bf8c7273997f0f238c6ad23a7399c4ccc696f9943b2ae28e55cb1433955ad91/package_data.py b/shared/package-files/0b/0bf8c7273997f0f238c6ad23a7399c4ccc696f9943b2ae28e55cb1433955ad91/package_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8501893bd153b7216524084cad23e90aeac0b1f8 --- /dev/null +++ b/shared/package-files/0b/0bf8c7273997f0f238c6ad23a7399c4ccc696f9943b2ae28e55cb1433955ad91/package_data.py @@ -0,0 +1,2 @@ +__version__ = '3.4' + diff --git a/shared/package-files/0b/0bfafe8a6eba5ad96eb4f016866e111b80a3bca5ec28d8edce9e12dd29915112/fuse_attention.py b/shared/package-files/0b/0bfafe8a6eba5ad96eb4f016866e111b80a3bca5ec28d8edce9e12dd29915112/fuse_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..b34d03116acbb085e6ebde0116b0675bfb4effb9 --- /dev/null +++ b/shared/package-files/0b/0bfafe8a6eba5ad96eb4f016866e111b80a3bca5ec28d8edce9e12dd29915112/fuse_attention.py @@ -0,0 +1,786 @@ +import functools +import inspect +import logging +import math + +import torch +from ..._dynamo.utils import counters +from ..pattern_matcher import ( + filter_nodes, + fwd_only, + joint_fwd_bwd, + register_replacement, +) + +log = logging.getLogger(__name__) +aten = torch.ops.aten + + +def _sfdp_pattern_1(query, key, value, inv_scale): + return ( + torch.matmul(query, key.transpose(-2, -1)) + .div(inv_scale) + .softmax(dim=-1) + .matmul(value) + ) + + +def _sfdp_replacement_1(query, key, value, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.contiguous(), + key.contiguous(), + value.contiguous(), + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_2(query, key, value, scale_factor): + return ( + torch.matmul(query, key.transpose(-2, -1)) + .mul(scale_factor) + .softmax(dim=-1) + .matmul(value) + ) + + +def _sfdp_replacement_2(query, key, value, scale_factor): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.contiguous(), + key.contiguous(), + value.contiguous(), + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=scale_factor, + ) + + +def _sfdp_pattern_3(query, key, value, inv_scale_factor, dropout_p): + return torch.nn.functional.dropout( + torch.matmul(query, key.transpose(-2, -1)) + .div(inv_scale_factor) + .softmax(dim=-1), + p=dropout_p, + ).matmul(value) + + +def _sfdp_replacement_3(query, key, value, inv_scale_factor, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.contiguous(), + key.contiguous(), + value.contiguous(), + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale_factor, + ) + + +def _sfdp_pattern_4(query, key, value, scale_factor, dropout_p): + return torch.nn.functional.dropout( + torch.matmul(query, key.transpose(-2, -1)).mul(scale_factor).softmax(dim=-1), + p=dropout_p, + ).matmul(value) + + +def _sfdp_replacement_4(query, key, value, scale_factor, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.contiguous(), + key.contiguous(), + value.contiguous(), + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=scale_factor, + ) + + +def _sfdp_pattern_5(query, key, value, attn_mask): + attn_weight = torch.softmax( + (query @ key.transpose(-2, -1) / math.sqrt(query.size(-1))) + attn_mask, dim=-1 + ) + # attn_weight = torch.dropout(attn_weight, dropout_p) + return attn_weight @ value + + +def _sfdp_replacement_5(query, key, value, attn_mask): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.contiguous(), + key.contiguous(), + value.contiguous(), + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=0.0, + is_causal=False, + ) + + +def _sfdp_pattern_6(query, key, value, attn_mask, dropout_p): + attn_weight = torch.softmax( + (query @ key.transpose(-2, -1) / math.sqrt(query.size(-1))) + attn_mask, dim=-1 + ) + attn_weight = torch.dropout(attn_weight, dropout_p, True) + return attn_weight @ value + + +def _sfdp_replacement_6(query, key, value, attn_mask, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.contiguous(), + key.contiguous(), + value.contiguous(), + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=dropout_p, + is_causal=False, + ) + + +def _sfdp_pattern_7(query, key, value, dropout_p): + # in real workloads inputs to matmul are permuted + # causing matmul to expand to a series of expand and clone calls + # we want the same to happen during pattern tracing + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + div = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1)) + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = torch.dropout(attn_weight, dropout_p, True) + attn_weight = attn_weight.to(torch.float16) + return attn_weight @ v + + +def _sfdp_replacement_7(query, key, value, dropout_p): + # sdpa prefers inputs in permuted format + # it makes a copy to put them in this format + # if they aren't already + # to make replacement efficient ensure that inputs to sdpa + # are in required order + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return aten.scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=dropout_p, + is_causal=False, + ) + + +def _sfdp_pattern_8(query, key, value): + # no dropout version of pattern 7 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + div = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1)) + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = attn_weight.to(torch.float16) + return attn_weight @ v + + +def _sfdp_replacement_8(query, key, value): + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return aten.scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=0.0, + is_causal=False, + ) + + +def _sfdp_pattern_9(query, key, value, dropout_p): + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + q = q / math.sqrt(q.size(-1)) + div = q @ k.transpose(-2, -1) + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = torch.dropout(attn_weight, dropout_p, True) + attn_weight = attn_weight.to(torch.float16) + return attn_weight @ v + + +def _sfdp_replacement_9(query, key, value, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return aten.scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=dropout_p, + is_causal=False, + ) + + +def _sfdp_pattern_10(query, key, value): + # no dropout version of 9 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + q = q / math.sqrt(q.size(-1)) + div = q @ k.transpose(-2, -1) + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = attn_weight.to(torch.float16) + return attn_weight @ v + + +def _sfdp_replacement_10(query, key, value): + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return aten.scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=0.0, + is_causal=False, + ) + + +def _sfdp_pattern_11(query, key, value, inv_scale): + # Mainly for huggingface models + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return torch.matmul(q, k.transpose(-2, -1)).div(inv_scale).softmax(dim=-1).matmul(v) + + +def _sfdp_replacement_11(query, key, value, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_12(query, key, value, inv_scale_factor, dropout_p): + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return torch.nn.functional.dropout( + torch.matmul(q, k.transpose(-2, -1)).div(inv_scale_factor).softmax(dim=-1), + p=dropout_p, + ).matmul(v) + + +def _sfdp_replacement_12(query, key, value, inv_scale_factor, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale_factor, + ) + + +def _sfdp_pattern_13(query, key, value, dropout_p): + attn_weight = torch.bmm(query, key.transpose(1, 2)).softmax(dim=-1) + attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p) + return torch.bmm(attn_weight, value) + + +def _sfdp_replacement_13(query, key, value, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.unsqueeze(0), + key.unsqueeze(0), + value.unsqueeze(0), + dropout_p=dropout_p, + scale=1.0, + ).squeeze(0) + + +def _sfdp_pattern_14(query, key, value, attn_mask, inv_scale): + # for BertLarge + # Permutations are needed to create clones in graph. + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + return ( + (torch.matmul(q, k.transpose(-2, -1)).div(inv_scale) + attn_mask) + .softmax(dim=-1) + .matmul(v) + ) + + +def _sfdp_replacement_14(query, key, value, attn_mask, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_15(query, key, value, attn_mask, inv_scale): + # for DistilBert + # Permutations are needed to create clones in graph. + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + bs = q.size(0) + k_len = k.size(-2) + scores = q @ k.transpose(-2, -1) + scores = scores.div(inv_scale) + fill_value = torch.full((), -float("inf"), dtype=query.dtype, device=query.device) + attn_mask = (attn_mask == 0).view((bs, 1, 1, k_len)).expand_as(scores) + return torch.softmax(scores.masked_fill(attn_mask, fill_value), dim=-1) @ v + + +def _sfdp_replacement_15(query, key, value, attn_mask, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + bs = query.size(0) + n_head = query.size(2) + q_len = query.size(1) + k_len = key.size(1) + # do attn_mask->logical_not() in aten.scaled_dot_product_attention + attn_mask = ( + (attn_mask == 1).view((bs, 1, 1, k_len)).expand((bs, n_head, q_len, k_len)) + ) + return aten.scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=torch.bool), + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_16(query, key, value, attn_mask, inv_scale, dropout_p): + # for BertLarge with dropout + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + return ( + torch.nn.functional.dropout( + (torch.matmul(q, k.transpose(-2, -1)).div(inv_scale) + attn_mask).softmax( + dim=-1 + ), + dropout_p, + ) + .to(dtype=query.dtype) + .matmul(v) + ) + + +def _sfdp_replacement_16(query, key, value, attn_mask, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return aten.scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_17(query, key, value, attn_mask, inv_scale, dropout_p): + # for DistilBert with dropout + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + bs = q.size(0) + k_len = k.size(-2) + scores = q @ k.transpose(-2, -1) + scores = scores.div(inv_scale) + fill_value = torch.full((), -float("inf"), dtype=query.dtype, device=query.device) + attn_mask = (attn_mask == 0).view((bs, 1, 1, k_len)).expand_as(scores) + return ( + torch.nn.functional.dropout( + torch.softmax(scores.masked_fill(attn_mask, fill_value), dim=-1), dropout_p + ) + @ v + ) + + +def _sfdp_replacement_17(query, key, value, attn_mask, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + bs = query.size(0) + n_head = query.size(2) + q_len = query.size(1) + k_len = key.size(1) + # do attn_mask->logical_not() in aten.scaled_dot_product_attention + attn_mask = ( + (attn_mask == 1).view((bs, 1, 1, k_len)).expand((bs, n_head, q_len, k_len)) + ) + return aten.scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=torch.bool), + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_params_check(match): + assert all(k in match.kwargs for k in ("query", "key", "value")) + query = match.kwargs["query"].meta["val"] + key = match.kwargs["key"].meta["val"] + value = match.kwargs["value"].meta["val"] + if not (query.dtype == key.dtype == value.dtype) or not ( + query.device == key.device == value.device + ): + return False + add_mask_node = filter_nodes(match.nodes, aten.add.Tensor) + # Has attn_mask add. + if len(add_mask_node) > 0: + attn_mask_node = add_mask_node[0].args[1] + # attn_mask_node may be a float/int number. + if not hasattr(attn_mask_node, "meta"): + return False + attn_mask = attn_mask_node.meta["val"] # type: ignore[union-attr] + # Make sure attn_mask.dtype == query.dtype or attn_mask.dtype == torch.bool + # attn_mask.dtype == torch.float for models like albert. + if ( + not isinstance(attn_mask, torch.Tensor) + or not ( + attn_mask.dtype == query.dtype + or attn_mask.dtype == torch.bool + or attn_mask.dtype == torch.float + ) + or query.device != attn_mask.device + ): + return False + return True + + +def _sfdp_extra_check(scale_factor_op, disable_cuda=False): + def fn(match): + scale_factor_node = filter_nodes(match.nodes, scale_factor_op)[0] + # Note: args[1] of the scale_factor_node is always the scale_factor for the current patterns. + scale_factor = scale_factor_node.args[1] + # make sure the scale_factor a float/int. SymInt? + if not isinstance(scale_factor, (float, int)): + return False + if ( + disable_cuda + and "query" in match.kwargs + and "cuda" in str(match.kwargs["query"].meta["val"].device) + ): + return False + return _sfdp_params_check(match) + + return fn + + +def partialize_and_update_signature(func, **kwargs): + """ + Equivalent to functools.partial but also updates the signature on returned function + """ + original_sig = inspect.signature(func) + parameters = original_sig.parameters + + new_parameters = { + key: value for key, value in parameters.items() if key not in kwargs + } + new_sig = inspect.Signature(parameters=list(new_parameters.values())) + + partial_func = functools.partial(func, **kwargs) + + def wrapper(*args, **kwargs): + return partial_func(*args, **kwargs) + + wrapper.__signature__ = new_sig # type: ignore[attr-defined] + wrapper.__name__ = func.__name__ + + return wrapper + + +def _get_sfdp_patterns(): + from .joint_graph import patterns + + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + else: + device = "cpu" + + # sizes/values don't actually matter for initial trace + # once we get a possible match we re-trace with the actual values and verify the match still holds + g_inp = functools.partial( + torch.empty, (2, 4, 8, 16), device=device, requires_grad=True + ) + # attn_mask + b_inp = functools.partial(torch.empty, (1, 1, 8, 8), device=device) + m_inp = functools.partial(torch.empty, (2, 1, 1, 4), device=device) + # inv_scale + c_inp = functools.partial(torch.tensor, 2.0, device=device) + # workaround https://github.com/pytorch/pytorch/issues/97894 + # 0.113377 is a "magic" value that lets us recover the lost input arg relationship + d = {"dropout_p": 0.113377} + + # we could also generate all these patterns in 3d.. TODO + g_3d_inp = functools.partial( + torch.empty, (1024, 128, 128), device=device, requires_grad=True + ) + + # reshape in matmul decomposition generates a clone when batch_size>1 due to the memory layout change. + # however when batch_size=1, reshape does not change the memory layout, so clone would not be generated. + # here we need to trace with input of batch_size=1 to generate a pattern graph without clone. + g_bs1_inp = functools.partial( + torch.empty, (1, 4, 8, 16), device=device, requires_grad=True + ) + m_bs1_inp = functools.partial(torch.empty, (1, 1, 1, 4), device=device) + + # softmax will generate a dtype conversion on inputs if they are in half, + # but will not in float, so we generate a pattern for both + for dtype in [torch.float, torch.half]: + g = functools.partial(g_inp, dtype=dtype) + b = functools.partial(b_inp, dtype=dtype) + m = functools.partial(m_inp, dtype=dtype) + m_float = functools.partial(m_inp, dtype=torch.float) + c = functools.partial(c_inp, dtype=dtype) + g_3d = functools.partial(g_3d_inp, dtype=dtype) + g_bs1 = functools.partial(g_bs1_inp, dtype=dtype) + m_bs1 = functools.partial(m_bs1_inp, dtype=dtype) + m_bs1_float = functools.partial(m_bs1_inp, dtype=torch.float) + + candidates = [ + ( + _sfdp_pattern_1, + _sfdp_replacement_1, + [g(), g(), g(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_2, + _sfdp_replacement_2, + [g(), g(), g(), c()], + {}, + _sfdp_extra_check(aten.mul.Tensor), + ), + ( + _sfdp_pattern_3, + _sfdp_replacement_3, + [g(), g(), g(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_4, + _sfdp_replacement_4, + [g(), g(), g(), c()], + d, + _sfdp_extra_check(aten.mul.Tensor), + ), + ( + _sfdp_pattern_5, + _sfdp_replacement_5, + [g(), g(), g(), b()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_6, + _sfdp_replacement_6, + [g(), g(), g(), b()], + d, + _sfdp_params_check, + ), + ( + _sfdp_pattern_7, + _sfdp_replacement_7, + [g(), g(), g()], + d, + _sfdp_params_check, + ), + ( + _sfdp_pattern_8, + _sfdp_replacement_8, + [g(), g(), g()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_9, + _sfdp_replacement_9, + [g(), g(), g()], + d, + _sfdp_params_check, + ), + ( + _sfdp_pattern_10, + _sfdp_replacement_10, + [g(), g(), g()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_11, + _sfdp_replacement_11, + [g(), g(), g(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_12, + _sfdp_replacement_12, + [g(), g(), g(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_13, + _sfdp_replacement_13, + [g_3d(), g_3d(), g_3d()], + d, + _sfdp_params_check, + ), + ( + _sfdp_pattern_14, + _sfdp_replacement_14, + [g(), g(), g(), m(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_15, + _sfdp_replacement_15, + [g(), g(), g(), m(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + # TODO: Enable CUDA after solving Bert accuracy issue of calling efficient attention + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g(), g(), g(), m(), c()], + d, + _sfdp_extra_check(aten.div.Tensor, disable_cuda=True), + ), + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g_bs1(), g_bs1(), g_bs1(), m_bs1(), c()], + d, + _sfdp_extra_check(aten.div.Tensor, disable_cuda=True), + ), + ( + _sfdp_pattern_17, + _sfdp_replacement_17, + [g(), g(), g(), m(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ] + mask_fp32_patterns = ["pattern_16"] + if dtype == torch.half: + # Add inputs of bf16 q/k/v and fp32 mask, for models like albert. + candidates.append( + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g(), g(), g(), m_float(), c()], + d, + _sfdp_extra_check(aten.div.Tensor, disable_cuda=True), + ) + ) + candidates.append( + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g_bs1(), g_bs1(), g_bs1(), m_bs1_float(), c()], + d, + _sfdp_extra_check(aten.div.Tensor, disable_cuda=True), + ) + ) + + for pattern, replacement, args, workaround, extra_check in candidates: + # XXX: when adding a new pattern, re-run `gen_attention_patterns` so the pattern + # gets serialized to a python file and does not require tracing at runtime. + assert isinstance(workaround, dict) + name = pattern.__name__ + + if dtype != torch.float: + name += "_half" + if ( + any(p in name for p in mask_fp32_patterns) + and args[3].dtype == torch.float32 + ): + name += "_mask_fp32" + if args[0].size(0) == 1: + name += "_bs1" + + training_name = name + "_training" + yield training_name, { + "search_fn": pattern, + "replace_fn": replacement, + "example_inputs": args, + "trace_fn": joint_fwd_bwd, + "pass_dicts": patterns, + "extra_check": extra_check, + "scalar_workaround": workaround, + } + + if workaround: + assert len(workaround) == 1 and "dropout_p" in workaround + # functools.partial insufficient because we look at signature downstream + pattern = partialize_and_update_signature(pattern, dropout_p=0.0) + replacement = partialize_and_update_signature( + replacement, dropout_p=0.0 + ) + workaround = {} + + inference_name = name + "_inference" + yield inference_name, { + "search_fn": pattern, + "replace_fn": replacement, + "example_inputs": args, + "trace_fn": fwd_only, + "pass_dicts": patterns, + "extra_check": extra_check, + "scalar_workaround": workaround, + } + + +@functools.lru_cache(None) +def _sfdp_init(): + from .serialized_patterns.central_index import get_serialized_pattern + + for key, register_replacement_kwargs in _get_sfdp_patterns(): + search_fn_pattern = get_serialized_pattern(key) + register_replacement( + **register_replacement_kwargs, search_fn_pattern=search_fn_pattern + ) diff --git a/shared/package-files/0b/0bfb3565cdbfd14fe805c89036de71269fbc15a2e692c7047669d7d8dab5e946/common.py b/shared/package-files/0b/0bfb3565cdbfd14fe805c89036de71269fbc15a2e692c7047669d7d8dab5e946/common.py new file mode 100644 index 0000000000000000000000000000000000000000..b608df1554154f4723a0147ea02c04c780839c65 --- /dev/null +++ b/shared/package-files/0b/0bfb3565cdbfd14fe805c89036de71269fbc15a2e692c7047669d7d8dab5e946/common.py @@ -0,0 +1,155 @@ +""" +Assertion helpers for arithmetic tests. +""" +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Index, + Series, + array, +) +import pandas._testing as tm +from pandas.core.arrays import ( + BooleanArray, + NumpyExtensionArray, +) + + +def assert_cannot_add(left, right, msg="cannot add"): + """ + Helper to assert that left and right cannot be added. + + Parameters + ---------- + left : object + right : object + msg : str, default "cannot add" + """ + with pytest.raises(TypeError, match=msg): + left + right + with pytest.raises(TypeError, match=msg): + right + left + + +def assert_invalid_addsub_type(left, right, msg=None): + """ + Helper to assert that left and right can be neither added nor subtracted. + + Parameters + ---------- + left : object + right : object + msg : str or None, default None + """ + with pytest.raises(TypeError, match=msg): + left + right + with pytest.raises(TypeError, match=msg): + right + left + with pytest.raises(TypeError, match=msg): + left - right + with pytest.raises(TypeError, match=msg): + right - left + + +def get_upcast_box(left, right, is_cmp: bool = False): + """ + Get the box to use for 'expected' in an arithmetic or comparison operation. + + Parameters + left : Any + right : Any + is_cmp : bool, default False + Whether the operation is a comparison method. + """ + + if isinstance(left, DataFrame) or isinstance(right, DataFrame): + return DataFrame + if isinstance(left, Series) or isinstance(right, Series): + if is_cmp and isinstance(left, Index): + # Index does not defer for comparisons + return np.array + return Series + if isinstance(left, Index) or isinstance(right, Index): + if is_cmp: + return np.array + return Index + return tm.to_array + + +def assert_invalid_comparison(left, right, box): + """ + Assert that comparison operations with mismatched types behave correctly. + + Parameters + ---------- + left : np.ndarray, ExtensionArray, Index, or Series + right : object + box : {pd.DataFrame, pd.Series, pd.Index, pd.array, tm.to_array} + """ + # Not for tznaive-tzaware comparison + + # Note: not quite the same as how we do this for tm.box_expected + xbox = box if box not in [Index, array] else np.array + + def xbox2(x): + # Eventually we'd like this to be tighter, but for now we'll + # just exclude NumpyExtensionArray[bool] + if isinstance(x, NumpyExtensionArray): + return x._ndarray + if isinstance(x, BooleanArray): + # NB: we are assuming no pd.NAs for now + return x.astype(bool) + return x + + # rev_box: box to use for reversed comparisons + rev_box = xbox + if isinstance(right, Index) and isinstance(left, Series): + rev_box = np.array + + result = xbox2(left == right) + expected = xbox(np.zeros(result.shape, dtype=np.bool_)) + + tm.assert_equal(result, expected) + + result = xbox2(right == left) + tm.assert_equal(result, rev_box(expected)) + + result = xbox2(left != right) + tm.assert_equal(result, ~expected) + + result = xbox2(right != left) + tm.assert_equal(result, rev_box(~expected)) + + msg = "|".join( + [ + "Invalid comparison between", + "Cannot compare type", + "not supported between", + "invalid type promotion", + ( + # GH#36706 npdev 1.20.0 2020-09-28 + r"The DTypes and " + r" do not have a common DType. " + "For example they cannot be stored in a single array unless the " + "dtype is `object`." + ), + ] + ) + with pytest.raises(TypeError, match=msg): + left < right + with pytest.raises(TypeError, match=msg): + left <= right + with pytest.raises(TypeError, match=msg): + left > right + with pytest.raises(TypeError, match=msg): + left >= right + with pytest.raises(TypeError, match=msg): + right < left + with pytest.raises(TypeError, match=msg): + right <= left + with pytest.raises(TypeError, match=msg): + right > left + with pytest.raises(TypeError, match=msg): + right >= left diff --git a/shared/package-files/2c/2c0302761ded6b2b249de4a3b73b8c9e7f5d38feb4213945efdf9f1a69674703/geometric_compositeexplicitautograd_dispatch.h b/shared/package-files/2c/2c0302761ded6b2b249de4a3b73b8c9e7f5d38feb4213945efdf9f1a69674703/geometric_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..face188b3b733fc49d7ca79cc1d76b4624b82492 --- /dev/null +++ b/shared/package-files/2c/2c0302761ded6b2b249de4a3b73b8c9e7f5d38feb4213945efdf9f1a69674703/geometric_compositeexplicitautograd_dispatch.h @@ -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 geometric(const at::Tensor & self, double p, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & geometric_out(at::Tensor & out, const at::Tensor & self, double p, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & geometric_outf(const at::Tensor & self, double p, c10::optional generator, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/2c/2c03d1a1f99e0e14a9538d7c293ce8013a79701d83f5d69681c80ffc0d98ac32/atom.pyi b/shared/package-files/2c/2c03d1a1f99e0e14a9538d7c293ce8013a79701d83f5d69681c80ffc0d98ac32/atom.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d02a482966cb232f855ed0e73d73221e0c0ef8df --- /dev/null +++ b/shared/package-files/2c/2c03d1a1f99e0e14a9538d7c293ce8013a79701d83f5d69681c80ffc0d98ac32/atom.pyi @@ -0,0 +1,50 @@ +from typing import Any, Optional + +XHTML_NAMESPACE: Any + +def format_iso8601(obj): ... + +class AtomFeed: + default_generator: Any + title: Any + title_type: Any + url: Any + feed_url: Any + id: Any + updated: Any + author: Any + icon: Any + logo: Any + rights: Any + rights_type: Any + subtitle: Any + subtitle_type: Any + generator: Any + links: Any + entries: Any + def __init__(self, title: Optional[Any] = ..., entries: Optional[Any] = ..., **kwargs): ... + def add(self, *args, **kwargs): ... + def generate(self): ... + def to_string(self): ... + def get_response(self): ... + def __call__(self, environ, start_response): ... + +class FeedEntry: + title: Any + title_type: Any + content: Any + content_type: Any + url: Any + id: Any + updated: Any + summary: Any + summary_type: Any + author: Any + published: Any + rights: Any + links: Any + categories: Any + xml_base: Any + def __init__(self, title: Optional[Any] = ..., content: Optional[Any] = ..., feed_url: Optional[Any] = ..., **kwargs): ... + def generate(self): ... + def to_string(self): ... diff --git a/shared/package-files/2c/2c04de0d2caef60630a3ede362754348a7ab3c43eefd14a87bd5fa35b9e1c90f/test_annotations.py b/shared/package-files/2c/2c04de0d2caef60630a3ede362754348a7ab3c43eefd14a87bd5fa35b9e1c90f/test_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..90e70eac808722d4b156c7ed36bb8ddd09bf9000 --- /dev/null +++ b/shared/package-files/2c/2c04de0d2caef60630a3ede362754348a7ab3c43eefd14a87bd5fa35b9e1c90f/test_annotations.py @@ -0,0 +1,252 @@ +import re +from io import StringIO + +import numba +from numba.core import types +from numba import jit, njit +from numba.tests.support import override_config, TestCase +import unittest + +try: + import jinja2 +except ImportError: + jinja2 = None + +try: + import pygments +except ImportError: + pygments = None + + +@unittest.skipIf(jinja2 is None, "please install the 'jinja2' package") +class TestAnnotation(TestCase): + + @TestCase.run_test_in_subprocess # annotations compound per module + def test_exercise_code_path(self): + """ + Ensures template.html is available + """ + + def foo(n, a): + s = a + for i in range(n): + s += i + return s + + cfunc = njit((types.int32, types.int32))(foo) + cres = cfunc.overloads[cfunc.signatures[0]] + ta = cres.type_annotation + + buf = StringIO() + ta.html_annotate(buf) + output = buf.getvalue() + buf.close() + self.assertIn("foo", output) + + @TestCase.run_test_in_subprocess # annotations compound per module + def test_exercise_code_path_with_lifted_loop(self): + """ + Ensures that lifted loops are handled correctly in obj mode + """ + # the functions to jit + def bar(x): + return x + + def foo(x): + h = 0. + for i in range(x): # py 38 needs two loops for one to lift?! + h = h + i + for k in range(x): + h = h + k + if x: + h = h - bar(x) + return h + + # compile into an isolated context + cfunc = jit((types.intp,), forceobj=True, looplift=True)(foo) + cres = cfunc.overloads[cfunc.signatures[0]] + + ta = cres.type_annotation + + buf = StringIO() + ta.html_annotate(buf) + output = buf.getvalue() + buf.close() + self.assertIn("bar", output) + self.assertIn("foo", output) + self.assertIn("LiftedLoop", output) + + @TestCase.run_test_in_subprocess # annotations compound per module + def test_html_output_with_lifted_loop(self): + """ + Test some format and behavior of the html annotation with lifted loop + """ + @numba.jit(forceobj=True) + def udt(x): + object() # to force object mode + z = 0 + for i in range(x): # this line is tagged + z += i + return z + + # Regex pattern to check for the "lifted_tag" in the line of the loop + re_lifted_tag = re.compile( + r'\s*' + r'\s*
' + r'\s*' + r'\s*' + r'\s*[0-9]+:' + r'\s*[ ]+for i in range\(x\): # this line is tagged\s*', + re.MULTILINE) + + # Compile int64 version + sig_i64 = (types.int64,) + udt.compile(sig_i64) # compile with lifted loop + cres = udt.overloads[sig_i64] + + # Make html output + buf = StringIO() + cres.type_annotation.html_annotate(buf) + output = buf.getvalue() + buf.close() + + # There should be only one function output. + self.assertEqual(output.count("Function name: udt"), 1) + + sigfmt = "with signature: {} -> pyobject" + self.assertEqual(output.count(sigfmt.format(sig_i64)), 1) + # Ensure the loop is tagged + self.assertEqual(len(re.findall(re_lifted_tag, output)), 1, + msg='%s not found in %s' % (re_lifted_tag, output)) + + # Compile float64 version + sig_f64 = (types.float64,) + udt.compile(sig_f64) + cres = udt.overloads[sig_f64] + + # Make html output + buf = StringIO() + cres.type_annotation.html_annotate(buf) + output = buf.getvalue() + buf.close() + + # There should be two function output + self.assertEqual(output.count("Function name: udt"), 2) + self.assertEqual(output.count(sigfmt.format(sig_i64)), 1) + self.assertEqual(output.count(sigfmt.format(sig_f64)), 1) + # Ensure the loop is tagged in both output + self.assertEqual(len(re.findall(re_lifted_tag, output)), 2) + + @unittest.skipIf(pygments is None, "please install the 'pygments' package") + def test_pretty_print(self): + + @numba.njit + def foo(x, y): + return x, y + + foo(1, 2) + # Exercise the method + foo.inspect_types(pretty=True) + + # Exercise but supply a not None file kwarg, this is invalid + with self.assertRaises(ValueError) as raises: + foo.inspect_types(pretty=True, file='should be None') + self.assertIn('`file` must be None if `pretty=True`', + str(raises.exception)) + + +class TestTypeAnnotation(unittest.TestCase): + + def findpatloc(self, lines, pat): + for i, ln in enumerate(lines): + if pat in ln: + return i + raise ValueError("can't find {!r}".format(pat)) + + def getlines(self, func): + strbuf = StringIO() + func.inspect_types(strbuf) + return strbuf.getvalue().splitlines() + + def test_delete(self): + @numba.njit + def foo(appleorange, berrycherry): + return appleorange + berrycherry + + foo(1, 2) + + lines = self.getlines(foo) + + # Ensure deletion show up after their use + sa = self.findpatloc(lines, 'appleorange = arg(0, name=appleorange)') + sb = self.findpatloc(lines, 'berrycherry = arg(1, name=berrycherry)') + + ea = self.findpatloc(lines, 'del appleorange') + eb = self.findpatloc(lines, 'del berrycherry') + + self.assertLess(sa, ea) + self.assertLess(sb, eb) + + def _lifetimes_impl(self, extend): + with override_config('EXTEND_VARIABLE_LIFETIMES', extend): + @njit + def foo(a): + b = a + return b + x = 10 + b = foo(x) + self.assertEqual(b, x) + + lines = self.getlines(foo) + + sa = self.findpatloc(lines, 'a = arg(0, name=a)') + sb = self.findpatloc(lines, 'b = a') + + cast_ret = self.findpatloc(lines, 'cast(value=b)') + + dela = self.findpatloc(lines, 'del a') + delb = self.findpatloc(lines, 'del b') + + return sa, sb, cast_ret, dela, delb + + def test_delete_standard_lifetimes(self): + # without extended lifetimes, dels occur as soon as dead + # + # label 0 + # a = arg(0, name=a) :: int64 + # b = a :: int64 + # del a + # $8return_value.2 = cast(value=b) :: int64 + # del b + # return $8return_value.2 + + sa, sb, cast_ret, dela, delb = self._lifetimes_impl(extend=0) + + self.assertLess(sa, dela) + self.assertLess(sb, delb) + # del a is before cast and del b is after + self.assertLess(dela, cast_ret) + self.assertGreater(delb, cast_ret) + + def test_delete_extended_lifetimes(self): + # with extended lifetimes, dels are last in block: + # + # label 0 + # a = arg(0, name=a) :: int64 + # b = a :: int64 + # $8return_value.2 = cast(value=b) :: int64 + # del a + # del b + # return $8return_value.2 + + sa, sb, cast_ret, dela, delb = self._lifetimes_impl(extend=1) + + self.assertLess(sa, dela) + self.assertLess(sb, delb) + # dels are after the cast + self.assertGreater(dela, cast_ret) + self.assertGreater(delb, cast_ret) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/2c/2c0535db8beb372562531c95396802451d27e20636af2fcc38307706098becfa/_is_any_true_native.h b/shared/package-files/2c/2c0535db8beb372562531c95396802451d27e20636af2fcc38307706098becfa/_is_any_true_native.h new file mode 100644 index 0000000000000000000000000000000000000000..d49a2682673648b539750ae39e5298329a1a9a86 --- /dev/null +++ b/shared/package-files/2c/2c0535db8beb372562531c95396802451d27e20636af2fcc38307706098becfa/_is_any_true_native.h @@ -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 _is_any_true(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/2c/2c0c13d03639caa958876d2134c611d7e38abbc03d18dc3e4db51f23ca6f8253/mips.py b/shared/package-files/2c/2c0c13d03639caa958876d2134c611d7e38abbc03d18dc3e4db51f23ca6f8253/mips.py new file mode 100644 index 0000000000000000000000000000000000000000..a0973804571b1404400e0749533a001d0833f905 --- /dev/null +++ b/shared/package-files/2c/2c0c13d03639caa958876d2134c611d7e38abbc03d18dc3e4db51f23ca6f8253/mips.py @@ -0,0 +1,54 @@ +from numpy.distutils.cpuinfo import cpu +from numpy.distutils.fcompiler import FCompiler + +compilers = ['MIPSFCompiler'] + +class MIPSFCompiler(FCompiler): + + compiler_type = 'mips' + description = 'MIPSpro Fortran Compiler' + version_pattern = r'MIPSpro Compilers: Version (?P[^\s*,]*)' + + executables = { + 'version_cmd' : ["", "-version"], + 'compiler_f77' : ["f77", "-f77"], + 'compiler_fix' : ["f90", "-fixedform"], + 'compiler_f90' : ["f90"], + 'linker_so' : ["f90", "-shared"], + 'archiver' : ["ar", "-cr"], + 'ranlib' : None + } + module_dir_switch = None #XXX: fix me + module_include_switch = None #XXX: fix me + pic_flags = ['-KPIC'] + + def get_flags(self): + return self.pic_flags + ['-n32'] + def get_flags_opt(self): + return ['-O3'] + def get_flags_arch(self): + opt = [] + for a in '19 20 21 22_4k 22_5k 24 25 26 27 28 30 32_5k 32_10k'.split(): + if getattr(cpu, 'is_IP%s'%a)(): + opt.append('-TARG:platform=IP%s' % a) + break + return opt + def get_flags_arch_f77(self): + r = None + if cpu.is_r10000(): r = 10000 + elif cpu.is_r12000(): r = 12000 + elif cpu.is_r8000(): r = 8000 + elif cpu.is_r5000(): r = 5000 + elif cpu.is_r4000(): r = 4000 + if r is not None: + return ['r%s' % (r)] + return [] + def get_flags_arch_f90(self): + r = self.get_flags_arch_f77() + if r: + r[0] = '-' + r[0] + return r + +if __name__ == '__main__': + from numpy.distutils import customized_fcompiler + print(customized_fcompiler(compiler='mips').get_version()) diff --git a/shared/package-files/2c/2c1a4e12fe31c5470be41ef015235add4c84efadbe1224976f528f40d2b0c025/Merida b/shared/package-files/2c/2c1a4e12fe31c5470be41ef015235add4c84efadbe1224976f528f40d2b0c025/Merida new file mode 100644 index 0000000000000000000000000000000000000000..e5c7d8cc2d2a986374f35561d8b629110b481a66 Binary files /dev/null and b/shared/package-files/2c/2c1a4e12fe31c5470be41ef015235add4c84efadbe1224976f528f40d2b0c025/Merida differ diff --git a/shared/package-files/2c/2c1a9427f689c06155ec83ed5338676f26215293b9f42393bfd8010bf7d6d931/ts_autograd_functions.h b/shared/package-files/2c/2c1a9427f689c06155ec83ed5338676f26215293b9f42393bfd8010bf7d6d931/ts_autograd_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..7e01724470384497a5fcdc9102d4b06403bdc640 --- /dev/null +++ b/shared/package-files/2c/2c1a9427f689c06155ec83ed5338676f26215293b9f42393bfd8010bf7d6d931/ts_autograd_functions.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +namespace torch { +namespace lazy { + +struct MaxPool3dAutogradFunctionTS + : public torch::autograd::Function { + static at::Tensor forward( + torch::autograd::AutogradContext* ctx, + at::Tensor self, + at::IntArrayRef kernel_size, + at::IntArrayRef stride, + at::IntArrayRef padding, + at::IntArrayRef dilation, + bool ceil_mode); + static torch::autograd::variable_list backward( + torch::autograd::AutogradContext* ctx, + torch::autograd::variable_list grad_output); +}; + +} // namespace lazy +} // namespace torch diff --git a/shared/package-files/2c/2c1e79d5b69f8ce9fe9191431b6fb8062f7b5b5d96840703e15a48d236169e5a/_num_threads.cpython-310-x86_64-linux-gnu.so b/shared/package-files/2c/2c1e79d5b69f8ce9fe9191431b6fb8062f7b5b5d96840703e15a48d236169e5a/_num_threads.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7c4fc43ebb6c349da50f104f01cdad2f84c42edf Binary files /dev/null and b/shared/package-files/2c/2c1e79d5b69f8ce9fe9191431b6fb8062f7b5b5d96840703e15a48d236169e5a/_num_threads.cpython-310-x86_64-linux-gnu.so differ diff --git a/shared/package-files/2c/2c1fc0f9c249f41749e976ca16253eae24b63bb5c3ad733933500bf40537e349/eq_meta_dispatch.h b/shared/package-files/2c/2c1fc0f9c249f41749e976ca16253eae24b63bb5c3ad733933500bf40537e349/eq_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ee920d04ed4f4443863897fb7b48bc4d8792a0cb --- /dev/null +++ b/shared/package-files/2c/2c1fc0f9c249f41749e976ca16253eae24b63bb5c3ad733933500bf40537e349/eq_meta_dispatch.h @@ -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 meta { + +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 meta +} // namespace at diff --git a/shared/package-files/2c/2c21bb290de160dcef04718d7f727e2770ec81e711f26894976b8e498e14a76b/cumprod_backward_ops.h b/shared/package-files/2c/2c21bb290de160dcef04718d7f727e2770ec81e711f26894976b8e498e14a76b/cumprod_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..74e54910b0e1e4efe117c4b8ca6544e4712991ce --- /dev/null +++ b/shared/package-files/2c/2c21bb290de160dcef04718d7f727e2770ec81e711f26894976b8e498e14a76b/cumprod_backward_ops.h @@ -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 cumprod_backward { + using schema = at::Tensor (const 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::cumprod_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cumprod_backward(Tensor grad, Tensor input, int dim, Tensor output) -> Tensor") + static at::Tensor call(const at::Tensor & grad, const at::Tensor & input, int64_t dim, const at::Tensor & output); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & input, int64_t dim, const at::Tensor & output); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/2c/2c241505516ca5a9dada48aa767b16a48cb9b44e262df4d934b19ba8f77dbae4/lme01.csv b/shared/package-files/2c/2c241505516ca5a9dada48aa767b16a48cb9b44e262df4d934b19ba8f77dbae4/lme01.csv new file mode 100644 index 0000000000000000000000000000000000000000..3ddba5bad170fc0525280920d5ac9318453ac189 --- /dev/null +++ b/shared/package-files/2c/2c241505516ca5a9dada48aa767b16a48cb9b44e262df4d934b19ba8f77dbae4/lme01.csv @@ -0,0 +1,255 @@ +groups,endog,exog_fe_0,exog_re_0 +0.000,0.485,0.129,1.000 +0.000,-3.069,1.252,1.000 +0.000,4.493,-0.152,1.000 +0.000,1.120,-0.743,1.000 +1.000,1.500,-0.012,1.000 +1.000,-0.081,0.301,1.000 +1.000,3.118,1.558,1.000 +2.000,2.614,0.617,1.000 +2.000,-0.171,-1.841,1.000 +2.000,-0.530,-1.249,1.000 +3.000,2.758,0.413,1.000 +3.000,1.782,0.264,1.000 +3.000,-0.886,-1.219,1.000 +4.000,-2.224,-0.713,1.000 +4.000,-0.616,0.195,1.000 +4.000,-5.375,2.514,1.000 +5.000,-1.631,1.394,1.000 +5.000,1.609,0.052,1.000 +5.000,2.378,-0.765,1.000 +5.000,-2.255,2.450,1.000 +6.000,-0.187,2.180,1.000 +6.000,-3.278,1.358,1.000 +6.000,0.376,-1.205,1.000 +7.000,-2.139,0.844,1.000 +7.000,1.653,-1.600,1.000 +7.000,-2.595,-1.068,1.000 +7.000,4.625,-1.433,1.000 +8.000,-1.756,-0.820,1.000 +9.000,-0.902,-0.317,1.000 +9.000,-0.262,-0.257,1.000 +10.000,-0.772,-0.702,1.000 +10.000,-4.059,0.476,1.000 +11.000,0.605,-0.087,1.000 +11.000,2.762,0.215,1.000 +12.000,-3.884,-0.952,1.000 +12.000,-0.360,-1.344,1.000 +13.000,1.551,-0.544,1.000 +13.000,-1.154,2.204,1.000 +13.000,-4.254,0.851,1.000 +13.000,-0.282,1.001,1.000 +14.000,0.303,1.423,1.000 +14.000,-4.621,0.548,1.000 +15.000,-4.256,2.048,1.000 +15.000,0.421,0.855,1.000 +16.000,-2.268,0.155,1.000 +16.000,-1.960,0.184,1.000 +16.000,5.805,-0.813,1.000 +16.000,1.274,1.063,1.000 +17.000,-2.424,1.155,1.000 +17.000,1.322,-0.605,1.000 +17.000,-2.933,0.936,1.000 +18.000,-2.180,-0.330,1.000 +19.000,2.098,-1.131,1.000 +19.000,-1.206,0.469,1.000 +20.000,3.930,-1.021,1.000 +21.000,-6.211,1.129,1.000 +21.000,0.135,0.001,1.000 +21.000,-3.799,-0.407,1.000 +22.000,1.136,-0.481,1.000 +23.000,4.401,-1.790,1.000 +23.000,1.007,-0.728,1.000 +24.000,1.638,0.395,1.000 +24.000,-1.234,0.995,1.000 +24.000,-1.178,-0.769,1.000 +24.000,-1.585,1.275,1.000 +25.000,1.253,-0.021,1.000 +25.000,0.803,0.618,1.000 +25.000,-0.136,-1.707,1.000 +26.000,-1.361,0.478,1.000 +26.000,-0.496,0.956,1.000 +26.000,3.948,-1.844,1.000 +26.000,-2.658,-0.784,1.000 +27.000,0.994,0.664,1.000 +27.000,-1.074,-1.216,1.000 +27.000,-0.510,1.469,1.000 +28.000,-0.308,-2.067,1.000 +29.000,1.814,-0.600,1.000 +30.000,0.474,-0.313,1.000 +30.000,-0.460,1.343,1.000 +30.000,3.230,-0.908,1.000 +31.000,1.720,-1.078,1.000 +31.000,-1.752,-0.720,1.000 +31.000,2.012,0.001,1.000 +31.000,0.244,-0.159,1.000 +32.000,1.083,1.051,1.000 +32.000,-4.109,1.458,1.000 +32.000,1.854,0.885,1.000 +33.000,6.614,-1.972,1.000 +34.000,-0.723,-0.578,1.000 +34.000,0.758,0.471,1.000 +35.000,-0.961,-0.529,1.000 +35.000,-2.384,0.558,1.000 +35.000,-2.451,2.146,1.000 +35.000,-1.053,0.286,1.000 +36.000,0.234,-1.027,1.000 +37.000,0.638,-1.547,1.000 +37.000,4.220,-0.840,1.000 +37.000,1.111,0.750,1.000 +38.000,-2.770,0.327,1.000 +38.000,2.867,-0.881,1.000 +38.000,0.872,-0.300,1.000 +38.000,0.449,1.746,1.000 +39.000,-4.268,0.253,1.000 +39.000,1.114,0.861,1.000 +39.000,-0.114,0.308,1.000 +40.000,-2.193,0.580,1.000 +40.000,3.547,-1.526,1.000 +40.000,5.288,-1.517,1.000 +41.000,-0.179,-0.132,1.000 +41.000,0.380,-1.089,1.000 +41.000,-0.723,1.797,1.000 +41.000,0.363,1.036,1.000 +42.000,-2.315,-0.880,1.000 +42.000,-4.394,1.640,1.000 +42.000,-1.120,-1.215,1.000 +43.000,-0.587,1.151,1.000 +44.000,-2.922,0.609,1.000 +44.000,0.478,-0.942,1.000 +44.000,-1.395,0.888,1.000 +44.000,-4.636,0.334,1.000 +45.000,-0.716,-0.043,1.000 +45.000,-1.082,0.616,1.000 +45.000,0.643,-0.115,1.000 +45.000,4.590,-0.430,1.000 +46.000,2.399,-2.143,1.000 +46.000,-0.213,2.303,1.000 +46.000,-0.151,-1.121,1.000 +47.000,2.052,-0.690,1.000 +47.000,-2.222,-0.251,1.000 +47.000,1.754,-2.730,1.000 +47.000,-3.498,0.826,1.000 +48.000,-0.880,-0.590,1.000 +48.000,-1.795,-0.060,1.000 +48.000,-3.200,0.459,1.000 +48.000,-1.208,0.311,1.000 +49.000,0.158,-0.990,1.000 +49.000,-0.603,0.044,1.000 +49.000,0.159,1.989,1.000 +49.000,1.706,-0.053,1.000 +50.000,-1.266,0.585,1.000 +50.000,-0.897,1.095,1.000 +51.000,-1.963,1.529,1.000 +52.000,1.650,0.617,1.000 +52.000,1.047,0.406,1.000 +52.000,2.128,-1.883,1.000 +53.000,2.635,-1.212,1.000 +53.000,-2.784,-1.825,1.000 +53.000,0.769,-1.630,1.000 +54.000,-0.281,0.014,1.000 +54.000,-1.039,0.631,1.000 +55.000,1.522,-0.071,1.000 +56.000,-0.949,1.470,1.000 +56.000,2.256,0.464,1.000 +56.000,2.703,0.093,1.000 +56.000,-3.660,0.831,1.000 +57.000,3.933,-2.168,1.000 +57.000,-2.349,0.775,1.000 +57.000,0.358,-1.376,1.000 +58.000,0.164,0.535,1.000 +58.000,0.088,0.725,1.000 +58.000,2.058,-0.655,1.000 +59.000,0.289,-0.872,1.000 +60.000,2.681,-0.296,1.000 +60.000,0.654,-0.087,1.000 +60.000,-0.815,-0.046,1.000 +61.000,-0.439,0.149,1.000 +61.000,0.847,0.329,1.000 +62.000,-0.135,0.395,1.000 +62.000,-1.547,1.004,1.000 +63.000,-2.543,-0.511,1.000 +64.000,-0.389,1.895,1.000 +64.000,4.990,-1.318,1.000 +64.000,0.448,-1.727,1.000 +64.000,0.528,-0.526,1.000 +65.000,-4.634,-1.060,1.000 +66.000,0.324,-1.468,1.000 +66.000,2.237,0.374,1.000 +66.000,0.530,0.084,1.000 +66.000,2.678,-1.159,1.000 +67.000,1.835,0.343,1.000 +68.000,2.721,-1.237,1.000 +68.000,5.082,-0.313,1.000 +68.000,-3.444,1.117,1.000 +68.000,1.246,-0.154,1.000 +69.000,-3.016,2.007,1.000 +70.000,2.145,-0.230,1.000 +71.000,0.594,-0.463,1.000 +72.000,-1.428,2.024,1.000 +72.000,0.156,-0.789,1.000 +72.000,1.816,-1.320,1.000 +73.000,-0.009,1.189,1.000 +74.000,3.159,-1.885,1.000 +74.000,-1.749,-0.614,1.000 +74.000,-1.020,0.960,1.000 +74.000,1.952,-1.254,1.000 +75.000,1.152,1.763,1.000 +75.000,1.666,-1.458,1.000 +75.000,-0.806,-0.377,1.000 +75.000,-1.264,-0.887,1.000 +76.000,1.879,-1.412,1.000 +76.000,1.837,-2.478,1.000 +76.000,-0.121,1.446,1.000 +77.000,-1.041,0.879,1.000 +77.000,0.245,-1.027,1.000 +78.000,-2.157,1.509,1.000 +78.000,-0.423,-0.166,1.000 +78.000,2.190,0.938,1.000 +79.000,0.032,0.581,1.000 +80.000,-0.736,1.585,1.000 +80.000,3.024,-0.429,1.000 +80.000,1.478,-1.844,1.000 +81.000,-0.443,0.742,1.000 +82.000,-3.551,-0.081,1.000 +82.000,-1.661,-0.661,1.000 +83.000,-2.173,0.886,1.000 +84.000,-0.493,-0.885,1.000 +84.000,-4.231,0.402,1.000 +85.000,-3.638,0.220,1.000 +85.000,-3.429,1.221,1.000 +85.000,-0.793,0.953,1.000 +86.000,1.713,-1.221,1.000 +86.000,2.557,-0.486,1.000 +87.000,0.259,-0.429,1.000 +88.000,3.555,-1.209,1.000 +88.000,0.381,-0.199,1.000 +89.000,2.622,-0.837,1.000 +89.000,0.471,0.023,1.000 +89.000,0.655,-0.431,1.000 +90.000,-5.319,2.154,1.000 +90.000,0.547,1.496,1.000 +91.000,-3.216,0.684,1.000 +92.000,-1.078,-0.751,1.000 +92.000,0.313,-0.780,1.000 +92.000,-0.936,0.313,1.000 +93.000,0.853,-1.164,1.000 +93.000,-2.950,0.972,1.000 +94.000,-0.536,0.351,1.000 +94.000,1.233,-0.772,1.000 +94.000,-0.774,-0.510,1.000 +95.000,-0.646,-2.312,1.000 +95.000,0.337,0.469,1.000 +95.000,2.949,-1.056,1.000 +95.000,1.661,-1.251,1.000 +96.000,1.626,-0.252,1.000 +96.000,2.413,-0.638,1.000 +97.000,2.691,-0.940,1.000 +97.000,0.152,-0.677,1.000 +97.000,-1.914,2.931,1.000 +98.000,-3.464,-0.723,1.000 +98.000,-0.201,1.543,1.000 +98.000,0.710,0.569,1.000 +98.000,-0.968,-0.208,1.000 +99.000,1.090,0.572,1.000 +99.000,0.607,0.420,1.000 diff --git a/shared/package-files/2c/2c242adc3aba5440d282356ad6f17c5ad983137174e2fb33ae4aee229b368b81/RECORD b/shared/package-files/2c/2c242adc3aba5440d282356ad6f17c5ad983137174e2fb33ae4aee229b368b81/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..78f2c47474876ba5ee456e31bc7b8e86061f89f1 --- /dev/null +++ b/shared/package-files/2c/2c242adc3aba5440d282356ad6f17c5ad983137174e2fb33ae4aee229b368b81/RECORD @@ -0,0 +1,20 @@ +exceptiongroup-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +exceptiongroup-1.2.0.dist-info/LICENSE,sha256=blBw12UDHgrUA6HL-Qrm0ZoCKPgC4yC3rP9GCqcu1Hw,3704 +exceptiongroup-1.2.0.dist-info/METADATA,sha256=HZmM9fFOVM8mE2DYVKBJYGaC9zgTtqItGx171R8Xui4,6603 +exceptiongroup-1.2.0.dist-info/RECORD,, +exceptiongroup-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +exceptiongroup-1.2.0.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +exceptiongroup-1.2.0.dist-info/direct_url.json,sha256=aRn6RPHrDSa0SIKVC13JweS_jL6Hk2RFH0HK5sbUj1w,74 +exceptiongroup/__init__.py,sha256=7DHS0hDk-RIs3IQc3SbZVB0-1MhiSCJ9XgvEyEloL7M,1049 +exceptiongroup/__pycache__/__init__.cpython-310.pyc,, +exceptiongroup/__pycache__/_catch.cpython-310.pyc,, +exceptiongroup/__pycache__/_exceptions.cpython-310.pyc,, +exceptiongroup/__pycache__/_formatting.cpython-310.pyc,, +exceptiongroup/__pycache__/_suppress.cpython-310.pyc,, +exceptiongroup/__pycache__/_version.cpython-310.pyc,, +exceptiongroup/_catch.py,sha256=kmx01LkEZI5-pmxh9ATEO4vzqAtkn7njV-5Z-F0Kp-I,4669 +exceptiongroup/_exceptions.py,sha256=f-WOXHw-lVWAAZjGY8c-KFxofCvDcEl4XeMDeqcgMyg,11010 +exceptiongroup/_formatting.py,sha256=mumIgRk61thv7wP6WzCpVNsGPhYZGWffJeGzQngFL0s,21005 +exceptiongroup/_suppress.py,sha256=8ymKx5AFcO15F47NfnRI-G98mn4ZBXuyt4qiLd5zD3Q,1338 +exceptiongroup/_version.py,sha256=CilGHycSRzmSEnCMQvTRJ5J_LWxMs---UqkVbOmQ2rA,160 +exceptiongroup/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/shared/package-files/2c/2c2504e89e74f5269d9849df9c11a53b63e9200dafc623157c8719d78af86771/select_copy_native.h b/shared/package-files/2c/2c2504e89e74f5269d9849df9c11a53b63e9200dafc623157c8719d78af86771/select_copy_native.h new file mode 100644 index 0000000000000000000000000000000000000000..9179e7e3e4599013de49c723c8838e9d9a72e85c --- /dev/null +++ b/shared/package-files/2c/2c2504e89e74f5269d9849df9c11a53b63e9200dafc623157c8719d78af86771/select_copy_native.h @@ -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 & select_copy_int_out_symint(const at::Tensor & self, int64_t dim, c10::SymInt index, at::Tensor & out); +TORCH_API at::Tensor select_copy_sparse_csr(const at::Tensor & self, int64_t dim, int64_t index); +TORCH_API at::Tensor select_copy_symint(const at::Tensor & self, int64_t dim, c10::SymInt index); +} // namespace native +} // namespace at diff --git a/shared/package-files/2c/2c256f4c754f9e085b3a86d22a307ceb8ec455a1d351b88fca517e6ffbfa13f6/util.py b/shared/package-files/2c/2c256f4c754f9e085b3a86d22a307ceb8ec455a1d351b88fca517e6ffbfa13f6/util.py new file mode 100644 index 0000000000000000000000000000000000000000..72b46cc481f54d4eb783bdfb422665337b9276b1 --- /dev/null +++ b/shared/package-files/2c/2c256f4c754f9e085b3a86d22a307ceb8ec455a1d351b88fca517e6ffbfa13f6/util.py @@ -0,0 +1,397 @@ +import os +import shutil +import subprocess +import sys + +# find_library(name) returns the pathname of a library, or None. +if os.name == "nt": + + def _get_build_version(): + """Return the version of MSVC that was used to build Python. + + For Python 2.3 and up, the version number is included in + sys.version. For earlier versions, assume the compiler is MSVC 6. + """ + # This function was copied from Lib/distutils/msvccompiler.py + prefix = "MSC v." + i = sys.version.find(prefix) + if i == -1: + return 6 + i = i + len(prefix) + s, rest = sys.version[i:].split(" ", 1) + majorVersion = int(s[:-2]) - 6 + if majorVersion >= 13: + majorVersion += 1 + minorVersion = int(s[2:3]) / 10.0 + # I don't think paths are affected by minor version in version 6 + if majorVersion == 6: + minorVersion = 0 + if majorVersion >= 6: + return majorVersion + minorVersion + # else we don't know what version of the compiler this is + return None + + def find_msvcrt(): + """Return the name of the VC runtime dll""" + version = _get_build_version() + if version is None: + # better be safe than sorry + return None + if version <= 6: + clibname = 'msvcrt' + elif version <= 13: + clibname = 'msvcr%d' % (version * 10) + else: + # CRT is no longer directly loadable. See issue23606 for the + # discussion about alternative approaches. + return None + + # If python was built with in debug mode + import importlib.machinery + if '_d.pyd' in importlib.machinery.EXTENSION_SUFFIXES: + clibname += 'd' + return clibname+'.dll' + + def find_library(name): + if name in ('c', 'm'): + return find_msvcrt() + # See MSDN for the REAL search order. + for directory in os.environ['PATH'].split(os.pathsep): + fname = os.path.join(directory, name) + if os.path.isfile(fname): + return fname + if fname.lower().endswith(".dll"): + continue + fname = fname + ".dll" + if os.path.isfile(fname): + return fname + return None + +elif os.name == "posix" and sys.platform == "darwin": + from ctypes.macholib.dyld import dyld_find as _dyld_find + def find_library(name): + possible = ['@executable_path/../lib/lib%s.dylib' % name, + 'lib%s.dylib' % name, + '%s.dylib' % name, + '%s.framework/%s' % (name, name)] + for name in possible: + try: + return _dyld_find(name) + except ValueError: + continue + return None + +elif sys.platform.startswith("aix"): + # AIX has two styles of storing shared libraries + # GNU auto_tools refer to these as svr4 and aix + # svr4 (System V Release 4) is a regular file, often with .so as suffix + # AIX style uses an archive (suffix .a) with members (e.g., shr.o, libssl.so) + # see issue#26439 and _aix.py for more details + + from ctypes._aix import find_library + +elif os.name == "posix": + # Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump + import re, tempfile + + def _is_elf(filename): + "Return True if the given file is an ELF file" + elf_header = b'\x7fELF' + with open(filename, 'br') as thefile: + return thefile.read(4) == elf_header + + def _findLib_gcc(name): + # Run GCC's linker with the -t (aka --trace) option and examine the + # library name it prints out. The GCC command will fail because we + # haven't supplied a proper program with main(), but that does not + # matter. + expr = os.fsencode(r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)) + + c_compiler = shutil.which('gcc') + if not c_compiler: + c_compiler = shutil.which('cc') + if not c_compiler: + # No C compiler available, give up + return None + + temp = tempfile.NamedTemporaryFile() + try: + args = [c_compiler, '-Wl,-t', '-o', temp.name, '-l' + name] + + env = dict(os.environ) + env['LC_ALL'] = 'C' + env['LANG'] = 'C' + try: + proc = subprocess.Popen(args, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env) + except OSError: # E.g. bad executable + return None + with proc: + trace = proc.stdout.read() + finally: + try: + temp.close() + except FileNotFoundError: + # Raised if the file was already removed, which is the normal + # behaviour of GCC if linking fails + pass + res = re.findall(expr, trace) + if not res: + return None + + for file in res: + # Check if the given file is an elf file: gcc can report + # some files that are linker scripts and not actual + # shared objects. See bpo-41976 for more details + if not _is_elf(file): + continue + return os.fsdecode(file) + + + if sys.platform == "sunos5": + # use /usr/ccs/bin/dump on solaris + def _get_soname(f): + if not f: + return None + + try: + proc = subprocess.Popen(("/usr/ccs/bin/dump", "-Lpv", f), + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + except OSError: # E.g. command not found + return None + with proc: + data = proc.stdout.read() + res = re.search(br'\[.*\]\sSONAME\s+([^\s]+)', data) + if not res: + return None + return os.fsdecode(res.group(1)) + else: + def _get_soname(f): + # assuming GNU binutils / ELF + if not f: + return None + objdump = shutil.which('objdump') + if not objdump: + # objdump is not available, give up + return None + + try: + proc = subprocess.Popen((objdump, '-p', '-j', '.dynamic', f), + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + except OSError: # E.g. bad executable + return None + with proc: + dump = proc.stdout.read() + res = re.search(br'\sSONAME\s+([^\s]+)', dump) + if not res: + return None + return os.fsdecode(res.group(1)) + + if sys.platform.startswith(("freebsd", "openbsd", "dragonfly")): + + def _num_version(libname): + # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ] + parts = libname.split(b".") + nums = [] + try: + while parts: + nums.insert(0, int(parts.pop())) + except ValueError: + pass + return nums or [sys.maxsize] + + def find_library(name): + ename = re.escape(name) + expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename) + expr = os.fsencode(expr) + + try: + proc = subprocess.Popen(('/sbin/ldconfig', '-r'), + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + except OSError: # E.g. command not found + data = b'' + else: + with proc: + data = proc.stdout.read() + + res = re.findall(expr, data) + if not res: + return _get_soname(_findLib_gcc(name)) + res.sort(key=_num_version) + return os.fsdecode(res[-1]) + + elif sys.platform == "sunos5": + + def _findLib_crle(name, is64): + if not os.path.exists('/usr/bin/crle'): + return None + + env = dict(os.environ) + env['LC_ALL'] = 'C' + + if is64: + args = ('/usr/bin/crle', '-64') + else: + args = ('/usr/bin/crle',) + + paths = None + try: + proc = subprocess.Popen(args, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + env=env) + except OSError: # E.g. bad executable + return None + with proc: + for line in proc.stdout: + line = line.strip() + if line.startswith(b'Default Library Path (ELF):'): + paths = os.fsdecode(line).split()[4] + + if not paths: + return None + + for dir in paths.split(":"): + libfile = os.path.join(dir, "lib%s.so" % name) + if os.path.exists(libfile): + return libfile + + return None + + def find_library(name, is64 = False): + return _get_soname(_findLib_crle(name, is64) or _findLib_gcc(name)) + + else: + + def _findSoname_ldconfig(name): + import struct + if struct.calcsize('l') == 4: + machine = os.uname().machine + '-32' + else: + machine = os.uname().machine + '-64' + mach_map = { + 'x86_64-64': 'libc6,x86-64', + 'ppc64-64': 'libc6,64bit', + 'sparc64-64': 'libc6,64bit', + 's390x-64': 'libc6,64bit', + 'ia64-64': 'libc6,IA-64', + } + abi_type = mach_map.get(machine, 'libc6') + + # XXX assuming GLIBC's ldconfig (with option -p) + regex = r'\s+(lib%s\.[^\s]+)\s+\(%s' + regex = os.fsencode(regex % (re.escape(name), abi_type)) + try: + with subprocess.Popen(['/sbin/ldconfig', '-p'], + stdin=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + stdout=subprocess.PIPE, + env={'LC_ALL': 'C', 'LANG': 'C'}) as p: + res = re.search(regex, p.stdout.read()) + if res: + return os.fsdecode(res.group(1)) + except OSError: + pass + + def _findLib_ld(name): + # See issue #9998 for why this is needed + expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) + cmd = ['ld', '-t'] + libpath = os.environ.get('LD_LIBRARY_PATH') + if libpath: + for d in libpath.split(':'): + cmd.extend(['-L', d]) + cmd.extend(['-o', os.devnull, '-l%s' % name]) + result = None + try: + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) + out, _ = p.communicate() + res = re.findall(expr, os.fsdecode(out)) + for file in res: + # Check if the given file is an elf file: gcc can report + # some files that are linker scripts and not actual + # shared objects. See bpo-41976 for more details + if not _is_elf(file): + continue + return os.fsdecode(file) + except Exception: + pass # result will be None + return result + + def _findLib_prefix(name): + if not name: + return None + for fullname in (name, "lib%s.so" % (name)): + path = os.path.join(sys.prefix, 'lib', fullname) + if os.path.exists(path): + return path + return None + + def find_library(name): + # See issue #9998 + # Yes calling _findLib_prefix twice is deliberate, because _get_soname ditches + # the full path. + # When objdump is unavailable this returns None + so_name = _get_soname(_findLib_prefix(name)) or name + if so_name != name: + return _findLib_prefix(so_name) or \ + _findLib_prefix(name) or \ + _findSoname_ldconfig(name) or \ + _get_soname(_findLib_gcc(name)) or _get_soname(_findLib_ld(name)) + else: + return _findLib_prefix(name) or \ + _findSoname_ldconfig(name) or \ + _get_soname(_findLib_gcc(name)) or _get_soname(_findLib_ld(name)) + +################################################################ +# test code + +def test(): + from ctypes import cdll + if os.name == "nt": + print(cdll.msvcrt) + print(cdll.load("msvcrt")) + print(find_library("msvcrt")) + + if os.name == "posix": + # find and load_version + print(find_library("m")) + print(find_library("c")) + print(find_library("bz2")) + + # load + if sys.platform == "darwin": + print(cdll.LoadLibrary("libm.dylib")) + print(cdll.LoadLibrary("libcrypto.dylib")) + print(cdll.LoadLibrary("libSystem.dylib")) + print(cdll.LoadLibrary("System.framework/System")) + # issue-26439 - fix broken test call for AIX + elif sys.platform.startswith("aix"): + from ctypes import CDLL + if sys.maxsize < 2**32: + print(f"Using CDLL(name, os.RTLD_MEMBER): {CDLL('libc.a(shr.o)', os.RTLD_MEMBER)}") + print(f"Using cdll.LoadLibrary(): {cdll.LoadLibrary('libc.a(shr.o)')}") + # librpm.so is only available as 32-bit shared library + print(find_library("rpm")) + print(cdll.LoadLibrary("librpm.so")) + else: + print(f"Using CDLL(name, os.RTLD_MEMBER): {CDLL('libc.a(shr_64.o)', os.RTLD_MEMBER)}") + print(f"Using cdll.LoadLibrary(): {cdll.LoadLibrary('libc.a(shr_64.o)')}") + print(f"crypt\t:: {find_library('crypt')}") + print(f"crypt\t:: {cdll.LoadLibrary(find_library('crypt'))}") + print(f"crypto\t:: {find_library('crypto')}") + print(f"crypto\t:: {cdll.LoadLibrary(find_library('crypto'))}") + else: + print(cdll.LoadLibrary("libm.so")) + print(cdll.LoadLibrary("libcrypt.so")) + print(find_library("crypt")) + +if __name__ == "__main__": + test() diff --git a/shared/package-files/2c/2c2b2b0888ee85c133fb2c378329399d828d88c17587c7a7ea740ed61853cb01/generic.py b/shared/package-files/2c/2c2b2b0888ee85c133fb2c378329399d828d88c17587c7a7ea740ed61853cb01/generic.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e314046fb749e7d32bf7fc76ca22eb1194a328 --- /dev/null +++ b/shared/package-files/2c/2c2b2b0888ee85c133fb2c378329399d828d88c17587c7a7ea740ed61853cb01/generic.py @@ -0,0 +1,2852 @@ +""" +Define the SeriesGroupBy and DataFrameGroupBy +classes that hold the groupby interfaces (and some implementations). + +These are user facing as the result of the ``df.groupby(...)`` operations, +which here returns a DataFrameGroupBy object. +""" +from __future__ import annotations + +from collections import abc +from functools import partial +from textwrap import dedent +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Literal, + NamedTuple, + TypeVar, + Union, + cast, +) +import warnings + +import numpy as np + +from pandas._libs import ( + Interval, + lib, +) +from pandas._libs.hashtable import duplicated +from pandas.errors import SpecificationError +from pandas.util._decorators import ( + Appender, + Substitution, + doc, +) +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.common import ( + ensure_int64, + is_bool, + is_dict_like, + is_integer_dtype, + is_list_like, + is_numeric_dtype, + is_scalar, +) +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + IntervalDtype, +) +from pandas.core.dtypes.inference import is_hashable +from pandas.core.dtypes.missing import ( + isna, + notna, +) + +from pandas.core import algorithms +from pandas.core.apply import ( + GroupByApply, + maybe_mangle_lambdas, + reconstruct_func, + validate_func_kwargs, + warn_alias_replacement, +) +import pandas.core.common as com +from pandas.core.frame import DataFrame +from pandas.core.groupby import ( + base, + ops, +) +from pandas.core.groupby.groupby import ( + GroupBy, + GroupByPlot, + _agg_template_frame, + _agg_template_series, + _apply_docs, + _transform_template, +) +from pandas.core.indexes.api import ( + Index, + MultiIndex, + all_indexes_same, + default_index, +) +from pandas.core.series import Series +from pandas.core.sorting import get_group_index +from pandas.core.util.numba_ import maybe_use_numba + +from pandas.plotting import boxplot_frame_groupby + +if TYPE_CHECKING: + from collections.abc import ( + Hashable, + Mapping, + Sequence, + ) + + from pandas._typing import ( + ArrayLike, + Axis, + AxisInt, + CorrelationMethod, + FillnaOptions, + IndexLabel, + Manager, + Manager2D, + SingleManager, + TakeIndexer, + ) + + from pandas import Categorical + from pandas.core.generic import NDFrame + +# TODO(typing) the return value on this callable should be any *scalar*. +AggScalar = Union[str, Callable[..., Any]] +# TODO: validate types on ScalarResult and move to _typing +# Blocked from using by https://github.com/python/mypy/issues/1484 +# See note at _mangle_lambda_list +ScalarResult = TypeVar("ScalarResult") + + +class NamedAgg(NamedTuple): + """ + Helper for column specific aggregation with control over output column names. + + Subclass of typing.NamedTuple. + + Parameters + ---------- + column : Hashable + Column label in the DataFrame to apply aggfunc. + aggfunc : function or str + Function to apply to the provided column. If string, the name of a built-in + pandas function. + + Examples + -------- + >>> df = pd.DataFrame({"key": [1, 1, 2], "a": [-1, 0, 1], 1: [10, 11, 12]}) + >>> agg_a = pd.NamedAgg(column="a", aggfunc="min") + >>> agg_1 = pd.NamedAgg(column=1, aggfunc=lambda x: np.mean(x)) + >>> df.groupby("key").agg(result_a=agg_a, result_1=agg_1) + result_a result_1 + key + 1 -1 10.5 + 2 1 12.0 + """ + + column: Hashable + aggfunc: AggScalar + + +class SeriesGroupBy(GroupBy[Series]): + def _wrap_agged_manager(self, mgr: Manager) -> Series: + out = self.obj._constructor_from_mgr(mgr, axes=mgr.axes) + out._name = self.obj.name + return out + + def _get_data_to_aggregate( + self, *, numeric_only: bool = False, name: str | None = None + ) -> SingleManager: + ser = self._obj_with_exclusions + single = ser._mgr + if numeric_only and not is_numeric_dtype(ser.dtype): + # GH#41291 match Series behavior + kwd_name = "numeric_only" + raise TypeError( + f"Cannot use {kwd_name}=True with " + f"{type(self).__name__}.{name} and non-numeric dtypes." + ) + return single + + _agg_examples_doc = dedent( + """ + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4]) + + >>> s + 0 1 + 1 2 + 2 3 + 3 4 + dtype: int64 + + >>> s.groupby([1, 1, 2, 2]).min() + 1 1 + 2 3 + dtype: int64 + + >>> s.groupby([1, 1, 2, 2]).agg('min') + 1 1 + 2 3 + dtype: int64 + + >>> s.groupby([1, 1, 2, 2]).agg(['min', 'max']) + min max + 1 1 2 + 2 3 4 + + The output column names can be controlled by passing + the desired column names and aggregations as keyword arguments. + + >>> s.groupby([1, 1, 2, 2]).agg( + ... minimum='min', + ... maximum='max', + ... ) + minimum maximum + 1 1 2 + 2 3 4 + + .. versionchanged:: 1.3.0 + + The resulting dtype will reflect the return value of the aggregating function. + + >>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min()) + 1 1.0 + 2 3.0 + dtype: float64 + """ + ) + + @Appender( + _apply_docs["template"].format( + input="series", examples=_apply_docs["series_examples"] + ) + ) + def apply(self, func, *args, **kwargs) -> Series: + return super().apply(func, *args, **kwargs) + + @doc(_agg_template_series, examples=_agg_examples_doc, klass="Series") + def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): + relabeling = func is None + columns = None + if relabeling: + columns, func = validate_func_kwargs(kwargs) + kwargs = {} + + if isinstance(func, str): + if maybe_use_numba(engine) and engine is not None: + # Not all agg functions support numba, only propagate numba kwargs + # if user asks for numba, and engine is not None + # (if engine is None, the called function will handle the case where + # numba is requested via the global option) + kwargs["engine"] = engine + if engine_kwargs is not None: + kwargs["engine_kwargs"] = engine_kwargs + return getattr(self, func)(*args, **kwargs) + + elif isinstance(func, abc.Iterable): + # Catch instances of lists / tuples + # but not the class list / tuple itself. + func = maybe_mangle_lambdas(func) + kwargs["engine"] = engine + kwargs["engine_kwargs"] = engine_kwargs + ret = self._aggregate_multiple_funcs(func, *args, **kwargs) + if relabeling: + # columns is not narrowed by mypy from relabeling flag + assert columns is not None # for mypy + ret.columns = columns + if not self.as_index: + ret = ret.reset_index() + return ret + + else: + cyfunc = com.get_cython_func(func) + if cyfunc and not args and not kwargs: + warn_alias_replacement(self, func, cyfunc) + return getattr(self, cyfunc)() + + if maybe_use_numba(engine): + return self._aggregate_with_numba( + func, *args, engine_kwargs=engine_kwargs, **kwargs + ) + + if self.ngroups == 0: + # e.g. test_evaluate_with_empty_groups without any groups to + # iterate over, we have no output on which to do dtype + # inference. We default to using the existing dtype. + # xref GH#51445 + obj = self._obj_with_exclusions + return self.obj._constructor( + [], + name=self.obj.name, + index=self._grouper.result_index, + dtype=obj.dtype, + ) + + if self._grouper.nkeys > 1: + return self._python_agg_general(func, *args, **kwargs) + + try: + return self._python_agg_general(func, *args, **kwargs) + except KeyError: + # KeyError raised in test_groupby.test_basic is bc the func does + # a dictionary lookup on group.name, but group name is not + # pinned in _python_agg_general, only in _aggregate_named + result = self._aggregate_named(func, *args, **kwargs) + + warnings.warn( + "Pinning the groupby key to each group in " + f"{type(self).__name__}.agg is deprecated, and cases that " + "relied on it will raise in a future version. " + "If your operation requires utilizing the groupby keys, " + "iterate over the groupby object instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + # result is a dict whose keys are the elements of result_index + result = Series(result, index=self._grouper.result_index) + result = self._wrap_aggregated_output(result) + return result + + agg = aggregate + + def _python_agg_general(self, func, *args, **kwargs): + orig_func = func + func = com.is_builtin_func(func) + if orig_func != func: + alias = com._builtin_table_alias[func] + warn_alias_replacement(self, orig_func, alias) + f = lambda x: func(x, *args, **kwargs) + + obj = self._obj_with_exclusions + result = self._grouper.agg_series(obj, f) + res = obj._constructor(result, name=obj.name) + return self._wrap_aggregated_output(res) + + def _aggregate_multiple_funcs(self, arg, *args, **kwargs) -> DataFrame: + if isinstance(arg, dict): + if self.as_index: + # GH 15931 + raise SpecificationError("nested renamer is not supported") + else: + # GH#50684 - This accidentally worked in 1.x + msg = ( + "Passing a dictionary to SeriesGroupBy.agg is deprecated " + "and will raise in a future version of pandas. Pass a list " + "of aggregations instead." + ) + warnings.warn( + message=msg, + category=FutureWarning, + stacklevel=find_stack_level(), + ) + arg = list(arg.items()) + elif any(isinstance(x, (tuple, list)) for x in arg): + arg = [(x, x) if not isinstance(x, (tuple, list)) else x for x in arg] + else: + # list of functions / function names + columns = (com.get_callable_name(f) or f for f in arg) + arg = zip(columns, arg) + + results: dict[base.OutputKey, DataFrame | Series] = {} + with com.temp_setattr(self, "as_index", True): + # Combine results using the index, need to adjust index after + # if as_index=False (GH#50724) + for idx, (name, func) in enumerate(arg): + key = base.OutputKey(label=name, position=idx) + results[key] = self.aggregate(func, *args, **kwargs) + + if any(isinstance(x, DataFrame) for x in results.values()): + from pandas import concat + + res_df = concat( + results.values(), axis=1, keys=[key.label for key in results] + ) + return res_df + + indexed_output = {key.position: val for key, val in results.items()} + output = self.obj._constructor_expanddim(indexed_output, index=None) + output.columns = Index(key.label for key in results) + + return output + + def _wrap_applied_output( + self, + data: Series, + values: list[Any], + not_indexed_same: bool = False, + is_transform: bool = False, + ) -> DataFrame | Series: + """ + Wrap the output of SeriesGroupBy.apply into the expected result. + + Parameters + ---------- + data : Series + Input data for groupby operation. + values : List[Any] + Applied output for each group. + not_indexed_same : bool, default False + Whether the applied outputs are not indexed the same as the group axes. + + Returns + ------- + DataFrame or Series + """ + if len(values) == 0: + # GH #6265 + if is_transform: + # GH#47787 see test_group_on_empty_multiindex + res_index = data.index + else: + res_index = self._grouper.result_index + + return self.obj._constructor( + [], + name=self.obj.name, + index=res_index, + dtype=data.dtype, + ) + assert values is not None + + if isinstance(values[0], dict): + # GH #823 #24880 + index = self._grouper.result_index + res_df = self.obj._constructor_expanddim(values, index=index) + res_df = self._reindex_output(res_df) + # if self.observed is False, + # keep all-NaN rows created while re-indexing + res_ser = res_df.stack(future_stack=True) + res_ser.name = self.obj.name + return res_ser + elif isinstance(values[0], (Series, DataFrame)): + result = self._concat_objects( + values, + not_indexed_same=not_indexed_same, + is_transform=is_transform, + ) + if isinstance(result, Series): + result.name = self.obj.name + if not self.as_index and not_indexed_same: + result = self._insert_inaxis_grouper(result) + result.index = default_index(len(result)) + return result + else: + # GH #6265 #24880 + result = self.obj._constructor( + data=values, index=self._grouper.result_index, name=self.obj.name + ) + if not self.as_index: + result = self._insert_inaxis_grouper(result) + result.index = default_index(len(result)) + return self._reindex_output(result) + + def _aggregate_named(self, func, *args, **kwargs): + # Note: this is very similar to _aggregate_series_pure_python, + # but that does not pin group.name + result = {} + initialized = False + + for name, group in self._grouper.get_iterator( + self._obj_with_exclusions, axis=self.axis + ): + # needed for pandas/tests/groupby/test_groupby.py::test_basic_aggregations + object.__setattr__(group, "name", name) + + output = func(group, *args, **kwargs) + output = ops.extract_result(output) + if not initialized: + # We only do this validation on the first iteration + ops.check_result_array(output, group.dtype) + initialized = True + result[name] = output + + return result + + __examples_series_doc = dedent( + """ + >>> ser = pd.Series([390.0, 350.0, 30.0, 20.0], + ... index=["Falcon", "Falcon", "Parrot", "Parrot"], + ... name="Max Speed") + >>> grouped = ser.groupby([1, 1, 2, 2]) + >>> grouped.transform(lambda x: (x - x.mean()) / x.std()) + Falcon 0.707107 + Falcon -0.707107 + Parrot 0.707107 + Parrot -0.707107 + Name: Max Speed, dtype: float64 + + Broadcast result of the transformation + + >>> grouped.transform(lambda x: x.max() - x.min()) + Falcon 40.0 + Falcon 40.0 + Parrot 10.0 + Parrot 10.0 + Name: Max Speed, dtype: float64 + + >>> grouped.transform("mean") + Falcon 370.0 + Falcon 370.0 + Parrot 25.0 + Parrot 25.0 + Name: Max Speed, dtype: float64 + + .. versionchanged:: 1.3.0 + + The resulting dtype will reflect the return value of the passed ``func``, + for example: + + >>> grouped.transform(lambda x: x.astype(int).max()) + Falcon 390 + Falcon 390 + Parrot 30 + Parrot 30 + Name: Max Speed, dtype: int64 + """ + ) + + @Substitution(klass="Series", example=__examples_series_doc) + @Appender(_transform_template) + def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): + return self._transform( + func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ) + + def _cython_transform( + self, how: str, numeric_only: bool = False, axis: AxisInt = 0, **kwargs + ): + assert axis == 0 # handled by caller + + obj = self._obj_with_exclusions + + try: + result = self._grouper._cython_operation( + "transform", obj._values, how, axis, **kwargs + ) + except NotImplementedError as err: + # e.g. test_groupby_raises_string + raise TypeError(f"{how} is not supported for {obj.dtype} dtype") from err + + return obj._constructor(result, index=self.obj.index, name=obj.name) + + def _transform_general( + self, func: Callable, engine, engine_kwargs, *args, **kwargs + ) -> Series: + """ + Transform with a callable `func`. + """ + if maybe_use_numba(engine): + return self._transform_with_numba( + func, *args, engine_kwargs=engine_kwargs, **kwargs + ) + assert callable(func) + klass = type(self.obj) + + results = [] + for name, group in self._grouper.get_iterator( + self._obj_with_exclusions, axis=self.axis + ): + # this setattr is needed for test_transform_lambda_with_datetimetz + object.__setattr__(group, "name", name) + res = func(group, *args, **kwargs) + + results.append(klass(res, index=group.index)) + + # check for empty "results" to avoid concat ValueError + if results: + from pandas.core.reshape.concat import concat + + concatenated = concat(results) + result = self._set_result_index_ordered(concatenated) + else: + result = self.obj._constructor(dtype=np.float64) + + result.name = self.obj.name + return result + + def filter(self, func, dropna: bool = True, *args, **kwargs): + """ + Filter elements from groups that don't satisfy a criterion. + + Elements from groups are filtered if they do not satisfy the + boolean criterion specified by func. + + Parameters + ---------- + func : function + Criterion to apply to each group. Should return True or False. + dropna : bool + Drop groups that do not pass the filter. True by default; if False, + groups that evaluate False are filled with NaNs. + + Returns + ------- + Series + + Notes + ----- + Functions that mutate the passed object can produce unexpected + behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` + for more details. + + Examples + -------- + >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', + ... 'foo', 'bar'], + ... 'B' : [1, 2, 3, 4, 5, 6], + ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) + >>> grouped = df.groupby('A') + >>> df.groupby('A').B.filter(lambda x: x.mean() > 3.) + 1 2 + 3 4 + 5 6 + Name: B, dtype: int64 + """ + if isinstance(func, str): + wrapper = lambda x: getattr(x, func)(*args, **kwargs) + else: + wrapper = lambda x: func(x, *args, **kwargs) + + # Interpret np.nan as False. + def true_and_notna(x) -> bool: + b = wrapper(x) + return notna(b) and b + + try: + indices = [ + self._get_index(name) + for name, group in self._grouper.get_iterator( + self._obj_with_exclusions, axis=self.axis + ) + if true_and_notna(group) + ] + except (ValueError, TypeError) as err: + raise TypeError("the filter must return a boolean result") from err + + filtered = self._apply_filter(indices, dropna) + return filtered + + def nunique(self, dropna: bool = True) -> Series | DataFrame: + """ + Return number of unique elements in the group. + + Returns + ------- + Series + Number of unique values within each group. + + Examples + -------- + For SeriesGroupby: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 3], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 3 + dtype: int64 + >>> ser.groupby(level=0).nunique() + a 2 + b 1 + dtype: int64 + + For Resampler: + + >>> ser = pd.Series([1, 2, 3, 3], index=pd.DatetimeIndex( + ... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15'])) + >>> ser + 2023-01-01 1 + 2023-01-15 2 + 2023-02-01 3 + 2023-02-15 3 + dtype: int64 + >>> ser.resample('MS').nunique() + 2023-01-01 2 + 2023-02-01 1 + Freq: MS, dtype: int64 + """ + ids, _, ngroups = self._grouper.group_info + val = self.obj._values + codes, uniques = algorithms.factorize(val, use_na_sentinel=dropna, sort=False) + + if self._grouper.has_dropped_na: + mask = ids >= 0 + ids = ids[mask] + codes = codes[mask] + + group_index = get_group_index( + labels=[ids, codes], + shape=(ngroups, len(uniques)), + sort=False, + xnull=dropna, + ) + + if dropna: + mask = group_index >= 0 + if (~mask).any(): + ids = ids[mask] + group_index = group_index[mask] + + mask = duplicated(group_index, "first") + res = np.bincount(ids[~mask], minlength=ngroups) + res = ensure_int64(res) + + ri = self._grouper.result_index + result: Series | DataFrame = self.obj._constructor( + res, index=ri, name=self.obj.name + ) + if not self.as_index: + result = self._insert_inaxis_grouper(result) + result.index = default_index(len(result)) + return self._reindex_output(result, fill_value=0) + + @doc(Series.describe) + def describe(self, percentiles=None, include=None, exclude=None) -> Series: + return super().describe( + percentiles=percentiles, include=include, exclude=exclude + ) + + def value_counts( + self, + normalize: bool = False, + sort: bool = True, + ascending: bool = False, + bins=None, + dropna: bool = True, + ) -> Series | DataFrame: + name = "proportion" if normalize else "count" + + if bins is None: + result = self._value_counts( + normalize=normalize, sort=sort, ascending=ascending, dropna=dropna + ) + result.name = name + return result + + from pandas.core.reshape.merge import get_join_indexers + from pandas.core.reshape.tile import cut + + ids, _, _ = self._grouper.group_info + val = self.obj._values + + index_names = self._grouper.names + [self.obj.name] + + if isinstance(val.dtype, CategoricalDtype) or ( + bins is not None and not np.iterable(bins) + ): + # scalar bins cannot be done at top level + # in a backward compatible way + # GH38672 relates to categorical dtype + ser = self.apply( + Series.value_counts, + normalize=normalize, + sort=sort, + ascending=ascending, + bins=bins, + ) + ser.name = name + ser.index.names = index_names + return ser + + # groupby removes null keys from groupings + mask = ids != -1 + ids, val = ids[mask], val[mask] + + lab: Index | np.ndarray + if bins is None: + lab, lev = algorithms.factorize(val, sort=True) + llab = lambda lab, inc: lab[inc] + else: + # lab is a Categorical with categories an IntervalIndex + cat_ser = cut(Series(val, copy=False), bins, include_lowest=True) + cat_obj = cast("Categorical", cat_ser._values) + lev = cat_obj.categories + lab = lev.take( + cat_obj.codes, + allow_fill=True, + fill_value=lev._na_value, + ) + llab = lambda lab, inc: lab[inc]._multiindex.codes[-1] + + if isinstance(lab.dtype, IntervalDtype): + # TODO: should we do this inside II? + lab_interval = cast(Interval, lab) + + sorter = np.lexsort((lab_interval.left, lab_interval.right, ids)) + else: + sorter = np.lexsort((lab, ids)) + + ids, lab = ids[sorter], lab[sorter] + + # group boundaries are where group ids change + idchanges = 1 + np.nonzero(ids[1:] != ids[:-1])[0] + idx = np.r_[0, idchanges] + if not len(ids): + idx = idchanges + + # new values are where sorted labels change + lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1)) + inc = np.r_[True, lchanges] + if not len(val): + inc = lchanges + inc[idx] = True # group boundaries are also new values + out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts + + # num. of times each group should be repeated + rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx)) + + # multi-index components + codes = self._grouper.reconstructed_codes + codes = [rep(level_codes) for level_codes in codes] + [llab(lab, inc)] + levels = [ping._group_index for ping in self._grouper.groupings] + [lev] + + if dropna: + mask = codes[-1] != -1 + if mask.all(): + dropna = False + else: + out, codes = out[mask], [level_codes[mask] for level_codes in codes] + + if normalize: + out = out.astype("float") + d = np.diff(np.r_[idx, len(ids)]) + if dropna: + m = ids[lab == -1] + np.add.at(d, m, -1) + acc = rep(d)[mask] + else: + acc = rep(d) + out /= acc + + if sort and bins is None: + cat = ids[inc][mask] if dropna else ids[inc] + sorter = np.lexsort((out if ascending else -out, cat)) + out, codes[-1] = out[sorter], codes[-1][sorter] + + if bins is not None: + # for compat. with libgroupby.value_counts need to ensure every + # bin is present at every index level, null filled with zeros + diff = np.zeros(len(out), dtype="bool") + for level_codes in codes[:-1]: + diff |= np.r_[True, level_codes[1:] != level_codes[:-1]] + + ncat, nbin = diff.sum(), len(levels[-1]) + + left = [np.repeat(np.arange(ncat), nbin), np.tile(np.arange(nbin), ncat)] + + right = [diff.cumsum() - 1, codes[-1]] + + # error: Argument 1 to "get_join_indexers" has incompatible type + # "List[ndarray[Any, Any]]"; expected "List[Union[Union[ExtensionArray, + # ndarray[Any, Any]], Index, Series]] + _, idx = get_join_indexers( + left, right, sort=False, how="left" # type: ignore[arg-type] + ) + if idx is not None: + out = np.where(idx != -1, out[idx], 0) + + if sort: + sorter = np.lexsort((out if ascending else -out, left[0])) + out, left[-1] = out[sorter], left[-1][sorter] + + # build the multi-index w/ full levels + def build_codes(lev_codes: np.ndarray) -> np.ndarray: + return np.repeat(lev_codes[diff], nbin) + + codes = [build_codes(lev_codes) for lev_codes in codes[:-1]] + codes.append(left[-1]) + + mi = MultiIndex( + levels=levels, codes=codes, names=index_names, verify_integrity=False + ) + + if is_integer_dtype(out.dtype): + out = ensure_int64(out) + result = self.obj._constructor(out, index=mi, name=name) + if not self.as_index: + result = result.reset_index() + return result + + def fillna( + self, + value: object | ArrayLike | None = None, + method: FillnaOptions | None = None, + axis: Axis | None | lib.NoDefault = lib.no_default, + inplace: bool = False, + limit: int | None = None, + downcast: dict | None | lib.NoDefault = lib.no_default, + ) -> Series | None: + """ + Fill NA/NaN values using the specified method within groups. + + .. deprecated:: 2.2.0 + This method is deprecated and will be removed in a future version. + Use the :meth:`.SeriesGroupBy.ffill` or :meth:`.SeriesGroupBy.bfill` + for forward or backward filling instead. If you want to fill with a + single value, use :meth:`Series.fillna` instead. + + Parameters + ---------- + value : scalar, dict, Series, or DataFrame + Value to use to fill holes (e.g. 0), alternately a + dict/Series/DataFrame of values specifying which value to use for + each index (for a Series) or column (for a DataFrame). Values not + in the dict/Series/DataFrame will not be filled. This value cannot + be a list. Users wanting to use the ``value`` argument and not ``method`` + should prefer :meth:`.Series.fillna` as this + will produce the same result and be more performant. + method : {{'bfill', 'ffill', None}}, default None + Method to use for filling holes. ``'ffill'`` will propagate + the last valid observation forward within a group. + ``'bfill'`` will use next valid observation to fill the gap. + axis : {0 or 'index', 1 or 'columns'} + Unused, only for compatibility with :meth:`DataFrameGroupBy.fillna`. + inplace : bool, default False + Broken. Do not set to True. + limit : int, default None + If method is specified, this is the maximum number of consecutive + NaN values to forward/backward fill within a group. In other words, + if there is a gap with more than this number of consecutive NaNs, + it will only be partially filled. If method is not specified, this is the + maximum number of entries along the entire axis where NaNs will be + filled. Must be greater than 0 if not None. + 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). + + Returns + ------- + Series + Object with missing values filled within groups. + + See Also + -------- + ffill : Forward fill values within a group. + bfill : Backward fill values within a group. + + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['cat', 'cat', 'cat', 'mouse', 'mouse'] + >>> ser = pd.Series([1, None, None, 2, None], index=lst) + >>> ser + cat 1.0 + cat NaN + cat NaN + mouse 2.0 + mouse NaN + dtype: float64 + >>> ser.groupby(level=0).fillna(0, limit=1) + cat 1.0 + cat 0.0 + cat NaN + mouse 2.0 + mouse 0.0 + dtype: float64 + """ + warnings.warn( + f"{type(self).__name__}.fillna is deprecated and " + "will be removed in a future version. Use obj.ffill() or obj.bfill() " + "for forward or backward filling instead. If you want to fill with a " + f"single value, use {type(self.obj).__name__}.fillna instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + result = self._op_via_apply( + "fillna", + value=value, + method=method, + axis=axis, + inplace=inplace, + limit=limit, + downcast=downcast, + ) + return result + + def take( + self, + indices: TakeIndexer, + axis: Axis | lib.NoDefault = lib.no_default, + **kwargs, + ) -> Series: + """ + Return the elements in the given *positional* indices in each group. + + This means that we are not indexing according to actual values in + the index attribute of the object. We are indexing according to the + actual position of the element in the object. + + If a requested index does not exist for some group, this method will raise. + To get similar behavior that ignores indices that don't exist, see + :meth:`.SeriesGroupBy.nth`. + + Parameters + ---------- + indices : array-like + An array of ints indicating which positions to take in each group. + axis : {0 or 'index', 1 or 'columns', None}, default 0 + The axis on which to select elements. ``0`` means that we are + selecting rows, ``1`` means that we are selecting columns. + For `SeriesGroupBy` this parameter is unused and defaults to 0. + + .. deprecated:: 2.1.0 + For axis=1, operate on the underlying object instead. Otherwise + the axis keyword is not necessary. + + **kwargs + For compatibility with :meth:`numpy.take`. Has no effect on the + output. + + Returns + ------- + Series + A Series containing the elements taken from each group. + + See Also + -------- + Series.take : Take elements from a Series along an axis. + Series.loc : Select a subset of a DataFrame by labels. + Series.iloc : Select a subset of a DataFrame by positions. + numpy.take : Take elements from an array along an axis. + SeriesGroupBy.nth : Similar to take, won't raise if indices don't exist. + + Examples + -------- + >>> df = pd.DataFrame([('falcon', 'bird', 389.0), + ... ('parrot', 'bird', 24.0), + ... ('lion', 'mammal', 80.5), + ... ('monkey', 'mammal', np.nan), + ... ('rabbit', 'mammal', 15.0)], + ... columns=['name', 'class', 'max_speed'], + ... index=[4, 3, 2, 1, 0]) + >>> df + name class max_speed + 4 falcon bird 389.0 + 3 parrot bird 24.0 + 2 lion mammal 80.5 + 1 monkey mammal NaN + 0 rabbit mammal 15.0 + >>> gb = df["name"].groupby([1, 1, 2, 2, 2]) + + Take elements at positions 0 and 1 along the axis 0 in each group (default). + + >>> gb.take([0, 1]) + 1 4 falcon + 3 parrot + 2 2 lion + 1 monkey + Name: name, dtype: object + + We may take elements using negative integers for positive indices, + starting from the end of the object, just like with Python lists. + + >>> gb.take([-1, -2]) + 1 3 parrot + 4 falcon + 2 0 rabbit + 1 monkey + Name: name, dtype: object + """ + result = self._op_via_apply("take", indices=indices, axis=axis, **kwargs) + return result + + def skew( + self, + axis: Axis | lib.NoDefault = lib.no_default, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ) -> Series: + """ + Return unbiased skew within groups. + + Normalized by N-1. + + Parameters + ---------- + axis : {0 or 'index', 1 or 'columns', None}, default 0 + Axis for the function to be applied on. + This parameter is only for compatibility with DataFrame and is unused. + + .. deprecated:: 2.1.0 + For axis=1, operate on the underlying object instead. Otherwise + the axis keyword is not necessary. + + skipna : bool, default True + Exclude NA/null values when computing the result. + + numeric_only : bool, default False + Include only float, int, boolean columns. Not implemented for Series. + + **kwargs + Additional keyword arguments to be passed to the function. + + Returns + ------- + Series + + See Also + -------- + Series.skew : Return unbiased skew over requested axis. + + Examples + -------- + >>> ser = pd.Series([390., 350., 357., np.nan, 22., 20., 30.], + ... index=['Falcon', 'Falcon', 'Falcon', 'Falcon', + ... 'Parrot', 'Parrot', 'Parrot'], + ... name="Max Speed") + >>> ser + Falcon 390.0 + Falcon 350.0 + Falcon 357.0 + Falcon NaN + Parrot 22.0 + Parrot 20.0 + Parrot 30.0 + Name: Max Speed, dtype: float64 + >>> ser.groupby(level=0).skew() + Falcon 1.525174 + Parrot 1.457863 + Name: Max Speed, dtype: float64 + >>> ser.groupby(level=0).skew(skipna=False) + Falcon NaN + Parrot 1.457863 + Name: Max Speed, dtype: float64 + """ + if axis is lib.no_default: + axis = 0 + + if axis != 0: + result = self._op_via_apply( + "skew", + axis=axis, + skipna=skipna, + numeric_only=numeric_only, + **kwargs, + ) + return result + + def alt(obj): + # This should not be reached since the cython path should raise + # TypeError and not NotImplementedError. + raise TypeError(f"'skew' is not supported for dtype={obj.dtype}") + + return self._cython_agg_general( + "skew", alt=alt, skipna=skipna, numeric_only=numeric_only, **kwargs + ) + + @property + @doc(Series.plot.__doc__) + def plot(self) -> GroupByPlot: + result = GroupByPlot(self) + return result + + @doc(Series.nlargest.__doc__) + def nlargest( + self, n: int = 5, keep: Literal["first", "last", "all"] = "first" + ) -> Series: + f = partial(Series.nlargest, n=n, keep=keep) + data = self._obj_with_exclusions + # Don't change behavior if result index happens to be the same, i.e. + # already ordered and n >= all group sizes. + result = self._python_apply_general(f, data, not_indexed_same=True) + return result + + @doc(Series.nsmallest.__doc__) + def nsmallest( + self, n: int = 5, keep: Literal["first", "last", "all"] = "first" + ) -> Series: + f = partial(Series.nsmallest, n=n, keep=keep) + data = self._obj_with_exclusions + # Don't change behavior if result index happens to be the same, i.e. + # already ordered and n >= all group sizes. + result = self._python_apply_general(f, data, not_indexed_same=True) + return result + + @doc(Series.idxmin.__doc__) + def idxmin( + self, axis: Axis | lib.NoDefault = lib.no_default, skipna: bool = True + ) -> Series: + return self._idxmax_idxmin("idxmin", axis=axis, skipna=skipna) + + @doc(Series.idxmax.__doc__) + def idxmax( + self, axis: Axis | lib.NoDefault = lib.no_default, skipna: bool = True + ) -> Series: + return self._idxmax_idxmin("idxmax", axis=axis, skipna=skipna) + + @doc(Series.corr.__doc__) + def corr( + self, + other: Series, + method: CorrelationMethod = "pearson", + min_periods: int | None = None, + ) -> Series: + result = self._op_via_apply( + "corr", other=other, method=method, min_periods=min_periods + ) + return result + + @doc(Series.cov.__doc__) + def cov( + self, other: Series, min_periods: int | None = None, ddof: int | None = 1 + ) -> Series: + result = self._op_via_apply( + "cov", other=other, min_periods=min_periods, ddof=ddof + ) + return result + + @property + def is_monotonic_increasing(self) -> Series: + """ + Return whether each group's values are monotonically increasing. + + Returns + ------- + Series + + Examples + -------- + >>> s = pd.Series([2, 1, 3, 4], index=['Falcon', 'Falcon', 'Parrot', 'Parrot']) + >>> s.groupby(level=0).is_monotonic_increasing + Falcon False + Parrot True + dtype: bool + """ + return self.apply(lambda ser: ser.is_monotonic_increasing) + + @property + def is_monotonic_decreasing(self) -> Series: + """ + Return whether each group's values are monotonically decreasing. + + Returns + ------- + Series + + Examples + -------- + >>> s = pd.Series([2, 1, 3, 4], index=['Falcon', 'Falcon', 'Parrot', 'Parrot']) + >>> s.groupby(level=0).is_monotonic_decreasing + Falcon True + Parrot False + dtype: bool + """ + return self.apply(lambda ser: ser.is_monotonic_decreasing) + + @doc(Series.hist.__doc__) + def hist( + self, + by=None, + ax=None, + grid: bool = True, + xlabelsize: int | None = None, + xrot: float | None = None, + ylabelsize: int | None = None, + yrot: float | None = None, + figsize: tuple[int, int] | None = None, + bins: int | Sequence[int] = 10, + backend: str | None = None, + legend: bool = False, + **kwargs, + ): + result = self._op_via_apply( + "hist", + by=by, + ax=ax, + grid=grid, + xlabelsize=xlabelsize, + xrot=xrot, + ylabelsize=ylabelsize, + yrot=yrot, + figsize=figsize, + bins=bins, + backend=backend, + legend=legend, + **kwargs, + ) + return result + + @property + @doc(Series.dtype.__doc__) + def dtype(self) -> Series: + return self.apply(lambda ser: ser.dtype) + + def unique(self) -> Series: + """ + Return unique values for each group. + + It returns unique values for each of the grouped values. Returned in + order of appearance. Hash table-based unique, therefore does NOT sort. + + Returns + ------- + Series + Unique values for each of the grouped values. + + See Also + -------- + Series.unique : Return unique values of Series object. + + Examples + -------- + >>> df = pd.DataFrame([('Chihuahua', 'dog', 6.1), + ... ('Beagle', 'dog', 15.2), + ... ('Chihuahua', 'dog', 6.9), + ... ('Persian', 'cat', 9.2), + ... ('Chihuahua', 'dog', 7), + ... ('Persian', 'cat', 8.8)], + ... columns=['breed', 'animal', 'height_in']) + >>> df + breed animal height_in + 0 Chihuahua dog 6.1 + 1 Beagle dog 15.2 + 2 Chihuahua dog 6.9 + 3 Persian cat 9.2 + 4 Chihuahua dog 7.0 + 5 Persian cat 8.8 + >>> ser = df.groupby('animal')['breed'].unique() + >>> ser + animal + cat [Persian] + dog [Chihuahua, Beagle] + Name: breed, dtype: object + """ + result = self._op_via_apply("unique") + return result + + +class DataFrameGroupBy(GroupBy[DataFrame]): + _agg_examples_doc = dedent( + """ + Examples + -------- + >>> data = {"A": [1, 1, 2, 2], + ... "B": [1, 2, 3, 4], + ... "C": [0.362838, 0.227877, 1.267767, -0.562860]} + >>> df = pd.DataFrame(data) + >>> df + A B C + 0 1 1 0.362838 + 1 1 2 0.227877 + 2 2 3 1.267767 + 3 2 4 -0.562860 + + The aggregation is for each column. + + >>> df.groupby('A').agg('min') + B C + A + 1 1 0.227877 + 2 3 -0.562860 + + Multiple aggregations + + >>> df.groupby('A').agg(['min', 'max']) + B C + min max min max + A + 1 1 2 0.227877 0.362838 + 2 3 4 -0.562860 1.267767 + + Select a column for aggregation + + >>> df.groupby('A').B.agg(['min', 'max']) + min max + A + 1 1 2 + 2 3 4 + + User-defined function for aggregation + + >>> df.groupby('A').agg(lambda x: sum(x) + 2) + B C + A + 1 5 2.590715 + 2 9 2.704907 + + Different aggregations per column + + >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'}) + B C + min max sum + A + 1 1 2 0.590715 + 2 3 4 0.704907 + + To control the output names with different aggregations per column, + pandas supports "named aggregation" + + >>> df.groupby("A").agg( + ... b_min=pd.NamedAgg(column="B", aggfunc="min"), + ... c_sum=pd.NamedAgg(column="C", aggfunc="sum") + ... ) + b_min c_sum + A + 1 1 0.590715 + 2 3 0.704907 + + - The keywords are the *output* column names + - The values are tuples whose first element is the column to select + and the second element is the aggregation to apply to that column. + Pandas provides the ``pandas.NamedAgg`` namedtuple with the fields + ``['column', 'aggfunc']`` to make it clearer what the arguments are. + As usual, the aggregation can be a callable or a string alias. + + See :ref:`groupby.aggregate.named` for more. + + .. versionchanged:: 1.3.0 + + The resulting dtype will reflect the return value of the aggregating function. + + >>> df.groupby("A")[["B"]].agg(lambda x: x.astype(float).min()) + B + A + 1 1.0 + 2 3.0 + """ + ) + + @doc(_agg_template_frame, examples=_agg_examples_doc, klass="DataFrame") + def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): + relabeling, func, columns, order = reconstruct_func(func, **kwargs) + func = maybe_mangle_lambdas(func) + + if maybe_use_numba(engine): + # Not all agg functions support numba, only propagate numba kwargs + # if user asks for numba + kwargs["engine"] = engine + kwargs["engine_kwargs"] = engine_kwargs + + op = GroupByApply(self, func, args=args, kwargs=kwargs) + result = op.agg() + if not is_dict_like(func) and result is not None: + # GH #52849 + if not self.as_index and is_list_like(func): + return result.reset_index() + else: + return result + elif relabeling: + # this should be the only (non-raising) case with relabeling + # used reordered index of columns + result = cast(DataFrame, result) + result = result.iloc[:, order] + result = cast(DataFrame, result) + # error: Incompatible types in assignment (expression has type + # "Optional[List[str]]", variable has type + # "Union[Union[Union[ExtensionArray, ndarray[Any, Any]], + # Index, Series], Sequence[Any]]") + result.columns = columns # type: ignore[assignment] + + if result is None: + # Remove the kwargs we inserted + # (already stored in engine, engine_kwargs arguments) + if "engine" in kwargs: + del kwargs["engine"] + del kwargs["engine_kwargs"] + # at this point func is not a str, list-like, dict-like, + # or a known callable(e.g. sum) + if maybe_use_numba(engine): + return self._aggregate_with_numba( + func, *args, engine_kwargs=engine_kwargs, **kwargs + ) + # grouper specific aggregations + if self._grouper.nkeys > 1: + # test_groupby_as_index_series_scalar gets here with 'not self.as_index' + return self._python_agg_general(func, *args, **kwargs) + elif args or kwargs: + # test_pass_args_kwargs gets here (with and without as_index) + # can't return early + result = self._aggregate_frame(func, *args, **kwargs) + + elif self.axis == 1: + # _aggregate_multiple_funcs does not allow self.axis == 1 + # Note: axis == 1 precludes 'not self.as_index', see __init__ + result = self._aggregate_frame(func) + return result + + else: + # try to treat as if we are passing a list + gba = GroupByApply(self, [func], args=(), kwargs={}) + try: + result = gba.agg() + + except ValueError as err: + if "No objects to concatenate" not in str(err): + raise + # _aggregate_frame can fail with e.g. func=Series.mode, + # where it expects 1D values but would be getting 2D values + # In other tests, using aggregate_frame instead of GroupByApply + # would give correct values but incorrect dtypes + # object vs float64 in test_cython_agg_empty_buckets + # float64 vs int64 in test_category_order_apply + result = self._aggregate_frame(func) + + else: + # GH#32040, GH#35246 + # e.g. test_groupby_as_index_select_column_sum_empty_df + result = cast(DataFrame, result) + result.columns = self._obj_with_exclusions.columns.copy() + + if not self.as_index: + result = self._insert_inaxis_grouper(result) + result.index = default_index(len(result)) + + return result + + agg = aggregate + + def _python_agg_general(self, func, *args, **kwargs): + orig_func = func + func = com.is_builtin_func(func) + if orig_func != func: + alias = com._builtin_table_alias[func] + warn_alias_replacement(self, orig_func, alias) + f = lambda x: func(x, *args, **kwargs) + + if self.ngroups == 0: + # e.g. test_evaluate_with_empty_groups different path gets different + # result dtype in empty case. + return self._python_apply_general(f, self._selected_obj, is_agg=True) + + obj = self._obj_with_exclusions + if self.axis == 1: + obj = obj.T + + if not len(obj.columns): + # e.g. test_margins_no_values_no_cols + return self._python_apply_general(f, self._selected_obj) + + output: dict[int, ArrayLike] = {} + for idx, (name, ser) in enumerate(obj.items()): + result = self._grouper.agg_series(ser, f) + output[idx] = result + + res = self.obj._constructor(output) + res.columns = obj.columns.copy(deep=False) + return self._wrap_aggregated_output(res) + + def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: + if self._grouper.nkeys != 1: + raise AssertionError("Number of keys must be 1") + + obj = self._obj_with_exclusions + + result: dict[Hashable, NDFrame | np.ndarray] = {} + for name, grp_df in self._grouper.get_iterator(obj, self.axis): + fres = func(grp_df, *args, **kwargs) + result[name] = fres + + result_index = self._grouper.result_index + other_ax = obj.axes[1 - self.axis] + out = self.obj._constructor(result, index=other_ax, columns=result_index) + if self.axis == 0: + out = out.T + + return out + + def _wrap_applied_output( + self, + data: DataFrame, + values: list, + not_indexed_same: bool = False, + is_transform: bool = False, + ): + if len(values) == 0: + if is_transform: + # GH#47787 see test_group_on_empty_multiindex + res_index = data.index + else: + res_index = self._grouper.result_index + + result = self.obj._constructor(index=res_index, columns=data.columns) + result = result.astype(data.dtypes, copy=False) + return result + + # GH12824 + # using values[0] here breaks test_groupby_apply_none_first + first_not_none = next(com.not_none(*values), None) + + if first_not_none is None: + # GH9684 - All values are None, return an empty frame. + return self.obj._constructor() + elif isinstance(first_not_none, DataFrame): + return self._concat_objects( + values, + not_indexed_same=not_indexed_same, + is_transform=is_transform, + ) + + key_index = self._grouper.result_index if self.as_index else None + + if isinstance(first_not_none, (np.ndarray, Index)): + # GH#1738: values is list of arrays of unequal lengths + # fall through to the outer else clause + # TODO: sure this is right? we used to do this + # after raising AttributeError above + # GH 18930 + if not is_hashable(self._selection): + # error: Need type annotation for "name" + name = tuple(self._selection) # type: ignore[var-annotated, arg-type] + else: + # error: Incompatible types in assignment + # (expression has type "Hashable", variable + # has type "Tuple[Any, ...]") + name = self._selection # type: ignore[assignment] + return self.obj._constructor_sliced(values, index=key_index, name=name) + elif not isinstance(first_not_none, Series): + # values are not series or array-like but scalars + # self._selection not passed through to Series as the + # result should not take the name of original selection + # of columns + if self.as_index: + return self.obj._constructor_sliced(values, index=key_index) + else: + result = self.obj._constructor(values, columns=[self._selection]) + result = self._insert_inaxis_grouper(result) + return result + else: + # values are Series + return self._wrap_applied_output_series( + values, + not_indexed_same, + first_not_none, + key_index, + is_transform, + ) + + def _wrap_applied_output_series( + self, + values: list[Series], + not_indexed_same: bool, + first_not_none, + key_index: Index | None, + is_transform: bool, + ) -> DataFrame | Series: + kwargs = first_not_none._construct_axes_dict() + backup = Series(**kwargs) + values = [x if (x is not None) else backup for x in values] + + all_indexed_same = all_indexes_same(x.index for x in values) + + if not all_indexed_same: + # GH 8467 + return self._concat_objects( + values, + not_indexed_same=True, + is_transform=is_transform, + ) + + # Combine values + # vstack+constructor is faster than concat and handles MI-columns + stacked_values = np.vstack([np.asarray(v) for v in values]) + + if self.axis == 0: + index = key_index + columns = first_not_none.index.copy() + if columns.name is None: + # GH6124 - propagate name of Series when it's consistent + names = {v.name for v in values} + if len(names) == 1: + columns.name = next(iter(names)) + else: + index = first_not_none.index + columns = key_index + stacked_values = stacked_values.T + + if stacked_values.dtype == object: + # We'll have the DataFrame constructor do inference + stacked_values = stacked_values.tolist() + result = self.obj._constructor(stacked_values, index=index, columns=columns) + + if not self.as_index: + result = self._insert_inaxis_grouper(result) + + return self._reindex_output(result) + + def _cython_transform( + self, + how: str, + numeric_only: bool = False, + axis: AxisInt = 0, + **kwargs, + ) -> DataFrame: + assert axis == 0 # handled by caller + + # With self.axis == 0, we have multi-block tests + # e.g. test_rank_min_int, test_cython_transform_frame + # test_transform_numeric_ret + # With self.axis == 1, _get_data_to_aggregate does a transpose + # so we always have a single block. + mgr: Manager2D = self._get_data_to_aggregate( + numeric_only=numeric_only, name=how + ) + + def arr_func(bvalues: ArrayLike) -> ArrayLike: + return self._grouper._cython_operation( + "transform", bvalues, how, 1, **kwargs + ) + + # We could use `mgr.apply` here and not have to set_axis, but + # we would have to do shape gymnastics for ArrayManager compat + res_mgr = mgr.grouped_reduce(arr_func) + res_mgr.set_axis(1, mgr.axes[1]) + + res_df = self.obj._constructor_from_mgr(res_mgr, axes=res_mgr.axes) + res_df = self._maybe_transpose_result(res_df) + return res_df + + def _transform_general(self, func, engine, engine_kwargs, *args, **kwargs): + if maybe_use_numba(engine): + return self._transform_with_numba( + func, *args, engine_kwargs=engine_kwargs, **kwargs + ) + from pandas.core.reshape.concat import concat + + applied = [] + obj = self._obj_with_exclusions + gen = self._grouper.get_iterator(obj, axis=self.axis) + fast_path, slow_path = self._define_paths(func, *args, **kwargs) + + # Determine whether to use slow or fast path by evaluating on the first group. + # Need to handle the case of an empty generator and process the result so that + # it does not need to be computed again. + try: + name, group = next(gen) + except StopIteration: + pass + else: + # 2023-02-27 No tests broken by disabling this pinning + object.__setattr__(group, "name", name) + try: + path, res = self._choose_path(fast_path, slow_path, group) + except ValueError as err: + # e.g. test_transform_with_non_scalar_group + msg = "transform must return a scalar value for each group" + raise ValueError(msg) from err + if group.size > 0: + res = _wrap_transform_general_frame(self.obj, group, res) + applied.append(res) + + # Compute and process with the remaining groups + for name, group in gen: + if group.size == 0: + continue + # 2023-02-27 No tests broken by disabling this pinning + object.__setattr__(group, "name", name) + res = path(group) + + res = _wrap_transform_general_frame(self.obj, group, res) + applied.append(res) + + concat_index = obj.columns if self.axis == 0 else obj.index + other_axis = 1 if self.axis == 0 else 0 # switches between 0 & 1 + concatenated = concat(applied, axis=self.axis, verify_integrity=False) + concatenated = concatenated.reindex(concat_index, axis=other_axis, copy=False) + return self._set_result_index_ordered(concatenated) + + __examples_dataframe_doc = dedent( + """ + >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', + ... 'foo', 'bar'], + ... 'B' : ['one', 'one', 'two', 'three', + ... 'two', 'two'], + ... 'C' : [1, 5, 5, 2, 5, 5], + ... 'D' : [2.0, 5., 8., 1., 2., 9.]}) + >>> grouped = df.groupby('A')[['C', 'D']] + >>> grouped.transform(lambda x: (x - x.mean()) / x.std()) + C D + 0 -1.154701 -0.577350 + 1 0.577350 0.000000 + 2 0.577350 1.154701 + 3 -1.154701 -1.000000 + 4 0.577350 -0.577350 + 5 0.577350 1.000000 + + Broadcast result of the transformation + + >>> grouped.transform(lambda x: x.max() - x.min()) + C D + 0 4.0 6.0 + 1 3.0 8.0 + 2 4.0 6.0 + 3 3.0 8.0 + 4 4.0 6.0 + 5 3.0 8.0 + + >>> grouped.transform("mean") + C D + 0 3.666667 4.0 + 1 4.000000 5.0 + 2 3.666667 4.0 + 3 4.000000 5.0 + 4 3.666667 4.0 + 5 4.000000 5.0 + + .. versionchanged:: 1.3.0 + + The resulting dtype will reflect the return value of the passed ``func``, + for example: + + >>> grouped.transform(lambda x: x.astype(int).max()) + C D + 0 5 8 + 1 5 9 + 2 5 8 + 3 5 9 + 4 5 8 + 5 5 9 + """ + ) + + @Substitution(klass="DataFrame", example=__examples_dataframe_doc) + @Appender(_transform_template) + def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): + return self._transform( + func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ) + + def _define_paths(self, func, *args, **kwargs): + if isinstance(func, str): + fast_path = lambda group: getattr(group, func)(*args, **kwargs) + slow_path = lambda group: group.apply( + lambda x: getattr(x, func)(*args, **kwargs), axis=self.axis + ) + else: + fast_path = lambda group: func(group, *args, **kwargs) + slow_path = lambda group: group.apply( + lambda x: func(x, *args, **kwargs), axis=self.axis + ) + return fast_path, slow_path + + def _choose_path(self, fast_path: Callable, slow_path: Callable, group: DataFrame): + path = slow_path + res = slow_path(group) + + if self.ngroups == 1: + # no need to evaluate multiple paths when only + # a single group exists + return path, res + + # if we make it here, test if we can use the fast path + try: + res_fast = fast_path(group) + except AssertionError: + raise # pragma: no cover + except Exception: + # GH#29631 For user-defined function, we can't predict what may be + # raised; see test_transform.test_transform_fastpath_raises + return path, res + + # verify fast path returns either: + # a DataFrame with columns equal to group.columns + # OR a Series with index equal to group.columns + if isinstance(res_fast, DataFrame): + if not res_fast.columns.equals(group.columns): + return path, res + elif isinstance(res_fast, Series): + if not res_fast.index.equals(group.columns): + return path, res + else: + return path, res + + if res_fast.equals(res): + path = fast_path + + return path, res + + def filter(self, func, dropna: bool = True, *args, **kwargs): + """ + Filter elements from groups that don't satisfy a criterion. + + Elements from groups are filtered if they do not satisfy the + boolean criterion specified by func. + + Parameters + ---------- + func : function + Criterion to apply to each group. Should return True or False. + dropna : bool + Drop groups that do not pass the filter. True by default; if False, + groups that evaluate False are filled with NaNs. + + Returns + ------- + DataFrame + + Notes + ----- + Each subframe is endowed the attribute 'name' in case you need to know + which group you are working on. + + Functions that mutate the passed object can produce unexpected + behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` + for more details. + + Examples + -------- + >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', + ... 'foo', 'bar'], + ... 'B' : [1, 2, 3, 4, 5, 6], + ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) + >>> grouped = df.groupby('A') + >>> grouped.filter(lambda x: x['B'].mean() > 3.) + A B C + 1 bar 2 5.0 + 3 bar 4 1.0 + 5 bar 6 9.0 + """ + indices = [] + + obj = self._selected_obj + gen = self._grouper.get_iterator(obj, axis=self.axis) + + for name, group in gen: + # 2023-02-27 no tests are broken this pinning, but it is documented in the + # docstring above. + object.__setattr__(group, "name", name) + + res = func(group, *args, **kwargs) + + try: + res = res.squeeze() + except AttributeError: # allow e.g., scalars and frames to pass + pass + + # interpret the result of the filter + if is_bool(res) or (is_scalar(res) and isna(res)): + if notna(res) and res: + indices.append(self._get_index(name)) + else: + # non scalars aren't allowed + raise TypeError( + f"filter function returned a {type(res).__name__}, " + "but expected a scalar bool" + ) + + return self._apply_filter(indices, dropna) + + def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: + if self.axis == 1: + # GH 37725 + raise ValueError("Cannot subset columns when using axis=1") + # per GH 23566 + if isinstance(key, tuple) and len(key) > 1: + # if len == 1, then it becomes a SeriesGroupBy and this is actually + # valid syntax, so don't raise + raise ValueError( + "Cannot subset columns with a tuple with more than one element. " + "Use a list instead." + ) + return super().__getitem__(key) + + def _gotitem(self, key, ndim: int, subset=None): + """ + sub-classes to define + return a sliced object + + Parameters + ---------- + key : string / list of selections + ndim : {1, 2} + requested ndim of result + subset : object, default None + subset to act on + """ + if ndim == 2: + if subset is None: + subset = self.obj + return DataFrameGroupBy( + subset, + self.keys, + axis=self.axis, + level=self.level, + grouper=self._grouper, + exclusions=self.exclusions, + selection=key, + as_index=self.as_index, + sort=self.sort, + group_keys=self.group_keys, + observed=self.observed, + dropna=self.dropna, + ) + elif ndim == 1: + if subset is None: + subset = self.obj[key] + return SeriesGroupBy( + subset, + self.keys, + level=self.level, + grouper=self._grouper, + exclusions=self.exclusions, + selection=key, + as_index=self.as_index, + sort=self.sort, + group_keys=self.group_keys, + observed=self.observed, + dropna=self.dropna, + ) + + raise AssertionError("invalid ndim for _gotitem") + + def _get_data_to_aggregate( + self, *, numeric_only: bool = False, name: str | None = None + ) -> Manager2D: + obj = self._obj_with_exclusions + if self.axis == 1: + mgr = obj.T._mgr + else: + mgr = obj._mgr + + if numeric_only: + mgr = mgr.get_numeric_data() + return mgr + + def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame: + return self.obj._constructor_from_mgr(mgr, axes=mgr.axes) + + def _apply_to_column_groupbys(self, func) -> DataFrame: + from pandas.core.reshape.concat import concat + + obj = self._obj_with_exclusions + columns = obj.columns + sgbs = [ + SeriesGroupBy( + obj.iloc[:, i], + selection=colname, + grouper=self._grouper, + exclusions=self.exclusions, + observed=self.observed, + ) + for i, colname in enumerate(obj.columns) + ] + results = [func(sgb) for sgb in sgbs] + + if not len(results): + # concat would raise + res_df = DataFrame([], columns=columns, index=self._grouper.result_index) + else: + res_df = concat(results, keys=columns, axis=1) + + if not self.as_index: + res_df.index = default_index(len(res_df)) + res_df = self._insert_inaxis_grouper(res_df) + return res_df + + def nunique(self, dropna: bool = True) -> DataFrame: + """ + Return DataFrame with counts of unique elements in each position. + + Parameters + ---------- + dropna : bool, default True + Don't include NaN in the counts. + + Returns + ------- + nunique: DataFrame + + Examples + -------- + >>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam', + ... 'ham', 'ham'], + ... 'value1': [1, 5, 5, 2, 5, 5], + ... 'value2': list('abbaxy')}) + >>> df + id value1 value2 + 0 spam 1 a + 1 egg 5 b + 2 egg 5 b + 3 spam 2 a + 4 ham 5 x + 5 ham 5 y + + >>> df.groupby('id').nunique() + value1 value2 + id + egg 1 1 + ham 1 2 + spam 2 1 + + Check for rows with the same id but conflicting values: + + >>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any()) + id value1 value2 + 0 spam 1 a + 3 spam 2 a + 4 ham 5 x + 5 ham 5 y + """ + + if self.axis != 0: + # see test_groupby_crash_on_nunique + return self._python_apply_general( + lambda sgb: sgb.nunique(dropna), self._obj_with_exclusions, is_agg=True + ) + + return self._apply_to_column_groupbys(lambda sgb: sgb.nunique(dropna)) + + def idxmax( + self, + axis: Axis | None | lib.NoDefault = lib.no_default, + skipna: bool = True, + numeric_only: bool = False, + ) -> DataFrame: + """ + Return index of first occurrence of maximum over requested axis. + + NA/null values are excluded. + + Parameters + ---------- + axis : {{0 or 'index', 1 or 'columns'}}, default None + The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise. + If axis is not provided, grouper's axis is used. + + .. versionchanged:: 2.0.0 + + .. deprecated:: 2.1.0 + For axis=1, operate on the underlying object instead. Otherwise + the axis keyword is not necessary. + + skipna : bool, default True + Exclude NA/null values. If an entire row/column is NA, the result + will be NA. + numeric_only : bool, default False + Include only `float`, `int` or `boolean` data. + + .. versionadded:: 1.5.0 + + Returns + ------- + Series + Indexes of maxima along the specified axis. + + Raises + ------ + ValueError + * If the row/column is empty + + See Also + -------- + Series.idxmax : Return index of the maximum element. + + Notes + ----- + This method is the DataFrame version of ``ndarray.argmax``. + + Examples + -------- + Consider a dataset containing food consumption in Argentina. + + >>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48], + ... 'co2_emissions': [37.2, 19.66, 1712]}, + ... index=['Pork', 'Wheat Products', 'Beef']) + + >>> df + consumption co2_emissions + Pork 10.51 37.20 + Wheat Products 103.11 19.66 + Beef 55.48 1712.00 + + By default, it returns the index for the maximum value in each column. + + >>> df.idxmax() + consumption Wheat Products + co2_emissions Beef + dtype: object + + To return the index for the maximum value in each row, use ``axis="columns"``. + + >>> df.idxmax(axis="columns") + Pork co2_emissions + Wheat Products consumption + Beef co2_emissions + dtype: object + """ + return self._idxmax_idxmin( + "idxmax", axis=axis, numeric_only=numeric_only, skipna=skipna + ) + + def idxmin( + self, + axis: Axis | None | lib.NoDefault = lib.no_default, + skipna: bool = True, + numeric_only: bool = False, + ) -> DataFrame: + """ + Return index of first occurrence of minimum over requested axis. + + NA/null values are excluded. + + Parameters + ---------- + axis : {{0 or 'index', 1 or 'columns'}}, default None + The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise. + If axis is not provided, grouper's axis is used. + + .. versionchanged:: 2.0.0 + + .. deprecated:: 2.1.0 + For axis=1, operate on the underlying object instead. Otherwise + the axis keyword is not necessary. + + skipna : bool, default True + Exclude NA/null values. If an entire row/column is NA, the result + will be NA. + numeric_only : bool, default False + Include only `float`, `int` or `boolean` data. + + .. versionadded:: 1.5.0 + + Returns + ------- + Series + Indexes of minima along the specified axis. + + Raises + ------ + ValueError + * If the row/column is empty + + See Also + -------- + Series.idxmin : Return index of the minimum element. + + Notes + ----- + This method is the DataFrame version of ``ndarray.argmin``. + + Examples + -------- + Consider a dataset containing food consumption in Argentina. + + >>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48], + ... 'co2_emissions': [37.2, 19.66, 1712]}, + ... index=['Pork', 'Wheat Products', 'Beef']) + + >>> df + consumption co2_emissions + Pork 10.51 37.20 + Wheat Products 103.11 19.66 + Beef 55.48 1712.00 + + By default, it returns the index for the minimum value in each column. + + >>> df.idxmin() + consumption Pork + co2_emissions Wheat Products + dtype: object + + To return the index for the minimum value in each row, use ``axis="columns"``. + + >>> df.idxmin(axis="columns") + Pork consumption + Wheat Products co2_emissions + Beef consumption + dtype: object + """ + return self._idxmax_idxmin( + "idxmin", axis=axis, numeric_only=numeric_only, skipna=skipna + ) + + boxplot = boxplot_frame_groupby + + def value_counts( + self, + subset: Sequence[Hashable] | None = None, + normalize: bool = False, + sort: bool = True, + ascending: bool = False, + dropna: bool = True, + ) -> DataFrame | Series: + """ + Return a Series or DataFrame containing counts of unique rows. + + .. versionadded:: 1.4.0 + + Parameters + ---------- + subset : list-like, optional + Columns to use when counting unique combinations. + normalize : bool, default False + Return proportions rather than frequencies. + sort : bool, default True + Sort by frequencies. + ascending : bool, default False + Sort in ascending order. + dropna : bool, default True + Don't include counts of rows that contain NA values. + + Returns + ------- + Series or DataFrame + Series if the groupby as_index is True, otherwise DataFrame. + + See Also + -------- + Series.value_counts: Equivalent method on Series. + DataFrame.value_counts: Equivalent method on DataFrame. + SeriesGroupBy.value_counts: Equivalent method on SeriesGroupBy. + + Notes + ----- + - If the groupby as_index is True then the returned Series will have a + MultiIndex with one level per input column. + - If the groupby as_index is False then the returned DataFrame will have an + additional column with the value_counts. The column is labelled 'count' or + 'proportion', depending on the ``normalize`` parameter. + + By default, rows that contain any NA values are omitted from + the result. + + By default, the result will be in descending order so that the + first element of each group is the most frequently-occurring row. + + Examples + -------- + >>> df = pd.DataFrame({ + ... 'gender': ['male', 'male', 'female', 'male', 'female', 'male'], + ... 'education': ['low', 'medium', 'high', 'low', 'high', 'low'], + ... 'country': ['US', 'FR', 'US', 'FR', 'FR', 'FR'] + ... }) + + >>> df + gender education country + 0 male low US + 1 male medium FR + 2 female high US + 3 male low FR + 4 female high FR + 5 male low FR + + >>> df.groupby('gender').value_counts() + gender education country + female high FR 1 + US 1 + male low FR 2 + US 1 + medium FR 1 + Name: count, dtype: int64 + + >>> df.groupby('gender').value_counts(ascending=True) + gender education country + female high FR 1 + US 1 + male low US 1 + medium FR 1 + low FR 2 + Name: count, dtype: int64 + + >>> df.groupby('gender').value_counts(normalize=True) + gender education country + female high FR 0.50 + US 0.50 + male low FR 0.50 + US 0.25 + medium FR 0.25 + Name: proportion, dtype: float64 + + >>> df.groupby('gender', as_index=False).value_counts() + gender education country count + 0 female high FR 1 + 1 female high US 1 + 2 male low FR 2 + 3 male low US 1 + 4 male medium FR 1 + + >>> df.groupby('gender', as_index=False).value_counts(normalize=True) + gender education country proportion + 0 female high FR 0.50 + 1 female high US 0.50 + 2 male low FR 0.50 + 3 male low US 0.25 + 4 male medium FR 0.25 + """ + return self._value_counts(subset, normalize, sort, ascending, dropna) + + def fillna( + self, + value: Hashable | Mapping | Series | DataFrame | None = None, + method: FillnaOptions | None = None, + axis: Axis | None | lib.NoDefault = lib.no_default, + inplace: bool = False, + limit: int | None = None, + downcast=lib.no_default, + ) -> DataFrame | None: + """ + Fill NA/NaN values using the specified method within groups. + + .. deprecated:: 2.2.0 + This method is deprecated and will be removed in a future version. + Use the :meth:`.DataFrameGroupBy.ffill` or :meth:`.DataFrameGroupBy.bfill` + for forward or backward filling instead. If you want to fill with a + single value, use :meth:`DataFrame.fillna` instead. + + Parameters + ---------- + value : scalar, dict, Series, or DataFrame + Value to use to fill holes (e.g. 0), alternately a + dict/Series/DataFrame of values specifying which value to use for + each index (for a Series) or column (for a DataFrame). Values not + in the dict/Series/DataFrame will not be filled. This value cannot + be a list. Users wanting to use the ``value`` argument and not ``method`` + should prefer :meth:`.DataFrame.fillna` as this + will produce the same result and be more performant. + method : {{'bfill', 'ffill', None}}, default None + Method to use for filling holes. ``'ffill'`` will propagate + the last valid observation forward within a group. + ``'bfill'`` will use next valid observation to fill the gap. + axis : {0 or 'index', 1 or 'columns'} + Axis along which to fill missing values. When the :class:`DataFrameGroupBy` + ``axis`` argument is ``0``, using ``axis=1`` here will produce + the same results as :meth:`.DataFrame.fillna`. When the + :class:`DataFrameGroupBy` ``axis`` argument is ``1``, using ``axis=0`` + or ``axis=1`` here will produce the same results. + inplace : bool, default False + Broken. Do not set to True. + limit : int, default None + If method is specified, this is the maximum number of consecutive + NaN values to forward/backward fill within a group. In other words, + if there is a gap with more than this number of consecutive NaNs, + it will only be partially filled. If method is not specified, this is the + maximum number of entries along the entire axis where NaNs will be + filled. Must be greater than 0 if not None. + 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). + + Returns + ------- + DataFrame + Object with missing values filled. + + See Also + -------- + ffill : Forward fill values within a group. + bfill : Backward fill values within a group. + + Examples + -------- + >>> df = pd.DataFrame( + ... { + ... "key": [0, 0, 1, 1, 1], + ... "A": [np.nan, 2, np.nan, 3, np.nan], + ... "B": [2, 3, np.nan, np.nan, np.nan], + ... "C": [np.nan, np.nan, 2, np.nan, np.nan], + ... } + ... ) + >>> df + key A B C + 0 0 NaN 2.0 NaN + 1 0 2.0 3.0 NaN + 2 1 NaN NaN 2.0 + 3 1 3.0 NaN NaN + 4 1 NaN NaN NaN + + Propagate non-null values forward or backward within each group along columns. + + >>> df.groupby("key").fillna(method="ffill") + A B C + 0 NaN 2.0 NaN + 1 2.0 3.0 NaN + 2 NaN NaN 2.0 + 3 3.0 NaN 2.0 + 4 3.0 NaN 2.0 + + >>> df.groupby("key").fillna(method="bfill") + A B C + 0 2.0 2.0 NaN + 1 2.0 3.0 NaN + 2 3.0 NaN 2.0 + 3 3.0 NaN NaN + 4 NaN NaN NaN + + Propagate non-null values forward or backward within each group along rows. + + >>> df.T.groupby(np.array([0, 0, 1, 1])).fillna(method="ffill").T + key A B C + 0 0.0 0.0 2.0 2.0 + 1 0.0 2.0 3.0 3.0 + 2 1.0 1.0 NaN 2.0 + 3 1.0 3.0 NaN NaN + 4 1.0 1.0 NaN NaN + + >>> df.T.groupby(np.array([0, 0, 1, 1])).fillna(method="bfill").T + key A B C + 0 0.0 NaN 2.0 NaN + 1 0.0 2.0 3.0 NaN + 2 1.0 NaN 2.0 2.0 + 3 1.0 3.0 NaN NaN + 4 1.0 NaN NaN NaN + + Only replace the first NaN element within a group along rows. + + >>> df.groupby("key").fillna(method="ffill", limit=1) + A B C + 0 NaN 2.0 NaN + 1 2.0 3.0 NaN + 2 NaN NaN 2.0 + 3 3.0 NaN 2.0 + 4 3.0 NaN NaN + """ + warnings.warn( + f"{type(self).__name__}.fillna is deprecated and " + "will be removed in a future version. Use obj.ffill() or obj.bfill() " + "for forward or backward filling instead. If you want to fill with a " + f"single value, use {type(self.obj).__name__}.fillna instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + + result = self._op_via_apply( + "fillna", + value=value, + method=method, + axis=axis, + inplace=inplace, + limit=limit, + downcast=downcast, + ) + return result + + def take( + self, + indices: TakeIndexer, + axis: Axis | None | lib.NoDefault = lib.no_default, + **kwargs, + ) -> DataFrame: + """ + Return the elements in the given *positional* indices in each group. + + This means that we are not indexing according to actual values in + the index attribute of the object. We are indexing according to the + actual position of the element in the object. + + If a requested index does not exist for some group, this method will raise. + To get similar behavior that ignores indices that don't exist, see + :meth:`.DataFrameGroupBy.nth`. + + Parameters + ---------- + indices : array-like + An array of ints indicating which positions to take. + axis : {0 or 'index', 1 or 'columns', None}, default 0 + The axis on which to select elements. ``0`` means that we are + selecting rows, ``1`` means that we are selecting columns. + + .. deprecated:: 2.1.0 + For axis=1, operate on the underlying object instead. Otherwise + the axis keyword is not necessary. + + **kwargs + For compatibility with :meth:`numpy.take`. Has no effect on the + output. + + Returns + ------- + DataFrame + An DataFrame containing the elements taken from each group. + + See Also + -------- + DataFrame.take : Take elements from a Series along an axis. + DataFrame.loc : Select a subset of a DataFrame by labels. + DataFrame.iloc : Select a subset of a DataFrame by positions. + numpy.take : Take elements from an array along an axis. + + Examples + -------- + >>> df = pd.DataFrame([('falcon', 'bird', 389.0), + ... ('parrot', 'bird', 24.0), + ... ('lion', 'mammal', 80.5), + ... ('monkey', 'mammal', np.nan), + ... ('rabbit', 'mammal', 15.0)], + ... columns=['name', 'class', 'max_speed'], + ... index=[4, 3, 2, 1, 0]) + >>> df + name class max_speed + 4 falcon bird 389.0 + 3 parrot bird 24.0 + 2 lion mammal 80.5 + 1 monkey mammal NaN + 0 rabbit mammal 15.0 + >>> gb = df.groupby([1, 1, 2, 2, 2]) + + Take elements at positions 0 and 1 along the axis 0 (default). + + Note how the indices selected in the result do not correspond to + our input indices 0 and 1. That's because we are selecting the 0th + and 1st rows, not rows whose indices equal 0 and 1. + + >>> gb.take([0, 1]) + name class max_speed + 1 4 falcon bird 389.0 + 3 parrot bird 24.0 + 2 2 lion mammal 80.5 + 1 monkey mammal NaN + + The order of the specified indices influences the order in the result. + Here, the order is swapped from the previous example. + + >>> gb.take([1, 0]) + name class max_speed + 1 3 parrot bird 24.0 + 4 falcon bird 389.0 + 2 1 monkey mammal NaN + 2 lion mammal 80.5 + + Take elements at indices 1 and 2 along the axis 1 (column selection). + + We may take elements using negative integers for positive indices, + starting from the end of the object, just like with Python lists. + + >>> gb.take([-1, -2]) + name class max_speed + 1 3 parrot bird 24.0 + 4 falcon bird 389.0 + 2 0 rabbit mammal 15.0 + 1 monkey mammal NaN + """ + result = self._op_via_apply("take", indices=indices, axis=axis, **kwargs) + return result + + def skew( + self, + axis: Axis | None | lib.NoDefault = lib.no_default, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ) -> DataFrame: + """ + Return unbiased skew within groups. + + Normalized by N-1. + + Parameters + ---------- + axis : {0 or 'index', 1 or 'columns', None}, default 0 + Axis for the function to be applied on. + + Specifying ``axis=None`` will apply the aggregation across both axes. + + .. versionadded:: 2.0.0 + + .. deprecated:: 2.1.0 + For axis=1, operate on the underlying object instead. Otherwise + the axis keyword is not necessary. + + skipna : bool, default True + Exclude NA/null values when computing the result. + + numeric_only : bool, default False + Include only float, int, boolean columns. + + **kwargs + Additional keyword arguments to be passed to the function. + + Returns + ------- + DataFrame + + See Also + -------- + DataFrame.skew : Return unbiased skew over requested axis. + + Examples + -------- + >>> arrays = [['falcon', 'parrot', 'cockatoo', 'kiwi', + ... 'lion', 'monkey', 'rabbit'], + ... ['bird', 'bird', 'bird', 'bird', + ... 'mammal', 'mammal', 'mammal']] + >>> index = pd.MultiIndex.from_arrays(arrays, names=('name', 'class')) + >>> df = pd.DataFrame({'max_speed': [389.0, 24.0, 70.0, np.nan, + ... 80.5, 21.5, 15.0]}, + ... index=index) + >>> df + max_speed + name class + falcon bird 389.0 + parrot bird 24.0 + cockatoo bird 70.0 + kiwi bird NaN + lion mammal 80.5 + monkey mammal 21.5 + rabbit mammal 15.0 + >>> gb = df.groupby(["class"]) + >>> gb.skew() + max_speed + class + bird 1.628296 + mammal 1.669046 + >>> gb.skew(skipna=False) + max_speed + class + bird NaN + mammal 1.669046 + """ + if axis is lib.no_default: + axis = 0 + + if axis != 0: + result = self._op_via_apply( + "skew", + axis=axis, + skipna=skipna, + numeric_only=numeric_only, + **kwargs, + ) + return result + + def alt(obj): + # This should not be reached since the cython path should raise + # TypeError and not NotImplementedError. + raise TypeError(f"'skew' is not supported for dtype={obj.dtype}") + + return self._cython_agg_general( + "skew", alt=alt, skipna=skipna, numeric_only=numeric_only, **kwargs + ) + + @property + @doc(DataFrame.plot.__doc__) + def plot(self) -> GroupByPlot: + result = GroupByPlot(self) + return result + + @doc(DataFrame.corr.__doc__) + def corr( + self, + method: str | Callable[[np.ndarray, np.ndarray], float] = "pearson", + min_periods: int = 1, + numeric_only: bool = False, + ) -> DataFrame: + result = self._op_via_apply( + "corr", method=method, min_periods=min_periods, numeric_only=numeric_only + ) + return result + + @doc(DataFrame.cov.__doc__) + def cov( + self, + min_periods: int | None = None, + ddof: int | None = 1, + numeric_only: bool = False, + ) -> DataFrame: + result = self._op_via_apply( + "cov", min_periods=min_periods, ddof=ddof, numeric_only=numeric_only + ) + return result + + @doc(DataFrame.hist.__doc__) + def hist( + self, + column: IndexLabel | None = None, + by=None, + grid: bool = True, + xlabelsize: int | None = None, + xrot: float | None = None, + ylabelsize: int | None = None, + yrot: float | None = None, + ax=None, + sharex: bool = False, + sharey: bool = False, + figsize: tuple[int, int] | None = None, + layout: tuple[int, int] | None = None, + bins: int | Sequence[int] = 10, + backend: str | None = None, + legend: bool = False, + **kwargs, + ): + result = self._op_via_apply( + "hist", + column=column, + by=by, + grid=grid, + xlabelsize=xlabelsize, + xrot=xrot, + ylabelsize=ylabelsize, + yrot=yrot, + ax=ax, + sharex=sharex, + sharey=sharey, + figsize=figsize, + layout=layout, + bins=bins, + backend=backend, + legend=legend, + **kwargs, + ) + return result + + @property + @doc(DataFrame.dtypes.__doc__) + def dtypes(self) -> Series: + # GH#51045 + warnings.warn( + f"{type(self).__name__}.dtypes is deprecated and will be removed in " + "a future version. Check the dtypes on the base object instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + + # error: Incompatible return value type (got "DataFrame", expected "Series") + return self._python_apply_general( # type: ignore[return-value] + lambda df: df.dtypes, self._selected_obj + ) + + @doc(DataFrame.corrwith.__doc__) + def corrwith( + self, + other: DataFrame | Series, + axis: Axis | lib.NoDefault = lib.no_default, + drop: bool = False, + method: CorrelationMethod = "pearson", + numeric_only: bool = False, + ) -> DataFrame: + result = self._op_via_apply( + "corrwith", + other=other, + axis=axis, + drop=drop, + method=method, + numeric_only=numeric_only, + ) + return result + + +def _wrap_transform_general_frame( + obj: DataFrame, group: DataFrame, res: DataFrame | Series +) -> DataFrame: + from pandas import concat + + if isinstance(res, Series): + # we need to broadcast across the + # other dimension; this will preserve dtypes + # GH14457 + if res.index.is_(obj.index): + res_frame = concat([res] * len(group.columns), axis=1) + res_frame.columns = group.columns + res_frame.index = group.index + else: + res_frame = obj._constructor( + np.tile(res.values, (len(group.index), 1)), + columns=group.columns, + index=group.index, + ) + assert isinstance(res_frame, DataFrame) + return res_frame + elif isinstance(res, DataFrame) and not res.index.is_(group.index): + return res._align_frame(group)[0] + else: + return res diff --git a/shared/package-files/2c/2c32dccf1461f21ef1dfd663addf868337501ebefcc98c4396bbf60bd5316f91/data.py b/shared/package-files/2c/2c32dccf1461f21ef1dfd663addf868337501ebefcc98c4396bbf60bd5316f91/data.py new file mode 100644 index 0000000000000000000000000000000000000000..519032305bed633f2ba8a6148076433caf81710b --- /dev/null +++ b/shared/package-files/2c/2c32dccf1461f21ef1dfd663addf868337501ebefcc98c4396bbf60bd5316f91/data.py @@ -0,0 +1,58 @@ +import base64 +import io +from typing import Optional +from urllib.parse import unquote + +from fsspec import AbstractFileSystem + + +class DataFileSystem(AbstractFileSystem): + """A handy decoder for data-URLs + + Example + ------- + >>> with fsspec.open("data:,Hello%2C%20World%21") as f: + ... print(f.read()) + b"Hello, World!" + + See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs + """ + + protocol = "data" + + def __init__(self, **kwargs): + """No parameters for this filesystem""" + super().__init__(**kwargs) + + def cat_file(self, path, start=None, end=None, **kwargs): + pref, data = path.split(",", 1) + if pref.endswith("base64"): + return base64.b64decode(data)[start:end] + return unquote(data).encode()[start:end] + + def info(self, path, **kwargs): + pref, name = path.split(",", 1) + data = self.cat_file(path) + mime = pref.split(":", 1)[1].split(";", 1)[0] + return {"name": name, "size": len(data), "type": "file", "mimetype": mime} + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + if "r" not in mode: + raise ValueError("Read only filesystem") + return io.BytesIO(self.cat_file(path)) + + @staticmethod + def encode(data: bytes, mime: Optional[str] = None): + """Format the given data into data-URL syntax + + This version always base64 encodes, even when the data is ascii/url-safe. + """ + return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}" diff --git a/shared/package-files/2c/2c358a7e1888cd63645eaaf5c707b1fa5d7286c5a4756089928e1b60cf9eb50f/runner.py b/shared/package-files/2c/2c358a7e1888cd63645eaaf5c707b1fa5d7286c5a4756089928e1b60cf9eb50f/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..0b60301bf5f4b6369cc0991624a2a939b55fc9e5 --- /dev/null +++ b/shared/package-files/2c/2c358a7e1888cd63645eaaf5c707b1fa5d7286c5a4756089928e1b60cf9eb50f/runner.py @@ -0,0 +1,571 @@ +# mypy: allow-untyped-defs +"""Basic collect and runtest protocol implementations.""" + +from __future__ import annotations + +import bdb +import dataclasses +import os +import sys +import types +from typing import Callable +from typing import cast +from typing import final +from typing import Generic +from typing import Literal +from typing import TYPE_CHECKING +from typing import TypeVar + +from .reports import BaseReport +from .reports import CollectErrorRepr +from .reports import CollectReport +from .reports import TestReport +from _pytest import timing +from _pytest._code.code import ExceptionChainRepr +from _pytest._code.code import ExceptionInfo +from _pytest._code.code import TerminalRepr +from _pytest.config.argparsing import Parser +from _pytest.deprecated import check_ispytest +from _pytest.nodes import Collector +from _pytest.nodes import Directory +from _pytest.nodes import Item +from _pytest.nodes import Node +from _pytest.outcomes import Exit +from _pytest.outcomes import OutcomeException +from _pytest.outcomes import Skipped +from _pytest.outcomes import TEST_OUTCOME + + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup + +if TYPE_CHECKING: + from _pytest.main import Session + from _pytest.terminal import TerminalReporter + +# +# pytest plugin hooks. + + +def pytest_addoption(parser: Parser) -> None: + group = parser.getgroup("terminal reporting", "Reporting", after="general") + group.addoption( + "--durations", + action="store", + type=int, + default=None, + metavar="N", + help="Show N slowest setup/test durations (N=0 for all)", + ) + group.addoption( + "--durations-min", + action="store", + type=float, + default=0.005, + metavar="N", + help="Minimal duration in seconds for inclusion in slowest list. " + "Default: 0.005.", + ) + + +def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None: + durations = terminalreporter.config.option.durations + durations_min = terminalreporter.config.option.durations_min + verbose = terminalreporter.config.get_verbosity() + if durations is None: + return + tr = terminalreporter + dlist = [] + for replist in tr.stats.values(): + for rep in replist: + if hasattr(rep, "duration"): + dlist.append(rep) + if not dlist: + return + dlist.sort(key=lambda x: x.duration, reverse=True) + if not durations: + tr.write_sep("=", "slowest durations") + else: + tr.write_sep("=", f"slowest {durations} durations") + dlist = dlist[:durations] + + for i, rep in enumerate(dlist): + if verbose < 2 and rep.duration < durations_min: + tr.write_line("") + tr.write_line( + f"({len(dlist) - i} durations < {durations_min:g}s hidden. Use -vv to show these durations.)" + ) + break + tr.write_line(f"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}") + + +def pytest_sessionstart(session: Session) -> None: + session._setupstate = SetupState() + + +def pytest_sessionfinish(session: Session) -> None: + session._setupstate.teardown_exact(None) + + +def pytest_runtest_protocol(item: Item, nextitem: Item | None) -> bool: + ihook = item.ihook + ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location) + runtestprotocol(item, nextitem=nextitem) + ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location) + return True + + +def runtestprotocol( + item: Item, log: bool = True, nextitem: Item | None = None +) -> list[TestReport]: + hasrequest = hasattr(item, "_request") + if hasrequest and not item._request: # type: ignore[attr-defined] + # This only happens if the item is re-run, as is done by + # pytest-rerunfailures. + item._initrequest() # type: ignore[attr-defined] + rep = call_and_report(item, "setup", log) + reports = [rep] + if rep.passed: + if item.config.getoption("setupshow", False): + show_test_item(item) + if not item.config.getoption("setuponly", False): + reports.append(call_and_report(item, "call", log)) + # If the session is about to fail or stop, teardown everything - this is + # necessary to correctly report fixture teardown errors (see #11706) + if item.session.shouldfail or item.session.shouldstop: + nextitem = None + reports.append(call_and_report(item, "teardown", log, nextitem=nextitem)) + # After all teardown hooks have been called + # want funcargs and request info to go away. + if hasrequest: + item._request = False # type: ignore[attr-defined] + item.funcargs = None # type: ignore[attr-defined] + return reports + + +def show_test_item(item: Item) -> None: + """Show test function, parameters and the fixtures of the test item.""" + tw = item.config.get_terminal_writer() + tw.line() + tw.write(" " * 8) + tw.write(item.nodeid) + used_fixtures = sorted(getattr(item, "fixturenames", [])) + if used_fixtures: + tw.write(" (fixtures used: {})".format(", ".join(used_fixtures))) + tw.flush() + + +def pytest_runtest_setup(item: Item) -> None: + _update_current_test_var(item, "setup") + item.session._setupstate.setup(item) + + +def pytest_runtest_call(item: Item) -> None: + _update_current_test_var(item, "call") + try: + del sys.last_type + del sys.last_value + del sys.last_traceback + if sys.version_info >= (3, 12, 0): + del sys.last_exc # type:ignore[attr-defined] + except AttributeError: + pass + try: + item.runtest() + except Exception as e: + # Store trace info to allow postmortem debugging + sys.last_type = type(e) + sys.last_value = e + if sys.version_info >= (3, 12, 0): + sys.last_exc = e # type:ignore[attr-defined] + assert e.__traceback__ is not None + # Skip *this* frame + sys.last_traceback = e.__traceback__.tb_next + raise + + +def pytest_runtest_teardown(item: Item, nextitem: Item | None) -> None: + _update_current_test_var(item, "teardown") + item.session._setupstate.teardown_exact(nextitem) + _update_current_test_var(item, None) + + +def _update_current_test_var( + item: Item, when: Literal["setup", "call", "teardown"] | None +) -> None: + """Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage. + + If ``when`` is None, delete ``PYTEST_CURRENT_TEST`` from the environment. + """ + var_name = "PYTEST_CURRENT_TEST" + if when: + value = f"{item.nodeid} ({when})" + # don't allow null bytes on environment variables (see #2644, #2957) + value = value.replace("\x00", "(null)") + os.environ[var_name] = value + else: + os.environ.pop(var_name) + + +def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None: + if report.when in ("setup", "teardown"): + if report.failed: + # category, shortletter, verbose-word + return "error", "E", "ERROR" + elif report.skipped: + return "skipped", "s", "SKIPPED" + else: + return "", "", "" + return None + + +# +# Implementation + + +def call_and_report( + item: Item, when: Literal["setup", "call", "teardown"], log: bool = True, **kwds +) -> TestReport: + ihook = item.ihook + if when == "setup": + runtest_hook: Callable[..., None] = ihook.pytest_runtest_setup + elif when == "call": + runtest_hook = ihook.pytest_runtest_call + elif when == "teardown": + runtest_hook = ihook.pytest_runtest_teardown + else: + assert False, f"Unhandled runtest hook case: {when}" + reraise: tuple[type[BaseException], ...] = (Exit,) + if not item.config.getoption("usepdb", False): + reraise += (KeyboardInterrupt,) + call = CallInfo.from_call( + lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise + ) + report: TestReport = ihook.pytest_runtest_makereport(item=item, call=call) + if log: + ihook.pytest_runtest_logreport(report=report) + if check_interactive_exception(call, report): + ihook.pytest_exception_interact(node=item, call=call, report=report) + return report + + +def check_interactive_exception(call: CallInfo[object], report: BaseReport) -> bool: + """Check whether the call raised an exception that should be reported as + interactive.""" + if call.excinfo is None: + # Didn't raise. + return False + if hasattr(report, "wasxfail"): + # Exception was expected. + return False + if isinstance(call.excinfo.value, (Skipped, bdb.BdbQuit)): + # Special control flow exception. + return False + return True + + +TResult = TypeVar("TResult", covariant=True) + + +@final +@dataclasses.dataclass +class CallInfo(Generic[TResult]): + """Result/Exception info of a function invocation.""" + + _result: TResult | None + #: The captured exception of the call, if it raised. + excinfo: ExceptionInfo[BaseException] | None + #: The system time when the call started, in seconds since the epoch. + start: float + #: The system time when the call ended, in seconds since the epoch. + stop: float + #: The call duration, in seconds. + duration: float + #: The context of invocation: "collect", "setup", "call" or "teardown". + when: Literal["collect", "setup", "call", "teardown"] + + def __init__( + self, + result: TResult | None, + excinfo: ExceptionInfo[BaseException] | None, + start: float, + stop: float, + duration: float, + when: Literal["collect", "setup", "call", "teardown"], + *, + _ispytest: bool = False, + ) -> None: + check_ispytest(_ispytest) + self._result = result + self.excinfo = excinfo + self.start = start + self.stop = stop + self.duration = duration + self.when = when + + @property + def result(self) -> TResult: + """The return value of the call, if it didn't raise. + + Can only be accessed if excinfo is None. + """ + if self.excinfo is not None: + raise AttributeError(f"{self!r} has no valid result") + # The cast is safe because an exception wasn't raised, hence + # _result has the expected function return type (which may be + # None, that's why a cast and not an assert). + return cast(TResult, self._result) + + @classmethod + def from_call( + cls, + func: Callable[[], TResult], + when: Literal["collect", "setup", "call", "teardown"], + reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None, + ) -> CallInfo[TResult]: + """Call func, wrapping the result in a CallInfo. + + :param func: + The function to call. Called without arguments. + :type func: Callable[[], _pytest.runner.TResult] + :param when: + The phase in which the function is called. + :param reraise: + Exception or exceptions that shall propagate if raised by the + function, instead of being wrapped in the CallInfo. + """ + excinfo = None + start = timing.time() + precise_start = timing.perf_counter() + try: + result: TResult | None = func() + except BaseException: + excinfo = ExceptionInfo.from_current() + if reraise is not None and isinstance(excinfo.value, reraise): + raise + result = None + # use the perf counter + precise_stop = timing.perf_counter() + duration = precise_stop - precise_start + stop = timing.time() + return cls( + start=start, + stop=stop, + duration=duration, + when=when, + result=result, + excinfo=excinfo, + _ispytest=True, + ) + + def __repr__(self) -> str: + if self.excinfo is None: + return f"" + return f"" + + +def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport: + return TestReport.from_item_and_call(item, call) + + +def pytest_make_collect_report(collector: Collector) -> CollectReport: + def collect() -> list[Item | Collector]: + # Before collecting, if this is a Directory, load the conftests. + # If a conftest import fails to load, it is considered a collection + # error of the Directory collector. This is why it's done inside of the + # CallInfo wrapper. + # + # Note: initial conftests are loaded early, not here. + if isinstance(collector, Directory): + collector.config.pluginmanager._loadconftestmodules( + collector.path, + collector.config.getoption("importmode"), + rootpath=collector.config.rootpath, + consider_namespace_packages=collector.config.getini( + "consider_namespace_packages" + ), + ) + + return list(collector.collect()) + + call = CallInfo.from_call( + collect, "collect", reraise=(KeyboardInterrupt, SystemExit) + ) + longrepr: None | tuple[str, int, str] | str | TerminalRepr = None + if not call.excinfo: + outcome: Literal["passed", "skipped", "failed"] = "passed" + else: + skip_exceptions = [Skipped] + unittest = sys.modules.get("unittest") + if unittest is not None: + skip_exceptions.append(unittest.SkipTest) + if isinstance(call.excinfo.value, tuple(skip_exceptions)): + outcome = "skipped" + r_ = collector._repr_failure_py(call.excinfo, "line") + assert isinstance(r_, ExceptionChainRepr), repr(r_) + r = r_.reprcrash + assert r + longrepr = (str(r.path), r.lineno, r.message) + else: + outcome = "failed" + errorinfo = collector.repr_failure(call.excinfo) + if not hasattr(errorinfo, "toterminal"): + assert isinstance(errorinfo, str) + errorinfo = CollectErrorRepr(errorinfo) + longrepr = errorinfo + result = call.result if not call.excinfo else None + rep = CollectReport(collector.nodeid, outcome, longrepr, result) + rep.call = call # type: ignore # see collect_one_node + return rep + + +class SetupState: + """Shared state for setting up/tearing down test items or collectors + in a session. + + Suppose we have a collection tree as follows: + + + + + + + + The SetupState maintains a stack. The stack starts out empty: + + [] + + During the setup phase of item1, setup(item1) is called. What it does + is: + + push session to stack, run session.setup() + push mod1 to stack, run mod1.setup() + push item1 to stack, run item1.setup() + + The stack is: + + [session, mod1, item1] + + While the stack is in this shape, it is allowed to add finalizers to + each of session, mod1, item1 using addfinalizer(). + + During the teardown phase of item1, teardown_exact(item2) is called, + where item2 is the next item to item1. What it does is: + + pop item1 from stack, run its teardowns + pop mod1 from stack, run its teardowns + + mod1 was popped because it ended its purpose with item1. The stack is: + + [session] + + During the setup phase of item2, setup(item2) is called. What it does + is: + + push mod2 to stack, run mod2.setup() + push item2 to stack, run item2.setup() + + Stack: + + [session, mod2, item2] + + During the teardown phase of item2, teardown_exact(None) is called, + because item2 is the last item. What it does is: + + pop item2 from stack, run its teardowns + pop mod2 from stack, run its teardowns + pop session from stack, run its teardowns + + Stack: + + [] + + The end! + """ + + def __init__(self) -> None: + # The stack is in the dict insertion order. + self.stack: dict[ + Node, + tuple[ + # Node's finalizers. + list[Callable[[], object]], + # Node's exception and original traceback, if its setup raised. + tuple[OutcomeException | Exception, types.TracebackType | None] | None, + ], + ] = {} + + def setup(self, item: Item) -> None: + """Setup objects along the collector chain to the item.""" + needed_collectors = item.listchain() + + # If a collector fails its setup, fail its entire subtree of items. + # The setup is not retried for each item - the same exception is used. + for col, (finalizers, exc) in self.stack.items(): + assert col in needed_collectors, "previous item was not torn down properly" + if exc: + raise exc[0].with_traceback(exc[1]) + + for col in needed_collectors[len(self.stack) :]: + assert col not in self.stack + # Push onto the stack. + self.stack[col] = ([col.teardown], None) + try: + col.setup() + except TEST_OUTCOME as exc: + self.stack[col] = (self.stack[col][0], (exc, exc.__traceback__)) + raise + + def addfinalizer(self, finalizer: Callable[[], object], node: Node) -> None: + """Attach a finalizer to the given node. + + The node must be currently active in the stack. + """ + assert node and not isinstance(node, tuple) + assert callable(finalizer) + assert node in self.stack, (node, self.stack) + self.stack[node][0].append(finalizer) + + def teardown_exact(self, nextitem: Item | None) -> None: + """Teardown the current stack up until reaching nodes that nextitem + also descends from. + + When nextitem is None (meaning we're at the last item), the entire + stack is torn down. + """ + needed_collectors = nextitem and nextitem.listchain() or [] + exceptions: list[BaseException] = [] + while self.stack: + if list(self.stack.keys()) == needed_collectors[: len(self.stack)]: + break + node, (finalizers, _) = self.stack.popitem() + these_exceptions = [] + while finalizers: + fin = finalizers.pop() + try: + fin() + except TEST_OUTCOME as e: + these_exceptions.append(e) + + if len(these_exceptions) == 1: + exceptions.extend(these_exceptions) + elif these_exceptions: + msg = f"errors while tearing down {node!r}" + exceptions.append(BaseExceptionGroup(msg, these_exceptions[::-1])) + + if len(exceptions) == 1: + raise exceptions[0] + elif exceptions: + raise BaseExceptionGroup("errors during test teardown", exceptions[::-1]) + if nextitem is None: + assert not self.stack + + +def collect_one_node(collector: Collector) -> CollectReport: + ihook = collector.ihook + ihook.pytest_collectstart(collector=collector) + rep: CollectReport = ihook.pytest_make_collect_report(collector=collector) + call = rep.__dict__.pop("call", None) + if call and check_interactive_exception(call, rep): + ihook.pytest_exception_interact(node=collector, call=call, report=rep) + return rep diff --git a/shared/package-files/2c/2c35c0a6f9c4a8331969963459bbdcf6cc844c434144a4084a7f03dffd7cc448/main.py b/shared/package-files/2c/2c35c0a6f9c4a8331969963459bbdcf6cc844c434144a4084a7f03dffd7cc448/main.py new file mode 100644 index 0000000000000000000000000000000000000000..20bd8d3eb1bea22b47bd67a262ef5d78e65c607f --- /dev/null +++ b/shared/package-files/2c/2c35c0a6f9c4a8331969963459bbdcf6cc844c434144a4084a7f03dffd7cc448/main.py @@ -0,0 +1,1667 @@ +# coding: utf-8 + +import sys +import os +import warnings +import glob +from importlib import import_module + + +import ruamel.yaml +from ruamel.yaml.error import UnsafeLoaderWarning, YAMLError # NOQA + +from ruamel.yaml.tokens import * # NOQA +from ruamel.yaml.events import * # NOQA +from ruamel.yaml.nodes import * # NOQA + +from ruamel.yaml.loader import BaseLoader, SafeLoader, Loader, RoundTripLoader # NOQA +from ruamel.yaml.dumper import BaseDumper, SafeDumper, Dumper, RoundTripDumper # NOQA +from ruamel.yaml.compat import StringIO, BytesIO, with_metaclass, nprint, nprintf # NOQA +from ruamel.yaml.resolver import VersionedResolver, Resolver # NOQA +from ruamel.yaml.representer import ( + BaseRepresenter, + SafeRepresenter, + Representer, + RoundTripRepresenter, +) +from ruamel.yaml.constructor import ( + BaseConstructor, + SafeConstructor, + Constructor, + RoundTripConstructor, +) +from ruamel.yaml.loader import Loader as UnsafeLoader +from ruamel.yaml.comments import CommentedMap, CommentedSeq, C_PRE + +if False: # MYPY + from typing import List, Set, Dict, Union, Any, Callable, Optional, Text # NOQA + from ruamel.yaml.compat import StreamType, StreamTextType, VersionType # NOQA + from pathlib import Path + +try: + from _ruamel_yaml import CParser, CEmitter # type: ignore +except: # NOQA + CParser = CEmitter = None + +# import io + + +# YAML is an acronym, i.e. spoken: rhymes with "camel". And thus a +# subset of abbreviations, which should be all caps according to PEP8 + + +class YAML: + def __init__(self, *, typ=None, pure=False, output=None, plug_ins=None): # input=None, + # type: (Any, Optional[Text], Any, Any, Any) -> None + """ + typ: 'rt'/None -> RoundTripLoader/RoundTripDumper, (default) + 'safe' -> SafeLoader/SafeDumper, + 'unsafe' -> normal/unsafe Loader/Dumper + 'base' -> baseloader + pure: if True only use Python modules + input/output: needed to work as context manager + plug_ins: a list of plug-in files + """ + + self.typ = ['rt'] if typ is None else (typ if isinstance(typ, list) else [typ]) + self.pure = pure + + # self._input = input + self._output = output + self._context_manager = None # type: Any + + self.plug_ins = [] # type: List[Any] + for pu in ([] if plug_ins is None else plug_ins) + self.official_plug_ins(): + file_name = pu.replace(os.sep, '.') + self.plug_ins.append(import_module(file_name)) + self.Resolver = ruamel.yaml.resolver.VersionedResolver # type: Any + self.allow_unicode = True + self.Reader = None # type: Any + self.Representer = None # type: Any + self.Constructor = None # type: Any + self.Scanner = None # type: Any + self.Serializer = None # type: Any + self.default_flow_style = None # type: Any + self.comment_handling = None + typ_found = 1 + setup_rt = False + if 'rt' in self.typ: + setup_rt = True + elif 'safe' in self.typ: + self.Emitter = ( + ruamel.yaml.emitter.Emitter if pure or CEmitter is None else CEmitter + ) + self.Representer = ruamel.yaml.representer.SafeRepresenter + self.Parser = ruamel.yaml.parser.Parser if pure or CParser is None else CParser + self.Composer = ruamel.yaml.composer.Composer + self.Constructor = ruamel.yaml.constructor.SafeConstructor + elif 'base' in self.typ: + self.Emitter = ruamel.yaml.emitter.Emitter + self.Representer = ruamel.yaml.representer.BaseRepresenter + self.Parser = ruamel.yaml.parser.Parser if pure or CParser is None else CParser + self.Composer = ruamel.yaml.composer.Composer + self.Constructor = ruamel.yaml.constructor.BaseConstructor + elif 'unsafe' in self.typ: + self.Emitter = ( + ruamel.yaml.emitter.Emitter if pure or CEmitter is None else CEmitter + ) + self.Representer = ruamel.yaml.representer.Representer + self.Parser = ruamel.yaml.parser.Parser if pure or CParser is None else CParser + self.Composer = ruamel.yaml.composer.Composer + self.Constructor = ruamel.yaml.constructor.Constructor + elif 'rtsc' in self.typ: + self.default_flow_style = False + # no optimized rt-dumper yet + self.Emitter = ruamel.yaml.emitter.Emitter + self.Serializer = ruamel.yaml.serializer.Serializer + self.Representer = ruamel.yaml.representer.RoundTripRepresenter + self.Scanner = ruamel.yaml.scanner.RoundTripScannerSC + # no optimized rt-parser yet + self.Parser = ruamel.yaml.parser.RoundTripParserSC + self.Composer = ruamel.yaml.composer.Composer + self.Constructor = ruamel.yaml.constructor.RoundTripConstructor + self.comment_handling = C_PRE + else: + setup_rt = True + typ_found = 0 + if setup_rt: + self.default_flow_style = False + # no optimized rt-dumper yet + self.Emitter = ruamel.yaml.emitter.Emitter + self.Serializer = ruamel.yaml.serializer.Serializer + self.Representer = ruamel.yaml.representer.RoundTripRepresenter + self.Scanner = ruamel.yaml.scanner.RoundTripScanner + # no optimized rt-parser yet + self.Parser = ruamel.yaml.parser.RoundTripParser + self.Composer = ruamel.yaml.composer.Composer + self.Constructor = ruamel.yaml.constructor.RoundTripConstructor + del setup_rt + self.stream = None + self.canonical = None + self.old_indent = None + self.width = None + self.line_break = None + + self.map_indent = None + self.sequence_indent = None + self.sequence_dash_offset = 0 + self.compact_seq_seq = None + self.compact_seq_map = None + self.sort_base_mapping_type_on_output = None # default: sort + + self.top_level_colon_align = None + self.prefix_colon = None + self.version = None + self.preserve_quotes = None + self.allow_duplicate_keys = False # duplicate keys in map, set + self.encoding = 'utf-8' + self.explicit_start = None + self.explicit_end = None + self.tags = None + self.default_style = None + self.top_level_block_style_scalar_no_indent_error_1_1 = False + # directives end indicator with single scalar document + self.scalar_after_indicator = None + # [a, b: 1, c: {d: 2}] vs. [a, {b: 1}, {c: {d: 2}}] + self.brace_single_entry_mapping_in_flow_sequence = False + for module in self.plug_ins: + if getattr(module, 'typ', None) in self.typ: + typ_found += 1 + module.init_typ(self) + break + if typ_found == 0: + raise NotImplementedError( + 'typ "{}"not recognised (need to install plug-in?)'.format(self.typ) + ) + + @property + def reader(self): + # type: () -> Any + try: + return self._reader # type: ignore + except AttributeError: + self._reader = self.Reader(None, loader=self) + return self._reader + + @property + def scanner(self): + # type: () -> Any + try: + return self._scanner # type: ignore + except AttributeError: + self._scanner = self.Scanner(loader=self) + return self._scanner + + @property + def parser(self): + # type: () -> Any + attr = '_' + sys._getframe().f_code.co_name + if not hasattr(self, attr): + if self.Parser is not CParser: + setattr(self, attr, self.Parser(loader=self)) + else: + if getattr(self, '_stream', None) is None: + # wait for the stream + return None + else: + # if not hasattr(self._stream, 'read') and hasattr(self._stream, 'open'): + # # pathlib.Path() instance + # setattr(self, attr, CParser(self._stream)) + # else: + setattr(self, attr, CParser(self._stream)) + # self._parser = self._composer = self + # nprint('scanner', self.loader.scanner) + + return getattr(self, attr) + + @property + def composer(self): + # type: () -> Any + attr = '_' + sys._getframe().f_code.co_name + if not hasattr(self, attr): + setattr(self, attr, self.Composer(loader=self)) + return getattr(self, attr) + + @property + def constructor(self): + # type: () -> Any + attr = '_' + sys._getframe().f_code.co_name + if not hasattr(self, attr): + cnst = self.Constructor(preserve_quotes=self.preserve_quotes, loader=self) + cnst.allow_duplicate_keys = self.allow_duplicate_keys + setattr(self, attr, cnst) + return getattr(self, attr) + + @property + def resolver(self): + # type: () -> Any + attr = '_' + sys._getframe().f_code.co_name + if not hasattr(self, attr): + setattr(self, attr, self.Resolver(version=self.version, loader=self)) + return getattr(self, attr) + + @property + def emitter(self): + # type: () -> Any + attr = '_' + sys._getframe().f_code.co_name + if not hasattr(self, attr): + if self.Emitter is not CEmitter: + _emitter = self.Emitter( + None, + canonical=self.canonical, + indent=self.old_indent, + width=self.width, + allow_unicode=self.allow_unicode, + line_break=self.line_break, + prefix_colon=self.prefix_colon, + brace_single_entry_mapping_in_flow_sequence=self.brace_single_entry_mapping_in_flow_sequence, # NOQA + dumper=self, + ) + setattr(self, attr, _emitter) + if self.map_indent is not None: + _emitter.best_map_indent = self.map_indent + if self.sequence_indent is not None: + _emitter.best_sequence_indent = self.sequence_indent + if self.sequence_dash_offset is not None: + _emitter.sequence_dash_offset = self.sequence_dash_offset + # _emitter.block_seq_indent = self.sequence_dash_offset + if self.compact_seq_seq is not None: + _emitter.compact_seq_seq = self.compact_seq_seq + if self.compact_seq_map is not None: + _emitter.compact_seq_map = self.compact_seq_map + else: + if getattr(self, '_stream', None) is None: + # wait for the stream + return None + return None + return getattr(self, attr) + + @property + def serializer(self): + # type: () -> Any + attr = '_' + sys._getframe().f_code.co_name + if not hasattr(self, attr): + setattr( + self, + attr, + self.Serializer( + encoding=self.encoding, + explicit_start=self.explicit_start, + explicit_end=self.explicit_end, + version=self.version, + tags=self.tags, + dumper=self, + ), + ) + return getattr(self, attr) + + @property + def representer(self): + # type: () -> Any + attr = '_' + sys._getframe().f_code.co_name + if not hasattr(self, attr): + repres = self.Representer( + default_style=self.default_style, + default_flow_style=self.default_flow_style, + dumper=self, + ) + if self.sort_base_mapping_type_on_output is not None: + repres.sort_base_mapping_type_on_output = self.sort_base_mapping_type_on_output + setattr(self, attr, repres) + return getattr(self, attr) + + def scan(self, stream): + # type: (StreamTextType) -> Any + """ + Scan a YAML stream and produce scanning tokens. + """ + if not hasattr(stream, 'read') and hasattr(stream, 'open'): + # pathlib.Path() instance + with stream.open('rb') as fp: + return self.scan(fp) + _, parser = self.get_constructor_parser(stream) + try: + while self.scanner.check_token(): + yield self.scanner.get_token() + finally: + parser.dispose() + try: + self._reader.reset_reader() + except AttributeError: + pass + try: + self._scanner.reset_scanner() + except AttributeError: + pass + + def parse(self, stream): + # type: (StreamTextType) -> Any + """ + Parse a YAML stream and produce parsing events. + """ + if not hasattr(stream, 'read') and hasattr(stream, 'open'): + # pathlib.Path() instance + with stream.open('rb') as fp: + return self.parse(fp) + _, parser = self.get_constructor_parser(stream) + try: + while parser.check_event(): + yield parser.get_event() + finally: + parser.dispose() + try: + self._reader.reset_reader() + except AttributeError: + pass + try: + self._scanner.reset_scanner() + except AttributeError: + pass + + def compose(self, stream): + # type: (Union[Path, StreamTextType]) -> Any + """ + Parse the first YAML document in a stream + and produce the corresponding representation tree. + """ + if not hasattr(stream, 'read') and hasattr(stream, 'open'): + # pathlib.Path() instance + with stream.open('rb') as fp: + return self.compose(fp) + constructor, parser = self.get_constructor_parser(stream) + try: + return constructor.composer.get_single_node() + finally: + parser.dispose() + try: + self._reader.reset_reader() + except AttributeError: + pass + try: + self._scanner.reset_scanner() + except AttributeError: + pass + + def compose_all(self, stream): + # type: (Union[Path, StreamTextType]) -> Any + """ + Parse all YAML documents in a stream + and produce corresponding representation trees. + """ + constructor, parser = self.get_constructor_parser(stream) + try: + while constructor.composer.check_node(): + yield constructor.composer.get_node() + finally: + parser.dispose() + try: + self._reader.reset_reader() + except AttributeError: + pass + try: + self._scanner.reset_scanner() + except AttributeError: + pass + + # separate output resolver? + + # def load(self, stream=None): + # if self._context_manager: + # if not self._input: + # raise TypeError("Missing input stream while dumping from context manager") + # for data in self._context_manager.load(): + # yield data + # return + # if stream is None: + # raise TypeError("Need a stream argument when not loading from context manager") + # return self.load_one(stream) + + def load(self, stream): + # type: (Union[Path, StreamTextType]) -> Any + """ + at this point you either have the non-pure Parser (which has its own reader and + scanner) or you have the pure Parser. + If the pure Parser is set, then set the Reader and Scanner, if not already set. + If either the Scanner or Reader are set, you cannot use the non-pure Parser, + so reset it to the pure parser and set the Reader resp. Scanner if necessary + """ + if not hasattr(stream, 'read') and hasattr(stream, 'open'): + # pathlib.Path() instance + with stream.open('rb') as fp: + return self.load(fp) + constructor, parser = self.get_constructor_parser(stream) + try: + return constructor.get_single_data() + finally: + parser.dispose() + try: + self._reader.reset_reader() + except AttributeError: + pass + try: + self._scanner.reset_scanner() + except AttributeError: + pass + + def load_all(self, stream): # *, skip=None): + # type: (Union[Path, StreamTextType]) -> Any + if not hasattr(stream, 'read') and hasattr(stream, 'open'): + # pathlib.Path() instance + with stream.open('r') as fp: + for d in self.load_all(fp): + yield d + return + # if skip is None: + # skip = [] + # elif isinstance(skip, int): + # skip = [skip] + constructor, parser = self.get_constructor_parser(stream) + try: + while constructor.check_data(): + yield constructor.get_data() + finally: + parser.dispose() + try: + self._reader.reset_reader() + except AttributeError: + pass + try: + self._scanner.reset_scanner() + except AttributeError: + pass + + def get_constructor_parser(self, stream): + # type: (StreamTextType) -> Any + """ + the old cyaml needs special setup, and therefore the stream + """ + if self.Parser is not CParser: + if self.Reader is None: + self.Reader = ruamel.yaml.reader.Reader + if self.Scanner is None: + self.Scanner = ruamel.yaml.scanner.Scanner + self.reader.stream = stream + else: + if self.Reader is not None: + if self.Scanner is None: + self.Scanner = ruamel.yaml.scanner.Scanner + self.Parser = ruamel.yaml.parser.Parser + self.reader.stream = stream + elif self.Scanner is not None: + if self.Reader is None: + self.Reader = ruamel.yaml.reader.Reader + self.Parser = ruamel.yaml.parser.Parser + self.reader.stream = stream + else: + # combined C level reader>scanner>parser + # does some calls to the resolver, e.g. BaseResolver.descend_resolver + # if you just initialise the CParser, to much of resolver.py + # is actually used + rslvr = self.Resolver + # if rslvr is ruamel.yaml.resolver.VersionedResolver: + # rslvr = ruamel.yaml.resolver.Resolver + + class XLoader(self.Parser, self.Constructor, rslvr): # type: ignore + def __init__(selfx, stream, version=self.version, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None # NOQA + CParser.__init__(selfx, stream) + selfx._parser = selfx._composer = selfx + self.Constructor.__init__(selfx, loader=selfx) + selfx.allow_duplicate_keys = self.allow_duplicate_keys + rslvr.__init__(selfx, version=version, loadumper=selfx) + + self._stream = stream + loader = XLoader(stream) + return loader, loader + return self.constructor, self.parser + + def emit(self, events, stream): + # type: (Any, Any) -> None + """ + Emit YAML parsing events into a stream. + If stream is None, return the produced string instead. + """ + _, _, emitter = self.get_serializer_representer_emitter(stream, None) + try: + for event in events: + emitter.emit(event) + finally: + try: + emitter.dispose() + except AttributeError: + raise + + def serialize(self, node, stream): + # type: (Any, Optional[StreamType]) -> Any + """ + Serialize a representation tree into a YAML stream. + If stream is None, return the produced string instead. + """ + self.serialize_all([node], stream) + + def serialize_all(self, nodes, stream): + # type: (Any, Optional[StreamType]) -> Any + """ + Serialize a sequence of representation trees into a YAML stream. + If stream is None, return the produced string instead. + """ + serializer, _, emitter = self.get_serializer_representer_emitter(stream, None) + try: + serializer.open() + for node in nodes: + serializer.serialize(node) + serializer.close() + finally: + try: + emitter.dispose() + except AttributeError: + raise + + def dump(self, data, stream=None, *, transform=None): + # type: (Any, Union[Path, StreamType], Any, Any) -> Any + if self._context_manager: + if not self._output: + raise TypeError('Missing output stream while dumping from context manager') + if transform is not None: + raise TypeError( + '{}.dump() in the context manager cannot have transform keyword ' + ''.format(self.__class__.__name__) + ) + self._context_manager.dump(data) + else: # old style + if stream is None: + raise TypeError('Need a stream argument when not dumping from context manager') + return self.dump_all([data], stream, transform=transform) + + def dump_all(self, documents, stream, *, transform=None): + # type: (Any, Union[Path, StreamType], Any) -> Any + if self._context_manager: + raise NotImplementedError + self._output = stream + self._context_manager = YAMLContextManager(self, transform=transform) + for data in documents: + self._context_manager.dump(data) + self._context_manager.teardown_output() + self._output = None + self._context_manager = None + + def Xdump_all(self, documents, stream, *, transform=None): + # type: (Any, Any, Any) -> Any + """ + Serialize a sequence of Python objects into a YAML stream. + """ + if not hasattr(stream, 'write') and hasattr(stream, 'open'): + # pathlib.Path() instance + with stream.open('w') as fp: + return self.dump_all(documents, fp, transform=transform) + # The stream should have the methods `write` and possibly `flush`. + if self.top_level_colon_align is True: + tlca = max([len(str(x)) for x in documents[0]]) # type: Any + else: + tlca = self.top_level_colon_align + if transform is not None: + fstream = stream + if self.encoding is None: + stream = StringIO() + else: + stream = BytesIO() + serializer, representer, emitter = self.get_serializer_representer_emitter( + stream, tlca + ) + try: + self.serializer.open() + for data in documents: + try: + self.representer.represent(data) + except AttributeError: + # nprint(dir(dumper._representer)) + raise + self.serializer.close() + finally: + try: + self.emitter.dispose() + except AttributeError: + raise + # self.dumper.dispose() # cyaml + delattr(self, '_serializer') + delattr(self, '_emitter') + if transform: + val = stream.getvalue() + if self.encoding: + val = val.decode(self.encoding) + if fstream is None: + transform(val) + else: + fstream.write(transform(val)) + return None + + def get_serializer_representer_emitter(self, stream, tlca): + # type: (StreamType, Any) -> Any + # we have only .Serializer to deal with (vs .Reader & .Scanner), much simpler + if self.Emitter is not CEmitter: + if self.Serializer is None: + self.Serializer = ruamel.yaml.serializer.Serializer + self.emitter.stream = stream + self.emitter.top_level_colon_align = tlca + if self.scalar_after_indicator is not None: + self.emitter.scalar_after_indicator = self.scalar_after_indicator + return self.serializer, self.representer, self.emitter + if self.Serializer is not None: + # cannot set serializer with CEmitter + self.Emitter = ruamel.yaml.emitter.Emitter + self.emitter.stream = stream + self.emitter.top_level_colon_align = tlca + if self.scalar_after_indicator is not None: + self.emitter.scalar_after_indicator = self.scalar_after_indicator + return self.serializer, self.representer, self.emitter + # C routines + + rslvr = ( + ruamel.yaml.resolver.BaseResolver + if 'base' in self.typ + else ruamel.yaml.resolver.Resolver + ) + + class XDumper(CEmitter, self.Representer, rslvr): # type: ignore + def __init__( + selfx, + 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__( + selfx, + 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, + ) + selfx._emitter = selfx._serializer = selfx._representer = selfx + self.Representer.__init__( + selfx, default_style=default_style, default_flow_style=default_flow_style + ) + rslvr.__init__(selfx) + + self._stream = stream + dumper = XDumper( + stream, + default_style=self.default_style, + default_flow_style=self.default_flow_style, + canonical=self.canonical, + indent=self.old_indent, + width=self.width, + allow_unicode=self.allow_unicode, + line_break=self.line_break, + explicit_start=self.explicit_start, + explicit_end=self.explicit_end, + version=self.version, + tags=self.tags, + ) + self._emitter = self._serializer = dumper + return dumper, dumper, dumper + + # basic types + def map(self, **kw): + # type: (Any) -> Any + if 'rt' in self.typ: + return CommentedMap(**kw) + else: + return dict(**kw) + + def seq(self, *args): + # type: (Any) -> Any + if 'rt' in self.typ: + return CommentedSeq(*args) + else: + return list(*args) + + # helpers + def official_plug_ins(self): + # type: () -> Any + """search for list of subdirs that are plug-ins, if __file__ is not available, e.g. + single file installers that are not properly emulating a file-system (issue 324) + no plug-ins will be found. If any are packaged, you know which file that are + and you can explicitly provide it during instantiation: + yaml = ruamel.yaml.YAML(plug_ins=['ruamel/yaml/jinja2/__plug_in__']) + """ + try: + bd = os.path.dirname(__file__) + except NameError: + return [] + gpbd = os.path.dirname(os.path.dirname(bd)) + res = [x.replace(gpbd, "")[1:-3] for x in glob.glob(bd + '/*/__plug_in__.py')] + return res + + def register_class(self, cls): + # type:(Any) -> Any + """ + register a class for dumping loading + - if it has attribute yaml_tag use that to register, else use class name + - if it has methods to_yaml/from_yaml use those to dump/load else dump attributes + as mapping + """ + tag = getattr(cls, 'yaml_tag', '!' + cls.__name__) + try: + self.representer.add_representer(cls, cls.to_yaml) + except AttributeError: + + def t_y(representer, data): + # type: (Any, Any) -> Any + return representer.represent_yaml_object( + tag, data, cls, flow_style=representer.default_flow_style + ) + + self.representer.add_representer(cls, t_y) + try: + self.constructor.add_constructor(tag, cls.from_yaml) + except AttributeError: + + def f_y(constructor, node): + # type: (Any, Any) -> Any + return constructor.construct_yaml_object(node, cls) + + self.constructor.add_constructor(tag, f_y) + return cls + + # ### context manager + + def __enter__(self): + # type: () -> Any + self._context_manager = YAMLContextManager(self) + return self + + def __exit__(self, typ, value, traceback): + # type: (Any, Any, Any) -> None + if typ: + nprint('typ', typ) + self._context_manager.teardown_output() + # self._context_manager.teardown_input() + self._context_manager = None + + # ### backwards compatibility + def _indent(self, mapping=None, sequence=None, offset=None): + # type: (Any, Any, Any) -> None + if mapping is not None: + self.map_indent = mapping + if sequence is not None: + self.sequence_indent = sequence + if offset is not None: + self.sequence_dash_offset = offset + + @property + def indent(self): + # type: () -> Any + return self._indent + + @indent.setter + def indent(self, val): + # type: (Any) -> None + self.old_indent = val + + @property + def block_seq_indent(self): + # type: () -> Any + return self.sequence_dash_offset + + @block_seq_indent.setter + def block_seq_indent(self, val): + # type: (Any) -> None + self.sequence_dash_offset = val + + def compact(self, seq_seq=None, seq_map=None): + # type: (Any, Any) -> None + self.compact_seq_seq = seq_seq + self.compact_seq_map = seq_map + + +class YAMLContextManager: + def __init__(self, yaml, transform=None): + # type: (Any, Any) -> None # used to be: (Any, Optional[Callable]) -> None + self._yaml = yaml + self._output_inited = False + self._output_path = None + self._output = self._yaml._output + self._transform = transform + + # self._input_inited = False + # self._input = input + # self._input_path = None + # self._transform = yaml.transform + # self._fstream = None + + if not hasattr(self._output, 'write') and hasattr(self._output, 'open'): + # pathlib.Path() instance, open with the same mode + self._output_path = self._output + self._output = self._output_path.open('w') + + # if not hasattr(self._stream, 'write') and hasattr(stream, 'open'): + # if not hasattr(self._input, 'read') and hasattr(self._input, 'open'): + # # pathlib.Path() instance, open with the same mode + # self._input_path = self._input + # self._input = self._input_path.open('r') + + if self._transform is not None: + self._fstream = self._output + if self._yaml.encoding is None: + self._output = StringIO() + else: + self._output = BytesIO() + + def teardown_output(self): + # type: () -> None + if self._output_inited: + self._yaml.serializer.close() + else: + return + try: + self._yaml.emitter.dispose() + except AttributeError: + raise + # self.dumper.dispose() # cyaml + try: + delattr(self._yaml, '_serializer') + delattr(self._yaml, '_emitter') + except AttributeError: + raise + if self._transform: + val = self._output.getvalue() + if self._yaml.encoding: + val = val.decode(self._yaml.encoding) + if self._fstream is None: + self._transform(val) + else: + self._fstream.write(self._transform(val)) + self._fstream.flush() + self._output = self._fstream # maybe not necessary + if self._output_path is not None: + self._output.close() + + def init_output(self, first_data): + # type: (Any) -> None + if self._yaml.top_level_colon_align is True: + tlca = max([len(str(x)) for x in first_data]) # type: Any + else: + tlca = self._yaml.top_level_colon_align + self._yaml.get_serializer_representer_emitter(self._output, tlca) + self._yaml.serializer.open() + self._output_inited = True + + def dump(self, data): + # type: (Any) -> None + if not self._output_inited: + self.init_output(data) + try: + self._yaml.representer.represent(data) + except AttributeError: + # nprint(dir(dumper._representer)) + raise + + # def teardown_input(self): + # pass + # + # def init_input(self): + # # set the constructor and parser on YAML() instance + # self._yaml.get_constructor_parser(stream) + # + # def load(self): + # if not self._input_inited: + # self.init_input() + # try: + # while self._yaml.constructor.check_data(): + # yield self._yaml.constructor.get_data() + # finally: + # parser.dispose() + # try: + # self._reader.reset_reader() # type: ignore + # except AttributeError: + # pass + # try: + # self._scanner.reset_scanner() # type: ignore + # except AttributeError: + # pass + + +def yaml_object(yml): + # type: (Any) -> Any + """ decorator for classes that needs to dump/load objects + The tag for such objects is taken from the class attribute yaml_tag (or the + class name in lowercase in case unavailable) + If methods to_yaml and/or from_yaml are available, these are called for dumping resp. + loading, default routines (dumping a mapping of the attributes) used otherwise. + """ + + def yo_deco(cls): + # type: (Any) -> Any + tag = getattr(cls, 'yaml_tag', '!' + cls.__name__) + try: + yml.representer.add_representer(cls, cls.to_yaml) + except AttributeError: + + def t_y(representer, data): + # type: (Any, Any) -> Any + return representer.represent_yaml_object( + tag, data, cls, flow_style=representer.default_flow_style + ) + + yml.representer.add_representer(cls, t_y) + try: + yml.constructor.add_constructor(tag, cls.from_yaml) + except AttributeError: + + def f_y(constructor, node): + # type: (Any, Any) -> Any + return constructor.construct_yaml_object(node, cls) + + yml.constructor.add_constructor(tag, f_y) + return cls + + return yo_deco + + +######################################################################################## +def warn_deprecation(fun, method, arg=''): + # type: (Any, Any, str) -> None + from ruamel.yaml.compat import _F + + warnings.warn( + _F( + '\n{fun} will be removed, use\n\n yaml=YAML({arg})\n yaml.{method}(...)\n\ninstead', # NOQA + fun=fun, + method=method, + arg=arg, + ), + PendingDeprecationWarning, # this will show when testing with pytest/tox + stacklevel=3, + ) + + +######################################################################################## + + +def scan(stream, Loader=Loader): + # type: (StreamTextType, Any) -> Any + """ + Scan a YAML stream and produce scanning tokens. + """ + warn_deprecation('scan', 'scan', arg="typ='unsafe', pure=True") + loader = Loader(stream) + try: + while loader.scanner.check_token(): + yield loader.scanner.get_token() + finally: + loader._parser.dispose() + + +def parse(stream, Loader=Loader): + # type: (StreamTextType, Any) -> Any + """ + Parse a YAML stream and produce parsing events. + """ + warn_deprecation('parse', 'parse', arg="typ='unsafe', pure=True") + loader = Loader(stream) + try: + while loader._parser.check_event(): + yield loader._parser.get_event() + finally: + loader._parser.dispose() + + +def compose(stream, Loader=Loader): + # type: (StreamTextType, Any) -> Any + """ + Parse the first YAML document in a stream + and produce the corresponding representation tree. + """ + warn_deprecation('compose', 'compose', arg="typ='unsafe', pure=True") + loader = Loader(stream) + try: + return loader.get_single_node() + finally: + loader.dispose() + + +def compose_all(stream, Loader=Loader): + # type: (StreamTextType, Any) -> Any + """ + Parse all YAML documents in a stream + and produce corresponding representation trees. + """ + warn_deprecation('compose', 'compose', arg="typ='unsafe', pure=True") + loader = Loader(stream) + try: + while loader.check_node(): + yield loader._composer.get_node() + finally: + loader._parser.dispose() + + +def load(stream, Loader=None, version=None, preserve_quotes=None): + # type: (Any, Any, Any, Any) -> Any + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + """ + warn_deprecation('load', 'load', arg="typ='unsafe', pure=True") + if Loader is None: + warnings.warn(UnsafeLoaderWarning.text, UnsafeLoaderWarning, stacklevel=2) + Loader = UnsafeLoader + loader = Loader(stream, version, preserve_quotes=preserve_quotes) # type: Any + try: + return loader._constructor.get_single_data() + finally: + loader._parser.dispose() + try: + loader._reader.reset_reader() + except AttributeError: + pass + try: + loader._scanner.reset_scanner() + except AttributeError: + pass + + +def load_all(stream, Loader=None, version=None, preserve_quotes=None): + # type: (Any, Any, Any, Any) -> Any # NOQA + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + """ + warn_deprecation('load_all', 'load_all', arg="typ='unsafe', pure=True") + if Loader is None: + warnings.warn(UnsafeLoaderWarning.text, UnsafeLoaderWarning, stacklevel=2) + Loader = UnsafeLoader + loader = Loader(stream, version, preserve_quotes=preserve_quotes) # type: Any + try: + while loader._constructor.check_data(): + yield loader._constructor.get_data() + finally: + loader._parser.dispose() + try: + loader._reader.reset_reader() + except AttributeError: + pass + try: + loader._scanner.reset_scanner() + except AttributeError: + pass + + +def safe_load(stream, version=None): + # type: (StreamTextType, Optional[VersionType]) -> Any + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + Resolve only basic YAML tags. + """ + warn_deprecation('safe_load', 'load', arg="typ='safe', pure=True") + return load(stream, SafeLoader, version) + + +def safe_load_all(stream, version=None): + # type: (StreamTextType, Optional[VersionType]) -> Any + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + Resolve only basic YAML tags. + """ + warn_deprecation('safe_load_all', 'load_all', arg="typ='safe', pure=True") + return load_all(stream, SafeLoader, version) + + +def round_trip_load(stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> Any + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + Resolve only basic YAML tags. + """ + warn_deprecation('round_trip_load_all', 'load') + return load(stream, RoundTripLoader, version, preserve_quotes=preserve_quotes) + + +def round_trip_load_all(stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> Any + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + Resolve only basic YAML tags. + """ + warn_deprecation('round_trip_load_all', 'load_all') + return load_all(stream, RoundTripLoader, version, preserve_quotes=preserve_quotes) + + +def emit( + events, + stream=None, + Dumper=Dumper, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, +): + # type: (Any, Optional[StreamType], Any, Optional[bool], Union[int, None], Optional[int], Optional[bool], Any) -> Any # NOQA + """ + Emit YAML parsing events into a stream. + If stream is None, return the produced string instead. + """ + warn_deprecation('emit', 'emit', arg="typ='safe', pure=True") + getvalue = None + if stream is None: + stream = StringIO() + getvalue = stream.getvalue + dumper = Dumper( + stream, + canonical=canonical, + indent=indent, + width=width, + allow_unicode=allow_unicode, + line_break=line_break, + ) + try: + for event in events: + dumper.emit(event) + finally: + try: + dumper._emitter.dispose() + except AttributeError: + raise + dumper.dispose() # cyaml + if getvalue is not None: + return getvalue() + + +enc = None + + +def serialize_all( + nodes, + stream=None, + Dumper=Dumper, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, + encoding=enc, + explicit_start=None, + explicit_end=None, + version=None, + tags=None, +): + # type: (Any, Optional[StreamType], Any, Any, Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Optional[VersionType], Any) -> Any # NOQA + """ + Serialize a sequence of representation trees into a YAML stream. + If stream is None, return the produced string instead. + """ + warn_deprecation('serialize_all', 'serialize_all', arg="typ='safe', pure=True") + getvalue = None + if stream is None: + if encoding is None: + stream = StringIO() + else: + stream = BytesIO() + getvalue = stream.getvalue + dumper = Dumper( + stream, + canonical=canonical, + indent=indent, + width=width, + allow_unicode=allow_unicode, + line_break=line_break, + encoding=encoding, + version=version, + tags=tags, + explicit_start=explicit_start, + explicit_end=explicit_end, + ) + try: + dumper._serializer.open() + for node in nodes: + dumper.serialize(node) + dumper._serializer.close() + finally: + try: + dumper._emitter.dispose() + except AttributeError: + raise + dumper.dispose() # cyaml + if getvalue is not None: + return getvalue() + + +def serialize(node, stream=None, Dumper=Dumper, **kwds): + # type: (Any, Optional[StreamType], Any, Any) -> Any + """ + Serialize a representation tree into a YAML stream. + If stream is None, return the produced string instead. + """ + warn_deprecation('serialize', 'serialize', arg="typ='safe', pure=True") + return serialize_all([node], stream, Dumper=Dumper, **kwds) + + +def dump_all( + documents, + stream=None, + Dumper=Dumper, + default_style=None, + default_flow_style=None, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, + encoding=enc, + explicit_start=None, + explicit_end=None, + version=None, + tags=None, + block_seq_indent=None, + top_level_colon_align=None, + prefix_colon=None, +): + # type: (Any, Optional[StreamType], Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> Any # NOQA + """ + Serialize a sequence of Python objects into a YAML stream. + If stream is None, return the produced string instead. + """ + warn_deprecation('dump_all', 'dump_all', arg="typ='unsafe', pure=True") + getvalue = None + if top_level_colon_align is True: + top_level_colon_align = max([len(str(x)) for x in documents[0]]) + if stream is None: + if encoding is None: + stream = StringIO() + else: + stream = BytesIO() + getvalue = stream.getvalue + dumper = Dumper( + stream, + default_style=default_style, + default_flow_style=default_flow_style, + canonical=canonical, + indent=indent, + width=width, + allow_unicode=allow_unicode, + line_break=line_break, + encoding=encoding, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + tags=tags, + block_seq_indent=block_seq_indent, + top_level_colon_align=top_level_colon_align, + prefix_colon=prefix_colon, + ) + try: + dumper._serializer.open() + for data in documents: + try: + dumper._representer.represent(data) + except AttributeError: + # nprint(dir(dumper._representer)) + raise + dumper._serializer.close() + finally: + try: + dumper._emitter.dispose() + except AttributeError: + raise + dumper.dispose() # cyaml + if getvalue is not None: + return getvalue() + return None + + +def dump( + data, + stream=None, + Dumper=Dumper, + default_style=None, + default_flow_style=None, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, + encoding=enc, + explicit_start=None, + explicit_end=None, + version=None, + tags=None, + block_seq_indent=None, +): + # type: (Any, Optional[StreamType], Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Optional[VersionType], Any, Any) -> Optional[Any] # NOQA + """ + Serialize a Python object into a YAML stream. + If stream is None, return the produced string instead. + + default_style ∈ None, '', '"', "'", '|', '>' + + """ + warn_deprecation('dump', 'dump', arg="typ='unsafe', pure=True") + return dump_all( + [data], + stream, + Dumper=Dumper, + default_style=default_style, + default_flow_style=default_flow_style, + canonical=canonical, + indent=indent, + width=width, + allow_unicode=allow_unicode, + line_break=line_break, + encoding=encoding, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + tags=tags, + block_seq_indent=block_seq_indent, + ) + + +def safe_dump_all(documents, stream=None, **kwds): + # type: (Any, Optional[StreamType], Any) -> Optional[Any] + """ + Serialize a sequence of Python objects into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + warn_deprecation('safe_dump_all', 'dump_all', arg="typ='safe', pure=True") + return dump_all(documents, stream, Dumper=SafeDumper, **kwds) + + +def safe_dump(data, stream=None, **kwds): + # type: (Any, Optional[StreamType], Any) -> Optional[Any] + """ + Serialize a Python object into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + warn_deprecation('safe_dump', 'dump', arg="typ='safe', pure=True") + return dump_all([data], stream, Dumper=SafeDumper, **kwds) + + +def round_trip_dump( + data, + stream=None, + Dumper=RoundTripDumper, + default_style=None, + default_flow_style=None, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, + encoding=enc, + explicit_start=None, + explicit_end=None, + version=None, + tags=None, + block_seq_indent=None, + top_level_colon_align=None, + prefix_colon=None, +): + # type: (Any, Optional[StreamType], Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Optional[VersionType], Any, Any, Any, Any) -> Optional[Any] # NOQA + allow_unicode = True if allow_unicode is None else allow_unicode + warn_deprecation('round_trip_dump', 'dump') + return dump_all( + [data], + stream, + Dumper=Dumper, + default_style=default_style, + default_flow_style=default_flow_style, + canonical=canonical, + indent=indent, + width=width, + allow_unicode=allow_unicode, + line_break=line_break, + encoding=encoding, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + tags=tags, + block_seq_indent=block_seq_indent, + top_level_colon_align=top_level_colon_align, + prefix_colon=prefix_colon, + ) + + +# Loader/Dumper are no longer composites, to get to the associated +# Resolver()/Representer(), etc., you need to instantiate the class + + +def add_implicit_resolver( + tag, regexp, first=None, Loader=None, Dumper=None, resolver=Resolver +): + # type: (Any, Any, Any, Any, Any, Any) -> None + """ + Add an implicit scalar detector. + If an implicit scalar value matches the given regexp, + the corresponding tag is assigned to the scalar. + first is a sequence of possible initial characters or None. + """ + if Loader is None and Dumper is None: + resolver.add_implicit_resolver(tag, regexp, first) + return + if Loader: + if hasattr(Loader, 'add_implicit_resolver'): + Loader.add_implicit_resolver(tag, regexp, first) + elif issubclass( + Loader, (BaseLoader, SafeLoader, ruamel.yaml.loader.Loader, RoundTripLoader) + ): + Resolver.add_implicit_resolver(tag, regexp, first) + else: + raise NotImplementedError + if Dumper: + if hasattr(Dumper, 'add_implicit_resolver'): + Dumper.add_implicit_resolver(tag, regexp, first) + elif issubclass( + Dumper, (BaseDumper, SafeDumper, ruamel.yaml.dumper.Dumper, RoundTripDumper) + ): + Resolver.add_implicit_resolver(tag, regexp, first) + else: + raise NotImplementedError + + +# this code currently not tested +def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=None, resolver=Resolver): + # type: (Any, Any, Any, Any, Any, Any) -> None + """ + Add a path based resolver for the given tag. + A path is a list of keys that forms a path + to a node in the representation tree. + Keys can be string values, integers, or None. + """ + if Loader is None and Dumper is None: + resolver.add_path_resolver(tag, path, kind) + return + if Loader: + if hasattr(Loader, 'add_path_resolver'): + Loader.add_path_resolver(tag, path, kind) + elif issubclass( + Loader, (BaseLoader, SafeLoader, ruamel.yaml.loader.Loader, RoundTripLoader) + ): + Resolver.add_path_resolver(tag, path, kind) + else: + raise NotImplementedError + if Dumper: + if hasattr(Dumper, 'add_path_resolver'): + Dumper.add_path_resolver(tag, path, kind) + elif issubclass( + Dumper, (BaseDumper, SafeDumper, ruamel.yaml.dumper.Dumper, RoundTripDumper) + ): + Resolver.add_path_resolver(tag, path, kind) + else: + raise NotImplementedError + + +def add_constructor(tag, object_constructor, Loader=None, constructor=Constructor): + # type: (Any, Any, Any, Any) -> None + """ + Add an object constructor for the given tag. + object_onstructor is a function that accepts a Loader instance + and a node object and produces the corresponding Python object. + """ + if Loader is None: + constructor.add_constructor(tag, object_constructor) + else: + if hasattr(Loader, 'add_constructor'): + Loader.add_constructor(tag, object_constructor) + return + if issubclass(Loader, BaseLoader): + BaseConstructor.add_constructor(tag, object_constructor) + elif issubclass(Loader, SafeLoader): + SafeConstructor.add_constructor(tag, object_constructor) + elif issubclass(Loader, Loader): + Constructor.add_constructor(tag, object_constructor) + elif issubclass(Loader, RoundTripLoader): + RoundTripConstructor.add_constructor(tag, object_constructor) + else: + raise NotImplementedError + + +def add_multi_constructor(tag_prefix, multi_constructor, Loader=None, constructor=Constructor): + # type: (Any, Any, Any, Any) -> None + """ + Add a multi-constructor for the given tag prefix. + Multi-constructor is called for a node if its tag starts with tag_prefix. + Multi-constructor accepts a Loader instance, a tag suffix, + and a node object and produces the corresponding Python object. + """ + if Loader is None: + constructor.add_multi_constructor(tag_prefix, multi_constructor) + else: + if False and hasattr(Loader, 'add_multi_constructor'): + Loader.add_multi_constructor(tag_prefix, constructor) + return + if issubclass(Loader, BaseLoader): + BaseConstructor.add_multi_constructor(tag_prefix, multi_constructor) + elif issubclass(Loader, SafeLoader): + SafeConstructor.add_multi_constructor(tag_prefix, multi_constructor) + elif issubclass(Loader, ruamel.yaml.loader.Loader): + Constructor.add_multi_constructor(tag_prefix, multi_constructor) + elif issubclass(Loader, RoundTripLoader): + RoundTripConstructor.add_multi_constructor(tag_prefix, multi_constructor) + else: + raise NotImplementedError + + +def add_representer(data_type, object_representer, Dumper=None, representer=Representer): + # type: (Any, Any, Any, Any) -> None + """ + Add a representer for the given type. + object_representer is a function accepting a Dumper instance + and an instance of the given data type + and producing the corresponding representation node. + """ + if Dumper is None: + representer.add_representer(data_type, object_representer) + else: + if hasattr(Dumper, 'add_representer'): + Dumper.add_representer(data_type, object_representer) + return + if issubclass(Dumper, BaseDumper): + BaseRepresenter.add_representer(data_type, object_representer) + elif issubclass(Dumper, SafeDumper): + SafeRepresenter.add_representer(data_type, object_representer) + elif issubclass(Dumper, Dumper): + Representer.add_representer(data_type, object_representer) + elif issubclass(Dumper, RoundTripDumper): + RoundTripRepresenter.add_representer(data_type, object_representer) + else: + raise NotImplementedError + + +# this code currently not tested +def add_multi_representer(data_type, multi_representer, Dumper=None, representer=Representer): + # type: (Any, Any, Any, Any) -> None + """ + Add a representer for the given type. + multi_representer is a function accepting a Dumper instance + and an instance of the given data type or subtype + and producing the corresponding representation node. + """ + if Dumper is None: + representer.add_multi_representer(data_type, multi_representer) + else: + if hasattr(Dumper, 'add_multi_representer'): + Dumper.add_multi_representer(data_type, multi_representer) + return + if issubclass(Dumper, BaseDumper): + BaseRepresenter.add_multi_representer(data_type, multi_representer) + elif issubclass(Dumper, SafeDumper): + SafeRepresenter.add_multi_representer(data_type, multi_representer) + elif issubclass(Dumper, Dumper): + Representer.add_multi_representer(data_type, multi_representer) + elif issubclass(Dumper, RoundTripDumper): + RoundTripRepresenter.add_multi_representer(data_type, multi_representer) + else: + raise NotImplementedError + + +class YAMLObjectMetaclass(type): + """ + The metaclass for YAMLObject. + """ + + def __init__(cls, name, bases, kwds): + # type: (Any, Any, Any) -> None + super().__init__(name, bases, kwds) + if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None: + cls.yaml_constructor.add_constructor(cls.yaml_tag, cls.from_yaml) # type: ignore + cls.yaml_representer.add_representer(cls, cls.to_yaml) # type: ignore + + +class YAMLObject(with_metaclass(YAMLObjectMetaclass)): # type: ignore + """ + An object that can dump itself to a YAML stream + and load itself from a YAML stream. + """ + + __slots__ = () # no direct instantiation, so allow immutable subclasses + + yaml_constructor = Constructor + yaml_representer = Representer + + yaml_tag = None # type: Any + yaml_flow_style = None # type: Any + + @classmethod + def from_yaml(cls, constructor, node): + # type: (Any, Any) -> Any + """ + Convert a representation node to a Python object. + """ + return constructor.construct_yaml_object(node, cls) + + @classmethod + def to_yaml(cls, representer, data): + # type: (Any, Any) -> Any + """ + Convert a Python object to a representation node. + """ + return representer.represent_yaml_object( + cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style + ) diff --git a/shared/package-files/2c/2c3a201f4589876100595e3f8a320a8ab62503a8bcec1fe475ac80ab7af8e94d/clamp_max_cpu_dispatch.h b/shared/package-files/2c/2c3a201f4589876100595e3f8a320a8ab62503a8bcec1fe475ac80ab7af8e94d/clamp_max_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f4e2e606f28f98b82b96985f1879a663c0a7f208 --- /dev/null +++ b/shared/package-files/2c/2c3a201f4589876100595e3f8a320a8ab62503a8bcec1fe475ac80ab7af8e94d/clamp_max_cpu_dispatch.h @@ -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 clamp_max(const at::Tensor & self, const at::Scalar & max); +TORCH_API at::Tensor & clamp_max_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & max); +TORCH_API at::Tensor & clamp_max_outf(const at::Tensor & self, const at::Scalar & max, at::Tensor & out); +TORCH_API at::Tensor & clamp_max_(at::Tensor & self, const at::Scalar & max); +TORCH_API at::Tensor clamp_max(const at::Tensor & self, const at::Tensor & max); +TORCH_API at::Tensor & clamp_max_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & max); +TORCH_API at::Tensor & clamp_max_outf(const at::Tensor & self, const at::Tensor & max, at::Tensor & out); +TORCH_API at::Tensor & clamp_max_(at::Tensor & self, const at::Tensor & max); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/2c/2c3ab41ec56c2429bfb8372e183d090a4b3a86290422108844dd67fb1aa2efd2/minitel1-nb b/shared/package-files/2c/2c3ab41ec56c2429bfb8372e183d090a4b3a86290422108844dd67fb1aa2efd2/minitel1-nb new file mode 100644 index 0000000000000000000000000000000000000000..16250a7e93f78814fcb069488c82383b4271d072 Binary files /dev/null and b/shared/package-files/2c/2c3ab41ec56c2429bfb8372e183d090a4b3a86290422108844dd67fb1aa2efd2/minitel1-nb differ diff --git a/shared/package-files/2c/2c3bc96391073e39de0def07514a30c64fc081939520ed482cb8349d33fcd96b/macrodata_jmulti_nc.txt b/shared/package-files/2c/2c3bc96391073e39de0def07514a30c64fc081939520ed482cb8349d33fcd96b/macrodata_jmulti_nc.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbf8a5124e413e60c528b8048ddb0a7919278fce --- /dev/null +++ b/shared/package-files/2c/2c3bc96391073e39de0def07514a30c64fc081939520ed482cb8349d33fcd96b/macrodata_jmulti_nc.txt @@ -0,0 +1,80 @@ +*** Sat, 3 Sep 2016 21:52:15 *** +VAR ESTIMATION RESULTS +endogenous variables: realcons realgdp realinv +exogenous variables: +deterministic variables: +endogenous lags: 4 +exogenous lags: 0 +sample range: [1960 Q1, 2009 Q3], T = 199 + +modulus of the eigenvalues of the reverse characteristic polynomial : +|z| = ( 1.5237 1.5237 2.1188 2.1188 4.0128 4.0128 1.5233 1.5233 1.1578 1.1578 1.0233 0.9937 ) +Legend: +======= + Equation 1 Equation 2 ... +------------------------------------------ +Variable 1 | Coefficient ... + | (Std. Dev.) + | {p - Value} + | [t - Value] +Variable 2 | ... +... +------------------------------------------ + + +Lagged endogenous term: +======================= + realcons realgdp realinv +------------------------------------------- +realcons(t-1)| 1.396 1.251 0.943 + | (0.112) (0.191) (0.137) + | {0.000} {0.000} {0.000} + | [12.500] [6.550] [6.862] +realgdp (t-1)| -0.234 0.591 -0.164 + | (0.087) (0.149) (0.107) + | {0.007} {0.000} {0.127} + | [-2.674] [3.956] [-1.526] +realinv (t-1)| 0.280 0.297 1.170 + | (0.102) (0.175) (0.126) + | {0.006} {0.090} {0.000} + | [2.734] [1.696] [9.292] +realcons(t-2)| -0.070 -0.617 -0.613 + | (0.188) (0.322) (0.232) + | {0.710} {0.055} {0.008} + | [-0.372] [-1.918] [-2.646] +realgdp (t-2)| 0.017 0.348 0.178 + | (0.127) (0.216) (0.156) + | {0.896} {0.108} {0.253} + | [0.131] [1.608] [1.144] +realinv (t-2)| -0.107 -0.424 -0.311 + | (0.162) (0.278) (0.200) + | {0.509} {0.127} {0.119} + | [-0.661] [-1.526] [-1.558] +realcons(t-3)| 0.100 -0.115 -0.146 + | (0.192) (0.329) (0.237) + | {0.604} {0.725} {0.538} + | [0.519] [-0.351] [-0.615] +realgdp (t-3)| 0.012 -0.165 -0.207 + | (0.126) (0.215) (0.155) + | {0.923} {0.442} {0.179} + | [0.097] [-0.769] [-1.343] +realinv (t-3)| -0.071 0.113 0.241 + | (0.160) (0.273) (0.197) + | {0.655} {0.679} {0.221} + | [-0.446] [0.414] [1.224] +realcons(t-4)| -0.448 -0.454 -0.112 + | (0.128) (0.219) (0.158) + | {0.000} {0.038} {0.475} + | [-3.497] [-2.075] [-0.714] +realgdp (t-4)| 0.224 0.201 0.155 + | (0.092) (0.157) (0.113) + | {0.014} {0.200} {0.169} + | [2.448] [1.282] [1.376] +realinv (t-4)| -0.111 -0.108 -0.201 + | (0.109) (0.187) (0.134) + | {0.310} {0.561} {0.136} + | [-1.016] [-0.581] [-1.492] +------------------------------------------- + + + diff --git a/shared/package-files/2c/2c3f5653e639956edb54ceccc82912196f4c5361598558cc079664f38f3fab53/test_qho_1d.py b/shared/package-files/2c/2c3f5653e639956edb54ceccc82912196f4c5361598558cc079664f38f3fab53/test_qho_1d.py new file mode 100644 index 0000000000000000000000000000000000000000..34e52c9e3a721496fc61f7d2b31414db15caa7a8 --- /dev/null +++ b/shared/package-files/2c/2c3f5653e639956edb54ceccc82912196f4c5361598558cc079664f38f3fab53/test_qho_1d.py @@ -0,0 +1,50 @@ +from sympy.core.numbers import (Rational, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.integrals.integrals import integrate +from sympy.simplify.simplify import simplify +from sympy.abc import omega, m, x +from sympy.physics.qho_1d import psi_n, E_n, coherent_state +from sympy.physics.quantum.constants import hbar + +nu = m * omega / hbar + + +def test_wavefunction(): + Psi = { + 0: (nu/pi)**Rational(1, 4) * exp(-nu * x**2 /2), + 1: (nu/pi)**Rational(1, 4) * sqrt(2*nu) * x * exp(-nu * x**2 /2), + 2: (nu/pi)**Rational(1, 4) * (2 * nu * x**2 - 1)/sqrt(2) * exp(-nu * x**2 /2), + 3: (nu/pi)**Rational(1, 4) * sqrt(nu/3) * (2 * nu * x**3 - 3 * x) * exp(-nu * x**2 /2) + } + for n in Psi: + assert simplify(psi_n(n, x, m, omega) - Psi[n]) == 0 + + +def test_norm(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + assert integrate(psi_n(i, x, 1, 1)**2, (x, -oo, oo)) == 1 + + +def test_orthogonality(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + for j in range(i + 1, n + 1): + assert integrate( + psi_n(i, x, 1, 1)*psi_n(j, x, 1, 1), (x, -oo, oo)) == 0 + + +def test_energies(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + assert E_n(i, omega) == hbar * omega * (i + S.Half) + +def test_coherent_state(n=10): + # Maximum "n" which is tested: + # test whether coherent state is the eigenstate of annihilation operator + alpha = Symbol("alpha") + for i in range(n + 1): + assert simplify(sqrt(n + 1) * coherent_state(n + 1, alpha)) == simplify(alpha * coherent_state(n, alpha)) diff --git a/shared/package-files/2c/2c409dd8b511f7f8b941094f9031579755472025e8b3a9bb1606c84d889213b9/namespace.py b/shared/package-files/2c/2c409dd8b511f7f8b941094f9031579755472025e8b3a9bb1606c84d889213b9/namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..120173b21fab3057ef3acf97a7e67d2e3733d8d7 --- /dev/null +++ b/shared/package-files/2c/2c409dd8b511f7f8b941094f9031579755472025e8b3a9bb1606c84d889213b9/namespace.py @@ -0,0 +1,614 @@ +from __future__ import annotations + +import operator +import warnings +from functools import reduce +from itertools import chain +from typing import TYPE_CHECKING, Any, Literal, Protocol, cast, overload + +import pandas as pd + +from narwhals._compliant import EagerNamespace +from narwhals._expression_parsing import ( + combine_alias_output_names, + combine_evaluate_output_names, +) +from narwhals._pandas_like.dataframe import PandasLikeDataFrame +from narwhals._pandas_like.expr import PandasLikeExpr +from narwhals._pandas_like.selectors import PandasSelectorNamespace +from narwhals._pandas_like.series import PandasLikeSeries +from narwhals._pandas_like.typing import NativeDataFrameT, NativeSeriesT +from narwhals._pandas_like.utils import ( + import_array_module, + is_dtype_pyarrow, + is_non_nullable_boolean, + set_index, +) +from narwhals._utils import check_column_names_are_unique, validate_separators + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + from typing import TypeAlias + + from narwhals._utils import Implementation, Version + from narwhals.typing import ( + CorrelationMethod, + IntoDType, + NormalizedSource, + PythonLiteral, + ) + + +Incomplete: TypeAlias = Any +"""Escape hatch, but leaving a trace that this isn't ideal.""" + + +_Vertical: TypeAlias = Literal[0] +_Horizontal: TypeAlias = Literal[1] +Axis: TypeAlias = Literal[_Vertical, _Horizontal] + +VERTICAL: _Vertical = 0 +HORIZONTAL: _Horizontal = 1 + + +class PandasLikeNamespace( + EagerNamespace[ + PandasLikeDataFrame, + PandasLikeSeries, + PandasLikeExpr, + NativeDataFrameT, + NativeSeriesT, + ] +): + @property + def _dataframe(self) -> type[PandasLikeDataFrame]: + return PandasLikeDataFrame + + @property + def _expr(self) -> type[PandasLikeExpr]: + return PandasLikeExpr + + @property + def _series(self) -> type[PandasLikeSeries]: + return PandasLikeSeries + + @property + def selectors(self) -> PandasSelectorNamespace: + return PandasSelectorNamespace.from_namespace(self) + + def __init__(self, implementation: Implementation, version: Version) -> None: + self._implementation = implementation + self._version = version + + def read_csv( + self, source: NormalizedSource, *, separator: str = ",", **kwds: Any + ) -> PandasLikeDataFrame: + validate_separators(separator, ("sep",), kwds) + ns = self._implementation.to_native_namespace() + native = ns.read_csv(source, sep=separator, **kwds) + return self._dataframe.from_native(native, context=self) + + def read_parquet(self, source: NormalizedSource, **kwds: Any) -> PandasLikeDataFrame: + ns = self._implementation.to_native_namespace() + return self._dataframe.from_native(ns.read_parquet(source, **kwds), context=self) + + def coalesce(self, *exprs: PandasLikeExpr) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + series = (s for _expr in exprs for s in _expr(df)) + return [ + reduce(lambda x, y: x.fill_null(y, strategy=None, limit=None), series) + ] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def lit(self, value: PythonLiteral, dtype: IntoDType | None) -> PandasLikeExpr: + def _lit_pandas_series(df: PandasLikeDataFrame) -> PandasLikeSeries: + if isinstance(value, (list, tuple, dict)): + try: + import pandas as pd # ignore-banned-import + import pyarrow as pa # ignore-banned-import + except ImportError as exc: # pragma: no cover + msg = ( + "Nested structures require pyarrow to be installed for pandas backend. " + "Please install pyarrow: pip install pyarrow" + ) + raise ImportError(msg) from exc + + from narwhals._arrow.utils import ( + narwhals_to_native_dtype as _to_arrow_dtype, + ) + + array_value = list(value) if isinstance(value, tuple) else value + pa_dtype = _to_arrow_dtype(dtype, self._version) if dtype else None + pa_array = pa.array([array_value], type=pa_dtype) # type: ignore[arg-type, list-item] + + # Use ArrowExtensionArray to avoid pandas unpacking the nested structure + ns = self._implementation.to_native_namespace() + pandas_series_native = ns.Series( + pd.arrays.ArrowExtensionArray(pa_array), + name="literal", + index=df._native_frame.index[0:1], + ) + + return self._series.from_native(pandas_series_native, context=self) + + pandas_like_series = self._series.from_iterable( + data=[value], + name="literal", + index=df._native_frame.index[0:1], + context=self, + ) + if dtype: + return pandas_like_series.cast(dtype) + return pandas_like_series + + return PandasLikeExpr( + lambda df: [_lit_pandas_series(df)], + evaluate_output_names=lambda _df: ["literal"], + alias_output_names=None, + implementation=self._implementation, + version=self._version, + ) + + def len(self) -> PandasLikeExpr: + return PandasLikeExpr( + lambda df: [ + self._series.from_iterable( + [len(df._native_frame)], name="len", index=[0], context=self + ) + ], + evaluate_output_names=lambda _df: ["len"], + alias_output_names=None, + implementation=self._implementation, + version=self._version, + ) + + # --- horizontal --- + def sum_horizontal(self, *exprs: PandasLikeExpr) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + it = chain.from_iterable(expr(df) for expr in exprs) + native_series = (s.fill_null(0, None, None) for s in it) + return [reduce(operator.add, native_series)] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def all_horizontal( + self, *exprs: PandasLikeExpr, ignore_nulls: bool + ) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + series = [s for _expr in exprs for s in _expr(df)] + if not ignore_nulls and any( + s.native.dtype == "object" and s.is_null().any() for s in series + ): + # classical NumPy boolean columns don't support missing values, so + # only do the full scan with `is_null` if we have `object` dtype. + msg = "Cannot use `ignore_nulls=False` in `all_horizontal` for non-nullable NumPy-backed pandas Series when nulls are present." + raise ValueError(msg) + it = ( + ( + # NumPy-backed 'bool' dtype can't contain nulls so doesn't need filling. + s if is_non_nullable_boolean(s) else s.fill_null(True, None, None) + for s in series + ) + if ignore_nulls + else iter(series) + ) + return [reduce(operator.and_, it)] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def any_horizontal( + self, *exprs: PandasLikeExpr, ignore_nulls: bool + ) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + series = [s for _expr in exprs for s in _expr(df)] + if not ignore_nulls and any( + s.native.dtype == "object" and s.is_null().any() for s in series + ): + # classical NumPy boolean columns don't support missing values, so + # only do the full scan with `is_null` if we have `object` dtype. + msg = "Cannot use `ignore_nulls=False` in `any_horizontal` for non-nullable NumPy-backed pandas Series when nulls are present." + raise ValueError(msg) + it = ( + ( + # NumPy-backed 'bool' dtype can't contain nulls so doesn't need filling. + s if is_non_nullable_boolean(s) else s.fill_null(False, None, None) + for s in series + ) + if ignore_nulls + else iter(series) + ) + return [reduce(operator.or_, it)] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def mean_horizontal(self, *exprs: PandasLikeExpr) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + expr_results = [s for _expr in exprs for s in _expr(df)] + series = (s.fill_null(0, strategy=None, limit=None) for s in expr_results) + non_na = (1 - s.is_null() for s in expr_results) + return [reduce(operator.add, series) / reduce(operator.add, non_na)] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def min_horizontal(self, *exprs: PandasLikeExpr) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + align = self._series._align_full_broadcast + series = align(*chain.from_iterable(expr(df) for expr in exprs)) + return [ + PandasLikeSeries( + self.concat( + (s.alias(str(i)).to_frame() for i, s in enumerate(series)), + how="horizontal", + )._native_frame.min(axis=1), + implementation=self._implementation, + version=self._version, + ).alias(series[0].name) + ] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def max_horizontal(self, *exprs: PandasLikeExpr) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + align = self._series._align_full_broadcast + series = align(*chain.from_iterable(expr(df) for expr in exprs)) + return [ + PandasLikeSeries( + self.concat( + (s.alias(str(i)).to_frame() for i, s in enumerate(series)), + how="horizontal", + ).native.max(axis=1), + implementation=self._implementation, + version=self._version, + ).alias(series[0].name) + ] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + @property + def _concat(self) -> _NativeConcat[NativeDataFrameT, NativeSeriesT]: + """Concatenate pandas objects along a particular axis. + + Return the **native** equivalent of `pd.concat`. + """ + return self._implementation.to_native_namespace().concat + + def _concat_diagonal(self, dfs: Sequence[NativeDataFrameT], /) -> NativeDataFrameT: + if self._implementation.is_pandas() and self._backend_version < (3,): + return self._concat(dfs, axis=VERTICAL, copy=False) + return self._concat(dfs, axis=VERTICAL) + + def _concat_by_index( + self, dfs: Sequence[NativeDataFrameT | NativeSeriesT], / + ) -> NativeDataFrameT: + """Concatenate horizontally, aligning inputs by their (label-based) index. + + Use this only when inputs are already known to share a meaningful, + aligned index (e.g. multiple aggregations from the same `group_by`). + For the general case, where inputs' indices may be unrelated, use + `_concat_horizontal` instead. + """ + if self._implementation.is_cudf(): + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="The behavior of array concatenation with empty entries is deprecated", + category=FutureWarning, + ) + return self._concat(dfs, axis=HORIZONTAL) + elif self._implementation.is_pandas() and self._backend_version < (3,): + return self._concat(dfs, axis=HORIZONTAL, copy=False) + return self._concat(dfs, axis=HORIZONTAL) + + def _concat_horizontal(self, dfs: Sequence[NativeDataFrameT], /) -> NativeDataFrameT: + # Follow the left-hand-rule documented in `docs/concepts/pandas_index.md`. + target_index = dfs[0].index + arange = import_array_module(self._implementation).arange + impl = self._implementation + + def reset(df: NativeDataFrameT) -> NativeDataFrameT: + # Value of type variable "NativeNDFrameT" of "set_index" cannot be "NativeDataFrameT" + return set_index( # type: ignore[type-var] + df, arange(len(df)), implementation=impl + ) + + concatenated = self._concat_by_index([reset(df) for df in dfs]) + # Value of type variable "NativeNDFrameT" of "set_index" cannot be "NativeDataFrameT" + return set_index( # type: ignore[type-var] + concatenated, target_index, implementation=impl + ) + + def _concat_vertical(self, dfs: Sequence[NativeDataFrameT], /) -> NativeDataFrameT: + cols_0 = dfs[0].columns + for i, df in enumerate(dfs[1:], start=1): + cols_current = df.columns + if not ( + (len(cols_current) == len(cols_0)) and (cols_current == cols_0).all() + ): + msg = ( + "unable to vstack, column names don't match:\n" + f" - dataframe 0: {cols_0.to_list()}\n" + f" - dataframe {i}: {cols_current.to_list()}\n" + ) + raise TypeError(msg) + if self._implementation.is_pandas() and self._backend_version < (3,): + return self._concat(dfs, axis=VERTICAL, copy=False) + return self._concat(dfs, axis=VERTICAL) + + def concat_str( + self, *exprs: PandasLikeExpr, separator: str, ignore_nulls: bool + ) -> PandasLikeExpr: + string = self._version.dtypes.String() + + def to_string(s: PandasLikeSeries) -> PandasLikeSeries: + result = s.cast(string) + if s.dtype.is_boolean(): + # NOTE: Polars renders booleans lowercase, pandas `astype(str)` does not. + # `.str.to_lowercase()` would drop the broadcast flag of a literal. + return result._with_native( + result.native.str.lower(), preserve_broadcast=True + ) + return result + + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + expr_results = [s for _expr in exprs for s in _expr(df)] + null_mask = [s.is_null() for s in expr_results] + # NOTE: The masks below decide what a null row becomes, so blank the nulls + # out first: before pandas 3 a string column is `object`, where adding + # `None` raises instead of propagating. + series = [to_string(s).fill_null("", None, None) for s in expr_results] + + if not ignore_nulls: + null_mask_result = reduce(operator.or_, null_mask) + result = reduce(lambda x, y: x + separator + y, series).zip_with( + ~null_mask_result, None + ) + else: + init_value, *values = series + # Literals stay scalars: `cast` and `fill_null` keep the flag and the + # binary ops extract them. Only the boolean masks are aligned to full + # length, which is cheap and is what `zip_with` needs for the separators. + null_mask = self._series._align_full_broadcast(*null_mask) + sep_array = null_mask[0]._with_native( + init_value.__native_namespace__().Series( + separator, + name="sep", + index=null_mask[0].native.index, + dtype=init_value.native.dtype, + ) + ) + # A separator goes before a value only if that value and some + # earlier one are both non-null, so `seen` accumulates the latter. + seen = ~null_mask[0] + result = init_value + for nm, value in zip(null_mask[1:], values, strict=True): + not_null = ~nm + result = result + sep_array.zip_with(seen & not_null, "") + value + seen = seen | not_null + + return [result] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def struct(self, *exprs: PandasLikeExpr) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + try: + import pandas as pd # ignore-banned-import + import pyarrow as pa # ignore-banned-import + import pyarrow.compute as pc # ignore-banned-import + except ImportError as exc: # pragma: no cover + msg = ( + "struct requires pyarrow to be installed for pandas backend. " + "Please install pyarrow: pip install pyarrow" + ) + raise ImportError(msg) from exc + + align = self._series._align_full_broadcast + series = align(*chain.from_iterable(expr(df) for expr in exprs)) + check_column_names_are_unique([s.name for s in series]) + name = series[0].name + struct_array = pc.make_struct( + *(pa.array(s.native, from_pandas=True) for s in series), + field_names=[s.name for s in series], + ) + result = pa.chunked_array([struct_array]) + + version = self._version + impl = self._implementation + ns = impl.to_native_namespace() + + result_native = ns.Series( + pd.arrays.ArrowExtensionArray(result), + name=name, + index=series[0].native.index, + ) + return [self._series(result_native, implementation=impl, version=version)] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def list(self, *exprs: PandasLikeExpr) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + try: + import pyarrow as pa # ignore-banned-import + except ImportError as exc: # pragma: no cover + msg = ( + "list requires pyarrow to be installed for pandas backend. " + "Please install pyarrow: pip install pyarrow" + ) + raise ImportError(msg) from exc + + from narwhals._arrow.utils import build_list_array + + align = self._series._align_full_broadcast + series = align(*chain.from_iterable(expr(df) for expr in exprs)) + arrays = [ + ( + s.native.array._pa_array.combine_chunks() + if is_dtype_pyarrow(s.native.dtype) + else pa.array(s.native, from_pandas=True) + ) + for s in series + ] + result = build_list_array(arrays) + + impl = self._implementation + result_native = impl.to_native_namespace().Series( + pd.arrays.ArrowExtensionArray(result), + name=series[0].name, + index=series[0].native.index, + ) + return [ + self._series(result_native, implementation=impl, version=self._version) + ] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + context=self, + ) + + def _if_then_else( + self, + when: NativeSeriesT, + then: NativeSeriesT, + otherwise: NativeSeriesT | None = None, + ) -> NativeSeriesT: + where: Incomplete = then.where + return where(when) if otherwise is None else where(when, otherwise) + + def corr( + self, a: PandasLikeExpr, b: PandasLikeExpr, *, method: CorrelationMethod + ) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + a_series = df._evaluate_single_output_expr(a) + b_series = df._evaluate_single_output_expr(b) + aligned = cast( + "list[NativeSeriesT]", + [df._extract_comparand(a_series), df._extract_comparand(b_series)], + ) + _df = self._concat_by_index(aligned) + corr = _df.corr(method=method).iloc[0, [1]] # type: ignore[union-attr] + return [ + PandasLikeSeries( + corr, implementation=self._implementation, version=self._version + ) + ] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(a, b), + alias_output_names=combine_alias_output_names(a, b), + context=self, + ) + + def cov(self, a: PandasLikeExpr, b: PandasLikeExpr, *, ddof: int) -> PandasLikeExpr: + def func(df: PandasLikeDataFrame) -> list[PandasLikeSeries]: + a_series = df._evaluate_single_output_expr(a) + b_series = df._evaluate_single_output_expr(b) + aligned = cast( + "list[NativeSeriesT]", + [df._extract_comparand(a_series), df._extract_comparand(b_series)], + ) + _df = cast("pd.DataFrame", self._concat_by_index(aligned)) + n = _df.count(axis=1).eq(2).sum() + if ddof == 0 and n == 1: + value = 0.0 + elif n - ddof <= 0: + value = float("nan") + else: + value = _df.cov(ddof=ddof).iloc[0, 1] + return [ + PandasLikeSeries.from_iterable([value], context=self, name=a_series.name) + ] + + return self._expr._from_callable( + func=func, + evaluate_output_names=combine_evaluate_output_names(a, b), + alias_output_names=combine_alias_output_names(a, b), + context=self, + ) + + +class _NativeConcat(Protocol[NativeDataFrameT, NativeSeriesT]): + @overload + def __call__( + self, + objs: Iterable[NativeDataFrameT], + *, + axis: _Vertical, + copy: bool | None = ..., + ) -> NativeDataFrameT: ... + @overload + def __call__( + self, objs: Iterable[NativeSeriesT], *, axis: _Vertical, copy: bool | None = ... + ) -> NativeSeriesT: ... + @overload + def __call__( + self, + objs: Iterable[NativeDataFrameT | NativeSeriesT], + *, + axis: _Horizontal, + copy: bool | None = ..., + ) -> NativeDataFrameT: ... + @overload + def __call__( + self, + objs: Iterable[NativeDataFrameT | NativeSeriesT], + *, + axis: Axis, + copy: bool | None = ..., + ) -> NativeDataFrameT | NativeSeriesT: ... + + def __call__( + self, + objs: Iterable[NativeDataFrameT | NativeSeriesT], + *, + axis: Axis, + copy: bool | None = None, + ) -> NativeDataFrameT | NativeSeriesT: ... diff --git a/shared/package-files/2c/2c40ded30ba64dfc8fac5545b26273f05a262fefda5a35cb81f9a0de9badfe49/crow_indices_copy_compositeexplicitautograd_dispatch.h b/shared/package-files/2c/2c40ded30ba64dfc8fac5545b26273f05a262fefda5a35cb81f9a0de9badfe49/crow_indices_copy_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b43360ccf40709a703260b907ce6f53e0d34e2bb --- /dev/null +++ b/shared/package-files/2c/2c40ded30ba64dfc8fac5545b26273f05a262fefda5a35cb81f9a0de9badfe49/crow_indices_copy_compositeexplicitautograd_dispatch.h @@ -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 & crow_indices_copy_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & crow_indices_copy_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/2c/2c461b49044dda57f28d70c53622b3401ff4880e3c776a10276c7e80be9401e1/vecm_e6_jmulti_ncs_granger_causality_dp_r.txt b/shared/package-files/2c/2c461b49044dda57f28d70c53622b3401ff4880e3c776a10276c7e80be9401e1/vecm_e6_jmulti_ncs_granger_causality_dp_r.txt new file mode 100644 index 0000000000000000000000000000000000000000..c08971aad0e090294546842f363bde861d1925e0 --- /dev/null +++ b/shared/package-files/2c/2c461b49044dda57f28d70c53622b3401ff4880e3c776a10276c7e80be9401e1/vecm_e6_jmulti_ncs_granger_causality_dp_r.txt @@ -0,0 +1,13 @@ +*** Mon, 25 Jul 2016 10:14:12 *** +TEST FOR GRANGER-CAUSALITY: +H0: "Dp" do not Granger-cause "R" + +Test statistic l = 0.2675 +pval-F( l; 4, 178) = 0.8986 + +TEST FOR INSTANTANEOUS CAUSALITY: +H0: No instantaneous causality between "Dp" and "R" + +Test statistic: c = 0.9519 +pval-Chi( c; 1) = 0.3292 + diff --git a/shared/package-files/2c/2c46595e5897fb637bdebca126d4c0b93bcffd1655b03e22ed2d424532cdb629/schema.pyi b/shared/package-files/2c/2c46595e5897fb637bdebca126d4c0b93bcffd1655b03e22ed2d424532cdb629/schema.pyi new file mode 100644 index 0000000000000000000000000000000000000000..10b65088cf80f45beef7150579bd1d2d66733a24 --- /dev/null +++ b/shared/package-files/2c/2c46595e5897fb637bdebca126d4c0b93bcffd1655b03e22ed2d424532cdb629/schema.pyi @@ -0,0 +1,97 @@ +import sys +from typing import List, Optional, Tuple + +if sys.platform == "win32": + from . import Table + + _Validation: Table + ActionText: Table + AdminExecuteSequence: Table + Condition: Table + AdminUISequence: Table + AdvtExecuteSequence: Table + AdvtUISequence: Table + AppId: Table + AppSearch: Table + Property: Table + BBControl: Table + Billboard: Table + Feature: Table + Binary: Table + BindImage: Table + File: Table + CCPSearch: Table + CheckBox: Table + Class: Table + Component: Table + Icon: Table + ProgId: Table + ComboBox: Table + CompLocator: Table + Complus: Table + Directory: Table + Control: Table + Dialog: Table + ControlCondition: Table + ControlEvent: Table + CreateFolder: Table + CustomAction: Table + DrLocator: Table + DuplicateFile: Table + Environment: Table + Error: Table + EventMapping: Table + Extension: Table + MIME: Table + FeatureComponents: Table + FileSFPCatalog: Table + SFPCatalog: Table + Font: Table + IniFile: Table + IniLocator: Table + InstallExecuteSequence: Table + InstallUISequence: Table + IsolatedComponent: Table + LaunchCondition: Table + ListBox: Table + ListView: Table + LockPermissions: Table + Media: Table + MoveFile: Table + MsiAssembly: Table + MsiAssemblyName: Table + MsiDigitalCertificate: Table + MsiDigitalSignature: Table + MsiFileHash: Table + MsiPatchHeaders: Table + ODBCAttribute: Table + ODBCDriver: Table + ODBCDataSource: Table + ODBCSourceAttribute: Table + ODBCTranslator: Table + Patch: Table + PatchPackage: Table + PublishComponent: Table + RadioButton: Table + Registry: Table + RegLocator: Table + RemoveFile: Table + RemoveIniFile: Table + RemoveRegistry: Table + ReserveCost: Table + SelfReg: Table + ServiceControl: Table + ServiceInstall: Table + Shortcut: Table + Signature: Table + TextStyle: Table + TypeLib: Table + UIText: Table + Upgrade: Table + Verb: Table + + tables: List[Table] + + _Validation_records: List[ + Tuple[str, str, str, Optional[int], Optional[int], Optional[str], Optional[int], Optional[str], Optional[str], str] + ] diff --git a/shared/package-files/2c/2c46b3091bc9006f5fca2ad90ea127ae0529cafdee925d2bfd200e954350430e/_fir_filter_design.py b/shared/package-files/2c/2c46b3091bc9006f5fca2ad90ea127ae0529cafdee925d2bfd200e954350430e/_fir_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..b46d1bcc72f5fb03965b66cf131c25c2ca2f5585 --- /dev/null +++ b/shared/package-files/2c/2c46b3091bc9006f5fca2ad90ea127ae0529cafdee925d2bfd200e954350430e/_fir_filter_design.py @@ -0,0 +1,1286 @@ +"""Functions for FIR filter design.""" + +from math import ceil, log +import operator +import warnings +from typing import Literal + +import numpy as np +from numpy.fft import irfft, fft, ifft +from scipy.special import sinc +from scipy.linalg import (toeplitz, hankel, solve, LinAlgError, LinAlgWarning, + lstsq) +from scipy.signal._arraytools import _validate_fs + +from . import _sigtools + +__all__ = ['kaiser_beta', 'kaiser_atten', 'kaiserord', + 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase'] + + +# Some notes on function parameters: +# +# `cutoff` and `width` are given as numbers between 0 and 1. These are +# relative frequencies, expressed as a fraction of the Nyquist frequency. +# For example, if the Nyquist frequency is 2 KHz, then width=0.15 is a width +# of 300 Hz. +# +# The `order` of a FIR filter is one less than the number of taps. +# This is a potential source of confusion, so in the following code, +# we will always use the number of taps as the parameterization of +# the 'size' of the filter. The "number of taps" means the number +# of coefficients, which is the same as the length of the impulse +# response of the filter. + + +def kaiser_beta(a): + """Compute the Kaiser parameter `beta`, given the attenuation `a`. + + Parameters + ---------- + a : float + The desired attenuation in the stopband and maximum ripple in + the passband, in dB. This should be a *positive* number. + + Returns + ------- + beta : float + The `beta` parameter to be used in the formula for a Kaiser window. + + References + ---------- + Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476. + + Examples + -------- + Suppose we want to design a lowpass filter, with 65 dB attenuation + in the stop band. The Kaiser window parameter to be used in the + window method is computed by ``kaiser_beta(65)``: + + >>> from scipy.signal import kaiser_beta + >>> kaiser_beta(65) + 6.20426 + + """ + if a > 50: + beta = 0.1102 * (a - 8.7) + elif a > 21: + beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21) + else: + beta = 0.0 + return beta + + +def kaiser_atten(numtaps, width): + """Compute the attenuation of a Kaiser FIR filter. + + Given the number of taps `N` and the transition width `width`, compute the + attenuation `a` in dB, given by Kaiser's formula: + + a = 2.285 * (N - 1) * pi * width + 7.95 + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. + width : float + The desired width of the transition region between passband and + stopband (or, in general, at any discontinuity) for the filter, + expressed as a fraction of the Nyquist frequency. + + Returns + ------- + a : float + The attenuation of the ripple, in dB. + + See Also + -------- + kaiserord, kaiser_beta + + Examples + -------- + Suppose we want to design a FIR filter using the Kaiser window method + that will have 211 taps and a transition width of 9 Hz for a signal that + is sampled at 480 Hz. Expressed as a fraction of the Nyquist frequency, + the width is 9/(0.5*480) = 0.0375. The approximate attenuation (in dB) + is computed as follows: + + >>> from scipy.signal import kaiser_atten + >>> kaiser_atten(211, 0.0375) + 64.48099630593983 + + """ + a = 2.285 * (numtaps - 1) * np.pi * width + 7.95 + return a + + +def kaiserord(ripple, width): + """ + Determine the filter window parameters for the Kaiser window method. + + The parameters returned by this function are generally used to create + a finite impulse response filter using the window method, with either + `firwin` or `firwin2`. + + Parameters + ---------- + ripple : float + Upper bound for the deviation (in dB) of the magnitude of the + filter's frequency response from that of the desired filter (not + including frequencies in any transition intervals). That is, if w + is the frequency expressed as a fraction of the Nyquist frequency, + A(w) is the actual frequency response of the filter and D(w) is the + desired frequency response, the design requirement is that:: + + abs(A(w) - D(w))) < 10**(-ripple/20) + + for 0 <= w <= 1 and w not in a transition interval. + width : float + Width of transition region, normalized so that 1 corresponds to pi + radians / sample. That is, the frequency is expressed as a fraction + of the Nyquist frequency. + + Returns + ------- + numtaps : int + The length of the Kaiser window. + beta : float + The beta parameter for the Kaiser window. + + See Also + -------- + kaiser_beta, kaiser_atten + + Notes + ----- + There are several ways to obtain the Kaiser window: + + - ``signal.windows.kaiser(numtaps, beta, sym=True)`` + - ``signal.get_window(beta, numtaps)`` + - ``signal.get_window(('kaiser', beta), numtaps)`` + + The empirical equations discovered by Kaiser are used. + + References + ---------- + Oppenheim, Schafer, "Discrete-Time Signal Processing", pp.475-476. + + Examples + -------- + We will use the Kaiser window method to design a lowpass FIR filter + for a signal that is sampled at 1000 Hz. + + We want at least 65 dB rejection in the stop band, and in the pass + band the gain should vary no more than 0.5%. + + We want a cutoff frequency of 175 Hz, with a transition between the + pass band and the stop band of 24 Hz. That is, in the band [0, 163], + the gain varies no more than 0.5%, and in the band [187, 500], the + signal is attenuated by at least 65 dB. + + >>> import numpy as np + >>> from scipy.signal import kaiserord, firwin, freqz + >>> import matplotlib.pyplot as plt + >>> fs = 1000.0 + >>> cutoff = 175 + >>> width = 24 + + The Kaiser method accepts just a single parameter to control the pass + band ripple and the stop band rejection, so we use the more restrictive + of the two. In this case, the pass band ripple is 0.005, or 46.02 dB, + so we will use 65 dB as the design parameter. + + Use `kaiserord` to determine the length of the filter and the + parameter for the Kaiser window. + + >>> numtaps, beta = kaiserord(65, width/(0.5*fs)) + >>> numtaps + 167 + >>> beta + 6.20426 + + Use `firwin` to create the FIR filter. + + >>> taps = firwin(numtaps, cutoff, window=('kaiser', beta), + ... scale=False, fs=fs) + + Compute the frequency response of the filter. ``w`` is the array of + frequencies, and ``h`` is the corresponding complex array of frequency + responses. + + >>> w, h = freqz(taps, worN=8000) + >>> w *= 0.5*fs/np.pi # Convert w to Hz. + + Compute the deviation of the magnitude of the filter's response from + that of the ideal lowpass filter. Values in the transition region are + set to ``nan``, so they won't appear in the plot. + + >>> ideal = w < cutoff # The "ideal" frequency response. + >>> deviation = np.abs(np.abs(h) - ideal) + >>> deviation[(w > cutoff - 0.5*width) & (w < cutoff + 0.5*width)] = np.nan + + Plot the deviation. A close look at the left end of the stop band shows + that the requirement for 65 dB attenuation is violated in the first lobe + by about 0.125 dB. This is not unusual for the Kaiser window method. + + >>> plt.plot(w, 20*np.log10(np.abs(deviation))) + >>> plt.xlim(0, 0.5*fs) + >>> plt.ylim(-90, -60) + >>> plt.grid(alpha=0.25) + >>> plt.axhline(-65, color='r', ls='--', alpha=0.3) + >>> plt.xlabel('Frequency (Hz)') + >>> plt.ylabel('Deviation from ideal (dB)') + >>> plt.title('Lowpass Filter Frequency Response') + >>> plt.show() + + """ + A = abs(ripple) # in case somebody is confused as to what's meant + if A < 8: + # Formula for N is not valid in this range. + raise ValueError("Requested maximum ripple attenuation " + f"{A:f} is too small for the Kaiser formula.") + beta = kaiser_beta(A) + + # Kaiser's formula (as given in Oppenheim and Schafer) is for the filter + # order, so we have to add 1 to get the number of taps. + numtaps = (A - 7.95) / 2.285 / (np.pi * width) + 1 + + return int(ceil(numtaps)), beta + + +def firwin(numtaps, cutoff, *, width=None, window='hamming', pass_zero=True, + scale=True, fs=None): + """ + FIR filter design using the window method. + + This function computes the coefficients of a finite impulse response + filter. The filter will have linear phase; it will be Type I if + `numtaps` is odd and Type II if `numtaps` is even. + + Type II filters always have zero response at the Nyquist frequency, so a + ValueError exception is raised if firwin is called with `numtaps` even and + having a passband whose right end is at the Nyquist frequency. + + Parameters + ---------- + numtaps : int + Length of the filter (number of coefficients, i.e. the filter + order + 1). `numtaps` must be odd if a passband includes the + Nyquist frequency. + cutoff : float or 1-D array_like + Cutoff frequency of filter (expressed in the same units as `fs`) + OR an array of cutoff frequencies (that is, band edges). In the + former case, as a float, the cutoff frequency should correspond + with the half-amplitude point, where the attenuation will be -6dB. + In the latter case, the frequencies in `cutoff` should be positive + and monotonically increasing between 0 and `fs/2`. The values 0 + and `fs/2` must not be included in `cutoff`. It should be noted + that this is different than the behavior of `scipy.signal.iirdesign`, + where the cutoff is the half-power point (-3dB). + width : float or None, optional + If `width` is not None, then assume it is the approximate width + of the transition region (expressed in the same units as `fs`) + for use in Kaiser FIR filter design. In this case, the `window` + argument is ignored. + window : string or tuple of string and parameter values, optional + Desired window to use. See `scipy.signal.get_window` for a list + of windows and required parameters. + pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional + If True, the gain at the frequency 0 (i.e., the "DC gain") is 1. + If False, the DC gain is 0. Can also be a string argument for the + desired filter type (equivalent to ``btype`` in IIR design functions). + + .. versionadded:: 1.3.0 + Support for string arguments. + scale : bool, optional + Set to True to scale the coefficients so that the frequency + response is exactly unity at a certain frequency. + That frequency is either: + + - 0 (DC) if the first passband starts at 0 (i.e. pass_zero + is True) + - `fs/2` (the Nyquist frequency) if the first passband ends at + `fs/2` (i.e the filter is a single band highpass filter); + center of first passband otherwise + + fs : float, optional + The sampling frequency of the signal. Each frequency in `cutoff` + must be between 0 and ``fs/2``. Default is 2. + + Returns + ------- + h : (numtaps,) ndarray + Coefficients of length `numtaps` FIR filter. + + Raises + ------ + ValueError + If any value in `cutoff` is less than or equal to 0 or greater + than or equal to ``fs/2``, if the values in `cutoff` are not strictly + monotonically increasing, or if `numtaps` is even but a passband + includes the Nyquist frequency. + + See Also + -------- + firwin2 + firls + minimum_phase + remez + + Examples + -------- + Low-pass from 0 to f: + + >>> from scipy import signal + >>> numtaps = 3 + >>> f = 0.1 + >>> signal.firwin(numtaps, f) + array([ 0.06799017, 0.86401967, 0.06799017]) + + Use a specific window function: + + >>> signal.firwin(numtaps, f, window='nuttall') + array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04]) + + High-pass ('stop' from 0 to f): + + >>> signal.firwin(numtaps, f, pass_zero=False) + array([-0.00859313, 0.98281375, -0.00859313]) + + Band-pass: + + >>> f1, f2 = 0.1, 0.2 + >>> signal.firwin(numtaps, [f1, f2], pass_zero=False) + array([ 0.06301614, 0.88770441, 0.06301614]) + + Band-stop: + + >>> signal.firwin(numtaps, [f1, f2]) + array([-0.00801395, 1.0160279 , -0.00801395]) + + Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]): + + >>> f3, f4 = 0.3, 0.4 + >>> signal.firwin(numtaps, [f1, f2, f3, f4]) + array([-0.01376344, 1.02752689, -0.01376344]) + + Multi-band (passbands are [f1, f2] and [f3,f4]): + + >>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False) + array([ 0.04890915, 0.91284326, 0.04890915]) + + """ + # The major enhancements to this function added in November 2010 were + # developed by Tom Krauss (see ticket #902). + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + + nyq = 0.5 * fs + + cutoff = np.atleast_1d(cutoff) / float(nyq) + + # Check for invalid input. + if cutoff.ndim > 1: + raise ValueError("The cutoff argument must be at most " + "one-dimensional.") + if cutoff.size == 0: + raise ValueError("At least one cutoff frequency must be given.") + if cutoff.min() <= 0 or cutoff.max() >= 1: + raise ValueError("Invalid cutoff frequency: frequencies must be " + "greater than 0 and less than fs/2.") + if np.any(np.diff(cutoff) <= 0): + raise ValueError("Invalid cutoff frequencies: the frequencies " + "must be strictly increasing.") + + if width is not None: + # A width was given. Find the beta parameter of the Kaiser window + # and set `window`. This overrides the value of `window` passed in. + atten = kaiser_atten(numtaps, float(width) / nyq) + beta = kaiser_beta(atten) + window = ('kaiser', beta) + + if isinstance(pass_zero, str): + if pass_zero in ('bandstop', 'lowpass'): + if pass_zero == 'lowpass': + if cutoff.size != 1: + raise ValueError('cutoff must have one element if ' + f'pass_zero=="lowpass", got {cutoff.shape}') + elif cutoff.size <= 1: + raise ValueError('cutoff must have at least two elements if ' + f'pass_zero=="bandstop", got {cutoff.shape}') + pass_zero = True + elif pass_zero in ('bandpass', 'highpass'): + if pass_zero == 'highpass': + if cutoff.size != 1: + raise ValueError('cutoff must have one element if ' + f'pass_zero=="highpass", got {cutoff.shape}') + elif cutoff.size <= 1: + raise ValueError('cutoff must have at least two elements if ' + f'pass_zero=="bandpass", got {cutoff.shape}') + pass_zero = False + else: + raise ValueError('pass_zero must be True, False, "bandpass", ' + '"lowpass", "highpass", or "bandstop", got ' + f'{pass_zero}') + pass_zero = bool(operator.index(pass_zero)) # ensure bool-like + + pass_nyquist = bool(cutoff.size & 1) ^ pass_zero + if pass_nyquist and numtaps % 2 == 0: + raise ValueError("A filter with an even number of coefficients must " + "have zero response at the Nyquist frequency.") + + # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff + # is even, and each pair in cutoff corresponds to passband. + cutoff = np.hstack(([0.0] * pass_zero, cutoff, [1.0] * pass_nyquist)) + + # `bands` is a 2-D array; each row gives the left and right edges of + # a passband. + bands = cutoff.reshape(-1, 2) + + # Build up the coefficients. + alpha = 0.5 * (numtaps - 1) + m = np.arange(0, numtaps) - alpha + h = 0 + for left, right in bands: + h += right * sinc(right * m) + h -= left * sinc(left * m) + + # Get and apply the window function. + from .windows import get_window + win = get_window(window, numtaps, fftbins=False) + h *= win + + # Now handle scaling if desired. + if scale: + # Get the first passband. + left, right = bands[0] + if left == 0: + scale_frequency = 0.0 + elif right == 1: + scale_frequency = 1.0 + else: + scale_frequency = 0.5 * (left + right) + c = np.cos(np.pi * m * scale_frequency) + s = np.sum(h * c) + h /= s + + return h + + +# Original version of firwin2 from scipy ticket #457, submitted by "tash". +# +# Rewritten by Warren Weckesser, 2010. +def firwin2(numtaps, freq, gain, *, nfreqs=None, window='hamming', + antisymmetric=False, fs=None): + """ + FIR filter design using the window method. + + From the given frequencies `freq` and corresponding gains `gain`, + this function constructs an FIR filter with linear phase and + (approximately) the given frequency response. + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. `numtaps` must be less than + `nfreqs`. + freq : array_like, 1-D + The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being + Nyquist. The Nyquist frequency is half `fs`. + The values in `freq` must be nondecreasing. A value can be repeated + once to implement a discontinuity. The first value in `freq` must + be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must + not be repeated. + gain : array_like + The filter gains at the frequency sampling points. Certain + constraints to gain values, depending on the filter type, are applied, + see Notes for details. + nfreqs : int, optional + The size of the interpolation mesh used to construct the filter. + For most efficient behavior, this should be a power of 2 plus 1 + (e.g, 129, 257, etc). The default is one more than the smallest + power of 2 that is not less than `numtaps`. `nfreqs` must be greater + than `numtaps`. + window : string or (string, float) or float, or None, optional + Window function to use. Default is "hamming". See + `scipy.signal.get_window` for the complete list of possible values. + If None, no window function is applied. + antisymmetric : bool, optional + Whether resulting impulse response is symmetric/antisymmetric. + See Notes for more details. + fs : float, optional + The sampling frequency of the signal. Each frequency in `cutoff` + must be between 0 and ``fs/2``. Default is 2. + + Returns + ------- + taps : ndarray + The filter coefficients of the FIR filter, as a 1-D array of length + `numtaps`. + + See Also + -------- + firls + firwin + minimum_phase + remez + + Notes + ----- + From the given set of frequencies and gains, the desired response is + constructed in the frequency domain. The inverse FFT is applied to the + desired response to create the associated convolution kernel, and the + first `numtaps` coefficients of this kernel, scaled by `window`, are + returned. + + The FIR filter will have linear phase. The type of filter is determined by + the value of 'numtaps` and `antisymmetric` flag. + There are four possible combinations: + + - odd `numtaps`, `antisymmetric` is False, type I filter is produced + - even `numtaps`, `antisymmetric` is False, type II filter is produced + - odd `numtaps`, `antisymmetric` is True, type III filter is produced + - even `numtaps`, `antisymmetric` is True, type IV filter is produced + + Magnitude response of all but type I filters are subjects to following + constraints: + + - type II -- zero at the Nyquist frequency + - type III -- zero at zero and Nyquist frequencies + - type IV -- zero at zero frequency + + .. versionadded:: 0.9.0 + + References + ---------- + .. [1] Oppenheim, A. V. and Schafer, R. W., "Discrete-Time Signal + Processing", Prentice-Hall, Englewood Cliffs, New Jersey (1989). + (See, for example, Section 7.4.) + + .. [2] Smith, Steven W., "The Scientist and Engineer's Guide to Digital + Signal Processing", Ch. 17. http://www.dspguide.com/ch17/1.htm + + Examples + -------- + A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and + that decreases linearly on [0.5, 1.0] from 1 to 0: + + >>> from scipy import signal + >>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) + >>> print(taps[72:78]) + [-0.02286961 -0.06362756 0.57310236 0.57310236 -0.06362756 -0.02286961] + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + nyq = 0.5 * fs + + if len(freq) != len(gain): + raise ValueError('freq and gain must be of same length.') + + if nfreqs is not None and numtaps >= nfreqs: + raise ValueError(('ntaps must be less than nfreqs, but firwin2 was ' + 'called with ntaps=%d and nfreqs=%s') % + (numtaps, nfreqs)) + + if freq[0] != 0 or freq[-1] != nyq: + raise ValueError('freq must start with 0 and end with fs/2.') + d = np.diff(freq) + if (d < 0).any(): + raise ValueError('The values in freq must be nondecreasing.') + d2 = d[:-1] + d[1:] + if (d2 == 0).any(): + raise ValueError('A value in freq must not occur more than twice.') + if freq[1] == 0: + raise ValueError('Value 0 must not be repeated in freq') + if freq[-2] == nyq: + raise ValueError('Value fs/2 must not be repeated in freq') + + if antisymmetric: + if numtaps % 2 == 0: + ftype = 4 + else: + ftype = 3 + else: + if numtaps % 2 == 0: + ftype = 2 + else: + ftype = 1 + + if ftype == 2 and gain[-1] != 0.0: + raise ValueError("A Type II filter must have zero gain at the " + "Nyquist frequency.") + elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0): + raise ValueError("A Type III filter must have zero gain at zero " + "and Nyquist frequencies.") + elif ftype == 4 and gain[0] != 0.0: + raise ValueError("A Type IV filter must have zero gain at zero " + "frequency.") + + if nfreqs is None: + nfreqs = 1 + 2 ** int(ceil(log(numtaps, 2))) + + if (d == 0).any(): + # Tweak any repeated values in freq so that interp works. + freq = np.array(freq, copy=True) + eps = np.finfo(float).eps * nyq + for k in range(len(freq) - 1): + if freq[k] == freq[k + 1]: + freq[k] = freq[k] - eps + freq[k + 1] = freq[k + 1] + eps + # Check if freq is strictly increasing after tweak + d = np.diff(freq) + if (d <= 0).any(): + raise ValueError("freq cannot contain numbers that are too close " + "(within eps * (fs/2): " + f"{eps}) to a repeated value") + + # Linearly interpolate the desired response on a uniform mesh `x`. + x = np.linspace(0.0, nyq, nfreqs) + fx = np.interp(x, freq, gain) + + # Adjust the phases of the coefficients so that the first `ntaps` of the + # inverse FFT are the desired filter coefficients. + shift = np.exp(-(numtaps - 1) / 2. * 1.j * np.pi * x / nyq) + if ftype > 2: + shift *= 1j + + fx2 = fx * shift + + # Use irfft to compute the inverse FFT. + out_full = irfft(fx2) + + if window is not None: + # Create the window to apply to the filter coefficients. + from .windows import get_window + wind = get_window(window, numtaps, fftbins=False) + else: + wind = 1 + + # Keep only the first `numtaps` coefficients in `out`, and multiply by + # the window. + out = out_full[:numtaps] * wind + + if ftype == 3: + out[out.size // 2] = 0.0 + + return out + + +def remez(numtaps, bands, desired, *, weight=None, type='bandpass', + maxiter=25, grid_density=16, fs=None): + """ + Calculate the minimax optimal filter using the Remez exchange algorithm. + + Calculate the filter-coefficients for the finite impulse response + (FIR) filter whose transfer function minimizes the maximum error + between the desired gain and the realized gain in the specified + frequency bands using the Remez exchange algorithm. + + Parameters + ---------- + numtaps : int + The desired number of taps in the filter. The number of taps is + the number of terms in the filter, or the filter order plus one. + bands : array_like + A monotonic sequence containing the band edges. + All elements must be non-negative and less than half the sampling + frequency as given by `fs`. + desired : array_like + A sequence half the size of bands containing the desired gain + in each of the specified bands. + weight : array_like, optional + A relative weighting to give to each band region. The length of + `weight` has to be half the length of `bands`. + type : {'bandpass', 'differentiator', 'hilbert'}, optional + The type of filter: + + * 'bandpass' : flat response in bands. This is the default. + + * 'differentiator' : frequency proportional response in bands. + + * 'hilbert' : filter with odd symmetry, that is, type III + (for even order) or type IV (for odd order) + linear phase filters. + + maxiter : int, optional + Maximum number of iterations of the algorithm. Default is 25. + grid_density : int, optional + Grid density. The dense grid used in `remez` is of size + ``(numtaps + 1) * grid_density``. Default is 16. + fs : float, optional + The sampling frequency of the signal. Default is 1. + + Returns + ------- + out : ndarray + A rank-1 array containing the coefficients of the optimal + (in a minimax sense) filter. + + See Also + -------- + firls + firwin + firwin2 + minimum_phase + + References + ---------- + .. [1] J. H. McClellan and T. W. Parks, "A unified approach to the + design of optimum FIR linear phase digital filters", + IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973. + .. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer + Program for Designing Optimum FIR Linear Phase Digital + Filters", IEEE Trans. Audio Electroacoust., vol. AU-21, + pp. 506-525, 1973. + + Examples + -------- + In these examples, `remez` is used to design low-pass, high-pass, + band-pass and band-stop filters. The parameters that define each filter + are the filter order, the band boundaries, the transition widths of the + boundaries, the desired gains in each band, and the sampling frequency. + + We'll use a sample frequency of 22050 Hz in all the examples. In each + example, the desired gain in each band is either 0 (for a stop band) + or 1 (for a pass band). + + `freqz` is used to compute the frequency response of each filter, and + the utility function ``plot_response`` defined below is used to plot + the response. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> fs = 22050 # Sample rate, Hz + + >>> def plot_response(w, h, title): + ... "Utility function to plot response functions" + ... fig = plt.figure() + ... ax = fig.add_subplot(111) + ... ax.plot(w, 20*np.log10(np.abs(h))) + ... ax.set_ylim(-40, 5) + ... ax.grid(True) + ... ax.set_xlabel('Frequency (Hz)') + ... ax.set_ylabel('Gain (dB)') + ... ax.set_title(title) + + The first example is a low-pass filter, with cutoff frequency 8 kHz. + The filter length is 325, and the transition width from pass to stop + is 100 Hz. + + >>> cutoff = 8000.0 # Desired cutoff frequency, Hz + >>> trans_width = 100 # Width of transition from pass to stop, Hz + >>> numtaps = 325 # Size of the FIR filter. + >>> taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5*fs], + ... [1, 0], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Low-pass Filter") + >>> plt.show() + + This example shows a high-pass filter: + + >>> cutoff = 2000.0 # Desired cutoff frequency, Hz + >>> trans_width = 250 # Width of transition from pass to stop, Hz + >>> numtaps = 125 # Size of the FIR filter. + >>> taps = signal.remez(numtaps, [0, cutoff - trans_width, cutoff, 0.5*fs], + ... [0, 1], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "High-pass Filter") + >>> plt.show() + + This example shows a band-pass filter with a pass-band from 2 kHz to + 5 kHz. The transition width is 260 Hz and the length of the filter + is 63, which is smaller than in the other examples: + + >>> band = [2000, 5000] # Desired pass band, Hz + >>> trans_width = 260 # Width of transition from pass to stop, Hz + >>> numtaps = 63 # Size of the FIR filter. + >>> edges = [0, band[0] - trans_width, band[0], band[1], + ... band[1] + trans_width, 0.5*fs] + >>> taps = signal.remez(numtaps, edges, [0, 1, 0], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Band-pass Filter") + >>> plt.show() + + The low order leads to higher ripple and less steep transitions. + + The next example shows a band-stop filter. + + >>> band = [6000, 8000] # Desired stop band, Hz + >>> trans_width = 200 # Width of transition from pass to stop, Hz + >>> numtaps = 175 # Size of the FIR filter. + >>> edges = [0, band[0] - trans_width, band[0], band[1], + ... band[1] + trans_width, 0.5*fs] + >>> taps = signal.remez(numtaps, edges, [1, 0, 1], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Band-stop Filter") + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 1.0 if fs is None else fs + + # Convert type + try: + tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type] + except KeyError as e: + raise ValueError("Type must be 'bandpass', 'differentiator', " + "or 'hilbert'") from e + + # Convert weight + if weight is None: + weight = [1] * len(desired) + + bands = np.asarray(bands).copy() + return _sigtools._remez(numtaps, bands, desired, weight, tnum, fs, + maxiter, grid_density) + + +def firls(numtaps, bands, desired, *, weight=None, fs=None): + """ + FIR filter design using least-squares error minimization. + + Calculate the filter coefficients for the linear-phase finite + impulse response (FIR) filter which has the best approximation + to the desired frequency response described by `bands` and + `desired` in the least squares sense (i.e., the integral of the + weighted mean-squared error within the specified bands is + minimized). + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. `numtaps` must be odd. + bands : array_like + A monotonic nondecreasing sequence containing the band edges in + Hz. All elements must be non-negative and less than or equal to + the Nyquist frequency given by `nyq`. The bands are specified as + frequency pairs, thus, if using a 1D array, its length must be + even, e.g., `np.array([0, 1, 2, 3, 4, 5])`. Alternatively, the + bands can be specified as an nx2 sized 2D array, where n is the + number of bands, e.g, `np.array([[0, 1], [2, 3], [4, 5]])`. + desired : array_like + A sequence the same size as `bands` containing the desired gain + at the start and end point of each band. + weight : array_like, optional + A relative weighting to give to each band region when solving + the least squares problem. `weight` has to be half the size of + `bands`. + fs : float, optional + The sampling frequency of the signal. Each frequency in `bands` + must be between 0 and ``fs/2`` (inclusive). Default is 2. + + Returns + ------- + coeffs : ndarray + Coefficients of the optimal (in a least squares sense) FIR filter. + + See Also + -------- + firwin + firwin2 + minimum_phase + remez + + Notes + ----- + This implementation follows the algorithm given in [1]_. + As noted there, least squares design has multiple advantages: + + 1. Optimal in a least-squares sense. + 2. Simple, non-iterative method. + 3. The general solution can obtained by solving a linear + system of equations. + 4. Allows the use of a frequency dependent weighting function. + + This function constructs a Type I linear phase FIR filter, which + contains an odd number of `coeffs` satisfying for :math:`n < numtaps`: + + .. math:: coeffs(n) = coeffs(numtaps - 1 - n) + + The odd number of coefficients and filter symmetry avoid boundary + conditions that could otherwise occur at the Nyquist and 0 frequencies + (e.g., for Type II, III, or IV variants). + + .. versionadded:: 0.18 + + References + ---------- + .. [1] Ivan Selesnick, Linear-Phase Fir Filter Design By Least Squares. + OpenStax CNX. Aug 9, 2005. + https://eeweb.engineering.nyu.edu/iselesni/EL713/firls/firls.pdf + + Examples + -------- + We want to construct a band-pass filter. Note that the behavior in the + frequency ranges between our stop bands and pass bands is unspecified, + and thus may overshoot depending on the parameters of our filter: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> fig, axs = plt.subplots(2) + >>> fs = 10.0 # Hz + >>> desired = (0, 0, 1, 1, 0, 0) + >>> for bi, bands in enumerate(((0, 1, 2, 3, 4, 5), (0, 1, 2, 4, 4.5, 5))): + ... fir_firls = signal.firls(73, bands, desired, fs=fs) + ... fir_remez = signal.remez(73, bands, desired[::2], fs=fs) + ... fir_firwin2 = signal.firwin2(73, bands, desired, fs=fs) + ... hs = list() + ... ax = axs[bi] + ... for fir in (fir_firls, fir_remez, fir_firwin2): + ... freq, response = signal.freqz(fir) + ... hs.append(ax.semilogy(0.5*fs*freq/np.pi, np.abs(response))[0]) + ... for band, gains in zip(zip(bands[::2], bands[1::2]), + ... zip(desired[::2], desired[1::2])): + ... ax.semilogy(band, np.maximum(gains, 1e-7), 'k--', linewidth=2) + ... if bi == 0: + ... ax.legend(hs, ('firls', 'remez', 'firwin2'), + ... loc='lower center', frameon=False) + ... else: + ... ax.set_xlabel('Frequency (Hz)') + ... ax.grid(True) + ... ax.set(title='Band-pass %d-%d Hz' % bands[2:4], ylabel='Magnitude') + ... + >>> fig.tight_layout() + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + nyq = 0.5 * fs + + numtaps = int(numtaps) + if numtaps % 2 == 0 or numtaps < 1: + raise ValueError("numtaps must be odd and >= 1") + M = (numtaps-1) // 2 + + # normalize bands 0->1 and make it 2 columns + nyq = float(nyq) + if nyq <= 0: + raise ValueError(f'nyq must be positive, got {nyq} <= 0.') + bands = np.asarray(bands).flatten() / nyq + if len(bands) % 2 != 0: + raise ValueError("bands must contain frequency pairs.") + if (bands < 0).any() or (bands > 1).any(): + raise ValueError("bands must be between 0 and 1 relative to Nyquist") + bands.shape = (-1, 2) + + # check remaining params + desired = np.asarray(desired).flatten() + if bands.size != desired.size: + raise ValueError( + f"desired must have one entry per frequency, got {desired.size} " + f"gains for {bands.size} frequencies." + ) + desired.shape = (-1, 2) + if (np.diff(bands) <= 0).any() or (np.diff(bands[:, 0]) < 0).any(): + raise ValueError("bands must be monotonically nondecreasing and have " + "width > 0.") + if (bands[:-1, 1] > bands[1:, 0]).any(): + raise ValueError("bands must not overlap.") + if (desired < 0).any(): + raise ValueError("desired must be non-negative.") + if weight is None: + weight = np.ones(len(desired)) + weight = np.asarray(weight).flatten() + if len(weight) != len(desired): + raise ValueError("weight must be the same size as the number of " + f"band pairs ({len(bands)}).") + if (weight < 0).any(): + raise ValueError("weight must be non-negative.") + + # Set up the linear matrix equation to be solved, Qa = b + + # We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n) + # where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel. + + # We omit the factor of 0.5 above, instead adding it during coefficient + # calculation. + + # We also omit the 1/π from both Q and b equations, as they cancel + # during solving. + + # We have that: + # q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π) + # Using our normalization ω=πf and with a constant weight W over each + # interval f1->f2 we get: + # q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf + # integrated over each f1->f2 pair (i.e., value at f2 - value at f1). + n = np.arange(numtaps)[:, np.newaxis, np.newaxis] + q = np.dot(np.diff(np.sinc(bands * n) * bands, axis=2)[:, :, 0], weight) + + # Now we assemble our sum of Toeplitz and Hankel + Q1 = toeplitz(q[:M+1]) + Q2 = hankel(q[:M+1], q[M:]) + Q = Q1 + Q2 + + # Now for b(n) we have that: + # b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π) + # Using our normalization ω=πf and with a constant weight W over each + # interval and a linear term for D(ω) we get (over each f1->f2 interval): + # b(n) = W ∫ (mf+c)cos(πnf)df + # = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2 + # integrated over each f1->f2 pair (i.e., value at f2 - value at f1). + n = n[:M + 1] # only need this many coefficients here + # Choose m and c such that we are at the start and end weights + m = (np.diff(desired, axis=1) / np.diff(bands, axis=1)) + c = desired[:, [0]] - bands[:, [0]] * m + b = bands * (m*bands + c) * np.sinc(bands * n) + # Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0 + b[0] -= m * bands * bands / 2. + b[1:] += m * np.cos(n[1:] * np.pi * bands) / (np.pi * n[1:]) ** 2 + b = np.dot(np.diff(b, axis=2)[:, :, 0], weight) + + # Now we can solve the equation + try: # try the fast way + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + a = solve(Q, b, assume_a="pos", check_finite=False) + for ww in w: + if (ww.category == LinAlgWarning and + str(ww.message).startswith('Ill-conditioned matrix')): + raise LinAlgError(str(ww.message)) + except LinAlgError: # in case Q is rank deficient + # This is faster than pinvh, even though we don't explicitly use + # the symmetry here. gelsy was faster than gelsd and gelss in + # some non-exhaustive tests. + a = lstsq(Q, b, lapack_driver='gelsy')[0] + + # make coefficients symmetric (linear phase) + coeffs = np.hstack((a[:0:-1], 2 * a[0], a[1:])) + return coeffs + + +def _dhtm(mag): + """Compute the modified 1-D discrete Hilbert transform + + Parameters + ---------- + mag : ndarray + The magnitude spectrum. Should be 1-D with an even length, and + preferably a fast length for FFT/IFFT. + """ + # Adapted based on code by Niranjan Damera-Venkata, + # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`) + sig = np.zeros(len(mag)) + # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5 + midpt = len(mag) // 2 + sig[1:midpt] = 1 + sig[midpt+1:] = -1 + # eventually if we want to support complex filters, we will need a + # np.abs() on the mag inside the log, and should remove the .real + recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real + return recon + + +def minimum_phase(h: np.ndarray, + method: Literal['homomorphic', 'hilbert'] = 'homomorphic', + n_fft: int | None = None, *, half: bool = True) -> np.ndarray: + """Convert a linear-phase FIR filter to minimum phase + + Parameters + ---------- + h : array + Linear-phase FIR filter coefficients. + method : {'hilbert', 'homomorphic'} + The provided methods are: + + 'homomorphic' (default) + This method [4]_ [5]_ works best with filters with an + odd number of taps, and the resulting minimum phase filter + will have a magnitude response that approximates the square + root of the original filter's magnitude response using half + the number of taps when ``half=True`` (default), or the + original magnitude spectrum using the same number of taps + when ``half=False``. + + 'hilbert' + This method [1]_ is designed to be used with equiripple + filters (e.g., from `remez`) with unity or zero gain + regions. + + n_fft : int + The number of points to use for the FFT. Should be at least a + few times larger than the signal length (see Notes). + half : bool + If ``True``, create a filter that is half the length of the original, with a + magnitude spectrum that is the square root of the original. If ``False``, + create a filter that is the same length as the original, with a magnitude + spectrum that is designed to match the original (only supported when + ``method='homomorphic'``). + + .. versionadded:: 1.14.0 + + Returns + ------- + h_minimum : array + The minimum-phase version of the filter, with length + ``(len(h) + 1) // 2`` when ``half is True`` or ``len(h)`` otherwise. + + See Also + -------- + firwin + firwin2 + remez + + Notes + ----- + Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection + of an FFT length to estimate the complex cepstrum of the filter. + + In the case of the Hilbert method, the deviation from the ideal + spectrum ``epsilon`` is related to the number of stopband zeros + ``n_stop`` and FFT length ``n_fft`` as:: + + epsilon = 2. * n_stop / n_fft + + For example, with 100 stopband zeros and a FFT length of 2048, + ``epsilon = 0.0976``. If we conservatively assume that the number of + stopband zeros is one less than the filter length, we can take the FFT + length to be the next power of 2 that satisfies ``epsilon=0.01`` as:: + + n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01))) + + This gives reasonable results for both the Hilbert and homomorphic + methods, and gives the value used when ``n_fft=None``. + + Alternative implementations exist for creating minimum-phase filters, + including zero inversion [2]_ and spectral factorization [3]_ [4]_. + For more information, see `this DSPGuru page + `__. + + References + ---------- + .. [1] N. Damera-Venkata and B. L. Evans, "Optimal design of real and + complex minimum phase digital FIR filters," Acoustics, Speech, + and Signal Processing, 1999. Proceedings., 1999 IEEE International + Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3. + :doi:`10.1109/ICASSP.1999.756179` + .. [2] X. Chen and T. W. Parks, "Design of optimal minimum phase FIR + filters by direct factorization," Signal Processing, + vol. 10, no. 4, pp. 369-383, Jun. 1986. + .. [3] T. Saramaki, "Finite Impulse Response Filter Design," in + Handbook for Digital Signal Processing, chapter 4, + New York: Wiley-Interscience, 1993. + .. [4] J. S. Lim, Advanced Topics in Signal Processing. + Englewood Cliffs, N.J.: Prentice Hall, 1988. + .. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck, + "Discrete-Time Signal Processing," 3rd edition. + Upper Saddle River, N.J.: Pearson, 2009. + + Examples + -------- + Create an optimal linear-phase low-pass filter `h` with a transition band of + [0.2, 0.3] (assuming a Nyquist frequency of 1): + + >>> import numpy as np + >>> from scipy.signal import remez, minimum_phase, freqz, group_delay + >>> import matplotlib.pyplot as plt + >>> freq = [0, 0.2, 0.3, 1.0] + >>> desired = [1, 0] + >>> h_linear = remez(151, freq, desired, fs=2) + + Convert it to minimum phase: + + >>> h_hil = minimum_phase(h_linear, method='hilbert') + >>> h_hom = minimum_phase(h_linear, method='homomorphic') + >>> h_hom_full = minimum_phase(h_linear, method='homomorphic', half=False) + + Compare the impulse and frequency response of the four filters: + + >>> fig0, ax0 = plt.subplots(figsize=(6, 3), tight_layout=True) + >>> fig1, axs = plt.subplots(3, sharex='all', figsize=(6, 6), tight_layout=True) + >>> ax0.set_title("Impulse response") + >>> ax0.set(xlabel='Samples', ylabel='Amplitude', xlim=(0, len(h_linear) - 1)) + >>> axs[0].set_title("Frequency Response") + >>> axs[0].set(xlim=(0, .65), ylabel="Magnitude / dB") + >>> axs[1].set(ylabel="Phase / rad") + >>> axs[2].set(ylabel="Group Delay / samples", ylim=(-31, 81), + ... xlabel='Normalized Frequency (Nyqist frequency: 1)') + >>> for h, lb in ((h_linear, f'Linear ({len(h_linear)})'), + ... (h_hil, f'Min-Hilbert ({len(h_hil)})'), + ... (h_hom, f'Min-Homomorphic ({len(h_hom)})'), + ... (h_hom_full, f'Min-Homom. Full ({len(h_hom_full)})')): + ... w_H, H = freqz(h, fs=2) + ... w_gd, gd = group_delay((h, 1), fs=2) + ... + ... alpha = 1.0 if lb == 'linear' else 0.5 # full opacity for 'linear' line + ... ax0.plot(h, '.-', alpha=alpha, label=lb) + ... axs[0].plot(w_H, 20 * np.log10(np.abs(H)), alpha=alpha) + ... axs[1].plot(w_H, np.unwrap(np.angle(H)), alpha=alpha, label=lb) + ... axs[2].plot(w_gd, gd, alpha=alpha) + >>> ax0.grid(True) + >>> ax0.legend(title='Filter Phase (Order)') + >>> axs[1].legend(title='Filter Phase (Order)', loc='lower right') + >>> for ax_ in axs: # shade transition band: + ... ax_.axvspan(freq[1], freq[2], color='y', alpha=.25) + ... ax_.grid(True) + >>> plt.show() + + The impulse response and group delay plot depict the 75 sample delay of the linear + phase filter `h`. The phase should also be linear in the stop band--due to the small + magnitude, numeric noise dominates there. Furthermore, the plots show that the + minimum phase filters clearly show a reduced (negative) phase slope in the pass and + transition band. The plots also illustrate that the filter with parameters + ``method='homomorphic', half=False`` has same order and magnitude response as the + linear filter `h` whereas the other minimum phase filters have only half the order + and the square root of the magnitude response. + """ + h = np.asarray(h) + if np.iscomplexobj(h): + raise ValueError('Complex filters not supported') + if h.ndim != 1 or h.size <= 2: + raise ValueError('h must be 1-D and at least 2 samples long') + n_half = len(h) // 2 + if not np.allclose(h[-n_half:][::-1], h[:n_half]): + warnings.warn('h does not appear to by symmetric, conversion may fail', + RuntimeWarning, stacklevel=2) + if not isinstance(method, str) or method not in \ + ('homomorphic', 'hilbert',): + raise ValueError(f'method must be "homomorphic" or "hilbert", got {method!r}') + if method == "hilbert" and not half: + raise ValueError("`half=False` is only supported when `method='homomorphic'`") + if n_fft is None: + n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01))) + n_fft = int(n_fft) + if n_fft < len(h): + raise ValueError(f'n_fft must be at least len(h)=={len(h)}') + if method == 'hilbert': + w = np.arange(n_fft) * (2 * np.pi / n_fft * n_half) + H = np.real(fft(h, n_fft) * np.exp(1j * w)) + dp = max(H) - 1 + ds = 0 - min(H) + S = 4. / (np.sqrt(1+dp+ds) + np.sqrt(1-dp+ds)) ** 2 + H += ds + H *= S + H = np.sqrt(H, out=H) + H += 1e-10 # ensure that the log does not explode + h_minimum = _dhtm(H) + else: # method == 'homomorphic' + # zero-pad; calculate the DFT + h_temp = np.abs(fft(h, n_fft)) + # take 0.25*log(|H|**2) = 0.5*log(|H|) + h_temp += 1e-7 * h_temp[h_temp > 0].min() # don't let log blow up + np.log(h_temp, out=h_temp) + if half: # halving of magnitude spectrum optional + h_temp *= 0.5 + # IDFT + h_temp = ifft(h_temp).real + # multiply pointwise by the homomorphic filter + # lmin[n] = 2u[n] - d[n] + # i.e., double the positive frequencies and zero out the negative ones; + # Oppenheim+Shafer 3rd ed p991 eq13.42b and p1004 fig13.7 + win = np.zeros(n_fft) + win[0] = 1 + stop = n_fft // 2 + win[1:stop] = 2 + if n_fft % 2: + win[stop] = 1 + h_temp *= win + h_temp = ifft(np.exp(fft(h_temp))) + h_minimum = h_temp.real + n_out = (n_half + len(h) % 2) if half else len(h) + return h_minimum[:n_out] diff --git a/shared/package-files/2c/2c46e133cf21bc0663ec5bb2068f77f824a9a9eeac5c7d06eb9817e812846308/CUDASparseDescriptors.h b/shared/package-files/2c/2c46e133cf21bc0663ec5bb2068f77f824a9a9eeac5c7d06eb9817e812846308/CUDASparseDescriptors.h new file mode 100644 index 0000000000000000000000000000000000000000..9e3d50f34e77b3e59feb7dd6499703459785f1c3 --- /dev/null +++ b/shared/package-files/2c/2c46e133cf21bc0663ec5bb2068f77f824a9a9eeac5c7d06eb9817e812846308/CUDASparseDescriptors.h @@ -0,0 +1,290 @@ +#pragma once + +#include +#include +#include + +#include + +#if defined(USE_ROCM) +#include +#endif + +namespace at::cuda::sparse { + +template +struct CuSparseDescriptorDeleter { + void operator()(T* x) { + if (x != nullptr) { + TORCH_CUDASPARSE_CHECK(destructor(x)); + } + } +}; + +template +class CuSparseDescriptor { + public: + T* descriptor() const { + return descriptor_.get(); + } + T* descriptor() { + return descriptor_.get(); + } + + protected: + std::unique_ptr> descriptor_; +}; + +#if AT_USE_CUSPARSE_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_CONST_DESCRIPTORS() +template +struct ConstCuSparseDescriptorDeleter { + void operator()(T* x) { + if (x != nullptr) { + TORCH_CUDASPARSE_CHECK(destructor(x)); + } + } +}; + +template +class ConstCuSparseDescriptor { + public: + T* descriptor() const { + return descriptor_.get(); + } + T* descriptor() { + return descriptor_.get(); + } + + protected: + std::unique_ptr> descriptor_; +}; +#endif // AT_USE_CUSPARSE_CONST_DESCRIPTORS || AT_USE_HIPSPARSE_CONST_DESCRIPTORS + +#if defined(USE_ROCM) +using cusparseMatDescr = std::remove_pointer::type; +using cusparseDnMatDescr = std::remove_pointer::type; +using cusparseDnVecDescr = std::remove_pointer::type; +using cusparseSpMatDescr = std::remove_pointer::type; +using cusparseSpMatDescr = std::remove_pointer::type; +using cusparseSpGEMMDescr = std::remove_pointer::type; +#if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() +using bsrsv2Info = std::remove_pointer::type; +using bsrsm2Info = std::remove_pointer::type; +#endif +#endif + +// NOTE: This is only needed for CUDA 11 and earlier, since CUDA 12 introduced +// API for const descriptors +cusparseStatus_t destroyConstDnMat(const cusparseDnMatDescr* dnMatDescr); + +class TORCH_CUDA_CPP_API CuSparseMatDescriptor + : public CuSparseDescriptor { + public: + CuSparseMatDescriptor() { + cusparseMatDescr_t raw_descriptor; + TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } + + CuSparseMatDescriptor(bool upper, bool unit) { + cusparseFillMode_t fill_mode = + upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER; + cusparseDiagType_t diag_type = + unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT; + cusparseMatDescr_t raw_descriptor; + TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor)); + TORCH_CUDASPARSE_CHECK(cusparseSetMatFillMode(raw_descriptor, fill_mode)); + TORCH_CUDASPARSE_CHECK(cusparseSetMatDiagType(raw_descriptor, diag_type)); + descriptor_.reset(raw_descriptor); + } +}; + +#if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() + +class TORCH_CUDA_CPP_API CuSparseBsrsv2Info + : public CuSparseDescriptor { + public: + CuSparseBsrsv2Info() { + bsrsv2Info_t raw_descriptor; + TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsv2Info(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; + +class TORCH_CUDA_CPP_API CuSparseBsrsm2Info + : public CuSparseDescriptor { + public: + CuSparseBsrsm2Info() { + bsrsm2Info_t raw_descriptor; + TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsm2Info(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; + +#endif // AT_USE_HIPSPARSE_TRIANGULAR_SOLVE + +#if AT_USE_CUSPARSE_GENERIC_API() || AT_USE_HIPSPARSE_GENERIC_API() + +cusparseIndexType_t getCuSparseIndexType(const c10::ScalarType& scalar_type); + +#if AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS() +class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor + : public CuSparseDescriptor { + public: + explicit CuSparseDnMatDescriptor(const Tensor& input, int64_t batch_offset = -1); +}; + +class TORCH_CUDA_CPP_API CuSparseConstDnMatDescriptor + : public CuSparseDescriptor { + public: + explicit CuSparseConstDnMatDescriptor(const Tensor& input, int64_t batch_offset = -1); + cusparseDnMatDescr* unsafe_mutable_descriptor() const { + return const_cast(descriptor()); + } + cusparseDnMatDescr* unsafe_mutable_descriptor() { + return const_cast(descriptor()); + } +}; + +class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor + : public CuSparseDescriptor { + public: + explicit CuSparseDnVecDescriptor(const Tensor& input); +}; + +class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor + : public CuSparseDescriptor {}; + +#elif AT_USE_CUSPARSE_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_CONST_DESCRIPTORS() + class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor + : public ConstCuSparseDescriptor< + cusparseDnMatDescr, + &cusparseDestroyDnMat> { + public: + explicit CuSparseDnMatDescriptor( + const Tensor& input, + int64_t batch_offset = -1); + }; + + class TORCH_CUDA_CPP_API CuSparseConstDnMatDescriptor + : public ConstCuSparseDescriptor< + const cusparseDnMatDescr, + &destroyConstDnMat> { + public: + explicit CuSparseConstDnMatDescriptor( + const Tensor& input, + int64_t batch_offset = -1); + cusparseDnMatDescr* unsafe_mutable_descriptor() const { + return const_cast(descriptor()); + } + cusparseDnMatDescr* unsafe_mutable_descriptor() { + return const_cast(descriptor()); + } + }; + + class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor + : public ConstCuSparseDescriptor< + cusparseDnVecDescr, + &cusparseDestroyDnVec> { + public: + explicit CuSparseDnVecDescriptor(const Tensor& input); + }; + + class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor + : public ConstCuSparseDescriptor< + cusparseSpMatDescr, + &cusparseDestroySpMat> {}; +#endif // AT_USE_CUSPARSE_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_CONST_DESCRIPTORS() + +class TORCH_CUDA_CPP_API CuSparseSpMatCsrDescriptor + : public CuSparseSpMatDescriptor { + public: + explicit CuSparseSpMatCsrDescriptor(const Tensor& input, int64_t batch_offset = -1); + + std::tuple get_size() { + int64_t rows, cols, nnz; + TORCH_CUDASPARSE_CHECK(cusparseSpMatGetSize( + this->descriptor(), + &rows, + &cols, + &nnz)); + return std::make_tuple(rows, cols, nnz); + } + + void set_tensor(const Tensor& input) { + auto crow_indices = input.crow_indices(); + auto col_indices = input.col_indices(); + auto values = input.values(); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(crow_indices.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(col_indices.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.is_contiguous()); + TORCH_CUDASPARSE_CHECK(cusparseCsrSetPointers( + this->descriptor(), + crow_indices.data_ptr(), + col_indices.data_ptr(), + values.data_ptr())); + } + +#if AT_USE_CUSPARSE_GENERIC_SPSV() + void set_mat_fill_mode(bool upper) { + cusparseFillMode_t fill_mode = + upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER; + TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute( + this->descriptor(), + CUSPARSE_SPMAT_FILL_MODE, + &fill_mode, + sizeof(fill_mode))); + } + + void set_mat_diag_type(bool unit) { + cusparseDiagType_t diag_type = + unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT; + TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute( + this->descriptor(), + CUSPARSE_SPMAT_DIAG_TYPE, + &diag_type, + sizeof(diag_type))); + } +#endif +}; + +#if AT_USE_CUSPARSE_GENERIC_SPSV() +class TORCH_CUDA_CPP_API CuSparseSpSVDescriptor + : public CuSparseDescriptor { + public: + CuSparseSpSVDescriptor() { + cusparseSpSVDescr_t raw_descriptor; + TORCH_CUDASPARSE_CHECK(cusparseSpSV_createDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; +#endif + +#if AT_USE_CUSPARSE_GENERIC_SPSM() +class TORCH_CUDA_CPP_API CuSparseSpSMDescriptor + : public CuSparseDescriptor { + public: + CuSparseSpSMDescriptor() { + cusparseSpSMDescr_t raw_descriptor; + TORCH_CUDASPARSE_CHECK(cusparseSpSM_createDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; +#endif + +#if (defined(USE_ROCM) && ROCM_VERSION >= 50200) || !defined(USE_ROCM) +class TORCH_CUDA_CPP_API CuSparseSpGEMMDescriptor + : public CuSparseDescriptor { + public: + CuSparseSpGEMMDescriptor() { + cusparseSpGEMMDescr_t raw_descriptor; + TORCH_CUDASPARSE_CHECK(cusparseSpGEMM_createDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; +#endif + +#endif // AT_USE_CUSPARSE_GENERIC_API() || AT_USE_HIPSPARSE_GENERIC_API() + +} // namespace at::cuda::sparse diff --git a/shared/package-files/2c/2c4f0ce7c591bbf72f4199ecd9dc5431e0558ea35fc115b0eafb562a206baf62/__init__.py b/shared/package-files/2c/2c4f0ce7c591bbf72f4199ecd9dc5431e0558ea35fc115b0eafb562a206baf62/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb413440ba9c1ef4c016cd874d19c2aba6d791e --- /dev/null +++ b/shared/package-files/2c/2c4f0ce7c591bbf72f4199ecd9dc5431e0558ea35fc115b0eafb562a206baf62/__init__.py @@ -0,0 +1,85 @@ +from pandas.core.internals.api import make_block # 2023-09-18 pyarrow uses this +from pandas.core.internals.array_manager import ( + ArrayManager, + SingleArrayManager, +) +from pandas.core.internals.base import ( + DataManager, + SingleDataManager, +) +from pandas.core.internals.concat import concatenate_managers +from pandas.core.internals.managers import ( + BlockManager, + SingleBlockManager, +) + +__all__ = [ + "Block", # pylint: disable=undefined-all-variable + "DatetimeTZBlock", # pylint: disable=undefined-all-variable + "ExtensionBlock", # pylint: disable=undefined-all-variable + "make_block", + "DataManager", + "ArrayManager", + "BlockManager", + "SingleDataManager", + "SingleBlockManager", + "SingleArrayManager", + "concatenate_managers", +] + + +def __getattr__(name: str): + # GH#55139 + import warnings + + if name == "create_block_manager_from_blocks": + # GH#33892 + warnings.warn( + f"{name} is deprecated and will be removed in a future version. " + "Use public APIs instead.", + DeprecationWarning, + # https://github.com/pandas-dev/pandas/pull/55139#pullrequestreview-1720690758 + # on hard-coding stacklevel + stacklevel=2, + ) + from pandas.core.internals.managers import create_block_manager_from_blocks + + return create_block_manager_from_blocks + + if name in [ + "NumericBlock", + "ObjectBlock", + "Block", + "ExtensionBlock", + "DatetimeTZBlock", + ]: + warnings.warn( + f"{name} is deprecated and will be removed in a future version. " + "Use public APIs instead.", + DeprecationWarning, + # https://github.com/pandas-dev/pandas/pull/55139#pullrequestreview-1720690758 + # on hard-coding stacklevel + stacklevel=2, + ) + if name == "NumericBlock": + from pandas.core.internals.blocks import NumericBlock + + return NumericBlock + elif name == "DatetimeTZBlock": + from pandas.core.internals.blocks import DatetimeTZBlock + + return DatetimeTZBlock + elif name == "ExtensionBlock": + from pandas.core.internals.blocks import ExtensionBlock + + return ExtensionBlock + elif name == "Block": + from pandas.core.internals.blocks import Block + + return Block + else: + from pandas.core.internals.blocks import ObjectBlock + + return ObjectBlock + + raise AttributeError(f"module 'pandas.core.internals' has no attribute '{name}'") diff --git a/shared/package-files/2c/2c5265d20d8a7256727e777f2059577a28b601bd40c774e414570af8897bfc0d/_foreach_acos_compositeexplicitautograd_dispatch.h b/shared/package-files/2c/2c5265d20d8a7256727e777f2059577a28b601bd40c774e414570af8897bfc0d/_foreach_acos_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..da40225787c7f246a0a1ee18aee17f4fc4bcf0a6 --- /dev/null +++ b/shared/package-files/2c/2c5265d20d8a7256727e777f2059577a28b601bd40c774e414570af8897bfc0d/_foreach_acos_compositeexplicitautograd_dispatch.h @@ -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_acos_out(at::TensorList out, at::TensorList self); +TORCH_API void _foreach_acos_outf(at::TensorList self, at::TensorList out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/2c/2c5512d40663644dfd784a1096c873e6950f00c279300d6a6c801beeba80e4d5/conv2d.h b/shared/package-files/2c/2c5512d40663644dfd784a1096c873e6950f00c279300d6a6c801beeba80e4d5/conv2d.h new file mode 100644 index 0000000000000000000000000000000000000000..c5cc39919d544f44c73ed313a5b5e057a4246653 --- /dev/null +++ b/shared/package-files/2c/2c5512d40663644dfd784a1096c873e6950f00c279300d6a6c801beeba80e4d5/conv2d.h @@ -0,0 +1,69 @@ +#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::conv2d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1, SymInt groups=1) -> Tensor +inline at::Tensor conv2d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, int64_t groups=1) { + return at::_ops::conv2d::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups); +} +namespace symint { + template ::value>> + at::Tensor conv2d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, int64_t groups=1) { + return at::_ops::conv2d::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups); + } +} + +// aten::conv2d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1, SymInt groups=1) -> Tensor +inline at::Tensor conv2d_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 dilation=c10::SymInt(1), c10::SymInt groups=1) { + return at::_ops::conv2d::call(input, weight, bias, stride, padding, dilation, groups); +} +namespace symint { + template ::value>> + at::Tensor conv2d(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 dilation=c10::SymInt(1), c10::SymInt groups=1) { + return at::_ops::conv2d::call(input, weight, bias, stride, padding, dilation, groups); + } +} + +// aten::conv2d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, str padding="valid", SymInt[2] dilation=1, SymInt groups=1) -> Tensor +inline at::Tensor conv2d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, c10::string_view padding, at::IntArrayRef dilation=1, int64_t groups=1) { + return at::_ops::conv2d_padding::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), padding, c10::fromIntArrayRefSlow(dilation), groups); +} +namespace symint { + template ::value>> + at::Tensor conv2d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, c10::string_view padding, at::IntArrayRef dilation=1, int64_t groups=1) { + return at::_ops::conv2d_padding::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), padding, c10::fromIntArrayRefSlow(dilation), groups); + } +} + +// aten::conv2d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, str padding="valid", SymInt[2] dilation=1, SymInt groups=1) -> Tensor +inline at::Tensor conv2d_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::string_view padding, c10::SymIntArrayRef dilation=c10::SymInt(1), c10::SymInt groups=1) { + return at::_ops::conv2d_padding::call(input, weight, bias, stride, padding, dilation, groups); +} +namespace symint { + template ::value>> + at::Tensor conv2d(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::string_view padding, c10::SymIntArrayRef dilation=c10::SymInt(1), c10::SymInt groups=1) { + return at::_ops::conv2d_padding::call(input, weight, bias, stride, padding, dilation, groups); + } +} + +} diff --git a/shared/package-files/2c/2c5b86928b54a097c6919156bb3d18dc8d4ed045de55a8f6b460a165b90d7d49/test_flow_control.py b/shared/package-files/2c/2c5b86928b54a097c6919156bb3d18dc8d4ed045de55a8f6b460a165b90d7d49/test_flow_control.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab9104ac4017024d43e181eb2f1737f992180a --- /dev/null +++ b/shared/package-files/2c/2c5b86928b54a097c6919156bb3d18dc8d4ed045de55a8f6b460a165b90d7d49/test_flow_control.py @@ -0,0 +1,1281 @@ +import itertools + +import unittest +from numba import jit +from numba.core.controlflow import CFGraph, ControlFlowAnalysis +from numba.core import types +from numba.core.bytecode import FunctionIdentity, ByteCode, _fix_LOAD_GLOBAL_arg +from numba.tests.support import TestCase + +enable_pyobj_flags = {} + +no_pyobj_flags = {'_nrt': True, 'nopython': True} + + +def for_loop_usecase1(x, y): + result = 0 + for i in range(x): + result += i + return result + + +def for_loop_usecase2(x, y): + result = 0 + for i, j in enumerate(range(x, y, -1)): + result += i * j + return result + + +def for_loop_usecase3(x, y): + result = 0 + lst = [x, y] + for i in lst: + result += i + return result + + +def for_loop_usecase4(x, y): + result = 0 + for i in range(10): + for j in range(10): + result += 1 + return result + + +def for_loop_usecase5(x, y): + result = 0 + for i in range(x): + result += 1 + if result > y: + break + return result + + +def for_loop_usecase6(x, y): + result = 0 + for i in range(x): + if i > y: + continue + result += 1 + return result + + +def for_loop_usecase7(x, y): + for i in range(x): + x = 0 + for j in range(x): + return 1 + else: + pass + return 0 + + +def for_loop_usecase8(x, y): + result = 0 + for i in range(x, y, y - x + 1): + result += 1 + return result + + +def for_loop_usecase9(x, y): + z = 0 + for i in range(x): + x = 0 + for j in range(x): + if j == x / 2: + z += j + break + else: + z += y + + return z + + +def for_loop_usecase10(x, y): + for i in range(x): + if i == y: + z = y + break + else: + z = i * 2 + return z + + +def while_loop_usecase1(x, y): + result = 0 + i = 0 + while i < x: + result += i + i += 1 + return result + + +def while_loop_usecase2(x, y): + result = 0 + while result != x: + result += 1 + return result + + +def while_loop_usecase3(x, y): + result = 0 + i = 0 + j = 0 + while i < x: + while j < y: + result += i + j + i += 1 + j += 1 + return result + + +def while_loop_usecase4(x, y): + result = 0 + while True: + result += 1 + if result > x: + break + return result + + +def while_loop_usecase5(x, y): + result = 0 + while result < x: + if result > y: + result += 2 + continue + result += 1 + return result + + +def ifelse_usecase1(x, y): + if x > 0: + pass + elif y > 0: + pass + else: + pass + return True + + +def ifelse_usecase2(x, y): + if x > y: + return 1 + elif x == 0 or y == 0: + return 2 + else: + return 3 + + +def ifelse_usecase3(x, y): + if x > 0: + if y > 0: + return 1 + elif y < 0: + return 1 + else: + return 0 + elif x < 0: + return 1 + else: + return 0 + + +def ifelse_usecase4(x, y): + if x == y: + return 1 + + +def ternary_ifelse_usecase1(x, y): + return True if x > y else False + + +def double_infinite_loop(x, y): + L = x + i = y + + while True: + while True: + if i == L - 1: + break + i += 1 + i += 1 + if i >= L: + break + + return i, L + + +def try_except_usecase(): + try: + pass + except Exception: + pass + + +class TestFlowControl(TestCase): + + def run_test(self, pyfunc, x_operands, y_operands, + flags=enable_pyobj_flags): + cfunc = jit((types.intp, types.intp), **flags)(pyfunc) + for x, y in itertools.product(x_operands, y_operands): + pyerr = None + cerr = None + try: + pyres = pyfunc(x, y) + except Exception as e: + pyerr = e + + try: + cres = cfunc(x, y) + except Exception as e: + if pyerr is None: + raise + cerr = e + self.assertEqual(type(pyerr), type(cerr)) + else: + if pyerr is not None: + self.fail("Invalid for pure-python but numba works\n" + + pyerr) + self.assertEqual(pyres, cres) + + def test_for_loop1(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase1, [-10, 0, 10], [0], flags=flags) + + def test_for_loop1_npm(self): + self.test_for_loop1(flags=no_pyobj_flags) + + def test_for_loop2(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase2, [-10, 0, 10], [-10, 0, 10], + flags=flags) + + def test_for_loop2_npm(self): + self.test_for_loop2(flags=no_pyobj_flags) + + def test_for_loop3(self, flags=enable_pyobj_flags): + """ + List requires pyobject + """ + self.run_test(for_loop_usecase3, [1], [2], + flags=flags) + + def test_for_loop3_npm(self): + self.test_for_loop3(flags=no_pyobj_flags) + + def test_for_loop4(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase4, [10], [10], flags=flags) + + def test_for_loop4_npm(self): + self.test_for_loop4(flags=no_pyobj_flags) + + def test_for_loop5(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase5, [100], [50], flags=flags) + + def test_for_loop5_npm(self): + self.test_for_loop5(flags=no_pyobj_flags) + + def test_for_loop6(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase6, [100], [50], flags=flags) + + def test_for_loop6_npm(self): + self.test_for_loop6(flags=no_pyobj_flags) + + def test_for_loop7(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase7, [5], [0], flags=flags) + + def test_for_loop7_npm(self): + self.test_for_loop7(flags=no_pyobj_flags) + + def test_for_loop8(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase8, [0, 1], [0, 2, 10], flags=flags) + + def test_for_loop8_npm(self): + self.test_for_loop8(flags=no_pyobj_flags) + + def test_for_loop9(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase9, [0, 1], [0, 2, 10], flags=flags) + + def test_for_loop9_npm(self): + self.test_for_loop9(flags=no_pyobj_flags) + + def test_for_loop10(self, flags=enable_pyobj_flags): + self.run_test(for_loop_usecase10, [5], [2, 7], flags=flags) + + def test_for_loop10_npm(self): + self.test_for_loop10(flags=no_pyobj_flags) + + def test_while_loop1(self, flags=enable_pyobj_flags): + self.run_test(while_loop_usecase1, [10], [0], flags=flags) + + def test_while_loop1_npm(self): + self.test_while_loop1(flags=no_pyobj_flags) + + def test_while_loop2(self, flags=enable_pyobj_flags): + self.run_test(while_loop_usecase2, [10], [0], flags=flags) + + def test_while_loop2_npm(self): + self.test_while_loop2(flags=no_pyobj_flags) + + def test_while_loop3(self, flags=enable_pyobj_flags): + self.run_test(while_loop_usecase3, [10], [10], flags=flags) + + def test_while_loop3_npm(self): + self.test_while_loop3(flags=no_pyobj_flags) + + def test_while_loop4(self, flags=enable_pyobj_flags): + self.run_test(while_loop_usecase4, [10], [0], flags=flags) + + def test_while_loop4_npm(self): + self.test_while_loop4(flags=no_pyobj_flags) + + def test_while_loop5(self, flags=enable_pyobj_flags): + self.run_test(while_loop_usecase5, [0, 5, 10], [0, 5, 10], flags=flags) + + def test_while_loop5_npm(self): + self.test_while_loop5(flags=no_pyobj_flags) + + def test_ifelse1(self, flags=enable_pyobj_flags): + self.run_test(ifelse_usecase1, [-1, 0, 1], [-1, 0, 1], flags=flags) + + def test_ifelse1_npm(self): + self.test_ifelse1(flags=no_pyobj_flags) + + def test_ifelse2(self, flags=enable_pyobj_flags): + self.run_test(ifelse_usecase2, [-1, 0, 1], [-1, 0, 1], flags=flags) + + def test_ifelse2_npm(self): + self.test_ifelse2(flags=no_pyobj_flags) + + def test_ifelse3(self, flags=enable_pyobj_flags): + self.run_test(ifelse_usecase3, [-1, 0, 1], [-1, 0, 1], flags=flags) + + def test_ifelse3_npm(self): + self.test_ifelse3(flags=no_pyobj_flags) + + def test_ifelse4(self, flags=enable_pyobj_flags): + self.run_test(ifelse_usecase4, [-1, 0, 1], [-1, 0, 1], flags=flags) + + def test_ifelse4_npm(self): + self.test_ifelse4(flags=no_pyobj_flags) + + def test_ternary_ifelse1(self, flags=enable_pyobj_flags): + self.run_test(ternary_ifelse_usecase1, [-1, 0, 1], [-1, 0, 1], + flags=flags) + + def test_ternary_ifelse1_npm(self): + self.test_ternary_ifelse1(flags=no_pyobj_flags) + + def test_double_infinite_loop(self, flags=enable_pyobj_flags): + self.run_test(double_infinite_loop, [10], [0], + flags=flags) + + def test_double_infinite_loop_npm(self): + self.test_double_infinite_loop(flags=no_pyobj_flags) + + +class TestCFGraph(TestCase): + """ + Test the numba.controlflow.CFGraph class. + """ + + def from_adj_list(self, d, entry_point=0): + """ + Build a CFGraph class from a dict of adjacency lists. + """ + g = CFGraph() + # Need to add all nodes before adding edges + for node in d: + g.add_node(node) + for node, dests in d.items(): + for dest in dests: + g.add_edge(node, dest) + return g + + def loopless1(self): + """ + A simple CFG corresponding to the following code structure: + + c = (... if ... else ...) + ... + return b + c + """ + g = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: []}) + g.set_entry_point(0) + g.process() + return g + + def loopless1_dead_nodes(self): + """ + Same as loopless1(), but with added dead blocks (some of them + in a loop). + """ + g = self.from_adj_list( + {0: [18, 12], + 12: [21], + 18: [21], + 21: [], + 91: [12, 0], + 92: [91, 93], + 93: [92], + 94: [], + }) + g.set_entry_point(0) + g.process() + return g + + def loopless2(self): + """ + A loopless CFG corresponding to the following code structure: + + c = (... if ... else ...) + ... + if c: + return ... + else: + return ... + + Note there are two exit points, and the entry point has been + changed to a non-zero value. + """ + g = self.from_adj_list( + {99: [18, 12], 12: [21], 18: [21], 21: [42, 34], 34: [], 42: []}) + g.set_entry_point(99) + g.process() + return g + + def multiple_loops(self): + """ + A CFG with multiple nested loops: + + for y in b: + for x in a: + # This loop has two back edges + if b: + continue + else: + continue + for z in c: + if z: + return ... + """ + g = self.from_adj_list({0: [7], + 7: [10, 60], + 10: [13], + 13: [20], + 20: [56, 23], + 23: [32, 44], + 32: [20], + 44: [20], + 56: [57], + 57: [7], + 60: [61], + 61: [68], + 68: [87, 71], + 71: [80, 68], + 80: [], + 87: [88], + 88: []} + ) + g.set_entry_point(0) + g.process() + return g + + def multiple_exits(self): + """ + A CFG with three loop exits, one of which is also a function + exit point, and another function exit point: + + for x in a: + if a: + return b + elif b: + break + return c + """ + g = self.from_adj_list( + {0: [7], + 7: [10, 36], + 10: [19, 23], + 19: [], + 23: [29, 7], + 29: [37], + 36: [37], + 37: [] + }) + g.set_entry_point(0) + g.process() + return g + + def infinite_loop1(self): + """ + A CFG with a infinite loop and an alternate exit point: + + if c: + return + while True: + if a: + ... + else: + ... + """ + g = self.from_adj_list( + {0: [10, 6], 6: [], 10: [13], 13: [26, 19], 19: [13], 26: [13]}) + g.set_entry_point(0) + g.process() + return g + + def infinite_loop2(self): + """ + A CFG with no exit point at all: + + while True: + if a: + ... + else: + ... + """ + g = self.from_adj_list({0: [3], 3: [16, 9], 9: [3], 16: [3]}) + g.set_entry_point(0) + g.process() + return g + + def test_simple_properties(self): + g = self.loopless1() + self.assertEqual(sorted(g.successors(0)), [(12, None), (18, None)]) + self.assertEqual(sorted(g.successors(21)), []) + self.assertEqual(sorted(g.predecessors(0)), []) + self.assertEqual(sorted(g.predecessors(21)), [(12, None), (18, None)]) + + def test_exit_points(self): + g = self.loopless1() + self.assertEqual(sorted(g.exit_points()), [21]) + g = self.loopless1_dead_nodes() + self.assertEqual(sorted(g.exit_points()), [21]) + g = self.loopless2() + self.assertEqual(sorted(g.exit_points()), [34, 42]) + g = self.multiple_loops() + self.assertEqual(sorted(g.exit_points()), [80, 88]) + g = self.infinite_loop1() + self.assertEqual(sorted(g.exit_points()), [6]) + g = self.infinite_loop2() + self.assertEqual(sorted(g.exit_points()), []) + g = self.multiple_exits() + self.assertEqual(sorted(g.exit_points()), [19, 37]) + + def test_dead_nodes(self): + g = self.loopless1() + self.assertEqual(len(g.dead_nodes()), 0) + self.assertEqual(sorted(g.nodes()), + [0, 12, 18, 21]) + g = self.loopless2() + self.assertEqual(len(g.dead_nodes()), 0) + self.assertEqual(sorted(g.nodes()), + [12, 18, 21, 34, 42, 99]) + g = self.multiple_loops() + self.assertEqual(len(g.dead_nodes()), 0) + g = self.infinite_loop1() + self.assertEqual(len(g.dead_nodes()), 0) + g = self.multiple_exits() + self.assertEqual(len(g.dead_nodes()), 0) + # Only this example has dead nodes + g = self.loopless1_dead_nodes() + self.assertEqual(sorted(g.dead_nodes()), + [91, 92, 93, 94]) + self.assertEqual(sorted(g.nodes()), + [0, 12, 18, 21]) + + def test_descendents(self): + g = self.loopless2() + d = g.descendents(34) + self.assertEqual(sorted(d), []) + d = g.descendents(42) + self.assertEqual(sorted(d), []) + d = g.descendents(21) + self.assertEqual(sorted(d), [34, 42]) + d = g.descendents(99) + self.assertEqual(sorted(d), [12, 18, 21, 34, 42]) + g = self.infinite_loop1() + d = g.descendents(26) + self.assertEqual(sorted(d), []) + d = g.descendents(19) + self.assertEqual(sorted(d), []) + d = g.descendents(13) + self.assertEqual(sorted(d), [19, 26]) + d = g.descendents(10) + self.assertEqual(sorted(d), [13, 19, 26]) + d = g.descendents(6) + self.assertEqual(sorted(d), []) + d = g.descendents(0) + self.assertEqual(sorted(d), [6, 10, 13, 19, 26]) + + def test_topo_order(self): + g = self.loopless1() + self.assertIn(g.topo_order(), + ([0, 12, 18, 21], [0, 18, 12, 21])) + g = self.loopless2() + self.assertIn(g.topo_order(), + ([99, 18, 12, 21, 34, 42], [99, 12, 18, 21, 34, 42], + [99, 18, 12, 21, 42, 34], [99, 12, 18, 21, 42, 34])) + g = self.infinite_loop2() + self.assertIn(g.topo_order(), + ([0, 3, 9, 16], [0, 3, 16, 9])) + g = self.infinite_loop1() + self.assertIn(g.topo_order(), + ([0, 6, 10, 13, 19, 26], [0, 6, 10, 13, 26, 19], + [0, 10, 13, 19, 26, 6], [0, 10, 13, 26, 19, 6])) + + def test_topo_sort(self): + def check_topo_sort(nodes, expected): + self.assertIn(list(g.topo_sort(nodes)), expected) + self.assertIn(list(g.topo_sort(nodes[::-1])), expected) + self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1], + expected) + self.assertIn(list(g.topo_sort(nodes[::-1], reverse=True))[::-1], + expected) + self.random.shuffle(nodes) + self.assertIn(list(g.topo_sort(nodes)), expected) + self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1], + expected) + + g = self.loopless2() + check_topo_sort([21, 99, 12, 34], ([99, 12, 21, 34],)) + # NOTE: topo_sort() is not stable + check_topo_sort([18, 12, 42, 99], + ([99, 12, 18, 42], [99, 18, 12, 42])) + g = self.multiple_exits() + check_topo_sort([19, 10, 7, 36], + ([7, 10, 19, 36], [7, 10, 36, 19], [7, 36, 10, 19])) + + def check_dominators(self, got, expected): + self.assertEqual(sorted(got), sorted(expected)) + for node in sorted(got): + self.assertEqual(sorted(got[node]), sorted(expected[node]), + "mismatch for %r" % (node,)) + + def test_dominators_loopless(self): + def eq_(d, l): + self.assertEqual(sorted(doms[d]), l) + for g in [self.loopless1(), self.loopless1_dead_nodes()]: + doms = g.dominators() + eq_(0, [0]) + eq_(12, [0, 12]) + eq_(18, [0, 18]) + eq_(21, [0, 21]) + g = self.loopless2() + doms = g.dominators() + eq_(99, [99]) + eq_(12, [12, 99]) + eq_(18, [18, 99]) + eq_(21, [21, 99]) + eq_(34, [21, 34, 99]) + eq_(42, [21, 42, 99]) + + def test_dominators_loops(self): + g = self.multiple_exits() + doms = g.dominators() + self.check_dominators(doms, + {0: [0], + 7: [0, 7], + 10: [0, 7, 10], + 19: [0, 7, 10, 19], + 23: [0, 7, 10, 23], + 29: [0, 7, 10, 23, 29], + 36: [0, 7, 36], + 37: [0, 7, 37], + }) + g = self.multiple_loops() + doms = g.dominators() + self.check_dominators(doms, + {0: [0], + 7: [0, 7], + 10: [0, 10, 7], + 13: [0, 10, 13, 7], + 20: [0, 10, 20, 13, 7], + 23: [0, 20, 23, 7, 10, 13], + 32: [32, 0, 20, 23, 7, 10, 13], + 44: [0, 20, 23, 7, 10, 44, 13], + 56: [0, 20, 7, 56, 10, 13], + 57: [0, 20, 7, 56, 57, 10, 13], + 60: [0, 60, 7], + 61: [0, 60, 61, 7], + 68: [0, 68, 60, 61, 7], + 71: [0, 68, 71, 7, 60, 61], + 80: [80, 0, 68, 71, 7, 60, 61], + 87: [0, 68, 87, 7, 60, 61], + 88: [0, 68, 87, 88, 7, 60, 61] + }) + g = self.infinite_loop1() + doms = g.dominators() + self.check_dominators(doms, + {0: [0], + 6: [0, 6], + 10: [0, 10], + 13: [0, 10, 13], + 19: [0, 10, 19, 13], + 26: [0, 10, 13, 26], + }) + + def test_post_dominators_loopless(self): + def eq_(d, l): + self.assertEqual(sorted(doms[d]), l) + for g in [self.loopless1(), self.loopless1_dead_nodes()]: + doms = g.post_dominators() + eq_(0, [0, 21]) + eq_(12, [12, 21]) + eq_(18, [18, 21]) + eq_(21, [21]) + g = self.loopless2() + doms = g.post_dominators() + eq_(34, [34]) + eq_(42, [42]) + eq_(21, [21]) + eq_(18, [18, 21]) + eq_(12, [12, 21]) + eq_(99, [21, 99]) + + def test_post_dominators_loops(self): + g = self.multiple_exits() + doms = g.post_dominators() + self.check_dominators(doms, + {0: [0, 7], + 7: [7], + 10: [10], + 19: [19], + 23: [23], + 29: [29, 37], + 36: [36, 37], + 37: [37], + }) + g = self.multiple_loops() + doms = g.post_dominators() + self.check_dominators(doms, + {0: [0, 60, 68, 61, 7], + 7: [60, 68, 61, 7], + 10: [68, 7, 10, 13, 20, 56, 57, 60, 61], + 13: [68, 7, 13, 20, 56, 57, 60, 61], + 20: [20, 68, 7, 56, 57, 60, 61], + 23: [68, 7, 20, 23, 56, 57, 60, 61], + 32: [32, 68, 7, 20, 56, 57, 60, 61], + 44: [68, 7, 44, 20, 56, 57, 60, 61], + 56: [68, 7, 56, 57, 60, 61], + 57: [57, 60, 68, 61, 7], + 60: [60, 68, 61], + 61: [68, 61], + 68: [68], + 71: [71], + 80: [80], + 87: [88, 87], + 88: [88] + }) + + def test_post_dominators_infinite_loops(self): + # Post-dominators with infinite loops need special care + # (the ordinary algorithm won't work). + g = self.infinite_loop1() + doms = g.post_dominators() + self.check_dominators(doms, + {0: [0], + 6: [6], + 10: [10, 13], + 13: [13], + 19: [19], + 26: [26], + }) + g = self.infinite_loop2() + doms = g.post_dominators() + self.check_dominators(doms, + {0: [0, 3], + 3: [3], + 9: [9], + 16: [16], + }) + + def test_dominator_tree(self): + def check(graph, expected): + domtree = graph.dominator_tree() + self.assertEqual(domtree, expected) + + check(self.loopless1(), + {0: {12, 18, 21}, 12: set(), 18: set(), 21: set()}) + check(self.loopless2(), + {12: set(), 18: set(), 21: {34, 42}, 34: set(), 42: set(), + 99: {18, 12, 21}}) + check(self.loopless1_dead_nodes(), + {0: {12, 18, 21}, 12: set(), 18: set(), 21: set()}) + check(self.multiple_loops(), + {0: {7}, 7: {10, 60}, 60: {61}, 61: {68}, 68: {71, 87}, + 87: {88}, 88: set(), 71: {80}, 80: set(), 10: {13}, + 13: {20}, 20: {56, 23}, 23: {32, 44}, 44: set(), + 32: set(), 56: {57}, 57: set()}) + check(self.multiple_exits(), + {0: {7}, 7: {10, 36, 37}, 36: set(), 10: {19, 23}, + 23: {29}, 29: set(), 37: set(), 19: set()}) + check(self.infinite_loop1(), + {0: {10, 6}, 6: set(), 10: {13}, 13: {26, 19}, 19: set(), + 26: set()}) + check(self.infinite_loop2(), + {0: {3}, 3: {16, 9}, 9: set(), 16: set()}) + + def test_immediate_dominators(self): + def check(graph, expected): + idoms = graph.immediate_dominators() + self.assertEqual(idoms, expected) + + check(self.loopless1(), + {0: 0, 12: 0, 18: 0, 21: 0}) + check(self.loopless2(), + {18: 99, 12: 99, 21: 99, 42: 21, 34: 21, 99: 99}) + check(self.loopless1_dead_nodes(), + {0: 0, 12: 0, 18: 0, 21: 0}) + check(self.multiple_loops(), + {0: 0, 7: 0, 10: 7, 13: 10, 20: 13, 23: 20, + 32: 23, 44: 23, 56: 20, 57: 56, 60: 7, 61: 60, + 68: 61, 71: 68, 80: 71, 87: 68, 88: 87}) + check(self.multiple_exits(), + {0:0, 7: 0, 10: 7, 19: 10, 23: 10, 29: 23, 36: 7, 37: 7}) + check(self.infinite_loop1(), + {0: 0, 6: 0, 10: 0, 13: 10, 19: 13, 26: 13}) + check(self.infinite_loop2(), + {0: 0, 3: 0, 9: 3, 16: 3}) + + def test_dominance_frontier(self): + def check(graph, expected): + df = graph.dominance_frontier() + self.assertEqual(df, expected) + + check(self.loopless1(), + {0: set(), 12: {21}, 18: {21}, 21: set()}) + check(self.loopless2(), + {18: {21}, 12: {21}, 21: set(), 42: set(), 34: set(), 99: set()}) + check(self.loopless1_dead_nodes(), + {0: set(), 12: {21}, 18: {21}, 21: set()}) + check(self.multiple_loops(), + {0: set(), 7: {7}, 10: {7}, 13: {7}, 20: {20, 7}, 23: {20}, + 32: {20}, 44: {20}, 56: {7}, 57: {7}, 60: set(), 61: set(), + 68: {68}, 71: {68}, 80: set(), 87: set(), 88: set()}) + check(self.multiple_exits(), + {0: set(), 7: {7}, 10: {37, 7}, 19: set(), + 23: {37, 7}, 29: {37}, 36: {37}, 37: set()}) + check(self.infinite_loop1(), + {0: set(), 6: set(), 10: set(), 13: {13}, 19: {13}, 26: {13}}) + check(self.infinite_loop2(), + {0: set(), 3: {3}, 9: {3}, 16: {3}}) + + def test_backbone_loopless(self): + for g in [self.loopless1(), self.loopless1_dead_nodes()]: + self.assertEqual(sorted(g.backbone()), [0, 21]) + g = self.loopless2() + self.assertEqual(sorted(g.backbone()), [21, 99]) + + def test_backbone_loops(self): + g = self.multiple_loops() + self.assertEqual(sorted(g.backbone()), [0, 7, 60, 61, 68]) + g = self.infinite_loop1() + self.assertEqual(sorted(g.backbone()), [0]) + g = self.infinite_loop2() + self.assertEqual(sorted(g.backbone()), [0, 3]) + + def test_loops(self): + for g in [self.loopless1(), self.loopless1_dead_nodes(), + self.loopless2()]: + self.assertEqual(len(g.loops()), 0) + + g = self.multiple_loops() + # Loop headers + self.assertEqual(sorted(g.loops()), [7, 20, 68]) + outer1 = g.loops()[7] + inner1 = g.loops()[20] + outer2 = g.loops()[68] + self.assertEqual(outer1.header, 7) + self.assertEqual(sorted(outer1.entries), [0]) + self.assertEqual(sorted(outer1.exits), [60]) + self.assertEqual(sorted(outer1.body), + [7, 10, 13, 20, 23, 32, 44, 56, 57]) + self.assertEqual(inner1.header, 20) + self.assertEqual(sorted(inner1.entries), [13]) + self.assertEqual(sorted(inner1.exits), [56]) + self.assertEqual(sorted(inner1.body), [20, 23, 32, 44]) + self.assertEqual(outer2.header, 68) + self.assertEqual(sorted(outer2.entries), [61]) + self.assertEqual(sorted(outer2.exits), [80, 87]) + self.assertEqual(sorted(outer2.body), [68, 71]) + for node in [0, 60, 61, 80, 87, 88]: + self.assertEqual(g.in_loops(node), []) + for node in [7, 10, 13, 56, 57]: + self.assertEqual(g.in_loops(node), [outer1]) + for node in [20, 23, 32, 44]: + self.assertEqual(g.in_loops(node), [inner1, outer1]) + for node in [68, 71]: + self.assertEqual(g.in_loops(node), [outer2]) + + g = self.infinite_loop1() + # Loop headers + self.assertEqual(sorted(g.loops()), [13]) + loop = g.loops()[13] + self.assertEqual(loop.header, 13) + self.assertEqual(sorted(loop.entries), [10]) + self.assertEqual(sorted(loop.exits), []) + self.assertEqual(sorted(loop.body), [13, 19, 26]) + for node in [0, 6, 10]: + self.assertEqual(g.in_loops(node), []) + for node in [13, 19, 26]: + self.assertEqual(g.in_loops(node), [loop]) + + g = self.infinite_loop2() + # Loop headers + self.assertEqual(sorted(g.loops()), [3]) + loop = g.loops()[3] + self.assertEqual(loop.header, 3) + self.assertEqual(sorted(loop.entries), [0]) + self.assertEqual(sorted(loop.exits), []) + self.assertEqual(sorted(loop.body), [3, 9, 16]) + for node in [0]: + self.assertEqual(g.in_loops(node), []) + for node in [3, 9, 16]: + self.assertEqual(g.in_loops(node), [loop]) + + g = self.multiple_exits() + # Loop headers + self.assertEqual(sorted(g.loops()), [7]) + loop = g.loops()[7] + self.assertEqual(loop.header, 7) + self.assertEqual(sorted(loop.entries), [0]) + self.assertEqual(sorted(loop.exits), [19, 29, 36]) + self.assertEqual(sorted(loop.body), [7, 10, 23]) + for node in [0, 19, 29, 36]: + self.assertEqual(g.in_loops(node), []) + for node in [7, 10, 23]: + self.assertEqual(g.in_loops(node), [loop]) + + def test_loop_dfs_pathological(self): + # The follow adjlist is an export from the reproducer in #6186 + g = self.from_adj_list({ + 0: {38, 14}, + 14: {38, 22}, + 22: {38, 30}, + 30: {42, 38}, + 38: {42}, + 42: {64, 50}, + 50: {64, 58}, + 58: {128}, + 64: {72, 86}, + 72: {80, 86}, + 80: {128}, + 86: {108, 94}, + 94: {108, 102}, + 102: {128}, + 108: {128, 116}, + 116: {128, 124}, + 124: {128}, + 128: {178, 174}, + 174: {178}, + 178: {210, 206}, + 206: {210}, + 210: {248, 252}, + 248: {252}, + 252: {282, 286}, + 282: {286}, + 286: {296, 326}, + 296: {330}, + 326: {330}, + 330: {370, 340}, + 340: {374}, + 370: {374}, + 374: {380, 382}, + 380: {382}, + 382: {818, 390}, + 390: {456, 458}, + 456: {458}, + 458: {538, 566}, + 538: {548, 566}, + 548: set(), + 566: {586, 572}, + 572: {586}, + 586: {708, 596}, + 596: {608}, + 608: {610}, + 610: {704, 620}, + 620: {666, 630}, + 630: {636, 646}, + 636: {666, 646}, + 646: {666}, + 666: {610}, + 704: {706}, + 706: {818}, + 708: {720}, + 720: {722}, + 722: {816, 732}, + 732: {778, 742}, + 742: {748, 758}, + 748: {778, 758}, + 758: {778}, + 778: {722}, + 816: {818}, + 818: set(), + }) + g.set_entry_point(0) + g.process() + stats = {} + # Compute backedges and store the iteration count for testing + back_edges = g._find_back_edges(stats=stats) + self.assertEqual(back_edges, {(666, 610), (778, 722)}) + self.assertEqual(stats['iteration_count'], 155) + + def test_equals(self): + + def get_new(): + g = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: []}) + g.set_entry_point(0) + g.process() + return g + + x = get_new() + y = get_new() + + # identical + self.assertEqual(x, y) + + # identical but defined in a different order + g = self.from_adj_list({0: [12, 18], 18: [21], 21: [], 12: [21]}) + g.set_entry_point(0) + g.process() + self.assertEqual(x, g) + + # different entry point + z = get_new() + z.set_entry_point(18) + z.process() + self.assertNotEqual(x, z) + + # extra node/edge, same entry point + z = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: [22], + 22: []}) + z.set_entry_point(0) + z.process() + self.assertNotEqual(x, z) + + # same nodes, different edges + a = self.from_adj_list({0: [18, 12], 12: [0], 18: []}) + a.set_entry_point(0) + a.process() + z = self.from_adj_list({0: [18, 12], 12: [18], 18: []}) + z.set_entry_point(0) + z.process() + self.assertNotEqual(a, z) + + +class TestRealCodeDomFront(TestCase): + """Test IDOM and DOMFRONT computation on real python bytecode. + Note: there will be less testing on IDOM (esp in loop) because of + the extra blocks inserted by the interpreter. But, testing on DOMFRONT + (which depends on IDOM) is easier. + + Testing is done by associating names to basicblock by using globals of + the pattern "SET_BLOCK_", which are scanned by + `.get_cfa_and_namedblocks` into *namedblocks* dictionary. That way, we + can check that a block of a certain name is a IDOM or DOMFRONT of another + named block. + """ + def cfa(self, bc): + cfa = ControlFlowAnalysis(bc) + cfa.run() + return cfa + + def get_cfa_and_namedblocks(self, fn): + fid = FunctionIdentity.from_function(fn) + bc = ByteCode(func_id=fid) + cfa = self.cfa(bc) + namedblocks = self._scan_namedblocks(bc, cfa) + + #### To debug, uncomment below + # print(bc.dump()) + # print("IDOMS") + # for k, v in sorted(cfa.graph.immediate_dominators().items()): + # print('{} -> {}'.format(k, v)) + # print("DOMFRONT") + # for k, vs in sorted(cfa.graph.dominance_frontier().items()): + # print('{} -> {}'.format(k, vs)) + # print(namedblocks) + # cfa.graph.render_dot().view() + + return cfa, namedblocks + + def _scan_namedblocks(self, bc, cfa): + """Scan namedblocks as denoted by a LOAD_GLOBAL bytecode referring + to global variables with the pattern "SET_BLOCK_", where "" + would be the name for the current block. + """ + namedblocks = {} + blocks = sorted([x.offset for x in cfa.iterblocks()]) + prefix = 'SET_BLOCK_' + + for inst in bc: + # Find LOAD_GLOBAL that refers to "SET_BLOCK_" + if inst.opname == 'LOAD_GLOBAL': + gv = bc.co_names[_fix_LOAD_GLOBAL_arg(inst.arg)] + if gv.startswith(prefix): + name = gv[len(prefix):] + # Find the block where this instruction resides + for s, e in zip(blocks, blocks[1:] + [blocks[-1] + 1]): + if s <= inst.offset < e: + break + else: + raise AssertionError('unreachable loop') + blkno = s + namedblocks[name] = blkno + return namedblocks + + def test_loop(self): + def foo(n): + c = 0 + SET_BLOCK_A # noqa: F821 + i = 0 + while SET_BLOCK_B0: # noqa: F821 + SET_BLOCK_B1 # noqa: F821 + c += 1 + i += 1 + SET_BLOCK_C # noqa: F821 + return c + + cfa, blkpts = self.get_cfa_and_namedblocks(foo) + + # Py3.10 turns while loop into if(...) { do {...} while(...) }. + # Also, `SET_BLOCK_B0` is duplicated. As a result, the second B0 + # is picked up by `blkpts`. + domfront = cfa.graph.dominance_frontier() + self.assertFalse(domfront[blkpts['A']]) + self.assertFalse(domfront[blkpts['C']]) + + def test_loop_nested_and_break(self): + def foo(n): + SET_BLOCK_A # noqa: F821 + while SET_BLOCK_B0: # noqa: F821 + SET_BLOCK_B1 # noqa: F821 + while SET_BLOCK_C0: # noqa: F821 + SET_BLOCK_C1 # noqa: F821 + if SET_BLOCK_D0: # noqa: F821 + SET_BLOCK_D1 # noqa: F821 + break + elif n: + SET_BLOCK_D2 # noqa: F821 + SET_BLOCK_E # noqa: F821 + SET_BLOCK_F # noqa: F821 + SET_BLOCK_G # noqa: F821 + + cfa, blkpts = self.get_cfa_and_namedblocks(foo) + self.assertEqual(blkpts['D0'], blkpts['C1']) + + # Py3.10 changes while loop into if-do-while + domfront = cfa.graph.dominance_frontier() + self.assertFalse(domfront[blkpts['A']]) + self.assertFalse(domfront[blkpts['G']]) + # 2 domfront members for C1 + # C0 because of the loop; F because of the break. + self.assertEqual({blkpts['F']}, domfront[blkpts['D1']]) + self.assertEqual({blkpts['E']}, domfront[blkpts['D2']]) + + def test_if_else(self): + def foo(a, b): + c = 0 + SET_BLOCK_A # noqa: F821 + if a < b: + SET_BLOCK_B # noqa: F821 + c = 1 + elif SET_BLOCK_C0: # noqa: F821 + SET_BLOCK_C1 # noqa: F821 + c = 2 + else: + SET_BLOCK_D # noqa: F821 + c = 3 + + SET_BLOCK_E # noqa: F821 + if a % b == 0: + SET_BLOCK_F # noqa: F821 + c += 1 + SET_BLOCK_G # noqa: F821 + return c + + cfa, blkpts = self.get_cfa_and_namedblocks(foo) + + idoms = cfa.graph.immediate_dominators() + self.assertEqual(blkpts['A'], idoms[blkpts['B']]) + self.assertEqual(blkpts['A'], idoms[blkpts['C0']]) + self.assertEqual(blkpts['C0'], idoms[blkpts['C1']]) + self.assertEqual(blkpts['C0'], idoms[blkpts['D']]) + self.assertEqual(blkpts['A'], idoms[blkpts['E']]) + self.assertEqual(blkpts['E'], idoms[blkpts['F']]) + self.assertEqual(blkpts['E'], idoms[blkpts['G']]) + + domfront = cfa.graph.dominance_frontier() + self.assertFalse(domfront[blkpts['A']]) + self.assertFalse(domfront[blkpts['E']]) + self.assertFalse(domfront[blkpts['G']]) + self.assertEqual({blkpts['E']}, domfront[blkpts['B']]) + self.assertEqual({blkpts['E']}, domfront[blkpts['C0']]) + self.assertEqual({blkpts['E']}, domfront[blkpts['C1']]) + self.assertEqual({blkpts['E']}, domfront[blkpts['D']]) + self.assertEqual({blkpts['G']}, domfront[blkpts['F']]) + + def test_if_else_nested(self): + def foo(): + if SET_BLOCK_A0: # noqa: F821 + SET_BLOCK_A1 # noqa: F821 + if SET_BLOCK_B0: # noqa: F821 + SET_BLOCK_B1 # noqa: F821 + a = 0 + else: + if SET_BLOCK_C0: # noqa: F821 + SET_BLOCK_C1 # noqa: F821 + a = 1 + else: + SET_BLOCK_C2 # noqa: F821 + a = 2 + SET_BLOCK_D # noqa: F821 + SET_BLOCK_E # noqa: F821 + SET_BLOCK_F # noqa: F821 + return a + + cfa, blkpts = self.get_cfa_and_namedblocks(foo) + + idoms = cfa.graph.immediate_dominators() + self.assertEqual(blkpts['A0'], idoms[blkpts['A1']]) + self.assertEqual(blkpts['A1'], idoms[blkpts['B1']]) + self.assertEqual(blkpts['A1'], idoms[blkpts['C0']]) + self.assertEqual(blkpts['C0'], idoms[blkpts['D']]) + self.assertEqual(blkpts['A1'], idoms[blkpts['E']]) + self.assertEqual(blkpts['A0'], idoms[blkpts['F']]) + + domfront = cfa.graph.dominance_frontier() + self.assertFalse(domfront[blkpts['A0']]) + self.assertFalse(domfront[blkpts['F']]) + self.assertEqual({blkpts['E']}, domfront[blkpts['B1']]) + self.assertEqual({blkpts['D']}, domfront[blkpts['C1']]) + self.assertEqual({blkpts['E']}, domfront[blkpts['D']]) + self.assertEqual({blkpts['F']}, domfront[blkpts['E']]) + + def test_infinite_loop(self): + def foo(): + SET_BLOCK_A # noqa: F821 + while True: # infinite loop + if SET_BLOCK_B: # noqa: F821 + SET_BLOCK_C # noqa: F821 + return + SET_BLOCK_D # noqa: F821 + SET_BLOCK_E # noqa: F821 + + cfa, blkpts = self.get_cfa_and_namedblocks(foo) + + idoms = cfa.graph.immediate_dominators() + # Py3.10 optimizes away the infinite loop and removes SET_BLOCK_E from + # the bytecode. + self.assertNotIn('E', blkpts) + self.assertEqual(blkpts['B'], idoms[blkpts['C']]) + self.assertEqual(blkpts['B'], idoms[blkpts['D']]) + + domfront = cfa.graph.dominance_frontier() + self.assertFalse(domfront[blkpts['A']]) + self.assertFalse(domfront[blkpts['C']]) + self.assertEqual({blkpts['B']}, domfront[blkpts['B']]) + self.assertEqual({blkpts['B']}, domfront[blkpts['D']]) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/2c/2c5d8f91b686565378274739f13ede913b96365874afb791a55da85b3b9fe233/test_curried.py b/shared/package-files/2c/2c5d8f91b686565378274739f13ede913b96365874afb791a55da85b3b9fe233/test_curried.py new file mode 100644 index 0000000000000000000000000000000000000000..32c4be5b66116ea7307a136bd9e81a75ceadfbc4 --- /dev/null +++ b/shared/package-files/2c/2c5d8f91b686565378274739f13ede913b96365874afb791a55da85b3b9fe233/test_curried.py @@ -0,0 +1,117 @@ +import toolz +import toolz.curried +from toolz.curried import (take, first, second, sorted, merge_with, reduce, + merge, operator as cop) +from collections import defaultdict +from importlib import import_module +from operator import add + + +def test_take(): + assert list(take(2)([1, 2, 3])) == [1, 2] + + +def test_first(): + assert first is toolz.itertoolz.first + + +def test_merge(): + assert merge(factory=lambda: defaultdict(int))({1: 1}) == {1: 1} + assert merge({1: 1}) == {1: 1} + assert merge({1: 1}, factory=lambda: defaultdict(int)) == {1: 1} + + +def test_merge_with(): + assert merge_with(sum)({1: 1}, {1: 2}) == {1: 3} + + +def test_merge_with_list(): + assert merge_with(sum, [{'a': 1}, {'a': 2}]) == {'a': 3} + + +def test_sorted(): + assert sorted(key=second)([(1, 2), (2, 1)]) == [(2, 1), (1, 2)] + + +def test_reduce(): + assert reduce(add)((1, 2, 3)) == 6 + + +def test_module_name(): + assert toolz.curried.__name__ == 'toolz.curried' + + +def should_curry(func): + if not callable(func) or isinstance(func, toolz.curry): + return False + nargs = toolz.functoolz.num_required_args(func) + if nargs is None or nargs > 1: + return True + return nargs == 1 and toolz.functoolz.has_keywords(func) + + +def test_curried_operator(): + import operator + + for k, v in vars(cop).items(): + if not callable(v): + continue + + if not isinstance(v, toolz.curry): + try: + # Make sure it is unary + v(1) + except TypeError: + try: + v('x') + except TypeError: + pass + else: + continue + raise AssertionError( + 'toolz.curried.operator.%s is not curried!' % k, + ) + assert should_curry(getattr(operator, k)) == isinstance(v, toolz.curry), k + + # Make sure this isn't totally empty. + assert len(set(vars(cop)) & {'add', 'sub', 'mul'}) == 3 + + +def test_curried_namespace(): + exceptions = import_module('toolz.curried.exceptions') + namespace = {} + + + def curry_namespace(ns): + return { + name: toolz.curry(f) if should_curry(f) else f + for name, f in ns.items() if '__' not in name + } + + from_toolz = curry_namespace(vars(toolz)) + from_exceptions = curry_namespace(vars(exceptions)) + namespace.update(toolz.merge(from_toolz, from_exceptions)) + + namespace = toolz.valfilter(callable, namespace) + curried_namespace = toolz.valfilter(callable, toolz.curried.__dict__) + + if namespace != curried_namespace: + missing = set(namespace) - set(curried_namespace) + if missing: + raise AssertionError('There are missing functions in toolz.curried:\n %s' + % ' \n'.join(sorted(missing))) + extra = set(curried_namespace) - set(namespace) + if extra: + raise AssertionError('There are extra functions in toolz.curried:\n %s' + % ' \n'.join(sorted(extra))) + unequal = toolz.merge_with(list, namespace, curried_namespace) + unequal = toolz.valfilter(lambda x: x[0] != x[1], unequal) + messages = [] + for name, (orig_func, auto_func) in sorted(unequal.items()): + if name in from_exceptions: + messages.append('%s should come from toolz.curried.exceptions' % name) + elif should_curry(getattr(toolz, name)): + messages.append('%s should be curried from toolz' % name) + else: + messages.append('%s should come from toolz and NOT be curried' % name) + raise AssertionError('\n'.join(messages)) diff --git a/shared/package-files/2c/2c5f7580a25c1c85a80fd6ad87ff7e63b1e053041b03410baa0558be6d580160/_morphology.py b/shared/package-files/2c/2c5f7580a25c1c85a80fd6ad87ff7e63b1e053041b03410baa0558be6d580160/_morphology.py new file mode 100644 index 0000000000000000000000000000000000000000..12972c09a7cd5de0ca059814281fb9d210fbd395 --- /dev/null +++ b/shared/package-files/2c/2c5f7580a25c1c85a80fd6ad87ff7e63b1e053041b03410baa0558be6d580160/_morphology.py @@ -0,0 +1,2629 @@ +# 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 warnings +import operator + +import numpy as np +from . import _ni_support +from . import _nd_image +from . import _filters + +__all__ = ['iterate_structure', 'generate_binary_structure', 'binary_erosion', + 'binary_dilation', 'binary_opening', 'binary_closing', + 'binary_hit_or_miss', 'binary_propagation', 'binary_fill_holes', + 'grey_erosion', 'grey_dilation', 'grey_opening', 'grey_closing', + 'morphological_gradient', 'morphological_laplace', 'white_tophat', + 'black_tophat', 'distance_transform_bf', 'distance_transform_cdt', + 'distance_transform_edt'] + + +def _center_is_true(structure, origin): + structure = np.asarray(structure) + coor = tuple([oo + ss // 2 for ss, oo in zip(structure.shape, + origin)]) + return bool(structure[coor]) + + +def iterate_structure(structure, iterations, origin=None): + """ + Iterate a structure by dilating it with itself. + + Parameters + ---------- + structure : array_like + Structuring element (an array of bools, for example), to be dilated with + itself. + iterations : int + number of dilations performed on the structure with itself + origin : optional + If origin is None, only the iterated structure is returned. If + not, a tuple of the iterated structure and the modified origin is + returned. + + Returns + ------- + iterate_structure : ndarray of bools + A new structuring element obtained by dilating `structure` + (`iterations` - 1) times with itself. + + See Also + -------- + generate_binary_structure + + Examples + -------- + >>> from scipy import ndimage + >>> struct = ndimage.generate_binary_structure(2, 1) + >>> struct.astype(int) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) + >>> ndimage.iterate_structure(struct, 2).astype(int) + array([[0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0]]) + >>> ndimage.iterate_structure(struct, 3).astype(int) + array([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]]) + + """ + structure = np.asarray(structure) + if iterations < 2: + return structure.copy() + ni = iterations - 1 + shape = [ii + ni * (ii - 1) for ii in structure.shape] + pos = [ni * (structure.shape[ii] // 2) for ii in range(len(shape))] + slc = tuple(slice(pos[ii], pos[ii] + structure.shape[ii], None) + for ii in range(len(shape))) + out = np.zeros(shape, bool) + out[slc] = structure != 0 + out = binary_dilation(out, structure, iterations=ni) + if origin is None: + return out + else: + origin = _ni_support._normalize_sequence(origin, structure.ndim) + origin = [iterations * o for o in origin] + return out, origin + + +def generate_binary_structure(rank, connectivity): + """ + Generate a binary structure for binary morphological operations. + + Parameters + ---------- + rank : int + Number of dimensions of the array to which the structuring element + will be applied, as returned by `np.ndim`. + connectivity : int + `connectivity` determines which elements of the output array belong + to the structure, i.e., are considered as neighbors of the central + element. Elements up to a squared distance of `connectivity` from + the center are considered neighbors. `connectivity` may range from 1 + (no diagonal elements are neighbors) to `rank` (all elements are + neighbors). + + Returns + ------- + output : ndarray of bools + Structuring element which may be used for binary morphological + operations, with `rank` dimensions and all dimensions equal to 3. + + See Also + -------- + iterate_structure, binary_dilation, binary_erosion + + Notes + ----- + `generate_binary_structure` can only create structuring elements with + dimensions equal to 3, i.e., minimal dimensions. For larger structuring + elements, that are useful e.g., for eroding large objects, one may either + use `iterate_structure`, or create directly custom arrays with + numpy functions such as `numpy.ones`. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> struct = ndimage.generate_binary_structure(2, 1) + >>> struct + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> a = np.zeros((5,5)) + >>> a[2, 2] = 1 + >>> a + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype) + >>> b + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype) + array([[ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 1., 1., 1., 1., 1.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.]]) + >>> struct = ndimage.generate_binary_structure(2, 2) + >>> struct + array([[ True, True, True], + [ True, True, True], + [ True, True, True]], dtype=bool) + >>> struct = ndimage.generate_binary_structure(3, 1) + >>> struct # no diagonal elements + array([[[False, False, False], + [False, True, False], + [False, False, False]], + [[False, True, False], + [ True, True, True], + [False, True, False]], + [[False, False, False], + [False, True, False], + [False, False, False]]], dtype=bool) + + """ + if connectivity < 1: + connectivity = 1 + if rank < 1: + return np.array(True, dtype=bool) + output = np.fabs(np.indices([3] * rank) - 1) + output = np.add.reduce(output, 0) + return output <= connectivity + + +def _binary_erosion(input, structure, iterations, mask, output, + border_value, origin, invert, brute_force, axes): + try: + iterations = operator.index(iterations) + except TypeError as e: + raise TypeError('iterations parameter should be an integer') from e + + input = np.asarray(input) + ndim = input.ndim + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + else: + structure = np.asarray(structure, dtype=bool) + if ndim > num_axes: + structure = _filters._expand_footprint(ndim, axes, structure, + footprint_name="structure") + + if structure.ndim != input.ndim: + raise RuntimeError('structure and input must have same dimensionality') + if not structure.flags.contiguous: + structure = structure.copy() + if structure.size < 1: + raise RuntimeError('structure must not be empty') + if mask is not None: + mask = np.asarray(mask) + if mask.shape != input.shape: + raise RuntimeError('mask and input must have equal sizes') + origin = _ni_support._normalize_sequence(origin, num_axes) + origin = _filters._expand_origin(ndim, axes, origin) + cit = _center_is_true(structure, origin) + if isinstance(output, np.ndarray): + if np.iscomplexobj(output): + raise TypeError('Complex output type not supported') + else: + output = bool + output = _ni_support._get_output(output, input) + temp_needed = np.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + if iterations == 1: + _nd_image.binary_erosion(input, structure, mask, output, + border_value, origin, invert, cit, 0) + elif cit and not brute_force: + changed, coordinate_list = _nd_image.binary_erosion( + input, structure, mask, output, + border_value, origin, invert, cit, 1) + structure = structure[tuple([slice(None, None, -1)] * + structure.ndim)] + for ii in range(len(origin)): + origin[ii] = -origin[ii] + if not structure.shape[ii] & 1: + origin[ii] -= 1 + if mask is not None: + mask = np.asarray(mask, dtype=np.int8) + if not structure.flags.contiguous: + structure = structure.copy() + _nd_image.binary_erosion2(output, structure, mask, iterations - 1, + origin, invert, coordinate_list) + else: + tmp_in = np.empty_like(input, dtype=bool) + tmp_out = output + if iterations >= 1 and not iterations & 1: + tmp_in, tmp_out = tmp_out, tmp_in + changed = _nd_image.binary_erosion( + input, structure, mask, tmp_out, + border_value, origin, invert, cit, 0) + ii = 1 + while ii < iterations or (iterations < 1 and changed): + tmp_in, tmp_out = tmp_out, tmp_in + changed = _nd_image.binary_erosion( + tmp_in, structure, mask, tmp_out, + border_value, origin, invert, cit, 0) + ii += 1 + if temp_needed: + temp[...] = output + output = temp + return output + + +def binary_erosion(input, structure=None, iterations=1, mask=None, output=None, + border_value=0, origin=0, brute_force=False, *, axes=None): + """ + Multidimensional binary erosion with a given structuring element. + + Binary erosion is a mathematical morphology operation used for image + processing. + + Parameters + ---------- + input : array_like + Binary image to be eroded. Non-zero (True) elements form + the subset to be eroded. + structure : array_like, optional + Structuring element used for the erosion. Non-zero elements are + considered True. If no structuring element is provided, an element + is generated with a square connectivity equal to one. + iterations : int, optional + The erosion is repeated `iterations` times (one, by default). + If iterations is less than 1, the erosion is repeated until the + result does not change anymore. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated (eroded) in + the current iteration; if True all pixels are considered as candidates + for erosion, regardless of what happened in the previous iteration. + False by default. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_erosion : ndarray of bools + Erosion of the input by the structuring element. + + See Also + -------- + grey_erosion, binary_dilation, binary_closing, binary_opening, + generate_binary_structure + + Notes + ----- + Erosion [1]_ is a mathematical morphology operation [2]_ that uses a + structuring element for shrinking the shapes in an image. The binary + erosion of an image by a structuring element is the locus of the points + where a superimposition of the structuring element centered on the point + is entirely contained in the set of non-zero elements of the image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_erosion(a).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> #Erosion removes objects smaller than the structure + >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) + array([[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, 0]]) + + """ + return _binary_erosion(input, structure, iterations, mask, + output, border_value, origin, 0, brute_force, axes) + + +def binary_dilation(input, structure=None, iterations=1, mask=None, + output=None, border_value=0, origin=0, + brute_force=False, *, axes=None): + """ + Multidimensional binary dilation with the given structuring element. + + Parameters + ---------- + input : array_like + Binary array_like to be dilated. Non-zero (True) elements form + the subset to be dilated. + structure : array_like, optional + Structuring element used for the dilation. Non-zero elements are + considered True. If no structuring element is provided an element + is generated with a square connectivity equal to one. + iterations : int, optional + The dilation is repeated `iterations` times (one, by default). + If iterations is less than 1, the dilation is repeated until the + result does not change anymore. Only an integer of iterations is + accepted. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated (dilated) + in the current iteration; if True all pixels are considered as + candidates for dilation, regardless of what happened in the previous + iteration. False by default. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_dilation : ndarray of bools + Dilation of the input by the structuring element. + + See Also + -------- + grey_dilation, binary_erosion, binary_closing, binary_opening, + generate_binary_structure + + Notes + ----- + Dilation [1]_ is a mathematical morphology operation [2]_ that uses a + structuring element for expanding the shapes in an image. The binary + dilation of an image by a structuring element is the locus of the points + covered by the structuring element, when its center lies within the + non-zero points of the image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a) + array([[False, False, False, False, False], + [False, False, True, False, False], + [False, True, True, True, False], + [False, False, True, False, False], + [False, False, False, False, False]], dtype=bool) + >>> ndimage.binary_dilation(a).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> # 3x3 structuring element with connectivity 1, used by default + >>> struct1 = ndimage.generate_binary_structure(2, 1) + >>> struct1 + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> # 3x3 structuring element with connectivity 2 + >>> struct2 = ndimage.generate_binary_structure(2, 2) + >>> struct2 + array([[ True, True, True], + [ True, True, True], + [ True, True, True]], dtype=bool) + >>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a, structure=struct1,\\ + ... iterations=2).astype(a.dtype) + array([[ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 1., 1., 1., 1., 1.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + origin = _ni_support._normalize_sequence(origin, num_axes) + structure = np.asarray(structure) + structure = structure[tuple([slice(None, None, -1)] * + structure.ndim)] + for ii in range(len(origin)): + origin[ii] = -origin[ii] + if not structure.shape[ii] & 1: + origin[ii] -= 1 + + return _binary_erosion(input, structure, iterations, mask, + output, border_value, origin, 1, brute_force, axes) + + +def binary_opening(input, structure=None, iterations=1, output=None, + origin=0, mask=None, border_value=0, brute_force=False, *, + axes=None): + """ + Multidimensional binary opening with the given structuring element. + + The *opening* of an input image by a structuring element is the + *dilation* of the *erosion* of the image by the structuring element. + + Parameters + ---------- + input : array_like + Binary array_like to be opened. Non-zero (True) elements form + the subset to be opened. + structure : array_like, optional + Structuring element used for the opening. Non-zero elements are + considered True. If no structuring element is provided an element + is generated with a square connectivity equal to one (i.e., only + nearest neighbors are connected to the center, diagonally-connected + elements are not considered neighbors). + iterations : int, optional + The erosion step of the opening, then the dilation step are each + repeated `iterations` times (one, by default). If `iterations` is + less than 1, each operation is repeated until the result does + not change anymore. Only an integer of iterations is accepted. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + + .. versionadded:: 1.1.0 + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + + .. versionadded:: 1.1.0 + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated in the + current iteration; if true all pixels are considered as candidates for + update, regardless of what happened in the previous iteration. + False by default. + + .. versionadded:: 1.1.0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_opening : ndarray of bools + Opening of the input by the structuring element. + + See Also + -------- + grey_opening, binary_closing, binary_erosion, binary_dilation, + generate_binary_structure + + Notes + ----- + *Opening* [1]_ is a mathematical morphology operation [2]_ that + consists in the succession of an erosion and a dilation of the + input with the same structuring element. Opening, therefore, removes + objects smaller than the structuring element. + + Together with *closing* (`binary_closing`), opening can be used for + noise removal. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Opening_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5,5), dtype=int) + >>> a[1:4, 1:4] = 1; a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> # Opening removes small objects + >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening can also smooth corners + >>> ndimage.binary_opening(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening is the dilation of the erosion of the input + >>> ndimage.binary_erosion(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]) + >>> ndimage.binary_dilation(ndimage.binary_erosion(a)).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + + tmp = binary_erosion(input, structure, iterations, mask, None, + border_value, origin, brute_force, axes=axes) + return binary_dilation(tmp, structure, iterations, mask, output, + border_value, origin, brute_force, axes=axes) + + +def binary_closing(input, structure=None, iterations=1, output=None, + origin=0, mask=None, border_value=0, brute_force=False, *, + axes=None): + """ + Multidimensional binary closing with the given structuring element. + + The *closing* of an input image by a structuring element is the + *erosion* of the *dilation* of the image by the structuring element. + + Parameters + ---------- + input : array_like + Binary array_like to be closed. Non-zero (True) elements form + the subset to be closed. + structure : array_like, optional + Structuring element used for the closing. Non-zero elements are + considered True. If no structuring element is provided an element + is generated with a square connectivity equal to one (i.e., only + nearest neighbors are connected to the center, diagonally-connected + elements are not considered neighbors). + iterations : int, optional + The dilation step of the closing, then the erosion step are each + repeated `iterations` times (one, by default). If iterations is + less than 1, each operations is repeated until the result does + not change anymore. Only an integer of iterations is accepted. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + + .. versionadded:: 1.1.0 + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + + .. versionadded:: 1.1.0 + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated in the + current iteration; if true al pixels are considered as candidates for + update, regardless of what happened in the previous iteration. + False by default. + + .. versionadded:: 1.1.0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_closing : ndarray of bools + Closing of the input by the structuring element. + + See Also + -------- + grey_closing, binary_opening, binary_dilation, binary_erosion, + generate_binary_structure + + Notes + ----- + *Closing* [1]_ is a mathematical morphology operation [2]_ that + consists in the succession of a dilation and an erosion of the + input with the same structuring element. Closing therefore fills + holes smaller than the structuring element. + + Together with *opening* (`binary_opening`), closing can be used for + noise removal. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5,5), dtype=int) + >>> a[1:-1, 1:-1] = 1; a[2,2] = 0 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Closing removes small holes + >>> ndimage.binary_closing(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Closing is the erosion of the dilation of the input + >>> ndimage.binary_dilation(a).astype(int) + array([[0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0]]) + >>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + + + >>> a = np.zeros((7,7), dtype=int) + >>> a[1:6, 2:5] = 1; a[1:3,3] = 0 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # In addition to removing holes, closing can also + >>> # coarsen boundaries with fine hollows. + >>> ndimage.binary_closing(a).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + + tmp = binary_dilation(input, structure, iterations, mask, None, + border_value, origin, brute_force, axes=axes) + return binary_erosion(tmp, structure, iterations, mask, output, + border_value, origin, brute_force, axes=axes) + + +def binary_hit_or_miss(input, structure1=None, structure2=None, + output=None, origin1=0, origin2=None, *, axes=None): + """ + Multidimensional binary hit-or-miss transform. + + The hit-or-miss transform finds the locations of a given pattern + inside the input image. + + Parameters + ---------- + input : array_like (cast to booleans) + Binary image where a pattern is to be detected. + structure1 : array_like (cast to booleans), optional + Part of the structuring element to be fitted to the foreground + (non-zero elements) of `input`. If no value is provided, a + structure of square connectivity 1 is chosen. + structure2 : array_like (cast to booleans), optional + Second part of the structuring element that has to miss completely + the foreground. If no value is provided, the complementary of + `structure1` is taken. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin1 : int or tuple of ints, optional + Placement of the first part of the structuring element `structure1`, + by default 0 for a centered structure. + origin2 : int or tuple of ints, optional + Placement of the second part of the structuring element `structure2`, + by default 0 for a centered structure. If a value is provided for + `origin1` and not for `origin2`, then `origin2` is set to `origin1`. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If `origin1` or `origin2` tuples are provided, their + length must match the number of axes. + + Returns + ------- + binary_hit_or_miss : ndarray + Hit-or-miss transform of `input` with the given structuring + element (`structure1`, `structure2`). + + See Also + -------- + binary_erosion + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Hit-or-miss_transform + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[1, 1] = 1; a[2:4, 2:4] = 1; a[4:6, 4:6] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> structure1 = np.array([[1, 0, 0], [0, 1, 1], [0, 1, 1]]) + >>> structure1 + array([[1, 0, 0], + [0, 1, 1], + [0, 1, 1]]) + >>> # Find the matches of structure1 in the array a + >>> ndimage.binary_hit_or_miss(a, structure1=structure1).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # Change the origin of the filter + >>> # origin1=1 is equivalent to origin1=(1,1) here + >>> ndimage.binary_hit_or_miss(a, structure1=structure1,\\ + ... origin1=1).astype(int) + array([[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, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure1 is None: + structure1 = generate_binary_structure(num_axes, 1) + else: + structure1 = np.asarray(structure1) + if structure2 is None: + structure2 = np.logical_not(structure1) + origin1 = _ni_support._normalize_sequence(origin1, num_axes) + if origin2 is None: + origin2 = origin1 + else: + origin2 = _ni_support._normalize_sequence(origin2, num_axes) + + tmp1 = _binary_erosion(input, structure1, 1, None, None, 0, origin1, + 0, False, axes) + inplace = isinstance(output, np.ndarray) + result = _binary_erosion(input, structure2, 1, None, output, 0, + origin2, 1, False, axes) + if inplace: + np.logical_not(output, output) + np.logical_and(tmp1, output, output) + else: + np.logical_not(result, result) + return np.logical_and(tmp1, result) + + +def binary_propagation(input, structure=None, mask=None, + output=None, border_value=0, origin=0, *, axes=None): + """ + Multidimensional binary propagation with the given structuring element. + + Parameters + ---------- + input : array_like + Binary image to be propagated inside `mask`. + structure : array_like, optional + Structuring element used in the successive dilations. The output + may depend on the structuring element, especially if `mask` has + several connex components. If no structuring element is + provided, an element is generated with a squared connectivity equal + to one. + mask : array_like, optional + Binary mask defining the region into which `input` is allowed to + propagate. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_propagation : ndarray + Binary propagation of `input` inside `mask`. + + Notes + ----- + This function is functionally equivalent to calling binary_dilation + with the number of iterations less than one: iterative dilation until + the result does not change anymore. + + The succession of an erosion and propagation inside the original image + can be used instead of an *opening* for deleting small objects while + keeping the contours of larger objects untouched. + + References + ---------- + .. [1] http://cmm.ensmp.fr/~serra/cours/pdf/en/ch6en.pdf, slide 15. + .. [2] I.T. Young, J.J. Gerbrands, and L.J. van Vliet, "Fundamentals of + image processing", 1998 + ftp://qiftp.tudelft.nl/DIPimage/docs/FIP2.3.pdf + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> input = np.zeros((8, 8), dtype=int) + >>> input[2, 2] = 1 + >>> mask = np.zeros((8, 8), dtype=int) + >>> mask[1:4, 1:4] = mask[4, 4] = mask[6:8, 6:8] = 1 + >>> input + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 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]]) + >>> mask + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0, 1, 1]]) + >>> ndimage.binary_propagation(input, mask=mask).astype(int) + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 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]]) + >>> ndimage.binary_propagation(input, mask=mask,\\ + ... structure=np.ones((3,3))).astype(int) + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 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]]) + + >>> # Comparison between opening and erosion+propagation + >>> a = np.zeros((6,6), dtype=int) + >>> a[2:5, 2:5] = 1; a[0, 0] = 1; a[5, 5] = 1 + >>> a + array([[1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1]]) + >>> ndimage.binary_opening(a).astype(int) + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0]]) + >>> b = ndimage.binary_erosion(a) + >>> b.astype(int) + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_propagation(b, mask=a).astype(int) + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0]]) + + """ + return binary_dilation(input, structure, -1, mask, output, + border_value, origin, axes=axes) + + +def binary_fill_holes(input, structure=None, output=None, origin=0, *, + axes=None): + """ + Fill the holes in binary objects. + + + Parameters + ---------- + input : array_like + N-D binary array with holes to be filled + structure : array_like, optional + Structuring element used in the computation; large-size elements + make computations faster but may miss holes separated from the + background by thin regions. The default element (with a square + connectivity equal to one) yields the intuitive result where all + holes in the input have been filled. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin : int, tuple of ints, optional + Position of the structuring element. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + out : ndarray + Transformation of the initial image `input` where holes have been + filled. + + See Also + -------- + binary_dilation, binary_propagation, label + + Notes + ----- + The algorithm used in this function consists in invading the complementary + of the shapes in `input` from the outer boundary of the image, + using binary dilations. Holes are not connected to the boundary and are + therefore not invaded. The result is the complementary subset of the + invaded region. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5, 5), dtype=int) + >>> a[1:4, 1:4] = 1 + >>> a[2,2] = 0 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> ndimage.binary_fill_holes(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Too big structuring element + >>> ndimage.binary_fill_holes(a, structure=np.ones((5,5))).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + mask = np.logical_not(input) + tmp = np.zeros(mask.shape, bool) + inplace = isinstance(output, np.ndarray) + if inplace: + binary_dilation(tmp, structure, -1, mask, output, 1, origin, axes=axes) + np.logical_not(output, output) + else: + output = binary_dilation(tmp, structure, -1, mask, None, 1, + origin, axes=axes) + np.logical_not(output, output) + return output + + +def grey_erosion(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Calculate a greyscale erosion, using either a structuring element, + or a footprint corresponding to a flat structuring element. + + Grayscale erosion is a mathematical morphology operation. For the + simple case of a full and flat structuring element, it can be viewed + as a minimum filter over a sliding window. + + Parameters + ---------- + input : array_like + Array over which the grayscale erosion is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + erosion. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale erosion. Non-zero values give the set of + neighbors of the center over which the minimum is chosen. + structure : array of ints, optional + Structuring element used for the grayscale erosion. `structure` + may be a non-flat structuring element. The `structure` array applies a + subtractive offset for each pixel in the neighborhood. + output : array, optional + An array used for storing the output of the erosion may be provided. + mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + output : ndarray + Grayscale erosion of `input`. + + See Also + -------- + binary_erosion, grey_dilation, grey_opening, grey_closing + generate_binary_structure, minimum_filter + + Notes + ----- + The grayscale erosion of an image input by a structuring element s defined + over a domain E is given by: + + (input+s)(x) = min {input(y) - s(x-y), for y in E} + + In particular, for structuring elements defined as + s(y) = 0 for y in E, the grayscale erosion computes the minimum of the + input image inside a sliding window defined by E. + + Grayscale erosion [1]_ is a *mathematical morphology* operation [2]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[1:6, 1:6] = 3 + >>> a[4,4] = 2; a[2,3] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 1, 3, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 3, 2, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_erosion(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 3, 2, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> footprint = ndimage.generate_binary_structure(2, 1) + >>> footprint + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> # Diagonally-connected elements are not considered neighbors + >>> ndimage.grey_erosion(a, footprint=footprint) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 3, 1, 2, 0, 0], + [0, 0, 3, 2, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + if size is None and footprint is None and structure is None: + raise ValueError("size, footprint, or structure must be specified") + + return _filters._min_or_max_filter(input, size, footprint, structure, + output, mode, cval, origin, 1, + axes=axes) + + +def grey_dilation(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Calculate a greyscale dilation, using either a structuring element, + or a footprint corresponding to a flat structuring element. + + Grayscale dilation is a mathematical morphology operation. For the + simple case of a full and flat structuring element, it can be viewed + as a maximum filter over a sliding window. + + Parameters + ---------- + input : array_like + Array over which the grayscale dilation is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + dilation. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale dilation. Non-zero values give the set of + neighbors of the center over which the maximum is chosen. + structure : array of ints, optional + Structuring element used for the grayscale dilation. `structure` + may be a non-flat structuring element. The `structure` array applies an + additive offset for each pixel in the neighborhood. + output : array, optional + An array used for storing the output of the dilation may be provided. + mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + grey_dilation : ndarray + Grayscale dilation of `input`. + + See Also + -------- + binary_dilation, grey_erosion, grey_closing, grey_opening + generate_binary_structure, maximum_filter + + Notes + ----- + The grayscale dilation of an image input by a structuring element s defined + over a domain E is given by: + + (input+s)(x) = max {input(y) + s(x-y), for y in E} + + In particular, for structuring elements defined as + s(y) = 0 for y in E, the grayscale dilation computes the maximum of the + input image inside a sliding window defined by E. + + Grayscale dilation [1]_ is a *mathematical morphology* operation [2]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[2:5, 2:5] = 1 + >>> a[4,4] = 2; a[2,3] = 3 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 3, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_dilation(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_dilation(a, footprint=np.ones((3,3))) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> s = ndimage.generate_binary_structure(2,1) + >>> s + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> ndimage.grey_dilation(a, footprint=s) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 3, 1, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 1, 3, 2, 1, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 1, 1, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_dilation(a, size=(3,3), structure=np.ones((3,3))) + array([[1, 1, 1, 1, 1, 1, 1], + [1, 2, 4, 4, 4, 2, 1], + [1, 2, 4, 4, 4, 2, 1], + [1, 2, 4, 4, 4, 3, 1], + [1, 2, 2, 3, 3, 3, 1], + [1, 2, 2, 3, 3, 3, 1], + [1, 1, 1, 1, 1, 1, 1]]) + + """ + if size is None and footprint is None and structure is None: + raise ValueError("size, footprint, or structure must be specified") + if structure is not None: + structure = np.asarray(structure) + structure = structure[tuple([slice(None, None, -1)] * + structure.ndim)] + if footprint is not None: + footprint = np.asarray(footprint) + footprint = footprint[tuple([slice(None, None, -1)] * + footprint.ndim)] + + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + origin = _ni_support._normalize_sequence(origin, len(axes)) + for ii in range(len(origin)): + origin[ii] = -origin[ii] + if footprint is not None: + sz = footprint.shape[ii] + elif structure is not None: + sz = structure.shape[ii] + elif np.isscalar(size): + sz = size + else: + sz = size[ii] + if not sz & 1: + origin[ii] -= 1 + + return _filters._min_or_max_filter(input, size, footprint, structure, + output, mode, cval, origin, 0, + axes=axes) + + +def grey_opening(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional grayscale opening. + + A grayscale opening consists in the succession of a grayscale erosion, + and a grayscale dilation. + + Parameters + ---------- + input : array_like + Array over which the grayscale opening is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + opening. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale opening. + structure : array of ints, optional + Structuring element used for the grayscale opening. `structure` + may be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion). + output : array, optional + An array used for storing the output of the opening may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + grey_opening : ndarray + Result of the grayscale opening of `input` with `structure`. + + See Also + -------- + binary_opening, grey_dilation, grey_erosion, grey_closing + generate_binary_structure + + Notes + ----- + The action of a grayscale opening with a flat structuring element amounts + to smoothen high local maxima, whereas binary opening erases small objects. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(36).reshape((6,6)) + >>> a[3, 3] = 50 + >>> a + array([[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 17], + [18, 19, 20, 50, 22, 23], + [24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35]]) + >>> ndimage.grey_opening(a, size=(3,3)) + array([[ 0, 1, 2, 3, 4, 4], + [ 6, 7, 8, 9, 10, 10], + [12, 13, 14, 15, 16, 16], + [18, 19, 20, 22, 22, 22], + [24, 25, 26, 27, 28, 28], + [24, 25, 26, 27, 28, 28]]) + >>> # Note that the local maximum a[3,3] has disappeared + + """ + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_erosion(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + return grey_dilation(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + + +def grey_closing(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional grayscale closing. + + A grayscale closing consists in the succession of a grayscale dilation, + and a grayscale erosion. + + Parameters + ---------- + input : array_like + Array over which the grayscale closing is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + closing. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale closing. + structure : array of ints, optional + Structuring element used for the grayscale closing. `structure` + may be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion) + output : array, optional + An array used for storing the output of the closing may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + grey_closing : ndarray + Result of the grayscale closing of `input` with `structure`. + + See Also + -------- + binary_closing, grey_dilation, grey_erosion, grey_opening, + generate_binary_structure + + Notes + ----- + The action of a grayscale closing with a flat structuring element amounts + to smoothen deep local minima, whereas binary closing fills small holes. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(36).reshape((6,6)) + >>> a[3,3] = 0 + >>> a + array([[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 17], + [18, 19, 20, 0, 22, 23], + [24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35]]) + >>> ndimage.grey_closing(a, size=(3,3)) + array([[ 7, 7, 8, 9, 10, 11], + [ 7, 7, 8, 9, 10, 11], + [13, 13, 14, 15, 16, 17], + [19, 19, 20, 20, 22, 23], + [25, 25, 26, 27, 28, 29], + [31, 31, 32, 33, 34, 35]]) + >>> # Note that the local minimum a[3,3] has disappeared + + """ + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + return grey_erosion(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + + +def morphological_gradient(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional morphological gradient. + + The morphological gradient is calculated as the difference between a + dilation and an erosion of the input with a given structuring element. + + Parameters + ---------- + input : array_like + Array over which to compute the morphlogical gradient. + size : tuple of ints + Shape of a flat and full structuring element used for the mathematical + morphology operations. Optional if `footprint` or `structure` is + provided. A larger `size` yields a more blurred gradient. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the morphology operations. Larger footprints + give a more blurred morphological gradient. + structure : array of ints, optional + Structuring element used for the morphology operations. `structure` may + be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion) + output : array, optional + An array used for storing the output of the morphological gradient + may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + morphological_gradient : ndarray + Morphological gradient of `input`. + + See Also + -------- + grey_dilation, grey_erosion, gaussian_gradient_magnitude + + Notes + ----- + For a flat structuring element, the morphological gradient + computed at a given point corresponds to the maximal difference + between elements of the input among the elements covered by the + structuring element centered on the point. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[2:5, 2:5] = 1 + >>> ndimage.morphological_gradient(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # The morphological gradient is computed as the difference + >>> # between a dilation and an erosion + >>> ndimage.grey_dilation(a, size=(3,3)) -\\ + ... ndimage.grey_erosion(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> a = np.zeros((7,7), dtype=int) + >>> a[2:5, 2:5] = 1 + >>> a[4,4] = 2; a[2,3] = 3 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 3, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.morphological_gradient(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 2, 3, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + tmp = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + if isinstance(output, np.ndarray): + grey_erosion(input, size, footprint, structure, output, mode, + cval, origin, axes=axes) + return np.subtract(tmp, output, output) + else: + return (tmp - grey_erosion(input, size, footprint, structure, + None, mode, cval, origin, axes=axes)) + + +def morphological_laplace(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional morphological laplace. + + Parameters + ---------- + input : array_like + Input. + size : tuple of ints + Shape of a flat and full structuring element used for the mathematical + morphology operations. Optional if `footprint` or `structure` is + provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the morphology operations. + structure : array of ints, optional + Structuring element used for the morphology operations. `structure` may + be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion) + output : ndarray, optional + An output array can optionally be provided. + mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional + The mode parameter determines how the array borders are handled. + For 'constant' mode, values beyond borders are set to be `cval`. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if mode is 'constant'. + Default is 0.0 + origin : origin, optional + The origin parameter controls the placement of the filter. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + morphological_laplace : ndarray + Output + + """ + tmp1 = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + if isinstance(output, np.ndarray): + grey_erosion(input, size, footprint, structure, output, mode, + cval, origin, axes=axes) + np.add(tmp1, output, output) + np.subtract(output, input, output) + return np.subtract(output, input, output) + else: + tmp2 = grey_erosion(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + np.add(tmp1, tmp2, tmp2) + np.subtract(tmp2, input, tmp2) + np.subtract(tmp2, input, tmp2) + return tmp2 + + +def white_tophat(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional white tophat filter. + + Parameters + ---------- + input : array_like + Input. + size : tuple of ints + Shape of a flat and full structuring element used for the filter. + Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of elements of a flat structuring element + used for the white tophat filter. + structure : array of ints, optional + Structuring element used for the filter. `structure` may be a non-flat + structuring element. The `structure` array applies offsets to the + pixels in a neighborhood (the offset is additive during dilation and + subtractive during erosion) + output : array, optional + An array used for storing the output of the filter may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. + Default is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default is 0. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + output : ndarray + Result of the filter of `input` with `structure`. + + See Also + -------- + black_tophat + + Examples + -------- + Subtract gray background from a bright peak. + + >>> from scipy.ndimage import generate_binary_structure, white_tophat + >>> import numpy as np + >>> square = generate_binary_structure(rank=2, connectivity=3) + >>> bright_on_gray = np.array([[2, 3, 3, 3, 2], + ... [3, 4, 5, 4, 3], + ... [3, 5, 9, 5, 3], + ... [3, 4, 5, 4, 3], + ... [2, 3, 3, 3, 2]]) + >>> white_tophat(input=bright_on_gray, structure=square) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 5, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_erosion(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + tmp = grey_dilation(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + if tmp is None: + tmp = output + + if input.dtype == np.bool_ and tmp.dtype == np.bool_: + np.bitwise_xor(input, tmp, out=tmp) + else: + np.subtract(input, tmp, out=tmp) + return tmp + + +def black_tophat(input, size=None, footprint=None, structure=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """ + Multidimensional black tophat filter. + + Parameters + ---------- + input : array_like + Input. + size : tuple of ints, optional + Shape of a flat and full structuring element used for the filter. + Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the black tophat filter. + structure : array of ints, optional + Structuring element used for the filter. `structure` may be a non-flat + structuring element. The `structure` array applies offsets to the + pixels in a neighborhood (the offset is additive during dilation and + subtractive during erosion) + output : array, optional + An array used for storing the output of the filter may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + black_tophat : ndarray + Result of the filter of `input` with `structure`. + + See Also + -------- + white_tophat, grey_opening, grey_closing + + Examples + -------- + Change dark peak to bright peak and subtract background. + + >>> from scipy.ndimage import generate_binary_structure, black_tophat + >>> import numpy as np + >>> square = generate_binary_structure(rank=2, connectivity=3) + >>> dark_on_gray = np.array([[7, 6, 6, 6, 7], + ... [6, 5, 4, 5, 6], + ... [6, 4, 0, 4, 6], + ... [6, 5, 4, 5, 6], + ... [7, 6, 6, 6, 7]]) + >>> black_tophat(input=dark_on_gray, structure=square) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 5, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + tmp = grey_erosion(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + if tmp is None: + tmp = output + + if input.dtype == np.bool_ and tmp.dtype == np.bool_: + np.bitwise_xor(tmp, input, out=tmp) + else: + np.subtract(tmp, input, out=tmp) + return tmp + + +def distance_transform_bf(input, metric="euclidean", sampling=None, + return_distances=True, return_indices=False, + distances=None, indices=None): + """ + Distance transform function by a brute force algorithm. + + This function calculates the distance transform of the `input`, by + replacing each foreground (non-zero) element, with its + shortest distance to the background (any zero-valued element). + + In addition to the distance transform, the feature transform can + be calculated. In this case the index of the closest background + element to each foreground element is returned in a separate array. + + Parameters + ---------- + input : array_like + Input + metric : {'euclidean', 'taxicab', 'chessboard'}, optional + 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'. + The default is 'euclidean'. + sampling : float, or sequence of float, optional + This parameter is only used when `metric` is 'euclidean'. + Spacing of elements along each dimension. If a sequence, must be of + length equal to the input rank; if a single number, this is used for + all axes. If not specified, a grid spacing of unity is implied. + return_distances : bool, optional + Whether to calculate the distance transform. + Default is True. + return_indices : bool, optional + Whether to calculate the feature transform. + Default is False. + distances : ndarray, optional + An output array to store the calculated distance transform, instead of + returning it. + `return_distances` must be True. + It must be the same shape as `input`, and of type float64 if `metric` + is 'euclidean', uint32 otherwise. + indices : int32 ndarray, optional + An output array to store the calculated feature transform, instead of + returning it. + `return_indicies` must be True. + Its shape must be ``(input.ndim,) + input.shape``. + + Returns + ------- + distances : ndarray, optional + The calculated distance transform. Returned only when + `return_distances` is True and `distances` is not supplied. + It will have the same shape as the input array. + indices : int32 ndarray, optional + The calculated feature transform. It has an input-shaped array for each + dimension of the input. See distance_transform_edt documentation for an + example. + Returned only when `return_indices` is True and `indices` is not + supplied. + + See Also + -------- + distance_transform_cdt : Faster distance transform for taxicab and + chessboard metrics + distance_transform_edt : Faster distance transform for euclidean metric + + Notes + ----- + This function employs a slow brute force algorithm. See also the + function `distance_transform_cdt` for more efficient taxicab [1]_ and + chessboard algorithms [2]_. + + References + ---------- + .. [1] Taxicab distance. Wikipedia, 2023. + https://en.wikipedia.org/wiki/Taxicab_geometry + .. [2] Chessboard distance. Wikipedia, 2023. + https://en.wikipedia.org/wiki/Chebyshev_distance + + Examples + -------- + Import the necessary modules. + + >>> import numpy as np + >>> from scipy.ndimage import distance_transform_bf + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1 import ImageGrid + + First, we create a toy binary image. + + >>> def add_circle(center_x, center_y, radius, image, fillvalue=1): + ... # fill circular area with 1 + ... xx, yy = np.mgrid[:image.shape[0], :image.shape[1]] + ... circle = (xx - center_x) ** 2 + (yy - center_y) ** 2 + ... circle_shape = np.sqrt(circle) < radius + ... image[circle_shape] = fillvalue + ... return image + >>> image = np.zeros((100, 100), dtype=np.uint8) + >>> image[35:65, 20:80] = 1 + >>> image = add_circle(28, 65, 10, image) + >>> image = add_circle(37, 30, 10, image) + >>> image = add_circle(70, 45, 20, image) + >>> image = add_circle(45, 80, 10, image) + + Next, we set up the figure. + + >>> fig = plt.figure(figsize=(8, 8)) # set up the figure structure + >>> grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=(0.4, 0.3), + ... label_mode="1", share_all=True, + ... cbar_location="right", cbar_mode="each", + ... cbar_size="7%", cbar_pad="2%") + >>> for ax in grid: + ... ax.axis('off') # remove axes from images + + The top left image is the original binary image. + + >>> binary_image = grid[0].imshow(image, cmap='gray') + >>> cbar_binary_image = grid.cbar_axes[0].colorbar(binary_image) + >>> cbar_binary_image.set_ticks([0, 1]) + >>> grid[0].set_title("Binary image: foreground in white") + + The distance transform calculates the distance between foreground pixels + and the image background according to a distance metric. Available metrics + in `distance_transform_bf` are: ``euclidean`` (default), ``taxicab`` + and ``chessboard``. The top right image contains the distance transform + based on the ``euclidean`` metric. + + >>> distance_transform_euclidean = distance_transform_bf(image) + >>> euclidean_transform = grid[1].imshow(distance_transform_euclidean, + ... cmap='gray') + >>> cbar_euclidean = grid.cbar_axes[1].colorbar(euclidean_transform) + >>> colorbar_ticks = [0, 10, 20] + >>> cbar_euclidean.set_ticks(colorbar_ticks) + >>> grid[1].set_title("Euclidean distance") + + The lower left image contains the distance transform using the ``taxicab`` + metric. + + >>> distance_transform_taxicab = distance_transform_bf(image, + ... metric='taxicab') + >>> taxicab_transformation = grid[2].imshow(distance_transform_taxicab, + ... cmap='gray') + >>> cbar_taxicab = grid.cbar_axes[2].colorbar(taxicab_transformation) + >>> cbar_taxicab.set_ticks(colorbar_ticks) + >>> grid[2].set_title("Taxicab distance") + + Finally, the lower right image contains the distance transform using the + ``chessboard`` metric. + + >>> distance_transform_cb = distance_transform_bf(image, + ... metric='chessboard') + >>> chessboard_transformation = grid[3].imshow(distance_transform_cb, + ... cmap='gray') + >>> cbar_taxicab = grid.cbar_axes[3].colorbar(chessboard_transformation) + >>> cbar_taxicab.set_ticks(colorbar_ticks) + >>> grid[3].set_title("Chessboard distance") + >>> plt.show() + + """ + ft_inplace = isinstance(indices, np.ndarray) + dt_inplace = isinstance(distances, np.ndarray) + _distance_tranform_arg_check( + dt_inplace, ft_inplace, return_distances, return_indices + ) + + tmp1 = np.asarray(input) != 0 + struct = generate_binary_structure(tmp1.ndim, tmp1.ndim) + tmp2 = binary_dilation(tmp1, struct) + tmp2 = np.logical_xor(tmp1, tmp2) + tmp1 = tmp1.astype(np.int8) - tmp2.astype(np.int8) + metric = metric.lower() + if metric == 'euclidean': + metric = 1 + elif metric in ['taxicab', 'cityblock', 'manhattan']: + metric = 2 + elif metric == 'chessboard': + metric = 3 + else: + raise RuntimeError('distance metric not supported') + if sampling is not None: + sampling = _ni_support._normalize_sequence(sampling, tmp1.ndim) + sampling = np.asarray(sampling, dtype=np.float64) + if not sampling.flags.contiguous: + sampling = sampling.copy() + if return_indices: + ft = np.zeros(tmp1.shape, dtype=np.int32) + else: + ft = None + if return_distances: + if distances is None: + if metric == 1: + dt = np.zeros(tmp1.shape, dtype=np.float64) + else: + dt = np.zeros(tmp1.shape, dtype=np.uint32) + else: + if distances.shape != tmp1.shape: + raise RuntimeError('distances array has wrong shape') + if metric == 1: + if distances.dtype.type != np.float64: + raise RuntimeError('distances array must be float64') + else: + if distances.dtype.type != np.uint32: + raise RuntimeError('distances array must be uint32') + dt = distances + else: + dt = None + + _nd_image.distance_transform_bf(tmp1, metric, sampling, dt, ft) + if return_indices: + if isinstance(indices, np.ndarray): + if indices.dtype.type != np.int32: + raise RuntimeError('indices array must be int32') + if indices.shape != (tmp1.ndim,) + tmp1.shape: + raise RuntimeError('indices array has wrong shape') + tmp2 = indices + else: + tmp2 = np.indices(tmp1.shape, dtype=np.int32) + ft = np.ravel(ft) + for ii in range(tmp2.shape[0]): + rtmp = np.ravel(tmp2[ii, ...])[ft] + rtmp.shape = tmp1.shape + tmp2[ii, ...] = rtmp + ft = tmp2 + + # construct and return the result + result = [] + if return_distances and not dt_inplace: + result.append(dt) + if return_indices and not ft_inplace: + result.append(ft) + + if len(result) == 2: + return tuple(result) + elif len(result) == 1: + return result[0] + else: + return None + + +def distance_transform_cdt(input, metric='chessboard', return_distances=True, + return_indices=False, distances=None, indices=None): + """ + Distance transform for chamfer type of transforms. + + This function calculates the distance transform of the `input`, by + replacing each foreground (non-zero) element, with its + shortest distance to the background (any zero-valued element). + + In addition to the distance transform, the feature transform can + be calculated. In this case the index of the closest background + element to each foreground element is returned in a separate array. + + Parameters + ---------- + input : array_like + Input. Values of 0 are treated as background. + metric : {'chessboard', 'taxicab'} or array_like, optional + The `metric` determines the type of chamfering that is done. If the + `metric` is equal to 'taxicab' a structure is generated using + `generate_binary_structure` with a squared distance equal to 1. If + the `metric` is equal to 'chessboard', a `metric` is generated + using `generate_binary_structure` with a squared distance equal to + the dimensionality of the array. These choices correspond to the + common interpretations of the 'taxicab' and the 'chessboard' + distance metrics in two dimensions. + A custom metric may be provided, in the form of a matrix where + each dimension has a length of three. + 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'. + The default is 'chessboard'. + return_distances : bool, optional + Whether to calculate the distance transform. + Default is True. + return_indices : bool, optional + Whether to calculate the feature transform. + Default is False. + distances : int32 ndarray, optional + An output array to store the calculated distance transform, instead of + returning it. + `return_distances` must be True. + It must be the same shape as `input`. + indices : int32 ndarray, optional + An output array to store the calculated feature transform, instead of + returning it. + `return_indicies` must be True. + Its shape must be ``(input.ndim,) + input.shape``. + + Returns + ------- + distances : int32 ndarray, optional + The calculated distance transform. Returned only when + `return_distances` is True, and `distances` is not supplied. + It will have the same shape as the input array. + indices : int32 ndarray, optional + The calculated feature transform. It has an input-shaped array for each + dimension of the input. See distance_transform_edt documentation for an + example. + Returned only when `return_indices` is True, and `indices` is not + supplied. + + See Also + -------- + distance_transform_edt : Fast distance transform for euclidean metric + distance_transform_bf : Distance transform for different metrics using + a slower brute force algorithm + + Examples + -------- + Import the necessary modules. + + >>> import numpy as np + >>> from scipy.ndimage import distance_transform_cdt + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1 import ImageGrid + + First, we create a toy binary image. + + >>> def add_circle(center_x, center_y, radius, image, fillvalue=1): + ... # fill circular area with 1 + ... xx, yy = np.mgrid[:image.shape[0], :image.shape[1]] + ... circle = (xx - center_x) ** 2 + (yy - center_y) ** 2 + ... circle_shape = np.sqrt(circle) < radius + ... image[circle_shape] = fillvalue + ... return image + >>> image = np.zeros((100, 100), dtype=np.uint8) + >>> image[35:65, 20:80] = 1 + >>> image = add_circle(28, 65, 10, image) + >>> image = add_circle(37, 30, 10, image) + >>> image = add_circle(70, 45, 20, image) + >>> image = add_circle(45, 80, 10, image) + + Next, we set up the figure. + + >>> fig = plt.figure(figsize=(5, 15)) + >>> grid = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=(0.5, 0.3), + ... label_mode="1", share_all=True, + ... cbar_location="right", cbar_mode="each", + ... cbar_size="7%", cbar_pad="2%") + >>> for ax in grid: + ... ax.axis('off') + >>> top, middle, bottom = grid + >>> colorbar_ticks = [0, 10, 20] + + The top image contains the original binary image. + + >>> binary_image = top.imshow(image, cmap='gray') + >>> cbar_binary_image = top.cax.colorbar(binary_image) + >>> cbar_binary_image.set_ticks([0, 1]) + >>> top.set_title("Binary image: foreground in white") + + The middle image contains the distance transform using the ``taxicab`` + metric. + + >>> distance_taxicab = distance_transform_cdt(image, metric="taxicab") + >>> taxicab_transform = middle.imshow(distance_taxicab, cmap='gray') + >>> cbar_taxicab = middle.cax.colorbar(taxicab_transform) + >>> cbar_taxicab.set_ticks(colorbar_ticks) + >>> middle.set_title("Taxicab metric") + + The bottom image contains the distance transform using the ``chessboard`` + metric. + + >>> distance_chessboard = distance_transform_cdt(image, + ... metric="chessboard") + >>> chessboard_transform = bottom.imshow(distance_chessboard, cmap='gray') + >>> cbar_chessboard = bottom.cax.colorbar(chessboard_transform) + >>> cbar_chessboard.set_ticks(colorbar_ticks) + >>> bottom.set_title("Chessboard metric") + >>> plt.tight_layout() + >>> plt.show() + + """ + ft_inplace = isinstance(indices, np.ndarray) + dt_inplace = isinstance(distances, np.ndarray) + _distance_tranform_arg_check( + dt_inplace, ft_inplace, return_distances, return_indices + ) + input = np.asarray(input) + if isinstance(metric, str): + if metric in ['taxicab', 'cityblock', 'manhattan']: + rank = input.ndim + metric = generate_binary_structure(rank, 1) + elif metric == 'chessboard': + rank = input.ndim + metric = generate_binary_structure(rank, rank) + else: + raise ValueError('invalid metric provided') + else: + try: + metric = np.asarray(metric) + except Exception as e: + raise ValueError('invalid metric provided') from e + for s in metric.shape: + if s != 3: + raise ValueError('metric sizes must be equal to 3') + + if not metric.flags.contiguous: + metric = metric.copy() + if dt_inplace: + if distances.dtype.type != np.int32: + raise ValueError('distances must be of int32 type') + if distances.shape != input.shape: + raise ValueError('distances has wrong shape') + dt = distances + dt[...] = np.where(input, -1, 0).astype(np.int32) + else: + dt = np.where(input, -1, 0).astype(np.int32) + + rank = dt.ndim + if return_indices: + ft = np.arange(dt.size, dtype=np.int32) + ft.shape = dt.shape + else: + ft = None + + _nd_image.distance_transform_op(metric, dt, ft) + dt = dt[tuple([slice(None, None, -1)] * rank)] + if return_indices: + ft = ft[tuple([slice(None, None, -1)] * rank)] + _nd_image.distance_transform_op(metric, dt, ft) + dt = dt[tuple([slice(None, None, -1)] * rank)] + if return_indices: + ft = ft[tuple([slice(None, None, -1)] * rank)] + ft = np.ravel(ft) + if ft_inplace: + if indices.dtype.type != np.int32: + raise ValueError('indices array must be int32') + if indices.shape != (dt.ndim,) + dt.shape: + raise ValueError('indices array has wrong shape') + tmp = indices + else: + tmp = np.indices(dt.shape, dtype=np.int32) + for ii in range(tmp.shape[0]): + rtmp = np.ravel(tmp[ii, ...])[ft] + rtmp.shape = dt.shape + tmp[ii, ...] = rtmp + ft = tmp + + # construct and return the result + result = [] + if return_distances and not dt_inplace: + result.append(dt) + if return_indices and not ft_inplace: + result.append(ft) + + if len(result) == 2: + return tuple(result) + elif len(result) == 1: + return result[0] + else: + return None + + +def distance_transform_edt(input, sampling=None, return_distances=True, + return_indices=False, distances=None, indices=None): + """ + Exact Euclidean distance transform. + + This function calculates the distance transform of the `input`, by + replacing each foreground (non-zero) element, with its + shortest distance to the background (any zero-valued element). + + In addition to the distance transform, the feature transform can + be calculated. In this case the index of the closest background + element to each foreground element is returned in a separate array. + + Parameters + ---------- + input : array_like + Input data to transform. Can be any type but will be converted + into binary: 1 wherever input equates to True, 0 elsewhere. + sampling : float, or sequence of float, optional + Spacing of elements along each dimension. If a sequence, must be of + length equal to the input rank; if a single number, this is used for + all axes. If not specified, a grid spacing of unity is implied. + return_distances : bool, optional + Whether to calculate the distance transform. + Default is True. + return_indices : bool, optional + Whether to calculate the feature transform. + Default is False. + distances : float64 ndarray, optional + An output array to store the calculated distance transform, instead of + returning it. + `return_distances` must be True. + It must be the same shape as `input`. + indices : int32 ndarray, optional + An output array to store the calculated feature transform, instead of + returning it. + `return_indicies` must be True. + Its shape must be ``(input.ndim,) + input.shape``. + + Returns + ------- + distances : float64 ndarray, optional + The calculated distance transform. Returned only when + `return_distances` is True and `distances` is not supplied. + It will have the same shape as the input array. + indices : int32 ndarray, optional + The calculated feature transform. It has an input-shaped array for each + dimension of the input. See example below. + Returned only when `return_indices` is True and `indices` is not + supplied. + + Notes + ----- + The Euclidean distance transform gives values of the Euclidean + distance:: + + n + y_i = sqrt(sum (x[i]-b[i])**2) + i + + where b[i] is the background point (value 0) with the smallest + Euclidean distance to input points x[i], and n is the + number of dimensions. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array(([0,1,1,1,1], + ... [0,0,1,1,1], + ... [0,1,1,1,1], + ... [0,1,1,1,0], + ... [0,1,1,0,0])) + >>> ndimage.distance_transform_edt(a) + array([[ 0. , 1. , 1.4142, 2.2361, 3. ], + [ 0. , 0. , 1. , 2. , 2. ], + [ 0. , 1. , 1.4142, 1.4142, 1. ], + [ 0. , 1. , 1.4142, 1. , 0. ], + [ 0. , 1. , 1. , 0. , 0. ]]) + + With a sampling of 2 units along x, 1 along y: + + >>> ndimage.distance_transform_edt(a, sampling=[2,1]) + array([[ 0. , 1. , 2. , 2.8284, 3.6056], + [ 0. , 0. , 1. , 2. , 3. ], + [ 0. , 1. , 2. , 2.2361, 2. ], + [ 0. , 1. , 2. , 1. , 0. ], + [ 0. , 1. , 1. , 0. , 0. ]]) + + Asking for indices as well: + + >>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True) + >>> inds + array([[[0, 0, 1, 1, 3], + [1, 1, 1, 1, 3], + [2, 2, 1, 3, 3], + [3, 3, 4, 4, 3], + [4, 4, 4, 4, 4]], + [[0, 0, 1, 1, 4], + [0, 1, 1, 1, 4], + [0, 0, 1, 4, 4], + [0, 0, 3, 3, 4], + [0, 0, 3, 3, 4]]], dtype=int32) + + With arrays provided for inplace outputs: + + >>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32) + >>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices) + array([[ 0. , 1. , 1.4142, 2.2361, 3. ], + [ 0. , 0. , 1. , 2. , 2. ], + [ 0. , 1. , 1.4142, 1.4142, 1. ], + [ 0. , 1. , 1.4142, 1. , 0. ], + [ 0. , 1. , 1. , 0. , 0. ]]) + >>> indices + array([[[0, 0, 1, 1, 3], + [1, 1, 1, 1, 3], + [2, 2, 1, 3, 3], + [3, 3, 4, 4, 3], + [4, 4, 4, 4, 4]], + [[0, 0, 1, 1, 4], + [0, 1, 1, 1, 4], + [0, 0, 1, 4, 4], + [0, 0, 3, 3, 4], + [0, 0, 3, 3, 4]]], dtype=int32) + + """ + ft_inplace = isinstance(indices, np.ndarray) + dt_inplace = isinstance(distances, np.ndarray) + _distance_tranform_arg_check( + dt_inplace, ft_inplace, return_distances, return_indices + ) + + # calculate the feature transform + input = np.atleast_1d(np.where(input, 1, 0).astype(np.int8)) + if sampling is not None: + sampling = _ni_support._normalize_sequence(sampling, input.ndim) + sampling = np.asarray(sampling, dtype=np.float64) + if not sampling.flags.contiguous: + sampling = sampling.copy() + + if ft_inplace: + ft = indices + if ft.shape != (input.ndim,) + input.shape: + raise RuntimeError('indices array has wrong shape') + if ft.dtype.type != np.int32: + raise RuntimeError('indices array must be int32') + else: + ft = np.zeros((input.ndim,) + input.shape, dtype=np.int32) + + _nd_image.euclidean_feature_transform(input, sampling, ft) + # if requested, calculate the distance transform + if return_distances: + dt = ft - np.indices(input.shape, dtype=ft.dtype) + dt = dt.astype(np.float64) + if sampling is not None: + for ii in range(len(sampling)): + dt[ii, ...] *= sampling[ii] + np.multiply(dt, dt, dt) + if dt_inplace: + dt = np.add.reduce(dt, axis=0) + if distances.shape != dt.shape: + raise RuntimeError('distances array has wrong shape') + if distances.dtype.type != np.float64: + raise RuntimeError('distances array must be float64') + np.sqrt(dt, distances) + else: + dt = np.add.reduce(dt, axis=0) + dt = np.sqrt(dt) + + # construct and return the result + result = [] + if return_distances and not dt_inplace: + result.append(dt) + if return_indices and not ft_inplace: + result.append(ft) + + if len(result) == 2: + return tuple(result) + elif len(result) == 1: + return result[0] + else: + return None + + +def _distance_tranform_arg_check(distances_out, indices_out, + return_distances, return_indices): + """Raise a RuntimeError if the arguments are invalid""" + error_msgs = [] + if (not return_distances) and (not return_indices): + error_msgs.append( + 'at least one of return_distances/return_indices must be True') + if distances_out and not return_distances: + error_msgs.append( + 'return_distances must be True if distances is supplied' + ) + if indices_out and not return_indices: + error_msgs.append('return_indices must be True if indices is supplied') + if error_msgs: + raise RuntimeError(', '.join(error_msgs)) diff --git a/shared/package-files/2c/2c6050638d7bce26d0f9f9cf8ace6b36d3ff235424f4e9611053a73ef9b05c72/nv.py b/shared/package-files/2c/2c6050638d7bce26d0f9f9cf8ace6b36d3ff235424f4e9611053a73ef9b05c72/nv.py new file mode 100644 index 0000000000000000000000000000000000000000..212f34806fc491f5c9ef3ff5148331bea92041c4 --- /dev/null +++ b/shared/package-files/2c/2c6050638d7bce26d0f9f9cf8ace6b36d3ff235424f4e9611053a73ef9b05c72/nv.py @@ -0,0 +1,53 @@ +from numpy.distutils.fcompiler import FCompiler + +compilers = ['NVHPCFCompiler'] + +class NVHPCFCompiler(FCompiler): + """ NVIDIA High Performance Computing (HPC) SDK Fortran Compiler + + https://developer.nvidia.com/hpc-sdk + + Since august 2020 the NVIDIA HPC SDK includes the compilers formerly known as The Portland Group compilers, + https://www.pgroup.com/index.htm. + See also `numpy.distutils.fcompiler.pg`. + """ + + compiler_type = 'nv' + description = 'NVIDIA HPC SDK' + version_pattern = r'\s*(nvfortran|(pg(f77|f90|fortran)) \(aka nvfortran\)) (?P[\d.-]+).*' + + executables = { + 'version_cmd': ["", "-V"], + 'compiler_f77': ["nvfortran"], + 'compiler_fix': ["nvfortran", "-Mfixed"], + 'compiler_f90': ["nvfortran"], + 'linker_so': [""], + 'archiver': ["ar", "-cr"], + 'ranlib': ["ranlib"] + } + pic_flags = ['-fpic'] + + module_dir_switch = '-module ' + module_include_switch = '-I' + + def get_flags(self): + opt = ['-Minform=inform', '-Mnosecond_underscore'] + return self.pic_flags + opt + + def get_flags_opt(self): + return ['-fast'] + + def get_flags_debug(self): + return ['-g'] + + def get_flags_linker_so(self): + return ["-shared", '-fpic'] + + def runtime_library_dir_option(self, dir): + return '-R%s' % dir + +if __name__ == '__main__': + from distutils import log + log.set_verbosity(2) + from numpy.distutils import customized_fcompiler + print(customized_fcompiler(compiler='nv').get_version()) diff --git a/shared/package-files/2c/2c64ef70aa61564ca76b806f65b582fa4b814bf885dbe4e8c928f4f2e296af74/polygamma_cpu_dispatch.h b/shared/package-files/2c/2c64ef70aa61564ca76b806f65b582fa4b814bf885dbe4e8c928f4f2e296af74/polygamma_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1a3aa0135ad01aba1e00ab2dbe1192f6547d2c63 --- /dev/null +++ b/shared/package-files/2c/2c64ef70aa61564ca76b806f65b582fa4b814bf885dbe4e8c928f4f2e296af74/polygamma_cpu_dispatch.h @@ -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 polygamma(int64_t n, const at::Tensor & self); +TORCH_API at::Tensor & polygamma_out(at::Tensor & out, int64_t n, const at::Tensor & self); +TORCH_API at::Tensor & polygamma_outf(int64_t n, const at::Tensor & self, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/2c/2c7419785a0b57a417f74adfb6cf4fa41a40fff0c608822b8bed6c65a8add57a/wheel.py b/shared/package-files/2c/2c7419785a0b57a417f74adfb6cf4fa41a40fff0c608822b8bed6c65a8add57a/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..692118cb1b1105a6902e482d2da012834e6b7e13 --- /dev/null +++ b/shared/package-files/2c/2c7419785a0b57a417f74adfb6cf4fa41a40fff0c608822b8bed6c65a8add57a/wheel.py @@ -0,0 +1,55 @@ +import io +import os +import zipfile + + +from .distribution import Distribution +from .distribution import parse + + +class Wheel(Distribution): + + def __init__(self, filename, metadata_version=None): + self.filename = filename + self.metadata_version = metadata_version + self.extractMetadata() + + def read(self): + fqn = os.path.abspath(os.path.normpath(self.filename)) + if not os.path.exists(fqn): + raise ValueError('No such file: %s' % fqn) + + if fqn.endswith('.whl'): + archive = zipfile.ZipFile(fqn) + names = archive.namelist() + + def read_file(name): + return archive.read(name) + + close = archive.close + + elif fqn.endswith('.dist-info'): + names = [os.path.join(fqn, p) for p in os.listdir(fqn)] + + def read_file(name): + with io.open(name, mode='rb') as inf: + return inf.read() + + close = lambda : None + + else: + raise ValueError('Not a known wheel archive format or ' + 'installed .dist-info: %s' % fqn) + + try: + tuples = [x.split('/') for x in names if 'METADATA' in x] + schwarz = sorted([(len(x), x) for x in tuples]) + for path in [x[1] for x in schwarz]: + candidate = '/'.join(path) + data = read_file(candidate) + if b'Metadata-Version' in data: + return data + finally: + close() + + raise ValueError('No METADATA in archive: %s' % fqn) diff --git a/shared/package-files/2c/2c75e0995a811c7ba85e5859074915c64a74ea8d07471a40787f1b4dee8df8c8/formw.pc b/shared/package-files/2c/2c75e0995a811c7ba85e5859074915c64a74ea8d07471a40787f1b4dee8df8c8/formw.pc new file mode 100644 index 0000000000000000000000000000000000000000..ebb2eb5357682a1bbaad92b2c0672e7f3911e9c9 --- /dev/null +++ b/shared/package-files/2c/2c75e0995a811c7ba85e5859074915c64a74ea8d07471a40787f1b4dee8df8c8/formw.pc @@ -0,0 +1,19 @@ +# pkg-config file generated by gen-pkgconfig +# vile:makemode + +prefix=/opt/conda +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include/ncursesw +abi_version=6 +major_version=6 +version=6.4.20221231 + +Name: formw +Description: ncurses 6.4 add-on library +Version: ${version} +URL: https://invisible-island.net/ncurses +Requires.private: ncursesw +Libs: -L/opt/conda/lib -Wl,-O2 -Wl,--sort-common -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,-rpath,/opt/conda/lib -Wl,-rpath-link,/opt/conda/lib -lformw +Libs.private: +Cflags: -D_GNU_SOURCE -DNCURSES_WIDECHAR -I${includedir} -I/opt/conda/include diff --git a/shared/package-files/2c/2c76ad3428756fa7dab3d50f134c7d531a00189ca81168b5af17526ade8e972b/insert_quant_dequant.h b/shared/package-files/2c/2c76ad3428756fa7dab3d50f134c7d531a00189ca81168b5af17526ade8e972b/insert_quant_dequant.h new file mode 100644 index 0000000000000000000000000000000000000000..de2b31fdba7ca80223bad52847b78060868ba9ce --- /dev/null +++ b/shared/package-files/2c/2c76ad3428756fa7dab3d50f134c7d531a00189ca81168b5af17526ade8e972b/insert_quant_dequant.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include + +namespace torch { +namespace jit { + +/** Replicate quantize node for prim::If blocks, so that we can match + * quantization patterns in prim::If blocks + */ +TORCH_API void ReplicateQuant(std::shared_ptr& graph); + +/** Replicate dequantize node for each use, so that we can match + * quantization patterns + */ +TORCH_API void ReplicateDeQuant(std::shared_ptr& graph); + +/** \brief Insert quantize - dequantize calls to the Tensors + * that are observed in insert_observers pass + * + * For each Tensor that is observed, get the observer module and call + * calculate_qparam on the observer module to get quantization parameters + * and add quantize - int_repr - dequantize function calls using these + * parameters we also have special handling for quantizing "bias" right now. + * + * \param module the input module + * \param method_name the method we want to insert quantization calls for + */ +TORCH_API Module InsertQuantDeQuant( + Module& module, + const std::string& method_name, + bool inplace, + bool debug, + QuantType quant_type = QuantType::STATIC); + +TORCH_API Module InsertQuantDeQuantOnDevicePTQ( + Module& module, + const std::string& method_name, + bool inplace, + bool debug, + QuantType quant_type = QuantType::STATIC); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/2c/2c770bac0680a5a180b1310102d14e1e120f2f2e8e47925b1574ec808cb8ad6d/posixpath.py b/shared/package-files/2c/2c770bac0680a5a180b1310102d14e1e120f2f2e8e47925b1574ec808cb8ad6d/posixpath.py new file mode 100644 index 0000000000000000000000000000000000000000..e550b470da5bebf60cf2ea4efc2b017520e5d670 --- /dev/null +++ b/shared/package-files/2c/2c770bac0680a5a180b1310102d14e1e120f2f2e8e47925b1574ec808cb8ad6d/posixpath.py @@ -0,0 +1,542 @@ +"""Common operations on Posix pathnames. + +Instead of importing this module directly, import os and refer to +this module as os.path. The "os.path" name is an alias for this +module on Posix systems; on other systems (e.g. Windows), +os.path provides the same operations in a manner specific to that +platform, and is an alias to another module (e.g. ntpath). + +Some of this can actually be useful on non-Posix systems too, e.g. +for manipulation of the pathname component of URLs. +""" + +# Strings representing various path-related bits and pieces. +# These are primarily for export; internally, they are hardcoded. +# Should be set before imports for resolving cyclic dependency. +curdir = '.' +pardir = '..' +extsep = '.' +sep = '/' +pathsep = ':' +defpath = '/bin:/usr/bin' +altsep = None +devnull = '/dev/null' + +import os +import sys +import stat +import genericpath +from genericpath import * + +__all__ = ["normcase","isabs","join","splitdrive","split","splitext", + "basename","dirname","commonprefix","getsize","getmtime", + "getatime","getctime","islink","exists","lexists","isdir","isfile", + "ismount", "expanduser","expandvars","normpath","abspath", + "samefile","sameopenfile","samestat", + "curdir","pardir","sep","pathsep","defpath","altsep","extsep", + "devnull","realpath","supports_unicode_filenames","relpath", + "commonpath"] + + +def _get_sep(path): + if isinstance(path, bytes): + return b'/' + else: + return '/' + +# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac. +# On MS-DOS this may also turn slashes into backslashes; however, other +# normalizations (such as optimizing '../' away) are not allowed +# (another function should be defined to do that). + +def normcase(s): + """Normalize case of pathname. Has no effect under Posix""" + return os.fspath(s) + + +# Return whether a path is absolute. +# Trivial in Posix, harder on the Mac or MS-DOS. + +def isabs(s): + """Test whether a path is absolute""" + s = os.fspath(s) + sep = _get_sep(s) + return s.startswith(sep) + + +# Join pathnames. +# Ignore the previous parts if a part is absolute. +# Insert a '/' unless the first part is empty or already ends in '/'. + +def join(a, *p): + """Join two or more pathname components, inserting '/' as needed. + If any component is an absolute path, all previous path components + will be discarded. An empty last part will result in a path that + ends with a separator.""" + a = os.fspath(a) + sep = _get_sep(a) + path = a + try: + if not p: + path[:0] + sep #23780: Ensure compatible data type even if p is null. + for b in map(os.fspath, p): + if b.startswith(sep): + path = b + elif not path or path.endswith(sep): + path += b + else: + path += sep + b + except (TypeError, AttributeError, BytesWarning): + genericpath._check_arg_types('join', a, *p) + raise + return path + + +# Split a path in head (everything up to the last '/') and tail (the +# rest). If the path ends in '/', tail will be empty. If there is no +# '/' in the path, head will be empty. +# Trailing '/'es are stripped from head unless it is the root. + +def split(p): + """Split a pathname. Returns tuple "(head, tail)" where "tail" is + everything after the final slash. Either part may be empty.""" + p = os.fspath(p) + sep = _get_sep(p) + i = p.rfind(sep) + 1 + head, tail = p[:i], p[i:] + if head and head != sep*len(head): + head = head.rstrip(sep) + return head, tail + + +# Split a path in root and extension. +# The extension is everything starting at the last dot in the last +# pathname component; the root is everything before that. +# It is always true that root + ext == p. + +def splitext(p): + p = os.fspath(p) + if isinstance(p, bytes): + sep = b'/' + extsep = b'.' + else: + sep = '/' + extsep = '.' + return genericpath._splitext(p, sep, None, extsep) +splitext.__doc__ = genericpath._splitext.__doc__ + +# Split a pathname into a drive specification and the rest of the +# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty. + +def splitdrive(p): + """Split a pathname into drive and path. On Posix, drive is always + empty.""" + p = os.fspath(p) + return p[:0], p + + +# Return the tail (basename) part of a path, same as split(path)[1]. + +def basename(p): + """Returns the final component of a pathname""" + p = os.fspath(p) + sep = _get_sep(p) + i = p.rfind(sep) + 1 + return p[i:] + + +# Return the head (dirname) part of a path, same as split(path)[0]. + +def dirname(p): + """Returns the directory component of a pathname""" + p = os.fspath(p) + sep = _get_sep(p) + i = p.rfind(sep) + 1 + head = p[:i] + if head and head != sep*len(head): + head = head.rstrip(sep) + return head + + +# Is a path a symbolic link? +# This will always return false on systems where os.lstat doesn't exist. + +def islink(path): + """Test whether a path is a symbolic link""" + try: + st = os.lstat(path) + except (OSError, ValueError, AttributeError): + return False + return stat.S_ISLNK(st.st_mode) + +# Being true for dangling symbolic links is also useful. + +def lexists(path): + """Test whether a path exists. Returns True for broken symbolic links""" + try: + os.lstat(path) + except (OSError, ValueError): + return False + return True + + +# Is a path a mount point? +# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?) + +def ismount(path): + """Test whether a path is a mount point""" + try: + s1 = os.lstat(path) + except (OSError, ValueError): + # It doesn't exist -- so not a mount point. :-) + return False + else: + # A symlink can never be a mount point + if stat.S_ISLNK(s1.st_mode): + return False + + path = os.fspath(path) + if isinstance(path, bytes): + parent = join(path, b'..') + else: + parent = join(path, '..') + parent = realpath(parent) + try: + s2 = os.lstat(parent) + except (OSError, ValueError): + return False + + dev1 = s1.st_dev + dev2 = s2.st_dev + if dev1 != dev2: + return True # path/.. on a different device as path + ino1 = s1.st_ino + ino2 = s2.st_ino + if ino1 == ino2: + return True # path/.. is the same i-node as path + return False + + +# Expand paths beginning with '~' or '~user'. +# '~' means $HOME; '~user' means that user's home directory. +# If the path doesn't begin with '~', or if the user or $HOME is unknown, +# the path is returned unchanged (leaving error reporting to whatever +# function is called with the expanded path as argument). +# See also module 'glob' for expansion of *, ? and [...] in pathnames. +# (A function should also be defined to do full *sh-style environment +# variable expansion.) + +def expanduser(path): + """Expand ~ and ~user constructions. If user or $HOME is unknown, + do nothing.""" + path = os.fspath(path) + if isinstance(path, bytes): + tilde = b'~' + else: + tilde = '~' + if not path.startswith(tilde): + return path + sep = _get_sep(path) + i = path.find(sep, 1) + if i < 0: + i = len(path) + if i == 1: + if 'HOME' not in os.environ: + import pwd + try: + userhome = pwd.getpwuid(os.getuid()).pw_dir + except KeyError: + # bpo-10496: if the current user identifier doesn't exist in the + # password database, return the path unchanged + return path + else: + userhome = os.environ['HOME'] + else: + import pwd + name = path[1:i] + if isinstance(name, bytes): + name = str(name, 'ASCII') + try: + pwent = pwd.getpwnam(name) + except KeyError: + # bpo-10496: if the user name from the path doesn't exist in the + # password database, return the path unchanged + return path + userhome = pwent.pw_dir + # if no user home, return the path unchanged on VxWorks + if userhome is None and sys.platform == "vxworks": + return path + if isinstance(path, bytes): + userhome = os.fsencode(userhome) + root = b'/' + else: + root = '/' + userhome = userhome.rstrip(root) + return (userhome + path[i:]) or root + + +# Expand paths containing shell variable substitutions. +# This expands the forms $variable and ${variable} only. +# Non-existent variables are left unchanged. + +_varprog = None +_varprogb = None + +def expandvars(path): + """Expand shell variables of form $var and ${var}. Unknown variables + are left unchanged.""" + path = os.fspath(path) + global _varprog, _varprogb + if isinstance(path, bytes): + if b'$' not in path: + return path + if not _varprogb: + import re + _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII) + search = _varprogb.search + start = b'{' + end = b'}' + environ = getattr(os, 'environb', None) + else: + if '$' not in path: + return path + if not _varprog: + import re + _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII) + search = _varprog.search + start = '{' + end = '}' + environ = os.environ + i = 0 + while True: + m = search(path, i) + if not m: + break + i, j = m.span(0) + name = m.group(1) + if name.startswith(start) and name.endswith(end): + name = name[1:-1] + try: + if environ is None: + value = os.fsencode(os.environ[os.fsdecode(name)]) + else: + value = environ[name] + except KeyError: + i = j + else: + tail = path[j:] + path = path[:i] + value + i = len(path) + path += tail + return path + + +# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. +# It should be understood that this may change the meaning of the path +# if it contains symbolic links! + +def normpath(path): + """Normalize path, eliminating double slashes, etc.""" + path = os.fspath(path) + if isinstance(path, bytes): + sep = b'/' + empty = b'' + dot = b'.' + dotdot = b'..' + else: + sep = '/' + empty = '' + dot = '.' + dotdot = '..' + if path == empty: + return dot + initial_slashes = path.startswith(sep) + # POSIX allows one or two initial slashes, but treats three or more + # as single slash. + # (see https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13) + if (initial_slashes and + path.startswith(sep*2) and not path.startswith(sep*3)): + initial_slashes = 2 + comps = path.split(sep) + new_comps = [] + for comp in comps: + if comp in (empty, dot): + continue + if (comp != dotdot or (not initial_slashes and not new_comps) or + (new_comps and new_comps[-1] == dotdot)): + new_comps.append(comp) + elif new_comps: + new_comps.pop() + comps = new_comps + path = sep.join(comps) + if initial_slashes: + path = sep*initial_slashes + path + return path or dot + + +def abspath(path): + """Return an absolute path.""" + path = os.fspath(path) + if not isabs(path): + if isinstance(path, bytes): + cwd = os.getcwdb() + else: + cwd = os.getcwd() + path = join(cwd, path) + return normpath(path) + + +# Return a canonical path (i.e. the absolute location of a file on the +# filesystem). + +def realpath(filename, *, strict=False): + """Return the canonical path of the specified filename, eliminating any +symbolic links encountered in the path.""" + filename = os.fspath(filename) + path, ok = _joinrealpath(filename[:0], filename, strict, {}) + return abspath(path) + +# Join two paths, normalizing and eliminating any symbolic links +# encountered in the second path. +def _joinrealpath(path, rest, strict, seen): + if isinstance(path, bytes): + sep = b'/' + curdir = b'.' + pardir = b'..' + else: + sep = '/' + curdir = '.' + pardir = '..' + + if isabs(rest): + rest = rest[1:] + path = sep + + while rest: + name, _, rest = rest.partition(sep) + if not name or name == curdir: + # current dir + continue + if name == pardir: + # parent dir + if path: + path, name = split(path) + if name == pardir: + path = join(path, pardir, pardir) + else: + path = pardir + continue + newpath = join(path, name) + try: + st = os.lstat(newpath) + except OSError: + if strict: + raise + is_link = False + else: + is_link = stat.S_ISLNK(st.st_mode) + if not is_link: + path = newpath + continue + # Resolve the symbolic link + if newpath in seen: + # Already seen this path + path = seen[newpath] + if path is not None: + # use cached value + continue + # The symlink is not resolved, so we must have a symlink loop. + if strict: + # Raise OSError(errno.ELOOP) + os.stat(newpath) + else: + # Return already resolved part + rest of the path unchanged. + return join(newpath, rest), False + seen[newpath] = None # not resolved symlink + path, ok = _joinrealpath(path, os.readlink(newpath), strict, seen) + if not ok: + return join(path, rest), False + seen[newpath] = path # resolved symlink + + return path, True + + +supports_unicode_filenames = (sys.platform == 'darwin') + +def relpath(path, start=None): + """Return a relative version of a path""" + + if not path: + raise ValueError("no path specified") + + path = os.fspath(path) + if isinstance(path, bytes): + curdir = b'.' + sep = b'/' + pardir = b'..' + else: + curdir = '.' + sep = '/' + pardir = '..' + + if start is None: + start = curdir + else: + start = os.fspath(start) + + try: + start_list = [x for x in abspath(start).split(sep) if x] + path_list = [x for x in abspath(path).split(sep) if x] + # Work out how much of the filepath is shared by start and path. + i = len(commonprefix([start_list, path_list])) + + rel_list = [pardir] * (len(start_list)-i) + path_list[i:] + if not rel_list: + return curdir + return join(*rel_list) + except (TypeError, AttributeError, BytesWarning, DeprecationWarning): + genericpath._check_arg_types('relpath', path, start) + raise + + +# Return the longest common sub-path of the sequence of paths given as input. +# The paths are not normalized before comparing them (this is the +# responsibility of the caller). Any trailing separator is stripped from the +# returned path. + +def commonpath(paths): + """Given a sequence of path names, returns the longest common sub-path.""" + + if not paths: + raise ValueError('commonpath() arg is an empty sequence') + + paths = tuple(map(os.fspath, paths)) + if isinstance(paths[0], bytes): + sep = b'/' + curdir = b'.' + else: + sep = '/' + curdir = '.' + + try: + split_paths = [path.split(sep) for path in paths] + + try: + isabs, = set(p[:1] == sep for p in paths) + except ValueError: + raise ValueError("Can't mix absolute and relative paths") from None + + split_paths = [[c for c in s if c and c != curdir] for s in split_paths] + s1 = min(split_paths) + s2 = max(split_paths) + common = s1 + for i, c in enumerate(s1): + if c != s2[i]: + common = s1[:i] + break + + prefix = sep if isabs else sep[:0] + return prefix + sep.join(common) + except (TypeError, AttributeError): + genericpath._check_arg_types('commonpath', *paths) + raise diff --git a/shared/package-files/2c/2c774b94425960addc24998b153ea48d7e48e7c2eb759bea7a7dcf2d21967251/PlumbingHelper.h b/shared/package-files/2c/2c774b94425960addc24998b153ea48d7e48e7c2eb759bea7a7dcf2d21967251/PlumbingHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..552a618b144c85016da7fe8101354344a4365982 --- /dev/null +++ b/shared/package-files/2c/2c774b94425960addc24998b153ea48d7e48e7c2eb759bea7a7dcf2d21967251/PlumbingHelper.h @@ -0,0 +1,63 @@ +// 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 +#include + +// NOTE: [vmap plumbing] +// +// Here's how "batching rules" work. +// - we register kernels to the Batched key +// - these kernels have the same signatures as the original operators. +// For example, at::sin(Tensor self) accepts a Tensor, and the batched kernel +// must also accept a Tensor +// - However, it is more natural for users to write a batching rule like the +// following: sin_batch_rule(Tensor self, optional self_bdim) +// - There is some codegenerated layer (the "plumbing") that wraps the user +// defined batching rule (e.g. sin_batch_rule) in a kernel that can be +// registered to the Batched key. +// +// The plumbing is responsible for wrapping a batching rule into a form that may +// be registered as the kernel for the batched key. + +namespace at::functorch { + +void vmap_check_escaped(const optional &layer, const char* what); + +// Create a BatchedTensor given a tensor, bdim, and level +TORCH_API Tensor makeBatched(const Tensor& tensor, optional bdim, int64_t level); + +// Given a Tensor that may or may not be a BatchedTensor, unwrap it. +// If `tensor` is not a BatchedTensor, or is a BatchedTensor but the level +// doesn't match, then this returns (tensor, nullopt). +// Otherwise, it returns (unwrap(tensor), bdim). +TORCH_API std::tuple> unwrapTensorAtLevel(const Tensor& tensor, int64_t level); + +// Creates a vector of BatchedTensor +TORCH_API std::vector makeBatchedVector(const std::vector& tensors, optional bdim, int64_t level); + +// Returns True if ANY tensor in tensors is batched at level +TORCH_API bool isBatchedAtLevel(ITensorListRef tensors, int64_t level); +TORCH_API bool isBatchedAtLevel(const c10::List>& maybe_tensors, int64_t level); +TORCH_API bool isBatchedAtLevel(const Tensor& tensor, int64_t level); +TORCH_API bool isBatchedAtLevel(const c10::optional& maybe_tensor, int64_t level); + +// Convenience helper. Returns true if any tensor is batched at level +TORCH_API bool areAnyBatchedAtLevel(ArrayRef> maybe_tensors, int64_t level); + +inline bool ivalueParticipatesInCurrentLevel(const IValue& ivalue) { + if (ivalue.isTensor()) { + auto maybe_level = maybeCurrentDynamicLayer(); + TORCH_INTERNAL_ASSERT(maybe_level.has_value()); + auto current_level = maybe_level->layerId(); + return isBatchedAtLevel(ivalue.toTensor(), current_level); + } + // TODO: should really check this + return false; +} + +} // namespace at::functorch diff --git a/shared/package-files/2c/2c77c61d3d238e0a5b0ec5dfc6a1a1c34d44c0bd452c813cddeae56f9512e224/_lazy_graph_module.py b/shared/package-files/2c/2c77c61d3d238e0a5b0ec5dfc6a1a1c34d44c0bd452c813cddeae56f9512e224/_lazy_graph_module.py new file mode 100644 index 0000000000000000000000000000000000000000..a4b4bc0d69d7c7e94c3119ed05eab220cfc7aaca --- /dev/null +++ b/shared/package-files/2c/2c77c61d3d238e0a5b0ec5dfc6a1a1c34d44c0bd452c813cddeae56f9512e224/_lazy_graph_module.py @@ -0,0 +1,182 @@ +from contextlib import contextmanager + +from torch.fx import GraphModule +from torch.fx.graph_module import ( + _format_import_block, + reduce_graph_module, + reduce_package_graph_module, +) +from torch.package import PackageExporter, sys_importer +from ._compatibility import compatibility + +_use_lazy_graph_module_flag = False +_force_skip_lazy_graph_module_flag = False + + +@compatibility(is_backward_compatible=False) +@contextmanager +def _force_skip_lazy_graph_module(): + """ + Skip using lazy graph module disregarding the setting of _use_lazy_graph_module. + Use to skip _LazyGraphModule when testing inductor torchscript related backend. + + torch.jit.script a _LazyGraphModule results in following error: + https://gist.github.com/shunting314/5143654c8084aed84ecd19b818258a69 + """ + try: + global _force_skip_lazy_graph_module_flag + prior = _force_skip_lazy_graph_module_flag + _force_skip_lazy_graph_module_flag = True + yield + finally: + _force_skip_lazy_graph_module_flag = prior + + +@compatibility(is_backward_compatible=False) +@contextmanager +def _use_lazy_graph_module(should_use: bool): + try: + global _use_lazy_graph_module_flag + prior = _use_lazy_graph_module_flag + _use_lazy_graph_module_flag = ( + should_use and not _force_skip_lazy_graph_module_flag + ) + yield + finally: + _use_lazy_graph_module_flag = prior + + +@compatibility(is_backward_compatible=False) +def _get_graph_module_cls(): + return _LazyGraphModule if _use_lazy_graph_module_flag else GraphModule + + +def _make_graph_module(*args, graph_module_cls=None, **kwargs): + if graph_module_cls is None: + graph_module_cls = _get_graph_module_cls() + + return graph_module_cls(*args, **kwargs) + + +@compatibility(is_backward_compatible=False) +class _LazyGraphModule(GraphModule): + """ + The main difference between _LazyGraphModule and GraphModule is how recompile happens. + GraphModule will do a 'recompile' call to generate python code and the forward method when it's + constructed. Later on if the graph get updated, recompile method can be called again to refresh + the saved python code and forward method. + + However in some cases especially in inductor, the recompilation can be a waste since we never + check the python code for the graph module or call its forward method. A few more concreate + examples regarding pattern matching fx passes in inductor: + 1. some passes will update the graph to be compiled and then call recompile on the GraphModule. + 2. some passes will trace small pattern function to search it in the graph being compiled and + replace the match with the traced graph of a replacement function. The pattern graph and + replacement graph are quite small but there are large amount of them. Doing GraphModule.recompile + for them in GraphModule.__init__ is also a waste of time. + + However simply skip calling GraphModule.recompile in these scenarios is also dangeruous. + People may want to check the python code or call the GraphModule's forward method for debugging purposes. + + The way _LazyGraphModule solves it is, we override the recompile method to just mark the + need for recompilation but does not do the actual recompilation. Later on if people really + access the compiled python code or call the GraphModule's forward method, we do the real + recompilation. + """ + + @classmethod + def from_graphmodule(cls, gm: GraphModule): + if isinstance(gm, _LazyGraphModule): + return gm + else: + return _LazyGraphModule(gm, gm.graph) + + @staticmethod + def force_recompile(gm): + """ + Sometimes we need force a recompile as a workaround + - we want to do the real recompilation before symbolic_trace to avoid error: + https://gist.github.com/shunting314/75549c2e82ae07ac1139c94a3583d259 + """ + if isinstance(gm, _LazyGraphModule): + gm.real_recompile() + + def real_recompile(self): + if self._needs_recompile(): + self._real_recompile() + + @classmethod + def _needs_recompile(cls): + return cls.forward is cls._lazy_forward + + def _lazy_forward(self, *args, **kwargs): + # Call self.real_recompile() rather than self._real_recompile() here. + # The _lazy_forward method may be saved and call repeatedly. + # Calling self.real_recompile can make sure we skip recompilation if + # we have already done so. + self.real_recompile() + assert not self._needs_recompile() + + # call `__call__` rather than 'forward' since recompilation may + # install a wrapper for `__call__` to provide a customized error + # message. + return self(*args, **kwargs) + + forward = _lazy_forward + + # TODO: we shold handle __reduce_deploy__ the same way as __reduce_package__, + # or __reduce__ by calling _real_recompile. But I don't find a good way + # to test __reduce_deploy__ out. Also it's very unlikely that LazyGraphModule + # will be used in torch::deploy. So it's skipped for now. + + def __reduce_package__(self, exporter: PackageExporter): + """ + Follow GraphModule.__reduce__ but call 'self._real_recompile' rather + than 'self.recompile' since for a _LazyGraphModule, self.recompile just + mark the need of recompilation and does not return the PythonCode object. + """ + python_code = self._real_recompile() + dict_without_graph = self.__dict__.copy() + dict_without_graph["_graphmodule_cls_name"] = self.__class__.__name__ + del dict_without_graph["_graph"] + + generated_module_name = f"fx-generated._{exporter.get_unique_id()}" + import_block = _format_import_block(python_code.globals, exporter.importer) + module_code = import_block + self.code + exporter.save_source_string(generated_module_name, module_code) + return ( + reduce_package_graph_module, + (dict_without_graph, generated_module_name), + ) + + def __reduce__(self): + """ + Follow GraphModule.__reduce__ but call 'self._real_recompile' rather + than 'self.recompile' since for a _LazyGraphModule, self.recompile just + mark the need of recompilation and does not return the PythonCode object. + """ + python_code = self._real_recompile() + dict_without_graph = self.__dict__.copy() + import_block = _format_import_block(python_code.globals, sys_importer) + del dict_without_graph["_graph"] + return (reduce_graph_module, (dict_without_graph, import_block)) + + def _real_recompile(self): + return super().recompile() + + @classmethod + def recompile(cls): + cls.forward = cls._lazy_forward + + @property + def code(self) -> str: + self.real_recompile() + return super().code + + def __str__(self) -> str: + """ + str(GraphModule) will access the _code attribute. Make sure recompile + happens so _code attribute is available. + """ + self.real_recompile() + return super().__str__() diff --git a/shared/package-files/2c/2c7dd06a82c3391151740b50b9f29b7d18f6367b31e4ff376bba33926334333a/small.py b/shared/package-files/2c/2c7dd06a82c3391151740b50b9f29b7d18f6367b31e4ff376bba33926334333a/small.py new file mode 100644 index 0000000000000000000000000000000000000000..60a4388e5f43912f93dca6c4877dc456faf36d16 --- /dev/null +++ b/shared/package-files/2c/2c7dd06a82c3391151740b50b9f29b7d18f6367b31e4ff376bba33926334333a/small.py @@ -0,0 +1,955 @@ +""" +Various small and named graphs, together with some compact generators. + +""" + +__all__ = [ + "LCF_graph", + "bull_graph", + "chvatal_graph", + "cubical_graph", + "desargues_graph", + "diamond_graph", + "dodecahedral_graph", + "frucht_graph", + "heawood_graph", + "hoffman_singleton_graph", + "house_graph", + "house_x_graph", + "icosahedral_graph", + "krackhardt_kite_graph", + "moebius_kantor_graph", + "octahedral_graph", + "pappus_graph", + "petersen_graph", + "sedgewick_maze_graph", + "tetrahedral_graph", + "truncated_cube_graph", + "truncated_tetrahedron_graph", + "tutte_graph", +] + +from functools import wraps + +import networkx as nx +from networkx.exception import NetworkXError +from networkx.generators.classic import ( + complete_graph, + cycle_graph, + empty_graph, + path_graph, +) + + +def _raise_on_directed(func): + """ + A decorator which inspects the `create_using` argument and raises a + NetworkX exception when `create_using` is a DiGraph (class or instance) for + graph generators that do not support directed outputs. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + if kwargs.get("create_using") is not None: + G = nx.empty_graph(create_using=kwargs["create_using"]) + if G.is_directed(): + raise NetworkXError("Directed Graph not supported") + return func(*args, **kwargs) + + return wrapper + + +def LCF_graph(n, shift_list, repeats, create_using=None): + """ + Return the cubic graph specified in LCF notation. + + LCF notation (LCF=Lederberg-Coxeter-Fruchte) is a compressed + notation used in the generation of various cubic Hamiltonian + graphs of high symmetry. See, for example, dodecahedral_graph, + desargues_graph, heawood_graph and pappus_graph below. + + n (number of nodes) + The starting graph is the n-cycle with nodes 0,...,n-1. + (The null graph is returned if n < 0.) + + shift_list = [s1,s2,..,sk], a list of integer shifts mod n, + + repeats + integer specifying the number of times that shifts in shift_list + are successively applied to each v_current in the n-cycle + to generate an edge between v_current and v_current+shift mod n. + + For v1 cycling through the n-cycle a total of k*repeats + with shift cycling through shiftlist repeats times connect + v1 with v1+shift mod n + + The utility graph $K_{3,3}$ + + >>> G = nx.LCF_graph(6, [3, -3], 3) + + The Heawood graph + + >>> G = nx.LCF_graph(14, [5, -5], 7) + + See http://mathworld.wolfram.com/LCFNotation.html for a description + and references. + + """ + if n <= 0: + return empty_graph(0, create_using) + + # start with the n-cycle + G = cycle_graph(n, create_using) + if G.is_directed(): + raise NetworkXError("Directed Graph not supported") + G.name = "LCF_graph" + nodes = sorted(G) + + n_extra_edges = repeats * len(shift_list) + # edges are added n_extra_edges times + # (not all of these need be new) + if n_extra_edges < 1: + return G + + for i in range(n_extra_edges): + shift = shift_list[i % len(shift_list)] # cycle through shift_list + v1 = nodes[i % n] # cycle repeatedly through nodes + v2 = nodes[(i + shift) % n] + G.add_edge(v1, v2) + return G + + +# ------------------------------------------------------------------------------- +# Various small and named graphs +# ------------------------------------------------------------------------------- + + +@_raise_on_directed +def bull_graph(create_using=None): + """ + Returns the Bull Graph + + The Bull Graph has 5 nodes and 5 edges. It is a planar undirected + graph in the form of a triangle with two disjoint pendant edges [1]_ + The name comes from the triangle and pendant edges representing + respectively the body and legs of a bull. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + A bull graph with 5 nodes + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Bull_graph. + + """ + G = nx.from_dict_of_lists( + {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 4], 3: [1], 4: [2]}, + create_using=create_using, + ) + G.name = "Bull Graph" + return G + + +@_raise_on_directed +def chvatal_graph(create_using=None): + """ + Returns the Chvátal Graph + + The Chvátal Graph is an undirected graph with 12 nodes and 24 edges [1]_. + It has 370 distinct (directed) Hamiltonian cycles, giving a unique generalized + LCF notation of order 4, two of order 6 , and 43 of order 1 [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + The Chvátal graph with 12 nodes and 24 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Chv%C3%A1tal_graph + .. [2] https://mathworld.wolfram.com/ChvatalGraph.html + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 4, 6, 9], + 1: [2, 5, 7], + 2: [3, 6, 8], + 3: [4, 7, 9], + 4: [5, 8], + 5: [10, 11], + 6: [10, 11], + 7: [8, 11], + 8: [10], + 9: [10, 11], + }, + create_using=create_using, + ) + G.name = "Chvatal Graph" + return G + + +@_raise_on_directed +def cubical_graph(create_using=None): + """ + Returns the 3-regular Platonic Cubical Graph + + The skeleton of the cube (the nodes and edges) form a graph, with 8 + nodes, and 12 edges. It is a special case of the hypercube graph. + It is one of 5 Platonic graphs, each a skeleton of its + Platonic solid [1]_. + Such graphs arise in parallel processing in computers. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + A cubical graph with 8 nodes and 12 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Cube#Cubical_graph + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 3, 4], + 1: [0, 2, 7], + 2: [1, 3, 6], + 3: [0, 2, 5], + 4: [0, 5, 7], + 5: [3, 4, 6], + 6: [2, 5, 7], + 7: [1, 4, 6], + }, + create_using=create_using, + ) + G.name = ("Platonic Cubical Graph",) + return G + + +def desargues_graph(create_using=None): + """ + Returns the Desargues Graph + + The Desargues Graph is a non-planar, distance-transitive cubic graph + with 20 nodes and 30 edges [1]_. + It is a symmetric graph. It can be represented in LCF notation + as [5,-5,9,-9]^5 [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Desargues Graph with 20 nodes and 30 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Desargues_graph + .. [2] https://mathworld.wolfram.com/DesarguesGraph.html + """ + G = LCF_graph(20, [5, -5, 9, -9], 5, create_using) + G.name = "Desargues Graph" + return G + + +@_raise_on_directed +def diamond_graph(create_using=None): + """ + Returns the Diamond graph + + The Diamond Graph is planar undirected graph with 4 nodes and 5 edges. + It is also sometimes known as the double triangle graph or kite graph [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Diamond Graph with 4 nodes and 5 edges + + References + ---------- + .. [1] https://mathworld.wolfram.com/DiamondGraph.html + """ + G = nx.from_dict_of_lists( + {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 3], 3: [1, 2]}, create_using=create_using + ) + G.name = "Diamond Graph" + return G + + +def dodecahedral_graph(create_using=None): + """ + Returns the Platonic Dodecahedral graph. + + The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the + dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_. + It can be described in LCF notation as: + ``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Dodecahedral Graph with 20 nodes and 30 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph + .. [2] https://mathworld.wolfram.com/DodecahedralGraph.html + + """ + G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using) + G.name = "Dodecahedral Graph" + return G + + +def frucht_graph(create_using=None): + """ + Returns the Frucht Graph. + + The Frucht Graph is the smallest cubical graph whose + automorphism group consists only of the identity element [1]_. + It has 12 nodes and 18 edges and no nontrivial symmetries. + It is planar and Hamiltonian [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Frucht Graph with 12 nodes and 18 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Frucht_graph + .. [2] https://mathworld.wolfram.com/FruchtGraph.html + + """ + G = cycle_graph(7, create_using) + G.add_edges_from( + [ + [0, 7], + [1, 7], + [2, 8], + [3, 9], + [4, 9], + [5, 10], + [6, 10], + [7, 11], + [8, 11], + [8, 9], + [10, 11], + ] + ) + + G.name = "Frucht Graph" + return G + + +def heawood_graph(create_using=None): + """ + Returns the Heawood Graph, a (3,6) cage. + + The Heawood Graph is an undirected graph with 14 nodes and 21 edges, + named after Percy John Heawood [1]_. + It is cubic symmetric, nonplanar, Hamiltonian, and can be represented + in LCF notation as ``[5,-5]^7`` [2]_. + It is the unique (3,6)-cage: the regular cubic graph of girth 6 with + minimal number of vertices [3]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Heawood Graph with 14 nodes and 21 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Heawood_graph + .. [2] https://mathworld.wolfram.com/HeawoodGraph.html + .. [3] https://www.win.tue.nl/~aeb/graphs/Heawood.html + + """ + G = LCF_graph(14, [5, -5], 7, create_using) + G.name = "Heawood Graph" + return G + + +def hoffman_singleton_graph(): + """ + Returns the Hoffman-Singleton Graph. + + The Hoffman–Singleton graph is a symmetrical undirected graph + with 50 nodes and 175 edges. + All indices lie in ``Z % 5``: that is, the integers mod 5 [1]_. + It is the only regular graph of vertex degree 7, diameter 2, and girth 5. + It is the unique (7,5)-cage graph and Moore graph, and contains many + copies of the Petersen graph [2]_. + + Returns + ------- + G : networkx Graph + Hoffman–Singleton Graph with 50 nodes and 175 edges + + Notes + ----- + Constructed from pentagon and pentagram as follows: Take five pentagons $P_h$ + and five pentagrams $Q_i$ . Join vertex $j$ of $P_h$ to vertex $h·i+j$ of $Q_i$ [3]_. + + References + ---------- + .. [1] https://blogs.ams.org/visualinsight/2016/02/01/hoffman-singleton-graph/ + .. [2] https://mathworld.wolfram.com/Hoffman-SingletonGraph.html + .. [3] https://en.wikipedia.org/wiki/Hoffman%E2%80%93Singleton_graph + + """ + G = nx.Graph() + for i in range(5): + for j in range(5): + G.add_edge(("pentagon", i, j), ("pentagon", i, (j - 1) % 5)) + G.add_edge(("pentagon", i, j), ("pentagon", i, (j + 1) % 5)) + G.add_edge(("pentagram", i, j), ("pentagram", i, (j - 2) % 5)) + G.add_edge(("pentagram", i, j), ("pentagram", i, (j + 2) % 5)) + for k in range(5): + G.add_edge(("pentagon", i, j), ("pentagram", k, (i * k + j) % 5)) + G = nx.convert_node_labels_to_integers(G) + G.name = "Hoffman-Singleton Graph" + return G + + +@_raise_on_directed +def house_graph(create_using=None): + """ + Returns the House graph (square with triangle on top) + + The house graph is a simple undirected graph with + 5 nodes and 6 edges [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + House graph in the form of a square with a triangle on top + + References + ---------- + .. [1] https://mathworld.wolfram.com/HouseGraph.html + """ + G = nx.from_dict_of_lists( + {0: [1, 2], 1: [0, 3], 2: [0, 3, 4], 3: [1, 2, 4], 4: [2, 3]}, + create_using=create_using, + ) + G.name = "House Graph" + return G + + +@_raise_on_directed +def house_x_graph(create_using=None): + """ + Returns the House graph with a cross inside the house square. + + The House X-graph is the House graph plus the two edges connecting diagonally + opposite vertices of the square base. It is also one of the two graphs + obtained by removing two edges from the pentatope graph [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + House graph with diagonal vertices connected + + References + ---------- + .. [1] https://mathworld.wolfram.com/HouseGraph.html + """ + G = house_graph(create_using) + G.add_edges_from([(0, 3), (1, 2)]) + G.name = "House-with-X-inside Graph" + return G + + +@_raise_on_directed +def icosahedral_graph(create_using=None): + """ + Returns the Platonic Icosahedral graph. + + The icosahedral graph has 12 nodes and 30 edges. It is a Platonic graph + whose nodes have the connectivity of the icosahedron. It is undirected, + regular and Hamiltonian [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Icosahedral graph with 12 nodes and 30 edges. + + References + ---------- + .. [1] https://mathworld.wolfram.com/IcosahedralGraph.html + """ + G = nx.from_dict_of_lists( + { + 0: [1, 5, 7, 8, 11], + 1: [2, 5, 6, 8], + 2: [3, 6, 8, 9], + 3: [4, 6, 9, 10], + 4: [5, 6, 10, 11], + 5: [6, 11], + 7: [8, 9, 10, 11], + 8: [9], + 9: [10], + 10: [11], + }, + create_using=create_using, + ) + G.name = "Platonic Icosahedral Graph" + return G + + +@_raise_on_directed +def krackhardt_kite_graph(create_using=None): + """ + Returns the Krackhardt Kite Social Network. + + A 10 actor social network introduced by David Krackhardt + to illustrate different centrality measures [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Krackhardt Kite graph with 10 nodes and 18 edges + + Notes + ----- + The traditional labeling is: + Andre=1, Beverley=2, Carol=3, Diane=4, + Ed=5, Fernando=6, Garth=7, Heather=8, Ike=9, Jane=10. + + References + ---------- + .. [1] Krackhardt, David. "Assessing the Political Landscape: Structure, + Cognition, and Power in Organizations". Administrative Science Quarterly. + 35 (2): 342–369. doi:10.2307/2393394. JSTOR 2393394. June 1990. + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 2, 3, 5], + 1: [0, 3, 4, 6], + 2: [0, 3, 5], + 3: [0, 1, 2, 4, 5, 6], + 4: [1, 3, 6], + 5: [0, 2, 3, 6, 7], + 6: [1, 3, 4, 5, 7], + 7: [5, 6, 8], + 8: [7, 9], + 9: [8], + }, + create_using=create_using, + ) + G.name = "Krackhardt Kite Social Network" + return G + + +def moebius_kantor_graph(create_using=None): + """ + Returns the Moebius-Kantor graph. + + The Möbius-Kantor graph is the cubic symmetric graph on 16 nodes. + Its LCF notation is [5,-5]^8, and it is isomorphic to the generalized + Petersen graph [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Moebius-Kantor graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius%E2%80%93Kantor_graph + + """ + G = LCF_graph(16, [5, -5], 8, create_using) + G.name = "Moebius-Kantor Graph" + return G + + +@_raise_on_directed +def octahedral_graph(create_using=None): + """ + Returns the Platonic Octahedral graph. + + The octahedral graph is the 6-node 12-edge Platonic graph having the + connectivity of the octahedron [1]_. If 6 couples go to a party, + and each person shakes hands with every person except his or her partner, + then this graph describes the set of handshakes that take place; + for this reason it is also called the cocktail party graph [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Octahedral graph + + References + ---------- + .. [1] https://mathworld.wolfram.com/OctahedralGraph.html + .. [2] https://en.wikipedia.org/wiki/Tur%C3%A1n_graph#Special_cases + + """ + G = nx.from_dict_of_lists( + {0: [1, 2, 3, 4], 1: [2, 3, 5], 2: [4, 5], 3: [4, 5], 4: [5]}, + create_using=create_using, + ) + G.name = "Platonic Octahedral Graph" + return G + + +def pappus_graph(): + """ + Returns the Pappus graph. + + The Pappus graph is a cubic symmetric distance-regular graph with 18 nodes + and 27 edges. It is Hamiltonian and can be represented in LCF notation as + [5,7,-7,7,-7,-5]^3 [1]_. + + Returns + ------- + G : networkx Graph + Pappus graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Pappus_graph + """ + G = LCF_graph(18, [5, 7, -7, 7, -7, -5], 3) + G.name = "Pappus Graph" + return G + + +@_raise_on_directed +def petersen_graph(create_using=None): + """ + Returns the Petersen graph. + + The Peterson graph is a cubic, undirected graph with 10 nodes and 15 edges [1]_. + Julius Petersen constructed the graph as the smallest counterexample + against the claim that a connected bridgeless cubic graph + has an edge colouring with three colours [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Petersen graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Petersen_graph + .. [2] https://www.win.tue.nl/~aeb/drg/graphs/Petersen.html + """ + G = nx.from_dict_of_lists( + { + 0: [1, 4, 5], + 1: [0, 2, 6], + 2: [1, 3, 7], + 3: [2, 4, 8], + 4: [3, 0, 9], + 5: [0, 7, 8], + 6: [1, 8, 9], + 7: [2, 5, 9], + 8: [3, 5, 6], + 9: [4, 6, 7], + }, + create_using=create_using, + ) + G.name = "Petersen Graph" + return G + + +def sedgewick_maze_graph(create_using=None): + """ + Return a small maze with a cycle. + + This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph + Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_. + Nodes are numbered 0,..,7 + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Small maze with a cycle + + References + ---------- + .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick + """ + G = empty_graph(0, create_using) + G.add_nodes_from(range(8)) + G.add_edges_from([[0, 2], [0, 7], [0, 5]]) + G.add_edges_from([[1, 7], [2, 6]]) + G.add_edges_from([[3, 4], [3, 5]]) + G.add_edges_from([[4, 5], [4, 7], [4, 6]]) + G.name = "Sedgewick Maze" + return G + + +def tetrahedral_graph(create_using=None): + """ + Returns the 3-regular Platonic Tetrahedral graph. + + Tetrahedral graph has 4 nodes and 6 edges. It is a + special case of the complete graph, K4, and wheel graph, W4. + It is one of the 5 platonic graphs [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Tetrahedral Grpah + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Tetrahedron#Tetrahedral_graph + + """ + G = complete_graph(4, create_using) + G.name = "Platonic Tetrahedral graph" + return G + + +@_raise_on_directed +def truncated_cube_graph(create_using=None): + """ + Returns the skeleton of the truncated cube. + + The truncated cube is an Archimedean solid with 14 regular + faces (6 octagonal and 8 triangular), 36 edges and 24 nodes [1]_. + The truncated cube is created by truncating (cutting off) the tips + of the cube one third of the way into each edge [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Skeleton of the truncated cube + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Truncated_cube + .. [2] https://www.coolmath.com/reference/polyhedra-truncated-cube + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 2, 4], + 1: [11, 14], + 2: [3, 4], + 3: [6, 8], + 4: [5], + 5: [16, 18], + 6: [7, 8], + 7: [10, 12], + 8: [9], + 9: [17, 20], + 10: [11, 12], + 11: [14], + 12: [13], + 13: [21, 22], + 14: [15], + 15: [19, 23], + 16: [17, 18], + 17: [20], + 18: [19], + 19: [23], + 20: [21], + 21: [22], + 22: [23], + }, + create_using=create_using, + ) + G.name = "Truncated Cube Graph" + return G + + +def truncated_tetrahedron_graph(create_using=None): + """ + Returns the skeleton of the truncated Platonic tetrahedron. + + The truncated tetrahedron is an Archimedean solid with 4 regular hexagonal faces, + 4 equilateral triangle faces, 12 nodes and 18 edges. It can be constructed by truncating + all 4 vertices of a regular tetrahedron at one third of the original edge length [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Skeleton of the truncated tetrahedron + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Truncated_tetrahedron + + """ + G = path_graph(12, create_using) + G.add_edges_from([(0, 2), (0, 9), (1, 6), (3, 11), (4, 11), (5, 7), (8, 10)]) + G.name = "Truncated Tetrahedron Graph" + return G + + +@_raise_on_directed +def tutte_graph(create_using=None): + """ + Returns the Tutte graph. + + The Tutte graph is a cubic polyhedral, non-Hamiltonian graph. It has + 46 nodes and 69 edges. + It is a counterexample to Tait's conjecture that every 3-regular polyhedron + has a Hamiltonian cycle. + It can be realized geometrically from a tetrahedron by multiply truncating + three of its vertices [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Tutte graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Tutte_graph + """ + G = nx.from_dict_of_lists( + { + 0: [1, 2, 3], + 1: [4, 26], + 2: [10, 11], + 3: [18, 19], + 4: [5, 33], + 5: [6, 29], + 6: [7, 27], + 7: [8, 14], + 8: [9, 38], + 9: [10, 37], + 10: [39], + 11: [12, 39], + 12: [13, 35], + 13: [14, 15], + 14: [34], + 15: [16, 22], + 16: [17, 44], + 17: [18, 43], + 18: [45], + 19: [20, 45], + 20: [21, 41], + 21: [22, 23], + 22: [40], + 23: [24, 27], + 24: [25, 32], + 25: [26, 31], + 26: [33], + 27: [28], + 28: [29, 32], + 29: [30], + 30: [31, 33], + 31: [32], + 34: [35, 38], + 35: [36], + 36: [37, 39], + 37: [38], + 40: [41, 44], + 41: [42], + 42: [43, 45], + 43: [44], + }, + create_using=create_using, + ) + G.name = "Tutte's Graph" + return G diff --git a/shared/package-files/2c/2c82b7c4970d563dd0a8c23ad964a5ffd1b65c36bacd6813d7e871dbb79257c9/abm85h b/shared/package-files/2c/2c82b7c4970d563dd0a8c23ad964a5ffd1b65c36bacd6813d7e871dbb79257c9/abm85h new file mode 100644 index 0000000000000000000000000000000000000000..81471e94f65fb04a8a472b18ab27998f63cf6b10 Binary files /dev/null and b/shared/package-files/2c/2c82b7c4970d563dd0a8c23ad964a5ffd1b65c36bacd6813d7e871dbb79257c9/abm85h differ diff --git a/shared/package-files/2c/2c83911f076397e3a092fbdde45b3f1994b793f2dc10e77daa0951a53427603b/__init__.pyi b/shared/package-files/2c/2c83911f076397e3a092fbdde45b3f1994b793f2dc10e77daa0951a53427603b/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f9eb4ee136d440d827b272caff54dd295e33d9d1 --- /dev/null +++ b/shared/package-files/2c/2c83911f076397e3a092fbdde45b3f1994b793f2dc10e77daa0951a53427603b/__init__.pyi @@ -0,0 +1,36 @@ +import logging +from typing import Any, Text + +from .api import ( + delete as delete, + get as get, + head as head, + options as options, + patch as patch, + post as post, + put as put, + request as request, +) +from .exceptions import ( + ConnectionError as ConnectionError, + HTTPError as HTTPError, + ReadTimeout as ReadTimeout, + RequestException as RequestException, + Timeout as Timeout, + TooManyRedirects as TooManyRedirects, + URLRequired as URLRequired, +) +from .models import PreparedRequest as PreparedRequest, Request as Request, Response as Response +from .sessions import Session as Session, session as session +from .status_codes import codes as codes + +__title__: Any +__build__: Any +__license__: Any +__copyright__: Any +__version__: Any + +class NullHandler(logging.Handler): + def emit(self, record): ... + +def check_compatibility(urllib3_version: Text, chardet_version: Text) -> None: ... diff --git a/shared/package-files/2c/2c83f822771c514bc3ec8e0d66baad63d5a355f3bfc092f2ad5728c40c3ddae5/focus.py b/shared/package-files/2c/2c83f822771c514bc3ec8e0d66baad63d5a355f3bfc092f2ad5728c40c3ddae5/focus.py new file mode 100644 index 0000000000000000000000000000000000000000..24aa3ce39ba798d47668212fa1c6a7afed069032 --- /dev/null +++ b/shared/package-files/2c/2c83f822771c514bc3ec8e0d66baad63d5a355f3bfc092f2ad5728c40c3ddae5/focus.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from prompt_toolkit.key_binding.key_processor import KeyPressEvent + +__all__ = [ + "focus_next", + "focus_previous", +] + +E = KeyPressEvent + + +def focus_next(event: E) -> None: + """ + Focus the next visible Window. + (Often bound to the `Tab` key.) + """ + event.app.layout.focus_next() + + +def focus_previous(event: E) -> None: + """ + Focus the previous visible Window. + (Often bound to the `BackTab` key.) + """ + event.app.layout.focus_previous() diff --git a/shared/package-files/2c/2c88d002dccbf7a0cc90934a769b3baf732775aaa8d4364030ab6fe275e40559/cit101e-n132 b/shared/package-files/2c/2c88d002dccbf7a0cc90934a769b3baf732775aaa8d4364030ab6fe275e40559/cit101e-n132 new file mode 100644 index 0000000000000000000000000000000000000000..2be5d7b15bdbdc57078aeef5dad8d2503e9bbb39 Binary files /dev/null and b/shared/package-files/2c/2c88d002dccbf7a0cc90934a769b3baf732775aaa8d4364030ab6fe275e40559/cit101e-n132 differ diff --git a/shared/package-files/2c/2c8a48b06f05d42c601c29ba664420241567655bb772a07ca9e810dcd878b03b/torch_shm_manager b/shared/package-files/2c/2c8a48b06f05d42c601c29ba664420241567655bb772a07ca9e810dcd878b03b/torch_shm_manager new file mode 100644 index 0000000000000000000000000000000000000000..914efd22edb11158471a32f469e4f4e16f9c7af8 Binary files /dev/null and b/shared/package-files/2c/2c8a48b06f05d42c601c29ba664420241567655bb772a07ca9e810dcd878b03b/torch_shm_manager differ diff --git a/shared/package-files/2c/2c8d0b93bb36edf31c1236b1b4d1c0008553868bd2fc9137570115b96b834f2e/shift_jisx0213.py b/shared/package-files/2c/2c8d0b93bb36edf31c1236b1b4d1c0008553868bd2fc9137570115b96b834f2e/shift_jisx0213.py new file mode 100644 index 0000000000000000000000000000000000000000..cb653f53055e679c513218b0102ffa9d1b4ca82c --- /dev/null +++ b/shared/package-files/2c/2c8d0b93bb36edf31c1236b1b4d1c0008553868bd2fc9137570115b96b834f2e/shift_jisx0213.py @@ -0,0 +1,39 @@ +# +# shift_jisx0213.py: Python Unicode Codec for SHIFT_JISX0213 +# +# Written by Hye-Shik Chang +# + +import _codecs_jp, codecs +import _multibytecodec as mbc + +codec = _codecs_jp.getcodec('shift_jisx0213') + +class Codec(codecs.Codec): + encode = codec.encode + decode = codec.decode + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, + codecs.IncrementalEncoder): + codec = codec + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, + codecs.IncrementalDecoder): + codec = codec + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): + codec = codec + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec = codec + +def getregentry(): + return codecs.CodecInfo( + name='shift_jisx0213', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) diff --git a/shared/package-files/2c/2c8f4bb15dd77090b497e2a841ff3323ecbbae4f9dbb9edead2f8dd8fb5d8bb4/ROK b/shared/package-files/2c/2c8f4bb15dd77090b497e2a841ff3323ecbbae4f9dbb9edead2f8dd8fb5d8bb4/ROK new file mode 100644 index 0000000000000000000000000000000000000000..96199e73e73aafacd89e48cb2855a96d7a134e1d Binary files /dev/null and b/shared/package-files/2c/2c8f4bb15dd77090b497e2a841ff3323ecbbae4f9dbb9edead2f8dd8fb5d8bb4/ROK differ diff --git a/shared/package-files/2c/2c8f4bb15dd77090b497e2a841ff3323ecbbae4f9dbb9edead2f8dd8fb5d8bb4/Seoul b/shared/package-files/2c/2c8f4bb15dd77090b497e2a841ff3323ecbbae4f9dbb9edead2f8dd8fb5d8bb4/Seoul new file mode 100644 index 0000000000000000000000000000000000000000..96199e73e73aafacd89e48cb2855a96d7a134e1d Binary files /dev/null and b/shared/package-files/2c/2c8f4bb15dd77090b497e2a841ff3323ecbbae4f9dbb9edead2f8dd8fb5d8bb4/Seoul differ diff --git a/shared/package-files/2c/2c94c473867fb3256752f3c6977c3042441fb9f4763825e0d3987f7f5dd23ffc/file_based_local_timer.py b/shared/package-files/2c/2c94c473867fb3256752f3c6977c3042441fb9f4763825e0d3987f7f5dd23ffc/file_based_local_timer.py new file mode 100644 index 0000000000000000000000000000000000000000..26ebce33dcb5b5062667cbb5fc9630b93eee4c79 --- /dev/null +++ b/shared/package-files/2c/2c94c473867fb3256752f3c6977c3042441fb9f4763825e0d3987f7f5dd23ffc/file_based_local_timer.py @@ -0,0 +1,333 @@ +# Copyright (c) Meta Platforms, 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 io +import json +import logging +import os +import select +import signal +import sys +import threading +import time +from typing import Callable, Dict, List, Optional, Set, Tuple + +from torch.distributed.elastic.timer.api import TimerClient, TimerRequest + +__all__ = ["FileTimerClient", "FileTimerRequest", "FileTimerServer"] + +log = logging.getLogger(__name__) + +class FileTimerRequest(TimerRequest): + """ + Data object representing a countdown timer acquisition and release + that is used between the ``FileTimerClient`` and ``FileTimerServer``. + A negative ``expiration_time`` should be interpreted as a "release" + request. + ``signal`` is the signal to reap the worker process from the server + process. + """ + + __slots__ = ["version", "worker_pid", "scope_id", "expiration_time", "signal"] + + def __init__(self, worker_pid: int, scope_id: str, expiration_time: float, signal: int = 0) -> None: + self.version = 1 + self.worker_pid = worker_pid + self.scope_id = scope_id + self.expiration_time = expiration_time + self.signal = signal + + def __eq__(self, other) -> bool: + if isinstance(other, FileTimerRequest): + return ( + self.version == other.version + and self.worker_pid == other.worker_pid + and self.scope_id == other.scope_id + and self.expiration_time == other.expiration_time + and self.signal == other.signal + ) + return False + + def to_json(self) -> str: + return json.dumps( + { + "version": self.version, + "pid": self.worker_pid, + "scope_id": self.scope_id, + "expiration_time": self.expiration_time, + "signal": self.signal + }, + ) + + +class FileTimerClient(TimerClient): + """ + Client side of ``FileTimerServer``. This client is meant to be used + on the same host that the ``FileTimerServer`` is running on and uses + pid to uniquely identify a worker. + This client uses a named_pipe to send timer requests to the + ``FileTimerServer``. This client is a producer while the + ``FileTimerServer`` is a consumer. Multiple clients can work with + the same ``FileTimerServer``. + + Args: + + file_path: str, the path of a FIFO special file. ``FileTimerServer`` + must have created it by calling os.mkfifo(). + + signal: signal, the signal to use to kill the process. Using a + negative or zero signal will not kill the process. + """ + def __init__(self, file_path: str, signal=(signal.SIGKILL if sys.platform != "win32" else + signal.CTRL_C_EVENT)) -> None: # type: ignore[attr-defined] + super().__init__() + self._file_path = file_path + self.signal = signal + + def _open_non_blocking(self) -> Optional[io.TextIOWrapper]: + try: + fd = os.open(self._file_path, os.O_WRONLY | os.O_NONBLOCK) + return os.fdopen(fd, "wt") + except Exception: + return None + + def _send_request(self, request: FileTimerRequest) -> None: + # The server may have crashed or may haven't started yet. + # In such case, calling open() in blocking model blocks the client. + # To avoid such issue, open it in non-blocking mode, and an OSError will + # be raised if the server is not there. + file = self._open_non_blocking() + if file is None: + raise BrokenPipeError("Could not send the FileTimerRequest because FileTimerServer is not available.") + with file: + json_request = request.to_json() + # Write request with no greater than select.PIPE_BUF is guarantee to be atomic. + if len(json_request) > select.PIPE_BUF: + raise RuntimeError( + f"FileTimerRequest larger than {select.PIPE_BUF} bytes " + f"is not supported: {json_request}" + ) + file.write(json_request + "\n") + + def acquire(self, scope_id: str, expiration_time: float) -> None: + self._send_request( + request=FileTimerRequest( + worker_pid=os.getpid(), + scope_id=scope_id, + expiration_time=expiration_time, + signal=self.signal + ), + ) + + def release(self, scope_id: str) -> None: + self._send_request( + request=FileTimerRequest( + worker_pid=os.getpid(), + scope_id=scope_id, + expiration_time=-1, + signal=0 + ), + ) + + +class FileTimerServer: + """ + Server that works with ``FileTimerClient``. Clients are expected to be + running on the same host as the process that is running this server. + Each host in the job is expected to start its own timer server locally + and each server instance manages timers for local workers (running on + processes on the same host). + + Args: + + file_path: str, the path of a FIFO special file to be created. + + max_interval: float, max interval in seconds for each watchdog loop. + + daemon: bool, running the watchdog thread in daemon mode or not. + A daemon thread will not block a process to stop. + log_event: Callable[[Dict[str, str]], None], an optional callback for + logging the events in JSON format. + """ + + def __init__( + self, + file_path: str, + max_interval: float = 10, + daemon: bool = True, + log_event: Optional[Callable[[str, Optional[FileTimerRequest]], None]] = None + ) -> None: + self._file_path = file_path + self._max_interval = max_interval + self._daemon = daemon + self._timers: Dict[Tuple[int, str], FileTimerRequest] = {} + self._stop_signaled = False + self._watchdog_thread: Optional[threading.Thread] = None + if os.path.exists(self._file_path): + os.remove(self._file_path) + os.mkfifo(self._file_path) + # For test only. Count the number of requests received. + self._request_count = 0 + # For test only. Process all requests and stop the server. + self._run_once = False + self._log_event = log_event if log_event is not None else lambda name, request: None + + + def start(self) -> None: + log.info( + "Starting %s..." + " max_interval=%s," + " daemon=%s", + type(self).__name__, self._max_interval, self._daemon + ) + self._watchdog_thread = threading.Thread(target=self._watchdog_loop, daemon=self._daemon) + log.info("Starting watchdog thread...") + self._watchdog_thread.start() + self._log_event("watchdog started", None) + + def stop(self) -> None: + log.info("Stopping %s", type(self).__name__) + self._stop_signaled = True + if self._watchdog_thread: + log.info("Stopping watchdog thread...") + self._watchdog_thread.join(self._max_interval) + self._watchdog_thread = None + else: + log.info("No watchdog thread running, doing nothing") + if os.path.exists(self._file_path): + os.remove(self._file_path) + self._log_event("watchdog stopped", None) + + def run_once(self) -> None: + self._run_once = True + if self._watchdog_thread: + log.info("Stopping watchdog thread...") + self._watchdog_thread.join() + self._watchdog_thread = None + else: + log.info("No watchdog thread running, doing nothing") + if os.path.exists(self._file_path): + os.remove(self._file_path) + + def _watchdog_loop(self) -> None: + # Open the pipe in blocking mode blocks the server thread. + # This is fine for the following reasons: + # 1. No client case usually does not happen. + # 2. We are running the watchdog loop in a separate daemon + # thread, which will not block the process to stop. + with open(self._file_path) as fd: + while not self._stop_signaled: + try: + run_once = self._run_once + self._run_watchdog(fd) + if run_once: + break + except Exception: + log.exception("Error running watchdog") + + def _run_watchdog(self, fd: io.TextIOWrapper) -> None: + timer_requests = self._get_requests(fd, self._max_interval) + self.register_timers(timer_requests) + now = time.time() + reaped_worker_pids = set() + for worker_pid, expired_timers in self.get_expired_timers(now).items(): + log.info("Reaping worker_pid=[%s]. Expired timers: %s", worker_pid, self._get_scopes(expired_timers)) + reaped_worker_pids.add(worker_pid) + # In case we have multiple expired timers, we find the first timer + # with a valid signal (>0) in the expiration time order. + expired_timers.sort(key=lambda timer: timer.expiration_time) + signal = 0 + expired_timer = None + for timer in expired_timers: + self._log_event("timer expired", timer) + if timer.signal > 0: + signal = timer.signal + expired_timer = timer + break + if signal <= 0: + log.info("No signal specified with worker=[%s]. Do not reap it.", worker_pid) + continue + if self._reap_worker(worker_pid, signal): + log.info("Successfully reaped worker=[%s] with signal=%s", worker_pid, signal) + self._log_event("kill worker process", expired_timer) + else: + log.error("Error reaping worker=[%s]. Will retry on next watchdog.", worker_pid) + self.clear_timers(reaped_worker_pids) + + def _get_scopes(self, timer_requests: List[FileTimerRequest]) -> List[str]: + return [r.scope_id for r in timer_requests] + + def _get_requests(self, fd: io.TextIOWrapper, max_interval: float) -> List[FileTimerRequest]: + start = time.time() + requests = [] + while not self._stop_signaled or self._run_once: + # For named pipe, readline() is blocking when at least one writer opens. + # It returns only when flush() is called at the writer side. + # Note that flush() is automatically called inside close(). + # After the last writer closes, readline() is not blocking. + # It will return an empty string when it's at end-of-file. + # Since the client side always opens the pipe, writes a message and closes + # the pipe immediately, the readline() call below is not blocking for long. + json_request = fd.readline() + if len(json_request) == 0: + if self._run_once: + break + time.sleep(min(max_interval, 1)) + else: + request = json.loads(json_request) + pid = request["pid"] + scope_id = request["scope_id"] + expiration_time = request["expiration_time"] + signal = request["signal"] + requests.append( + FileTimerRequest( + worker_pid=pid, scope_id=scope_id, expiration_time=expiration_time, signal=signal + ) + ) + now = time.time() + if now - start > max_interval: + break + return requests + + def register_timers(self, timer_requests: List[FileTimerRequest]) -> None: + for request in timer_requests: + pid = request.worker_pid + scope_id = request.scope_id + expiration_time = request.expiration_time + self._request_count += 1 + + key = (pid, scope_id) + # negative expiration is a proxy for a release call + if expiration_time < 0: + if key in self._timers: + del self._timers[key] + else: + self._timers[key] = request + + def clear_timers(self, worker_pids: Set[int]) -> None: + for (pid, scope_id) in list(self._timers.keys()): + if pid in worker_pids: + del self._timers[(pid, scope_id)] + + def get_expired_timers(self, deadline: float) -> Dict[int, List[FileTimerRequest]]: + # pid -> [timer_requests...] + expired_timers: Dict[int, List[FileTimerRequest]] = {} + for request in self._timers.values(): + if request.expiration_time <= deadline: + expired_scopes = expired_timers.setdefault(request.worker_pid, []) + expired_scopes.append(request) + return expired_timers + + def _reap_worker(self, worker_pid: int, signal: int) -> bool: + try: + os.kill(worker_pid, signal) + return True + except ProcessLookupError: + log.info("Process with pid=%s does not exist. Skipping", worker_pid) + return True + except Exception: + log.exception("Error terminating pid=%s", worker_pid) + return False diff --git a/shared/package-files/2c/2c9d7d88d4ca755feda92867e46c896d373726d1abec87aca02432d39f0a3f1d/FLAG.pyi b/shared/package-files/2c/2c9d7d88d4ca755feda92867e46c896d373726d1abec87aca02432d39f0a3f1d/FLAG.pyi new file mode 100644 index 0000000000000000000000000000000000000000..04b99fadc4ee72a1bf7cb2234210145ccc50074a --- /dev/null +++ b/shared/package-files/2c/2c9d7d88d4ca755feda92867e46c896d373726d1abec87aca02432d39f0a3f1d/FLAG.pyi @@ -0,0 +1,17 @@ +from typing import Any + +NOT_NULL: Any +PRI_KEY: Any +UNIQUE_KEY: Any +MULTIPLE_KEY: Any +BLOB: Any +UNSIGNED: Any +ZEROFILL: Any +BINARY: Any +ENUM: Any +AUTO_INCREMENT: Any +TIMESTAMP: Any +SET: Any +PART_KEY: Any +GROUP: Any +UNIQUE: Any diff --git a/shared/package-files/2c/2c9e36b8a315d001ccd306d34dc31851515a03364c78400226fe9b2c7d971f9b/sspaddmm_native.h b/shared/package-files/2c/2c9e36b8a315d001ccd306d34dc31851515a03364c78400226fe9b2c7d971f9b/sspaddmm_native.h new file mode 100644 index 0000000000000000000000000000000000000000..78e8443ae493b07f40d50c94b89cae125b633c73 --- /dev/null +++ b/shared/package-files/2c/2c9e36b8a315d001ccd306d34dc31851515a03364c78400226fe9b2c7d971f9b/sspaddmm_native.h @@ -0,0 +1,25 @@ +#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 sspaddmm(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1); +TORCH_API at::Tensor & _sspaddmm_out_only_sparse(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & _sspaddmm_out_only_sparse_cuda(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & _sspaddmm_out_cpu(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & _sspaddmm_out_cuda(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/2c/2ca026e5d803e40d9e146085638098513225e4e4d6526e689bafe0e7ea01affe/signbit_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/2c/2ca026e5d803e40d9e146085638098513225e4e4d6526e689bafe0e7ea01affe/signbit_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..02a5fa77d6eb669a8a83057ff7c554fdb34d6894 --- /dev/null +++ b/shared/package-files/2c/2ca026e5d803e40d9e146085638098513225e4e4d6526e689bafe0e7ea01affe/signbit_compositeexplicitautogradnonfunctional_dispatch.h @@ -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 signbit(const at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/2c/2ca7b64b360528702bcdf425cbd6d038ba40b8067a4317b80ed54e0559e3587e/libmpc.la b/shared/package-files/2c/2ca7b64b360528702bcdf425cbd6d038ba40b8067a4317b80ed54e0559e3587e/libmpc.la new file mode 100644 index 0000000000000000000000000000000000000000..1c9c4340fc9b1e9bbd6644d53637f3600c41bc5f --- /dev/null +++ b/shared/package-files/2c/2ca7b64b360528702bcdf425cbd6d038ba40b8067a4317b80ed54e0559e3587e/libmpc.la @@ -0,0 +1,41 @@ +# libmpc.la - a libtool library file +# Generated by libtool (GNU libtool) 2.4.6 +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='libmpc.so.3' + +# Names of this library. +library_names='libmpc.so.3.1.0 libmpc.so.3 libmpc.so' + +# The name of the static archive. +old_library='libmpc.a' + +# Linker flags that cannot go in dependency_libs. +inherited_linker_flags='' + +# Libraries that this one depends upon. +dependency_libs=' -L/opt/conda/lib /opt/conda/lib/libmpfr.la /opt/conda/lib/libgmp.la -lm' + +# Names of additional weak libraries provided by this library +weak_library_names='' + +# Version information for libmpc. +current=4 +age=1 +revision=0 + +# Is this an already installed library? +installed=yes + +# Should we warn about portability when linking against -modules? +shouldnotlink=no + +# Files to dlopen/dlpreopen +dlopen='' +dlpreopen='' + +# Directory that this library needs to be installed in: +libdir='/opt/conda/lib' diff --git a/shared/package-files/2c/2ca8f54987a8d57a5f6234f25cf8e2890efec3bf871631a075e351947219ca49/cdc456 b/shared/package-files/2c/2ca8f54987a8d57a5f6234f25cf8e2890efec3bf871631a075e351947219ca49/cdc456 new file mode 100644 index 0000000000000000000000000000000000000000..a23755e2fb5cacbe213966c831a3aae79885617c Binary files /dev/null and b/shared/package-files/2c/2ca8f54987a8d57a5f6234f25cf8e2890efec3bf871631a075e351947219ca49/cdc456 differ diff --git a/shared/package-files/2c/2cac98404f592e3e4a8080d792b7131d045722081fa22bd7d78fd45489f9e980/parser.py b/shared/package-files/2c/2cac98404f592e3e4a8080d792b7131d045722081fa22bd7d78fd45489f9e980/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa7adfac842bfa5689fd1a41ae4017be1ebff6f --- /dev/null +++ b/shared/package-files/2c/2cac98404f592e3e4a8080d792b7131d045722081fa22bd7d78fd45489f9e980/parser.py @@ -0,0 +1,529 @@ +""" +This module started out as largely a copy paste from the stdlib's +optparse module with the features removed that we do not need from +optparse because we implement them in Click on a higher level (for +instance type handling, help formatting and a lot more). + +The plan is to remove more and more from here over time. + +The reason this is a different module and not optparse from the stdlib +is that there are differences in 2.x and 3.x about the error messages +generated and optparse in the stdlib uses gettext for no good reason +and might cause us issues. + +Click uses parts of optparse written by Gregory P. Ward and maintained +by the Python Software Foundation. This is limited to code in parser.py. + +Copyright 2001-2006 Gregory P. Ward. All rights reserved. +Copyright 2002-2006 Python Software Foundation. All rights reserved. +""" +# This code uses parts of optparse written by Gregory P. Ward and +# maintained by the Python Software Foundation. +# Copyright 2001-2006 Gregory P. Ward +# Copyright 2002-2006 Python Software Foundation +import typing as t +from collections import deque +from gettext import gettext as _ +from gettext import ngettext + +from .exceptions import BadArgumentUsage +from .exceptions import BadOptionUsage +from .exceptions import NoSuchOption +from .exceptions import UsageError + +if t.TYPE_CHECKING: + import typing_extensions as te + from .core import Argument as CoreArgument + from .core import Context + from .core import Option as CoreOption + from .core import Parameter as CoreParameter + +V = t.TypeVar("V") + +# Sentinel value that indicates an option was passed as a flag without a +# value but is not a flag option. Option.consume_value uses this to +# prompt or use the flag_value. +_flag_needs_value = object() + + +def _unpack_args( + args: t.Sequence[str], nargs_spec: t.Sequence[int] +) -> t.Tuple[t.Sequence[t.Union[str, t.Sequence[t.Optional[str]], None]], t.List[str]]: + """Given an iterable of arguments and an iterable of nargs specifications, + it returns a tuple with all the unpacked arguments at the first index + and all remaining arguments as the second. + + The nargs specification is the number of arguments that should be consumed + or `-1` to indicate that this position should eat up all the remainders. + + Missing items are filled with `None`. + """ + args = deque(args) + nargs_spec = deque(nargs_spec) + rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = [] + spos: t.Optional[int] = None + + def _fetch(c: "te.Deque[V]") -> t.Optional[V]: + try: + if spos is None: + return c.popleft() + else: + return c.pop() + except IndexError: + return None + + while nargs_spec: + nargs = _fetch(nargs_spec) + + if nargs is None: + continue + + if nargs == 1: + rv.append(_fetch(args)) + elif nargs > 1: + x = [_fetch(args) for _ in range(nargs)] + + # If we're reversed, we're pulling in the arguments in reverse, + # so we need to turn them around. + if spos is not None: + x.reverse() + + rv.append(tuple(x)) + elif nargs < 0: + if spos is not None: + raise TypeError("Cannot have two nargs < 0") + + spos = len(rv) + rv.append(None) + + # spos is the position of the wildcard (star). If it's not `None`, + # we fill it with the remainder. + if spos is not None: + rv[spos] = tuple(args) + args = [] + rv[spos + 1 :] = reversed(rv[spos + 1 :]) + + return tuple(rv), list(args) + + +def split_opt(opt: str) -> t.Tuple[str, str]: + first = opt[:1] + if first.isalnum(): + return "", opt + if opt[1:2] == first: + return opt[:2], opt[2:] + return first, opt[1:] + + +def normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str: + if ctx is None or ctx.token_normalize_func is None: + return opt + prefix, opt = split_opt(opt) + return f"{prefix}{ctx.token_normalize_func(opt)}" + + +def split_arg_string(string: str) -> t.List[str]: + """Split an argument string as with :func:`shlex.split`, but don't + fail if the string is incomplete. Ignores a missing closing quote or + incomplete escape sequence and uses the partial token as-is. + + .. code-block:: python + + split_arg_string("example 'my file") + ["example", "my file"] + + split_arg_string("example my\\") + ["example", "my"] + + :param string: String to split. + """ + import shlex + + lex = shlex.shlex(string, posix=True) + lex.whitespace_split = True + lex.commenters = "" + out = [] + + try: + for token in lex: + out.append(token) + except ValueError: + # Raised when end-of-string is reached in an invalid state. Use + # the partial token as-is. The quote or escape character is in + # lex.state, not lex.token. + out.append(lex.token) + + return out + + +class Option: + def __init__( + self, + obj: "CoreOption", + opts: t.Sequence[str], + dest: t.Optional[str], + action: t.Optional[str] = None, + nargs: int = 1, + const: t.Optional[t.Any] = None, + ): + self._short_opts = [] + self._long_opts = [] + self.prefixes: t.Set[str] = set() + + for opt in opts: + prefix, value = split_opt(opt) + if not prefix: + raise ValueError(f"Invalid start character for option ({opt})") + self.prefixes.add(prefix[0]) + if len(prefix) == 1 and len(value) == 1: + self._short_opts.append(opt) + else: + self._long_opts.append(opt) + self.prefixes.add(prefix) + + if action is None: + action = "store" + + self.dest = dest + self.action = action + self.nargs = nargs + self.const = const + self.obj = obj + + @property + def takes_value(self) -> bool: + return self.action in ("store", "append") + + def process(self, value: t.Any, state: "ParsingState") -> None: + if self.action == "store": + state.opts[self.dest] = value # type: ignore + elif self.action == "store_const": + state.opts[self.dest] = self.const # type: ignore + elif self.action == "append": + state.opts.setdefault(self.dest, []).append(value) # type: ignore + elif self.action == "append_const": + state.opts.setdefault(self.dest, []).append(self.const) # type: ignore + elif self.action == "count": + state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore + else: + raise ValueError(f"unknown action '{self.action}'") + state.order.append(self.obj) + + +class Argument: + def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1): + self.dest = dest + self.nargs = nargs + self.obj = obj + + def process( + self, + value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]], + state: "ParsingState", + ) -> None: + if self.nargs > 1: + assert value is not None + holes = sum(1 for x in value if x is None) + if holes == len(value): + value = None + elif holes != 0: + raise BadArgumentUsage( + _("Argument {name!r} takes {nargs} values.").format( + name=self.dest, nargs=self.nargs + ) + ) + + if self.nargs == -1 and self.obj.envvar is not None and value == (): + # Replace empty tuple with None so that a value from the + # environment may be tried. + value = None + + state.opts[self.dest] = value # type: ignore + state.order.append(self.obj) + + +class ParsingState: + def __init__(self, rargs: t.List[str]) -> None: + self.opts: t.Dict[str, t.Any] = {} + self.largs: t.List[str] = [] + self.rargs = rargs + self.order: t.List["CoreParameter"] = [] + + +class OptionParser: + """The option parser is an internal class that is ultimately used to + parse options and arguments. It's modelled after optparse and brings + a similar but vastly simplified API. It should generally not be used + directly as the high level Click classes wrap it for you. + + It's not nearly as extensible as optparse or argparse as it does not + implement features that are implemented on a higher level (such as + types or defaults). + + :param ctx: optionally the :class:`~click.Context` where this parser + should go with. + """ + + def __init__(self, ctx: t.Optional["Context"] = None) -> None: + #: The :class:`~click.Context` for this parser. This might be + #: `None` for some advanced use cases. + self.ctx = ctx + #: This controls how the parser deals with interspersed arguments. + #: If this is set to `False`, the parser will stop on the first + #: non-option. Click uses this to implement nested subcommands + #: safely. + self.allow_interspersed_args: bool = True + #: This tells the parser how to deal with unknown options. By + #: default it will error out (which is sensible), but there is a + #: second mode where it will ignore it and continue processing + #: after shifting all the unknown options into the resulting args. + self.ignore_unknown_options: bool = False + + if ctx is not None: + self.allow_interspersed_args = ctx.allow_interspersed_args + self.ignore_unknown_options = ctx.ignore_unknown_options + + self._short_opt: t.Dict[str, Option] = {} + self._long_opt: t.Dict[str, Option] = {} + self._opt_prefixes = {"-", "--"} + self._args: t.List[Argument] = [] + + def add_option( + self, + obj: "CoreOption", + opts: t.Sequence[str], + dest: t.Optional[str], + action: t.Optional[str] = None, + nargs: int = 1, + const: t.Optional[t.Any] = None, + ) -> None: + """Adds a new option named `dest` to the parser. The destination + is not inferred (unlike with optparse) and needs to be explicitly + provided. Action can be any of ``store``, ``store_const``, + ``append``, ``append_const`` or ``count``. + + The `obj` can be used to identify the option in the order list + that is returned from the parser. + """ + opts = [normalize_opt(opt, self.ctx) for opt in opts] + option = Option(obj, opts, dest, action=action, nargs=nargs, const=const) + self._opt_prefixes.update(option.prefixes) + for opt in option._short_opts: + self._short_opt[opt] = option + for opt in option._long_opts: + self._long_opt[opt] = option + + def add_argument( + self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1 + ) -> None: + """Adds a positional argument named `dest` to the parser. + + The `obj` can be used to identify the option in the order list + that is returned from the parser. + """ + self._args.append(Argument(obj, dest=dest, nargs=nargs)) + + def parse_args( + self, args: t.List[str] + ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]: + """Parses positional arguments and returns ``(values, args, order)`` + for the parsed options and arguments as well as the leftover + arguments if there are any. The order is a list of objects as they + appear on the command line. If arguments appear multiple times they + will be memorized multiple times as well. + """ + state = ParsingState(args) + try: + self._process_args_for_options(state) + self._process_args_for_args(state) + except UsageError: + if self.ctx is None or not self.ctx.resilient_parsing: + raise + return state.opts, state.largs, state.order + + def _process_args_for_args(self, state: ParsingState) -> None: + pargs, args = _unpack_args( + state.largs + state.rargs, [x.nargs for x in self._args] + ) + + for idx, arg in enumerate(self._args): + arg.process(pargs[idx], state) + + state.largs = args + state.rargs = [] + + def _process_args_for_options(self, state: ParsingState) -> None: + while state.rargs: + arg = state.rargs.pop(0) + arglen = len(arg) + # Double dashes always handled explicitly regardless of what + # prefixes are valid. + if arg == "--": + return + elif arg[:1] in self._opt_prefixes and arglen > 1: + self._process_opts(arg, state) + elif self.allow_interspersed_args: + state.largs.append(arg) + else: + state.rargs.insert(0, arg) + return + + # Say this is the original argument list: + # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] + # ^ + # (we are about to process arg(i)). + # + # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of + # [arg0, ..., arg(i-1)] (any options and their arguments will have + # been removed from largs). + # + # The while loop will usually consume 1 or more arguments per pass. + # If it consumes 1 (eg. arg is an option that takes no arguments), + # then after _process_arg() is done the situation is: + # + # largs = subset of [arg0, ..., arg(i)] + # rargs = [arg(i+1), ..., arg(N-1)] + # + # If allow_interspersed_args is false, largs will always be + # *empty* -- still a subset of [arg0, ..., arg(i-1)], but + # not a very interesting subset! + + def _match_long_opt( + self, opt: str, explicit_value: t.Optional[str], state: ParsingState + ) -> None: + if opt not in self._long_opt: + from difflib import get_close_matches + + possibilities = get_close_matches(opt, self._long_opt) + raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx) + + option = self._long_opt[opt] + if option.takes_value: + # At this point it's safe to modify rargs by injecting the + # explicit value, because no exception is raised in this + # branch. This means that the inserted value will be fully + # consumed. + if explicit_value is not None: + state.rargs.insert(0, explicit_value) + + value = self._get_value_from_state(opt, option, state) + + elif explicit_value is not None: + raise BadOptionUsage( + opt, _("Option {name!r} does not take a value.").format(name=opt) + ) + + else: + value = None + + option.process(value, state) + + def _match_short_opt(self, arg: str, state: ParsingState) -> None: + stop = False + i = 1 + prefix = arg[0] + unknown_options = [] + + for ch in arg[1:]: + opt = normalize_opt(f"{prefix}{ch}", self.ctx) + option = self._short_opt.get(opt) + i += 1 + + if not option: + if self.ignore_unknown_options: + unknown_options.append(ch) + continue + raise NoSuchOption(opt, ctx=self.ctx) + if option.takes_value: + # Any characters left in arg? Pretend they're the + # next arg, and stop consuming characters of arg. + if i < len(arg): + state.rargs.insert(0, arg[i:]) + stop = True + + value = self._get_value_from_state(opt, option, state) + + else: + value = None + + option.process(value, state) + + if stop: + break + + # If we got any unknown options we recombine the string of the + # remaining options and re-attach the prefix, then report that + # to the state as new larg. This way there is basic combinatorics + # that can be achieved while still ignoring unknown arguments. + if self.ignore_unknown_options and unknown_options: + state.largs.append(f"{prefix}{''.join(unknown_options)}") + + def _get_value_from_state( + self, option_name: str, option: Option, state: ParsingState + ) -> t.Any: + nargs = option.nargs + + if len(state.rargs) < nargs: + if option.obj._flag_needs_value: + # Option allows omitting the value. + value = _flag_needs_value + else: + raise BadOptionUsage( + option_name, + ngettext( + "Option {name!r} requires an argument.", + "Option {name!r} requires {nargs} arguments.", + nargs, + ).format(name=option_name, nargs=nargs), + ) + elif nargs == 1: + next_rarg = state.rargs[0] + + if ( + option.obj._flag_needs_value + and isinstance(next_rarg, str) + and next_rarg[:1] in self._opt_prefixes + and len(next_rarg) > 1 + ): + # The next arg looks like the start of an option, don't + # use it as the value if omitting the value is allowed. + value = _flag_needs_value + else: + value = state.rargs.pop(0) + else: + value = tuple(state.rargs[:nargs]) + del state.rargs[:nargs] + + return value + + def _process_opts(self, arg: str, state: ParsingState) -> None: + explicit_value = None + # Long option handling happens in two parts. The first part is + # supporting explicitly attached values. In any case, we will try + # to long match the option first. + if "=" in arg: + long_opt, explicit_value = arg.split("=", 1) + else: + long_opt = arg + norm_long_opt = normalize_opt(long_opt, self.ctx) + + # At this point we will match the (assumed) long option through + # the long option matching code. Note that this allows options + # like "-foo" to be matched as long options. + try: + self._match_long_opt(norm_long_opt, explicit_value, state) + except NoSuchOption: + # At this point the long option matching failed, and we need + # to try with short options. However there is a special rule + # which says, that if we have a two character options prefix + # (applies to "--foo" for instance), we do not dispatch to the + # short option code and will instead raise the no option + # error. + if arg[:2] not in self._opt_prefixes: + self._match_short_opt(arg, state) + return + + if not self.ignore_unknown_options: + raise + + state.largs.append(arg) diff --git a/shared/package-files/2c/2cacc292623160e48c0a408e0429725d10d844c93bcbf348dce58cdcd058b548/special_erfinv_ops.h b/shared/package-files/2c/2cacc292623160e48c0a408e0429725d10d844c93bcbf348dce58cdcd058b548/special_erfinv_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e7e2983dd345e6837f5d82a5b626491e7f40e7b9 --- /dev/null +++ b/shared/package-files/2c/2cacc292623160e48c0a408e0429725d10d844c93bcbf348dce58cdcd058b548/special_erfinv_ops.h @@ -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 special_erfinv { + 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::special_erfinv") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_erfinv(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 special_erfinv_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::special_erfinv") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_erfinv.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/2c/2cb078479575d76276d53695130438dd72006e85160c6873adefffb24cb425cd/checkpoint_utils.py b/shared/package-files/2c/2cb078479575d76276d53695130438dd72006e85160c6873adefffb24cb425cd/checkpoint_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7499575d81380b3513b344826e55d29aa738e9 --- /dev/null +++ b/shared/package-files/2c/2cb078479575d76276d53695130438dd72006e85160c6873adefffb24cb425cd/checkpoint_utils.py @@ -0,0 +1,51 @@ +# mypy: ignore-errors + +# Copyright (c) Meta Platforms, Inc. and affiliates + +import os +import shutil +import tempfile +from functools import wraps +from typing import Any, Callable, Dict, Optional, Tuple + +import torch.distributed as dist + + +def with_temp_dir( + func: Optional[Callable] = None, +) -> Optional[Callable]: + """ + Wrapper to initialize temp directory for distributed checkpoint. + """ + assert func is not None + + @wraps(func) + def wrapper(self, *args: Tuple[object], **kwargs: Dict[str, Any]) -> None: + if dist.is_initialized(): + # Only create temp_dir when rank is 0 + if dist.get_rank() == 0: + temp_dir = tempfile.mkdtemp() + print(f"Using temp directory: {temp_dir}") + else: + temp_dir = "" + object_list = [temp_dir] + + # Broadcast temp_dir to all the other ranks + os.sync() + dist.broadcast_object_list(object_list) + self.temp_dir = object_list[0] + os.sync() + else: + temp_dir = tempfile.mkdtemp() + print(f"No process group initialized, using temp directory: {temp_dir}") + self.temp_dir = temp_dir + + try: + func(self, *args, **kwargs) + finally: + if dist.is_initialized() and dist.get_rank() == 0: + shutil.rmtree(self.temp_dir, ignore_errors=True) + else: + shutil.rmtree(self.temp_dir, ignore_errors=True) + + return wrapper diff --git a/shared/package-files/2c/2cb79462d2648ff1019a4a7049f7e7a29c18fe5b0fa68a73bccfa45d03b083f2/_symtable.pyi b/shared/package-files/2c/2cb79462d2648ff1019a4a7049f7e7a29c18fe5b0fa68a73bccfa45d03b083f2/_symtable.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5b2370449c3174bd0f9c16f1ac885ae1992489e6 --- /dev/null +++ b/shared/package-files/2c/2cb79462d2648ff1019a4a7049f7e7a29c18fe5b0fa68a73bccfa45d03b083f2/_symtable.pyi @@ -0,0 +1,37 @@ +from typing import Dict, List + +CELL: int +DEF_BOUND: int +DEF_FREE: int +DEF_FREE_CLASS: int +DEF_GLOBAL: int +DEF_IMPORT: int +DEF_LOCAL: int +DEF_PARAM: int +FREE: int +GLOBAL_EXPLICIT: int +GLOBAL_IMPLICIT: int +LOCAL: int +OPT_BARE_EXEC: int +OPT_EXEC: int +OPT_IMPORT_STAR: int +SCOPE_MASK: int +SCOPE_OFF: int +TYPE_CLASS: int +TYPE_FUNCTION: int +TYPE_MODULE: int +USE: int + +class _symtable_entry(object): ... + +class symtable(object): + children: List[_symtable_entry] + id: int + lineno: int + name: str + nested: int + optimized: int + symbols: Dict[str, int] + type: int + varnames: List[str] + def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/shared/package-files/2c/2cb8d2f121625d7b8b11c0f604d7457468692967b9a291edbe7eca363f402112/top_level.txt b/shared/package-files/2c/2cb8d2f121625d7b8b11c0f604d7457468692967b9a291edbe7eca363f402112/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..723a22ca00a76ffd3df5b5513c78c751654f075c --- /dev/null +++ b/shared/package-files/2c/2cb8d2f121625d7b8b11c0f604d7457468692967b9a291edbe7eca363f402112/top_level.txt @@ -0,0 +1 @@ +wcwidth diff --git a/shared/package-files/2c/2cc589106028bd5ffa1488bc8e522ba9e577bb778c53db1d0cf6f7d8e2aea5e1/cartesian_prod_ops.h b/shared/package-files/2c/2cc589106028bd5ffa1488bc8e522ba9e577bb778c53db1d0cf6f7d8e2aea5e1/cartesian_prod_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..85d312cac632f4e20b3d6349ca6a27bdd6d3cba3 --- /dev/null +++ b/shared/package-files/2c/2cc589106028bd5ffa1488bc8e522ba9e577bb778c53db1d0cf6f7d8e2aea5e1/cartesian_prod_ops.h @@ -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 cartesian_prod { + using schema = at::Tensor (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cartesian_prod") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cartesian_prod(Tensor[] tensors) -> Tensor") + static at::Tensor call(at::TensorList tensors); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/2c/2cc9da2c5776eba119de9e03d5980e20219166463ab3b60cd16be5afaca5467d/dok.py b/shared/package-files/2c/2cc9da2c5776eba119de9e03d5980e20219166463ab3b60cd16be5afaca5467d/dok.py new file mode 100644 index 0000000000000000000000000000000000000000..847824456eaa3145d5ecb078e30251875168775b --- /dev/null +++ b/shared/package-files/2c/2cc9da2c5776eba119de9e03d5980e20219166463ab3b60cd16be5afaca5467d/dok.py @@ -0,0 +1,32 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'IndexMixin', + 'check_shape', + 'dok_matrix', + 'getdtype', + 'isdense', + 'isintlike', + 'isscalarlike', + 'isshape', + 'isspmatrix_dok', + 'itertools', + 'spmatrix', + 'upcast', + 'upcast_scalar', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="dok", + private_modules=["_dok"], all=__all__, + attribute=name) diff --git a/shared/package-files/2c/2ccc1eb81ad845c79250ecedb46db3c8a83dc811e1397c97c3a8b9dd9af18d92/upsample_nearest3d_backward_meta_dispatch.h b/shared/package-files/2c/2ccc1eb81ad845c79250ecedb46db3c8a83dc811e1397c97c3a8b9dd9af18d92/upsample_nearest3d_backward_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2e260aaf393dbde5eb16acebd676da1255cc9ca1 --- /dev/null +++ b/shared/package-files/2c/2ccc1eb81ad845c79250ecedb46db3c8a83dc811e1397c97c3a8b9dd9af18d92/upsample_nearest3d_backward_meta_dispatch.h @@ -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_nearest3d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor upsample_nearest3d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_nearest3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_nearest3d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); +TORCH_API at::Tensor & upsample_nearest3d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_nearest3d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/2c/2cce177d9d42ecc3dd343620aa1cb72261c869f208a784607ad0d57b5e2486fd/test_agraph.py b/shared/package-files/2c/2cce177d9d42ecc3dd343620aa1cb72261c869f208a784607ad0d57b5e2486fd/test_agraph.py new file mode 100644 index 0000000000000000000000000000000000000000..c99d29fbb74c63bbc38355ed3da51c4d7bb4419f --- /dev/null +++ b/shared/package-files/2c/2cce177d9d42ecc3dd343620aa1cb72261c869f208a784607ad0d57b5e2486fd/test_agraph.py @@ -0,0 +1,242 @@ +"""Unit tests for PyGraphviz interface.""" +import os +import tempfile + +import pytest + +pygraphviz = pytest.importorskip("pygraphviz") + + +import networkx as nx +from networkx.utils import edges_equal, graphs_equal, nodes_equal + + +class TestAGraph: + def build_graph(self, G): + edges = [("A", "B"), ("A", "C"), ("A", "C"), ("B", "C"), ("A", "D")] + G.add_edges_from(edges) + G.add_node("E") + G.graph["metal"] = "bronze" + return G + + def assert_equal(self, G1, G2): + assert nodes_equal(G1.nodes(), G2.nodes()) + assert edges_equal(G1.edges(), G2.edges()) + assert G1.graph["metal"] == G2.graph["metal"] + + def agraph_checks(self, G): + G = self.build_graph(G) + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + self.assert_equal(G, H) + + fd, fname = tempfile.mkstemp() + nx.drawing.nx_agraph.write_dot(H, fname) + Hin = nx.nx_agraph.read_dot(fname) + self.assert_equal(H, Hin) + os.close(fd) + os.unlink(fname) + + (fd, fname) = tempfile.mkstemp() + with open(fname, "w") as fh: + nx.drawing.nx_agraph.write_dot(H, fh) + + with open(fname) as fh: + Hin = nx.nx_agraph.read_dot(fh) + os.close(fd) + os.unlink(fname) + self.assert_equal(H, Hin) + + def test_from_agraph_name(self): + G = nx.Graph(name="test") + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + assert G.name == "test" + + @pytest.mark.parametrize( + "graph_class", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph) + ) + def test_from_agraph_create_using(self, graph_class): + G = nx.path_graph(3) + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A, create_using=graph_class) + assert isinstance(H, graph_class) + + def test_from_agraph_named_edges(self): + # Create an AGraph from an existing (non-multi) Graph + G = nx.Graph() + G.add_nodes_from([0, 1]) + A = nx.nx_agraph.to_agraph(G) + # Add edge (+ name, given by key) to the AGraph + A.add_edge(0, 1, key="foo") + # Verify a.name roundtrips out to 'key' in from_agraph + H = nx.nx_agraph.from_agraph(A) + assert isinstance(H, nx.Graph) + assert ("0", "1", {"key": "foo"}) in H.edges(data=True) + + def test_undirected(self): + self.agraph_checks(nx.Graph()) + + def test_directed(self): + self.agraph_checks(nx.DiGraph()) + + def test_multi_undirected(self): + self.agraph_checks(nx.MultiGraph()) + + def test_multi_directed(self): + self.agraph_checks(nx.MultiDiGraph()) + + def test_to_agraph_with_nodedata(self): + G = nx.Graph() + G.add_node(1, color="red") + A = nx.nx_agraph.to_agraph(G) + assert dict(A.nodes()[0].attr) == {"color": "red"} + + @pytest.mark.parametrize("graph_class", (nx.Graph, nx.MultiGraph)) + def test_to_agraph_with_edgedata(self, graph_class): + G = graph_class() + G.add_nodes_from([0, 1]) + G.add_edge(0, 1, color="yellow") + A = nx.nx_agraph.to_agraph(G) + assert dict(A.edges()[0].attr) == {"color": "yellow"} + + def test_view_pygraphviz_path(self, tmp_path): + G = nx.complete_graph(3) + input_path = str(tmp_path / "graph.png") + out_path, A = nx.nx_agraph.view_pygraphviz(G, path=input_path, show=False) + assert out_path == input_path + # Ensure file is not empty + with open(input_path, "rb") as fh: + data = fh.read() + assert len(data) > 0 + + def test_view_pygraphviz_file_suffix(self, tmp_path): + G = nx.complete_graph(3) + path, A = nx.nx_agraph.view_pygraphviz(G, suffix=1, show=False) + assert path[-6:] == "_1.png" + + def test_view_pygraphviz(self): + G = nx.Graph() # "An empty graph cannot be drawn." + pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G) + G = nx.barbell_graph(4, 6) + nx.nx_agraph.view_pygraphviz(G, show=False) + + def test_view_pygraphviz_edgelabel(self): + G = nx.Graph() + G.add_edge(1, 2, weight=7) + G.add_edge(2, 3, weight=8) + path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="weight", show=False) + for edge in A.edges(): + assert edge.attr["weight"] in ("7", "8") + + def test_view_pygraphviz_callable_edgelabel(self): + G = nx.complete_graph(3) + + def foo_label(data): + return "foo" + + path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel=foo_label, show=False) + for edge in A.edges(): + assert edge.attr["label"] == "foo" + + def test_view_pygraphviz_multigraph_edgelabels(self): + G = nx.MultiGraph() + G.add_edge(0, 1, key=0, name="left_fork") + G.add_edge(0, 1, key=1, name="right_fork") + path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="name", show=False) + edges = A.edges() + assert len(edges) == 2 + for edge in edges: + assert edge.attr["label"].strip() in ("left_fork", "right_fork") + + def test_graph_with_reserved_keywords(self): + # test attribute/keyword clash case for #1582 + # node: n + # edges: u,v + G = nx.Graph() + G = self.build_graph(G) + G.nodes["E"]["n"] = "keyword" + G.edges[("A", "B")]["u"] = "keyword" + G.edges[("A", "B")]["v"] = "keyword" + A = nx.nx_agraph.to_agraph(G) + + def test_view_pygraphviz_no_added_attrs_to_input(self): + G = nx.complete_graph(2) + path, A = nx.nx_agraph.view_pygraphviz(G, show=False) + assert G.graph == {} + + @pytest.mark.xfail(reason="known bug in clean_attrs") + def test_view_pygraphviz_leaves_input_graph_unmodified(self): + G = nx.complete_graph(2) + # Add entries to graph dict that to_agraph handles specially + G.graph["node"] = {"width": "0.80"} + G.graph["edge"] = {"fontsize": "14"} + path, A = nx.nx_agraph.view_pygraphviz(G, show=False) + assert G.graph == {"node": {"width": "0.80"}, "edge": {"fontsize": "14"}} + + def test_graph_with_AGraph_attrs(self): + G = nx.complete_graph(2) + # Add entries to graph dict that to_agraph handles specially + G.graph["node"] = {"width": "0.80"} + G.graph["edge"] = {"fontsize": "14"} + path, A = nx.nx_agraph.view_pygraphviz(G, show=False) + # Ensure user-specified values are not lost + assert dict(A.node_attr)["width"] == "0.80" + assert dict(A.edge_attr)["fontsize"] == "14" + + def test_round_trip_empty_graph(self): + G = nx.Graph() + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + # assert graphs_equal(G, H) + AA = nx.nx_agraph.to_agraph(H) + HH = nx.nx_agraph.from_agraph(AA) + assert graphs_equal(H, HH) + G.graph["graph"] = {} + G.graph["node"] = {} + G.graph["edge"] = {} + assert graphs_equal(G, HH) + + @pytest.mark.xfail(reason="integer->string node conversion in round trip") + def test_round_trip_integer_nodes(self): + G = nx.complete_graph(3) + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + assert graphs_equal(G, H) + + def test_graphviz_alias(self): + G = self.build_graph(nx.Graph()) + pos_graphviz = nx.nx_agraph.graphviz_layout(G) + pos_pygraphviz = nx.nx_agraph.pygraphviz_layout(G) + assert pos_graphviz == pos_pygraphviz + + @pytest.mark.parametrize("root", range(5)) + def test_pygraphviz_layout_root(self, root): + # NOTE: test depends on layout prog being deterministic + G = nx.complete_graph(5) + A = nx.nx_agraph.to_agraph(G) + # Get layout with root arg is not None + pygv_layout = nx.nx_agraph.pygraphviz_layout(G, prog="circo", root=root) + # Equivalent layout directly on AGraph + A.layout(args=f"-Groot={root}", prog="circo") + # Parse AGraph layout + a1_pos = tuple(float(v) for v in dict(A.get_node("1").attr)["pos"].split(",")) + assert pygv_layout[1] == a1_pos + + def test_2d_layout(self): + G = nx.Graph() + G = self.build_graph(G) + G.graph["dimen"] = 2 + pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato") + pos = list(pos.values()) + assert len(pos) == 5 + assert len(pos[0]) == 2 + + def test_3d_layout(self): + G = nx.Graph() + G = self.build_graph(G) + G.graph["dimen"] = 3 + pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato") + pos = list(pos.values()) + assert len(pos) == 5 + assert len(pos[0]) == 3 diff --git a/shared/package-files/2c/2ccf10763f929471b86663185334d237f6bef3528ecad54979931de05f9f704c/filter.R b/shared/package-files/2c/2ccf10763f929471b86663185334d237f6bef3528ecad54979931de05f9f704c/filter.R new file mode 100644 index 0000000000000000000000000000000000000000..46d406f722dcd359e4d5389b42b2b63059cb612b --- /dev/null +++ b/shared/package-files/2c/2ccf10763f929471b86663185334d237f6bef3528ecad54979931de05f9f704c/filter.R @@ -0,0 +1,49 @@ +library(R2nparray) + +x <- c(-50, 175, 149, 214, 247, 237, 225, 329, 729, 809, 530, 489, 540, 457, + 195, 176, 337, 239, 128, 102, 232, 429, 3, 98, 43, -141, -77, -13, + 125, 361, -45, 184) +x <- ts(x, start=c(1951, 1), frequency=4) + + +conv2 <- filter(x, c(.75, .25), method="convolution") + +conv1 <- filter(x, c(.75, .25), method="convolution", sides=1) + +recurse <- filter(x, c(.75, .25), method="recursive") + +recurse.init <- filter(x, c(.75, .25), method="recursive", init=c(150, 100)) + +conv2.odd <- filter(x, c(.75, .5, .3, .2, .1), method="convolution", + sides=2) +conv1.odd <- filter(x, c(.75, .5, .3, .2, .1), method="convolution", + sides=1) +recurse.odd <- filter(x, c(.75, .5, .3, .2, .1), method="recursive", + init=c(150, 100, 125, 135, 145)) + +# missing values + +x[10] = NaN + +conv2.na <- filter(x, c(.75, .25), method="convolution") + +conv1.na <- filter(x, c(.75, .25), method="convolution", sides=1) + +recurse.na <- filter(x, c(.75, .25), method="recursive") + +recurse.init.na <- filter(x, c(.75, .25), method="recursive", init=c(150, 100)) + + +options(digits=12) + +R2nparray(list(conv2=as.numeric(conv2), conv1=as.numeric(conv1), + recurse=as.numeric(recurse), + recurse_init=as.numeric(recurse.init), + conv2_na=as.numeric(conv2.na), conv1_na=as.numeric(conv1.na), + recurse_na=as.numeric(recurse.na), + recurse_init_na=as.numeric(recurse.init.na), + conv2_odd=as.numeric(conv2.odd), + conv1_odd=as.numeric(conv1.odd), + recurse_odd=as.numeric(recurse.odd)), + fname="filter_results.py") + diff --git a/shared/package-files/2c/2ccf23110a3b1bbecfc698eeb09ec4a831105b86076291326fbc6713a46b11ac/strdispatch.py b/shared/package-files/2c/2ccf23110a3b1bbecfc698eeb09ec4a831105b86076291326fbc6713a46b11ac/strdispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..d6bf510535ed339becbaeaf2c81d9464f57ccbd7 --- /dev/null +++ b/shared/package-files/2c/2ccf23110a3b1bbecfc698eeb09ec4a831105b86076291326fbc6713a46b11ac/strdispatch.py @@ -0,0 +1,68 @@ +"""String dispatch class to match regexps and dispatch commands. +""" + +# Stdlib imports +import re + +# Our own modules +from IPython.core.hooks import CommandChainDispatcher + +# Code begins +class StrDispatch(object): + """Dispatch (lookup) a set of strings / regexps for match. + + Example: + + >>> dis = StrDispatch() + >>> dis.add_s('hei',34, priority = 4) + >>> dis.add_s('hei',123, priority = 2) + >>> dis.add_re('h.i', 686) + >>> print(list(dis.flat_matches('hei'))) + [123, 34, 686] + """ + + def __init__(self): + self.strs = {} + self.regexs = {} + + def add_s(self, s, obj, priority= 0 ): + """ Adds a target 'string' for dispatching """ + + chain = self.strs.get(s, CommandChainDispatcher()) + chain.add(obj,priority) + self.strs[s] = chain + + def add_re(self, regex, obj, priority= 0 ): + """ Adds a target regexp for dispatching """ + + chain = self.regexs.get(regex, CommandChainDispatcher()) + chain.add(obj,priority) + self.regexs[regex] = chain + + def dispatch(self, key): + """ Get a seq of Commandchain objects that match key """ + if key in self.strs: + yield self.strs[key] + + for r, obj in self.regexs.items(): + if re.match(r, key): + yield obj + else: + #print "nomatch",key # dbg + pass + + def __repr__(self): + return "" % (self.strs, self.regexs) + + def s_matches(self, key): + if key not in self.strs: + return + for el in self.strs[key]: + yield el[1] + + def flat_matches(self, key): + """ Yield all 'value' targets, without priority """ + for val in self.dispatch(key): + for el in val: + yield el[1] # only value, no priority + return diff --git a/shared/package-files/2c/2cd18a7ccb2762fc089a34f2cd7acb84c3871c3bbba88ebb45b60d2afbc8d792/Bermuda b/shared/package-files/2c/2cd18a7ccb2762fc089a34f2cd7acb84c3871c3bbba88ebb45b60d2afbc8d792/Bermuda new file mode 100644 index 0000000000000000000000000000000000000000..527524ed295aba41b9a0448ffd7993c489a2cb99 Binary files /dev/null and b/shared/package-files/2c/2cd18a7ccb2762fc089a34f2cd7acb84c3871c3bbba88ebb45b60d2afbc8d792/Bermuda differ diff --git a/shared/package-files/2c/2cd39fd9526c575ec50d3f688040db6ba95ae35e325269b9cffec1f7b9cb376e/test_infer_objects.py b/shared/package-files/2c/2cd39fd9526c575ec50d3f688040db6ba95ae35e325269b9cffec1f7b9cb376e/test_infer_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..a824a615b5c297c13afeedeba600c1a0ba986695 --- /dev/null +++ b/shared/package-files/2c/2cd39fd9526c575ec50d3f688040db6ba95ae35e325269b9cffec1f7b9cb376e/test_infer_objects.py @@ -0,0 +1,42 @@ +from datetime import datetime + +from pandas import DataFrame +import pandas._testing as tm + + +class TestInferObjects: + def test_infer_objects(self): + # GH#11221 + df = DataFrame( + { + "a": ["a", 1, 2, 3], + "b": ["b", 2.0, 3.0, 4.1], + "c": [ + "c", + datetime(2016, 1, 1), + datetime(2016, 1, 2), + datetime(2016, 1, 3), + ], + "d": [1, 2, 3, "d"], + }, + columns=["a", "b", "c", "d"], + ) + df = df.iloc[1:].infer_objects() + + assert df["a"].dtype == "int64" + assert df["b"].dtype == "float64" + assert df["c"].dtype == "M8[ns]" + assert df["d"].dtype == "object" + + expected = DataFrame( + { + "a": [1, 2, 3], + "b": [2.0, 3.0, 4.1], + "c": [datetime(2016, 1, 1), datetime(2016, 1, 2), datetime(2016, 1, 3)], + "d": [2, 3, "d"], + }, + columns=["a", "b", "c", "d"], + ) + # reconstruct frame to verify inference is same + result = df.reset_index(drop=True) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/2c/2cd53a5c59dfbb7eaae092bc04f037dc894d9a30bab25080640d9e2553467882/multinomial.py b/shared/package-files/2c/2cd53a5c59dfbb7eaae092bc04f037dc894d9a30bab25080640d9e2553467882/multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..3f316e823a79577c4cd42b2b1a23264844232663 --- /dev/null +++ b/shared/package-files/2c/2cd53a5c59dfbb7eaae092bc04f037dc894d9a30bab25080640d9e2553467882/multinomial.py @@ -0,0 +1,135 @@ +import torch +from torch import inf +from torch.distributions import Categorical, constraints +from torch.distributions.binomial import Binomial +from torch.distributions.distribution import Distribution +from torch.distributions.utils import broadcast_all + +__all__ = ["Multinomial"] + + +class Multinomial(Distribution): + r""" + Creates a Multinomial distribution parameterized by :attr:`total_count` and + either :attr:`probs` or :attr:`logits` (but not both). The innermost dimension of + :attr:`probs` indexes over categories. All other dimensions index over batches. + + Note that :attr:`total_count` need not be specified if only :meth:`log_prob` is + called (see example below) + + .. 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. + + - :meth:`sample` requires a single shared `total_count` for all + parameters and samples. + - :meth:`log_prob` allows different `total_count` for each parameter and + sample. + + Example:: + + >>> # xdoctest: +SKIP("FIXME: found invalid values") + >>> m = Multinomial(100, torch.tensor([ 1., 1., 1., 1.])) + >>> x = m.sample() # equal probability of 0, 1, 2, 3 + tensor([ 21., 24., 30., 25.]) + + >>> Multinomial(probs=torch.tensor([1., 1., 1., 1.])).log_prob(x) + tensor([-4.1338]) + + Args: + total_count (int): number of trials + probs (Tensor): event probabilities + logits (Tensor): event log probabilities (unnormalized) + """ + arg_constraints = {"probs": constraints.simplex, "logits": constraints.real_vector} + total_count: int + + @property + def mean(self): + return self.probs * self.total_count + + @property + def variance(self): + return self.total_count * self.probs * (1 - self.probs) + + def __init__(self, total_count=1, probs=None, logits=None, validate_args=None): + if not isinstance(total_count, int): + raise NotImplementedError("inhomogeneous total_count is not supported") + self.total_count = total_count + self._categorical = Categorical(probs=probs, logits=logits) + self._binomial = Binomial(total_count=total_count, probs=self.probs) + batch_shape = self._categorical.batch_shape + event_shape = self._categorical.param_shape[-1:] + super().__init__(batch_shape, event_shape, validate_args=validate_args) + + def expand(self, batch_shape, _instance=None): + new = self._get_checked_instance(Multinomial, _instance) + batch_shape = torch.Size(batch_shape) + new.total_count = self.total_count + new._categorical = self._categorical.expand(batch_shape) + super(Multinomial, new).__init__( + batch_shape, self.event_shape, validate_args=False + ) + new._validate_args = self._validate_args + return new + + def _new(self, *args, **kwargs): + return self._categorical._new(*args, **kwargs) + + @constraints.dependent_property(is_discrete=True, event_dim=1) + def support(self): + return constraints.multinomial(self.total_count) + + @property + def logits(self): + return self._categorical.logits + + @property + def probs(self): + return self._categorical.probs + + @property + def param_shape(self): + return self._categorical.param_shape + + def sample(self, sample_shape=torch.Size()): + sample_shape = torch.Size(sample_shape) + samples = self._categorical.sample( + torch.Size((self.total_count,)) + sample_shape + ) + # samples.shape is (total_count, sample_shape, batch_shape), need to change it to + # (sample_shape, batch_shape, total_count) + shifted_idx = list(range(samples.dim())) + shifted_idx.append(shifted_idx.pop(0)) + samples = samples.permute(*shifted_idx) + counts = samples.new(self._extended_shape(sample_shape)).zero_() + counts.scatter_add_(-1, samples, torch.ones_like(samples)) + return counts.type_as(self.probs) + + def entropy(self): + n = torch.tensor(self.total_count) + + cat_entropy = self._categorical.entropy() + term1 = n * cat_entropy - torch.lgamma(n + 1) + + support = self._binomial.enumerate_support(expand=False)[1:] + binomial_probs = torch.exp(self._binomial.log_prob(support)) + weights = torch.lgamma(support + 1) + term2 = (binomial_probs * weights).sum([0, -1]) + + return term1 + term2 + + def log_prob(self, value): + if self._validate_args: + self._validate_sample(value) + logits, value = broadcast_all(self.logits, value) + logits = logits.clone(memory_format=torch.contiguous_format) + log_factorial_n = torch.lgamma(value.sum(-1) + 1) + log_factorial_xs = torch.lgamma(value + 1).sum(-1) + logits[(value == 0) & (logits == -inf)] = 0 + log_powers = (logits * value).sum(-1) + return log_factorial_n - log_factorial_xs + log_powers diff --git a/shared/package-files/2c/2cd8aba1b4724471b0e8f6c8a8c7ff98a0540144992528c0183466455041452e/_foreach_neg_cuda_dispatch.h b/shared/package-files/2c/2cd8aba1b4724471b0e8f6c8a8c7ff98a0540144992528c0183466455041452e/_foreach_neg_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2712134847d4fea3c58c91f02a0251ba627f2eb5 --- /dev/null +++ b/shared/package-files/2c/2cd8aba1b4724471b0e8f6c8a8c7ff98a0540144992528c0183466455041452e/_foreach_neg_cuda_dispatch.h @@ -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_neg(at::TensorList self); +TORCH_API void _foreach_neg_(at::TensorList self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/2c/2cd998c783a9ce38db2ec8d81ceadde2fc496632a6f69127b6aeb7237996b6d7/test_value_counts.py b/shared/package-files/2c/2cd998c783a9ce38db2ec8d81ceadde2fc496632a6f69127b6aeb7237996b6d7/test_value_counts.py new file mode 100644 index 0000000000000000000000000000000000000000..859010d9c79c64fbac70f2f5eaa0033bddb4a0c2 --- /dev/null +++ b/shared/package-files/2c/2cd998c783a9ce38db2ec8d81ceadde2fc496632a6f69127b6aeb7237996b6d7/test_value_counts.py @@ -0,0 +1,271 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Categorical, + CategoricalIndex, + Index, + Series, +) +import pandas._testing as tm + + +class TestSeriesValueCounts: + def test_value_counts_datetime(self, unit): + # most dtypes are tested in tests/base + values = [ + pd.Timestamp("2011-01-01 09:00"), + pd.Timestamp("2011-01-01 10:00"), + pd.Timestamp("2011-01-01 11:00"), + pd.Timestamp("2011-01-01 09:00"), + pd.Timestamp("2011-01-01 09:00"), + pd.Timestamp("2011-01-01 11:00"), + ] + + exp_idx = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 11:00", "2011-01-01 10:00"], + name="xxx", + ).as_unit(unit) + exp = Series([3, 2, 1], index=exp_idx, name="count") + + ser = Series(values, name="xxx").dt.as_unit(unit) + tm.assert_series_equal(ser.value_counts(), exp) + # check DatetimeIndex outputs the same result + idx = pd.DatetimeIndex(values, name="xxx").as_unit(unit) + tm.assert_series_equal(idx.value_counts(), exp) + + # normalize + exp = Series(np.array([3.0, 2.0, 1]) / 6.0, index=exp_idx, name="proportion") + tm.assert_series_equal(ser.value_counts(normalize=True), exp) + tm.assert_series_equal(idx.value_counts(normalize=True), exp) + + def test_value_counts_datetime_tz(self, unit): + values = [ + pd.Timestamp("2011-01-01 09:00", tz="US/Eastern"), + pd.Timestamp("2011-01-01 10:00", tz="US/Eastern"), + pd.Timestamp("2011-01-01 11:00", tz="US/Eastern"), + pd.Timestamp("2011-01-01 09:00", tz="US/Eastern"), + pd.Timestamp("2011-01-01 09:00", tz="US/Eastern"), + pd.Timestamp("2011-01-01 11:00", tz="US/Eastern"), + ] + + exp_idx = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 11:00", "2011-01-01 10:00"], + tz="US/Eastern", + name="xxx", + ).as_unit(unit) + exp = Series([3, 2, 1], index=exp_idx, name="count") + + ser = Series(values, name="xxx").dt.as_unit(unit) + tm.assert_series_equal(ser.value_counts(), exp) + idx = pd.DatetimeIndex(values, name="xxx").as_unit(unit) + tm.assert_series_equal(idx.value_counts(), exp) + + exp = Series(np.array([3.0, 2.0, 1]) / 6.0, index=exp_idx, name="proportion") + tm.assert_series_equal(ser.value_counts(normalize=True), exp) + tm.assert_series_equal(idx.value_counts(normalize=True), exp) + + def test_value_counts_period(self): + values = [ + pd.Period("2011-01", freq="M"), + pd.Period("2011-02", freq="M"), + pd.Period("2011-03", freq="M"), + pd.Period("2011-01", freq="M"), + pd.Period("2011-01", freq="M"), + pd.Period("2011-03", freq="M"), + ] + + exp_idx = pd.PeriodIndex( + ["2011-01", "2011-03", "2011-02"], freq="M", name="xxx" + ) + exp = Series([3, 2, 1], index=exp_idx, name="count") + + ser = Series(values, name="xxx") + tm.assert_series_equal(ser.value_counts(), exp) + # check DatetimeIndex outputs the same result + idx = pd.PeriodIndex(values, name="xxx") + tm.assert_series_equal(idx.value_counts(), exp) + + # normalize + exp = Series(np.array([3.0, 2.0, 1]) / 6.0, index=exp_idx, name="proportion") + tm.assert_series_equal(ser.value_counts(normalize=True), exp) + tm.assert_series_equal(idx.value_counts(normalize=True), exp) + + def test_value_counts_categorical_ordered(self): + # most dtypes are tested in tests/base + values = Categorical([1, 2, 3, 1, 1, 3], ordered=True) + + exp_idx = CategoricalIndex( + [1, 3, 2], categories=[1, 2, 3], ordered=True, name="xxx" + ) + exp = Series([3, 2, 1], index=exp_idx, name="count") + + ser = Series(values, name="xxx") + tm.assert_series_equal(ser.value_counts(), exp) + # check CategoricalIndex outputs the same result + idx = CategoricalIndex(values, name="xxx") + tm.assert_series_equal(idx.value_counts(), exp) + + # normalize + exp = Series(np.array([3.0, 2.0, 1]) / 6.0, index=exp_idx, name="proportion") + tm.assert_series_equal(ser.value_counts(normalize=True), exp) + tm.assert_series_equal(idx.value_counts(normalize=True), exp) + + def test_value_counts_categorical_not_ordered(self): + values = Categorical([1, 2, 3, 1, 1, 3], ordered=False) + + exp_idx = CategoricalIndex( + [1, 3, 2], categories=[1, 2, 3], ordered=False, name="xxx" + ) + exp = Series([3, 2, 1], index=exp_idx, name="count") + + ser = Series(values, name="xxx") + tm.assert_series_equal(ser.value_counts(), exp) + # check CategoricalIndex outputs the same result + idx = CategoricalIndex(values, name="xxx") + tm.assert_series_equal(idx.value_counts(), exp) + + # normalize + exp = Series(np.array([3.0, 2.0, 1]) / 6.0, index=exp_idx, name="proportion") + tm.assert_series_equal(ser.value_counts(normalize=True), exp) + tm.assert_series_equal(idx.value_counts(normalize=True), exp) + + def test_value_counts_categorical(self): + # GH#12835 + cats = Categorical(list("abcccb"), categories=list("cabd")) + ser = Series(cats, name="xxx") + res = ser.value_counts(sort=False) + + exp_index = CategoricalIndex( + list("cabd"), categories=cats.categories, name="xxx" + ) + exp = Series([3, 1, 2, 0], name="count", index=exp_index) + tm.assert_series_equal(res, exp) + + res = ser.value_counts(sort=True) + + exp_index = CategoricalIndex( + list("cbad"), categories=cats.categories, name="xxx" + ) + exp = Series([3, 2, 1, 0], name="count", index=exp_index) + tm.assert_series_equal(res, exp) + + # check object dtype handles the Series.name as the same + # (tested in tests/base) + ser = Series(["a", "b", "c", "c", "c", "b"], name="xxx") + res = ser.value_counts() + exp = Series([3, 2, 1], name="count", index=Index(["c", "b", "a"], name="xxx")) + tm.assert_series_equal(res, exp) + + def test_value_counts_categorical_with_nan(self): + # see GH#9443 + + # sanity check + ser = Series(["a", "b", "a"], dtype="category") + exp = Series([2, 1], index=CategoricalIndex(["a", "b"]), name="count") + + res = ser.value_counts(dropna=True) + tm.assert_series_equal(res, exp) + + res = ser.value_counts(dropna=True) + tm.assert_series_equal(res, exp) + + # same Series via two different constructions --> same behaviour + series = [ + Series(["a", "b", None, "a", None, None], dtype="category"), + Series( + Categorical(["a", "b", None, "a", None, None], categories=["a", "b"]) + ), + ] + + for ser in series: + # None is a NaN value, so we exclude its count here + exp = Series([2, 1], index=CategoricalIndex(["a", "b"]), name="count") + res = ser.value_counts(dropna=True) + tm.assert_series_equal(res, exp) + + # we don't exclude the count of None and sort by counts + exp = Series( + [3, 2, 1], index=CategoricalIndex([np.nan, "a", "b"]), name="count" + ) + res = ser.value_counts(dropna=False) + tm.assert_series_equal(res, exp) + + # When we aren't sorting by counts, and np.nan isn't a + # category, it should be last. + exp = Series( + [2, 1, 3], index=CategoricalIndex(["a", "b", np.nan]), name="count" + ) + res = ser.value_counts(dropna=False, sort=False) + tm.assert_series_equal(res, exp) + + @pytest.mark.parametrize( + "ser, dropna, exp", + [ + ( + Series([False, True, True, pd.NA]), + False, + Series([2, 1, 1], index=[True, False, pd.NA], name="count"), + ), + ( + Series([False, True, True, pd.NA]), + True, + Series([2, 1], index=Index([True, False], dtype=object), name="count"), + ), + ( + Series(range(3), index=[True, False, np.nan]).index, + False, + Series([1, 1, 1], index=[True, False, np.nan], name="count"), + ), + ], + ) + def test_value_counts_bool_with_nan(self, ser, dropna, exp): + # GH32146 + out = ser.value_counts(dropna=dropna) + tm.assert_series_equal(out, exp) + + @pytest.mark.parametrize( + "input_array,expected", + [ + ( + [1 + 1j, 1 + 1j, 1, 3j, 3j, 3j], + Series( + [3, 2, 1], + index=Index([3j, 1 + 1j, 1], dtype=np.complex128), + name="count", + ), + ), + ( + np.array([1 + 1j, 1 + 1j, 1, 3j, 3j, 3j], dtype=np.complex64), + Series( + [3, 2, 1], + index=Index([3j, 1 + 1j, 1], dtype=np.complex64), + name="count", + ), + ), + ], + ) + def test_value_counts_complex_numbers(self, input_array, expected): + # GH 17927 + result = Series(input_array).value_counts() + tm.assert_series_equal(result, expected) + + def test_value_counts_masked(self): + # GH#54984 + dtype = "Int64" + ser = Series([1, 2, None, 2, None, 3], dtype=dtype) + result = ser.value_counts(dropna=False) + expected = Series( + [2, 2, 1, 1], + index=Index([2, None, 1, 3], dtype=dtype), + dtype=dtype, + name="count", + ) + tm.assert_series_equal(result, expected) + + result = ser.value_counts(dropna=True) + expected = Series( + [2, 1, 1], index=Index([2, 1, 3], dtype=dtype), dtype=dtype, name="count" + ) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/ibm3163 b/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/ibm3163 new file mode 100644 index 0000000000000000000000000000000000000000..dad679d25c87441556402d9d75aae7ed19602945 Binary files /dev/null and b/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/ibm3163 differ diff --git a/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/wy60-316X b/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/wy60-316X new file mode 100644 index 0000000000000000000000000000000000000000..dad679d25c87441556402d9d75aae7ed19602945 Binary files /dev/null and b/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/wy60-316X differ diff --git a/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/wyse60-316X b/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/wyse60-316X new file mode 100644 index 0000000000000000000000000000000000000000..dad679d25c87441556402d9d75aae7ed19602945 Binary files /dev/null and b/shared/package-files/2c/2cdb3226e270731e2b119108a9002329270de68bfb237fcb5ca71eec53c460f8/wyse60-316X differ diff --git a/shared/package-files/2c/2ce20f34659a95f3cb2fb0cd01a88b0a9e09fc6d6666951899308dc77923aa0c/test_spin.py b/shared/package-files/2c/2ce20f34659a95f3cb2fb0cd01a88b0a9e09fc6d6666951899308dc77923aa0c/test_spin.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc038e656b55d6d041ae10eeea09a5d3ba05f04 --- /dev/null +++ b/shared/package-files/2c/2ce20f34659a95f3cb2fb0cd01a88b0a9e09fc6d6666951899308dc77923aa0c/test_spin.py @@ -0,0 +1,4303 @@ +from sympy.concrete.summations import Sum +from sympy.core.function import expand +from sympy.core.numbers import (I, Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.dense import Matrix +from sympy.abc import alpha, beta, gamma, j, m +from sympy.physics.quantum import hbar, represent, Commutator, InnerProduct +from sympy.physics.quantum.qapply import qapply +from sympy.physics.quantum.tensorproduct import TensorProduct +from sympy.physics.quantum.cg import CG +from sympy.physics.quantum.spin import ( + Jx, Jy, Jz, Jplus, Jminus, J2, + JxBra, JyBra, JzBra, + JxKet, JyKet, JzKet, + JxKetCoupled, JyKetCoupled, JzKetCoupled, + couple, uncouple, + Rotation, WignerD +) + +from sympy.testing.pytest import raises, slow + +j1, j2, j3, j4, m1, m2, m3, m4 = symbols('j1:5 m1:5') +j12, j13, j24, j34, j123, j134, mi, mi1, mp = symbols( + 'j12 j13 j24 j34 j123 j134 mi mi1 mp') + + +def test_represent_spin_operators(): + assert represent(Jx) == hbar*Matrix([[0, 1], [1, 0]])/2 + assert represent( + Jx, j=1) == hbar*sqrt(2)*Matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]])/2 + assert represent(Jy) == hbar*I*Matrix([[0, -1], [1, 0]])/2 + assert represent(Jy, j=1) == hbar*I*sqrt(2)*Matrix([[0, -1, 0], [1, + 0, -1], [0, 1, 0]])/2 + assert represent(Jz) == hbar*Matrix([[1, 0], [0, -1]])/2 + assert represent( + Jz, j=1) == hbar*Matrix([[1, 0, 0], [0, 0, 0], [0, 0, -1]]) + + +def test_represent_spin_states(): + # Jx basis + assert represent(JxKet(S.Half, S.Half), basis=Jx) == Matrix([1, 0]) + assert represent(JxKet(S.Half, Rational(-1, 2)), basis=Jx) == Matrix([0, 1]) + assert represent(JxKet(1, 1), basis=Jx) == Matrix([1, 0, 0]) + assert represent(JxKet(1, 0), basis=Jx) == Matrix([0, 1, 0]) + assert represent(JxKet(1, -1), basis=Jx) == Matrix([0, 0, 1]) + assert represent( + JyKet(S.Half, S.Half), basis=Jx) == Matrix([exp(-I*pi/4), 0]) + assert represent( + JyKet(S.Half, Rational(-1, 2)), basis=Jx) == Matrix([0, exp(I*pi/4)]) + assert represent(JyKet(1, 1), basis=Jx) == Matrix([-I, 0, 0]) + assert represent(JyKet(1, 0), basis=Jx) == Matrix([0, 1, 0]) + assert represent(JyKet(1, -1), basis=Jx) == Matrix([0, 0, I]) + assert represent( + JzKet(S.Half, S.Half), basis=Jx) == sqrt(2)*Matrix([-1, 1])/2 + assert represent( + JzKet(S.Half, Rational(-1, 2)), basis=Jx) == sqrt(2)*Matrix([-1, -1])/2 + assert represent(JzKet(1, 1), basis=Jx) == Matrix([1, -sqrt(2), 1])/2 + assert represent(JzKet(1, 0), basis=Jx) == sqrt(2)*Matrix([1, 0, -1])/2 + assert represent(JzKet(1, -1), basis=Jx) == Matrix([1, sqrt(2), 1])/2 + # Jy basis + assert represent( + JxKet(S.Half, S.Half), basis=Jy) == Matrix([exp(I*pi*Rational(-3, 4)), 0]) + assert represent( + JxKet(S.Half, Rational(-1, 2)), basis=Jy) == Matrix([0, exp(I*pi*Rational(3, 4))]) + assert represent(JxKet(1, 1), basis=Jy) == Matrix([I, 0, 0]) + assert represent(JxKet(1, 0), basis=Jy) == Matrix([0, 1, 0]) + assert represent(JxKet(1, -1), basis=Jy) == Matrix([0, 0, -I]) + assert represent(JyKet(S.Half, S.Half), basis=Jy) == Matrix([1, 0]) + assert represent(JyKet(S.Half, Rational(-1, 2)), basis=Jy) == Matrix([0, 1]) + assert represent(JyKet(1, 1), basis=Jy) == Matrix([1, 0, 0]) + assert represent(JyKet(1, 0), basis=Jy) == Matrix([0, 1, 0]) + assert represent(JyKet(1, -1), basis=Jy) == Matrix([0, 0, 1]) + assert represent( + JzKet(S.Half, S.Half), basis=Jy) == sqrt(2)*Matrix([-1, I])/2 + assert represent( + JzKet(S.Half, Rational(-1, 2)), basis=Jy) == sqrt(2)*Matrix([I, -1])/2 + assert represent(JzKet(1, 1), basis=Jy) == Matrix([1, -I*sqrt(2), -1])/2 + assert represent( + JzKet(1, 0), basis=Jy) == Matrix([-sqrt(2)*I, 0, -sqrt(2)*I])/2 + assert represent(JzKet(1, -1), basis=Jy) == Matrix([-1, -sqrt(2)*I, 1])/2 + # Jz basis + assert represent( + JxKet(S.Half, S.Half), basis=Jz) == sqrt(2)*Matrix([1, 1])/2 + assert represent( + JxKet(S.Half, Rational(-1, 2)), basis=Jz) == sqrt(2)*Matrix([-1, 1])/2 + assert represent(JxKet(1, 1), basis=Jz) == Matrix([1, sqrt(2), 1])/2 + assert represent(JxKet(1, 0), basis=Jz) == sqrt(2)*Matrix([-1, 0, 1])/2 + assert represent(JxKet(1, -1), basis=Jz) == Matrix([1, -sqrt(2), 1])/2 + assert represent( + JyKet(S.Half, S.Half), basis=Jz) == sqrt(2)*Matrix([-1, -I])/2 + assert represent( + JyKet(S.Half, Rational(-1, 2)), basis=Jz) == sqrt(2)*Matrix([-I, -1])/2 + assert represent(JyKet(1, 1), basis=Jz) == Matrix([1, sqrt(2)*I, -1])/2 + assert represent(JyKet(1, 0), basis=Jz) == sqrt(2)*Matrix([I, 0, I])/2 + assert represent(JyKet(1, -1), basis=Jz) == Matrix([-1, sqrt(2)*I, 1])/2 + assert represent(JzKet(S.Half, S.Half), basis=Jz) == Matrix([1, 0]) + assert represent(JzKet(S.Half, Rational(-1, 2)), basis=Jz) == Matrix([0, 1]) + assert represent(JzKet(1, 1), basis=Jz) == Matrix([1, 0, 0]) + assert represent(JzKet(1, 0), basis=Jz) == Matrix([0, 1, 0]) + assert represent(JzKet(1, -1), basis=Jz) == Matrix([0, 0, 1]) + + +def test_represent_uncoupled_states(): + # Jx basis + assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jx) == \ + Matrix([1, 0, 0, 0]) + assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jx) == \ + Matrix([0, 1, 0, 0]) + assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jx) == \ + Matrix([0, 0, 1, 0]) + assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jx) == \ + Matrix([0, 0, 0, 1]) + assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jx) == \ + Matrix([-I, 0, 0, 0]) + assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jx) == \ + Matrix([0, 1, 0, 0]) + assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jx) == \ + Matrix([0, 0, 1, 0]) + assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jx) == \ + Matrix([0, 0, 0, I]) + assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jx) == \ + Matrix([S.Half, Rational(-1, 2), Rational(-1, 2), S.Half]) + assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jx) == \ + Matrix([S.Half, S.Half, Rational(-1, 2), Rational(-1, 2)]) + assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jx) == \ + Matrix([S.Half, Rational(-1, 2), S.Half, Rational(-1, 2)]) + assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jx) == \ + Matrix([S.Half, S.Half, S.Half, S.Half]) + # Jy basis + assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jy) == \ + Matrix([I, 0, 0, 0]) + assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jy) == \ + Matrix([0, 1, 0, 0]) + assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jy) == \ + Matrix([0, 0, 1, 0]) + assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jy) == \ + Matrix([0, 0, 0, -I]) + assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jy) == \ + Matrix([1, 0, 0, 0]) + assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jy) == \ + Matrix([0, 1, 0, 0]) + assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jy) == \ + Matrix([0, 0, 1, 0]) + assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jy) == \ + Matrix([0, 0, 0, 1]) + assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jy) == \ + Matrix([S.Half, -I/2, -I/2, Rational(-1, 2)]) + assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jy) == \ + Matrix([-I/2, S.Half, Rational(-1, 2), -I/2]) + assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jy) == \ + Matrix([-I/2, Rational(-1, 2), S.Half, -I/2]) + assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jy) == \ + Matrix([Rational(-1, 2), -I/2, -I/2, S.Half]) + # Jz basis + assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jz) == \ + Matrix([S.Half, S.Half, S.Half, S.Half]) + assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jz) == \ + Matrix([Rational(-1, 2), S.Half, Rational(-1, 2), S.Half]) + assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jz) == \ + Matrix([Rational(-1, 2), Rational(-1, 2), S.Half, S.Half]) + assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jz) == \ + Matrix([S.Half, Rational(-1, 2), Rational(-1, 2), S.Half]) + assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jz) == \ + Matrix([S.Half, I/2, I/2, Rational(-1, 2)]) + assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jz) == \ + Matrix([I/2, S.Half, Rational(-1, 2), I/2]) + assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jz) == \ + Matrix([I/2, Rational(-1, 2), S.Half, I/2]) + assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jz) == \ + Matrix([Rational(-1, 2), I/2, I/2, S.Half]) + assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jz) == \ + Matrix([1, 0, 0, 0]) + assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jz) == \ + Matrix([0, 1, 0, 0]) + assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jz) == \ + Matrix([0, 0, 1, 0]) + assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jz) == \ + Matrix([0, 0, 0, 1]) + + +def test_represent_coupled_states(): + # Jx basis + assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \ + Matrix([1, 0, 0, 0]) + assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, 1, 0, 0]) + assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, 0, 1, 0]) + assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, 0, 0, 1]) + assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \ + Matrix([1, 0, 0, 0]) + assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, -I, 0, 0]) + assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, 0, 1, 0]) + assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, 0, 0, I]) + assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \ + Matrix([1, 0, 0, 0]) + assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, S.Half, -sqrt(2)/2, S.Half]) + assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, sqrt(2)/2, 0, -sqrt(2)/2]) + assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \ + Matrix([0, S.Half, sqrt(2)/2, S.Half]) + # Jy basis + assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \ + Matrix([1, 0, 0, 0]) + assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, I, 0, 0]) + assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, 0, 1, 0]) + assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, 0, 0, -I]) + assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \ + Matrix([1, 0, 0, 0]) + assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, 1, 0, 0]) + assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, 0, 1, 0]) + assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, 0, 0, 1]) + assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \ + Matrix([1, 0, 0, 0]) + assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, S.Half, -I*sqrt(2)/2, Rational(-1, 2)]) + assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, -I*sqrt(2)/2, 0, -I*sqrt(2)/2]) + assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \ + Matrix([0, Rational(-1, 2), -I*sqrt(2)/2, S.Half]) + # Jz basis + assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \ + Matrix([1, 0, 0, 0]) + assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, S.Half, sqrt(2)/2, S.Half]) + assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, -sqrt(2)/2, 0, sqrt(2)/2]) + assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, S.Half, -sqrt(2)/2, S.Half]) + assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \ + Matrix([1, 0, 0, 0]) + assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, S.Half, I*sqrt(2)/2, Rational(-1, 2)]) + assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, I*sqrt(2)/2, 0, I*sqrt(2)/2]) + assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, Rational(-1, 2), I*sqrt(2)/2, S.Half]) + assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \ + Matrix([1, 0, 0, 0]) + assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, 1, 0, 0]) + assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, 0, 1, 0]) + assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \ + Matrix([0, 0, 0, 1]) + + +def test_represent_rotation(): + assert represent(Rotation(0, pi/2, 0)) == \ + Matrix( + [[WignerD( + S( + 1)/2, S( + 1)/2, S( + 1)/2, 0, pi/2, 0), WignerD( + S.Half, S.Half, Rational(-1, 2), 0, pi/2, 0)], + [WignerD(S.Half, Rational(-1, 2), S.Half, 0, pi/2, 0), WignerD(S.Half, Rational(-1, 2), Rational(-1, 2), 0, pi/2, 0)]]) + assert represent(Rotation(0, pi/2, 0), doit=True) == \ + Matrix([[sqrt(2)/2, -sqrt(2)/2], + [sqrt(2)/2, sqrt(2)/2]]) + + +def test_rewrite_same(): + # Rewrite to same basis + assert JxBra(1, 1).rewrite('Jx') == JxBra(1, 1) + assert JxBra(j, m).rewrite('Jx') == JxBra(j, m) + assert JxKet(1, 1).rewrite('Jx') == JxKet(1, 1) + assert JxKet(j, m).rewrite('Jx') == JxKet(j, m) + + +def test_rewrite_Bra(): + # Numerical + assert JxBra(1, 1).rewrite('Jy') == -I*JyBra(1, 1) + assert JxBra(1, 0).rewrite('Jy') == JyBra(1, 0) + assert JxBra(1, -1).rewrite('Jy') == I*JyBra(1, -1) + assert JxBra(1, 1).rewrite( + 'Jz') == JzBra(1, 1)/2 + JzBra(1, 0)/sqrt(2) + JzBra(1, -1)/2 + assert JxBra( + 1, 0).rewrite('Jz') == -sqrt(2)*JzBra(1, 1)/2 + sqrt(2)*JzBra(1, -1)/2 + assert JxBra(1, -1).rewrite( + 'Jz') == JzBra(1, 1)/2 - JzBra(1, 0)/sqrt(2) + JzBra(1, -1)/2 + assert JyBra(1, 1).rewrite('Jx') == I*JxBra(1, 1) + assert JyBra(1, 0).rewrite('Jx') == JxBra(1, 0) + assert JyBra(1, -1).rewrite('Jx') == -I*JxBra(1, -1) + assert JyBra(1, 1).rewrite( + 'Jz') == JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, 0)/2 - JzBra(1, -1)/2 + assert JyBra(1, 0).rewrite( + 'Jz') == -sqrt(2)*I*JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, -1)/2 + assert JyBra(1, -1).rewrite( + 'Jz') == -JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, 0)/2 + JzBra(1, -1)/2 + assert JzBra(1, 1).rewrite( + 'Jx') == JxBra(1, 1)/2 - sqrt(2)*JxBra(1, 0)/2 + JxBra(1, -1)/2 + assert JzBra( + 1, 0).rewrite('Jx') == sqrt(2)*JxBra(1, 1)/2 - sqrt(2)*JxBra(1, -1)/2 + assert JzBra(1, -1).rewrite( + 'Jx') == JxBra(1, 1)/2 + sqrt(2)*JxBra(1, 0)/2 + JxBra(1, -1)/2 + assert JzBra(1, 1).rewrite( + 'Jy') == JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, 0)/2 - JyBra(1, -1)/2 + assert JzBra(1, 0).rewrite( + 'Jy') == sqrt(2)*I*JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, -1)/2 + assert JzBra(1, -1).rewrite( + 'Jy') == -JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, 0)/2 + JyBra(1, -1)/2 + # Symbolic + assert JxBra(j, m).rewrite('Jy') == Sum( + WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyBra(j, mi), (mi, -j, j)) + assert JxBra(j, m).rewrite('Jz') == Sum( + WignerD(j, mi, m, 0, pi/2, 0) * JzBra(j, mi), (mi, -j, j)) + assert JyBra(j, m).rewrite('Jx') == Sum( + WignerD(j, mi, m, 0, 0, pi/2) * JxBra(j, mi), (mi, -j, j)) + assert JyBra(j, m).rewrite('Jz') == Sum( + WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzBra(j, mi), (mi, -j, j)) + assert JzBra(j, m).rewrite('Jx') == Sum( + WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxBra(j, mi), (mi, -j, j)) + assert JzBra(j, m).rewrite('Jy') == Sum( + WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyBra(j, mi), (mi, -j, j)) + + +def test_rewrite_Ket(): + # Numerical + assert JxKet(1, 1).rewrite('Jy') == I*JyKet(1, 1) + assert JxKet(1, 0).rewrite('Jy') == JyKet(1, 0) + assert JxKet(1, -1).rewrite('Jy') == -I*JyKet(1, -1) + assert JxKet(1, 1).rewrite( + 'Jz') == JzKet(1, 1)/2 + JzKet(1, 0)/sqrt(2) + JzKet(1, -1)/2 + assert JxKet( + 1, 0).rewrite('Jz') == -sqrt(2)*JzKet(1, 1)/2 + sqrt(2)*JzKet(1, -1)/2 + assert JxKet(1, -1).rewrite( + 'Jz') == JzKet(1, 1)/2 - JzKet(1, 0)/sqrt(2) + JzKet(1, -1)/2 + assert JyKet(1, 1).rewrite('Jx') == -I*JxKet(1, 1) + assert JyKet(1, 0).rewrite('Jx') == JxKet(1, 0) + assert JyKet(1, -1).rewrite('Jx') == I*JxKet(1, -1) + assert JyKet(1, 1).rewrite( + 'Jz') == JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, 0)/2 - JzKet(1, -1)/2 + assert JyKet(1, 0).rewrite( + 'Jz') == sqrt(2)*I*JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, -1)/2 + assert JyKet(1, -1).rewrite( + 'Jz') == -JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, 0)/2 + JzKet(1, -1)/2 + assert JzKet(1, 1).rewrite( + 'Jx') == JxKet(1, 1)/2 - sqrt(2)*JxKet(1, 0)/2 + JxKet(1, -1)/2 + assert JzKet( + 1, 0).rewrite('Jx') == sqrt(2)*JxKet(1, 1)/2 - sqrt(2)*JxKet(1, -1)/2 + assert JzKet(1, -1).rewrite( + 'Jx') == JxKet(1, 1)/2 + sqrt(2)*JxKet(1, 0)/2 + JxKet(1, -1)/2 + assert JzKet(1, 1).rewrite( + 'Jy') == JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, 0)/2 - JyKet(1, -1)/2 + assert JzKet(1, 0).rewrite( + 'Jy') == -sqrt(2)*I*JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, -1)/2 + assert JzKet(1, -1).rewrite( + 'Jy') == -JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, 0)/2 + JyKet(1, -1)/2 + # Symbolic + assert JxKet(j, m).rewrite('Jy') == Sum( + WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyKet(j, mi), (mi, -j, j)) + assert JxKet(j, m).rewrite('Jz') == Sum( + WignerD(j, mi, m, 0, pi/2, 0) * JzKet(j, mi), (mi, -j, j)) + assert JyKet(j, m).rewrite('Jx') == Sum( + WignerD(j, mi, m, 0, 0, pi/2) * JxKet(j, mi), (mi, -j, j)) + assert JyKet(j, m).rewrite('Jz') == Sum( + WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzKet(j, mi), (mi, -j, j)) + assert JzKet(j, m).rewrite('Jx') == Sum( + WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxKet(j, mi), (mi, -j, j)) + assert JzKet(j, m).rewrite('Jy') == Sum( + WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j, mi), (mi, -j, j)) + + +def test_rewrite_uncoupled_state(): + # Numerical + assert TensorProduct(JyKet(1, 1), JxKet( + 1, 1)).rewrite('Jx') == -I*TensorProduct(JxKet(1, 1), JxKet(1, 1)) + assert TensorProduct(JyKet(1, 0), JxKet( + 1, 1)).rewrite('Jx') == TensorProduct(JxKet(1, 0), JxKet(1, 1)) + assert TensorProduct(JyKet(1, -1), JxKet( + 1, 1)).rewrite('Jx') == I*TensorProduct(JxKet(1, -1), JxKet(1, 1)) + assert TensorProduct(JzKet(1, 1), JxKet(1, 1)).rewrite('Jx') == \ + TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 - sqrt(2)*TensorProduct(JxKet( + 1, 0), JxKet(1, 1))/2 + TensorProduct(JxKet(1, 1), JxKet(1, 1))/2 + assert TensorProduct(JzKet(1, 0), JxKet(1, 1)).rewrite('Jx') == \ + -sqrt(2)*TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 + sqrt( + 2)*TensorProduct(JxKet(1, 1), JxKet(1, 1))/2 + assert TensorProduct(JzKet(1, -1), JxKet(1, 1)).rewrite('Jx') == \ + TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 + sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, 1))/2 + TensorProduct(JxKet(1, 1), JxKet(1, 1))/2 + assert TensorProduct(JxKet(1, 1), JyKet( + 1, 1)).rewrite('Jy') == I*TensorProduct(JyKet(1, 1), JyKet(1, 1)) + assert TensorProduct(JxKet(1, 0), JyKet( + 1, 1)).rewrite('Jy') == TensorProduct(JyKet(1, 0), JyKet(1, 1)) + assert TensorProduct(JxKet(1, -1), JyKet( + 1, 1)).rewrite('Jy') == -I*TensorProduct(JyKet(1, -1), JyKet(1, 1)) + assert TensorProduct(JzKet(1, 1), JyKet(1, 1)).rewrite('Jy') == \ + -TensorProduct(JyKet(1, -1), JyKet(1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2 + TensorProduct(JyKet(1, 1), JyKet(1, 1))/2 + assert TensorProduct(JzKet(1, 0), JyKet(1, 1)).rewrite('Jy') == \ + -sqrt(2)*I*TensorProduct(JyKet(1, -1), JyKet( + 1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 1), JyKet(1, 1))/2 + assert TensorProduct(JzKet(1, -1), JyKet(1, 1)).rewrite('Jy') == \ + TensorProduct(JyKet(1, -1), JyKet(1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2 - TensorProduct(JyKet(1, 1), JyKet(1, 1))/2 + assert TensorProduct(JxKet(1, 1), JzKet(1, 1)).rewrite('Jz') == \ + TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2 + assert TensorProduct(JxKet(1, 0), JzKet(1, 1)).rewrite('Jz') == \ + sqrt(2)*TensorProduct(JzKet(1, -1), JzKet( + 1, 1))/2 - sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 1))/2 + assert TensorProduct(JxKet(1, -1), JzKet(1, 1)).rewrite('Jz') == \ + TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 - sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2 + assert TensorProduct(JyKet(1, 1), JzKet(1, 1)).rewrite('Jz') == \ + -TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2 + assert TensorProduct(JyKet(1, 0), JzKet(1, 1)).rewrite('Jz') == \ + sqrt(2)*I*TensorProduct(JzKet(1, -1), JzKet( + 1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 1), JzKet(1, 1))/2 + assert TensorProduct(JyKet(1, -1), JzKet(1, 1)).rewrite('Jz') == \ + TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 - TensorProduct(JzKet(1, 1), JzKet(1, 1))/2 + # Symbolic + assert TensorProduct(JyKet(j1, m1), JxKet(j2, m2)).rewrite('Jy') == \ + TensorProduct(JyKet(j1, m1), Sum( + WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0) * JyKet(j2, mi), (mi, -j2, j2))) + assert TensorProduct(JzKet(j1, m1), JxKet(j2, m2)).rewrite('Jz') == \ + TensorProduct(JzKet(j1, m1), Sum( + WignerD(j2, mi, m2, 0, pi/2, 0) * JzKet(j2, mi), (mi, -j2, j2))) + assert TensorProduct(JxKet(j1, m1), JyKet(j2, m2)).rewrite('Jx') == \ + TensorProduct(JxKet(j1, m1), Sum( + WignerD(j2, mi, m2, 0, 0, pi/2) * JxKet(j2, mi), (mi, -j2, j2))) + assert TensorProduct(JzKet(j1, m1), JyKet(j2, m2)).rewrite('Jz') == \ + TensorProduct(JzKet(j1, m1), Sum(WignerD( + j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) * JzKet(j2, mi), (mi, -j2, j2))) + assert TensorProduct(JxKet(j1, m1), JzKet(j2, m2)).rewrite('Jx') == \ + TensorProduct(JxKet(j1, m1), Sum( + WignerD(j2, mi, m2, 0, pi*Rational(3, 2), 0) * JxKet(j2, mi), (mi, -j2, j2))) + assert TensorProduct(JyKet(j1, m1), JzKet(j2, m2)).rewrite('Jy') == \ + TensorProduct(JyKet(j1, m1), Sum(WignerD( + j2, mi, m2, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j2, mi), (mi, -j2, j2))) + + +def test_rewrite_coupled_state(): + # Numerical + assert JyKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jx') == \ + JxKetCoupled(0, 0, (S.Half, S.Half)) + assert JyKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jx') == \ + -I*JxKetCoupled(1, 1, (S.Half, S.Half)) + assert JyKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jx') == \ + JxKetCoupled(1, 0, (S.Half, S.Half)) + assert JyKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jx') == \ + I*JxKetCoupled(1, -1, (S.Half, S.Half)) + assert JzKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jx') == \ + JxKetCoupled(0, 0, (S.Half, S.Half)) + assert JzKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jx') == \ + JxKetCoupled(1, 1, (S.Half, S.Half))/2 - sqrt(2)*JxKetCoupled(1, 0, ( + S.Half, S.Half))/2 + JxKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JzKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jx') == \ + sqrt(2)*JxKetCoupled(1, 1, (S( + 1)/2, S.Half))/2 - sqrt(2)*JxKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JzKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jx') == \ + JxKetCoupled(1, 1, (S.Half, S.Half))/2 + sqrt(2)*JxKetCoupled(1, 0, ( + S.Half, S.Half))/2 + JxKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JxKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jy') == \ + JyKetCoupled(0, 0, (S.Half, S.Half)) + assert JxKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jy') == \ + I*JyKetCoupled(1, 1, (S.Half, S.Half)) + assert JxKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jy') == \ + JyKetCoupled(1, 0, (S.Half, S.Half)) + assert JxKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jy') == \ + -I*JyKetCoupled(1, -1, (S.Half, S.Half)) + assert JzKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jy') == \ + JyKetCoupled(0, 0, (S.Half, S.Half)) + assert JzKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jy') == \ + JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(2)*JyKetCoupled(1, 0, ( + S.Half, S.Half))/2 - JyKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JzKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jy') == \ + -I*sqrt(2)*JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt( + 2)*JyKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JzKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jy') == \ + -JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(2)*JyKetCoupled(1, 0, (S.Half, S.Half))/2 + JyKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JxKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jz') == \ + JzKetCoupled(0, 0, (S.Half, S.Half)) + assert JxKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jz') == \ + JzKetCoupled(1, 1, (S.Half, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, ( + S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JxKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jz') == \ + -sqrt(2)*JzKetCoupled(1, 1, (S( + 1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JxKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jz') == \ + JzKetCoupled(1, 1, (S.Half, S.Half))/2 - sqrt(2)*JzKetCoupled(1, 0, ( + S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JyKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jz') == \ + JzKetCoupled(0, 0, (S.Half, S.Half)) + assert JyKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jz') == \ + JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(2)*JzKetCoupled(1, 0, ( + S.Half, S.Half))/2 - JzKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JyKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jz') == \ + I*sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt( + 2)*JzKetCoupled(1, -1, (S.Half, S.Half))/2 + assert JyKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jz') == \ + -JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2 + # Symbolic + assert JyKetCoupled(j, m, (j1, j2)).rewrite('Jx') == \ + Sum(WignerD(j, mi, m, 0, 0, pi/2) * JxKetCoupled(j, mi, ( + j1, j2)), (mi, -j, j)) + assert JzKetCoupled(j, m, (j1, j2)).rewrite('Jx') == \ + Sum(WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxKetCoupled(j, mi, ( + j1, j2)), (mi, -j, j)) + assert JxKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \ + Sum(WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyKetCoupled(j, mi, ( + j1, j2)), (mi, -j, j)) + assert JzKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \ + Sum(WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyKetCoupled(j, + mi, (j1, j2)), (mi, -j, j)) + assert JxKetCoupled(j, m, (j1, j2)).rewrite('Jz') == \ + Sum(WignerD(j, mi, m, 0, pi/2, 0) * JzKetCoupled(j, mi, ( + j1, j2)), (mi, -j, j)) + assert JyKetCoupled(j, m, (j1, j2)).rewrite('Jz') == \ + Sum(WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzKetCoupled( + j, mi, (j1, j2)), (mi, -j, j)) + + +def test_innerproducts_of_rewritten_states(): + # Numerical + assert qapply(JxBra(1, 1)*JxKet(1, 1).rewrite('Jy')).doit() == 1 + assert qapply(JxBra(1, 0)*JxKet(1, 0).rewrite('Jy')).doit() == 1 + assert qapply(JxBra(1, -1)*JxKet(1, -1).rewrite('Jy')).doit() == 1 + assert qapply(JxBra(1, 1)*JxKet(1, 1).rewrite('Jz')).doit() == 1 + assert qapply(JxBra(1, 0)*JxKet(1, 0).rewrite('Jz')).doit() == 1 + assert qapply(JxBra(1, -1)*JxKet(1, -1).rewrite('Jz')).doit() == 1 + assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jx')).doit() == 1 + assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jx')).doit() == 1 + assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jx')).doit() == 1 + assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jz')).doit() == 1 + assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jz')).doit() == 1 + assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jz')).doit() == 1 + assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jz')).doit() == 1 + assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jz')).doit() == 1 + assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jz')).doit() == 1 + assert qapply(JzBra(1, 1)*JzKet(1, 1).rewrite('Jy')).doit() == 1 + assert qapply(JzBra(1, 0)*JzKet(1, 0).rewrite('Jy')).doit() == 1 + assert qapply(JzBra(1, -1)*JzKet(1, -1).rewrite('Jy')).doit() == 1 + assert qapply(JxBra(1, 1)*JxKet(1, 0).rewrite('Jy')).doit() == 0 + assert qapply(JxBra(1, 1)*JxKet(1, -1).rewrite('Jy')) == 0 + assert qapply(JxBra(1, 1)*JxKet(1, 0).rewrite('Jz')).doit() == 0 + assert qapply(JxBra(1, 1)*JxKet(1, -1).rewrite('Jz')) == 0 + assert qapply(JyBra(1, 1)*JyKet(1, 0).rewrite('Jx')).doit() == 0 + assert qapply(JyBra(1, 1)*JyKet(1, -1).rewrite('Jx')) == 0 + assert qapply(JyBra(1, 1)*JyKet(1, 0).rewrite('Jz')).doit() == 0 + assert qapply(JyBra(1, 1)*JyKet(1, -1).rewrite('Jz')) == 0 + assert qapply(JzBra(1, 1)*JzKet(1, 0).rewrite('Jx')).doit() == 0 + assert qapply(JzBra(1, 1)*JzKet(1, -1).rewrite('Jx')) == 0 + assert qapply(JzBra(1, 1)*JzKet(1, 0).rewrite('Jy')).doit() == 0 + assert qapply(JzBra(1, 1)*JzKet(1, -1).rewrite('Jy')) == 0 + assert qapply(JxBra(1, 0)*JxKet(1, 1).rewrite('Jy')) == 0 + assert qapply(JxBra(1, 0)*JxKet(1, -1).rewrite('Jy')) == 0 + assert qapply(JxBra(1, 0)*JxKet(1, 1).rewrite('Jz')) == 0 + assert qapply(JxBra(1, 0)*JxKet(1, -1).rewrite('Jz')) == 0 + assert qapply(JyBra(1, 0)*JyKet(1, 1).rewrite('Jx')) == 0 + assert qapply(JyBra(1, 0)*JyKet(1, -1).rewrite('Jx')) == 0 + assert qapply(JyBra(1, 0)*JyKet(1, 1).rewrite('Jz')) == 0 + assert qapply(JyBra(1, 0)*JyKet(1, -1).rewrite('Jz')) == 0 + assert qapply(JzBra(1, 0)*JzKet(1, 1).rewrite('Jx')) == 0 + assert qapply(JzBra(1, 0)*JzKet(1, -1).rewrite('Jx')) == 0 + assert qapply(JzBra(1, 0)*JzKet(1, 1).rewrite('Jy')) == 0 + assert qapply(JzBra(1, 0)*JzKet(1, -1).rewrite('Jy')) == 0 + assert qapply(JxBra(1, -1)*JxKet(1, 1).rewrite('Jy')) == 0 + assert qapply(JxBra(1, -1)*JxKet(1, 0).rewrite('Jy')).doit() == 0 + assert qapply(JxBra(1, -1)*JxKet(1, 1).rewrite('Jz')) == 0 + assert qapply(JxBra(1, -1)*JxKet(1, 0).rewrite('Jz')).doit() == 0 + assert qapply(JyBra(1, -1)*JyKet(1, 1).rewrite('Jx')) == 0 + assert qapply(JyBra(1, -1)*JyKet(1, 0).rewrite('Jx')).doit() == 0 + assert qapply(JyBra(1, -1)*JyKet(1, 1).rewrite('Jz')) == 0 + assert qapply(JyBra(1, -1)*JyKet(1, 0).rewrite('Jz')).doit() == 0 + assert qapply(JzBra(1, -1)*JzKet(1, 1).rewrite('Jx')) == 0 + assert qapply(JzBra(1, -1)*JzKet(1, 0).rewrite('Jx')).doit() == 0 + assert qapply(JzBra(1, -1)*JzKet(1, 1).rewrite('Jy')) == 0 + assert qapply(JzBra(1, -1)*JzKet(1, 0).rewrite('Jy')).doit() == 0 + + +def test_uncouple_2_coupled_states(): + # j1=1/2, j2=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) ))) + # j1=1/2, j2=1 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1)) == \ + expand(uncouple( + couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0)) == \ + expand(uncouple( + couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1)) == \ + expand(uncouple( + couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)) == \ + expand(uncouple( + couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)) == \ + expand(uncouple( + couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)) == \ + expand(uncouple( + couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)) ))) + # j1=1, j2=1 + assert TensorProduct(JzKet(1, 1), JzKet(1, 1)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, 1)) ))) + assert TensorProduct(JzKet(1, 1), JzKet(1, 0)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, 0)) ))) + assert TensorProduct(JzKet(1, 1), JzKet(1, -1)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, -1)) ))) + assert TensorProduct(JzKet(1, 0), JzKet(1, 1)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, 1)) ))) + assert TensorProduct(JzKet(1, 0), JzKet(1, 0)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, 0)) ))) + assert TensorProduct(JzKet(1, 0), JzKet(1, -1)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, -1)) ))) + assert TensorProduct(JzKet(1, -1), JzKet(1, 1)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, 1)) ))) + assert TensorProduct(JzKet(1, -1), JzKet(1, 0)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, 0)) ))) + assert TensorProduct(JzKet(1, -1), JzKet(1, -1)) == \ + expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, -1)) ))) + + +def test_uncouple_3_coupled_states(): + # Default coupling + # j1=1/2, j2=1/2, j3=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.NegativeOne/ + 2), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) ))) + # j1=1/2, j2=1, j3=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) ))) + # Coupling j1+j3=j13, j13+j2=j + # j1=1/2, j2=1/2, j3=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + # j1=1/2, j2=1, j3=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + 1)/2), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + 1)/2), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + 1)/2), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + 1)/2), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + 1)/2), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + 1)/2), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + -1)/2), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + -1)/2), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + -1)/2), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + -1)/2), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S( + -1)/2), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.NegativeOne/ + 2), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ))) + + +@slow +def test_uncouple_4_coupled_states(): + # j1=1/2, j2=1/2, j3=1/2, j4=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S( + 1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S( + 1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S( + 1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S( + 1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S( + 1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) ))) + # j1=1/2, j2=1/2, j3=1, j4=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), + JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), + JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), + JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), + JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), + JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet( + S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) ))) + # Couple j1+j3=j13, j2+j4=j24, j13+j24=j + # j1=1/2, j2=1/2, j3=1/2, j4=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + # j1=1/2, j2=1/2, j3=1, j4=1/2 + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) ))) + assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \ + expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) ))) + + +def test_uncouple_2_coupled_states_numerical(): + # j1=1/2, j2=1/2 + assert uncouple(JzKetCoupled(0, 0, (S.Half, S.Half))) == \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/2 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/2 + assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half))) == \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) + assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half))) == \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/2 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/2 + assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half))) == \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) + # j1=1, j2=1/2 + assert uncouple(JzKetCoupled(S.Half, S.Half, (1, S.Half))) == \ + -sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))/3 + \ + sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))/3 + assert uncouple(JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half))) == \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))/3 - \ + sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half))) == \ + TensorProduct(JzKet(1, 1), JzKet(S.Half, S.Half)) + assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))) == \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))/3 + \ + sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))) == \ + sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half))) == \ + TensorProduct(JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) + # j1=1, j2=1 + assert uncouple(JzKetCoupled(0, 0, (1, 1))) == \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/3 - \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/3 + assert uncouple(JzKetCoupled(1, 1, (1, 1))) == \ + sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 - \ + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + assert uncouple(JzKetCoupled(1, 0, (1, 1))) == \ + sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/2 - \ + sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + assert uncouple(JzKetCoupled(1, -1, (1, 1))) == \ + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 - \ + sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 0))/2 + assert uncouple(JzKetCoupled(2, 2, (1, 1))) == \ + TensorProduct(JzKet(1, 1), JzKet(1, 1)) + assert uncouple(JzKetCoupled(2, 1, (1, 1))) == \ + sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \ + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + assert uncouple(JzKetCoupled(2, 0, (1, 1))) == \ + sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/6 + \ + sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, 0))/3 + \ + sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/6 + assert uncouple(JzKetCoupled(2, -1, (1, 1))) == \ + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 + \ + sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 0))/2 + assert uncouple(JzKetCoupled(2, -2, (1, 1))) == \ + TensorProduct(JzKet(1, -1), JzKet(1, -1)) + + +def test_uncouple_3_coupled_states_numerical(): + # Default coupling + # j1=1/2, j2=1/2, j3=1/2 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half))) == \ + TensorProduct(JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) + assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half))) == \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))/3 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/3 + \ + sqrt(3)*TensorProduct(JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half))) == \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/3 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/3 + \ + sqrt(3)*TensorProduct(JzKet( + S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half))) == \ + TensorProduct(JzKet( + S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) + # j1=1/2, j2=1/2, j3=1 + assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1))) == \ + TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)) + assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1))) == \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \ + sqrt(2)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/2 + assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1))) == \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))/3 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/3 + \ + sqrt(6)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1))) == \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/2 + \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/2 + \ + TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1))) == \ + TensorProduct( + JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)) + assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1))) == \ + -TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \ + sqrt(2)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/2 + assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1))) == \ + -sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \ + sqrt(2)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1))) == \ + -sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/2 + \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))/2 + \ + TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/2 + # j1=1/2, j2=1, j3=1 + assert uncouple(JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, 1, 1))) == \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1)) + assert uncouple(JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, 1, 1))) == \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/5 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/5 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), + JzKet(1, 0))/5 + assert uncouple(JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1))) == \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/5 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/5 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \ + sqrt(10)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10 + assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1))) == \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/5 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), + JzKet(1, -1))/5 + assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1))) == \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/5 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/5 + \ + sqrt(5)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/5 + assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, 1, 1))) == \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1)) + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1))) == \ + -sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 - \ + 2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), + JzKet(1, 0))/5 + assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1))) == \ + -4*sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 - \ + 2*sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), + JzKet(1, -1))/5 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1))) == \ + -sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/5 - \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \ + 2*sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 - \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \ + 4*sqrt(5)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1))) == \ + -sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/5 + \ + 2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \ + sqrt(30)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1))) == \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/3 - \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/3 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), + JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1))) == \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/3 + \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/3 + # j1=1, j2=1, j3=1 + assert uncouple(JzKetCoupled(3, 3, (1, 1, 1))) == \ + TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1)) + assert uncouple(JzKetCoupled(3, 2, (1, 1, 1))) == \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/3 + assert uncouple(JzKetCoupled(3, 1, (1, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(3, 0, (1, 1, 1))) == \ + sqrt(10)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/10 + \ + sqrt(10)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/10 + \ + sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/10 + \ + sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))/5 + \ + sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/10 + \ + sqrt(10)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/10 + \ + sqrt(10)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/10 + assert uncouple(JzKetCoupled(3, -1, (1, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(3, -2, (1, 1, 1))) == \ + sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(3, -3, (1, 1, 1))) == \ + TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1)) + assert uncouple(JzKetCoupled(2, 2, (1, 1, 1))) == \ + -sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/6 - \ + sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/3 + assert uncouple(JzKetCoupled(2, 1, (1, 1, 1))) == \ + -sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/6 - \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/6 - \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(2, 0, (1, 1, 1))) == \ + -TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/2 + \ + TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(2, -1, (1, 1, 1))) == \ + -sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/3 - \ + sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/6 - \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/3 + \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(2, -2, (1, 1, 1))) == \ + -sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/3 + \ + sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))/6 + \ + sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(1, 1, (1, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/30 + \ + sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/15 - \ + sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/10 + \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/30 - \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/10 + \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/5 + assert uncouple(JzKetCoupled(1, 0, (1, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/10 - \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/10 - \ + 2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/10 - \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/10 + assert uncouple(JzKetCoupled(1, -1, (1, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/5 - \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/10 + \ + sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/30 - \ + sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/10 + \ + sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/15 + \ + sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/30 + # Defined j13 + # j1=1/2, j2=1/2, j3=1, j13=1/2 + assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \ + -sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/3 + \ + sqrt(3)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/3 + assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/3 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/3 + \ + sqrt(6)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/3 + # j1=1/2, j2=1, j3=1, j13=1/2 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \ + -sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), + JzKet(1, 0))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \ + -2*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/3 - \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/3 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), + JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \ + -sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/3 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 + \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/3 + \ + 2*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \ + sqrt(6)*TensorProduct( + JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/3 + # j1=1, j2=1, j3=1, j13=1 + assert uncouple(JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \ + -sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/2 + \ + sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/2 + assert uncouple(JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \ + -TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/2 + \ + TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \ + -sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/3 - \ + sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/6 - \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/6 + \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \ + -TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/2 + \ + TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/2 + \ + TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \ + -sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/2 + \ + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \ + TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/2 - \ + TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \ + TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/2 - \ + TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/2 + \ + TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/2 + assert uncouple(JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \ + -TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/2 - \ + TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/2 + \ + TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/2 + + +def test_uncouple_4_coupled_states_numerical(): + # j1=1/2, j2=1/2, j3=1, j4=1, default coupling + assert uncouple(JzKetCoupled(3, 3, (S.Half, S.Half, 1, 1))) == \ + TensorProduct(JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1)) + assert uncouple(JzKetCoupled(3, 2, (S.Half, S.Half, 1, 1))) == \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/3 + \ + sqrt(3)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3 + assert uncouple(JzKetCoupled(3, 1, (S.Half, S.Half, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, 1), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(3, 0, (S.Half, S.Half, 1, 1))) == \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, 0), JzKet(1, -1))/10 + assert uncouple(JzKetCoupled(3, -1, (S.Half, S.Half, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, -1), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(3, -2, (S.Half, S.Half, 1, 1))) == \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/3 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(3, -3, (S.Half, S.Half, 1, 1))) == \ + TensorProduct(JzKet(S.Half, -S( + 1)/2), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1)) + assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 - \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3 + assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/12 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/12 - \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1))) == \ + -TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/4 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/4 + \ + TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/3 - \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/12 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/6 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/12 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, -1), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1))) == \ + -sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/30 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/20 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/20 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 - \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/10 + \ + sqrt(15)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/5 + assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 - \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/20 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/20 - \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, 0), JzKet(1, -1))/10 + assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/5 - \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/10 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/20 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/20 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/30 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, -1), JzKet(1, -1))/30 + # j1=1/2, j2=1/2, j3=1, j4=1, j12=1, j34=1 + assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \ + -sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/2 + \ + sqrt(2)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/2 + assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \ + -sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/4 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/4 - \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/6 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/6 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/6 + \ + sqrt(3)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \ + -TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/2 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/4 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/4 + assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \ + -sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/2 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, + Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/4 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/4 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/4 - \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/2 + \ + TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/2 - \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/2 + \ + TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/2 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/4 - \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/4 + \ + sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/4 + # j1=1/2, j2=1/2, j3=1, j4=1, j12=1, j34=2 + assert uncouple(JzKetCoupled(3, 3, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \ + TensorProduct(JzKet( + S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1)) + assert uncouple(JzKetCoupled(3, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/3 + \ + sqrt(3)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3 + assert uncouple(JzKetCoupled(3, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, 1), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(3, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \ + sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \ + sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, 0), JzKet(1, -1))/10 + assert uncouple(JzKetCoupled(3, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/15 + \ + 2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/15 + \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, -1), JzKet(1, -1))/15 + assert uncouple(JzKetCoupled(3, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/3 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(3, -3, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \ + TensorProduct(JzKet(S.Half, -S( + 1)/2), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1)) + assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/3 - \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/6 + assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/12 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/12 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/12 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/12 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \ + sqrt(3)*TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/6 + assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \ + -TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \ + TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/2 + \ + TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/2 + \ + TensorProduct(JzKet(S( + 1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2 + assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \ + -sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/6 - \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 - \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/12 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/12 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/12 + \ + sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/12 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, -1), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \ + -sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/6 - \ + sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/3 + \ + sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/3 + assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/5 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/20 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, 1), JzKet(1, -1))/30 + assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, 0), JzKet(1, -1))/10 + assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/30 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/20 - \ + sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/20 + \ + sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, + S.Half), JzKet(1, -1), JzKet(1, -1))/5 + + +def test_uncouple_symbolic(): + assert uncouple(JzKetCoupled(j, m, (j1, j2) )) == \ + Sum(CG(j1, m1, j2, m2, j, m) * + TensorProduct(JzKet(j1, m1), JzKet(j2, m2)), + (m1, -j1, j1), (m2, -j2, j2)) + assert uncouple(JzKetCoupled(j, m, (j1, j2, j3) )) == \ + Sum(CG(j1, m1, j2, m2, j1 + j2, m1 + m2) * CG(j1 + j2, m1 + m2, j3, m3, j, m) * + TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)), + (m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3)) + assert uncouple(JzKetCoupled(j, m, (j1, j2, j3), ((1, 3, j13), (1, 2, j)) )) == \ + Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j2, m2, j, m) * + TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)), + (m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3)) + assert uncouple(JzKetCoupled(j, m, (j1, j2, j3, j4) )) == \ + Sum(CG(j1, m1, j2, m2, j1 + j2, m1 + m2) * CG(j1 + j2, m1 + m2, j3, m3, j1 + j2 + j3, m1 + m2 + m3) * CG(j1 + j2 + j3, m1 + m2 + m3, j4, m4, j, m) * + TensorProduct( + JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), + (m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3), (m4, -j4, j4)) + assert uncouple(JzKetCoupled(j, m, (j1, j2, j3, j4), ((1, 3, j13), (2, 4, j24), (1, 2, j)) )) == \ + Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j2, m2, j4, m4, j24, m2 + m4) * CG(j13, m1 + m3, j24, m2 + m4, j, m) * + TensorProduct( + JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), + (m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3), (m4, -j4, j4)) + + +def test_couple_2_states(): + # j1=1/2, j2=1/2 + assert JzKetCoupled(0, 0, (S.Half, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, S.Half)) ))) + assert JzKetCoupled(1, 1, (S.Half, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half)) ))) + assert JzKetCoupled(1, 0, (S.Half, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half)) ))) + assert JzKetCoupled(1, -1, (S.Half, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half)) ))) + # j1=1, j2=1/2 + assert JzKetCoupled(S.Half, S.Half, (1, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (1, S.Half)) ))) + assert JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half)) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half)) ))) + # j1=1, j2=1 + assert JzKetCoupled(0, 0, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(0, 0, (1, 1)) ))) + assert JzKetCoupled(1, 1, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(1, 1, (1, 1)) ))) + assert JzKetCoupled(1, 0, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(1, 0, (1, 1)) ))) + assert JzKetCoupled(1, -1, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(1, -1, (1, 1)) ))) + assert JzKetCoupled(2, 2, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, 2, (1, 1)) ))) + assert JzKetCoupled(2, 1, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, 1, (1, 1)) ))) + assert JzKetCoupled(2, 0, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, 0, (1, 1)) ))) + assert JzKetCoupled(2, -1, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, -1, (1, 1)) ))) + assert JzKetCoupled(2, -2, (1, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, -2, (1, 1)) ))) + # j1=1/2, j2=3/2 + assert JzKetCoupled(1, 1, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, Rational(3, 2))) ))) + assert JzKetCoupled(1, 0, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, Rational(3, 2))) ))) + assert JzKetCoupled(1, -1, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, Rational(3, 2))) ))) + assert JzKetCoupled(2, 2, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, Rational(3, 2))) ))) + assert JzKetCoupled(2, 1, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, Rational(3, 2))) ))) + assert JzKetCoupled(2, 0, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, Rational(3, 2))) ))) + assert JzKetCoupled(2, -1, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, Rational(3, 2))) ))) + assert JzKetCoupled(2, -2, (S.Half, Rational(3, 2))) == \ + expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, Rational(3, 2))) ))) + + +def test_couple_3_states(): + # Default coupling + # j1=1/2, j2=1/2, j3=1/2 + assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half)) ))) + # j1=1/2, j2=1/2, j3=1 + assert JzKetCoupled(0, 0, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(1, 1, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(1, 0, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(1, -1, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(2, 2, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(2, 1, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(2, 0, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(2, -1, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, S.Half, 1)) ))) + assert JzKetCoupled(2, -2, (S.Half, S.Half, 1)) == \ + expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, S.Half, 1)) ))) + # Couple j1+j3=j13, j13+j2=j + # j1=1/2, j2=1/2, j3=1/2, j13=0 + assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half))) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (S.Half, S( + 1)/2, S.Half), ((1, 3, 0), (1, 2, S.Half))) ), ((1, 3), (1, 2)) )) + assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half))) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S( + 1)/2, S.Half), ((1, 3, 0), (1, 2, S.Half))) ), ((1, 3), (1, 2)) )) + # j1=1, j2=1/2, j3=1, j13=1 + assert JzKetCoupled(S.Half, S.Half, (1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, ( + 1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) ), ((1, 3), (1, 2)) )) + assert JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), ( + 1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) ), ((1, 3), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), ( + 1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, ( + 1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), ( + 1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), ( + 1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) )) + + +def test_couple_4_states(): + # Default coupling + # j1=1/2, j2=1/2, j3=1/2, j4=1/2 + assert JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple( + uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple( + uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(2, 2, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple( + uncouple( JzKetCoupled(2, 2, (S.Half, S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(2, 1, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple( + uncouple( JzKetCoupled(2, 1, (S.Half, S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple( + uncouple( JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(2, -1, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(2, -1, (S.Half, S.Half, S.Half, S.Half)) ))) + assert JzKetCoupled(2, -2, (S.Half, S.Half, S.Half, S.Half)) == \ + expand(couple(uncouple( + JzKetCoupled(2, -2, (S.Half, S.Half, S.Half, S.Half)) ))) + # j1=1/2, j2=1/2, j3=1/2, j4=1 + assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) ))) + assert JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S.Half, S.Half, 1)) == \ + expand(couple(uncouple( + JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S.Half, S.Half, 1)) ))) + # Coupling j1+j3=j13, j2+j4=j24, j13+j24=j + # j1=1/2, j2=1/2, j3=1/2, j4=1/2, j13=1, j24=0 + assert JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) )) + # j1=1/2, j2=1/2, j3=1/2, j4=1, j13=1, j24=1/2 + assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) )), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) == \ + expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \ + expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) )) + # j1=1/2, j2=1, j3=1/2, j4=1, j13=0, j24=1 + assert JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ( + (1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ( + (1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ( + (1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) )) + # j1=1/2, j2=1, j3=1/2, j4=1, j13=1, j24=1 + assert JzKetCoupled(0, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 0)) ) == \ + expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 0))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \ + expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(2, 2, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \ + expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(2, 1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \ + expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(2, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \ + expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(2, -1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \ + expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) )) + assert JzKetCoupled(2, -2, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \ + expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, 1, S.Half, 1), ( + (1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) )) + + +def test_couple_2_states_numerical(): + # j1=1/2, j2=1/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \ + JzKetCoupled(1, 1, (S.Half, S.Half)) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(2)*JzKetCoupled(0, 0, (S( + 1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + -sqrt(2)*JzKetCoupled(0, 0, (S( + 1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + JzKetCoupled(1, -1, (S.Half, S.Half)) + # j1=1, j2=1/2 + assert couple(TensorProduct(JzKet(1, 1), JzKet(S.Half, S.Half))) == \ + JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half)) + assert couple(TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (1, S.Half))/3 + sqrt( + 3)*JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))/3 + assert couple(TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))) == \ + -sqrt(3)*JzKetCoupled(S.Half, S.Half, (1, S.Half))/3 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))/3 + assert couple(TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half))/3 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (1, S( + 1)/2))/3 + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(S.Half, Rational(-1, 2)))) == \ + JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half)) + # j1=1, j2=1 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \ + JzKetCoupled(2, 2, (1, 1)) + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0))) == \ + sqrt(2)*JzKetCoupled( + 1, 1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, 1, (1, 1))/2 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + sqrt(3)*JzKetCoupled(0, 0, (1, 1))/3 + sqrt(2)*JzKetCoupled( + 1, 0, (1, 1))/2 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/6 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1))) == \ + -sqrt(2)*JzKetCoupled( + 1, 1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, 1, (1, 1))/2 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0))) == \ + -sqrt(3)*JzKetCoupled( + 0, 0, (1, 1))/3 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/3 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1))) == \ + sqrt(2)*JzKetCoupled( + 1, -1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, -1, (1, 1))/2 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1))) == \ + sqrt(3)*JzKetCoupled(0, 0, (1, 1))/3 - sqrt(2)*JzKetCoupled( + 1, 0, (1, 1))/2 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/6 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0))) == \ + -sqrt(2)*JzKetCoupled( + 1, -1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, -1, (1, 1))/2 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1))) == \ + JzKetCoupled(2, -2, (1, 1)) + # j1=3/2, j2=1/2 + assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(3, 2)), JzKet(S.Half, S.Half))) == \ + JzKetCoupled(2, 2, (Rational(3, 2), S.Half)) + assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(3, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(3)*JzKetCoupled( + 1, 1, (Rational(3, 2), S.Half))/2 + JzKetCoupled(2, 1, (Rational(3, 2), S.Half))/2 + assert couple(TensorProduct(JzKet(Rational(3, 2), S.Half), JzKet(S.Half, S.Half))) == \ + -JzKetCoupled(1, 1, (S( + 3)/2, S.Half))/2 + sqrt(3)*JzKetCoupled(2, 1, (Rational(3, 2), S.Half))/2 + assert couple(TensorProduct(JzKet(Rational(3, 2), S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(2)*JzKetCoupled(1, 0, (S( + 3)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(2, 0, (Rational(3, 2), S.Half))/2 + assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + -sqrt(2)*JzKetCoupled(1, 0, (S( + 3)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(2, 0, (Rational(3, 2), S.Half))/2 + assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + JzKetCoupled(1, -1, (S( + 3)/2, S.Half))/2 + sqrt(3)*JzKetCoupled(2, -1, (Rational(3, 2), S.Half))/2 + assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-3, 2)), JzKet(S.Half, S.Half))) == \ + -sqrt(3)*JzKetCoupled(1, -1, (Rational(3, 2), S.Half))/2 + \ + JzKetCoupled(2, -1, (Rational(3, 2), S.Half))/2 + assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-3, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + JzKetCoupled(2, -2, (Rational(3, 2), S.Half)) + + +def test_couple_3_states_numerical(): + # Default coupling + # j1=1/2,j2=1/2,j3=1/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \ + JzKetCoupled(Rational(3, 2), S( + 3)/2, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 - \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 + \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One + /2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \ + -sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 - \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + -sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 + \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One + /2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One + /2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + JzKetCoupled(Rational(3, 2), -S( + 3)/2, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2))) ) + # j1=S.Half, j2=S.Half, j3=1 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \ + JzKetCoupled(2, 2, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \ + sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(2)*JzKetCoupled( + 2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/3 + \ + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \ + sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \ + -sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \ + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \ + sqrt(3)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/3 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \ + sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \ + -sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \ + -sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \ + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \ + sqrt(3)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \ + -sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/3 - \ + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \ + -sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(2)*JzKetCoupled( + 2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \ + JzKetCoupled(2, -2, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) ) + # j1=S.Half, j2=1, j3=1 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))) == \ + JzKetCoupled( + Rational(5, 2), Rational(5, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))) == \ + sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(S( + 5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/2 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))) == \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + 2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(S( + 5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))) == \ + JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(S( + 5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + 4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))) == \ + -2*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))) == \ + -sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \ + 2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))) == \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))) == \ + -sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(S( + 5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))) == \ + -sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \ + 2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(S( + 5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))) == \ + -2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + 4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(S( + 5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))) == \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))) == \ + -sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + 2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/2 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))) == \ + -sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, + 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))) == \ + JzKetCoupled(S( + 5)/2, Rational(-5, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) ) + # j1=1, j2=1, j3=1 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1))) == \ + JzKetCoupled(3, 3, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) ) + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))) == \ + sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \ + sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))) == \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/5 + \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \ + sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))) == \ + sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \ + sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))) == \ + JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))) == \ + sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 + \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))) == \ + sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \ + JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 + \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))) == \ + -sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \ + sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/3 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))) == \ + sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \ + JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 + \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))) == \ + -sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \ + sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))) == \ + -JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))) == \ + -sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 + \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))) == \ + -sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 - \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \ + 2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))) == \ + -sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \ + 2*sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/5 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))) == \ + -sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \ + 2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))) == \ + sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 - \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))) == \ + -JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))) == \ + sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \ + sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))) == \ + sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \ + JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 - \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))) == \ + sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \ + sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 - \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/3 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))) == \ + sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \ + JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 - \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))) == \ + -sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 - \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))) == \ + JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))) == \ + -sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \ + sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))) == \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/5 - \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \ + sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))) == \ + -sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \ + sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1))) == \ + JzKetCoupled(3, -3, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) ) + # j1=S.Half, j2=S.Half, j3=Rational(3, 2) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2)))) == \ + JzKetCoupled(Rational(5, 2), S( + 5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half))) == \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3) + /2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2)))) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \ + 2*sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2)))) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/2 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2)))) == \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/ + 2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half))) == \ + -sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2)))) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2)))) == \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3) + /2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2)))) == \ + -sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/ + 2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half))) == \ + -sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2)))) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2)))) == \ + -sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3) + /2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2)))) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/2 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half))) == \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \ + 2*sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2)))) == \ + -sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S( + 3)/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2)))) == \ + JzKetCoupled(Rational(5, 2), -S( + 5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) ) + # Couple j1 to j3 + # j1=1/2, j2=1/2, j3=1/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(Rational(3, 2), S( + 3)/2, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, Rational(3, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 - \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/ + 2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/ + 2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 + \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One + /2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 - \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/ + 2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One + /2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 + \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One + /2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(Rational(3, 2), -S( + 3)/2, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, Rational(3, 2))) ) + # j1=1/2, j2=1/2, j3=1 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(2, 2, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \ + sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \ + sqrt(2)*JzKetCoupled( + 2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/3 + \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \ + sqrt(6)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/6 + \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/6 + \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/3 + \ + sqrt(3)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/3 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \ + sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \ + JzKetCoupled( + 2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \ + sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \ + JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/6 - \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/6 - \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/3 + \ + sqrt(3)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/3 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/2 + \ + JzKetCoupled( + 2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/3 - \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \ + sqrt(6)*JzKetCoupled( + 2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \ + sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \ + sqrt(2)*JzKetCoupled( + 2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(2, -2, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) ) + # j 1=1/2, j 2=1, j 3=1 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled( + Rational(5, 2), Rational(5, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \ + 2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(S( + 5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -2*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(S( + 5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(S( + 5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \ + 2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/2 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \ + 4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(S( + 5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \ + JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \ + 4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(S( + 5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/2 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \ + 2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(S( + 5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \ + 2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, + 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(S( + 5)/2, Rational(-5, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) ) + # j1=1, 1, 1 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(3, 3, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) ) + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \ + sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \ + JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 + \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \ + sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \ + sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/3 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/5 + \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \ + sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 + \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \ + JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 + \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \ + sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 - \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \ + 2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 - \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 - \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \ + 2*sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/5 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 - \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 + \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \ + 2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \ + sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \ + JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 - \ + JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \ + JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 - \ + JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/5 - \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \ + sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \ + sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \ + sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 - \ + sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/3 + \ + sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + 2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \ + sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \ + JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \ + sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 - \ + JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \ + sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \ + sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \ + sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3 + assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(3, -3, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) ) + # j1=1/2, j2=1/2, j3=3/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(Rational(5, 2), S( + 5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \ + sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3) + /2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/2 + \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \ + sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \ + 2*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/ + 2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/6 + \ + 3*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3) + /2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \ + -sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/ + 2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/6 - \ + 3*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \ + -2*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3) + /2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/2 - \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \ + sqrt(15)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \ + sqrt(30)*JzKetCoupled(Rational(5, 2), -S( + 1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \ + -JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \ + sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \ + sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S( + 3)/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \ + JzKetCoupled(Rational(5, 2), -S( + 5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) ) + + +def test_couple_4_states_numerical(): + # Default coupling + # j1=1/2, j2=1/2, j3=1/2, j4=1/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \ + JzKetCoupled(2, 2, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 - \ + sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/3 + \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 + \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \ + sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \ + sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \ + sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), + JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), + ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)))/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), + ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)))/6 + \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), + ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)))/2 - \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), + ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)))/6 + \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), + ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)))/6 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half), + ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)))/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + -JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 + \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \ + sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \ + -sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \ + sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \ + sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + -JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 - \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 - \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + -sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \ + sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/3 - \ + sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 - \ + sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \ + -sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 + \ + sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \ + -sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/2 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \ + JzKetCoupled(2, -2, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) ) + # j1=S.Half, S.Half, S.Half, 1 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \ + JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \ + sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/2 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \ + 2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \ + 2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 - \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \ + sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \ + -sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \ + -sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 - \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \ + -sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \ + -sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \ + sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \ + sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \ + -sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \ + 2*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \ + 2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \ + -sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/2 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \ + -sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \ + JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) ) + # Couple j1 to j2, j3 to j4 + # j1=1/2, j2=1/2, j3=1/2, j4=1/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + JzKetCoupled(2, 2, (S( + 1)/2, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 + \ + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + -JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, 1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + -JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 - \ + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/ + 2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \ + JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \ + JzKetCoupled(2, -1, (S.Half, S( + 1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \ + JzKetCoupled(2, -2, (S( + 1)/2, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) ) + # j1=S.Half, S.Half, S.Half, 1 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) ) + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + 2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + 2*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + 4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/2 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 + \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \ + sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 - \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \ + sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 + \ + JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 + \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \ + sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \ + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 - \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \ + sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 + \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/2 - \ + sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \ + JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + 4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \ + 2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \ + sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \ + sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + 2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \ + -sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \ + 2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \ + sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5 + assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \ + JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S( + 1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) ) + + +def test_couple_symbolic(): + assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + Sum(CG(j1, m1, j2, m2, j, m1 + m2) * JzKetCoupled(j, m1 + m2, ( + j1, j2)), (j, m1 + m2, j1 + j2)) + assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3))) == \ + Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j12, m1 + m2, j3, m3, j, m1 + m2 + m3) * + JzKetCoupled(j, m1 + m2 + m3, (j1, j2, j3), ((1, 2, j12), (1, 3, j)) ), + (j12, m1 + m2, j1 + j2), (j, m1 + m2 + m3, j12 + j3)) + assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)), ((1, 3), (1, 2)) ) == \ + Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j2, m2, j, m1 + m2 + m3) * + JzKetCoupled(j, m1 + m2 + m3, (j1, j2, j3), ((1, 3, j13), (1, 2, j)) ), + (j13, m1 + m3, j1 + j3), (j, m1 + m2 + m3, j13 + j2)) + assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4))) == \ + Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j12, m1 + m2, j3, m3, j123, m1 + m2 + m3) * CG(j123, m1 + m2 + m3, j4, m4, j, m1 + m2 + m3 + m4) * + JzKetCoupled(j, m1 + m2 + m3 + m4, ( + j1, j2, j3, j4), ((1, 2, j12), (1, 3, j123), (1, 4, j)) ), + (j12, m1 + m2, j1 + j2), (j123, m1 + m2 + m3, j12 + j3), (j, m1 + m2 + m3 + m4, j123 + j4)) + assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), ((1, 2), (3, 4), (1, 3)) ) == \ + Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j3, m3, j4, m4, j34, m3 + m4) * CG(j12, m1 + m2, j34, m3 + m4, j, m1 + m2 + m3 + m4) * + JzKetCoupled(j, m1 + m2 + m3 + m4, ( + j1, j2, j3, j4), ((1, 2, j12), (3, 4, j34), (1, 3, j)) ), + (j12, m1 + m2, j1 + j2), (j34, m3 + m4, j3 + j4), (j, m1 + m2 + m3 + m4, j12 + j34)) + assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), ((1, 3), (1, 4), (1, 2)) ) == \ + Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j4, m4, j134, m1 + m3 + m4) * CG(j134, m1 + m3 + m4, j2, m2, j, m1 + m2 + m3 + m4) * + JzKetCoupled(j, m1 + m2 + m3 + m4, ( + j1, j2, j3, j4), ((1, 3, j13), (1, 4, j134), (1, 2, j)) ), + (j13, m1 + m3, j1 + j3), (j134, m1 + m3 + m4, j13 + j4), (j, m1 + m2 + m3 + m4, j134 + j2)) + + +def test_innerproduct(): + assert InnerProduct(JzBra(1, 1), JzKet(1, 1)).doit() == 1 + assert InnerProduct( + JzBra(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))).doit() == 0 + assert InnerProduct(JzBra(j, m), JzKet(j, m)).doit() == 1 + assert InnerProduct(JzBra(1, 0), JyKet(1, 1)).doit() == I/sqrt(2) + assert InnerProduct( + JxBra(S.Half, S.Half), JzKet(S.Half, S.Half)).doit() == -sqrt(2)/2 + assert InnerProduct(JyBra(1, 1), JzKet(1, 1)).doit() == S.Half + assert InnerProduct(JxBra(1, -1), JyKet(1, 1)).doit() == 0 + + +def test_rotation_small_d(): + # Symbolic tests + # j = 1/2 + assert Rotation.d(S.Half, S.Half, S.Half, beta).doit() == cos(beta/2) + assert Rotation.d(S.Half, S.Half, Rational(-1, 2), beta).doit() == -sin(beta/2) + assert Rotation.d(S.Half, Rational(-1, 2), S.Half, beta).doit() == sin(beta/2) + assert Rotation.d(S.Half, Rational(-1, 2), Rational(-1, 2), beta).doit() == cos(beta/2) + # j = 1 + assert Rotation.d(1, 1, 1, beta).doit() == (1 + cos(beta))/2 + assert Rotation.d(1, 1, 0, beta).doit() == -sin(beta)/sqrt(2) + assert Rotation.d(1, 1, -1, beta).doit() == (1 - cos(beta))/2 + assert Rotation.d(1, 0, 1, beta).doit() == sin(beta)/sqrt(2) + assert Rotation.d(1, 0, 0, beta).doit() == cos(beta) + assert Rotation.d(1, 0, -1, beta).doit() == -sin(beta)/sqrt(2) + assert Rotation.d(1, -1, 1, beta).doit() == (1 - cos(beta))/2 + assert Rotation.d(1, -1, 0, beta).doit() == sin(beta)/sqrt(2) + assert Rotation.d(1, -1, -1, beta).doit() == (1 + cos(beta))/2 + # j = 3/2 + assert Rotation.d(S( + 3)/2, Rational(3, 2), Rational(3, 2), beta).doit() == (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), S( + 3)/2, S.Half, beta).doit() == -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), S( + 3)/2, Rational(-1, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), S( + 3)/2, Rational(-3, 2), beta).doit() == (-3*sin(beta/2) + sin(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), S( + 1)/2, Rational(3, 2), beta).doit() == sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4 + assert Rotation.d(S( + 3)/2, S.Half, S.Half, beta).doit() == (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4 + assert Rotation.d(S( + 3)/2, S.Half, Rational(-1, 2), beta).doit() == (sin(beta/2) - 3*sin(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), S( + 1)/2, Rational(-3, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), -S( + 1)/2, Rational(3, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), -S( + 1)/2, S.Half, beta).doit() == (-sin(beta/2) + 3*sin(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), -S( + 1)/2, Rational(-1, 2), beta).doit() == (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), -S( + 1)/2, Rational(-3, 2), beta).doit() == -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4 + assert Rotation.d(S( + 3)/2, Rational(-3, 2), Rational(3, 2), beta).doit() == (3*sin(beta/2) - sin(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), -S( + 3)/2, S.Half, beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), -S( + 3)/2, Rational(-1, 2), beta).doit() == sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4 + assert Rotation.d(Rational(3, 2), -S( + 3)/2, Rational(-3, 2), beta).doit() == (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4 + # j = 2 + assert Rotation.d(2, 2, 2, beta).doit() == (3 + 4*cos(beta) + cos(2*beta))/8 + assert Rotation.d(2, 2, 1, beta).doit() == -((cos(beta) + 1)*sin(beta))/2 + assert Rotation.d(2, 2, 0, beta).doit() == sqrt(6)*sin(beta)**2/4 + assert Rotation.d(2, 2, -1, beta).doit() == (cos(beta) - 1)*sin(beta)/2 + assert Rotation.d(2, 2, -2, beta).doit() == (3 - 4*cos(beta) + cos(2*beta))/8 + assert Rotation.d(2, 1, 2, beta).doit() == (cos(beta) + 1)*sin(beta)/2 + assert Rotation.d(2, 1, 1, beta).doit() == (cos(beta) + cos(2*beta))/2 + assert Rotation.d(2, 1, 0, beta).doit() == -sqrt(6)*sin(2*beta)/4 + assert Rotation.d(2, 1, -1, beta).doit() == (cos(beta) - cos(2*beta))/2 + assert Rotation.d(2, 1, -2, beta).doit() == (cos(beta) - 1)*sin(beta)/2 + assert Rotation.d(2, 0, 2, beta).doit() == sqrt(6)*sin(beta)**2/4 + assert Rotation.d(2, 0, 1, beta).doit() == sqrt(6)*sin(2*beta)/4 + assert Rotation.d(2, 0, 0, beta).doit() == (1 + 3*cos(2*beta))/4 + assert Rotation.d(2, 0, -1, beta).doit() == -sqrt(6)*sin(2*beta)/4 + assert Rotation.d(2, 0, -2, beta).doit() == sqrt(6)*sin(beta)**2/4 + assert Rotation.d(2, -1, 2, beta).doit() == (2*sin(beta) - sin(2*beta))/4 + assert Rotation.d(2, -1, 1, beta).doit() == (cos(beta) - cos(2*beta))/2 + assert Rotation.d(2, -1, 0, beta).doit() == sqrt(6)*sin(2*beta)/4 + assert Rotation.d(2, -1, -1, beta).doit() == (cos(beta) + cos(2*beta))/2 + assert Rotation.d(2, -1, -2, beta).doit() == -((cos(beta) + 1)*sin(beta))/2 + assert Rotation.d(2, -2, 2, beta).doit() == (3 - 4*cos(beta) + cos(2*beta))/8 + assert Rotation.d(2, -2, 1, beta).doit() == (2*sin(beta) - sin(2*beta))/4 + assert Rotation.d(2, -2, 0, beta).doit() == sqrt(6)*sin(beta)**2/4 + assert Rotation.d(2, -2, -1, beta).doit() == (cos(beta) + 1)*sin(beta)/2 + assert Rotation.d(2, -2, -2, beta).doit() == (3 + 4*cos(beta) + cos(2*beta))/8 + # Numerical tests + # j = 1/2 + assert Rotation.d(S.Half, S.Half, S.Half, pi/2).doit() == sqrt(2)/2 + assert Rotation.d(S.Half, S.Half, Rational(-1, 2), pi/2).doit() == -sqrt(2)/2 + assert Rotation.d(S.Half, Rational(-1, 2), S.Half, pi/2).doit() == sqrt(2)/2 + assert Rotation.d(S.Half, Rational(-1, 2), Rational(-1, 2), pi/2).doit() == sqrt(2)/2 + # j = 1 + assert Rotation.d(1, 1, 1, pi/2).doit() == S.Half + assert Rotation.d(1, 1, 0, pi/2).doit() == -sqrt(2)/2 + assert Rotation.d(1, 1, -1, pi/2).doit() == S.Half + assert Rotation.d(1, 0, 1, pi/2).doit() == sqrt(2)/2 + assert Rotation.d(1, 0, 0, pi/2).doit() == 0 + assert Rotation.d(1, 0, -1, pi/2).doit() == -sqrt(2)/2 + assert Rotation.d(1, -1, 1, pi/2).doit() == S.Half + assert Rotation.d(1, -1, 0, pi/2).doit() == sqrt(2)/2 + assert Rotation.d(1, -1, -1, pi/2).doit() == S.Half + # j = 3/2 + assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(3, 2), pi/2).doit() == sqrt(2)/4 + assert Rotation.d(Rational(3, 2), Rational(3, 2), S.Half, pi/2).doit() == -sqrt(6)/4 + assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(-1, 2), pi/2).doit() == sqrt(6)/4 + assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(-3, 2), pi/2).doit() == -sqrt(2)/4 + assert Rotation.d(Rational(3, 2), S.Half, Rational(3, 2), pi/2).doit() == sqrt(6)/4 + assert Rotation.d(Rational(3, 2), S.Half, S.Half, pi/2).doit() == -sqrt(2)/4 + assert Rotation.d(Rational(3, 2), S.Half, Rational(-1, 2), pi/2).doit() == -sqrt(2)/4 + assert Rotation.d(Rational(3, 2), S.Half, Rational(-3, 2), pi/2).doit() == sqrt(6)/4 + assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(3, 2), pi/2).doit() == sqrt(6)/4 + assert Rotation.d(Rational(3, 2), Rational(-1, 2), S.Half, pi/2).doit() == sqrt(2)/4 + assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(-1, 2), pi/2).doit() == -sqrt(2)/4 + assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(-3, 2), pi/2).doit() == -sqrt(6)/4 + assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(3, 2), pi/2).doit() == sqrt(2)/4 + assert Rotation.d(Rational(3, 2), Rational(-3, 2), S.Half, pi/2).doit() == sqrt(6)/4 + assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(-1, 2), pi/2).doit() == sqrt(6)/4 + assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(-3, 2), pi/2).doit() == sqrt(2)/4 + # j = 2 + assert Rotation.d(2, 2, 2, pi/2).doit() == Rational(1, 4) + assert Rotation.d(2, 2, 1, pi/2).doit() == Rational(-1, 2) + assert Rotation.d(2, 2, 0, pi/2).doit() == sqrt(6)/4 + assert Rotation.d(2, 2, -1, pi/2).doit() == Rational(-1, 2) + assert Rotation.d(2, 2, -2, pi/2).doit() == Rational(1, 4) + assert Rotation.d(2, 1, 2, pi/2).doit() == S.Half + assert Rotation.d(2, 1, 1, pi/2).doit() == Rational(-1, 2) + assert Rotation.d(2, 1, 0, pi/2).doit() == 0 + assert Rotation.d(2, 1, -1, pi/2).doit() == S.Half + assert Rotation.d(2, 1, -2, pi/2).doit() == Rational(-1, 2) + assert Rotation.d(2, 0, 2, pi/2).doit() == sqrt(6)/4 + assert Rotation.d(2, 0, 1, pi/2).doit() == 0 + assert Rotation.d(2, 0, 0, pi/2).doit() == Rational(-1, 2) + assert Rotation.d(2, 0, -1, pi/2).doit() == 0 + assert Rotation.d(2, 0, -2, pi/2).doit() == sqrt(6)/4 + assert Rotation.d(2, -1, 2, pi/2).doit() == S.Half + assert Rotation.d(2, -1, 1, pi/2).doit() == S.Half + assert Rotation.d(2, -1, 0, pi/2).doit() == 0 + assert Rotation.d(2, -1, -1, pi/2).doit() == Rational(-1, 2) + assert Rotation.d(2, -1, -2, pi/2).doit() == Rational(-1, 2) + assert Rotation.d(2, -2, 2, pi/2).doit() == Rational(1, 4) + assert Rotation.d(2, -2, 1, pi/2).doit() == S.Half + assert Rotation.d(2, -2, 0, pi/2).doit() == sqrt(6)/4 + assert Rotation.d(2, -2, -1, pi/2).doit() == S.Half + assert Rotation.d(2, -2, -2, pi/2).doit() == Rational(1, 4) + + +def test_rotation_d(): + # Symbolic tests + # j = 1/2 + assert Rotation.D(S.Half, S.Half, S.Half, alpha, beta, gamma).doit() == \ + cos(beta/2)*exp(-I*alpha/2)*exp(-I*gamma/2) + assert Rotation.D(S.Half, S.Half, Rational(-1, 2), alpha, beta, gamma).doit() == \ + -sin(beta/2)*exp(-I*alpha/2)*exp(I*gamma/2) + assert Rotation.D(S.Half, Rational(-1, 2), S.Half, alpha, beta, gamma).doit() == \ + sin(beta/2)*exp(I*alpha/2)*exp(-I*gamma/2) + assert Rotation.D(S.Half, Rational(-1, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \ + cos(beta/2)*exp(I*alpha/2)*exp(I*gamma/2) + # j = 1 + assert Rotation.D(1, 1, 1, alpha, beta, gamma).doit() == \ + (1 + cos(beta))/2*exp(-I*alpha)*exp(-I*gamma) + assert Rotation.D(1, 1, 0, alpha, beta, gamma).doit() == -sin( + beta)/sqrt(2)*exp(-I*alpha) + assert Rotation.D(1, 1, -1, alpha, beta, gamma).doit() == \ + (1 - cos(beta))/2*exp(-I*alpha)*exp(I*gamma) + assert Rotation.D(1, 0, 1, alpha, beta, gamma).doit() == \ + sin(beta)/sqrt(2)*exp(-I*gamma) + assert Rotation.D(1, 0, 0, alpha, beta, gamma).doit() == cos(beta) + assert Rotation.D(1, 0, -1, alpha, beta, gamma).doit() == \ + -sin(beta)/sqrt(2)*exp(I*gamma) + assert Rotation.D(1, -1, 1, alpha, beta, gamma).doit() == \ + (1 - cos(beta))/2*exp(I*alpha)*exp(-I*gamma) + assert Rotation.D(1, -1, 0, alpha, beta, gamma).doit() == \ + sin(beta)/sqrt(2)*exp(I*alpha) + assert Rotation.D(1, -1, -1, alpha, beta, gamma).doit() == \ + (1 + cos(beta))/2*exp(I*alpha)*exp(I*gamma) + # j = 3/2 + assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(3, 2), alpha, beta, gamma).doit() == \ + (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma*Rational(-3, 2)) + assert Rotation.D(Rational(3, 2), Rational(3, 2), S.Half, alpha, beta, gamma).doit() == \ + -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(-I*gamma/2) + assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \ + sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma/2) + assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \ + (-3*sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma*Rational(3, 2)) + assert Rotation.D(Rational(3, 2), S.Half, Rational(3, 2), alpha, beta, gamma).doit() == \ + sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma*Rational(-3, 2)) + assert Rotation.D(Rational(3, 2), S.Half, S.Half, alpha, beta, gamma).doit() == \ + (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(-I*gamma/2) + assert Rotation.D(Rational(3, 2), S.Half, Rational(-1, 2), alpha, beta, gamma).doit() == \ + (sin(beta/2) - 3*sin(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma/2) + assert Rotation.D(Rational(3, 2), S.Half, Rational(-3, 2), alpha, beta, gamma).doit() == \ + sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma*Rational(3, 2)) + assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(3, 2), alpha, beta, gamma).doit() == \ + sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma*Rational(-3, 2)) + assert Rotation.D(Rational(3, 2), Rational(-1, 2), S.Half, alpha, beta, gamma).doit() == \ + (-sin(beta/2) + 3*sin(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(-I*gamma/2) + assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \ + (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma/2) + assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \ + -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma*Rational(3, 2)) + assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(3, 2), alpha, beta, gamma).doit() == \ + (3*sin(beta/2) - sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma*Rational(-3, 2)) + assert Rotation.D(Rational(3, 2), Rational(-3, 2), S.Half, alpha, beta, gamma).doit() == \ + sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(-I*gamma/2) + assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \ + sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma/2) + assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \ + (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma*Rational(3, 2)) + # j = 2 + assert Rotation.D(2, 2, 2, alpha, beta, gamma).doit() == \ + (3 + 4*cos(beta) + cos(2*beta))/8*exp(-2*I*alpha)*exp(-2*I*gamma) + assert Rotation.D(2, 2, 1, alpha, beta, gamma).doit() == \ + -((cos(beta) + 1)*exp(-2*I*alpha)*exp(-I*gamma)*sin(beta))/2 + assert Rotation.D(2, 2, 0, alpha, beta, gamma).doit() == \ + sqrt(6)*sin(beta)**2/4*exp(-2*I*alpha) + assert Rotation.D(2, 2, -1, alpha, beta, gamma).doit() == \ + (cos(beta) - 1)*sin(beta)/2*exp(-2*I*alpha)*exp(I*gamma) + assert Rotation.D(2, 2, -2, alpha, beta, gamma).doit() == \ + (3 - 4*cos(beta) + cos(2*beta))/8*exp(-2*I*alpha)*exp(2*I*gamma) + assert Rotation.D(2, 1, 2, alpha, beta, gamma).doit() == \ + (cos(beta) + 1)*sin(beta)/2*exp(-I*alpha)*exp(-2*I*gamma) + assert Rotation.D(2, 1, 1, alpha, beta, gamma).doit() == \ + (cos(beta) + cos(2*beta))/2*exp(-I*alpha)*exp(-I*gamma) + assert Rotation.D(2, 1, 0, alpha, beta, gamma).doit() == -sqrt(6)* \ + sin(2*beta)/4*exp(-I*alpha) + assert Rotation.D(2, 1, -1, alpha, beta, gamma).doit() == \ + (cos(beta) - cos(2*beta))/2*exp(-I*alpha)*exp(I*gamma) + assert Rotation.D(2, 1, -2, alpha, beta, gamma).doit() == \ + (cos(beta) - 1)*sin(beta)/2*exp(-I*alpha)*exp(2*I*gamma) + assert Rotation.D(2, 0, 2, alpha, beta, gamma).doit() == \ + sqrt(6)*sin(beta)**2/4*exp(-2*I*gamma) + assert Rotation.D(2, 0, 1, alpha, beta, gamma).doit() == sqrt(6)* \ + sin(2*beta)/4*exp(-I*gamma) + assert Rotation.D( + 2, 0, 0, alpha, beta, gamma).doit() == (1 + 3*cos(2*beta))/4 + assert Rotation.D(2, 0, -1, alpha, beta, gamma).doit() == -sqrt(6)* \ + sin(2*beta)/4*exp(I*gamma) + assert Rotation.D(2, 0, -2, alpha, beta, gamma).doit() == \ + sqrt(6)*sin(beta)**2/4*exp(2*I*gamma) + assert Rotation.D(2, -1, 2, alpha, beta, gamma).doit() == \ + (2*sin(beta) - sin(2*beta))/4*exp(I*alpha)*exp(-2*I*gamma) + assert Rotation.D(2, -1, 1, alpha, beta, gamma).doit() == \ + (cos(beta) - cos(2*beta))/2*exp(I*alpha)*exp(-I*gamma) + assert Rotation.D(2, -1, 0, alpha, beta, gamma).doit() == sqrt(6)* \ + sin(2*beta)/4*exp(I*alpha) + assert Rotation.D(2, -1, -1, alpha, beta, gamma).doit() == \ + (cos(beta) + cos(2*beta))/2*exp(I*alpha)*exp(I*gamma) + assert Rotation.D(2, -1, -2, alpha, beta, gamma).doit() == \ + -((cos(beta) + 1)*sin(beta))/2*exp(I*alpha)*exp(2*I*gamma) + assert Rotation.D(2, -2, 2, alpha, beta, gamma).doit() == \ + (3 - 4*cos(beta) + cos(2*beta))/8*exp(2*I*alpha)*exp(-2*I*gamma) + assert Rotation.D(2, -2, 1, alpha, beta, gamma).doit() == \ + (2*sin(beta) - sin(2*beta))/4*exp(2*I*alpha)*exp(-I*gamma) + assert Rotation.D(2, -2, 0, alpha, beta, gamma).doit() == \ + sqrt(6)*sin(beta)**2/4*exp(2*I*alpha) + assert Rotation.D(2, -2, -1, alpha, beta, gamma).doit() == \ + (cos(beta) + 1)*sin(beta)/2*exp(2*I*alpha)*exp(I*gamma) + assert Rotation.D(2, -2, -2, alpha, beta, gamma).doit() == \ + (3 + 4*cos(beta) + cos(2*beta))/8*exp(2*I*alpha)*exp(2*I*gamma) + # Numerical tests + # j = 1/2 + assert Rotation.D( + S.Half, S.Half, S.Half, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2 + assert Rotation.D( + S.Half, S.Half, Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/2 + assert Rotation.D( + S.Half, Rational(-1, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(2)/2 + assert Rotation.D( + S.Half, Rational(-1, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2 + # j = 1 + assert Rotation.D(1, 1, 1, pi/2, pi/2, pi/2).doit() == Rational(-1, 2) + assert Rotation.D(1, 1, 0, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2 + assert Rotation.D(1, 1, -1, pi/2, pi/2, pi/2).doit() == S.Half + assert Rotation.D(1, 0, 1, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2 + assert Rotation.D(1, 0, 0, pi/2, pi/2, pi/2).doit() == 0 + assert Rotation.D(1, 0, -1, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2 + assert Rotation.D(1, -1, 1, pi/2, pi/2, pi/2).doit() == S.Half + assert Rotation.D(1, -1, 0, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2 + assert Rotation.D(1, -1, -1, pi/2, pi/2, pi/2).doit() == Rational(-1, 2) + # j = 3/2 + assert Rotation.D( + Rational(3, 2), Rational(3, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4 + assert Rotation.D( + Rational(3, 2), Rational(3, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), Rational(3, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), Rational(3, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/4 + assert Rotation.D( + Rational(3, 2), S.Half, Rational(3, 2), pi/2, pi/2, pi/2).doit() == -sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), S.Half, S.Half, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4 + assert Rotation.D( + Rational(3, 2), S.Half, Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/4 + assert Rotation.D( + Rational(3, 2), S.Half, Rational(-3, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), Rational(-1, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), Rational(-1, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(2)/4 + assert Rotation.D( + Rational(3, 2), Rational(-1, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/4 + assert Rotation.D( + Rational(3, 2), Rational(-1, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), Rational(-3, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == sqrt(2)/4 + assert Rotation.D( + Rational(3, 2), Rational(-3, 2), S.Half, pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), Rational(-3, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(6)/4 + assert Rotation.D( + Rational(3, 2), Rational(-3, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/4 + # j = 2 + assert Rotation.D(2, 2, 2, pi/2, pi/2, pi/2).doit() == Rational(1, 4) + assert Rotation.D(2, 2, 1, pi/2, pi/2, pi/2).doit() == -I/2 + assert Rotation.D(2, 2, 0, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4 + assert Rotation.D(2, 2, -1, pi/2, pi/2, pi/2).doit() == I/2 + assert Rotation.D(2, 2, -2, pi/2, pi/2, pi/2).doit() == Rational(1, 4) + assert Rotation.D(2, 1, 2, pi/2, pi/2, pi/2).doit() == I/2 + assert Rotation.D(2, 1, 1, pi/2, pi/2, pi/2).doit() == S.Half + assert Rotation.D(2, 1, 0, pi/2, pi/2, pi/2).doit() == 0 + assert Rotation.D(2, 1, -1, pi/2, pi/2, pi/2).doit() == S.Half + assert Rotation.D(2, 1, -2, pi/2, pi/2, pi/2).doit() == -I/2 + assert Rotation.D(2, 0, 2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4 + assert Rotation.D(2, 0, 1, pi/2, pi/2, pi/2).doit() == 0 + assert Rotation.D(2, 0, 0, pi/2, pi/2, pi/2).doit() == Rational(-1, 2) + assert Rotation.D(2, 0, -1, pi/2, pi/2, pi/2).doit() == 0 + assert Rotation.D(2, 0, -2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4 + assert Rotation.D(2, -1, 2, pi/2, pi/2, pi/2).doit() == -I/2 + assert Rotation.D(2, -1, 1, pi/2, pi/2, pi/2).doit() == S.Half + assert Rotation.D(2, -1, 0, pi/2, pi/2, pi/2).doit() == 0 + assert Rotation.D(2, -1, -1, pi/2, pi/2, pi/2).doit() == S.Half + assert Rotation.D(2, -1, -2, pi/2, pi/2, pi/2).doit() == I/2 + assert Rotation.D(2, -2, 2, pi/2, pi/2, pi/2).doit() == Rational(1, 4) + assert Rotation.D(2, -2, 1, pi/2, pi/2, pi/2).doit() == I/2 + assert Rotation.D(2, -2, 0, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4 + assert Rotation.D(2, -2, -1, pi/2, pi/2, pi/2).doit() == -I/2 + assert Rotation.D(2, -2, -2, pi/2, pi/2, pi/2).doit() == Rational(1, 4) + + +def test_wignerd(): + assert Rotation.D( + j, m, mp, alpha, beta, gamma) == WignerD(j, m, mp, alpha, beta, gamma) + assert Rotation.d(j, m, mp, beta) == WignerD(j, m, mp, 0, beta, 0) + +def test_wignerD(): + i,j=symbols('i j') + assert Rotation.D(1, 1, 1, 0, 0, 0) == WignerD(1, 1, 1, 0, 0, 0) + assert Rotation.D(1, 1, 2, 0, 0, 0) == WignerD(1, 1, 2, 0, 0, 0) + assert Rotation.D(1, i**2 - j**2, i**2 - j**2, 0, 0, 0) == WignerD(1, i**2 - j**2, i**2 - j**2, 0, 0, 0) + assert Rotation.D(1, i, i, 0, 0, 0) == WignerD(1, i, i, 0, 0, 0) + assert Rotation.D(1, i, i+1, 0, 0, 0) == WignerD(1, i, i+1, 0, 0, 0) + assert Rotation.D(1, 0, 0, 0, 0, 0) == WignerD(1, 0, 0, 0, 0, 0) + +def test_jplus(): + assert Commutator(Jplus, Jminus).doit() == 2*hbar*Jz + assert Jplus.matrix_element(1, 1, 1, 1) == 0 + assert Jplus.rewrite('xyz') == Jx + I*Jy + # Normal operators, normal states + # Numerical + assert qapply(Jplus*JxKet(1, 1)) == \ + -hbar*sqrt(2)*JxKet(1, 0)/2 + hbar*JxKet(1, 1) + assert qapply(Jplus*JyKet(1, 1)) == \ + hbar*sqrt(2)*JyKet(1, 0)/2 + I*hbar*JyKet(1, 1) + assert qapply(Jplus*JzKet(1, 1)) == 0 + # Symbolic + assert qapply(Jplus*JxKet(j, m)) == \ + Sum(hbar * sqrt(-mi**2 - mi + j**2 + j) * WignerD(j, mi, m, 0, pi/2, 0) * + Sum(WignerD(j, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j, mi1), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jplus*JyKet(j, m)) == \ + Sum(hbar * sqrt(j**2 + j - mi**2 - mi) * WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * + Sum(WignerD(j, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j, mi1), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jplus*JzKet(j, m)) == \ + hbar*sqrt(j**2 + j - m**2 - m)*JzKet(j, m + 1) + # Normal operators, coupled states + # Numerical + assert qapply(Jplus*JxKetCoupled(1, 1, (1, 1))) == -hbar*sqrt(2) * \ + JxKetCoupled(1, 0, (1, 1))/2 + hbar*JxKetCoupled(1, 1, (1, 1)) + assert qapply(Jplus*JyKetCoupled(1, 1, (1, 1))) == hbar*sqrt(2) * \ + JyKetCoupled(1, 0, (1, 1))/2 + I*hbar*JyKetCoupled(1, 1, (1, 1)) + assert qapply(Jplus*JzKet(1, 1)) == 0 + # Symbolic + assert qapply(Jplus*JxKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar * sqrt(-mi**2 - mi + j**2 + j) * WignerD(j, mi, m, 0, pi/2, 0) * + Sum( + WignerD( + j, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKetCoupled(j, mi1, (j1, j2)), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jplus*JyKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar * sqrt(j**2 + j - mi**2 - mi) * WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * + Sum( + WignerD(j, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * + JyKetCoupled(j, mi1, (j1, j2)), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jplus*JzKetCoupled(j, m, (j1, j2))) == \ + hbar*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2)) + # Uncoupled operators, uncoupled states + # Numerical + assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + -hbar*sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2 + \ + hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(1, Jplus)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + -hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + \ + hbar*sqrt(2)*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2 + assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + hbar*sqrt(2)*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2 + \ + hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(1, Jplus)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + -hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + \ + hbar*sqrt(2)*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2 + assert qapply( + TensorProduct(Jplus, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0 + assert qapply(TensorProduct(1, Jplus)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + hbar*sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0)) + # Symbolic + assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(Sum(hbar * sqrt(-mi**2 - mi + j1**2 + j1) * WignerD(j1, mi, m1, 0, pi/2, 0) * + Sum(WignerD(j1, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j1, mi1), + (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2)) + assert qapply(TensorProduct(1, Jplus)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(JxKet(j1, m1), Sum(hbar * sqrt(-mi**2 - mi + j2**2 + j2) * WignerD(j2, mi, m2, 0, pi/2, 0) * + Sum(WignerD(j2, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j2, mi1), + (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(Sum(hbar * sqrt(j1**2 + j1 - mi**2 - mi) * WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2) * + Sum(WignerD(j1, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j1, mi1), + (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + assert qapply(TensorProduct(1, Jplus)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(JyKet(j1, m1), Sum(hbar * sqrt(j2**2 + j2 - mi**2 - mi) * WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) * + Sum(WignerD(j2, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j2, mi1), + (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*sqrt( + j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2)) + assert qapply(TensorProduct(1, Jplus)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*sqrt( + j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1)) + + +def test_jminus(): + assert qapply(Jminus*JzKet(1, -1)) == 0 + assert Jminus.matrix_element(1, 0, 1, 1) == sqrt(2)*hbar + assert Jminus.rewrite('xyz') == Jx - I*Jy + # Normal operators, normal states + # Numerical + assert qapply(Jminus*JxKet(1, 1)) == \ + hbar*sqrt(2)*JxKet(1, 0)/2 + hbar*JxKet(1, 1) + assert qapply(Jminus*JyKet(1, 1)) == \ + hbar*sqrt(2)*JyKet(1, 0)/2 - hbar*I*JyKet(1, 1) + assert qapply(Jminus*JzKet(1, 1)) == sqrt(2)*hbar*JzKet(1, 0) + # Symbolic + assert qapply(Jminus*JxKet(j, m)) == \ + Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, 0, pi/2, 0) * + Sum(WignerD(j, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j, mi1), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jminus*JyKet(j, m)) == \ + Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * + Sum(WignerD(j, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j, mi1), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jminus*JzKet(j, m)) == \ + hbar*sqrt(j**2 + j - m**2 + m)*JzKet(j, m - 1) + # Normal operators, coupled states + # Numerical + assert qapply(Jminus*JxKetCoupled(1, 1, (1, 1))) == \ + hbar*sqrt(2)*JxKetCoupled(1, 0, (1, 1))/2 + \ + hbar*JxKetCoupled(1, 1, (1, 1)) + assert qapply(Jminus*JyKetCoupled(1, 1, (1, 1))) == \ + hbar*sqrt(2)*JyKetCoupled(1, 0, (1, 1))/2 - \ + hbar*I*JyKetCoupled(1, 1, (1, 1)) + assert qapply(Jminus*JzKetCoupled(1, 1, (1, 1))) == \ + sqrt(2)*hbar*JzKetCoupled(1, 0, (1, 1)) + # Symbolic + assert qapply(Jminus*JxKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, 0, pi/2, 0) * + Sum(WignerD(j, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKetCoupled(j, mi1, (j1, j2)), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jminus*JyKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * + Sum( + WignerD(j, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)* + JyKetCoupled(j, mi1, (j1, j2)), + (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jminus*JzKetCoupled(j, m, (j1, j2))) == \ + hbar*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2)) + # Uncoupled operators, uncoupled states + # Numerical + assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + hbar*sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2 + \ + hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(1, Jminus)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + -hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) - \ + hbar*sqrt(2)*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2 + assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + hbar*sqrt(2)*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2 - \ + hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(1, Jminus)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + \ + hbar*sqrt(2)*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2 + assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + sqrt(2)*hbar*TensorProduct(JzKet(1, 0), JzKet(1, -1)) + assert qapply(TensorProduct( + 1, Jminus)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0 + # Symbolic + assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(Sum(hbar*sqrt(j1**2 + j1 - mi**2 + mi)*WignerD(j1, mi, m1, 0, pi/2, 0) * + Sum(WignerD(j1, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1), + (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2)) + assert qapply(TensorProduct(1, Jminus)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(JxKet(j1, m1), Sum(hbar*sqrt(j2**2 + j2 - mi**2 + mi)*WignerD(j2, mi, m2, 0, pi/2, 0) * + Sum(WignerD(j2, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1), + (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(Sum(hbar*sqrt(j1**2 + j1 - mi**2 + mi)*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2) * + Sum(WignerD(j1, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1), + (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + assert qapply(TensorProduct(1, Jminus)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(JyKet(j1, m1), Sum(hbar*sqrt(j2**2 + j2 - mi**2 + mi)*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) * + Sum(WignerD(j2, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1), + (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*sqrt( + j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2)) + assert qapply(TensorProduct(1, Jminus)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*sqrt( + j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1)) + + +def test_j2(): + assert Commutator(J2, Jz).doit() == 0 + assert J2.matrix_element(1, 1, 1, 1) == 2*hbar**2 + # Normal operators, normal states + # Numerical + assert qapply(J2*JxKet(1, 1)) == 2*hbar**2*JxKet(1, 1) + assert qapply(J2*JyKet(1, 1)) == 2*hbar**2*JyKet(1, 1) + assert qapply(J2*JzKet(1, 1)) == 2*hbar**2*JzKet(1, 1) + # Symbolic + assert qapply(J2*JxKet(j, m)) == \ + hbar**2*j**2*JxKet(j, m) + hbar**2*j*JxKet(j, m) + assert qapply(J2*JyKet(j, m)) == \ + hbar**2*j**2*JyKet(j, m) + hbar**2*j*JyKet(j, m) + assert qapply(J2*JzKet(j, m)) == \ + hbar**2*j**2*JzKet(j, m) + hbar**2*j*JzKet(j, m) + # Normal operators, coupled states + # Numerical + assert qapply(J2*JxKetCoupled(1, 1, (1, 1))) == \ + 2*hbar**2*JxKetCoupled(1, 1, (1, 1)) + assert qapply(J2*JyKetCoupled(1, 1, (1, 1))) == \ + 2*hbar**2*JyKetCoupled(1, 1, (1, 1)) + assert qapply(J2*JzKetCoupled(1, 1, (1, 1))) == \ + 2*hbar**2*JzKetCoupled(1, 1, (1, 1)) + # Symbolic + assert qapply(J2*JxKetCoupled(j, m, (j1, j2))) == \ + hbar**2*j**2*JxKetCoupled(j, m, (j1, j2)) + \ + hbar**2*j*JxKetCoupled(j, m, (j1, j2)) + assert qapply(J2*JyKetCoupled(j, m, (j1, j2))) == \ + hbar**2*j**2*JyKetCoupled(j, m, (j1, j2)) + \ + hbar**2*j*JyKetCoupled(j, m, (j1, j2)) + assert qapply(J2*JzKetCoupled(j, m, (j1, j2))) == \ + hbar**2*j**2*JzKetCoupled(j, m, (j1, j2)) + \ + hbar**2*j*JzKetCoupled(j, m, (j1, j2)) + # Uncoupled operators, uncoupled states + # Numerical + assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + 2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + 2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + 2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + 2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + 2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1)) + assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + 2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1)) + # Symbolic + assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + hbar**2*j1**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \ + hbar**2*j1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + hbar**2*j2**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \ + hbar**2*j2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + hbar**2*j1**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \ + hbar**2*j1*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + hbar**2*j2**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \ + hbar**2*j2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar**2*j1**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \ + hbar**2*j1*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar**2*j2**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \ + hbar**2*j2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + + +def test_jx(): + assert Commutator(Jx, Jz).doit() == -I*hbar*Jy + assert Jx.rewrite('plusminus') == (Jminus + Jplus)/2 + assert represent(Jx, basis=Jz, j=1) == ( + represent(Jplus, basis=Jz, j=1) + represent(Jminus, basis=Jz, j=1))/2 + # Normal operators, normal states + # Numerical + assert qapply(Jx*JxKet(1, 1)) == hbar*JxKet(1, 1) + assert qapply(Jx*JyKet(1, 1)) == hbar*JyKet(1, 1) + assert qapply(Jx*JzKet(1, 1)) == sqrt(2)*hbar*JzKet(1, 0)/2 + # Symbolic + assert qapply(Jx*JxKet(j, m)) == hbar*m*JxKet(j, m) + assert qapply(Jx*JyKet(j, m)) == \ + Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j, + mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j, mi1), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jx*JzKet(j, m)) == \ + hbar*sqrt(j**2 + j - m**2 - m)*JzKet(j, m + 1)/2 + hbar*sqrt(j**2 + + j - m**2 + m)*JzKet(j, m - 1)/2 + # Normal operators, coupled states + # Numerical + assert qapply(Jx*JxKetCoupled(1, 1, (1, 1))) == \ + hbar*JxKetCoupled(1, 1, (1, 1)) + assert qapply(Jx*JyKetCoupled(1, 1, (1, 1))) == \ + hbar*JyKetCoupled(1, 1, (1, 1)) + assert qapply(Jx*JzKetCoupled(1, 1, (1, 1))) == \ + sqrt(2)*hbar*JzKetCoupled(1, 0, (1, 1))/2 + # Symbolic + assert qapply(Jx*JxKetCoupled(j, m, (j1, j2))) == \ + hbar*m*JxKetCoupled(j, m, (j1, j2)) + assert qapply(Jx*JyKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jx*JzKetCoupled(j, m, (j1, j2))) == \ + hbar*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \ + hbar*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2 + # Normal operators, uncoupled states + # Numerical + assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \ + 2*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1)) + assert qapply(Jx*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \ + hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1)) + \ + hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1)) + assert qapply(Jx*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \ + sqrt(2)*hbar*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \ + sqrt(2)*hbar*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == 0 + # Symbolic + assert qapply(Jx*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \ + hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + assert qapply(Jx*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + \ + TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(Jx*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \ + hbar*sqrt(j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + \ + hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \ + hbar*sqrt( + j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2 + # Uncoupled operators, uncoupled states + # Numerical + assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + -hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + -hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + hbar*sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 + assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + hbar*sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + # Symbolic + assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2) * Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2) * Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \ + hbar*sqrt( + j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \ + hbar*sqrt( + j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2 + + +def test_jy(): + assert Commutator(Jy, Jz).doit() == I*hbar*Jx + assert Jy.rewrite('plusminus') == (Jplus - Jminus)/(2*I) + assert represent(Jy, basis=Jz) == ( + represent(Jplus, basis=Jz) - represent(Jminus, basis=Jz))/(2*I) + # Normal operators, normal states + # Numerical + assert qapply(Jy*JxKet(1, 1)) == hbar*JxKet(1, 1) + assert qapply(Jy*JyKet(1, 1)) == hbar*JyKet(1, 1) + assert qapply(Jy*JzKet(1, 1)) == sqrt(2)*hbar*I*JzKet(1, 0)/2 + # Symbolic + assert qapply(Jy*JxKet(j, m)) == \ + Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), 0, 0)*Sum(WignerD( + j, mi1, mi, 0, 0, pi/2)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jy*JyKet(j, m)) == hbar*m*JyKet(j, m) + assert qapply(Jy*JzKet(j, m)) == \ + -hbar*I*sqrt(j**2 + j - m**2 - m)*JzKet( + j, m + 1)/2 + hbar*I*sqrt(j**2 + j - m**2 + m)*JzKet(j, m - 1)/2 + # Normal operators, coupled states + # Numerical + assert qapply(Jy*JxKetCoupled(1, 1, (1, 1))) == \ + hbar*JxKetCoupled(1, 1, (1, 1)) + assert qapply(Jy*JyKetCoupled(1, 1, (1, 1))) == \ + hbar*JyKetCoupled(1, 1, (1, 1)) + assert qapply(Jy*JzKetCoupled(1, 1, (1, 1))) == \ + sqrt(2)*hbar*I*JzKetCoupled(1, 0, (1, 1))/2 + # Symbolic + assert qapply(Jy*JxKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j, mi1, mi, 0, 0, pi/2)*JxKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jy*JyKetCoupled(j, m, (j1, j2))) == \ + hbar*m*JyKetCoupled(j, m, (j1, j2)) + assert qapply(Jy*JzKetCoupled(j, m, (j1, j2))) == \ + -hbar*I*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \ + hbar*I*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2 + # Normal operators, uncoupled states + # Numerical + assert qapply(Jy*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \ + hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1)) + \ + hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1)) + assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \ + 2*hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1)) + assert qapply(Jy*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \ + sqrt(2)*hbar*I*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \ + sqrt(2)*hbar*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == 0 + # Symbolic + assert qapply(Jy*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j2, mi1, mi, 0, 0, pi/2)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j1, mi1, mi, 0, 0, pi/2)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2)) + assert qapply(Jy*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + hbar*m1*TensorProduct(JyKet(j1, m1), JyKet( + j2, m2)) + hbar*m2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + assert qapply(Jy*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + -hbar*I*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \ + hbar*I*sqrt(j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + \ + -hbar*I*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \ + hbar*I*sqrt( + j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2 + # Uncoupled operators, uncoupled states + # Numerical + assert qapply(TensorProduct(Jy, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(1, Jy)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + -hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + assert qapply(TensorProduct(Jy, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(1, Jy)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + -hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + assert qapply(TensorProduct(Jy, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + hbar*sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 + assert qapply(TensorProduct(1, Jy)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + -hbar*sqrt(2)*I*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + # Symbolic + assert qapply(TensorProduct(Jy, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), 0, 0) * Sum(WignerD(j1, mi1, mi, 0, 0, pi/2)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2)) + assert qapply(TensorProduct(1, Jy)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0) * Sum(WignerD(j2, mi1, mi, 0, 0, pi/2)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jy, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + hbar*m1*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + assert qapply(TensorProduct(1, Jy)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + hbar*m2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + assert qapply(TensorProduct(Jy, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + -hbar*I*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \ + hbar*I*sqrt( + j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + assert qapply(TensorProduct(1, Jy)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + -hbar*I*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \ + hbar*I*sqrt( + j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2 + + +def test_jz(): + assert Commutator(Jz, Jminus).doit() == -hbar*Jminus + # Normal operators, normal states + # Numerical + assert qapply(Jz*JxKet(1, 1)) == -sqrt(2)*hbar*JxKet(1, 0)/2 + assert qapply(Jz*JyKet(1, 1)) == -sqrt(2)*hbar*I*JyKet(1, 0)/2 + assert qapply(Jz*JzKet(2, 1)) == hbar*JzKet(2, 1) + # Symbolic + assert qapply(Jz*JxKet(j, m)) == \ + Sum(hbar*mi*WignerD(j, mi, m, 0, pi/2, 0)*Sum(WignerD(j, + mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jz*JyKet(j, m)) == \ + Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j, mi1, + mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j, mi1), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jz*JzKet(j, m)) == hbar*m*JzKet(j, m) + # Normal operators, coupled states + # Numerical + assert qapply(Jz*JxKetCoupled(1, 1, (1, 1))) == \ + -sqrt(2)*hbar*JxKetCoupled(1, 0, (1, 1))/2 + assert qapply(Jz*JyKetCoupled(1, 1, (1, 1))) == \ + -sqrt(2)*hbar*I*JyKetCoupled(1, 0, (1, 1))/2 + assert qapply(Jz*JzKetCoupled(1, 1, (1, 1))) == \ + hbar*JzKetCoupled(1, 1, (1, 1)) + # Symbolic + assert qapply(Jz*JxKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar*mi*WignerD(j, mi, m, 0, pi/2, 0)*Sum(WignerD(j, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jz*JyKetCoupled(j, m, (j1, j2))) == \ + Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j)) + assert qapply(Jz*JzKetCoupled(j, m, (j1, j2))) == \ + hbar*m*JzKetCoupled(j, m, (j1, j2)) + # Normal operators, uncoupled states + # Numerical + assert qapply(Jz*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \ + -sqrt(2)*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2 - \ + sqrt(2)*hbar*TensorProduct(JxKet(1, 0), JxKet(1, 1))/2 + assert qapply(Jz*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \ + -sqrt(2)*hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2 - \ + sqrt(2)*hbar*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2 + assert qapply(Jz*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \ + 2*hbar*TensorProduct(JzKet(1, 1), JzKet(1, 1)) + assert qapply(Jz*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0 + # Symbolic + assert qapply(Jz*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, pi/2, 0)*Sum(WignerD(j2, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, pi/2, 0)*Sum(WignerD(j1, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2)) + assert qapply(Jz*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + assert qapply(Jz*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*m1*TensorProduct(JzKet(j1, m1), JzKet( + j2, m2)) + hbar*m2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + # Uncoupled Operators + # Numerical + assert qapply(TensorProduct(Jz, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + -sqrt(2)*hbar*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2 + assert qapply(TensorProduct(1, Jz)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \ + -sqrt(2)*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2 + assert qapply(TensorProduct(Jz, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + -sqrt(2)*I*hbar*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2 + assert qapply(TensorProduct(1, Jz)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \ + sqrt(2)*I*hbar*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2 + assert qapply(TensorProduct(Jz, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + hbar*TensorProduct(JzKet(1, 1), JzKet(1, -1)) + assert qapply(TensorProduct(1, Jz)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \ + -hbar*TensorProduct(JzKet(1, 1), JzKet(1, -1)) + # Symbolic + assert qapply(TensorProduct(Jz, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, pi/2, 0)*Sum(WignerD(j1, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2)) + assert qapply(TensorProduct(1, Jz)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \ + TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, pi/2, 0)*Sum(WignerD(j2, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jz, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + assert qapply(TensorProduct(1, Jz)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \ + TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + assert qapply(TensorProduct(Jz, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*m1*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + assert qapply(TensorProduct(1, Jz)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \ + hbar*m2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + + +def test_rotation(): + a, b, g = symbols('a b g') + j, m = symbols('j m') + #Uncoupled + answ = [JxKet(1,-1)/2 - sqrt(2)*JxKet(1,0)/2 + JxKet(1,1)/2 , + JyKet(1,-1)/2 - sqrt(2)*JyKet(1,0)/2 + JyKet(1,1)/2 , + JzKet(1,-1)/2 - sqrt(2)*JzKet(1,0)/2 + JzKet(1,1)/2] + fun = [state(1, 1) for state in (JxKet, JyKet, JzKet)] + for state in fun: + got = qapply(Rotation(0, pi/2, 0)*state) + assert got in answ + answ.remove(got) + assert not answ + arg = Rotation(a, b, g)*fun[0] + assert qapply(arg) == (-exp(-I*a)*exp(I*g)*cos(b)*JxKet(1,-1)/2 + + exp(-I*a)*exp(I*g)*JxKet(1,-1)/2 - sqrt(2)*exp(-I*a)*sin(b)*JxKet(1,0)/2 + + exp(-I*a)*exp(-I*g)*cos(b)*JxKet(1,1)/2 + exp(-I*a)*exp(-I*g)*JxKet(1,1)/2) + #dummy effective + assert str(qapply(Rotation(a, b, g)*JzKet(j, m), dummy=False)) == str( + qapply(Rotation(a, b, g)*JzKet(j, m), dummy=True)).replace('_','') + #Coupled + ans = [JxKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JxKetCoupled(1,0,(1,1))/2 + + JxKetCoupled(1,1,(1,1))/2 , + JyKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JyKetCoupled(1,0,(1,1))/2 + + JyKetCoupled(1,1,(1,1))/2 , + JzKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JzKetCoupled(1,0,(1,1))/2 + + JzKetCoupled(1,1,(1,1))/2] + fun = [state(1, 1, (1,1)) for state in (JxKetCoupled, JyKetCoupled, JzKetCoupled)] + for state in fun: + got = qapply(Rotation(0, pi/2, 0)*state) + assert got in ans + ans.remove(got) + assert not ans + arg = Rotation(a, b, g)*fun[0] + assert qapply(arg) == ( + -exp(-I*a)*exp(I*g)*cos(b)*JxKetCoupled(1,-1,(1,1))/2 + + exp(-I*a)*exp(I*g)*JxKetCoupled(1,-1,(1,1))/2 - + sqrt(2)*exp(-I*a)*sin(b)*JxKetCoupled(1,0,(1,1))/2 + + exp(-I*a)*exp(-I*g)*cos(b)*JxKetCoupled(1,1,(1,1))/2 + + exp(-I*a)*exp(-I*g)*JxKetCoupled(1,1,(1,1))/2) + #dummy effective + assert str(qapply(Rotation(a,b,g)*JzKetCoupled(j,m,(j1,j2)), dummy=False)) == str( + qapply(Rotation(a,b,g)*JzKetCoupled(j,m,(j1,j2)), dummy=True)).replace('_','') + + +def test_jzket(): + j, m = symbols('j m') + # j not integer or half integer + raises(ValueError, lambda: JzKet(Rational(2, 3), Rational(-1, 3))) + raises(ValueError, lambda: JzKet(Rational(2, 3), m)) + # j < 0 + raises(ValueError, lambda: JzKet(-1, 1)) + raises(ValueError, lambda: JzKet(-1, m)) + # m not integer or half integer + raises(ValueError, lambda: JzKet(j, Rational(-1, 3))) + # abs(m) > j + raises(ValueError, lambda: JzKet(1, 2)) + raises(ValueError, lambda: JzKet(1, -2)) + # j-m not integer + raises(ValueError, lambda: JzKet(1, S.Half)) + + +def test_jzketcoupled(): + j, m = symbols('j m') + # j not integer or half integer + raises(ValueError, lambda: JzKetCoupled(Rational(2, 3), Rational(-1, 3), (1,))) + raises(ValueError, lambda: JzKetCoupled(Rational(2, 3), m, (1,))) + # j < 0 + raises(ValueError, lambda: JzKetCoupled(-1, 1, (1,))) + raises(ValueError, lambda: JzKetCoupled(-1, m, (1,))) + # m not integer or half integer + raises(ValueError, lambda: JzKetCoupled(j, Rational(-1, 3), (1,))) + # abs(m) > j + raises(ValueError, lambda: JzKetCoupled(1, 2, (1,))) + raises(ValueError, lambda: JzKetCoupled(1, -2, (1,))) + # j-m not integer + raises(ValueError, lambda: JzKetCoupled(1, S.Half, (1,))) + # checks types on coupling scheme + raises(TypeError, lambda: JzKetCoupled(1, 1, 1)) + raises(TypeError, lambda: JzKetCoupled(1, 1, (1,), 1)) + raises(TypeError, lambda: JzKetCoupled(1, 1, (1, 1), (1,))) + raises(TypeError, lambda: JzKetCoupled(1, 1, (1, 1, 1), (1, 2, 1), + (1, 3, 1))) + # checks length of coupling terms + raises(ValueError, lambda: JzKetCoupled(1, 1, (1,), ((1, 2, 1),))) + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 2),))) + # all jn are integer or half-integer + raises(ValueError, lambda: JzKetCoupled(1, 1, (Rational(1, 3), Rational(2, 3)))) + # indices in coupling scheme must be integers + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((S.Half, 1, 2),) )) + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, S.Half, 2),) )) + # indices out of range + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((0, 2, 1),) )) + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((3, 2, 1),) )) + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 0, 1),) )) + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 3, 1),) )) + # all j values in coupling scheme must by integer or half-integer + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, S( + 4)/3), (1, 3, 1)) )) + # each coupling must satisfy |j1-j2| <= j3 <= j1+j2 + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 5))) + raises(ValueError, lambda: JzKetCoupled(5, 1, (1, 1))) + # final j of coupling must be j of the state + raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 2, 2),) )) diff --git a/shared/package-files/2c/2ce3f911e1aa222f23e91d15fb87a81bd899357df47377506f5279f6d77fe0ab/message_factory.pyi b/shared/package-files/2c/2ce3f911e1aa222f23e91d15fb87a81bd899357df47377506f5279f6d77fe0ab/message_factory.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d8a42d30bc654ffa985584eb53f695ad4cbf5ef6 --- /dev/null +++ b/shared/package-files/2c/2ce3f911e1aa222f23e91d15fb87a81bd899357df47377506f5279f6d77fe0ab/message_factory.pyi @@ -0,0 +1,14 @@ +from typing import Any, Dict, Iterable, Optional, Type + +from google.protobuf.descriptor import Descriptor +from google.protobuf.descriptor_pb2 import FileDescriptorProto +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +class MessageFactory: + pool: Any + def __init__(self, pool: Optional[DescriptorPool] = ...) -> None: ... + def GetPrototype(self, descriptor: Descriptor) -> Type[Message]: ... + def GetMessages(self, files: Iterable[str]) -> Dict[str, Type[Message]]: ... + +def GetMessages(file_protos: Iterable[FileDescriptorProto]) -> Dict[str, Type[Message]]: ... diff --git a/shared/package-files/2c/2cec417b28c18306bf86609f97386c39f090283bd2714d387144d2e07acc12b8/__init__.pyi b/shared/package-files/2c/2cec417b28c18306bf86609f97386c39f090283bd2714d387144d2e07acc12b8/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cc54647732cc0ea554c17fe3bf30ef303e728e6f --- /dev/null +++ b/shared/package-files/2c/2cec417b28c18306bf86609f97386c39f090283bd2714d387144d2e07acc12b8/__init__.pyi @@ -0,0 +1,59 @@ +# 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 + +from cryptography.hazmat.bindings._rust.openssl import ( + aead, + cmac, + dh, + dsa, + ec, + ed448, + ed25519, + hashes, + hmac, + kdf, + keys, + poly1305, + rsa, + x448, + x25519, +) + +__all__ = [ + "openssl_version", + "raise_openssl_error", + "aead", + "cmac", + "dh", + "dsa", + "ec", + "hashes", + "hmac", + "kdf", + "keys", + "ed448", + "ed25519", + "rsa", + "poly1305", + "x448", + "x25519", +] + +_legacy_provider_loaded: bool + +def openssl_version() -> int: ... +def raise_openssl_error() -> typing.NoReturn: ... +def capture_error_stack() -> list[OpenSSLError]: ... +def is_fips_enabled() -> bool: ... + +class OpenSSLError: + @property + def lib(self) -> int: ... + @property + def reason(self) -> int: ... + @property + def reason_text(self) -> bytes: ... + def _lib_reason_match(self, lib: int, reason: int) -> bool: ... diff --git a/shared/package-files/2c/2cedc3619ce75fad437ba6eed9440fa8bb4b3125bb49ca8895ee33f63c1f347d/ansi+local b/shared/package-files/2c/2cedc3619ce75fad437ba6eed9440fa8bb4b3125bb49ca8895ee33f63c1f347d/ansi+local new file mode 100644 index 0000000000000000000000000000000000000000..4a3abd05396b36888f567d96df096378aff62803 Binary files /dev/null and b/shared/package-files/2c/2cedc3619ce75fad437ba6eed9440fa8bb4b3125bb49ca8895ee33f63c1f347d/ansi+local differ diff --git a/shared/package-files/2c/2cf06e812cde63bd5f33c691655c5ad220d0c439c9042d51f534f9c31782a5bf/attributes.h b/shared/package-files/2c/2cf06e812cde63bd5f33c691655c5ad220d0c439c9042d51f534f9c31782a5bf/attributes.h new file mode 100644 index 0000000000000000000000000000000000000000..c053fc9d8d9d231425c20b389c71559b87a422d8 --- /dev/null +++ b/shared/package-files/2c/2cf06e812cde63bd5f33c691655c5ad220d0c439c9042d51f534f9c31782a5bf/attributes.h @@ -0,0 +1,184 @@ +#pragma once +#include +#include +#include + +#include +#include + +#include + +namespace torch { +namespace jit { + +using ::c10::Symbol; + +constexpr int max_tensor_display_size = 10; + +enum class AttributeKind { + f, + fs, + c, + cs, + i, + is, + s, + ss, + t, + ts, + g, + gs, + ty, + tys, + ival +}; +static inline const char* toString(AttributeKind kind) { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + static const char* names[] = { + "f", + "c", + "cs", + "fs", + "i", + "is", + "s", + "ss", + "t", + "ts", + "g", + "gs", + "ty", + "tys", + "ival"}; + AT_ASSERT(size_t(kind) < sizeof(names) / sizeof(*names)); + return names[int(kind)]; +} + +struct AttributeValue { + AttributeValue(Symbol name) : name(name) {} + using Ptr = std::unique_ptr; + Symbol name; + virtual AttributeKind kind() const = 0; + virtual Ptr clone() const = 0; + virtual ~AttributeValue() = default; +}; + +template +struct ScalarAttributeValue : public AttributeValue { + using ConstructorType = T; + using ValueType = T; + ScalarAttributeValue(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + Ptr clone() const override { + return Ptr(new ScalarAttributeValue(name, value_)); + } + AttributeKind kind() const override { + return Kind; + } + + private: + ValueType value_; +}; + +template +struct VectorAttributeValue : public AttributeValue { + using ConstructorType = std::vector; + using ValueType = std::vector; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + VectorAttributeValue(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + AttributeKind kind() const override { + return Kind; + } + std::unique_ptr clone() const override { + auto copy = value_; + return Ptr(new VectorAttributeValue(name, std::move(copy))); + } + + private: + ValueType value_; +}; + +using ComplexAttr = + ScalarAttributeValue, AttributeKind::c>; +using ComplexValsAttr = + VectorAttributeValue, AttributeKind::cs>; +using FloatAttr = ScalarAttributeValue; +using FloatsAttr = VectorAttributeValue; +using IntAttr = ScalarAttributeValue; +using IntsAttr = VectorAttributeValue; +using StringAttr = ScalarAttributeValue; +using StringsAttr = VectorAttributeValue; +using TensorAttr = ScalarAttributeValue; +using TensorsAttr = VectorAttributeValue; +using TypeAttr = ScalarAttributeValue; +using TypesAttr = VectorAttributeValue; +using IValueAttr = ScalarAttributeValue; + +struct Graph; + +// We special case Graph attributes like this because we want to ensure that +// Graph::copy() is called when we clone() these attributes. +struct TORCH_API GraphAttr : public AttributeValue { + using ConstructorType = std::shared_ptr; + using ValueType = std::shared_ptr; + GraphAttr(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + Ptr clone() const override; + AttributeKind kind() const override { + return AttributeKind::g; + } + + private: + std::shared_ptr value_; +}; + +struct TORCH_API GraphsAttr : public AttributeValue { + using ConstructorType = std::vector>; + using ValueType = std::vector>; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + GraphsAttr(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + AttributeKind kind() const override { + return AttributeKind::gs; + } + std::unique_ptr clone() const override; + + private: + ValueType value_; +}; + +struct IRAttributeError : public std::exception { + IRAttributeError(Symbol name, bool defined) { + std::stringstream ss; + // NOLINTNEXTLINE(bugprone-branch-clone) + if (!defined) { + ss << "required keyword attribute '" << name.toUnqualString() + << "' is undefined"; + } else { + ss << "required keyword attribute '" << name.toUnqualString() + << "' has the wrong type"; + } + msg = ss.str(); + } + const char* what() const noexcept override { + return msg.c_str(); + } + + private: + std::string msg; +}; +} // namespace jit +} // namespace torch diff --git a/shared/package-files/2c/2cf3b3f857a74c9eac721e2ed9462c9847d71c30bea83be92c534257fc170ec8/ConvolutionMM3d.h b/shared/package-files/2c/2cf3b3f857a74c9eac721e2ed9462c9847d71c30bea83be92c534257fc170ec8/ConvolutionMM3d.h new file mode 100644 index 0000000000000000000000000000000000000000..3de6763015c6616599a604ee169dacc55985a385 --- /dev/null +++ b/shared/package-files/2c/2cf3b3f857a74c9eac721e2ed9462c9847d71c30bea83be92c534257fc170ec8/ConvolutionMM3d.h @@ -0,0 +1,14 @@ +#include + +namespace at::native { + +std::tuple slow_conv3d_backward_cpu( + const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + std::array output_mask); + +} // namespace at::native diff --git a/shared/package-files/2c/2cf52464a1e19296593a1fc28ba7c6bb792273b39286fea4c4637523af61c262/special_polygamma_native.h b/shared/package-files/2c/2cf52464a1e19296593a1fc28ba7c6bb792273b39286fea4c4637523af61c262/special_polygamma_native.h new file mode 100644 index 0000000000000000000000000000000000000000..bc898d5f5dc755aa5ae4d85d76767994ed15755c --- /dev/null +++ b/shared/package-files/2c/2cf52464a1e19296593a1fc28ba7c6bb792273b39286fea4c4637523af61c262/special_polygamma_native.h @@ -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 special_polygamma(int64_t n, const at::Tensor & self); +TORCH_API at::Tensor & special_polygamma_out(int64_t n, const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/2c/2cf600c68b99ec9622bb7cf81e7363906b6360bb88b1c3b1297898e91893bfaa/test_retrieve_autoconverted_arrays.py b/shared/package-files/2c/2cf600c68b99ec9622bb7cf81e7363906b6360bb88b1c3b1297898e91893bfaa/test_retrieve_autoconverted_arrays.py new file mode 100644 index 0000000000000000000000000000000000000000..640efcac3de4c0803789797d1e4b33211b1aa790 --- /dev/null +++ b/shared/package-files/2c/2cf600c68b99ec9622bb7cf81e7363906b6360bb88b1c3b1297898e91893bfaa/test_retrieve_autoconverted_arrays.py @@ -0,0 +1,83 @@ +import numpy as np + +from numba import cuda +from numba.cuda.args import wrap_arg +from numba.cuda.testing import CUDATestCase +import unittest + + +class DefaultIn(object): + def prepare_args(self, ty, val, **kwargs): + return ty, wrap_arg(val, default=cuda.In) + + +def nocopy(kernel): + kernel.extensions.append(DefaultIn()) + return kernel + + +def set_array_to_three(arr): + arr[0] = 3 + + +def set_record_to_three(rec): + rec[0]['b'] = 3 + + +recordtype = np.dtype( + [('b', np.int32)], + align=True +) + + +class TestRetrieveAutoconvertedArrays(CUDATestCase): + def setUp(self): + super().setUp() + self.set_array_to_three = cuda.jit(set_array_to_three) + self.set_array_to_three_nocopy = nocopy(cuda.jit(set_array_to_three)) + self.set_record_to_three = cuda.jit(set_record_to_three) + self.set_record_to_three_nocopy = nocopy(cuda.jit(set_record_to_three)) + + def test_array_inout(self): + host_arr = np.zeros(1, dtype=np.int64) + self.set_array_to_three[1, 1](cuda.InOut(host_arr)) + self.assertEqual(3, host_arr[0]) + + def test_array_in(self): + host_arr = np.zeros(1, dtype=np.int64) + self.set_array_to_three[1, 1](cuda.In(host_arr)) + self.assertEqual(0, host_arr[0]) + + def test_array_in_from_config(self): + host_arr = np.zeros(1, dtype=np.int64) + self.set_array_to_three_nocopy[1, 1](host_arr) + self.assertEqual(0, host_arr[0]) + + def test_array_default(self): + host_arr = np.zeros(1, dtype=np.int64) + self.set_array_to_three[1, 1](host_arr) + self.assertEqual(3, host_arr[0]) + + def test_record_in(self): + host_rec = np.zeros(1, dtype=recordtype) + self.set_record_to_three[1, 1](cuda.In(host_rec)) + self.assertEqual(0, host_rec[0]['b']) + + def test_record_inout(self): + host_rec = np.zeros(1, dtype=recordtype) + self.set_record_to_three[1, 1](cuda.InOut(host_rec)) + self.assertEqual(3, host_rec[0]['b']) + + def test_record_default(self): + host_rec = np.zeros(1, dtype=recordtype) + self.set_record_to_three[1, 1](host_rec) + self.assertEqual(3, host_rec[0]['b']) + + def test_record_in_from_config(self): + host_rec = np.zeros(1, dtype=recordtype) + self.set_record_to_three_nocopy[1, 1](host_rec) + self.assertEqual(0, host_rec[0]['b']) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/2c/2cf698f91c982fb5edddd8c280d69612023c6de23d128fd79ef3b08ba63bf9ea/linalg.pyi b/shared/package-files/2c/2cf698f91c982fb5edddd8c280d69612023c6de23d128fd79ef3b08ba63bf9ea/linalg.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f011aedd93db337e468a6f4f450c11800a5f3ae4 --- /dev/null +++ b/shared/package-files/2c/2cf698f91c982fb5edddd8c280d69612023c6de23d128fd79ef3b08ba63bf9ea/linalg.pyi @@ -0,0 +1,106 @@ +import sys +from typing import Any + +import numpy as np +import numpy.typing as npt +from numpy.linalg.linalg import QRResult, EigResult, EighResult, SVDResult, SlogdetResult + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +AR_i8: npt.NDArray[np.int64] +AR_f8: npt.NDArray[np.float64] +AR_c16: npt.NDArray[np.complex128] +AR_O: npt.NDArray[np.object_] +AR_m: npt.NDArray[np.timedelta64] +AR_S: npt.NDArray[np.str_] + +assert_type(np.linalg.tensorsolve(AR_i8, AR_i8), npt.NDArray[np.float64]) +assert_type(np.linalg.tensorsolve(AR_i8, AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.tensorsolve(AR_c16, AR_f8), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.linalg.solve(AR_i8, AR_i8), npt.NDArray[np.float64]) +assert_type(np.linalg.solve(AR_i8, AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.solve(AR_c16, AR_f8), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.linalg.tensorinv(AR_i8), npt.NDArray[np.float64]) +assert_type(np.linalg.tensorinv(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.tensorinv(AR_c16), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.linalg.inv(AR_i8), npt.NDArray[np.float64]) +assert_type(np.linalg.inv(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.inv(AR_c16), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.linalg.matrix_power(AR_i8, -1), npt.NDArray[Any]) +assert_type(np.linalg.matrix_power(AR_f8, 0), npt.NDArray[Any]) +assert_type(np.linalg.matrix_power(AR_c16, 1), npt.NDArray[Any]) +assert_type(np.linalg.matrix_power(AR_O, 2), npt.NDArray[Any]) + +assert_type(np.linalg.cholesky(AR_i8), npt.NDArray[np.float64]) +assert_type(np.linalg.cholesky(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.cholesky(AR_c16), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.linalg.qr(AR_i8), QRResult) +assert_type(np.linalg.qr(AR_f8), QRResult) +assert_type(np.linalg.qr(AR_c16), QRResult) + +assert_type(np.linalg.eigvals(AR_i8), npt.NDArray[np.float64] | npt.NDArray[np.complex128]) +assert_type(np.linalg.eigvals(AR_f8), npt.NDArray[np.floating[Any]] | npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(np.linalg.eigvals(AR_c16), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.linalg.eigvalsh(AR_i8), npt.NDArray[np.float64]) +assert_type(np.linalg.eigvalsh(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.eigvalsh(AR_c16), npt.NDArray[np.floating[Any]]) + +assert_type(np.linalg.eig(AR_i8), EigResult) +assert_type(np.linalg.eig(AR_f8), EigResult) +assert_type(np.linalg.eig(AR_c16), EigResult) + +assert_type(np.linalg.eigh(AR_i8), EighResult) +assert_type(np.linalg.eigh(AR_f8), EighResult) +assert_type(np.linalg.eigh(AR_c16), EighResult) + +assert_type(np.linalg.svd(AR_i8), SVDResult) +assert_type(np.linalg.svd(AR_f8), SVDResult) +assert_type(np.linalg.svd(AR_c16), SVDResult) +assert_type(np.linalg.svd(AR_i8, compute_uv=False), npt.NDArray[np.float64]) +assert_type(np.linalg.svd(AR_f8, compute_uv=False), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.svd(AR_c16, compute_uv=False), npt.NDArray[np.floating[Any]]) + +assert_type(np.linalg.cond(AR_i8), Any) +assert_type(np.linalg.cond(AR_f8), Any) +assert_type(np.linalg.cond(AR_c16), Any) + +assert_type(np.linalg.matrix_rank(AR_i8), Any) +assert_type(np.linalg.matrix_rank(AR_f8), Any) +assert_type(np.linalg.matrix_rank(AR_c16), Any) + +assert_type(np.linalg.pinv(AR_i8), npt.NDArray[np.float64]) +assert_type(np.linalg.pinv(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.linalg.pinv(AR_c16), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.linalg.slogdet(AR_i8), SlogdetResult) +assert_type(np.linalg.slogdet(AR_f8), SlogdetResult) +assert_type(np.linalg.slogdet(AR_c16), SlogdetResult) + +assert_type(np.linalg.det(AR_i8), Any) +assert_type(np.linalg.det(AR_f8), Any) +assert_type(np.linalg.det(AR_c16), Any) + +assert_type(np.linalg.lstsq(AR_i8, AR_i8), tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], np.int32, npt.NDArray[np.float64]]) +assert_type(np.linalg.lstsq(AR_i8, AR_f8), tuple[npt.NDArray[np.floating[Any]], npt.NDArray[np.floating[Any]], np.int32, npt.NDArray[np.floating[Any]]]) +assert_type(np.linalg.lstsq(AR_f8, AR_c16), tuple[npt.NDArray[np.complexfloating[Any, Any]], npt.NDArray[np.floating[Any]], np.int32, npt.NDArray[np.floating[Any]]]) + +assert_type(np.linalg.norm(AR_i8), np.floating[Any]) +assert_type(np.linalg.norm(AR_f8), np.floating[Any]) +assert_type(np.linalg.norm(AR_c16), np.floating[Any]) +assert_type(np.linalg.norm(AR_S), np.floating[Any]) +assert_type(np.linalg.norm(AR_f8, axis=0), Any) + +assert_type(np.linalg.multi_dot([AR_i8, AR_i8]), Any) +assert_type(np.linalg.multi_dot([AR_i8, AR_f8]), Any) +assert_type(np.linalg.multi_dot([AR_f8, AR_c16]), Any) +assert_type(np.linalg.multi_dot([AR_O, AR_O]), Any) +assert_type(np.linalg.multi_dot([AR_m, AR_m]), Any) diff --git a/shared/package-files/2c/2cf75f64436fb5be374a2eaa27ab8b7e1fd651c9b46daea6c67b02fd64e2458b/metaschema.json b/shared/package-files/2c/2cf75f64436fb5be374a2eaa27ab8b7e1fd651c9b46daea6c67b02fd64e2458b/metaschema.json new file mode 100644 index 0000000000000000000000000000000000000000..8b26b1f89f9852e4f69f466dd7d718b21ba5b989 --- /dev/null +++ b/shared/package-files/2c/2cf75f64436fb5be374a2eaa27ab8b7e1fd651c9b46daea6c67b02fd64e2458b/metaschema.json @@ -0,0 +1,172 @@ +{ + "$schema" : "http://json-schema.org/draft-03/schema#", + "id" : "http://json-schema.org/draft-03/schema#", + "type" : "object", + + "properties" : { + "type" : { + "type" : ["string", "array"], + "items" : { + "type" : ["string", {"$ref" : "#"}] + }, + "uniqueItems" : true, + "default" : "any" + }, + + "properties" : { + "type" : "object", + "additionalProperties" : {"$ref" : "#"}, + "default" : {} + }, + + "patternProperties" : { + "type" : "object", + "additionalProperties" : {"$ref" : "#"}, + "default" : {} + }, + + "additionalProperties" : { + "type" : [{"$ref" : "#"}, "boolean"], + "default" : {} + }, + + "items" : { + "type" : [{"$ref" : "#"}, "array"], + "items" : {"$ref" : "#"}, + "default" : {} + }, + + "additionalItems" : { + "type" : [{"$ref" : "#"}, "boolean"], + "default" : {} + }, + + "required" : { + "type" : "boolean", + "default" : false + }, + + "dependencies" : { + "type" : "object", + "additionalProperties" : { + "type" : ["string", "array", {"$ref" : "#"}], + "items" : { + "type" : "string" + } + }, + "default" : {} + }, + + "minimum" : { + "type" : "number" + }, + + "maximum" : { + "type" : "number" + }, + + "exclusiveMinimum" : { + "type" : "boolean", + "default" : false + }, + + "exclusiveMaximum" : { + "type" : "boolean", + "default" : false + }, + + "minItems" : { + "type" : "integer", + "minimum" : 0, + "default" : 0 + }, + + "maxItems" : { + "type" : "integer", + "minimum" : 0 + }, + + "uniqueItems" : { + "type" : "boolean", + "default" : false + }, + + "pattern" : { + "type" : "string", + "format" : "regex" + }, + + "minLength" : { + "type" : "integer", + "minimum" : 0, + "default" : 0 + }, + + "maxLength" : { + "type" : "integer" + }, + + "enum" : { + "type" : "array", + "minItems" : 1, + "uniqueItems" : true + }, + + "default" : { + "type" : "any" + }, + + "title" : { + "type" : "string" + }, + + "description" : { + "type" : "string" + }, + + "format" : { + "type" : "string" + }, + + "divisibleBy" : { + "type" : "number", + "minimum" : 0, + "exclusiveMinimum" : true, + "default" : 1 + }, + + "disallow" : { + "type" : ["string", "array"], + "items" : { + "type" : ["string", {"$ref" : "#"}] + }, + "uniqueItems" : true + }, + + "extends" : { + "type" : [{"$ref" : "#"}, "array"], + "items" : {"$ref" : "#"}, + "default" : {} + }, + + "id" : { + "type" : "string" + }, + + "$ref" : { + "type" : "string" + }, + + "$schema" : { + "type" : "string", + "format" : "uri" + } + }, + + "dependencies" : { + "exclusiveMinimum" : "minimum", + "exclusiveMaximum" : "maximum" + }, + + "default" : {} +} diff --git a/shared/package-files/2c/2cfbc0bc8c54fa9e62fd07be89cee112fa383937d2acda69971306ece0197bc4/type_check.pyi b/shared/package-files/2c/2cfbc0bc8c54fa9e62fd07be89cee112fa383937d2acda69971306ece0197bc4/type_check.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b04da21d44b6bad5cb50ea8abaa091b5a753da11 --- /dev/null +++ b/shared/package-files/2c/2cfbc0bc8c54fa9e62fd07be89cee112fa383937d2acda69971306ece0197bc4/type_check.pyi @@ -0,0 +1,222 @@ +from collections.abc import Container, Iterable +from typing import ( + Literal as L, + Any, + overload, + TypeVar, + Protocol, +) + +from numpy import ( + dtype, + generic, + bool_, + floating, + float64, + complexfloating, + integer, +) + +from numpy._typing import ( + ArrayLike, + DTypeLike, + NBitBase, + NDArray, + _64Bit, + _SupportsDType, + _ScalarLike_co, + _ArrayLike, + _DTypeLikeComplex, +) + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_SCT = TypeVar("_SCT", bound=generic) +_NBit1 = TypeVar("_NBit1", bound=NBitBase) +_NBit2 = TypeVar("_NBit2", bound=NBitBase) + +class _SupportsReal(Protocol[_T_co]): + @property + def real(self) -> _T_co: ... + +class _SupportsImag(Protocol[_T_co]): + @property + def imag(self) -> _T_co: ... + +__all__: list[str] + +def mintypecode( + typechars: Iterable[str | ArrayLike], + typeset: Container[str] = ..., + default: str = ..., +) -> str: ... + +# `asfarray` ignores dtypes if they're not inexact + +@overload +def asfarray( + a: object, + dtype: None | type[float] = ..., +) -> NDArray[float64]: ... +@overload +def asfarray( # type: ignore[misc] + a: Any, + dtype: _DTypeLikeComplex, +) -> NDArray[complexfloating[Any, Any]]: ... +@overload +def asfarray( + a: Any, + dtype: DTypeLike, +) -> NDArray[floating[Any]]: ... + +@overload +def real(val: _SupportsReal[_T]) -> _T: ... +@overload +def real(val: ArrayLike) -> NDArray[Any]: ... + +@overload +def imag(val: _SupportsImag[_T]) -> _T: ... +@overload +def imag(val: ArrayLike) -> NDArray[Any]: ... + +@overload +def iscomplex(x: _ScalarLike_co) -> bool_: ... # type: ignore[misc] +@overload +def iscomplex(x: ArrayLike) -> NDArray[bool_]: ... + +@overload +def isreal(x: _ScalarLike_co) -> bool_: ... # type: ignore[misc] +@overload +def isreal(x: ArrayLike) -> NDArray[bool_]: ... + +def iscomplexobj(x: _SupportsDType[dtype[Any]] | ArrayLike) -> bool: ... + +def isrealobj(x: _SupportsDType[dtype[Any]] | ArrayLike) -> bool: ... + +@overload +def nan_to_num( # type: ignore[misc] + x: _SCT, + copy: bool = ..., + nan: float = ..., + posinf: None | float = ..., + neginf: None | float = ..., +) -> _SCT: ... +@overload +def nan_to_num( + x: _ScalarLike_co, + copy: bool = ..., + nan: float = ..., + posinf: None | float = ..., + neginf: None | float = ..., +) -> Any: ... +@overload +def nan_to_num( + x: _ArrayLike[_SCT], + copy: bool = ..., + nan: float = ..., + posinf: None | float = ..., + neginf: None | float = ..., +) -> NDArray[_SCT]: ... +@overload +def nan_to_num( + x: ArrayLike, + copy: bool = ..., + nan: float = ..., + posinf: None | float = ..., + neginf: None | float = ..., +) -> NDArray[Any]: ... + +# If one passes a complex array to `real_if_close`, then one is reasonably +# expected to verify the output dtype (so we can return an unsafe union here) + +@overload +def real_if_close( # type: ignore[misc] + a: _ArrayLike[complexfloating[_NBit1, _NBit1]], + tol: float = ..., +) -> NDArray[floating[_NBit1]] | NDArray[complexfloating[_NBit1, _NBit1]]: ... +@overload +def real_if_close( + a: _ArrayLike[_SCT], + tol: float = ..., +) -> NDArray[_SCT]: ... +@overload +def real_if_close( + a: ArrayLike, + tol: float = ..., +) -> NDArray[Any]: ... + +@overload +def typename(char: L['S1']) -> L['character']: ... +@overload +def typename(char: L['?']) -> L['bool']: ... +@overload +def typename(char: L['b']) -> L['signed char']: ... +@overload +def typename(char: L['B']) -> L['unsigned char']: ... +@overload +def typename(char: L['h']) -> L['short']: ... +@overload +def typename(char: L['H']) -> L['unsigned short']: ... +@overload +def typename(char: L['i']) -> L['integer']: ... +@overload +def typename(char: L['I']) -> L['unsigned integer']: ... +@overload +def typename(char: L['l']) -> L['long integer']: ... +@overload +def typename(char: L['L']) -> L['unsigned long integer']: ... +@overload +def typename(char: L['q']) -> L['long long integer']: ... +@overload +def typename(char: L['Q']) -> L['unsigned long long integer']: ... +@overload +def typename(char: L['f']) -> L['single precision']: ... +@overload +def typename(char: L['d']) -> L['double precision']: ... +@overload +def typename(char: L['g']) -> L['long precision']: ... +@overload +def typename(char: L['F']) -> L['complex single precision']: ... +@overload +def typename(char: L['D']) -> L['complex double precision']: ... +@overload +def typename(char: L['G']) -> L['complex long double precision']: ... +@overload +def typename(char: L['S']) -> L['string']: ... +@overload +def typename(char: L['U']) -> L['unicode']: ... +@overload +def typename(char: L['V']) -> L['void']: ... +@overload +def typename(char: L['O']) -> L['object']: ... + +@overload +def common_type( # type: ignore[misc] + *arrays: _SupportsDType[dtype[ + integer[Any] + ]] +) -> type[floating[_64Bit]]: ... +@overload +def common_type( # type: ignore[misc] + *arrays: _SupportsDType[dtype[ + floating[_NBit1] + ]] +) -> type[floating[_NBit1]]: ... +@overload +def common_type( # type: ignore[misc] + *arrays: _SupportsDType[dtype[ + integer[Any] | floating[_NBit1] + ]] +) -> type[floating[_NBit1 | _64Bit]]: ... +@overload +def common_type( # type: ignore[misc] + *arrays: _SupportsDType[dtype[ + floating[_NBit1] | complexfloating[_NBit2, _NBit2] + ]] +) -> type[complexfloating[_NBit1 | _NBit2, _NBit1 | _NBit2]]: ... +@overload +def common_type( + *arrays: _SupportsDType[dtype[ + integer[Any] | floating[_NBit1] | complexfloating[_NBit2, _NBit2] + ]] +) -> type[complexfloating[_64Bit | _NBit1 | _NBit2, _64Bit | _NBit1 | _NBit2]]: ... diff --git a/shared/package-files/2c/2cfd70eef996be62b0caa2da535676e3714e58635032b80c519aef805b8e95ca/pkgconfig.py b/shared/package-files/2c/2cfd70eef996be62b0caa2da535676e3714e58635032b80c519aef805b8e95ca/pkgconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..5c93f15a60e6f904b2dd108d6e22044a5890bcb4 --- /dev/null +++ b/shared/package-files/2c/2cfd70eef996be62b0caa2da535676e3714e58635032b80c519aef805b8e95ca/pkgconfig.py @@ -0,0 +1,121 @@ +# pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi +import sys, os, subprocess + +from .error import PkgConfigError + + +def merge_flags(cfg1, cfg2): + """Merge values from cffi config flags cfg2 to cf1 + + Example: + merge_flags({"libraries": ["one"]}, {"libraries": ["two"]}) + {"libraries": ["one", "two"]} + """ + for key, value in cfg2.items(): + if key not in cfg1: + cfg1[key] = value + else: + if not isinstance(cfg1[key], list): + raise TypeError("cfg1[%r] should be a list of strings" % (key,)) + if not isinstance(value, list): + raise TypeError("cfg2[%r] should be a list of strings" % (key,)) + cfg1[key].extend(value) + return cfg1 + + +def call(libname, flag, encoding=sys.getfilesystemencoding()): + """Calls pkg-config and returns the output if found + """ + a = ["pkg-config", "--print-errors"] + a.append(flag) + a.append(libname) + try: + pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + except EnvironmentError as e: + raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),)) + + bout, berr = pc.communicate() + if pc.returncode != 0: + try: + berr = berr.decode(encoding) + except Exception: + pass + raise PkgConfigError(berr.strip()) + + if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x + try: + bout = bout.decode(encoding) + except UnicodeDecodeError: + raise PkgConfigError("pkg-config %s %s returned bytes that cannot " + "be decoded with encoding %r:\n%r" % + (flag, libname, encoding, bout)) + + if os.altsep != '\\' and '\\' in bout: + raise PkgConfigError("pkg-config %s %s returned an unsupported " + "backslash-escaped output:\n%r" % + (flag, libname, bout)) + return bout + + +def flags_from_pkgconfig(libs): + r"""Return compiler line flags for FFI.set_source based on pkg-config output + + Usage + ... + ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"]) + + If pkg-config is installed on build machine, then arguments include_dirs, + library_dirs, libraries, define_macros, extra_compile_args and + extra_link_args are extended with an output of pkg-config for libfoo and + libbar. + + Raises PkgConfigError in case the pkg-config call fails. + """ + + def get_include_dirs(string): + return [x[2:] for x in string.split() if x.startswith("-I")] + + def get_library_dirs(string): + return [x[2:] for x in string.split() if x.startswith("-L")] + + def get_libraries(string): + return [x[2:] for x in string.split() if x.startswith("-l")] + + # convert -Dfoo=bar to list of tuples [("foo", "bar")] expected by distutils + def get_macros(string): + def _macro(x): + x = x[2:] # drop "-D" + if '=' in x: + return tuple(x.split("=", 1)) # "-Dfoo=bar" => ("foo", "bar") + else: + return (x, None) # "-Dfoo" => ("foo", None) + return [_macro(x) for x in string.split() if x.startswith("-D")] + + def get_other_cflags(string): + return [x for x in string.split() if not x.startswith("-I") and + not x.startswith("-D")] + + def get_other_libs(string): + return [x for x in string.split() if not x.startswith("-L") and + not x.startswith("-l")] + + # return kwargs for given libname + def kwargs(libname): + fse = sys.getfilesystemencoding() + all_cflags = call(libname, "--cflags") + all_libs = call(libname, "--libs") + return { + "include_dirs": get_include_dirs(all_cflags), + "library_dirs": get_library_dirs(all_libs), + "libraries": get_libraries(all_libs), + "define_macros": get_macros(all_cflags), + "extra_compile_args": get_other_cflags(all_cflags), + "extra_link_args": get_other_libs(all_libs), + } + + # merge all arguments together + ret = {} + for libname in libs: + lib_flags = kwargs(libname) + merge_flags(ret, lib_flags) + return ret diff --git a/shared/package-files/2c/2cffeaca932be37bf1d11de45102ac0090bf8ee8006a3180bb18c405e0f003b2/inline_closurecall.py b/shared/package-files/2c/2cffeaca932be37bf1d11de45102ac0090bf8ee8006a3180bb18c405e0f003b2/inline_closurecall.py new file mode 100644 index 0000000000000000000000000000000000000000..1c547d1ffd4cc0fa5327a509f2bc5570d45ab3ea --- /dev/null +++ b/shared/package-files/2c/2cffeaca932be37bf1d11de45102ac0090bf8ee8006a3180bb18c405e0f003b2/inline_closurecall.py @@ -0,0 +1,1692 @@ +import types as pytypes # avoid confusion with numba.types +import copy +import ctypes +import numba.core.analysis +from numba.core import (types, typing, errors, ir, rewrites, config, ir_utils, + cgutils) +from numba.parfors.parfor import internal_prange +from numba.core.ir_utils import ( + next_label, + add_offset_to_labels, + replace_vars, + remove_dels, + rename_labels, + find_topo_order, + merge_adjacent_blocks, + GuardException, + require, + guard, + get_definition, + find_callname, + find_build_sequence, + get_np_ufunc_typ, + get_ir_of_code, + simplify_CFG, + canonicalize_array_math, + dead_code_elimination, +) + +from numba.core.analysis import ( + compute_cfg_from_blocks, + compute_use_defs, + compute_live_variables) +from numba.core.imputils import impl_ret_untracked +from numba.core.extending import intrinsic +from numba.core.typing import signature +from numba.cpython.listobj import ListIterInstance +from numba.cpython.rangeobj import range_impl_map +from numba.np.arrayobj import make_array + +from numba.core import postproc +from numba.np.unsafe.ndarray import empty_inferred as unsafe_empty_inferred +import numpy as np +import operator +import numba.misc.special + +""" +Variable enable_inline_arraycall is only used for testing purpose. +""" +enable_inline_arraycall = True + + +def callee_ir_validator(func_ir): + """Checks the IR of a callee is supported for inlining + """ + for blk in func_ir.blocks.values(): + for stmt in blk.find_insts(ir.Assign): + if isinstance(stmt.value, ir.Yield): + msg = "The use of yield in a closure is unsupported." + raise errors.UnsupportedError(msg, loc=stmt.loc) + + +def _created_inlined_var_name(function_name, var_name): + """Creates a name for an inlined variable based on the function name and the + variable name. It does this "safely" to avoid the use of characters that are + illegal in python variable names as there are occasions when function + generation needs valid python name tokens.""" + inlined_name = f'{function_name}.{var_name}' + # Replace angle brackets, e.g. "" is replaced with "_locals_" + new_name = inlined_name.replace('<', '_').replace('>', '_') + # The version "version" of the closure function e.g. foo$2 (id 2) is + # rewritten as "foo_v2". Further "." is also replaced with "_". + new_name = new_name.replace('.', '_').replace('$', '_v') + return new_name + + +class InlineClosureCallPass(object): + """InlineClosureCallPass class looks for direct calls to locally defined + closures, and inlines the body of the closure function to the call site. + """ + + def __init__(self, func_ir, parallel_options, swapped=None, typed=False): + if swapped is None: + swapped = {} + self.func_ir = func_ir + self.parallel_options = parallel_options + self.swapped = swapped + self._processed_stencils = [] + self.typed = typed + + def run(self): + """Run inline closure call pass. + """ + # Analysis relies on ir.Del presence, strip out later + pp = postproc.PostProcessor(self.func_ir) + pp.run(True) + + modified = False + work_list = list(self.func_ir.blocks.items()) + debug_print = _make_debug_print("InlineClosureCallPass") + debug_print(f"START {self.func_ir.func_id.func_qualname}") + while work_list: + _label, block = work_list.pop() + for i, instr in enumerate(block.body): + if isinstance(instr, ir.Assign): + expr = instr.value + if isinstance(expr, ir.Expr) and expr.op == 'call': + call_name = guard(find_callname, self.func_ir, expr) + func_def = guard(get_definition, self.func_ir, + expr.func) + + if guard(self._inline_reduction, + work_list, block, i, expr, call_name): + modified = True + break # because block structure changed + + if guard(self._inline_closure, + work_list, block, i, func_def): + modified = True + break # because block structure changed + + if guard(self._inline_stencil, + instr, call_name, func_def): + modified = True + + if enable_inline_arraycall: + # Identify loop structure + if modified: + # Need to do some cleanups if closure inlining kicked in + merge_adjacent_blocks(self.func_ir.blocks) + cfg = compute_cfg_from_blocks(self.func_ir.blocks) + debug_print("start inline arraycall") + _debug_dump(cfg) + loops = cfg.loops() + sized_loops = [(k, len(loops[k].body)) for k in loops.keys()] + visited = [] + # We go over all loops, bigger loops first (outer first) + for k, s in sorted(sized_loops, key=lambda tup: tup[1], + reverse=True): + visited.append(k) + if guard(_inline_arraycall, self.func_ir, cfg, visited, + loops[k], self.swapped, + self.parallel_options.comprehension, self.typed): + modified = True + if modified: + _fix_nested_array(self.func_ir) + + if modified: + # clean up now dead/unreachable blocks, e.g. unconditionally raising + # an exception in an inlined function would render some parts of the + # inliner unreachable + cfg = compute_cfg_from_blocks(self.func_ir.blocks) + for dead in cfg.dead_nodes(): + del self.func_ir.blocks[dead] + + # run dead code elimination + dead_code_elimination(self.func_ir) + # do label renaming + self.func_ir.blocks = rename_labels(self.func_ir.blocks) + + # inlining done, strip dels + remove_dels(self.func_ir.blocks) + + debug_print("END") + + def _inline_reduction(self, work_list, block, i, expr, call_name): + # only inline reduction in sequential execution, parallel handling + # is done in ParforPass. + require(not self.parallel_options.reduction) + require(call_name == ('reduce', 'builtins') or + call_name == ('reduce', '_functools')) + if len(expr.args) not in (2, 3): + raise TypeError("invalid reduce call, " + "two arguments are required (optional initial " + "value can also be specified)") + check_reduce_func(self.func_ir, expr.args[0]) + + def reduce_func(f, A, v=None): + it = iter(A) + if v is not None: + s = v + else: + s = next(it) + for a in it: + s = f(s, a) + return s + + inline_closure_call( + self.func_ir, self.func_ir.func_id.func.__globals__, + block, i, reduce_func, work_list=work_list, + callee_validator=callee_ir_validator + ) + return True + + def _inline_stencil(self, instr, call_name, func_def): + from numba.stencils.stencil import StencilFunc + lhs = instr.target + expr = instr.value + # We keep the escaping variables of the stencil kernel + # alive by adding them to the actual kernel call as extra + # keyword arguments, which is ignored anyway. + if (isinstance(func_def, ir.Global) and + func_def.name == 'stencil' and + isinstance(func_def.value, StencilFunc)): + if expr.kws: + expr.kws += func_def.value.kws + else: + expr.kws = func_def.value.kws + return True + # Otherwise we proceed to check if it is a call to numba.stencil + require(call_name == ('stencil', 'numba.stencils.stencil') or + call_name == ('stencil', 'numba')) + require(expr not in self._processed_stencils) + self._processed_stencils.append(expr) + if not len(expr.args) == 1: + raise ValueError("As a minimum Stencil requires" + " a kernel as an argument") + stencil_def = guard(get_definition, self.func_ir, expr.args[0]) + require(isinstance(stencil_def, ir.Expr) and + stencil_def.op == "make_function") + kernel_ir = get_ir_of_code(self.func_ir.func_id.func.__globals__, + stencil_def.code) + options = dict(expr.kws) + if 'neighborhood' in options: + fixed = guard(self._fix_stencil_neighborhood, options) + if not fixed: + raise ValueError( + "stencil neighborhood option should be a tuple" + " with constant structure such as ((-w, w),)" + ) + if 'index_offsets' in options: + fixed = guard(self._fix_stencil_index_offsets, options) + if not fixed: + raise ValueError( + "stencil index_offsets option should be a tuple" + " with constant structure such as (offset, )" + ) + sf = StencilFunc(kernel_ir, 'constant', options) + sf.kws = expr.kws # hack to keep variables live + sf_global = ir.Global('stencil', sf, expr.loc) + self.func_ir._definitions[lhs.name] = [sf_global] + instr.value = sf_global + return True + + def _fix_stencil_neighborhood(self, options): + """ + Extract the two-level tuple representing the stencil neighborhood + from the program IR to provide a tuple to StencilFunc. + """ + # build_tuple node with neighborhood for each dimension + dims_build_tuple = get_definition(self.func_ir, options['neighborhood']) + require(hasattr(dims_build_tuple, 'items')) + res = [] + for window_var in dims_build_tuple.items: + win_build_tuple = get_definition(self.func_ir, window_var) + require(hasattr(win_build_tuple, 'items')) + res.append(tuple(win_build_tuple.items)) + options['neighborhood'] = tuple(res) + return True + + def _fix_stencil_index_offsets(self, options): + """ + Extract the tuple representing the stencil index offsets + from the program IR to provide to StencilFunc. + """ + offset_tuple = get_definition(self.func_ir, options['index_offsets']) + require(hasattr(offset_tuple, 'items')) + options['index_offsets'] = tuple(offset_tuple.items) + return True + + def _inline_closure(self, work_list, block, i, func_def): + require(isinstance(func_def, ir.Expr) and + func_def.op == "make_function") + inline_closure_call(self.func_ir, + self.func_ir.func_id.func.__globals__, + block, i, func_def, work_list=work_list, + callee_validator=callee_ir_validator) + return True + + +def check_reduce_func(func_ir, func_var): + """Checks the function at func_var in func_ir to make sure it's amenable + for inlining. Returns the function itself""" + reduce_func = guard(get_definition, func_ir, func_var) + if reduce_func is None: + raise ValueError("Reduce function cannot be found for njit \ + analysis") + if isinstance(reduce_func, (ir.FreeVar, ir.Global)): + if not isinstance(reduce_func.value, + numba.core.registry.CPUDispatcher): + raise ValueError("Invalid reduction function") + # pull out the python function for inlining + reduce_func = reduce_func.value.py_func + elif not (hasattr(reduce_func, 'code') + or hasattr(reduce_func, '__code__')): + raise ValueError("Invalid reduction function") + f_code = (reduce_func.code + if hasattr(reduce_func, 'code') + else reduce_func.__code__) + if not f_code.co_argcount == 2: + raise TypeError("Reduction function should take 2 arguments") + return reduce_func + + +class InlineWorker(object): + """ A worker class for inlining, this is a more advanced version of + `inline_closure_call` in that it permits inlining from function type, Numba + IR and code object. It also, runs the entire untyped compiler pipeline on + the inlinee to ensure that it is transformed as though it were compiled + directly. + """ + + def __init__(self, + typingctx=None, + targetctx=None, + locals=None, + pipeline=None, + flags=None, + validator=callee_ir_validator, + typemap=None, + calltypes=None): + """ + Instantiate a new InlineWorker, all arguments are optional though some + must be supplied together for certain use cases. The methods will refuse + to run if the object isn't configured in the manner needed. Args are the + same as those in a numba.core.Compiler.state, except the validator which + is a function taking Numba IR and validating it for use when inlining + (this is optional and really to just provide better error messages about + things which the inliner cannot handle like yield in closure). + """ + def check(arg, name): + if arg is None: + raise TypeError("{} must not be None".format(name)) + + from numba.core.compiler import DefaultPassBuilder + + # check the stuff needed to run the more advanced compilation pipeline + # is valid if any of it is provided + compiler_args = (targetctx, locals, pipeline, flags) + compiler_group = [x is not None for x in compiler_args] + if any(compiler_group) and not all(compiler_group): + check(targetctx, 'targetctx') + check(locals, 'locals') + check(pipeline, 'pipeline') + check(flags, 'flags') + elif all(compiler_group): + check(typingctx, 'typingctx') + + self._compiler_pipeline = DefaultPassBuilder.define_untyped_pipeline + + self.typingctx = typingctx + self.targetctx = targetctx + self.locals = locals + self.pipeline = pipeline + self.flags = flags + self.validator = validator + self.debug_print = _make_debug_print("InlineWorker") + + # check whether this inliner can also support typemap and calltypes + # update and if what's provided is valid + pair = (typemap, calltypes) + pair_is_none = [x is None for x in pair] + if any(pair_is_none) and not all(pair_is_none): + msg = ("typemap and calltypes must both be either None or have a " + "value, got: %s, %s") + raise TypeError(msg % pair) + self._permit_update_type_and_call_maps = not all(pair_is_none) + self.typemap = typemap + self.calltypes = calltypes + + def inline_ir(self, caller_ir, block, i, callee_ir, callee_freevars, + arg_typs=None): + """ Inlines the callee_ir in the caller_ir at statement index i of block + `block`, callee_freevars are the free variables for the callee_ir. If + the callee_ir is derived from a function `func` then this is + `func.__code__.co_freevars`. If `arg_typs` is given and the InlineWorker + instance was initialized with a typemap and calltypes then they will be + appropriately updated based on the arg_typs. + """ + + # Always copy the callee IR, it gets mutated + def copy_ir(the_ir): + kernel_copy = the_ir.copy() + kernel_copy.blocks = {} + for block_label, block in the_ir.blocks.items(): + new_block = copy.deepcopy(the_ir.blocks[block_label]) + kernel_copy.blocks[block_label] = new_block + return kernel_copy + + callee_ir = copy_ir(callee_ir) + + # check that the contents of the callee IR is something that can be + # inlined if a validator is present + if self.validator is not None: + self.validator(callee_ir) + + # save an unmutated copy of the callee_ir to return + callee_ir_original = copy_ir(callee_ir) + scope = block.scope + instr = block.body[i] + call_expr = instr.value + callee_blocks = callee_ir.blocks + + # 1. relabel callee_ir by adding an offset + max_label = max( + ir_utils._the_max_label.next(), + max(caller_ir.blocks.keys()), + ) + callee_blocks = add_offset_to_labels(callee_blocks, max_label + 1) + callee_blocks = simplify_CFG(callee_blocks) + callee_ir.blocks = callee_blocks + min_label = min(callee_blocks.keys()) + max_label = max(callee_blocks.keys()) + # reset globals in ir_utils before we use it + ir_utils._the_max_label.update(max_label) + self.debug_print("After relabel") + _debug_dump(callee_ir) + + # 2. rename all local variables in callee_ir with new locals created in + # caller_ir + callee_scopes = _get_all_scopes(callee_blocks) + self.debug_print("callee_scopes = ", callee_scopes) + # one function should only have one local scope + assert (len(callee_scopes) == 1) + callee_scope = callee_scopes[0] + var_dict = {} + for var in tuple(callee_scope.localvars._con.values()): + if not (var.name in callee_freevars): + inlined_name = _created_inlined_var_name( + callee_ir.func_id.unique_name, var.name) + # Update the caller scope with the new names + new_var = scope.redefine(inlined_name, loc=var.loc) + # Also update the callee scope with the new names. Should the + # type and call maps need updating (which requires SSA form) the + # transformation to SSA is valid as the IR object is internally + # consistent. + callee_scope.redefine(inlined_name, loc=var.loc) + var_dict[var.name] = new_var + self.debug_print("var_dict = ", var_dict) + replace_vars(callee_blocks, var_dict) + self.debug_print("After local var rename") + _debug_dump(callee_ir) + + # 3. replace formal parameters with actual arguments + callee_func = callee_ir.func_id.func + args = _get_callee_args(call_expr, callee_func, block.body[i].loc, + caller_ir) + + # 4. Update typemap + if self._permit_update_type_and_call_maps: + if arg_typs is None: + raise TypeError('arg_typs should have a value not None') + self.update_type_and_call_maps(callee_ir, arg_typs) + # update_type_and_call_maps replaces blocks + callee_blocks = callee_ir.blocks + + self.debug_print("After arguments rename: ") + _debug_dump(callee_ir) + + _replace_args_with(callee_blocks, args) + # 5. split caller blocks into two + new_blocks = [] + new_block = ir.Block(scope, block.loc) + new_block.body = block.body[i + 1:] + new_label = next_label() + caller_ir.blocks[new_label] = new_block + new_blocks.append((new_label, new_block)) + block.body = block.body[:i] + block.body.append(ir.Jump(min_label, instr.loc)) + + # 6. replace Return with assignment to LHS + topo_order = find_topo_order(callee_blocks) + _replace_returns(callee_blocks, instr.target, new_label) + + # remove the old definition of instr.target too + if (instr.target.name in caller_ir._definitions + and call_expr in caller_ir._definitions[instr.target.name]): + # NOTE: target can have multiple definitions due to control flow + caller_ir._definitions[instr.target.name].remove(call_expr) + + # 7. insert all new blocks, and add back definitions + for label in topo_order: + # block scope must point to parent's + block = callee_blocks[label] + block.scope = scope + _add_definitions(caller_ir, block) + caller_ir.blocks[label] = block + new_blocks.append((label, block)) + self.debug_print("After merge in") + _debug_dump(caller_ir) + + return callee_ir_original, callee_blocks, var_dict, new_blocks + + def inline_function(self, caller_ir, block, i, function, arg_typs=None): + """ Inlines the function in the caller_ir at statement index i of block + `block`. If `arg_typs` is given and the InlineWorker instance was + initialized with a typemap and calltypes then they will be appropriately + updated based on the arg_typs. + """ + callee_ir = self.run_untyped_passes(function) + freevars = function.__code__.co_freevars + return self.inline_ir(caller_ir, block, i, callee_ir, freevars, + arg_typs=arg_typs) + + def run_untyped_passes(self, func, enable_ssa=False): + """ + Run the compiler frontend's untyped passes over the given Python + function, and return the function's canonical Numba IR. + + Disable SSA transformation by default, since the call site won't be in + SSA form and self.inline_ir depends on this being the case. + """ + from numba.core.compiler import StateDict, _CompileStatus + from numba.core.untyped_passes import ExtractByteCode + from numba.core import bytecode + from numba.parfors.parfor import ParforDiagnostics + state = StateDict() + state.func_ir = None + state.typingctx = self.typingctx + state.targetctx = self.targetctx + state.locals = self.locals + state.pipeline = self.pipeline + state.flags = self.flags + state.flags.enable_ssa = enable_ssa + + state.func_id = bytecode.FunctionIdentity.from_function(func) + + state.typemap = None + state.calltypes = None + state.type_annotation = None + state.status = _CompileStatus(False) + state.return_type = None + state.parfor_diagnostics = ParforDiagnostics() + state.metadata = {} + + ExtractByteCode().run_pass(state) + # This is a lie, just need *some* args for the case where an obj mode + # with lift is needed + state.args = len(state.bc.func_id.pysig.parameters) * (types.pyobject,) + + pm = self._compiler_pipeline(state) + + pm.finalize() + pm.run(state) + return state.func_ir + + def update_type_and_call_maps(self, callee_ir, arg_typs): + """ Updates the type and call maps based on calling callee_ir with + arguments from arg_typs""" + from numba.core.ssa import reconstruct_ssa + from numba.core.typed_passes import PreLowerStripPhis + + if not self._permit_update_type_and_call_maps: + msg = ("InlineWorker instance not configured correctly, typemap or " + "calltypes missing in initialization.") + raise ValueError(msg) + from numba.core import typed_passes + # call branch pruning to simplify IR and avoid inference errors + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + numba.core.analysis.dead_branch_prune(callee_ir, arg_typs) + # callee's typing may require SSA + callee_ir = reconstruct_ssa(callee_ir) + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + [f_typemap, + _f_return_type, + f_calltypes, _] = typed_passes.type_inference_stage( + self.typingctx, self.targetctx, callee_ir, arg_typs, None, + ) + callee_ir = PreLowerStripPhis()._strip_phi_nodes(callee_ir) + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + canonicalize_array_math(callee_ir, f_typemap, + f_calltypes, self.typingctx) + # remove argument entries like arg.a from typemap + arg_names = [vname for vname in f_typemap if vname.startswith("arg.")] + for a in arg_names: + f_typemap.pop(a) + self.typemap.update(f_typemap) + self.calltypes.update(f_calltypes) + + +def inline_closure_call(func_ir, glbls, block, i, callee, typingctx=None, + targetctx=None, arg_typs=None, typemap=None, + calltypes=None, work_list=None, callee_validator=None, + replace_freevars=True): + """Inline the body of `callee` at its callsite (`i`-th instruction of + `block`) + + `func_ir` is the func_ir object of the caller function and `glbls` is its + global variable environment (func_ir.func_id.func.__globals__). + `block` is the IR block of the callsite and `i` is the index of the + callsite's node. `callee` is either the called function or a + make_function node. `typingctx`, `typemap` and `calltypes` are typing + data structures of the caller, available if we are in a typed pass. + `arg_typs` includes the types of the arguments at the callsite. + `callee_validator` is an optional callable which can be used to validate the + IR of the callee to ensure that it contains IR supported for inlining, it + takes one argument, the func_ir of the callee + + Returns IR blocks of the callee and the variable renaming dictionary used + for them to facilitate further processing of new blocks. + """ + scope = block.scope + instr = block.body[i] + call_expr = instr.value + debug_print = _make_debug_print("inline_closure_call") + debug_print("Found closure call: ", instr, " with callee = ", callee) + # support both function object and make_function Expr + callee_code = callee.code if hasattr(callee, 'code') else callee.__code__ + callee_closure = (callee.closure + if hasattr(callee, 'closure') else callee.__closure__) + # first, get the IR of the callee + if isinstance(callee, pytypes.FunctionType): + from numba.core import compiler + callee_ir = compiler.run_frontend(callee, inline_closures=True) + else: + callee_ir = get_ir_of_code(glbls, callee_code) + + # check that the contents of the callee IR is something that can be inlined + # if a validator is supplied + if callee_validator is not None: + callee_validator(callee_ir) + + callee_blocks = callee_ir.blocks + + # 1. relabel callee_ir by adding an offset + max_label = max(ir_utils._the_max_label.next(), max(func_ir.blocks.keys())) + callee_blocks = add_offset_to_labels(callee_blocks, max_label + 1) + callee_blocks = simplify_CFG(callee_blocks) + callee_ir.blocks = callee_blocks + min_label = min(callee_blocks.keys()) + max_label = max(callee_blocks.keys()) + # reset globals in ir_utils before we use it + ir_utils._the_max_label.update(max_label) + debug_print("After relabel") + _debug_dump(callee_ir) + + # 2. rename all local variables in callee_ir with new locals created in + # func_ir + callee_scopes = _get_all_scopes(callee_blocks) + debug_print("callee_scopes = ", callee_scopes) + # one function should only have one local scope + assert (len(callee_scopes) == 1) + callee_scope = callee_scopes[0] + var_dict = {} + for var in callee_scope.localvars._con.values(): + if not (var.name in callee_code.co_freevars): + inlined_name = _created_inlined_var_name( + callee_ir.func_id.unique_name, var.name) + new_var = scope.redefine(inlined_name, loc=var.loc) + var_dict[var.name] = new_var + debug_print("var_dict = ", var_dict) + replace_vars(callee_blocks, var_dict) + debug_print("After local var rename") + _debug_dump(callee_ir) + + # 3. replace formal parameters with actual arguments + args = _get_callee_args(call_expr, callee, block.body[i].loc, func_ir) + + debug_print("After arguments rename: ") + _debug_dump(callee_ir) + + # 4. replace freevar with actual closure var + if callee_closure and replace_freevars: + # A nonlocal assigned more than once is SSA-versioned (``x``, ``x.1``); + # inlining keeps only the base name, dropping later writes (#10379). + for freevar in callee_code.co_freevars: + if callee_scope.get_versions_of(freevar): + msg = ("Reassigning the nonlocal variable '%s' inside an " + "inlined closure is unsupported. Assign it once " + "instead." % (freevar,)) + raise errors.UnsupportedError(msg, instr.loc) + closure = func_ir.get_definition(callee_closure) + debug_print("callee's closure = ", closure) + if isinstance(closure, tuple): + cellget = ctypes.pythonapi.PyCell_Get + cellget.restype = ctypes.py_object + cellget.argtypes = (ctypes.py_object,) + items = tuple(cellget(x) for x in closure) + else: + assert (isinstance(closure, ir.Expr) + and closure.op == 'build_tuple') + items = closure.items + assert (len(callee_code.co_freevars) == len(items)) + _replace_freevars(callee_blocks, items) + debug_print("After closure rename") + _debug_dump(callee_ir) + + if typingctx: + from numba.core import typed_passes + # call branch pruning to simplify IR and avoid inference errors + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + numba.core.analysis.dead_branch_prune(callee_ir, arg_typs) + try: + [f_typemap, f_return_type, + f_calltypes, _] = typed_passes.type_inference_stage( + typingctx, targetctx, callee_ir, arg_typs, None) + except Exception: + [f_typemap, f_return_type, + f_calltypes, _] = typed_passes.type_inference_stage( + typingctx, targetctx, callee_ir, arg_typs, None) + canonicalize_array_math(callee_ir, f_typemap, + f_calltypes, typingctx) + # remove argument entries like arg.a from typemap + arg_names = [vname for vname in f_typemap if vname.startswith("arg.")] + for a in arg_names: + f_typemap.pop(a) + typemap.update(f_typemap) + calltypes.update(f_calltypes) + + _replace_args_with(callee_blocks, args) + # 5. split caller blocks into two + new_blocks = [] + new_block = ir.Block(scope, block.loc) + new_block.body = block.body[i + 1:] + new_label = next_label() + func_ir.blocks[new_label] = new_block + new_blocks.append((new_label, new_block)) + block.body = block.body[:i] + block.body.append(ir.Jump(min_label, instr.loc)) + + # 6. replace Return with assignment to LHS + topo_order = find_topo_order(callee_blocks) + _replace_returns(callee_blocks, instr.target, new_label) + + # remove the old definition of instr.target too + if (instr.target.name in func_ir._definitions + and call_expr in func_ir._definitions[instr.target.name]): + # NOTE: target can have multiple definitions due to control flow + func_ir._definitions[instr.target.name].remove(call_expr) + + # 7. insert all new blocks, and add back definitions + for label in topo_order: + # block scope must point to parent's + block = callee_blocks[label] + block.scope = scope + _add_definitions(func_ir, block) + func_ir.blocks[label] = block + new_blocks.append((label, block)) + debug_print("After merge in") + _debug_dump(func_ir) + + if work_list is not None: + for block in new_blocks: + work_list.append(block) + return callee_blocks, var_dict + + +def _get_callee_args(call_expr, callee, loc, func_ir): + """Get arguments for calling 'callee', including the default arguments. + keyword arguments are currently only handled when 'callee' is a function. + """ + if call_expr.op == 'call': + args = list(call_expr.args) + if call_expr.vararg: + msg = "Calling a closure with *args is unsupported." + raise errors.UnsupportedError(msg, call_expr.loc) + elif call_expr.op == 'getattr': + args = [call_expr.value] + elif ir_utils.is_operator_or_getitem(call_expr): + args = call_expr.list_vars() + else: + raise TypeError("Unsupported ir.Expr.{}".format(call_expr.op)) + + debug_print = _make_debug_print("inline_closure_call default handling") + + # handle defaults and kw arguments using pysignature if callee is function + if isinstance(callee, pytypes.FunctionType): + pysig = numba.core.utils.pysignature(callee) + normal_handler = lambda index, param, default: default + default_handler = lambda index, param, default: ir.Const(default, loc) + + # Throw error for stararg + # TODO: handle stararg + def stararg_handler(index, param, default): + raise NotImplementedError( + "Stararg not supported in inliner for arg {} {}".format( + index, param)) + if call_expr.op == 'call': + kws = dict(call_expr.kws) + else: + kws = {} + return numba.core.typing.fold_arguments( + pysig, args, kws, normal_handler, default_handler, + stararg_handler) + else: + # TODO: handle arguments for make_function case similar to function + # case above + callee_defaults = (callee.defaults if hasattr(callee, 'defaults') + else callee.__defaults__) + if callee_defaults: + debug_print("defaults = ", callee_defaults) + if isinstance(callee_defaults, tuple): # Python 3.5 + defaults_list = [] + for x in callee_defaults: + if isinstance(x, ir.Var): + defaults_list.append(x) + else: + # this branch is predominantly for kwargs from + # inlinable functions + defaults_list.append(ir.Const(value=x, loc=loc)) + args = args + defaults_list + elif (isinstance(callee_defaults, ir.Var) + or isinstance(callee_defaults, str)): + default_tuple = func_ir.get_definition(callee_defaults) + assert (isinstance(default_tuple, ir.Expr)) + assert (default_tuple.op == "build_tuple") + const_vals = [func_ir.get_definition(x) for + x in default_tuple.items] + args = args + const_vals + else: + raise NotImplementedError( + "Unsupported defaults to make_function: {}".format( + callee_defaults)) + return args + + +def _make_debug_print(prefix): + def debug_print(*args): + if config.DEBUG_INLINE_CLOSURE: + print(prefix + ": " + "".join(str(x) for x in args)) + return debug_print + + +def _debug_dump(func_ir): + if config.DEBUG_INLINE_CLOSURE: + func_ir.dump() + + +def _get_all_scopes(blocks): + """Get all block-local scopes from an IR. + """ + all_scopes = [] + for label, block in blocks.items(): + if not (block.scope in all_scopes): + all_scopes.append(block.scope) + return all_scopes + + +def _replace_args_with(blocks, args): + """ + Replace ir.Arg(...) with real arguments from call site + """ + for label, block in blocks.items(): + assigns = block.find_insts(ir.Assign) + for stmt in assigns: + if isinstance(stmt.value, ir.Arg): + idx = stmt.value.index + assert (idx < len(args)) + stmt.value = args[idx] + + +def _replace_freevars(blocks, args): + """ + Replace ir.FreeVar(...) with real variables from parent function + """ + for label, block in blocks.items(): + assigns = block.find_insts(ir.Assign) + for stmt in assigns: + if isinstance(stmt.value, ir.FreeVar): + idx = stmt.value.index + assert (idx < len(args)) + if isinstance(args[idx], ir.Var): + stmt.value = args[idx] + else: + stmt.value = ir.Const(args[idx], stmt.loc) + + +def _replace_returns(blocks, target, return_label): + """ + Return return statement by assigning directly to target, and a jump. + """ + for label, block in blocks.items(): + casts = [] + for i in range(len(block.body)): + stmt = block.body[i] + if isinstance(stmt, ir.Return): + assert (i + 1 == len(block.body)) + block.body[i] = ir.Assign(stmt.value, target, stmt.loc) + block.body.append(ir.Jump(return_label, stmt.loc)) + # remove cast of the returned value + for cast in casts: + if cast.target.name == stmt.value.name: + cast.value = cast.value.value + elif (isinstance(stmt, ir.Assign) and + isinstance(stmt.value, ir.Expr) and + stmt.value.op == 'cast'): + casts.append(stmt) + + +def _add_definitions(func_ir, block): + """ + Add variable definitions found in a block to parent func_ir. + """ + definitions = func_ir._definitions + assigns = block.find_insts(ir.Assign) + for stmt in assigns: + definitions[stmt.target.name].append(stmt.value) + + +def _find_arraycall(func_ir, block): + """Look for statement like "x = numpy.array(y)" or "x[..] = y" + immediately after the closure call that creates list y (the i-th + statement in block). Return the statement index if found, or + raise GuardException. + """ + array_var = None + list_var_dead_after_array_call = False + list_var = None + + i = 0 + while i < len(block.body): + instr = block.body[i] + if isinstance(instr, ir.Del): + # Stop the process if list_var becomes dead + if list_var and array_var and instr.value == list_var.name: + list_var_dead_after_array_call = True + break + pass + elif isinstance(instr, ir.Assign): + # Found array_var = array(list_var) + lhs = instr.target + expr = instr.value + if (guard(find_callname, func_ir, expr) == ('array', 'numpy') and + isinstance(expr.args[0], ir.Var)): + list_var = expr.args[0] + array_var = lhs + array_stmt_index = i + array_kws = dict(expr.kws) + elif (isinstance(instr, ir.SetItem) and + isinstance(instr.value, ir.Var) and + not list_var): + list_var = instr.value + # Found array_var[..] = list_var, the case for nested array + array_var = instr.target + array_def = get_definition(func_ir, array_var) + require(guard(_find_unsafe_empty_inferred, func_ir, array_def)) + array_stmt_index = i + array_kws = {} + else: + # Bail out otherwise + break + i = i + 1 + # require array_var is found, and list_var is dead after array_call. + require(array_var and list_var_dead_after_array_call) + _make_debug_print("find_array_call")(block.body[array_stmt_index]) + return list_var, array_stmt_index, array_kws + + +def _find_iter_range(func_ir, range_iter_var, swapped): + """Find the iterator's actual range if it is either range(n), or + range(m, n), otherwise return raise GuardException. + """ + debug_print = _make_debug_print("find_iter_range") + range_iter_def = get_definition(func_ir, range_iter_var) + debug_print("range_iter_var = ", range_iter_var, " def = ", range_iter_def) + require(isinstance(range_iter_def, ir.Expr) and + range_iter_def.op == 'getiter') + range_var = range_iter_def.value + range_def = get_definition(func_ir, range_var) + debug_print("range_var = ", range_var, " range_def = ", range_def) + require(isinstance(range_def, ir.Expr) and range_def.op == 'call') + func_var = range_def.func + func_def = get_definition(func_ir, func_var) + debug_print("func_var = ", func_var, " func_def = ", func_def) + require(isinstance(func_def, ir.Global) and + (func_def.value == range or + func_def.value == numba.misc.special.prange)) + nargs = len(range_def.args) + swapping = [('"array comprehension"', 'closure of'), range_def.func.loc] + if nargs == 1: + swapped[range_def.func.name] = swapping + stop = get_definition(func_ir, range_def.args[0], lhs_only=True) + return (0, range_def.args[0], func_def) + elif nargs == 2: + swapped[range_def.func.name] = swapping + start = get_definition(func_ir, range_def.args[0], lhs_only=True) + stop = get_definition(func_ir, range_def.args[1], lhs_only=True) + return (start, stop, func_def) + else: + raise GuardException + + +@intrinsic +def length_of_iterator(typingctx, val): + """ + An implementation of len(iter) for internal use. + Primary use is for array comprehensions (see inline_closurecall). + """ + if isinstance(val, types.RangeIteratorType): + val_type = val.yield_type + + def codegen(context, builder, sig, args): + (value,) = args + iter_type = range_impl_map[val_type][1] + iterobj = cgutils.create_struct_proxy(iter_type)(context, builder, + value) + int_type = iterobj.count.type + return impl_ret_untracked(context, builder, int_type, + builder.load(iterobj.count)) + return signature(val_type, val), codegen + elif isinstance(val, types.ListIter): + def codegen(context, builder, sig, args): + (value,) = args + intp_t = context.get_value_type(types.intp) + iterobj = ListIterInstance(context, builder, sig.args[0], value) + return impl_ret_untracked(context, builder, intp_t, iterobj.size) + return signature(types.intp, val), codegen + elif isinstance(val, types.ArrayIterator): + def codegen(context, builder, sig, args): + (iterty,) = sig.args + (value,) = args + intp_t = context.get_value_type(types.intp) + iterobj = context.make_helper(builder, iterty, value=value) + arrayty = iterty.array_type + ary = make_array(arrayty)(context, builder, value=iterobj.array) + shape = cgutils.unpack_tuple(builder, ary.shape) + # array iterates along the outer dimension + return impl_ret_untracked(context, builder, intp_t, shape[0]) + return signature(types.intp, val), codegen + elif isinstance(val, types.UniTupleIter): + def codegen(context, builder, sig, args): + (iterty,) = sig.args + tuplety = iterty.container + intp_t = context.get_value_type(types.intp) + count_const = intp_t(tuplety.count) + return impl_ret_untracked(context, builder, intp_t, count_const) + + return signature(types.intp, val), codegen + elif isinstance(val, types.ListTypeIteratorType): + def codegen(context, builder, sig, args): + (value,) = args + intp_t = context.get_value_type(types.intp) + from numba.typed.listobject import ListIterInstance + iterobj = ListIterInstance(context, builder, sig.args[0], value) + return impl_ret_untracked(context, builder, intp_t, iterobj.size) + return signature(types.intp, val), codegen + else: + msg = ('Unsupported iterator found in array comprehension, try ' + 'preallocating the array and filling manually.') + raise errors.TypingError(msg) + + +def _inline_arraycall(func_ir, cfg, visited, loop, swapped, enable_prange=False, + typed=False): + """Look for array(list) call in the exit block of a given loop, and turn + list operations into array operations in the loop if the following + conditions are met: + 1. The exit block contains an array call on the list; + 2. The list variable is no longer live after array call; + 3. The list is created in the loop entry block; + 4. The loop is created from an range iterator whose length is known prior + to the loop; + 5. There is only one list_append operation on the list variable in the + loop body; + 6. The block that contains list_append dominates the loop head, which + ensures list length is the same as loop length; + If any condition check fails, no modification will be made to the incoming + IR. + """ + debug_print = _make_debug_print("inline_arraycall") + # There should only be one loop exit + require(len(loop.exits) == 1) + exit_block = next(iter(loop.exits)) + list_var, array_call_index, array_kws = _find_arraycall( + func_ir, func_ir.blocks[exit_block], + ) + + # check if dtype is present in array call + dtype_def = None + dtype_mod_def = None + if 'dtype' in array_kws: + require(isinstance(array_kws['dtype'], ir.Var)) + # We require that dtype argument to be a constant of getattr Expr, and + # we'll remember its definition for later use. + dtype_def = get_definition(func_ir, array_kws['dtype']) + require(isinstance(dtype_def, ir.Expr) and dtype_def.op == 'getattr') + dtype_mod_def = get_definition(func_ir, dtype_def.value) + + list_var_def = get_definition(func_ir, list_var) + debug_print("list_var = ", list_var, " def = ", list_var_def) + if isinstance(list_var_def, ir.Expr) and list_var_def.op == 'cast': + list_var_def = get_definition(func_ir, list_var_def.value) + # Check if the definition is a build_list + require(isinstance(list_var_def, ir.Expr) and + list_var_def.op == 'build_list') + # The build_list must be empty + require(len(list_var_def.items) == 0) + + # Look for list_append in "last" block in loop body, which should be a block + # that is a post-dominator of the loop header. + list_append_stmts = [] + for label in loop.body: + # We have to consider blocks of this loop, but not sub-loops. + # To achieve this, we require the set of "in_loops" of "label" to be + # visited loops. + in_visited_loops = [l.header in visited for l in cfg.in_loops(label)] + if not all(in_visited_loops): + continue + block = func_ir.blocks[label] + debug_print("check loop body block ", label) + for stmt in block.find_insts(ir.Assign): + expr = stmt.value + if isinstance(expr, ir.Expr) and expr.op == 'call': + func_def = get_definition(func_ir, expr.func) + if (isinstance(func_def, ir.Expr) and func_def.op == 'getattr' + and func_def.attr == 'append'): + list_def = get_definition(func_ir, func_def.value) + debug_print("list_def = ", list_def, + list_def is list_var_def) + if list_def is list_var_def: + # found matching append call + list_append_stmts.append((label, block, stmt)) + + # Require only one list_append, otherwise we won't know the indices + require(len(list_append_stmts) == 1) + append_block_label, append_block, append_stmt = list_append_stmts[0] + + # Check if append_block (besides loop entry) dominates loop header. + # Since CFG doesn't give us this info without loop entry, we approximate + # by checking if the predecessor set of the header block is the same + # as loop_entries plus append_block, which is certainly more restrictive + # than necessary, and can be relaxed if needed. + preds = set(l for l, b in cfg.predecessors(loop.header)) + debug_print("preds = ", preds, (loop.entries | set([append_block_label]))) + require(preds == (loop.entries | set([append_block_label]))) + + # Find iterator in loop header + iter_vars = [] + iter_first_vars = [] + loop_header = func_ir.blocks[loop.header] + for stmt in loop_header.find_insts(ir.Assign): + expr = stmt.value + if isinstance(expr, ir.Expr): + if expr.op == 'iternext': + iter_def = get_definition(func_ir, expr.value) + debug_print("iter_def = ", iter_def) + iter_vars.append(expr.value) + elif expr.op == 'pair_first': + iter_first_vars.append(stmt.target) + + # Require only one iterator in loop header + require(len(iter_vars) == 1 and len(iter_first_vars) == 1) + # variable that holds the iterator object + iter_var = iter_vars[0] + # variable that holds the value out of iterator + iter_first_var = iter_first_vars[0] + + # Final requirement: only one loop entry, and we're going to modify it by: + # 1. replacing the list definition with an array definition; + # 2. adding a counter for the array iteration. + require(len(loop.entries) == 1) + loop_entry = func_ir.blocks[next(iter(loop.entries))] + terminator = loop_entry.terminator + scope = loop_entry.scope + loc = loop_entry.loc + stmts = [] + removed = [] + + def is_removed(val, removed): + if isinstance(val, ir.Var): + for x in removed: + if x.name == val.name: + return True + return False + + # Skip list construction and skip terminator, add the rest to stmts + for i in range(len(loop_entry.body) - 1): + stmt = loop_entry.body[i] + if (isinstance(stmt, ir.Assign) and + (stmt.value is list_def or is_removed(stmt.value, removed))): + removed.append(stmt.target) + else: + stmts.append(stmt) + debug_print("removed variables: ", removed) + + # Define an index_var to index the array. + # If the range happens to be single step ranges like range(n), or + # range(m, n), then the index_var correlates to iterator index; otherwise + # we'll have to define a new counter. + range_def = guard(_find_iter_range, func_ir, iter_var, swapped) + index_var = scope.redefine("index", loc) + if range_def and range_def[0] == 0: + # iterator starts with 0, index_var can just be iter_first_var + index_var = iter_first_var + else: + # index_var = -1 # starting the index with -1 since it will incremented + # in loop header + stmts.append(_new_definition(func_ir, index_var, + ir.Const(value=-1, loc=loc), loc)) + + # Insert statement to get the size of the loop iterator + size_var = scope.redefine("size", loc) + if range_def: + start, stop, range_func_def = range_def + if start == 0: + size_val = stop + else: + size_val = ir.Expr.binop(fn=operator.sub, lhs=stop, rhs=start, + loc=loc) + # we can parallelize this loop if enable_prange = True, by changing + # range function from range, to prange. + if enable_prange and isinstance(range_func_def, ir.Global): + range_func_def.name = 'internal_prange' + range_func_def.value = internal_prange + + else: + # this doesn't work in objmode as it's effectively untyped + if typed: + len_func_var = scope.redefine("len_func", loc) + stmts.append(_new_definition(func_ir, len_func_var, + ir.Global('length_of_iterator', + length_of_iterator, + loc=loc), + loc)) + size_val = ir.Expr.call(len_func_var, (iter_var,), (), loc=loc) + else: + raise GuardException + + stmts.append(_new_definition(func_ir, size_var, size_val, loc)) + + size_tuple_var = scope.redefine("size_tuple", loc) + stmts.append(_new_definition(func_ir, size_tuple_var, + ir.Expr.build_tuple(items=[size_var], loc=loc), loc)) + + # Insert array allocation + array_var = scope.redefine("array", loc) + empty_func = scope.redefine("empty_func", loc) + if dtype_def and dtype_mod_def: + # when dtype is present, we'll call empty with dtype + dtype_mod_var = scope.redefine("dtype_mod", loc) + dtype_var = scope.redefine("dtype", loc) + stmts.append(_new_definition( + func_ir, dtype_mod_var, dtype_mod_def, loc)) + stmts.append(_new_definition( + func_ir, dtype_var, + ir.Expr.getattr(dtype_mod_var, dtype_def.attr, loc), loc)) + stmts.append(_new_definition( + func_ir, empty_func, ir.Global('empty', np.empty, loc=loc), loc)) + array_kws = [('dtype', dtype_var)] + else: + # this doesn't work in objmode as it's effectively untyped + if typed: + # otherwise we'll call unsafe_empty_inferred + stmts.append(_new_definition( + func_ir, empty_func, + ir.Global('unsafe_empty_inferred', unsafe_empty_inferred, + loc=loc), + loc)) + array_kws = [] + else: + raise GuardException + + # array_var = empty_func(size_tuple_var) + stmts.append(_new_definition(func_ir, array_var, + ir.Expr.call(empty_func, (size_tuple_var,), list(array_kws), + loc=loc), loc)) + + # Add back removed just in case they are used by something else + for var in removed: + stmts.append(_new_definition(func_ir, var, array_var, loc)) + + # Add back terminator + stmts.append(terminator) + # Modify loop_entry + loop_entry.body = stmts + + if range_def: + if range_def[0] != 0: + # when range doesn't start from 0, index_var becomes loop index + # (iter_first_var) minus an offset (range_def[0]) + terminator = loop_header.terminator + assert (isinstance(terminator, ir.Branch)) + # find the block in the loop body that header jumps to + block_id = terminator.truebr + blk = func_ir.blocks[block_id] + loc = blk.loc + blk.body.insert( + 0, + _new_definition( + func_ir, index_var, + ir.Expr.binop(fn=operator.sub, lhs=iter_first_var, + rhs=range_def[0], loc=loc), + loc + ) + ) + else: + # Insert index_var increment to the end of loop header + loc = loop_header.loc + terminator = loop_header.terminator + stmts = loop_header.body[0:-1] + next_index_var = scope.redefine("next_index", loc) + one = scope.redefine("one", loc) + # one = 1 + stmts.append(_new_definition(func_ir, one, + ir.Const(value=1,loc=loc), loc)) + # next_index_var = index_var + 1 + stmts.append(_new_definition(func_ir, next_index_var, + ir.Expr.binop(fn=operator.add, lhs=index_var, rhs=one, + loc=loc), loc)) + # index_var = next_index_var + stmts.append(_new_definition(func_ir, index_var, next_index_var, loc)) + stmts.append(terminator) + loop_header.body = stmts + + # In append_block, change list_append into array assign + for i in range(len(append_block.body)): + if append_block.body[i] is append_stmt: + debug_print("Replace append with SetItem") + append_block.body[i] = ir.SetItem( + target=array_var, index=index_var, + value=append_stmt.value.args[0], loc=append_stmt.loc) + + # replace array call, by changing "a = array(b)" to "a = b" + stmt = func_ir.blocks[exit_block].body[array_call_index] + # stmt can be either array call or SetItem, we only replace array call + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr): + stmt.value = array_var + func_ir._definitions[stmt.target.name] = [stmt.value] + + return True + + +def _find_unsafe_empty_inferred(func_ir, expr): + unsafe_empty_inferred + require(isinstance(expr, ir.Expr) and expr.op == 'call') + callee = expr.func + callee_def = get_definition(func_ir, callee) + require(isinstance(callee_def, ir.Global)) + _make_debug_print("_find_unsafe_empty_inferred")(callee_def.value) + return callee_def.value == unsafe_empty_inferred + + +def _fix_nested_array(func_ir): + """Look for assignment like: a[..] = b, where both a and b are numpy arrays, + and try to eliminate array b by expanding a with an extra dimension. + """ + blocks = func_ir.blocks + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + empty_deadmap = dict([(label, set()) for label in blocks.keys()]) + livemap = compute_live_variables(cfg, blocks, usedefs.defmap, empty_deadmap) + + def find_array_def(arr): + """Find numpy array definition such as + arr = numba.unsafe.ndarray.empty_inferred(...). + If it is arr = b[...], find array definition of b recursively. + """ + arr_def = get_definition(func_ir, arr) + _make_debug_print("find_array_def")(arr, arr_def) + if isinstance(arr_def, ir.Expr): + if guard(_find_unsafe_empty_inferred, func_ir, arr_def): + return arr_def + elif arr_def.op == 'getitem': + return find_array_def(arr_def.value) + raise GuardException + + def fix_dependencies(expr, varlist): + """Double check if all variables in varlist are defined before + expr is used. Try to move constant definition when the check fails. + Bails out by raising GuardException if it can't be moved. + """ + debug_print = _make_debug_print("fix_dependencies") + for label, block in blocks.items(): + scope = block.scope + body = block.body + defined = set() + for i in range(len(body)): + inst = body[i] + if isinstance(inst, ir.Assign): + defined.add(inst.target.name) + if inst.value is expr: + new_varlist = [] + for var in varlist: + # var must be defined before this inst, or live + # and not later defined. + if (var.name in defined or + (var.name in livemap[label] and + not (var.name in usedefs.defmap[label]))): + debug_print(var.name, " already defined") + new_varlist.append(var) + else: + debug_print(var.name, " not yet defined") + var_def = get_definition(func_ir, var.name) + if isinstance(var_def, ir.Const): + loc = var.loc + new_var = scope.redefine("new_var", loc) + new_const = ir.Const(var_def.value, loc) + new_vardef = _new_definition( + func_ir, new_var, new_const, loc) + new_body = [] + new_body.extend(body[:i]) + new_body.append(new_vardef) + new_body.extend(body[i:]) + block.body = new_body + new_varlist.append(new_var) + else: + raise GuardException + return new_varlist + # when expr is not found in block + raise GuardException + + def fix_array_assign(stmt): + """For assignment like lhs[idx] = rhs, where both lhs and rhs are + arrays, do the following: + 1. find the definition of rhs, which has to be a call to + numba.unsafe.ndarray.empty_inferred + 2. find the source array creation for lhs, insert an extra dimension of + size of b. + 3. replace the definition of + rhs = numba.unsafe.ndarray.empty_inferred(...) with rhs = lhs[idx] + """ + require(isinstance(stmt, ir.SetItem)) + require(isinstance(stmt.value, ir.Var)) + debug_print = _make_debug_print("fix_array_assign") + debug_print("found SetItem: ", stmt) + lhs = stmt.target + # Find the source array creation of lhs + lhs_def = find_array_def(lhs) + debug_print("found lhs_def: ", lhs_def) + rhs_def = get_definition(func_ir, stmt.value) + debug_print("found rhs_def: ", rhs_def) + require(isinstance(rhs_def, ir.Expr)) + if rhs_def.op == 'cast': + rhs_def = get_definition(func_ir, rhs_def.value) + require(isinstance(rhs_def, ir.Expr)) + require(_find_unsafe_empty_inferred(func_ir, rhs_def)) + # Find the array dimension of rhs + dim_def = get_definition(func_ir, rhs_def.args[0]) + require(isinstance(dim_def, ir.Expr) and dim_def.op == 'build_tuple') + debug_print("dim_def = ", dim_def) + extra_dims = [get_definition(func_ir, x, lhs_only=True) + for x in dim_def.items ] + debug_print("extra_dims = ", extra_dims) + # Expand size tuple when creating lhs_def with extra_dims + size_tuple_def = get_definition(func_ir, lhs_def.args[0]) + require(isinstance(size_tuple_def, ir.Expr) and + size_tuple_def.op == 'build_tuple') + debug_print("size_tuple_def = ", size_tuple_def) + extra_dims = fix_dependencies(size_tuple_def, extra_dims) + size_tuple_def.items += extra_dims + # In-place modify rhs_def to be getitem + rhs_def.op = 'getitem' + rhs_def.fn = operator.getitem + rhs_def.value = get_definition(func_ir, lhs, lhs_only=True) + rhs_def.index = stmt.index + del rhs_def._kws['func'] + del rhs_def._kws['args'] + del rhs_def._kws['vararg'] + del rhs_def._kws['kws'] + # success + return True + + for label in find_topo_order(func_ir.blocks): + block = func_ir.blocks[label] + for stmt in block.body: + if guard(fix_array_assign, stmt): + block.body.remove(stmt) + + +def _new_definition(func_ir, var, value, loc): + func_ir._definitions[var.name] = [value] + return ir.Assign(value=value, target=var, loc=loc) + + +@rewrites.register_rewrite('after-inference') +class RewriteArrayOfConsts(rewrites.Rewrite): + '''The RewriteArrayOfConsts class is responsible for finding + 1D array creations from a constant list, and rewriting it into + direct initialization of array elements without creating the list. + ''' + def __init__(self, state, *args, **kws): + self.typingctx = state.typingctx + super(RewriteArrayOfConsts, self).__init__(*args, **kws) + + def match(self, func_ir, block, typemap, calltypes): + if len(calltypes) == 0: + return False + self.crnt_block = block + self.new_body = guard(_inline_const_arraycall, block, func_ir, + self.typingctx, typemap, calltypes) + return self.new_body is not None + + def apply(self): + self.crnt_block.body = self.new_body + return self.crnt_block + + +def _inline_const_arraycall(block, func_ir, context, typemap, calltypes): + """Look for array(list) call where list is a constant list created by + build_list, and turn them into direct array creation and initialization, if + the following conditions are met: + 1. The build_list call immediate precedes the array call; + 2. The list variable is no longer live after array call; + If any condition check fails, no modification will be made. + """ + debug_print = _make_debug_print("inline_const_arraycall") + scope = block.scope + + def inline_array(array_var, expr, stmts, list_vars, dels): + """Check to see if the given "array_var" is created from a list + of constants, and try to inline the list definition as array + initialization. + + Extra statements produced with be appended to "stmts". + """ + callname = guard(find_callname, func_ir, expr) + require(callname and callname[1] == 'numpy' and callname[0] == 'array') + require(expr.args[0].name in list_vars) + ret_type = calltypes[expr].return_type + require(isinstance(ret_type, types.ArrayCompatible) and + ret_type.ndim == 1) + loc = expr.loc + list_var = expr.args[0] + # Get the type of the array to be created. + array_typ = typemap[array_var.name] + debug_print("inline array_var = ", array_var, " list_var = ", list_var) + # Get the element type of the array to be created. + dtype = array_typ.dtype + # Get the sequence of operations to provide values to the new array. + seq, _ = find_build_sequence(func_ir, list_var) + size = len(seq) + # Create a tuple to pass to empty below to specify the new array size. + size_var = scope.redefine("size", loc) + size_tuple_var = scope.redefine("size_tuple", loc) + size_typ = types.intp + size_tuple_typ = types.UniTuple(size_typ, 1) + typemap[size_var.name] = size_typ + typemap[size_tuple_var.name] = size_tuple_typ + stmts.append( + _new_definition(func_ir, size_var, + ir.Const(size, loc=loc), loc)) + stmts.append( + _new_definition(func_ir, size_tuple_var, + ir.Expr.build_tuple(items=[size_var], loc=loc), + loc)) + + # The general approach is to create an empty array and then fill + # the elements in one-by-one from their specification. + + # Get the numpy type to pass to empty. + nptype = types.DType(dtype) + + # Create a variable to hold the numpy empty function. + empty_func = scope.redefine("empty_func", loc) + fnty = get_np_ufunc_typ(np.empty, context) + context.resolve_function_type(fnty, (size_typ,), {'dtype': nptype}) + + typemap[empty_func.name] = fnty + + stmts.append( + _new_definition(func_ir, empty_func, + ir.Global('empty', np.empty, loc=loc), loc)) + + # We pass two arguments to empty, first the size tuple and second + # the dtype of the new array. Here, we created typ_var which is + # the dtype argument of the new array. typ_var in turn is created + # by getattr of the dtype string on the numpy module. + + # Create var for numpy module. + g_np_var = scope.redefine("$np_g_var", loc) + typemap[g_np_var.name] = types.misc.Module(np) + g_np = ir.Global('np', np, loc) + stmts.append(_new_definition(func_ir, g_np_var, g_np, loc)) + + # Create var for result of numpy.. + typ_var = scope.redefine("$np_typ_var", loc) + typemap[typ_var.name] = nptype + dtype_str = str(dtype) + if dtype_str == 'bool': + dtype_str = 'bool_' + # Get dtype attribute of numpy module. + np_typ_getattr = ir.Expr.getattr(g_np_var, dtype_str, loc) + stmts.append(_new_definition(func_ir, typ_var, np_typ_getattr, loc)) + + # Create the call to numpy.empty passing the size tuple and dtype var. + empty_call = ir.Expr.call(empty_func, [size_var, typ_var], {}, loc=loc) + calltypes[empty_call] = typing.signature(array_typ, size_typ, nptype) + stmts.append(_new_definition(func_ir, array_var, empty_call, loc)) + + # Fill in the new empty array one-by-one. + for i in range(size): + index_var = scope.redefine("index", loc) + index_typ = types.intp + typemap[index_var.name] = index_typ + stmts.append( + _new_definition(func_ir, index_var, ir.Const(i, loc), loc)) + setitem = ir.SetItem(array_var, index_var, seq[i], loc) + calltypes[setitem] = typing.signature(types.none, array_typ, + index_typ, dtype) + stmts.append(setitem) + + stmts.extend(dels) + return True + + class State(object): + """ + This class is used to hold the state in the following loop so as to make + it easy to reset the state of the variables tracking the various + statement kinds + """ + + def __init__(self): + # list_vars keep track of the variable created from the latest + # build_list instruction, as well as its synonyms. + self.list_vars = [] + # dead_vars keep track of those in list_vars that are considered + # dead. + self.dead_vars = [] + # list_items keep track of the elements used in build_list. + self.list_items = [] + self.stmts = [] + # dels keep track of the deletion of list_items, which will need to + # be moved after array initialization. + self.dels = [] + # tracks if a modification has taken place + self.modified = False + + def reset(self): + """ + Resets the internal state of the variables used for tracking + """ + self.list_vars = [] + self.dead_vars = [] + self.list_items = [] + self.dels = [] + + def list_var_used(self, inst): + """ + Returns True if the list being analysed is used between the + build_list and the array call. + """ + return any([x.name in self.list_vars for x in inst.list_vars()]) + + state = State() + + for inst in block.body: + if isinstance(inst, ir.Assign): + if isinstance(inst.value, ir.Var): + if inst.value.name in state.list_vars: + state.list_vars.append(inst.target.name) + state.stmts.append(inst) + continue + elif isinstance(inst.value, ir.Expr): + expr = inst.value + if expr.op == 'build_list': + # new build_list encountered, reset state + state.reset() + state.list_items = [x.name for x in expr.items] + state.list_vars = [inst.target.name] + state.stmts.append(inst) + continue + elif expr.op == 'call' and expr in calltypes: + if guard(inline_array, inst.target, expr, + state.stmts, state.list_vars, state.dels): + state.modified = True + continue + elif isinstance(inst, ir.Del): + removed_var = inst.value + if removed_var in state.list_items: + state.dels.append(inst) + continue + elif removed_var in state.list_vars: + # one of the list_vars is considered dead. + state.dead_vars.append(removed_var) + state.list_vars.remove(removed_var) + state.stmts.append(inst) + if state.list_vars == []: + # if all list_vars are considered dead, we need to filter + # them out from existing stmts to completely remove + # build_list. + # Note that if a translation didn't take place, dead_vars + # will also be empty when we reach this point. + body = [] + for inst in state.stmts: + if ((isinstance(inst, ir.Assign) and + inst.target.name in state.dead_vars) or + (isinstance(inst, ir.Del) and + inst.value in state.dead_vars)): + continue + body.append(inst) + state.stmts = body + state.dead_vars = [] + state.modified = True + continue + state.stmts.append(inst) + + # If the list is used in any capacity between build_list and array + # call, then we must call off the translation for this list because + # it could be mutated and list_items would no longer be applicable. + if state.list_var_used(inst): + state.reset() + + return state.stmts if state.modified else None diff --git a/shared/package-files/38/38018006a757341f200a524510631c928c9cb997086ac31a0254b646488a44e2/dtype.pyi b/shared/package-files/38/38018006a757341f200a524510631c928c9cb997086ac31a0254b646488a44e2/dtype.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0f3810f3c014aafac0e149cfc6da0ec38c61f165 --- /dev/null +++ b/shared/package-files/38/38018006a757341f200a524510631c928c9cb997086ac31a0254b646488a44e2/dtype.pyi @@ -0,0 +1,20 @@ +import numpy as np + + +class Test1: + not_dtype = np.dtype(float) + + +class Test2: + dtype = float + + +np.dtype(Test1()) # E: No overload variant of "dtype" matches +np.dtype(Test2()) # E: incompatible type + +np.dtype( # E: No overload variant of "dtype" matches + { + "field1": (float, 1), + "field2": (int, 3), + } +) diff --git a/shared/package-files/38/380554f7e2ef0ca5c82cb620dfc547c63ebda009b9ee471f518624ebb10d7ca6/torch_version.py b/shared/package-files/38/380554f7e2ef0ca5c82cb620dfc547c63ebda009b9ee471f518624ebb10d7ca6/torch_version.py new file mode 100644 index 0000000000000000000000000000000000000000..f73a0b71c1a815be6b15d1972fed8350004d6721 --- /dev/null +++ b/shared/package-files/38/380554f7e2ef0ca5c82cb620dfc547c63ebda009b9ee471f518624ebb10d7ca6/torch_version.py @@ -0,0 +1,58 @@ +# mypy: ignore-errors + +from typing import Any, Iterable +from .version import __version__ as internal_version +from ._vendor.packaging.version import Version, InvalidVersion + +__all__ = ['TorchVersion'] + + +class TorchVersion(str): + """A string with magic powers to compare to both Version and iterables! + Prior to 1.10.0 torch.__version__ was stored as a str and so many did + comparisons against torch.__version__ as if it were a str. In order to not + break them we have TorchVersion which masquerades as a str while also + having the ability to compare against both packaging.version.Version as + well as tuples of values, eg. (1, 2, 1) + Examples: + Comparing a TorchVersion object to a Version object + TorchVersion('1.10.0a') > Version('1.10.0a') + Comparing a TorchVersion object to a Tuple object + TorchVersion('1.10.0a') > (1, 2) # 1.2 + TorchVersion('1.10.0a') > (1, 2, 1) # 1.2.1 + Comparing a TorchVersion object against a string + TorchVersion('1.10.0a') > '1.2' + TorchVersion('1.10.0a') > '1.2.1' + """ + # fully qualified type names here to appease mypy + def _convert_to_version(self, inp: Any) -> Any: + if isinstance(inp, Version): + return inp + elif isinstance(inp, str): + return Version(inp) + elif isinstance(inp, Iterable): + # Ideally this should work for most cases by attempting to group + # the version tuple, assuming the tuple looks (MAJOR, MINOR, ?PATCH) + # Examples: + # * (1) -> Version("1") + # * (1, 20) -> Version("1.20") + # * (1, 20, 1) -> Version("1.20.1") + return Version('.'.join(str(item) for item in inp)) + else: + raise InvalidVersion(inp) + + def _cmp_wrapper(self, cmp: Any, method: str) -> bool: + try: + return getattr(Version(self), method)(self._convert_to_version(cmp)) + except BaseException as e: + if not isinstance(e, InvalidVersion): + raise + # Fall back to regular string comparison if dealing with an invalid + # version like 'parrot' + return getattr(super(), method)(cmp) + + +for cmp_method in ["__gt__", "__lt__", "__eq__", "__ge__", "__le__"]: + setattr(TorchVersion, cmp_method, lambda x, y, method=cmp_method: x._cmp_wrapper(y, method)) + +__version__ = TorchVersion(internal_version) diff --git a/shared/package-files/38/380a0b769ae22557aec27ceac295ccac4f1f2f1c7a1e9007f2f52fefcd9f844c/_nested_from_padded_cpu_dispatch.h b/shared/package-files/38/380a0b769ae22557aec27ceac295ccac4f1f2f1c7a1e9007f2f52fefcd9f844c/_nested_from_padded_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7b58fb64779165a7eba1d06fe0c710d4bbb28aa1 --- /dev/null +++ b/shared/package-files/38/380a0b769ae22557aec27ceac295ccac4f1f2f1c7a1e9007f2f52fefcd9f844c/_nested_from_padded_cpu_dispatch.h @@ -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 at::Tensor _nested_from_padded(const at::Tensor & padded, const at::Tensor & cpu_nested_shape_example, bool fuse_transform_0213=false); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/38/380bd25cce6eb52dc1ce3902c824488f7399312d229be887a17d9856cdbd1a98/lerp_meta_dispatch.h b/shared/package-files/38/380bd25cce6eb52dc1ce3902c824488f7399312d229be887a17d9856cdbd1a98/lerp_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a320092df1fdf8c7bf3eef483d5feddf1b83063c --- /dev/null +++ b/shared/package-files/38/380bd25cce6eb52dc1ce3902c824488f7399312d229be887a17d9856cdbd1a98/lerp_meta_dispatch.h @@ -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 meta { + +TORCH_API at::Tensor lerp(const at::Tensor & self, const at::Tensor & end, const at::Scalar & weight); +TORCH_API at::Tensor & lerp_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & end, const at::Scalar & weight); +TORCH_API at::Tensor & lerp_outf(const at::Tensor & self, const at::Tensor & end, const at::Scalar & weight, at::Tensor & out); +TORCH_API at::Tensor & lerp_(at::Tensor & self, const at::Tensor & end, const at::Scalar & weight); +TORCH_API at::Tensor lerp(const at::Tensor & self, const at::Tensor & end, const at::Tensor & weight); +TORCH_API at::Tensor & lerp_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & end, const at::Tensor & weight); +TORCH_API at::Tensor & lerp_outf(const at::Tensor & self, const at::Tensor & end, const at::Tensor & weight, at::Tensor & out); +TORCH_API at::Tensor & lerp_(at::Tensor & self, const at::Tensor & end, const at::Tensor & weight); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/38/380ed3c8ae0cab557a1074da34b21f9493c2418129e7fcc84a44edb3af5a6082/test_stencils.py b/shared/package-files/38/380ed3c8ae0cab557a1074da34b21f9493c2418129e7fcc84a44edb3af5a6082/test_stencils.py new file mode 100644 index 0000000000000000000000000000000000000000..a06a737a944ab58bf4d974f04dcc270e8a00fd24 --- /dev/null +++ b/shared/package-files/38/380ed3c8ae0cab557a1074da34b21f9493c2418129e7fcc84a44edb3af5a6082/test_stencils.py @@ -0,0 +1,3223 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import numpy as np +from contextlib import contextmanager + +import numba +from numba import njit, stencil +from numba.core import types, registry +from numba.core.compiler import compile_extra, Flags +from numba.core.cpu import ParallelOptions +from numba.tests.support import skip_parfors_unsupported, _32bit +from numba.core.errors import LoweringError, TypingError, NumbaValueError +import unittest + + +skip_unsupported = skip_parfors_unsupported + + +@stencil +def stencil1_kernel(a): + return 0.25 * (a[0, 1] + a[1, 0] + a[0, -1] + a[-1, 0]) + + +@stencil(neighborhood=((-5, 0), )) +def stencil2_kernel(a): + cum = a[-5] + for i in range(-4, 1): + cum += a[i] + return 0.3 * cum + + +@stencil(cval=1.0) +def stencil3_kernel(a): + return 0.25 * a[-2, 2] + + +@stencil +def stencil_multiple_input_kernel(a, b): + return 0.25 * (a[0, 1] + a[1, 0] + a[0, -1] + a[-1, 0] + + b[0, 1] + b[1, 0] + b[0, -1] + b[-1, 0]) + + +@stencil +def stencil_multiple_input_kernel_var(a, b, w): + return w * (a[0, 1] + a[1, 0] + a[0, -1] + a[-1, 0] + + b[0, 1] + b[1, 0] + b[0, -1] + b[-1, 0]) + + +@stencil +def stencil_multiple_input_mixed_types_2d(a, b, f): + return a[0, 0] if f[0, 0] else b[0, 0] + + +@stencil(standard_indexing=("b",)) +def stencil_with_standard_indexing_1d(a, b): + return a[-1] * b[0] + a[0] * b[1] + + +@stencil(standard_indexing=("b",)) +def stencil_with_standard_indexing_2d(a, b): + return (a[0, 1] * b[0, 1] + a[1, 0] * b[1, 0] + + a[0, -1] * b[0, -1] + a[-1, 0] * b[-1, 0]) + + +@njit +def addone_njit(a): + return a + 1 + + +if not _32bit: # prevent compilation on unsupported 32bit targets + @njit(parallel=True) + def addone_pjit(a): + return a + 1 + + +class TestStencilBase(unittest.TestCase): + + _numba_parallel_test_ = False + + def __init__(self, *args): + # flags for njit() + self.cflags = Flags() + self.cflags.nrt = True + + super(TestStencilBase, self).__init__(*args) + + def _compile_this(self, func, sig, flags): + return compile_extra(registry.cpu_target.typing_context, + registry.cpu_target.target_context, func, sig, + None, flags, {}) + + def compile_parallel(self, func, sig, **kws): + flags = Flags() + flags.nrt = True + options = True if not kws else kws + flags.auto_parallel = ParallelOptions(options) + return self._compile_this(func, sig, flags) + + def compile_njit(self, func, sig): + return self._compile_this(func, sig, flags=self.cflags) + + def compile_all(self, pyfunc, *args, **kwargs): + sig = tuple([numba.typeof(x) for x in args]) + # compile with parallel=True + cpfunc = self.compile_parallel(pyfunc, sig) + # compile a standard njit of the original function + cfunc = self.compile_njit(pyfunc, sig) + return cfunc, cpfunc + + def check(self, no_stencil_func, pyfunc, *args): + cfunc, cpfunc = self.compile_all(pyfunc, *args) + # results without stencil macro + expected = no_stencil_func(*args) + # python result + py_output = pyfunc(*args) + + # njit result + njit_output = cfunc.entry_point(*args) + + # parfor result + parfor_output = cpfunc.entry_point(*args) + + np.testing.assert_almost_equal(py_output, expected, decimal=3) + np.testing.assert_almost_equal(njit_output, expected, decimal=3) + np.testing.assert_almost_equal(parfor_output, expected, decimal=3) + + # make sure parfor set up scheduling + self.assertIn('@do_scheduling', cpfunc.library.get_llvm_str()) + + +class TestStencil(TestStencilBase): + + def __init__(self, *args, **kwargs): + super(TestStencil, self).__init__(*args, **kwargs) + + @skip_unsupported + def test_stencil1(self): + """Tests whether the optional out argument to stencil calls works. + """ + def test_with_out(n): + A = np.arange(n**2).reshape((n, n)) + B = np.zeros(n**2).reshape((n, n)) + B = stencil1_kernel(A, out=B) + return B + + def test_without_out(n): + A = np.arange(n**2).reshape((n, n)) + B = stencil1_kernel(A) + return B + + def test_impl_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = np.zeros(n**2).reshape((n, n)) + for i in range(1, n - 1): + for j in range(1, n - 1): + B[i, j] = 0.25 * (A[i, j + 1] + + A[i + 1, j] + A[i, j - 1] + A[i - 1, j]) + return B + + n = 100 + self.check(test_impl_seq, test_with_out, n) + self.check(test_impl_seq, test_without_out, n) + + @skip_unsupported + def test_stencil2(self): + """Tests whether the optional neighborhood argument to the stencil + decorate works. + """ + def test_seq(n): + A = np.arange(n) + B = stencil2_kernel(A) + return B + + def test_impl_seq(n): + A = np.arange(n) + B = np.zeros(n) + for i in range(5, len(A)): + B[i] = 0.3 * sum(A[i - 5:i + 1]) + return B + + n = 100 + self.check(test_impl_seq, test_seq, n) + # variable length neighborhood in numba.stencil call + # only supported in parallel path + + def test_seq(n, w): + A = np.arange(n) + + def stencil2_kernel(a, w): + cum = a[-w] + for i in range(-w + 1, w + 1): + cum += a[i] + return 0.3 * cum + B = numba.stencil(stencil2_kernel, neighborhood=((-w, w), ))(A, w) + return B + + def test_impl_seq(n, w): + A = np.arange(n) + B = np.zeros(n) + for i in range(w, len(A) - w): + B[i] = 0.3 * sum(A[i - w:i + w + 1]) + return B + n = 100 + w = 5 + cpfunc = self.compile_parallel(test_seq, (types.intp, types.intp)) + expected = test_impl_seq(n, w) + # parfor result + parfor_output = cpfunc.entry_point(n, w) + np.testing.assert_almost_equal(parfor_output, expected, decimal=3) + self.assertIn('@do_scheduling', cpfunc.library.get_llvm_str()) + # test index_offsets + + def test_seq(n, w, offset): + A = np.arange(n) + + def stencil2_kernel(a, w): + cum = a[-w + 1] + for i in range(-w + 1, w + 1): + cum += a[i + 1] + return 0.3 * cum + B = numba.stencil(stencil2_kernel, neighborhood=((-w, w), ), + index_offsets=(-offset, ))(A, w) + return B + + offset = 1 + cpfunc = self.compile_parallel(test_seq, (types.intp, types.intp, + types.intp)) + parfor_output = cpfunc.entry_point(n, w, offset) + np.testing.assert_almost_equal(parfor_output, expected, decimal=3) + self.assertIn('@do_scheduling', cpfunc.library.get_llvm_str()) + # test slice in kernel + + def test_seq(n, w, offset): + A = np.arange(n) + + def stencil2_kernel(a, w): + return 0.3 * np.sum(a[-w + 1:w + 2]) + B = numba.stencil(stencil2_kernel, neighborhood=((-w, w), ), + index_offsets=(-offset, ))(A, w) + return B + + offset = 1 + cpfunc = self.compile_parallel(test_seq, (types.intp, types.intp, + types.intp)) + parfor_output = cpfunc.entry_point(n, w, offset) + np.testing.assert_almost_equal(parfor_output, expected, decimal=3) + self.assertIn('@do_scheduling', cpfunc.library.get_llvm_str()) + + @skip_unsupported + def test_stencil3(self): + """Tests whether a non-zero optional cval argument to the stencil + decorator works. Also tests integer result type. + """ + def test_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = stencil3_kernel(A) + return B + + test_njit = njit(test_seq) + test_par = njit(test_seq, parallel=True) + + n = 5 + seq_res = test_seq(n) + njit_res = test_njit(n) + par_res = test_par(n) + + self.assertTrue(seq_res[0, 0] == 1.0 and seq_res[4, 4] == 1.0) + self.assertTrue(njit_res[0, 0] == 1.0 and njit_res[4, 4] == 1.0) + self.assertTrue(par_res[0, 0] == 1.0 and par_res[4, 4] == 1.0) + + @skip_unsupported + def test_stencil_standard_indexing_1d(self): + """Tests standard indexing with a 1d array. + """ + def test_seq(n): + A = np.arange(n) + B = [3.0, 7.0] + C = stencil_with_standard_indexing_1d(A, B) + return C + + def test_impl_seq(n): + A = np.arange(n) + B = [3.0, 7.0] + C = np.zeros(n) + + for i in range(1, n): + C[i] = A[i - 1] * B[0] + A[i] * B[1] + return C + + n = 100 + self.check(test_impl_seq, test_seq, n) + + @skip_unsupported + def test_stencil_standard_indexing_2d(self): + """Tests standard indexing with a 2d array and multiple stencil calls. + """ + def test_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = np.ones((3, 3)) + C = stencil_with_standard_indexing_2d(A, B) + D = stencil_with_standard_indexing_2d(C, B) + return D + + def test_impl_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = np.ones((3, 3)) + C = np.zeros(n**2).reshape((n, n)) + D = np.zeros(n**2).reshape((n, n)) + + for i in range(1, n - 1): + for j in range(1, n - 1): + C[i, j] = (A[i, j + 1] * B[0, 1] + A[i + 1, j] * B[1, 0] + + A[i, j - 1] * B[0, -1] + A[i - 1, j] * B[-1, 0]) + for i in range(1, n - 1): + for j in range(1, n - 1): + D[i, j] = (C[i, j + 1] * B[0, 1] + C[i + 1, j] * B[1, 0] + + C[i, j - 1] * B[0, -1] + C[i - 1, j] * B[-1, 0]) + return D + + n = 5 + self.check(test_impl_seq, test_seq, n) + + @skip_unsupported + def test_stencil_multiple_inputs(self): + """Tests whether multiple inputs of the same size work. + """ + def test_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = np.arange(n**2).reshape((n, n)) + C = stencil_multiple_input_kernel(A, B) + return C + + def test_impl_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = np.arange(n**2).reshape((n, n)) + C = np.zeros(n**2).reshape((n, n)) + for i in range(1, n - 1): + for j in range(1, n - 1): + C[i, j] = 0.25 * \ + (A[i, j + 1] + A[i + 1, j] + + A[i, j - 1] + A[i - 1, j] + + B[i, j + 1] + B[i + 1, j] + + B[i, j - 1] + B[i - 1, j]) + return C + + n = 3 + self.check(test_impl_seq, test_seq, n) + # test stencil with a non-array input + + def test_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = np.arange(n**2).reshape((n, n)) + w = 0.25 + C = stencil_multiple_input_kernel_var(A, B, w) + return C + self.check(test_impl_seq, test_seq, n) + + @skip_unsupported + def test_stencil_mixed_types(self): + def test_impl_seq(n): + A = np.arange(n ** 2).reshape((n, n)) + B = n ** 2 - np.arange(n ** 2).reshape((n, n)) + S = np.eye(n, dtype=np.bool_) + O = np.zeros((n, n), dtype=A.dtype) + for i in range(0, n): + for j in range(0, n): + O[i, j] = A[i, j] if S[i, j] else B[i, j] + return O + + def test_seq(n): + A = np.arange(n ** 2).reshape((n, n)) + B = n ** 2 - np.arange(n ** 2).reshape((n, n)) + S = np.eye(n, dtype=np.bool_) + O = stencil_multiple_input_mixed_types_2d(A, B, S) + return O + + n = 3 + self.check(test_impl_seq, test_seq, n) + + @skip_unsupported + def test_stencil_call(self): + """Tests 2D numba.stencil calls. + """ + def test_impl1(n): + A = np.arange(n**2).reshape((n, n)) + B = np.zeros(n**2).reshape((n, n)) + numba.stencil(lambda a: 0.25 * (a[0, 1] + a[1, 0] + a[0, -1] + + a[-1, 0]))(A, out=B) + return B + + def test_impl2(n): + A = np.arange(n**2).reshape((n, n)) + B = np.zeros(n**2).reshape((n, n)) + + def sf(a): + return 0.25 * (a[0, 1] + a[1, 0] + a[0, -1] + a[-1, 0]) + B = numba.stencil(sf)(A) + return B + + def test_impl_seq(n): + A = np.arange(n**2).reshape((n, n)) + B = np.zeros(n**2).reshape((n, n)) + for i in range(1, n - 1): + for j in range(1, n - 1): + B[i, j] = 0.25 * (A[i, j + 1] + A[i + 1, j] + + A[i, j - 1] + A[i - 1, j]) + return B + + n = 100 + self.check(test_impl_seq, test_impl1, n) + self.check(test_impl_seq, test_impl2, n) + + @skip_unsupported + def test_stencil_call_1D(self): + """Tests 1D numba.stencil calls. + """ + def test_impl(n): + A = np.arange(n) + B = np.zeros(n) + numba.stencil(lambda a: 0.3 * (a[-1] + a[0] + a[1]))(A, out=B) + return B + + def test_impl_seq(n): + A = np.arange(n) + B = np.zeros(n) + for i in range(1, n - 1): + B[i] = 0.3 * (A[i - 1] + A[i] + A[i + 1]) + return B + + n = 100 + self.check(test_impl_seq, test_impl, n) + + @skip_unsupported + def test_stencil_call_const(self): + """Tests numba.stencil call that has an index that can be inferred as + constant from a unary expr. Otherwise, this would raise an error since + neighborhood length is not specified. + """ + def test_impl1(n): + A = np.arange(n) + B = np.zeros(n) + c = 1 + numba.stencil(lambda a,c : 0.3 * (a[-c] + a[0] + a[c]))(A, c, out=B) + return B + + def test_impl2(n): + A = np.arange(n) + B = np.zeros(n) + c = 2 + numba.stencil( + lambda a,c : 0.3 * (a[1 - c] + a[0] + a[c - 1]))(A, c, out=B) + return B + + # recursive expr case + def test_impl3(n): + A = np.arange(n) + B = np.zeros(n) + c = 2 + numba.stencil( + lambda a,c : 0.3 * (a[-c + 1] + a[0] + a[c - 1]))(A, c, out=B) + return B + + # multi-constant case + def test_impl4(n): + A = np.arange(n) + B = np.zeros(n) + d = 1 + c = 2 + numba.stencil( + lambda a,c,d : 0.3 * (a[-c + d] + a[0] + a[c - d]))(A, c, d, + out=B) + return B + + def test_impl_seq(n): + A = np.arange(n) + B = np.zeros(n) + c = 1 + for i in range(1, n - 1): + B[i] = 0.3 * (A[i - c] + A[i] + A[i + c]) + return B + + n = 100 + # constant inference is only possible in parallel path + cpfunc1 = self.compile_parallel(test_impl1, (types.intp,)) + cpfunc2 = self.compile_parallel(test_impl2, (types.intp,)) + cpfunc3 = self.compile_parallel(test_impl3, (types.intp,)) + cpfunc4 = self.compile_parallel(test_impl4, (types.intp,)) + expected = test_impl_seq(n) + # parfor result + parfor_output1 = cpfunc1.entry_point(n) + parfor_output2 = cpfunc2.entry_point(n) + parfor_output3 = cpfunc3.entry_point(n) + parfor_output4 = cpfunc4.entry_point(n) + np.testing.assert_almost_equal(parfor_output1, expected, decimal=3) + np.testing.assert_almost_equal(parfor_output2, expected, decimal=3) + np.testing.assert_almost_equal(parfor_output3, expected, decimal=3) + np.testing.assert_almost_equal(parfor_output4, expected, decimal=3) + + # check error in regular Python path + with self.assertRaises(NumbaValueError) as e: + test_impl4(4) + + self.assertIn("stencil kernel index is not constant, " + "'neighborhood' option required", str(e.exception)) + # check error in njit path + # TODO: ValueError should be thrown instead of LoweringError + with self.assertRaises((LoweringError, NumbaValueError)) as e: + njit(test_impl4)(4) + + self.assertIn("stencil kernel index is not constant, " + "'neighborhood' option required", str(e.exception)) + + @skip_unsupported + def test_stencil_parallel_off(self): + """Tests 1D numba.stencil calls without parallel translation + turned off. + """ + def test_impl(A): + return numba.stencil(lambda a: 0.3 * (a[-1] + a[0] + a[1]))(A) + + cpfunc = self.compile_parallel(test_impl, (numba.float64[:],), + stencil=False) + self.assertNotIn('@do_scheduling', cpfunc.library.get_llvm_str()) + + @skip_unsupported + def test_stencil_nested1(self): + """Tests whether nested stencil decorator works. + """ + @njit(parallel=True) + def test_impl(n): + @stencil + def fun(a): + c = 2 + return a[-c + 1] + B = fun(n) + return B + + def test_impl_seq(n): + B = np.zeros(len(n), dtype=int) + for i in range(1, len(n)): + B[i] = n[i - 1] + return B + + n = np.arange(10) + np.testing.assert_equal(test_impl(n), test_impl_seq(n)) + + @skip_unsupported + def test_out_kwarg_w_cval(self): + """ Issue #3518, out kwarg did not work with cval.""" + # test const value that matches the arg dtype, and one that can be cast + const_vals = [7, 7.0] + + def kernel(a): + return (a[0, 0] - a[1, 0]) + + for const_val in const_vals: + stencil_fn = numba.stencil(kernel, cval=const_val) + + def wrapped(): + A = np.arange(12).reshape((3, 4)) + ret = np.ones_like(A) + stencil_fn(A, out=ret) + return ret + + # stencil function case + A = np.arange(12).reshape((3, 4)) + expected = np.full_like(A, -4) + expected[-1, :] = const_val + ret = np.ones_like(A) + stencil_fn(A, out=ret) + np.testing.assert_almost_equal(ret, expected) + + # wrapped function case, check njit, then njit(parallel=True) + impls = self.compile_all(wrapped,) + for impl in impls: + got = impl.entry_point() + np.testing.assert_almost_equal(got, expected) + + # now check exceptions for cval dtype mismatch with out kwarg dtype + stencil_fn = numba.stencil(kernel, cval=1j) + + def wrapped(): + A = np.arange(12).reshape((3, 4)) + ret = np.ones_like(A) + stencil_fn(A, out=ret) + return ret + + A = np.arange(12).reshape((3, 4)) + ret = np.ones_like(A) + with self.assertRaises(NumbaValueError) as e: + stencil_fn(A, out=ret) + msg = "cval type does not match stencil return type." + self.assertIn(msg, str(e.exception)) + + for compiler in [self.compile_njit, self.compile_parallel]: + try: + compiler(wrapped,()) + except (NumbaValueError, LoweringError) as e: + self.assertIn(msg, str(e)) + else: + raise AssertionError("Expected error was not raised") + + @skip_unsupported + def test_out_kwarg_w_cval_np_attr(self): + """ Test issue #7286 where the cval is a np attr/string-based numerical + constant""" + for cval in (np.nan, np.inf, -np.inf, float('inf'), -float('inf')): + def kernel(a): + return (a[0, 0] - a[1, 0]) + + stencil_fn = numba.stencil(kernel, cval=cval) + + def wrapped(): + A = np.arange(12.).reshape((3, 4)) + ret = np.ones_like(A) + stencil_fn(A, out=ret) + return ret + + # stencil function case + A = np.arange(12.).reshape((3, 4)) + expected = np.full_like(A, -4) + expected[-1, :] = cval + ret = np.ones_like(A) + stencil_fn(A, out=ret) + np.testing.assert_almost_equal(ret, expected) + + # wrapped function case, check njit, then njit(parallel=True) + impls = self.compile_all(wrapped,) + for impl in impls: + got = impl.entry_point() + np.testing.assert_almost_equal(got, expected) + + +@skip_unsupported +class TestManyStencils(TestStencilBase): + # NOTE: the original implementation of this test used manipulations of the + # Python AST repr of a kernel to create another implementation of the + # stencil being tested so to act as another reference point when + # comparing the various forms of @stencil calls. This implementation was + # based on the cPython 3.7 version of the AST and proved too much effort to + # continuously port to newer python versions. Ahead of dropping Python 3.7 + # support, all the kernel invocations were translated via the ``astor`` + # package ``astor.to_source()`` function to pure python source and this + # source was hardcoded into the tests themselves. In the following tests, + # regions demarked with dashed lines (----) and with the header + # "Autogenerated kernel" correspond to these translations. + + def __init__(self, *args, **kwargs): + super(TestManyStencils, self).__init__(*args, **kwargs) + + def check_against_expected(self, pyfunc, expected, *args, **kwargs): + """ + For a given kernel: + + The expected result is available from argument `expected`. + + The following results are then computed: + * from a pure @stencil decoration of the kernel. + * from the njit of a trivial wrapper function around the pure @stencil + decorated function. + * from the njit(parallel=True) of a trivial wrapper function around + the pure @stencil decorated function. + + The results are then compared. + """ + + options = kwargs.get('options', dict()) + expected_exception = kwargs.get('expected_exception') + + # DEBUG print output arrays + DEBUG_OUTPUT = False + + # collect fails + should_fail = [] + should_not_fail = [] + + # runner that handles fails + @contextmanager + def errorhandler(exty=None, usecase=None): + try: + yield + except Exception as e: + if exty is not None: + lexty = exty if hasattr(exty, '__iter__') else [exty, ] + found = False + for ex in lexty: + found |= isinstance(e, ex) + if not found: + raise + else: + should_not_fail.append( + (usecase, "%s: %s" % + (type(e), str(e)))) + else: + if exty is not None: + should_fail.append(usecase) + + if isinstance(expected_exception, dict): + stencil_ex = expected_exception['stencil'] + njit_ex = expected_exception['njit'] + parfor_ex = expected_exception['parfor'] + else: + stencil_ex = expected_exception + njit_ex = expected_exception + parfor_ex = expected_exception + + stencil_args = {'func_or_mode': pyfunc} + stencil_args.update(options) + + stencilfunc_output = None + with errorhandler(stencil_ex, "@stencil"): + stencil_func_impl = stencil(**stencil_args) + # stencil result + stencilfunc_output = stencil_func_impl(*args) + + # wrapped stencil impl, could this be generated? + if len(args) == 1: + def wrap_stencil(arg0): + return stencil_func_impl(arg0) + elif len(args) == 2: + def wrap_stencil(arg0, arg1): + return stencil_func_impl(arg0, arg1) + elif len(args) == 3: + def wrap_stencil(arg0, arg1, arg2): + return stencil_func_impl(arg0, arg1, arg2) + else: + raise ValueError( + "Up to 3 arguments can be provided, found %s" % + len(args)) + + sig = tuple([numba.typeof(x) for x in args]) + + njit_output = None + with errorhandler(njit_ex, "njit"): + wrapped_cfunc = self.compile_njit(wrap_stencil, sig) + # njit result + njit_output = wrapped_cfunc.entry_point(*args) + + parfor_output = None + with errorhandler(parfor_ex, "parfors"): + wrapped_cpfunc = self.compile_parallel(wrap_stencil, sig) + # parfor result + parfor_output = wrapped_cpfunc.entry_point(*args) + + if DEBUG_OUTPUT: + print("\n@stencil_output:\n", stencilfunc_output) + print("\nnjit_output:\n", njit_output) + print("\nparfor_output:\n", parfor_output) + + try: + if not stencil_ex: + np.testing.assert_almost_equal( + stencilfunc_output, expected, decimal=1) + self.assertEqual(expected.dtype, stencilfunc_output.dtype) + except Exception as e: + should_not_fail.append( + ('@stencil', "%s: %s" % + (type(e), str(e)))) + print("@stencil failed: %s" % str(e)) + + try: + if not njit_ex: + np.testing.assert_almost_equal( + njit_output, expected, decimal=1) + self.assertEqual(expected.dtype, njit_output.dtype) + except Exception as e: + should_not_fail.append(('njit', "%s: %s" % (type(e), str(e)))) + print("@njit failed: %s" % str(e)) + + try: + if not parfor_ex: + np.testing.assert_almost_equal( + parfor_output, expected, decimal=1) + self.assertEqual(expected.dtype, parfor_output.dtype) + try: + self.assertIn( + '@do_scheduling', + wrapped_cpfunc.library.get_llvm_str()) + except AssertionError: + msg = 'Could not find `@do_scheduling` in LLVM IR' + raise AssertionError(msg) + except Exception as e: + should_not_fail.append( + ('parfors', "%s: %s" % + (type(e), str(e)))) + print("@njit(parallel=True) failed: %s" % str(e)) + + if DEBUG_OUTPUT: + print("\n\n") + + if should_fail: + msg = ["%s" % x for x in should_fail] + raise RuntimeError(("The following implementations should have " + "raised an exception but did not:\n%s") % msg) + + if should_not_fail: + impls = ["%s" % x[0] for x in should_not_fail] + errs = ''.join(["%s: Message: %s\n\n" % + x for x in should_not_fail]) + str1 = ("The following implementations should not have raised an " + "exception but did:\n%s\n" % impls) + str2 = "Errors were:\n\n%s" % errs + raise RuntimeError(str1 + str2) + + def check_exceptions(self, pyfunc, *args, **kwargs): + """ + For a given kernel: + + The expected result is computed from a pyStencil version of the + stencil. + + The following results are then computed: + * from a pure @stencil decoration of the kernel. + * from the njit of a trivial wrapper function around the pure @stencil + decorated function. + * from the njit(parallel=True) of a trivial wrapper function around + the pure @stencil decorated function. + + The results are then compared. + """ + options = kwargs.get('options', dict()) + expected_exception = kwargs.get('expected_exception') + + # collect fails + should_fail = [] + should_not_fail = [] + + # runner that handles fails + @contextmanager + def errorhandler(exty=None, usecase=None): + try: + yield + except Exception as e: + if exty is not None: + lexty = exty if hasattr(exty, '__iter__') else [exty, ] + found = False + for ex in lexty: + found |= isinstance(e, ex) + if not found: + raise + else: + should_not_fail.append( + (usecase, "%s: %s" % + (type(e), str(e)))) + else: + if exty is not None: + should_fail.append(usecase) + + if isinstance(expected_exception, dict): + stencil_ex = expected_exception['stencil'] + njit_ex = expected_exception['njit'] + parfor_ex = expected_exception['parfor'] + else: + stencil_ex = expected_exception + njit_ex = expected_exception + parfor_ex = expected_exception + + stencil_args = {'func_or_mode': pyfunc} + stencil_args.update(options) + + with errorhandler(stencil_ex, "@stencil"): + stencil_func_impl = stencil(**stencil_args) + # stencil result + stencil_func_impl(*args) + + # wrapped stencil impl, could this be generated? + if len(args) == 1: + def wrap_stencil(arg0): + return stencil_func_impl(arg0) + elif len(args) == 2: + def wrap_stencil(arg0, arg1): + return stencil_func_impl(arg0, arg1) + elif len(args) == 3: + def wrap_stencil(arg0, arg1, arg2): + return stencil_func_impl(arg0, arg1, arg2) + else: + raise ValueError( + "Up to 3 arguments can be provided, found %s" % + len(args)) + + sig = tuple([numba.typeof(x) for x in args]) + + with errorhandler(njit_ex, "njit"): + wrapped_cfunc = self.compile_njit(wrap_stencil, sig) + # njit result + wrapped_cfunc.entry_point(*args) + + with errorhandler(parfor_ex, "parfors"): + wrapped_cpfunc = self.compile_parallel(wrap_stencil, sig) + # parfor result + wrapped_cpfunc.entry_point(*args) + + if should_fail: + msg = ["%s" % x for x in should_fail] + raise RuntimeError(("The following implementations should have " + "raised an exception but did not:\n%s") % msg) + + if should_not_fail: + impls = ["%s" % x[0] for x in should_not_fail] + errs = ''.join(["%s: Message: %s\n\n" % + x for x in should_not_fail]) + str1 = ("The following implementations should not have raised an " + "exception but did:\n%s\n" % impls) + str2 = "Errors were:\n\n%s" % errs + raise RuntimeError(str1 + str2) + + def exception_dict(self, **kwargs): + d = dict() + d['pyStencil'] = None + d['stencil'] = None + d['njit'] = None + d['parfor'] = None + for k, v in kwargs.items(): + d[k] = v + return d + + def check_stencil_arrays(self, *args, **kwargs): + neighborhood = kwargs.get('neighborhood') + init_shape = args[0].shape + if neighborhood is not None: + if len(init_shape) != len(neighborhood): + raise ValueError('Invalid neighborhood supplied') + for x in args[1:]: + if hasattr(x, 'shape'): + if init_shape != x.shape: + raise ValueError('Input stencil arrays do not commute') + + def test_basic00(self): + """rel index""" + def kernel(a): + return a[0, 0] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic01(self): + """rel index add const""" + def kernel(a): + return a[0, 1] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic02(self): + """rel index add const""" + def kernel(a): + return a[0, -1] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + -1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic03(self): + """rel index add const""" + def kernel(a): + return a[1, 0] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = a[__a + 1, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic04(self): + """rel index add const""" + def kernel(a): + return a[-1, 0] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(1, a.shape[0]): + __b0[__a, __b] = a[__a + -1, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic05(self): + """rel index add const""" + def kernel(a): + return a[-1, 1] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(1, a.shape[0]): + __b0[__a, __b] = a[__a + -1, __b + 1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic06(self): + """rel index add const""" + def kernel(a): + return a[1, -1] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1]): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = a[__a + 1, __b + -1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic07(self): + """rel index add const""" + def kernel(a): + return a[1, 1] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = a[__a + 1, __b + 1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic08(self): + """rel index add const""" + def kernel(a): + return a[-1, -1] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1]): + for __a in range(1, a.shape[0]): + __b0[__a, __b] = a[__a + -1, __b + -1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic09(self): + """rel index add const""" + def kernel(a): + return a[-2, 2] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 2): + for __a in range(2, a.shape[0]): + __b0[__a, __b] = a[__a + -2, __b + 2] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic10(self): + """rel index add const""" + def kernel(a): + return a[0, 0] + a[1, 0] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = a[__a + 0, __b + 0] + a[__a + 1, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic11(self): + """rel index add const""" + def kernel(a): + return a[-1, 0] + a[1, 0] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(1, a.shape[0] - 1): + __b0[__a, __b] = a[__a + -1, __b + 0] + a[__a + 1, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic12(self): + """rel index add const""" + def kernel(a): + return a[-1, 1] + a[1, -1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(1, a.shape[0] - 1): + __b0[__a, __b] = a[__a + -1, __b + 1] + a[__a + 1, __b + -1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic13(self): + """rel index add const""" + def kernel(a): + return a[-1, -1] + a[1, 1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(1, a.shape[0] - 1): + __b0[__a, __b] = a[__a + -1, __b + -1] + a[__a + 1, __b + 1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic14(self): + """rel index add domain change const""" + def kernel(a): + return a[0, 0] + 1j + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 0] + 1.0j + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic14b(self): + """rel index add domain change const""" + def kernel(a): + t = 1.j + return a[0, 0] + t + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + t = 1.0j + __b0[__a, __b] = a[__a + 0, __b + 0] + t + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic15(self): + """two rel index, add const""" + def kernel(a): + return a[0, 0] + a[1, 0] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + a[__a + 1, __b + 0] + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic17(self): + """two rel index boundary test, add const""" + def kernel(a): + return a[0, 0] + a[2, 0] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0] - 2): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + a[__a + 2, __b + 0] + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic18(self): + """two rel index boundary test, add const""" + def kernel(a): + return a[0, 0] + a[-2, 0] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(2, a.shape[0]): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + a[__a + -2, __b + 0] + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic19(self): + """two rel index boundary test, add const""" + def kernel(a): + return a[0, 0] + a[0, 3] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 3): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + a[__a + 0, __b + 3] + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic20(self): + """two rel index boundary test, add const""" + def kernel(a): + return a[0, 0] + a[0, -3] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(3, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + a[__a + 0, __b + -3] + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic21(self): + """same rel, add const""" + def kernel(a): + return a[0, 0] + a[0, 0] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + a[__a + 0, __b + 0] + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic22(self): + """rel idx const expr folding, add const""" + def kernel(a): + return a[1 + 0, 0] + a[0, 0] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 1, __b + 0] + + a[__a + 0, __b + 0] + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic23(self): + """rel idx, work in body""" + def kernel(a): + x = np.sin(10 + a[2, 1]) + return a[1 + 0, 0] + a[0, 0] + x + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0] - 2): + x = np.sin(10 + a[__a + 2, __b + 1]) + __b0[__a, __b] = (a[__a + 1, __b + 0] + + a[__a + 0, __b + 0] + x) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic23a(self): + """rel idx, dead code should not impact rel idx""" + def kernel(a): + x = np.sin(10 + a[2, 1]) # noqa: F841 # dead code expected + return a[1 + 0, 0] + a[0, 0] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0] - 2): + x = np.sin(10 + a[__a + 2, __b + 1]) # noqa: F841 + __b0[__a, __b] = a[__a + 1, __b + 0] + a[__a + 0, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic24(self): + """1d idx on 2d arr""" + a = np.arange(12).reshape(3, 4) + + def kernel(a): + return a[0] + 1. + + self.check_exceptions(kernel, a, expected_exception=[TypingError,]) + + def test_basic25(self): + """no idx on 2d arr""" + a = np.arange(12).reshape(3, 4) + + def kernel(a): + return 1. + self.check_exceptions(kernel, a, expected_exception=[ValueError, + NumbaValueError,]) + + def test_basic26(self): + """3d arr""" + + def kernel(a): + return a[0, 0, 0] - a[0, 1, 0] + 1. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __c in range(0, a.shape[2]): + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b, __c] = (a[__a + 0, __b + 0, __c + 0] - + a[__a + 0, __b + 1, __c + 0] + + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(64).reshape(4, 8, 2) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic27(self): + """4d arr""" + def kernel(a): + return a[0, 0, 0, 0] - a[0, 1, 0, -1] + 1. + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __d in range(1, a.shape[3]): + for __c in range(0, a.shape[2]): + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b, __c, __d] = (a[__a + 0, __b + 0, + __c + 0, __d + 0] - + a[__a + 0, __b + 1, + __c + 0, __d + -1] + + 1.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(128).reshape(4, 8, 2, 2) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic28(self): + """type widen """ + def kernel(a): + return a[0, 0] + np.float64(10.) + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 0] + np.float64(10.0) + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4).astype(np.float32) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic29(self): + """const index from func """ + a = np.arange(12.).reshape(3, 4) + + def kernel(a): + return a[0, int(np.cos(0))] + self.check_exceptions(kernel, a, expected_exception=[ValueError, + NumbaValueError, + LoweringError]) + + def test_basic30(self): + """signed zeros""" + def kernel(a): + return a[-0, -0] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + -0, __b + -0] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12).reshape(3, 4).astype(np.float32) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic31(self): + """does a const propagate? 2D""" + def kernel(a): + t = 1 + return a[t, 0] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0] - 1): + t = 1 + __b0[__a, __b] = a[__a + t, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12).reshape(3, 4).astype(np.float32) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + @unittest.skip("constant folding not implemented") + def test_basic31b(self): + """does a const propagate?""" + a = np.arange(12.).reshape(3, 4) # noqa: F841 + + def kernel(a): + s = 1 + t = 1 - s + return a[t, 0] + + #TODO: add check should this be implemented + + def test_basic31c(self): + """does a const propagate? 1D""" + def kernel(a): + t = 1 + return a[t] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __a in range(0, a.shape[0] - 1): + t = 1 + __b0[__a,] = a[__a + t] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic32(self): + """typed int index""" + a = np.arange(12.).reshape(3, 4) + + def kernel(a): + return a[np.int8(1), 0] + self.check_exceptions(kernel, a, expected_exception=[ValueError, + NumbaValueError, + LoweringError]) + + def test_basic33(self): + """add 0d array""" + def kernel(a): + return a[0, 0] + np.array(1) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 0] + np.array(1) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic34(self): + """More complex rel index with dependency on addition rel index""" + def kernel(a): + g = 4. + a[0, 1] + return g + (a[0, 1] + a[1, 0] + a[0, -1] + np.sin(a[-2, 0])) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(2, a.shape[0] - 1): + g = 4.0 + a[__a + 0, __b + 1] + __b0[__a, __b] = g + (a[__a + 0, __b + 1] + + a[__a + 1, __b + 0] + + a[__a + 0, __b + -1] + + np.sin(a[__a + -2, __b + 0])) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(144).reshape(12, 12) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic35(self): + """simple cval where cval is int but castable to dtype of float""" + def kernel(a): + return a[0, 1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 5, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 1] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a, options={'cval': 5}) + + def test_basic36(self): + """more complex with cval""" + def kernel(a): + return a[0, 1] + a[0, -1] + a[1, -1] + a[1, -1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 5.0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 0, __b + 1] + + a[__a + 0, __b + -1] + + a[__a + 1, __b + -1] + + a[__a + 1, __b + -1]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a, options={'cval': 5}) + + def test_basic37(self): + """cval is expr""" + def kernel(a): + return a[0, 1] + a[0, -1] + a[1, -1] + a[1, -1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 68.0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 0, __b + 1] + + a[__a + 0, __b + -1] + + a[__a + 1, __b + -1] + + a[__a + 1, __b + -1]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a, + options={'cval': 5 + 63.}) + + def test_basic38(self): + """cval is complex""" + def kernel(a): + return a[0, 1] + a[0, -1] + a[1, -1] + a[1, -1] + a = np.arange(12.).reshape(3, 4) + ex = self.exception_dict( + stencil=NumbaValueError, + parfor=NumbaValueError, + njit=NumbaValueError) + self.check_exceptions(kernel, a, options={'cval': 1.j}, + expected_exception=ex) + + def test_basic39(self): + """cval is func expr""" + def kernel(a): + return a[0, 1] + a[0, -1] + a[1, -1] + a[1, -1] + + cval = np.sin(3.) + np.cos(2) + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, cval, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 0, __b + 1] + + a[__a + 0, __b + -1] + + a[__a + 1, __b + -1] + + a[__a + 1, __b + -1]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a, + options={'cval': cval}) + + def test_basic40(self): + """2 args!""" + def kernel(a, b): + return a[0, 1] + b[0, -2] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(2, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 1] + b[__a + 0, __b + -2] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b) + + def test_basic41(self): + """2 args! rel arrays wildly not same size!""" + def kernel(a, b): + return a[0, 1] + b[0, -2] + a = np.arange(12.).reshape(3, 4) + b = np.arange(1.).reshape(1, 1) + self.check_exceptions(kernel, a, b, expected_exception=[ValueError, + AssertionError]) + + def test_basic42(self): + """2 args! rel arrays very close in size""" + def kernel(a, b): + return a[0, 1] + b[0, -2] + a = np.arange(12.).reshape(3, 4) + b = np.arange(9.).reshape(3, 3) + self.check_exceptions(kernel, a, b, expected_exception=[ValueError, + AssertionError]) + + def test_basic43(self): + """2 args more complexity""" + def kernel(a, b): + return a[0, 1] + a[1, 2] + b[-2, 0] + b[0, -1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 2): + for __a in range(2, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 0, __b + 1] + + a[__a + 1, __b + 2] + + b[__a + -2, __b + 0] + + b[__a + 0, __b + -1]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(30.).reshape(5, 6) + b = np.arange(30.).reshape(5, 6) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b) + + def test_basic44(self): + """2 args, has assignment before use""" + def kernel(a, b): + a[0, 1] = 12 + return a[0, 1] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + self.check_exceptions(kernel, a, b, expected_exception=[NumbaValueError, + LoweringError]) + + def test_basic45(self): + """2 args, has assignment and then cross dependency""" + def kernel(a, b): + a[0, 1] = 12 + return a[0, 1] + a[1, 0] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + self.check_exceptions(kernel, a, b, expected_exception=[NumbaValueError, + LoweringError]) + + def test_basic46(self): + """2 args, has cross relidx assignment""" + def kernel(a, b): + a[0, 1] = b[1, 2] + return a[0, 1] + a[1, 0] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + self.check_exceptions(kernel, a, b, expected_exception=[NumbaValueError, + LoweringError]) + + def test_basic47(self): + """3 args""" + def kernel(a, b, c): + return a[0, 1] + b[1, 0] + c[-1, 0] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, c, neighborhood): + self.check_stencil_arrays(a, b, c, neighborhood=neighborhood) + __retdtype = kernel(a, b, c) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(1, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 0, __b + 1] + + b[__a + 1, __b + 0] + + c[__a + -1, __b + 0]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + c = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, c, None) + self.check_against_expected(kernel, expected, a, b, c) + + # matches pyStencil, but all ought to fail + # probably hard to detect? + def test_basic48(self): + """2 args, has assignment before use via memory alias""" + def kernel(a): + c = a.T + c[:, :] = 10 + return a[0, 1] + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a,neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + c = a.T + c[:, :] = 10 + __b0[__a, __b] = a[__a + 0, __b + 1] + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic49(self): + """2 args, standard_indexing on second""" + def kernel(a, b): + return a[0, 1] + b[0, 3] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 1] + b[0, 3] + return __b0 + + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b, + options={'standard_indexing': 'b'}) + + @unittest.skip("dynamic range checking not implemented") + def test_basic50(self): + """2 args, standard_indexing OOB""" + def kernel(a, b): + return a[0, 1] + b[0, 15] + #TODO: add check should this be implemented + + def test_basic51(self): + """2 args, standard_indexing, no relidx""" + def kernel(a, b): + return a[0, 1] + b[0, 2] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + self.check_exceptions(kernel, a, b, + options={'standard_indexing': ['a', 'b']}, + expected_exception=[ValueError, NumbaValueError]) + + def test_basic52(self): + """3 args, standard_indexing on middle arg """ + def kernel(a, b, c): + return a[0, 1] + b[0, 1] + c[1, 2] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, c, neighborhood): + self.check_stencil_arrays(a, c, neighborhood=neighborhood) + __retdtype = kernel(a, b, c) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 2): + for __a in range(0, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + 0, __b + 1] + b[0, 1] + + c[__a + 1, __b + 2]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(4.).reshape(2, 2) + c = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, c, None) + self.check_against_expected(kernel, expected, a, b, c, + options={'standard_indexing': 'b'}) + + def test_basic53(self): + """2 args, standard_indexing on variable that does not exist""" + def kernel(a, b): + return a[0, 1] + b[0, 2] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + ex = self.exception_dict( + stencil=Exception, + parfor=NumbaValueError, + njit=Exception) + self.check_exceptions(kernel, a, b, options={'standard_indexing': 'c'}, + expected_exception=ex) + + def test_basic54(self): + """2 args, standard_indexing, index from var""" + def kernel(a, b): + t = 2 + return a[0, 1] + b[0, t] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + t = 2 + __b0[__a, __b] = a[__a + 0, __b + 1] + b[0, t] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b, + options={'standard_indexing': 'b'}) + + def test_basic55(self): + """2 args, standard_indexing, index from more complex var""" + def kernel(a, b): + s = 1 + t = 2 - s + return a[0, 1] + b[0, t] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + s = 1 + t = 2 - s + __b0[__a, __b] = a[__a + 0, __b + 1] + b[0, t] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b, + options={'standard_indexing': 'b'}) + + def test_basic56(self): + """2 args, standard_indexing, added complexity """ + def kernel(a, b): + s = 1 + acc = 0 + for k in b[0, :]: + acc += k + t = 2 - s - 1 + return a[0, 1] + b[0, t] + acc + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + s = 1 + acc = 0 + for k in b[(0), :]: + acc += k + t = 2 - s - 1 + __b0[__a, __b] = a[__a + 0, __b + 1] + b[0, t] + acc + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b, + options={'standard_indexing': 'b'}) + + def test_basic57(self): + """2 args, standard_indexing, split index operation """ + def kernel(a, b): + c = b[0] + return a[0, 1] + c[1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + c = b[0] + __b0[__a, __b] = a[__a + 0, __b + 1] + c[1] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b, + options={'standard_indexing': 'b'}) + + def test_basic58(self): + """2 args, standard_indexing, split index with broadcast mutation """ + def kernel(a, b): + c = b[0] + 1 + return a[0, 1] + c[1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + c = b[0] + 1 + __b0[__a, __b] = a[__a + 0, __b + 1] + c[1] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b, + options={'standard_indexing': 'b'}) + + def test_basic59(self): + """3 args, mix of array, relative and standard indexing and const""" + def kernel(a, b, c): + return a[0, 1] + b[1, 1] + c + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, c, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b, c) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 1] + b[1, 1] + c + return __b0 + # ---------------------------------------------------------------------- + + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + c = 10 + expected = __kernel(a, b, c, None) + self.check_against_expected(kernel, expected, a, b, c, + options={'standard_indexing': ['b', 'c']}) + + def test_basic60(self): + """3 args, mix of array, relative and standard indexing, + tuple pass through""" + def kernel(a, b, c): + return a[0, 1] + b[1, 1] + c[0] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + c = (10,) + # parfors does not support tuple args for stencil kernels + ex = self.exception_dict(parfor=NumbaValueError) + self.check_exceptions(kernel, a, b, c, + options={'standard_indexing': ['b', 'c']}, + expected_exception=ex) + + def test_basic61(self): + """2 args, standard_indexing on first""" + def kernel(a, b): + return a[0, 1] + b[1, 1] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + self.check_exceptions(kernel, a, b, + options={'standard_indexing': 'a'}, + expected_exception=Exception) + + def test_basic62(self): + """2 args, standard_indexing and cval""" + def kernel(a, b): + return a[0, 1] + b[1, 1] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 10.0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = a[__a + 0, __b + 1] + b[1, 1] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(12.).reshape(3, 4) + b = np.arange(12.).reshape(3, 4) + expected = __kernel(a, b, None) + self.check_against_expected(kernel, expected, a, b, + options={'standard_indexing': 'b', + 'cval': 10.}) + + def test_basic63(self): + """2 args, standard_indexing applied to relative, should fail, + non-const idx""" + def kernel(a, b): + return a[0, b[0, 1]] + a = np.arange(12.).reshape(3, 4) + b = np.arange(12).reshape(3, 4) + ex = self.exception_dict( + stencil=NumbaValueError, + parfor=NumbaValueError, + njit=NumbaValueError) + self.check_exceptions(kernel, a, b, options={'standard_indexing': 'b'}, + expected_exception=ex) + + # stencil, njit, parfors all fail. Does this make sense? + def test_basic64(self): + """1 arg that uses standard_indexing""" + def kernel(a): + return a[0, 0] + a = np.arange(12.).reshape(3, 4) + self.check_exceptions(kernel, a, options={'standard_indexing': 'a'}, + expected_exception=[ValueError, NumbaValueError]) + + def test_basic65(self): + """basic induced neighborhood test""" + def kernel(a): + cumul = 0 + for i in range(-29, 1): + cumul += a[i] + return cumul / 30 + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(29, a.shape[0]): + cumul = 0 + for i in range(-29, 1): + cumul += a[__an + i] + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((-29, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + # Should this work? a[0] is out of neighborhood? + def test_basic66(self): + """basic const neighborhood test""" + def kernel(a): + cumul = 0 + for i in range(-29, 1): + cumul += a[0] + return cumul / 30 + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(29, a.shape[0]): + cumul = 0 + for i in range(-29, 1): + cumul += a[__an + 0] + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((-29, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic67(self): + """basic 2d induced neighborhood test""" + def kernel(a): + cumul = 0 + for i in range(-5, 1): + for j in range(-10, 1): + cumul += a[i, j] + return cumul / (10 * 5) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(10, a.shape[1]): + for __an in range(5, a.shape[0]): + cumul = 0 + for i in range(-5, 1): + for j in range(-10, 1): + cumul += a[__an + i, __bn + j] + __b0[__an, __bn] = cumul / 50 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + nh = ((-5, 0), (-10, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic67b(self): + """basic 2d induced 1D neighborhood""" + def kernel(a): + cumul = 0 + for j in range(-10, 1): + cumul += a[0, j] + return cumul / (10 * 5) + a = np.arange(10. * 20.).reshape(10, 20) + self.check_exceptions(kernel, a, options={'neighborhood': ((-10, 0),)}, + expected_exception=[TypingError, ValueError]) + + # Should this work or is it UB? a[i, 0] is out of neighborhood? + def test_basic68(self): + """basic 2d one induced, one cost neighborhood test""" + def kernel(a): + cumul = 0 + for i in range(-5, 1): + for j in range(-10, 1): + cumul += a[i, 0] + return cumul / (10 * 5) + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(10, a.shape[1]): + for __an in range(5, a.shape[0]): + cumul = 0 + for i in range(-5, 1): + for j in range(-10, 1): + cumul += a[__an + i, __bn + 0] + __b0[__an, __bn] = cumul / 50 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + nh = ((-5, 0), (-10, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + # Should this work or is it UB? a[0, 0] is out of neighborhood? + def test_basic69(self): + """basic 2d two cost neighborhood test""" + def kernel(a): + cumul = 0 + for i in range(-5, 1): + for j in range(-10, 1): + cumul += a[0, 0] + return cumul / (10 * 5) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(10, a.shape[1]): + for __an in range(5, a.shape[0]): + cumul = 0 + for i in range(-5, 1): + for j in range(-10, 1): + cumul += a[__an + 0, __bn + 0] + __b0[__an, __bn] = cumul / 50 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + nh = ((-5, 0), (-10, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic70(self): + """neighborhood adding complexity""" + def kernel(a): + cumul = 0 + zz = 12. + for i in range(-5, 1): + t = zz + i + for j in range(-10, 1): + cumul += a[i, j] + t + return cumul / (10 * 5) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(10, a.shape[1]): + for __an in range(5, a.shape[0]): + cumul = 0 + zz = 12.0 + for i in range(-5, 1): + t = zz + i + for j in range(-10, 1): + cumul += a[__an + i, __bn + j] + t + __b0[__an, __bn] = cumul / 50 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + nh = ((-5, 0), (-10, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic71(self): + """neighborhood, type change""" + def kernel(a): + cumul = 0 + for i in range(-29, 1): + k = 0. + if i > -15: + k = 1j + cumul += a[i] + k + return cumul / 30 + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(29, a.shape[0]): + cumul = 0 + for i in range(-29, 1): + k = 0.0 + if i > -15: + k = 1.0j + cumul += a[__an + i] + k + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((-29, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic72(self): + """neighborhood, narrower range than specified""" + def kernel(a): + cumul = 0 + for i in range(-19, -3): + cumul += a[i] + return cumul / 30 + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(29, a.shape[0]): + cumul = 0 + for i in range(-19, -3): + cumul += a[__an + i] + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((-29, 0),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic73(self): + """neighborhood, +ve range""" + def kernel(a): + cumul = 0 + for i in range(5, 11): + cumul += a[i] + return cumul / 30 + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(0, a.shape[0] - 10): + cumul = 0 + for i in range(5, 11): + cumul += a[__an + i] + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((5, 10),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic73b(self): + """neighborhood, -ve range""" + def kernel(a): + cumul = 0 + for i in range(-10, -4): + cumul += a[i] + return cumul / 30 + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(10, a.shape[0]): + cumul = 0 + for i in range(-10, -4): + cumul += a[__an + i] + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((-10, -5),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic74(self): + """neighborhood, -ve->+ve range span""" + def kernel(a): + cumul = 0 + for i in range(-5, 11): + cumul += a[i] + return cumul / 30 + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(5, a.shape[0] - 10): + cumul = 0 + for i in range(-5, 11): + cumul += a[__an + i] + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((-5, 10),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic75(self): + """neighborhood, -ve->-ve range span""" + def kernel(a): + cumul = 0 + for i in range(-10, -1): + cumul += a[i] + return cumul / 30 + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(10, a.shape[0]): + cumul = 0 + for i in range(-10, -1): + cumul += a[__an + i] + __b0[__an,] = cumul / 30 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(60.) + nh = ((-10, -2),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic76(self): + """neighborhood, mixed range span""" + def kernel(a): + cumul = 0 + zz = 12. + for i in range(-3, 0): + t = zz + i + for j in range(-3, 4): + cumul += a[i, j] + t + return cumul / (10 * 5) + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(3, a.shape[1] - 3): + for __an in range(3, a.shape[0]): + cumul = 0 + zz = 12.0 + for i in range(-3, 0): + t = zz + i + for j in range(-3, 4): + cumul += a[__an + i, __bn + j] + t + __b0[__an, __bn] = cumul / 50 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + nh = ((-3, -1), (-3, 3),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + def test_basic77(self): + """ neighborhood, two args """ + def kernel(a, b): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[i, j] + b[i, j] + return cumul / (9.) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(3, a.shape[1]): + for __an in range(3, a.shape[0]): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += (a[__an + i, __bn + j] + + b[__an + i, __bn + j]) + __b0[__an, __bn] = cumul / 9.0 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + b = np.arange(10. * 20.).reshape(10, 20) + nh = ((-3, 0), (-3, 0),) + expected = __kernel(a, b, nh) + self.check_against_expected(kernel, expected, a, b, + options={'neighborhood': nh}) + + def test_basic78(self): + """ neighborhood, two args, -ve range, -ve range """ + def kernel(a, b): + cumul = 0 + for i in range(-6, -2): + for j in range(-7, -1): + cumul += a[i, j] + b[i, j] + return cumul / (9.) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(7, a.shape[1]): + for __an in range(6, a.shape[0]): + cumul = 0 + for i in range(-6, -2): + for j in range(-7, -1): + cumul += (a[__an + i, __bn + j] + + b[__an + i, __bn + j]) + __b0[__an, __bn] = cumul / 9.0 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(15. * 20.).reshape(15, 20) + b = np.arange(15. * 20.).reshape(15, 20) + nh = ((-6, -3), (-7, -2),) + expected = __kernel(a, b, nh) + self.check_against_expected(kernel, expected, a, b, + options={'neighborhood': nh}) + + def test_basic78b(self): + """ neighborhood, two args, -ve range, +ve range """ + def kernel(a, b): + cumul = 0 + for i in range(-6, -2): + for j in range(2, 10): + cumul += a[i, j] + b[i, j] + return cumul / (9.) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(0, a.shape[1] - 9): + for __an in range(6, a.shape[0]): + cumul = 0 + for i in range(-6, -2): + for j in range(2, 10): + cumul += (a[__an + i, __bn + j] + + b[__an + i, __bn + j]) + __b0[__an, __bn] = cumul / 9.0 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(15. * 20.).reshape(15, 20) + b = np.arange(15. * 20.).reshape(15, 20) + nh = ((-6, -3), (2, 9),) + expected = __kernel(a, b, nh) + self.check_against_expected(kernel, expected, a, b, + options={'neighborhood': nh}) + + def test_basic79(self): + """ neighborhood, two incompatible args """ + def kernel(a, b): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[i, j] + b[i, j] + return cumul / (9.) + a = np.arange(10. * 20.).reshape(10, 20) + b = np.arange(10. * 20.).reshape(10, 10, 2) + ex = self.exception_dict( + stencil=TypingError, + parfor=TypingError, + njit=TypingError) + self.check_exceptions(kernel, a, b, options={'neighborhood': + ((-3, 0), (-3, 0),)}, + expected_exception=ex) + + def test_basic80(self): + """ neighborhood, type change """ + def kernel(a, b): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[i, j] + b + return cumul / (9.) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(3, a.shape[1]): + for __an in range(3, a.shape[0]): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[__an + i, __bn + j] + b + __b0[__an, __bn] = cumul / 9.0 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + b = 12.j + nh = ((-3, 0), (-3, 0)) + expected = __kernel(a, b, nh) + self.check_against_expected(kernel, expected, a, b, + options={'neighborhood': nh}) + + def test_basic81(self): + """ neighborhood, dimensionally incompatible arrays """ + def kernel(a, b): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[i, j] + b[i] + return cumul / (9.) + a = np.arange(10. * 20.).reshape(10, 20) + b = a[0].copy() + ex = self.exception_dict( + stencil=TypingError, + parfor=AssertionError, + njit=TypingError) + self.check_exceptions(kernel, a, b, + options={'neighborhood': ((-3, 0), (-3, 0))}, + expected_exception=ex) + + def test_basic82(self): + """ neighborhood, with standard_indexing""" + def kernel(a, b): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[i, j] + b[1, 3] + return cumul / (9.) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(3, a.shape[1]): + for __an in range(3, a.shape[0]): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[__an + i, __bn + j] + b[1, 3] + __b0[__an, __bn] = cumul / 9.0 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + b = a.copy() + nh = ((-3, 0), (-3, 0)) + expected = __kernel(a, b, nh) + self.check_against_expected(kernel, expected, a, b, + options={'neighborhood': nh, + 'standard_indexing': 'b'}) + + def test_basic83(self): + """ neighborhood, with standard_indexing and cval""" + def kernel(a, b): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[i, j] + b[1, 3] + return cumul / (9.) + a = np.arange(10. * 20.).reshape(10, 20) + b = a.copy() + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 1.5, dtype=type(__retdtype)) + for __bn in range(3, a.shape[1]): + for __an in range(3, a.shape[0]): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[__an + i, __bn + j] + b[1, 3] + __b0[__an, __bn] = cumul / 9.0 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + b = a.copy() + nh = ((-3, 0), (-3, 0)) + expected = __kernel(a, b, nh) + self.check_against_expected(kernel, expected, a, b, + options={'neighborhood': nh, + 'standard_indexing': 'b', + 'cval': 1.5,}) + + def test_basic84(self): + """ kernel calls njit """ + def kernel(a): + return a[0, 0] + addone_njit(a[0, 1]) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + addone_njit.py_func(a[__a + 0, __b + 1])) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic85(self): + """ kernel calls njit(parallel=True)""" + def kernel(a): + return a[0, 0] + addone_pjit(a[0, 1]) + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 1): + for __a in range(0, a.shape[0]): + __b0[__a, __b] = (a[__a + 0, __b + 0] + + addone_pjit.py_func(a[__a + 0, __b + 1])) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + # njit/parfors fail correctly, but the error message isn't very informative + def test_basic86(self): + """ bad kwarg """ + def kernel(a): + return a[0, 0] + + a = np.arange(10. * 20.).reshape(10, 20) + self.check_exceptions(kernel, a, options={'bad': 10}, + expected_exception=[ValueError, TypingError]) + + def test_basic87(self): + """ reserved arg name in use """ + def kernel(__sentinel__): + return __sentinel__[0, 0] + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(__sentinel__, neighborhood): + self.check_stencil_arrays(__sentinel__, neighborhood=neighborhood) + __retdtype = kernel(__sentinel__) + __b0 = np.full(__sentinel__.shape, 0, dtype=type(__retdtype)) + for __b in range(0, __sentinel__.shape[1]): + for __a in range(0, __sentinel__.shape[0]): + __b0[__a, __b] = __sentinel__[__a + 0, __b + 0] + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic88(self): + """ use of reserved word """ + def kernel(a, out): + return out * a[0, 1] + a = np.arange(12.).reshape(3, 4) + ex = self.exception_dict( + stencil=NumbaValueError, + parfor=NumbaValueError, + njit=NumbaValueError) + self.check_exceptions(kernel, a, 1.0, options={}, expected_exception=ex) + + def test_basic89(self): + """ basic multiple return""" + def kernel(a): + if a[0, 1] > 10: + return 10. + elif a[0, 3] < 8: + return a[0, 0] + else: + return 7. + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1] - 3): + for __a in range(0, a.shape[0]): + if a[__a + 0, __b + 1] > 10: + __b0[__a, __b] = 10.0 + elif a[__a + 0, __b + 3] < 8: + __b0[__a, __b] = a[__a + 0, __b + 0] + else: + __b0[__a, __b] = 7.0 + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic90(self): + """ neighborhood, with standard_indexing and cval, multiple returns""" + def kernel(a, b): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[i, j] + b[1, 3] + res = cumul / (9.) + if res > 200.0: + return res + 1.0 + else: + return res + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, b, neighborhood): + self.check_stencil_arrays(a, b, neighborhood=neighborhood) + __retdtype = kernel(a, b) + __b0 = np.full(a.shape, 1.5, dtype=type(__retdtype)) + for __bn in range(3, a.shape[1]): + for __an in range(3, a.shape[0]): + cumul = 0 + for i in range(-3, 1): + for j in range(-3, 1): + cumul += a[__an + i, __bn + j] + b[1, 3] + res = cumul / 9.0 + if res > 200.0: + __b0[__an, __bn] = res + 1.0 + else: + __b0[__an, __bn] = res + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + b = a.copy() + nh = ((-3, 0), (-3, 0)) + expected = __kernel(a, b, nh) + self.check_against_expected(kernel, expected, a, b, + options={'neighborhood': nh, + 'standard_indexing': 'b', + 'cval': 1.5,}) + + def test_basic91(self): + """ Issue #3454, const(int) == const(int) evaluating incorrectly. """ + def kernel(a): + b = 0 + if (2 == 0): + b = 2 + return a[0, 0] + b + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(0, a.shape[1]): + for __a in range(0, a.shape[0]): + b = 0 + if 2 == 0: + b = 2 + __b0[__a, __b] = a[__a + 0, __b + 0] + b + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(10. * 20.).reshape(10, 20) + expected = __kernel(a, None) + self.check_against_expected(kernel, expected, a) + + def test_basic92(self): + """ Issue #3497, bool return type evaluating incorrectly. """ + def kernel(a): + return (a[-1, -1] ^ a[-1, 0] ^ a[-1, 1] ^ + a[0, -1] ^ a[0, 0] ^ a[0, 1] ^ + a[1, -1] ^ a[1, 0] ^ a[1, 1]) + + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(1, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + -1, __b + -1] ^ + a[__a + -1, __b + 0] ^ + a[__a + -1, __b + 1] ^ + a[__a + 0, __b + -1] ^ + a[__a + 0, __b + 0] ^ + a[__a + 0, __b + 1] ^ + a[__a + 1, __b + -1] ^ + a[__a + 1, __b + 0] ^ + a[__a + 1, __b + 1]) + return __b0 + # ---------------------------------------------------------------------- + A = np.array(np.arange(20) % 2).reshape(4, 5).astype(np.bool_) + expected = __kernel(A, None) + self.check_against_expected(kernel, expected, A) + + def test_basic93(self): + """ Issue #3497, bool return type evaluating incorrectly. """ + def kernel(a): + return (a[-1, -1] ^ a[-1, 0] ^ a[-1, 1] ^ + a[0, -1] ^ a[0, 0] ^ a[0, 1] ^ + a[1, -1] ^ a[1, 0] ^ a[1, 1]) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 1, dtype=type(__retdtype)) + for __b in range(1, a.shape[1] - 1): + for __a in range(1, a.shape[0] - 1): + __b0[__a, __b] = (a[__a + -1, __b + -1] ^ + a[__a + -1, __b + 0] ^ + a[__a + -1, __b + 1] ^ + a[__a + 0, __b + -1] ^ + a[__a + 0, __b + 0] ^ + a[__a + 0, __b + 1] ^ + a[__a + 1, __b + -1] ^ + a[__a + 1, __b + 0] ^ + a[__a + 1, __b + 1]) + return __b0 + # ---------------------------------------------------------------------- + A = np.array(np.arange(20) % 2).reshape(4, 5).astype(np.bool_) + expected = __kernel(A, None) + self.check_against_expected(kernel, expected, A, options={'cval': True}) + + def test_basic94(self): + """ Issue #3528. Support for slices. """ + def kernel(a): + return np.median(a[-1:2, -1:2]) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __bn in range(1, a.shape[1] - 1): + for __an in range(1, a.shape[0] - 1): + __b0[__an, __bn] = np.median(a[__an + -1:__an + 2, + __bn + -1:__bn + 2]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(20, dtype=np.uint32).reshape(4, 5) + nh = ((-1, 1), (-1, 1),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + @unittest.skip("not yet supported") + def test_basic95(self): + """ Slice, calculate neighborhood. """ + def kernel(a): + return np.median(a[-1:2, -3:4]) + #TODO: add check should this be implemented + + def test_basic96(self): + """ 1D slice. """ + def kernel(a): + return np.median(a[-1:2]) + # ---------------------------------------------------------------------- + # Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, 0, dtype=type(__retdtype)) + for __an in range(1, a.shape[0] - 1): + __b0[__an,] = np.median(a[__an + -1:__an + 2]) + return __b0 + # ---------------------------------------------------------------------- + a = np.arange(20, dtype=np.uint32) + nh = ((-1, 1),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh}) + + @unittest.skip("not yet supported") + def test_basic97(self): + """ 2D slice and index. """ + def kernel(a): + return np.median(a[-1:2, 3]) + #TODO: add check should this be implemented + + def test_basic98(self): + """ Test issue #7286 where the cval is a np attr/string-based numerical + constant""" + for cval in (np.nan, np.inf, -np.inf, float('inf'), -float('inf')): + def kernel(a): + return a[0, 0] + ## ----------------------------------------------------------------- + ## Autogenerated kernel + + def __kernel(a, neighborhood): + self.check_stencil_arrays(a, neighborhood=neighborhood) + __retdtype = kernel(a) + __b0 = np.full(a.shape, cval, dtype=type(__retdtype)) + for __bn in range(1, a.shape[1] - 1): + for __an in range(1, a.shape[0] - 1): + __b0[__an, __bn] = a[__an + 0, __bn + 0] + return __b0 + + ## ----------------------------------------------------------------- + a = np.arange(6.).reshape((2, 3)) + nh = ((-1, 1), (-1, 1),) + expected = __kernel(a, nh) + self.check_against_expected(kernel, expected, a, + options={'neighborhood': nh, + 'cval':cval}) + + +if __name__ == "__main__": + unittest.main() diff --git a/shared/package-files/38/381445e370cecdefc8cc36da5bebd6549d49f9950a80eb16ee02e42f2da9bdaa/RECORD b/shared/package-files/38/381445e370cecdefc8cc36da5bebd6549d49f9950a80eb16ee02e42f2da9bdaa/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f6514b54c388d3ff9bcf751e7d6d9c76fb5fb415 --- /dev/null +++ b/shared/package-files/38/381445e370cecdefc8cc36da5bebd6549d49f9950a80eb16ee02e42f2da9bdaa/RECORD @@ -0,0 +1,22 @@ +anaconda_anon_usage-0.4.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +anaconda_anon_usage-0.4.4.dist-info/LICENSE,sha256=7m8sKzw2HzaMUsdX01Gt8dgptqsbPnjf_WUiFhKAZzY,1504 +anaconda_anon_usage-0.4.4.dist-info/METADATA,sha256=0a61Vf9poLoAdtu8SEFTf7q6bXcrjgSuOv-bkVIC8Bc,622 +anaconda_anon_usage-0.4.4.dist-info/RECORD,, +anaconda_anon_usage-0.4.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anaconda_anon_usage-0.4.4.dist-info/WHEEL,sha256=iYlv5fX357PQyRT2o6tw1bN-YcKFFHKqB_LwHO5wP-g,110 +anaconda_anon_usage-0.4.4.dist-info/direct_url.json,sha256=bK1_RsRglvxZMbWOeT6mEt8_vReYngUkmtbUEkGreDU,79 +anaconda_anon_usage-0.4.4.dist-info/top_level.txt,sha256=8L-7p0_HHpqMNVCZl2mDgrLfssfZrYcCZpNiWguXpPM,20 +anaconda_anon_usage/__init__.py,sha256=t9KZdp_DIvv91kyAlbqfXkrky_63qicYujvE-nd8xlM,93 +anaconda_anon_usage/__pycache__/__init__.cpython-310.pyc,, +anaconda_anon_usage/__pycache__/_version.cpython-310.pyc,, +anaconda_anon_usage/__pycache__/install.cpython-310.pyc,, +anaconda_anon_usage/__pycache__/patch.cpython-310.pyc,, +anaconda_anon_usage/__pycache__/plugin.cpython-310.pyc,, +anaconda_anon_usage/__pycache__/tokens.cpython-310.pyc,, +anaconda_anon_usage/__pycache__/utils.cpython-310.pyc,, +anaconda_anon_usage/_version.py,sha256=xoxmX-Gf8ICpjYLmtkVKkOpk33BYJAy0E1ji84afugY,497 +anaconda_anon_usage/install.py,sha256=4G-fpa1INLRI1x9CQOmifNONirzxw11UFYskDlVFlsM,6299 +anaconda_anon_usage/patch.py,sha256=P0_USqfpdbR2G6sIidYA8ElM8-WDdu7futrKEgmelVU,3568 +anaconda_anon_usage/plugin.py,sha256=KZ3Q4M0gPCgAeNxwGuzhMXksaBf9-IR0ZlCiSd686A4,608 +anaconda_anon_usage/tokens.py,sha256=MS5IqMRgvxwQNSaOEPzq0z1gCA-G429kApqBubRuP-8,2510 +anaconda_anon_usage/utils.py,sha256=kdO2z5Wa-81Z-AgBaLD5Hi9HQTFAPO40ILLBpuJSKv0,5665 diff --git a/shared/package-files/38/3816e33ca5d9b9a1157429b083e17ea0fbaff0fac96bc11c1222684126433496/__init__.py b/shared/package-files/38/3816e33ca5d9b9a1157429b083e17ea0fbaff0fac96bc11c1222684126433496/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1669d7d9244e7f91d53c0798a6050f55ff03f4f --- /dev/null +++ b/shared/package-files/38/3816e33ca5d9b9a1157429b083e17ea0fbaff0fac96bc11c1222684126433496/__init__.py @@ -0,0 +1,9 @@ +from ._compute import ComputeTime +from ._explanation_error import ExplanationError +from ._result import BenchmarkResult +from ._sequential import SequentialMasker + +# from . import framework +# from .. import datasets + +__all__ = ["ComputeTime", "ExplanationError", "BenchmarkResult", "SequentialMasker"] diff --git a/shared/package-files/38/381730022b8cc78f7fe7ff763f51971e64f31b3ecfbca106469945af207c01a5/greater_equal.h b/shared/package-files/38/381730022b8cc78f7fe7ff763f51971e64f31b3ecfbca106469945af207c01a5/greater_equal.h new file mode 100644 index 0000000000000000000000000000000000000000..14be05f2c3f4735edb36e99fa51a7cf31bc281a0 --- /dev/null +++ b/shared/package-files/38/381730022b8cc78f7fe7ff763f51971e64f31b3ecfbca106469945af207c01a5/greater_equal.h @@ -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::greater_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & greater_equal_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other) { + return at::_ops::greater_equal_Scalar_out::call(self, other, out); +} +// aten::greater_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & greater_equal_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out) { + return at::_ops::greater_equal_Scalar_out::call(self, other, out); +} + +// aten::greater_equal.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor greater_equal(const at::Tensor & self, const at::Scalar & other) { + return at::_ops::greater_equal_Scalar::call(self, other); +} + +// aten::greater_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & greater_equal_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::greater_equal_Tensor_out::call(self, other, out); +} +// aten::greater_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & greater_equal_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::greater_equal_Tensor_out::call(self, other, out); +} + +// aten::greater_equal.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor greater_equal(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::greater_equal_Tensor::call(self, other); +} + +} diff --git a/shared/package-files/38/38178d1317541eba0f950e51ea764cb7f83477e0390c0ef255a0bf11ba5fecb9/reflection_pad1d.h b/shared/package-files/38/38178d1317541eba0f950e51ea764cb7f83477e0390c0ef255a0bf11ba5fecb9/reflection_pad1d.h new file mode 100644 index 0000000000000000000000000000000000000000..b05510c4302e9ab62d278c942afc957cd66a82e1 --- /dev/null +++ b/shared/package-files/38/38178d1317541eba0f950e51ea764cb7f83477e0390c0ef255a0bf11ba5fecb9/reflection_pad1d.h @@ -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::reflection_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & reflection_pad1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::reflection_pad1d_out::call(self, c10::fromIntArrayRefSlow(padding), out); +} +namespace symint { + template ::value>> + at::Tensor & reflection_pad1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::reflection_pad1d_out::call(self, c10::fromIntArrayRefSlow(padding), out); + } +} + +// aten::reflection_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & reflection_pad1d_outf(const at::Tensor & self, at::IntArrayRef padding, at::Tensor & out) { + return at::_ops::reflection_pad1d_out::call(self, c10::fromIntArrayRefSlow(padding), out); +} +namespace symint { + template ::value>> + at::Tensor & reflection_pad1d_outf(const at::Tensor & self, at::IntArrayRef padding, at::Tensor & out) { + return at::_ops::reflection_pad1d_out::call(self, c10::fromIntArrayRefSlow(padding), out); + } +} + +// aten::reflection_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & reflection_pad1d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::reflection_pad1d_out::call(self, padding, out); +} +namespace symint { + template ::value>> + at::Tensor & reflection_pad1d_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::reflection_pad1d_out::call(self, padding, out); + } +} + +// aten::reflection_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & reflection_pad1d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & out) { + return at::_ops::reflection_pad1d_out::call(self, padding, out); +} +namespace symint { + template ::value>> + at::Tensor & reflection_pad1d_outf(const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & out) { + return at::_ops::reflection_pad1d_out::call(self, padding, out); + } +} + +// aten::reflection_pad1d(Tensor self, SymInt[2] padding) -> Tensor +inline at::Tensor reflection_pad1d(const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::reflection_pad1d::call(self, c10::fromIntArrayRefSlow(padding)); +} +namespace symint { + template ::value>> + at::Tensor reflection_pad1d(const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::reflection_pad1d::call(self, c10::fromIntArrayRefSlow(padding)); + } +} + +// aten::reflection_pad1d(Tensor self, SymInt[2] padding) -> Tensor +inline at::Tensor reflection_pad1d_symint(const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::reflection_pad1d::call(self, padding); +} +namespace symint { + template ::value>> + at::Tensor reflection_pad1d(const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::reflection_pad1d::call(self, padding); + } +} + +} diff --git a/shared/package-files/38/38191f0a043e347be3f85e31c01a207399162df66683b88a7d7f38b613f15698/special_modified_bessel_i0_cpu_dispatch.h b/shared/package-files/38/38191f0a043e347be3f85e31c01a207399162df66683b88a7d7f38b613f15698/special_modified_bessel_i0_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6f57a5360904b20817e617360fb7c38ffba83001 --- /dev/null +++ b/shared/package-files/38/38191f0a043e347be3f85e31c01a207399162df66683b88a7d7f38b613f15698/special_modified_bessel_i0_cpu_dispatch.h @@ -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_i0(const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_i0_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_i0_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/38/381a2b296737bc248696c5ab6a3a05d7fed678d77d42d75b5f4c0e1cb7512360/_pade.py b/shared/package-files/38/381a2b296737bc248696c5ab6a3a05d7fed678d77d42d75b5f4c0e1cb7512360/_pade.py new file mode 100644 index 0000000000000000000000000000000000000000..387ef11dde5d3ace8a15324058c10fa31899c92c --- /dev/null +++ b/shared/package-files/38/381a2b296737bc248696c5ab6a3a05d7fed678d77d42d75b5f4c0e1cb7512360/_pade.py @@ -0,0 +1,67 @@ +from numpy import zeros, asarray, eye, poly1d, hstack, r_ +from scipy import linalg + +__all__ = ["pade"] + +def pade(an, m, n=None): + """ + Return Pade approximation to a polynomial as the ratio of two polynomials. + + Parameters + ---------- + an : (N,) array_like + Taylor series coefficients. + m : int + The order of the returned approximating polynomial `q`. + n : int, optional + The order of the returned approximating polynomial `p`. By default, + the order is ``len(an)-1-m``. + + Returns + ------- + p, q : Polynomial class + The Pade approximation of the polynomial defined by `an` is + ``p(x)/q(x)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import pade + >>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0] + >>> p, q = pade(e_exp, 2) + + >>> e_exp.reverse() + >>> e_poly = np.poly1d(e_exp) + + Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)`` + + >>> e_poly(1) + 2.7166666666666668 + + >>> p(1)/q(1) + 2.7179487179487181 + + """ + an = asarray(an) + if n is None: + n = len(an) - 1 - m + if n < 0: + raise ValueError("Order of q must be smaller than len(an)-1.") + if n < 0: + raise ValueError("Order of p must be greater than 0.") + N = m + n + if N > len(an)-1: + raise ValueError("Order of q+p must be smaller than len(an).") + an = an[:N+1] + Akj = eye(N+1, n+1, dtype=an.dtype) + Bkj = zeros((N+1, m), dtype=an.dtype) + for row in range(1, m+1): + Bkj[row,:row] = -(an[:row])[::-1] + for row in range(m+1, N+1): + Bkj[row,:] = -(an[row-m:row])[::-1] + C = hstack((Akj, Bkj)) + pq = linalg.solve(C, an) + p = pq[:n+1] + q = r_[1.0, pq[n+1:]] + return poly1d(p[::-1]), poly1d(q[::-1]) + diff --git a/shared/package-files/38/381a59936ddbe8f6d6874809a92ba83f53a59761ea54640e6e64fa135d911fd6/libarchive.pc b/shared/package-files/38/381a59936ddbe8f6d6874809a92ba83f53a59761ea54640e6e64fa135d911fd6/libarchive.pc new file mode 100644 index 0000000000000000000000000000000000000000..7196be38dbc771251ba067531fa4a296c5a5a643 --- /dev/null +++ b/shared/package-files/38/381a59936ddbe8f6d6874809a92ba83f53a59761ea54640e6e64fa135d911fd6/libarchive.pc @@ -0,0 +1,13 @@ +prefix=/opt/conda +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include + +Name: libarchive +Description: library that can create and read several streaming archive formats +Version: 3.6.2 +Cflags: -I${includedir} +Cflags.private: -DLIBARCHIVE_STATIC +Libs: -L${libdir} -larchive +Libs.private: -lz -lbz2 -llzma -llz4 -lzstd -lcrypto -lxml2 -lssl -L/opt/conda/lib -lxml2 -lz -llzma -licui18n -licuuc -licudata -lm +Requires.private: diff --git a/shared/package-files/38/381b39e6de6018a48f853b2719a7e2e54aacae39aad5c2a97eec162d4051f14a/test_business_year.py b/shared/package-files/38/381b39e6de6018a48f853b2719a7e2e54aacae39aad5c2a97eec162d4051f14a/test_business_year.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7a1025cc19c9c1c966b9448ceffdb12dcd8159 --- /dev/null +++ b/shared/package-files/38/381b39e6de6018a48f853b2719a7e2e54aacae39aad5c2a97eec162d4051f14a/test_business_year.py @@ -0,0 +1,215 @@ +""" +Tests for the following offsets: +- BYearBegin +- BYearEnd +""" +from __future__ import annotations + +from datetime import datetime + +import pytest + +from pandas.tests.tseries.offsets.common import ( + assert_is_on_offset, + assert_offset_equal, +) + +from pandas.tseries.offsets import ( + BYearBegin, + BYearEnd, +) + + +class TestBYearBegin: + def test_misspecified(self): + msg = "Month must go from 1 to 12" + with pytest.raises(ValueError, match=msg): + BYearBegin(month=13) + with pytest.raises(ValueError, match=msg): + BYearEnd(month=13) + + offset_cases = [] + offset_cases.append( + ( + BYearBegin(), + { + datetime(2008, 1, 1): datetime(2009, 1, 1), + datetime(2008, 6, 30): datetime(2009, 1, 1), + datetime(2008, 12, 31): datetime(2009, 1, 1), + datetime(2011, 1, 1): datetime(2011, 1, 3), + datetime(2011, 1, 3): datetime(2012, 1, 2), + datetime(2005, 12, 30): datetime(2006, 1, 2), + datetime(2005, 12, 31): datetime(2006, 1, 2), + }, + ) + ) + + offset_cases.append( + ( + BYearBegin(0), + { + datetime(2008, 1, 1): datetime(2008, 1, 1), + datetime(2008, 6, 30): datetime(2009, 1, 1), + datetime(2008, 12, 31): datetime(2009, 1, 1), + datetime(2005, 12, 30): datetime(2006, 1, 2), + datetime(2005, 12, 31): datetime(2006, 1, 2), + }, + ) + ) + + offset_cases.append( + ( + BYearBegin(-1), + { + datetime(2007, 1, 1): datetime(2006, 1, 2), + datetime(2009, 1, 4): datetime(2009, 1, 1), + datetime(2009, 1, 1): datetime(2008, 1, 1), + datetime(2008, 6, 30): datetime(2008, 1, 1), + datetime(2008, 12, 31): datetime(2008, 1, 1), + datetime(2006, 12, 29): datetime(2006, 1, 2), + datetime(2006, 12, 30): datetime(2006, 1, 2), + datetime(2006, 1, 1): datetime(2005, 1, 3), + }, + ) + ) + + offset_cases.append( + ( + BYearBegin(-2), + { + datetime(2007, 1, 1): datetime(2005, 1, 3), + datetime(2007, 6, 30): datetime(2006, 1, 2), + datetime(2008, 12, 31): datetime(2007, 1, 1), + }, + ) + ) + + @pytest.mark.parametrize("case", offset_cases) + def test_offset(self, case): + offset, cases = case + for base, expected in cases.items(): + assert_offset_equal(offset, base, expected) + + +class TestBYearEnd: + offset_cases = [] + offset_cases.append( + ( + BYearEnd(), + { + datetime(2008, 1, 1): datetime(2008, 12, 31), + datetime(2008, 6, 30): datetime(2008, 12, 31), + datetime(2008, 12, 31): datetime(2009, 12, 31), + datetime(2005, 12, 30): datetime(2006, 12, 29), + datetime(2005, 12, 31): datetime(2006, 12, 29), + }, + ) + ) + + offset_cases.append( + ( + BYearEnd(0), + { + datetime(2008, 1, 1): datetime(2008, 12, 31), + datetime(2008, 6, 30): datetime(2008, 12, 31), + datetime(2008, 12, 31): datetime(2008, 12, 31), + datetime(2005, 12, 31): datetime(2006, 12, 29), + }, + ) + ) + + offset_cases.append( + ( + BYearEnd(-1), + { + datetime(2007, 1, 1): datetime(2006, 12, 29), + datetime(2008, 6, 30): datetime(2007, 12, 31), + datetime(2008, 12, 31): datetime(2007, 12, 31), + datetime(2006, 12, 29): datetime(2005, 12, 30), + datetime(2006, 12, 30): datetime(2006, 12, 29), + datetime(2007, 1, 1): datetime(2006, 12, 29), + }, + ) + ) + + offset_cases.append( + ( + BYearEnd(-2), + { + datetime(2007, 1, 1): datetime(2005, 12, 30), + datetime(2008, 6, 30): datetime(2006, 12, 29), + datetime(2008, 12, 31): datetime(2006, 12, 29), + }, + ) + ) + + @pytest.mark.parametrize("case", offset_cases) + def test_offset(self, case): + offset, cases = case + for base, expected in cases.items(): + assert_offset_equal(offset, base, expected) + + on_offset_cases = [ + (BYearEnd(), datetime(2007, 12, 31), True), + (BYearEnd(), datetime(2008, 1, 1), False), + (BYearEnd(), datetime(2006, 12, 31), False), + (BYearEnd(), datetime(2006, 12, 29), True), + ] + + @pytest.mark.parametrize("case", on_offset_cases) + def test_is_on_offset(self, case): + offset, dt, expected = case + assert_is_on_offset(offset, dt, expected) + + +class TestBYearEndLagged: + def test_bad_month_fail(self): + msg = "Month must go from 1 to 12" + with pytest.raises(ValueError, match=msg): + BYearEnd(month=13) + with pytest.raises(ValueError, match=msg): + BYearEnd(month=0) + + offset_cases = [] + offset_cases.append( + ( + BYearEnd(month=6), + { + datetime(2008, 1, 1): datetime(2008, 6, 30), + datetime(2007, 6, 30): datetime(2008, 6, 30), + }, + ) + ) + + offset_cases.append( + ( + BYearEnd(n=-1, month=6), + { + datetime(2008, 1, 1): datetime(2007, 6, 29), + datetime(2007, 6, 30): datetime(2007, 6, 29), + }, + ) + ) + + @pytest.mark.parametrize("case", offset_cases) + def test_offset(self, case): + offset, cases = case + for base, expected in cases.items(): + assert_offset_equal(offset, base, expected) + + def test_roll(self): + offset = BYearEnd(month=6) + date = datetime(2009, 11, 30) + + assert offset.rollforward(date) == datetime(2010, 6, 30) + assert offset.rollback(date) == datetime(2009, 6, 30) + + on_offset_cases = [ + (BYearEnd(month=2), datetime(2007, 2, 28), True), + (BYearEnd(month=6), datetime(2007, 6, 30), False), + ] + + @pytest.mark.parametrize("case", on_offset_cases) + def test_is_on_offset(self, case): + offset, dt, expected = case + assert_is_on_offset(offset, dt, expected) diff --git a/shared/package-files/38/381f3642007a4b0b6cc53e2de39dce5528fe07befb5eb1c610638c80c0f55c67/testmatrix_6.5.1_GLNX86.mat b/shared/package-files/38/381f3642007a4b0b6cc53e2de39dce5528fe07befb5eb1c610638c80c0f55c67/testmatrix_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..a8735e9a23558ce86a528ceafa8f3475b053e43b Binary files /dev/null and b/shared/package-files/38/381f3642007a4b0b6cc53e2de39dce5528fe07befb5eb1c610638c80c0f55c67/testmatrix_6.5.1_GLNX86.mat differ diff --git a/shared/package-files/38/38218746c62bcc98ab99e70512bc73b9c647dd88234f9b3754e659d99d8ac00d/s3.py b/shared/package-files/38/38218746c62bcc98ab99e70512bc73b9c647dd88234f9b3754e659d99d8ac00d/s3.py new file mode 100644 index 0000000000000000000000000000000000000000..8a7b67bc5e2b159752513ef8ad2e5cd73481beeb --- /dev/null +++ b/shared/package-files/38/38218746c62bcc98ab99e70512bc73b9c647dd88234f9b3754e659d99d8ac00d/s3.py @@ -0,0 +1,130 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import json +from logging import LoggerAdapter, getLogger +from tempfile import SpooledTemporaryFile + +have_boto3 = have_boto = False +try: + import boto3 + + have_boto3 = True +except ImportError: + try: + import boto + + have_boto = True + except ImportError: + pass + +from ....common.compat import ensure_binary +from ....common.url import url_to_s3_info +from .. import BaseAdapter, CaseInsensitiveDict, Response + +log = getLogger(__name__) +stderrlog = LoggerAdapter(getLogger("conda.stderrlog"), extra=dict(terminator="\n")) + + +class S3Adapter(BaseAdapter): + def __init__(self): + super().__init__() + + def send( + self, request, stream=None, timeout=None, verify=None, cert=None, proxies=None + ): + resp = Response() + resp.status_code = 200 + resp.url = request.url + if have_boto3: + return self._send_boto3(boto3, resp, request) + elif have_boto: + return self._send_boto(boto, resp, request) + else: + stderrlog.info( + "\nError: boto3 is required for S3 channels. " + "Please install with `conda install boto3`\n" + "Make sure to run `conda deactivate` if you " + "are in a conda environment.\n" + ) + resp.status_code = 404 + return resp + + def close(self): + pass + + def _send_boto3(self, boto3, resp, request): + from botocore.exceptions import BotoCoreError, ClientError + + bucket_name, key_string = url_to_s3_info(request.url) + # https://github.com/conda/conda/issues/8993 + # creating a separate boto3 session to make this thread safe + session = boto3.session.Session() + # create a resource client using this thread's session object + s3 = session.resource("s3") + # finally get the S3 object + key = s3.Object(bucket_name, key_string[1:]) + + try: + response = key.get() + except (BotoCoreError, ClientError) as e: + resp.status_code = 404 + message = { + "error": "error downloading file from s3", + "path": request.url, + "exception": repr(e), + } + resp.raw = self._write_tempfile( + lambda x: x.write(ensure_binary(json.dumps(message))) + ) + resp.close = resp.raw.close + return resp + + key_headers = response["ResponseMetadata"]["HTTPHeaders"] + resp.headers = CaseInsensitiveDict( + { + "Content-Type": key_headers.get("content-type", "text/plain"), + "Content-Length": key_headers["content-length"], + "Last-Modified": key_headers["last-modified"], + } + ) + + resp.raw = self._write_tempfile(key.download_fileobj) + resp.close = resp.raw.close + + return resp + + def _send_boto(self, boto, resp, request): + conn = boto.connect_s3() + + bucket_name, key_string = url_to_s3_info(request.url) + bucket = conn.get_bucket(bucket_name, validate=False) + try: + key = bucket.get_key(key_string) + except boto.exception.S3ResponseError as exc: + resp.status_code = 404 + resp.raw = exc + return resp + + if key and key.exists: + modified = key.last_modified + content_type = key.content_type or "text/plain" + resp.headers = CaseInsensitiveDict( + { + "Content-Type": content_type, + "Content-Length": key.size, + "Last-Modified": modified, + } + ) + + resp.raw = self._write_tempfile(key.get_contents_to_file) + resp.close = resp.raw.close + else: + resp.status_code = 404 + + return resp + + def _write_tempfile(self, writer_callable): + fh = SpooledTemporaryFile() + writer_callable(fh) + fh.seek(0) + return fh diff --git a/shared/package-files/38/382e74dfdd8f949dd29a57fc19c576a0411c4595b01058e1a1641a0f5202554b/builder.py b/shared/package-files/38/382e74dfdd8f949dd29a57fc19c576a0411c4595b01058e1a1641a0f5202554b/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a5365da72b01855177025b83492ded0bbb504bbc --- /dev/null +++ b/shared/package-files/38/382e74dfdd8f949dd29a57fc19c576a0411c4595b01058e1a1641a0f5202554b/builder.py @@ -0,0 +1,3495 @@ +from __future__ import annotations + +from collections import namedtuple, OrderedDict +import itertools +from typing import Dict, Union +from fontTools.misc.fixedTools import fixedToFloat +from fontTools.misc.roundTools import otRound +from fontTools import ttLib +from fontTools.ttLib.tables import otTables as ot +from fontTools.ttLib.tables.otBase import ( + ValueRecord, + valueRecordFormatDict, + OTLOffsetOverflowError, + OTTableWriter, +) +from fontTools.ttLib.ttFont import TTFont +from fontTools.feaLib.ast import STATNameStatement +from fontTools.otlLib.optimize.gpos import ( + _compression_level_from_env, + compact_lookup, +) +from fontTools.otlLib.error import OpenTypeLibError +from fontTools.misc.loggingTools import deprecateFunction +from functools import reduce +import logging +import copy + +log = logging.getLogger(__name__) + + +def buildCoverage(glyphs, glyphMap): + """Builds a coverage table. + + Coverage tables (as defined in the `OpenType spec `__) + are used in all OpenType Layout lookups apart from the Extension type, and + define the glyphs involved in a layout subtable. This allows shaping engines + to compare the glyph stream with the coverage table and quickly determine + whether a subtable should be involved in a shaping operation. + + This function takes a list of glyphs and a glyphname-to-ID map, and + returns a ``Coverage`` object representing the coverage table. + + Example:: + + glyphMap = font.getReverseGlyphMap() + glyphs = [ "A", "B", "C" ] + coverage = buildCoverage(glyphs, glyphMap) + + Args: + glyphs: a sequence of glyph names. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + An ``otTables.Coverage`` object (empty if no glyphs supplied). + """ + # Per the OpenType spec: "For cases in which subtable offset fields are not + # documented as permitting NULL values, font compilers must include a subtable + # of the indicated format, even if it is a header stub without further data + # (for example, a coverage table with no glyph IDs)." + # https://github.com/fonttools/fonttools/issues/4003 + self = ot.Coverage() + if glyphs: + try: + self.glyphs = sorted(set(glyphs), key=glyphMap.__getitem__) + except KeyError as e: + raise ValueError(f"Could not find glyph {e} in font") from e + else: + self.glyphs = [] + return self + + +LOOKUP_FLAG_RIGHT_TO_LEFT = 0x0001 +LOOKUP_FLAG_IGNORE_BASE_GLYPHS = 0x0002 +LOOKUP_FLAG_IGNORE_LIGATURES = 0x0004 +LOOKUP_FLAG_IGNORE_MARKS = 0x0008 +LOOKUP_FLAG_USE_MARK_FILTERING_SET = 0x0010 + + +def buildLookup(subtables, flags=0, markFilterSet=None, table=None, extension=False): + """Turns a collection of rules into a lookup. + + A Lookup (as defined in the `OpenType Spec `__) + wraps the individual rules in a layout operation (substitution or + positioning) in a data structure expressing their overall lookup type - + for example, single substitution, mark-to-base attachment, and so on - + as well as the lookup flags and any mark filtering sets. You may import + the following constants to express lookup flags: + + - ``LOOKUP_FLAG_RIGHT_TO_LEFT`` + - ``LOOKUP_FLAG_IGNORE_BASE_GLYPHS`` + - ``LOOKUP_FLAG_IGNORE_LIGATURES`` + - ``LOOKUP_FLAG_IGNORE_MARKS`` + - ``LOOKUP_FLAG_USE_MARK_FILTERING_SET`` + + Args: + subtables: A list of layout subtable objects (e.g. + ``MultipleSubst``, ``PairPos``, etc.) or ``None``. + flags (int): This lookup's flags. + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + table (str): The name of the table this lookup belongs to, e.g. "GPOS" or "GSUB". + extension (bool): ``True`` if this is an extension lookup, ``False`` otherwise. + + Returns: + An ``otTables.Lookup`` object or ``None`` if there are no subtables + supplied. + """ + if subtables is None: + return None + subtables = [st for st in subtables if st is not None] + if not subtables: + return None + assert all( + t.LookupType == subtables[0].LookupType for t in subtables + ), "all subtables must have the same LookupType; got %s" % repr( + [t.LookupType for t in subtables] + ) + + if extension: + assert table in ("GPOS", "GSUB") + lookupType = 7 if table == "GSUB" else 9 + extSubTableClass = ot.lookupTypes[table][lookupType] + for i, st in enumerate(subtables): + subtables[i] = extSubTableClass() + subtables[i].Format = 1 + subtables[i].ExtSubTable = st + subtables[i].ExtensionLookupType = st.LookupType + else: + lookupType = subtables[0].LookupType + + self = ot.Lookup() + self.LookupType = lookupType + self.LookupFlag = flags + self.SubTable = subtables + self.SubTableCount = len(self.SubTable) + if markFilterSet is not None: + self.LookupFlag |= LOOKUP_FLAG_USE_MARK_FILTERING_SET + assert isinstance(markFilterSet, int), markFilterSet + self.MarkFilteringSet = markFilterSet + else: + assert (self.LookupFlag & LOOKUP_FLAG_USE_MARK_FILTERING_SET) == 0, ( + "if markFilterSet is None, flags must not set " + "LOOKUP_FLAG_USE_MARK_FILTERING_SET; flags=0x%04x" % flags + ) + return self + + +class LookupBuilder(object): + SUBTABLE_BREAK_ = "SUBTABLE_BREAK" + + def __init__(self, font, location, table, lookup_type, extension=False): + self.font = font + self.glyphMap = font.getReverseGlyphMap() + self.location = location + self.table, self.lookup_type = table, lookup_type + self.lookupflag = 0 + self.markFilterSet = None + self.lookup_index = None # assigned when making final tables + self.extension = extension + assert table in ("GPOS", "GSUB") + + def equals(self, other): + return ( + isinstance(other, self.__class__) + and self.table == other.table + and self.lookupflag == other.lookupflag + and self.markFilterSet == other.markFilterSet + and self.extension == other.extension + ) + + def promote_lookup_type(self, is_named_lookup): + return [self] + + def inferGlyphClasses(self): + """Infers glyph glasses for the GDEF table, such as {"cedilla":3}.""" + return {} + + def getAlternateGlyphs(self): + """Helper for building 'aalt' features.""" + return {} + + def buildLookup_(self, subtables): + return buildLookup( + subtables, + self.lookupflag, + self.markFilterSet, + self.table, + self.extension, + ) + + def buildMarkClasses_(self, marks): + """{"cedilla": ("BOTTOM", ast.Anchor), ...} --> {"BOTTOM":0, "TOP":1} + + Helper for MarkBasePostBuilder, MarkLigPosBuilder, and + MarkMarkPosBuilder. Seems to return the same numeric IDs + for mark classes as the AFDKO makeotf tool. + """ + ids = {} + for mark in sorted(marks.keys(), key=self.font.getGlyphID): + markClassName, _markAnchor = marks[mark] + if markClassName not in ids: + ids[markClassName] = len(ids) + return ids + + def setBacktrackCoverage_(self, prefix, subtable): + subtable.BacktrackGlyphCount = len(prefix) + subtable.BacktrackCoverage = [] + for p in reversed(prefix): + coverage = buildCoverage(p, self.glyphMap) + subtable.BacktrackCoverage.append(coverage) + + def setLookAheadCoverage_(self, suffix, subtable): + subtable.LookAheadGlyphCount = len(suffix) + subtable.LookAheadCoverage = [] + for s in suffix: + coverage = buildCoverage(s, self.glyphMap) + subtable.LookAheadCoverage.append(coverage) + + def setInputCoverage_(self, glyphs, subtable): + subtable.InputGlyphCount = len(glyphs) + subtable.InputCoverage = [] + for g in glyphs: + coverage = buildCoverage(g, self.glyphMap) + subtable.InputCoverage.append(coverage) + + def setCoverage_(self, glyphs, subtable): + subtable.GlyphCount = len(glyphs) + subtable.Coverage = [] + for g in glyphs: + coverage = buildCoverage(g, self.glyphMap) + subtable.Coverage.append(coverage) + + def build_subst_subtables(self, mapping, klass): + substitutions = [{}] + for key in mapping: + if key[0] == self.SUBTABLE_BREAK_: + substitutions.append({}) + else: + substitutions[-1][key] = mapping[key] + subtables = [klass(s) for s in substitutions] + return subtables + + def add_subtable_break(self, location): + """Add an explicit subtable break. + + Args: + location: A string or tuple representing the location in the + original source which produced this break, or ``None`` if + no location is provided. + """ + log.warning( + OpenTypeLibError( + 'unsupported "subtable" statement for lookup type', location + ) + ) + + def can_add_mapping(self, _mapping) -> bool: + # used by AnySubstBuilder, below + return True + + +class AlternateSubstBuilder(LookupBuilder): + """Builds an Alternate Substitution (GSUB3) lookup. + + Users are expected to manually add alternate glyph substitutions to + the ``alternates`` attribute after the object has been initialized, + e.g.:: + + builder.alternates["A"] = ["A.alt1", "A.alt2"] + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + alternates: An ordered dictionary of alternates, mapping glyph names + to a list of names of alternates. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GSUB", 3) + self.alternates = OrderedDict() + + def equals(self, other): + return LookupBuilder.equals(self, other) and self.alternates == other.alternates + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the alternate + substitution lookup. + """ + subtables = self.build_subst_subtables( + self.alternates, buildAlternateSubstSubtable + ) + return self.buildLookup_(subtables) + + def getAlternateGlyphs(self): + return self.alternates + + def add_subtable_break(self, location): + self.alternates[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_ + + +class ChainContextualRule( + namedtuple("ChainContextualRule", ["prefix", "glyphs", "suffix", "lookups"]) +): + @property + def is_subtable_break(self): + return self.prefix == LookupBuilder.SUBTABLE_BREAK_ + + +class ChainContextualRuleset: + def __init__(self): + self.rules = [] + + def addRule(self, rule): + self.rules.append(rule) + + @property + def hasPrefixOrSuffix(self): + # Do we have any prefixes/suffixes? If this is False for all + # rulesets, we can express the whole lookup as GPOS5/GSUB7. + for rule in self.rules: + if len(rule.prefix) > 0 or len(rule.suffix) > 0: + return True + return False + + @property + def hasAnyGlyphClasses(self): + # Do we use glyph classes anywhere in the rules? If this is False + # we can express this subtable as a Format 1. + for rule in self.rules: + for coverage in (rule.prefix, rule.glyphs, rule.suffix): + if any(len(x) > 1 for x in coverage): + return True + return False + + def format2ClassDefs(self): + PREFIX, GLYPHS, SUFFIX = 0, 1, 2 + classDefBuilders = [] + for ix in [PREFIX, GLYPHS, SUFFIX]: + context = [] + for r in self.rules: + context.append(r[ix]) + classes = self._classBuilderForContext(context) + if not classes: + return None + classDefBuilders.append(classes) + return classDefBuilders + + def _classBuilderForContext(self, context): + classdefbuilder = ClassDefBuilder(useClass0=False) + for position in context: + for glyphset in position: + glyphs = set(glyphset) + if not classdefbuilder.canAdd(glyphs): + return None + classdefbuilder.add(glyphs) + return classdefbuilder + + +class ChainContextualBuilder(LookupBuilder): + def equals(self, other): + return LookupBuilder.equals(self, other) and self.rules == other.rules + + def rulesets(self): + # Return a list of ChainContextRuleset objects, taking explicit + # subtable breaks into account + ruleset = [ChainContextualRuleset()] + for rule in self.rules: + if rule.is_subtable_break: + ruleset.append(ChainContextualRuleset()) + continue + ruleset[-1].addRule(rule) + # Squish any empty subtables + return [x for x in ruleset if len(x.rules) > 0] + + def getCompiledSize_(self, subtables): + if not subtables: + return 0 + # We need to make a copy here because compiling + # modifies the subtable (finalizing formats etc.) + table = self.buildLookup_(copy.deepcopy(subtables)) + w = OTTableWriter(tableTag=self.table) + # This standalone lookup has no LookupList parent to set its metadata. + # Overflow reporting still needs a lookup name and index. + w.name = "Lookup" + w.repeatIndex = 0 + table.compile(w, self.font) + size = len(w.getAllData()) + return size + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the chained + contextual positioning lookup. + """ + subtables = [] + + rulesets = self.rulesets() + chaining = any(ruleset.hasPrefixOrSuffix for ruleset in rulesets) + + # https://github.com/fonttools/fonttools/issues/2539 + # + # Unfortunately, as of 2022-03-07, Apple's CoreText renderer does not + # correctly process GPOS7 lookups, so for now we force contextual + # positioning lookups to be chaining (GPOS8). + # + # This seems to be fixed as of macOS 13.2, but we keep disabling this + # for now until we are no longer concerned about old macOS versions. + # But we allow people to opt-out of this with the config key below. + write_gpos7 = self.font.cfg.get("fontTools.otlLib.builder:WRITE_GPOS7") + # horrible separation of concerns breach + if not write_gpos7 and self.subtable_type == "Pos": + chaining = True + + pending_rulesets = list(reversed(rulesets)) + while pending_rulesets: + ruleset = pending_rulesets.pop() + # Determine format strategy. We try to build formats 1, 2 and 3 + # subtables and then work out which is best. candidates list holds + # the subtables in each format for this ruleset (including a dummy + # "format 0" to make the addressing match the format numbers). + + # We can always build a format 3 lookup by accumulating each of + # the rules into a list, so start with that. + candidates = [None, None, None, []] + for rule in ruleset.rules: + candidates[3].append(self.buildFormat3Subtable(rule, chaining)) + + # Can we express the whole ruleset as a format 2 subtable? + classdefs = ruleset.format2ClassDefs() + if classdefs: + candidates[2] = [ + self.buildFormat2Subtable(ruleset, classdefs, chaining) + ] + + if not ruleset.hasAnyGlyphClasses: + candidates[1] = [self.buildFormat1Subtable(ruleset, chaining)] + + candidates_by_size = [] + for i in [1, 2, 3]: + if candidates[i]: + try: + size = self.getCompiledSize_(candidates[i]) + except OTLOffsetOverflowError as e: + log.warning( + "Contextual format %i at %s overflowed (%s)" + % (i, str(self.location), e) + ) + else: + candidates_by_size.append((size, candidates[i])) + + if not candidates_by_size: + if len(ruleset.rules) <= 1: + raise OpenTypeLibError("All candidates overflowed", self.location) + # Retry smaller consecutive groups in the same lookup. Keeping + # their order preserves the first-matching-rule semantics. + midpoint = len(ruleset.rules) // 2 + for rules in (ruleset.rules[midpoint:], ruleset.rules[:midpoint]): + part = ChainContextualRuleset() + part.rules = rules + pending_rulesets.append(part) + continue + + _min_size, winner = min(candidates_by_size, key=lambda x: x[0]) + subtables.extend(winner) + + # If we are not chaining, lookup type will be automatically fixed by + # buildLookup_ + return self.buildLookup_(subtables) + + def buildFormat1Subtable(self, ruleset, chaining=True): + st = self.newSubtable_(chaining=chaining) + st.Format = 1 + st.populateDefaults() + coverage = set() + rulesetsByFirstGlyph = {} + ruleAttr = self.ruleAttr_(format=1, chaining=chaining) + + for rule in ruleset.rules: + ruleAsSubtable = self.newRule_(format=1, chaining=chaining) + + if chaining: + ruleAsSubtable.BacktrackGlyphCount = len(rule.prefix) + ruleAsSubtable.LookAheadGlyphCount = len(rule.suffix) + ruleAsSubtable.Backtrack = [list(x)[0] for x in reversed(rule.prefix)] + ruleAsSubtable.LookAhead = [list(x)[0] for x in rule.suffix] + + ruleAsSubtable.InputGlyphCount = len(rule.glyphs) + else: + ruleAsSubtable.GlyphCount = len(rule.glyphs) + + ruleAsSubtable.Input = [list(x)[0] for x in rule.glyphs[1:]] + + self.buildLookupList(rule, ruleAsSubtable) + + firstGlyph = list(rule.glyphs[0])[0] + if firstGlyph not in rulesetsByFirstGlyph: + coverage.add(firstGlyph) + rulesetsByFirstGlyph[firstGlyph] = [] + rulesetsByFirstGlyph[firstGlyph].append(ruleAsSubtable) + + st.Coverage = buildCoverage(coverage, self.glyphMap) + ruleSets = [] + for g in st.Coverage.glyphs: + ruleSet = self.newRuleSet_(format=1, chaining=chaining) + setattr(ruleSet, ruleAttr, rulesetsByFirstGlyph[g]) + setattr(ruleSet, f"{ruleAttr}Count", len(rulesetsByFirstGlyph[g])) + ruleSets.append(ruleSet) + + setattr(st, self.ruleSetAttr_(format=1, chaining=chaining), ruleSets) + setattr( + st, self.ruleSetAttr_(format=1, chaining=chaining) + "Count", len(ruleSets) + ) + + return st + + def buildFormat2Subtable(self, ruleset, classdefs, chaining=True): + st = self.newSubtable_(chaining=chaining) + st.Format = 2 + st.populateDefaults() + + if chaining: + ( + st.BacktrackClassDef, + st.InputClassDef, + st.LookAheadClassDef, + ) = [c.build() for c in classdefs] + else: + st.ClassDef = classdefs[1].build() + + inClasses = classdefs[1].classes() + + classSets = [] + for _ in inClasses: + classSet = self.newRuleSet_(format=2, chaining=chaining) + classSets.append(classSet) + + coverage = set() + classRuleAttr = self.ruleAttr_(format=2, chaining=chaining) + + for rule in ruleset.rules: + ruleAsSubtable = self.newRule_(format=2, chaining=chaining) + if chaining: + ruleAsSubtable.BacktrackGlyphCount = len(rule.prefix) + ruleAsSubtable.LookAheadGlyphCount = len(rule.suffix) + # The glyphs in the rule may be list, tuple, odict_keys... + # Order is not important anyway because they are guaranteed + # to be members of the same class. + ruleAsSubtable.Backtrack = [ + st.BacktrackClassDef.classDefs[list(x)[0]] + for x in reversed(rule.prefix) + ] + ruleAsSubtable.LookAhead = [ + st.LookAheadClassDef.classDefs[list(x)[0]] for x in rule.suffix + ] + + ruleAsSubtable.InputGlyphCount = len(rule.glyphs) + ruleAsSubtable.Input = [ + st.InputClassDef.classDefs[list(x)[0]] for x in rule.glyphs[1:] + ] + setForThisRule = classSets[ + st.InputClassDef.classDefs[list(rule.glyphs[0])[0]] + ] + else: + ruleAsSubtable.GlyphCount = len(rule.glyphs) + ruleAsSubtable.Class = [ # The spec calls this InputSequence + st.ClassDef.classDefs[list(x)[0]] for x in rule.glyphs[1:] + ] + setForThisRule = classSets[ + st.ClassDef.classDefs[list(rule.glyphs[0])[0]] + ] + + self.buildLookupList(rule, ruleAsSubtable) + coverage |= set(rule.glyphs[0]) + + getattr(setForThisRule, classRuleAttr).append(ruleAsSubtable) + setattr( + setForThisRule, + f"{classRuleAttr}Count", + getattr(setForThisRule, f"{classRuleAttr}Count") + 1, + ) + for i, classSet in enumerate(classSets): + if not getattr(classSet, classRuleAttr): + # class sets can be null so replace nop sets with None + classSets[i] = None + setattr(st, self.ruleSetAttr_(format=2, chaining=chaining), classSets) + setattr( + st, self.ruleSetAttr_(format=2, chaining=chaining) + "Count", len(classSets) + ) + st.Coverage = buildCoverage(coverage, self.glyphMap) + return st + + def buildFormat3Subtable(self, rule, chaining=True): + st = self.newSubtable_(chaining=chaining) + st.Format = 3 + if chaining: + self.setBacktrackCoverage_(rule.prefix, st) + self.setLookAheadCoverage_(rule.suffix, st) + self.setInputCoverage_(rule.glyphs, st) + else: + self.setCoverage_(rule.glyphs, st) + self.buildLookupList(rule, st) + return st + + def buildLookupList(self, rule, st): + for sequenceIndex, lookupList in enumerate(rule.lookups): + if lookupList is not None: + if not isinstance(lookupList, list): + # Can happen with synthesised lookups + lookupList = [lookupList] + for l in lookupList: + if l.lookup_index is None: + if isinstance(self, ChainContextPosBuilder): + other = "substitution" + else: + other = "positioning" + raise OpenTypeLibError( + "Missing index of the specified " + f"lookup, might be a {other} lookup", + self.location, + ) + rec = self.newLookupRecord_(st) + rec.SequenceIndex = sequenceIndex + rec.LookupListIndex = l.lookup_index + + def add_subtable_break(self, location): + self.rules.append( + ChainContextualRule( + self.SUBTABLE_BREAK_, + self.SUBTABLE_BREAK_, + self.SUBTABLE_BREAK_, + [self.SUBTABLE_BREAK_], + ) + ) + + def newSubtable_(self, chaining=True): + subtablename = f"Context{self.subtable_type}" + if chaining: + subtablename = "Chain" + subtablename + st = getattr(ot, subtablename)() # ot.ChainContextPos()/ot.ChainSubst()/etc. + setattr(st, f"{self.subtable_type}Count", 0) + setattr(st, f"{self.subtable_type}LookupRecord", []) + return st + + # Format 1 and format 2 GSUB5/GSUB6/GPOS7/GPOS8 rulesets and rules form a family: + # + # format 1 ruleset format 1 rule format 2 ruleset format 2 rule + # GSUB5 SubRuleSet SubRule SubClassSet SubClassRule + # GSUB6 ChainSubRuleSet ChainSubRule ChainSubClassSet ChainSubClassRule + # GPOS7 PosRuleSet PosRule PosClassSet PosClassRule + # GPOS8 ChainPosRuleSet ChainPosRule ChainPosClassSet ChainPosClassRule + # + # The following functions generate the attribute names and subtables according + # to this naming convention. + def ruleSetAttr_(self, format=1, chaining=True): + if format == 1: + formatType = "Rule" + elif format == 2: + formatType = "Class" + else: + raise AssertionError(formatType) + subtablename = f"{self.subtable_type[0:3]}{formatType}Set" # Sub, not Subst. + if chaining: + subtablename = "Chain" + subtablename + return subtablename + + def ruleAttr_(self, format=1, chaining=True): + if format == 1: + formatType = "" + elif format == 2: + formatType = "Class" + else: + raise AssertionError(formatType) + subtablename = f"{self.subtable_type[0:3]}{formatType}Rule" # Sub, not Subst. + if chaining: + subtablename = "Chain" + subtablename + return subtablename + + def newRuleSet_(self, format=1, chaining=True): + st = getattr( + ot, self.ruleSetAttr_(format, chaining) + )() # ot.ChainPosRuleSet()/ot.SubRuleSet()/etc. + st.populateDefaults() + return st + + def newRule_(self, format=1, chaining=True): + st = getattr( + ot, self.ruleAttr_(format, chaining) + )() # ot.ChainPosClassRule()/ot.SubClassRule()/etc. + st.populateDefaults() + return st + + def attachSubtableWithCount_( + self, st, subtable_name, count_name, existing=None, index=None, chaining=False + ): + if chaining: + subtable_name = "Chain" + subtable_name + count_name = "Chain" + count_name + + if not hasattr(st, count_name): + setattr(st, count_name, 0) + setattr(st, subtable_name, []) + + if existing: + new_subtable = existing + else: + # Create a new, empty subtable from otTables + new_subtable = getattr(ot, subtable_name)() + + setattr(st, count_name, getattr(st, count_name) + 1) + + if index: + getattr(st, subtable_name).insert(index, new_subtable) + else: + getattr(st, subtable_name).append(new_subtable) + + return new_subtable + + def newLookupRecord_(self, st): + return self.attachSubtableWithCount_( + st, + f"{self.subtable_type}LookupRecord", + f"{self.subtable_type}Count", + chaining=False, + ) # Oddly, it isn't ChainSubstLookupRecord + + +class ChainContextPosBuilder(ChainContextualBuilder): + """Builds a Chained Contextual Positioning (GPOS8) lookup. + + Users are expected to manually add rules to the ``rules`` attribute after + the object has been initialized, e.g.:: + + # pos [A B] [C D] x' lookup lu1 y' z' lookup lu2 E; + + prefix = [ ["A", "B"], ["C", "D"] ] + suffix = [ ["E"] ] + glyphs = [ ["x"], ["y"], ["z"] ] + lookups = [ [lu1], None, [lu2] ] + builder.rules.append( (prefix, glyphs, suffix, lookups) ) + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + rules: A list of tuples representing the rules in this lookup. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GPOS", 8) + self.rules = [] + self.subtable_type = "Pos" + + def find_chainable_single_pos(self, lookups, glyphs, value): + """Helper for add_single_pos_chained_()""" + res = None + for lookup in lookups[::-1]: + if lookup == self.SUBTABLE_BREAK_: + return res + if isinstance(lookup, SinglePosBuilder) and all( + lookup.can_add(glyph, value) for glyph in glyphs + ): + res = lookup + return res + + +class ChainContextSubstBuilder(ChainContextualBuilder): + """Builds a Chained Contextual Substitution (GSUB6) lookup. + + Users are expected to manually add rules to the ``rules`` attribute after + the object has been initialized, e.g.:: + + # sub [A B] [C D] x' lookup lu1 y' z' lookup lu2 E; + + prefix = [ ["A", "B"], ["C", "D"] ] + suffix = [ ["E"] ] + glyphs = [ ["x"], ["y"], ["z"] ] + lookups = [ [lu1], None, [lu2] ] + builder.rules.append( (prefix, glyphs, suffix, lookups) ) + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + rules: A list of tuples representing the rules in this lookup. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GSUB", 6) + self.rules = [] # (prefix, input, suffix, lookups) + self.subtable_type = "Subst" + + def getAlternateGlyphs(self): + result = {} + for rule in self.rules: + if rule.is_subtable_break: + continue + for lookups in rule.lookups: + if not isinstance(lookups, list): + lookups = [lookups] + for lookup in lookups: + if lookup is not None: + alts = lookup.getAlternateGlyphs() + for glyph, replacements in alts.items(): + alts_for_glyph = result.setdefault(glyph, []) + alts_for_glyph.extend( + g for g in replacements if g not in alts_for_glyph + ) + return result + + def find_chainable_subst(self, mapping, builder_class): + """Helper for add_{single,multi}_subst_chained_()""" + res = None + for rule in self.rules[::-1]: + if rule.is_subtable_break: + return res + for sub in rule.lookups: + if isinstance(sub, builder_class) and not any( + g in mapping and mapping[g] != sub.mapping[g] for g in sub.mapping + ): + res = sub + return res + + def find_chainable_alternate_subst(self, glyph): + """Helper for add_alternate_subst()""" + res = None + for rule in self.rules[::-1]: + if rule.is_subtable_break: + return res + for sub in rule.lookups: + if isinstance(sub, AlternateSubstBuilder) and ( + glyph not in sub.alternates + ): + res = sub + return res + + def find_chainable_ligature_subst(self, glyphs, replacement): + """Helper for add_ligature_subst_chained_()""" + res = None + for rule in self.rules[::-1]: + if rule.is_subtable_break: + return res + for sub in rule.lookups: + if not isinstance(sub, LigatureSubstBuilder): + continue + if all( + sub.ligatures.get(seq, replacement) == replacement + for seq in itertools.product(*glyphs) + ): + res = sub + return res + + +class LigatureSubstBuilder(LookupBuilder): + """Builds a Ligature Substitution (GSUB4) lookup. + + Users are expected to manually add ligatures to the ``ligatures`` + attribute after the object has been initialized, e.g.:: + + # sub f i by f_i; + builder.ligatures[("f","f","i")] = "f_f_i" + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + ligatures: An ordered dictionary mapping a tuple of glyph names to the + ligature glyphname. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GSUB", 4) + self.ligatures = OrderedDict() # {('f','f','i'): 'f_f_i'} + + def equals(self, other): + return LookupBuilder.equals(self, other) and self.ligatures == other.ligatures + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the ligature + substitution lookup. + """ + subtables = self.build_subst_subtables( + self.ligatures, buildLigatureSubstSubtable + ) + return self.buildLookup_(subtables) + + def getAlternateGlyphs(self): + # https://github.com/fonttools/fonttools/issues/3845 + return { + components[0]: [ligature] + for components, ligature in self.ligatures.items() + if len(components) == 1 + } + + def add_subtable_break(self, location): + self.ligatures[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_ + + +class MultipleSubstBuilder(LookupBuilder): + """Builds a Multiple Substitution (GSUB2) lookup. + + Users are expected to manually add substitutions to the ``mapping`` + attribute after the object has been initialized, e.g.:: + + # sub uni06C0 by uni06D5.fina hamza.above; + builder.mapping["uni06C0"] = [ "uni06D5.fina", "hamza.above"] + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + mapping: An ordered dictionary mapping a glyph name to a list of + substituted glyph names. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GSUB", 2) + self.mapping = OrderedDict() + + def equals(self, other): + return LookupBuilder.equals(self, other) and self.mapping == other.mapping + + def build(self): + subtables = self.build_subst_subtables(self.mapping, buildMultipleSubstSubtable) + return self.buildLookup_(subtables) + + def getAlternateGlyphs(self): + # https://github.com/fonttools/fonttools/issues/3845 + return { + glyph: replacements + for glyph, replacements in self.mapping.items() + if len(replacements) == 1 + } + + def add_subtable_break(self, location): + self.mapping[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_ + + +class CursivePosBuilder(LookupBuilder): + """Builds a Cursive Positioning (GPOS3) lookup. + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + attachments: An ordered dictionary mapping a glyph name to a two-element + tuple of ``otTables.Anchor`` objects. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GPOS", 3) + self.attachments = {} + + def equals(self, other): + return ( + LookupBuilder.equals(self, other) and self.attachments == other.attachments + ) + + def add_attachment(self, location, glyphs, entryAnchor, exitAnchor): + """Adds attachment information to the cursive positioning lookup. + + Args: + location: A string or tuple representing the location in the + original source which produced this lookup. (Unused.) + glyphs: A list of glyph names sharing these entry and exit + anchor locations. + entryAnchor: A ``otTables.Anchor`` object representing the + entry anchor, or ``None`` if no entry anchor is present. + exitAnchor: A ``otTables.Anchor`` object representing the + exit anchor, or ``None`` if no exit anchor is present. + """ + for glyph in glyphs: + self.attachments[glyph] = (entryAnchor, exitAnchor) + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the cursive + positioning lookup. + """ + attachments = [{}] + for key in self.attachments: + if key[0] == self.SUBTABLE_BREAK_: + attachments.append({}) + else: + attachments[-1][key] = self.attachments[key] + subtables = [buildCursivePosSubtable(s, self.glyphMap) for s in attachments] + return self.buildLookup_(subtables) + + def add_subtable_break(self, location): + self.attachments[(self.SUBTABLE_BREAK_, location)] = ( + self.SUBTABLE_BREAK_, + self.SUBTABLE_BREAK_, + ) + + +class MarkBasePosBuilder(LookupBuilder): + """Builds a Mark-To-Base Positioning (GPOS4) lookup. + + Users are expected to manually add marks and bases to the ``marks`` + and ``bases`` attributes after the object has been initialized, e.g.:: + + builder.marks["acute"] = (0, a1) + builder.marks["grave"] = (0, a1) + builder.marks["cedilla"] = (1, a2) + builder.bases["a"] = {0: a3, 1: a5} + builder.bases["b"] = {0: a4, 1: a5} + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + marks: An dictionary mapping a glyph name to a two-element + tuple containing a mark class ID and ``otTables.Anchor`` object. + bases: An dictionary mapping a glyph name to a dictionary of + mark class IDs and ``otTables.Anchor`` object. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GPOS", 4) + self.marks = {} # glyphName -> (markClassName, anchor) + self.bases = {} # glyphName -> {markClassName: anchor} + self.subtables_ = [] + + def get_subtables_(self): + subtables_ = self.subtables_ + if self.bases or self.marks: + subtables_.append((self.marks, self.bases)) + return subtables_ + + def equals(self, other): + return ( + LookupBuilder.equals(self, other) + and self.get_subtables_() == other.get_subtables_() + ) + + def inferGlyphClasses(self): + result = {} + for marks, bases in self.get_subtables_(): + result.update({glyph: 1 for glyph in bases}) + result.update({glyph: 3 for glyph in marks}) + return result + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the mark-to-base + positioning lookup. + """ + subtables = [] + for subtable in self.get_subtables_(): + markClasses = self.buildMarkClasses_(subtable[0]) + marks = {} + for mark, (mc, anchor) in subtable[0].items(): + if mc not in markClasses: + raise ValueError( + "Mark class %s not found for mark glyph %s" % (mc, mark) + ) + marks[mark] = (markClasses[mc], anchor) + bases = {} + for glyph, anchors in subtable[1].items(): + bases[glyph] = {} + for mc, anchor in anchors.items(): + if mc not in markClasses: + raise ValueError( + "Mark class %s not found for base glyph %s" % (mc, glyph) + ) + bases[glyph][markClasses[mc]] = anchor + subtables.append(buildMarkBasePosSubtable(marks, bases, self.glyphMap)) + return self.buildLookup_(subtables) + + def add_subtable_break(self, location): + self.subtables_.append((self.marks, self.bases)) + self.marks = {} + self.bases = {} + + +class MarkLigPosBuilder(LookupBuilder): + """Builds a Mark-To-Ligature Positioning (GPOS5) lookup. + + Users are expected to manually add marks and bases to the ``marks`` + and ``ligatures`` attributes after the object has been initialized, e.g.:: + + builder.marks["acute"] = (0, a1) + builder.marks["grave"] = (0, a1) + builder.marks["cedilla"] = (1, a2) + builder.ligatures["f_i"] = [ + { 0: a3, 1: a5 }, # f + { 0: a4, 1: a5 } # i + ] + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + marks: An dictionary mapping a glyph name to a two-element + tuple containing a mark class ID and ``otTables.Anchor`` object. + ligatures: An dictionary mapping a glyph name to an array with one + element for each ligature component. Each array element should be + a dictionary mapping mark class IDs to ``otTables.Anchor`` objects. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GPOS", 5) + self.marks = {} # glyphName -> (markClassName, anchor) + self.ligatures = {} # glyphName -> [{markClassName: anchor}, ...] + self.subtables_ = [] + + def get_subtables_(self): + subtables_ = self.subtables_ + if self.ligatures or self.marks: + subtables_.append((self.marks, self.ligatures)) + return subtables_ + + def equals(self, other): + return ( + LookupBuilder.equals(self, other) + and self.get_subtables_() == other.get_subtables_() + ) + + def inferGlyphClasses(self): + result = {} + for marks, ligatures in self.get_subtables_(): + result.update({glyph: 2 for glyph in ligatures}) + result.update({glyph: 3 for glyph in marks}) + return result + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the mark-to-ligature + positioning lookup. + """ + subtables = [] + for subtable in self.get_subtables_(): + markClasses = self.buildMarkClasses_(subtable[0]) + marks = { + mark: (markClasses[mc], anchor) + for mark, (mc, anchor) in subtable[0].items() + } + ligs = {} + for lig, components in subtable[1].items(): + ligs[lig] = [] + for c in components: + ligs[lig].append({markClasses[mc]: a for mc, a in c.items()}) + subtables.append(buildMarkLigPosSubtable(marks, ligs, self.glyphMap)) + return self.buildLookup_(subtables) + + def add_subtable_break(self, location): + self.subtables_.append((self.marks, self.ligatures)) + self.marks = {} + self.ligatures = {} + + +class MarkMarkPosBuilder(LookupBuilder): + """Builds a Mark-To-Mark Positioning (GPOS6) lookup. + + Users are expected to manually add marks and bases to the ``marks`` + and ``baseMarks`` attributes after the object has been initialized, e.g.:: + + builder.marks["acute"] = (0, a1) + builder.marks["grave"] = (0, a1) + builder.marks["cedilla"] = (1, a2) + builder.baseMarks["acute"] = {0: a3} + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + marks: An dictionary mapping a glyph name to a two-element + tuple containing a mark class ID and ``otTables.Anchor`` object. + baseMarks: An dictionary mapping a glyph name to a dictionary + containing one item: a mark class ID and a ``otTables.Anchor`` object. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GPOS", 6) + self.marks = {} # glyphName -> (markClassName, anchor) + self.baseMarks = {} # glyphName -> {markClassName: anchor} + self.subtables_ = [] + + def get_subtables_(self): + subtables_ = self.subtables_ + if self.baseMarks or self.marks: + subtables_.append((self.marks, self.baseMarks)) + return subtables_ + + def equals(self, other): + return ( + LookupBuilder.equals(self, other) + and self.get_subtables_() == other.get_subtables_() + ) + + def inferGlyphClasses(self): + result = {} + for marks, baseMarks in self.get_subtables_(): + result.update({glyph: 3 for glyph in baseMarks}) + result.update({glyph: 3 for glyph in marks}) + return result + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the mark-to-mark + positioning lookup. + """ + subtables = [] + for subtable in self.get_subtables_(): + markClasses = self.buildMarkClasses_(subtable[0]) + markClassList = sorted(markClasses.keys(), key=markClasses.get) + marks = { + mark: (markClasses[mc], anchor) + for mark, (mc, anchor) in subtable[0].items() + } + + st = ot.MarkMarkPos() + st.Format = 1 + st.ClassCount = len(markClasses) + st.Mark1Coverage = buildCoverage(marks, self.glyphMap) + st.Mark2Coverage = buildCoverage(subtable[1], self.glyphMap) + st.Mark1Array = buildMarkArray(marks, self.glyphMap) + st.Mark2Array = ot.Mark2Array() + st.Mark2Array.Mark2Count = len(st.Mark2Coverage.glyphs) + st.Mark2Array.Mark2Record = [] + for base in st.Mark2Coverage.glyphs: + anchors = [subtable[1][base].get(mc) for mc in markClassList] + st.Mark2Array.Mark2Record.append(buildMark2Record(anchors)) + subtables.append(st) + return self.buildLookup_(subtables) + + def add_subtable_break(self, location): + self.subtables_.append((self.marks, self.baseMarks)) + self.marks = {} + self.baseMarks = {} + + +class ReverseChainSingleSubstBuilder(LookupBuilder): + """Builds a Reverse Chaining Contextual Single Substitution (GSUB8) lookup. + + Users are expected to manually add substitutions to the ``substitutions`` + attribute after the object has been initialized, e.g.:: + + # reversesub [a e n] d' by d.alt; + prefix = [ ["a", "e", "n"] ] + suffix = [] + mapping = { "d": "d.alt" } + builder.substitutions.append( (prefix, suffix, mapping) ) + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + substitutions: A three-element tuple consisting of a prefix sequence, + a suffix sequence, and a dictionary of single substitutions. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GSUB", 8) + self.rules = [] # (prefix, suffix, mapping) + + def equals(self, other): + return LookupBuilder.equals(self, other) and self.rules == other.rules + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the chained + contextual substitution lookup. + """ + subtables = [] + for prefix, suffix, mapping in self.rules: + st = ot.ReverseChainSingleSubst() + st.Format = 1 + self.setBacktrackCoverage_(prefix, st) + self.setLookAheadCoverage_(suffix, st) + st.Coverage = buildCoverage(mapping.keys(), self.glyphMap) + st.GlyphCount = len(mapping) + st.Substitute = [mapping[g] for g in st.Coverage.glyphs] + subtables.append(st) + return self.buildLookup_(subtables) + + def add_subtable_break(self, location): + # Nothing to do here, each substitution is in its own subtable. + pass + + +class AnySubstBuilder(LookupBuilder): + """A temporary builder for Single, Multiple, or Ligature substitution lookup. + + Users are expected to manually add substitutions to the ``mapping`` + attribute after the object has been initialized, e.g.:: + + # sub x by y; + builder.mapping[("x",)] = ("y",) + # sub a by b c; + builder.mapping[("a",)] = ("b", "c") + # sub f i by f_i; + builder.mapping[("f", "i")] = ("f_i",) + + Then call `promote_lookup_type()` to convert this builder into the + appropriate type of substitution lookup builder. This would promote single + substitutions to either multiple or ligature substitutions, depending on the + rest of the rules in the mapping. + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + mapping: An ordered dictionary mapping a tuple of glyph names to another + tuple of glyph names. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GSUB", 0) + self.mapping = OrderedDict() + + def _add_to_single_subst(self, builder, key, value): + if key[0] != self.SUBTABLE_BREAK_: + key = key[0] + builder.mapping[key] = value[0] + + def _add_to_multiple_subst(self, builder, key, value): + if key[0] != self.SUBTABLE_BREAK_: + key = key[0] + builder.mapping[key] = value + + def _add_to_ligature_subst(self, builder, key, value): + builder.ligatures[key] = value[0] + + def can_add_mapping(self, mapping) -> bool: + if mapping is None: + return True + # single sub rules can be treated as (degenerate) liga-or-multi sub + # rules, but multi and liga sub rules themselves have incompatible + # representations. It is uncommon that these are in the same set of + # rules, but it happens. + is_multi = any(len(v) > 1 for v in mapping.values()) + is_liga = any(len(k) > 1 for k in mapping.keys()) + + has_existing_multi = False + has_existing_liga = False + + for k, v in self.mapping.items(): + if k[0] == self.SUBTABLE_BREAK_: + continue + if len(k) > 1: + has_existing_liga = True + if len(v) > 1: + has_existing_multi = True + + can_reuse = not (has_existing_multi and is_liga) and not ( + has_existing_liga and is_multi + ) + return can_reuse + + def promote_lookup_type(self, is_named_lookup): + # https://github.com/fonttools/fonttools/issues/612 + # A multiple substitution may have a single destination, in which case + # it will look just like a single substitution. So if there are both + # multiple and single substitutions, upgrade all the single ones to + # multiple substitutions. Similarly, a ligature substitution may have a + # single source glyph, so if there are both ligature and single + # substitutions, upgrade all the single ones to ligature substitutions. + builder_classes = [] + for key, value in self.mapping.items(): + if key[0] == self.SUBTABLE_BREAK_: + builder_classes.append(None) + elif len(key) == 1 and len(value) == 1: + builder_classes.append(SingleSubstBuilder) + elif len(key) == 1 and len(value) != 1: + builder_classes.append(MultipleSubstBuilder) + elif len(key) > 1 and len(value) == 1: + builder_classes.append(LigatureSubstBuilder) + else: + assert False, "Should not happen" + + has_multiple = any(b is MultipleSubstBuilder for b in builder_classes) + has_ligature = any(b is LigatureSubstBuilder for b in builder_classes) + + # If we have mixed single and multiple substitutions, + # upgrade all single substitutions to multiple substitutions. + to_multiple = has_multiple and not has_ligature + + # If we have mixed single and ligature substitutions, + # upgrade all single substitutions to ligature substitutions. + to_ligature = has_ligature and not has_multiple + + # If we have only single substitutions, we can keep them as is. + to_single = not has_ligature and not has_multiple + + ret = [] + if to_single: + builder = SingleSubstBuilder(self.font, self.location) + for key, value in self.mapping.items(): + self._add_to_single_subst(builder, key, value) + ret = [builder] + elif to_multiple: + builder = MultipleSubstBuilder(self.font, self.location) + for key, value in self.mapping.items(): + self._add_to_multiple_subst(builder, key, value) + ret = [builder] + elif to_ligature: + builder = LigatureSubstBuilder(self.font, self.location) + for key, value in self.mapping.items(): + self._add_to_ligature_subst(builder, key, value) + ret = [builder] + elif is_named_lookup: + # This is a named lookup with mixed substitutions that can’t be promoted, + # since we can’t split it into multiple lookups, we return None here to + # signal that to the caller + return None + else: + curr_builder = None + for builder_class, (key, value) in zip( + builder_classes, self.mapping.items() + ): + if curr_builder is None or type(curr_builder) is not builder_class: + curr_builder = builder_class(self.font, self.location) + ret.append(curr_builder) + if builder_class is SingleSubstBuilder: + self._add_to_single_subst(curr_builder, key, value) + elif builder_class is MultipleSubstBuilder: + self._add_to_multiple_subst(curr_builder, key, value) + elif builder_class is LigatureSubstBuilder: + self._add_to_ligature_subst(curr_builder, key, value) + else: + assert False, "Should not happen" + + for builder in ret: + builder.extension = self.extension + builder.lookupflag = self.lookupflag + builder.markFilterSet = self.markFilterSet + return ret + + def equals(self, other): + return LookupBuilder.equals(self, other) and self.mapping == other.mapping + + def build(self): + assert False + + def getAlternateGlyphs(self): + return { + key[0]: value + for key, value in self.mapping.items() + if len(key) == 1 and len(value) == 1 + } + + def add_subtable_break(self, location): + self.mapping[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_ + + +class SingleSubstBuilder(LookupBuilder): + """Builds a Single Substitution (GSUB1) lookup. + + Users are expected to manually add substitutions to the ``mapping`` + attribute after the object has been initialized, e.g.:: + + # sub x by y; + builder.mapping["x"] = "y" + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + mapping: A dictionary mapping a single glyph name to another glyph name. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GSUB", 1) + self.mapping = OrderedDict() + + def equals(self, other): + return LookupBuilder.equals(self, other) and self.mapping == other.mapping + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the multiple + substitution lookup. + """ + subtables = self.build_subst_subtables(self.mapping, buildSingleSubstSubtable) + return self.buildLookup_(subtables) + + def getAlternateGlyphs(self): + return {glyph: [repl] for glyph, repl in self.mapping.items()} + + def add_subtable_break(self, location): + self.mapping[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_ + + +class ClassPairPosSubtableBuilder(object): + """Builds class-based Pair Positioning (GPOS2 format 2) subtables. + + Note that this does *not* build a GPOS2 ``otTables.Lookup`` directly, + but builds a list of ``otTables.PairPos`` subtables. It is used by the + :class:`PairPosBuilder` below. + + Attributes: + builder (PairPosBuilder): A pair positioning lookup builder. + """ + + def __init__(self, builder): + self.builder_ = builder + self.classDef1_, self.classDef2_ = None, None + self.values_ = {} # (glyphclass1, glyphclass2) --> (value1, value2) + self.forceSubtableBreak_ = False + self.subtables_ = [] + + def addPair(self, gc1, value1, gc2, value2): + """Add a pair positioning rule. + + Args: + gc1: A set of glyph names for the "left" glyph + value1: An ``otTables.ValueRecord`` object for the left glyph's + positioning. + gc2: A set of glyph names for the "right" glyph + value2: An ``otTables.ValueRecord`` object for the right glyph's + positioning. + """ + mergeable = ( + not self.forceSubtableBreak_ + and self.classDef1_ is not None + and self.classDef1_.canAdd(gc1) + and self.classDef2_ is not None + and self.classDef2_.canAdd(gc2) + ) + if not mergeable: + self.flush_() + self.classDef1_ = ClassDefBuilder(useClass0=True) + self.classDef2_ = ClassDefBuilder(useClass0=False) + self.values_ = {} + self.classDef1_.add(gc1) + self.classDef2_.add(gc2) + self.values_[(gc1, gc2)] = (value1, value2) + + def addSubtableBreak(self): + """Add an explicit subtable break at this point.""" + self.forceSubtableBreak_ = True + + def subtables(self): + """Return the list of ``otTables.PairPos`` subtables constructed.""" + self.flush_() + return self.subtables_ + + def flush_(self): + if self.classDef1_ is None or self.classDef2_ is None: + return + st = buildPairPosClassesSubtable(self.values_, self.builder_.glyphMap) + if st.Coverage is None: + return + self.subtables_.append(st) + self.forceSubtableBreak_ = False + + +class PairPosBuilder(LookupBuilder): + """Builds a Pair Positioning (GPOS2) lookup. + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + pairs: An array of class-based pair positioning tuples. Usually + manipulated with the :meth:`addClassPair` method below. + glyphPairs: A dictionary mapping a tuple of glyph names to a tuple + of ``otTables.ValueRecord`` objects. Usually manipulated with the + :meth:`addGlyphPair` method below. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GPOS", 2) + self.pairs = [] # [(gc1, value1, gc2, value2)*] + self.glyphPairs = {} # (glyph1, glyph2) --> (value1, value2) + self.locations = {} # (gc1, gc2) --> (filepath, line, column) + + def addClassPair(self, location, glyphclass1, value1, glyphclass2, value2): + """Add a class pair positioning rule to the current lookup. + + Args: + location: A string or tuple representing the location in the + original source which produced this rule. Unused. + glyphclass1: A set of glyph names for the "left" glyph in the pair. + value1: A ``otTables.ValueRecord`` for positioning the left glyph. + glyphclass2: A set of glyph names for the "right" glyph in the pair. + value2: A ``otTables.ValueRecord`` for positioning the right glyph. + """ + self.pairs.append((glyphclass1, value1, glyphclass2, value2)) + + def addGlyphPair(self, location, glyph1, value1, glyph2, value2): + """Add a glyph pair positioning rule to the current lookup. + + Args: + location: A string or tuple representing the location in the + original source which produced this rule. + glyph1: A glyph name for the "left" glyph in the pair. + value1: A ``otTables.ValueRecord`` for positioning the left glyph. + glyph2: A glyph name for the "right" glyph in the pair. + value2: A ``otTables.ValueRecord`` for positioning the right glyph. + """ + key = (glyph1, glyph2) + oldValue = self.glyphPairs.get(key, None) + if oldValue is not None: + # the Feature File spec explicitly allows specific pairs generated + # by an 'enum' rule to be overridden by preceding single pairs + otherLoc = self.locations[key] + log.debug( + "Already defined position for pair %s %s at %s; " + "choosing the first value", + glyph1, + glyph2, + otherLoc, + ) + else: + self.glyphPairs[key] = (value1, value2) + self.locations[key] = location + + def add_subtable_break(self, location): + self.pairs.append( + ( + self.SUBTABLE_BREAK_, + self.SUBTABLE_BREAK_, + self.SUBTABLE_BREAK_, + self.SUBTABLE_BREAK_, + ) + ) + + def equals(self, other): + return ( + LookupBuilder.equals(self, other) + and self.glyphPairs == other.glyphPairs + and self.pairs == other.pairs + ) + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the pair positioning + lookup. + """ + builders = {} + builder = ClassPairPosSubtableBuilder(self) + for glyphclass1, value1, glyphclass2, value2 in self.pairs: + if glyphclass1 is self.SUBTABLE_BREAK_: + builder.addSubtableBreak() + continue + builder.addPair(glyphclass1, value1, glyphclass2, value2) + subtables = [] + if self.glyphPairs: + subtables.extend(buildPairPosGlyphs(self.glyphPairs, self.glyphMap)) + subtables.extend(builder.subtables()) + lookup = self.buildLookup_(subtables) + + # Compact the lookup + # This is a good moment to do it because the compaction should create + # smaller subtables, which may prevent overflows from happening. + # Keep reading the value from the ENV until ufo2ft switches to the config system + level = self.font.cfg.get( + "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL", + default=_compression_level_from_env(), + ) + if level != 0: + log.info("Compacting GPOS...") + compact_lookup(self.font, level, lookup) + + return lookup + + +class SinglePosBuilder(LookupBuilder): + """Builds a Single Positioning (GPOS1) lookup. + + Attributes: + font (``fontTools.TTLib.TTFont``): A font object. + location: A string or tuple representing the location in the original + source which produced this lookup. + mapping: A dictionary mapping a glyph name to a ``otTables.ValueRecord`` + objects. Usually manipulated with the :meth:`add_pos` method below. + lookupflag (int): The lookup's flag + markFilterSet: Either ``None`` if no mark filtering set is used, or + an integer representing the filtering set to be used for this + lookup. If a mark filtering set is provided, + `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's + flags. + """ + + def __init__(self, font, location): + LookupBuilder.__init__(self, font, location, "GPOS", 1) + self.locations = {} # glyph -> (filename, line, column) + self.mapping = {} # glyph -> ot.ValueRecord + + def add_pos(self, location, glyph, otValueRecord): + """Add a single positioning rule. + + Args: + location: A string or tuple representing the location in the + original source which produced this lookup. + glyph: A glyph name. + otValueRection: A ``otTables.ValueRecord`` used to position the + glyph. + """ + if otValueRecord is None: + otValueRecord = ValueRecord() + if not self.can_add(glyph, otValueRecord): + otherLoc = self.locations[glyph] + raise OpenTypeLibError( + 'Already defined different position for glyph "%s" at %s' + % (glyph, otherLoc), + location, + ) + if otValueRecord: + self.mapping[glyph] = otValueRecord + self.locations[glyph] = location + + def can_add(self, glyph, value): + assert isinstance(value, ValueRecord) + curValue = self.mapping.get(glyph) + return curValue is None or curValue == value + + def equals(self, other): + return LookupBuilder.equals(self, other) and self.mapping == other.mapping + + def build(self): + """Build the lookup. + + Returns: + An ``otTables.Lookup`` object representing the single positioning + lookup. + """ + subtables = buildSinglePos(self.mapping, self.glyphMap) + return self.buildLookup_(subtables) + + +# GSUB + + +def buildSingleSubstSubtable(mapping): + """Builds a single substitution (GSUB1) subtable. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.SingleSubstBuilder` instead. + + Args: + mapping: A dictionary mapping input glyph names to output glyph names. + + Returns: + An ``otTables.SingleSubst`` object, or ``None`` if the mapping dictionary + is empty. + """ + if not mapping: + return None + self = ot.SingleSubst() + self.mapping = dict(mapping) + return self + + +def buildMultipleSubstSubtable(mapping): + """Builds a multiple substitution (GSUB2) subtable. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead. + + Example:: + + # sub uni06C0 by uni06D5.fina hamza.above + # sub uni06C2 by uni06C1.fina hamza.above; + + subtable = buildMultipleSubstSubtable({ + "uni06C0": [ "uni06D5.fina", "hamza.above"], + "uni06C2": [ "uni06D1.fina", "hamza.above"] + }) + + Args: + mapping: A dictionary mapping input glyph names to a list of output + glyph names. + + Returns: + An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary + is empty. + """ + if not mapping: + return None + self = ot.MultipleSubst() + self.mapping = dict(mapping) + return self + + +def buildAlternateSubstSubtable(mapping): + """Builds an alternate substitution (GSUB3) subtable. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead. + + Args: + mapping: A dictionary mapping input glyph names to a list of output + glyph names. + + Returns: + An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary + is empty. + """ + if not mapping: + return None + self = ot.AlternateSubst() + self.alternates = dict(mapping) + return self + + +def buildLigatureSubstSubtable(mapping): + """Builds a ligature substitution (GSUB4) subtable. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead. + + Example:: + + # sub f f i by f_f_i; + # sub f i by f_i; + + subtable = buildLigatureSubstSubtable({ + ("f", "f", "i"): "f_f_i", + ("f", "i"): "f_i", + }) + + Args: + mapping: A dictionary mapping tuples of glyph names to output + glyph names. + + Returns: + An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary + is empty. + """ + + if not mapping: + return None + self = ot.LigatureSubst() + # The following single line can replace the rest of this function + # with fontTools >= 3.1: + # self.ligatures = dict(mapping) + self.ligatures = {} + for components in sorted(mapping.keys(), key=self._getLigatureSortKey): + ligature = ot.Ligature() + ligature.Component = components[1:] + ligature.CompCount = len(ligature.Component) + 1 + ligature.LigGlyph = mapping[components] + firstGlyph = components[0] + self.ligatures.setdefault(firstGlyph, []).append(ligature) + return self + + +# GPOS + + +def buildAnchor(x, y, point=None, deviceX=None, deviceY=None): + """Builds an Anchor table. + + This determines the appropriate anchor format based on the passed parameters. + + Args: + x (int): X coordinate. + y (int): Y coordinate. + point (int): Index of glyph contour point, if provided. + deviceX (``otTables.Device``): X coordinate device table, if provided. + deviceY (``otTables.Device``): Y coordinate device table, if provided. + + Returns: + An ``otTables.Anchor`` object. + """ + self = ot.Anchor() + self.XCoordinate, self.YCoordinate = x, y + self.Format = 1 + if point is not None: + self.AnchorPoint = point + self.Format = 2 + if deviceX is not None or deviceY is not None: + assert ( + self.Format == 1 + ), "Either point, or both of deviceX/deviceY, must be None." + self.XDeviceTable = deviceX + self.YDeviceTable = deviceY + self.Format = 3 + return self + + +def buildBaseArray(bases, numMarkClasses, glyphMap): + """Builds a base array record. + + As part of building mark-to-base positioning rules, you will need to define + a ``BaseArray`` record, which "defines for each base glyph an array of + anchors, one for each mark class." This function builds the base array + subtable. + + Example:: + + bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} + basearray = buildBaseArray(bases, 2, font.getReverseGlyphMap()) + + Args: + bases (dict): A dictionary mapping anchors to glyphs; the keys being + glyph names, and the values being dictionaries mapping mark class ID + to the appropriate ``otTables.Anchor`` object used for attaching marks + of that class. + numMarkClasses (int): The total number of mark classes for which anchors + are defined. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + An ``otTables.BaseArray`` object. + """ + self = ot.BaseArray() + self.BaseRecord = [] + for base in sorted(bases, key=glyphMap.__getitem__): + b = bases[base] + anchors = [b.get(markClass) for markClass in range(numMarkClasses)] + self.BaseRecord.append(buildBaseRecord(anchors)) + self.BaseCount = len(self.BaseRecord) + return self + + +def buildBaseRecord(anchors): + # [otTables.Anchor, otTables.Anchor, ...] --> otTables.BaseRecord + self = ot.BaseRecord() + self.BaseAnchor = anchors + return self + + +def buildComponentRecord(anchors): + """Builds a component record. + + As part of building mark-to-ligature positioning rules, you will need to + define ``ComponentRecord`` objects, which contain "an array of offsets... + to the Anchor tables that define all the attachment points used to attach + marks to the component." This function builds the component record. + + Args: + anchors: A list of ``otTables.Anchor`` objects or ``None``. + + Returns: + A ``otTables.ComponentRecord`` object or ``None`` if no anchors are + supplied. + """ + if not anchors: + return None + self = ot.ComponentRecord() + self.LigatureAnchor = anchors + return self + + +def buildCursivePosSubtable(attach, glyphMap): + """Builds a cursive positioning (GPOS3) subtable. + + Cursive positioning lookups are made up of a coverage table of glyphs, + and a set of ``EntryExitRecord`` records containing the anchors for + each glyph. This function builds the cursive positioning subtable. + + Example:: + + subtable = buildCursivePosSubtable({ + "AlifIni": (None, buildAnchor(0, 50)), + "BehMed": (buildAnchor(500,250), buildAnchor(0,50)), + # ... + }, font.getReverseGlyphMap()) + + Args: + attach (dict): A mapping between glyph names and a tuple of two + ``otTables.Anchor`` objects representing entry and exit anchors. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + An ``otTables.CursivePos`` object, or ``None`` if the attachment + dictionary was empty. + """ + if not attach: + return None + self = ot.CursivePos() + self.Format = 1 + self.Coverage = buildCoverage(attach.keys(), glyphMap) + self.EntryExitRecord = [] + for glyph in self.Coverage.glyphs: + entryAnchor, exitAnchor = attach[glyph] + rec = ot.EntryExitRecord() + rec.EntryAnchor = entryAnchor + rec.ExitAnchor = exitAnchor + self.EntryExitRecord.append(rec) + self.EntryExitCount = len(self.EntryExitRecord) + return self + + +def buildDevice(deltas): + """Builds a Device record as part of a ValueRecord or Anchor. + + Device tables specify size-specific adjustments to value records + and anchors to reflect changes based on the resolution of the output. + For example, one could specify that an anchor's Y position should be + increased by 1 pixel when displayed at 8 pixels per em. This routine + builds device records. + + Args: + deltas: A dictionary mapping pixels-per-em sizes to the delta + adjustment in pixels when the font is displayed at that size. + + Returns: + An ``otTables.Device`` object if any deltas were supplied, or + ``None`` otherwise. + """ + if not deltas: + return None + self = ot.Device() + keys = deltas.keys() + self.StartSize = startSize = min(keys) + self.EndSize = endSize = max(keys) + assert 0 <= startSize <= endSize + self.DeltaValue = deltaValues = [ + deltas.get(size, 0) for size in range(startSize, endSize + 1) + ] + maxDelta = max(deltaValues) + minDelta = min(deltaValues) + assert minDelta > -129 and maxDelta < 128 + if minDelta > -3 and maxDelta < 2: + self.DeltaFormat = 1 + elif minDelta > -9 and maxDelta < 8: + self.DeltaFormat = 2 + else: + self.DeltaFormat = 3 + return self + + +def buildLigatureArray(ligs, numMarkClasses, glyphMap): + """Builds a LigatureArray subtable. + + As part of building a mark-to-ligature lookup, you will need to define + the set of anchors (for each mark class) on each component of the ligature + where marks can be attached. For example, for an Arabic divine name ligature + (lam lam heh), you may want to specify mark attachment positioning for + superior marks (fatha, etc.) and inferior marks (kasra, etc.) on each glyph + of the ligature. This routine builds the ligature array record. + + Example:: + + buildLigatureArray({ + "lam-lam-heh": [ + { 0: superiorAnchor1, 1: inferiorAnchor1 }, # attach points for lam1 + { 0: superiorAnchor2, 1: inferiorAnchor2 }, # attach points for lam2 + { 0: superiorAnchor3, 1: inferiorAnchor3 }, # attach points for heh + ] + }, 2, font.getReverseGlyphMap()) + + Args: + ligs (dict): A mapping of ligature names to an array of dictionaries: + for each component glyph in the ligature, an dictionary mapping + mark class IDs to anchors. + numMarkClasses (int): The number of mark classes. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + An ``otTables.LigatureArray`` object if deltas were supplied. + """ + self = ot.LigatureArray() + self.LigatureAttach = [] + for lig in sorted(ligs, key=glyphMap.__getitem__): + anchors = [] + for component in ligs[lig]: + anchors.append([component.get(mc) for mc in range(numMarkClasses)]) + self.LigatureAttach.append(buildLigatureAttach(anchors)) + self.LigatureCount = len(self.LigatureAttach) + return self + + +def buildLigatureAttach(components): + # [[Anchor, Anchor], [Anchor, Anchor, Anchor]] --> LigatureAttach + self = ot.LigatureAttach() + self.ComponentRecord = [buildComponentRecord(c) for c in components] + self.ComponentCount = len(self.ComponentRecord) + return self + + +def buildMarkArray(marks, glyphMap): + """Builds a mark array subtable. + + As part of building mark-to-* positioning rules, you will need to define + a MarkArray subtable, which "defines the class and the anchor point + for a mark glyph." This function builds the mark array subtable. + + Example:: + + mark = { + "acute": (0, buildAnchor(300,712)), + # ... + } + markarray = buildMarkArray(marks, font.getReverseGlyphMap()) + + Args: + marks (dict): A dictionary mapping anchors to glyphs; the keys being + glyph names, and the values being a tuple of mark class number and + an ``otTables.Anchor`` object representing the mark's attachment + point. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + An ``otTables.MarkArray`` object. + """ + self = ot.MarkArray() + self.MarkRecord = [] + for mark in sorted(marks.keys(), key=glyphMap.__getitem__): + markClass, anchor = marks[mark] + markrec = buildMarkRecord(markClass, anchor) + self.MarkRecord.append(markrec) + self.MarkCount = len(self.MarkRecord) + return self + + +@deprecateFunction( + "use buildMarkBasePosSubtable() instead", category=DeprecationWarning +) +def buildMarkBasePos(marks, bases, glyphMap): + """Build a list of MarkBasePos (GPOS4) subtables. + + .. deprecated:: 4.58.0 + Use :func:`buildMarkBasePosSubtable` instead. + """ + return [buildMarkBasePosSubtable(marks, bases, glyphMap)] + + +def buildMarkBasePosSubtable(marks, bases, glyphMap): + """Build a single MarkBasePos (GPOS4) subtable. + + This builds a mark-to-base lookup subtable containing all of the referenced + marks and bases. + + Example:: + + # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... + + marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)} + bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} + markbaseposes = [buildMarkBasePosSubtable(marks, bases, font.getReverseGlyphMap())] + + Args: + marks (dict): A dictionary mapping anchors to glyphs; the keys being + glyph names, and the values being a tuple of mark class number and + an ``otTables.Anchor`` object representing the mark's attachment + point. (See :func:`buildMarkArray`.) + bases (dict): A dictionary mapping anchors to glyphs; the keys being + glyph names, and the values being dictionaries mapping mark class ID + to the appropriate ``otTables.Anchor`` object used for attaching marks + of that class. (See :func:`buildBaseArray`.) + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + A ``otTables.MarkBasePos`` object. + """ + self = ot.MarkBasePos() + self.Format = 1 + self.MarkCoverage = buildCoverage(marks, glyphMap) + self.MarkArray = buildMarkArray(marks, glyphMap) + self.ClassCount = max([mc for mc, _ in marks.values()]) + 1 + self.BaseCoverage = buildCoverage(bases, glyphMap) + self.BaseArray = buildBaseArray(bases, self.ClassCount, glyphMap) + return self + + +@deprecateFunction("use buildMarkLigPosSubtable() instead", category=DeprecationWarning) +def buildMarkLigPos(marks, ligs, glyphMap): + """Build a list of MarkLigPos (GPOS5) subtables. + + .. deprecated:: 4.58.0 + Use :func:`buildMarkLigPosSubtable` instead. + """ + return [buildMarkLigPosSubtable(marks, ligs, glyphMap)] + + +def buildMarkLigPosSubtable(marks, ligs, glyphMap): + """Build a single MarkLigPos (GPOS5) subtable. + + This builds a mark-to-base lookup subtable containing all of the referenced + marks and bases. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead. + + Example:: + + # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... + marks = { + "acute": (0, a1), + "grave": (0, a1), + "cedilla": (1, a2) + } + ligs = { + "f_i": [ + { 0: a3, 1: a5 }, # f + { 0: a4, 1: a5 } # i + ], + # "c_t": [{...}, {...}] + } + markligpose = buildMarkLigPosSubtable(marks, ligs, + font.getReverseGlyphMap()) + + Args: + marks (dict): A dictionary mapping anchors to glyphs; the keys being + glyph names, and the values being a tuple of mark class number and + an ``otTables.Anchor`` object representing the mark's attachment + point. (See :func:`buildMarkArray`.) + ligs (dict): A mapping of ligature names to an array of dictionaries: + for each component glyph in the ligature, an dictionary mapping + mark class IDs to anchors. (See :func:`buildLigatureArray`.) + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + A ``otTables.MarkLigPos`` object. + """ + self = ot.MarkLigPos() + self.Format = 1 + self.MarkCoverage = buildCoverage(marks, glyphMap) + self.MarkArray = buildMarkArray(marks, glyphMap) + self.ClassCount = max([mc for mc, _ in marks.values()]) + 1 + self.LigatureCoverage = buildCoverage(ligs, glyphMap) + self.LigatureArray = buildLigatureArray(ligs, self.ClassCount, glyphMap) + return self + + +def buildMarkRecord(classID, anchor): + assert isinstance(classID, int) + assert isinstance(anchor, ot.Anchor) + self = ot.MarkRecord() + self.Class = classID + self.MarkAnchor = anchor + return self + + +def buildMark2Record(anchors): + # [otTables.Anchor, otTables.Anchor, ...] --> otTables.Mark2Record + self = ot.Mark2Record() + self.Mark2Anchor = anchors + return self + + +def _getValueFormat(f, values, i): + # Helper for buildPairPos{Glyphs|Classes}Subtable. + if f is not None: + return f + mask = 0 + for value in values: + if value is not None and value[i] is not None: + mask |= value[i].getFormat() + return mask + + +def buildPairPosClassesSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None): + """Builds a class pair adjustment (GPOS2 format 2) subtable. + + Kerning tables are generally expressed as pair positioning tables using + class-based pair adjustments. This routine builds format 2 PairPos + subtables. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.ClassPairPosSubtableBuilder` + instead, as this takes care of ensuring that the supplied pairs can be + formed into non-overlapping classes and emitting individual subtables + whenever the non-overlapping requirement means that a new subtable is + required. + + Example:: + + pairs = {} + + pairs[( + [ "K", "X" ], + [ "W", "V" ] + )] = ( buildValue(xAdvance=+5), buildValue() ) + # pairs[(... , ...)] = (..., ...) + + pairpos = buildPairPosClassesSubtable(pairs, font.getReverseGlyphMap()) + + Args: + pairs (dict): Pair positioning data; the keys being a two-element + tuple of lists of glyphnames, and the values being a two-element + tuple of ``otTables.ValueRecord`` objects. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + valueFormat1: Force the "left" value records to the given format. + valueFormat2: Force the "right" value records to the given format. + + Returns: + A ``otTables.PairPos`` object. + """ + coverage = set() + classDef1 = ClassDefBuilder(useClass0=True) + classDef2 = ClassDefBuilder(useClass0=False) + for gc1, gc2 in sorted(pairs): + coverage.update(gc1) + classDef1.add(gc1) + classDef2.add(gc2) + self = ot.PairPos() + self.Format = 2 + valueFormat1 = self.ValueFormat1 = _getValueFormat(valueFormat1, pairs.values(), 0) + valueFormat2 = self.ValueFormat2 = _getValueFormat(valueFormat2, pairs.values(), 1) + self.Coverage = buildCoverage(coverage, glyphMap) + self.ClassDef1 = classDef1.build() + self.ClassDef2 = classDef2.build() + classes1 = classDef1.classes() + classes2 = classDef2.classes() + self.Class1Record = [] + for c1 in classes1: + rec1 = ot.Class1Record() + rec1.Class2Record = [] + self.Class1Record.append(rec1) + for c2 in classes2: + rec2 = ot.Class2Record() + val1, val2 = pairs.get((c1, c2), (None, None)) + rec2.Value1 = ( + ValueRecord(src=val1, valueFormat=valueFormat1) + if valueFormat1 + else None + ) + rec2.Value2 = ( + ValueRecord(src=val2, valueFormat=valueFormat2) + if valueFormat2 + else None + ) + rec1.Class2Record.append(rec2) + self.Class1Count = len(self.Class1Record) + self.Class2Count = len(classes2) + return self + + +def buildPairPosGlyphs(pairs, glyphMap): + """Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables. + + This organises a list of pair positioning adjustments into subtables based + on common value record formats. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` + instead. + + Example:: + + pairs = { + ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), + ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), + # ... + } + + subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap()) + + Args: + pairs (dict): Pair positioning data; the keys being a two-element + tuple of glyphnames, and the values being a two-element + tuple of ``otTables.ValueRecord`` objects. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + A list of ``otTables.PairPos`` objects. + """ + + p = {} # (formatA, formatB) --> {(glyphA, glyphB): (valA, valB)} + for (glyphA, glyphB), (valA, valB) in pairs.items(): + formatA = valA.getFormat() if valA is not None else 0 + formatB = valB.getFormat() if valB is not None else 0 + pos = p.setdefault((formatA, formatB), {}) + pos[(glyphA, glyphB)] = (valA, valB) + return [ + buildPairPosGlyphsSubtable(pos, glyphMap, formatA, formatB) + for ((formatA, formatB), pos) in sorted(p.items()) + ] + + +def buildPairPosGlyphsSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None): + """Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable. + + This builds a PairPos subtable from a dictionary of glyph pairs and + their positioning adjustments. See also :func:`buildPairPosGlyphs`. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. + + Example:: + + pairs = { + ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), + ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), + # ... + } + + pairpos = buildPairPosGlyphsSubtable(pairs, font.getReverseGlyphMap()) + + Args: + pairs (dict): Pair positioning data; the keys being a two-element + tuple of glyphnames, and the values being a two-element + tuple of ``otTables.ValueRecord`` objects. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + valueFormat1: Force the "left" value records to the given format. + valueFormat2: Force the "right" value records to the given format. + + Returns: + A ``otTables.PairPos`` object. + """ + self = ot.PairPos() + self.Format = 1 + valueFormat1 = self.ValueFormat1 = _getValueFormat(valueFormat1, pairs.values(), 0) + valueFormat2 = self.ValueFormat2 = _getValueFormat(valueFormat2, pairs.values(), 1) + p = {} + for (glyphA, glyphB), (valA, valB) in pairs.items(): + p.setdefault(glyphA, []).append((glyphB, valA, valB)) + self.Coverage = buildCoverage({g for g, _ in pairs.keys()}, glyphMap) + self.PairSet = [] + for glyph in self.Coverage.glyphs: + ps = ot.PairSet() + ps.PairValueRecord = [] + self.PairSet.append(ps) + for glyph2, val1, val2 in sorted(p[glyph], key=lambda x: glyphMap[x[0]]): + pvr = ot.PairValueRecord() + pvr.SecondGlyph = glyph2 + pvr.Value1 = ( + ValueRecord(src=val1, valueFormat=valueFormat1) + if valueFormat1 + else None + ) + pvr.Value2 = ( + ValueRecord(src=val2, valueFormat=valueFormat2) + if valueFormat2 + else None + ) + ps.PairValueRecord.append(pvr) + ps.PairValueCount = len(ps.PairValueRecord) + self.PairSetCount = len(self.PairSet) + return self + + +def buildSinglePos(mapping, glyphMap): + """Builds a list of single adjustment (GPOS1) subtables. + + This builds a list of SinglePos subtables from a dictionary of glyph + names and their positioning adjustments. The format of the subtables are + determined to optimize the size of the resulting subtables. + See also :func:`buildSinglePosSubtable`. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead. + + Example:: + + mapping = { + "V": buildValue({ "xAdvance" : +5 }), + # ... + } + + subtables = buildSinglePos(pairs, font.getReverseGlyphMap()) + + Args: + mapping (dict): A mapping between glyphnames and + ``otTables.ValueRecord`` objects. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + A list of ``otTables.SinglePos`` objects. + """ + result, handled = [], set() + # In SinglePos format 1, the covered glyphs all share the same ValueRecord. + # In format 2, each glyph has its own ValueRecord, but these records + # all have the same properties (eg., all have an X but no Y placement). + coverages, masks, values = {}, {}, {} + for glyph, value in mapping.items(): + key = _getSinglePosValueKey(value) + coverages.setdefault(key, []).append(glyph) + masks.setdefault(key[0], []).append(key) + values[key] = value + + # If a ValueRecord is shared between multiple glyphs, we generate + # a SinglePos format 1 subtable; that is the most compact form. + for key, glyphs in coverages.items(): + # 5 ushorts is the length of introducing another sublookup + if len(glyphs) * _getSinglePosValueSize(key) > 5: + format1Mapping = {g: values[key] for g in glyphs} + result.append(buildSinglePosSubtable(format1Mapping, glyphMap)) + handled.add(key) + + # In the remaining ValueRecords, look for those whose valueFormat + # (the set of used properties) is shared between multiple records. + # These will get encoded in format 2. + for valueFormat, keys in masks.items(): + f2 = [k for k in keys if k not in handled] + if len(f2) > 1: + format2Mapping = {} + for k in f2: + format2Mapping.update((g, values[k]) for g in coverages[k]) + result.append(buildSinglePosSubtable(format2Mapping, glyphMap)) + handled.update(f2) + + # The remaining ValueRecords are only used by a few glyphs, normally + # one. We encode these in format 1 again. + for key, glyphs in coverages.items(): + if key not in handled: + for g in glyphs: + st = buildSinglePosSubtable({g: values[key]}, glyphMap) + result.append(st) + + # When the OpenType layout engine traverses the subtables, it will + # stop after the first matching subtable. Therefore, we sort the + # resulting subtables by decreasing coverage size; this increases + # the chance that the layout engine can do an early exit. (Of course, + # this would only be true if all glyphs were equally frequent, which + # is not really the case; but we do not know their distribution). + # If two subtables cover the same number of glyphs, we sort them + # by glyph ID so that our output is deterministic. + result.sort(key=lambda t: _getSinglePosTableKey(t, glyphMap)) + return result + + +def buildSinglePosSubtable(values, glyphMap): + """Builds a single adjustment (GPOS1) subtable. + + This builds a list of SinglePos subtables from a dictionary of glyph + names and their positioning adjustments. The format of the subtable is + determined to optimize the size of the output. + See also :func:`buildSinglePos`. + + Note that if you are implementing a layout compiler, you may find it more + flexible to use + :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead. + + Example:: + + mapping = { + "V": buildValue({ "xAdvance" : +5 }), + # ... + } + + subtable = buildSinglePos(pairs, font.getReverseGlyphMap()) + + Args: + mapping (dict): A mapping between glyphnames and + ``otTables.ValueRecord`` objects. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + A ``otTables.SinglePos`` object. + """ + self = ot.SinglePos() + self.Coverage = buildCoverage(values.keys(), glyphMap) + valueFormat = self.ValueFormat = reduce( + int.__or__, [v.getFormat() for v in values.values()], 0 + ) + valueRecords = [ + ValueRecord(src=values[g], valueFormat=valueFormat) + for g in self.Coverage.glyphs + ] + if all(v == valueRecords[0] for v in valueRecords): + self.Format = 1 + if self.ValueFormat != 0: + self.Value = valueRecords[0] + else: + self.Value = None + else: + self.Format = 2 + self.Value = valueRecords + self.ValueCount = len(self.Value) + return self + + +def _getSinglePosTableKey(subtable, glyphMap): + assert isinstance(subtable, ot.SinglePos), subtable + glyphs = subtable.Coverage.glyphs + return (-len(glyphs), glyphMap[glyphs[0]]) + + +def _getSinglePosValueKey(valueRecord): + # otBase.ValueRecord --> (2, ("YPlacement": 12)) + assert isinstance(valueRecord, ValueRecord), valueRecord + valueFormat, result = 0, [] + for name, value in valueRecord.__dict__.items(): + if isinstance(value, ot.Device): + result.append((name, _makeDeviceTuple(value))) + else: + result.append((name, value)) + valueFormat |= valueRecordFormatDict[name][0] + result.sort() + result.insert(0, valueFormat) + return tuple(result) + + +_DeviceTuple = namedtuple("_DeviceTuple", "DeltaFormat StartSize EndSize DeltaValue") + + +def _makeDeviceTuple(device): + # otTables.Device --> tuple, for making device tables unique + return _DeviceTuple( + device.DeltaFormat, + device.StartSize, + device.EndSize, + () if device.DeltaFormat & 0x8000 else tuple(device.DeltaValue), + ) + + +def _getSinglePosValueSize(valueKey): + # Returns how many ushorts this valueKey (short form of ValueRecord) takes up + count = 0 + for _, v in valueKey[1:]: + if isinstance(v, _DeviceTuple): + count += len(v.DeltaValue) + 3 + else: + count += 1 + return count + + +def buildValue(value): + """Builds a positioning value record. + + Value records are used to specify coordinates and adjustments for + positioning and attaching glyphs. Many of the positioning functions + in this library take ``otTables.ValueRecord`` objects as arguments. + This function builds value records from dictionaries. + + Args: + value (dict): A dictionary with zero or more of the following keys: + - ``xPlacement`` + - ``yPlacement`` + - ``xAdvance`` + - ``yAdvance`` + - ``xPlaDevice`` + - ``yPlaDevice`` + - ``xAdvDevice`` + - ``yAdvDevice`` + + Returns: + An ``otTables.ValueRecord`` object. + """ + self = ValueRecord() + for k, v in value.items(): + setattr(self, k, v) + return self + + +# GDEF + + +def buildAttachList(attachPoints, glyphMap): + """Builds an AttachList subtable. + + A GDEF table may contain an Attachment Point List table (AttachList) + which stores the contour indices of attachment points for glyphs with + attachment points. This routine builds AttachList subtables. + + Args: + attachPoints (dict): A mapping between glyph names and a list of + contour indices. + + Returns: + An ``otTables.AttachList`` object if attachment points are supplied, + or ``None`` otherwise. + """ + if not attachPoints: + return None + self = ot.AttachList() + self.Coverage = buildCoverage(attachPoints.keys(), glyphMap) + self.AttachPoint = [buildAttachPoint(attachPoints[g]) for g in self.Coverage.glyphs] + self.GlyphCount = len(self.AttachPoint) + return self + + +def buildAttachPoint(points): + # [4, 23, 41] --> otTables.AttachPoint + # Only used by above. + if not points: + return None + self = ot.AttachPoint() + self.PointIndex = sorted(set(points)) + self.PointCount = len(self.PointIndex) + return self + + +def buildCaretValueForCoord(coord): + # 500 --> otTables.CaretValue, format 1 + # (500, DeviceTable) --> otTables.CaretValue, format 3 + self = ot.CaretValue() + if isinstance(coord, tuple): + self.Format = 3 + self.Coordinate, self.DeviceTable = coord + else: + self.Format = 1 + self.Coordinate = coord + return self + + +def buildCaretValueForPoint(point): + # 4 --> otTables.CaretValue, format 2 + self = ot.CaretValue() + self.Format = 2 + self.CaretValuePoint = point + return self + + +def buildLigCaretList(coords, points, glyphMap): + """Builds a ligature caret list table. + + Ligatures appear as a single glyph representing multiple characters; however + when, for example, editing text containing a ``f_i`` ligature, the user may + want to place the cursor between the ``f`` and the ``i``. The ligature caret + list in the GDEF table specifies the position to display the "caret" (the + character insertion indicator, typically a flashing vertical bar) "inside" + the ligature to represent an insertion point. The insertion positions may + be specified either by coordinate or by contour point. + + Example:: + + coords = { + "f_f_i": [300, 600] # f|fi cursor at 300 units, ff|i cursor at 600. + } + points = { + "c_t": [28] # c|t cursor appears at coordinate of contour point 28. + } + ligcaretlist = buildLigCaretList(coords, points, font.getReverseGlyphMap()) + + Args: + coords: A mapping between glyph names and a list of coordinates for + the insertion point of each ligature component after the first one. + points: A mapping between glyph names and a list of contour points for + the insertion point of each ligature component after the first one. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns: + A ``otTables.LigCaretList`` object if any carets are present, or + ``None`` otherwise.""" + glyphs = set(coords.keys()) if coords else set() + if points: + glyphs.update(points.keys()) + carets = {g: buildLigGlyph(coords.get(g), points.get(g)) for g in glyphs} + carets = {g: c for g, c in carets.items() if c is not None} + if not carets: + return None + self = ot.LigCaretList() + self.Coverage = buildCoverage(carets.keys(), glyphMap) + self.LigGlyph = [carets[g] for g in self.Coverage.glyphs] + self.LigGlyphCount = len(self.LigGlyph) + return self + + +def buildLigGlyph(coords, points): + # ([500], [4]) --> otTables.LigGlyph; None for empty coords/points + carets = [] + if coords: + coords = sorted(coords, key=lambda c: c[0] if isinstance(c, tuple) else c) + carets.extend([buildCaretValueForCoord(c) for c in coords]) + if points: + carets.extend([buildCaretValueForPoint(p) for p in sorted(points)]) + if not carets: + return None + self = ot.LigGlyph() + self.CaretValue = carets + self.CaretCount = len(self.CaretValue) + return self + + +def buildMarkGlyphSetsDef(markSets, glyphMap): + """Builds a mark glyph sets definition table. + + OpenType Layout lookups may choose to use mark filtering sets to consider + or ignore particular combinations of marks. These sets are specified by + setting a flag on the lookup, but the mark filtering sets are defined in + the ``GDEF`` table. This routine builds the subtable containing the mark + glyph set definitions. + + Example:: + + set0 = set("acute", "grave") + set1 = set("caron", "grave") + + markglyphsets = buildMarkGlyphSetsDef([set0, set1], font.getReverseGlyphMap()) + + Args: + + markSets: A list of sets of glyphnames. + glyphMap: a glyph name to ID map, typically returned from + ``font.getReverseGlyphMap()``. + + Returns + An ``otTables.MarkGlyphSetsDef`` object. + """ + if not markSets: + return None + self = ot.MarkGlyphSetsDef() + self.MarkSetTableFormat = 1 + self.Coverage = [buildCoverage(m, glyphMap) for m in markSets] + self.MarkSetCount = len(self.Coverage) + return self + + +class ClassDefBuilder(object): + """Helper for building ClassDef tables.""" + + def __init__(self, useClass0): + self.classes_ = set() + self.glyphs_ = {} + self.useClass0_ = useClass0 + + def canAdd(self, glyphs): + if isinstance(glyphs, (set, frozenset)): + glyphs = sorted(glyphs) + glyphs = tuple(glyphs) + if glyphs in self.classes_: + return True + for glyph in glyphs: + if glyph in self.glyphs_: + return False + return True + + def add(self, glyphs): + if isinstance(glyphs, (set, frozenset)): + glyphs = sorted(glyphs) + glyphs = tuple(glyphs) + if glyphs in self.classes_: + return + self.classes_.add(glyphs) + for glyph in glyphs: + if glyph in self.glyphs_: + raise OpenTypeLibError( + f"Glyph {glyph} is already present in class.", None + ) + self.glyphs_[glyph] = glyphs + + def classes(self): + # In ClassDef1 tables, class id #0 does not need to be encoded + # because zero is the default. Therefore, we use id #0 for the + # glyph class that has the largest number of members. However, + # in other tables than ClassDef1, 0 means "every other glyph" + # so we should not use that ID for any real glyph classes; + # we implement this by inserting an empty set at position 0. + # + # TODO: Instead of counting the number of glyphs in each class, + # we should determine the encoded size. If the glyphs in a large + # class form a contiguous range, the encoding is actually quite + # compact, whereas a non-contiguous set might need a lot of bytes + # in the output file. We don't get this right with the key below. + result = sorted(self.classes_, key=lambda s: (-len(s), s)) + if not self.useClass0_: + result.insert(0, frozenset()) + return result + + def build(self): + glyphClasses = {} + for classID, glyphs in enumerate(self.classes()): + if classID == 0: + continue + for glyph in glyphs: + glyphClasses[glyph] = classID + classDef = ot.ClassDef() + classDef.classDefs = glyphClasses + return classDef + + +AXIS_VALUE_NEGATIVE_INFINITY = fixedToFloat(-0x80000000, 16) +AXIS_VALUE_POSITIVE_INFINITY = fixedToFloat(0x7FFFFFFF, 16) + +STATName = Union[int, str, Dict[str, str]] +"""A raw name ID, English name, or multilingual name.""" + + +def buildStatTable( + ttFont: TTFont, + axes, + locations=None, + elidedFallbackName: Union[STATName, STATNameStatement] = 2, + windowsNames: bool = True, + macNames: bool = True, +) -> None: + """Add a 'STAT' table to 'ttFont'. + + 'axes' is a list of dictionaries describing axes and their + values. + + Example:: + + axes = [ + dict( + tag="wght", + name="Weight", + ordering=0, # optional + values=[ + dict(value=100, name='Thin'), + dict(value=300, name='Light'), + dict(value=400, name='Regular', flags=0x2), + dict(value=900, name='Black'), + ], + ) + ] + + Each axis dict must have 'tag' and 'name' items. 'tag' maps + to the 'AxisTag' field. 'name' can be a name ID (int), a string, + or a dictionary containing multilingual names (see the + addMultilingualName() name table method), and will translate to + the AxisNameID field. + + An axis dict may contain an 'ordering' item that maps to the + AxisOrdering field. If omitted, the order of the axes list is + used to calculate AxisOrdering fields. + + The axis dict may contain a 'values' item, which is a list of + dictionaries describing AxisValue records belonging to this axis. + + Each value dict must have a 'name' item, which can be a name ID + (int), a string, or a dictionary containing multilingual names, + like the axis name. It translates to the ValueNameID field. + + Optionally the value dict can contain a 'flags' item. It maps to + the AxisValue Flags field, and will be 0 when omitted. + + The format of the AxisValue is determined by the remaining contents + of the value dictionary: + + If the value dict contains a 'value' item, an AxisValue record + Format 1 is created. If in addition to the 'value' item it contains + a 'linkedValue' item, an AxisValue record Format 3 is built. + + If the value dict contains a 'nominalValue' item, an AxisValue + record Format 2 is built. Optionally it may contain 'rangeMinValue' + and 'rangeMaxValue' items. These map to -Infinity and +Infinity + respectively if omitted. + + You cannot specify Format 4 AxisValue tables this way, as they are + not tied to a single axis, and specify a name for a location that + is defined by multiple axes values. Instead, you need to supply the + 'locations' argument. + + The optional 'locations' argument specifies AxisValue Format 4 + tables. It should be a list of dicts, where each dict has a 'name' + item, which works just like the value dicts above, an optional + 'flags' item (defaulting to 0x0), and a 'location' dict. A + location dict key is an axis tag, and the associated value is the + location on the specified axis. They map to the AxisIndex and Value + fields of the AxisValueRecord. + + Example:: + + locations = [ + dict(name='Regular ABCD', location=dict(wght=300, ABCD=100)), + dict(name='Bold ABCD XYZ', location=dict(wght=600, ABCD=200)), + ] + + The optional 'elidedFallbackName' argument can be a name ID (int), + a string, a dictionary containing multilingual names, or a list of + STATNameStatements. It translates to the ElidedFallbackNameID field. + + The 'ttFont' argument must be a TTFont instance that already has a + 'name' table. If a 'STAT' table already exists, it will be + overwritten by the newly created one. + """ + ttFont["STAT"] = ttLib.newTable("STAT") + statTable = ttFont["STAT"].table = ot.STAT() + statTable.ElidedFallbackNameID = _addName( + ttFont, elidedFallbackName, windows=windowsNames, mac=macNames + ) + + # 'locations' contains data for AxisValue Format 4 + axisRecords, axisValues = _buildAxisRecords( + axes, ttFont, windowsNames=windowsNames, macNames=macNames + ) + if not locations: + statTable.Version = 0x00010001 + else: + # We'll be adding Format 4 AxisValue records, which + # requires a higher table version + statTable.Version = 0x00010002 + multiAxisValues = _buildAxisValuesFormat4( + locations, axes, ttFont, windowsNames=windowsNames, macNames=macNames + ) + axisValues = multiAxisValues + axisValues + ttFont["name"].names.sort() + + # Store AxisRecords + axisRecordArray = ot.AxisRecordArray() + axisRecordArray.Axis = axisRecords + # XXX these should not be hard-coded but computed automatically + statTable.DesignAxisRecordSize = 8 + statTable.DesignAxisRecord = axisRecordArray + statTable.DesignAxisCount = len(axisRecords) + + statTable.AxisValueCount = 0 + statTable.AxisValueArray = None + if axisValues: + # Store AxisValueRecords + axisValueArray = ot.AxisValueArray() + axisValueArray.AxisValue = axisValues + statTable.AxisValueArray = axisValueArray + statTable.AxisValueCount = len(axisValues) + + +def _buildAxisRecords(axes, ttFont, windowsNames=True, macNames=True): + axisRecords = [] + axisValues = [] + for axisRecordIndex, axisDict in enumerate(axes): + axis = ot.AxisRecord() + axis.AxisTag = axisDict["tag"] + axis.AxisNameID = _addName( + ttFont, axisDict["name"], 256, windows=windowsNames, mac=macNames + ) + axis.AxisOrdering = axisDict.get("ordering", axisRecordIndex) + axisRecords.append(axis) + + for axisVal in axisDict.get("values", ()): + axisValRec = ot.AxisValue() + axisValRec.AxisIndex = axisRecordIndex + axisValRec.Flags = axisVal.get("flags", 0) + axisValRec.ValueNameID = _addName( + ttFont, axisVal["name"], windows=windowsNames, mac=macNames + ) + + if "value" in axisVal: + axisValRec.Value = axisVal["value"] + if "linkedValue" in axisVal: + axisValRec.Format = 3 + axisValRec.LinkedValue = axisVal["linkedValue"] + else: + axisValRec.Format = 1 + elif "nominalValue" in axisVal: + axisValRec.Format = 2 + axisValRec.NominalValue = axisVal["nominalValue"] + axisValRec.RangeMinValue = axisVal.get( + "rangeMinValue", AXIS_VALUE_NEGATIVE_INFINITY + ) + axisValRec.RangeMaxValue = axisVal.get( + "rangeMaxValue", AXIS_VALUE_POSITIVE_INFINITY + ) + else: + raise ValueError("Can't determine format for AxisValue") + + axisValues.append(axisValRec) + return axisRecords, axisValues + + +def _buildAxisValuesFormat4(locations, axes, ttFont, windowsNames=True, macNames=True): + axisTagToIndex = {} + for axisRecordIndex, axisDict in enumerate(axes): + axisTagToIndex[axisDict["tag"]] = axisRecordIndex + + axisValues = [] + for axisLocationDict in locations: + axisValRec = ot.AxisValue() + axisValRec.Format = 4 + axisValRec.ValueNameID = _addName( + ttFont, axisLocationDict["name"], windows=windowsNames, mac=macNames + ) + axisValRec.Flags = axisLocationDict.get("flags", 0) + axisValueRecords = [] + for tag, value in axisLocationDict["location"].items(): + avr = ot.AxisValueRecord() + avr.AxisIndex = axisTagToIndex[tag] + avr.Value = value + axisValueRecords.append(avr) + axisValueRecords.sort(key=lambda avr: avr.AxisIndex) + axisValRec.AxisCount = len(axisValueRecords) + axisValRec.AxisValueRecord = axisValueRecords + axisValues.append(axisValRec) + return axisValues + + +def _addName( + ttFont: TTFont, + value: Union[STATName, STATNameStatement], + minNameID: int = 0, + windows: bool = True, + mac: bool = True, +) -> int: + nameTable = ttFont["name"] + if isinstance(value, int): + # Already a nameID + return value + if isinstance(value, str): + names = dict(en=value) + elif isinstance(value, dict): + names = value + elif isinstance(value, list): + nameID = nameTable._findUnusedNameID() + for nameRecord in value: + if isinstance(nameRecord, STATNameStatement): + nameTable.setName( + nameRecord.string, + nameID, + nameRecord.platformID, + nameRecord.platEncID, + nameRecord.langID, + ) + else: + raise TypeError("value must be a list of STATNameStatements") + return nameID + else: + raise TypeError("value must be int, str, dict or list") + return nameTable.addMultilingualName( + names, ttFont=ttFont, windows=windows, mac=mac, minNameID=minNameID + ) + + +def buildMathTable( + ttFont, + constants=None, + italicsCorrections=None, + topAccentAttachments=None, + extendedShapes=None, + mathKerns=None, + minConnectorOverlap=0, + vertGlyphVariants=None, + horizGlyphVariants=None, + vertGlyphAssembly=None, + horizGlyphAssembly=None, +): + """ + Add a 'MATH' table to 'ttFont'. + + 'constants' is a dictionary of math constants. The keys are the constant + names from the MATH table specification (with capital first letter), and the + values are the constant values as numbers. + + 'italicsCorrections' is a dictionary of italic corrections. The keys are the + glyph names, and the values are the italic corrections as numbers. + + 'topAccentAttachments' is a dictionary of top accent attachments. The keys + are the glyph names, and the values are the top accent horizontal positions + as numbers. + + 'extendedShapes' is a set of extended shape glyphs. + + 'mathKerns' is a dictionary of math kerns. The keys are the glyph names, and + the values are dictionaries. The keys of these dictionaries are the side + names ('TopRight', 'TopLeft', 'BottomRight', 'BottomLeft'), and the values + are tuples of two lists. The first list contains the correction heights as + numbers, and the second list contains the kern values as numbers. + + 'minConnectorOverlap' is the minimum connector overlap as a number. + + 'vertGlyphVariants' is a dictionary of vertical glyph variants. The keys are + the glyph names, and the values are tuples of glyph name and full advance height. + + 'horizGlyphVariants' is a dictionary of horizontal glyph variants. The keys + are the glyph names, and the values are tuples of glyph name and full + advance width. + + 'vertGlyphAssembly' is a dictionary of vertical glyph assemblies. The keys + are the glyph names, and the values are tuples of assembly parts and italics + correction. The assembly parts are tuples of glyph name, flags, start + connector length, end connector length, and full advance height. + + 'horizGlyphAssembly' is a dictionary of horizontal glyph assemblies. The + keys are the glyph names, and the values are tuples of assembly parts + and italics correction. The assembly parts are tuples of glyph name, flags, + start connector length, end connector length, and full advance width. + + Where a number is expected, an integer or a float can be used. The floats + will be rounded. + + Example:: + + constants = { + "ScriptPercentScaleDown": 70, + "ScriptScriptPercentScaleDown": 50, + "DelimitedSubFormulaMinHeight": 24, + "DisplayOperatorMinHeight": 60, + ... + } + italicsCorrections = { + "fitalic-math": 100, + "fbolditalic-math": 120, + ... + } + topAccentAttachments = { + "circumflexcomb": 500, + "acutecomb": 400, + "A": 300, + "B": 340, + ... + } + extendedShapes = {"parenleft", "parenright", ...} + mathKerns = { + "A": { + "TopRight": ([-50, -100], [10, 20, 30]), + "TopLeft": ([50, 100], [10, 20, 30]), + ... + }, + ... + } + vertGlyphVariants = { + "parenleft": [("parenleft", 700), ("parenleft.size1", 1000), ...], + "parenright": [("parenright", 700), ("parenright.size1", 1000), ...], + ... + } + vertGlyphAssembly = { + "braceleft": [ + ( + ("braceleft.bottom", 0, 0, 200, 500), + ("braceleft.extender", 1, 200, 200, 200)), + ("braceleft.middle", 0, 100, 100, 700), + ("braceleft.extender", 1, 200, 200, 200), + ("braceleft.top", 0, 200, 0, 500), + ), + 100, + ], + ... + } + """ + glyphMap = ttFont.getReverseGlyphMap() + + ttFont["MATH"] = math = ttLib.newTable("MATH") + math.table = table = ot.MATH() + table.Version = 0x00010000 + table.populateDefaults() + + table.MathConstants = _buildMathConstants(constants) + table.MathGlyphInfo = _buildMathGlyphInfo( + glyphMap, + italicsCorrections, + topAccentAttachments, + extendedShapes, + mathKerns, + ) + table.MathVariants = _buildMathVariants( + glyphMap, + minConnectorOverlap, + vertGlyphVariants, + horizGlyphVariants, + vertGlyphAssembly, + horizGlyphAssembly, + ) + + +def _buildMathConstants(constants): + if not constants: + return None + + mathConstants = ot.MathConstants() + for conv in mathConstants.getConverters(): + value = otRound(constants.get(conv.name, 0)) + if conv.tableClass: + assert issubclass(conv.tableClass, ot.MathValueRecord) + value = _mathValueRecord(value) + setattr(mathConstants, conv.name, value) + return mathConstants + + +def _buildMathGlyphInfo( + glyphMap, + italicsCorrections, + topAccentAttachments, + extendedShapes, + mathKerns, +): + if not any([extendedShapes, italicsCorrections, topAccentAttachments, mathKerns]): + return None + + info = ot.MathGlyphInfo() + info.populateDefaults() + + if italicsCorrections: + coverage = buildCoverage(italicsCorrections.keys(), glyphMap) + info.MathItalicsCorrectionInfo = ot.MathItalicsCorrectionInfo() + info.MathItalicsCorrectionInfo.Coverage = coverage + info.MathItalicsCorrectionInfo.ItalicsCorrectionCount = len(coverage.glyphs) + info.MathItalicsCorrectionInfo.ItalicsCorrection = [ + _mathValueRecord(italicsCorrections[n]) for n in coverage.glyphs + ] + + if topAccentAttachments: + coverage = buildCoverage(topAccentAttachments.keys(), glyphMap) + info.MathTopAccentAttachment = ot.MathTopAccentAttachment() + info.MathTopAccentAttachment.TopAccentCoverage = coverage + info.MathTopAccentAttachment.TopAccentAttachmentCount = len(coverage.glyphs) + info.MathTopAccentAttachment.TopAccentAttachment = [ + _mathValueRecord(topAccentAttachments[n]) for n in coverage.glyphs + ] + + if extendedShapes: + info.ExtendedShapeCoverage = buildCoverage(extendedShapes, glyphMap) + + if mathKerns: + coverage = buildCoverage(mathKerns.keys(), glyphMap) + info.MathKernInfo = ot.MathKernInfo() + info.MathKernInfo.MathKernCoverage = coverage + info.MathKernInfo.MathKernCount = len(coverage.glyphs) + info.MathKernInfo.MathKernInfoRecords = [] + for glyph in coverage.glyphs: + record = ot.MathKernInfoRecord() + for side in {"TopRight", "TopLeft", "BottomRight", "BottomLeft"}: + if side in mathKerns[glyph]: + correctionHeights, kernValues = mathKerns[glyph][side] + assert len(correctionHeights) == len(kernValues) - 1 + kern = ot.MathKern() + kern.HeightCount = len(correctionHeights) + kern.CorrectionHeight = [ + _mathValueRecord(h) for h in correctionHeights + ] + kern.KernValue = [_mathValueRecord(v) for v in kernValues] + setattr(record, f"{side}MathKern", kern) + info.MathKernInfo.MathKernInfoRecords.append(record) + + return info + + +def _buildMathVariants( + glyphMap, + minConnectorOverlap, + vertGlyphVariants, + horizGlyphVariants, + vertGlyphAssembly, + horizGlyphAssembly, +): + if not any( + [vertGlyphVariants, horizGlyphVariants, vertGlyphAssembly, horizGlyphAssembly] + ): + return None + + variants = ot.MathVariants() + variants.populateDefaults() + + variants.MinConnectorOverlap = minConnectorOverlap + + if vertGlyphVariants or vertGlyphAssembly: + variants.VertGlyphCoverage, variants.VertGlyphConstruction = ( + _buildMathGlyphConstruction( + glyphMap, + vertGlyphVariants, + vertGlyphAssembly, + ) + ) + + if horizGlyphVariants or horizGlyphAssembly: + variants.HorizGlyphCoverage, variants.HorizGlyphConstruction = ( + _buildMathGlyphConstruction( + glyphMap, + horizGlyphVariants, + horizGlyphAssembly, + ) + ) + + return variants + + +def _buildMathGlyphConstruction(glyphMap, variants, assemblies): + glyphs = set() + if variants: + glyphs.update(variants.keys()) + if assemblies: + glyphs.update(assemblies.keys()) + coverage = buildCoverage(glyphs, glyphMap) + constructions = [] + + for glyphName in coverage.glyphs: + construction = ot.MathGlyphConstruction() + construction.populateDefaults() + + if variants and glyphName in variants: + construction.VariantCount = len(variants[glyphName]) + construction.MathGlyphVariantRecord = [] + for variantName, advance in variants[glyphName]: + record = ot.MathGlyphVariantRecord() + record.VariantGlyph = variantName + record.AdvanceMeasurement = otRound(advance) + construction.MathGlyphVariantRecord.append(record) + + if assemblies and glyphName in assemblies: + parts, ic = assemblies[glyphName] + construction.GlyphAssembly = ot.GlyphAssembly() + construction.GlyphAssembly.ItalicsCorrection = _mathValueRecord(ic) + construction.GlyphAssembly.PartCount = len(parts) + construction.GlyphAssembly.PartRecords = [] + for part in parts: + part_name, flags, start, end, advance = part + record = ot.GlyphPartRecord() + record.glyph = part_name + record.PartFlags = int(flags) + record.StartConnectorLength = otRound(start) + record.EndConnectorLength = otRound(end) + record.FullAdvance = otRound(advance) + construction.GlyphAssembly.PartRecords.append(record) + + constructions.append(construction) + + return coverage, constructions + + +def _mathValueRecord(value): + value_record = ot.MathValueRecord() + value_record.Value = otRound(value) + return value_record diff --git a/shared/package-files/38/383022b2fa827deb3c07815ec8cfcf83d1d8dd90e7132682893e01c72ce873ac/langhungarianmodel.py b/shared/package-files/38/383022b2fa827deb3c07815ec8cfcf83d1d8dd90e7132682893e01c72ce873ac/langhungarianmodel.py new file mode 100644 index 0000000000000000000000000000000000000000..24a097f5207993012f26eba9e2368022b6645f88 --- /dev/null +++ b/shared/package-files/38/383022b2fa827deb3c07815ec8cfcf83d1d8dd90e7132682893e01c72ce873ac/langhungarianmodel.py @@ -0,0 +1,4650 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from chardet.sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +HUNGARIAN_LANG_MODEL = { + 28: { # 'A' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 2, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 2, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 2, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 1, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 1, # 'Á' + 44: 0, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 40: { # 'B' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 0, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 3, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 54: { # 'C' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 0, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 3, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 45: { # 'D' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 0, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 1, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 32: { # 'E' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 2, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 1, # 't' + 21: 2, # 'u' + 19: 1, # 'v' + 62: 1, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 50: { # 'F' + 28: 1, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 0, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 49: { # 'G' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 2, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 38: { # 'H' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 0, # 'D' + 32: 1, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 1, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 1, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 0, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 2, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 2, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 39: { # 'I' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 2, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 0, # 'e' + 27: 1, # 'f' + 12: 2, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 53: { # 'J' + 28: 2, # 'A' + 40: 0, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 1, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 0, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 36: { # 'K' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 2, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 41: { # 'L' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 34: { # 'M' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 3, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 1, # 'ű' + }, + 35: { # 'N' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 2, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 2, # 'Y' + 52: 1, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 47: { # 'O' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 2, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 2, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 1, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 46: { # 'P' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 0, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 3, # 'á' + 15: 2, # 'é' + 30: 0, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 43: { # 'R' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 2, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 2, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 33: { # 'S' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 3, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 1, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 1, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 37: { # 'T' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 1, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 2, # 'Á' + 44: 2, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 57: { # 'U' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 2, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 48: { # 'V' + 28: 2, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 0, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 2, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 55: { # 'Y' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 2, # 'Z' + 2: 1, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 52: { # 'Z' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 1, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 1, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 2, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 2: { # 'a' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 2, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 2, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 18: { # 'b' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 2, # 's' + 3: 1, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 26: { # 'c' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 1, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 1, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 2, # 't' + 21: 2, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 2, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 17: { # 'd' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 2, # 'k' + 6: 1, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 1: { # 'e' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 3, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 2, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 2, # 'u' + 19: 3, # 'v' + 62: 2, # 'x' + 16: 2, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 27: { # 'f' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 3, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 2, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 3, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 12: { # 'g' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 2, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 2, # 'k' + 6: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 3, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 20: { # 'h' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 2, # 's' + 3: 1, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 9: { # 'i' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 3, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 2, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 3, # 'ó' + 24: 1, # 'ö' + 31: 2, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 1, # 'ű' + }, + 22: { # 'j' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 1, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 1, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 7: { # 'k' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 2, # 'ó' + 24: 3, # 'ö' + 31: 1, # 'ú' + 29: 3, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 6: { # 'l' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 1, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 3, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 3, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 3, # 'ő' + 56: 1, # 'ű' + }, + 13: { # 'm' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 1, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 3, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 2, # 'ű' + }, + 4: { # 'n' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 1, # 'x' + 16: 3, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 8: { # 'o' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 2, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 23: { # 'p' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 10: { # 'r' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 2, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 2, # 'ű' + }, + 5: { # 's' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 2, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 2, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 3: { # 't' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 1, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 3, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 3, # 'ü' + 42: 3, # 'ő' + 56: 2, # 'ű' + }, + 21: { # 'u' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 2, # 'b' + 26: 2, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 1, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 0, # 'ö' + 31: 1, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 19: { # 'v' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 2, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 62: { # 'x' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 16: { # 'y' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 2, # 'ű' + }, + 11: { # 'z' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 2, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 51: { # 'Á' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 44: { # 'É' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 0, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 61: { # 'Í' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 0, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 2, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 1, # 'm' + 4: 0, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 0, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 58: { # 'Ó' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 2, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 0, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 59: { # 'Ö' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 0, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 60: { # 'Ú' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 2, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 2, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 63: { # 'Ü' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 0, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 14: { # 'á' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 1, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 2, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 2, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 15: { # 'é' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 3, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 0, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 30: { # 'í' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 2, # 's' + 3: 3, # 't' + 21: 0, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 25: { # 'ó' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 3, # 'd' + 1: 1, # 'e' + 27: 2, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 1, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 24: { # 'ö' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 0, # 'a' + 18: 3, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 0, # 'e' + 27: 1, # 'f' + 12: 2, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 0, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 0, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 31: { # 'ú' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 3, # 'j' + 7: 1, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 2, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 29: { # 'ü' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 3, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 0, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 42: { # 'ő' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 56: { # 'ű' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 0, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +WINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 28, # 'A' + 66: 40, # 'B' + 67: 54, # 'C' + 68: 45, # 'D' + 69: 32, # 'E' + 70: 50, # 'F' + 71: 49, # 'G' + 72: 38, # 'H' + 73: 39, # 'I' + 74: 53, # 'J' + 75: 36, # 'K' + 76: 41, # 'L' + 77: 34, # 'M' + 78: 35, # 'N' + 79: 47, # 'O' + 80: 46, # 'P' + 81: 72, # 'Q' + 82: 43, # 'R' + 83: 33, # 'S' + 84: 37, # 'T' + 85: 57, # 'U' + 86: 48, # 'V' + 87: 64, # 'W' + 88: 68, # 'X' + 89: 55, # 'Y' + 90: 52, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 2, # 'a' + 98: 18, # 'b' + 99: 26, # 'c' + 100: 17, # 'd' + 101: 1, # 'e' + 102: 27, # 'f' + 103: 12, # 'g' + 104: 20, # 'h' + 105: 9, # 'i' + 106: 22, # 'j' + 107: 7, # 'k' + 108: 6, # 'l' + 109: 13, # 'm' + 110: 4, # 'n' + 111: 8, # 'o' + 112: 23, # 'p' + 113: 67, # 'q' + 114: 10, # 'r' + 115: 5, # 's' + 116: 3, # 't' + 117: 21, # 'u' + 118: 19, # 'v' + 119: 65, # 'w' + 120: 62, # 'x' + 121: 16, # 'y' + 122: 11, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 161, # '€' + 129: 162, # None + 130: 163, # '‚' + 131: 164, # None + 132: 165, # '„' + 133: 166, # '…' + 134: 167, # '†' + 135: 168, # '‡' + 136: 169, # None + 137: 170, # '‰' + 138: 171, # 'Š' + 139: 172, # '‹' + 140: 173, # 'Ś' + 141: 174, # 'Ť' + 142: 175, # 'Ž' + 143: 176, # 'Ź' + 144: 177, # None + 145: 178, # '‘' + 146: 179, # '’' + 147: 180, # '“' + 148: 78, # '”' + 149: 181, # '•' + 150: 69, # '–' + 151: 182, # '—' + 152: 183, # None + 153: 184, # '™' + 154: 185, # 'š' + 155: 186, # '›' + 156: 187, # 'ś' + 157: 188, # 'ť' + 158: 189, # 'ž' + 159: 190, # 'ź' + 160: 191, # '\xa0' + 161: 192, # 'ˇ' + 162: 193, # '˘' + 163: 194, # 'Ł' + 164: 195, # '¤' + 165: 196, # 'Ą' + 166: 197, # '¦' + 167: 76, # '§' + 168: 198, # '¨' + 169: 199, # '©' + 170: 200, # 'Ş' + 171: 201, # '«' + 172: 202, # '¬' + 173: 203, # '\xad' + 174: 204, # '®' + 175: 205, # 'Ż' + 176: 81, # '°' + 177: 206, # '±' + 178: 207, # '˛' + 179: 208, # 'ł' + 180: 209, # '´' + 181: 210, # 'µ' + 182: 211, # '¶' + 183: 212, # '·' + 184: 213, # '¸' + 185: 214, # 'ą' + 186: 215, # 'ş' + 187: 216, # '»' + 188: 217, # 'Ľ' + 189: 218, # '˝' + 190: 219, # 'ľ' + 191: 220, # 'ż' + 192: 221, # 'Ŕ' + 193: 51, # 'Á' + 194: 83, # 'Â' + 195: 222, # 'Ă' + 196: 80, # 'Ä' + 197: 223, # 'Ĺ' + 198: 224, # 'Ć' + 199: 225, # 'Ç' + 200: 226, # 'Č' + 201: 44, # 'É' + 202: 227, # 'Ę' + 203: 228, # 'Ë' + 204: 229, # 'Ě' + 205: 61, # 'Í' + 206: 230, # 'Î' + 207: 231, # 'Ď' + 208: 232, # 'Đ' + 209: 233, # 'Ń' + 210: 234, # 'Ň' + 211: 58, # 'Ó' + 212: 235, # 'Ô' + 213: 66, # 'Ő' + 214: 59, # 'Ö' + 215: 236, # '×' + 216: 237, # 'Ř' + 217: 238, # 'Ů' + 218: 60, # 'Ú' + 219: 70, # 'Ű' + 220: 63, # 'Ü' + 221: 239, # 'Ý' + 222: 240, # 'Ţ' + 223: 241, # 'ß' + 224: 84, # 'ŕ' + 225: 14, # 'á' + 226: 75, # 'â' + 227: 242, # 'ă' + 228: 71, # 'ä' + 229: 82, # 'ĺ' + 230: 243, # 'ć' + 231: 73, # 'ç' + 232: 244, # 'č' + 233: 15, # 'é' + 234: 85, # 'ę' + 235: 79, # 'ë' + 236: 86, # 'ě' + 237: 30, # 'í' + 238: 77, # 'î' + 239: 87, # 'ď' + 240: 245, # 'đ' + 241: 246, # 'ń' + 242: 247, # 'ň' + 243: 25, # 'ó' + 244: 74, # 'ô' + 245: 42, # 'ő' + 246: 24, # 'ö' + 247: 248, # '÷' + 248: 249, # 'ř' + 249: 250, # 'ů' + 250: 31, # 'ú' + 251: 56, # 'ű' + 252: 29, # 'ü' + 253: 251, # 'ý' + 254: 252, # 'ţ' + 255: 253, # '˙' +} + +WINDOWS_1250_HUNGARIAN_MODEL = SingleByteCharSetModel(charset_name='windows-1250', + language='Hungarian', + char_to_order_map=WINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER, + language_model=HUNGARIAN_LANG_MODEL, + typical_positive_ratio=0.947368, + keep_ascii_letters=True, + alphabet='ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű') + +ISO_8859_2_HUNGARIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 28, # 'A' + 66: 40, # 'B' + 67: 54, # 'C' + 68: 45, # 'D' + 69: 32, # 'E' + 70: 50, # 'F' + 71: 49, # 'G' + 72: 38, # 'H' + 73: 39, # 'I' + 74: 53, # 'J' + 75: 36, # 'K' + 76: 41, # 'L' + 77: 34, # 'M' + 78: 35, # 'N' + 79: 47, # 'O' + 80: 46, # 'P' + 81: 71, # 'Q' + 82: 43, # 'R' + 83: 33, # 'S' + 84: 37, # 'T' + 85: 57, # 'U' + 86: 48, # 'V' + 87: 64, # 'W' + 88: 68, # 'X' + 89: 55, # 'Y' + 90: 52, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 2, # 'a' + 98: 18, # 'b' + 99: 26, # 'c' + 100: 17, # 'd' + 101: 1, # 'e' + 102: 27, # 'f' + 103: 12, # 'g' + 104: 20, # 'h' + 105: 9, # 'i' + 106: 22, # 'j' + 107: 7, # 'k' + 108: 6, # 'l' + 109: 13, # 'm' + 110: 4, # 'n' + 111: 8, # 'o' + 112: 23, # 'p' + 113: 67, # 'q' + 114: 10, # 'r' + 115: 5, # 's' + 116: 3, # 't' + 117: 21, # 'u' + 118: 19, # 'v' + 119: 65, # 'w' + 120: 62, # 'x' + 121: 16, # 'y' + 122: 11, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 159, # '\x80' + 129: 160, # '\x81' + 130: 161, # '\x82' + 131: 162, # '\x83' + 132: 163, # '\x84' + 133: 164, # '\x85' + 134: 165, # '\x86' + 135: 166, # '\x87' + 136: 167, # '\x88' + 137: 168, # '\x89' + 138: 169, # '\x8a' + 139: 170, # '\x8b' + 140: 171, # '\x8c' + 141: 172, # '\x8d' + 142: 173, # '\x8e' + 143: 174, # '\x8f' + 144: 175, # '\x90' + 145: 176, # '\x91' + 146: 177, # '\x92' + 147: 178, # '\x93' + 148: 179, # '\x94' + 149: 180, # '\x95' + 150: 181, # '\x96' + 151: 182, # '\x97' + 152: 183, # '\x98' + 153: 184, # '\x99' + 154: 185, # '\x9a' + 155: 186, # '\x9b' + 156: 187, # '\x9c' + 157: 188, # '\x9d' + 158: 189, # '\x9e' + 159: 190, # '\x9f' + 160: 191, # '\xa0' + 161: 192, # 'Ą' + 162: 193, # '˘' + 163: 194, # 'Ł' + 164: 195, # '¤' + 165: 196, # 'Ľ' + 166: 197, # 'Ś' + 167: 75, # '§' + 168: 198, # '¨' + 169: 199, # 'Š' + 170: 200, # 'Ş' + 171: 201, # 'Ť' + 172: 202, # 'Ź' + 173: 203, # '\xad' + 174: 204, # 'Ž' + 175: 205, # 'Ż' + 176: 79, # '°' + 177: 206, # 'ą' + 178: 207, # '˛' + 179: 208, # 'ł' + 180: 209, # '´' + 181: 210, # 'ľ' + 182: 211, # 'ś' + 183: 212, # 'ˇ' + 184: 213, # '¸' + 185: 214, # 'š' + 186: 215, # 'ş' + 187: 216, # 'ť' + 188: 217, # 'ź' + 189: 218, # '˝' + 190: 219, # 'ž' + 191: 220, # 'ż' + 192: 221, # 'Ŕ' + 193: 51, # 'Á' + 194: 81, # 'Â' + 195: 222, # 'Ă' + 196: 78, # 'Ä' + 197: 223, # 'Ĺ' + 198: 224, # 'Ć' + 199: 225, # 'Ç' + 200: 226, # 'Č' + 201: 44, # 'É' + 202: 227, # 'Ę' + 203: 228, # 'Ë' + 204: 229, # 'Ě' + 205: 61, # 'Í' + 206: 230, # 'Î' + 207: 231, # 'Ď' + 208: 232, # 'Đ' + 209: 233, # 'Ń' + 210: 234, # 'Ň' + 211: 58, # 'Ó' + 212: 235, # 'Ô' + 213: 66, # 'Ő' + 214: 59, # 'Ö' + 215: 236, # '×' + 216: 237, # 'Ř' + 217: 238, # 'Ů' + 218: 60, # 'Ú' + 219: 69, # 'Ű' + 220: 63, # 'Ü' + 221: 239, # 'Ý' + 222: 240, # 'Ţ' + 223: 241, # 'ß' + 224: 82, # 'ŕ' + 225: 14, # 'á' + 226: 74, # 'â' + 227: 242, # 'ă' + 228: 70, # 'ä' + 229: 80, # 'ĺ' + 230: 243, # 'ć' + 231: 72, # 'ç' + 232: 244, # 'č' + 233: 15, # 'é' + 234: 83, # 'ę' + 235: 77, # 'ë' + 236: 84, # 'ě' + 237: 30, # 'í' + 238: 76, # 'î' + 239: 85, # 'ď' + 240: 245, # 'đ' + 241: 246, # 'ń' + 242: 247, # 'ň' + 243: 25, # 'ó' + 244: 73, # 'ô' + 245: 42, # 'ő' + 246: 24, # 'ö' + 247: 248, # '÷' + 248: 249, # 'ř' + 249: 250, # 'ů' + 250: 31, # 'ú' + 251: 56, # 'ű' + 252: 29, # 'ü' + 253: 251, # 'ý' + 254: 252, # 'ţ' + 255: 253, # '˙' +} + +ISO_8859_2_HUNGARIAN_MODEL = SingleByteCharSetModel(charset_name='ISO-8859-2', + language='Hungarian', + char_to_order_map=ISO_8859_2_HUNGARIAN_CHAR_TO_ORDER, + language_model=HUNGARIAN_LANG_MODEL, + typical_positive_ratio=0.947368, + keep_ascii_letters=True, + alphabet='ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű') + diff --git a/shared/package-files/38/3832f92b2cd36c5649a76ff60d361f1a8769d2e15df695e777f7b78682212e77/slow_conv_dilated2d_ops.h b/shared/package-files/38/3832f92b2cd36c5649a76ff60d361f1a8769d2e15df695e777f7b78682212e77/slow_conv_dilated2d_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..2faa6c605fe1030f66d48b853006c0d96818cb12 --- /dev/null +++ b/shared/package-files/38/3832f92b2cd36c5649a76ff60d361f1a8769d2e15df695e777f7b78682212e77/slow_conv_dilated2d_ops.h @@ -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 slow_conv_dilated2d { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, const c10::optional &, c10::SymIntArrayRef, 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::slow_conv_dilated2d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "slow_conv_dilated2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation); +}; + +struct TORCH_API slow_conv_dilated2d_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, const c10::optional &, c10::SymIntArrayRef, 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::slow_conv_dilated2d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "slow_conv_dilated2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/3834b0db1d4a1d7374bdd2879b8be7a2f67192869f73021d51e93437c11dbb98/_upfirdn.py b/shared/package-files/38/3834b0db1d4a1d7374bdd2879b8be7a2f67192869f73021d51e93437c11dbb98/_upfirdn.py new file mode 100644 index 0000000000000000000000000000000000000000..d64cc142ff194b1404e380507289ddbaffab3359 --- /dev/null +++ b/shared/package-files/38/3834b0db1d4a1d7374bdd2879b8be7a2f67192869f73021d51e93437c11dbb98/_upfirdn.py @@ -0,0 +1,216 @@ +# Code adapted from "upfirdn" python library with permission: +# +# Copyright (c) 2009, Motorola, Inc +# +# 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 Motorola 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 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. + +import numpy as np + +from ._upfirdn_apply import _output_len, _apply, mode_enum + +__all__ = ['upfirdn', '_output_len'] + +_upfirdn_modes = [ + 'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect', + 'antisymmetric', 'antireflect', 'line', +] + + +def _pad_h(h, up): + """Store coefficients in a transposed, flipped arrangement. + + For example, suppose upRate is 3, and the + input number of coefficients is 10, represented as h[0], ..., h[9]. + + Then the internal buffer will look like this:: + + h[9], h[6], h[3], h[0], // flipped phase 0 coefs + 0, h[7], h[4], h[1], // flipped phase 1 coefs (zero-padded) + 0, h[8], h[5], h[2], // flipped phase 2 coefs (zero-padded) + + """ + h_padlen = len(h) + (-len(h) % up) + h_full = np.zeros(h_padlen, h.dtype) + h_full[:len(h)] = h + h_full = h_full.reshape(-1, up).T[:, ::-1].ravel() + return h_full + + +def _check_mode(mode): + mode = mode.lower() + enum = mode_enum(mode) + return enum + + +class _UpFIRDn: + """Helper for resampling.""" + + def __init__(self, h, x_dtype, up, down): + h = np.asarray(h) + if h.ndim != 1 or h.size == 0: + raise ValueError('h must be 1-D with non-zero length') + self._output_type = np.result_type(h.dtype, x_dtype, np.float32) + h = np.asarray(h, self._output_type) + self._up = int(up) + self._down = int(down) + if self._up < 1 or self._down < 1: + raise ValueError('Both up and down must be >= 1') + # This both transposes, and "flips" each phase for filtering + self._h_trans_flip = _pad_h(h, self._up) + self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip) + self._h_len_orig = len(h) + + def apply_filter(self, x, axis=-1, mode='constant', cval=0): + """Apply the prepared filter to the specified axis of N-D signal x.""" + output_len = _output_len(self._h_len_orig, x.shape[axis], + self._up, self._down) + # Explicit use of np.int64 for output_shape dtype avoids OverflowError + # when allocating large array on platforms where intp is 32 bits. + output_shape = np.asarray(x.shape, dtype=np.int64) + output_shape[axis] = output_len + out = np.zeros(output_shape, dtype=self._output_type, order='C') + axis = axis % x.ndim + mode = _check_mode(mode) + _apply(np.asarray(x, self._output_type), + self._h_trans_flip, out, + self._up, self._down, axis, mode, cval) + return out + + +def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0): + """Upsample, FIR filter, and downsample. + + Parameters + ---------- + h : array_like + 1-D FIR (finite-impulse response) filter coefficients. + x : array_like + Input signal array. + up : int, optional + Upsampling rate. Default is 1. + down : int, optional + Downsampling rate. Default is 1. + axis : int, optional + The axis of the input data array along which to apply the + linear filter. The filter is applied to each subarray along + this axis. Default is -1. + mode : str, optional + The signal extension mode to use. The set + ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to + modes provided by `numpy.pad`. ``"smooth"`` implements a smooth + extension by extending based on the slope of the last 2 points at each + end of the array. ``"antireflect"`` and ``"antisymmetric"`` are + anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode + `"line"` extends the signal based on a linear trend defined by the + first and last points along the ``axis``. + + .. versionadded:: 1.4.0 + cval : float, optional + The constant value to use when ``mode == "constant"``. + + .. versionadded:: 1.4.0 + + Returns + ------- + y : ndarray + The output signal array. Dimensions will be the same as `x` except + for along `axis`, which will change size according to the `h`, + `up`, and `down` parameters. + + Notes + ----- + The algorithm is an implementation of the block diagram shown on page 129 + of the Vaidyanathan text [1]_ (Figure 4.3-8d). + + The direct approach of upsampling by factor of P with zero insertion, + FIR filtering of length ``N``, and downsampling by factor of Q is + O(N*Q) per output sample. The polyphase implementation used here is + O(N/P). + + .. versionadded:: 0.18 + + References + ---------- + .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks, + Prentice Hall, 1993. + + Examples + -------- + Simple operations: + + >>> import numpy as np + >>> from scipy.signal import upfirdn + >>> upfirdn([1, 1, 1], [1, 1, 1]) # FIR filter + array([ 1., 2., 3., 2., 1.]) + >>> upfirdn([1], [1, 2, 3], 3) # upsampling with zeros insertion + array([ 1., 0., 0., 2., 0., 0., 3.]) + >>> upfirdn([1, 1, 1], [1, 2, 3], 3) # upsampling with sample-and-hold + array([ 1., 1., 1., 2., 2., 2., 3., 3., 3.]) + >>> upfirdn([.5, 1, .5], [1, 1, 1], 2) # linear interpolation + array([ 0.5, 1. , 1. , 1. , 1. , 1. , 0.5]) + >>> upfirdn([1], np.arange(10), 1, 3) # decimation by 3 + array([ 0., 3., 6., 9.]) + >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3) # linear interp, rate 2/3 + array([ 0. , 1. , 2.5, 4. , 5.5, 7. , 8.5]) + + Apply a single filter to multiple signals: + + >>> x = np.reshape(np.arange(8), (4, 2)) + >>> x + array([[0, 1], + [2, 3], + [4, 5], + [6, 7]]) + + Apply along the last dimension of ``x``: + + >>> h = [1, 1] + >>> upfirdn(h, x, 2) + array([[ 0., 0., 1., 1.], + [ 2., 2., 3., 3.], + [ 4., 4., 5., 5.], + [ 6., 6., 7., 7.]]) + + Apply along the 0th dimension of ``x``: + + >>> upfirdn(h, x, 2, axis=0) + array([[ 0., 1.], + [ 0., 1.], + [ 2., 3.], + [ 2., 3.], + [ 4., 5.], + [ 4., 5.], + [ 6., 7.], + [ 6., 7.]]) + """ + x = np.asarray(x) + ufd = _UpFIRDn(h, x.dtype, up, down) + # This is equivalent to (but faster than) using np.apply_along_axis + return ufd.apply_filter(x, axis, mode, cval) diff --git a/shared/package-files/38/38392f69f72311bee609d0f42c6ded9c46212aa962982803f7e816a28c8f3673/direct_url.json b/shared/package-files/38/38392f69f72311bee609d0f42c6ded9c46212aa962982803f7e816a28c8f3673/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..7a101f6772d6a4f576a802329788ee8fb2d63bb0 --- /dev/null +++ b/shared/package-files/38/38392f69f72311bee609d0f42c6ded9c46212aa962982803f7e816a28c8f3673/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/jsonpatch_1710807507480/work"} \ No newline at end of file diff --git a/shared/package-files/38/383bd6abbf096ad627aefc6365bf2d6b1cbe9ce04e0ba544d2c6674a9c62c05b/Dimname.h b/shared/package-files/38/383bd6abbf096ad627aefc6365bf2d6b1cbe9ce04e0ba544d2c6674a9c62c05b/Dimname.h new file mode 100644 index 0000000000000000000000000000000000000000..71836a9e25d3d82d9cd5024b2f33e147e14bf87e --- /dev/null +++ b/shared/package-files/38/383bd6abbf096ad627aefc6365bf2d6b1cbe9ce04e0ba544d2c6674a9c62c05b/Dimname.h @@ -0,0 +1 @@ +#include diff --git a/shared/package-files/38/383f71601a1393ec91861b5b09ac7271e83596c9c2694725a7f3565b8b9a3586/rust.py b/shared/package-files/38/383f71601a1393ec91861b5b09ac7271e83596c9c2694725a7f3565b8b9a3586/rust.py new file mode 100644 index 0000000000000000000000000000000000000000..04c6b6399ec84fca233ded96c53c997844f8143b --- /dev/null +++ b/shared/package-files/38/383f71601a1393ec91861b5b09ac7271e83596c9c2694725a7f3565b8b9a3586/rust.py @@ -0,0 +1,625 @@ +""" +Rust code printer + +The `RustCodePrinter` converts SymPy expressions into Rust expressions. + +A complete code generator, which uses `rust_code` extensively, can be found +in `sympy.utilities.codegen`. The `codegen` module can be used to generate +complete source code files. + +""" + +# Possible Improvement +# +# * make sure we follow Rust Style Guidelines_ +# * make use of pattern matching +# * better support for reference +# * generate generic code and use trait to make sure they have specific methods +# * use crates_ to get more math support +# - num_ +# + BigInt_, BigUint_ +# + Complex_ +# + Rational64_, Rational32_, BigRational_ +# +# .. _crates: https://crates.io/ +# .. _Guidelines: https://github.com/rust-lang/rust/tree/master/src/doc/style +# .. _num: http://rust-num.github.io/num/num/ +# .. _BigInt: http://rust-num.github.io/num/num/bigint/struct.BigInt.html +# .. _BigUint: http://rust-num.github.io/num/num/bigint/struct.BigUint.html +# .. _Complex: http://rust-num.github.io/num/num/complex/struct.Complex.html +# .. _Rational32: http://rust-num.github.io/num/num/rational/type.Rational32.html +# .. _Rational64: http://rust-num.github.io/num/num/rational/type.Rational64.html +# .. _BigRational: http://rust-num.github.io/num/num/rational/type.BigRational.html + +from __future__ import annotations +from typing import Any + +from sympy.core import S, Rational, Float, Lambda +from sympy.core.numbers import equal_valued +from sympy.printing.codeprinter import CodePrinter + +# Rust's methods for integer and float can be found at here : +# +# * `Rust - Primitive Type f64 `_ +# * `Rust - Primitive Type i64 `_ +# +# Function Style : +# +# 1. args[0].func(args[1:]), method with arguments +# 2. args[0].func(), method without arguments +# 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp()) +# 4. func(args), function with arguments + +# dictionary mapping SymPy function to (argument_conditions, Rust_function). +# Used in RustCodePrinter._print_Function(self) + +# f64 method in Rust +known_functions = { + # "": "is_nan", + # "": "is_infinite", + # "": "is_finite", + # "": "is_normal", + # "": "classify", + "floor": "floor", + "ceiling": "ceil", + # "": "round", + # "": "trunc", + # "": "fract", + "Abs": "abs", + "sign": "signum", + # "": "is_sign_positive", + # "": "is_sign_negative", + # "": "mul_add", + "Pow": [(lambda base, exp: equal_valued(exp, -1), "recip", 2), # 1.0/x + (lambda base, exp: equal_valued(exp, 0.5), "sqrt", 2), # x ** 0.5 + (lambda base, exp: equal_valued(exp, -0.5), "sqrt().recip", 2), # 1/(x ** 0.5) + (lambda base, exp: exp == Rational(1, 3), "cbrt", 2), # x ** (1/3) + (lambda base, exp: equal_valued(base, 2), "exp2", 3), # 2 ** x + (lambda base, exp: exp.is_integer, "powi", 1), # x ** y, for i32 + (lambda base, exp: not exp.is_integer, "powf", 1)], # x ** y, for f64 + "exp": [(lambda exp: True, "exp", 2)], # e ** x + "log": "ln", + # "": "log", # number.log(base) + # "": "log2", + # "": "log10", + # "": "to_degrees", + # "": "to_radians", + "Max": "max", + "Min": "min", + # "": "hypot", # (x**2 + y**2) ** 0.5 + "sin": "sin", + "cos": "cos", + "tan": "tan", + "asin": "asin", + "acos": "acos", + "atan": "atan", + "atan2": "atan2", + # "": "sin_cos", + # "": "exp_m1", # e ** x - 1 + # "": "ln_1p", # ln(1 + x) + "sinh": "sinh", + "cosh": "cosh", + "tanh": "tanh", + "asinh": "asinh", + "acosh": "acosh", + "atanh": "atanh", + "sqrt": "sqrt", # To enable automatic rewrites +} + +# i64 method in Rust +# known_functions_i64 = { +# "": "min_value", +# "": "max_value", +# "": "from_str_radix", +# "": "count_ones", +# "": "count_zeros", +# "": "leading_zeros", +# "": "trainling_zeros", +# "": "rotate_left", +# "": "rotate_right", +# "": "swap_bytes", +# "": "from_be", +# "": "from_le", +# "": "to_be", # to big endian +# "": "to_le", # to little endian +# "": "checked_add", +# "": "checked_sub", +# "": "checked_mul", +# "": "checked_div", +# "": "checked_rem", +# "": "checked_neg", +# "": "checked_shl", +# "": "checked_shr", +# "": "checked_abs", +# "": "saturating_add", +# "": "saturating_sub", +# "": "saturating_mul", +# "": "wrapping_add", +# "": "wrapping_sub", +# "": "wrapping_mul", +# "": "wrapping_div", +# "": "wrapping_rem", +# "": "wrapping_neg", +# "": "wrapping_shl", +# "": "wrapping_shr", +# "": "wrapping_abs", +# "": "overflowing_add", +# "": "overflowing_sub", +# "": "overflowing_mul", +# "": "overflowing_div", +# "": "overflowing_rem", +# "": "overflowing_neg", +# "": "overflowing_shl", +# "": "overflowing_shr", +# "": "overflowing_abs", +# "Pow": "pow", +# "Abs": "abs", +# "sign": "signum", +# "": "is_positive", +# "": "is_negnative", +# } + +# These are the core reserved words in the Rust language. Taken from: +# http://doc.rust-lang.org/grammar.html#keywords + +reserved_words = ['abstract', + 'alignof', + 'as', + 'become', + 'box', + 'break', + 'const', + 'continue', + 'crate', + 'do', + 'else', + 'enum', + 'extern', + 'false', + 'final', + 'fn', + 'for', + 'if', + 'impl', + 'in', + 'let', + 'loop', + 'macro', + 'match', + 'mod', + 'move', + 'mut', + 'offsetof', + 'override', + 'priv', + 'proc', + 'pub', + 'pure', + 'ref', + 'return', + 'Self', + 'self', + 'sizeof', + 'static', + 'struct', + 'super', + 'trait', + 'true', + 'type', + 'typeof', + 'unsafe', + 'unsized', + 'use', + 'virtual', + 'where', + 'while', + 'yield'] + + +class RustCodePrinter(CodePrinter): + """A printer to convert SymPy expressions to strings of Rust code""" + printmethod = "_rust_code" + language = "Rust" + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'contract': True, + 'dereference': set(), + 'error_on_reserved': False, + 'reserved_word_suffix': '_', + 'inline': False, + } + + def __init__(self, settings={}): + CodePrinter.__init__(self, settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + self._dereference = set(settings.get('dereference', [])) + self.reserved_words = set(reserved_words) + + def _rate_index_position(self, p): + return p*5 + + def _get_statement(self, codestring): + return "%s;" % codestring + + def _get_comment(self, text): + return "// %s" % text + + def _declare_number_const(self, name, value): + return "const %s: f64 = %s;" % (name, value) + + 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)) + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + loopstart = "for %(var)s in %(start)s..%(end)s {" + for i in indices: + # Rust arrays start at 0 and end at dimension-1 + open_lines.append(loopstart % { + 'var': self._print(i), + 'start': self._print(i.lower), + 'end': self._print(i.upper + 1)}) + close_lines.append("}") + return open_lines, close_lines + + def _print_caller_var(self, expr): + if len(expr.args) > 1: + # for something like `sin(x + y + z)`, + # make sure we can get '(x + y + z).sin()' + # instead of 'x + y + z.sin()' + return '(' + self._print(expr) + ')' + elif expr.is_number: + return self._print(expr, _type=True) + else: + return self._print(expr) + + def _print_Function(self, expr): + """ + basic function for printing `Function` + + Function Style : + + 1. args[0].func(args[1:]), method with arguments + 2. args[0].func(), method without arguments + 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp()) + 4. func(args), function with arguments + """ + + if expr.func.__name__ in self.known_functions: + cond_func = self.known_functions[expr.func.__name__] + func = None + style = 1 + if isinstance(cond_func, str): + func = cond_func + else: + for cond, func, style in cond_func: + if cond(*expr.args): + break + if func is not None: + if style == 1: + ret = "%(var)s.%(method)s(%(args)s)" % { + 'var': self._print_caller_var(expr.args[0]), + 'method': func, + 'args': self.stringify(expr.args[1:], ", ") if len(expr.args) > 1 else '' + } + elif style == 2: + ret = "%(var)s.%(method)s()" % { + 'var': self._print_caller_var(expr.args[0]), + 'method': func, + } + elif style == 3: + ret = "%(var)s.%(method)s()" % { + 'var': self._print_caller_var(expr.args[1]), + 'method': func, + } + else: + ret = "%(func)s(%(args)s)" % { + 'func': func, + 'args': self.stringify(expr.args, ", "), + } + return ret + elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda): + # inlined function + return self._print(expr._imp_(*expr.args)) + elif expr.func.__name__ in self._rewriteable_functions: + # Simple rewrite to supported function possible + target_f, required_fs = self._rewriteable_functions[expr.func.__name__] + if self._can_print(target_f) and all(self._can_print(f) for f in required_fs): + return self._print(expr.rewrite(target_f)) + else: + return self._print_not_supported(expr) + + def _print_Pow(self, expr): + if expr.base.is_integer and not expr.exp.is_integer: + expr = type(expr)(Float(expr.base), expr.exp) + return self._print(expr) + return self._print_Function(expr) + + def _print_Float(self, expr, _type=False): + ret = super()._print_Float(expr) + if _type: + return ret + '_f64' + else: + return ret + + def _print_Integer(self, expr, _type=False): + ret = super()._print_Integer(expr) + if _type: + return ret + '_i32' + else: + return ret + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + return '%d_f64/%d.0' % (p, q) + + 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_Indexed(self, expr): + # calculate index for 1d array + dims = expr.shape + elem = S.Zero + offset = S.One + for i in reversed(range(expr.rank)): + elem += expr.indices[i]*offset + offset *= dims[i] + return "%s[%s]" % (self._print(expr.base.label), self._print(elem)) + + def _print_Idx(self, expr): + return expr.label.name + + def _print_Dummy(self, expr): + return expr.name + + def _print_Exp1(self, expr, _type=False): + return "E" + + def _print_Pi(self, expr, _type=False): + return 'PI' + + def _print_Infinity(self, expr, _type=False): + return 'INFINITY' + + def _print_NegativeInfinity(self, expr, _type=False): + return 'NEG_INFINITY' + + def _print_BooleanTrue(self, expr, _type=False): + return "true" + + def _print_BooleanFalse(self, expr, _type=False): + return "false" + + def _print_bool(self, expr, _type=False): + return str(expr).lower() + + def _print_NaN(self, expr, _type=False): + return "NAN" + + 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 = [] + + 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[-1] += " else {" + else: + lines[-1] += " else if (%s) {" % self._print(c) + code0 = self._print(e) + lines.append(code0) + lines.append("}") + + if self._settings['inline']: + return " ".join(lines) + else: + return "\n".join(lines) + + def _print_ITE(self, expr): + from sympy.functions import Piecewise + return self._print(expr.rewrite(Piecewise, deep=False)) + + def _print_MatrixBase(self, A): + if A.cols == 1: + return "[%s]" % ", ".join(self._print(a) for a in A) + else: + raise ValueError("Full Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).") + + def _print_SparseRepMatrix(self, mat): + # do not allow sparse matrices to be made dense + return self._print_not_supported(mat) + + def _print_MatrixElement(self, expr): + return "%s[%s]" % (expr.parent, + expr.j + expr.i*expr.parent.shape[1]) + + def _print_Symbol(self, expr): + + name = super()._print_Symbol(expr) + + if expr in self._dereference: + return '(*%s)' % name + else: + return name + + def _print_Assignment(self, expr): + from sympy.tensor.indexed import IndexedBase + lhs = expr.lhs + rhs = expr.rhs + if self._settings["contract"] and (lhs.has(IndexedBase) or + rhs.has(IndexedBase)): + # Here we check if there is looping to be done, and if so + # print the required loops. + return self._doprint_loops(rhs, lhs) + else: + lhs_code = self._print(lhs) + rhs_code = self._print(rhs) + return self._get_statement("%s = %s" % (lhs_code, rhs_code)) + + 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 rust_code(expr, assign_to=None, **settings): + """Converts an expr to a string of Rust code + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of + line-wrapping, or for expressions that generate multi-line statements. + precision : integer, optional + The precision for numbers such as pi [default=15]. + user_functions : dict, optional + A dictionary where the keys are string representations of either + ``FunctionClass`` or ``UndefinedFunction`` instances and the values + are their desired C string representations. Alternatively, the + dictionary value can be a list of tuples i.e. [(argument_test, + cfunction_string)]. See below for examples. + dereference : iterable, optional + An iterable of symbols that should be dereferenced in the printed code + expression. These would be values passed by address to the function. + For example, if ``dereference=[a]``, the resulting code would print + ``(*a)`` instead of ``a``. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + + Examples + ======== + + >>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function + >>> x, tau = symbols("x, tau") + >>> rust_code((2*tau)**Rational(7, 2)) + '8*1.4142135623731*tau.powf(7_f64/2.0)' + >>> rust_code(sin(x), assign_to="s") + 's = x.sin();' + + Simple custom printing can be defined for certain types by passing a + dictionary of {"type" : "function"} to the ``user_functions`` kwarg. + Alternatively, the dictionary value can be a list of tuples i.e. + [(argument_test, cfunction_string)]. + + >>> custom_functions = { + ... "ceiling": "CEIL", + ... "Abs": [(lambda x: not x.is_integer, "fabs", 4), + ... (lambda x: x.is_integer, "ABS", 4)], + ... "func": "f" + ... } + >>> func = Function('func') + >>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions) + '(fabs(x) + x.CEIL()).f()' + + ``Piecewise`` expressions are converted into conditionals. If an + ``assign_to`` variable is provided an if statement is created, otherwise + the ternary operator is used. Note that if the ``Piecewise`` lacks a + default term, represented by ``(expr, True)`` then an error will be thrown. + This is to prevent generating an expression that may not evaluate to + anything. + + >>> from sympy import Piecewise + >>> expr = Piecewise((x + 1, x > 0), (x, True)) + >>> print(rust_code(expr, tau)) + tau = if (x > 0) { + x + 1 + } else { + x + }; + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> rust_code(e.rhs, assign_to=e.lhs, contract=False) + 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' + + Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions + must be provided to ``assign_to``. Note that any expression that can be + generated normally can also exist inside a Matrix: + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) + >>> A = MatrixSymbol('A', 3, 1) + >>> print(rust_code(mat, A)) + A = [x.powi(2), if (x > 0) { + x + 1 + } else { + x + }, x.sin()]; + """ + + return RustCodePrinter(settings).doprint(expr, assign_to) + + +def print_rust_code(expr, **settings): + """Prints Rust representation of the given expression.""" + print(rust_code(expr, **settings)) diff --git a/shared/package-files/38/38416435ef1382b0658bf303316f7d4ef86be384b8c923da610a268d55e95140/hatch.pyi b/shared/package-files/38/38416435ef1382b0658bf303316f7d4ef86be384b8c923da610a268d55e95140/hatch.pyi new file mode 100644 index 0000000000000000000000000000000000000000..348cf5214984bd0ba23b3953b2e79300d0e04e3f --- /dev/null +++ b/shared/package-files/38/38416435ef1382b0658bf303316f7d4ef86be384b8c923da610a268d55e95140/hatch.pyi @@ -0,0 +1,68 @@ +from matplotlib.path import Path + +import numpy as np +from numpy.typing import ArrayLike + +class HatchPatternBase: ... + +class HorizontalHatch(HatchPatternBase): + num_lines: int + num_vertices: int + def __init__(self, hatch: str, density: int) -> None: ... + def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ... + +class VerticalHatch(HatchPatternBase): + num_lines: int + num_vertices: int + def __init__(self, hatch: str, density: int) -> None: ... + def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ... + +class NorthEastHatch(HatchPatternBase): + num_lines: int + num_vertices: int + def __init__(self, hatch: str, density: int) -> None: ... + def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ... + +class SouthEastHatch(HatchPatternBase): + num_lines: int + num_vertices: int + def __init__(self, hatch: str, density: int) -> None: ... + def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ... + +class Shapes(HatchPatternBase): + filled: bool + num_shapes: int + num_vertices: int + def __init__(self, hatch: str, density: int) -> None: ... + def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ... + +class Circles(Shapes): + shape_vertices: np.ndarray + shape_codes: np.ndarray + def __init__(self, hatch: str, density: int) -> None: ... + +class SmallCircles(Circles): + size: float + num_rows: int + def __init__(self, hatch: str, density: int) -> None: ... + +class LargeCircles(Circles): + size: float + num_rows: int + def __init__(self, hatch: str, density: int) -> None: ... + +class SmallFilledCircles(Circles): + size: float + filled: bool + num_rows: int + def __init__(self, hatch: str, density: int) -> None: ... + +class Stars(Shapes): + size: float + filled: bool + num_rows: int + shape_vertices: np.ndarray + shape_codes: np.ndarray + def __init__(self, hatch: str, density: int) -> None: ... + +def get_path(hatchpattern: str, density: int = ...) -> Path: ... diff --git a/shared/package-files/38/3843b6bb9a38e2ddf128dbc3b2122f8901bc1cc647ddf314ac5f90622ba5e3eb/test_indexing.py b/shared/package-files/38/3843b6bb9a38e2ddf128dbc3b2122f8901bc1cc647ddf314ac5f90622ba5e3eb/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..b5be7e0713cdf612a3b4371a5a5b432b6a8f2c47 --- /dev/null +++ b/shared/package-files/38/3843b6bb9a38e2ddf128dbc3b2122f8901bc1cc647ddf314ac5f90622ba5e3eb/test_indexing.py @@ -0,0 +1,674 @@ +import re + +import numpy as np +import pytest + +from pandas.errors import InvalidIndexError + +from pandas import ( + NA, + CategoricalIndex, + DatetimeIndex, + Index, + Interval, + IntervalIndex, + MultiIndex, + NaT, + Timedelta, + Timestamp, + array, + date_range, + interval_range, + isna, + period_range, + timedelta_range, +) +import pandas._testing as tm + + +class TestGetItem: + def test_getitem(self, closed): + idx = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed) + assert idx[0] == Interval(0.0, 1.0, closed=closed) + assert idx[1] == Interval(1.0, 2.0, closed=closed) + assert isna(idx[2]) + + result = idx[0:1] + expected = IntervalIndex.from_arrays((0.0,), (1.0,), closed=closed) + tm.assert_index_equal(result, expected) + + result = idx[0:2] + expected = IntervalIndex.from_arrays((0.0, 1), (1.0, 2.0), closed=closed) + tm.assert_index_equal(result, expected) + + result = idx[1:3] + expected = IntervalIndex.from_arrays( + (1.0, np.nan), (2.0, np.nan), closed=closed + ) + tm.assert_index_equal(result, expected) + + def test_getitem_2d_deprecated(self): + # GH#30588 multi-dim indexing is deprecated, but raising is also acceptable + idx = IntervalIndex.from_breaks(range(11), closed="right") + with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): + idx[:, None] + with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): + # GH#44051 + idx[True] + with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): + # GH#44051 + idx[False] + + +class TestWhere: + def test_where(self, listlike_box): + klass = listlike_box + + idx = IntervalIndex.from_breaks(range(11), closed="right") + cond = [True] * len(idx) + expected = idx + result = expected.where(klass(cond)) + tm.assert_index_equal(result, expected) + + cond = [False] + [True] * len(idx[1:]) + expected = IntervalIndex([np.nan] + idx[1:].tolist()) + result = idx.where(klass(cond)) + tm.assert_index_equal(result, expected) + + +class TestTake: + def test_take(self, closed): + index = IntervalIndex.from_breaks(range(11), closed=closed) + + result = index.take(range(10)) + tm.assert_index_equal(result, index) + + result = index.take([0, 0, 1]) + expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], closed=closed) + tm.assert_index_equal(result, expected) + + +class TestGetLoc: + @pytest.mark.parametrize("side", ["right", "left", "both", "neither"]) + def test_get_loc_interval(self, closed, side): + idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) + + for bound in [[0, 1], [1, 2], [2, 3], [3, 4], [0, 2], [2.5, 3], [-1, 4]]: + # if get_loc is supplied an interval, it should only search + # for exact matches, not overlaps or covers, else KeyError. + msg = re.escape(f"Interval({bound[0]}, {bound[1]}, closed='{side}')") + if closed == side: + if bound == [0, 1]: + assert idx.get_loc(Interval(0, 1, closed=side)) == 0 + elif bound == [2, 3]: + assert idx.get_loc(Interval(2, 3, closed=side)) == 1 + else: + with pytest.raises(KeyError, match=msg): + idx.get_loc(Interval(*bound, closed=side)) + else: + with pytest.raises(KeyError, match=msg): + idx.get_loc(Interval(*bound, closed=side)) + + @pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5]) + def test_get_loc_scalar(self, closed, scalar): + # correct = {side: {query: answer}}. + # If query is not in the dict, that query should raise a KeyError + correct = { + "right": {0.5: 0, 1: 0, 2.5: 1, 3: 1}, + "left": {0: 0, 0.5: 0, 2: 1, 2.5: 1}, + "both": {0: 0, 0.5: 0, 1: 0, 2: 1, 2.5: 1, 3: 1}, + "neither": {0.5: 0, 2.5: 1}, + } + + idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) + + # if get_loc is supplied a scalar, it should return the index of + # the interval which contains the scalar, or KeyError. + if scalar in correct[closed].keys(): + assert idx.get_loc(scalar) == correct[closed][scalar] + else: + with pytest.raises(KeyError, match=str(scalar)): + idx.get_loc(scalar) + + @pytest.mark.parametrize("scalar", [-1, 0, 0.5, 3, 4.5, 5, 6]) + def test_get_loc_length_one_scalar(self, scalar, closed): + # GH 20921 + index = IntervalIndex.from_tuples([(0, 5)], closed=closed) + if scalar in index[0]: + result = index.get_loc(scalar) + assert result == 0 + else: + with pytest.raises(KeyError, match=str(scalar)): + index.get_loc(scalar) + + @pytest.mark.parametrize("other_closed", ["left", "right", "both", "neither"]) + @pytest.mark.parametrize("left, right", [(0, 5), (-1, 4), (-1, 6), (6, 7)]) + def test_get_loc_length_one_interval(self, left, right, closed, other_closed): + # GH 20921 + index = IntervalIndex.from_tuples([(0, 5)], closed=closed) + interval = Interval(left, right, closed=other_closed) + if interval == index[0]: + result = index.get_loc(interval) + assert result == 0 + else: + with pytest.raises( + KeyError, + match=re.escape(f"Interval({left}, {right}, closed='{other_closed}')"), + ): + index.get_loc(interval) + + # Make consistent with test_interval_new.py (see #16316, #16386) + @pytest.mark.parametrize( + "breaks", + [ + date_range("20180101", periods=4), + date_range("20180101", periods=4, tz="US/Eastern"), + timedelta_range("0 days", periods=4), + ], + ids=lambda x: str(x.dtype), + ) + def test_get_loc_datetimelike_nonoverlapping(self, breaks): + # GH 20636 + # nonoverlapping = IntervalIndex method and no i8 conversion + index = IntervalIndex.from_breaks(breaks) + + value = index[0].mid + result = index.get_loc(value) + expected = 0 + assert result == expected + + interval = Interval(index[0].left, index[0].right) + result = index.get_loc(interval) + expected = 0 + assert result == expected + + @pytest.mark.parametrize( + "arrays", + [ + (date_range("20180101", periods=4), date_range("20180103", periods=4)), + ( + date_range("20180101", periods=4, tz="US/Eastern"), + date_range("20180103", periods=4, tz="US/Eastern"), + ), + ( + timedelta_range("0 days", periods=4), + timedelta_range("2 days", periods=4), + ), + ], + ids=lambda x: str(x[0].dtype), + ) + def test_get_loc_datetimelike_overlapping(self, arrays): + # GH 20636 + index = IntervalIndex.from_arrays(*arrays) + + value = index[0].mid + Timedelta("12 hours") + result = index.get_loc(value) + expected = slice(0, 2, None) + assert result == expected + + interval = Interval(index[0].left, index[0].right) + result = index.get_loc(interval) + expected = 0 + assert result == expected + + @pytest.mark.parametrize( + "values", + [ + date_range("2018-01-04", periods=4, freq="-1D"), + date_range("2018-01-04", periods=4, freq="-1D", tz="US/Eastern"), + timedelta_range("3 days", periods=4, freq="-1D"), + np.arange(3.0, -1.0, -1.0), + np.arange(3, -1, -1), + ], + ids=lambda x: str(x.dtype), + ) + def test_get_loc_decreasing(self, values): + # GH 25860 + index = IntervalIndex.from_arrays(values[1:], values[:-1]) + result = index.get_loc(index[0]) + expected = 0 + assert result == expected + + @pytest.mark.parametrize("key", [[5], (2, 3)]) + def test_get_loc_non_scalar_errors(self, key): + # GH 31117 + idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)]) + + msg = str(key) + with pytest.raises(InvalidIndexError, match=msg): + idx.get_loc(key) + + def test_get_indexer_with_nans(self): + # GH#41831 + index = IntervalIndex([np.nan, Interval(1, 2), np.nan]) + + expected = np.array([True, False, True]) + for key in [None, np.nan, NA]: + assert key in index + result = index.get_loc(key) + tm.assert_numpy_array_equal(result, expected) + + for key in [NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")]: + with pytest.raises(KeyError, match=str(key)): + index.get_loc(key) + + +class TestGetIndexer: + @pytest.mark.parametrize( + "query, expected", + [ + ([Interval(2, 4, closed="right")], [1]), + ([Interval(2, 4, closed="left")], [-1]), + ([Interval(2, 4, closed="both")], [-1]), + ([Interval(2, 4, closed="neither")], [-1]), + ([Interval(1, 4, closed="right")], [-1]), + ([Interval(0, 4, closed="right")], [-1]), + ([Interval(0.5, 1.5, closed="right")], [-1]), + ([Interval(2, 4, closed="right"), Interval(0, 1, closed="right")], [1, -1]), + ([Interval(2, 4, closed="right"), Interval(2, 4, closed="right")], [1, 1]), + ([Interval(5, 7, closed="right"), Interval(2, 4, closed="right")], [2, 1]), + ([Interval(2, 4, closed="right"), Interval(2, 4, closed="left")], [1, -1]), + ], + ) + def test_get_indexer_with_interval(self, query, expected): + tuples = [(0, 2), (2, 4), (5, 7)] + index = IntervalIndex.from_tuples(tuples, closed="right") + + result = index.get_indexer(query) + expected = np.array(expected, dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "query, expected", + [ + ([-0.5], [-1]), + ([0], [-1]), + ([0.5], [0]), + ([1], [0]), + ([1.5], [1]), + ([2], [1]), + ([2.5], [-1]), + ([3], [-1]), + ([3.5], [2]), + ([4], [2]), + ([4.5], [-1]), + ([1, 2], [0, 1]), + ([1, 2, 3], [0, 1, -1]), + ([1, 2, 3, 4], [0, 1, -1, 2]), + ([1, 2, 3, 4, 2], [0, 1, -1, 2, 1]), + ], + ) + def test_get_indexer_with_int_and_float(self, query, expected): + tuples = [(0, 1), (1, 2), (3, 4)] + index = IntervalIndex.from_tuples(tuples, closed="right") + + result = index.get_indexer(query) + expected = np.array(expected, dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("item", [[3], np.arange(0.5, 5, 0.5)]) + def test_get_indexer_length_one(self, item, closed): + # GH 17284 + index = IntervalIndex.from_tuples([(0, 5)], closed=closed) + result = index.get_indexer(item) + expected = np.array([0] * len(item), dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("size", [1, 5]) + def test_get_indexer_length_one_interval(self, size, closed): + # GH 17284 + index = IntervalIndex.from_tuples([(0, 5)], closed=closed) + result = index.get_indexer([Interval(0, 5, closed)] * size) + expected = np.array([0] * size, dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "target", + [ + IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]), + IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4), np.nan]), + IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], closed="both"), + [-1, 0, 0.5, 1, 2, 2.5, np.nan], + ["foo", "foo", "bar", "baz"], + ], + ) + def test_get_indexer_categorical(self, target, ordered): + # GH 30063: categorical and non-categorical results should be consistent + index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]) + categorical_target = CategoricalIndex(target, ordered=ordered) + + result = index.get_indexer(categorical_target) + expected = index.get_indexer(target) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:invalid value encountered in cast:RuntimeWarning" + ) + def test_get_indexer_categorical_with_nans(self): + # GH#41934 nans in both index and in target + ii = IntervalIndex.from_breaks(range(5)) + ii2 = ii.append(IntervalIndex([np.nan])) + ci2 = CategoricalIndex(ii2) + + result = ii2.get_indexer(ci2) + expected = np.arange(5, dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + # not-all-matches + result = ii2[1:].get_indexer(ci2[::-1]) + expected = np.array([3, 2, 1, 0, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + # non-unique target, non-unique nans + result = ii2.get_indexer(ci2.append(ci2)) + expected = np.array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_datetime(self): + ii = IntervalIndex.from_breaks(date_range("2018-01-01", periods=4)) + # TODO: with mismatched resolution get_indexer currently raises; + # this should probably coerce? + target = DatetimeIndex(["2018-01-02"], dtype="M8[ns]") + result = ii.get_indexer(target) + expected = np.array([0], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = ii.get_indexer(target.astype(str)) + tm.assert_numpy_array_equal(result, expected) + + # https://github.com/pandas-dev/pandas/issues/47772 + result = ii.get_indexer(target.asi8) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "tuples, closed", + [ + ([(0, 2), (1, 3), (3, 4)], "neither"), + ([(0, 5), (1, 4), (6, 7)], "left"), + ([(0, 1), (0, 1), (1, 2)], "right"), + ([(0, 1), (2, 3), (3, 4)], "both"), + ], + ) + def test_get_indexer_errors(self, tuples, closed): + # IntervalIndex needs non-overlapping for uniqueness when querying + index = IntervalIndex.from_tuples(tuples, closed=closed) + + msg = ( + "cannot handle overlapping indices; use " + "IntervalIndex.get_indexer_non_unique" + ) + with pytest.raises(InvalidIndexError, match=msg): + index.get_indexer([0, 2]) + + @pytest.mark.parametrize( + "query, expected", + [ + ([-0.5], ([-1], [0])), + ([0], ([0], [])), + ([0.5], ([0], [])), + ([1], ([0, 1], [])), + ([1.5], ([0, 1], [])), + ([2], ([0, 1, 2], [])), + ([2.5], ([1, 2], [])), + ([3], ([2], [])), + ([3.5], ([2], [])), + ([4], ([-1], [0])), + ([4.5], ([-1], [0])), + ([1, 2], ([0, 1, 0, 1, 2], [])), + ([1, 2, 3], ([0, 1, 0, 1, 2, 2], [])), + ([1, 2, 3, 4], ([0, 1, 0, 1, 2, 2, -1], [3])), + ([1, 2, 3, 4, 2], ([0, 1, 0, 1, 2, 2, -1, 0, 1, 2], [3])), + ], + ) + def test_get_indexer_non_unique_with_int_and_float(self, query, expected): + tuples = [(0, 2.5), (1, 3), (2, 4)] + index = IntervalIndex.from_tuples(tuples, closed="left") + + result_indexer, result_missing = index.get_indexer_non_unique(query) + expected_indexer = np.array(expected[0], dtype="intp") + expected_missing = np.array(expected[1], dtype="intp") + + tm.assert_numpy_array_equal(result_indexer, expected_indexer) + tm.assert_numpy_array_equal(result_missing, expected_missing) + + # TODO we may also want to test get_indexer for the case when + # the intervals are duplicated, decreasing, non-monotonic, etc.. + + def test_get_indexer_non_monotonic(self): + # GH 16410 + idx1 = IntervalIndex.from_tuples([(2, 3), (4, 5), (0, 1)]) + idx2 = IntervalIndex.from_tuples([(0, 1), (2, 3), (6, 7), (8, 9)]) + result = idx1.get_indexer(idx2) + expected = np.array([2, 0, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = idx1.get_indexer(idx1[1:]) + expected = np.array([1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_with_nans(self): + # GH#41831 + index = IntervalIndex([np.nan, np.nan]) + other = IntervalIndex([np.nan]) + + assert not index._index_as_unique + + result = index.get_indexer_for(other) + expected = np.array([0, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_index_non_unique_non_monotonic(self): + # GH#44084 (root cause) + index = IntervalIndex.from_tuples( + [(0.0, 1.0), (1.0, 2.0), (0.0, 1.0), (1.0, 2.0)] + ) + + result, _ = index.get_indexer_non_unique([Interval(1.0, 2.0)]) + expected = np.array([1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_multiindex_with_intervals(self): + # GH#44084 (MultiIndex case as reported) + interval_index = IntervalIndex.from_tuples( + [(2.0, 3.0), (0.0, 1.0), (1.0, 2.0)], name="interval" + ) + foo_index = Index([1, 2, 3], name="foo") + + multi_index = MultiIndex.from_product([foo_index, interval_index]) + + result = multi_index.get_level_values("interval").get_indexer_for( + [Interval(0.0, 1.0)] + ) + expected = np.array([1, 4, 7], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("box", [IntervalIndex, array, list]) + def test_get_indexer_interval_index(self, box): + # GH#30178 + rng = period_range("2022-07-01", freq="D", periods=3) + idx = box(interval_range(Timestamp("2022-07-01"), freq="3D", periods=3)) + + actual = rng.get_indexer(idx) + expected = np.array([-1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(actual, expected) + + def test_get_indexer_read_only(self): + idx = interval_range(start=0, end=5) + arr = np.array([1, 2]) + arr.flags.writeable = False + result = idx.get_indexer(arr) + expected = np.array([0, 1]) + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + + result = idx.get_indexer_non_unique(arr)[0] + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + + +class TestSliceLocs: + def test_slice_locs_with_interval(self): + # increasing monotonically + index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)]) + + assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(start=Interval(0, 2)) == (0, 3) + assert index.slice_locs(end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=Interval(0, 2)) == (0, 1) + assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 1) + + # decreasing monotonically + index = IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)]) + + assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (2, 1) + assert index.slice_locs(start=Interval(0, 2)) == (2, 3) + assert index.slice_locs(end=Interval(2, 4)) == (0, 1) + assert index.slice_locs(end=Interval(0, 2)) == (0, 3) + assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (0, 3) + + # sorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)]) + + assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(start=Interval(0, 2)) == (0, 3) + assert index.slice_locs(end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=Interval(0, 2)) == (0, 2) + assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2) + + # unsorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)]) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get left slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get left slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(start=Interval(0, 2)) + + assert index.slice_locs(end=Interval(2, 4)) == (0, 2) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get right slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(end=Interval(0, 2)) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get right slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) + + # another unsorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)]) + + assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(start=Interval(0, 2)) == (0, 4) + assert index.slice_locs(end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=Interval(0, 2)) == (0, 2) + assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2) + + def test_slice_locs_with_ints_and_floats_succeeds(self): + # increasing non-overlapping + index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]) + + assert index.slice_locs(0, 1) == (0, 1) + assert index.slice_locs(0, 2) == (0, 2) + assert index.slice_locs(0, 3) == (0, 2) + assert index.slice_locs(3, 1) == (2, 1) + assert index.slice_locs(3, 4) == (2, 3) + assert index.slice_locs(0, 4) == (0, 3) + + # decreasing non-overlapping + index = IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)]) + assert index.slice_locs(0, 1) == (3, 3) + assert index.slice_locs(0, 2) == (3, 2) + assert index.slice_locs(0, 3) == (3, 1) + assert index.slice_locs(3, 1) == (1, 3) + assert index.slice_locs(3, 4) == (1, 1) + assert index.slice_locs(0, 4) == (3, 1) + + @pytest.mark.parametrize("query", [[0, 1], [0, 2], [0, 3], [0, 4]]) + @pytest.mark.parametrize( + "tuples", + [ + [(0, 2), (1, 3), (2, 4)], + [(2, 4), (1, 3), (0, 2)], + [(0, 2), (0, 2), (2, 4)], + [(0, 2), (2, 4), (0, 2)], + [(0, 2), (0, 2), (2, 4), (1, 3)], + ], + ) + def test_slice_locs_with_ints_and_floats_errors(self, tuples, query): + start, stop = query + index = IntervalIndex.from_tuples(tuples) + with pytest.raises( + KeyError, + match=( + "'can only get slices from an IntervalIndex if bounds are " + "non-overlapping and all monotonic increasing or decreasing'" + ), + ): + index.slice_locs(start, stop) + + +class TestPutmask: + @pytest.mark.parametrize("tz", ["US/Pacific", None]) + def test_putmask_dt64(self, tz): + # GH#37968 + dti = date_range("2016-01-01", periods=9, tz=tz) + idx = IntervalIndex.from_breaks(dti) + mask = np.zeros(idx.shape, dtype=bool) + mask[0:3] = True + + result = idx.putmask(mask, idx[-1]) + expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:])) + tm.assert_index_equal(result, expected) + + def test_putmask_td64(self): + # GH#37968 + dti = date_range("2016-01-01", periods=9) + tdi = dti - dti[0] + idx = IntervalIndex.from_breaks(tdi) + mask = np.zeros(idx.shape, dtype=bool) + mask[0:3] = True + + result = idx.putmask(mask, idx[-1]) + expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:])) + tm.assert_index_equal(result, expected) + + +class TestContains: + # .__contains__, not .contains + + def test_contains_dunder(self): + index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right") + + # __contains__ requires perfect matches to intervals. + assert 0 not in index + assert 1 not in index + assert 2 not in index + + assert Interval(0, 1, closed="right") in index + assert Interval(0, 2, closed="right") not in index + assert Interval(0, 0.5, closed="right") not in index + assert Interval(3, 5, closed="right") not in index + assert Interval(-1, 0, closed="left") not in index + assert Interval(0, 1, closed="left") not in index + assert Interval(0, 1, closed="both") not in index diff --git a/shared/package-files/38/3845fa5bbc018f5689222ab7f6a171b2dc96271900a74f11cce2e895739b7883/str.py b/shared/package-files/38/3845fa5bbc018f5689222ab7f6a171b2dc96271900a74f11cce2e895739b7883/str.py new file mode 100644 index 0000000000000000000000000000000000000000..d748c244758219f0278ad9f1081eeb923e9b8591 --- /dev/null +++ b/shared/package-files/38/3845fa5bbc018f5689222ab7f6a171b2dc96271900a74f11cce2e895739b7883/str.py @@ -0,0 +1,1027 @@ +""" +A Printer for generating readable representation of most SymPy classes. +""" + +from __future__ import annotations +from typing import Any + +from sympy.core import S, Rational, Pow, Basic, Mul, Number +from sympy.core.mul import _keep_coeff +from sympy.core.relational import Relational +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import SympifyError +from sympy.utilities.iterables import sift +from .precedence import precedence, PRECEDENCE +from .printer import Printer, print_function + +from mpmath.libmp import prec_to_dps, to_str as mlib_to_str + + +class StrPrinter(Printer): + printmethod = "_sympystr" + _default_settings: dict[str, Any] = { + "order": None, + "full_prec": "auto", + "sympy_integers": False, + "abbrev": False, + "perm_cyclic": True, + "min": None, + "max": None, + } + + _relationals: dict[str, str] = {} + + def parenthesize(self, item, level, strict=False): + if (precedence(item) < level) or ((not strict) and precedence(item) <= level): + return "(%s)" % self._print(item) + else: + return self._print(item) + + def stringify(self, args, sep, level=0): + return sep.join([self.parenthesize(item, level) for item in args]) + + def emptyPrinter(self, expr): + if isinstance(expr, str): + return expr + elif isinstance(expr, Basic): + return repr(expr) + else: + return str(expr) + + def _print_Add(self, expr, order=None): + terms = self._as_ordered_terms(expr, order=order) + + prec = precedence(expr) + l = [] + for term in terms: + t = self._print(term) + if t.startswith('-') and not term.is_Add: + sign = "-" + t = t[1:] + else: + sign = "+" + if precedence(term) < prec or term.is_Add: + l.extend([sign, "(%s)" % t]) + else: + l.extend([sign, t]) + sign = l.pop(0) + if sign == '+': + sign = "" + return sign + ' '.join(l) + + def _print_BooleanTrue(self, expr): + return "True" + + def _print_BooleanFalse(self, expr): + return "False" + + def _print_Not(self, expr): + return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) + + def _print_And(self, expr): + args = list(expr.args) + for j, i in enumerate(args): + if isinstance(i, Relational) and ( + i.canonical.rhs is S.NegativeInfinity): + args.insert(0, args.pop(j)) + return self.stringify(args, " & ", PRECEDENCE["BitwiseAnd"]) + + def _print_Or(self, expr): + return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) + + def _print_Xor(self, expr): + return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) + + def _print_AppliedPredicate(self, expr): + return '%s(%s)' % ( + self._print(expr.function), self.stringify(expr.arguments, ", ")) + + def _print_Basic(self, expr): + l = [self._print(o) for o in expr.args] + return expr.__class__.__name__ + "(%s)" % ", ".join(l) + + def _print_BlockMatrix(self, B): + if B.blocks.shape == (1, 1): + self._print(B.blocks[0, 0]) + return self._print(B.blocks) + + def _print_Catalan(self, expr): + return 'Catalan' + + def _print_ComplexInfinity(self, expr): + return 'zoo' + + def _print_ConditionSet(self, s): + args = tuple([self._print(i) for i in (s.sym, s.condition)]) + if s.base_set is S.UniversalSet: + return 'ConditionSet(%s, %s)' % args + args += (self._print(s.base_set),) + return 'ConditionSet(%s, %s, %s)' % args + + def _print_Derivative(self, expr): + dexpr = expr.expr + dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] + return 'Derivative(%s)' % ", ".join((self._print(arg) for arg in [dexpr] + dvars)) + + def _print_dict(self, d): + keys = sorted(d.keys(), key=default_sort_key) + items = [] + + for key in keys: + item = "%s: %s" % (self._print(key), self._print(d[key])) + items.append(item) + + return "{%s}" % ", ".join(items) + + def _print_Dict(self, expr): + return self._print_dict(expr) + + def _print_RandomDomain(self, d): + if hasattr(d, 'as_boolean'): + return 'Domain: ' + self._print(d.as_boolean()) + elif hasattr(d, 'set'): + return ('Domain: ' + self._print(d.symbols) + ' in ' + + self._print(d.set)) + else: + return 'Domain on ' + self._print(d.symbols) + + def _print_Dummy(self, expr): + return '_' + expr.name + + def _print_EulerGamma(self, expr): + return 'EulerGamma' + + def _print_Exp1(self, expr): + return 'E' + + def _print_ExprCondPair(self, expr): + return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) + + def _print_Function(self, expr): + return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") + + def _print_GoldenRatio(self, expr): + return 'GoldenRatio' + + def _print_Heaviside(self, expr): + # Same as _print_Function but uses pargs to suppress default 1/2 for + # 2nd args + return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ") + + def _print_TribonacciConstant(self, expr): + return 'TribonacciConstant' + + def _print_ImaginaryUnit(self, expr): + return 'I' + + def _print_Infinity(self, expr): + return 'oo' + + def _print_Integral(self, expr): + def _xab_tostr(xab): + if len(xab) == 1: + return self._print(xab[0]) + else: + return self._print((xab[0],) + tuple(xab[1:])) + L = ', '.join([_xab_tostr(l) for l in expr.limits]) + return 'Integral(%s, %s)' % (self._print(expr.function), L) + + def _print_Interval(self, i): + fin = 'Interval{m}({a}, {b})' + a, b, l, r = i.args + if a.is_infinite and b.is_infinite: + m = '' + elif a.is_infinite and not r: + m = '' + elif b.is_infinite and not l: + m = '' + elif not l and not r: + m = '' + elif l and r: + m = '.open' + elif l: + m = '.Lopen' + else: + m = '.Ropen' + return fin.format(**{'a': a, 'b': b, 'm': m}) + + def _print_AccumulationBounds(self, i): + return "AccumBounds(%s, %s)" % (self._print(i.min), + self._print(i.max)) + + def _print_Inverse(self, I): + return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) + + def _print_Lambda(self, obj): + expr = obj.expr + sig = obj.signature + if len(sig) == 1 and sig[0].is_symbol: + sig = sig[0] + return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) + + def _print_LatticeOp(self, expr): + args = sorted(expr.args, key=default_sort_key) + return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) + + def _print_Limit(self, expr): + e, z, z0, dir = expr.args + return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) + + + def _print_list(self, expr): + return "[%s]" % self.stringify(expr, ", ") + + def _print_List(self, expr): + return self._print_list(expr) + + def _print_MatrixBase(self, expr): + return expr._format_str(self) + + def _print_MatrixElement(self, expr): + return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) + + def _print_MatrixSlice(self, expr): + def strslice(x, dim): + x = list(x) + if x[2] == 1: + del x[2] + if x[0] == 0: + x[0] = '' + if x[1] == dim: + x[1] = '' + return ':'.join((self._print(arg) for arg in x)) + return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + + strslice(expr.rowslice, expr.parent.rows) + ', ' + + strslice(expr.colslice, expr.parent.cols) + ']') + + def _print_DeferredVector(self, expr): + return expr.name + + def _print_Mul(self, expr): + + prec = precedence(expr) + + # Check for unevaluated Mul. In this case we need to make sure the + # identities are visible, multiple Rational factors are not combined + # etc so we display in a straight-forward form that fully preserves all + # args and their order. + args = expr.args + if args[0] is S.One or any( + isinstance(a, Number) or + a.is_Pow and all(ai.is_Integer for ai in a.args) + for a in args[1:]): + d, n = sift(args, lambda x: + isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0), + binary=True) + for i, di in enumerate(d): + if di.exp.is_Number: + e = -di.exp + else: + dargs = list(di.exp.args) + dargs[0] = -dargs[0] + e = Mul._from_args(dargs) + d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base + + pre = [] + # don't parenthesize first factor if negative + if n and not n[0].is_Add and n[0].could_extract_minus_sign(): + pre = [self._print(n.pop(0))] + + nfactors = pre + [self.parenthesize(a, prec, strict=False) + for a in n] + if not nfactors: + nfactors = ['1'] + + # don't parenthesize first of denominator unless singleton + if len(d) > 1 and d[0].could_extract_minus_sign(): + pre = [self._print(d.pop(0))] + else: + pre = [] + dfactors = pre + [self.parenthesize(a, prec, strict=False) + for a in d] + + n = '*'.join(nfactors) + d = '*'.join(dfactors) + if len(dfactors) > 1: + return '%s/(%s)' % (n, d) + elif dfactors: + return '%s/%s' % (n, d) + return n + + c, e = expr.as_coeff_Mul() + if c < 0: + expr = _keep_coeff(-c, e) + sign = "-" + else: + sign = "" + + a = [] # items in the numerator + b = [] # items that are in the denominator (if any) + + pow_paren = [] # Will collect all pow with more than one base element and exp = -1 + + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + # Gather args for numerator/denominator + def apow(i): + b, e = i.as_base_exp() + eargs = list(Mul.make_args(e)) + if eargs[0] is S.NegativeOne: + eargs = eargs[1:] + else: + eargs[0] = -eargs[0] + e = Mul._from_args(eargs) + if isinstance(i, Pow): + return i.func(b, e, evaluate=False) + return i.func(e, evaluate=False) + for item in args: + if (item.is_commutative and + isinstance(item, Pow) and + bool(item.exp.as_coeff_Mul()[0] < 0)): + if item.exp is not S.NegativeOne: + b.append(apow(item)) + else: + if (len(item.args[0].args) != 1 and + isinstance(item.base, (Mul, Pow))): + # To avoid situations like #14160 + pow_paren.append(item) + b.append(item.base) + elif item.is_Rational and item is not S.Infinity: + if item.p != 1: + a.append(Rational(item.p)) + if item.q != 1: + b.append(Rational(item.q)) + else: + a.append(item) + + a = a or [S.One] + + a_str = [self.parenthesize(x, prec, strict=False) for x in a] + b_str = [self.parenthesize(x, prec, strict=False) for x in b] + + # To parenthesize Pow with exp = -1 and having more than one Symbol + for item in pow_paren: + if item.base in b: + b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] + + if not b: + return sign + '*'.join(a_str) + elif len(b) == 1: + return sign + '*'.join(a_str) + "/" + b_str[0] + else: + return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) + + def _print_MatMul(self, expr): + c, m = expr.as_coeff_mmul() + + sign = "" + if c.is_number: + re, im = c.as_real_imag() + if im.is_zero and re.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + elif re.is_zero and im.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + + return sign + '*'.join( + [self.parenthesize(arg, precedence(expr)) for arg in expr.args] + ) + + def _print_ElementwiseApplyFunction(self, expr): + return "{}.({})".format( + expr.function, + self._print(expr.expr), + ) + + def _print_NaN(self, expr): + return 'nan' + + def _print_NegativeInfinity(self, expr): + return '-oo' + + def _print_Order(self, expr): + if not expr.variables or all(p is S.Zero for p in expr.point): + if len(expr.variables) <= 1: + return 'O(%s)' % self._print(expr.expr) + else: + return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) + else: + return 'O(%s)' % self.stringify(expr.args, ', ', 0) + + def _print_Ordinal(self, expr): + return expr.__str__() + + def _print_Cycle(self, expr): + return expr.__str__() + + def _print_Permutation(self, expr): + from sympy.combinatorics.permutations import Permutation, Cycle + from sympy.utilities.exceptions import sympy_deprecation_warning + + perm_cyclic = Permutation.print_cyclic + if perm_cyclic is not None: + sympy_deprecation_warning( + f""" + Setting Permutation.print_cyclic is deprecated. Instead use + init_printing(perm_cyclic={perm_cyclic}). + """, + deprecated_since_version="1.6", + active_deprecations_target="deprecated-permutation-print_cyclic", + stacklevel=7, + ) + else: + perm_cyclic = self._settings.get("perm_cyclic", True) + + if perm_cyclic: + if not expr.size: + return '()' + # before taking Cycle notation, see if the last element is + # a singleton and move it to the head of the string + s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] + last = s.rfind('(') + if not last == 0 and ',' not in s[last:]: + s = s[last:] + s[:last] + s = s.replace(',', '') + return s + else: + s = expr.support() + if not s: + if expr.size < 5: + return 'Permutation(%s)' % self._print(expr.array_form) + return 'Permutation([], size=%s)' % self._print(expr.size) + trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) + use = full = self._print(expr.array_form) + if len(trim) < len(full): + use = trim + return 'Permutation(%s)' % use + + def _print_Subs(self, obj): + expr, old, new = obj.args + if len(obj.point) == 1: + old = old[0] + new = new[0] + return "Subs(%s, %s, %s)" % ( + self._print(expr), self._print(old), self._print(new)) + + def _print_TensorIndex(self, expr): + return expr._print() + + def _print_TensorHead(self, expr): + return expr._print() + + def _print_Tensor(self, expr): + return expr._print() + + def _print_TensMul(self, expr): + # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" + sign, args = expr._get_args_for_traditional_printer() + return sign + "*".join( + [self.parenthesize(arg, precedence(expr)) for arg in args] + ) + + def _print_TensAdd(self, expr): + return expr._print() + + def _print_ArraySymbol(self, expr): + return self._print(expr.name) + + def _print_ArrayElement(self, expr): + return "%s[%s]" % ( + self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([self._print(i) for i in expr.indices])) + + def _print_PermutationGroup(self, expr): + p = [' %s' % self._print(a) for a in expr.args] + return 'PermutationGroup([\n%s])' % ',\n'.join(p) + + def _print_Pi(self, expr): + return 'pi' + + def _print_PolyRing(self, ring): + return "Polynomial ring in %s over %s with %s order" % \ + (", ".join((self._print(rs) for rs in ring.symbols)), + self._print(ring.domain), self._print(ring.order)) + + def _print_FracField(self, field): + return "Rational function field in %s over %s with %s order" % \ + (", ".join((self._print(fs) for fs in field.symbols)), + self._print(field.domain), self._print(field.order)) + + def _print_FreeGroupElement(self, elm): + return elm.__str__() + + def _print_GaussianElement(self, poly): + return "(%s + %s*I)" % (poly.x, poly.y) + + def _print_PolyElement(self, poly): + return poly.str(self, PRECEDENCE, "%s**%s", "*") + + def _print_FracElement(self, frac): + if frac.denom == 1: + return self._print(frac.numer) + else: + numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) + denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) + return numer + "/" + denom + + def _print_Poly(self, expr): + ATOM_PREC = PRECEDENCE["Atom"] - 1 + terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] + + for monom, coeff in expr.terms(): + s_monom = [] + + for i, e in enumerate(monom): + if e > 0: + if e == 1: + s_monom.append(gens[i]) + else: + s_monom.append(gens[i] + "**%d" % e) + + s_monom = "*".join(s_monom) + + if coeff.is_Add: + if s_monom: + s_coeff = "(" + self._print(coeff) + ")" + else: + s_coeff = self._print(coeff) + else: + if s_monom: + if coeff is S.One: + terms.extend(['+', s_monom]) + continue + + if coeff is S.NegativeOne: + terms.extend(['-', s_monom]) + continue + + s_coeff = self._print(coeff) + + if not s_monom: + s_term = s_coeff + else: + s_term = s_coeff + "*" + s_monom + + if s_term.startswith('-'): + terms.extend(['-', s_term[1:]]) + else: + terms.extend(['+', s_term]) + + if terms[0] in ('-', '+'): + modifier = terms.pop(0) + + if modifier == '-': + terms[0] = '-' + terms[0] + + format = expr.__class__.__name__ + "(%s, %s" + + from sympy.polys.polyerrors import PolynomialError + + try: + format += ", modulus=%s" % expr.get_modulus() + except PolynomialError: + format += ", domain='%s'" % expr.get_domain() + + format += ")" + + for index, item in enumerate(gens): + if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): + gens[index] = item[1:len(item) - 1] + + return format % (' '.join(terms), ', '.join(gens)) + + def _print_UniversalSet(self, p): + return 'UniversalSet' + + def _print_AlgebraicNumber(self, expr): + if expr.is_aliased: + return self._print(expr.as_poly().as_expr()) + else: + return self._print(expr.as_expr()) + + def _print_Pow(self, expr, rational=False): + """Printing helper function for ``Pow`` + + Parameters + ========== + + rational : bool, optional + If ``True``, it will not attempt printing ``sqrt(x)`` or + ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` + instead. + + See examples for additional details + + Examples + ======== + + >>> from sympy import sqrt, StrPrinter + >>> from sympy.abc import x + + How ``rational`` keyword works with ``sqrt``: + + >>> printer = StrPrinter() + >>> printer._print_Pow(sqrt(x), rational=True) + 'x**(1/2)' + >>> printer._print_Pow(sqrt(x), rational=False) + 'sqrt(x)' + >>> printer._print_Pow(1/sqrt(x), rational=True) + 'x**(-1/2)' + >>> printer._print_Pow(1/sqrt(x), rational=False) + '1/sqrt(x)' + + Notes + ===== + + ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, + so there is no need of defining a separate printer for ``sqrt``. + Instead, it should be handled here as well. + """ + PREC = precedence(expr) + + if expr.exp is S.Half and not rational: + return "sqrt(%s)" % self._print(expr.base) + + if expr.is_commutative: + if -expr.exp is S.Half and not rational: + # Note: Don't test "expr.exp == -S.Half" here, because that will + # match -0.5, which we don't want. + return "%s/sqrt(%s)" % tuple((self._print(arg) for arg in (S.One, expr.base))) + if expr.exp is -S.One: + # Similarly to the S.Half case, don't test with "==" here. + return '%s/%s' % (self._print(S.One), + self.parenthesize(expr.base, PREC, strict=False)) + + e = self.parenthesize(expr.exp, PREC, strict=False) + if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: + # the parenthesized exp should be '(Rational(a, b))' so strip parens, + # but just check to be sure. + if e.startswith('(Rational'): + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) + + def _print_UnevaluatedExpr(self, expr): + return self._print(expr.args[0]) + + def _print_MatPow(self, expr): + PREC = precedence(expr) + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), + self.parenthesize(expr.exp, PREC, strict=False)) + + def _print_Integer(self, expr): + if self._settings.get("sympy_integers", False): + return "S(%s)" % (expr) + return str(expr.p) + + def _print_Integers(self, expr): + return 'Integers' + + def _print_Naturals(self, expr): + return 'Naturals' + + def _print_Naturals0(self, expr): + return 'Naturals0' + + def _print_Rationals(self, expr): + return 'Rationals' + + def _print_Reals(self, expr): + return 'Reals' + + def _print_Complexes(self, expr): + return 'Complexes' + + def _print_EmptySet(self, expr): + return 'EmptySet' + + def _print_EmptySequence(self, expr): + return 'EmptySequence' + + def _print_int(self, expr): + return str(expr) + + def _print_mpz(self, expr): + return str(expr) + + def _print_Rational(self, expr): + if expr.q == 1: + return str(expr.p) + else: + if self._settings.get("sympy_integers", False): + return "S(%s)/%s" % (expr.p, expr.q) + return "%s/%s" % (expr.p, expr.q) + + def _print_PythonRational(self, expr): + if expr.q == 1: + return str(expr.p) + else: + return "%d/%d" % (expr.p, expr.q) + + def _print_Fraction(self, expr): + if expr.denominator == 1: + return str(expr.numerator) + else: + return "%s/%s" % (expr.numerator, expr.denominator) + + def _print_mpq(self, expr): + if expr.denominator == 1: + return str(expr.numerator) + else: + return "%s/%s" % (expr.numerator, expr.denominator) + + def _print_Float(self, expr): + prec = expr._prec + if prec < 5: + dps = 0 + else: + dps = prec_to_dps(expr._prec) + if self._settings["full_prec"] is True: + strip = False + elif self._settings["full_prec"] is False: + strip = True + elif self._settings["full_prec"] == "auto": + strip = self._print_level > 1 + low = self._settings["min"] if "min" in self._settings else None + high = self._settings["max"] if "max" in self._settings else None + rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) + if rv.startswith('-.0'): + rv = '-0.' + rv[3:] + elif rv.startswith('.0'): + rv = '0.' + rv[2:] + if rv.startswith('+'): + # e.g., +inf -> inf + rv = rv[1:] + return rv + + def _print_Relational(self, expr): + + charmap = { + "==": "Eq", + "!=": "Ne", + ":=": "Assignment", + '+=': "AddAugmentedAssignment", + "-=": "SubAugmentedAssignment", + "*=": "MulAugmentedAssignment", + "/=": "DivAugmentedAssignment", + "%=": "ModAugmentedAssignment", + } + + if expr.rel_op in charmap: + return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), + self._print(expr.rhs)) + + return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), + self._relationals.get(expr.rel_op) or expr.rel_op, + self.parenthesize(expr.rhs, precedence(expr))) + + def _print_ComplexRootOf(self, expr): + return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), + expr.index) + + def _print_RootSum(self, expr): + args = [self._print_Add(expr.expr, order='lex')] + + if expr.fun is not S.IdentityFunction: + args.append(self._print(expr.fun)) + + return "RootSum(%s)" % ", ".join(args) + + def _print_GroebnerBasis(self, basis): + cls = basis.__class__.__name__ + + exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] + exprs = "[%s]" % ", ".join(exprs) + + gens = [ self._print(gen) for gen in basis.gens ] + domain = "domain='%s'" % self._print(basis.domain) + order = "order='%s'" % self._print(basis.order) + + args = [exprs] + gens + [domain, order] + + return "%s(%s)" % (cls, ", ".join(args)) + + def _print_set(self, s): + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(item) for item in items) + if not args: + return "set()" + return '{%s}' % args + + def _print_FiniteSet(self, s): + from sympy.sets.sets import FiniteSet + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(item) for item in items) + if any(item.has(FiniteSet) for item in items): + return 'FiniteSet({})'.format(args) + return '{{{}}}'.format(args) + + def _print_Partition(self, s): + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(arg) for arg in items) + return 'Partition({})'.format(args) + + def _print_frozenset(self, s): + if not s: + return "frozenset()" + return "frozenset(%s)" % self._print_set(s) + + def _print_Sum(self, expr): + def _xab_tostr(xab): + if len(xab) == 1: + return self._print(xab[0]) + else: + return self._print((xab[0],) + tuple(xab[1:])) + L = ', '.join([_xab_tostr(l) for l in expr.limits]) + return 'Sum(%s, %s)' % (self._print(expr.function), L) + + def _print_Symbol(self, expr): + return expr.name + _print_MatrixSymbol = _print_Symbol + _print_RandomSymbol = _print_Symbol + + def _print_Identity(self, expr): + return "I" + + def _print_ZeroMatrix(self, expr): + return "0" + + def _print_OneMatrix(self, expr): + return "1" + + def _print_Predicate(self, expr): + return "Q.%s" % expr.name + + def _print_str(self, expr): + return str(expr) + + def _print_tuple(self, expr): + if len(expr) == 1: + return "(%s,)" % self._print(expr[0]) + else: + return "(%s)" % self.stringify(expr, ", ") + + def _print_Tuple(self, expr): + return self._print_tuple(expr) + + def _print_Transpose(self, T): + return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) + + def _print_Uniform(self, expr): + return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) + + def _print_Quantity(self, expr): + if self._settings.get("abbrev", False): + return "%s" % expr.abbrev + return "%s" % expr.name + + def _print_Quaternion(self, expr): + s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] + a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] + return " + ".join(a) + + def _print_Dimension(self, expr): + return str(expr) + + def _print_Wild(self, expr): + return expr.name + '_' + + def _print_WildFunction(self, expr): + return expr.name + '_' + + def _print_WildDot(self, expr): + return expr.name + + def _print_WildPlus(self, expr): + return expr.name + + def _print_WildStar(self, expr): + return expr.name + + def _print_Zero(self, expr): + if self._settings.get("sympy_integers", False): + return "S(0)" + return "0" + + def _print_DMP(self, p): + try: + if p.ring is not None: + # TODO incorporate order + return self._print(p.ring.to_sympy(p)) + except SympifyError: + pass + + cls = p.__class__.__name__ + rep = self._print(p.rep) + dom = self._print(p.dom) + ring = self._print(p.ring) + + return "%s(%s, %s, %s)" % (cls, rep, dom, ring) + + def _print_DMF(self, expr): + return self._print_DMP(expr) + + def _print_Object(self, obj): + return 'Object("%s")' % obj.name + + def _print_IdentityMorphism(self, morphism): + return 'IdentityMorphism(%s)' % morphism.domain + + def _print_NamedMorphism(self, morphism): + return 'NamedMorphism(%s, %s, "%s")' % \ + (morphism.domain, morphism.codomain, morphism.name) + + def _print_Category(self, category): + return 'Category("%s")' % category.name + + def _print_Manifold(self, manifold): + return manifold.name.name + + def _print_Patch(self, patch): + return patch.name.name + + def _print_CoordSystem(self, coords): + return coords.name.name + + def _print_BaseScalarField(self, field): + return field._coord_sys.symbols[field._index].name + + def _print_BaseVectorField(self, field): + return 'e_%s' % field._coord_sys.symbols[field._index].name + + def _print_Differential(self, diff): + field = diff._form_field + if hasattr(field, '_coord_sys'): + return 'd%s' % field._coord_sys.symbols[field._index].name + else: + return 'd(%s)' % self._print(field) + + def _print_Tr(self, expr): + #TODO : Handle indices + return "%s(%s)" % ("Tr", self._print(expr.args[0])) + + def _print_Str(self, s): + return self._print(s.name) + + def _print_AppliedBinaryRelation(self, expr): + rel = expr.function + return '%s(%s, %s)' % (self._print(rel), + self._print(expr.lhs), + self._print(expr.rhs)) + + +@print_function(StrPrinter) +def sstr(expr, **settings): + """Returns the expression as a string. + + For large expressions where speed is a concern, use the setting + order='none'. If abbrev=True setting is used then units are printed in + abbreviated form. + + Examples + ======== + + >>> from sympy import symbols, Eq, sstr + >>> a, b = symbols('a b') + >>> sstr(Eq(a + b, 0)) + 'Eq(a + b, 0)' + """ + + p = StrPrinter(settings) + s = p.doprint(expr) + + return s + + +class StrReprPrinter(StrPrinter): + """(internal) -- see sstrrepr""" + + def _print_str(self, s): + return repr(s) + + def _print_Str(self, s): + # Str does not to be printed same as str here + return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) + + +@print_function(StrReprPrinter) +def sstrrepr(expr, **settings): + """return expr in mixed str/repr form + + i.e. strings are returned in repr form with quotes, and everything else + is returned in str form. + + This function could be useful for hooking into sys.displayhook + """ + + p = StrReprPrinter(settings) + s = p.doprint(expr) + + return s diff --git a/shared/package-files/38/3847c5cf08ffb27d27ecdd7aab3bab4ca7fff2e3cc8d2a03ae16a12cdb8920c1/RECORD b/shared/package-files/38/3847c5cf08ffb27d27ecdd7aab3bab4ca7fff2e3cc8d2a03ae16a12cdb8920c1/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..49ab1ac7defb4ca6fd3cadf62b5e834272b20209 --- /dev/null +++ b/shared/package-files/38/3847c5cf08ffb27d27ecdd7aab3bab4ca7fff2e3cc8d2a03ae16a12cdb8920c1/RECORD @@ -0,0 +1,39 @@ +pexpect-4.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pexpect-4.8.0.dist-info/LICENSE,sha256=Skg64cTcc4psi3P-tJB04YNdoCq1qmhvJnUCmQb6Nk0,987 +pexpect-4.8.0.dist-info/METADATA,sha256=gD4QNR0Xubt0nLzHH_YhdcXrQS5MIHGuxE-kJs0RNJo,2180 +pexpect-4.8.0.dist-info/RECORD,, +pexpect-4.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pexpect-4.8.0.dist-info/WHEEL,sha256=ADKeyaGyKF5DwBNE0sRE5pvW-bSkFMJfBuhzZ3rceP4,110 +pexpect-4.8.0.dist-info/direct_url.json,sha256=eCMvawUc5vVZsEri7i8XkqbpTmHJw8EjPixOLeBkX18,80 +pexpect-4.8.0.dist-info/top_level.txt,sha256=O-b3UY9VQZkW3yDAeFNatUOKO4GojVWO4TTHoI9-E7k,8 +pexpect/ANSI.py,sha256=aA-3tdXz_FZ4G7PAqFZi5g1KBGQ6PzJzS0gm3ALZKZw,12177 +pexpect/FSM.py,sha256=tluiyUGMyIH3q_wLG6Ak1NZVuXUAGNDjq6k6BK1q8RY,13419 +pexpect/__init__.py,sha256=xF4qylJdK-FRy40tmhAXu99fV9ewFasxTH3DSgoZjzQ,3902 +pexpect/__pycache__/ANSI.cpython-36.pyc,, +pexpect/__pycache__/FSM.cpython-36.pyc,, +pexpect/__pycache__/__init__.cpython-36.pyc,, +pexpect/__pycache__/_async.cpython-36.pyc,, +pexpect/__pycache__/exceptions.cpython-36.pyc,, +pexpect/__pycache__/expect.cpython-36.pyc,, +pexpect/__pycache__/fdpexpect.cpython-36.pyc,, +pexpect/__pycache__/popen_spawn.cpython-36.pyc,, +pexpect/__pycache__/pty_spawn.cpython-36.pyc,, +pexpect/__pycache__/pxssh.cpython-36.pyc,, +pexpect/__pycache__/replwrap.cpython-36.pyc,, +pexpect/__pycache__/run.cpython-36.pyc,, +pexpect/__pycache__/screen.cpython-36.pyc,, +pexpect/__pycache__/spawnbase.cpython-36.pyc,, +pexpect/__pycache__/utils.cpython-36.pyc,, +pexpect/_async.py,sha256=UCUC9kbBZGjzG12YcR_M5yBjB4Dwc8nJOYNPklL-OdU,3304 +pexpect/bashrc.sh,sha256=CHK8qDg_HtDVdfyDULOV8MZDRDr4pOaIbo31XV58nQs,380 +pexpect/exceptions.py,sha256=A9C1PWbBc2j9AKvnv7UkPCawhFTEGYmeULW0vwbMvXQ,1068 +pexpect/expect.py,sha256=KKtBmx2MYa-yDE715XlHUcloKe5ndBD359a4OYVXD84,13827 +pexpect/fdpexpect.py,sha256=ugTrwveFi-zfl_nOPjbRyLUER1Wmhu8YxczCWtZgZWc,5828 +pexpect/popen_spawn.py,sha256=hVHOqr22jD2Pr-yVgsfwgqGAtULLi6kJLKQRrTBPvEg,6161 +pexpect/pty_spawn.py,sha256=ZygSYsdnVJ5acxiNM9gLvLrT2AVqgwJvbDcPaTxxv9E,37382 +pexpect/pxssh.py,sha256=bZHwFDOn1gC8U_Sl07eFFRlYfCjGCwEoC9WaZCHQo5Y,24279 +pexpect/replwrap.py,sha256=Raq9XgYfIlF-rH_CALgFbzK1H_A4o0NqmK9q45anmVA,5633 +pexpect/run.py,sha256=XK2GwW6_wbUZ6buIDbhouaOySVPnc5IahbgSjieks50,6628 +pexpect/screen.py,sha256=-twD4sIEp83nzuYH9lRDzwHfesoTgVGWglsBYWOK7Ks,13704 +pexpect/spawnbase.py,sha256=FoaNvkGYIXrD6xmBedrJmm_oVLMatqbGCXc027CugkQ,21247 +pexpect/utils.py,sha256=1jIhzU7eBvY3pbW3LZoJhCOU2KWqgty5HgQ6VBYIp5U,6019 diff --git a/shared/package-files/38/384c95034123e05c6cc0e125ad436dd089f8b38621ae6b5ac44fcd1c666f1ad8/clusterfuzz-testcase-minimized-bs4_fuzzer-4999465949331456.testcase b/shared/package-files/38/384c95034123e05c6cc0e125ad436dd089f8b38621ae6b5ac44fcd1c666f1ad8/clusterfuzz-testcase-minimized-bs4_fuzzer-4999465949331456.testcase new file mode 100644 index 0000000000000000000000000000000000000000..dbeed3f57aba4e459e3f8d8036db72ad223e1845 --- /dev/null +++ b/shared/package-files/38/384c95034123e05c6cc0e125ad436dd089f8b38621ae6b5ac44fcd1c666f1ad8/clusterfuzz-testcase-minimized-bs4_fuzzer-4999465949331456.testcase @@ -0,0 +1 @@ +)

\ No newline at end of file diff --git a/shared/package-files/38/3850dd04f827fb35b1778689cbc1f19c5b3dd9eb93b412f0073902d7728f952b/xterm-mono b/shared/package-files/38/3850dd04f827fb35b1778689cbc1f19c5b3dd9eb93b412f0073902d7728f952b/xterm-mono new file mode 100644 index 0000000000000000000000000000000000000000..df66b3ee5184440b1c012395c4426de9986563ab Binary files /dev/null and b/shared/package-files/38/3850dd04f827fb35b1778689cbc1f19c5b3dd9eb93b412f0073902d7728f952b/xterm-mono differ diff --git a/shared/package-files/38/3852fb817818f2fd21ceb8588bb299fa6976a17fa348f00d8974f7b78af11e74/linalg_diagonal_ops.h b/shared/package-files/38/3852fb817818f2fd21ceb8588bb299fa6976a17fa348f00d8974f7b78af11e74/linalg_diagonal_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..1f7e3aed19d74b094368b44060145d583adc5a06 --- /dev/null +++ b/shared/package-files/38/3852fb817818f2fd21ceb8588bb299fa6976a17fa348f00d8974f7b78af11e74/linalg_diagonal_ops.h @@ -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 linalg_diagonal { + using schema = 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::linalg_diagonal") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_diagonal(Tensor(a) A, *, int offset=0, int dim1=-2, int dim2=-1) -> Tensor(a)") + static at::Tensor call(const at::Tensor & A, int64_t offset, int64_t dim1, int64_t dim2); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, int64_t offset, int64_t dim1, int64_t dim2); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/3854577e14fcfac9cbff855e3a36ce09dff26081aa552f8846b66858d70bdefe/_typing.py b/shared/package-files/38/3854577e14fcfac9cbff855e3a36ce09dff26081aa552f8846b66858d70bdefe/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ebb5abb987572be625ee864a37e61126d36d8b --- /dev/null +++ b/shared/package-files/38/3854577e14fcfac9cbff855e3a36ce09dff26081aa552f8846b66858d70bdefe/_typing.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +__all__ = [ + "ndarray", + "Device", + "Dtype", +] + +import sys +from typing import ( + Literal, + Union, + TYPE_CHECKING, +) + +from numpy import ( + ndarray, + dtype, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float32, + float64, +) + +Device = Literal["cpu"] +if TYPE_CHECKING or sys.version_info >= (3, 9): + Dtype = dtype[Union[ + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float32, + float64, + ]] +else: + Dtype = dtype diff --git a/shared/package-files/38/385dcdc4627a48dddb7ca5837068c982864f3db2cafa6c7d23443e839f483484/test_markov_autoregression.py b/shared/package-files/38/385dcdc4627a48dddb7ca5837068c982864f3db2cafa6c7d23443e839f483484/test_markov_autoregression.py new file mode 100644 index 0000000000000000000000000000000000000000..a22010b6e3f8c63a9dd85c85490f7929c58c0871 --- /dev/null +++ b/shared/package-files/38/385dcdc4627a48dddb7ca5837068c982864f3db2cafa6c7d23443e839f483484/test_markov_autoregression.py @@ -0,0 +1,903 @@ +""" +Tests for Markov Autoregression models + +Author: Chad Fulton +License: BSD-3 +""" +from pathlib import Path +import warnings + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pandas as pd +import pytest + +from statsmodels.tools import add_constant +from statsmodels.tsa.regime_switching import markov_autoregression + +current_path = Path(__file__).resolve().parent + + +rgnp = [2.59316421, 2.20217133, 0.45827562, 0.9687438, + -0.24130757, 0.89647478, 2.05393219, 1.73353648, + 0.93871289, -0.46477833, -0.80983406, -1.39763689, + -0.39886093, 1.1918416, 1.45620048, 2.11808228, + 1.08957863, 1.32390273, 0.87296367, -0.19773273, + 0.45420215, 0.07221876, 1.1030364, 0.82097489, + -0.05795795, 0.58447772, -1.56192672, -2.05041027, + 0.53637183, 2.33676839, 2.34014559, 1.2339263, + 1.8869648, -0.45920792, 0.84940469, 1.70139849, + -0.28756312, 0.09594627, -0.86080289, 1.03447127, + 1.23685944, 1.42004502, 2.22410631, 1.30210173, + 1.03517699, 0.9253425, -0.16559951, 1.3444382, + 1.37500131, 1.73222184, 0.71605635, 2.21032143, + 0.85333031, 1.00238776, 0.42725441, 2.14368343, + 1.43789184, 1.57959926, 2.27469826, 1.95962656, + 0.25992399, 1.01946914, 0.49016398, 0.5636338, + 0.5959546, 1.43082857, 0.56230122, 1.15388393, + 1.68722844, 0.77438205, -0.09647045, 1.39600146, + 0.13646798, 0.55223715, -0.39944872, -0.61671102, + -0.08722561, 1.2101835, -0.90729755, 2.64916158, + -0.0080694, 0.51111895, -0.00401437, 2.16821432, + 1.92586732, 1.03504717, 1.85897219, 2.32004929, + 0.25570789, -0.09855274, 0.89073682, -0.55896485, + 0.28350255, -1.31155407, -0.88278776, -1.97454941, + 1.01275265, 1.68264723, 1.38271284, 1.86073637, + 0.4447377, 0.41449001, 0.99202275, 1.36283576, + 1.59970522, 1.98845816, -0.25684232, 0.87786949, + 3.1095655, 0.85324478, 1.23337317, 0.00314302, + -0.09433369, 0.89883322, -0.19036628, 0.99772376, + -2.39120054, 0.06649673, 1.26136017, 1.91637838, + -0.3348029, 0.44207108, -1.40664911, -1.52129889, + 0.29919869, -0.80197448, 0.15204792, 0.98585027, + 2.13034606, 1.34397924, 1.61550522, 2.70930099, + 1.24461412, 0.50835466, 0.14802167] + +rec = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] + + +def test_predict(): + # AR(1) without mean, k_regimes=2 + endog = np.ones(10) + markov_autoregression.MarkovAutoregression( + endog, + k_regimes=2, + order=1, + trend="n" + ) + mod = markov_autoregression.MarkovAutoregression( + endog, k_regimes=2, order=1, trend="n") + assert_equal(mod.nobs, 9) + assert_equal(mod.endog, np.ones(9)) + + params = np.r_[0.5, 0.5, 1., 0.1, 0.5] + mod_resid = mod._resid(params) + resids = np.zeros((2, 2, mod.nobs)) + # Resids when: S_{t} = 0 + resids[0, :, :] = np.ones(9) - 0.1 * np.ones(9) + assert_allclose(mod_resid[0, :, :], resids[0, :, :]) + # Resids when: S_{t} = 1 + resids[1, :, :] = np.ones(9) - 0.5 * np.ones(9) + assert_allclose(mod_resid[1, :, :], resids[1, :, :]) + + # AR(1) with mean, k_regimes=2 + endog = np.arange(10) + mod = markov_autoregression.MarkovAutoregression( + endog, k_regimes=2, order=1) + assert_equal(mod.nobs, 9) + assert_equal(mod.endog, np.arange(1, 10)) + + params = np.r_[0.5, 0.5, 2., 3., 1., 0.1, 0.5] + mod_resid = mod._resid(params) + resids = np.zeros((2, 2, mod.nobs)) + # Resids when: S_t = 0, S_{t-1} = 0 + resids[0, 0, :] = (np.arange(1, 10) - 2.) - 0.1 * (np.arange(9) - 2.) + assert_allclose(mod_resid[0, 0, :], resids[0, 0, :]) + # Resids when: S_t = 0, S_{t-1} = 1 + resids[0, 1, :] = (np.arange(1, 10) - 2.) - 0.1 * (np.arange(9) - 3.) + assert_allclose(mod_resid[0, 1, :], resids[0, 1, :]) + # Resids when: S_t = 1, S_{t-1} = 0 + resids[1, 0, :] = (np.arange(1, 10) - 3.) - 0.5 * (np.arange(9) - 2.) + assert_allclose(mod_resid[1, 0, :], resids[1, 0, :]) + # Resids when: S_t = 1, S_{t-1} = 1 + resids[1, 1, :] = (np.arange(1, 10) - 3.) - 0.5 * (np.arange(9) - 3.) + assert_allclose(mod_resid[1, 1, :], resids[1, 1, :]) + + # AR(2) with mean, k_regimes=3 + endog = np.arange(10) + mod = markov_autoregression.MarkovAutoregression( + endog, k_regimes=3, order=2) + assert_equal(mod.nobs, 8) + assert_equal(mod.endog, np.arange(2, 10)) + + params = np.r_[[0.3] * 6, 2., 3., 4, 1., 0.1, 0.5, 0.8, -0.05, -0.25, -0.4] + mod_resid = mod._resid(params) + resids = np.zeros((3, 3, 3, mod.nobs)) + # Resids when: S_t = 0, S_{t-1} = 0, S_{t-2} = 0 + resids[0, 0, 0, :] = ( + (np.arange(2, 10) - 2.) - + 0.1 * (np.arange(1, 9) - 2.) - + (-0.05) * (np.arange(8) - 2.)) + assert_allclose(mod_resid[0, 0, 0, :], resids[0, 0, 0, :]) + + # Resids when: S_t = 1, S_{t-1} = 0, S_{t-2} = 0 + resids[1, 0, 0, :] = ( + (np.arange(2, 10) - 3.) - + 0.5 * (np.arange(1, 9) - 2.) - + (-0.25) * (np.arange(8) - 2.)) + assert_allclose(mod_resid[1, 0, 0, :], resids[1, 0, 0, :]) + + # Resids when: S_t = 0, S_{t-1} = 2, S_{t-2} = 1 + resids[0, 2, 1, :] = ( + (np.arange(2, 10) - 2.) - + 0.1 * (np.arange(1, 9) - 4.) - + (-0.05) * (np.arange(8) - 3.)) + assert_allclose(mod_resid[0, 2, 1, :], resids[0, 2, 1, :]) + + # AR(1) with mean + non-switching exog + endog = np.arange(10) + exog = np.r_[0.4, 5, 0.2, 1.2, -0.3, 2.5, 0.2, -0.7, 2., -1.1] + mod = markov_autoregression.MarkovAutoregression( + endog, k_regimes=2, order=1, exog=exog) + assert_equal(mod.nobs, 9) + assert_equal(mod.endog, np.arange(1, 10)) + + params = np.r_[0.5, 0.5, 2., 3., 1.5, 1., 0.1, 0.5] + mod_resid = mod._resid(params) + resids = np.zeros((2, 2, mod.nobs)) + # Resids when: S_t = 0, S_{t-1} = 0 + resids[0, 0, :] = ( + (np.arange(1, 10) - 2. - 1.5 * exog[1:]) - + 0.1 * (np.arange(9) - 2. - 1.5 * exog[:-1])) + assert_allclose(mod_resid[0, 0, :], resids[0, 0, :]) + # Resids when: S_t = 0, S_{t-1} = 1 + resids[0, 1, :] = ( + (np.arange(1, 10) - 2. - 1.5 * exog[1:]) - + 0.1 * (np.arange(9) - 3. - 1.5 * exog[:-1])) + assert_allclose(mod_resid[0, 1, :], resids[0, 1, :]) + # Resids when: S_t = 1, S_{t-1} = 0 + resids[1, 0, :] = ( + (np.arange(1, 10) - 3. - 1.5 * exog[1:]) - + 0.5 * (np.arange(9) - 2. - 1.5 * exog[:-1])) + assert_allclose(mod_resid[1, 0, :], resids[1, 0, :]) + # Resids when: S_t = 1, S_{t-1} = 1 + resids[1, 1, :] = ( + (np.arange(1, 10) - 3. - 1.5 * exog[1:]) - + 0.5 * (np.arange(9) - 3. - 1.5 * exog[:-1])) + assert_allclose(mod_resid[1, 1, :], resids[1, 1, :]) + + +def test_conditional_loglikelihoods(): + # AR(1) without mean, k_regimes=2, non-switching variance + endog = np.ones(10) + mod = markov_autoregression.MarkovAutoregression( + endog, k_regimes=2, order=1) + assert_equal(mod.nobs, 9) + assert_equal(mod.endog, np.ones(9)) + + params = np.r_[0.5, 0.5, 2., 3., 2., 0.1, 0.5] + resid = mod._resid(params) + conditional_likelihoods = ( + np.exp(-0.5 * resid**2 / 2) / np.sqrt(2 * np.pi * 2)) + assert_allclose(mod._conditional_loglikelihoods(params), + np.log(conditional_likelihoods)) + + # AR(1) without mean, k_regimes=3, switching variance + endog = np.ones(10) + mod = markov_autoregression.MarkovAutoregression( + endog, k_regimes=3, order=1, switching_variance=True) + assert_equal(mod.nobs, 9) + assert_equal(mod.endog, np.ones(9)) + + params = np.r_[[0.3]*6, 2., 3., 4., 1.5, 3., 4.5, 0.1, 0.5, 0.8] + mod_conditional_loglikelihoods = mod._conditional_loglikelihoods(params) + conditional_likelihoods = mod._resid(params) + + # S_t = 0 + conditional_likelihoods[0, :, :] = ( + np.exp(-0.5 * conditional_likelihoods[0, :, :]**2 / 1.5) / + np.sqrt(2 * np.pi * 1.5)) + assert_allclose(mod_conditional_loglikelihoods[0, :, :], + np.log(conditional_likelihoods[0, :, :])) + # S_t = 1 + conditional_likelihoods[1, :, :] = ( + np.exp(-0.5 * conditional_likelihoods[1, :, :]**2 / 3.) / + np.sqrt(2 * np.pi * 3.)) + assert_allclose(mod_conditional_loglikelihoods[1, :, :], + np.log(conditional_likelihoods[1, :, :])) + # S_t = 2 + conditional_likelihoods[2, :, :] = ( + np.exp(-0.5 * conditional_likelihoods[2, :, :]**2 / 4.5) / + np.sqrt(2 * np.pi * 4.5)) + assert_allclose(mod_conditional_loglikelihoods[2, :, :], + np.log(conditional_likelihoods[2, :, :])) + + +class MarkovAutoregression: + @classmethod + def setup_class(cls, true, endog, atol=1e-5, rtol=1e-7, **kwargs): + cls.model = markov_autoregression.MarkovAutoregression(endog, **kwargs) + cls.true = true + cls.result = cls.model.smooth(cls.true["params"]) + cls.atol = atol + cls.rtol = rtol + + def test_llf(self): + assert_allclose(self.result.llf, self.true["llf"], atol=self.atol, + rtol=self.rtol) + + def test_fit(self, **kwargs): + # Test fitting against Stata + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + res = self.model.fit(disp=False, **kwargs) + assert_allclose(res.llf, self.true["llf_fit"], atol=self.atol, + rtol=self.rtol) + + @pytest.mark.smoke + def test_fit_em(self, **kwargs): + # Test EM fitting (smoke test) + res_em = self.model._fit_em(**kwargs) + assert_allclose(res_em.llf, self.true["llf_fit_em"], atol=self.atol, + rtol=self.rtol) + + +hamilton_ar2_short_filtered_joint_probabilities = np.array([ + [[[4.99506987e-02, 6.44048275e-04, 6.22227140e-05, + 4.45756755e-06, 5.26645567e-07, 7.99846146e-07, + 1.19425705e-05, 6.87762063e-03], + [1.95930395e-02, 3.25884335e-04, 1.12955091e-04, + 3.38537103e-04, 9.81927968e-06, 2.71696750e-05, + 5.83828290e-03, 7.64261509e-02]], + + [[1.97113193e-03, 9.50372207e-05, 1.98390978e-04, + 1.88188953e-06, 4.83449400e-07, 1.14872860e-05, + 4.02918239e-06, 4.35015431e-04], + [2.24870443e-02, 1.27331172e-03, 9.62155856e-03, + 4.04178695e-03, 2.75516282e-04, 1.18179572e-02, + 5.99778157e-02, 1.48149567e-01]]], + + + [[[6.70912859e-02, 1.84223872e-02, 2.55621792e-04, + 4.48500688e-05, 7.80481515e-05, 2.73734559e-06, + 7.59835896e-06, 1.42930726e-03], + [2.10053328e-02, 7.44036383e-03, 3.70388879e-04, + 2.71878370e-03, 1.16152088e-03, 7.42182691e-05, + 2.96490192e-03, 1.26774695e-02]], + + [[8.09335679e-02, 8.31016518e-02, 2.49149080e-02, + 5.78825626e-04, 2.19019941e-03, 1.20179130e-03, + 7.83659430e-05, 2.76363377e-03], + [7.36967899e-01, 8.88697316e-01, 9.64463954e-01, + 9.92270877e-01, 9.96283886e-01, 9.86863839e-01, + 9.31117063e-01, 7.51241236e-01]]]]) + + +hamilton_ar2_short_predicted_joint_probabilities = np.array([[ + [[[1.20809334e-01, 3.76964436e-02, 4.86045844e-04, + 4.69578023e-05, 3.36400588e-06, 3.97445190e-07, + 6.03622290e-07, 9.01273552e-06], + [3.92723623e-02, 1.47863379e-02, 2.45936108e-04, + 8.52441571e-05, 2.55484811e-04, 7.41034525e-06, + 2.05042201e-05, 4.40599447e-03]], + + [[4.99131230e-03, 1.48756005e-03, 7.17220245e-05, + 1.49720314e-04, 1.42021122e-06, 3.64846209e-07, + 8.66914462e-06, 3.04071516e-06], + [4.70476003e-02, 1.69703652e-02, 9.60933974e-04, + 7.26113047e-03, 3.05022748e-03, 2.07924699e-04, + 8.91869322e-03, 4.52636381e-02]]], + + + [[[4.99131230e-03, 6.43506069e-03, 1.76698327e-03, + 2.45179642e-05, 4.30179435e-06, 7.48598845e-06, + 2.62552503e-07, 7.28796600e-07], + [1.62256192e-03, 2.01472650e-03, 7.13642497e-04, + 3.55258493e-05, 2.60772139e-04, 1.11407276e-04, + 7.11864528e-06, 2.84378568e-04]], + + [[5.97950448e-03, 7.76274317e-03, 7.97069493e-03, + 2.38971340e-03, 5.55180599e-05, 2.10072977e-04, + 1.15269812e-04, 7.51646942e-06], + [5.63621989e-02, 7.06862760e-02, 8.52394030e-02, + 9.25065601e-02, 9.51736612e-02, 9.55585689e-02, + 9.46550451e-02, 8.93080931e-02]]]], + + + + [[[[3.92723623e-02, 1.22542551e-02, 1.58002431e-04, + 1.52649118e-05, 1.09356167e-06, 1.29200377e-07, + 1.96223855e-07, 2.92983500e-06], + [1.27665503e-02, 4.80670161e-03, 7.99482261e-05, + 2.77109335e-05, 8.30522919e-05, 2.40893443e-06, + 6.66545485e-06, 1.43228843e-03]], + + [[1.62256192e-03, 4.83571884e-04, 2.33151963e-05, + 4.86706634e-05, 4.61678312e-07, 1.18603191e-07, + 2.81814142e-06, 9.88467229e-07], + [1.52941031e-02, 5.51667911e-03, 3.12377744e-04, + 2.36042810e-03, 9.91559466e-04, 6.75915830e-05, + 2.89926399e-03, 1.47141776e-02]]], + + + [[[4.70476003e-02, 6.06562252e-02, 1.66554040e-02, + 2.31103828e-04, 4.05482745e-05, 7.05621631e-05, + 2.47479309e-06, 6.86956236e-06], + [1.52941031e-02, 1.89906063e-02, 6.72672133e-03, + 3.34863029e-04, 2.45801156e-03, 1.05011361e-03, + 6.70996238e-05, 2.68052335e-03]], + + [[5.63621989e-02, 7.31708248e-02, 7.51309569e-02, + 2.25251946e-02, 5.23307566e-04, 1.98012644e-03, + 1.08652148e-03, 7.08494735e-05], + [5.31264334e-01, 6.66281623e-01, 8.03457913e-01, + 8.71957394e-01, 8.97097216e-01, 9.00725317e-01, + 8.92208794e-01, 8.41808970e-01]]]]]) + + +hamilton_ar2_short_smoothed_joint_probabilities = np.array([ + [[[1.29898189e-02, 1.66298475e-04, 1.29822987e-05, + 9.95268382e-07, 1.84473346e-07, 7.18761267e-07, + 1.69576494e-05, 6.87762063e-03], + [5.09522472e-03, 8.41459714e-05, 2.35672254e-05, + 7.55872505e-05, 3.43949612e-06, 2.44153330e-05, + 8.28997024e-03, 7.64261509e-02]], + + [[5.90021731e-04, 2.55342733e-05, 4.50698224e-05, + 5.30734135e-07, 1.80741761e-07, 1.11483792e-05, + 5.98539007e-06, 4.35015431e-04], + [6.73107901e-03, 3.42109009e-04, 2.18579464e-03, + 1.13987259e-03, 1.03004157e-04, 1.14692946e-02, + 8.90976350e-02, 1.48149567e-01]]], + + + [[[6.34648123e-02, 1.79187451e-02, 2.37462147e-04, + 3.55542558e-05, 7.63980455e-05, 2.90520820e-06, + 8.17644492e-06, 1.42930726e-03], + [1.98699352e-02, 7.23695477e-03, 3.44076057e-04, + 2.15527721e-03, 1.13696383e-03, 7.87695658e-05, + 3.19047276e-03, 1.26774695e-02]], + + [[8.81925054e-02, 8.33092133e-02, 2.51106301e-02, + 5.81007470e-04, 2.19065072e-03, 1.20221350e-03, + 7.56893839e-05, 2.76363377e-03], + [8.03066603e-01, 8.90916999e-01, 9.72040418e-01, + 9.96011175e-01, 9.96489179e-01, 9.87210535e-01, + 8.99315113e-01, 7.51241236e-01]]]]) + + +class TestHamiltonAR2Short(MarkovAutoregression): + # This is just a set of regression tests + @classmethod + def setup_class(cls): + true = { + "params": np.r_[0.754673, 0.095915, -0.358811, 1.163516, + np.exp(-0.262658)**2, 0.013486, -0.057521], + "llf": -10.14066, + "llf_fit": -4.0523073, + "llf_fit_em": -8.885836 + } + super().setup_class( + true, rgnp[-10:], k_regimes=2, order=2, switching_ar=False) + + def test_fit_em(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().test_fit_em() + + def test_filter_output(self, **kwargs): + res = self.result + + # Filtered + assert_allclose(res.filtered_joint_probabilities, + hamilton_ar2_short_filtered_joint_probabilities) + + # Predicted + desired = hamilton_ar2_short_predicted_joint_probabilities + if desired.ndim > res.predicted_joint_probabilities.ndim: + desired = desired.sum(axis=-2) + assert_allclose(res.predicted_joint_probabilities, desired) + + def test_smoother_output(self, **kwargs): + res = self.result + + # Filtered + assert_allclose(res.filtered_joint_probabilities, + hamilton_ar2_short_filtered_joint_probabilities) + + # Predicted + desired = hamilton_ar2_short_predicted_joint_probabilities + if desired.ndim > res.predicted_joint_probabilities.ndim: + desired = desired.sum(axis=-2) + assert_allclose(res.predicted_joint_probabilities, desired) + + # Smoothed, entry-by-entry + assert_allclose( + res.smoothed_joint_probabilities[..., -1], + hamilton_ar2_short_smoothed_joint_probabilities[..., -1]) + assert_allclose( + res.smoothed_joint_probabilities[..., -2], + hamilton_ar2_short_smoothed_joint_probabilities[..., -2]) + assert_allclose( + res.smoothed_joint_probabilities[..., -3], + hamilton_ar2_short_smoothed_joint_probabilities[..., -3]) + assert_allclose( + res.smoothed_joint_probabilities[..., :-3], + hamilton_ar2_short_smoothed_joint_probabilities[..., :-3]) + + +hamilton_ar4_filtered = [ + 0.776712, 0.949192, 0.996320, 0.990258, 0.940111, 0.537442, + 0.140001, 0.008942, 0.048480, 0.614097, 0.910889, 0.995463, + 0.979465, 0.992324, 0.984561, 0.751038, 0.776268, 0.522048, + 0.814956, 0.821786, 0.472729, 0.673567, 0.029031, 0.001556, + 0.433276, 0.985463, 0.995025, 0.966067, 0.998445, 0.801467, + 0.960997, 0.996431, 0.461365, 0.199357, 0.027398, 0.703626, + 0.946388, 0.985321, 0.998244, 0.989567, 0.984510, 0.986811, + 0.793788, 0.973675, 0.984848, 0.990418, 0.918427, 0.998769, + 0.977647, 0.978742, 0.927635, 0.998691, 0.988934, 0.991654, + 0.999288, 0.999073, 0.918636, 0.987710, 0.966876, 0.910015, + 0.826150, 0.969451, 0.844049, 0.941525, 0.993363, 0.949978, + 0.615206, 0.970915, 0.787585, 0.707818, 0.200476, 0.050835, + 0.140723, 0.809850, 0.086422, 0.990344, 0.785963, 0.817425, + 0.659152, 0.996578, 0.992860, 0.948501, 0.996883, 0.999712, + 0.906694, 0.725013, 0.963690, 0.386960, 0.241302, 0.009078, + 0.015789, 0.000896, 0.541530, 0.928686, 0.953704, 0.992741, + 0.935877, 0.918958, 0.977316, 0.987941, 0.987300, 0.996769, + 0.645469, 0.921285, 0.999917, 0.949335, 0.968914, 0.886025, + 0.777141, 0.904381, 0.368277, 0.607429, 0.002491, 0.227610, + 0.871284, 0.987717, 0.288705, 0.512124, 0.030329, 0.005177, + 0.256183, 0.020955, 0.051620, 0.549009, 0.991715, 0.987892, + 0.995377, 0.999833, 0.993756, 0.956164, 0.927714] + +hamilton_ar4_smoothed = [ + 0.968096, 0.991071, 0.998559, 0.958534, 0.540652, 0.072784, + 0.010999, 0.006228, 0.172144, 0.898574, 0.989054, 0.998293, + 0.986434, 0.993248, 0.976868, 0.858521, 0.847452, 0.675670, + 0.596294, 0.165407, 0.035270, 0.127967, 0.007414, 0.004944, + 0.815829, 0.998128, 0.998091, 0.993227, 0.999283, 0.921100, + 0.977171, 0.971757, 0.124680, 0.063710, 0.114570, 0.954701, + 0.994852, 0.997302, 0.999345, 0.995817, 0.996218, 0.994580, + 0.933990, 0.996054, 0.998151, 0.996976, 0.971489, 0.999786, + 0.997362, 0.996755, 0.993053, 0.999947, 0.998469, 0.997987, + 0.999830, 0.999360, 0.953176, 0.992673, 0.975235, 0.938121, + 0.946784, 0.986897, 0.905792, 0.969755, 0.995379, 0.914480, + 0.772814, 0.931385, 0.541742, 0.394596, 0.063428, 0.027829, + 0.124527, 0.286105, 0.069362, 0.995950, 0.961153, 0.962449, + 0.945022, 0.999855, 0.998943, 0.980041, 0.999028, 0.999838, + 0.863305, 0.607421, 0.575983, 0.013300, 0.007562, 0.000635, + 0.001806, 0.002196, 0.803550, 0.972056, 0.984503, 0.998059, + 0.985211, 0.988486, 0.994452, 0.994498, 0.998873, 0.999192, + 0.870482, 0.976282, 0.999961, 0.984283, 0.973045, 0.786176, + 0.403673, 0.275418, 0.115199, 0.257560, 0.004735, 0.493936, + 0.907360, 0.873199, 0.052959, 0.076008, 0.001653, 0.000847, + 0.062027, 0.021257, 0.219547, 0.955654, 0.999851, 0.997685, + 0.998324, 0.999939, 0.996858, 0.969209, 0.927714] + + +class TestHamiltonAR4(MarkovAutoregression): + @classmethod + def setup_class(cls): + # Results from E-views: + # Dependent variable followed by a list of switching regressors: + # rgnp c + # List of non-switching regressors: + # ar(1) ar(2) ar(3) ar(4) + # Do not check "Regime specific error variances" + # Switching type: Markov + # Number of Regimes: 2 + # Probability regressors: + # c + # Method SWITCHREG + # Sample 1951q1 1984q4 + true = { + "params": np.r_[0.754673, 0.095915, -0.358811, 1.163516, + np.exp(-0.262658)**2, 0.013486, -0.057521, + -0.246983, -0.212923], + "llf": -181.26339, + "llf_fit": -181.26339, + "llf_fit_em": -183.85444, + "bse_oim": np.r_[.0965189, .0377362, .2645396, .0745187, np.nan, + .1199942, .137663, .1069103, .1105311, ] + } + super().setup_class( + true, rgnp, k_regimes=2, order=4, switching_ar=False) + + def test_filtered_regimes(self): + res = self.result + assert_equal(len(res.filtered_marginal_probabilities[:, 1]), + self.model.nobs) + assert_allclose(res.filtered_marginal_probabilities[:, 1], + hamilton_ar4_filtered, atol=1e-5) + + def test_smoothed_regimes(self): + res = self.result + assert_equal(len(res.smoothed_marginal_probabilities[:, 1]), + self.model.nobs) + assert_allclose(res.smoothed_marginal_probabilities[:, 1], + hamilton_ar4_smoothed, atol=1e-5) + + def test_bse(self): + # Cannot compare middle element of bse because we estimate sigma^2 + # rather than sigma + bse = self.result.cov_params_approx.diagonal()**0.5 + assert_allclose(bse[:4], self.true["bse_oim"][:4], atol=1e-6) + assert_allclose(bse[6:], self.true["bse_oim"][6:], atol=1e-6) + + +class TestHamiltonAR2Switch(MarkovAutoregression): + # Results from Stata, see http://www.stata.com/manuals14/tsmswitch.pdf + @classmethod + def setup_class(cls): + path = Path(current_path).joinpath("results", "results_predict_rgnp.csv") + results = pd.read_csv(path) + + true = { + "params": np.r_[.3812383, .3564492, -.0055216, 1.195482, + .6677098**2, .3710719, .4621503, .7002937, + -.3206652], + "llf": -179.32354, + "llf_fit": -179.38684, + "llf_fit_em": -184.99606, + "bse_oim": np.r_[.1424841, .0994742, .2057086, .1225987, np.nan, + .1754383, .1652473, .187409, .1295937], + "smoothed0": results.iloc[3:]["switchar2_sm1"], + "smoothed1": results.iloc[3:]["switchar2_sm2"], + "predict0": results.iloc[3:]["switchar2_yhat1"], + "predict1": results.iloc[3:]["switchar2_yhat2"], + "predict_predicted": results.iloc[3:]["switchar2_pyhat"], + "predict_filtered": results.iloc[3:]["switchar2_fyhat"], + "predict_smoothed": results.iloc[3:]["switchar2_syhat"], + } + super().setup_class( + true, rgnp, k_regimes=2, order=2) + + def test_smoothed_marginal_probabilities(self): + assert_allclose(self.result.smoothed_marginal_probabilities[:, 0], + self.true["smoothed0"], atol=1e-6) + assert_allclose(self.result.smoothed_marginal_probabilities[:, 1], + self.true["smoothed1"], atol=1e-6) + + def test_predict(self): + # Smoothed + actual = self.model.predict( + self.true["params"], probabilities="smoothed") + assert_allclose(actual, self.true["predict_smoothed"], atol=1e-6) + actual = self.model.predict( + self.true["params"], probabilities=None) + assert_allclose(actual, self.true["predict_smoothed"], atol=1e-6) + + actual = self.result.predict(probabilities="smoothed") + assert_allclose(actual, self.true["predict_smoothed"], atol=1e-6) + actual = self.result.predict(probabilities=None) + assert_allclose(actual, self.true["predict_smoothed"], atol=1e-6) + + def test_bse(self): + # Cannot compare middle element of bse because we estimate sigma^2 + # rather than sigma + bse = self.result.cov_params_approx.diagonal()**0.5 + assert_allclose(bse[:4], self.true["bse_oim"][:4], atol=1e-7) + assert_allclose(bse[6:], self.true["bse_oim"][6:], atol=1e-7) + + +hamilton_ar1_switch_filtered = [ + 0.840288, 0.730337, 0.900234, 0.596492, 0.921618, 0.983828, + 0.959039, 0.898366, 0.477335, 0.251089, 0.049367, 0.386782, + 0.942868, 0.965632, 0.982857, 0.897603, 0.946986, 0.916413, + 0.640912, 0.849296, 0.778371, 0.954420, 0.929906, 0.723930, + 0.891196, 0.061163, 0.004806, 0.977369, 0.997871, 0.977950, + 0.896580, 0.963246, 0.430539, 0.906586, 0.974589, 0.514506, + 0.683457, 0.276571, 0.956475, 0.966993, 0.971618, 0.987019, + 0.916670, 0.921652, 0.930265, 0.655554, 0.965858, 0.964981, + 0.976790, 0.868267, 0.983240, 0.852052, 0.919150, 0.854467, + 0.987868, 0.935840, 0.958138, 0.979535, 0.956541, 0.716322, + 0.919035, 0.866437, 0.899609, 0.914667, 0.976448, 0.867252, + 0.953075, 0.977850, 0.884242, 0.688299, 0.968461, 0.737517, + 0.870674, 0.559413, 0.380339, 0.582813, 0.941311, 0.240020, + 0.999349, 0.619258, 0.828343, 0.729726, 0.991009, 0.966291, + 0.899148, 0.970798, 0.977684, 0.695877, 0.637555, 0.915824, + 0.434600, 0.771277, 0.113756, 0.144002, 0.008466, 0.994860, + 0.993173, 0.961722, 0.978555, 0.789225, 0.836283, 0.940383, + 0.968368, 0.974473, 0.980248, 0.518125, 0.904086, 0.993023, + 0.802936, 0.920906, 0.685445, 0.666524, 0.923285, 0.643861, + 0.938184, 0.008862, 0.945406, 0.990061, 0.991500, 0.486669, + 0.805039, 0.089036, 0.025067, 0.863309, 0.352784, 0.733295, + 0.928710, 0.984257, 0.926597, 0.959887, 0.984051, 0.872682, + 0.824375, 0.780157] + +hamilton_ar1_switch_smoothed = [ + 0.900074, 0.758232, 0.914068, 0.637248, 0.901951, 0.979905, + 0.958935, 0.888641, 0.261602, 0.148761, 0.056919, 0.424396, + 0.932184, 0.954962, 0.983958, 0.895595, 0.949519, 0.923473, + 0.678898, 0.848793, 0.807294, 0.958868, 0.942936, 0.809137, + 0.960892, 0.032947, 0.007127, 0.967967, 0.996551, 0.979278, + 0.896181, 0.987462, 0.498965, 0.908803, 0.986893, 0.488720, + 0.640492, 0.325552, 0.951996, 0.959703, 0.960914, 0.986989, + 0.916779, 0.924570, 0.935348, 0.677118, 0.960749, 0.958966, + 0.976974, 0.838045, 0.986562, 0.847774, 0.908866, 0.821110, + 0.984965, 0.915302, 0.938196, 0.976518, 0.973780, 0.744159, + 0.922006, 0.873292, 0.904035, 0.917547, 0.978559, 0.870915, + 0.948420, 0.979747, 0.884791, 0.711085, 0.973235, 0.726311, + 0.828305, 0.446642, 0.411135, 0.639357, 0.973151, 0.141707, + 0.999805, 0.618207, 0.783239, 0.672193, 0.987618, 0.964655, + 0.877390, 0.962437, 0.989002, 0.692689, 0.699370, 0.937934, + 0.522535, 0.824567, 0.058746, 0.146549, 0.009864, 0.994072, + 0.992084, 0.956945, 0.984297, 0.795926, 0.845698, 0.935364, + 0.963285, 0.972767, 0.992168, 0.528278, 0.826349, 0.996574, + 0.811431, 0.930873, 0.680756, 0.721072, 0.937977, 0.731879, + 0.996745, 0.016121, 0.951187, 0.989820, 0.996968, 0.592477, + 0.889144, 0.036015, 0.040084, 0.858128, 0.418984, 0.746265, + 0.907990, 0.980984, 0.900449, 0.934741, 0.986807, 0.872818, + 0.812080, 0.780157] + + +class TestHamiltonAR1Switch(MarkovAutoregression): + @classmethod + def setup_class(cls): + # Results from E-views: + # Dependent variable followed by a list of switching regressors: + # rgnp c ar(1) + # List of non-switching regressors: + # Do not check "Regime specific error variances" + # Switching type: Markov + # Number of Regimes: 2 + # Probability regressors: + # c + # Method SWITCHREG + # Sample 1951q1 1984q4 + true = { + "params": np.r_[0.85472458, 0.53662099, 1.041419, -0.479157, + np.exp(-0.231404)**2, 0.243128, 0.713029], + "llf": -186.7575, + "llf_fit": -186.7575, + "llf_fit_em": -189.25446 + } + super().setup_class( + true, rgnp, k_regimes=2, order=1) + + def test_filtered_regimes(self): + assert_allclose(self.result.filtered_marginal_probabilities[:, 0], + hamilton_ar1_switch_filtered, atol=1e-5) + + def test_smoothed_regimes(self): + assert_allclose(self.result.smoothed_marginal_probabilities[:, 0], + hamilton_ar1_switch_smoothed, atol=1e-5) + + def test_expected_durations(self): + expected_durations = [6.883477, 1.863513] + assert_allclose(self.result.expected_durations, expected_durations, + atol=1e-5) + + +hamilton_ar1_switch_tvtp_filtered = [ + 0.999996, 0.999211, 0.999849, 0.996007, 0.999825, 0.999991, + 0.999981, 0.999819, 0.041745, 0.001116, 1.74e-05, 0.000155, + 0.999976, 0.999958, 0.999993, 0.999878, 0.999940, 0.999791, + 0.996553, 0.999486, 0.998485, 0.999894, 0.999765, 0.997657, + 0.999619, 0.002853, 1.09e-05, 0.999884, 0.999996, 0.999997, + 0.999919, 0.999987, 0.989762, 0.999807, 0.999978, 0.050734, + 0.010660, 0.000217, 0.006174, 0.999977, 0.999954, 0.999995, + 0.999934, 0.999867, 0.999824, 0.996783, 0.999941, 0.999948, + 0.999981, 0.999658, 0.999994, 0.999753, 0.999859, 0.999330, + 0.999993, 0.999956, 0.999970, 0.999996, 0.999991, 0.998674, + 0.999869, 0.999432, 0.999570, 0.999600, 0.999954, 0.999499, + 0.999906, 0.999978, 0.999712, 0.997441, 0.999948, 0.998379, + 0.999578, 0.994745, 0.045936, 0.006816, 0.027384, 0.000278, + 1.000000, 0.996382, 0.999541, 0.998130, 0.999992, 0.999990, + 0.999860, 0.999986, 0.999997, 0.998520, 0.997777, 0.999821, + 0.033353, 0.011629, 6.95e-05, 4.52e-05, 2.04e-06, 0.999963, + 0.999977, 0.999949, 0.999986, 0.999240, 0.999373, 0.999858, + 0.999946, 0.999972, 0.999991, 0.994039, 0.999817, 0.999999, + 0.999715, 0.999924, 0.997763, 0.997944, 0.999825, 0.996592, + 0.695147, 0.000161, 0.999665, 0.999928, 0.999988, 0.992742, + 0.374214, 0.001569, 2.16e-05, 0.000941, 4.32e-05, 0.000556, + 0.999955, 0.999993, 0.999942, 0.999973, 0.999999, 0.999919, + 0.999438, 0.998738] + +hamilton_ar1_switch_tvtp_smoothed = [ + 0.999997, 0.999246, 0.999918, 0.996118, 0.999740, 0.999990, + 0.999984, 0.999783, 0.035454, 0.000958, 1.53e-05, 0.000139, + 0.999973, 0.999939, 0.999994, 0.999870, 0.999948, 0.999884, + 0.997243, 0.999668, 0.998424, 0.999909, 0.999860, 0.998037, + 0.999559, 0.002533, 1.16e-05, 0.999801, 0.999993, 0.999997, + 0.999891, 0.999994, 0.990096, 0.999753, 0.999974, 0.048495, + 0.009289, 0.000542, 0.005991, 0.999974, 0.999929, 0.999995, + 0.999939, 0.999880, 0.999901, 0.996221, 0.999937, 0.999935, + 0.999985, 0.999450, 0.999995, 0.999768, 0.999897, 0.998930, + 0.999992, 0.999949, 0.999954, 0.999995, 0.999994, 0.998687, + 0.999902, 0.999547, 0.999653, 0.999538, 0.999966, 0.999485, + 0.999883, 0.999982, 0.999831, 0.996940, 0.999968, 0.998678, + 0.999780, 0.993895, 0.055372, 0.020421, 0.022913, 0.000127, + 1.000000, 0.997072, 0.999715, 0.996893, 0.999990, 0.999991, + 0.999811, 0.999978, 0.999998, 0.999100, 0.997866, 0.999787, + 0.034912, 0.009932, 5.91e-05, 3.99e-05, 1.77e-06, 0.999954, + 0.999976, 0.999932, 0.999991, 0.999429, 0.999393, 0.999845, + 0.999936, 0.999961, 0.999995, 0.994246, 0.999570, 1.000000, + 0.999702, 0.999955, 0.998611, 0.998019, 0.999902, 0.998486, + 0.673991, 0.000205, 0.999627, 0.999902, 0.999994, 0.993707, + 0.338707, 0.001359, 2.36e-05, 0.000792, 4.47e-05, 0.000565, + 0.999932, 0.999993, 0.999931, 0.999950, 0.999999, 0.999940, + 0.999626, 0.998738] + +expected_durations = [ + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [1.223309, 1864.084], + [1.223309, 1864.084], [1.223309, 1864.084], [1.223309, 1864.084], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [1.223309, 1864.084], [1.223309, 1864.084], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [1.223309, 1864.084], + [1.223309, 1864.084], [1.223309, 1864.084], [1.223309, 1864.084], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [1.223309, 1864.084], + [1.223309, 1864.084], [1.223309, 1864.084], [1.223309, 1864.084], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [1.223309, 1864.084], [1.223309, 1864.084], [1.223309, 1864.084], + [1.223309, 1864.084], [1.223309, 1864.084], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [1.223309, 1864.084], [1.223309, 1864.084], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [1.223309, 1864.084], [1.223309, 1864.084], [1.223309, 1864.084], + [1.223309, 1864.084], [1.223309, 1864.084], [1.223309, 1864.084], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391], [710.7573, 1.000391], + [710.7573, 1.000391], [710.7573, 1.000391]] + + +class TestHamiltonAR1SwitchTVTP(MarkovAutoregression): + @classmethod + def setup_class(cls): + # Results from E-views: + # Dependent variable followed by a list of switching regressors: + # rgnp c ar(1) + # List of non-switching regressors: + # Do not check "Regime specific error variances" + # Switching type: Markov + # Number of Regimes: 2 + # Probability regressors: + # c recession + # Method SWITCHREG + # Sample 1951q1 1984q4 + true = { + "params": np.r_[6.564923, 7.846371, -8.064123, -15.37636, + 1.027190, -0.719760, + np.exp(-0.217003)**2, 0.161489, 0.022536], + "llf": -163.914049, + "llf_fit": -161.786477, + "llf_fit_em": -163.914049 + } + exog_tvtp = np.c_[np.ones(len(rgnp)), rec] + super().setup_class( + true, rgnp, k_regimes=2, order=1, exog_tvtp=exog_tvtp) + + @pytest.mark.skip # TODO(ChadFulton): give reason for skip + def test_fit_em(self): + pass + + def test_filtered_regimes(self): + assert_allclose(self.result.filtered_marginal_probabilities[:, 0], + hamilton_ar1_switch_tvtp_filtered, atol=1e-5) + + def test_smoothed_regimes(self): + assert_allclose(self.result.smoothed_marginal_probabilities[:, 0], + hamilton_ar1_switch_tvtp_smoothed, atol=1e-5) + + def test_expected_durations(self): + assert_allclose(self.result.expected_durations, expected_durations, + rtol=1e-5, atol=1e-7) + + +class TestFilardo(MarkovAutoregression): + @classmethod + def setup_class(cls): + path = Path(current_path).joinpath("results", "mar_filardo.csv") + cls.mar_filardo = pd.read_csv(path) + true = { + "params": np.r_[4.35941747, -1.6493936, 1.7702123, 0.9945672, + 0.517298, -0.865888, + np.exp(-0.362469)**2, + 0.189474, 0.079344, 0.110944, 0.122251], + "llf": -586.5718, + "llf_fit": -586.5718, + "llf_fit_em": -586.5718 + } + endog = cls.mar_filardo["dlip"].iloc[1:].values + exog_tvtp = add_constant( + cls.mar_filardo["dmdlleading"].iloc[:-1].values) + super().setup_class( + true, endog, k_regimes=2, order=4, switching_ar=False, + exog_tvtp=exog_tvtp) + + @pytest.mark.skip # TODO(ChadFulton): give reason for skip + def test_fit(self, **kwargs): + pass + + @pytest.mark.skip # TODO(ChadFulton): give reason for skip + def test_fit_em(self): + pass + + def test_filtered_regimes(self): + assert_allclose(self.result.filtered_marginal_probabilities[:, 0], + self.mar_filardo["filtered_0"].iloc[5:], atol=1e-5) + + def test_smoothed_regimes(self): + assert_allclose(self.result.smoothed_marginal_probabilities[:, 0], + self.mar_filardo["smoothed_0"].iloc[5:], atol=1e-5) + + def test_expected_durations(self): + assert_allclose(self.result.expected_durations, + self.mar_filardo[["duration0", "duration1"]].iloc[5:], + rtol=1e-5, atol=1e-7) + + +class TestFilardoPandas(MarkovAutoregression): + @classmethod + def setup_class(cls): + path = Path(current_path).joinpath("results", "mar_filardo.csv") + cls.mar_filardo = pd.read_csv(path) + cls.mar_filardo.index = pd.date_range("1948-02-01", "1991-04-01", + freq="MS") + true = { + "params": np.r_[4.35941747, -1.6493936, 1.7702123, 0.9945672, + 0.517298, -0.865888, + np.exp(-0.362469)**2, + 0.189474, 0.079344, 0.110944, 0.122251], + "llf": -586.5718, + "llf_fit": -586.5718, + "llf_fit_em": -586.5718 + } + endog = cls.mar_filardo["dlip"].iloc[1:] + exog_tvtp = add_constant( + cls.mar_filardo["dmdlleading"].iloc[:-1]) + super().setup_class( + true, endog, k_regimes=2, order=4, switching_ar=False, + exog_tvtp=exog_tvtp) + + @pytest.mark.skip # TODO(ChadFulton): give reason for skip + def test_fit(self, **kwargs): + pass + + @pytest.mark.skip # TODO(ChadFulton): give reason for skip + def test_fit_em(self): + pass + + def test_filtered_regimes(self): + assert_allclose(self.result.filtered_marginal_probabilities[0], + self.mar_filardo["filtered_0"].iloc[5:], atol=1e-5) + + def test_smoothed_regimes(self): + assert_allclose(self.result.smoothed_marginal_probabilities[0], + self.mar_filardo["smoothed_0"].iloc[5:], atol=1e-5) + + def test_expected_durations(self): + assert_allclose(self.result.expected_durations, + self.mar_filardo[["duration0", "duration1"]].iloc[5:], + rtol=1e-5, atol=1e-7) diff --git a/shared/package-files/38/3861979f86de5488e3201e5a911da47b263b81015a300c4cfc0a1934dfc8dc19/test_warp_ops.py b/shared/package-files/38/3861979f86de5488e3201e5a911da47b263b81015a300c4cfc0a1934dfc8dc19/test_warp_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc157d07a3e07f3b5831a9031adf5a31315337e --- /dev/null +++ b/shared/package-files/38/3861979f86de5488e3201e5a911da47b263b81015a300c4cfc0a1934dfc8dc19/test_warp_ops.py @@ -0,0 +1,276 @@ +import numpy as np +from numba import cuda, int32, int64, float32, float64 +from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim +from numba.core import config + + +def useful_syncwarp(ary): + i = cuda.grid(1) + if i == 0: + ary[0] = 42 + cuda.syncwarp(0xffffffff) + ary[i] = ary[0] + + +def use_shfl_sync_idx(ary, idx): + i = cuda.grid(1) + val = cuda.shfl_sync(0xffffffff, i, idx) + ary[i] = val + + +def use_shfl_sync_up(ary, delta): + i = cuda.grid(1) + val = cuda.shfl_up_sync(0xffffffff, i, delta) + ary[i] = val + + +def use_shfl_sync_down(ary, delta): + i = cuda.grid(1) + val = cuda.shfl_down_sync(0xffffffff, i, delta) + ary[i] = val + + +def use_shfl_sync_xor(ary, xor): + i = cuda.grid(1) + val = cuda.shfl_xor_sync(0xffffffff, i, xor) + ary[i] = val + + +def use_shfl_sync_with_val(ary, into): + i = cuda.grid(1) + val = cuda.shfl_sync(0xffffffff, into, 0) + ary[i] = val + + +def use_vote_sync_all(ary_in, ary_out): + i = cuda.grid(1) + pred = cuda.all_sync(0xffffffff, ary_in[i]) + ary_out[i] = pred + + +def use_vote_sync_any(ary_in, ary_out): + i = cuda.grid(1) + pred = cuda.any_sync(0xffffffff, ary_in[i]) + ary_out[i] = pred + + +def use_vote_sync_eq(ary_in, ary_out): + i = cuda.grid(1) + pred = cuda.eq_sync(0xffffffff, ary_in[i]) + ary_out[i] = pred + + +def use_vote_sync_ballot(ary): + i = cuda.threadIdx.x + ballot = cuda.ballot_sync(0xffffffff, True) + ary[i] = ballot + + +def use_match_any_sync(ary_in, ary_out): + i = cuda.grid(1) + ballot = cuda.match_any_sync(0xffffffff, ary_in[i]) + ary_out[i] = ballot + + +def use_match_all_sync(ary_in, ary_out): + i = cuda.grid(1) + ballot, pred = cuda.match_all_sync(0xffffffff, ary_in[i]) + ary_out[i] = ballot if pred else 0 + + +def use_independent_scheduling(arr): + i = cuda.threadIdx.x + if i % 4 == 0: + ballot = cuda.ballot_sync(0x11111111, True) + elif i % 4 == 1: + ballot = cuda.ballot_sync(0x22222222, True) + elif i % 4 == 2: + ballot = cuda.ballot_sync(0x44444444, True) + elif i % 4 == 3: + ballot = cuda.ballot_sync(0x88888888, True) + arr[i] = ballot + + +def _safe_cc_check(cc): + if config.ENABLE_CUDASIM: + return True + else: + return cuda.get_current_device().compute_capability >= cc + + +@skip_on_cudasim("Warp Operations are not yet implemented on cudasim") +class TestCudaWarpOperations(CUDATestCase): + def test_useful_syncwarp(self): + compiled = cuda.jit("void(int32[:])")(useful_syncwarp) + nelem = 32 + ary = np.empty(nelem, dtype=np.int32) + compiled[1, nelem](ary) + self.assertTrue(np.all(ary == 42)) + + def test_shfl_sync_idx(self): + compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_idx) + nelem = 32 + idx = 4 + ary = np.empty(nelem, dtype=np.int32) + compiled[1, nelem](ary, idx) + self.assertTrue(np.all(ary == idx)) + + def test_shfl_sync_up(self): + compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_up) + nelem = 32 + delta = 4 + ary = np.empty(nelem, dtype=np.int32) + exp = np.arange(nelem, dtype=np.int32) + exp[delta:] -= delta + compiled[1, nelem](ary, delta) + self.assertTrue(np.all(ary == exp)) + + def test_shfl_sync_down(self): + compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_down) + nelem = 32 + delta = 4 + ary = np.empty(nelem, dtype=np.int32) + exp = np.arange(nelem, dtype=np.int32) + exp[:-delta] += delta + compiled[1, nelem](ary, delta) + self.assertTrue(np.all(ary == exp)) + + def test_shfl_sync_xor(self): + compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_xor) + nelem = 32 + xor = 16 + ary = np.empty(nelem, dtype=np.int32) + exp = np.arange(nelem, dtype=np.int32) ^ xor + compiled[1, nelem](ary, xor) + self.assertTrue(np.all(ary == exp)) + + def test_shfl_sync_types(self): + types = int32, int64, float32, float64 + values = (np.int32(-1), np.int64(1 << 42), + np.float32(np.pi), np.float64(np.pi)) + for typ, val in zip(types, values): + compiled = cuda.jit((typ[:], typ))(use_shfl_sync_with_val) + nelem = 32 + ary = np.empty(nelem, dtype=val.dtype) + compiled[1, nelem](ary, val) + self.assertTrue(np.all(ary == val)) + + def test_vote_sync_all(self): + compiled = cuda.jit("void(int32[:], int32[:])")(use_vote_sync_all) + nelem = 32 + ary_in = np.ones(nelem, dtype=np.int32) + ary_out = np.empty(nelem, dtype=np.int32) + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 1)) + ary_in[-1] = 0 + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 0)) + + def test_vote_sync_any(self): + compiled = cuda.jit("void(int32[:], int32[:])")(use_vote_sync_any) + nelem = 32 + ary_in = np.zeros(nelem, dtype=np.int32) + ary_out = np.empty(nelem, dtype=np.int32) + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 0)) + ary_in[2] = 1 + ary_in[5] = 1 + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 1)) + + def test_vote_sync_eq(self): + compiled = cuda.jit("void(int32[:], int32[:])")(use_vote_sync_eq) + nelem = 32 + ary_in = np.zeros(nelem, dtype=np.int32) + ary_out = np.empty(nelem, dtype=np.int32) + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 1)) + ary_in[1] = 1 + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 0)) + ary_in[:] = 1 + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 1)) + + def test_vote_sync_ballot(self): + compiled = cuda.jit("void(uint32[:])")(use_vote_sync_ballot) + nelem = 32 + ary = np.empty(nelem, dtype=np.uint32) + compiled[1, nelem](ary) + self.assertTrue(np.all(ary == np.uint32(0xffffffff))) + + @unittest.skipUnless(_safe_cc_check((7, 0)), + "Matching requires at least Volta Architecture") + def test_match_any_sync(self): + compiled = cuda.jit("void(int32[:], int32[:])")(use_match_any_sync) + nelem = 10 + ary_in = np.arange(nelem, dtype=np.int32) % 2 + ary_out = np.empty(nelem, dtype=np.int32) + exp = np.tile((0b0101010101, 0b1010101010), 5) + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == exp)) + + @unittest.skipUnless(_safe_cc_check((7, 0)), + "Matching requires at least Volta Architecture") + def test_match_all_sync(self): + compiled = cuda.jit("void(int32[:], int32[:])")(use_match_all_sync) + nelem = 10 + ary_in = np.zeros(nelem, dtype=np.int32) + ary_out = np.empty(nelem, dtype=np.int32) + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 0b1111111111)) + ary_in[1] = 4 + compiled[1, nelem](ary_in, ary_out) + self.assertTrue(np.all(ary_out == 0)) + + @unittest.skipUnless(_safe_cc_check((7, 0)), + "Independent scheduling requires at least Volta " + "Architecture") + def test_independent_scheduling(self): + compiled = cuda.jit("void(uint32[:])")(use_independent_scheduling) + arr = np.empty(32, dtype=np.uint32) + exp = np.tile((0x11111111, 0x22222222, 0x44444444, 0x88888888), 8) + compiled[1, 32](arr) + self.assertTrue(np.all(arr == exp)) + + def test_activemask(self): + @cuda.jit + def use_activemask(x): + i = cuda.grid(1) + if (i % 2) == 0: + # Even numbered threads fill in even numbered array entries + # with binary "...01010101" + x[i] = cuda.activemask() + else: + # Odd numbered threads fill in odd numbered array entries + # with binary "...10101010" + x[i] = cuda.activemask() + + out = np.zeros(32, dtype=np.uint32) + use_activemask[1, 32](out) + + # 0x5 = 0101: The pattern from even-numbered threads + # 0xA = 1010: The pattern from odd-numbered threads + expected = np.tile((0x55555555, 0xAAAAAAAA), 16) + np.testing.assert_equal(expected, out) + + def test_lanemask_lt(self): + @cuda.jit + def use_lanemask_lt(x): + i = cuda.grid(1) + x[i] = cuda.lanemask_lt() + + out = np.zeros(32, dtype=np.uint32) + use_lanemask_lt[1, 32](out) + + # A string of 1s that grows from the LSB for each entry: + # 0, 1, 3, 7, F, 1F, 3F, 7F, FF, 1FF, etc. + # or in binary: + # ...0001, ....0011, ...0111, etc. + expected = np.asarray([(2 ** i) - 1 for i in range(32)], + dtype=np.uint32) + np.testing.assert_equal(expected, out) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/38/38682587a9d8536ed841cb6eb8456748342cc623661d9b271d043928163b405b/elu_meta.h b/shared/package-files/38/38682587a9d8536ed841cb6eb8456748342cc623661d9b271d043928163b405b/elu_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..5fc1d7845bd88ce0a4fdf78d27bc3f8f6eb8dfcc --- /dev/null +++ b/shared/package-files/38/38682587a9d8536ed841cb6eb8456748342cc623661d9b271d043928163b405b/elu_meta.h @@ -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_elu : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/38/386af345695f9181e96950dfcafa24b54f1442ae90c95ef11ad0944ff9b83f71/_foreach_erfc_cuda_dispatch.h b/shared/package-files/38/386af345695f9181e96950dfcafa24b54f1442ae90c95ef11ad0944ff9b83f71/_foreach_erfc_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e88579040af34e53524b8c83a5f698841f8e4054 --- /dev/null +++ b/shared/package-files/38/386af345695f9181e96950dfcafa24b54f1442ae90c95ef11ad0944ff9b83f71/_foreach_erfc_cuda_dispatch.h @@ -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_erfc(at::TensorList self); +TORCH_API void _foreach_erfc_(at::TensorList self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/38/386c690eaa918ccaaaad2769b8264e10bf659166017cc06a09c4a8f0df756ca4/test_rls.do b/shared/package-files/38/386c690eaa918ccaaaad2769b8264e10bf659166017cc06a09c4a8f0df756ca4/test_rls.do new file mode 100644 index 0000000000000000000000000000000000000000..4c76ffcf1f597a4e67de03882b07918055401f02 --- /dev/null +++ b/shared/package-files/38/386c690eaa918ccaaaad2769b8264e10bf659166017cc06a09c4a8f0df756ca4/test_rls.do @@ -0,0 +1,20 @@ +insheet using /Users/fulton/projects/statsmodels/statsmodels/datasets/macrodata/macrodata.csv, clear + +gen tq = yq(year, quarter) +format tq %tq +tsset tq + +cusum6 cpi m1, rr(rr) cs(cusum) lw(lw) uw(uw) cs2(cusum2) lww(lww) uww(uww) noplot + +outsheet rr-lww using results_rls_stata.csv, comma replace + +// Section for restricted least squares + +constraint 1 m1 + unemp = 1 +cnsreg infl m1 unemp, c(1) + +disp %18.13f e(ll) // -534.4292052931121 +matrix list e(b), format(%15.13f) // -0.0018477514060 1.0018477514060 -0.7001083844336 + +mata: se=sqrt(diagonal(st_matrix("e(V)"))) +mata: se // .0005369357, .0005369357, .4699552366 diff --git a/shared/package-files/38/386d6772a104c4283211858b66845e7186a6cb068bbc2e883f32a828e40479dc/_colors.py b/shared/package-files/38/386d6772a104c4283211858b66845e7186a6cb068bbc2e883f32a828e40479dc/_colors.py new file mode 100644 index 0000000000000000000000000000000000000000..481ff6ae859ee74cc0c6532a74eb1cafeb5f05d6 --- /dev/null +++ b/shared/package-files/38/386d6772a104c4283211858b66845e7186a6cb068bbc2e883f32a828e40479dc/_colors.py @@ -0,0 +1,130 @@ +"""This defines some common colors.""" + +import numpy as np +from matplotlib.colors import LinearSegmentedColormap + +from ._colorconv import lab2rgb, lch2lab + + +def lch2rgb(x: list[float]) -> np.ndarray: + return lab2rgb(lch2lab([[x]]))[0][0] + + +# define our colors using Lch +# note that we intentionally vary the lightness during interpolation so as to better +# enable the eye to see patterns (since patterns are most easily recognized through +# lightness variability) +blue_lch = [54.0, 70.0, 4.6588] +l_mid = 40.0 +red_lch = [54.0, 90.0, 0.35470565 + 2 * np.pi] +gray_lch = [55.0, 0.0, 0.0] +blue_rgb = lch2rgb(blue_lch) +red_rgb = lch2rgb(red_lch) +gray_rgb = lch2rgb(gray_lch) +white_rgb = np.array([1.0, 1.0, 1.0]) + +light_blue_rgb = np.array([127.0, 196, 252]) / 255 +light_red_rgb = np.array([255.0, 127, 167]) / 255 + +# define a perceptually uniform color scale using the Lch color space +reds = [] +greens = [] +blues = [] +alphas = [] +nsteps = 100 +l_vals = list(np.linspace(blue_lch[0], l_mid, nsteps // 2)) + list(np.linspace(l_mid, red_lch[0], nsteps // 2)) +c_vals = np.linspace(blue_lch[1], red_lch[1], nsteps) +h_vals = np.linspace(blue_lch[2], red_lch[2], nsteps) +for pos, l, c, h in zip(np.linspace(0, 1, nsteps), l_vals, c_vals, h_vals): # noqa: E741 + lch = [l, c, h] + rgb = lch2rgb(lch) + reds.append((pos, rgb[0], rgb[0])) + greens.append((pos, rgb[1], rgb[1])) + blues.append((pos, rgb[2], rgb[2])) + alphas.append((pos, 1.0, 1.0)) + +red_blue = LinearSegmentedColormap("red_blue", {"red": reds, "green": greens, "blue": blues, "alpha": alphas}) +red_blue.set_bad(gray_rgb.tolist(), 1.0) +red_blue.set_over(gray_rgb.tolist(), 1.0) +red_blue.set_under(gray_rgb.tolist(), 1.0) # "under" is incorrectly used instead of "bad" in the scatter plot + +red_blue_no_bounds = LinearSegmentedColormap( + "red_blue_no_bounds", {"red": reds, "green": greens, "blue": blues, "alpha": alphas} +) + +red_blue_transparent = LinearSegmentedColormap( + "red_blue_transparent", {"red": reds, "green": greens, "blue": blues, "alpha": [(a[0], 0.5, 0.5) for a in alphas]} +) + +# define a circular version of the color scale for categorical coloring +reds = [] +greens = [] +blues = [] +alphas = [] +nsteps = 100 +c_vals = np.linspace(blue_lch[1], red_lch[1], nsteps) +h_vals = np.linspace(blue_lch[2], red_lch[2], nsteps) +for pos, c, h in zip(np.linspace(0, 0.5, nsteps), c_vals, h_vals): + lch = [blue_lch[0], c, h] + rgb = lch2rgb(lch) + reds.append((pos, rgb[0], rgb[0])) + greens.append((pos, rgb[1], rgb[1])) + blues.append((pos, rgb[2], rgb[2])) + alphas.append((pos, 1.0, 1.0)) +c_vals = np.linspace(red_lch[1], blue_lch[1], nsteps) +h_vals = np.linspace(red_lch[2] - 2 * np.pi, blue_lch[2], nsteps) +for pos, c, h in zip(np.linspace(0.5, 1, nsteps), c_vals, h_vals): + lch = [blue_lch[0], c, h] + rgb = lch2rgb(lch) + reds.append((pos, rgb[0], rgb[0])) + greens.append((pos, rgb[1], rgb[1])) + blues.append((pos, rgb[2], rgb[2])) + alphas.append((pos, 1.0, 1.0)) + +red_blue_circle = LinearSegmentedColormap( + "red_blue_circle", {"red": reds, "green": greens, "blue": blues, "alpha": alphas} +) + +colors = [] +for j in np.linspace(1, 0, 100): + colors.append((30.0 / 255, 136.0 / 255, 229.0 / 255, j)) +for j in np.linspace(0, 1, 100): + colors.append((255.0 / 255, 13.0 / 255, 87.0 / 255, j)) +red_transparent_blue = LinearSegmentedColormap.from_list("red_transparent_blue", colors) + +colors = [] +for j in np.linspace(0, 1, 100): + colors.append((30.0 / 255, 136.0 / 255, 229.0 / 255, j)) +transparent_blue = LinearSegmentedColormap.from_list("transparent_blue", colors) + +colors = [] +for j in np.linspace(0, 1, 100): + colors.append((255.0 / 255, 13.0 / 255, 87.0 / 255, j)) +transparent_red = LinearSegmentedColormap.from_list("transparent_red", colors) + +old_blue_rgb = np.array([30, 136, 229]) / 255 +old_red_rgb = np.array([255, 13, 87]) / 255 + +colors = [] +for alpha in np.linspace(1, 0, 100): + c = blue_rgb * alpha + (1 - alpha) * white_rgb + colors.append(c) +for alpha in np.linspace(0, 1, 100): + c = red_rgb * alpha + (1 - alpha) * white_rgb + colors.append(c) +red_white_blue = LinearSegmentedColormap.from_list("red_white_blue", colors) + + +# default_colors = ["#1E88E5", "#ff0d57", "#13B755", "#7C52FF", "#FFC000", "#00AEEF"] + +# blue_rgba = np.array([0.11764705882352941, 0.5333333333333333, 0.8980392156862745, 1.0]) +# blue_rgba = np.array([30, 136, 229, 255]) / 255 +# blue_rgb = np.array([30, 136, 229]) / 255 +# red_rgb = np.array([255, 13, 87]) / 255 + +# default_blue_colors = [] +# tmp = blue_rgba.copy() +# for i in range(10): +# default_blue_colors.append(tmp.copy()) +# if tmp[-1] > 0.1: +# tmp[-1] *= 0.7 diff --git a/shared/package-files/38/3870bd60428b1bceeb65bcf558fd7ee0575be3720d740e887b7bd6662bd75cc6/vendor.txt b/shared/package-files/38/3870bd60428b1bceeb65bcf558fd7ee0575be3720d740e887b7bd6662bd75cc6/vendor.txt new file mode 100644 index 0000000000000000000000000000000000000000..798ed63adce72d4053fb50d240fd72af4cfddf52 --- /dev/null +++ b/shared/package-files/38/3870bd60428b1bceeb65bcf558fd7ee0575be3720d740e887b7bd6662bd75cc6/vendor.txt @@ -0,0 +1,7 @@ +boltons==21.0.0 +toolz==0.9.0 +tqdm==4.61.1 +appdirs==1.2.0 +py-cpuinfo==9.0.0 +distro==1.0.4 +frozendict==1.2 diff --git a/shared/package-files/38/3877f5009fbbfce74dc7cc607622c878cc9710ce19b9c290c63336202ca002a7/dt-100 b/shared/package-files/38/3877f5009fbbfce74dc7cc607622c878cc9710ce19b9c290c63336202ca002a7/dt-100 new file mode 100644 index 0000000000000000000000000000000000000000..5792c0af0f12e0f6df07cf9176987e99b44eb5f9 Binary files /dev/null and b/shared/package-files/38/3877f5009fbbfce74dc7cc607622c878cc9710ce19b9c290c63336202ca002a7/dt-100 differ diff --git a/shared/package-files/38/3877f5009fbbfce74dc7cc607622c878cc9710ce19b9c290c63336202ca002a7/dt100 b/shared/package-files/38/3877f5009fbbfce74dc7cc607622c878cc9710ce19b9c290c63336202ca002a7/dt100 new file mode 100644 index 0000000000000000000000000000000000000000..5792c0af0f12e0f6df07cf9176987e99b44eb5f9 Binary files /dev/null and b/shared/package-files/38/3877f5009fbbfce74dc7cc607622c878cc9710ce19b9c290c63336202ca002a7/dt100 differ diff --git a/shared/package-files/38/387869dbb0bf862b143bfc4ceea0a600ff8e5bdfce1561eb64967ec1598a2240/bitwise_or_native.h b/shared/package-files/38/387869dbb0bf862b143bfc4ceea0a600ff8e5bdfce1561eb64967ec1598a2240/bitwise_or_native.h new file mode 100644 index 0000000000000000000000000000000000000000..268e2b6462bb99e73fbdc8bf07e4c6a2eca32c00 --- /dev/null +++ b/shared/package-files/38/387869dbb0bf862b143bfc4ceea0a600ff8e5bdfce1561eb64967ec1598a2240/bitwise_or_native.h @@ -0,0 +1,28 @@ +#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_bitwise_or_out : public at::meta::structured_bitwise_or_Tensor { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out); +}; +TORCH_API at::Tensor bitwise_or(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & bitwise_or_out(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & bitwise_or_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor bitwise_or(const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_or_Scalar_Tensor_out(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/38/3878ab176d292dea9a0e985932f610983550da661463a8e45ca2da8381bcf5dd/gt_native.h b/shared/package-files/38/3878ab176d292dea9a0e985932f610983550da661463a8e45ca2da8381bcf5dd/gt_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b61d0dabb303f36984bf3d908be456045bbc58e8 --- /dev/null +++ b/shared/package-files/38/3878ab176d292dea9a0e985932f610983550da661463a8e45ca2da8381bcf5dd/gt_native.h @@ -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_gt_Scalar_out : public at::meta::structured_gt_Scalar { +void impl(const at::Tensor & self, const at::Scalar & other, const at::Tensor & out); +}; +TORCH_API at::Tensor gt_scalar_nested(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor gt_quantized_cpu(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & gt_out_quantized_cpu(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +struct TORCH_API structured_gt_Tensor_out : public at::meta::structured_gt_Tensor { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out); +}; +TORCH_API at::Tensor gt_quantized_cpu(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & gt_out_quantized_cpu(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/38/38790c33fc8e2cfe82d5a008641fa53dbcf80184bd8b6b218455c61418bdfcb7/from_array_to_matrix.py b/shared/package-files/38/38790c33fc8e2cfe82d5a008641fa53dbcf80184bd8b6b218455c61418bdfcb7/from_array_to_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..69acd9cac52d8c8817409278f82cf41a098aaf6e --- /dev/null +++ b/shared/package-files/38/38790c33fc8e2cfe82d5a008641fa53dbcf80184bd8b6b218455c61418bdfcb7/from_array_to_matrix.py @@ -0,0 +1,1003 @@ +import itertools +from collections import defaultdict +from typing import Tuple as tTuple, Union as tUnion, FrozenSet, Dict as tDict, List, Optional +from functools import singledispatch +from itertools import accumulate + +from sympy import MatMul, Basic, Wild, KroneckerProduct +from sympy.assumptions.ask import (Q, ask) +from sympy.core.mul import Mul +from sympy.core.singleton import S +from sympy.matrices.expressions.diagonal import DiagMatrix +from sympy.matrices.expressions.hadamard import hadamard_product, HadamardPower +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.special import (Identity, ZeroMatrix, OneMatrix) +from sympy.matrices.expressions.trace import Trace +from sympy.matrices.expressions.transpose import Transpose +from sympy.combinatorics.permutations import _af_invert, Permutation +from sympy.matrices.common import MatrixCommon +from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction +from sympy.matrices.expressions.matexpr import MatrixElement +from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \ + ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \ + ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE, \ + ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims +from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks + + +def _get_candidate_for_matmul_from_contraction(scan_indices: List[Optional[int]], remaining_args: List[_ArgE]) -> tTuple[Optional[_ArgE], bool, int]: + + scan_indices_int: List[int] = [i for i in scan_indices if i is not None] + if len(scan_indices_int) == 0: + return None, False, -1 + + transpose: bool = False + candidate: Optional[_ArgE] = None + candidate_index: int = -1 + for arg_with_ind2 in remaining_args: + if not isinstance(arg_with_ind2.element, MatrixExpr): + continue + for index in scan_indices_int: + if candidate_index != -1 and candidate_index != index: + # A candidate index has already been selected, check + # repetitions only for that index: + continue + if index in arg_with_ind2.indices: + if set(arg_with_ind2.indices) == {index}: + # Index repeated twice in arg_with_ind2 + candidate = None + break + if candidate is None: + candidate = arg_with_ind2 + candidate_index = index + transpose = (index == arg_with_ind2.indices[1]) + else: + # Index repeated more than twice, break + candidate = None + break + return candidate, transpose, candidate_index + + +def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool): + other = candidate.element + other_index: Optional[int] + if transpose2: + other = Transpose(other) + other_index = candidate.indices[0] + else: + other_index = candidate.indices[1] + new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other + editor.args_with_ind.remove(candidate) + new_arge = _ArgE(new_element) + return new_arge, other_index + + +def _support_function_tp1_recognize(contraction_indices, args): + if len(contraction_indices) == 0: + return _a2m_tensor_product(*args) + + ac = _array_contraction(_array_tensor_product(*args), *contraction_indices) + editor = _EditArrayContraction(ac) + editor.track_permutation_start() + + while True: + flag_stop = True + for i, arg_with_ind in enumerate(editor.args_with_ind): + if not isinstance(arg_with_ind.element, MatrixExpr): + continue + + first_index = arg_with_ind.indices[0] + second_index = arg_with_ind.indices[1] + + first_frequency = editor.count_args_with_index(first_index) + second_frequency = editor.count_args_with_index(second_index) + + if first_index is not None and first_frequency == 1 and first_index == second_index: + flag_stop = False + arg_with_ind.element = Trace(arg_with_ind.element)._normalize() + arg_with_ind.indices = [] + break + + scan_indices = [] + if first_frequency == 2: + scan_indices.append(first_index) + if second_frequency == 2: + scan_indices.append(second_index) + + candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:]) + if candidate is not None: + flag_stop = False + editor.track_permutation_merge(arg_with_ind, candidate) + transpose1 = found_index == first_index + new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose) + if found_index == first_index: + new_arge.indices = [second_index, other_index] + else: + new_arge.indices = [first_index, other_index] + set_indices = set(new_arge.indices) + if len(set_indices) == 1 and set_indices != {None}: + # This is a trace: + new_arge.element = Trace(new_arge.element)._normalize() + new_arge.indices = [] + editor.args_with_ind[i] = new_arge + # TODO: is this break necessary? + break + + if flag_stop: + break + + editor.refresh_indices() + return editor.to_array_contraction() + + +def _find_trivial_matrices_rewrite(expr: ArrayTensorProduct): + # If there are matrices of trivial shape in the tensor product (i.e. shape + # (1, 1)), try to check if there is a suitable non-trivial MatMul where the + # expression can be inserted. + + # For example, if "a" has shape (1, 1) and "b" has shape (k, 1), the + # expressions "_array_tensor_product(a, b*b.T)" can be rewritten as + # "b*a*b.T" + + trivial_matrices = [] + pos: Optional[int] = None + first: Optional[MatrixExpr] = None + second: Optional[MatrixExpr] = None + removed: List[int] = [] + counter: int = 0 + args: List[Optional[Basic]] = list(expr.args) + for i, arg in enumerate(expr.args): + if isinstance(arg, MatrixExpr): + if arg.shape == (1, 1): + trivial_matrices.append(arg) + args[i] = None + removed.extend([counter, counter+1]) + elif pos is None and isinstance(arg, MatMul): + margs = arg.args + for j, e in enumerate(margs): + if isinstance(e, MatrixExpr) and e.shape[1] == 1: + pos = i + first = MatMul.fromiter(margs[:j+1]) + second = MatMul.fromiter(margs[j+1:]) + break + counter += get_rank(arg) + if pos is None: + return expr, [] + args[pos] = (first*MatMul.fromiter(i for i in trivial_matrices)*second).doit() + return _array_tensor_product(*[i for i in args if i is not None]), removed + + +def _find_trivial_kronecker_products_broadcast(expr: ArrayTensorProduct): + newargs: List[Basic] = [] + removed = [] + count_dims = 0 + for i, arg in enumerate(expr.args): + count_dims += get_rank(arg) + shape = get_shape(arg) + current_range = [count_dims-i for i in range(len(shape), 0, -1)] + if (shape == (1, 1) and len(newargs) > 0 and 1 not in get_shape(newargs[-1]) and + isinstance(newargs[-1], MatrixExpr) and isinstance(arg, MatrixExpr)): + # KroneckerProduct object allows the trick of broadcasting: + newargs[-1] = KroneckerProduct(newargs[-1], arg) + removed.extend(current_range) + elif 1 not in shape and len(newargs) > 0 and get_shape(newargs[-1]) == (1, 1): + # Broadcast: + newargs[-1] = KroneckerProduct(newargs[-1], arg) + prev_range = [i for i in range(min(current_range)) if i not in removed] + removed.extend(prev_range[-2:]) + else: + newargs.append(arg) + return _array_tensor_product(*newargs), removed + + +@singledispatch +def _array2matrix(expr): + return expr + + +@_array2matrix.register(ZeroArray) +def _(expr: ZeroArray): + if get_rank(expr) == 2: + return ZeroMatrix(*expr.shape) + else: + return expr + + +@_array2matrix.register(ArrayTensorProduct) +def _(expr: ArrayTensorProduct): + return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args]) + + +@_array2matrix.register(ArrayContraction) +def _(expr: ArrayContraction): + expr = expr.flatten_contraction_of_diagonal() + expr = identify_removable_identity_matrices(expr) + expr = expr.split_multiple_contractions() + expr = identify_hadamard_products(expr) + if not isinstance(expr, ArrayContraction): + return _array2matrix(expr) + subexpr = expr.expr + contraction_indices: tTuple[tTuple[int]] = expr.contraction_indices + if contraction_indices == ((0,), (1,)) or ( + contraction_indices == ((0,),) and subexpr.shape[1] == 1 + ) or ( + contraction_indices == ((1,),) and subexpr.shape[0] == 1 + ): + shape = subexpr.shape + subexpr = _array2matrix(subexpr) + if isinstance(subexpr, MatrixExpr): + return OneMatrix(1, shape[0])*subexpr*OneMatrix(shape[1], 1) + if isinstance(subexpr, ArrayTensorProduct): + newexpr = _array_contraction(_array2matrix(subexpr), *contraction_indices) + contraction_indices = newexpr.contraction_indices + if any(i > 2 for i in newexpr.subranks): + addends = _array_add(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i, + ArrayAdd) else [i] for i in expr.expr.args])]) + newexpr = _array_contraction(addends, *contraction_indices) + if isinstance(newexpr, ArrayAdd): + ret = _array2matrix(newexpr) + return ret + assert isinstance(newexpr, ArrayContraction) + ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args)) + return ret + elif not isinstance(subexpr, _CodegenArrayAbstract): + ret = _array2matrix(subexpr) + if isinstance(ret, MatrixExpr): + assert expr.contraction_indices == ((0, 1),) + return _a2m_trace(ret) + else: + return _array_contraction(ret, *expr.contraction_indices) + + +@_array2matrix.register(ArrayDiagonal) +def _(expr: ArrayDiagonal): + pexpr = _array_diagonal(_array2matrix(expr.expr), *expr.diagonal_indices) + pexpr = identify_hadamard_products(pexpr) + if isinstance(pexpr, ArrayDiagonal): + pexpr = _array_diag2contr_diagmatrix(pexpr) + if expr == pexpr: + return expr + return _array2matrix(pexpr) + + +@_array2matrix.register(PermuteDims) +def _(expr: PermuteDims): + if expr.permutation.array_form == [1, 0]: + return _a2m_transpose(_array2matrix(expr.expr)) + elif isinstance(expr.expr, ArrayTensorProduct): + ranks = expr.expr.subranks + inv_permutation = expr.permutation**(-1) + newrange = [inv_permutation(i) for i in range(sum(ranks))] + newpos = [] + counter = 0 + for rank in ranks: + newpos.append(newrange[counter:counter+rank]) + counter += rank + newargs = [] + newperm = [] + scalars = [] + for pos, arg in zip(newpos, expr.expr.args): + if len(pos) == 0: + scalars.append(_array2matrix(arg)) + elif pos == sorted(pos): + newargs.append((_array2matrix(arg), pos[0])) + newperm.extend(pos) + elif len(pos) == 2: + newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0])) + newperm.extend(reversed(pos)) + else: + raise NotImplementedError() + newargs = [i[0] for i in newargs] + return _permute_dims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm)) + elif isinstance(expr.expr, ArrayContraction): + mat_mul_lines = _array2matrix(expr.expr) + if not isinstance(mat_mul_lines, ArrayTensorProduct): + return _permute_dims(mat_mul_lines, expr.permutation) + # TODO: this assumes that all arguments are matrices, it may not be the case: + permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation + permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))] + args_array = [None for i in mat_mul_lines.args] + for i in range(len(mat_mul_lines.args)): + p1 = permuted[2*i] + p2 = permuted[2*i+1] + if p1 // 2 != p2 // 2: + return _permute_dims(mat_mul_lines, permutation) + if p1 > p2: + args_array[i] = _a2m_transpose(mat_mul_lines.args[p1 // 2]) + else: + args_array[i] = mat_mul_lines.args[p1 // 2] + return _a2m_tensor_product(*args_array) + else: + return expr + + +@_array2matrix.register(ArrayAdd) +def _(expr: ArrayAdd): + addends = [_array2matrix(arg) for arg in expr.args] + return _a2m_add(*addends) + + +@_array2matrix.register(ArrayElementwiseApplyFunc) +def _(expr: ArrayElementwiseApplyFunc): + subexpr = _array2matrix(expr.expr) + if isinstance(subexpr, MatrixExpr): + if subexpr.shape != (1, 1): + d = expr.function.bound_symbols[0] + w = Wild("w", exclude=[d]) + p = Wild("p", exclude=[d]) + m = expr.function.expr.match(w*d**p) + if m is not None: + return m[w]*HadamardPower(subexpr, m[p]) + return ElementwiseApplyFunction(expr.function, subexpr) + else: + return ArrayElementwiseApplyFunc(expr.function, subexpr) + + +@_array2matrix.register(ArrayElement) +def _(expr: ArrayElement): + ret = _array2matrix(expr.name) + if isinstance(ret, MatrixExpr): + return MatrixElement(ret, *expr.indices) + return ArrayElement(ret, expr.indices) + + +@singledispatch +def _remove_trivial_dims(expr): + return expr, [] + + +@_remove_trivial_dims.register(ArrayTensorProduct) +def _(expr: ArrayTensorProduct): + # Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`. + # The matrix expression has to be equivalent to the tensor product of the + # matrices, with trivial dimensions (i.e. dim=1) dropped. + # That is, add contractions over trivial dimensions: + + removed = [] + newargs = [] + cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args])) + pending = None + prev_i = None + for i, arg in enumerate(expr.args): + current_range = list(range(cumul[i], cumul[i+1])) + if isinstance(arg, OneArray): + removed.extend(current_range) + continue + if not isinstance(arg, (MatrixExpr, MatrixCommon)): + rarg, rem = _remove_trivial_dims(arg) + removed.extend(rem) + newargs.append(rarg) + continue + elif getattr(arg, "is_Identity", False) and arg.shape == (1, 1): + if arg.shape == (1, 1): + # Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1. + removed.extend(current_range) + continue + elif arg.shape == (1, 1): + arg, _ = _remove_trivial_dims(arg) + # Matrix is equivalent to scalar: + if len(newargs) == 0: + newargs.append(arg) + elif 1 in get_shape(newargs[-1]): + if newargs[-1].shape[1] == 1: + newargs[-1] = newargs[-1]*arg + else: + newargs[-1] = arg*newargs[-1] + removed.extend(current_range) + else: + newargs.append(arg) + elif 1 in arg.shape: + k = [i for i in arg.shape if i != 1][0] + if pending is None: + pending = k + prev_i = i + newargs.append(arg) + elif pending == k: + prev = newargs[-1] + if prev.shape[0] == 1: + d1 = cumul[prev_i] + prev = _a2m_transpose(prev) + else: + d1 = cumul[prev_i] + 1 + if arg.shape[1] == 1: + d2 = cumul[i] + 1 + arg = _a2m_transpose(arg) + else: + d2 = cumul[i] + newargs[-1] = prev*arg + pending = None + removed.extend([d1, d2]) + else: + newargs.append(arg) + pending = k + prev_i = i + else: + newargs.append(arg) + pending = None + newexpr, newremoved = _a2m_tensor_product(*newargs), sorted(removed) + if isinstance(newexpr, ArrayTensorProduct): + newexpr, newremoved2 = _find_trivial_matrices_rewrite(newexpr) + newremoved = _combine_removed(-1, newremoved, newremoved2) + if isinstance(newexpr, ArrayTensorProduct): + newexpr, newremoved2 = _find_trivial_kronecker_products_broadcast(newexpr) + newremoved = _combine_removed(-1, newremoved, newremoved2) + return newexpr, newremoved + + +@_remove_trivial_dims.register(ArrayAdd) +def _(expr: ArrayAdd): + rec = [_remove_trivial_dims(arg) for arg in expr.args] + newargs, removed = zip(*rec) + if len({get_shape(i) for i in newargs}) > 1: + return expr, [] + if len(removed) == 0: + return expr, removed + removed1 = removed[0] + return _a2m_add(*newargs), removed1 + + +@_remove_trivial_dims.register(PermuteDims) +def _(expr: PermuteDims): + subexpr, subremoved = _remove_trivial_dims(expr.expr) + p = expr.permutation.array_form + pinv = _af_invert(expr.permutation.array_form) + shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))])) + premoved = [pinv[i] for i in subremoved] + p2 = [e - shift[e] for i, e in enumerate(p) if e not in subremoved] + # TODO: check if subremoved should be permuted as well... + newexpr = _permute_dims(subexpr, p2) + premoved = sorted(premoved) + if newexpr != expr: + newexpr, removed2 = _remove_trivial_dims(_array2matrix(newexpr)) + premoved = _combine_removed(-1, premoved, removed2) + return newexpr, premoved + + +@_remove_trivial_dims.register(ArrayContraction) +def _(expr: ArrayContraction): + new_expr, removed0 = _array_contraction_to_diagonal_multiple_identity(expr) + if new_expr != expr: + new_expr2, removed1 = _remove_trivial_dims(_array2matrix(new_expr)) + removed = _combine_removed(-1, removed0, removed1) + return new_expr2, removed + rank1 = get_rank(expr) + expr, removed1 = remove_identity_matrices(expr) + if not isinstance(expr, ArrayContraction): + expr2, removed2 = _remove_trivial_dims(expr) + return expr2, _combine_removed(rank1, removed1, removed2) + newexpr, removed2 = _remove_trivial_dims(expr.expr) + shifts = list(accumulate([1 if i in removed2 else 0 for i in range(get_rank(expr.expr))])) + new_contraction_indices = [tuple(j for j in i if j not in removed2) for i in expr.contraction_indices] + # Remove possible empty tuples "()": + new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0] + contraction_indices_flat = [j for i in expr.contraction_indices for j in i] + removed2 = [i for i in removed2 if i not in contraction_indices_flat] + new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices] + # Shift removed2: + removed2 = ArrayContraction._push_indices_up(expr.contraction_indices, removed2) + removed = _combine_removed(rank1, removed1, removed2) + return _array_contraction(newexpr, *new_contraction_indices), list(removed) + + +def _remove_diagonalized_identity_matrices(expr: ArrayDiagonal): + assert isinstance(expr, ArrayDiagonal) + editor = _EditArrayContraction(expr) + mapping = {i: {j for j in editor.args_with_ind if i in j.indices} for i in range(-1, -1-editor.number_of_diagonal_indices, -1)} + removed = [] + counter: int = 0 + for i, arg_with_ind in enumerate(editor.args_with_ind): + counter += len(arg_with_ind.indices) + if isinstance(arg_with_ind.element, Identity): + if None in arg_with_ind.indices and any(i is not None and (i < 0) == True for i in arg_with_ind.indices): + diag_ind = [j for j in arg_with_ind.indices if j is not None][0] + other = [j for j in mapping[diag_ind] if j != arg_with_ind][0] + if not isinstance(other.element, MatrixExpr): + continue + if 1 not in other.element.shape: + continue + if None not in other.indices: + continue + editor.args_with_ind[i].element = None + none_index = other.indices.index(None) + other.element = DiagMatrix(other.element) + other_range = editor.get_absolute_range(other) + removed.extend([other_range[0] + none_index]) + editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] + removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, get_rank(expr.expr)) + return editor.to_array_contraction(), removed + + +@_remove_trivial_dims.register(ArrayDiagonal) +def _(expr: ArrayDiagonal): + newexpr, removed = _remove_trivial_dims(expr.expr) + shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))])) + new_diag_indices_map = {i: tuple(j for j in i if j not in removed) for i in expr.diagonal_indices} + for old_diag_tuple, new_diag_tuple in new_diag_indices_map.items(): + if len(new_diag_tuple) == 1: + removed = [i for i in removed if i not in old_diag_tuple] + new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices_map.values()] + rank = get_rank(expr.expr) + removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank) + removed = sorted(set(removed)) + # If there are single axes to diagonalize remaining, it means that their + # corresponding dimension has been removed, they no longer need diagonalization: + new_diag_indices = [i for i in new_diag_indices if len(i) > 0] + if len(new_diag_indices) > 0: + newexpr2 = _array_diagonal(newexpr, *new_diag_indices, allow_trivial_diags=True) + else: + newexpr2 = newexpr + if isinstance(newexpr2, ArrayDiagonal): + newexpr3, removed2 = _remove_diagonalized_identity_matrices(newexpr2) + removed = _combine_removed(-1, removed, removed2) + return newexpr3, removed + else: + return newexpr2, removed + + +@_remove_trivial_dims.register(ElementwiseApplyFunction) +def _(expr: ElementwiseApplyFunction): + subexpr, removed = _remove_trivial_dims(expr.expr) + if subexpr.shape == (1, 1): + # TODO: move this to ElementwiseApplyFunction + return expr.function(subexpr), removed + [0, 1] + return ElementwiseApplyFunction(expr.function, subexpr), [] + + +@_remove_trivial_dims.register(ArrayElementwiseApplyFunc) +def _(expr: ArrayElementwiseApplyFunc): + subexpr, removed = _remove_trivial_dims(expr.expr) + return ArrayElementwiseApplyFunc(expr.function, subexpr), removed + + +def convert_array_to_matrix(expr): + r""" + Recognize matrix expressions in codegen objects. + + If more than one matrix multiplication line have been detected, return a + list with the matrix expressions. + + Examples + ======== + + >>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array + >>> from sympy.tensor.array import tensorcontraction, tensorproduct + >>> from sympy import MatrixSymbol, Sum + >>> from sympy.abc import i, j, k, l, N + >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array + >>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix + >>> A = MatrixSymbol("A", N, N) + >>> B = MatrixSymbol("B", N, N) + >>> C = MatrixSymbol("C", N, N) + >>> D = MatrixSymbol("D", N, N) + + >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + A*B + >>> cg = convert_indexed_to_array(expr, first_indices=[k]) + >>> convert_array_to_matrix(cg) + B.T*A.T + + Transposition is detected: + + >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + A.T*B + >>> cg = convert_indexed_to_array(expr, first_indices=[k]) + >>> convert_array_to_matrix(cg) + B.T*A + + Detect the trace: + + >>> expr = Sum(A[i, i], (i, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + Trace(A) + + Recognize some more complex traces: + + >>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + Trace(A*B) + + More complicated expressions: + + >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + A*B.T*A.T + + Expressions constructed from matrix expressions do not contain literal + indices, the positions of free indices are returned instead: + + >>> expr = A*B + >>> cg = convert_matrix_to_array(expr) + >>> convert_array_to_matrix(cg) + A*B + + If more than one line of matrix multiplications is detected, return + separate matrix multiplication factors embedded in a tensor product object: + + >>> cg = tensorcontraction(tensorproduct(A, B, C, D), (1, 2), (5, 6)) + >>> convert_array_to_matrix(cg) + ArrayTensorProduct(A*B, C*D) + + The two lines have free indices at axes 0, 3 and 4, 7, respectively. + """ + rec = _array2matrix(expr) + rec, removed = _remove_trivial_dims(rec) + return rec + + +def _array_diag2contr_diagmatrix(expr: ArrayDiagonal): + if isinstance(expr.expr, ArrayTensorProduct): + args = list(expr.expr.args) + diag_indices = list(expr.diagonal_indices) + mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args]) + tuple_links = [[mapping[j] for j in i] for i in diag_indices] + contr_indices = [] + total_rank = get_rank(expr) + replaced = [False for arg in args] + for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)): + if len(abs_pos) != 2: + continue + (pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos + arg1 = args[pos1_outer] + arg2 = args[pos2_outer] + if get_rank(arg1) != 2 or get_rank(arg2) != 2: + if replaced[pos1_outer]: + diag_indices[i] = None + if replaced[pos2_outer]: + diag_indices[i] = None + continue + pos1_in2 = 1 - pos1_inner + pos2_in2 = 1 - pos2_inner + if arg1.shape[pos1_in2] == 1: + if arg1.shape[pos1_inner] != 1: + darg1 = DiagMatrix(arg1) + else: + darg1 = arg1 + args.append(darg1) + contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner))) + total_rank += 1 + diag_indices[i] = None + args[pos1_outer] = OneArray(arg1.shape[pos1_in2]) + replaced[pos1_outer] = True + elif arg2.shape[pos2_in2] == 1: + if arg2.shape[pos2_inner] != 1: + darg2 = DiagMatrix(arg2) + else: + darg2 = arg2 + args.append(darg2) + contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner))) + total_rank += 1 + diag_indices[i] = None + args[pos2_outer] = OneArray(arg2.shape[pos2_in2]) + replaced[pos2_outer] = True + diag_indices_new = [i for i in diag_indices if i is not None] + cumul = list(accumulate([0] + [get_rank(arg) for arg in args])) + contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices] + tc = _array_contraction( + _array_tensor_product(*args), *contr_indices2 + ) + td = _array_diagonal(tc, *diag_indices_new) + return td + return expr + + +def _a2m_mul(*args): + if not any(isinstance(i, _CodegenArrayAbstract) for i in args): + from sympy.matrices.expressions.matmul import MatMul + return MatMul(*args).doit() + else: + return _array_contraction( + _array_tensor_product(*args), + *[(2*i-1, 2*i) for i in range(1, len(args))] + ) + + +def _a2m_tensor_product(*args): + scalars = [] + arrays = [] + for arg in args: + if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)): + arrays.append(arg) + else: + scalars.append(arg) + scalar = Mul.fromiter(scalars) + if len(arrays) == 0: + return scalar + if scalar != 1: + if isinstance(arrays[0], _CodegenArrayAbstract): + arrays = [scalar] + arrays + else: + arrays[0] *= scalar + return _array_tensor_product(*arrays) + + +def _a2m_add(*args): + if not any(isinstance(i, _CodegenArrayAbstract) for i in args): + from sympy.matrices.expressions.matadd import MatAdd + return MatAdd(*args).doit() + else: + return _array_add(*args) + + +def _a2m_trace(arg): + if isinstance(arg, _CodegenArrayAbstract): + return _array_contraction(arg, (0, 1)) + else: + from sympy.matrices.expressions.trace import Trace + return Trace(arg) + + +def _a2m_transpose(arg): + if isinstance(arg, _CodegenArrayAbstract): + return _permute_dims(arg, [1, 0]) + else: + from sympy.matrices.expressions.transpose import Transpose + return Transpose(arg).doit() + + +def identify_hadamard_products(expr: tUnion[ArrayContraction, ArrayDiagonal]): + + editor: _EditArrayContraction = _EditArrayContraction(expr) + + map_contr_to_args: tDict[FrozenSet, List[_ArgE]] = defaultdict(list) + map_ind_to_inds: tDict[Optional[int], int] = defaultdict(int) + for arg_with_ind in editor.args_with_ind: + for ind in arg_with_ind.indices: + map_ind_to_inds[ind] += 1 + if None in arg_with_ind.indices: + continue + map_contr_to_args[frozenset(arg_with_ind.indices)].append(arg_with_ind) + + k: FrozenSet[int] + v: List[_ArgE] + for k, v in map_contr_to_args.items(): + make_trace: bool = False + if len(k) == 1 and next(iter(k)) >= 0 and sum([next(iter(k)) in i for i in map_contr_to_args]) == 1: + # This is a trace: the arguments are fully contracted with only one + # index, and the index isn't used anywhere else: + make_trace = True + first_element = S.One + elif len(k) != 2: + # Hadamard product only defined for matrices: + continue + if len(v) == 1: + # Hadamard product with a single argument makes no sense: + continue + for ind in k: + if map_ind_to_inds[ind] <= 2: + # There is no other contraction, skip: + continue + + def check_transpose(x): + x = [i if i >= 0 else -1-i for i in x] + return x == sorted(x) + + # Check if expression is a trace: + if all([map_ind_to_inds[j] == len(v) and j >= 0 for j in k]) and all([j >= 0 for j in k]): + # This is a trace + make_trace = True + first_element = v[0].element + if not check_transpose(v[0].indices): + first_element = first_element.T + hadamard_factors = v[1:] + else: + hadamard_factors = v + + # This is a Hadamard product: + + hp = hadamard_product(*[i.element if check_transpose(i.indices) else Transpose(i.element) for i in hadamard_factors]) + hp_indices = v[0].indices + if not check_transpose(hadamard_factors[0].indices): + hp_indices = list(reversed(hp_indices)) + if make_trace: + hp = Trace(first_element*hp.T)._normalize() + hp_indices = [] + editor.insert_after(v[0], _ArgE(hp, hp_indices)) + for i in v: + editor.args_with_ind.remove(i) + + return editor.to_array_contraction() + + +def identify_removable_identity_matrices(expr): + editor = _EditArrayContraction(expr) + + flag = True + while flag: + flag = False + for arg_with_ind in editor.args_with_ind: + if isinstance(arg_with_ind.element, Identity): + k = arg_with_ind.element.shape[0] + # Candidate for removal: + if arg_with_ind.indices == [None, None]: + # Free identity matrix, will be cleared by _remove_trivial_dims: + continue + elif None in arg_with_ind.indices: + ind = [j for j in arg_with_ind.indices if j is not None][0] + counted = editor.count_args_with_index(ind) + if counted == 1: + # Identity matrix contracted only on one index with itself, + # transform to a OneArray(k) element: + editor.insert_after(arg_with_ind, OneArray(k)) + editor.args_with_ind.remove(arg_with_ind) + flag = True + break + elif counted > 2: + # Case counted = 2 is a matrix multiplication by identity matrix, skip it. + # Case counted > 2 is a multiple contraction, + # this is a case where the contraction becomes a diagonalization if the + # identity matrix is dropped. + continue + elif arg_with_ind.indices[0] == arg_with_ind.indices[1]: + ind = arg_with_ind.indices[0] + counted = editor.count_args_with_index(ind) + if counted > 1: + editor.args_with_ind.remove(arg_with_ind) + flag = True + break + else: + # This is a trace, skip it as it will be recognized somewhere else: + pass + elif ask(Q.diagonal(arg_with_ind.element)): + if arg_with_ind.indices == [None, None]: + continue + elif None in arg_with_ind.indices: + pass + elif arg_with_ind.indices[0] == arg_with_ind.indices[1]: + ind = arg_with_ind.indices[0] + counted = editor.count_args_with_index(ind) + if counted == 3: + # A_ai B_bi D_ii ==> A_ai D_ij B_bj + ind_new = editor.get_new_contraction_index() + other_args = [j for j in editor.args_with_ind if j != arg_with_ind] + other_args[1].indices = [ind_new if j == ind else j for j in other_args[1].indices] + arg_with_ind.indices = [ind, ind_new] + flag = True + break + + return editor.to_array_contraction() + + +def remove_identity_matrices(expr: ArrayContraction): + editor = _EditArrayContraction(expr) + removed: List[int] = [] + + permutation_map = {} + + free_indices = list(accumulate([0] + [sum([i is None for i in arg.indices]) for arg in editor.args_with_ind])) + free_map = {k: v for k, v in zip(editor.args_with_ind, free_indices[:-1])} + + update_pairs = {} + + for ind in range(editor.number_of_contraction_indices): + args = editor.get_args_with_index(ind) + identity_matrices = [i for i in args if isinstance(i.element, Identity)] + number_identity_matrices = len(identity_matrices) + # If the contraction involves a non-identity matrix and multiple identity matrices: + if number_identity_matrices != len(args) - 1 or number_identity_matrices == 0: + continue + # Get the non-identity element: + non_identity = [i for i in args if not isinstance(i.element, Identity)][0] + # Check that all identity matrices have at least one free index + # (otherwise they would be contractions to some other elements) + if any([None not in i.indices for i in identity_matrices]): + continue + # Mark the identity matrices for removal: + for i in identity_matrices: + i.element = None + removed.extend(range(free_map[i], free_map[i] + len([j for j in i.indices if j is None]))) + last_removed = removed.pop(-1) + update_pairs[last_removed, ind] = non_identity.indices[:] + # Remove the indices from the non-identity matrix, as the contraction + # no longer exists: + non_identity.indices = [None if i == ind else i for i in non_identity.indices] + + removed.sort() + + shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr))])) + for (last_removed, ind), non_identity_indices in update_pairs.items(): + pos = [free_map[non_identity] + i for i, e in enumerate(non_identity_indices) if e == ind] + assert len(pos) == 1 + for j in pos: + permutation_map[j] = last_removed + + editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] + ret_expr = editor.to_array_contraction() + permutation = [] + counter = 0 + counter2 = 0 + for j in range(get_rank(expr)): + if j in removed: + continue + if counter2 in permutation_map: + target = permutation_map[counter2] + permutation.append(target - shifts[target]) + counter2 += 1 + else: + while counter in permutation_map.values(): + counter += 1 + permutation.append(counter) + counter += 1 + counter2 += 1 + ret_expr2 = _permute_dims(ret_expr, _af_invert(permutation)) + return ret_expr2, removed + + +def _combine_removed(dim: int, removed1: List[int], removed2: List[int]) -> List[int]: + # Concatenate two axis removal operations as performed by + # _remove_trivial_dims, + removed1 = sorted(removed1) + removed2 = sorted(removed2) + i = 0 + j = 0 + removed = [] + while True: + if j >= len(removed2): + while i < len(removed1): + removed.append(removed1[i]) + i += 1 + break + elif i < len(removed1) and removed1[i] <= i + removed2[j]: + removed.append(removed1[i]) + i += 1 + else: + removed.append(i + removed2[j]) + j += 1 + return removed + + +def _array_contraction_to_diagonal_multiple_identity(expr: ArrayContraction): + editor = _EditArrayContraction(expr) + editor.track_permutation_start() + removed: List[int] = [] + diag_index_counter: int = 0 + for i in range(editor.number_of_contraction_indices): + identities = [] + args = [] + for j, arg in enumerate(editor.args_with_ind): + if i not in arg.indices: + continue + if isinstance(arg.element, Identity): + identities.append(arg) + else: + args.append(arg) + if len(identities) == 0: + continue + if len(args) + len(identities) < 3: + continue + new_diag_ind = -1 - diag_index_counter + diag_index_counter += 1 + # Variable "flag" to control whether to skip this contraction set: + flag: bool = True + for i1, id1 in enumerate(identities): + if None not in id1.indices: + flag = True + break + free_pos = list(range(*editor.get_absolute_free_range(id1)))[0] + editor._track_permutation[-1].append(free_pos) # type: ignore + id1.element = None + flag = False + break + if flag: + continue + for arg in identities[:i1] + identities[i1+1:]: + arg.element = None + removed.extend(range(*editor.get_absolute_free_range(arg))) + for arg in args: + arg.indices = [new_diag_ind if j == i else j for j in arg.indices] + for j, e in enumerate(editor.args_with_ind): + if e.element is None: + editor._track_permutation[j] = None # type: ignore + editor._track_permutation = [i for i in editor._track_permutation if i is not None] # type: ignore + # Renumber permutation array form in order to deal with deleted positions: + remap = {e: i for i, e in enumerate(sorted({k for j in editor._track_permutation for k in j}))} + editor._track_permutation = [[remap[j] for j in i] for i in editor._track_permutation] + editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] + new_expr = editor.to_array_contraction() + return new_expr, removed diff --git a/shared/package-files/38/3879966b059c08c5441bf245452e39fc91f0a0f53745432abdb15e198d841bbe/control_flow_opinfo_db.py b/shared/package-files/38/3879966b059c08c5441bf245452e39fc91f0a0f53745432abdb15e198d841bbe/control_flow_opinfo_db.py new file mode 100644 index 0000000000000000000000000000000000000000..6cd17627939e848d2195ef51b2159c1b1b5af424 --- /dev/null +++ b/shared/package-files/38/3879966b059c08c5441bf245452e39fc91f0a0f53745432abdb15e198d841bbe/control_flow_opinfo_db.py @@ -0,0 +1,77 @@ +# mypy: ignore-errors + +import torch +import functools +from torch.testing import make_tensor +from functorch.experimental.control_flow import map +from torch.testing._internal.opinfo.core import ( + OpInfo, + SampleInput, +) +from torch.testing._internal.common_dtype import all_types_and + +def sample_inputs_map(opinfo, device, dtype, requires_grad, **kwargs): + make_arg = functools.partial( + make_tensor, device=device, dtype=dtype, requires_grad=requires_grad) + yield SampleInput([make_arg(2, 2, 2, low=0.1, high=2), make_arg(2, 2, 2, low=0.1, high=2)], + args=(make_arg(1, low=0.1, high=2), make_arg(1, low=0.1, high=2))) + +def inner_f(x, y0, y1): + return [x[0].cos().add_(1.) * y0, (x[1] + y1.sin()).cos_().view(x[1].size())] + +def simple_map(xs, y0, y1): + def f(x, y0, y1): + return inner_f(x, y0, y1) + return map(f, xs, y0, y1) + +def nested_map(xs, y0, y1): + def f1(xx, y0, y1): + def f2(x, y0, y1): + return inner_f(x, y0, y1) + return map(f2, xx, y0, y1) + return map(f1, xs, y0, y1) + +def triple_nested_map(xs, y0, y1): + def f0(xs, y0, y1): + def f1(xx, y0, y1): + def f2(x, y0, y1): + return inner_f(x, y0, y1) + return map(f2, xx, y0, y1) + return map(f1, xs, y0, y1) + return map(f0, xs, y0, y1) + +control_flow_opinfo_db = [ + OpInfo( + "MapControlflowOp", + op=simple_map, + sample_inputs_func=sample_inputs_map, + dtypes=all_types_and(torch.bool, torch.half), + supports_out=False, + check_batched_grad=False, + check_batched_gradgrad=False, + check_batched_forward_grad=False, + check_inplace_batched_forward_grad=False, + ), + OpInfo( + "NestedMapControlflowOp", + op=nested_map, + sample_inputs_func=sample_inputs_map, + dtypes=all_types_and(torch.bool, torch.half), + supports_out=False, + check_batched_grad=False, + check_batched_gradgrad=False, + check_batched_forward_grad=False, + check_inplace_batched_forward_grad=False, + ), + OpInfo( + "TripleNestedMapControlflowOp", + op=triple_nested_map, + sample_inputs_func=sample_inputs_map, + dtypes=all_types_and(torch.bool, torch.half), + supports_out=False, + check_batched_grad=False, + check_batched_gradgrad=False, + check_batched_forward_grad=False, + check_inplace_batched_forward_grad=False, + ) +] diff --git a/shared/package-files/38/387c4edc75134519f92221c1422d68605b05790d29b7c01edb397c748d7d6fc5/RECORD b/shared/package-files/38/387c4edc75134519f92221c1422d68605b05790d29b7c01edb397c748d7d6fc5/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0f3fb436f07da6bce79f81465c5bc48ece9f39df --- /dev/null +++ b/shared/package-files/38/387c4edc75134519f92221c1422d68605b05790d29b7c01edb397c748d7d6fc5/RECORD @@ -0,0 +1,11 @@ +Brotli-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +Brotli-1.0.9.dist-info/LICENSE,sha256=PRgACONpIqTo2uwRw0x68mT-1ZYtB5JK6pKMOOhmPJQ,1084 +Brotli-1.0.9.dist-info/METADATA,sha256=F-hhct3u9qHLnoc4-lY5EPl6q2CvNkaqe3XHiNPQs9E,1366 +Brotli-1.0.9.dist-info/RECORD,, +Brotli-1.0.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +Brotli-1.0.9.dist-info/WHEEL,sha256=nTy_Z8ivGEB6qFwVLg7_h6rq0Jt0JU5Pz2cL2_FjSMQ,105 +Brotli-1.0.9.dist-info/direct_url.json,sha256=1vQFFEnet4t6aNzIPlhugWstIpZ9MKfdGeO8ODIR5Vk,99 +Brotli-1.0.9.dist-info/top_level.txt,sha256=gsS54HrhO3ZveFxeMrKo_7qH4Sm4TbQ7jGLVBEqJ4NI,15 +__pycache__/brotli.cpython-310.pyc,, +_brotli.cpython-310-x86_64-linux-gnu.so,sha256=HvmkW7vYowhn_U936N0O77HeRxtlp-TBA1KMaVknvt8,5214600 +brotli.py,sha256=iwoQnPvrANtaJYTJ6mSjOQUENH7Z8RgAEbn-HxMR-kU,1857 diff --git a/shared/package-files/38/387d1d0f828dad511ff05942ef931eced860103a2103c772937bb1c28b85f0b3/test_timedelta64.py b/shared/package-files/38/387d1d0f828dad511ff05942ef931eced860103a2103c772937bb1c28b85f0b3/test_timedelta64.py new file mode 100644 index 0000000000000000000000000000000000000000..d02e827d435cf16c806b5130f5949143f51c15e3 --- /dev/null +++ b/shared/package-files/38/387d1d0f828dad511ff05942ef931eced860103a2103c772937bb1c28b85f0b3/test_timedelta64.py @@ -0,0 +1,2179 @@ +# Arithmetic tests for DataFrame/Series/Index/Array classes that should +# behave identically. +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +from pandas.errors import ( + OutOfBoundsDatetime, + PerformanceWarning, +) + +import pandas as pd +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + NaT, + Series, + Timedelta, + TimedeltaIndex, + Timestamp, + offsets, + timedelta_range, +) +import pandas._testing as tm +from pandas.core.arrays import NumpyExtensionArray +from pandas.tests.arithmetic.common import ( + assert_invalid_addsub_type, + assert_invalid_comparison, + get_upcast_box, +) + + +def assert_dtype(obj, expected_dtype): + """ + Helper to check the dtype for a Series, Index, or single-column DataFrame. + """ + dtype = tm.get_dtype(obj) + + assert dtype == expected_dtype + + +def get_expected_name(box, names): + if box is DataFrame: + # Since we are operating with a DataFrame and a non-DataFrame, + # the non-DataFrame is cast to Series and its name ignored. + exname = names[0] + elif box in [tm.to_array, pd.array]: + exname = names[1] + else: + exname = names[2] + return exname + + +# ------------------------------------------------------------------ +# Timedelta64[ns] dtype Comparisons + + +class TestTimedelta64ArrayLikeComparisons: + # Comparison tests for timedelta64[ns] vectors fully parametrized over + # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all comparison + # tests will eventually end up here. + + def test_compare_timedelta64_zerodim(self, box_with_array): + # GH#26689 should unbox when comparing with zerodim array + box = box_with_array + xbox = box_with_array if box_with_array not in [Index, pd.array] else np.ndarray + + tdi = timedelta_range("2h", periods=4) + other = np.array(tdi.to_numpy()[0]) + + tdi = tm.box_expected(tdi, box) + res = tdi <= other + expected = np.array([True, False, False, False]) + expected = tm.box_expected(expected, xbox) + tm.assert_equal(res, expected) + + @pytest.mark.parametrize( + "td_scalar", + [ + timedelta(days=1), + Timedelta(days=1), + Timedelta(days=1).to_timedelta64(), + offsets.Hour(24), + ], + ) + def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar): + # regression test for GH#5963 + box = box_with_array + xbox = box if box not in [Index, pd.array] else np.ndarray + + ser = Series([timedelta(days=1), timedelta(days=2)]) + ser = tm.box_expected(ser, box) + actual = ser > td_scalar + expected = Series([False, True]) + expected = tm.box_expected(expected, xbox) + tm.assert_equal(actual, expected) + + @pytest.mark.parametrize( + "invalid", + [ + 345600000000000, + "a", + Timestamp("2021-01-01"), + Timestamp("2021-01-01").now("UTC"), + Timestamp("2021-01-01").now().to_datetime64(), + Timestamp("2021-01-01").now().to_pydatetime(), + Timestamp("2021-01-01").date(), + np.array(4), # zero-dim mismatched dtype + ], + ) + def test_td64_comparisons_invalid(self, box_with_array, invalid): + # GH#13624 for str + box = box_with_array + + rng = timedelta_range("1 days", periods=10) + obj = tm.box_expected(rng, box) + + assert_invalid_comparison(obj, invalid, box) + + @pytest.mark.parametrize( + "other", + [ + list(range(10)), + np.arange(10), + np.arange(10).astype(np.float32), + np.arange(10).astype(object), + pd.date_range("1970-01-01", periods=10, tz="UTC").array, + np.array(pd.date_range("1970-01-01", periods=10)), + list(pd.date_range("1970-01-01", periods=10)), + pd.date_range("1970-01-01", periods=10).astype(object), + pd.period_range("1971-01-01", freq="D", periods=10).array, + pd.period_range("1971-01-01", freq="D", periods=10).astype(object), + ], + ) + def test_td64arr_cmp_arraylike_invalid(self, other, box_with_array): + # We don't parametrize this over box_with_array because listlike + # other plays poorly with assert_invalid_comparison reversed checks + + rng = timedelta_range("1 days", periods=10)._data + rng = tm.box_expected(rng, box_with_array) + assert_invalid_comparison(rng, other, box_with_array) + + def test_td64arr_cmp_mixed_invalid(self): + rng = timedelta_range("1 days", periods=5)._data + other = np.array([0, 1, 2, rng[3], Timestamp("2021-01-01")]) + + result = rng == other + expected = np.array([False, False, False, True, False]) + tm.assert_numpy_array_equal(result, expected) + + result = rng != other + tm.assert_numpy_array_equal(result, ~expected) + + msg = "Invalid comparison between|Cannot compare type|not supported between" + with pytest.raises(TypeError, match=msg): + rng < other + with pytest.raises(TypeError, match=msg): + rng > other + with pytest.raises(TypeError, match=msg): + rng <= other + with pytest.raises(TypeError, match=msg): + rng >= other + + +class TestTimedelta64ArrayComparisons: + # TODO: All of these need to be parametrized over box + + @pytest.mark.parametrize("dtype", [None, object]) + def test_comp_nat(self, dtype): + left = TimedeltaIndex([Timedelta("1 days"), NaT, Timedelta("3 days")]) + right = TimedeltaIndex([NaT, NaT, Timedelta("3 days")]) + + lhs, rhs = left, right + if dtype is object: + lhs, rhs = left.astype(object), right.astype(object) + + result = rhs == lhs + expected = np.array([False, False, True]) + tm.assert_numpy_array_equal(result, expected) + + result = rhs != lhs + expected = np.array([True, True, False]) + tm.assert_numpy_array_equal(result, expected) + + expected = np.array([False, False, False]) + tm.assert_numpy_array_equal(lhs == NaT, expected) + tm.assert_numpy_array_equal(NaT == rhs, expected) + + expected = np.array([True, True, True]) + tm.assert_numpy_array_equal(lhs != NaT, expected) + tm.assert_numpy_array_equal(NaT != lhs, expected) + + expected = np.array([False, False, False]) + tm.assert_numpy_array_equal(lhs < NaT, expected) + tm.assert_numpy_array_equal(NaT > lhs, expected) + + @pytest.mark.parametrize( + "idx2", + [ + TimedeltaIndex( + ["2 day", "2 day", NaT, NaT, "1 day 00:00:02", "5 days 00:00:03"] + ), + np.array( + [ + np.timedelta64(2, "D"), + np.timedelta64(2, "D"), + np.timedelta64("nat"), + np.timedelta64("nat"), + np.timedelta64(1, "D") + np.timedelta64(2, "s"), + np.timedelta64(5, "D") + np.timedelta64(3, "s"), + ] + ), + ], + ) + def test_comparisons_nat(self, idx2): + idx1 = TimedeltaIndex( + [ + "1 day", + NaT, + "1 day 00:00:01", + NaT, + "1 day 00:00:01", + "5 day 00:00:03", + ] + ) + # Check pd.NaT is handles as the same as np.nan + result = idx1 < idx2 + expected = np.array([True, False, False, False, True, False]) + tm.assert_numpy_array_equal(result, expected) + + result = idx2 > idx1 + expected = np.array([True, False, False, False, True, False]) + tm.assert_numpy_array_equal(result, expected) + + result = idx1 <= idx2 + expected = np.array([True, False, False, False, True, True]) + tm.assert_numpy_array_equal(result, expected) + + result = idx2 >= idx1 + expected = np.array([True, False, False, False, True, True]) + tm.assert_numpy_array_equal(result, expected) + + result = idx1 == idx2 + expected = np.array([False, False, False, False, False, True]) + tm.assert_numpy_array_equal(result, expected) + + result = idx1 != idx2 + expected = np.array([True, True, True, True, True, False]) + tm.assert_numpy_array_equal(result, expected) + + # TODO: better name + def test_comparisons_coverage(self): + rng = timedelta_range("1 days", periods=10) + + result = rng < rng[3] + expected = np.array([True, True, True] + [False] * 7) + tm.assert_numpy_array_equal(result, expected) + + result = rng == list(rng) + exp = rng == rng + tm.assert_numpy_array_equal(result, exp) + + +# ------------------------------------------------------------------ +# Timedelta64[ns] dtype Arithmetic Operations + + +class TestTimedelta64ArithmeticUnsorted: + # Tests moved from type-specific test files but not + # yet sorted/parametrized/de-duplicated + + def test_ufunc_coercions(self): + # normal ops are also tested in tseries/test_timedeltas.py + idx = TimedeltaIndex(["2h", "4h", "6h", "8h", "10h"], freq="2h", name="x") + + for result in [idx * 2, np.multiply(idx, 2)]: + assert isinstance(result, TimedeltaIndex) + exp = TimedeltaIndex(["4h", "8h", "12h", "16h", "20h"], freq="4h", name="x") + tm.assert_index_equal(result, exp) + assert result.freq == "4h" + + for result in [idx / 2, np.divide(idx, 2)]: + assert isinstance(result, TimedeltaIndex) + exp = TimedeltaIndex(["1h", "2h", "3h", "4h", "5h"], freq="h", name="x") + tm.assert_index_equal(result, exp) + assert result.freq == "h" + + for result in [-idx, np.negative(idx)]: + assert isinstance(result, TimedeltaIndex) + exp = TimedeltaIndex( + ["-2h", "-4h", "-6h", "-8h", "-10h"], freq="-2h", name="x" + ) + tm.assert_index_equal(result, exp) + assert result.freq == "-2h" + + idx = TimedeltaIndex(["-2h", "-1h", "0h", "1h", "2h"], freq="h", name="x") + for result in [abs(idx), np.absolute(idx)]: + assert isinstance(result, TimedeltaIndex) + exp = TimedeltaIndex(["2h", "1h", "0h", "1h", "2h"], freq=None, name="x") + tm.assert_index_equal(result, exp) + assert result.freq is None + + def test_subtraction_ops(self): + # with datetimes/timedelta and tdi/dti + tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") + dti = pd.date_range("20130101", periods=3, name="bar") + td = Timedelta("1 days") + dt = Timestamp("20130101") + + msg = "cannot subtract a datelike from a TimedeltaArray" + with pytest.raises(TypeError, match=msg): + tdi - dt + with pytest.raises(TypeError, match=msg): + tdi - dti + + msg = r"unsupported operand type\(s\) for -" + with pytest.raises(TypeError, match=msg): + td - dt + + msg = "(bad|unsupported) operand type for unary" + with pytest.raises(TypeError, match=msg): + td - dti + + result = dt - dti + expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"], name="bar") + tm.assert_index_equal(result, expected) + + result = dti - dt + expected = TimedeltaIndex(["0 days", "1 days", "2 days"], name="bar") + tm.assert_index_equal(result, expected) + + result = tdi - td + expected = TimedeltaIndex(["0 days", NaT, "1 days"], name="foo") + tm.assert_index_equal(result, expected) + + result = td - tdi + expected = TimedeltaIndex(["0 days", NaT, "-1 days"], name="foo") + tm.assert_index_equal(result, expected) + + result = dti - td + expected = DatetimeIndex( + ["20121231", "20130101", "20130102"], dtype="M8[ns]", freq="D", name="bar" + ) + tm.assert_index_equal(result, expected) + + result = dt - tdi + expected = DatetimeIndex( + ["20121231", NaT, "20121230"], dtype="M8[ns]", name="foo" + ) + tm.assert_index_equal(result, expected) + + def test_subtraction_ops_with_tz(self, box_with_array): + # check that dt/dti subtraction ops with tz are validated + dti = pd.date_range("20130101", periods=3) + dti = tm.box_expected(dti, box_with_array) + ts = Timestamp("20130101") + dt = ts.to_pydatetime() + dti_tz = pd.date_range("20130101", periods=3).tz_localize("US/Eastern") + dti_tz = tm.box_expected(dti_tz, box_with_array) + ts_tz = Timestamp("20130101").tz_localize("US/Eastern") + ts_tz2 = Timestamp("20130101").tz_localize("CET") + dt_tz = ts_tz.to_pydatetime() + td = Timedelta("1 days") + + def _check(result, expected): + assert result == expected + assert isinstance(result, Timedelta) + + # scalars + result = ts - ts + expected = Timedelta("0 days") + _check(result, expected) + + result = dt_tz - ts_tz + expected = Timedelta("0 days") + _check(result, expected) + + result = ts_tz - dt_tz + expected = Timedelta("0 days") + _check(result, expected) + + # tz mismatches + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects." + with pytest.raises(TypeError, match=msg): + dt_tz - ts + msg = "can't subtract offset-naive and offset-aware datetimes" + with pytest.raises(TypeError, match=msg): + dt_tz - dt + msg = "can't subtract offset-naive and offset-aware datetimes" + with pytest.raises(TypeError, match=msg): + dt - dt_tz + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects." + with pytest.raises(TypeError, match=msg): + ts - dt_tz + with pytest.raises(TypeError, match=msg): + ts_tz2 - ts + with pytest.raises(TypeError, match=msg): + ts_tz2 - dt + + msg = "Cannot subtract tz-naive and tz-aware" + # with dti + with pytest.raises(TypeError, match=msg): + dti - ts_tz + with pytest.raises(TypeError, match=msg): + dti_tz - ts + + result = dti_tz - dt_tz + expected = TimedeltaIndex(["0 days", "1 days", "2 days"]) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + result = dt_tz - dti_tz + expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"]) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + result = dti_tz - ts_tz + expected = TimedeltaIndex(["0 days", "1 days", "2 days"]) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + result = ts_tz - dti_tz + expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"]) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + result = td - td + expected = Timedelta("0 days") + _check(result, expected) + + result = dti_tz - td + expected = DatetimeIndex( + ["20121231", "20130101", "20130102"], tz="US/Eastern" + ).as_unit("ns") + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + def test_dti_tdi_numeric_ops(self): + # These are normally union/diff set-like ops + tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") + dti = pd.date_range("20130101", periods=3, name="bar") + + result = tdi - tdi + expected = TimedeltaIndex(["0 days", NaT, "0 days"], name="foo") + tm.assert_index_equal(result, expected) + + result = tdi + tdi + expected = TimedeltaIndex(["2 days", NaT, "4 days"], name="foo") + tm.assert_index_equal(result, expected) + + result = dti - tdi # name will be reset + expected = DatetimeIndex(["20121231", NaT, "20130101"], dtype="M8[ns]") + tm.assert_index_equal(result, expected) + + def test_addition_ops(self): + # with datetimes/timedelta and tdi/dti + tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") + dti = pd.date_range("20130101", periods=3, name="bar") + td = Timedelta("1 days") + dt = Timestamp("20130101") + + result = tdi + dt + expected = DatetimeIndex( + ["20130102", NaT, "20130103"], dtype="M8[ns]", name="foo" + ) + tm.assert_index_equal(result, expected) + + result = dt + tdi + expected = DatetimeIndex( + ["20130102", NaT, "20130103"], dtype="M8[ns]", name="foo" + ) + tm.assert_index_equal(result, expected) + + result = td + tdi + expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo") + tm.assert_index_equal(result, expected) + + result = tdi + td + expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo") + tm.assert_index_equal(result, expected) + + # unequal length + msg = "cannot add indices of unequal length" + with pytest.raises(ValueError, match=msg): + tdi + dti[0:1] + with pytest.raises(ValueError, match=msg): + tdi[0:1] + dti + + # random indexes + msg = "Addition/subtraction of integers and integer-arrays" + with pytest.raises(TypeError, match=msg): + tdi + Index([1, 2, 3], dtype=np.int64) + + # this is a union! + # FIXME: don't leave commented-out + # pytest.raises(TypeError, lambda : Index([1,2,3]) + tdi) + + result = tdi + dti # name will be reset + expected = DatetimeIndex(["20130102", NaT, "20130105"], dtype="M8[ns]") + tm.assert_index_equal(result, expected) + + result = dti + tdi # name will be reset + expected = DatetimeIndex(["20130102", NaT, "20130105"], dtype="M8[ns]") + tm.assert_index_equal(result, expected) + + result = dt + td + expected = Timestamp("20130102") + assert result == expected + + result = td + dt + expected = Timestamp("20130102") + assert result == expected + + # TODO: Needs more informative name, probably split up into + # more targeted tests + @pytest.mark.parametrize("freq", ["D", "B"]) + def test_timedelta(self, freq): + index = pd.date_range("1/1/2000", periods=50, freq=freq) + + shifted = index + timedelta(1) + back = shifted + timedelta(-1) + back = back._with_freq("infer") + tm.assert_index_equal(index, back) + + if freq == "D": + expected = pd.tseries.offsets.Day(1) + assert index.freq == expected + assert shifted.freq == expected + assert back.freq == expected + else: # freq == 'B' + assert index.freq == pd.tseries.offsets.BusinessDay(1) + assert shifted.freq is None + assert back.freq == pd.tseries.offsets.BusinessDay(1) + + result = index - timedelta(1) + expected = index + timedelta(-1) + tm.assert_index_equal(result, expected) + + def test_timedelta_tick_arithmetic(self): + # GH#4134, buggy with timedeltas + rng = pd.date_range("2013", "2014") + s = Series(rng) + result1 = rng - offsets.Hour(1) + result2 = DatetimeIndex(s - np.timedelta64(100000000)) + result3 = rng - np.timedelta64(100000000) + result4 = DatetimeIndex(s - offsets.Hour(1)) + + assert result1.freq == rng.freq + result1 = result1._with_freq(None) + tm.assert_index_equal(result1, result4) + + assert result3.freq == rng.freq + result3 = result3._with_freq(None) + tm.assert_index_equal(result2, result3) + + def test_tda_add_sub_index(self): + # Check that TimedeltaArray defers to Index on arithmetic ops + tdi = TimedeltaIndex(["1 days", NaT, "2 days"]) + tda = tdi.array + + dti = pd.date_range("1999-12-31", periods=3, freq="D") + + result = tda + dti + expected = tdi + dti + tm.assert_index_equal(result, expected) + + result = tda + tdi + expected = tdi + tdi + tm.assert_index_equal(result, expected) + + result = tda - tdi + expected = tdi - tdi + tm.assert_index_equal(result, expected) + + def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture): + # Result should be cast back to DatetimeArray + box = box_with_array + + dti = pd.date_range("2016-01-01", periods=3, tz=tz_naive_fixture) + dti = dti._with_freq(None) + tdi = dti - dti + + obj = tm.box_expected(tdi, box) + other = tm.box_expected(dti, box) + + with tm.assert_produces_warning(PerformanceWarning): + result = obj + other.astype(object) + tm.assert_equal(result, other.astype(object)) + + # ------------------------------------------------------------- + # Binary operations TimedeltaIndex and timedelta-like + + def test_tdi_iadd_timedeltalike(self, two_hours, box_with_array): + # only test adding/sub offsets as + is now numeric + rng = timedelta_range("1 days", "10 days") + expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D") + + rng = tm.box_expected(rng, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + orig_rng = rng + rng += two_hours + tm.assert_equal(rng, expected) + if box_with_array is not Index: + # Check that operation is actually inplace + tm.assert_equal(orig_rng, expected) + + def test_tdi_isub_timedeltalike(self, two_hours, box_with_array): + # only test adding/sub offsets as - is now numeric + rng = timedelta_range("1 days", "10 days") + expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00") + + rng = tm.box_expected(rng, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + orig_rng = rng + rng -= two_hours + tm.assert_equal(rng, expected) + if box_with_array is not Index: + # Check that operation is actually inplace + tm.assert_equal(orig_rng, expected) + + # ------------------------------------------------------------- + + def test_tdi_ops_attributes(self): + rng = timedelta_range("2 days", periods=5, freq="2D", name="x") + + result = rng + 1 * rng.freq + exp = timedelta_range("4 days", periods=5, freq="2D", name="x") + tm.assert_index_equal(result, exp) + assert result.freq == "2D" + + result = rng - 2 * rng.freq + exp = timedelta_range("-2 days", periods=5, freq="2D", name="x") + tm.assert_index_equal(result, exp) + assert result.freq == "2D" + + result = rng * 2 + exp = timedelta_range("4 days", periods=5, freq="4D", name="x") + tm.assert_index_equal(result, exp) + assert result.freq == "4D" + + result = rng / 2 + exp = timedelta_range("1 days", periods=5, freq="D", name="x") + tm.assert_index_equal(result, exp) + assert result.freq == "D" + + result = -rng + exp = timedelta_range("-2 days", periods=5, freq="-2D", name="x") + tm.assert_index_equal(result, exp) + assert result.freq == "-2D" + + rng = timedelta_range("-2 days", periods=5, freq="D", name="x") + + result = abs(rng) + exp = TimedeltaIndex( + ["2 days", "1 days", "0 days", "1 days", "2 days"], name="x" + ) + tm.assert_index_equal(result, exp) + assert result.freq is None + + +class TestAddSubNaTMasking: + # TODO: parametrize over boxes + + @pytest.mark.parametrize("str_ts", ["1950-01-01", "1980-01-01"]) + def test_tdarr_add_timestamp_nat_masking(self, box_with_array, str_ts): + # GH#17991 checking for overflow-masking with NaT + tdinat = pd.to_timedelta(["24658 days 11:15:00", "NaT"]) + tdobj = tm.box_expected(tdinat, box_with_array) + + ts = Timestamp(str_ts) + ts_variants = [ + ts, + ts.to_pydatetime(), + ts.to_datetime64().astype("datetime64[ns]"), + ts.to_datetime64().astype("datetime64[D]"), + ] + + for variant in ts_variants: + res = tdobj + variant + if box_with_array is DataFrame: + assert res.iloc[1, 1] is NaT + else: + assert res[1] is NaT + + def test_tdi_add_overflow(self): + # See GH#14068 + # preliminary test scalar analogue of vectorized tests below + # TODO: Make raised error message more informative and test + with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"): + pd.to_timedelta(106580, "D") + Timestamp("2000") + with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"): + Timestamp("2000") + pd.to_timedelta(106580, "D") + + _NaT = NaT._value + 1 + msg = "Overflow in int64 addition" + with pytest.raises(OverflowError, match=msg): + pd.to_timedelta([106580], "D") + Timestamp("2000") + with pytest.raises(OverflowError, match=msg): + Timestamp("2000") + pd.to_timedelta([106580], "D") + with pytest.raises(OverflowError, match=msg): + pd.to_timedelta([_NaT]) - Timedelta("1 days") + with pytest.raises(OverflowError, match=msg): + pd.to_timedelta(["5 days", _NaT]) - Timedelta("1 days") + with pytest.raises(OverflowError, match=msg): + ( + pd.to_timedelta([_NaT, "5 days", "1 hours"]) + - pd.to_timedelta(["7 seconds", _NaT, "4 hours"]) + ) + + # These should not overflow! + exp = TimedeltaIndex([NaT]) + result = pd.to_timedelta([NaT]) - Timedelta("1 days") + tm.assert_index_equal(result, exp) + + exp = TimedeltaIndex(["4 days", NaT]) + result = pd.to_timedelta(["5 days", NaT]) - Timedelta("1 days") + tm.assert_index_equal(result, exp) + + exp = TimedeltaIndex([NaT, NaT, "5 hours"]) + result = pd.to_timedelta([NaT, "5 days", "1 hours"]) + pd.to_timedelta( + ["7 seconds", NaT, "4 hours"] + ) + tm.assert_index_equal(result, exp) + + +class TestTimedeltaArraylikeAddSubOps: + # Tests for timedelta64[ns] __add__, __sub__, __radd__, __rsub__ + + def test_sub_nat_retain_unit(self): + ser = pd.to_timedelta(Series(["00:00:01"])).astype("m8[s]") + + result = ser - NaT + expected = Series([NaT], dtype="m8[s]") + tm.assert_series_equal(result, expected) + + # TODO: moved from tests.indexes.timedeltas.test_arithmetic; needs + # parametrization+de-duplication + def test_timedelta_ops_with_missing_values(self): + # setup + s1 = pd.to_timedelta(Series(["00:00:01"])) + s2 = pd.to_timedelta(Series(["00:00:02"])) + + sn = pd.to_timedelta(Series([NaT], dtype="m8[ns]")) + + df1 = DataFrame(["00:00:01"]).apply(pd.to_timedelta) + df2 = DataFrame(["00:00:02"]).apply(pd.to_timedelta) + + dfn = DataFrame([NaT._value]).apply(pd.to_timedelta) + + scalar1 = pd.to_timedelta("00:00:01") + scalar2 = pd.to_timedelta("00:00:02") + timedelta_NaT = pd.to_timedelta("NaT") + + actual = scalar1 + scalar1 + assert actual == scalar2 + actual = scalar2 - scalar1 + assert actual == scalar1 + + actual = s1 + s1 + tm.assert_series_equal(actual, s2) + actual = s2 - s1 + tm.assert_series_equal(actual, s1) + + actual = s1 + scalar1 + tm.assert_series_equal(actual, s2) + actual = scalar1 + s1 + tm.assert_series_equal(actual, s2) + actual = s2 - scalar1 + tm.assert_series_equal(actual, s1) + actual = -scalar1 + s2 + tm.assert_series_equal(actual, s1) + + actual = s1 + timedelta_NaT + tm.assert_series_equal(actual, sn) + actual = timedelta_NaT + s1 + tm.assert_series_equal(actual, sn) + actual = s1 - timedelta_NaT + tm.assert_series_equal(actual, sn) + actual = -timedelta_NaT + s1 + tm.assert_series_equal(actual, sn) + + msg = "unsupported operand type" + with pytest.raises(TypeError, match=msg): + s1 + np.nan + with pytest.raises(TypeError, match=msg): + np.nan + s1 + with pytest.raises(TypeError, match=msg): + s1 - np.nan + with pytest.raises(TypeError, match=msg): + -np.nan + s1 + + actual = s1 + NaT + tm.assert_series_equal(actual, sn) + actual = s2 - NaT + tm.assert_series_equal(actual, sn) + + actual = s1 + df1 + tm.assert_frame_equal(actual, df2) + actual = s2 - df1 + tm.assert_frame_equal(actual, df1) + actual = df1 + s1 + tm.assert_frame_equal(actual, df2) + actual = df2 - s1 + tm.assert_frame_equal(actual, df1) + + actual = df1 + df1 + tm.assert_frame_equal(actual, df2) + actual = df2 - df1 + tm.assert_frame_equal(actual, df1) + + actual = df1 + scalar1 + tm.assert_frame_equal(actual, df2) + actual = df2 - scalar1 + tm.assert_frame_equal(actual, df1) + + actual = df1 + timedelta_NaT + tm.assert_frame_equal(actual, dfn) + actual = df1 - timedelta_NaT + tm.assert_frame_equal(actual, dfn) + + msg = "cannot subtract a datelike from|unsupported operand type" + with pytest.raises(TypeError, match=msg): + df1 + np.nan + with pytest.raises(TypeError, match=msg): + df1 - np.nan + + actual = df1 + NaT # NaT is datetime, not timedelta + tm.assert_frame_equal(actual, dfn) + actual = df1 - NaT + tm.assert_frame_equal(actual, dfn) + + # TODO: moved from tests.series.test_operators, needs splitting, cleanup, + # de-duplication, box-parametrization... + def test_operators_timedelta64(self): + # series ops + v1 = pd.date_range("2012-1-1", periods=3, freq="D") + v2 = pd.date_range("2012-1-2", periods=3, freq="D") + rs = Series(v2) - Series(v1) + xp = Series(1e9 * 3600 * 24, rs.index).astype("int64").astype("timedelta64[ns]") + tm.assert_series_equal(rs, xp) + assert rs.dtype == "timedelta64[ns]" + + df = DataFrame({"A": v1}) + td = Series([timedelta(days=i) for i in range(3)]) + assert td.dtype == "timedelta64[ns]" + + # series on the rhs + result = df["A"] - df["A"].shift() + assert result.dtype == "timedelta64[ns]" + + result = df["A"] + td + assert result.dtype == "M8[ns]" + + # scalar Timestamp on rhs + maxa = df["A"].max() + assert isinstance(maxa, Timestamp) + + resultb = df["A"] - df["A"].max() + assert resultb.dtype == "timedelta64[ns]" + + # timestamp on lhs + result = resultb + df["A"] + values = [Timestamp("20111230"), Timestamp("20120101"), Timestamp("20120103")] + expected = Series(values, dtype="M8[ns]", name="A") + tm.assert_series_equal(result, expected) + + # datetimes on rhs + result = df["A"] - datetime(2001, 1, 1) + expected = Series([timedelta(days=4017 + i) for i in range(3)], name="A") + tm.assert_series_equal(result, expected) + assert result.dtype == "m8[ns]" + + d = datetime(2001, 1, 1, 3, 4) + resulta = df["A"] - d + assert resulta.dtype == "m8[ns]" + + # roundtrip + resultb = resulta + d + tm.assert_series_equal(df["A"], resultb) + + # timedeltas on rhs + td = timedelta(days=1) + resulta = df["A"] + td + resultb = resulta - td + tm.assert_series_equal(resultb, df["A"]) + assert resultb.dtype == "M8[ns]" + + # roundtrip + td = timedelta(minutes=5, seconds=3) + resulta = df["A"] + td + resultb = resulta - td + tm.assert_series_equal(df["A"], resultb) + assert resultb.dtype == "M8[ns]" + + # inplace + value = rs[2] + np.timedelta64(timedelta(minutes=5, seconds=1)) + rs[2] += np.timedelta64(timedelta(minutes=5, seconds=1)) + assert rs[2] == value + + def test_timedelta64_ops_nat(self): + # GH 11349 + timedelta_series = Series([NaT, Timedelta("1s")]) + nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]") + single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]") + + # subtraction + tm.assert_series_equal(timedelta_series - NaT, nat_series_dtype_timedelta) + tm.assert_series_equal(-NaT + timedelta_series, nat_series_dtype_timedelta) + + tm.assert_series_equal( + timedelta_series - single_nat_dtype_timedelta, nat_series_dtype_timedelta + ) + tm.assert_series_equal( + -single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta + ) + + # addition + tm.assert_series_equal( + nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta + ) + tm.assert_series_equal( + NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta + ) + + tm.assert_series_equal( + nat_series_dtype_timedelta + single_nat_dtype_timedelta, + nat_series_dtype_timedelta, + ) + tm.assert_series_equal( + single_nat_dtype_timedelta + nat_series_dtype_timedelta, + nat_series_dtype_timedelta, + ) + + tm.assert_series_equal(timedelta_series + NaT, nat_series_dtype_timedelta) + tm.assert_series_equal(NaT + timedelta_series, nat_series_dtype_timedelta) + + tm.assert_series_equal( + timedelta_series + single_nat_dtype_timedelta, nat_series_dtype_timedelta + ) + tm.assert_series_equal( + single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta + ) + + tm.assert_series_equal( + nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta + ) + tm.assert_series_equal( + NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta + ) + + tm.assert_series_equal( + nat_series_dtype_timedelta + single_nat_dtype_timedelta, + nat_series_dtype_timedelta, + ) + tm.assert_series_equal( + single_nat_dtype_timedelta + nat_series_dtype_timedelta, + nat_series_dtype_timedelta, + ) + + # multiplication + tm.assert_series_equal( + nat_series_dtype_timedelta * 1.0, nat_series_dtype_timedelta + ) + tm.assert_series_equal( + 1.0 * nat_series_dtype_timedelta, nat_series_dtype_timedelta + ) + + tm.assert_series_equal(timedelta_series * 1, timedelta_series) + tm.assert_series_equal(1 * timedelta_series, timedelta_series) + + tm.assert_series_equal(timedelta_series * 1.5, Series([NaT, Timedelta("1.5s")])) + tm.assert_series_equal(1.5 * timedelta_series, Series([NaT, Timedelta("1.5s")])) + + tm.assert_series_equal(timedelta_series * np.nan, nat_series_dtype_timedelta) + tm.assert_series_equal(np.nan * timedelta_series, nat_series_dtype_timedelta) + + # division + tm.assert_series_equal(timedelta_series / 2, Series([NaT, Timedelta("0.5s")])) + tm.assert_series_equal(timedelta_series / 2.0, Series([NaT, Timedelta("0.5s")])) + tm.assert_series_equal(timedelta_series / np.nan, nat_series_dtype_timedelta) + + # ------------------------------------------------------------- + # Binary operations td64 arraylike and datetime-like + + @pytest.mark.parametrize("cls", [Timestamp, datetime, np.datetime64]) + def test_td64arr_add_sub_datetimelike_scalar( + self, cls, box_with_array, tz_naive_fixture + ): + # GH#11925, GH#29558, GH#23215 + tz = tz_naive_fixture + + dt_scalar = Timestamp("2012-01-01", tz=tz) + if cls is datetime: + ts = dt_scalar.to_pydatetime() + elif cls is np.datetime64: + if tz_naive_fixture is not None: + pytest.skip(f"{cls} doesn support {tz_naive_fixture}") + ts = dt_scalar.to_datetime64() + else: + ts = dt_scalar + + tdi = timedelta_range("1 day", periods=3) + expected = pd.date_range("2012-01-02", periods=3, tz=tz) + + tdarr = tm.box_expected(tdi, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + tm.assert_equal(ts + tdarr, expected) + tm.assert_equal(tdarr + ts, expected) + + expected2 = pd.date_range("2011-12-31", periods=3, freq="-1D", tz=tz) + expected2 = tm.box_expected(expected2, box_with_array) + + tm.assert_equal(ts - tdarr, expected2) + tm.assert_equal(ts + (-tdarr), expected2) + + msg = "cannot subtract a datelike" + with pytest.raises(TypeError, match=msg): + tdarr - ts + + def test_td64arr_add_datetime64_nat(self, box_with_array): + # GH#23215 + other = np.datetime64("NaT") + + tdi = timedelta_range("1 day", periods=3) + expected = DatetimeIndex(["NaT", "NaT", "NaT"], dtype="M8[ns]") + + tdser = tm.box_expected(tdi, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + tm.assert_equal(tdser + other, expected) + tm.assert_equal(other + tdser, expected) + + def test_td64arr_sub_dt64_array(self, box_with_array): + dti = pd.date_range("2016-01-01", periods=3) + tdi = TimedeltaIndex(["-1 Day"] * 3) + dtarr = dti.values + expected = DatetimeIndex(dtarr) - tdi + + tdi = tm.box_expected(tdi, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + msg = "cannot subtract a datelike from" + with pytest.raises(TypeError, match=msg): + tdi - dtarr + + # TimedeltaIndex.__rsub__ + result = dtarr - tdi + tm.assert_equal(result, expected) + + def test_td64arr_add_dt64_array(self, box_with_array): + dti = pd.date_range("2016-01-01", periods=3) + tdi = TimedeltaIndex(["-1 Day"] * 3) + dtarr = dti.values + expected = DatetimeIndex(dtarr) + tdi + + tdi = tm.box_expected(tdi, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = tdi + dtarr + tm.assert_equal(result, expected) + result = dtarr + tdi + tm.assert_equal(result, expected) + + # ------------------------------------------------------------------ + # Invalid __add__/__sub__ operations + + @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"]) + @pytest.mark.parametrize("tdi_freq", [None, "h"]) + def test_td64arr_sub_periodlike( + self, box_with_array, box_with_array2, tdi_freq, pi_freq + ): + # GH#20049 subtracting PeriodIndex should raise TypeError + tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq) + dti = Timestamp("2018-03-07 17:16:40") + tdi + pi = dti.to_period(pi_freq) + per = pi[0] + + tdi = tm.box_expected(tdi, box_with_array) + pi = tm.box_expected(pi, box_with_array2) + msg = "cannot subtract|unsupported operand type" + with pytest.raises(TypeError, match=msg): + tdi - pi + + # GH#13078 subtraction of Period scalar not supported + with pytest.raises(TypeError, match=msg): + tdi - per + + @pytest.mark.parametrize( + "other", + [ + # GH#12624 for str case + "a", + # GH#19123 + 1, + 1.5, + np.array(2), + ], + ) + def test_td64arr_addsub_numeric_scalar_invalid(self, box_with_array, other): + # vector-like others are tested in test_td64arr_add_sub_numeric_arr_invalid + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + tdarr = tm.box_expected(tdser, box_with_array) + + assert_invalid_addsub_type(tdarr, other) + + @pytest.mark.parametrize( + "vec", + [ + np.array([1, 2, 3]), + Index([1, 2, 3]), + Series([1, 2, 3]), + DataFrame([[1, 2, 3]]), + ], + ids=lambda x: type(x).__name__, + ) + def test_td64arr_addsub_numeric_arr_invalid( + self, box_with_array, vec, any_real_numpy_dtype + ): + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + tdarr = tm.box_expected(tdser, box_with_array) + + vector = vec.astype(any_real_numpy_dtype) + assert_invalid_addsub_type(tdarr, vector) + + def test_td64arr_add_sub_int(self, box_with_array, one): + # Variants of `one` for #19012, deprecated GH#22535 + rng = timedelta_range("1 days 09:00:00", freq="h", periods=10) + tdarr = tm.box_expected(rng, box_with_array) + + msg = "Addition/subtraction of integers" + assert_invalid_addsub_type(tdarr, one, msg) + + # TODO: get inplace ops into assert_invalid_addsub_type + with pytest.raises(TypeError, match=msg): + tdarr += one + with pytest.raises(TypeError, match=msg): + tdarr -= one + + def test_td64arr_add_sub_integer_array(self, box_with_array): + # GH#19959, deprecated GH#22535 + # GH#22696 for DataFrame case, check that we don't dispatch to numpy + # implementation, which treats int64 as m8[ns] + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + rng = timedelta_range("1 days 09:00:00", freq="h", periods=3) + tdarr = tm.box_expected(rng, box) + other = tm.box_expected([4, 3, 2], xbox) + + msg = "Addition/subtraction of integers and integer-arrays" + assert_invalid_addsub_type(tdarr, other, msg) + + def test_td64arr_addsub_integer_array_no_freq(self, box_with_array): + # GH#19959 + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + tdi = TimedeltaIndex(["1 Day", "NaT", "3 Hours"]) + tdarr = tm.box_expected(tdi, box) + other = tm.box_expected([14, -1, 16], xbox) + + msg = "Addition/subtraction of integers" + assert_invalid_addsub_type(tdarr, other, msg) + + # ------------------------------------------------------------------ + # Operations with timedelta-like others + + def test_td64arr_add_sub_td64_array(self, box_with_array): + box = box_with_array + dti = pd.date_range("2016-01-01", periods=3) + tdi = dti - dti.shift(1) + tdarr = tdi.values + + expected = 2 * tdi + tdi = tm.box_expected(tdi, box) + expected = tm.box_expected(expected, box) + + result = tdi + tdarr + tm.assert_equal(result, expected) + result = tdarr + tdi + tm.assert_equal(result, expected) + + expected_sub = 0 * tdi + result = tdi - tdarr + tm.assert_equal(result, expected_sub) + result = tdarr - tdi + tm.assert_equal(result, expected_sub) + + def test_td64arr_add_sub_tdi(self, box_with_array, names): + # GH#17250 make sure result dtype is correct + # GH#19043 make sure names are propagated correctly + box = box_with_array + exname = get_expected_name(box, names) + + tdi = TimedeltaIndex(["0 days", "1 day"], name=names[1]) + tdi = np.array(tdi) if box in [tm.to_array, pd.array] else tdi + ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[0]) + expected = Series([Timedelta(hours=3), Timedelta(days=1, hours=4)], name=exname) + + ser = tm.box_expected(ser, box) + expected = tm.box_expected(expected, box) + + result = tdi + ser + tm.assert_equal(result, expected) + assert_dtype(result, "timedelta64[ns]") + + result = ser + tdi + tm.assert_equal(result, expected) + assert_dtype(result, "timedelta64[ns]") + + expected = Series( + [Timedelta(hours=-3), Timedelta(days=1, hours=-4)], name=exname + ) + expected = tm.box_expected(expected, box) + + result = tdi - ser + tm.assert_equal(result, expected) + assert_dtype(result, "timedelta64[ns]") + + result = ser - tdi + tm.assert_equal(result, -expected) + assert_dtype(result, "timedelta64[ns]") + + @pytest.mark.parametrize("tdnat", [np.timedelta64("NaT"), NaT]) + def test_td64arr_add_sub_td64_nat(self, box_with_array, tdnat): + # GH#18808, GH#23320 special handling for timedelta64("NaT") + box = box_with_array + tdi = TimedeltaIndex([NaT, Timedelta("1s")]) + expected = TimedeltaIndex(["NaT"] * 2) + + obj = tm.box_expected(tdi, box) + expected = tm.box_expected(expected, box) + + result = obj + tdnat + tm.assert_equal(result, expected) + result = tdnat + obj + tm.assert_equal(result, expected) + result = obj - tdnat + tm.assert_equal(result, expected) + result = tdnat - obj + tm.assert_equal(result, expected) + + def test_td64arr_add_timedeltalike(self, two_hours, box_with_array): + # only test adding/sub offsets as + is now numeric + # GH#10699 for Tick cases + box = box_with_array + rng = timedelta_range("1 days", "10 days") + expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D") + rng = tm.box_expected(rng, box) + expected = tm.box_expected(expected, box) + + result = rng + two_hours + tm.assert_equal(result, expected) + + result = two_hours + rng + tm.assert_equal(result, expected) + + def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array): + # only test adding/sub offsets as - is now numeric + # GH#10699 for Tick cases + box = box_with_array + rng = timedelta_range("1 days", "10 days") + expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00") + + rng = tm.box_expected(rng, box) + expected = tm.box_expected(expected, box) + + result = rng - two_hours + tm.assert_equal(result, expected) + + result = two_hours - rng + tm.assert_equal(result, -expected) + + # ------------------------------------------------------------------ + # __add__/__sub__ with DateOffsets and arrays of DateOffsets + + def test_td64arr_add_sub_offset_index(self, names, box_with_array): + # GH#18849, GH#19744 + box = box_with_array + exname = get_expected_name(box, names) + + tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0]) + other = Index([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1]) + other = np.array(other) if box in [tm.to_array, pd.array] else other + + expected = TimedeltaIndex( + [tdi[n] + other[n] for n in range(len(tdi))], freq="infer", name=exname + ) + expected_sub = TimedeltaIndex( + [tdi[n] - other[n] for n in range(len(tdi))], freq="infer", name=exname + ) + + tdi = tm.box_expected(tdi, box) + expected = tm.box_expected(expected, box).astype(object, copy=False) + expected_sub = tm.box_expected(expected_sub, box).astype(object, copy=False) + + with tm.assert_produces_warning(PerformanceWarning): + res = tdi + other + tm.assert_equal(res, expected) + + with tm.assert_produces_warning(PerformanceWarning): + res2 = other + tdi + tm.assert_equal(res2, expected) + + with tm.assert_produces_warning(PerformanceWarning): + res_sub = tdi - other + tm.assert_equal(res_sub, expected_sub) + + def test_td64arr_add_sub_offset_array(self, box_with_array): + # GH#18849, GH#18824 + box = box_with_array + tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"]) + other = np.array([offsets.Hour(n=1), offsets.Minute(n=-2)]) + + expected = TimedeltaIndex( + [tdi[n] + other[n] for n in range(len(tdi))], freq="infer" + ) + expected_sub = TimedeltaIndex( + [tdi[n] - other[n] for n in range(len(tdi))], freq="infer" + ) + + tdi = tm.box_expected(tdi, box) + expected = tm.box_expected(expected, box).astype(object) + + with tm.assert_produces_warning(PerformanceWarning): + res = tdi + other + tm.assert_equal(res, expected) + + with tm.assert_produces_warning(PerformanceWarning): + res2 = other + tdi + tm.assert_equal(res2, expected) + + expected_sub = tm.box_expected(expected_sub, box_with_array).astype(object) + with tm.assert_produces_warning(PerformanceWarning): + res_sub = tdi - other + tm.assert_equal(res_sub, expected_sub) + + def test_td64arr_with_offset_series(self, names, box_with_array): + # GH#18849 + box = box_with_array + box2 = Series if box in [Index, tm.to_array, pd.array] else box + exname = get_expected_name(box, names) + + tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0]) + other = Series([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1]) + + expected_add = Series( + [tdi[n] + other[n] for n in range(len(tdi))], name=exname, dtype=object + ) + obj = tm.box_expected(tdi, box) + expected_add = tm.box_expected(expected_add, box2).astype(object) + + with tm.assert_produces_warning(PerformanceWarning): + res = obj + other + tm.assert_equal(res, expected_add) + + with tm.assert_produces_warning(PerformanceWarning): + res2 = other + obj + tm.assert_equal(res2, expected_add) + + expected_sub = Series( + [tdi[n] - other[n] for n in range(len(tdi))], name=exname, dtype=object + ) + expected_sub = tm.box_expected(expected_sub, box2).astype(object) + + with tm.assert_produces_warning(PerformanceWarning): + res3 = obj - other + tm.assert_equal(res3, expected_sub) + + @pytest.mark.parametrize("obox", [np.array, Index, Series]) + def test_td64arr_addsub_anchored_offset_arraylike(self, obox, box_with_array): + # GH#18824 + tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"]) + tdi = tm.box_expected(tdi, box_with_array) + + anchored = obox([offsets.MonthEnd(), offsets.Day(n=2)]) + + # addition/subtraction ops with anchored offsets should issue + # a PerformanceWarning and _then_ raise a TypeError. + msg = "has incorrect type|cannot add the type MonthEnd" + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(PerformanceWarning): + tdi + anchored + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(PerformanceWarning): + anchored + tdi + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(PerformanceWarning): + tdi - anchored + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(PerformanceWarning): + anchored - tdi + + # ------------------------------------------------------------------ + # Unsorted + + def test_td64arr_add_sub_object_array(self, box_with_array): + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + tdi = timedelta_range("1 day", periods=3, freq="D") + tdarr = tm.box_expected(tdi, box) + + other = np.array([Timedelta(days=1), offsets.Day(2), Timestamp("2000-01-04")]) + + with tm.assert_produces_warning(PerformanceWarning): + result = tdarr + other + + expected = Index( + [Timedelta(days=2), Timedelta(days=4), Timestamp("2000-01-07")] + ) + expected = tm.box_expected(expected, xbox).astype(object) + tm.assert_equal(result, expected) + + msg = "unsupported operand type|cannot subtract a datelike" + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(PerformanceWarning): + tdarr - other + + with tm.assert_produces_warning(PerformanceWarning): + result = other - tdarr + + expected = Index([Timedelta(0), Timedelta(0), Timestamp("2000-01-01")]) + expected = tm.box_expected(expected, xbox).astype(object) + tm.assert_equal(result, expected) + + +class TestTimedeltaArraylikeMulDivOps: + # Tests for timedelta64[ns] + # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__ + + # ------------------------------------------------------------------ + # Multiplication + # organized with scalar others first, then array-like + + def test_td64arr_mul_int(self, box_with_array): + idx = TimedeltaIndex(np.arange(5, dtype="int64")) + idx = tm.box_expected(idx, box_with_array) + + result = idx * 1 + tm.assert_equal(result, idx) + + result = 1 * idx + tm.assert_equal(result, idx) + + def test_td64arr_mul_tdlike_scalar_raises(self, two_hours, box_with_array): + rng = timedelta_range("1 days", "10 days", name="foo") + rng = tm.box_expected(rng, box_with_array) + msg = "|".join( + [ + "argument must be an integer", + "cannot use operands with types dtype", + "Cannot multiply with", + ] + ) + with pytest.raises(TypeError, match=msg): + rng * two_hours + + def test_tdi_mul_int_array_zerodim(self, box_with_array): + rng5 = np.arange(5, dtype="int64") + idx = TimedeltaIndex(rng5) + expected = TimedeltaIndex(rng5 * 5) + + idx = tm.box_expected(idx, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = idx * np.array(5, dtype="int64") + tm.assert_equal(result, expected) + + def test_tdi_mul_int_array(self, box_with_array): + rng5 = np.arange(5, dtype="int64") + idx = TimedeltaIndex(rng5) + expected = TimedeltaIndex(rng5**2) + + idx = tm.box_expected(idx, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = idx * rng5 + tm.assert_equal(result, expected) + + def test_tdi_mul_int_series(self, box_with_array): + box = box_with_array + xbox = Series if box in [Index, tm.to_array, pd.array] else box + + idx = TimedeltaIndex(np.arange(5, dtype="int64")) + expected = TimedeltaIndex(np.arange(5, dtype="int64") ** 2) + + idx = tm.box_expected(idx, box) + expected = tm.box_expected(expected, xbox) + + result = idx * Series(np.arange(5, dtype="int64")) + tm.assert_equal(result, expected) + + def test_tdi_mul_float_series(self, box_with_array): + box = box_with_array + xbox = Series if box in [Index, tm.to_array, pd.array] else box + + idx = TimedeltaIndex(np.arange(5, dtype="int64")) + idx = tm.box_expected(idx, box) + + rng5f = np.arange(5, dtype="float64") + expected = TimedeltaIndex(rng5f * (rng5f + 1.0)) + expected = tm.box_expected(expected, xbox) + + result = idx * Series(rng5f + 1.0) + tm.assert_equal(result, expected) + + # TODO: Put Series/DataFrame in others? + @pytest.mark.parametrize( + "other", + [ + np.arange(1, 11), + Index(np.arange(1, 11), np.int64), + Index(range(1, 11), np.uint64), + Index(range(1, 11), np.float64), + pd.RangeIndex(1, 11), + ], + ids=lambda x: type(x).__name__, + ) + def test_tdi_rmul_arraylike(self, other, box_with_array): + box = box_with_array + + tdi = TimedeltaIndex(["1 Day"] * 10) + expected = timedelta_range("1 days", "10 days")._with_freq(None) + + tdi = tm.box_expected(tdi, box) + xbox = get_upcast_box(tdi, other) + + expected = tm.box_expected(expected, xbox) + + result = other * tdi + tm.assert_equal(result, expected) + commute = tdi * other + tm.assert_equal(commute, expected) + + # ------------------------------------------------------------------ + # __div__, __rdiv__ + + def test_td64arr_div_nat_invalid(self, box_with_array): + # don't allow division by NaT (maybe could in the future) + rng = timedelta_range("1 days", "10 days", name="foo") + rng = tm.box_expected(rng, box_with_array) + + with pytest.raises(TypeError, match="unsupported operand type"): + rng / NaT + with pytest.raises(TypeError, match="Cannot divide NaTType by"): + NaT / rng + + dt64nat = np.datetime64("NaT", "ns") + msg = "|".join( + [ + # 'divide' on npdev as of 2021-12-18 + "ufunc '(true_divide|divide)' cannot use operands", + "cannot perform __r?truediv__", + "Cannot divide datetime64 by TimedeltaArray", + ] + ) + with pytest.raises(TypeError, match=msg): + rng / dt64nat + with pytest.raises(TypeError, match=msg): + dt64nat / rng + + def test_td64arr_div_td64nat(self, box_with_array): + # GH#23829 + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + rng = timedelta_range("1 days", "10 days") + rng = tm.box_expected(rng, box) + + other = np.timedelta64("NaT") + + expected = np.array([np.nan] * 10) + expected = tm.box_expected(expected, xbox) + + result = rng / other + tm.assert_equal(result, expected) + + result = other / rng + tm.assert_equal(result, expected) + + def test_td64arr_div_int(self, box_with_array): + idx = TimedeltaIndex(np.arange(5, dtype="int64")) + idx = tm.box_expected(idx, box_with_array) + + result = idx / 1 + tm.assert_equal(result, idx) + + with pytest.raises(TypeError, match="Cannot divide"): + # GH#23829 + 1 / idx + + def test_td64arr_div_tdlike_scalar(self, two_hours, box_with_array): + # GH#20088, GH#22163 ensure DataFrame returns correct dtype + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + rng = timedelta_range("1 days", "10 days", name="foo") + expected = Index((np.arange(10) + 1) * 12, dtype=np.float64, name="foo") + + rng = tm.box_expected(rng, box) + expected = tm.box_expected(expected, xbox) + + result = rng / two_hours + tm.assert_equal(result, expected) + + result = two_hours / rng + expected = 1 / expected + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("m", [1, 3, 10]) + @pytest.mark.parametrize("unit", ["D", "h", "m", "s", "ms", "us", "ns"]) + def test_td64arr_div_td64_scalar(self, m, unit, box_with_array): + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + ser = Series([Timedelta(days=59)] * 3) + ser[2] = np.nan + flat = ser + ser = tm.box_expected(ser, box) + + # op + expected = Series([x / np.timedelta64(m, unit) for x in flat]) + expected = tm.box_expected(expected, xbox) + result = ser / np.timedelta64(m, unit) + tm.assert_equal(result, expected) + + # reverse op + expected = Series([Timedelta(np.timedelta64(m, unit)) / x for x in flat]) + expected = tm.box_expected(expected, xbox) + result = np.timedelta64(m, unit) / ser + tm.assert_equal(result, expected) + + def test_td64arr_div_tdlike_scalar_with_nat(self, two_hours, box_with_array): + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + rng = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") + expected = Index([12, np.nan, 24], dtype=np.float64, name="foo") + + rng = tm.box_expected(rng, box) + expected = tm.box_expected(expected, xbox) + + result = rng / two_hours + tm.assert_equal(result, expected) + + result = two_hours / rng + expected = 1 / expected + tm.assert_equal(result, expected) + + def test_td64arr_div_td64_ndarray(self, box_with_array): + # GH#22631 + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + rng = TimedeltaIndex(["1 days", NaT, "2 days"]) + expected = Index([12, np.nan, 24], dtype=np.float64) + + rng = tm.box_expected(rng, box) + expected = tm.box_expected(expected, xbox) + + other = np.array([2, 4, 2], dtype="m8[h]") + result = rng / other + tm.assert_equal(result, expected) + + result = rng / tm.box_expected(other, box) + tm.assert_equal(result, expected) + + result = rng / other.astype(object) + tm.assert_equal(result, expected.astype(object)) + + result = rng / list(other) + tm.assert_equal(result, expected) + + # reversed op + expected = 1 / expected + result = other / rng + tm.assert_equal(result, expected) + + result = tm.box_expected(other, box) / rng + tm.assert_equal(result, expected) + + result = other.astype(object) / rng + tm.assert_equal(result, expected) + + result = list(other) / rng + tm.assert_equal(result, expected) + + def test_tdarr_div_length_mismatch(self, box_with_array): + rng = TimedeltaIndex(["1 days", NaT, "2 days"]) + mismatched = [1, 2, 3, 4] + + rng = tm.box_expected(rng, box_with_array) + msg = "Cannot divide vectors|Unable to coerce to Series" + for obj in [mismatched, mismatched[:2]]: + # one shorter, one longer + for other in [obj, np.array(obj), Index(obj)]: + with pytest.raises(ValueError, match=msg): + rng / other + with pytest.raises(ValueError, match=msg): + other / rng + + def test_td64_div_object_mixed_result(self, box_with_array): + # Case where we having a NaT in the result inseat of timedelta64("NaT") + # is misleading + orig = timedelta_range("1 Day", periods=3).insert(1, NaT) + tdi = tm.box_expected(orig, box_with_array, transpose=False) + + other = np.array([orig[0], 1.5, 2.0, orig[2]], dtype=object) + other = tm.box_expected(other, box_with_array, transpose=False) + + res = tdi / other + + expected = Index([1.0, np.timedelta64("NaT", "ns"), orig[0], 1.5], dtype=object) + expected = tm.box_expected(expected, box_with_array, transpose=False) + if isinstance(expected, NumpyExtensionArray): + expected = expected.to_numpy() + tm.assert_equal(res, expected) + if box_with_array is DataFrame: + # We have a np.timedelta64(NaT), not pd.NaT + assert isinstance(res.iloc[1, 0], np.timedelta64) + + res = tdi // other + + expected = Index([1, np.timedelta64("NaT", "ns"), orig[0], 1], dtype=object) + expected = tm.box_expected(expected, box_with_array, transpose=False) + if isinstance(expected, NumpyExtensionArray): + expected = expected.to_numpy() + tm.assert_equal(res, expected) + if box_with_array is DataFrame: + # We have a np.timedelta64(NaT), not pd.NaT + assert isinstance(res.iloc[1, 0], np.timedelta64) + + # ------------------------------------------------------------------ + # __floordiv__, __rfloordiv__ + + def test_td64arr_floordiv_td64arr_with_nat( + self, box_with_array, using_array_manager + ): + # GH#35529 + box = box_with_array + xbox = np.ndarray if box is pd.array else box + + left = Series([1000, 222330, 30], dtype="timedelta64[ns]") + right = Series([1000, 222330, None], dtype="timedelta64[ns]") + + left = tm.box_expected(left, box) + right = tm.box_expected(right, box) + + expected = np.array([1.0, 1.0, np.nan], dtype=np.float64) + expected = tm.box_expected(expected, xbox) + if box is DataFrame and using_array_manager: + # INFO(ArrayManager) floordiv returns integer, and ArrayManager + # performs ops column-wise and thus preserves int64 dtype for + # columns without missing values + expected[[0, 1]] = expected[[0, 1]].astype("int64") + + with tm.maybe_produces_warning( + RuntimeWarning, box is pd.array, check_stacklevel=False + ): + result = left // right + + tm.assert_equal(result, expected) + + # case that goes through __rfloordiv__ with arraylike + with tm.maybe_produces_warning( + RuntimeWarning, box is pd.array, check_stacklevel=False + ): + result = np.asarray(left) // right + tm.assert_equal(result, expected) + + @pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning") + def test_td64arr_floordiv_tdscalar(self, box_with_array, scalar_td): + # GH#18831, GH#19125 + box = box_with_array + xbox = np.ndarray if box is pd.array else box + td = Timedelta("5m3s") # i.e. (scalar_td - 1sec) / 2 + + td1 = Series([td, td, NaT], dtype="m8[ns]") + td1 = tm.box_expected(td1, box, transpose=False) + + expected = Series([0, 0, np.nan]) + expected = tm.box_expected(expected, xbox, transpose=False) + + result = td1 // scalar_td + tm.assert_equal(result, expected) + + # Reversed op + expected = Series([2, 2, np.nan]) + expected = tm.box_expected(expected, xbox, transpose=False) + + result = scalar_td // td1 + tm.assert_equal(result, expected) + + # same thing buts let's be explicit about calling __rfloordiv__ + result = td1.__rfloordiv__(scalar_td) + tm.assert_equal(result, expected) + + def test_td64arr_floordiv_int(self, box_with_array): + idx = TimedeltaIndex(np.arange(5, dtype="int64")) + idx = tm.box_expected(idx, box_with_array) + result = idx // 1 + tm.assert_equal(result, idx) + + pattern = "floor_divide cannot use operands|Cannot divide int by Timedelta*" + with pytest.raises(TypeError, match=pattern): + 1 // idx + + # ------------------------------------------------------------------ + # mod, divmod + # TODO: operations with timedelta-like arrays, numeric arrays, + # reversed ops + + def test_td64arr_mod_tdscalar(self, box_with_array, three_days): + tdi = timedelta_range("1 Day", "9 days") + tdarr = tm.box_expected(tdi, box_with_array) + + expected = TimedeltaIndex(["1 Day", "2 Days", "0 Days"] * 3) + expected = tm.box_expected(expected, box_with_array) + + result = tdarr % three_days + tm.assert_equal(result, expected) + + warn = None + if box_with_array is DataFrame and isinstance(three_days, pd.DateOffset): + warn = PerformanceWarning + # TODO: making expected be object here a result of DataFrame.__divmod__ + # being defined in a naive way that does not dispatch to the underlying + # array's __divmod__ + expected = expected.astype(object) + + with tm.assert_produces_warning(warn): + result = divmod(tdarr, three_days) + + tm.assert_equal(result[1], expected) + tm.assert_equal(result[0], tdarr // three_days) + + def test_td64arr_mod_int(self, box_with_array): + tdi = timedelta_range("1 ns", "10 ns", periods=10) + tdarr = tm.box_expected(tdi, box_with_array) + + expected = TimedeltaIndex(["1 ns", "0 ns"] * 5) + expected = tm.box_expected(expected, box_with_array) + + result = tdarr % 2 + tm.assert_equal(result, expected) + + msg = "Cannot divide int by" + with pytest.raises(TypeError, match=msg): + 2 % tdarr + + result = divmod(tdarr, 2) + tm.assert_equal(result[1], expected) + tm.assert_equal(result[0], tdarr // 2) + + def test_td64arr_rmod_tdscalar(self, box_with_array, three_days): + tdi = timedelta_range("1 Day", "9 days") + tdarr = tm.box_expected(tdi, box_with_array) + + expected = ["0 Days", "1 Day", "0 Days"] + ["3 Days"] * 6 + expected = TimedeltaIndex(expected) + expected = tm.box_expected(expected, box_with_array) + + result = three_days % tdarr + tm.assert_equal(result, expected) + + result = divmod(three_days, tdarr) + tm.assert_equal(result[1], expected) + tm.assert_equal(result[0], three_days // tdarr) + + # ------------------------------------------------------------------ + # Operations with invalid others + + def test_td64arr_mul_tdscalar_invalid(self, box_with_array, scalar_td): + td1 = Series([timedelta(minutes=5, seconds=3)] * 3) + td1.iloc[2] = np.nan + + td1 = tm.box_expected(td1, box_with_array) + + # check that we are getting a TypeError + # with 'operate' (from core/ops.py) for the ops that are not + # defined + pattern = "operate|unsupported|cannot|not supported" + with pytest.raises(TypeError, match=pattern): + td1 * scalar_td + with pytest.raises(TypeError, match=pattern): + scalar_td * td1 + + def test_td64arr_mul_too_short_raises(self, box_with_array): + idx = TimedeltaIndex(np.arange(5, dtype="int64")) + idx = tm.box_expected(idx, box_with_array) + msg = "|".join( + [ + "cannot use operands with types dtype", + "Cannot multiply with unequal lengths", + "Unable to coerce to Series", + ] + ) + with pytest.raises(TypeError, match=msg): + # length check before dtype check + idx * idx[:3] + with pytest.raises(ValueError, match=msg): + idx * np.array([1, 2]) + + def test_td64arr_mul_td64arr_raises(self, box_with_array): + idx = TimedeltaIndex(np.arange(5, dtype="int64")) + idx = tm.box_expected(idx, box_with_array) + msg = "cannot use operands with types dtype" + with pytest.raises(TypeError, match=msg): + idx * idx + + # ------------------------------------------------------------------ + # Operations with numeric others + + def test_td64arr_mul_numeric_scalar(self, box_with_array, one): + # GH#4521 + # divide/multiply by integers + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + expected = Series(["-59 Days", "-59 Days", "NaT"], dtype="timedelta64[ns]") + + tdser = tm.box_expected(tdser, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = tdser * (-one) + tm.assert_equal(result, expected) + result = (-one) * tdser + tm.assert_equal(result, expected) + + expected = Series(["118 Days", "118 Days", "NaT"], dtype="timedelta64[ns]") + expected = tm.box_expected(expected, box_with_array) + + result = tdser * (2 * one) + tm.assert_equal(result, expected) + result = (2 * one) * tdser + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)]) + def test_td64arr_div_numeric_scalar(self, box_with_array, two): + # GH#4521 + # divide/multiply by integers + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]") + + tdser = tm.box_expected(tdser, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = tdser / two + tm.assert_equal(result, expected) + + with pytest.raises(TypeError, match="Cannot divide"): + two / tdser + + @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)]) + def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two): + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]") + + tdser = tm.box_expected(tdser, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = tdser // two + tm.assert_equal(result, expected) + + with pytest.raises(TypeError, match="Cannot divide"): + two // tdser + + @pytest.mark.parametrize( + "vector", + [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])], + ids=lambda x: type(x).__name__, + ) + def test_td64arr_rmul_numeric_array( + self, + box_with_array, + vector, + any_real_numpy_dtype, + ): + # GH#4521 + # divide/multiply by integers + + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + vector = vector.astype(any_real_numpy_dtype) + + expected = Series(["1180 Days", "1770 Days", "NaT"], dtype="timedelta64[ns]") + + tdser = tm.box_expected(tdser, box_with_array) + xbox = get_upcast_box(tdser, vector) + + expected = tm.box_expected(expected, xbox) + + result = tdser * vector + tm.assert_equal(result, expected) + + result = vector * tdser + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "vector", + [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])], + ids=lambda x: type(x).__name__, + ) + def test_td64arr_div_numeric_array( + self, box_with_array, vector, any_real_numpy_dtype + ): + # GH#4521 + # divide/multiply by integers + + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + vector = vector.astype(any_real_numpy_dtype) + + expected = Series(["2.95D", "1D 23h 12m", "NaT"], dtype="timedelta64[ns]") + + tdser = tm.box_expected(tdser, box_with_array) + xbox = get_upcast_box(tdser, vector) + expected = tm.box_expected(expected, xbox) + + result = tdser / vector + tm.assert_equal(result, expected) + + pattern = "|".join( + [ + "true_divide'? cannot use operands", + "cannot perform __div__", + "cannot perform __truediv__", + "unsupported operand", + "Cannot divide", + "ufunc 'divide' cannot use operands with types", + ] + ) + with pytest.raises(TypeError, match=pattern): + vector / tdser + + result = tdser / vector.astype(object) + if box_with_array is DataFrame: + expected = [tdser.iloc[0, n] / vector[n] for n in range(len(vector))] + expected = tm.box_expected(expected, xbox).astype(object) + # We specifically expect timedelta64("NaT") here, not pd.NA + msg = "The 'downcast' keyword in fillna" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected[2] = expected[2].fillna( + np.timedelta64("NaT", "ns"), downcast=False + ) + else: + expected = [tdser[n] / vector[n] for n in range(len(tdser))] + expected = [ + x if x is not NaT else np.timedelta64("NaT", "ns") for x in expected + ] + if xbox is tm.to_array: + expected = tm.to_array(expected).astype(object) + else: + expected = xbox(expected, dtype=object) + + tm.assert_equal(result, expected) + + with pytest.raises(TypeError, match=pattern): + vector.astype(object) / tdser + + def test_td64arr_mul_int_series(self, box_with_array, names): + # GH#19042 test for correct name attachment + box = box_with_array + exname = get_expected_name(box, names) + + tdi = TimedeltaIndex( + ["0days", "1day", "2days", "3days", "4days"], name=names[0] + ) + # TODO: Should we be parametrizing over types for `ser` too? + ser = Series([0, 1, 2, 3, 4], dtype=np.int64, name=names[1]) + + expected = Series( + ["0days", "1day", "4days", "9days", "16days"], + dtype="timedelta64[ns]", + name=exname, + ) + + tdi = tm.box_expected(tdi, box) + xbox = get_upcast_box(tdi, ser) + + expected = tm.box_expected(expected, xbox) + + result = ser * tdi + tm.assert_equal(result, expected) + + result = tdi * ser + tm.assert_equal(result, expected) + + # TODO: Should we be parametrizing over types for `ser` too? + def test_float_series_rdiv_td64arr(self, box_with_array, names): + # GH#19042 test for correct name attachment + box = box_with_array + tdi = TimedeltaIndex( + ["0days", "1day", "2days", "3days", "4days"], name=names[0] + ) + ser = Series([1.5, 3, 4.5, 6, 7.5], dtype=np.float64, name=names[1]) + + xname = names[2] if box not in [tm.to_array, pd.array] else names[1] + expected = Series( + [tdi[n] / ser[n] for n in range(len(ser))], + dtype="timedelta64[ns]", + name=xname, + ) + + tdi = tm.box_expected(tdi, box) + xbox = get_upcast_box(tdi, ser) + expected = tm.box_expected(expected, xbox) + + result = ser.__rtruediv__(tdi) + if box is DataFrame: + assert result is NotImplemented + else: + tm.assert_equal(result, expected) + + def test_td64arr_all_nat_div_object_dtype_numeric(self, box_with_array): + # GH#39750 make sure we infer the result as td64 + tdi = TimedeltaIndex([NaT, NaT]) + + left = tm.box_expected(tdi, box_with_array) + right = np.array([2, 2.0], dtype=object) + + tdnat = np.timedelta64("NaT", "ns") + expected = Index([tdnat] * 2, dtype=object) + if box_with_array is not Index: + expected = tm.box_expected(expected, box_with_array).astype(object) + if box_with_array in [Series, DataFrame]: + msg = "The 'downcast' keyword in fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = expected.fillna(tdnat, downcast=False) # GH#18463 + + result = left / right + tm.assert_equal(result, expected) + + result = left // right + tm.assert_equal(result, expected) + + +class TestTimedelta64ArrayLikeArithmetic: + # Arithmetic tests for timedelta64[ns] vectors fully parametrized over + # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all arithmetic + # tests will eventually end up here. + + def test_td64arr_pow_invalid(self, scalar_td, box_with_array): + td1 = Series([timedelta(minutes=5, seconds=3)] * 3) + td1.iloc[2] = np.nan + + td1 = tm.box_expected(td1, box_with_array) + + # check that we are getting a TypeError + # with 'operate' (from core/ops.py) for the ops that are not + # defined + pattern = "operate|unsupported|cannot|not supported" + with pytest.raises(TypeError, match=pattern): + scalar_td**td1 + + with pytest.raises(TypeError, match=pattern): + td1**scalar_td + + +def test_add_timestamp_to_timedelta(): + # GH: 35897 + timestamp = Timestamp("2021-01-01") + result = timestamp + timedelta_range("0s", "1s", periods=31) + expected = DatetimeIndex( + [ + timestamp + + ( + pd.to_timedelta("0.033333333s") * i + + pd.to_timedelta("0.000000001s") * divmod(i, 3)[0] + ) + for i in range(31) + ] + ) + tm.assert_index_equal(result, expected) diff --git a/shared/package-files/38/388225505859c0bd9cb71ddfc4835b6361c30c099243b8b66405205fb1318e0c/GMT+8 b/shared/package-files/38/388225505859c0bd9cb71ddfc4835b6361c30c099243b8b66405205fb1318e0c/GMT+8 new file mode 100644 index 0000000000000000000000000000000000000000..9bdc2283c07d8dae0bb0147c7a7c648ac6a30405 Binary files /dev/null and b/shared/package-files/38/388225505859c0bd9cb71ddfc4835b6361c30c099243b8b66405205fb1318e0c/GMT+8 differ diff --git a/shared/package-files/38/38897ecc1b892641521f32fa64525f075109d6cfa3d5a74bb44c8569a910c72f/__init__.py b/shared/package-files/38/38897ecc1b892641521f32fa64525f075109d6cfa3d5a74bb44c8569a910c72f/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8863fe489f3b62740757c3801ee55d7e1e406703 --- /dev/null +++ b/shared/package-files/38/38897ecc1b892641521f32fa64525f075109d6cfa3d5a74bb44c8569a910c72f/__init__.py @@ -0,0 +1,166 @@ +"""Utilities to load popular datasets and artificial data generators.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import textwrap + +from ._base import ( + clear_data_home, + fetch_file, + get_data_home, + load_breast_cancer, + load_diabetes, + load_digits, + load_files, + load_iris, + load_linnerud, + load_sample_image, + load_sample_images, + load_wine, +) +from ._california_housing import fetch_california_housing +from ._covtype import fetch_covtype +from ._kddcup99 import fetch_kddcup99 +from ._lfw import fetch_lfw_pairs, fetch_lfw_people +from ._olivetti_faces import fetch_olivetti_faces +from ._openml import fetch_openml +from ._rcv1 import fetch_rcv1 +from ._samples_generator import ( + make_biclusters, + make_blobs, + make_checkerboard, + make_circles, + make_classification, + make_friedman1, + make_friedman2, + make_friedman3, + make_gaussian_quantiles, + make_hastie_10_2, + make_low_rank_matrix, + make_moons, + make_multilabel_classification, + make_regression, + make_s_curve, + make_sparse_coded_signal, + make_sparse_spd_matrix, + make_sparse_uncorrelated, + make_spd_matrix, + make_swiss_roll, +) +from ._species_distributions import fetch_species_distributions +from ._svmlight_format_io import ( + dump_svmlight_file, + load_svmlight_file, + load_svmlight_files, +) +from ._twenty_newsgroups import fetch_20newsgroups, fetch_20newsgroups_vectorized + +__all__ = [ + "clear_data_home", + "dump_svmlight_file", + "fetch_20newsgroups", + "fetch_20newsgroups_vectorized", + "fetch_california_housing", + "fetch_covtype", + "fetch_file", + "fetch_kddcup99", + "fetch_lfw_pairs", + "fetch_lfw_people", + "fetch_olivetti_faces", + "fetch_openml", + "fetch_rcv1", + "fetch_species_distributions", + "get_data_home", + "load_breast_cancer", + "load_diabetes", + "load_digits", + "load_files", + "load_iris", + "load_linnerud", + "load_sample_image", + "load_sample_images", + "load_svmlight_file", + "load_svmlight_files", + "load_wine", + "make_biclusters", + "make_blobs", + "make_checkerboard", + "make_circles", + "make_classification", + "make_friedman1", + "make_friedman2", + "make_friedman3", + "make_gaussian_quantiles", + "make_hastie_10_2", + "make_low_rank_matrix", + "make_moons", + "make_multilabel_classification", + "make_regression", + "make_s_curve", + "make_sparse_coded_signal", + "make_sparse_spd_matrix", + "make_sparse_uncorrelated", + "make_spd_matrix", + "make_swiss_roll", +] + + +def __getattr__(name): + if name == "load_boston": + msg = textwrap.dedent( + """ + `load_boston` has been removed from scikit-learn since version 1.2. + + The Boston housing prices dataset has an ethical problem: as + investigated in [1], the authors of this dataset engineered a + non-invertible variable "B" assuming that racial self-segregation had a + positive impact on house prices [2]. Furthermore the goal of the + research that led to the creation of this dataset was to study the + impact of air quality but it did not give adequate demonstration of the + validity of this assumption. + + The scikit-learn maintainers therefore strongly discourage the use of + this dataset unless the purpose of the code is to study and educate + about ethical issues in data science and machine learning. + + In this special case, you can fetch the dataset from the original + source:: + + import pandas as pd + import numpy as np + + data_url = "http://lib.stat.cmu.edu/datasets/boston" + raw_df = pd.read_csv(data_url, sep="\\s+", skiprows=22, header=None) + data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]]) + target = raw_df.values[1::2, 2] + + Alternative datasets include the California housing dataset and the + Ames housing dataset. You can load the datasets as follows:: + + from sklearn.datasets import fetch_california_housing + housing = fetch_california_housing() + + for the California housing dataset and:: + + from sklearn.datasets import fetch_openml + housing = fetch_openml(name="house_prices", as_frame=True) + + for the Ames housing dataset. + + [1] M Carlisle. + "Racist data destruction?" + + + [2] Harrison Jr, David, and Daniel L. Rubinfeld. + "Hedonic housing prices and the demand for clean air." + Journal of environmental economics and management 5.1 (1978): 81-102. + + """ + ) + raise ImportError(msg) + try: + return globals()[name] + except KeyError: + # This is turned into the appropriate ImportError + raise AttributeError diff --git a/shared/package-files/38/388a8ef6da9a758f243381f08457f543ad9f508a7bbfc283ad3468f3258ccfb6/uninstall.py b/shared/package-files/38/388a8ef6da9a758f243381f08457f543ad9f508a7bbfc283ad3468f3258ccfb6/uninstall.py new file mode 100644 index 0000000000000000000000000000000000000000..f198fc313ff57929d95d36216e3e6ecec3877673 --- /dev/null +++ b/shared/package-files/38/388a8ef6da9a758f243381f08457f543ad9f508a7bbfc283ad3468f3258ccfb6/uninstall.py @@ -0,0 +1,113 @@ +import logging +from optparse import Values +from typing import List + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.req_command import SessionCommandMixin, warn_if_run_as_root +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import InstallationError +from pip._internal.req import parse_requirements +from pip._internal.req.constructors import ( + install_req_from_line, + install_req_from_parsed_requirement, +) +from pip._internal.utils.misc import ( + check_externally_managed, + protect_pip_from_modification_on_windows, +) + +logger = logging.getLogger(__name__) + + +class UninstallCommand(Command, SessionCommandMixin): + """ + Uninstall packages. + + pip is able to uninstall most installed packages. Known exceptions are: + + - Pure distutils packages installed with ``python setup.py install``, which + leave behind no metadata to determine what files were installed. + - Script wrappers installed by ``python setup.py develop``. + """ + + usage = """ + %prog [options] ... + %prog [options] -r ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help=( + "Uninstall all the packages listed in the given requirements " + "file. This option can be used multiple times." + ), + ) + self.cmd_opts.add_option( + "-y", + "--yes", + dest="yes", + action="store_true", + help="Don't ask for confirmation of uninstall deletions.", + ) + self.cmd_opts.add_option(cmdoptions.root_user_action()) + self.cmd_opts.add_option(cmdoptions.override_externally_managed()) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + session = self.get_default_session(options) + + reqs_to_uninstall = {} + for name in args: + req = install_req_from_line( + name, + isolated=options.isolated_mode, + ) + if req.name: + reqs_to_uninstall[canonicalize_name(req.name)] = req + else: + logger.warning( + "Invalid requirement: %r ignored -" + " the uninstall command expects named" + " requirements.", + name, + ) + for filename in options.requirements: + for parsed_req in parse_requirements( + filename, options=options, session=session + ): + req = install_req_from_parsed_requirement( + parsed_req, isolated=options.isolated_mode + ) + if req.name: + reqs_to_uninstall[canonicalize_name(req.name)] = req + if not reqs_to_uninstall: + raise InstallationError( + f"You must give at least one requirement to {self.name} (see " + f'"pip help {self.name}")' + ) + + if not options.override_externally_managed: + check_externally_managed() + + protect_pip_from_modification_on_windows( + modifying_pip="pip" in reqs_to_uninstall + ) + + for req in reqs_to_uninstall.values(): + uninstall_pathset = req.uninstall( + auto_confirm=options.yes, + verbose=self.verbosity > 0, + ) + if uninstall_pathset: + uninstall_pathset.commit() + if options.root_user_action == "warn": + warn_if_run_as_root() + return SUCCESS diff --git a/shared/package-files/38/388abc7f2e98fb431dda961fbf6663ca0ab1d7fea89541583fc7fec739de2d4b/conv_fused.py b/shared/package-files/38/388abc7f2e98fb431dda961fbf6663ca0ab1d7fea89541583fc7fec739de2d4b/conv_fused.py new file mode 100644 index 0000000000000000000000000000000000000000..2f70dc038b5c4f8a8aa8b5c900314b9f409b5d89 --- /dev/null +++ b/shared/package-files/38/388abc7f2e98fb431dda961fbf6663ca0ab1d7fea89541583fc7fec739de2d4b/conv_fused.py @@ -0,0 +1,37 @@ +# flake8: noqa: F401 +r"""Intrinsic QAT Modules. + +This file is in the process of migration to `torch/ao/nn/intrinsic/qat`, 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 +appropriate file under the `torch/ao/nn/intrinsic/qat/modules`, +while adding an import statement here. +""" + +__all__ = [ + # Modules + 'ConvBn1d', + 'ConvBnReLU1d', + 'ConvReLU1d', + 'ConvBn2d', + 'ConvBnReLU2d', + 'ConvReLU2d', + 'ConvBn3d', + 'ConvBnReLU3d', + 'ConvReLU3d', + # Utilities + 'freeze_bn_stats', + 'update_bn_stats', +] + +from torch.ao.nn.intrinsic.qat import ConvBn1d +from torch.ao.nn.intrinsic.qat import ConvBnReLU1d +from torch.ao.nn.intrinsic.qat import ConvReLU1d +from torch.ao.nn.intrinsic.qat import ConvBn2d +from torch.ao.nn.intrinsic.qat import ConvBnReLU2d +from torch.ao.nn.intrinsic.qat import ConvReLU2d +from torch.ao.nn.intrinsic.qat import ConvBn3d +from torch.ao.nn.intrinsic.qat import ConvBnReLU3d +from torch.ao.nn.intrinsic.qat import ConvReLU3d +from torch.ao.nn.intrinsic.qat import freeze_bn_stats +from torch.ao.nn.intrinsic.qat import update_bn_stats diff --git a/shared/package-files/38/388d3ddc5700d20b6425c512339da0047dc680fdd3f502869f6930511e2822bb/qscheme_ops.h b/shared/package-files/38/388d3ddc5700d20b6425c512339da0047dc680fdd3f502869f6930511e2822bb/qscheme_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..58ff85e666397529bcb954cc468d3a0076285d78 --- /dev/null +++ b/shared/package-files/38/388d3ddc5700d20b6425c512339da0047dc680fdd3f502869f6930511e2822bb/qscheme_ops.h @@ -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 qscheme { + using schema = at::QScheme (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::qscheme") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "qscheme(Tensor self) -> QScheme") + static at::QScheme call(const at::Tensor & self); + static at::QScheme redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/3890d5a425265fa1fcbffee5575ce27d5d5f731f760abd9d862521ebdf3d5092/bcppcompiler.py b/shared/package-files/38/3890d5a425265fa1fcbffee5575ce27d5d5f731f760abd9d862521ebdf3d5092/bcppcompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..071fea5d038cb0425a962a8b6bea55a9c158dd5d --- /dev/null +++ b/shared/package-files/38/3890d5a425265fa1fcbffee5575ce27d5d5f731f760abd9d862521ebdf3d5092/bcppcompiler.py @@ -0,0 +1,393 @@ +"""distutils.bcppcompiler + +Contains BorlandCCompiler, an implementation of the abstract CCompiler class +for the Borland C++ compiler. +""" + +# This implementation by Lyle Johnson, based on the original msvccompiler.py +# module and using the directions originally published by Gordon Williams. + +# XXX looks like there's a LOT of overlap between these two classes: +# someone should sit down and factor out the common code as +# WindowsCCompiler! --GPW + + +import os +from distutils.errors import \ + DistutilsExecError, \ + CompileError, LibError, LinkError, UnknownFileError +from distutils.ccompiler import \ + CCompiler, gen_preprocess_options +from distutils.file_util import write_file +from distutils.dep_util import newer +from distutils import log + +class BCPPCompiler(CCompiler) : + """Concrete class that implements an interface to the Borland C/C++ + compiler, as defined by the CCompiler abstract class. + """ + + compiler_type = 'bcpp' + + # Just set this so CCompiler's constructor doesn't barf. We currently + # don't use the 'set_executables()' bureaucracy provided by CCompiler, + # as it really isn't necessary for this sort of single-compiler class. + # Would be nice to have a consistent interface with UnixCCompiler, + # though, so it's worth thinking about. + executables = {} + + # Private class data (need to distinguish C from C++ source for compiler) + _c_extensions = ['.c'] + _cpp_extensions = ['.cc', '.cpp', '.cxx'] + + # Needed for the filename generation methods provided by the + # base class, CCompiler. + src_extensions = _c_extensions + _cpp_extensions + obj_extension = '.obj' + static_lib_extension = '.lib' + shared_lib_extension = '.dll' + static_lib_format = shared_lib_format = '%s%s' + exe_extension = '.exe' + + + def __init__ (self, + verbose=0, + dry_run=0, + force=0): + + CCompiler.__init__ (self, verbose, dry_run, force) + + # These executables are assumed to all be in the path. + # Borland doesn't seem to use any special registry settings to + # indicate their installation locations. + + self.cc = "bcc32.exe" + self.linker = "ilink32.exe" + self.lib = "tlib.exe" + + self.preprocess_options = None + self.compile_options = ['/tWM', '/O2', '/q', '/g0'] + self.compile_options_debug = ['/tWM', '/Od', '/q', '/g0'] + + self.ldflags_shared = ['/Tpd', '/Gn', '/q', '/x'] + self.ldflags_shared_debug = ['/Tpd', '/Gn', '/q', '/x'] + self.ldflags_static = [] + self.ldflags_exe = ['/Gn', '/q', '/x'] + self.ldflags_exe_debug = ['/Gn', '/q', '/x','/r'] + + + # -- Worker methods ------------------------------------------------ + + def compile(self, sources, + output_dir=None, macros=None, include_dirs=None, debug=0, + extra_preargs=None, extra_postargs=None, depends=None): + + macros, objects, extra_postargs, pp_opts, build = \ + self._setup_compile(output_dir, macros, include_dirs, sources, + depends, extra_postargs) + compile_opts = extra_preargs or [] + compile_opts.append ('-c') + if debug: + compile_opts.extend (self.compile_options_debug) + else: + compile_opts.extend (self.compile_options) + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + # XXX why do the normpath here? + src = os.path.normpath(src) + obj = os.path.normpath(obj) + # XXX _setup_compile() did a mkpath() too but before the normpath. + # Is it possible to skip the normpath? + self.mkpath(os.path.dirname(obj)) + + if ext == '.res': + # This is already a binary file -- skip it. + continue # the 'for' loop + if ext == '.rc': + # This needs to be compiled to a .res file -- do it now. + try: + self.spawn (["brcc32", "-fo", obj, src]) + except DistutilsExecError as msg: + raise CompileError(msg) + continue # the 'for' loop + + # The next two are both for the real compiler. + if ext in self._c_extensions: + input_opt = "" + elif ext in self._cpp_extensions: + input_opt = "-P" + else: + # Unknown file type -- no extra options. The compiler + # will probably fail, but let it just in case this is a + # file the compiler recognizes even if we don't. + input_opt = "" + + output_opt = "-o" + obj + + # Compiler command line syntax is: "bcc32 [options] file(s)". + # Note that the source file names must appear at the end of + # the command line. + try: + self.spawn ([self.cc] + compile_opts + pp_opts + + [input_opt, output_opt] + + extra_postargs + [src]) + except DistutilsExecError as msg: + raise CompileError(msg) + + return objects + + # compile () + + + def create_static_lib (self, + objects, + output_libname, + output_dir=None, + debug=0, + target_lang=None): + + (objects, output_dir) = self._fix_object_args (objects, output_dir) + output_filename = \ + self.library_filename (output_libname, output_dir=output_dir) + + if self._need_link (objects, output_filename): + lib_args = [output_filename, '/u'] + objects + if debug: + pass # XXX what goes here? + try: + self.spawn ([self.lib] + lib_args) + except DistutilsExecError as msg: + raise LibError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + # create_static_lib () + + + def link (self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=0, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None): + + # XXX this ignores 'build_temp'! should follow the lead of + # msvccompiler.py + + (objects, output_dir) = self._fix_object_args (objects, output_dir) + (libraries, library_dirs, runtime_library_dirs) = \ + self._fix_lib_args (libraries, library_dirs, runtime_library_dirs) + + if runtime_library_dirs: + log.warn("I don't know what to do with 'runtime_library_dirs': %s", + str(runtime_library_dirs)) + + if output_dir is not None: + output_filename = os.path.join (output_dir, output_filename) + + if self._need_link (objects, output_filename): + + # Figure out linker args based on type of target. + if target_desc == CCompiler.EXECUTABLE: + startup_obj = 'c0w32' + if debug: + ld_args = self.ldflags_exe_debug[:] + else: + ld_args = self.ldflags_exe[:] + else: + startup_obj = 'c0d32' + if debug: + ld_args = self.ldflags_shared_debug[:] + else: + ld_args = self.ldflags_shared[:] + + + # Create a temporary exports file for use by the linker + if export_symbols is None: + def_file = '' + else: + head, tail = os.path.split (output_filename) + modname, ext = os.path.splitext (tail) + temp_dir = os.path.dirname(objects[0]) # preserve tree structure + def_file = os.path.join (temp_dir, '%s.def' % modname) + contents = ['EXPORTS'] + for sym in (export_symbols or []): + contents.append(' %s=_%s' % (sym, sym)) + self.execute(write_file, (def_file, contents), + "writing %s" % def_file) + + # Borland C++ has problems with '/' in paths + objects2 = map(os.path.normpath, objects) + # split objects in .obj and .res files + # Borland C++ needs them at different positions in the command line + objects = [startup_obj] + resources = [] + for file in objects2: + (base, ext) = os.path.splitext(os.path.normcase(file)) + if ext == '.res': + resources.append(file) + else: + objects.append(file) + + + for l in library_dirs: + ld_args.append("/L%s" % os.path.normpath(l)) + ld_args.append("/L.") # we sometimes use relative paths + + # list of object files + ld_args.extend(objects) + + # XXX the command-line syntax for Borland C++ is a bit wonky; + # certain filenames are jammed together in one big string, but + # comma-delimited. This doesn't mesh too well with the + # Unix-centric attitude (with a DOS/Windows quoting hack) of + # 'spawn()', so constructing the argument list is a bit + # awkward. Note that doing the obvious thing and jamming all + # the filenames and commas into one argument would be wrong, + # because 'spawn()' would quote any filenames with spaces in + # them. Arghghh!. Apparently it works fine as coded... + + # name of dll/exe file + ld_args.extend([',',output_filename]) + # no map file and start libraries + ld_args.append(',,') + + for lib in libraries: + # see if we find it and if there is a bcpp specific lib + # (xxx_bcpp.lib) + libfile = self.find_library_file(library_dirs, lib, debug) + if libfile is None: + ld_args.append(lib) + # probably a BCPP internal library -- don't warn + else: + # full name which prefers bcpp_xxx.lib over xxx.lib + ld_args.append(libfile) + + # some default libraries + ld_args.append ('import32') + ld_args.append ('cw32mt') + + # def file for export symbols + ld_args.extend([',',def_file]) + # add resource files + ld_args.append(',') + ld_args.extend(resources) + + + if extra_preargs: + ld_args[:0] = extra_preargs + if extra_postargs: + ld_args.extend(extra_postargs) + + self.mkpath (os.path.dirname (output_filename)) + try: + self.spawn ([self.linker] + ld_args) + except DistutilsExecError as msg: + raise LinkError(msg) + + else: + log.debug("skipping %s (up-to-date)", output_filename) + + # link () + + # -- Miscellaneous methods ----------------------------------------- + + + def find_library_file (self, dirs, lib, debug=0): + # List of effective library names to try, in order of preference: + # xxx_bcpp.lib is better than xxx.lib + # and xxx_d.lib is better than xxx.lib if debug is set + # + # The "_bcpp" suffix is to handle a Python installation for people + # with multiple compilers (primarily Distutils hackers, I suspect + # ;-). The idea is they'd have one static library for each + # compiler they care about, since (almost?) every Windows compiler + # seems to have a different format for static libraries. + if debug: + dlib = (lib + "_d") + try_names = (dlib + "_bcpp", lib + "_bcpp", dlib, lib) + else: + try_names = (lib + "_bcpp", lib) + + for dir in dirs: + for name in try_names: + libfile = os.path.join(dir, self.library_filename(name)) + if os.path.exists(libfile): + return libfile + else: + # Oops, didn't find it in *any* of 'dirs' + return None + + # overwrite the one from CCompiler to support rc and res-files + def object_filenames (self, + source_filenames, + strip_dir=0, + output_dir=''): + if output_dir is None: output_dir = '' + obj_names = [] + for src_name in source_filenames: + # use normcase to make sure '.rc' is really '.rc' and not '.RC' + (base, ext) = os.path.splitext (os.path.normcase(src_name)) + if ext not in (self.src_extensions + ['.rc','.res']): + raise UnknownFileError("unknown file type '%s' (from '%s')" % \ + (ext, src_name)) + if strip_dir: + base = os.path.basename (base) + if ext == '.res': + # these can go unchanged + obj_names.append (os.path.join (output_dir, base + ext)) + elif ext == '.rc': + # these need to be compiled to .res-files + obj_names.append (os.path.join (output_dir, base + '.res')) + else: + obj_names.append (os.path.join (output_dir, + base + self.obj_extension)) + return obj_names + + # object_filenames () + + def preprocess (self, + source, + output_file=None, + macros=None, + include_dirs=None, + extra_preargs=None, + extra_postargs=None): + + (_, macros, include_dirs) = \ + self._fix_compile_args(None, macros, include_dirs) + pp_opts = gen_preprocess_options(macros, include_dirs) + pp_args = ['cpp32.exe'] + pp_opts + if output_file is not None: + pp_args.append('-o' + output_file) + if extra_preargs: + pp_args[:0] = extra_preargs + if extra_postargs: + pp_args.extend(extra_postargs) + pp_args.append(source) + + # We need to preprocess: either we're being forced to, or the + # source file is newer than the target (or the target doesn't + # exist). + if self.force or output_file is None or newer(source, output_file): + if output_file: + self.mkpath(os.path.dirname(output_file)) + try: + self.spawn(pp_args) + except DistutilsExecError as msg: + print(msg) + raise CompileError(msg) + + # preprocess() diff --git a/shared/package-files/38/3896a3dfd0d7d6e1812d071952590e5365c9b41938a777f596a7ad0eef2d3704/_tzpath.py b/shared/package-files/38/3896a3dfd0d7d6e1812d071952590e5365c9b41938a777f596a7ad0eef2d3704/_tzpath.py new file mode 100644 index 0000000000000000000000000000000000000000..672560b9514429e18598cdada8e1a086c6b29cef --- /dev/null +++ b/shared/package-files/38/3896a3dfd0d7d6e1812d071952590e5365c9b41938a777f596a7ad0eef2d3704/_tzpath.py @@ -0,0 +1,175 @@ +import os +import sysconfig + + +def reset_tzpath(to=None): + global TZPATH + + tzpaths = to + if tzpaths is not None: + if isinstance(tzpaths, (str, bytes)): + raise TypeError( + f"tzpaths must be a list or tuple, " + + f"not {type(tzpaths)}: {tzpaths!r}" + ) + + if not all(map(os.path.isabs, tzpaths)): + raise ValueError(_get_invalid_paths_message(tzpaths)) + base_tzpath = tzpaths + else: + env_var = os.environ.get("PYTHONTZPATH", None) + if env_var is not None: + base_tzpath = _parse_python_tzpath(env_var) + else: + base_tzpath = _parse_python_tzpath( + sysconfig.get_config_var("TZPATH") + ) + + TZPATH = tuple(base_tzpath) + + +def _parse_python_tzpath(env_var): + if not env_var: + return () + + raw_tzpath = env_var.split(os.pathsep) + new_tzpath = tuple(filter(os.path.isabs, raw_tzpath)) + + # If anything has been filtered out, we will warn about it + if len(new_tzpath) != len(raw_tzpath): + import warnings + + msg = _get_invalid_paths_message(raw_tzpath) + + warnings.warn( + "Invalid paths specified in PYTHONTZPATH environment variable. " + + msg, + InvalidTZPathWarning, + ) + + return new_tzpath + + +def _get_invalid_paths_message(tzpaths): + invalid_paths = (path for path in tzpaths if not os.path.isabs(path)) + + prefix = "\n " + indented_str = prefix + prefix.join(invalid_paths) + + return ( + "Paths should be absolute but found the following relative paths:" + + indented_str + ) + + +def find_tzfile(key): + """Retrieve the path to a TZif file from a key.""" + _validate_tzfile_path(key) + for search_path in TZPATH: + filepath = os.path.join(search_path, key) + if os.path.isfile(filepath): + return filepath + + return None + + +_TEST_PATH = os.path.normpath(os.path.join("_", "_"))[:-1] + + +def _validate_tzfile_path(path, _base=_TEST_PATH): + if os.path.isabs(path): + raise ValueError( + f"ZoneInfo keys may not be absolute paths, got: {path}" + ) + + # We only care about the kinds of path normalizations that would change the + # length of the key - e.g. a/../b -> a/b, or a/b/ -> a/b. On Windows, + # normpath will also change from a/b to a\b, but that would still preserve + # the length. + new_path = os.path.normpath(path) + if len(new_path) != len(path): + raise ValueError( + f"ZoneInfo keys must be normalized relative paths, got: {path}" + ) + + resolved = os.path.normpath(os.path.join(_base, new_path)) + if not resolved.startswith(_base): + raise ValueError( + f"ZoneInfo keys must refer to subdirectories of TZPATH, got: {path}" + ) + + +del _TEST_PATH + + +def available_timezones(): + """Returns a set containing all available time zones. + + .. caution:: + + This may attempt to open a large number of files, since the best way to + determine if a given file on the time zone search path is to open it + and check for the "magic string" at the beginning. + """ + from importlib import resources + + valid_zones = set() + + # Start with loading from the tzdata package if it exists: this has a + # pre-assembled list of zones that only requires opening one file. + try: + with resources.open_text("tzdata", "zones") as f: + for zone in f: + zone = zone.strip() + if zone: + valid_zones.add(zone) + except (ImportError, FileNotFoundError): + pass + + def valid_key(fpath): + try: + with open(fpath, "rb") as f: + return f.read(4) == b"TZif" + except Exception: # pragma: nocover + return False + + for tz_root in TZPATH: + if not os.path.exists(tz_root): + continue + + for root, dirnames, files in os.walk(tz_root): + if root == tz_root: + # right/ and posix/ are special directories and shouldn't be + # included in the output of available zones + if "right" in dirnames: + dirnames.remove("right") + if "posix" in dirnames: + dirnames.remove("posix") + + for file in files: + fpath = os.path.join(root, file) + + key = os.path.relpath(fpath, start=tz_root) + if os.sep != "/": # pragma: nocover + key = key.replace(os.sep, "/") + + if not key or key in valid_zones: + continue + + if valid_key(fpath): + valid_zones.add(key) + + if "posixrules" in valid_zones: + # posixrules is a special symlink-only time zone where it exists, it + # should not be included in the output + valid_zones.remove("posixrules") + + return valid_zones + + +class InvalidTZPathWarning(RuntimeWarning): + """Warning raised if an invalid path is specified in PYTHONTZPATH.""" + + +TZPATH = () +reset_tzpath() diff --git a/shared/package-files/38/38970acb0f866668476fc4445ccb070e7ed6e553f96e19b18153c80181be163e/fortran-si4-15x10x22.dat b/shared/package-files/38/38970acb0f866668476fc4445ccb070e7ed6e553f96e19b18153c80181be163e/fortran-si4-15x10x22.dat new file mode 100644 index 0000000000000000000000000000000000000000..98c09c2dff6e1ef605e25ed1d00afe94597abddc Binary files /dev/null and b/shared/package-files/38/38970acb0f866668476fc4445ccb070e7ed6e553f96e19b18153c80181be163e/fortran-si4-15x10x22.dat differ diff --git a/shared/package-files/38/389b2b6e54b69c7a6d65cb6f6bea402852f9abcc8f1009219a33d9a49e9303de/ed25519.pyi b/shared/package-files/38/389b2b6e54b69c7a6d65cb6f6bea402852f9abcc8f1009219a33d9a49e9303de/ed25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5233f9a1d1c8e45f928bd4b41cf1e821332a2a67 --- /dev/null +++ b/shared/package-files/38/389b2b6e54b69c7a6d65cb6f6bea402852f9abcc8f1009219a33d9a49e9303de/ed25519.pyi @@ -0,0 +1,12 @@ +# 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 cryptography.hazmat.primitives.asymmetric import ed25519 + +class Ed25519PrivateKey: ... +class Ed25519PublicKey: ... + +def generate_key() -> ed25519.Ed25519PrivateKey: ... +def from_private_bytes(data: bytes) -> ed25519.Ed25519PrivateKey: ... +def from_public_bytes(data: bytes) -> ed25519.Ed25519PublicKey: ... diff --git a/shared/package-files/38/389b811835f9a3ba72b192c3487b0266fa31f6e571b7a83ceb2a34792dc0d9fc/robotparser.py b/shared/package-files/38/389b811835f9a3ba72b192c3487b0266fa31f6e571b7a83ceb2a34792dc0d9fc/robotparser.py new file mode 100644 index 0000000000000000000000000000000000000000..c58565e39451461f03dc7d9fb652554c96615f00 --- /dev/null +++ b/shared/package-files/38/389b811835f9a3ba72b192c3487b0266fa31f6e571b7a83ceb2a34792dc0d9fc/robotparser.py @@ -0,0 +1,273 @@ +""" robotparser.py + + Copyright (C) 2000 Bastian Kleineidam + + You can choose between two licenses when using this package: + 1) GNU GPLv2 + 2) PSF license for Python 2.2 + + The robots.txt Exclusion Protocol is implemented as specified in + http://www.robotstxt.org/norobots-rfc.txt +""" + +import collections +import urllib.parse +import urllib.request + +__all__ = ["RobotFileParser"] + +RequestRate = collections.namedtuple("RequestRate", "requests seconds") + + +class RobotFileParser: + """ This class provides a set of methods to read, parse and answer + questions about a single robots.txt file. + + """ + + def __init__(self, url=''): + self.entries = [] + self.sitemaps = [] + self.default_entry = None + self.disallow_all = False + self.allow_all = False + self.set_url(url) + self.last_checked = 0 + + def mtime(self): + """Returns the time the robots.txt file was last fetched. + + This is useful for long-running web spiders that need to + check for new robots.txt files periodically. + + """ + return self.last_checked + + def modified(self): + """Sets the time the robots.txt file was last fetched to the + current time. + + """ + import time + self.last_checked = time.time() + + def set_url(self, url): + """Sets the URL referring to a robots.txt file.""" + self.url = url + self.host, self.path = urllib.parse.urlparse(url)[1:3] + + def read(self): + """Reads the robots.txt URL and feeds it to the parser.""" + try: + f = urllib.request.urlopen(self.url) + except urllib.error.HTTPError as err: + if err.code in (401, 403): + self.disallow_all = True + elif err.code >= 400 and err.code < 500: + self.allow_all = True + else: + raw = f.read() + self.parse(raw.decode("utf-8").splitlines()) + + def _add_entry(self, entry): + if "*" in entry.useragents: + # the default entry is considered last + if self.default_entry is None: + # the first default entry wins + self.default_entry = entry + else: + self.entries.append(entry) + + def parse(self, lines): + """Parse the input lines from a robots.txt file. + + We allow that a user-agent: line is not preceded by + one or more blank lines. + """ + # states: + # 0: start state + # 1: saw user-agent line + # 2: saw an allow or disallow line + state = 0 + entry = Entry() + + self.modified() + for line in lines: + if not line: + if state == 1: + entry = Entry() + state = 0 + elif state == 2: + self._add_entry(entry) + entry = Entry() + state = 0 + # remove optional comment and strip line + i = line.find('#') + if i >= 0: + line = line[:i] + line = line.strip() + if not line: + continue + line = line.split(':', 1) + if len(line) == 2: + line[0] = line[0].strip().lower() + line[1] = urllib.parse.unquote(line[1].strip()) + if line[0] == "user-agent": + if state == 2: + self._add_entry(entry) + entry = Entry() + entry.useragents.append(line[1]) + state = 1 + elif line[0] == "disallow": + if state != 0: + entry.rulelines.append(RuleLine(line[1], False)) + state = 2 + elif line[0] == "allow": + if state != 0: + entry.rulelines.append(RuleLine(line[1], True)) + state = 2 + elif line[0] == "crawl-delay": + if state != 0: + # before trying to convert to int we need to make + # sure that robots.txt has valid syntax otherwise + # it will crash + if line[1].strip().isdigit(): + entry.delay = int(line[1]) + state = 2 + elif line[0] == "request-rate": + if state != 0: + numbers = line[1].split('/') + # check if all values are sane + if (len(numbers) == 2 and numbers[0].strip().isdigit() + and numbers[1].strip().isdigit()): + entry.req_rate = RequestRate(int(numbers[0]), int(numbers[1])) + state = 2 + elif line[0] == "sitemap": + # According to http://www.sitemaps.org/protocol.html + # "This directive is independent of the user-agent line, + # so it doesn't matter where you place it in your file." + # Therefore we do not change the state of the parser. + self.sitemaps.append(line[1]) + if state == 2: + self._add_entry(entry) + + def can_fetch(self, useragent, url): + """using the parsed robots.txt decide if useragent can fetch url""" + if self.disallow_all: + return False + if self.allow_all: + return True + # Until the robots.txt file has been read or found not + # to exist, we must assume that no url is allowable. + # This prevents false positives when a user erroneously + # calls can_fetch() before calling read(). + if not self.last_checked: + return False + # search for given user agent matches + # the first match counts + parsed_url = urllib.parse.urlparse(urllib.parse.unquote(url)) + url = urllib.parse.urlunparse(('','',parsed_url.path, + parsed_url.params,parsed_url.query, parsed_url.fragment)) + url = urllib.parse.quote(url) + if not url: + url = "/" + for entry in self.entries: + if entry.applies_to(useragent): + return entry.allowance(url) + # try the default entry last + if self.default_entry: + return self.default_entry.allowance(url) + # agent not found ==> access granted + return True + + def crawl_delay(self, useragent): + if not self.mtime(): + return None + for entry in self.entries: + if entry.applies_to(useragent): + return entry.delay + if self.default_entry: + return self.default_entry.delay + return None + + def request_rate(self, useragent): + if not self.mtime(): + return None + for entry in self.entries: + if entry.applies_to(useragent): + return entry.req_rate + if self.default_entry: + return self.default_entry.req_rate + return None + + def site_maps(self): + if not self.sitemaps: + return None + return self.sitemaps + + def __str__(self): + entries = self.entries + if self.default_entry is not None: + entries = entries + [self.default_entry] + return '\n\n'.join(map(str, entries)) + + +class RuleLine: + """A rule line is a single "Allow:" (allowance==True) or "Disallow:" + (allowance==False) followed by a path.""" + def __init__(self, path, allowance): + if path == '' and not allowance: + # an empty value means allow all + allowance = True + path = urllib.parse.urlunparse(urllib.parse.urlparse(path)) + self.path = urllib.parse.quote(path) + self.allowance = allowance + + def applies_to(self, filename): + return self.path == "*" or filename.startswith(self.path) + + def __str__(self): + return ("Allow" if self.allowance else "Disallow") + ": " + self.path + + +class Entry: + """An entry has one or more user-agents and zero or more rulelines""" + def __init__(self): + self.useragents = [] + self.rulelines = [] + self.delay = None + self.req_rate = None + + def __str__(self): + ret = [] + for agent in self.useragents: + ret.append(f"User-agent: {agent}") + if self.delay is not None: + ret.append(f"Crawl-delay: {self.delay}") + if self.req_rate is not None: + rate = self.req_rate + ret.append(f"Request-rate: {rate.requests}/{rate.seconds}") + ret.extend(map(str, self.rulelines)) + return '\n'.join(ret) + + def applies_to(self, useragent): + """check if this entry applies to the specified agent""" + # split the name token and make it lower case + useragent = useragent.split("/")[0].lower() + for agent in self.useragents: + if agent == '*': + # we have the catch-all agent + return True + agent = agent.lower() + if agent in useragent: + return True + return False + + def allowance(self, filename): + """Preconditions: + - our agent applies to this entry + - filename is URL decoded""" + for line in self.rulelines: + if line.applies_to(filename): + return line.allowance + return True diff --git a/shared/package-files/38/38a45adb2b8732d9d57278acbbec5c69e762d912ac1fd42b814f5ec60a0e2b7d/test_exceptions.py b/shared/package-files/38/38a45adb2b8732d9d57278acbbec5c69e762d912ac1fd42b814f5ec60a0e2b7d/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d91e55e95d0ae4ac57cdd1989e0b3d39a55cd07d --- /dev/null +++ b/shared/package-files/38/38a45adb2b8732d9d57278acbbec5c69e762d912ac1fd42b814f5ec60a0e2b7d/test_exceptions.py @@ -0,0 +1,12 @@ +from sympy.testing.pytest import raises +from sympy.utilities.exceptions import sympy_deprecation_warning + +# Only test exceptions here because the other cases are tested in the +# warns_deprecated_sympy tests +def test_sympy_deprecation_warning(): + raises(TypeError, lambda: sympy_deprecation_warning('test', + deprecated_since_version=1.10, + active_deprecations_target='active-deprecations')) + + raises(ValueError, lambda: sympy_deprecation_warning('test', + deprecated_since_version="1.10", active_deprecations_target='(active-deprecations)=')) diff --git a/shared/package-files/38/38a66a56612284319dcea255add7353f155d050a1a245aebc63769c994490e0e/test_setops.py b/shared/package-files/38/38a66a56612284319dcea255add7353f155d050a1a245aebc63769c994490e0e/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..0980e93c5727544816141b3dab71041116f59db7 --- /dev/null +++ b/shared/package-files/38/38a66a56612284319dcea255add7353f155d050a1a245aebc63769c994490e0e/test_setops.py @@ -0,0 +1,973 @@ +""" +The tests in this package are to ensure the proper resultant dtypes of +set operations. +""" +from datetime import datetime +import operator + +import numpy as np +import pytest + +from pandas._libs import lib + +from pandas.core.dtypes.cast import find_common_type + +from pandas import ( + CategoricalDtype, + CategoricalIndex, + DatetimeTZDtype, + Index, + MultiIndex, + PeriodDtype, + RangeIndex, + Series, + Timestamp, +) +import pandas._testing as tm +from pandas.api.types import ( + is_signed_integer_dtype, + pandas_dtype, +) + + +def equal_contents(arr1, arr2) -> bool: + """ + Checks if the set of unique elements of arr1 and arr2 are equivalent. + """ + return frozenset(arr1) == frozenset(arr2) + + +@pytest.fixture( + params=tm.ALL_REAL_NUMPY_DTYPES + + [ + "object", + "category", + "datetime64[ns]", + "timedelta64[ns]", + ] +) +def any_dtype_for_small_pos_integer_indexes(request): + """ + Dtypes that can be given to an Index with small positive integers. + + This means that for any dtype `x` in the params list, `Index([1, 2, 3], dtype=x)` is + valid and gives the correct Index (sub-)class. + """ + return request.param + + +def test_union_same_types(index): + # Union with a non-unique, non-monotonic index raises error + # Only needed for bool index factory + idx1 = index.sort_values() + idx2 = index.sort_values() + assert idx1.union(idx2).dtype == idx1.dtype + + +def test_union_different_types(index_flat, index_flat2, request, using_infer_string): + # This test only considers combinations of indices + # GH 23525 + idx1 = index_flat + idx2 = index_flat2 + + if ( + not idx1.is_unique + and not idx2.is_unique + and idx1.dtype.kind == "i" + and idx2.dtype.kind == "b" + ) or ( + not idx2.is_unique + and not idx1.is_unique + and idx2.dtype.kind == "i" + and idx1.dtype.kind == "b" + ): + # Each condition had idx[1|2].is_monotonic_decreasing + # but failed when e.g. + # idx1 = Index( + # [True, True, True, True, True, True, True, True, False, False], dtype='bool' + # ) + # idx2 = Index([0, 0, 1, 1, 2, 2], dtype='int64') + mark = pytest.mark.xfail( + reason="GH#44000 True==1", raises=ValueError, strict=False + ) + request.applymarker(mark) + + common_dtype = find_common_type([idx1.dtype, idx2.dtype]) + if using_infer_string: + if len(idx1) == 0 and (idx1.dtype.kind == "O" or isinstance(idx1, RangeIndex)): + common_dtype = idx2.dtype + elif len(idx2) == 0 and ( + idx2.dtype.kind == "O" or isinstance(idx2, RangeIndex) + ): + common_dtype = idx1.dtype + + warn = None + msg = "'<' not supported between" + if not len(idx1) or not len(idx2): + pass + elif (idx1.dtype.kind == "c" and (not lib.is_np_dtype(idx2.dtype, "iufc"))) or ( + idx2.dtype.kind == "c" and (not lib.is_np_dtype(idx1.dtype, "iufc")) + ): + # complex objects non-sortable + warn = RuntimeWarning + elif ( + isinstance(idx1.dtype, PeriodDtype) and isinstance(idx2.dtype, CategoricalDtype) + ) or ( + isinstance(idx2.dtype, PeriodDtype) and isinstance(idx1.dtype, CategoricalDtype) + ): + warn = FutureWarning + msg = r"PeriodDtype\[B\] is deprecated" + mark = pytest.mark.xfail( + reason="Warning not produced on all builds", + raises=AssertionError, + strict=False, + ) + request.applymarker(mark) + + any_uint64 = np.uint64 in (idx1.dtype, idx2.dtype) + idx1_signed = is_signed_integer_dtype(idx1.dtype) + idx2_signed = is_signed_integer_dtype(idx2.dtype) + + # Union with a non-unique, non-monotonic index raises error + # This applies to the boolean index + idx1 = idx1.sort_values() + idx2 = idx2.sort_values() + + with tm.assert_produces_warning(warn, match=msg): + res1 = idx1.union(idx2) + res2 = idx2.union(idx1) + + if any_uint64 and (idx1_signed or idx2_signed): + assert res1.dtype == np.dtype("O") + assert res2.dtype == np.dtype("O") + else: + assert res1.dtype == common_dtype + assert res2.dtype == common_dtype + + +@pytest.mark.parametrize( + "idx1,idx2", + [ + (Index(np.arange(5), dtype=np.int64), RangeIndex(5)), + (Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.int64)), + (Index(np.arange(5), dtype=np.float64), RangeIndex(5)), + (Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.uint64)), + ], +) +def test_compatible_inconsistent_pairs(idx1, idx2): + # GH 23525 + res1 = idx1.union(idx2) + res2 = idx2.union(idx1) + + assert res1.dtype in (idx1.dtype, idx2.dtype) + assert res2.dtype in (idx1.dtype, idx2.dtype) + + +@pytest.mark.parametrize( + "left, right, expected", + [ + ("int64", "int64", "int64"), + ("int64", "uint64", "object"), + ("int64", "float64", "float64"), + ("uint64", "float64", "float64"), + ("uint64", "uint64", "uint64"), + ("float64", "float64", "float64"), + ("datetime64[ns]", "int64", "object"), + ("datetime64[ns]", "uint64", "object"), + ("datetime64[ns]", "float64", "object"), + ("datetime64[ns, CET]", "int64", "object"), + ("datetime64[ns, CET]", "uint64", "object"), + ("datetime64[ns, CET]", "float64", "object"), + ("Period[D]", "int64", "object"), + ("Period[D]", "uint64", "object"), + ("Period[D]", "float64", "object"), + ], +) +@pytest.mark.parametrize("names", [("foo", "foo", "foo"), ("foo", "bar", None)]) +def test_union_dtypes(left, right, expected, names): + left = pandas_dtype(left) + right = pandas_dtype(right) + a = Index([], dtype=left, name=names[0]) + b = Index([], dtype=right, name=names[1]) + result = a.union(b) + assert result.dtype == expected + assert result.name == names[2] + + # Testing name retention + # TODO: pin down desired dtype; do we want it to be commutative? + result = a.intersection(b) + assert result.name == names[2] + + +@pytest.mark.parametrize("values", [[1, 2, 2, 3], [3, 3]]) +def test_intersection_duplicates(values): + # GH#31326 + a = Index(values) + b = Index([3, 3]) + result = a.intersection(b) + expected = Index([3]) + tm.assert_index_equal(result, expected) + + +class TestSetOps: + # Set operation tests shared by all indexes in the `index` fixture + @pytest.mark.parametrize("case", [0.5, "xxx"]) + @pytest.mark.parametrize( + "method", ["intersection", "union", "difference", "symmetric_difference"] + ) + def test_set_ops_error_cases(self, case, method, index): + # non-iterable input + msg = "Input must be Index or array-like" + with pytest.raises(TypeError, match=msg): + getattr(index, method)(case) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_intersection_base(self, index): + if isinstance(index, CategoricalIndex): + pytest.skip(f"Not relevant for {type(index).__name__}") + + first = index[:5].unique() + second = index[:3].unique() + intersect = first.intersection(second) + tm.assert_index_equal(intersect, second) + + if isinstance(index.dtype, DatetimeTZDtype): + # The second.values below will drop tz, so the rest of this test + # is not applicable. + return + + # GH#10149 + cases = [second.to_numpy(), second.to_series(), second.to_list()] + for case in cases: + result = first.intersection(case) + assert equal_contents(result, second) + + if isinstance(index, MultiIndex): + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.intersection([1, 2, 3]) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_union_base(self, index): + index = index.unique() + first = index[3:] + second = index[:5] + everything = index + + union = first.union(second) + tm.assert_index_equal(union.sort_values(), everything.sort_values()) + + if isinstance(index.dtype, DatetimeTZDtype): + # The second.values below will drop tz, so the rest of this test + # is not applicable. + return + + # GH#10149 + cases = [second.to_numpy(), second.to_series(), second.to_list()] + for case in cases: + result = first.union(case) + assert equal_contents(result, everything) + + if isinstance(index, MultiIndex): + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.union([1, 2, 3]) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_difference_base(self, sort, index): + first = index[2:] + second = index[:4] + if index.inferred_type == "boolean": + # i think (TODO: be sure) there assumptions baked in about + # the index fixture that don't hold here? + answer = set(first).difference(set(second)) + elif isinstance(index, CategoricalIndex): + answer = [] + else: + answer = index[4:] + result = first.difference(second, sort) + assert equal_contents(result, answer) + + # GH#10149 + cases = [second.to_numpy(), second.to_series(), second.to_list()] + for case in cases: + result = first.difference(case, sort) + assert equal_contents(result, answer) + + if isinstance(index, MultiIndex): + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.difference([1, 2, 3], sort) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_symmetric_difference(self, index, using_infer_string, request): + if ( + using_infer_string + and index.dtype == "object" + and index.inferred_type == "string" + ): + request.applymarker(pytest.mark.xfail(reason="TODO: infer_string")) + if isinstance(index, CategoricalIndex): + pytest.skip(f"Not relevant for {type(index).__name__}") + if len(index) < 2: + pytest.skip("Too few values for test") + if index[0] in index[1:] or index[-1] in index[:-1]: + # index fixture has e.g. an index of bools that does not satisfy this, + # another with [0, 0, 1, 1, 2, 2] + pytest.skip("Index values no not satisfy test condition.") + + first = index[1:] + second = index[:-1] + answer = index[[0, -1]] + result = first.symmetric_difference(second) + tm.assert_index_equal(result.sort_values(), answer.sort_values()) + + # GH#10149 + cases = [second.to_numpy(), second.to_series(), second.to_list()] + for case in cases: + result = first.symmetric_difference(case) + assert equal_contents(result, answer) + + if isinstance(index, MultiIndex): + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.symmetric_difference([1, 2, 3]) + + @pytest.mark.parametrize( + "fname, sname, expected_name", + [ + ("A", "A", "A"), + ("A", "B", None), + ("A", None, None), + (None, "B", None), + (None, None, None), + ], + ) + def test_corner_union(self, index_flat, fname, sname, expected_name): + # GH#9943, GH#9862 + # Test unions with various name combinations + # Do not test MultiIndex or repeats + if not index_flat.is_unique: + index = index_flat.unique() + else: + index = index_flat + + # Test copy.union(copy) + first = index.copy().set_names(fname) + second = index.copy().set_names(sname) + union = first.union(second) + expected = index.copy().set_names(expected_name) + tm.assert_index_equal(union, expected) + + # Test copy.union(empty) + first = index.copy().set_names(fname) + second = index.drop(index).set_names(sname) + union = first.union(second) + expected = index.copy().set_names(expected_name) + tm.assert_index_equal(union, expected) + + # Test empty.union(copy) + first = index.drop(index).set_names(fname) + second = index.copy().set_names(sname) + union = first.union(second) + expected = index.copy().set_names(expected_name) + tm.assert_index_equal(union, expected) + + # Test empty.union(empty) + first = index.drop(index).set_names(fname) + second = index.drop(index).set_names(sname) + union = first.union(second) + expected = index.drop(index).set_names(expected_name) + tm.assert_index_equal(union, expected) + + @pytest.mark.parametrize( + "fname, sname, expected_name", + [ + ("A", "A", "A"), + ("A", "B", None), + ("A", None, None), + (None, "B", None), + (None, None, None), + ], + ) + def test_union_unequal(self, index_flat, fname, sname, expected_name): + if not index_flat.is_unique: + index = index_flat.unique() + else: + index = index_flat + + # test copy.union(subset) - need sort for unicode and string + first = index.copy().set_names(fname) + second = index[1:].set_names(sname) + union = first.union(second).sort_values() + expected = index.set_names(expected_name).sort_values() + tm.assert_index_equal(union, expected) + + @pytest.mark.parametrize( + "fname, sname, expected_name", + [ + ("A", "A", "A"), + ("A", "B", None), + ("A", None, None), + (None, "B", None), + (None, None, None), + ], + ) + def test_corner_intersect(self, index_flat, fname, sname, expected_name): + # GH#35847 + # Test intersections with various name combinations + if not index_flat.is_unique: + index = index_flat.unique() + else: + index = index_flat + + # Test copy.intersection(copy) + first = index.copy().set_names(fname) + second = index.copy().set_names(sname) + intersect = first.intersection(second) + expected = index.copy().set_names(expected_name) + tm.assert_index_equal(intersect, expected) + + # Test copy.intersection(empty) + first = index.copy().set_names(fname) + second = index.drop(index).set_names(sname) + intersect = first.intersection(second) + expected = index.drop(index).set_names(expected_name) + tm.assert_index_equal(intersect, expected) + + # Test empty.intersection(copy) + first = index.drop(index).set_names(fname) + second = index.copy().set_names(sname) + intersect = first.intersection(second) + expected = index.drop(index).set_names(expected_name) + tm.assert_index_equal(intersect, expected) + + # Test empty.intersection(empty) + first = index.drop(index).set_names(fname) + second = index.drop(index).set_names(sname) + intersect = first.intersection(second) + expected = index.drop(index).set_names(expected_name) + tm.assert_index_equal(intersect, expected) + + @pytest.mark.parametrize( + "fname, sname, expected_name", + [ + ("A", "A", "A"), + ("A", "B", None), + ("A", None, None), + (None, "B", None), + (None, None, None), + ], + ) + def test_intersect_unequal(self, index_flat, fname, sname, expected_name): + if not index_flat.is_unique: + index = index_flat.unique() + else: + index = index_flat + + # test copy.intersection(subset) - need sort for unicode and string + first = index.copy().set_names(fname) + second = index[1:].set_names(sname) + intersect = first.intersection(second).sort_values() + expected = index[1:].set_names(expected_name).sort_values() + tm.assert_index_equal(intersect, expected) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_intersection_name_retention_with_nameless(self, index): + if isinstance(index, MultiIndex): + index = index.rename(list(range(index.nlevels))) + else: + index = index.rename("foo") + + other = np.asarray(index) + + result = index.intersection(other) + assert result.name == index.name + + # empty other, same dtype + result = index.intersection(other[:0]) + assert result.name == index.name + + # empty `self` + result = index[:0].intersection(other) + assert result.name == index.name + + def test_difference_preserves_type_empty(self, index, sort): + # GH#20040 + # If taking difference of a set and itself, it + # needs to preserve the type of the index + if not index.is_unique: + pytest.skip("Not relevant since index is not unique") + result = index.difference(index, sort=sort) + expected = index[:0] + tm.assert_index_equal(result, expected, exact=True) + + def test_difference_name_retention_equals(self, index, names): + if isinstance(index, MultiIndex): + names = [[x] * index.nlevels for x in names] + index = index.rename(names[0]) + other = index.rename(names[1]) + + assert index.equals(other) + + result = index.difference(other) + expected = index[:0].rename(names[2]) + tm.assert_index_equal(result, expected) + + def test_intersection_difference_match_empty(self, index, sort): + # GH#20040 + # Test that the intersection of an index with an + # empty index produces the same index as the difference + # of an index with itself. Test for all types + if not index.is_unique: + pytest.skip("Not relevant because index is not unique") + inter = index.intersection(index[:0]) + diff = index.difference(index, sort=sort) + tm.assert_index_equal(inter, diff, exact=True) + + +@pytest.mark.filterwarnings("ignore:invalid value encountered in cast:RuntimeWarning") +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") +@pytest.mark.parametrize( + "method", ["intersection", "union", "difference", "symmetric_difference"] +) +def test_setop_with_categorical(index_flat, sort, method, using_infer_string): + # MultiIndex tested separately in tests.indexes.multi.test_setops + index = index_flat + + other = index.astype("category") + exact = "equiv" if isinstance(index, RangeIndex) else True + + result = getattr(index, method)(other, sort=sort) + expected = getattr(index, method)(index, sort=sort) + if ( + using_infer_string + and index.empty + and method in ("union", "symmetric_difference") + ): + expected = expected.astype("category") + tm.assert_index_equal(result, expected, exact=exact) + + result = getattr(index, method)(other[:5], sort=sort) + expected = getattr(index, method)(index[:5], sort=sort) + if ( + using_infer_string + and index.empty + and method in ("union", "symmetric_difference") + ): + expected = expected.astype("category") + tm.assert_index_equal(result, expected, exact=exact) + + +def test_intersection_duplicates_all_indexes(index): + # GH#38743 + if index.empty: + # No duplicates in empty indexes + pytest.skip("Not relevant for empty Index") + + idx = index + idx_non_unique = idx[[0, 0, 1, 2]] + + assert idx.intersection(idx_non_unique).equals(idx_non_unique.intersection(idx)) + assert idx.intersection(idx_non_unique).is_unique + + +def test_union_duplicate_index_subsets_of_each_other( + any_dtype_for_small_pos_integer_indexes, +): + # GH#31326 + dtype = any_dtype_for_small_pos_integer_indexes + a = Index([1, 2, 2, 3], dtype=dtype) + b = Index([3, 3, 4], dtype=dtype) + + expected = Index([1, 2, 2, 3, 3, 4], dtype=dtype) + if isinstance(a, CategoricalIndex): + expected = Index([1, 2, 2, 3, 3, 4]) + result = a.union(b) + tm.assert_index_equal(result, expected) + result = a.union(b, sort=False) + tm.assert_index_equal(result, expected) + + +def test_union_with_duplicate_index_and_non_monotonic( + any_dtype_for_small_pos_integer_indexes, +): + # GH#36289 + dtype = any_dtype_for_small_pos_integer_indexes + a = Index([1, 0, 0], dtype=dtype) + b = Index([0, 1], dtype=dtype) + expected = Index([0, 0, 1], dtype=dtype) + + result = a.union(b) + tm.assert_index_equal(result, expected) + + result = b.union(a) + tm.assert_index_equal(result, expected) + + +def test_union_duplicate_index_different_dtypes(): + # GH#36289 + a = Index([1, 2, 2, 3]) + b = Index(["1", "0", "0"]) + expected = Index([1, 2, 2, 3, "1", "0", "0"]) + result = a.union(b, sort=False) + tm.assert_index_equal(result, expected) + + +def test_union_same_value_duplicated_in_both(): + # GH#36289 + a = Index([0, 0, 1]) + b = Index([0, 0, 1, 2]) + result = a.union(b) + expected = Index([0, 0, 1, 2]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("dup", [1, np.nan]) +def test_union_nan_in_both(dup): + # GH#36289 + a = Index([np.nan, 1, 2, 2]) + b = Index([np.nan, dup, 1, 2]) + result = a.union(b, sort=False) + expected = Index([np.nan, dup, 1.0, 2.0, 2.0]) + tm.assert_index_equal(result, expected) + + +def test_union_rangeindex_sort_true(): + # GH 53490 + idx1 = RangeIndex(1, 100, 6) + idx2 = RangeIndex(1, 50, 3) + result = idx1.union(idx2, sort=True) + expected = Index( + [ + 1, + 4, + 7, + 10, + 13, + 16, + 19, + 22, + 25, + 28, + 31, + 34, + 37, + 40, + 43, + 46, + 49, + 55, + 61, + 67, + 73, + 79, + 85, + 91, + 97, + ] + ) + tm.assert_index_equal(result, expected) + + +def test_union_with_duplicate_index_not_subset_and_non_monotonic( + any_dtype_for_small_pos_integer_indexes, +): + # GH#36289 + dtype = any_dtype_for_small_pos_integer_indexes + a = Index([1, 0, 2], dtype=dtype) + b = Index([0, 0, 1], dtype=dtype) + expected = Index([0, 0, 1, 2], dtype=dtype) + if isinstance(a, CategoricalIndex): + expected = Index([0, 0, 1, 2]) + + result = a.union(b) + tm.assert_index_equal(result, expected) + + result = b.union(a) + tm.assert_index_equal(result, expected) + + +def test_union_int_categorical_with_nan(): + ci = CategoricalIndex([1, 2, np.nan]) + assert ci.categories.dtype.kind == "i" + + idx = Index([1, 2]) + + result = idx.union(ci) + expected = Index([1, 2, np.nan], dtype=np.float64) + tm.assert_index_equal(result, expected) + + result = ci.union(idx) + tm.assert_index_equal(result, expected) + + +class TestSetOpsUnsorted: + # These may eventually belong in a dtype-specific test_setops, or + # parametrized over a more general fixture + def test_intersect_str_dates(self): + dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] + + index1 = Index(dt_dates, dtype=object) + index2 = Index(["aa"], dtype=object) + result = index2.intersection(index1) + + expected = Index([], dtype=object) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_intersection(self, index, sort): + first = index[:20] + second = index[:10] + intersect = first.intersection(second, sort=sort) + if sort in (None, False): + tm.assert_index_equal(intersect.sort_values(), second.sort_values()) + else: + tm.assert_index_equal(intersect, second) + + # Corner cases + inter = first.intersection(first, sort=sort) + assert inter is first + + @pytest.mark.parametrize( + "index2,keeps_name", + [ + (Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name + (Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names + (Index([3, 4, 5, 6, 7]), False), + ], + ) + def test_intersection_name_preservation(self, index2, keeps_name, sort): + index1 = Index([1, 2, 3, 4, 5], name="index") + expected = Index([3, 4, 5]) + result = index1.intersection(index2, sort) + + if keeps_name: + expected.name = "index" + + assert result.name == expected.name + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + @pytest.mark.parametrize( + "first_name,second_name,expected_name", + [("A", "A", "A"), ("A", "B", None), (None, "B", None)], + ) + def test_intersection_name_preservation2( + self, index, first_name, second_name, expected_name, sort + ): + first = index[5:20] + second = index[:10] + first.name = first_name + second.name = second_name + intersect = first.intersection(second, sort=sort) + assert intersect.name == expected_name + + def test_chained_union(self, sort): + # Chained unions handles names correctly + i1 = Index([1, 2], name="i1") + i2 = Index([5, 6], name="i2") + i3 = Index([3, 4], name="i3") + union = i1.union(i2.union(i3, sort=sort), sort=sort) + expected = i1.union(i2, sort=sort).union(i3, sort=sort) + tm.assert_index_equal(union, expected) + + j1 = Index([1, 2], name="j1") + j2 = Index([], name="j2") + j3 = Index([], name="j3") + union = j1.union(j2.union(j3, sort=sort), sort=sort) + expected = j1.union(j2, sort=sort).union(j3, sort=sort) + tm.assert_index_equal(union, expected) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union(self, index, sort): + first = index[5:20] + second = index[:10] + everything = index[:20] + + union = first.union(second, sort=sort) + if sort in (None, False): + tm.assert_index_equal(union.sort_values(), everything.sort_values()) + else: + tm.assert_index_equal(union, everything) + + @pytest.mark.parametrize("klass", [np.array, Series, list]) + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union_from_iterables(self, index, klass, sort): + # GH#10149 + first = index[5:20] + second = index[:10] + everything = index[:20] + + case = klass(second.values) + result = first.union(case, sort=sort) + if sort in (None, False): + tm.assert_index_equal(result.sort_values(), everything.sort_values()) + else: + tm.assert_index_equal(result, everything) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union_identity(self, index, sort): + first = index[5:20] + + union = first.union(first, sort=sort) + # i.e. identity is not preserved when sort is True + assert (union is first) is (not sort) + + # This should no longer be the same object, since [] is not consistent, + # both objects will be recast to dtype('O') + union = first.union(Index([], dtype=first.dtype), sort=sort) + assert (union is first) is (not sort) + + union = Index([], dtype=first.dtype).union(first, sort=sort) + assert (union is first) is (not sort) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + @pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")]) + def test_difference_name_preservation(self, index, second_name, expected, sort): + first = index[5:20] + second = index[:10] + answer = index[10:20] + + first.name = "name" + second.name = second_name + result = first.difference(second, sort=sort) + + if sort is True: + tm.assert_index_equal(result, answer) + else: + answer.name = second_name + tm.assert_index_equal(result.sort_values(), answer.sort_values()) + + if expected is None: + assert result.name is None + else: + assert result.name == expected + + def test_difference_empty_arg(self, index, sort): + first = index.copy() + first = first[5:20] + first.name = "name" + result = first.difference([], sort) + expected = index[5:20].unique() + expected.name = "name" + tm.assert_index_equal(result, expected) + + def test_difference_should_not_compare(self): + # GH 55113 + left = Index([1, 1]) + right = Index([True]) + result = left.difference(right) + expected = Index([1]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_difference_identity(self, index, sort): + first = index[5:20] + first.name = "name" + result = first.difference(first, sort) + + assert len(result) == 0 + assert result.name == first.name + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_difference_sort(self, index, sort): + first = index[5:20] + second = index[:10] + + result = first.difference(second, sort) + expected = index[10:20] + + if sort is None: + expected = expected.sort_values() + + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) + def test_difference_incomparable(self, opname): + a = Index([3, Timestamp("2000"), 1]) + b = Index([2, Timestamp("1999"), 1]) + op = operator.methodcaller(opname, b) + + with tm.assert_produces_warning(RuntimeWarning): + # sort=None, the default + result = op(a) + expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")]) + if opname == "difference": + expected = expected[:2] + tm.assert_index_equal(result, expected) + + # sort=False + op = operator.methodcaller(opname, b, sort=False) + result = op(a) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) + def test_difference_incomparable_true(self, opname): + a = Index([3, Timestamp("2000"), 1]) + b = Index([2, Timestamp("1999"), 1]) + op = operator.methodcaller(opname, b, sort=True) + + msg = "'<' not supported between instances of 'Timestamp' and 'int'" + with pytest.raises(TypeError, match=msg): + op(a) + + def test_symmetric_difference_mi(self, sort): + index1 = MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])) + index2 = MultiIndex.from_tuples([("foo", 1), ("bar", 3)]) + result = index1.symmetric_difference(index2, sort=sort) + expected = MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)]) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "index2,expected", + [ + (Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])), + (Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])), + ], + ) + def test_symmetric_difference_missing(self, index2, expected, sort): + # GH#13514 change: {nan} - {nan} == {} + # (GH#6444, sorting of nans, is no longer an issue) + index1 = Index([1, np.nan, 2, 3]) + + result = index1.symmetric_difference(index2, sort=sort) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + def test_symmetric_difference_non_index(self, sort): + index1 = Index([1, 2, 3, 4], name="index1") + index2 = np.array([2, 3, 4, 5]) + expected = Index([1, 5], name="index1") + result = index1.symmetric_difference(index2, sort=sort) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + assert result.name == "index1" + + result = index1.symmetric_difference(index2, result_name="new_name", sort=sort) + expected.name = "new_name" + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + assert result.name == "new_name" + + def test_union_ea_dtypes(self, any_numeric_ea_and_arrow_dtype): + # GH#51365 + idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype) + idx2 = Index([3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype) + result = idx.union(idx2) + expected = Index([1, 2, 3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype) + tm.assert_index_equal(result, expected) + + def test_union_string_array(self, any_string_dtype): + idx1 = Index(["a"], dtype=any_string_dtype) + idx2 = Index(["b"], dtype=any_string_dtype) + result = idx1.union(idx2) + expected = Index(["a", "b"], dtype=any_string_dtype) + tm.assert_index_equal(result, expected) diff --git a/shared/package-files/38/38a95a88853e863ef6069d38ce33627f0bac383ff7fa663121fbf2bb2b3c73fa/_philox.pyi b/shared/package-files/38/38a95a88853e863ef6069d38ce33627f0bac383ff7fa663121fbf2bb2b3c73fa/_philox.pyi new file mode 100644 index 0000000000000000000000000000000000000000..26ce726ecf4a6f0e9fda4d596368a05da5629124 --- /dev/null +++ b/shared/package-files/38/38a95a88853e863ef6069d38ce33627f0bac383ff7fa663121fbf2bb2b3c73fa/_philox.pyi @@ -0,0 +1,36 @@ +from typing import Any, TypedDict + +from numpy import dtype, ndarray, uint64 +from numpy.random.bit_generator import BitGenerator, SeedSequence +from numpy._typing import _ArrayLikeInt_co + +class _PhiloxInternal(TypedDict): + counter: ndarray[Any, dtype[uint64]] + key: ndarray[Any, dtype[uint64]] + +class _PhiloxState(TypedDict): + bit_generator: str + state: _PhiloxInternal + buffer: ndarray[Any, dtype[uint64]] + buffer_pos: int + has_uint32: int + uinteger: int + +class Philox(BitGenerator): + def __init__( + self, + seed: None | _ArrayLikeInt_co | SeedSequence = ..., + counter: None | _ArrayLikeInt_co = ..., + key: None | _ArrayLikeInt_co = ..., + ) -> None: ... + @property + def state( + self, + ) -> _PhiloxState: ... + @state.setter + def state( + self, + value: _PhiloxState, + ) -> None: ... + def jumped(self, jumps: int = ...) -> Philox: ... + def advance(self, delta: int) -> Philox: ... diff --git a/shared/package-files/38/38ab10f7446bc4ff4557ae9b20f56cb22c940abc65a13fbed1e8dba0bfa56cb3/__init__.py b/shared/package-files/38/38ab10f7446bc4ff4557ae9b20f56cb22c940abc65a13fbed1e8dba0bfa56cb3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad785ffccdc766f8d829719de78f7837c9598490 --- /dev/null +++ b/shared/package-files/38/38ab10f7446bc4ff4557ae9b20f56cb22c940abc65a13fbed1e8dba0bfa56cb3/__init__.py @@ -0,0 +1,12 @@ +# 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/. + +"""hypothesis.utils is a package for things that you can consider part of the +semi-public Hypothesis API but aren't really the core point.""" diff --git a/shared/package-files/38/38ac6a6226295e0d8e1de5bd0a7e0d379ed37815c568a8e3b81231a82165ff41/linalg_ldl_factor_ex_meta_dispatch.h b/shared/package-files/38/38ac6a6226295e0d8e1de5bd0a7e0d379ed37815c568a8e3b81231a82165ff41/linalg_ldl_factor_ex_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..253e3d0b5039420d2d7905110cc48f9736b037e2 --- /dev/null +++ b/shared/package-files/38/38ac6a6226295e0d8e1de5bd0a7e0d379ed37815c568a8e3b81231a82165ff41/linalg_ldl_factor_ex_meta_dispatch.h @@ -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_ldl_factor_ex(const at::Tensor & self, bool hermitian=false, bool check_errors=false); +TORCH_API ::std::tuple linalg_ldl_factor_ex_out(at::Tensor & LD, at::Tensor & pivots, at::Tensor & info, const at::Tensor & self, bool hermitian=false, bool check_errors=false); +TORCH_API ::std::tuple linalg_ldl_factor_ex_outf(const at::Tensor & self, bool hermitian, bool check_errors, at::Tensor & LD, at::Tensor & pivots, at::Tensor & info); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/38/38aea2b8c03bdeb44e58bbb37c40940804c7958142a45b72c36115fc5b0181e2/smooth_l1_loss_meta_dispatch.h b/shared/package-files/38/38aea2b8c03bdeb44e58bbb37c40940804c7958142a45b72c36115fc5b0181e2/smooth_l1_loss_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8c6fdde84b89dcb823d2780e454327577281a142 --- /dev/null +++ b/shared/package-files/38/38aea2b8c03bdeb44e58bbb37c40940804c7958142a45b72c36115fc5b0181e2/smooth_l1_loss_meta_dispatch.h @@ -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 at::Tensor smooth_l1_loss(const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean, double beta=1.0); +TORCH_API at::Tensor & smooth_l1_loss_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean, double beta=1.0); +TORCH_API at::Tensor & smooth_l1_loss_outf(const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/38/38babc683d47badb02f309e92a7db721e479ef00c45761e2c33a9ff4f824a682/names.txt b/shared/package-files/38/38babc683d47badb02f309e92a7db721e479ef00c45761e2c33a9ff4f824a682/names.txt new file mode 100644 index 0000000000000000000000000000000000000000..8408cca818741b2ef0ff81cc835f6b47a29e7e67 --- /dev/null +++ b/shared/package-files/38/38babc683d47badb02f309e92a7db721e479ef00c45761e2c33a9ff4f824a682/names.txt @@ -0,0 +1,14 @@ +MDR = Number of derogator reports + +Acc = Credit card application accpeted (1=yes) + +Age = Age in years + 12ths of a year + +Income = Income divided by 10,000 + +Avgexp = Avg. monthly credit card expenditure + +Ownrent = Indiviual owns(1) or rents(0) home + +Selfempl = (1=yes, 0=no) + diff --git a/shared/package-files/38/38bad24b2965918e12bf4d082bedfb03677af20af83b09d626cc67d5a17dc535/compare.h b/shared/package-files/38/38bad24b2965918e12bf4d082bedfb03677af20af83b09d626cc67d5a17dc535/compare.h new file mode 100644 index 0000000000000000000000000000000000000000..0594b6002ff573afcb420b260c921a78277c9daf --- /dev/null +++ b/shared/package-files/38/38bad24b2965918e12bf4d082bedfb03677af20af83b09d626cc67d5a17dc535/compare.h @@ -0,0 +1,62 @@ +// 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/macros.h" + +namespace arrow { +namespace util { + +/// CRTP helper for declaring equality comparison. Defines operator== and operator!= +template +class EqualityComparable { + public: + ~EqualityComparable() { + static_assert( + std::is_same().Equals(std::declval())), + bool>::value, + "EqualityComparable depends on the method T::Equals(const T&) const"); + } + + template + bool Equals(const std::shared_ptr& other, Extra&&... extra) const { + if (other == NULLPTR) { + return false; + } + return cast().Equals(*other, std::forward(extra)...); + } + + struct PtrsEqual { + bool operator()(const std::shared_ptr& l, const std::shared_ptr& r) const { + return l->Equals(*r); + } + }; + + friend bool operator==(T const& a, T const& b) { return a.Equals(b); } + friend bool operator!=(T const& a, T const& b) { return !(a == b); } + + private: + const T& cast() const { return static_cast(*this); } +}; + +} // namespace util +} // namespace arrow diff --git a/shared/package-files/38/38bbed501dbd4db691425d7f631c970f1244150696de866a137a9be391f06d78/sort_compositeexplicitautograd_dispatch.h b/shared/package-files/38/38bbed501dbd4db691425d7f631c970f1244150696de866a137a9be391f06d78/sort_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0944e03bce1c7e7d8200c50d223fad7fffbcd06a --- /dev/null +++ b/shared/package-files/38/38bbed501dbd4db691425d7f631c970f1244150696de866a137a9be391f06d78/sort_compositeexplicitautograd_dispatch.h @@ -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 sort(const at::Tensor & self, int64_t dim=-1, bool descending=false); +TORCH_API ::std::tuple sort_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t dim=-1, bool descending=false); +TORCH_API ::std::tuple sort_outf(const at::Tensor & self, int64_t dim, bool descending, at::Tensor & values, at::Tensor & indices); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/38/38c4da5d9feeaf45773d58f596e0f056f0d59ff602d2c91ea57c518020ca7d88/screen3 b/shared/package-files/38/38c4da5d9feeaf45773d58f596e0f056f0d59ff602d2c91ea57c518020ca7d88/screen3 new file mode 100644 index 0000000000000000000000000000000000000000..a1f00e06ba5c7227d0ce4836ce8b4bfd6643a5be Binary files /dev/null and b/shared/package-files/38/38c4da5d9feeaf45773d58f596e0f056f0d59ff602d2c91ea57c518020ca7d88/screen3 differ diff --git a/shared/package-files/38/38cbeb706c8d92bce313f1eb423bdee15d8b79be925d2bf0b3d1ff464d7107cf/group_batch_fusion.py b/shared/package-files/38/38cbeb706c8d92bce313f1eb423bdee15d8b79be925d2bf0b3d1ff464d7107cf/group_batch_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..cd06a1f13a1aa4011c346d4136709862f4516cd8 --- /dev/null +++ b/shared/package-files/38/38cbeb706c8d92bce313f1eb423bdee15d8b79be925d2bf0b3d1ff464d7107cf/group_batch_fusion.py @@ -0,0 +1,1059 @@ +import collections +import logging +import operator +from collections import OrderedDict +from typing import ( + Any, + DefaultDict, + Deque, + Dict, + Iterable, + Iterator, + List, + Optional, + Set, + Tuple, +) + +import torch +from torch._dynamo.utils import counters + +from .. import config +from ..pattern_matcher import ( + CallFunctionVarArgs, + get_arg_value, + stable_topological_sort, +) + +try: + # importing this will register fbgemm lowerings for inductor + import deeplearning.fbgemm.fbgemm_gpu.fb.inductor_lowerings # noqa: F401 + + has_fbgemm = True +except Exception: + has_fbgemm = False + pass + +aten = torch.ops.aten + +log = logging.getLogger(__name__) + +MIN_FUSE_SET_SIZE = 5 +MAX_FUSE_SET_SIZE = 300 +MAX_FUSE_SEARCH_DEPTH = 5 +# The maximum tensor size that can go into the fusion group +MAX_FUSE_TENSOR_SIZE_GROUP_LINEAR = 4096 + +# exclude these nodes from BFS +# excluding get item improves optimizer compilation time by 60s +SEARCH_EXCLUSIONS = {operator.getitem} + + +default_graph_search_options = { + "min_fuse_set_size": MIN_FUSE_SET_SIZE, + "max_fuse_set_size": MAX_FUSE_SET_SIZE, + "max_fuse_search_depth": MAX_FUSE_SEARCH_DEPTH, + "max_fuse_tensor_size_group_linear": MAX_FUSE_TENSOR_SIZE_GROUP_LINEAR, +} + +graph_search_options = default_graph_search_options + + +def update_stack_example_value(node, metadata, dim=0, op=torch.stack): + """ + Update the example value of the node in the graph to enable followup split cat opt. + """ + if node is not None and hasattr(node, "meta"): + if op == torch.stack: + example_value = torch.stack(metadata, dim=dim) + elif op == torch.unbind: + example_value = torch.unbind(metadata, dim=dim) # type: ignore[assignment] + else: + return + node.meta["example_value"] = example_value + + +def update_pointwise_example_value(pointwise_node, input, other, op): + """ + Update the example value of the add node in the graph to enable followup split cat opt. + """ + if pointwise_node is not None and hasattr(pointwise_node, "meta"): + if op == torch.add: + example_value = torch.add(input, other) + elif op == torch.mul: + example_value = torch.mul(input, other) + else: + return + pointwise_node.meta["example_value"] = example_value + + +class GroupBatchFusionBase: + def __init__(self, **kwargs): + self.graph_search_options = kwargs.pop( + "graph_search_options", default_graph_search_options + ) + + def match(self, node): + raise NotImplementedError("match called on base") + + def fuse(self, graph, subset): + raise NotImplementedError("fuse called on base") + + +PRE_GRAD_FUSIONS: Dict[str, GroupBatchFusionBase] = dict() +POST_GRAD_FUSIONS: Dict[str, GroupBatchFusionBase] = dict() + + +def register_fusion(name: str, pre_grad=True): + def decorator(fusion_cls: GroupBatchFusionBase): + if pre_grad: + PRE_GRAD_FUSIONS[name] = fusion_cls + else: + POST_GRAD_FUSIONS[name] = fusion_cls + return fusion_cls + + return decorator + + +def list_group_batch_fusions(pre_grad=True) -> List[str]: + if pre_grad: + return list(PRE_GRAD_FUSIONS.keys()) + else: + return list(POST_GRAD_FUSIONS.keys()) + + +def decompose_stack(graph: torch.fx.GraphModule, input_tensors: List[Any]) -> Any: + unsqueezed_inputs = [] + for input_tensor in input_tensors: + unsqueezed_input = graph.call_function( + aten.unsqueeze, args=(input_tensor,), kwargs={"dim": 0} + ) + unsqueezed_inputs.append(unsqueezed_input) + stacked_inputs = graph.call_function( + aten.cat, args=(unsqueezed_inputs,), kwargs={"dim": 0} + ) + return stacked_inputs + + +class GroupFusion(GroupBatchFusionBase): + """ + Fuse ops in a group way, e.g, fuse mm/addmm of arbitrary input shapes with fbgemm.gmm. + """ + + pass + + +class BatchFusion(GroupBatchFusionBase): + """ + Fuse ops in a batch way, e.g, fuse mm/addmm of same input shapes with bmm. + """ + + pass + + +class BatchPointwiseOpsFusionFactory(BatchFusion): + def __init__(self, op, **kwargs): + super().__init__(**kwargs) + self.op = op + + +@register_fusion("batch_linear_post_grad", pre_grad=False) +class PostGradBatchLinearFusion(BatchFusion): + """ + Fuse ops in a batch way in post grad (aten level). + """ + + def _addmm_node_can_be_fused(self, node: torch.fx.Node) -> bool: + return ( + node.kwargs.get("beta", 1.0) == 1.0 and node.kwargs.get("alpha", 1.0) == 1.0 # type: ignore[return-value] + ) + + def _is_input_2d(self, input: torch.fx.Node) -> bool: + input_shapes = input.meta["tensor_meta"].shape + return ( + len(input_shapes) == 2 + and isinstance(input_shapes[0], int) + and isinstance(input_shapes[1], int) + ) + + def match(self, node: torch.fx.Node) -> Optional[Tuple[str, int, int, int, bool]]: + if CallFunctionVarArgs(aten.mm).match(node): + input_m, weight_m = node.args + bias_m = None + + elif CallFunctionVarArgs(aten.addmm.default).match( + node + ) and self._addmm_node_can_be_fused(node): + bias_m, input_m, weight_m = node.args + else: + return None + + # only handle the cases where inputs are 2D tensors + if not self._is_input_2d(input_m) or not self._is_input_2d(weight_m): # type: ignore[arg-type] + return None + m, k = input_m.meta["tensor_meta"].shape # type: ignore[union-attr] + n = weight_m.meta["tensor_meta"].shape[1] # type: ignore[union-attr] + batch_key = ("batch_linear", m, k, n, bias_m is not None) + return batch_key + + def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]): + batch_inputs = [] + batch_weights = [] + batch_biases = [] + batch_nodes = [] + + for node in subset: + if CallFunctionVarArgs(aten.addmm.default).match(node): + bias, input, weight = node.args + elif CallFunctionVarArgs(aten.mm.default).match(node): + input, weight = node.args + bias = None + batch_nodes.append(node) + batch_inputs.append(input) # type: ignore[possibly-undefined] + batch_weights.append(weight) # type: ignore[possibly-undefined] + batch_biases.append(bias) # type: ignore[possibly-undefined] + + with graph.inserting_before(subset[-1]): + fused_inputs = decompose_stack(graph, batch_inputs) + fused_weights = decompose_stack(graph, batch_weights) + fused_bmm = graph.call_function( + aten.bmm, + args=(fused_inputs, fused_weights), + ) + + for i, original_mm in enumerate(batch_nodes): + has_bias = False + with graph.inserting_after(fused_bmm): + new_mm = graph.call_function(aten.select, args=((fused_bmm, 0, i))) + if batch_biases[i]: + has_bias = True + new_bias_add = graph.call_function( + aten.add, args=((batch_biases[i], new_mm)) + ) + new_mm_cont = new_bias_add if has_bias else new_mm # type: ignore[possibly-undefined] + original_mm.replace_all_uses_with(new_mm_cont) + new_mm_cont.meta.update(original_mm.meta) + graph.erase_node(original_mm) + + +@register_fusion("group_linear", pre_grad=False) +class GroupLinearFusion(GroupFusion): + def _addmm_node_can_be_fused(self, node: torch.fx.Node): + input_shape = node.args[1].meta["tensor_meta"].shape # type: ignore[union-attr] + weight_shape = node.args[2].meta["tensor_meta"].shape # type: ignore[union-attr] + return ( + node.kwargs.get("beta", 1.0) == 1.0 + and node.kwargs.get("alpha", 1.0) == 1.0 + and len(input_shape) == 2 + and len(weight_shape) == 2 + and all(x % 2 == 0 for x in input_shape + weight_shape) + and all( + shape <= self.graph_search_options["max_fuse_tensor_size_group_linear"] + for shape in input_shape + weight_shape + ) + ) + + def _mm_node_can_be_fused(self, node: torch.fx.Node): + input_shape = node.args[0].meta["tensor_meta"].shape # type: ignore[union-attr] + weight_shape = node.args[1].meta["tensor_meta"].shape # type: ignore[union-attr] + return ( + len(input_shape) == 2 + and len(weight_shape) == 2 + and all(x % 2 == 0 for x in input_shape + weight_shape) + and all( + shape <= self.graph_search_options["max_fuse_tensor_size_group_linear"] + for shape in input_shape + weight_shape + ) + ) + + def match(self, node: torch.fx.Node) -> Optional[Tuple[str, bool]]: + if CallFunctionVarArgs(aten.mm.default).match( + node + ) and self._mm_node_can_be_fused(node): + group_key = ("group_linear", True) + elif CallFunctionVarArgs(aten.addmm.default).match( + node + ) and self._addmm_node_can_be_fused(node): + bias = node.args[0] + group_key = ("group_linear", bias is None) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]): + group_inputs = [] + group_weights = [] + group_biases = [] + group_nodes = [] + for node in subset: + if CallFunctionVarArgs(aten.addmm.default).match(node): + bias, input, weight = node.args + else: + assert CallFunctionVarArgs(aten.mm.default).match(node) + input, weight = node.args + bias = None + + group_nodes.append(node) + group_inputs.append(input) + group_weights.append(weight) + group_biases.append(bias) + + if all(bias is None for bias in group_biases): + group_biases = None # type: ignore[assignment] + group_biases: Optional[List[Any]] + + with graph.inserting_before(subset[0]): + fused_mm = graph.call_function( + torch.ops.fbgemm.gmm.default, + args=(group_inputs, group_weights, group_biases), + kwargs={"smart_fused": True}, + ) + + for i, original_mm in enumerate(group_nodes): + with graph.inserting_after(fused_mm): + new_mm = graph.call_function(operator.getitem, args=(fused_mm, i)) + original_mm.replace_all_uses_with(new_mm) + new_mm.meta.update(original_mm.meta) + graph.erase_node(original_mm) + + +class BatchPointwiseOpsPostGradFusion(BatchPointwiseOpsFusionFactory): + """ + Batch pointwise operator (e.g., add, mul) in post grad pass. + """ + + def __init__(self, op, **kwargs): + super().__init__(op, **kwargs) + self.op = op + + def _pointwise_node_can_be_fused(self, node: torch.fx.Node): + # note: we only consider the case where the inputs are tensors + # for mixed precision training, we need to make sure the inputs + # of the aten.cat when do the stack should be the same dtype + # otherwise, the output of the aten.cat may be not the same as + # its inputs, and cause dtype not same error in mm or addmm + input, other = node.args + return ( + input.meta["tensor_meta"].shape == other.meta["tensor_meta"].shape # type: ignore[union-attr] + if hasattr(input, "meta") + and hasattr(other, "meta") + and "tensor_meta" in input.meta # type: ignore[union-attr] + and "tensor_meta" in other.meta # type: ignore[union-attr] + else False + ) + + def match(self, node: torch.fx.Node): + if CallFunctionVarArgs(self.op).match( + node + ) and self._pointwise_node_can_be_fused(node): + alpha = node.kwargs.get("alpha", 1.0) + rounding_mode = node.kwargs.get("rounding_mode", None) + input, other = node.args + shape = list(input.meta["tensor_meta"].shape) # type: ignore[union-attr] + group_key = ( + "batch_" + self.op.__name__.lower() + "_post_grad", + str(shape), + str(input.meta["tensor_meta"].dtype), # type: ignore[union-attr] + str(other.meta["tensor_meta"].dtype), # type: ignore[union-attr] + str(alpha), + str(rounding_mode), + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]): + batch_inputs, batch_others = [], [] + alpha = subset[0].kwargs.get("alpha", 1.0) + + for node in subset: + input, other = node.args + batch_inputs.append(input) + batch_others.append(other) + + with graph.inserting_before(subset[0]): + stack_inputs = decompose_stack(graph, batch_inputs) + stack_others = decompose_stack(graph, batch_others) + + batch_op = graph.call_function( + self.op, + args=(stack_inputs, stack_others), + kwargs={"alpha": alpha} if self.op == aten.add.Tensor else {}, + ) + for i, original_add in enumerate(subset): + with graph.inserting_after(batch_op): + new_add = graph.call_function( + torch.ops.aten.select, args=((batch_op, 0, i)) + ) + original_add.replace_all_uses_with(new_add) + new_add.meta.update(original_add.meta) + graph.erase_node(original_add) + + +@register_fusion("batch_linear_lhs") +class BatchLinearLHSFusion(BatchFusion): + """ + Batch linear left-hand side fusion. This pass tries to fuse the following patterns: + + torch.nn.functional.linear(x, w1), linear(x, w2),... * linear(x, wn) + -> torch.mm(x, torch.cat([w1, w2,... * wn]).transpose(0, 1)) + + We have a separate pass to eliminate contiguous transpose in a generic way. + """ + + def match(self, node: torch.fx.Node) -> Optional[Tuple[str, bool, Any]]: + if CallFunctionVarArgs(torch.nn.functional.linear).match( + node + ) and is_linear_node_can_be_fused(node): + input = get_arg_value(node, 0, "input") + bias = get_arg_value(node, 2, "bias") + group_key = ("batch_linear_lhs", bias is None, input) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]): + batch_nodes = [] + batch_input = None + batch_weights = [] + batch_biases = [] + split_sections = [] + for node in subset: + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + bias = get_arg_value(node, 2, "bias") + batch_nodes.append(node) + if batch_input is None: + batch_input = input + else: + assert batch_input is input + batch_weights.append(weight) + if bias: + batch_biases.append(bias) + split_sections.append(weight.meta["example_value"].shape[0]) + + with graph.inserting_before(subset[0]): + cat_weights = graph.call_function( + torch.cat, args=(batch_weights,), kwargs={"dim": 0} + ) + transposed_weights = graph.call_function( + torch.transpose, args=(cat_weights, 0, 1) + ) + if len(batch_biases) > 0: + cat_biases = graph.call_function( + torch.cat, args=(batch_biases,), kwargs={"dim": 0} + ) + fused_lhs = graph.call_function( + torch.addmm, + args=(cat_biases, batch_input, transposed_weights), + ) + else: + fused_lhs = graph.call_function( + torch.mm, + args=(batch_input, transposed_weights), + ) + fused_lhs_list = graph.call_function( + torch.split, args=(fused_lhs, split_sections), kwargs={"dim": 1} + ) + + for i, node in enumerate(batch_nodes): + with graph.inserting_after(fused_lhs_list): + new_node = graph.call_function( + operator.getitem, args=(fused_lhs_list, i) + ) + node.replace_all_uses_with(new_node) + new_node.meta.update(node.meta) + graph.erase_node(node) + + +def is_node_meta_valid(node: Optional[torch.fx.Node]): + if node is None: + return True + if "example_value" not in node.meta: + return False + return True + + +def is_linear_node_can_be_fused(node: torch.fx.Node): + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + return ( + is_node_meta_valid(node) + and is_node_meta_valid(input) + and is_node_meta_valid(weight) + and len(input.meta["example_value"].shape) == 2 + and len(weight.meta["example_value"].shape) == 2 + ) + + +@register_fusion("batch_linear") +class PreGradBatchLinearFusion(BatchFusion): + """ + Batch linear fusion in pre grad pass. + Fuse linear with same size with torch.baddmm + """ + + def _getitem_args(self, getitem_node: torch.fx.Node): + if getitem_node.target != operator.__getitem__ or ( + getitem_node.op != "call_function" + ): + return None + return getitem_node.args[0] + + def match(self, node: torch.fx.Node): + if CallFunctionVarArgs(torch.nn.functional.linear).match( + node + ) and is_linear_node_can_be_fused(node): + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + bias = get_arg_value(node, 2, "bias") + group_key = ( + "batch_linear_pre_grad", + self._getitem_args(input), + str(input.meta["example_value"].shape), + str(weight.meta["example_value"].shape), + bias is None, + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]): + batch_nodes = [] + batch_inputs = [] + batch_weights = [] + batch_biases = [] + batch_inputs_metadata = [] + batch_weights_metadata = [] + batch_biases_metadata = [] + for node in subset: + batch_nodes.append(node) + input = get_arg_value(node, 0, "input") + batch_inputs.append(input) + batch_inputs_metadata.append(input.meta["example_value"]) + weight = get_arg_value(node, 1, "weight") + batch_weights.append(weight) + batch_weights_metadata.append(weight.meta["example_value"]) + bias = get_arg_value(node, 2, "bias") + batch_biases.append(bias) + if bias is not None and hasattr(bias, "meta"): + batch_biases_metadata.append(bias.meta["example_value"]) + + with graph.inserting_before(subset[0]): + stack_inputs = graph.call_function( + torch.stack, args=(batch_inputs,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_inputs, batch_inputs_metadata) + stack_weights = graph.call_function( + torch.stack, args=(batch_weights,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_weights, batch_weights_metadata) + transpose_weight = graph.call_function( + torch.transpose, args=(stack_weights, 1, 2) + ) + if all(bias is None for bias in batch_biases): + bmm = graph.call_function( + torch.bmm, + args=(stack_inputs, transpose_weight), + ) + else: + stack_biases = graph.call_function( + torch.stack, args=(batch_biases,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_biases, batch_biases_metadata) + unsqueeze_biases = graph.call_function( + torch.unsqueeze, args=(stack_biases, 1) + ) + bmm = graph.call_function( + torch.baddbmm, + args=(unsqueeze_biases, stack_inputs, transpose_weight), + ) + + bmm = graph.call_function(torch.unbind, args=(bmm,), kwargs={"dim": 0}) + for i, linear in enumerate(batch_nodes): + with graph.inserting_after(bmm): + getitem = graph.call_function(operator.getitem, args=(bmm, i)) + linear.replace_all_uses_with(getitem) + getitem.meta.update(linear.meta) + graph.erase_node(linear) + + +@register_fusion("batch_layernorm") +class BatchLayernormFusion(BatchFusion): + """ + Batch layer norm fusion in pre grad pass + """ + + def match(self, node: torch.fx.Node): + if CallFunctionVarArgs(torch.nn.functional.layer_norm).match(node): + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 2, "weight") + bias = get_arg_value(node, 3, "bias") + group_key = ( + ( + "batch_layernorm", + str(input.meta["example_value"].shape), + str(weight.meta["example_value"].shape) + if weight is not None + else "", + str(bias.meta["example_value"].shape) if bias is not None else "", + str(get_arg_value(node, 1, "normalized_shape")), + str(get_arg_value(node, 4, "eps")), + ) + if "example_value" in input.meta + and is_node_meta_valid(weight) + and is_node_meta_valid(bias) + else None + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]): + group_inputs = [] + group_shapes = [] + group_weights = [] + group_biases = [] + group_epss = [] + group_nodes = [] + group_inputs_metadata = [] + group_biases_metadata = [] + group_weights_metadata = [] + for node in subset: + group_nodes.append(node) + input = get_arg_value(node, 0, "input") + group_inputs.append(input) + group_inputs_metadata.append(input.meta["example_value"]) + group_shapes.append(get_arg_value(node, 1, "normalized_shape")) + weight = get_arg_value(node, 2, "weight") + group_weights.append(weight) + if weight is not None and hasattr(weight, "meta"): + group_weights_metadata.append(weight.meta["example_value"]) + bias = get_arg_value(node, 3, "bias") + group_biases.append(bias) + if bias is not None and hasattr(bias, "meta"): + group_biases_metadata.append(bias.meta["example_value"]) + eps = get_arg_value(node, 4, "eps") + if eps is None: + eps = 1e-5 + group_epss.append(eps) + stack_dim = -1 - len(group_shapes[-1]) + + if all(bias is None for bias in group_biases): + group_biases = None # type: ignore[assignment] + group_biases: Optional[List[Any]] + if all(weight is None for weight in group_weights): + group_weights = None # type: ignore[assignment] + group_weights: Optional[List[Any]] + assert all( + eps == group_epss[0] for eps in group_epss + ), "all epsilon values must be equal" + + with graph.inserting_before(subset[0]): + stack_input = graph.call_function( + torch.stack, args=(group_inputs,), kwargs={"dim": stack_dim} + ) + update_stack_example_value(stack_input, group_inputs_metadata, stack_dim) + if group_weights is not None: + stack_weight = graph.call_function( + torch.stack, args=(group_weights,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_weight, group_weights_metadata) + else: + stack_weight = None + if group_biases is not None: + stack_bias = graph.call_function( + torch.stack, args=(group_biases,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_bias, group_biases_metadata) + else: + stack_bias = None + + batch_layer_norm = graph.call_function( + torch.nn.functional.layer_norm, + args=(stack_input, group_shapes[-1]), + kwargs={"eps": group_epss[-1]}, + ) + batch_layer_norm.meta["example_value"] = stack_input.meta["example_value"] + + if group_weights is not None and group_biases is not None: + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + batch_layer_norm = graph.call_function( + torch.mul, args=(stack_weight, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + stack_weight.meta["example_value"], + previous_batch_layer_norm_meta, + torch.mul, + ) + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + batch_layer_norm = graph.call_function( + torch.add, args=(stack_bias, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + stack_bias.meta["example_value"], + previous_batch_layer_norm_meta, + torch.add, + ) + elif group_weights is not None and group_biases is None: + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + batch_layer_norm = graph.call_function( + torch.mul, args=(stack_weight, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + stack_weight.meta["example_value"], + previous_batch_layer_norm_meta, + torch.mul, + ) + elif group_weights is None and group_biases is not None: + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + batch_layer_norm = graph.call_function( + torch.add, args=(stack_bias, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + stack_bias.meta["example_value"], + previous_batch_layer_norm_meta, + torch.add, + ) + + batch_layer_norm_unbind = graph.call_function( + torch.unbind, + args=(batch_layer_norm,), + kwargs={"dim": stack_dim}, + ) + update_stack_example_value( + batch_layer_norm_unbind, + batch_layer_norm.meta["example_value"], + op=torch.unbind, + dim=stack_dim, + ) + + for i, node in enumerate(group_nodes): + with graph.inserting_after(batch_layer_norm_unbind): + new_node = graph.call_function( + operator.getitem, args=(batch_layer_norm_unbind, i) + ) + node.replace_all_uses_with(new_node) + new_node.meta.update(node.meta) + graph.erase_node(node) + + +class BatchPointwiseOpsPreGradFusion(BatchPointwiseOpsFusionFactory): + """ + Batch poinwise ops (e.g., sigmoid, relu, tanh) fusion in pre grad pass. + We fuse it in random place, and the introduced stack node may be merged in split cat. + """ + + def __init__(self, op, **kwargs): + super().__init__(op, **kwargs) + self.op = op + + def match(self, node: torch.fx.Node): + input = get_arg_value(node, 0, "input") + if CallFunctionVarArgs(self.op).match(node) and is_node_meta_valid(node): + # for relu op, we also use the inplace to construct the key + group_key = ( + "batch_" + self.op.__name__.lower() + "_pre_grad", + str(input.meta["example_value"].shape), + str(node.kwargs.get("inplace", False)), + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]): + batch_nodes = [] + batch_inputs = [] + batch_inputs_metadata = [] + + for node in subset: + batch_nodes.append(node) + input = get_arg_value(node, 0, "input") + batch_inputs.append(input) + batch_inputs_metadata.append(input.meta["example_value"]) + + with graph.inserting_before(subset[0]): + stack_inputs = graph.call_function( + torch.stack, args=(batch_inputs,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_inputs, batch_inputs_metadata) + if self.op == torch.nn.functional.relu: + batch_op = graph.call_function( + self.op, + args=(stack_inputs,), + kwargs={"inplace": subset[0].kwargs.get("inplace", False)}, + ) + else: + batch_op = graph.call_function( + self.op, + args=(stack_inputs,), + ) + unbind_op = graph.call_function( + torch.unbind, args=(batch_op,), kwargs={"dim": 0} + ) + for i, node in enumerate(batch_nodes): + with graph.inserting_after(unbind_op): + getitem = graph.call_function(operator.getitem, args=(unbind_op, i)) + node.replace_all_uses_with(getitem) + getitem.meta.update(node.meta) + graph.erase_node(node) + + +@register_fusion("batch_tanh") +class BatchTanhPreGradFusion(BatchPointwiseOpsPreGradFusion): + def __init__(self, **kwargs): + super().__init__(torch.tanh, **kwargs) + + +@register_fusion("batch_sigmoid") +class BatchSigmoidPreGradFusion(BatchPointwiseOpsPreGradFusion): + def __init__(self, **kwargs): + super().__init__(torch.sigmoid, **kwargs) + + +@register_fusion("batch_relu") +class BatchReLuPreGradFusion(BatchPointwiseOpsPreGradFusion): + def __init__(self, **kwargs): + super().__init__(torch.nn.functional.relu, **kwargs) + + +@register_fusion("batch_aten_add", pre_grad=False) +class BatchAddPostGradFusion(BatchPointwiseOpsPostGradFusion): + def __init__(self, **kwargs): + super().__init__(aten.add.Tensor, **kwargs) + + +@register_fusion("batch_aten_sub", pre_grad=False) +class BatchSubPostGradFusion(BatchPointwiseOpsPostGradFusion): + def __init__(self, **kwargs): + super().__init__(aten.sub.Tensor, **kwargs) + + +@register_fusion("batch_aten_div", pre_grad=False) +class BatchDivPostGradFusion(BatchPointwiseOpsPostGradFusion): + def __init__(self, **kwargs): + super().__init__(aten.div.Tensor, **kwargs) + + +@register_fusion("batch_aten_mul", pre_grad=False) +class BatchMulPostGradFusion(BatchPointwiseOpsPostGradFusion): + def __init__(self, **kwargs): + super().__init__(aten.mul.Tensor, **kwargs) + + +class _OrderedSet: + def __init__(self, param=None): + if param: + self.rep = OrderedDict({k: None for k in param}) + else: + self.rep = OrderedDict() + + def __contains__(self, o): + return o in self.rep + + def __len__(self): + return self.rep.__len__() + + def append(self, o): + self.rep[o] = None + + def __iter__(self): + return self.rep.keys().__iter__() + + +def find_independent_subset_greedy( + node_list: Iterable[torch.fx.Node], + graph_search_options: Dict[str, Any], +) -> Iterator[Iterable[torch.fx.Node]]: + """ + Yields a list of subsets of `node_list` where no element in the subset + depends on any other element in the subset. This results in a set of + independent nodes which can be fused together. + + The order of `node_list` is preserved within each subset so we can benefit + from split-cat elimination in later passes. + + During iteration it is only safe to mutate the graph by changing the nodes + that have been returned. + + graph_search_options: + - min_fuse_set_size: Minimum size of the subset to consider. Subsets below + this size will be ignored. + - max_fuse_set_size: Maximum size of the subset to consider. Subsets will + be broken to be at most this size. + """ + + # Compute all the children of `node` which are members of + # `interesting_nodes`. + def find_dependent_nodes(node, interesting_nodes): + visited_node_set: Set[torch.fx.Node] = {node} + dep_set: Set[torch.fx.Node] = set() + + work = [node] + while work: + node = work.pop() + for input_node in node.all_input_nodes: + if input_node in interesting_nodes: + dep_set.add(input_node) + + if input_node not in visited_node_set: + visited_node_set.add(input_node) + work.append(input_node) + + return dep_set + + min_fuse_set_size = graph_search_options["min_fuse_set_size"] + max_fuse_set_size = graph_search_options["max_fuse_set_size"] + + # node_list needs to be a set because we only track the nodes that are left + # in it (and we want to do the `in` on a set, not a list). But we want to + # keep the correct order. + node_list = _OrderedSet(node_list) + + cache: Dict[torch.fx.Node, Set[torch.fx.Node]] = {} + while node_list: + subset: List[torch.fx.Node] = [] + subset_deps: Set[torch.fx.Node] = set() + + next_round_node_list = _OrderedSet() + for node in node_list: + if len(subset) >= max_fuse_set_size or node in subset_deps: + next_round_node_list.append(node) + continue + + dep_set = cache.pop(node, None) + if dep_set is None: + dep_set = find_dependent_nodes(node, node_list) + + if not dep_set.intersection(subset): + subset.append(node) + subset_deps.update(dep_set) + else: + next_round_node_list.append(node) + cache[node] = dep_set + + if len(subset) >= min_fuse_set_size: + # Careful here - the caller uses the subsets to fuse nodes together + # so we need to clear any cache entry that contains one of the + # returned nodes because the dependency list could be different + # (larger) after the merge. + cache = {k: v for k, v in cache.items() if v.isdisjoint(subset)} + yield subset + + node_list = next_round_node_list + + +def get_fusion_candidates( + rule: GroupBatchFusionBase, root_node: torch.fx.Node, fused_set: Set[torch.fx.Node] +) -> DefaultDict[Any, List[torch.fx.Node]]: + """ + Search fusion candidates for a specific rule using BFS starting from the root node. + We only search the subgraph within graph_search_options["max_fuse_search_depth"]. + """ + q: Deque[Tuple[int, torch.fx.Node]] = collections.deque() + + candidate_dict: DefaultDict[Any, List[torch.fx.Node]] = collections.defaultdict( + list + ) + + if root_node.target in SEARCH_EXCLUSIONS: + return candidate_dict + + visited_set: Set[torch.fx.Node] = set() + + for next_node in root_node.all_input_nodes: + q.append((1, next_node)) + visited_set.add(next_node) + + while len(q) > 0: + depth, node = q.popleft() + + if node in fused_set: + continue + + key = rule.match(node) + if key is not None: + candidate_nodes = candidate_dict[key] + if node not in candidate_nodes: + candidate_nodes.append(node) + else: + if depth < rule.graph_search_options["max_fuse_search_depth"]: + for next_node in node.all_input_nodes: + if next_node not in visited_set: + visited_set.add(next_node) + q.append((depth + 1, next_node)) + + return candidate_dict + + +def apply_group_batch_fusion(graph: torch.fx.GraphModule, rule: GroupBatchFusionBase): + stable_topological_sort(graph) # type: ignore[arg-type] + fused_set: Set[torch.fx.Node] = set() + + for node in reversed(graph.nodes): + candidates = get_fusion_candidates(rule, node, fused_set) + + for key, candidate_nodes in candidates.items(): + if len(candidate_nodes) < rule.graph_search_options["min_fuse_set_size"]: + continue + + for subset in find_independent_subset_greedy( + candidate_nodes, rule.graph_search_options + ): + rule.fuse(graph, subset) + fused_set.update(subset) + if isinstance(rule, GroupFusion): + counters["inductor"]["group_fusion"] += 1 + elif isinstance(rule, BatchFusion): + counters["inductor"]["batch_fusion"] += 1 + else: + counters["inductor"]["unknown_group_batch_fusion"] += 1 + + log.debug( + f"{rule.__class__.__name__}: key = {key}; subset size = {len(list(subset))}" # noqa: G004 + ) + + +def generate_fusion_from_config(config_options: Dict[str, Any], pre_grad=True): + fusions: List[GroupBatchFusionBase] = [] + for name, options in config_options.items(): + fusion_cls = PRE_GRAD_FUSIONS[name] if pre_grad else POST_GRAD_FUSIONS[name] + _options = graph_search_options.copy() + _options.update(options) + fusions.append(fusion_cls(graph_search_options=_options)) # type: ignore[operator] + return fusions + + +def group_batch_fusion_passes(graph: torch.fx.Graph, pre_grad=True): + fusions: List[GroupBatchFusionBase] = [] + # we keep all current pre grad fusions to keep + # current implementation, will remove this later + if pre_grad: + fusions += generate_fusion_from_config( + config.pre_grad_fusion_options, pre_grad=True + ) + else: + fbgemm_fusion_keys = [ + x + for x in config.post_grad_fusion_options + if config.post_grad_fusion_options[x].get("require_fbgemm", False) + ] + fbgemm_fusions = { + fusion: config.post_grad_fusion_options[fusion] + for fusion in fbgemm_fusion_keys + } + non_fbgemm_fusions = { + fusion: config.post_grad_fusion_options[fusion] + for fusion in config.post_grad_fusion_options.keys() + if fusion not in fbgemm_fusion_keys + } + fusions += generate_fusion_from_config(non_fbgemm_fusions, pre_grad=False) + if has_fbgemm: + fusions += generate_fusion_from_config(fbgemm_fusions, pre_grad=False) + + for rule in fusions: + apply_group_batch_fusion(graph, rule) # type: ignore[arg-type] diff --git a/shared/package-files/38/38cddb54195fd7b304dfdd85550ba4fd96730bc6251763acb1d8c4a51894859d/test_cross_val.py b/shared/package-files/38/38cddb54195fd7b304dfdd85550ba4fd96730bc6251763acb1d8c4a51894859d/test_cross_val.py new file mode 100644 index 0000000000000000000000000000000000000000..053f122948660d0034f8c6d9ffc98c5cead92b08 --- /dev/null +++ b/shared/package-files/38/38cddb54195fd7b304dfdd85550ba4fd96730bc6251763acb1d8c4a51894859d/test_cross_val.py @@ -0,0 +1,224 @@ +""" +Tests corresponding to sandbox.tools.cross_val +""" +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +import pytest + +from statsmodels.sandbox.tools.cross_val import ( + KFold, + KStepAhead, + LeaveOneLabelOut, + LeaveOneOut, + LeavePOut, + split, +) + + +def test_leave_one_out(): + loo = LeaveOneOut(4) + folds = list(loo) + assert_equal(len(folds), 4) + for i, (train, test) in enumerate(folds): + assert_equal(test.sum(), 1) + assert test[i] + # train/test partition the full index set with no overlap + assert_array_equal(train, ~test) + assert_equal(train.sum() + test.sum(), 4) + + +def test_leave_one_out_repr(): + loo = LeaveOneOut(4) + assert repr(loo) == "statsmodels.sandbox.tools.cross_val.LeaveOneOut(n=4)" + + +def test_leave_p_out(): + lpo = LeavePOut(4, 2) + folds = list(lpo) + # C(4, 2) == 6 combinations + assert_equal(len(folds), 6) + for train, test in folds: + assert_equal(test.sum(), 2) + assert_equal(train.sum(), 2) + assert_array_equal(train, ~test) + # every 2-combination of indices appears as a test set exactly once + seen = {tuple(np.flatnonzero(test)) for _, test in folds} + assert_equal(len(seen), 6) + + +def test_leave_p_out_repr(): + lpo = LeavePOut(4, 2) + assert repr(lpo) == "statsmodels.sandbox.tools.cross_val.LeavePOut(n=4, p=2)" + + +def test_kfold_partitions_all_indices_without_overlap(): + # regression test for the fold-size formula, not just the total count + for n, k in [(10, 3), (5, 2), (7, 4), (12, 5)]: + kf = KFold(n, k) + folds = list(kf) + assert_equal(len(folds), k) + seen = np.zeros(n, dtype=int) + for train, test in folds: + assert_array_equal(train, ~test) + seen += test.astype(int) + # each index appears in exactly one test fold + assert_array_equal(seen, np.ones(n, dtype=int)) + + +def test_kfold_fold_sizes_use_ceil_not_trunc(): + # KFold's docstring claims "All the folds have size trunc(n/k), the + # last one has the complementary", but the implementation computes + # j = ceil(n / k) and gives the *last* fold the (smaller) remainder, + # not trunc(n/k). Document the actual behavior here since it disagrees + # with the docstring. + kf = KFold(10, 3) + sizes = [int(test.sum()) for _, test in kf] + assert_equal(sizes, [4, 4, 2]) # ceil(10/3) == 4, not trunc(10/3) == 3 + + kf = KFold(5, 2) + sizes = [int(test.sum()) for _, test in kf] + assert_equal(sizes, [3, 2]) # ceil(5/2) == 3, not trunc(5/2) == 2 + + +def test_kfold_k_equal_one_is_degenerate(): + # k=1 is accepted by the k > 0 check, but produces a single fold where + # the entire sample is the test set and nothing is left to train on. + kf = KFold(5, 1) + folds = list(kf) + assert_equal(len(folds), 1) + train, test = folds[0] + assert_equal(train.sum(), 0) + assert_equal(test.sum(), 5) + + +def test_kfold_invalid_k_raises_assertion_error_not_value_error(): + # BUG: KFold validates its arguments with + # assert k > 0, ValueError("cannot have k below 1") + # This constructs a ValueError but never raises it; `assert` raises + # AssertionError using that ValueError instance as its message. So + # callers doing `except ValueError` will NOT catch invalid k, and + # running Python with -O strips the assertions entirely, silently + # disabling this validation. This test documents the current + # (buggy) behavior; it should be updated if the bug is fixed to + # actually `raise ValueError(...)` instead. + with pytest.raises(AssertionError): + KFold(5, 0) + with pytest.raises(AssertionError): + KFold(5, 5) + with pytest.raises(AssertionError): + KFold(5, -1) + + with pytest.raises(AssertionError) as exc_info: + KFold(5, 0) + assert isinstance(exc_info.value.args[0], ValueError) + + +def test_kfold_repr(): + kf = KFold(5, 2) + assert repr(kf) == "statsmodels.sandbox.tools.cross_val.KFold(n=5, k=2)" + + +def test_leave_one_label_out(): + labels = [1, 1, 2, 2, 3] + lol = LeaveOneLabelOut(labels) + folds = list(lol) + assert_equal(len(folds), 3) # 3 unique labels + for train, test in folds: + assert_array_equal(train, ~test) + # the label-2 fold selects exactly indices 2 and 3 + _, test_for_label_2 = folds[1] + assert_array_equal(np.flatnonzero(test_for_label_2), [2, 3]) + + +def test_leave_one_label_out_does_not_mutate_input(): + labels = [1, 1, 2, 2, 3] + lol = LeaveOneLabelOut(labels) + list(lol) + assert_equal(labels, [1, 1, 2, 2, 3]) + + +def test_leave_one_label_out_repr(): + labels = [1, 1, 2] + lol = LeaveOneLabelOut(labels) + assert repr(lol) == ( + "statsmodels.sandbox.tools.cross_val.LeaveOneLabelOut(labels=[1, 1, 2])" + ) + + +def test_split(): + x = np.arange(10).reshape(5, 2) + y = np.arange(5) + train = np.array([True, True, False, False, True]) + test = ~train + + x_train, x_test, y_train, y_test = split(train, test, x, y) + assert_array_equal(x_train, x[train]) + assert_array_equal(x_test, x[test]) + assert_array_equal(y_train, y[train]) + assert_array_equal(y_test, y[test]) + + +def test_split_single_array(): + x = np.arange(5) + train = np.array([True, False, True, False, True]) + test = ~train + x_train, x_test = split(train, test, x) + assert_array_equal(x_train, [0, 2, 4]) + assert_array_equal(x_test, [1, 3]) + + +def test_split_accepts_list_input(): + # split() calls np.asanyarray on each arg, so plain lists should work + x_train, x_test = split( + np.array([True, False, True]), np.array([False, True, False]), [10, 20, 30] + ) + assert_array_equal(x_train, [10, 30]) + assert_array_equal(x_test, [20]) + + +def test_kstepahead_slice_mode_default_kall(): + ks = KStepAhead(10, k=2, start=5) + folds = list(ks) + assert_equal(len(folds), 3) # range(start, n - k) == range(5, 8) + train_slice, test_slice = folds[0] + assert_equal(train_slice, slice(None, 5, None)) + assert_equal(test_slice, slice(5, 7, None)) # kall=True: both steps + train_slice, test_slice = folds[-1] + assert_equal(train_slice, slice(None, 7, None)) + assert_equal(test_slice, slice(7, 9, None)) + + +def test_kstepahead_slice_mode_kall_false(): + # kall=False: only the k-th step ahead is in the test slice + ks = KStepAhead(10, k=2, start=5, kall=False) + train_slice, test_slice = next(iter(ks)) + assert_equal(train_slice, slice(None, 5, None)) + assert_equal(test_slice, slice(6, 7, None)) + + +def test_kstepahead_boolean_mode_matches_slice_mode(): + ks_slices = KStepAhead(10, k=2, start=5, return_slice=True) + ks_bools = KStepAhead(10, k=2, start=5, return_slice=False) + n = 10 + for (train_slice, test_slice), (train_bool, test_bool) in zip( + ks_slices, ks_bools, strict=True + ): + expected_train = np.zeros(n, dtype=bool) + expected_train[train_slice] = True + expected_test = np.zeros(n, dtype=bool) + expected_test[test_slice] = True + assert_array_equal(train_bool, expected_train) + assert_array_equal(test_bool, expected_test) + + +def test_kstepahead_default_start_is_quarter_of_n(): + # start=None defaults to trunc(n * 0.25) + ks = KStepAhead(20, k=1) + assert_equal(ks.start, 5) + first_train_slice, _ = next(iter(ks)) + assert_equal(first_train_slice, slice(None, 5, None)) + + +def test_kstepahead_repr(): + ks = KStepAhead(10, k=2, start=5) + assert repr(ks) == "statsmodels.sandbox.tools.cross_val.KStepAhead(n=10)" diff --git a/shared/package-files/38/38d0e095e3ca6489b94855b469bd5b6c7857bf6a3d71ab525e054299d24b6b3f/OperationUtils.h b/shared/package-files/38/38d0e095e3ca6489b94855b469bd5b6c7857bf6a3d71ab525e054299d24b6b3f/OperationUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..8384f4391f9a854c45f625b171dc28d6e2400e4a --- /dev/null +++ b/shared/package-files/38/38d0e095e3ca6489b94855b469bd5b6c7857bf6a3d71ab525e054299d24b6b3f/OperationUtils.h @@ -0,0 +1,394 @@ +// Copyright © 2022 Apple Inc. + +#pragma once + +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +#include + +// Fwd declarations +namespace at { + struct TensorIteratorBase; +} +using namespace at::mps; + +namespace at::native::mps { + +void dispatch_sync_with_rethrow(dispatch_queue_t queue, void (^block)()); + +struct MPSScalar { + id getMTLBuffer() const { return __builtin_bit_cast(id, buffer.get()); } + + size_t size = 0; + ScalarType type = ScalarType::Undefined; + c10::DataPtr buffer; // stores MTLBuffer (frees buffer if MPSScalar instance goes out of scope) + union { + float f; // MPS doesn't support 'double' + at::Half h; + int64_t i; + bool b; + c10::complex cf; + c10::complex ch; + at::BFloat16 bf16; + } value {}; +}; + +void runMPSGraph(MPSStream* mpsStream, + MPSGraph* mpsGraph, + NSDictionary* feeds, + NSDictionary* results); + +MPSDataType getMPSDataType(ScalarType scalar_type); +static inline MPSDataType getMPSDataType(const Tensor& t) { + return getMPSDataType(t.scalar_type()); +} +MPSDataType getMPSScalarType(ScalarType scalar_type); +static inline MPSDataType getMPSScalarType(const Tensor& t) { + return getMPSScalarType(t.scalar_type()); +} +MPSScalar getMPSScalar(const Scalar& scalar, ScalarType type); +std::string getMPSTypeString(ScalarType scalar_type, bool short_name = false); +static inline std::string getMPSTypeString(const Tensor& t, bool short_name = false) { + return getMPSTypeString(t.scalar_type(), short_name); +} +std::string scalarToMetalTypeString(const c10::ScalarType& scalar_type); +NSArray* getTensorAxes(const Tensor& t); +NSArray* getTensorAxes(const IntArrayRef& sizes, at::OptionalIntArrayRef dim); +std::string getMPSShapeString(MPSShape* shape); +std::string getTensorsStringKey(const TensorList& tensors, bool short_dtype = true); +std::string getArrayRefString(const IntArrayRef s); +// use has_storage() on the returned tensor to determine if src actually is a view +Tensor gatherViewTensor(const at::Tensor& src, at::Tensor& dst); +Tensor& scatterViewTensor(const at::Tensor& src, at::Tensor& output); +bool canSliceViewTensor(const Tensor& src, MPSShape *mpsShape); +MPSGraphTensorData* getMPSGraphTensorDataForView(const Tensor& src, MPSShape *mpsShape, const MPSDataType mpsDataType); +MPSGraphTensor* castToIHFTypes(MPSGraph* mpsGraph, MPSGraphTensor* inputTensor, const Tensor& input, bool includesInt64 = false); +MPSGraphTensor* castFromIHFTypes(MPSGraph* mpsGraph, MPSGraphTensor* inputTensor, const Tensor& input, bool includesInt64 = false); + +// The MPSShape could vary based on memory format +MPSShape* getMPSShape(const Tensor& t, c10::MemoryFormat memory_format = MemoryFormat::Contiguous); +MPSShape* getMPSShape(IntArrayRef sizes, c10::MemoryFormat memory_format = MemoryFormat::Contiguous); + +static inline id getMTLBufferStorage(const at::Tensor& tensor) { + return __builtin_bit_cast(id, tensor.storage().data()); +} + +class Placeholder { + public: + Placeholder() : _placeholder(nullptr), _value(nullptr), _tensor(Tensor()) {} + Placeholder(MPSGraphTensor* mpsGraphTensor) : _placeholder(mpsGraphTensor), _value(nullptr), _tensor(Tensor()) {} + Placeholder(MPSGraphTensor* mpsGraphTensor, const Tensor& self, MPSShape *mpsShape = nullptr, + bool gatherTensorData = true, MPSDataType dataType = MPSDataTypeInvalid); + MPSGraphTensor* getMPSGraphTensor() { + return _placeholder; + } + MPSGraphTensorData* getMPSGraphTensorData() { + return _value; + } + bool isIntermediate() { + return _value == nullptr; + } + + private: + MPSGraphTensor* _placeholder; + MPSGraphTensorData* _value; + Tensor _tensor; +}; + +void resize_tensor(Tensor* output); +Tensor wrapped_scalar_tensor_mps(const Scalar& scalar, const Device device); +MPSGraphTensor* trunc_tensor(MPSGraph* mpsGraph, MPSGraphTensor* inputTensor); +MPSGraphTensor* convertNHWCtoNCHW(MPSGraph *mpsGraph, MPSGraphTensor* tensor); +MPSGraphTensor* castMPSTensor(MPSGraph *mpsGraph, MPSGraphTensor* tensor, ScalarType toType); +MPSGraphTensor* castMPSTensor(MPSGraph *mpsGraph, MPSGraphTensor* tensor, MPSDataType toType); +MPSGraphTensorData *getMPSGraphTensorData(MPSGraph* mpsGraph, MPSStream* mpsStream, const Tensor& tensor); +MPSGraphTensorData* getMPSGraphTensorFromScalar(MPSStream* mpsStream, MPSScalar& scalar); + +MPSGraph* make_mps_graph(); +void printTensorNDArray(const Tensor& t); +MPSNDArray* ndArrayFromTensor(const Tensor& tensor, MPSShape *shape, MPSDataType mpsType); + +MPSGraphTensor* mpsGraphUnrankedPlaceHolder(MPSGraph *mpsGraph, MPSDataType dataType); +MPSGraphTensor* mpsGraphRankedPlaceHolder(MPSGraph *mpsGraph, MPSDataType dataType, MPSShape* mpsShape); +MPSGraphTensor* mpsGraphRankedPlaceHolder(MPSGraph *mpsGraph, const Tensor& tensor); +MPSGraphTensor* mpsGraphScalarPlaceHolder(MPSGraph *mpsGraph, MPSDataType dataType); +MPSGraphTensor* mpsGraphScalarPlaceHolder(MPSGraph *mpsGraph, const Scalar& scalar); + +string get_mem_format_string(c10::MemoryFormat memory_format); + +using MPSCacheKey = uint64_t; + +// derive this class to cache a graph and its inputs/outputs +// can be used to store any NSObject +struct MPSCachedGraph +{ + MPSCachedGraph(NSObject *object) : _object([object retain]) {} + virtual ~MPSCachedGraph() { + [_object release]; + _object = nullptr; + } + + template + inline T* as() { + return static_cast(this); + } + + MPSGraph *graph() const { return (MPSGraph *)_object; } + NSObject *object() const { return _object; } +private: + NSObject *_object = nullptr; +}; + +struct MPSUnaryCachedGraph : public MPSCachedGraph +{ + MPSUnaryCachedGraph(MPSGraph *graph) : MPSCachedGraph(graph) {} + MPSGraphTensor *inputTensor_ = nil; + MPSGraphTensor *outputTensor_ = nil; +}; + +struct MPSUnaryGradCachedGraph : public MPSCachedGraph +{ + MPSUnaryGradCachedGraph(MPSGraph *graph) : MPSCachedGraph(graph) {} + MPSGraphTensor *gradOutputTensor_ = nil; + MPSGraphTensor *inputTensor_ = nil; + MPSGraphTensor *outputTensor_ = nil; // some backward input is actually the forward's output + MPSGraphTensor *gradInputTensor_ = nil; +}; + +struct MPSBinaryCachedGraph : public MPSCachedGraph +{ + MPSBinaryCachedGraph(MPSGraph *graph) : MPSCachedGraph(graph) {} + MPSGraphTensor *inputTensor_ = nil; + MPSGraphTensor *otherTensor_ = nil; + MPSGraphTensor *outputTensor_ = nil; +}; + +struct MPSBinaryGradCachedGraph : public MPSCachedGraph +{ + MPSBinaryGradCachedGraph(MPSGraph *graph) : MPSCachedGraph(graph) {} + MPSGraphTensor *gradOutputTensor_ = nil; + MPSGraphTensor *inputTensor_ = nil; + MPSGraphTensor *otherTensor_ = nil; + MPSGraphTensor *gradInputTensor_ = nil; +}; + +// TODO: Improve the overall design of MPSGraphCache. +// https://github.com/pytorch/pytorch/issues/77176 +// Cache holding various keys mapped to graphs +struct MPSGraphCache +{ + typedef MPSCachedGraph * (^CreateCachedGraphBlock)(); + + struct CacheEntry { + CacheEntry(const std::string& key, MPSCachedGraph *cachedGraph) : cachedGraph_(cachedGraph), key_(key) {} + MPSCachedGraph* cachedGraph_ = nullptr; + std::string key_; + }; + + public: + + static MPSGraphCache* getInstance() { + if(_instance_cache == nullptr) { + _instance_cache = new MPSGraphCache(); + } + return _instance_cache; + } + + ~MPSGraphCache() { + dispatch_release(serialQueue_); + + for (const auto& i : cache_) { + delete i.second.cachedGraph_; + } + } + + // Disallow the copy constructor and operator= functions + MPSGraphCache(const MPSGraphCache&) = delete; + void operator=(const MPSGraphCache&) = delete; + + MPSCachedGraph* CreateCachedGraph(const std::string& key, CreateCachedGraphBlock createCacheBlock) { + + __block MPSCachedGraph* cachedGraph = nil; + + MPSCacheKey hash = std::hash{}(key); + + dispatch_sync_with_rethrow(serialQueue_, ^() { + // verify the cached entry doesn't already exist + if (cache_.count(hash) != 0) { + auto& entry = cache_.at(hash); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(key == entry.key_, "Key collision in the MPS cached graph!\n"); + cachedGraph = entry.cachedGraph_; + } else { + cachedGraph = createCacheBlock(); + CacheEntry entry(key, cachedGraph); + cache_.emplace(hash, entry); + profileCachedGraph(entry); + } + }); + return cachedGraph; + } + + template + inline T* CreateCachedGraphAs(const std::string& key, CreateCachedGraphBlock createCacheBlock) { + return static_cast(CreateCachedGraph(key, createCacheBlock)); + } + + MPSCachedGraph* LookUp(const std::string& key) const { + + __block MPSCachedGraph* cachedGraph = nullptr; + + MPSCacheKey hash = std::hash{}(key); + + dispatch_sync(serialQueue_, ^() { + + if (cache_.count(hash) != 0) { + auto& entry = cache_.at(hash); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(key == entry.key_, "Key collision in the MPS cached graph!\n"); + cachedGraph = entry.cachedGraph_; + profileCachedGraph(entry); + } + }); + return cachedGraph; + } + + template + inline T* LookUpAs(const std::string& key) const { + return static_cast(LookUp(key)); + } + + private: + MPSGraphCache() { + serialQueue_ = dispatch_queue_create("cache queue", DISPATCH_QUEUE_SERIAL); + } + // this is defined in OperationUtils.mm to not include + // MPSProfiler.h in header OperationUtils.h + void profileCachedGraph(const CacheEntry& cacheEntry) const; + + static MPSGraphCache* _instance_cache; + std::unordered_map cache_; + dispatch_queue_t serialQueue_ = nullptr; + +}; + +// Common template for creating graph with a specified cache if missing +template +inline T* LookUpOrCreateCachedGraph(const std::string& key, std::function instantiate) { + auto cache_ = MPSGraphCache::getInstance(); + if (auto rc = cache_->LookUpAs(key)) { + return rc; + } + return cache_->CreateCachedGraphAs(key, ^mps::MPSCachedGraph*() { + T* newCachedGraph = nil; + @autoreleasepool { + // Initialize graph + auto mpsGraph = mps::make_mps_graph(); + newCachedGraph = new T(mpsGraph); + instantiate(mpsGraph, newCachedGraph); + } + return newCachedGraph; + }); +} + +// Common math operations +MPSGraphTensor* log1p(MPSGraph* mpsGraph, MPSGraphTensor* inputTensor); + +#define MPS_CHECK_INT64_OP_SUPPORTED(input_tensor, mac_os_13_3_plus, op_name) \ + if (!mac_os_13_3_plus && input_tensor.scalar_type() == kLong) { \ + TORCH_WARN_ONCE("MPS: no support for int64 for ", op_name, \ + ", downcasting to a smaller data type (int32/float32). Native support for int64 has been added in macOS 13.3."); \ + } + +/** + * Returns distance from lowest to highest element offset in given tensor. + */ +size_t compute_storage_numel_distance(const at::Tensor& t); + +/** + * Checks whether tensor is mapped to a contiguous area in the storage. + */ +inline bool is_dense_in_storage(const at::Tensor& t) { + return compute_storage_numel_distance(t) == static_cast(t.numel()); +} + +static inline void mtl_setBuffer(id encoder, const Tensor& t, unsigned idx) { + [encoder setBuffer:getMTLBufferStorage(t) + offset:t.storage_offset() * t.element_size() + atIndex:idx]; +} + +static inline void mtl_dispatch1DJob(id encoder, + id cplState, + uint32_t length) { + const uint32_t maxThreadsPerGroup = [cplState maxTotalThreadsPerThreadgroup]; + auto size = MTLSizeMake(length, 1, 1); + auto threadGroupSize = MTLSizeMake(std::min(maxThreadsPerGroup, length), 1, 1); + [encoder dispatchThreads:size threadsPerThreadgroup:threadGroupSize]; +} + +id generateKernelDataOffsets(id commandEncoder, const TensorIteratorBase& iter, bool use_64bit_index = false); + +inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1) { + return @{ p1.getMPSGraphTensor(): p1.getMPSGraphTensorData() }; +} + +inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1, Placeholder& p2) { + return @{ + p1.getMPSGraphTensor(): p1.getMPSGraphTensorData(), + p2.getMPSGraphTensor(): p2.getMPSGraphTensorData(), + }; +} + +inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1, Placeholder& p2, Placeholder& p3) { + return @{ + p1.getMPSGraphTensor(): p1.getMPSGraphTensorData(), + p2.getMPSGraphTensor(): p2.getMPSGraphTensorData(), + p3.getMPSGraphTensor(): p3.getMPSGraphTensorData(), + }; +} + +inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1, Placeholder& p2, Placeholder& p3, Placeholder& p4) { + return @{ + p1.getMPSGraphTensor(): p1.getMPSGraphTensorData(), + p2.getMPSGraphTensor(): p2.getMPSGraphTensorData(), + p3.getMPSGraphTensor(): p3.getMPSGraphTensorData(), + p4.getMPSGraphTensor(): p4.getMPSGraphTensorData(), + }; +} + +inline void runMPSGraph(MPSStream* stream, MPSGraph* graph, NSDictionary* feeds, Placeholder& result) { + runMPSGraph(stream, graph, feeds, dictionaryFromPlaceholders(result)); +} + +inline bool supportsComplex() { + return is_macos_13_or_newer(MacOSVersion::MACOS_VER_14_0_PLUS); +} + +// MPS yet to support double types, but starting from MacOS 14, supports bfloat16 +inline bool supportedFloatingType(ScalarType dtype) { + return dtype == kFloat || dtype == kHalf || dtype == kBFloat16; +} + +inline bool supportedFloatingType(const Tensor& t) { + return supportedFloatingType(t.scalar_type()); +} + +} // namespace at::native::mps diff --git a/shared/package-files/38/38d2543cff6e2949fabb25091f01c10f7a907899ad33eec6163140f2a0a78894/_cdnmf_fast.pyx b/shared/package-files/38/38d2543cff6e2949fabb25091f01c10f7a907899ad33eec6163140f2a0a78894/_cdnmf_fast.pyx new file mode 100644 index 0000000000000000000000000000000000000000..b2a07fb275bded974524b0c372a931de850d9142 --- /dev/null +++ b/shared/package-files/38/38d2543cff6e2949fabb25091f01c10f7a907899ad33eec6163140f2a0a78894/_cdnmf_fast.pyx @@ -0,0 +1,38 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from cython cimport floating +from libc.math cimport fabs + + +def _update_cdnmf_fast(floating[:, ::1] W, floating[:, :] HHt, + floating[:, :] XHt, Py_ssize_t[::1] permutation): + cdef: + floating violation = 0 + Py_ssize_t n_components = W.shape[1] + Py_ssize_t n_samples = W.shape[0] # n_features for H update + floating grad, pg, hess + Py_ssize_t i, r, s, t + + with nogil: + for s in range(n_components): + t = permutation[s] + + for i in range(n_samples): + # gradient = GW[t, i] where GW = np.dot(W, HHt) - XHt + grad = -XHt[i, t] + + for r in range(n_components): + grad += HHt[t, r] * W[i, r] + + # projected gradient + pg = min(0., grad) if W[i, t] == 0 else grad + violation += fabs(pg) + + # Hessian + hess = HHt[t, t] + + if hess != 0: + W[i, t] = max(W[i, t] - grad / hess, 0.) + + return violation diff --git a/shared/package-files/38/38d320d7718869e7e8a391a0b358a75e2d38c5211c69b1ae6196e9437f236894/framework.py b/shared/package-files/38/38d320d7718869e7e8a391a0b358a75e2d38c5211c69b1ae6196e9437f236894/framework.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc65fb389700d92b9a32023a948afb202c9d18e --- /dev/null +++ b/shared/package-files/38/38d320d7718869e7e8a391a0b358a75e2d38c5211c69b1ae6196e9437f236894/framework.py @@ -0,0 +1,117 @@ +import itertools as it + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd + +from . import perturbation + + +def update(model, attributions, X, y, masker, sort_order, perturbation_method, scores): + metric = perturbation_method + " " + sort_order + sp = perturbation.SequentialPerturbation(model, masker, sort_order, perturbation_method) + xs, ys, auc = sp.model_score(attributions, X, y=y) + scores["metrics"].append(metric) + scores["values"][metric] = [xs, ys, auc] + + +def get_benchmark(model, attributions, X, y, masker, metrics): + # convert dataframes + if isinstance(X, (pd.Series, pd.DataFrame)): + X = X.values + if isinstance(masker, (pd.Series, pd.DataFrame)): + masker = masker.values + + # record scores per metric + scores = {"metrics": list(), "values": dict()} + for sort_order, perturbation_method in list(it.product(metrics["sort_order"], metrics["perturbation"])): + update(model, attributions, X, y, masker, sort_order, perturbation_method, scores) + + return scores + + +def get_metrics(benchmarks, selection): + # select metrics to plot using selection function + explainer_metrics = set() + for explainer in benchmarks: + scores = benchmarks[explainer] + if len(explainer_metrics) == 0: + explainer_metrics = set(scores["metrics"]) + else: + explainer_metrics = selection(explainer_metrics, set(scores["metrics"])) + + return list(explainer_metrics) + + +def trend_plot(benchmarks): + explainer_metrics = get_metrics(benchmarks, lambda x, y: x.union(y)) + + # plot all curves if metric exists + for metric in explainer_metrics: + plt.clf() + + for explainer in benchmarks: + scores = benchmarks[explainer] + if metric in scores["values"]: + x, y, auc = scores["values"][metric] + plt.plot(x, y, label=f"{round(auc, 3)} - {explainer}") + + if "keep" in metric: + xlabel = "Percent Unmasked" + if "remove" in metric: + xlabel = "Percent Masked" + + plt.ylabel("Model Output") + plt.xlabel(xlabel) + plt.title(metric) + plt.legend() + plt.show() + + +def compare_plot(benchmarks): + explainer_metrics = get_metrics(benchmarks, lambda x, y: x.intersection(y)) + explainers = list(benchmarks.keys()) + num_explainers = len(explainers) + num_metrics = len(explainer_metrics) + + # dummy start to evenly distribute explainers on the left + # can later be replaced by boolean metrics + aucs = dict() + for i in range(num_explainers): + explainer = explainers[i] + aucs[explainer] = [i / (num_explainers - 1)] + + # normalize per metric + for metric in explainer_metrics: + max_auc, min_auc = -float("inf"), float("inf") + + for explainer in explainers: + scores = benchmarks[explainer] + _, _, auc = scores["values"][metric] + min_auc = min(auc, min_auc) + max_auc = max(auc, max_auc) + + for explainer in explainers: + scores = benchmarks[explainer] + _, _, auc = scores["values"][metric] + aucs[explainer].append((auc - min_auc) / (max_auc - min_auc)) + + # plot common curves + ax = plt.gca() + for explainer in explainers: + plt.plot(np.linspace(0, 1, len(explainer_metrics) + 1), aucs[explainer], "--o") + + ax.tick_params(which="major", axis="both", labelsize=8) + + ax.set_yticks([i / (num_explainers - 1) for i in range(0, num_explainers)]) + ax.set_yticklabels(explainers, rotation=0) + + ax.set_xticks(np.linspace(0, 1, num_metrics + 1)) + ax.set_xticklabels([" "] + explainer_metrics, rotation=45, ha="right") + + plt.grid(which="major", axis="x", linestyle="--") + plt.tight_layout() + plt.ylabel("Relative Performance of Each Explanation Method") + plt.xlabel("Evaluation Metrics") + plt.title("Explanation Method Performance Across Metrics") + plt.show() diff --git a/shared/package-files/38/38dbf806011a0b8fca782f4296196b8538388b64219be3430deca2482b530b1b/kl.py b/shared/package-files/38/38dbf806011a0b8fca782f4296196b8538388b64219be3430deca2482b530b1b/kl.py new file mode 100644 index 0000000000000000000000000000000000000000..45e89c77d0a201480ff14e022d81bb100dd02947 --- /dev/null +++ b/shared/package-files/38/38dbf806011a0b8fca782f4296196b8538388b64219be3430deca2482b530b1b/kl.py @@ -0,0 +1,971 @@ +import math +import warnings +from functools import total_ordering +from typing import Callable, Dict, Tuple, Type + +import torch +from torch import inf + +from .bernoulli import Bernoulli +from .beta import Beta +from .binomial import Binomial +from .categorical import Categorical +from .cauchy import Cauchy +from .continuous_bernoulli import ContinuousBernoulli +from .dirichlet import Dirichlet +from .distribution import Distribution +from .exp_family import ExponentialFamily +from .exponential import Exponential +from .gamma import Gamma +from .geometric import Geometric +from .gumbel import Gumbel +from .half_normal import HalfNormal +from .independent import Independent +from .laplace import Laplace +from .lowrank_multivariate_normal import ( + _batch_lowrank_logdet, + _batch_lowrank_mahalanobis, + LowRankMultivariateNormal, +) +from .multivariate_normal import _batch_mahalanobis, MultivariateNormal +from .normal import Normal +from .one_hot_categorical import OneHotCategorical +from .pareto import Pareto +from .poisson import Poisson +from .transformed_distribution import TransformedDistribution +from .uniform import Uniform +from .utils import _sum_rightmost, euler_constant as _euler_gamma + +_KL_REGISTRY: Dict[ + Tuple[Type, Type], Callable +] = {} # Source of truth mapping a few general (type, type) pairs to functions. +_KL_MEMOIZE: Dict[ + Tuple[Type, Type], Callable +] = {} # Memoized version mapping many specific (type, type) pairs to functions. + +__all__ = ["register_kl", "kl_divergence"] + + +def register_kl(type_p, type_q): + """ + Decorator to register a pairwise function with :meth:`kl_divergence`. + Usage:: + + @register_kl(Normal, Normal) + def kl_normal_normal(p, q): + # insert implementation here + + Lookup returns the most specific (type,type) match ordered by subclass. If + the match is ambiguous, a `RuntimeWarning` is raised. For example to + resolve the ambiguous situation:: + + @register_kl(BaseP, DerivedQ) + def kl_version1(p, q): ... + @register_kl(DerivedP, BaseQ) + def kl_version2(p, q): ... + + you should register a third most-specific implementation, e.g.:: + + register_kl(DerivedP, DerivedQ)(kl_version1) # Break the tie. + + Args: + type_p (type): A subclass of :class:`~torch.distributions.Distribution`. + type_q (type): A subclass of :class:`~torch.distributions.Distribution`. + """ + if not isinstance(type_p, type) and issubclass(type_p, Distribution): + raise TypeError( + f"Expected type_p to be a Distribution subclass but got {type_p}" + ) + if not isinstance(type_q, type) and issubclass(type_q, Distribution): + raise TypeError( + f"Expected type_q to be a Distribution subclass but got {type_q}" + ) + + def decorator(fun): + _KL_REGISTRY[type_p, type_q] = fun + _KL_MEMOIZE.clear() # reset since lookup order may have changed + return fun + + return decorator + + +@total_ordering +class _Match: + __slots__ = ["types"] + + def __init__(self, *types): + self.types = types + + def __eq__(self, other): + return self.types == other.types + + def __le__(self, other): + for x, y in zip(self.types, other.types): + if not issubclass(x, y): + return False + if x is not y: + break + return True + + +def _dispatch_kl(type_p, type_q): + """ + Find the most specific approximate match, assuming single inheritance. + """ + matches = [ + (super_p, super_q) + for super_p, super_q in _KL_REGISTRY + if issubclass(type_p, super_p) and issubclass(type_q, super_q) + ] + if not matches: + return NotImplemented + # Check that the left- and right- lexicographic orders agree. + # mypy isn't smart enough to know that _Match implements __lt__ + # see: https://github.com/python/typing/issues/760#issuecomment-710670503 + left_p, left_q = min(_Match(*m) for m in matches).types # type: ignore[type-var] + right_q, right_p = min(_Match(*reversed(m)) for m in matches).types # type: ignore[type-var] + left_fun = _KL_REGISTRY[left_p, left_q] + right_fun = _KL_REGISTRY[right_p, right_q] + if left_fun is not right_fun: + warnings.warn( + "Ambiguous kl_divergence({}, {}). Please register_kl({}, {})".format( + type_p.__name__, type_q.__name__, left_p.__name__, right_q.__name__ + ), + RuntimeWarning, + ) + return left_fun + + +def _infinite_like(tensor): + """ + Helper function for obtaining infinite KL Divergence throughout + """ + return torch.full_like(tensor, inf) + + +def _x_log_x(tensor): + """ + Utility function for calculating x log x + """ + return tensor * tensor.log() + + +def _batch_trace_XXT(bmat): + """ + Utility function for calculating the trace of XX^{T} with X having arbitrary trailing batch dimensions + """ + n = bmat.size(-1) + m = bmat.size(-2) + flat_trace = bmat.reshape(-1, m * n).pow(2).sum(-1) + return flat_trace.reshape(bmat.shape[:-2]) + + +def kl_divergence(p: Distribution, q: Distribution) -> torch.Tensor: + r""" + Compute Kullback-Leibler divergence :math:`KL(p \| q)` between two distributions. + + .. math:: + + KL(p \| q) = \int p(x) \log\frac {p(x)} {q(x)} \,dx + + Args: + p (Distribution): A :class:`~torch.distributions.Distribution` object. + q (Distribution): A :class:`~torch.distributions.Distribution` object. + + Returns: + Tensor: A batch of KL divergences of shape `batch_shape`. + + Raises: + NotImplementedError: If the distribution types have not been registered via + :meth:`register_kl`. + """ + try: + fun = _KL_MEMOIZE[type(p), type(q)] + except KeyError: + fun = _dispatch_kl(type(p), type(q)) + _KL_MEMOIZE[type(p), type(q)] = fun + if fun is NotImplemented: + raise NotImplementedError( + f"No KL(p || q) is implemented for p type {p.__class__.__name__} and q type {q.__class__.__name__}" + ) + return fun(p, q) + + +################################################################################ +# KL Divergence Implementations +################################################################################ + +# Same distributions + + +@register_kl(Bernoulli, Bernoulli) +def _kl_bernoulli_bernoulli(p, q): + t1 = p.probs * ( + torch.nn.functional.softplus(-q.logits) + - torch.nn.functional.softplus(-p.logits) + ) + t1[q.probs == 0] = inf + t1[p.probs == 0] = 0 + t2 = (1 - p.probs) * ( + torch.nn.functional.softplus(q.logits) - torch.nn.functional.softplus(p.logits) + ) + t2[q.probs == 1] = inf + t2[p.probs == 1] = 0 + return t1 + t2 + + +@register_kl(Beta, Beta) +def _kl_beta_beta(p, q): + sum_params_p = p.concentration1 + p.concentration0 + sum_params_q = q.concentration1 + q.concentration0 + t1 = q.concentration1.lgamma() + q.concentration0.lgamma() + (sum_params_p).lgamma() + t2 = p.concentration1.lgamma() + p.concentration0.lgamma() + (sum_params_q).lgamma() + t3 = (p.concentration1 - q.concentration1) * torch.digamma(p.concentration1) + t4 = (p.concentration0 - q.concentration0) * torch.digamma(p.concentration0) + t5 = (sum_params_q - sum_params_p) * torch.digamma(sum_params_p) + return t1 - t2 + t3 + t4 + t5 + + +@register_kl(Binomial, Binomial) +def _kl_binomial_binomial(p, q): + # from https://math.stackexchange.com/questions/2214993/ + # kullback-leibler-divergence-for-binomial-distributions-p-and-q + if (p.total_count < q.total_count).any(): + raise NotImplementedError( + "KL between Binomials where q.total_count > p.total_count is not implemented" + ) + kl = p.total_count * ( + p.probs * (p.logits - q.logits) + (-p.probs).log1p() - (-q.probs).log1p() + ) + inf_idxs = p.total_count > q.total_count + kl[inf_idxs] = _infinite_like(kl[inf_idxs]) + return kl + + +@register_kl(Categorical, Categorical) +def _kl_categorical_categorical(p, q): + t = p.probs * (p.logits - q.logits) + t[(q.probs == 0).expand_as(t)] = inf + t[(p.probs == 0).expand_as(t)] = 0 + return t.sum(-1) + + +@register_kl(ContinuousBernoulli, ContinuousBernoulli) +def _kl_continuous_bernoulli_continuous_bernoulli(p, q): + t1 = p.mean * (p.logits - q.logits) + t2 = p._cont_bern_log_norm() + torch.log1p(-p.probs) + t3 = -q._cont_bern_log_norm() - torch.log1p(-q.probs) + return t1 + t2 + t3 + + +@register_kl(Dirichlet, Dirichlet) +def _kl_dirichlet_dirichlet(p, q): + # From http://bariskurt.com/kullback-leibler-divergence-between-two-dirichlet-and-beta-distributions/ + sum_p_concentration = p.concentration.sum(-1) + sum_q_concentration = q.concentration.sum(-1) + t1 = sum_p_concentration.lgamma() - sum_q_concentration.lgamma() + t2 = (p.concentration.lgamma() - q.concentration.lgamma()).sum(-1) + t3 = p.concentration - q.concentration + t4 = p.concentration.digamma() - sum_p_concentration.digamma().unsqueeze(-1) + return t1 - t2 + (t3 * t4).sum(-1) + + +@register_kl(Exponential, Exponential) +def _kl_exponential_exponential(p, q): + rate_ratio = q.rate / p.rate + t1 = -rate_ratio.log() + return t1 + rate_ratio - 1 + + +@register_kl(ExponentialFamily, ExponentialFamily) +def _kl_expfamily_expfamily(p, q): + if not type(p) == type(q): + raise NotImplementedError( + "The cross KL-divergence between different exponential families cannot \ + be computed using Bregman divergences" + ) + p_nparams = [np.detach().requires_grad_() for np in p._natural_params] + q_nparams = q._natural_params + lg_normal = p._log_normalizer(*p_nparams) + gradients = torch.autograd.grad(lg_normal.sum(), p_nparams, create_graph=True) + result = q._log_normalizer(*q_nparams) - lg_normal + for pnp, qnp, g in zip(p_nparams, q_nparams, gradients): + term = (qnp - pnp) * g + result -= _sum_rightmost(term, len(q.event_shape)) + return result + + +@register_kl(Gamma, Gamma) +def _kl_gamma_gamma(p, q): + t1 = q.concentration * (p.rate / q.rate).log() + t2 = torch.lgamma(q.concentration) - torch.lgamma(p.concentration) + t3 = (p.concentration - q.concentration) * torch.digamma(p.concentration) + t4 = (q.rate - p.rate) * (p.concentration / p.rate) + return t1 + t2 + t3 + t4 + + +@register_kl(Gumbel, Gumbel) +def _kl_gumbel_gumbel(p, q): + ct1 = p.scale / q.scale + ct2 = q.loc / q.scale + ct3 = p.loc / q.scale + t1 = -ct1.log() - ct2 + ct3 + t2 = ct1 * _euler_gamma + t3 = torch.exp(ct2 + (1 + ct1).lgamma() - ct3) + return t1 + t2 + t3 - (1 + _euler_gamma) + + +@register_kl(Geometric, Geometric) +def _kl_geometric_geometric(p, q): + return -p.entropy() - torch.log1p(-q.probs) / p.probs - q.logits + + +@register_kl(HalfNormal, HalfNormal) +def _kl_halfnormal_halfnormal(p, q): + return _kl_normal_normal(p.base_dist, q.base_dist) + + +@register_kl(Laplace, Laplace) +def _kl_laplace_laplace(p, q): + # From http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf + scale_ratio = p.scale / q.scale + loc_abs_diff = (p.loc - q.loc).abs() + t1 = -scale_ratio.log() + t2 = loc_abs_diff / q.scale + t3 = scale_ratio * torch.exp(-loc_abs_diff / p.scale) + return t1 + t2 + t3 - 1 + + +@register_kl(LowRankMultivariateNormal, LowRankMultivariateNormal) +def _kl_lowrankmultivariatenormal_lowrankmultivariatenormal(p, q): + if p.event_shape != q.event_shape: + raise ValueError( + "KL-divergence between two Low Rank Multivariate Normals with\ + different event shapes cannot be computed" + ) + + term1 = _batch_lowrank_logdet( + q._unbroadcasted_cov_factor, q._unbroadcasted_cov_diag, q._capacitance_tril + ) - _batch_lowrank_logdet( + p._unbroadcasted_cov_factor, p._unbroadcasted_cov_diag, p._capacitance_tril + ) + term3 = _batch_lowrank_mahalanobis( + q._unbroadcasted_cov_factor, + q._unbroadcasted_cov_diag, + q.loc - p.loc, + q._capacitance_tril, + ) + # Expands term2 according to + # inv(qcov) @ pcov = [inv(qD) - inv(qD) @ qW @ inv(qC) @ qW.T @ inv(qD)] @ (pW @ pW.T + pD) + # = [inv(qD) - A.T @ A] @ (pD + pW @ pW.T) + qWt_qDinv = q._unbroadcasted_cov_factor.mT / q._unbroadcasted_cov_diag.unsqueeze(-2) + A = torch.linalg.solve_triangular(q._capacitance_tril, qWt_qDinv, upper=False) + term21 = (p._unbroadcasted_cov_diag / q._unbroadcasted_cov_diag).sum(-1) + term22 = _batch_trace_XXT( + p._unbroadcasted_cov_factor * q._unbroadcasted_cov_diag.rsqrt().unsqueeze(-1) + ) + term23 = _batch_trace_XXT(A * p._unbroadcasted_cov_diag.sqrt().unsqueeze(-2)) + term24 = _batch_trace_XXT(A.matmul(p._unbroadcasted_cov_factor)) + term2 = term21 + term22 - term23 - term24 + return 0.5 * (term1 + term2 + term3 - p.event_shape[0]) + + +@register_kl(MultivariateNormal, LowRankMultivariateNormal) +def _kl_multivariatenormal_lowrankmultivariatenormal(p, q): + if p.event_shape != q.event_shape: + raise ValueError( + "KL-divergence between two (Low Rank) Multivariate Normals with\ + different event shapes cannot be computed" + ) + + term1 = _batch_lowrank_logdet( + q._unbroadcasted_cov_factor, q._unbroadcasted_cov_diag, q._capacitance_tril + ) - 2 * p._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) + term3 = _batch_lowrank_mahalanobis( + q._unbroadcasted_cov_factor, + q._unbroadcasted_cov_diag, + q.loc - p.loc, + q._capacitance_tril, + ) + # Expands term2 according to + # inv(qcov) @ pcov = [inv(qD) - inv(qD) @ qW @ inv(qC) @ qW.T @ inv(qD)] @ p_tril @ p_tril.T + # = [inv(qD) - A.T @ A] @ p_tril @ p_tril.T + qWt_qDinv = q._unbroadcasted_cov_factor.mT / q._unbroadcasted_cov_diag.unsqueeze(-2) + A = torch.linalg.solve_triangular(q._capacitance_tril, qWt_qDinv, upper=False) + term21 = _batch_trace_XXT( + p._unbroadcasted_scale_tril * q._unbroadcasted_cov_diag.rsqrt().unsqueeze(-1) + ) + term22 = _batch_trace_XXT(A.matmul(p._unbroadcasted_scale_tril)) + term2 = term21 - term22 + return 0.5 * (term1 + term2 + term3 - p.event_shape[0]) + + +@register_kl(LowRankMultivariateNormal, MultivariateNormal) +def _kl_lowrankmultivariatenormal_multivariatenormal(p, q): + if p.event_shape != q.event_shape: + raise ValueError( + "KL-divergence between two (Low Rank) Multivariate Normals with\ + different event shapes cannot be computed" + ) + + term1 = 2 * q._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum( + -1 + ) - _batch_lowrank_logdet( + p._unbroadcasted_cov_factor, p._unbroadcasted_cov_diag, p._capacitance_tril + ) + term3 = _batch_mahalanobis(q._unbroadcasted_scale_tril, (q.loc - p.loc)) + # Expands term2 according to + # inv(qcov) @ pcov = inv(q_tril @ q_tril.T) @ (pW @ pW.T + pD) + combined_batch_shape = torch._C._infer_size( + q._unbroadcasted_scale_tril.shape[:-2], p._unbroadcasted_cov_factor.shape[:-2] + ) + n = p.event_shape[0] + q_scale_tril = q._unbroadcasted_scale_tril.expand(combined_batch_shape + (n, n)) + p_cov_factor = p._unbroadcasted_cov_factor.expand( + combined_batch_shape + (n, p.cov_factor.size(-1)) + ) + p_cov_diag = torch.diag_embed(p._unbroadcasted_cov_diag.sqrt()).expand( + combined_batch_shape + (n, n) + ) + term21 = _batch_trace_XXT( + torch.linalg.solve_triangular(q_scale_tril, p_cov_factor, upper=False) + ) + term22 = _batch_trace_XXT( + torch.linalg.solve_triangular(q_scale_tril, p_cov_diag, upper=False) + ) + term2 = term21 + term22 + return 0.5 * (term1 + term2 + term3 - p.event_shape[0]) + + +@register_kl(MultivariateNormal, MultivariateNormal) +def _kl_multivariatenormal_multivariatenormal(p, q): + # From https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Kullback%E2%80%93Leibler_divergence + if p.event_shape != q.event_shape: + raise ValueError( + "KL-divergence between two Multivariate Normals with\ + different event shapes cannot be computed" + ) + + half_term1 = q._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum( + -1 + ) - p._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) + combined_batch_shape = torch._C._infer_size( + q._unbroadcasted_scale_tril.shape[:-2], p._unbroadcasted_scale_tril.shape[:-2] + ) + n = p.event_shape[0] + q_scale_tril = q._unbroadcasted_scale_tril.expand(combined_batch_shape + (n, n)) + p_scale_tril = p._unbroadcasted_scale_tril.expand(combined_batch_shape + (n, n)) + term2 = _batch_trace_XXT( + torch.linalg.solve_triangular(q_scale_tril, p_scale_tril, upper=False) + ) + term3 = _batch_mahalanobis(q._unbroadcasted_scale_tril, (q.loc - p.loc)) + return half_term1 + 0.5 * (term2 + term3 - n) + + +@register_kl(Normal, Normal) +def _kl_normal_normal(p, q): + var_ratio = (p.scale / q.scale).pow(2) + t1 = ((p.loc - q.loc) / q.scale).pow(2) + return 0.5 * (var_ratio + t1 - 1 - var_ratio.log()) + + +@register_kl(OneHotCategorical, OneHotCategorical) +def _kl_onehotcategorical_onehotcategorical(p, q): + return _kl_categorical_categorical(p._categorical, q._categorical) + + +@register_kl(Pareto, Pareto) +def _kl_pareto_pareto(p, q): + # From http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf + scale_ratio = p.scale / q.scale + alpha_ratio = q.alpha / p.alpha + t1 = q.alpha * scale_ratio.log() + t2 = -alpha_ratio.log() + result = t1 + t2 + alpha_ratio - 1 + result[p.support.lower_bound < q.support.lower_bound] = inf + return result + + +@register_kl(Poisson, Poisson) +def _kl_poisson_poisson(p, q): + return p.rate * (p.rate.log() - q.rate.log()) - (p.rate - q.rate) + + +@register_kl(TransformedDistribution, TransformedDistribution) +def _kl_transformed_transformed(p, q): + if p.transforms != q.transforms: + raise NotImplementedError + if p.event_shape != q.event_shape: + raise NotImplementedError + return kl_divergence(p.base_dist, q.base_dist) + + +@register_kl(Uniform, Uniform) +def _kl_uniform_uniform(p, q): + result = ((q.high - q.low) / (p.high - p.low)).log() + result[(q.low > p.low) | (q.high < p.high)] = inf + return result + + +# Different distributions +@register_kl(Bernoulli, Poisson) +def _kl_bernoulli_poisson(p, q): + return -p.entropy() - (p.probs * q.rate.log() - q.rate) + + +@register_kl(Beta, ContinuousBernoulli) +def _kl_beta_continuous_bernoulli(p, q): + return ( + -p.entropy() + - p.mean * q.logits + - torch.log1p(-q.probs) + - q._cont_bern_log_norm() + ) + + +@register_kl(Beta, Pareto) +def _kl_beta_infinity(p, q): + return _infinite_like(p.concentration1) + + +@register_kl(Beta, Exponential) +def _kl_beta_exponential(p, q): + return ( + -p.entropy() + - q.rate.log() + + q.rate * (p.concentration1 / (p.concentration1 + p.concentration0)) + ) + + +@register_kl(Beta, Gamma) +def _kl_beta_gamma(p, q): + t1 = -p.entropy() + t2 = q.concentration.lgamma() - q.concentration * q.rate.log() + t3 = (q.concentration - 1) * ( + p.concentration1.digamma() - (p.concentration1 + p.concentration0).digamma() + ) + t4 = q.rate * p.concentration1 / (p.concentration1 + p.concentration0) + return t1 + t2 - t3 + t4 + + +# TODO: Add Beta-Laplace KL Divergence + + +@register_kl(Beta, Normal) +def _kl_beta_normal(p, q): + E_beta = p.concentration1 / (p.concentration1 + p.concentration0) + var_normal = q.scale.pow(2) + t1 = -p.entropy() + t2 = 0.5 * (var_normal * 2 * math.pi).log() + t3 = ( + E_beta * (1 - E_beta) / (p.concentration1 + p.concentration0 + 1) + + E_beta.pow(2) + ) * 0.5 + t4 = q.loc * E_beta + t5 = q.loc.pow(2) * 0.5 + return t1 + t2 + (t3 - t4 + t5) / var_normal + + +@register_kl(Beta, Uniform) +def _kl_beta_uniform(p, q): + result = -p.entropy() + (q.high - q.low).log() + result[(q.low > p.support.lower_bound) | (q.high < p.support.upper_bound)] = inf + return result + + +# Note that the KL between a ContinuousBernoulli and Beta has no closed form + + +@register_kl(ContinuousBernoulli, Pareto) +def _kl_continuous_bernoulli_infinity(p, q): + return _infinite_like(p.probs) + + +@register_kl(ContinuousBernoulli, Exponential) +def _kl_continuous_bernoulli_exponential(p, q): + return -p.entropy() - torch.log(q.rate) + q.rate * p.mean + + +# Note that the KL between a ContinuousBernoulli and Gamma has no closed form +# TODO: Add ContinuousBernoulli-Laplace KL Divergence + + +@register_kl(ContinuousBernoulli, Normal) +def _kl_continuous_bernoulli_normal(p, q): + t1 = -p.entropy() + t2 = 0.5 * (math.log(2.0 * math.pi) + torch.square(q.loc / q.scale)) + torch.log( + q.scale + ) + t3 = (p.variance + torch.square(p.mean) - 2.0 * q.loc * p.mean) / ( + 2.0 * torch.square(q.scale) + ) + return t1 + t2 + t3 + + +@register_kl(ContinuousBernoulli, Uniform) +def _kl_continuous_bernoulli_uniform(p, q): + result = -p.entropy() + (q.high - q.low).log() + return torch.where( + torch.max( + torch.ge(q.low, p.support.lower_bound), + torch.le(q.high, p.support.upper_bound), + ), + torch.ones_like(result) * inf, + result, + ) + + +@register_kl(Exponential, Beta) +@register_kl(Exponential, ContinuousBernoulli) +@register_kl(Exponential, Pareto) +@register_kl(Exponential, Uniform) +def _kl_exponential_infinity(p, q): + return _infinite_like(p.rate) + + +@register_kl(Exponential, Gamma) +def _kl_exponential_gamma(p, q): + ratio = q.rate / p.rate + t1 = -q.concentration * torch.log(ratio) + return ( + t1 + + ratio + + q.concentration.lgamma() + + q.concentration * _euler_gamma + - (1 + _euler_gamma) + ) + + +@register_kl(Exponential, Gumbel) +def _kl_exponential_gumbel(p, q): + scale_rate_prod = p.rate * q.scale + loc_scale_ratio = q.loc / q.scale + t1 = scale_rate_prod.log() - 1 + t2 = torch.exp(loc_scale_ratio) * scale_rate_prod / (scale_rate_prod + 1) + t3 = scale_rate_prod.reciprocal() + return t1 - loc_scale_ratio + t2 + t3 + + +# TODO: Add Exponential-Laplace KL Divergence + + +@register_kl(Exponential, Normal) +def _kl_exponential_normal(p, q): + var_normal = q.scale.pow(2) + rate_sqr = p.rate.pow(2) + t1 = 0.5 * torch.log(rate_sqr * var_normal * 2 * math.pi) + t2 = rate_sqr.reciprocal() + t3 = q.loc / p.rate + t4 = q.loc.pow(2) * 0.5 + return t1 - 1 + (t2 - t3 + t4) / var_normal + + +@register_kl(Gamma, Beta) +@register_kl(Gamma, ContinuousBernoulli) +@register_kl(Gamma, Pareto) +@register_kl(Gamma, Uniform) +def _kl_gamma_infinity(p, q): + return _infinite_like(p.concentration) + + +@register_kl(Gamma, Exponential) +def _kl_gamma_exponential(p, q): + return -p.entropy() - q.rate.log() + q.rate * p.concentration / p.rate + + +@register_kl(Gamma, Gumbel) +def _kl_gamma_gumbel(p, q): + beta_scale_prod = p.rate * q.scale + loc_scale_ratio = q.loc / q.scale + t1 = ( + (p.concentration - 1) * p.concentration.digamma() + - p.concentration.lgamma() + - p.concentration + ) + t2 = beta_scale_prod.log() + p.concentration / beta_scale_prod + t3 = ( + torch.exp(loc_scale_ratio) + * (1 + beta_scale_prod.reciprocal()).pow(-p.concentration) + - loc_scale_ratio + ) + return t1 + t2 + t3 + + +# TODO: Add Gamma-Laplace KL Divergence + + +@register_kl(Gamma, Normal) +def _kl_gamma_normal(p, q): + var_normal = q.scale.pow(2) + beta_sqr = p.rate.pow(2) + t1 = ( + 0.5 * torch.log(beta_sqr * var_normal * 2 * math.pi) + - p.concentration + - p.concentration.lgamma() + ) + t2 = 0.5 * (p.concentration.pow(2) + p.concentration) / beta_sqr + t3 = q.loc * p.concentration / p.rate + t4 = 0.5 * q.loc.pow(2) + return ( + t1 + + (p.concentration - 1) * p.concentration.digamma() + + (t2 - t3 + t4) / var_normal + ) + + +@register_kl(Gumbel, Beta) +@register_kl(Gumbel, ContinuousBernoulli) +@register_kl(Gumbel, Exponential) +@register_kl(Gumbel, Gamma) +@register_kl(Gumbel, Pareto) +@register_kl(Gumbel, Uniform) +def _kl_gumbel_infinity(p, q): + return _infinite_like(p.loc) + + +# TODO: Add Gumbel-Laplace KL Divergence + + +@register_kl(Gumbel, Normal) +def _kl_gumbel_normal(p, q): + param_ratio = p.scale / q.scale + t1 = (param_ratio / math.sqrt(2 * math.pi)).log() + t2 = (math.pi * param_ratio * 0.5).pow(2) / 3 + t3 = ((p.loc + p.scale * _euler_gamma - q.loc) / q.scale).pow(2) * 0.5 + return -t1 + t2 + t3 - (_euler_gamma + 1) + + +@register_kl(Laplace, Beta) +@register_kl(Laplace, ContinuousBernoulli) +@register_kl(Laplace, Exponential) +@register_kl(Laplace, Gamma) +@register_kl(Laplace, Pareto) +@register_kl(Laplace, Uniform) +def _kl_laplace_infinity(p, q): + return _infinite_like(p.loc) + + +@register_kl(Laplace, Normal) +def _kl_laplace_normal(p, q): + var_normal = q.scale.pow(2) + scale_sqr_var_ratio = p.scale.pow(2) / var_normal + t1 = 0.5 * torch.log(2 * scale_sqr_var_ratio / math.pi) + t2 = 0.5 * p.loc.pow(2) + t3 = p.loc * q.loc + t4 = 0.5 * q.loc.pow(2) + return -t1 + scale_sqr_var_ratio + (t2 - t3 + t4) / var_normal - 1 + + +@register_kl(Normal, Beta) +@register_kl(Normal, ContinuousBernoulli) +@register_kl(Normal, Exponential) +@register_kl(Normal, Gamma) +@register_kl(Normal, Pareto) +@register_kl(Normal, Uniform) +def _kl_normal_infinity(p, q): + return _infinite_like(p.loc) + + +@register_kl(Normal, Gumbel) +def _kl_normal_gumbel(p, q): + mean_scale_ratio = p.loc / q.scale + var_scale_sqr_ratio = (p.scale / q.scale).pow(2) + loc_scale_ratio = q.loc / q.scale + t1 = var_scale_sqr_ratio.log() * 0.5 + t2 = mean_scale_ratio - loc_scale_ratio + t3 = torch.exp(-mean_scale_ratio + 0.5 * var_scale_sqr_ratio + loc_scale_ratio) + return -t1 + t2 + t3 - (0.5 * (1 + math.log(2 * math.pi))) + + +@register_kl(Normal, Laplace) +def _kl_normal_laplace(p, q): + loc_diff = p.loc - q.loc + scale_ratio = p.scale / q.scale + loc_diff_scale_ratio = loc_diff / p.scale + t1 = torch.log(scale_ratio) + t2 = ( + math.sqrt(2 / math.pi) * p.scale * torch.exp(-0.5 * loc_diff_scale_ratio.pow(2)) + ) + t3 = loc_diff * torch.erf(math.sqrt(0.5) * loc_diff_scale_ratio) + return -t1 + (t2 + t3) / q.scale - (0.5 * (1 + math.log(0.5 * math.pi))) + + +@register_kl(Pareto, Beta) +@register_kl(Pareto, ContinuousBernoulli) +@register_kl(Pareto, Uniform) +def _kl_pareto_infinity(p, q): + return _infinite_like(p.scale) + + +@register_kl(Pareto, Exponential) +def _kl_pareto_exponential(p, q): + scale_rate_prod = p.scale * q.rate + t1 = (p.alpha / scale_rate_prod).log() + t2 = p.alpha.reciprocal() + t3 = p.alpha * scale_rate_prod / (p.alpha - 1) + result = t1 - t2 + t3 - 1 + result[p.alpha <= 1] = inf + return result + + +@register_kl(Pareto, Gamma) +def _kl_pareto_gamma(p, q): + common_term = p.scale.log() + p.alpha.reciprocal() + t1 = p.alpha.log() - common_term + t2 = q.concentration.lgamma() - q.concentration * q.rate.log() + t3 = (1 - q.concentration) * common_term + t4 = q.rate * p.alpha * p.scale / (p.alpha - 1) + result = t1 + t2 + t3 + t4 - 1 + result[p.alpha <= 1] = inf + return result + + +# TODO: Add Pareto-Laplace KL Divergence + + +@register_kl(Pareto, Normal) +def _kl_pareto_normal(p, q): + var_normal = 2 * q.scale.pow(2) + common_term = p.scale / (p.alpha - 1) + t1 = (math.sqrt(2 * math.pi) * q.scale * p.alpha / p.scale).log() + t2 = p.alpha.reciprocal() + t3 = p.alpha * common_term.pow(2) / (p.alpha - 2) + t4 = (p.alpha * common_term - q.loc).pow(2) + result = t1 - t2 + (t3 + t4) / var_normal - 1 + result[p.alpha <= 2] = inf + return result + + +@register_kl(Poisson, Bernoulli) +@register_kl(Poisson, Binomial) +def _kl_poisson_infinity(p, q): + return _infinite_like(p.rate) + + +@register_kl(Uniform, Beta) +def _kl_uniform_beta(p, q): + common_term = p.high - p.low + t1 = torch.log(common_term) + t2 = ( + (q.concentration1 - 1) + * (_x_log_x(p.high) - _x_log_x(p.low) - common_term) + / common_term + ) + t3 = ( + (q.concentration0 - 1) + * (_x_log_x(1 - p.high) - _x_log_x(1 - p.low) + common_term) + / common_term + ) + t4 = ( + q.concentration1.lgamma() + + q.concentration0.lgamma() + - (q.concentration1 + q.concentration0).lgamma() + ) + result = t3 + t4 - t1 - t2 + result[(p.high > q.support.upper_bound) | (p.low < q.support.lower_bound)] = inf + return result + + +@register_kl(Uniform, ContinuousBernoulli) +def _kl_uniform_continuous_bernoulli(p, q): + result = ( + -p.entropy() + - p.mean * q.logits + - torch.log1p(-q.probs) + - q._cont_bern_log_norm() + ) + return torch.where( + torch.max( + torch.ge(p.high, q.support.upper_bound), + torch.le(p.low, q.support.lower_bound), + ), + torch.ones_like(result) * inf, + result, + ) + + +@register_kl(Uniform, Exponential) +def _kl_uniform_exponetial(p, q): + result = q.rate * (p.high + p.low) / 2 - ((p.high - p.low) * q.rate).log() + result[p.low < q.support.lower_bound] = inf + return result + + +@register_kl(Uniform, Gamma) +def _kl_uniform_gamma(p, q): + common_term = p.high - p.low + t1 = common_term.log() + t2 = q.concentration.lgamma() - q.concentration * q.rate.log() + t3 = ( + (1 - q.concentration) + * (_x_log_x(p.high) - _x_log_x(p.low) - common_term) + / common_term + ) + t4 = q.rate * (p.high + p.low) / 2 + result = -t1 + t2 + t3 + t4 + result[p.low < q.support.lower_bound] = inf + return result + + +@register_kl(Uniform, Gumbel) +def _kl_uniform_gumbel(p, q): + common_term = q.scale / (p.high - p.low) + high_loc_diff = (p.high - q.loc) / q.scale + low_loc_diff = (p.low - q.loc) / q.scale + t1 = common_term.log() + 0.5 * (high_loc_diff + low_loc_diff) + t2 = common_term * (torch.exp(-high_loc_diff) - torch.exp(-low_loc_diff)) + return t1 - t2 + + +# TODO: Uniform-Laplace KL Divergence + + +@register_kl(Uniform, Normal) +def _kl_uniform_normal(p, q): + common_term = p.high - p.low + t1 = (math.sqrt(math.pi * 2) * q.scale / common_term).log() + t2 = (common_term).pow(2) / 12 + t3 = ((p.high + p.low - 2 * q.loc) / 2).pow(2) + return t1 + 0.5 * (t2 + t3) / q.scale.pow(2) + + +@register_kl(Uniform, Pareto) +def _kl_uniform_pareto(p, q): + support_uniform = p.high - p.low + t1 = (q.alpha * q.scale.pow(q.alpha) * (support_uniform)).log() + t2 = (_x_log_x(p.high) - _x_log_x(p.low) - support_uniform) / support_uniform + result = t2 * (q.alpha + 1) - t1 + result[p.low < q.support.lower_bound] = inf + return result + + +@register_kl(Independent, Independent) +def _kl_independent_independent(p, q): + if p.reinterpreted_batch_ndims != q.reinterpreted_batch_ndims: + raise NotImplementedError + result = kl_divergence(p.base_dist, q.base_dist) + return _sum_rightmost(result, p.reinterpreted_batch_ndims) + + +@register_kl(Cauchy, Cauchy) +def _kl_cauchy_cauchy(p, q): + # From https://arxiv.org/abs/1905.10965 + t1 = ((p.scale + q.scale).pow(2) + (p.loc - q.loc).pow(2)).log() + t2 = (4 * p.scale * q.scale).log() + return t1 - t2 + + +def _add_kl_info(): + """Appends a list of implemented KL functions to the doc for kl_divergence.""" + rows = [ + "KL divergence is currently implemented for the following distribution pairs:" + ] + for p, q in sorted( + _KL_REGISTRY, key=lambda p_q: (p_q[0].__name__, p_q[1].__name__) + ): + rows.append( + f"* :class:`~torch.distributions.{p.__name__}` and :class:`~torch.distributions.{q.__name__}`" + ) + kl_info = "\n\t".join(rows) + if kl_divergence.__doc__: + kl_divergence.__doc__ += kl_info # type: ignore[operator] diff --git a/shared/package-files/38/38dc06b9b50904e84a59d961d229bdb2aee3ffa87f6bac00234e48e1f83f45e2/cosine_similarity_native.h b/shared/package-files/38/38dc06b9b50904e84a59d961d229bdb2aee3ffa87f6bac00234e48e1f83f45e2/cosine_similarity_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b38963a1074e678899ffd4d40697c04b662f1c2f --- /dev/null +++ b/shared/package-files/38/38dc06b9b50904e84a59d961d229bdb2aee3ffa87f6bac00234e48e1f83f45e2/cosine_similarity_native.h @@ -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 cosine_similarity(const at::Tensor & x1, const at::Tensor & x2, int64_t dim=1, double eps=1e-08); +} // namespace native +} // namespace at diff --git a/shared/package-files/38/38de4fc44e6c611e982dff20ad6cbef05c147c6890b76f25d6cd9e96faca818c/poly1305.pyi b/shared/package-files/38/38de4fc44e6c611e982dff20ad6cbef05c147c6890b76f25d6cd9e96faca818c/poly1305.pyi new file mode 100644 index 0000000000000000000000000000000000000000..886f670276817b1e6eb89d841777ffacbb9c25e8 --- /dev/null +++ b/shared/package-files/38/38de4fc44e6c611e982dff20ad6cbef05c147c6890b76f25d6cd9e96faca818c/poly1305.pyi @@ -0,0 +1,9 @@ +class Poly1305(object): + def __init__(self, key: bytes) -> None: ... + def finalize(self) -> bytes: ... + @classmethod + def generate_tag(cls, key: bytes, data: bytes) -> bytes: ... + def update(self, data: bytes) -> None: ... + def verify(self, tag: bytes) -> None: ... + @classmethod + def verify_tag(cls, key: bytes, data: bytes, tag: bytes) -> None: ... diff --git a/shared/package-files/38/38de8216ea5a6d705096df21859e1dcc3bedcfa101f4fb91f332b190a6efab89/api.py b/shared/package-files/38/38de8216ea5a6d705096df21859e1dcc3bedcfa101f4fb91f332b190a6efab89/api.py new file mode 100644 index 0000000000000000000000000000000000000000..8b7f385168efb3b9d61682d62924c62250048ace --- /dev/null +++ b/shared/package-files/38/38de8216ea5a6d705096df21859e1dcc3bedcfa101f4fb91f332b190a6efab89/api.py @@ -0,0 +1,10 @@ +__all__ = [ + "SimpleTable", + "csv2st", + "load_pickle", + "save_pickle", + "savetxt" +] +from .foreign import savetxt +from .smpickle import load_pickle, save_pickle +from .table import SimpleTable, csv2st diff --git a/shared/package-files/38/38df84f99a924a1799f3c56b297d8cdcf5e915b18451464f31afc07f497ee1fd/abc.py b/shared/package-files/38/38df84f99a924a1799f3c56b297d8cdcf5e915b18451464f31afc07f497ee1fd/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e498efabfab0dcf31cd7731f8f821cc423bc4f --- /dev/null +++ b/shared/package-files/38/38df84f99a924a1799f3c56b297d8cdcf5e915b18451464f31afc07f497ee1fd/abc.py @@ -0,0 +1,33 @@ +from abc import ABC + + +class RichRenderable(ABC): + """An abstract base class for Rich renderables. + + Note that there is no need to extend this class, the intended use is to check if an + object supports the Rich renderable protocol. For example:: + + if isinstance(my_object, RichRenderable): + console.print(my_object) + + """ + + @classmethod + def __subclasshook__(cls, other: type) -> bool: + """Check if this class supports the rich render protocol.""" + return hasattr(other, "__rich_console__") or hasattr(other, "__rich__") + + +if __name__ == "__main__": # pragma: no cover + from pip._vendor.rich.text import Text + + t = Text() + print(isinstance(Text, RichRenderable)) + print(isinstance(t, RichRenderable)) + + class Foo: + pass + + f = Foo() + print(isinstance(f, RichRenderable)) + print(isinstance("", RichRenderable)) diff --git a/shared/package-files/38/38e0a3302947d417f5e12cbb8c0770cc4782c453dbf1751edaa78f6c4c6f5f07/dh.py b/shared/package-files/38/38e0a3302947d417f5e12cbb8c0770cc4782c453dbf1751edaa78f6c4c6f5f07/dh.py new file mode 100644 index 0000000000000000000000000000000000000000..31c9748a91cdf891d436a0c68448dc2bf7f005eb --- /dev/null +++ b/shared/package-files/38/38e0a3302947d417f5e12cbb8c0770cc4782c453dbf1751edaa78f6c4c6f5f07/dh.py @@ -0,0 +1,135 @@ +# 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.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + +generate_parameters = rust_openssl.dh.generate_parameters + + +DHPrivateNumbers = rust_openssl.dh.DHPrivateNumbers +DHPublicNumbers = rust_openssl.dh.DHPublicNumbers +DHParameterNumbers = rust_openssl.dh.DHParameterNumbers + + +class DHParameters(metaclass=abc.ABCMeta): + @abc.abstractmethod + def generate_private_key(self) -> DHPrivateKey: + """ + Generates and returns a DHPrivateKey. + """ + + @abc.abstractmethod + def parameter_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.ParameterFormat, + ) -> bytes: + """ + Returns the parameters serialized as bytes. + """ + + @abc.abstractmethod + def parameter_numbers(self) -> DHParameterNumbers: + """ + Returns a DHParameterNumbers. + """ + + +DHParametersWithSerialization = DHParameters +DHParameters.register(rust_openssl.dh.DHParameters) + + +class DHPublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this public key. + """ + + @abc.abstractmethod + def public_numbers(self) -> DHPublicNumbers: + """ + Returns a DHPublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +DHPublicKeyWithSerialization = DHPublicKey +DHPublicKey.register(rust_openssl.dh.DHPublicKey) + + +class DHPrivateKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def public_key(self) -> DHPublicKey: + """ + The DHPublicKey associated with this private key. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this private key. + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: DHPublicKey) -> bytes: + """ + Given peer's DHPublicKey, carry out the key exchange and + return shared key as bytes. + """ + + @abc.abstractmethod + def private_numbers(self) -> DHPrivateNumbers: + """ + Returns a DHPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + +DHPrivateKeyWithSerialization = DHPrivateKey +DHPrivateKey.register(rust_openssl.dh.DHPrivateKey) diff --git a/shared/package-files/38/38e437d6d14b0e56a6816a9b8e5d0b9642df49e4a4ca0a330cf552c28a3e07b6/subtract.h b/shared/package-files/38/38e437d6d14b0e56a6816a9b8e5d0b9642df49e4a4ca0a330cf552c28a3e07b6/subtract.h new file mode 100644 index 0000000000000000000000000000000000000000..574f877f647674dce6a86ad581547f4d10945477 --- /dev/null +++ b/shared/package-files/38/38e437d6d14b0e56a6816a9b8e5d0b9642df49e4a4ca0a330cf552c28a3e07b6/subtract.h @@ -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::subtract.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & subtract_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1) { + return at::_ops::subtract_out::call(self, other, alpha, out); +} +// aten::subtract.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & subtract_outf(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out) { + return at::_ops::subtract_out::call(self, other, alpha, out); +} + +// aten::subtract.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor +inline at::Tensor subtract(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1) { + return at::_ops::subtract_Tensor::call(self, other, alpha); +} + +// aten::subtract.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor +inline at::Tensor subtract(const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha=1) { + return at::_ops::subtract_Scalar::call(self, other, alpha); +} + +} diff --git a/shared/package-files/38/38e4a5aac47b6591bb76b9923bbbf93e5acf71baeaa6feec12dea1f292cd6325/test_piecewise.py b/shared/package-files/38/38e4a5aac47b6591bb76b9923bbbf93e5acf71baeaa6feec12dea1f292cd6325/test_piecewise.py new file mode 100644 index 0000000000000000000000000000000000000000..2d4de12b284ec701a7a25ea5ecde00cd9b55b3c7 --- /dev/null +++ b/shared/package-files/38/38e4a5aac47b6591bb76b9923bbbf93e5acf71baeaa6feec12dea1f292cd6325/test_piecewise.py @@ -0,0 +1,1606 @@ +from sympy.concrete.summations import Sum +from sympy.core.add import Add +from sympy.core.basic import Basic +from sympy.core.containers import Tuple +from sympy.core.expr import unchanged +from sympy.core.function import (Function, diff, expand) +from sympy.core.mul import Mul +from sympy.core.mod import Mod +from sympy.core.numbers import (Float, I, Rational, oo, pi, zoo) +from sympy.core.relational import (Eq, Ge, Gt, Ne) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, transpose) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) +from sympy.functions.elementary.piecewise import (Piecewise, + piecewise_fold, piecewise_exclusive, Undefined, ExprCondPair) +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.integrals.integrals import (Integral, integrate) +from sympy.logic.boolalg import (And, ITE, Not, Or) +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.printing import srepr +from sympy.sets.contains import Contains +from sympy.sets.sets import Interval +from sympy.solvers.solvers import solve +from sympy.testing.pytest import raises, slow +from sympy.utilities.lambdify import lambdify + +a, b, c, d, x, y = symbols('a:d, x, y') +z = symbols('z', nonzero=True) + + +def test_piecewise1(): + + # Test canonicalization + assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True)) + assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1), + ExprCondPair(0, True)) + assert Piecewise((x, x < 1), (0, True), (1, True)) == \ + Piecewise((x, x < 1), (0, True)) + assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \ + Piecewise((x, x < 1)) + assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \ + Piecewise((x, x < 1), (0, True)) + assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \ + Piecewise((x, x < 1), (0, True)) + assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \ + Piecewise((x, Or(x < 1, x < 2)), (0, True)) + assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x + assert Piecewise((x, True)) == x + # Explicitly constructed empty Piecewise not accepted + raises(TypeError, lambda: Piecewise()) + # False condition is never retained + assert Piecewise((2*x, x < 0), (x, False)) == \ + Piecewise((2*x, x < 0), (x, False), evaluate=False) == \ + Piecewise((2*x, x < 0)) + assert Piecewise((x, False)) == Undefined + raises(TypeError, lambda: Piecewise(x)) + assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False + raises(TypeError, lambda: Piecewise((x, 2))) + raises(TypeError, lambda: Piecewise((x, x**2))) + raises(TypeError, lambda: Piecewise(([1], True))) + assert Piecewise(((1, 2), True)) == Tuple(1, 2) + cond = (Piecewise((1, x < 0), (2, True)) < y) + assert Piecewise((1, cond) + ) == Piecewise((1, ITE(x < 0, y > 1, y > 2))) + + assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1)) + ) == Piecewise((1, x > 0), (2, x > -1)) + assert Piecewise((1, x <= 0), (2, (x < 0) & (x > -1)) + ) == Piecewise((1, x <= 0)) + + # test for supporting Contains in Piecewise + pwise = Piecewise( + (1, And(x <= 6, x > 1, Contains(x, S.Integers))), + (0, True)) + assert pwise.subs(x, pi) == 0 + assert pwise.subs(x, 2) == 1 + assert pwise.subs(x, 7) == 0 + + # Test subs + p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0)) + p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0)) + assert p.subs(x, x**2) == p_x2 + assert p.subs(x, -5) == -1 + assert p.subs(x, -1) == 1 + assert p.subs(x, 1) == log(1) + + # More subs tests + p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi)) + p3 = Piecewise((1, Eq(x, 0)), (1/x, True)) + p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2)) + assert p2.subs(x, 2) == 1 + assert p2.subs(x, 4) == -1 + assert p2.subs(x, 10) == 0 + assert p3.subs(x, 0.0) == 1 + assert p4.subs(x, 0.0) == 1 + + + f, g, h = symbols('f,g,h', cls=Function) + pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1)) + pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1)) + assert pg.subs(g, f) == pf + + assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1 + assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0 + assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1 + assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1 + assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \ + Piecewise((1, Eq(exp(z), cos(z))), (0, True)) + + p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True)) + assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True)) + + assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True) + ).subs(x, 1) == Piecewise((-1, y < 1), (2, True)) + assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1 + + p6 = Piecewise((x, x > 0)) + n = symbols('n', negative=True) + assert p6.subs(x, n) == Undefined + + # Test evalf + assert p.evalf() == Piecewise((-1.0, x < -1), (x**2, x < 0), (log(x), True)) + assert p.evalf(subs={x: -2}) == -1.0 + assert p.evalf(subs={x: -1}) == 1.0 + assert p.evalf(subs={x: 1}) == log(1) + assert p6.evalf(subs={x: -5}) == Undefined + + # Test doit + f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1)) + assert f_int.doit() == Piecewise( (S.Half, x < 1) ) + + # Test differentiation + f = x + fp = x*p + dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0)) + fp_dx = x*dp + p + assert diff(p, x) == dp + assert diff(f*p, x) == fp_dx + + # Test simple arithmetic + assert x*p == fp + assert x*p + p == p + x*p + assert p + f == f + p + assert p + dp == dp + p + assert p - dp == -(dp - p) + + # Test power + dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0)) + assert dp**2 == dp2 + + # Test _eval_interval + f1 = x*y + 2 + f2 = x*y**2 + 3 + peval = Piecewise((f1, x < 0), (f2, x > 0)) + peval_interval = f1.subs( + x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0) + assert peval._eval_interval(x, 0, 0) == 0 + assert peval._eval_interval(x, -1, 1) == peval_interval + peval2 = Piecewise((f1, x < 0), (f2, True)) + assert peval2._eval_interval(x, 0, 0) == 0 + assert peval2._eval_interval(x, 1, -1) == -peval_interval + assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1) + assert peval2._eval_interval(x, -1, 1) == peval_interval + assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0) + assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1) + + # Test integration + assert p.integrate() == Piecewise( + (-x, x < -1), + (x**3/3 + Rational(4, 3), x < 0), + (x*log(x) - x + Rational(4, 3), True)) + p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) + assert integrate(p, (x, -2, 2)) == Rational(5, 6) + assert integrate(p, (x, 2, -2)) == Rational(-5, 6) + p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True)) + assert integrate(p, (x, -oo, oo)) == 2 + p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) + assert integrate(p, (x, -2, 2)) == Undefined + + # Test commutativity + assert isinstance(p, Piecewise) and p.is_commutative is True + + +def test_piecewise_free_symbols(): + f = Piecewise((x, a < 0), (y, True)) + assert f.free_symbols == {x, y, a} + + +def test_piecewise_integrate1(): + x, y = symbols('x y', real=True) + + f = Piecewise(((x - 2)**2, x >= 0), (1, True)) + assert integrate(f, (x, -2, 2)) == Rational(14, 3) + + g = Piecewise(((x - 5)**5, x >= 4), (f, True)) + assert integrate(g, (x, -2, 2)) == Rational(14, 3) + assert integrate(g, (x, -2, 5)) == Rational(43, 6) + + assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) + + g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2)) + assert integrate(g, (x, -2, 2)) == Rational(14, 3) + assert integrate(g, (x, -2, 5)) == Rational(-701, 6) + + assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True)) + + g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True)) + assert integrate(g, (x, -2, 2)) == Rational(28, 3) + assert integrate(g, (x, -2, 5)) == Rational(-673, 6) + + +def test_piecewise_integrate1b(): + g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0)) + assert integrate(g, (x, -1, 1)) == 0 + + g = Piecewise((1, x - y < 0), (0, True)) + assert integrate(g, (y, -oo, 0)) == -Min(0, x) + assert g.subs(x, -3).integrate((y, -oo, 0)) == 3 + assert integrate(g, (y, 0, -oo)) == Min(0, x) + assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo + assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42 + assert integrate(g, (y, -oo, oo)) == -x + oo + + g = Piecewise((0, x < 0), (x, x <= 1), (1, True)) + gy1 = g.integrate((x, y, 1)) + g1y = g.integrate((x, 1, y)) + for yy in (-1, S.Half, 2): + assert g.integrate((x, yy, 1)) == gy1.subs(y, yy) + assert g.integrate((x, 1, yy)) == g1y.subs(y, yy) + assert gy1 == Piecewise( + (-Min(1, Max(0, y))**2/2 + S.Half, y < 1), + (-y + 1, True)) + assert g1y == Piecewise( + (Min(1, Max(0, y))**2/2 - S.Half, y < 1), + (y - 1, True)) + + +@slow +def test_piecewise_integrate1ca(): + y = symbols('y', real=True) + g = Piecewise( + (1 - x, Interval(0, 1).contains(x)), + (1 + x, Interval(-1, 0).contains(x)), + (0, True) + ) + gy1 = g.integrate((x, y, 1)) + g1y = g.integrate((x, 1, y)) + + assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) + assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) + assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) + assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) + assert g.integrate((x, 2, 1)) == gy1.subs(y, 2) + assert g.integrate((x, 1, 2)) == g1y.subs(y, 2) + assert piecewise_fold(gy1.rewrite(Piecewise) + ).simplify() == Piecewise( + (1, y <= -1), + (-y**2/2 - y + S.Half, y <= 0), + (y**2/2 - y + S.Half, y < 1), + (0, True)) + assert piecewise_fold(g1y.rewrite(Piecewise) + ).simplify() == Piecewise( + (-1, y <= -1), + (y**2/2 + y - S.Half, y <= 0), + (-y**2/2 + y - S.Half, y < 1), + (0, True)) + assert gy1 == Piecewise( + ( + -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + + Min(1, Max(0, y))**2 + S.Half, y < 1), + (0, True) + ) + assert g1y == Piecewise( + ( + Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - + Min(1, Max(0, y))**2 - S.Half, y < 1), + (0, True)) + + +@slow +def test_piecewise_integrate1cb(): + y = symbols('y', real=True) + g = Piecewise( + (0, Or(x <= -1, x >= 1)), + (1 - x, x > 0), + (1 + x, True) + ) + gy1 = g.integrate((x, y, 1)) + g1y = g.integrate((x, 1, y)) + + assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) + assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) + assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) + assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) + assert g.integrate((x, 2, 1)) == gy1.subs(y, 2) + assert g.integrate((x, 1, 2)) == g1y.subs(y, 2) + + assert piecewise_fold(gy1.rewrite(Piecewise) + ).simplify() == Piecewise( + (1, y <= -1), + (-y**2/2 - y + S.Half, y <= 0), + (y**2/2 - y + S.Half, y < 1), + (0, True)) + assert piecewise_fold(g1y.rewrite(Piecewise) + ).simplify() == Piecewise( + (-1, y <= -1), + (y**2/2 + y - S.Half, y <= 0), + (-y**2/2 + y - S.Half, y < 1), + (0, True)) + + # g1y and gy1 should simplify if the condition that y < 1 + # is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y) + assert gy1 == Piecewise( + ( + -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + + Min(1, Max(0, y))**2 + S.Half, y < 1), + (0, True) + ) + assert g1y == Piecewise( + ( + Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - + Min(1, Max(0, y))**2 - S.Half, y < 1), + (0, True)) + + +def test_piecewise_integrate2(): + from itertools import permutations + lim = Tuple(x, c, d) + p = Piecewise((1, x < a), (2, x > b), (3, True)) + q = p.integrate(lim) + assert q == Piecewise( + (-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d), + (-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True)) + for v in permutations((1, 2, 3, 4)): + r = dict(zip((a, b, c, d), v)) + assert p.subs(r).integrate(lim.subs(r)) == q.subs(r) + + +def test_meijer_bypass(): + # totally bypass meijerg machinery when dealing + # with Piecewise in integrate + assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3 + + +def test_piecewise_integrate3_inequality_conditions(): + from sympy.utilities.iterables import cartes + lim = (x, 0, 5) + # set below includes two pts below range, 2 pts in range, + # 2 pts above range, and the boundaries + N = (-2, -1, 0, 1, 2, 5, 6, 7) + + p = Piecewise((1, x > a), (2, x > b), (0, True)) + ans = p.integrate(lim) + for i, j in cartes(N, repeat=2): + reps = dict(zip((a, b), (i, j))) + assert ans.subs(reps) == p.subs(reps).integrate(lim) + assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1 + + p = Piecewise((1, x > a), (2, x < b), (0, True)) + ans = p.integrate(lim) + for i, j in cartes(N, repeat=2): + reps = dict(zip((a, b), (i, j))) + assert ans.subs(reps) == p.subs(reps).integrate(lim) + + # delete old tests that involved c1 and c2 since those + # reduce to the above except that a value of 0 was used + # for two expressions whereas the above uses 3 different + # values + + +@slow +def test_piecewise_integrate4_symbolic_conditions(): + a = Symbol('a', real=True) + b = Symbol('b', real=True) + x = Symbol('x', real=True) + y = Symbol('y', real=True) + p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) + p1 = Piecewise((0, x < a), (0, x > b), (1, True)) + p2 = Piecewise((0, x > b), (0, x < a), (1, True)) + p3 = Piecewise((0, x < a), (1, x < b), (0, True)) + p4 = Piecewise((0, x > b), (1, x > a), (0, True)) + p5 = Piecewise((1, And(a < x, x < b)), (0, True)) + + # check values of a=1, b=3 (and reversed) with values + # of y of 0, 1, 2, 3, 4 + lim = Tuple(x, -oo, y) + for p in (p0, p1, p2, p3, p4, p5): + ans = p.integrate(lim) + for i in range(5): + reps = {a:1, b:3, y:i} + assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) + reps = {a: 3, b:1, y:i} + assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) + lim = Tuple(x, y, oo) + for p in (p0, p1, p2, p3, p4, p5): + ans = p.integrate(lim) + for i in range(5): + reps = {a:1, b:3, y:i} + assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) + reps = {a:3, b:1, y:i} + assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) + + ans = Piecewise( + (0, x <= Min(a, b)), + (x - Min(a, b), x <= b), + (b - Min(a, b), True)) + for i in (p0, p1, p2, p4): + assert i.integrate(x) == ans + assert p3.integrate(x) == Piecewise( + (0, x < a), + (-a + x, x <= Max(a, b)), + (-a + Max(a, b), True)) + assert p5.integrate(x) == Piecewise( + (0, x <= a), + (-a + x, x <= Max(a, b)), + (-a + Max(a, b), True)) + + p1 = Piecewise((0, x < a), (S.Half, x > b), (1, True)) + p2 = Piecewise((S.Half, x > b), (0, x < a), (1, True)) + p3 = Piecewise((0, x < a), (1, x < b), (S.Half, True)) + p4 = Piecewise((S.Half, x > b), (1, x > a), (0, True)) + p5 = Piecewise((1, And(a < x, x < b)), (S.Half, x > b), (0, True)) + + # check values of a=1, b=3 (and reversed) with values + # of y of 0, 1, 2, 3, 4 + lim = Tuple(x, -oo, y) + for p in (p1, p2, p3, p4, p5): + ans = p.integrate(lim) + for i in range(5): + reps = {a:1, b:3, y:i} + assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) + reps = {a: 3, b:1, y:i} + assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) + + +def test_piecewise_integrate5_independent_conditions(): + p = Piecewise((0, Eq(y, 0)), (x*y, True)) + assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True)) + + +def test_issue_22917(): + p = (Piecewise((0, ITE((x - y > 1) | (2 * x - 2 * y > 1), False, + ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))), + (Piecewise((0, ITE(x - y > 1, True, 2 * x - 2 * y > 1)), + (2 * Piecewise((0, x - y > 1), (y, True)), True)), True)) + + 2 * Piecewise((1, ITE((x - y > 1) | (2 * x - 2 * y > 1), False, + ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))), + (Piecewise((1, ITE(x - y > 1, True, 2 * x - 2 * y > 1)), + (2 * Piecewise((1, x - y > 1), (x, True)), True)), True))) + assert piecewise_fold(p) == Piecewise((2, (x - y > S.Half) | (x - y > 1)), + (2*y + 4, x - y > 1), + (4*x + 2*y, True)) + assert piecewise_fold(p > 1).rewrite(ITE) == ITE((x - y > S.Half) | (x - y > 1), True, + ITE(x - y > 1, 2*y + 4 > 1, 4*x + 2*y > 1)) + + +def test_piecewise_simplify(): + p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)), + ((-1)**x*(-1), True)) + assert p.simplify() == \ + Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True)) + # simplify when there are Eq in conditions + assert Piecewise( + (a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify( + ) == Piecewise( + (0, And(Eq(a, 0), Eq(b, 0))), (1, True)) + assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)), + Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y + + a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify( + ) == Piecewise( + (2*x, And(Eq(a, 0), Eq(y, 0))), + (2, And(Eq(a, 1), Eq(y, 0))), + (0, True)) + args = (2, And(Eq(x, 2), Ge(y, 0))), (x, True) + assert Piecewise(*args).simplify() == Piecewise(*args) + args = (1, Eq(x, 0)), (sin(x)/x, True) + assert Piecewise(*args).simplify() == Piecewise(*args) + assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True) + ).simplify() == x + # check that x or f(x) are recognized as being Symbol-like for lhs + args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True)) + ans = x + sin(x) + 1 + f = Function('f') + assert Piecewise(*args).simplify() == ans + assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x)) + + # issue 18634 + d = Symbol("d", integer=True) + n = Symbol("n", integer=True) + t = Symbol("t", positive=True) + expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True)) + assert expr.simplify() == -d + 2*n + + # issue 22747 + p = Piecewise((0, (t < -2) & (t < -1) & (t < 0)), ((t/2 + 1)*(t + + 1)*(t + 2), (t < -1) & (t < 0)), ((S.Half - t/2)*(1 - t)*(t + 1), + (t < -2) & (t < -1) & (t < 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half + - t/2)*(1 - t)), (t < -2) & (t < -1) & (t < 0) & (t < 1)), ((t + + 1)*((S.Half - t/2)*(1 - t) + (t/2 + 1)*(t + 2)), (t < -1) & (t < + 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(1 - t)), (t < -1) & + (t < 0) & (t < 1)), (0, (t < -2) & (t < -1)), ((t/2 + 1)*(t + + 1)*(t + 2), t < -1), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(t + + 1)), (t < 0) & ((t < -2) | (t < 0))), ((S.Half - t/2)*(1 - t)*(t + + 1), (t < 1) & ((t < -2) | (t < 1))), (0, True)) + Piecewise((0, + (t < -1) & (t < 0) & (t < 1)), ((1 - t)*(t/2 + S.Half)*(t + 1), + (t < 0) & (t < 1)), ((1 - t)*(1 - t/2)*(2 - t), (t < -1) & (t < + 0) & (t < 2)), ((1 - t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 - + t)), (t < -1) & (t < 0) & (t < 1) & (t < 2)), ((1 - t)*((1 - + t/2)*(2 - t) + (t/2 + S.Half)*(t + 1)), (t < 0) & (t < 2)), ((1 - + t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 - t)), (t < 0) & (t < + 1) & (t < 2)), (0, (t < -1) & (t < 0)), ((1 - t)*(t/2 + + S.Half)*(t + 1), t < 0), ((1 - t)*(t*(1 - t/2) + (1 - t)*(t/2 + + S.Half)), (t < 1) & ((t < -1) | (t < 1))), ((1 - t)*(1 - t/2)*(2 + - t), (t < 2) & ((t < -1) | (t < 2))), (0, True)) + assert p.simplify() == Piecewise( + (0, t < -2), ((t + 1)*(t + 2)**2/2, t < -1), (-3*t**3/2 + - 5*t**2/2 + 1, t < 0), (3*t**3/2 - 5*t**2/2 + 1, t < 1), ((1 - + t)*(t - 2)**2/2, t < 2), (0, True)) + + # coverage + nan = Undefined + covered = Piecewise((1, x > 3), (2, x < 2), (3, x > 1)) + assert covered.simplify().args == covered.args + assert Piecewise((1, x < 2), (2, x < 1), (3, True)).simplify( + ) == Piecewise((1, x < 2), (3, True)) + assert Piecewise((1, x > 2)).simplify() == Piecewise((1, x > 2), + (nan, True)) + assert Piecewise((1, (x >= 2) & (x < oo)) + ).simplify() == Piecewise((1, (x >= 2) & (x < oo)), (nan, True)) + assert Piecewise((1, x < 2), (2, (x > 1) & (x < 3)), (3, True) + ). simplify() == Piecewise((1, x < 2), (2, x < 3), (3, True)) + assert Piecewise((1, x < 2), (2, (x <= 3) & (x > 1)), (3, True) + ).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True)) + assert Piecewise((1, x < 2), (2, (x > 2) & (x < 3)), (3, True) + ).simplify() == Piecewise((1, x < 2), (2, (x > 2) & (x < 3)), + (3, True)) + assert Piecewise((1, x < 2), (2, (x >= 1) & (x <= 3)), (3, True) + ).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True)) + assert Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)), (3, True) + ).simplify() == Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)), + (3, True)) + + +def test_piecewise_solve(): + abs2 = Piecewise((-x, x <= 0), (x, x > 0)) + f = abs2.subs(x, x - 2) + assert solve(f, x) == [2] + assert solve(f - 1, x) == [1, 3] + + f = Piecewise(((x - 2)**2, x >= 0), (1, True)) + assert solve(f, x) == [2] + + g = Piecewise(((x - 5)**5, x >= 4), (f, True)) + assert solve(g, x) == [2, 5] + + g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) + assert solve(g, x) == [2, 5] + + g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2)) + assert solve(g, x) == [5] + + g = Piecewise(((x - 5)**5, x >= 2), (f, True)) + assert solve(g, x) == [5] + + g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False)) + assert solve(g, x) == [5] + + g = Piecewise(((x - 5)**5, x >= 2), + (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0)) + assert solve(g, x) == [5] + + # if no symbol is given the piecewise detection must still work + assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5] + + f = Piecewise(((x - 2)**2, x >= 0), (0, True)) + raises(NotImplementedError, lambda: solve(f, x)) + + def nona(ans): + return list(filter(lambda x: x is not S.NaN, ans)) + p = Piecewise((x**2 - 4, x < y), (x - 2, True)) + ans = solve(p, x) + assert nona([i.subs(y, -2) for i in ans]) == [2] + assert nona([i.subs(y, 2) for i in ans]) == [-2, 2] + assert nona([i.subs(y, 3) for i in ans]) == [-2, 2] + assert ans == [ + Piecewise((-2, y > -2), (S.NaN, True)), + Piecewise((2, y <= 2), (S.NaN, True)), + Piecewise((2, y > 2), (S.NaN, True))] + + # issue 6060 + absxm3 = Piecewise( + (x - 3, 0 <= x - 3), + (3 - x, 0 > x - 3) + ) + assert solve(absxm3 - y, x) == [ + Piecewise((-y + 3, -y < 0), (S.NaN, True)), + Piecewise((y + 3, y >= 0), (S.NaN, True))] + p = Symbol('p', positive=True) + assert solve(absxm3 - p, x) == [-p + 3, p + 3] + + # issue 6989 + f = Function('f') + assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \ + [Piecewise((-1, x > 0), (0, True))] + + # issue 8587 + f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True)) + assert solve(f - 1) == [1/sqrt(2)] + + +def test_piecewise_fold(): + p = Piecewise((x, x < 1), (1, 1 <= x)) + + assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x)) + assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x)) + assert piecewise_fold(Piecewise((1, x < 0), (2, True)) + + Piecewise((10, x < 0), (-10, True))) == \ + Piecewise((11, x < 0), (-8, True)) + + p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True)) + p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True)) + + p = 4*p1 + 2*p2 + assert integrate( + piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1)) + + assert piecewise_fold( + Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True) + )) == Piecewise((1, y <= 0), (-2, y >= 0)) + + assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1))) + ) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1)))) + + a, b = (Piecewise((2, Eq(x, 0)), (0, True)), + Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True))) + assert piecewise_fold(Mul(a, b, evaluate=False) + ) == piecewise_fold(Mul(b, a, evaluate=False)) + + +def test_piecewise_fold_piecewise_in_cond(): + p1 = Piecewise((cos(x), x < 0), (0, True)) + p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True)) + assert p2.subs(x, -pi/2) == 0 + assert p2.subs(x, 1) == 0 + assert p2.subs(x, -pi/4) == 1 + p4 = Piecewise((0, Eq(p1, 0)), (1,True)) + ans = piecewise_fold(p4) + for i in range(-1, 1): + assert ans.subs(x, i) == p4.subs(x, i) + + r1 = 1 < Piecewise((1, x < 1), (3, True)) + ans = piecewise_fold(r1) + for i in range(2): + assert ans.subs(x, i) == r1.subs(x, i) + + p5 = Piecewise((1, x < 0), (3, True)) + p6 = Piecewise((1, x < 1), (3, True)) + p7 = Piecewise((1, p5 < p6), (0, True)) + ans = piecewise_fold(p7) + for i in range(-1, 2): + assert ans.subs(x, i) == p7.subs(x, i) + + +def test_piecewise_fold_piecewise_in_cond_2(): + p1 = Piecewise((cos(x), x < 0), (0, True)) + p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True)) + p3 = Piecewise( + (0, (x >= 0) | Eq(cos(x), 0)), + (1/cos(x), x < 0), + (zoo, True)) # redundant b/c all x are already covered + assert(piecewise_fold(p2) == p3) + + +def test_piecewise_fold_expand(): + p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True)) + + p2 = piecewise_fold(expand((1 - x)*p1)) + cond = ((x >= 0) & (x < 1)) + assert piecewise_fold(expand((1 - x)*p1), evaluate=False + ) == Piecewise((1 - x, cond), (-x, cond), (1, cond), (0, True), evaluate=False) + assert piecewise_fold(expand((1 - x)*p1), evaluate=None + ) == Piecewise((1 - x, cond), (0, True)) + assert p2 == Piecewise((1 - x, cond), (0, True)) + assert p2 == expand(piecewise_fold((1 - x)*p1)) + + +def test_piecewise_duplicate(): + p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) + assert p == Piecewise(*p.args) + + +def test_doit(): + p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) + p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x)) + assert p2.doit() == p1 + assert p2.doit(deep=False) == p2 + # issue 17165 + p1 = Sum(y**x, (x, -1, oo)).doit() + assert p1.doit() == p1 + + +def test_piecewise_interval(): + p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True)) + assert p1.subs(x, -0.5) == 0 + assert p1.subs(x, 0.5) == 0.5 + assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True)) + assert integrate(p1, x) == Piecewise( + (0, x <= 0), + (x**2/2, x <= 1), + (S.Half, True)) + + +def test_piecewise_exclusive(): + p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True)) + assert piecewise_exclusive(p) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)), + (1, x > 0), evaluate=False) + assert piecewise_exclusive(p + 2) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)), + (1, x > 0), evaluate=False) + 2 + assert piecewise_exclusive(Piecewise((1, y <= 0), + (-Piecewise((2, y >= 0)), True))) == \ + Piecewise((1, y <= 0), + (-Piecewise((2, y >= 0), + (S.NaN, y < 0), evaluate=False), y > 0), evaluate=False) + assert piecewise_exclusive(Piecewise((1, x > y))) == Piecewise((1, x > y), + (S.NaN, x <= y), + evaluate=False) + assert piecewise_exclusive(Piecewise((1, x > y)), + skip_nan=True) == Piecewise((1, x > y)) + + xr, yr = symbols('xr, yr', real=True) + + p1 = Piecewise((1, xr < 0), (2, True), evaluate=False) + p1x = Piecewise((1, xr < 0), (2, xr >= 0), evaluate=False) + + p2 = Piecewise((p1, yr < 0), (3, True), evaluate=False) + p2x = Piecewise((p1, yr < 0), (3, yr >= 0), evaluate=False) + p2xx = Piecewise((p1x, yr < 0), (3, yr >= 0), evaluate=False) + + assert piecewise_exclusive(p2) == p2xx + assert piecewise_exclusive(p2, deep=False) == p2x + + +def test_piecewise_collapse(): + assert Piecewise((x, True)) == x + a = x < 1 + assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a)) + assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a)) + b = x < 5 + def canonical(i): + if isinstance(i, Piecewise): + return Piecewise(*i.args) + return i + for args in [ + ((1, a), (Piecewise((2, a), (3, b)), b)), + ((1, a), (Piecewise((2, a), (3, b.reversed)), b)), + ((1, a), (Piecewise((2, a), (3, b)), b), (4, True)), + ((1, a), (Piecewise((2, a), (3, b), (4, True)), b)), + ((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]: + for i in (0, 2, 10): + assert canonical( + Piecewise(*args, evaluate=False).subs(x, i) + ) == canonical(Piecewise(*args).subs(x, i)) + r1, r2, r3, r4 = symbols('r1:5') + a = x < r1 + b = x < r2 + c = x < r3 + d = x < r4 + assert Piecewise((1, a), (Piecewise( + (2, a), (3, b), (4, c)), b), (5, c) + ) == Piecewise((1, a), (3, b), (5, c)) + assert Piecewise((1, a), (Piecewise( + (2, a), (3, b), (4, c), (6, True)), c), (5, d) + ) == Piecewise((1, a), (Piecewise( + (3, b), (4, c)), c), (5, d)) + assert Piecewise((1, Or(a, d)), (Piecewise( + (2, d), (3, b), (4, c)), b), (5, c) + ) == Piecewise((1, Or(a, d)), (Piecewise( + (2, d), (3, b)), b), (5, c)) + assert Piecewise((1, c), (2, ~c), (3, S.true) + ) == Piecewise((1, c), (2, S.true)) + assert Piecewise((1, c), (2, And(~c, b)), (3,True) + ) == Piecewise((1, c), (2, b), (3, True)) + assert Piecewise((1, c), (2, Or(~c, b)), (3,True) + ).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2 + assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True)) + + +def test_piecewise_lambdify(): + p = Piecewise( + (x**2, x < 0), + (x, Interval(0, 1, False, True).contains(x)), + (2 - x, x >= 1), + (0, True) + ) + + f = lambdify(x, p) + assert f(-2.0) == 4.0 + assert f(0.0) == 0.0 + assert f(0.5) == 0.5 + assert f(2.0) == 0.0 + + +def test_piecewise_series(): + from sympy.series.order import O + p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0)) + p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0)) + assert p1.nseries(x, n=2) == p2 + + +def test_piecewise_as_leading_term(): + p1 = Piecewise((1/x, x > 1), (0, True)) + p2 = Piecewise((x, x > 1), (0, True)) + p3 = Piecewise((1/x, x > 1), (x, True)) + p4 = Piecewise((x, x > 1), (1/x, True)) + p5 = Piecewise((1/x, x > 1), (x, True)) + p6 = Piecewise((1/x, x < 1), (x, True)) + p7 = Piecewise((x, x < 1), (1/x, True)) + p8 = Piecewise((x, x > 1), (1/x, True)) + assert p1.as_leading_term(x) == 0 + assert p2.as_leading_term(x) == 0 + assert p3.as_leading_term(x) == x + assert p4.as_leading_term(x) == 1/x + assert p5.as_leading_term(x) == x + assert p6.as_leading_term(x) == 1/x + assert p7.as_leading_term(x) == x + assert p8.as_leading_term(x) == 1/x + + +def test_piecewise_complex(): + p1 = Piecewise((2, x < 0), (1, 0 <= x)) + p2 = Piecewise((2*I, x < 0), (I, 0 <= x)) + p3 = Piecewise((I*x, x > 1), (1 + I, True)) + p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True)) + + assert conjugate(p1) == p1 + assert conjugate(p2) == piecewise_fold(-p2) + assert conjugate(p3) == p4 + + assert p1.is_imaginary is False + assert p1.is_real is True + assert p2.is_imaginary is True + assert p2.is_real is False + assert p3.is_imaginary is None + assert p3.is_real is None + + assert p1.as_real_imag() == (p1, 0) + assert p2.as_real_imag() == (0, -I*p2) + + +def test_conjugate_transpose(): + A, B = symbols("A B", commutative=False) + p = Piecewise((A*B**2, x > 0), (A**2*B, True)) + assert p.adjoint() == \ + Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True)) + assert p.conjugate() == \ + Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True)) + assert p.transpose() == \ + Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True)) + + +def test_piecewise_evaluate(): + assert Piecewise((x, True)) == x + assert Piecewise((x, True), evaluate=True) == x + assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),) + assert Piecewise((1, Eq(1, x)), evaluate=False).args == ( + (1, Eq(1, x)),) + # like the additive and multiplicative identities that + # cannot be kept in Add/Mul, we also do not keep a single True + p = Piecewise((x, True), evaluate=False) + assert p == x + + +def test_as_expr_set_pairs(): + assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \ + [(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))] + + assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \ + [((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))] + + +def test_S_srepr_is_identity(): + p = Piecewise((10, Eq(x, 0)), (12, True)) + q = S(srepr(p)) + assert p == q + + +def test_issue_12587(): + # sort holes into intervals + p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True)) + assert p.integrate((x, -5, 5)) == 23 + p = Piecewise((1, x > 1), (2, x < y), (3, True)) + lim = x, -3, 3 + ans = p.integrate(lim) + for i in range(-1, 3): + assert ans.subs(y, i) == p.subs(y, i).integrate(lim) + + +def test_issue_11045(): + assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3 + + # handle And with Or arguments + assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True) + ).integrate((x, 0, 3)) == 1 + + # hidden false + assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) + ).integrate((x, 0, 3)) == 5 + # targetcond is Eq + assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True) + ).integrate((x, 0, 4)) == 6 + # And has Relational needing to be solved + assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True) + ).integrate((x, 0, 3)) == 1 + # Or has Relational needing to be solved + assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True) + ).integrate((x, 0, 3)) == 2 + # ignore hidden false (handled in canonicalization) + assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) + ).integrate((x, 0, 3)) == 5 + # watch for hidden True Piecewise + assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True) + ).integrate((x, 0, 3)) == 6 + + # overlapping conditions of targetcond are recognized and ignored; + # the condition x > 3 will be pre-empted by the first condition + assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True) + ).integrate((x, 0, 4)) == 6 + + # convert Ne to Or + assert Piecewise((1, Ne(x, 0)), (2, True) + ).integrate((x, -1, 1)) == 2 + + # no default but well defined + assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)) + ).integrate((x, 1, 4)) == 5 + + p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))) + nan = Undefined + i = p.integrate((x, 1, y)) + assert i == Piecewise( + (y - 1, y < 1), + (Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half, + y <= Min(4, y)), + (nan, True)) + assert p.integrate((x, 1, -1)) == i.subs(y, -1) + assert p.integrate((x, 1, 4)) == 5 + assert p.integrate((x, 1, 5)) is nan + + # handle Not + p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True)) + assert p.integrate((x, 0, 3)) == 4 + + # handle updating of int_expr when there is overlap + p = Piecewise( + (1, And(5 > x, x > 1)), + (2, Or(x < 3, x > 7)), + (4, x < 8)) + assert p.integrate((x, 0, 10)) == 20 + + # And with Eq arg handling + assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)) + ).integrate((x, 0, 3)) is S.NaN + assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True) + ).integrate((x, 0, 3)) == 7 + assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True) + ).integrate((x, -1, 1)) == 4 + # middle condition doesn't matter: it's a zero width interval + assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True) + ).integrate((x, 0, 3)) == 7 + + +def test_holes(): + nan = Undefined + assert Piecewise((1, x < 2)).integrate(x) == Piecewise( + (x, x < 2), (nan, True)) + assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise( + (nan, x < 1), (x, x < 2), (nan, True)) + assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan + assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2 + + # this also tests that the integrate method is used on non-Piecwise + # arguments in _eval_integral + A, B = symbols("A B") + a, b = symbols('a b', real=True) + assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2)) + ).integrate(x) == Piecewise( + (B*x, (a > 2)), + (Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1), + (Piecewise((B*x, x < 1), (nan, True)), True)) + + +def test_issue_11922(): + def f(x): + return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True)) + autocorr = lambda k: ( + f(x) * f(x + k)).integrate((x, -1, 1)) + assert autocorr(1.9) > 0 + k = symbols('k') + good_autocorr = lambda k: ( + (1 - x**2) * f(x + k)).integrate((x, -1, 1)) + a = good_autocorr(k) + assert a.subs(k, 3) == 0 + k = symbols('k', positive=True) + a = good_autocorr(k) + assert a.subs(k, 3) == 0 + assert Piecewise((0, x < 1), (10, (x >= 1)) + ).integrate() == Piecewise((0, x < 1), (10*x - 10, True)) + + +def test_issue_5227(): + f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539), + (-0.0160799238820171*x + 1.33215984776403, x < 2), + (Piecewise((0.3, x > 123), (0.7, True)) + + Piecewise((0.4, x > 2), (0.6, True)), x <= + 123), (-0.00817409766454352*x + 2.10541401273885, x < + 380.571428571429), (0, True)) + i = integrate(f, (x, -oo, oo)) + assert i == Integral(f, (x, -oo, oo)).doit() + assert str(i) == '1.00195081676351' + assert Piecewise((1, x - y < 0), (0, True) + ).integrate(y) == Piecewise((0, y <= x), (-x + y, True)) + + +def test_issue_10137(): + a = Symbol('a', real=True) + b = Symbol('b', real=True) + x = Symbol('x', real=True) + y = Symbol('y', real=True) + p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) + p1 = Piecewise((0, Or(a > x, b < x)), (1, True)) + assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo)) + p3 = Piecewise((1, And(0 < x, x < a)), (0, True)) + p4 = Piecewise((1, And(a > x, x > 0)), (0, True)) + ip3 = integrate(p3, x) + assert ip3 == Piecewise( + (0, x <= 0), + (x, x <= Max(0, a)), + (Max(0, a), True)) + ip4 = integrate(p4, x) + assert ip4 == ip3 + assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 + assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 + + +def test_stackoverflow_43852159(): + f = lambda x: Piecewise((1, (x >= -1) & (x <= 1)), (0, True)) + Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo)) + cx = Conv(x) + assert cx.subs(x, -1.5) == cx.subs(x, 1.5) + assert cx.subs(x, 3) == 0 + assert piecewise_fold(f(x - y)*f(y)) == Piecewise( + (1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)), + (0, True)) + + +def test_issue_12557(): + ''' + # 3200 seconds to compute the fourier part of issue + import sympy as sym + x,y,z,t = sym.symbols('x y z t') + k = sym.symbols("k", integer=True) + fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2), + (x, -sym.pi, sym.pi)) + assert fourier == FourierSeries( + sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2, + Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi), + SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) & + Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n, + 0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n, + -k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & + Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) | + (Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n, + -k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + + pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 + - pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + + pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - + pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 - + 2*pi*_n**2*k**2 + pi*k**4) + + (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - + pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + + pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - + pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4), + True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo)))) + ''' + x = symbols("x", real=True) + k = symbols('k', integer=True, finite=True) + abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0)) + assert integrate(abs2(x), (x, -pi, pi)) == pi**2 + func = cos(k*x)*sqrt(x**2) + assert integrate(func, (x, -pi, pi)) == Piecewise( + (2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True)) + +def test_issue_6900(): + from itertools import permutations + t0, t1, T, t = symbols('t0, t1 T t') + f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1)) + g = f.integrate(t) + assert g == Piecewise( + (0, t <= t0), + (t*x - t0*x, t <= Max(t0, t1)), + (-t0*x + x*Max(t0, t1), True)) + for i in permutations(range(2)): + reps = dict(zip((t0,t1), i)) + for tt in range(-1,3): + assert (g.xreplace(reps).subs(t,tt) == + f.xreplace(reps).integrate(t).subs(t,tt)) + lim = Tuple(t, t0, T) + g = f.integrate(lim) + ans = Piecewise( + (-t0*x + x*Min(T, Max(t0, t1)), T > t0), + (0, True)) + for i in permutations(range(3)): + reps = dict(zip((t0,t1,T), i)) + tru = f.xreplace(reps).integrate(lim.xreplace(reps)) + assert tru == ans.xreplace(reps) + assert g == ans + + +def test_issue_10122(): + assert solve(abs(x) + abs(x - 1) - 1 > 0, x + ) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo)) + + +def test_issue_4313(): + u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True)) + e = (u - u.subs(x, y))**2/(x - y)**2 + M = Max(0, a) + assert integrate(e, x).expand() == Piecewise( + (Piecewise( + (0, x <= 0), + (-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 + + 2*y*log(x - y)/a**2 - y/a**2, x <= M), + (-y**2/(-a**2*y + a**2*M) + 1/(-y + M) - + 1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y + + M)/a**2 - y/a**2 + M/a**2, True)), + ((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))), + (Piecewise( + (-1/(x - y), x <= 0), + (-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) - + y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a + + 2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 - + y/a**2, x <= M), + (-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y + + a**2*M) - y**2/(-a**2*y + a**2*M) + + 2*log(-y)/a - 2*log(-y + M)/a + 2/a - + 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 - + y/a**2 + M/a**2, True)), + a <= y), + (Piecewise( + (-y**2/(a**2*x - a**2*y), x <= 0), + (x/a**2 + y/a**2, x <= M), + (a**2/(-a**2*y + a**2*M) - + a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) + + 2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) - + y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)), + True)) + + +def test__intervals(): + assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == (True, []) + assert Piecewise( + (1, x > x + 1), + (Piecewise((1, x < x + 1)), 2*x < 2*x + 1), + (1, True))._intervals(x) == (True, [(-oo, oo, 1, 1)]) + assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == (True, + [(-oo, oo, 1, 0)]) + assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True) + )._intervals(x) == (True, + [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)]) + # the following tests that duplicates are removed and that non-Eq + # generated zero-width intervals are removed + assert Piecewise((1, Abs(x**(-2)) > 1), (0, True) + )._intervals(x) == (True, + [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)]) + + +def test_containment(): + a, b, c, d, e = [1, 2, 3, 4, 5] + p = (Piecewise((d, x > 1), (e, True))* + Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True))) + assert p.integrate(x).diff(x) == Piecewise( + (c*e, x <= 0), + (a*e, x <= 1), + (a*d, x < 2), # this is what we want to get right + (b*d, x < 4), + (c*d, True)) + + +def test_piecewise_with_DiracDelta(): + d1 = DiracDelta(x - 1) + assert integrate(d1, (x, -oo, oo)) == 1 + assert integrate(d1, (x, 0, 2)) == 1 + assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0 + assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise( + (Heaviside(x - 1), x < 2), (1, True)) + # TODO raise error if function is discontinuous at limit of + # integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise( + # (d1, Eq(x, 1) + + +def test_issue_10258(): + assert Piecewise((0, x < 1), (1, True)).is_zero is None + assert Piecewise((-1, x < 1), (1, True)).is_zero is False + a = Symbol('a', zero=True) + assert Piecewise((0, x < 1), (a, True)).is_zero + assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None + a = Symbol('a') + assert Piecewise((0, x < 1), (a, True)).is_zero is None + assert Piecewise((0, x < 1), (1, True)).is_nonzero is None + assert Piecewise((1, x < 1), (2, True)).is_nonzero + assert Piecewise((0, x < 1), (oo, True)).is_finite is None + assert Piecewise((0, x < 1), (1, True)).is_finite + b = Basic() + assert Piecewise((b, x < 1)).is_finite is None + + # 10258 + c = Piecewise((1, x < 0), (2, True)) < 3 + assert c != True + assert piecewise_fold(c) == True + + +def test_issue_10087(): + a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True)) + m = a*b + f = piecewise_fold(m) + for i in (0, 2, 4): + assert m.subs(x, i) == f.subs(x, i) + m = a + b + f = piecewise_fold(m) + for i in (0, 2, 4): + assert m.subs(x, i) == f.subs(x, i) + + +def test_issue_8919(): + c = symbols('c:5') + x = symbols("x") + f1 = Piecewise((c[1], x < 1), (c[2], True)) + f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True)) + assert integrate(f1*f2, (x, 0, 2) + ) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4] + f1 = Piecewise((0, x < 1), (2, True)) + f2 = Piecewise((3, x < 2), (0, True)) + assert integrate(f1*f2, (x, 0, 3)) == 6 + + y = symbols("y", positive=True) + a, b, c, x, z = symbols("a,b,c,x,z", real=True) + I = Integral(Piecewise( + (0, (x >= y) | (x < 0) | (b > c)), + (a, True)), (x, 0, z)) + ans = I.doit() + assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True)) + for cond in (True, False): + for yy in range(1, 3): + for zz in range(-yy, 0, yy): + reps = [(b > c, cond), (y, yy), (z, zz)] + assert ans.subs(reps) == I.subs(reps).doit() + + +def test_unevaluated_integrals(): + f = Function('f') + p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True)) + assert p.integrate(x) == Integral(p, x) + assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5)) + # test it by replacing f(x) with x%2 which will not + # affect the answer: the integrand is essentially 2 over + # the domain of integration + assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10.0 + + # this is a test of using _solve_inequality when + # solve_univariate_inequality fails + assert p.integrate(y) == Piecewise( + (y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))), + (2*y, (x > -oo) & (x < 10)), (0, True)) + + +def test_conditions_as_alternate_booleans(): + a, b, c = symbols('a:c') + assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True))) + ) == Piecewise((x, ITE(x > 0, y < 1, y > 1))) + + +def test_Piecewise_rewrite_as_ITE(): + a, b, c, d = symbols('a:d') + + def _ITE(*args): + return Piecewise(*args).rewrite(ITE) + + assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b) + assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b) + assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0) + ) == ITE(x < 1, a, b) + assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b) + assert _ITE((a, x < 1), (b, x < 2), (c, True) + ) == ITE(x < 1, a, ITE(x < 2, b, c)) + assert _ITE((a, x < 1), (b, y < 2), (c, True) + ) == ITE(x < 1, a, ITE(y < 2, b, c)) + assert _ITE((a, x < 1), (b, x < oo), (c, y < 1) + ) == ITE(x < 1, a, b) + assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True) + ) == ITE(x < 1, a, ITE(y < 1, c, b)) + assert _ITE((a, x < 0), (b, Or(x < oo, y < 1)) + ) == ITE(x < 0, a, b) + raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True))) + # if `a` in the following were replaced with y then the coverage + # is complete but something other than as_set would need to be + # used to detect this + raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a))) + raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3))) + + +def test_issue_14052(): + assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4 + + +def test_issue_14240(): + assert piecewise_fold( + Piecewise((1, a), (2, b), (4, True)) + + Piecewise((8, a), (16, True)) + ) == Piecewise((9, a), (18, b), (20, True)) + assert piecewise_fold( + Piecewise((2, a), (3, b), (5, True)) * + Piecewise((7, a), (11, True)) + ) == Piecewise((14, a), (33, b), (55, True)) + # these will hang if naive folding is used + assert piecewise_fold(Add(*[ + Piecewise((i, a), (0, True)) for i in range(40)]) + ) == Piecewise((780, a), (0, True)) + assert piecewise_fold(Mul(*[ + Piecewise((i, a), (0, True)) for i in range(1, 41)]) + ) == Piecewise((factorial(40), a), (0, True)) + + +def test_issue_14787(): + x = Symbol('x') + f = Piecewise((x, x < 1), ((S(58) / 7), True)) + assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))" + +def test_issue_21481(): + b, e = symbols('b e') + C = Piecewise( + (2, + ((b > 1) & (e > 0)) | + ((b > 0) & (b < 1) & (e < 0)) | + ((e >= 2) & (b < -1) & Eq(Mod(e, 2), 0)) | + ((e <= -2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))), + (S.Half, + ((b > 1) & (e < 0)) | + ((b > 0) & (e > 0) & (b < 1)) | + ((e <= -2) & (b < -1) & Eq(Mod(e, 2), 0)) | + ((e >= 2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))), + (-S.Half, + Eq(Mod(e, 2), 1) & + (((e <= -1) & (b < -1)) | ((e >= 1) & (b > -1) & (b < 0)))), + (-2, + ((e >= 1) & (b < -1) & Eq(Mod(e, 2), 1)) | + ((e <= -1) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 1))) + ) + A = Piecewise( + (1, Eq(b, 1) | Eq(e, 0) | (Eq(b, -1) & Eq(Mod(e, 2), 0))), + (0, Eq(b, 0) & (e > 0)), + (-1, Eq(b, -1) & Eq(Mod(e, 2), 1)), + (C, Eq(im(b), 0) & Eq(im(e), 0)) + ) + + B = piecewise_fold(A) + sa = A.simplify() + sb = B.simplify() + v = (-2, -1, -S.Half, 0, S.Half, 1, 2) + for i in v: + for j in v: + r = {b:i, e:j} + ok = [k.xreplace(r) for k in (A, B, sa, sb)] + assert len(set(ok)) == 1 + + +def test_issue_8458(): + x, y = symbols('x y') + # Original issue + p1 = Piecewise((0, Eq(x, 0)), (sin(x), True)) + assert p1.simplify() == sin(x) + # Slightly larger variant + p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) + assert p2.simplify() == sin(x) + # Test for problem highlighted during review + p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) + assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True)) + + +def test_issue_16417(): + z = Symbol('z') + assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True)) + + x = Symbol('x') + assert unchanged(Piecewise, (S.Pi, re(x) < 0), + (0, Or(re(x) > 0, Ne(im(x), 0))), + (S.NaN, True)) + r = Symbol('r', real=True) + p = Piecewise((S.Pi, re(r) < 0), + (0, Or(re(r) > 0, Ne(im(r), 0))), + (S.NaN, True)) + assert p == Piecewise((S.Pi, r < 0), + (0, r > 0), + (S.NaN, True), evaluate=False) + # Does not work since imaginary != 0... + #i = Symbol('i', imaginary=True) + #p = Piecewise((S.Pi, re(i) < 0), + # (0, Or(re(i) > 0, Ne(im(i), 0))), + # (S.NaN, True)) + #assert p == Piecewise((0, Ne(im(i), 0)), + # (S.NaN, True), evaluate=False) + i = I*r + p = Piecewise((S.Pi, re(i) < 0), + (0, Or(re(i) > 0, Ne(im(i), 0))), + (S.NaN, True)) + assert p == Piecewise((0, Ne(im(i), 0)), + (S.NaN, True), evaluate=False) + assert p == Piecewise((0, Ne(r, 0)), + (S.NaN, True), evaluate=False) + + +def test_eval_rewrite_as_KroneckerDelta(): + x, y, z, n, t, m = symbols('x y z n t m') + K = KroneckerDelta + f = lambda p: expand(p.rewrite(K)) + + p1 = Piecewise((0, Eq(x, y)), (1, True)) + assert f(p1) == 1 - K(x, y) + + p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True)) + assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \ + x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t) + + p3 = Piecewise((1, Ne(x, y)), (0, True)) + assert f(p3) == 1 - K(x, y) + + p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True)) + assert f(p4) == 4 - 3*K(3, x) + + p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True)) + assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3 + + p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True)) + assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y) + + p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True)) + assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1 + + p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True)) + assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1 + + p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True)) + assert f(p9) == 5 * K(1, y) * K(4, x) + 1 + + p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True)) + assert f(p10) == -3 * K(-4, x) * K(1, y) + 4 + + p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True)) + assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1 + + p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True)) + assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1 + + p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True)) + assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1 + + p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True)) + assert f(p14) == 2 * K(0, x) * K(1, y) + 1 + + p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True)) + assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \ + 2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2 + + p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\ + *Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True)) + assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x) + + p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))), + (1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True)) + assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x) + + p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True)) + assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4 + + p19 = Piecewise((0, x > 2), (1, True)) + assert f(p19) == p19 + + p20 = Piecewise((0, And(x < 2, x > -5)), (1, True)) + assert f(p20) == p20 + + p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True)) + assert f(p21) == p21 + + p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True)) + assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1 + + +@slow +def test_identical_conds_issue(): + from sympy.stats import Uniform, density + u1 = Uniform('u1', 0, 1) + u2 = Uniform('u2', 0, 1) + # Result is quite big, so not really important here (and should ideally be + # simpler). Should not give an exception though. + density(u1 + u2) + + +def test_issue_7370(): + f = Piecewise((1, x <= 2400)) + v = integrate(f, (x, 0, Float("252.4", 30))) + assert str(v) == '252.400000000000000000000000000' + + +def test_issue_14933(): + x = Symbol('x') + y = Symbol('y') + + inp = MatrixSymbol('inp', 1, 1) + rep_dict = {y: inp[0, 0], x: inp[0, 0]} + + p = Piecewise((1, ITE(y > 0, x < 0, True))) + assert p.xreplace(rep_dict) == Piecewise((1, ITE(inp[0, 0] > 0, inp[0, 0] < 0, True))) + + +def test_issue_16715(): + raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs()) + + +def test_issue_20360(): + t, tau = symbols("t tau", real=True) + n = symbols("n", integer=True) + lam = pi * (n - S.Half) + eq = integrate(exp(lam * tau), (tau, 0, t)) + assert eq.simplify() == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1)) + + +def test_piecewise_eval(): + # XXX these tests might need modification if this + # simplification is moved out of eval and into + # boolalg or Piecewise simplification functions + f = lambda x: x.args[0].cond + # unsimplified + assert f(Piecewise((x, (x > -oo) & (x < 3))) + ) == ((x > -oo) & (x < 3)) + assert f(Piecewise((x, (x > -oo) & (x < oo))) + ) == ((x > -oo) & (x < oo)) + assert f(Piecewise((x, (x > -3) & (x < 3))) + ) == ((x > -3) & (x < 3)) + assert f(Piecewise((x, (x > -3) & (x < oo))) + ) == ((x > -3) & (x < oo)) + assert f(Piecewise((x, (x <= 3) & (x > -oo))) + ) == ((x <= 3) & (x > -oo)) + assert f(Piecewise((x, (x <= 3) & (x > -3))) + ) == ((x <= 3) & (x > -3)) + assert f(Piecewise((x, (x >= -3) & (x < 3))) + ) == ((x >= -3) & (x < 3)) + assert f(Piecewise((x, (x >= -3) & (x < oo))) + ) == ((x >= -3) & (x < oo)) + assert f(Piecewise((x, (x >= -3) & (x <= 3))) + ) == ((x >= -3) & (x <= 3)) + # could simplify by keeping only the first + # arg of result + assert f(Piecewise((x, (x <= oo) & (x > -oo))) + ) == (x > -oo) & (x <= oo) + assert f(Piecewise((x, (x <= oo) & (x > -3))) + ) == (x > -3) & (x <= oo) + assert f(Piecewise((x, (x >= -oo) & (x < 3))) + ) == (x < 3) & (x >= -oo) + assert f(Piecewise((x, (x >= -oo) & (x < oo))) + ) == (x < oo) & (x >= -oo) + assert f(Piecewise((x, (x >= -oo) & (x <= 3))) + ) == (x <= 3) & (x >= -oo) + assert f(Piecewise((x, (x >= -oo) & (x <= oo))) + ) == (x <= oo) & (x >= -oo) # but cannot be True unless x is real + assert f(Piecewise((x, (x >= -3) & (x <= oo))) + ) == (x >= -3) & (x <= oo) + assert f(Piecewise((x, (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1))) + ) == (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1) + + +def test_issue_22533(): + x = Symbol('x', real=True) + f = Piecewise((-1 / x, x <= 0), (1 / x, True)) + assert integrate(f, x) == Piecewise((-log(x), x <= 0), (log(x), True)) + + +def test_issue_24072(): + assert Piecewise((1, x > 1), (2, x <= 1), (3, x <= 1) + ) == Piecewise((1, x > 1), (2, True)) + + +def test_piecewise__eval_is_meromorphic(): + """ Issue 24127: Tests eval_is_meromorphic auxiliary method """ + x = symbols('x', real=True) + f = Piecewise((1, x < 0), (sqrt(1 - x), True)) + assert f.is_meromorphic(x, I) is None + assert f.is_meromorphic(x, -1) == True + assert f.is_meromorphic(x, 0) == None + assert f.is_meromorphic(x, 1) == False + assert f.is_meromorphic(x, 2) == True + assert f.is_meromorphic(x, Symbol('a')) == None + assert f.is_meromorphic(x, Symbol('a', real=True)) == None diff --git a/shared/package-files/38/38ecebdb0a138161c1ac91133510abcddbe22d38e248373106033a81356464c6/_decomp_schur.py b/shared/package-files/38/38ecebdb0a138161c1ac91133510abcddbe22d38e248373106033a81356464c6/_decomp_schur.py new file mode 100644 index 0000000000000000000000000000000000000000..8609a175e16d663938386c6b45d190cd0e5dafd8 --- /dev/null +++ b/shared/package-files/38/38ecebdb0a138161c1ac91133510abcddbe22d38e248373106033a81356464c6/_decomp_schur.py @@ -0,0 +1,334 @@ +"""Schur decomposition functions.""" +import numpy as np +from numpy import asarray_chkfinite, single, asarray, array +from numpy.linalg import norm + + +# Local imports. +from ._misc import LinAlgError, _datacopied +from .lapack import get_lapack_funcs +from ._decomp import eigvals + +__all__ = ['schur', 'rsf2csf'] + +_double_precision = ['i', 'l', 'd'] + + +def schur(a, output='real', lwork=None, overwrite_a=False, sort=None, + check_finite=True): + """ + Compute Schur decomposition of a matrix. + + The Schur decomposition is:: + + A = Z T Z^H + + where Z is unitary and T is either upper-triangular, or for real + Schur decomposition (output='real'), quasi-upper triangular. In + the quasi-triangular form, 2x2 blocks describing complex-valued + eigenvalue pairs may extrude from the diagonal. + + Parameters + ---------- + a : (M, M) array_like + Matrix to decompose + output : {'real', 'complex'}, optional + When the dtype of `a` is real, this specifies whether to compute + the real or complex Schur decomposition. + When the dtype of `a` is complex, this argument is ignored, and the + complex Schur decomposition is computed. + lwork : int, optional + Work array size. If None or -1, it is automatically computed. + overwrite_a : bool, optional + Whether to overwrite data in a (may improve performance). + sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional + Specifies whether the upper eigenvalues should be sorted. A callable + may be passed that, given an eigenvalue, returns a boolean denoting + whether the eigenvalue should be sorted to the top-left (True). + + - If ``output='complex'`` OR the dtype of `a` is complex, the callable + should have one argument: the eigenvalue expressed as a complex number. + - If ``output='real'`` AND the dtype of `a` is real, the callable should have + two arguments: the real and imaginary parts of the eigenvalue, respectively. + + Alternatively, string parameters may be used:: + + 'lhp' Left-hand plane (real(eigenvalue) < 0.0) + 'rhp' Right-hand plane (real(eigenvalue) >= 0.0) + 'iuc' Inside the unit circle (abs(eigenvalue) <= 1.0) + 'ouc' Outside the unit circle (abs(eigenvalue) > 1.0) + + Defaults to None (no sorting). + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + T : (M, M) ndarray + Schur form of A. It is real-valued for the real Schur decomposition. + Z : (M, M) ndarray + An unitary Schur transformation matrix for A. + It is real-valued for the real Schur decomposition. + sdim : int + If and only if sorting was requested, a third return value will + contain the number of eigenvalues satisfying the sort condition. + Note that complex conjugate pairs for which the condition is true + for either eigenvalue count as 2. + + Raises + ------ + LinAlgError + Error raised under three conditions: + + 1. The algorithm failed due to a failure of the QR algorithm to + compute all eigenvalues. + 2. If eigenvalue sorting was requested, the eigenvalues could not be + reordered due to a failure to separate eigenvalues, usually because + of poor conditioning. + 3. If eigenvalue sorting was requested, roundoff errors caused the + leading eigenvalues to no longer satisfy the sorting condition. + + See Also + -------- + rsf2csf : Convert real Schur form to complex Schur form + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import schur, eigvals + >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]]) + >>> T, Z = schur(A) + >>> T + array([[ 2.65896708, 1.42440458, -1.92933439], + [ 0. , -0.32948354, -0.49063704], + [ 0. , 1.31178921, -0.32948354]]) + >>> Z + array([[0.72711591, -0.60156188, 0.33079564], + [0.52839428, 0.79801892, 0.28976765], + [0.43829436, 0.03590414, -0.89811411]]) + + >>> T2, Z2 = schur(A, output='complex') + >>> T2 + array([[ 2.65896708, -1.22839825+1.32378589j, 0.42590089+1.51937378j], # may vary + [ 0. , -0.32948354+0.80225456j, -0.59877807+0.56192146j], + [ 0. , 0. , -0.32948354-0.80225456j]]) + >>> eigvals(T2) + array([2.65896708, -0.32948354+0.80225456j, -0.32948354-0.80225456j]) # may vary + + A custom eigenvalue-sorting condition that sorts by positive imaginary part + is satisfied by only one eigenvalue. + + >>> _, _, sdim = schur(A, output='complex', sort=lambda x: x.imag > 1e-15) + >>> sdim + 1 + + When ``output='real'`` and the array `a` is real, the `sort` callable must accept + the real and imaginary parts as separate arguments. Note that now the complex + eigenvalues ``-0.32948354+0.80225456j`` and ``-0.32948354-0.80225456j`` will be + treated as a complex conjugate pair, and according to the `sdim` documentation, + complex conjugate pairs for which the condition is True for *either* eigenvalue + increase `sdim` by *two*. + + >>> _, _, sdim = schur(A, output='real', sort=lambda x, y: y > 1e-15) + >>> sdim + 2 + + """ + if output not in ['real', 'complex', 'r', 'c']: + raise ValueError("argument must be 'real', or 'complex'") + if check_finite: + a1 = asarray_chkfinite(a) + else: + a1 = asarray(a) + if np.issubdtype(a1.dtype, np.integer): + a1 = asarray(a, dtype=np.dtype("long")) + if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]): + raise ValueError('expected square matrix') + + typ = a1.dtype.char + if output in ['complex', 'c'] and typ not in ['F', 'D']: + if typ in _double_precision: + a1 = a1.astype('D') + else: + a1 = a1.astype('F') + + # accommodate empty matrix + if a1.size == 0: + t0, z0 = schur(np.eye(2, dtype=a1.dtype)) + if sort is None: + return (np.empty_like(a1, dtype=t0.dtype), + np.empty_like(a1, dtype=z0.dtype)) + else: + return (np.empty_like(a1, dtype=t0.dtype), + np.empty_like(a1, dtype=z0.dtype), 0) + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + gees, = get_lapack_funcs(('gees',), (a1,)) + if lwork is None or lwork == -1: + # get optimal work array + result = gees(lambda x: None, a1, lwork=-1) + lwork = result[-2][0].real.astype(np.int_) + + if sort is None: + sort_t = 0 + def sfunction(x, y=None): + return None + else: + sort_t = 1 + if callable(sort): + sfunction = sort + elif sort == 'lhp': + def sfunction(x, y=None): + return x.real < 0.0 + elif sort == 'rhp': + def sfunction(x, y=None): + return x.real >= 0.0 + elif sort == 'iuc': + def sfunction(x, y=None): + z = x if y is None else x + y*1j + return abs(z) <= 1.0 + elif sort == 'ouc': + def sfunction(x, y=None): + z = x if y is None else x + y*1j + return abs(z) > 1.0 + else: + raise ValueError("'sort' parameter must either be 'None', or a " + "callable, or one of ('lhp','rhp','iuc','ouc')") + + result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a, + sort_t=sort_t) + + info = result[-1] + if info < 0: + raise ValueError(f'illegal value in {-info}-th argument of internal gees') + elif info == a1.shape[0] + 1: + raise LinAlgError('Eigenvalues could not be separated for reordering.') + elif info == a1.shape[0] + 2: + raise LinAlgError('Leading eigenvalues do not satisfy sort condition.') + elif info > 0: + raise LinAlgError("Schur form not found. Possibly ill-conditioned.") + + if sort is None: + return result[0], result[-3] + else: + return result[0], result[-3], result[1] + + +eps = np.finfo(float).eps +feps = np.finfo(single).eps + +_array_kind = {'b': 0, 'h': 0, 'B': 0, 'i': 0, 'l': 0, + 'f': 0, 'd': 0, 'F': 1, 'D': 1} +_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1} +_array_type = [['f', 'd'], ['F', 'D']] + + +def _commonType(*arrays): + kind = 0 + precision = 0 + for a in arrays: + t = a.dtype.char + kind = max(kind, _array_kind[t]) + precision = max(precision, _array_precision[t]) + return _array_type[kind][precision] + + +def _castCopy(type, *arrays): + cast_arrays = () + for a in arrays: + if a.dtype.char == type: + cast_arrays = cast_arrays + (a.copy(),) + else: + cast_arrays = cast_arrays + (a.astype(type),) + if len(cast_arrays) == 1: + return cast_arrays[0] + else: + return cast_arrays + + +def rsf2csf(T, Z, check_finite=True): + """ + Convert real Schur form to complex Schur form. + + Convert a quasi-diagonal real-valued Schur form to the upper-triangular + complex-valued Schur form. + + Parameters + ---------- + T : (M, M) array_like + Real Schur form of the original array + Z : (M, M) array_like + Schur transformation matrix + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + T : (M, M) ndarray + Complex Schur form of the original array + Z : (M, M) ndarray + Schur transformation matrix corresponding to the complex form + + See Also + -------- + schur : Schur decomposition of an array + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import schur, rsf2csf + >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]]) + >>> T, Z = schur(A) + >>> T + array([[ 2.65896708, 1.42440458, -1.92933439], + [ 0. , -0.32948354, -0.49063704], + [ 0. , 1.31178921, -0.32948354]]) + >>> Z + array([[0.72711591, -0.60156188, 0.33079564], + [0.52839428, 0.79801892, 0.28976765], + [0.43829436, 0.03590414, -0.89811411]]) + >>> T2 , Z2 = rsf2csf(T, Z) + >>> T2 + array([[2.65896708+0.j, -1.64592781+0.743164187j, -1.21516887+1.00660462j], + [0.+0.j , -0.32948354+8.02254558e-01j, -0.82115218-2.77555756e-17j], + [0.+0.j , 0.+0.j, -0.32948354-0.802254558j]]) + >>> Z2 + array([[0.72711591+0.j, 0.28220393-0.31385693j, 0.51319638-0.17258824j], + [0.52839428+0.j, 0.24720268+0.41635578j, -0.68079517-0.15118243j], + [0.43829436+0.j, -0.76618703+0.01873251j, -0.03063006+0.46857912j]]) + + """ + if check_finite: + Z, T = map(asarray_chkfinite, (Z, T)) + else: + Z, T = map(asarray, (Z, T)) + + for ind, X in enumerate([Z, T]): + if X.ndim != 2 or X.shape[0] != X.shape[1]: + raise ValueError(f"Input '{'ZT'[ind]}' must be square.") + + if T.shape[0] != Z.shape[0]: + message = f"Input array shapes must match: Z: {Z.shape} vs. T: {T.shape}" + raise ValueError(message) + N = T.shape[0] + t = _commonType(Z, T, array([3.0], 'F')) + Z, T = _castCopy(t, Z, T) + + for m in range(N-1, 0, -1): + if abs(T[m, m-1]) > eps*(abs(T[m-1, m-1]) + abs(T[m, m])): + mu = eigvals(T[m-1:m+1, m-1:m+1]) - T[m, m] + r = norm([mu[0], T[m, m-1]]) + c = mu[0] / r + s = T[m, m-1] / r + G = array([[c.conj(), s], [-s, c]], dtype=t) + + T[m-1:m+1, m-1:] = G.dot(T[m-1:m+1, m-1:]) + T[:m+1, m-1:m+1] = T[:m+1, m-1:m+1].dot(G.conj().T) + Z[:, m-1:m+1] = Z[:, m-1:m+1].dot(G.conj().T) + + T[m, m-1] = 0.0 + return T, Z diff --git a/shared/package-files/38/38f5b939e4165451f263b48c1b6b58f00afce52b57cb3d337ec65ef72f677b5e/test_orthogonal_eval.py b/shared/package-files/38/38f5b939e4165451f263b48c1b6b58f00afce52b57cb3d337ec65ef72f677b5e/test_orthogonal_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..8a4f379effdc9c3aa18bd2948fbd9f716b1f8d57 --- /dev/null +++ b/shared/package-files/38/38f5b939e4165451f263b48c1b6b58f00afce52b57cb3d337ec65ef72f677b5e/test_orthogonal_eval.py @@ -0,0 +1,275 @@ +import numpy as np +from numpy.testing import assert_, assert_allclose +import pytest + +from scipy.special import _ufuncs +import scipy.special._orthogonal as orth +from scipy.special._testutils import FuncData + + +def test_eval_chebyt(): + n = np.arange(0, 10000, 7, dtype=np.dtype("long")) + x = 2*np.random.rand() - 1 + v1 = np.cos(n*np.arccos(x)) + v2 = _ufuncs.eval_chebyt(n, x) + assert_(np.allclose(v1, v2, rtol=1e-15)) + + +def test_eval_chebyt_gh20129(): + # https://github.com/scipy/scipy/issues/20129 + assert _ufuncs.eval_chebyt(7, 2 + 0j) == 5042.0 + + +def test_eval_genlaguerre_restriction(): + # check it returns nan for alpha <= -1 + assert_(np.isnan(_ufuncs.eval_genlaguerre(0, -1, 0))) + assert_(np.isnan(_ufuncs.eval_genlaguerre(0.1, -1, 0))) + + +def test_warnings(): + # ticket 1334 + with np.errstate(all='raise'): + # these should raise no fp warnings + _ufuncs.eval_legendre(1, 0) + _ufuncs.eval_laguerre(1, 1) + _ufuncs.eval_gegenbauer(1, 1, 0) + + +class TestPolys: + """ + Check that the eval_* functions agree with the constructed polynomials + + """ + + def check_poly(self, func, cls, param_ranges=(), x_range=(), nn=10, + nparam=10, nx=10, rtol=1e-8): + rng = np.random.RandomState(1234) + + dataset = [] + for n in np.arange(nn): + params = [a + (b-a)*rng.rand(nparam) for a,b in param_ranges] + params = np.asarray(params).T + if not param_ranges: + params = [0] + for p in params: + if param_ranges: + p = (n,) + tuple(p) + else: + p = (n,) + x = x_range[0] + (x_range[1] - x_range[0])*rng.rand(nx) + x[0] = x_range[0] # always include domain start point + x[1] = x_range[1] # always include domain end point + poly = np.poly1d(cls(*p).coef) + z = np.c_[np.tile(p, (nx,1)), x, poly(x)] + dataset.append(z) + + dataset = np.concatenate(dataset, axis=0) + + def polyfunc(*p): + p = (p[0].astype(np.dtype("long")),) + p[1:] + return func(*p) + + with np.errstate(all='raise'): + ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1, + rtol=rtol) + ds.check() + + def test_jacobi(self): + self.check_poly(_ufuncs.eval_jacobi, orth.jacobi, + param_ranges=[(-0.99, 10), (-0.99, 10)], + x_range=[-1, 1], rtol=1e-5) + + def test_sh_jacobi(self): + self.check_poly(_ufuncs.eval_sh_jacobi, orth.sh_jacobi, + param_ranges=[(1, 10), (0, 1)], x_range=[0, 1], + rtol=1e-5) + + def test_gegenbauer(self): + self.check_poly(_ufuncs.eval_gegenbauer, orth.gegenbauer, + param_ranges=[(-0.499, 10)], x_range=[-1, 1], + rtol=1e-7) + + def test_chebyt(self): + self.check_poly(_ufuncs.eval_chebyt, orth.chebyt, + param_ranges=[], x_range=[-1, 1]) + + def test_chebyu(self): + self.check_poly(_ufuncs.eval_chebyu, orth.chebyu, + param_ranges=[], x_range=[-1, 1]) + + def test_chebys(self): + self.check_poly(_ufuncs.eval_chebys, orth.chebys, + param_ranges=[], x_range=[-2, 2]) + + def test_chebyc(self): + self.check_poly(_ufuncs.eval_chebyc, orth.chebyc, + param_ranges=[], x_range=[-2, 2]) + + def test_sh_chebyt(self): + with np.errstate(all='ignore'): + self.check_poly(_ufuncs.eval_sh_chebyt, orth.sh_chebyt, + param_ranges=[], x_range=[0, 1]) + + def test_sh_chebyu(self): + self.check_poly(_ufuncs.eval_sh_chebyu, orth.sh_chebyu, + param_ranges=[], x_range=[0, 1]) + + def test_legendre(self): + self.check_poly(_ufuncs.eval_legendre, orth.legendre, + param_ranges=[], x_range=[-1, 1]) + + def test_sh_legendre(self): + with np.errstate(all='ignore'): + self.check_poly(_ufuncs.eval_sh_legendre, orth.sh_legendre, + param_ranges=[], x_range=[0, 1]) + + def test_genlaguerre(self): + self.check_poly(_ufuncs.eval_genlaguerre, orth.genlaguerre, + param_ranges=[(-0.99, 10)], x_range=[0, 100]) + + def test_laguerre(self): + self.check_poly(_ufuncs.eval_laguerre, orth.laguerre, + param_ranges=[], x_range=[0, 100]) + + def test_hermite(self): + self.check_poly(_ufuncs.eval_hermite, orth.hermite, + param_ranges=[], x_range=[-100, 100]) + + def test_hermitenorm(self): + self.check_poly(_ufuncs.eval_hermitenorm, orth.hermitenorm, + param_ranges=[], x_range=[-100, 100]) + + +class TestRecurrence: + """ + Check that the eval_* functions sig='ld->d' and 'dd->d' agree. + + """ + + def check_poly(self, func, param_ranges=(), x_range=(), nn=10, + nparam=10, nx=10, rtol=1e-8): + np.random.seed(1234) + + dataset = [] + for n in np.arange(nn): + params = [a + (b-a)*np.random.rand(nparam) for a,b in param_ranges] + params = np.asarray(params).T + if not param_ranges: + params = [0] + for p in params: + if param_ranges: + p = (n,) + tuple(p) + else: + p = (n,) + x = x_range[0] + (x_range[1] - x_range[0])*np.random.rand(nx) + x[0] = x_range[0] # always include domain start point + x[1] = x_range[1] # always include domain end point + kw = dict(sig=(len(p)+1)*'d'+'->d') + z = np.c_[np.tile(p, (nx,1)), x, func(*(p + (x,)), **kw)] + dataset.append(z) + + dataset = np.concatenate(dataset, axis=0) + + def polyfunc(*p): + p0 = p[0].astype(np.intp) + p = (p0,) + p[1:] + p0_type_char = p0.dtype.char + kw = dict(sig=p0_type_char + (len(p)-1)*'d' + '->d') + return func(*p, **kw) + + with np.errstate(all='raise'): + ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1, + rtol=rtol) + ds.check() + + def test_jacobi(self): + self.check_poly(_ufuncs.eval_jacobi, + param_ranges=[(-0.99, 10), (-0.99, 10)], + x_range=[-1, 1]) + + def test_sh_jacobi(self): + self.check_poly(_ufuncs.eval_sh_jacobi, + param_ranges=[(1, 10), (0, 1)], x_range=[0, 1]) + + def test_gegenbauer(self): + self.check_poly(_ufuncs.eval_gegenbauer, + param_ranges=[(-0.499, 10)], x_range=[-1, 1]) + + def test_chebyt(self): + self.check_poly(_ufuncs.eval_chebyt, + param_ranges=[], x_range=[-1, 1]) + + def test_chebyu(self): + self.check_poly(_ufuncs.eval_chebyu, + param_ranges=[], x_range=[-1, 1]) + + def test_chebys(self): + self.check_poly(_ufuncs.eval_chebys, + param_ranges=[], x_range=[-2, 2]) + + def test_chebyc(self): + self.check_poly(_ufuncs.eval_chebyc, + param_ranges=[], x_range=[-2, 2]) + + def test_sh_chebyt(self): + self.check_poly(_ufuncs.eval_sh_chebyt, + param_ranges=[], x_range=[0, 1]) + + def test_sh_chebyu(self): + self.check_poly(_ufuncs.eval_sh_chebyu, + param_ranges=[], x_range=[0, 1]) + + def test_legendre(self): + self.check_poly(_ufuncs.eval_legendre, + param_ranges=[], x_range=[-1, 1]) + + def test_sh_legendre(self): + self.check_poly(_ufuncs.eval_sh_legendre, + param_ranges=[], x_range=[0, 1]) + + def test_genlaguerre(self): + self.check_poly(_ufuncs.eval_genlaguerre, + param_ranges=[(-0.99, 10)], x_range=[0, 100]) + + def test_laguerre(self): + self.check_poly(_ufuncs.eval_laguerre, + param_ranges=[], x_range=[0, 100]) + + def test_hermite(self): + v = _ufuncs.eval_hermite(70, 1.0) + a = -1.457076485701412e60 + assert_allclose(v, a) + + +def test_hermite_domain(): + # Regression test for gh-11091. + assert np.isnan(_ufuncs.eval_hermite(-1, 1.0)) + assert np.isnan(_ufuncs.eval_hermitenorm(-1, 1.0)) + + +@pytest.mark.parametrize("n", [0, 1, 2]) +@pytest.mark.parametrize("x", [0, 1, np.nan]) +def test_hermite_nan(n, x): + # Regression test for gh-11369. + assert np.isnan(_ufuncs.eval_hermite(n, x)) == np.any(np.isnan([n, x])) + assert np.isnan(_ufuncs.eval_hermitenorm(n, x)) == np.any(np.isnan([n, x])) + + +@pytest.mark.parametrize('n', [0, 1, 2, 3.2]) +@pytest.mark.parametrize('alpha', [1, np.nan]) +@pytest.mark.parametrize('x', [2, np.nan]) +def test_genlaguerre_nan(n, alpha, x): + # Regression test for gh-11361. + nan_laguerre = np.isnan(_ufuncs.eval_genlaguerre(n, alpha, x)) + nan_arg = np.any(np.isnan([n, alpha, x])) + assert nan_laguerre == nan_arg + + +@pytest.mark.parametrize('n', [0, 1, 2, 3.2]) +@pytest.mark.parametrize('alpha', [0.0, 1, np.nan]) +@pytest.mark.parametrize('x', [1e-6, 2, np.nan]) +def test_gegenbauer_nan(n, alpha, x): + # Regression test for gh-11370. + nan_gegenbauer = np.isnan(_ufuncs.eval_gegenbauer(n, alpha, x)) + nan_arg = np.any(np.isnan([n, alpha, x])) + assert nan_gegenbauer == nan_arg diff --git a/shared/package-files/38/38f6aa7f799abf682b05c6c661bdd3e9a0b58029c390d889562150c6ac039049/test_pretty.py b/shared/package-files/38/38f6aa7f799abf682b05c6c661bdd3e9a0b58029c390d889562150c6ac039049/test_pretty.py new file mode 100644 index 0000000000000000000000000000000000000000..57e258b9c8855bb49c1b8afa153fe068c5739a88 --- /dev/null +++ b/shared/package-files/38/38f6aa7f799abf682b05c6c661bdd3e9a0b58029c390d889562150c6ac039049/test_pretty.py @@ -0,0 +1,540 @@ +# coding: utf-8 +"""Tests for IPython.lib.pretty.""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + +from collections import Counter, defaultdict, deque, OrderedDict, UserList +import os +import pytest +import types +import string +import sys +import unittest + +import pytest + +from IPython.lib import pretty + +from io import StringIO + + +class MyList(object): + def __init__(self, content): + self.content = content + def _repr_pretty_(self, p, cycle): + if cycle: + p.text("MyList(...)") + else: + with p.group(3, "MyList(", ")"): + for (i, child) in enumerate(self.content): + if i: + p.text(",") + p.breakable() + else: + p.breakable("") + p.pretty(child) + + +class MyDict(dict): + def _repr_pretty_(self, p, cycle): + p.text("MyDict(...)") + +class MyObj(object): + def somemethod(self): + pass + + +class Dummy1(object): + def _repr_pretty_(self, p, cycle): + p.text("Dummy1(...)") + +class Dummy2(Dummy1): + _repr_pretty_ = None + +class NoModule(object): + pass + +NoModule.__module__ = None + +class Breaking(object): + def _repr_pretty_(self, p, cycle): + with p.group(4,"TG: ",":"): + p.text("Breaking(") + p.break_() + p.text(")") + +class BreakingRepr(object): + def __repr__(self): + return "Breaking(\n)" + +class BadRepr(object): + def __repr__(self): + return 1/0 + + +def test_indentation(): + """Test correct indentation in groups""" + count = 40 + gotoutput = pretty.pretty(MyList(range(count))) + expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")" + + assert gotoutput == expectedoutput + + +def test_dispatch(): + """ + Test correct dispatching: The _repr_pretty_ method for MyDict + must be found before the registered printer for dict. + """ + gotoutput = pretty.pretty(MyDict()) + expectedoutput = "MyDict(...)" + + assert gotoutput == expectedoutput + + +def test_callability_checking(): + """ + Test that the _repr_pretty_ method is tested for callability and skipped if + not. + """ + gotoutput = pretty.pretty(Dummy2()) + expectedoutput = "Dummy1(...)" + + assert gotoutput == expectedoutput + + +@pytest.mark.parametrize( + "obj,expected_output", + zip( + [ + set(), + frozenset(), + set([1]), + frozenset([1]), + set([1, 2]), + frozenset([1, 2]), + set([-1, -2, -3]), + ], + [ + "set()", + "frozenset()", + "{1}", + "frozenset({1})", + "{1, 2}", + "frozenset({1, 2})", + "{-3, -2, -1}", + ], + ), +) +def test_sets(obj, expected_output): + """ + Test that set and frozenset use Python 3 formatting. + """ + got_output = pretty.pretty(obj) + assert got_output == expected_output + + +def test_pprint_heap_allocated_type(): + """ + Test that pprint works for heap allocated types. + """ + module_name = "xxlimited_35" + expected_output = ( + "xxlimited.Null" if sys.version_info < (3, 10, 6) else "xxlimited_35.Null" + ) + xxlimited = pytest.importorskip(module_name) + output = pretty.pretty(xxlimited.Null) + assert output == expected_output + + +def test_pprint_nomod(): + """ + Test that pprint works for classes with no __module__. + """ + output = pretty.pretty(NoModule) + assert output == "NoModule" + + +def test_pprint_break(): + """ + Test that p.break_ produces expected output + """ + output = pretty.pretty(Breaking()) + expected = "TG: Breaking(\n ):" + assert output == expected + +def test_pprint_break_repr(): + """ + Test that p.break_ is used in repr + """ + output = pretty.pretty([[BreakingRepr()]]) + expected = "[[Breaking(\n )]]" + assert output == expected + + output = pretty.pretty([[BreakingRepr()]*2]) + expected = "[[Breaking(\n ),\n Breaking(\n )]]" + assert output == expected + +def test_bad_repr(): + """Don't catch bad repr errors""" + with pytest.raises(ZeroDivisionError): + pretty.pretty(BadRepr()) + +class BadException(Exception): + def __str__(self): + return -1 + +class ReallyBadRepr(object): + __module__ = 1 + @property + def __class__(self): + raise ValueError("I am horrible") + + def __repr__(self): + raise BadException() + +def test_really_bad_repr(): + with pytest.raises(BadException): + pretty.pretty(ReallyBadRepr()) + + +class SA(object): + pass + +class SB(SA): + pass + +class TestsPretty(unittest.TestCase): + + def test_super_repr(self): + # "" + output = pretty.pretty(super(SA)) + self.assertRegex(output, r"") + + # ">" + sb = SB() + output = pretty.pretty(super(SA, sb)) + self.assertRegex(output, r">") + + + def test_long_list(self): + lis = list(range(10000)) + p = pretty.pretty(lis) + last2 = p.rsplit('\n', 2)[-2:] + self.assertEqual(last2, [' 999,', ' ...]']) + + def test_long_set(self): + s = set(range(10000)) + p = pretty.pretty(s) + last2 = p.rsplit('\n', 2)[-2:] + self.assertEqual(last2, [' 999,', ' ...}']) + + def test_long_tuple(self): + tup = tuple(range(10000)) + p = pretty.pretty(tup) + last2 = p.rsplit('\n', 2)[-2:] + self.assertEqual(last2, [' 999,', ' ...)']) + + def test_long_dict(self): + d = { n:n for n in range(10000) } + p = pretty.pretty(d) + last2 = p.rsplit('\n', 2)[-2:] + self.assertEqual(last2, [' 999: 999,', ' ...}']) + + def test_unbound_method(self): + output = pretty.pretty(MyObj.somemethod) + self.assertIn('MyObj.somemethod', output) + + +class MetaClass(type): + def __new__(cls, name): + return type.__new__(cls, name, (object,), {'name': name}) + + def __repr__(self): + return "[CUSTOM REPR FOR CLASS %s]" % self.name + + +ClassWithMeta = MetaClass('ClassWithMeta') + + +def test_metaclass_repr(): + output = pretty.pretty(ClassWithMeta) + assert output == "[CUSTOM REPR FOR CLASS ClassWithMeta]" + + +def test_unicode_repr(): + u = u"üniçodé" + ustr = u + + class C(object): + def __repr__(self): + return ustr + + c = C() + p = pretty.pretty(c) + assert p == u + p = pretty.pretty([c]) + assert p == "[%s]" % u + + +def test_basic_class(): + def type_pprint_wrapper(obj, p, cycle): + if obj is MyObj: + type_pprint_wrapper.called = True + return pretty._type_pprint(obj, p, cycle) + type_pprint_wrapper.called = False + + stream = StringIO() + printer = pretty.RepresentationPrinter(stream) + printer.type_pprinters[type] = type_pprint_wrapper + printer.pretty(MyObj) + printer.flush() + output = stream.getvalue() + + assert output == "%s.MyObj" % __name__ + assert type_pprint_wrapper.called is True + + +def test_collections_userlist(): + # Create userlist with cycle + a = UserList() + a.append(a) + + cases = [ + (UserList(), "UserList([])"), + ( + UserList(i for i in range(1000, 1020)), + "UserList([1000,\n" + " 1001,\n" + " 1002,\n" + " 1003,\n" + " 1004,\n" + " 1005,\n" + " 1006,\n" + " 1007,\n" + " 1008,\n" + " 1009,\n" + " 1010,\n" + " 1011,\n" + " 1012,\n" + " 1013,\n" + " 1014,\n" + " 1015,\n" + " 1016,\n" + " 1017,\n" + " 1018,\n" + " 1019])", + ), + (a, "UserList([UserList(...)])"), + ] + for obj, expected in cases: + assert pretty.pretty(obj) == expected + + +# TODO : pytest.mark.parametrise once nose is gone. +def test_collections_defaultdict(): + # Create defaultdicts with cycles + a = defaultdict() + a.default_factory = a + b = defaultdict(list) + b['key'] = b + + # Dictionary order cannot be relied on, test against single keys. + cases = [ + (defaultdict(list), 'defaultdict(list, {})'), + (defaultdict(list, {'key': '-' * 50}), + "defaultdict(list,\n" + " {'key': '--------------------------------------------------'})"), + (a, 'defaultdict(defaultdict(...), {})'), + (b, "defaultdict(list, {'key': defaultdict(...)})"), + ] + for obj, expected in cases: + assert pretty.pretty(obj) == expected + + +# TODO : pytest.mark.parametrise once nose is gone. +def test_collections_ordereddict(): + # Create OrderedDict with cycle + a = OrderedDict() + a['key'] = a + + cases = [ + (OrderedDict(), 'OrderedDict()'), + (OrderedDict((i, i) for i in range(1000, 1010)), + 'OrderedDict([(1000, 1000),\n' + ' (1001, 1001),\n' + ' (1002, 1002),\n' + ' (1003, 1003),\n' + ' (1004, 1004),\n' + ' (1005, 1005),\n' + ' (1006, 1006),\n' + ' (1007, 1007),\n' + ' (1008, 1008),\n' + ' (1009, 1009)])'), + (a, "OrderedDict([('key', OrderedDict(...))])"), + ] + for obj, expected in cases: + assert pretty.pretty(obj) == expected + + +# TODO : pytest.mark.parametrise once nose is gone. +def test_collections_deque(): + # Create deque with cycle + a = deque() + a.append(a) + + cases = [ + (deque(), 'deque([])'), + (deque(i for i in range(1000, 1020)), + 'deque([1000,\n' + ' 1001,\n' + ' 1002,\n' + ' 1003,\n' + ' 1004,\n' + ' 1005,\n' + ' 1006,\n' + ' 1007,\n' + ' 1008,\n' + ' 1009,\n' + ' 1010,\n' + ' 1011,\n' + ' 1012,\n' + ' 1013,\n' + ' 1014,\n' + ' 1015,\n' + ' 1016,\n' + ' 1017,\n' + ' 1018,\n' + ' 1019])'), + (a, 'deque([deque(...)])'), + ] + for obj, expected in cases: + assert pretty.pretty(obj) == expected + + +# TODO : pytest.mark.parametrise once nose is gone. +def test_collections_counter(): + class MyCounter(Counter): + pass + cases = [ + (Counter(), 'Counter()'), + (Counter(a=1), "Counter({'a': 1})"), + (MyCounter(a=1), "MyCounter({'a': 1})"), + (Counter(a=1, c=22), "Counter({'c': 22, 'a': 1})"), + ] + for obj, expected in cases: + assert pretty.pretty(obj) == expected + +# TODO : pytest.mark.parametrise once nose is gone. +def test_mappingproxy(): + MP = types.MappingProxyType + underlying_dict = {} + mp_recursive = MP(underlying_dict) + underlying_dict[2] = mp_recursive + underlying_dict[3] = underlying_dict + + cases = [ + (MP({}), "mappingproxy({})"), + (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"), + (MP({k: k.upper() for k in string.ascii_lowercase}), + "mappingproxy({'a': 'A',\n" + " 'b': 'B',\n" + " 'c': 'C',\n" + " 'd': 'D',\n" + " 'e': 'E',\n" + " 'f': 'F',\n" + " 'g': 'G',\n" + " 'h': 'H',\n" + " 'i': 'I',\n" + " 'j': 'J',\n" + " 'k': 'K',\n" + " 'l': 'L',\n" + " 'm': 'M',\n" + " 'n': 'N',\n" + " 'o': 'O',\n" + " 'p': 'P',\n" + " 'q': 'Q',\n" + " 'r': 'R',\n" + " 's': 'S',\n" + " 't': 'T',\n" + " 'u': 'U',\n" + " 'v': 'V',\n" + " 'w': 'W',\n" + " 'x': 'X',\n" + " 'y': 'Y',\n" + " 'z': 'Z'})"), + (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"), + (underlying_dict, + "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"), + ] + for obj, expected in cases: + assert pretty.pretty(obj) == expected + + +# TODO : pytest.mark.parametrise once nose is gone. +def test_simplenamespace(): + SN = types.SimpleNamespace + + sn_recursive = SN() + sn_recursive.first = sn_recursive + sn_recursive.second = sn_recursive + cases = [ + (SN(), "namespace()"), + (SN(x=SN()), "namespace(x=namespace())"), + (SN(a_long_name=[SN(s=string.ascii_lowercase)]*3, a_short_name=None), + "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n" + " namespace(s='abcdefghijklmnopqrstuvwxyz'),\n" + " namespace(s='abcdefghijklmnopqrstuvwxyz')],\n" + " a_short_name=None)"), + (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"), + ] + for obj, expected in cases: + assert pretty.pretty(obj) == expected + + +def test_pretty_environ(): + dict_repr = pretty.pretty(dict(os.environ)) + # reindent to align with 'environ' prefix + dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ'))) + env_repr = pretty.pretty(os.environ) + assert env_repr == "environ" + dict_indented + + +def test_function_pretty(): + "Test pretty print of function" + # posixpath is a pure python module, its interface is consistent + # across Python distributions + import posixpath + + assert pretty.pretty(posixpath.join) == "" + + # custom function + def meaning_of_life(question=None): + if question: + return 42 + return "Don't panic" + + assert "meaning_of_life(question=None)" in pretty.pretty(meaning_of_life) + + +class OrderedCounter(Counter, OrderedDict): + 'Counter that remembers the order elements are first encountered' + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) + + def __reduce__(self): + return self.__class__, (OrderedDict(self),) + +class MySet(set): # Override repr of a basic type + def __repr__(self): + return 'mine' + +def test_custom_repr(): + """A custom repr should override a pretty printer for a parent type""" + oc = OrderedCounter("abracadabra") + assert "OrderedCounter(OrderedDict" in pretty.pretty(oc) + + assert pretty.pretty(MySet()) == "mine" diff --git a/shared/package-files/38/38fe2d77b07d4cb33bf734cf4008b92cb2c6bd6f350f588db91dbb1ce959700f/test_shortest_path.py b/shared/package-files/38/38fe2d77b07d4cb33bf734cf4008b92cb2c6bd6f350f588db91dbb1ce959700f/test_shortest_path.py new file mode 100644 index 0000000000000000000000000000000000000000..ba50f760e750ce1dbdec3624c2ab985fca1af7d1 --- /dev/null +++ b/shared/package-files/38/38fe2d77b07d4cb33bf734cf4008b92cb2c6bd6f350f588db91dbb1ce959700f/test_shortest_path.py @@ -0,0 +1,484 @@ +from io import StringIO +import warnings +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_allclose +from pytest import raises as assert_raises +from scipy.sparse.csgraph import (shortest_path, dijkstra, johnson, + bellman_ford, construct_dist_matrix, yen, + NegativeCycleError) +import scipy.sparse +from scipy.io import mmread +import pytest + +directed_G = np.array([[0, 3, 3, 0, 0], + [0, 0, 0, 2, 4], + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 0], + [2, 0, 0, 2, 0]], dtype=float) + +undirected_G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + +unweighted_G = (directed_G > 0).astype(float) + +directed_SP = [[0, 3, 3, 5, 7], + [3, 0, 6, 2, 4], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 4, 4, 0, 8], + [2, 5, 5, 2, 0]] + +directed_2SP_0_to_3 = [[-9999, 0, -9999, 1, -9999], + [-9999, 0, -9999, 4, 1]] + +directed_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 1, 2, 3, 1], + ([0, 1, 2, 3, 4], [1, 2, 0, 4, 3]), + ), + shape=(5, 5), +) + +directed_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [3, 0, 1, np.inf, np.inf], + [2, 2, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 3], + [np.inf, np.inf, np.inf, 1, 0]] + +undirected_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 0, 1, 1, 2, 2, 1, 1], + ([0, 1, 1, 2, 2, 0, 3, 4], [1, 0, 2, 1, 0, 2, 4, 3]) + ), + shape=(5, 5), +) + +undirected_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [0, 0, 1, np.inf, np.inf], + [1, 1, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 1], + [np.inf, np.inf, np.inf, 1, 0]] + +directed_pred = np.array([[-9999, 0, 0, 1, 1], + [3, -9999, 0, 1, 1], + [-9999, -9999, -9999, -9999, -9999], + [3, 0, 0, -9999, 1], + [4, 0, 0, 4, -9999]], dtype=float) + +undirected_SP = np.array([[0, 3, 3, 1, 2], + [3, 0, 6, 2, 4], + [3, 6, 0, 4, 5], + [1, 2, 4, 0, 2], + [2, 4, 5, 2, 0]], dtype=float) + +undirected_SP_limit_2 = np.array([[0, np.inf, np.inf, 1, 2], + [np.inf, 0, np.inf, 2, np.inf], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 2, np.inf, 0, 2], + [2, np.inf, np.inf, 2, 0]], dtype=float) + +undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5) +undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf + +undirected_pred = np.array([[-9999, 0, 0, 0, 0], + [1, -9999, 0, 1, 1], + [2, 0, -9999, 0, 0], + [3, 3, 0, -9999, 3], + [4, 4, 0, 4, -9999]], dtype=float) + +directed_negative_weighted_G = np.array([[0, 0, 0], + [-1, 0, 0], + [0, -1, 0]], dtype=float) + +directed_negative_weighted_SP = np.array([[0, np.inf, np.inf], + [-1, 0, np.inf], + [-2, -1, 0]], dtype=float) + +methods = ['auto', 'FW', 'D', 'BF', 'J'] + + +def test_dijkstra_limit(): + limits = [0, 2, np.inf] + results = [undirected_SP_limit_0, + undirected_SP_limit_2, + undirected_SP] + + def check(limit, result): + SP = dijkstra(undirected_G, directed=False, limit=limit) + assert_array_almost_equal(SP, result) + + for limit, result in zip(limits, results): + check(limit, result) + + +def test_directed(): + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_undirected(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_SP) + else: + SP2 = shortest_path(undirected_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +def test_directed_sparse_zero(): + # test directed sparse graph with zero-weight edge and two connected components + def check(method): + SP = shortest_path(directed_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_sparse_zero_SP) + + for method in methods: + check(method) + + +def test_undirected_sparse_zero(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_sparse_zero_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_sparse_zero_SP) + else: + SP2 = shortest_path(undirected_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_sparse_zero_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +@pytest.mark.parametrize('directed, SP_ans', + ((True, directed_SP), + (False, undirected_SP))) +@pytest.mark.parametrize('indices', ([0, 2, 4], [0, 4], [3, 4], [0, 0])) +def test_dijkstra_indices_min_only(directed, SP_ans, indices): + SP_ans = np.array(SP_ans) + indices = np.array(indices, dtype=np.int64) + min_ind_ans = indices[np.argmin(SP_ans[indices, :], axis=0)] + min_d_ans = np.zeros(SP_ans.shape[0], SP_ans.dtype) + for k in range(SP_ans.shape[0]): + min_d_ans[k] = SP_ans[min_ind_ans[k], k] + min_ind_ans[np.isinf(min_d_ans)] = -9999 + + SP, pred, sources = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=True) + assert_array_almost_equal(SP, min_d_ans) + assert_array_equal(min_ind_ans, sources) + SP = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=False) + assert_array_almost_equal(SP, min_d_ans) + + +@pytest.mark.parametrize('n', (10, 100, 1000)) +def test_dijkstra_min_only_random(n): + rng = np.random.default_rng(7345782358920239234) + data = scipy.sparse.random_array((n, n), density=0.5, format='lil', + rng=rng, dtype=np.float64) + data.setdiag(np.zeros(n, dtype=np.bool_)) + # choose some random vertices + v = np.arange(n) + rng.shuffle(v) + indices = v[:int(n*.1)] + ds, pred, sources = dijkstra(data, + directed=True, + indices=indices, + min_only=True, + return_predecessors=True) + for k in range(n): + p = pred[k] + s = sources[k] + while p != -9999: + assert sources[p] == s + p = pred[p] + + +def test_dijkstra_random(): + # reproduces the hang observed in gh-17782 + n = 10 + indices = [0, 4, 4, 5, 7, 9, 0, 6, 2, 3, 7, 9, 1, 2, 9, 2, 5, 6] + indptr = [0, 0, 2, 5, 6, 7, 8, 12, 15, 18, 18] + data = [0.33629, 0.40458, 0.47493, 0.42757, 0.11497, 0.91653, 0.69084, + 0.64979, 0.62555, 0.743, 0.01724, 0.99945, 0.31095, 0.15557, + 0.02439, 0.65814, 0.23478, 0.24072] + graph = scipy.sparse.csr_array((data, indices, indptr), shape=(n, n)) + dijkstra(graph, directed=True, return_predecessors=True) + + +def test_gh_17782_segfault(): + text = """%%MatrixMarket matrix coordinate real general + 84 84 22 + 2 1 4.699999809265137e+00 + 6 14 1.199999973177910e-01 + 9 6 1.199999973177910e-01 + 10 16 2.012000083923340e+01 + 11 10 1.422000026702881e+01 + 12 1 9.645999908447266e+01 + 13 18 2.012000083923340e+01 + 14 13 4.679999828338623e+00 + 15 11 1.199999973177910e-01 + 16 12 1.199999973177910e-01 + 18 15 1.199999973177910e-01 + 32 2 2.299999952316284e+00 + 33 20 6.000000000000000e+00 + 33 32 5.000000000000000e+00 + 36 9 3.720000028610229e+00 + 36 37 3.720000028610229e+00 + 36 38 3.720000028610229e+00 + 37 44 8.159999847412109e+00 + 38 32 7.903999328613281e+01 + 43 20 2.400000000000000e+01 + 43 33 4.000000000000000e+00 + 44 43 6.028000259399414e+01 + """ + data = mmread(StringIO(text), spmatrix=False) + dijkstra(data, directed=True, return_predecessors=True) + + +def test_shortest_path_indices(): + indices = np.arange(4) + + def check(func, indshape): + outshape = indshape + (5,) + SP = func(directed_G, directed=False, + indices=indices.reshape(indshape)) + assert_array_almost_equal(SP, undirected_SP[indices].reshape(outshape)) + + for indshape in [(4,), (4, 1), (2, 2)]: + for func in (dijkstra, bellman_ford, johnson, shortest_path): + check(func, indshape) + + assert_raises(ValueError, shortest_path, directed_G, method='FW', + indices=indices) + + +def test_predecessors(): + SP_res = {True: directed_SP, + False: undirected_SP} + pred_res = {True: directed_pred, + False: undirected_pred} + + def check(method, directed): + SP, pred = shortest_path(directed_G, method, directed=directed, + overwrite=False, + return_predecessors=True) + assert_array_almost_equal(SP, SP_res[directed]) + assert_array_almost_equal(pred, pred_res[directed]) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_construct_shortest_path(): + def check(method, directed): + SP1, pred = shortest_path(directed_G, + directed=directed, + overwrite=False, + return_predecessors=True) + SP2 = construct_dist_matrix(directed_G, pred, directed=directed) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_unweighted_path(): + def check(method, directed): + SP1 = shortest_path(directed_G, + directed=directed, + overwrite=False, + unweighted=True) + SP2 = shortest_path(unweighted_G, + directed=directed, + overwrite=False, + unweighted=False) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_negative_cycles(): + # create a small graph with a negative cycle + graph = np.ones([5, 5]) + graph.flat[::6] = 0 + graph[1, 2] = -2 + + def check(method, directed): + assert_raises(NegativeCycleError, shortest_path, graph, method, + directed) + + for directed in (True, False): + for method in ['FW', 'J', 'BF']: + check(method, directed) + + assert_raises(NegativeCycleError, yen, graph, 0, 1, 1, + directed=directed) + + +@pytest.mark.parametrize("method", ['FW', 'J', 'BF']) +def test_negative_weights(method): + SP = shortest_path(directed_negative_weighted_G, method, directed=True) + assert_allclose(SP, directed_negative_weighted_SP, atol=1e-10) + + +def test_masked_input(): + np.ma.masked_equal(directed_G, 0) + + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_overwrite(): + G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + foo = G.copy() + shortest_path(foo, overwrite=False) + assert_array_equal(foo, G) + + +@pytest.mark.parametrize('method', methods) +def test_buffer(method): + # Smoke test that sparse matrices with read-only buffers (e.g., those from + # joblib workers) do not cause:: + # + # ValueError: buffer source array is read-only + # + G = scipy.sparse.csr_array([[1.]]) + G.data.flags['WRITEABLE'] = False + shortest_path(G, method=method) + + +def test_NaN_warnings(): + with warnings.catch_warnings(record=True) as record: + shortest_path(np.array([[0, 1], [np.nan, 0]])) + for r in record: + assert r.category is not RuntimeWarning + + +def test_sparse_matrices(): + # Test that using lil,csr and csc sparse matrix do not cause error + G_dense = np.array([[0, 3, 0, 0, 0], + [0, 0, -1, 0, 0], + [0, 0, 0, 2, 0], + [0, 0, 0, 0, 4], + [0, 0, 0, 0, 0]], dtype=float) + SP = shortest_path(G_dense) + G_csr = scipy.sparse.csr_array(G_dense) + G_csc = scipy.sparse.csc_array(G_dense) + G_lil = scipy.sparse.lil_array(G_dense) + assert_array_almost_equal(SP, shortest_path(G_csr)) + assert_array_almost_equal(SP, shortest_path(G_csc)) + assert_array_almost_equal(SP, shortest_path(G_lil)) + + +def test_yen_directed(): + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=2, + return_predecessors=True + ) + assert_allclose(distances, [5., 9.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + + +def test_yen_undirected(): + distances = yen( + undirected_G, + source=0, + sink=3, + K=4, + ) + assert_allclose(distances, [1., 4., 5., 8.]) + +def test_yen_unweighted(): + # Ask for more paths than there are, verify only the available paths are returned + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=4, + unweighted=True, + return_predecessors=True, + ) + assert_allclose(distances, [2., 3.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + +def test_yen_no_paths(): + distances = yen( + directed_G, + source=2, + sink=3, + K=1, + ) + assert distances.size == 0 + +def test_yen_negative_weights(): + distances = yen( + directed_negative_weighted_G, + source=2, + sink=0, + K=1, + ) + assert_allclose(distances, [-2.]) + + +@pytest.mark.parametrize("min_only", (True, False)) +@pytest.mark.parametrize("directed", (True, False)) +@pytest.mark.parametrize("return_predecessors", (True, False)) +@pytest.mark.parametrize("index_dtype", (np.int32, np.int64)) +@pytest.mark.parametrize("indices", (None, [1])) +def test_20904(min_only, directed, return_predecessors, index_dtype, indices): + """Test two failures from gh-20904: int32 and indices-as-None.""" + adj_mat = scipy.sparse.eye_array(4, format="csr") + adj_mat = scipy.sparse.csr_array( + ( + adj_mat.data, + adj_mat.indices.astype(index_dtype), + adj_mat.indptr.astype(index_dtype), + ), + ) + dijkstra( + adj_mat, + directed, + indices=indices, + min_only=min_only, + return_predecessors=return_predecessors, + ) diff --git a/shared/package-files/3a/3a0067d1c1c344bd367bfc1bce91a6319492da3cb7ae2cb2233247b7559b76dc/test_x13.py b/shared/package-files/3a/3a0067d1c1c344bd367bfc1bce91a6319492da3cb7ae2cb2233247b7559b76dc/test_x13.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf8ba308e03c191525a36ff86d62ea59adea57d --- /dev/null +++ b/shared/package-files/3a/3a0067d1c1c344bd367bfc1bce91a6319492da3cb7ae2cb2233247b7559b76dc/test_x13.py @@ -0,0 +1,10 @@ +import pandas as pd + +from statsmodels.tsa.x13 import _make_var_names + + +def test_make_var_names(): + # Check that _make_var_names return the current name when exog is + # a pandas Series + exog = pd.Series([1, 2, 3], name="abc") + assert _make_var_names(exog) == exog.name diff --git a/shared/package-files/3a/3a00bdbe1bc4959e727567c730ba51b03455ecd455f7c190c5ad14386eb79b0d/Calcutta b/shared/package-files/3a/3a00bdbe1bc4959e727567c730ba51b03455ecd455f7c190c5ad14386eb79b0d/Calcutta new file mode 100644 index 0000000000000000000000000000000000000000..00bc80a65e9a7aa470d63fba1ce1b29ef173d922 Binary files /dev/null and b/shared/package-files/3a/3a00bdbe1bc4959e727567c730ba51b03455ecd455f7c190c5ad14386eb79b0d/Calcutta differ diff --git a/shared/package-files/3a/3a00bdbe1bc4959e727567c730ba51b03455ecd455f7c190c5ad14386eb79b0d/Kolkata b/shared/package-files/3a/3a00bdbe1bc4959e727567c730ba51b03455ecd455f7c190c5ad14386eb79b0d/Kolkata new file mode 100644 index 0000000000000000000000000000000000000000..00bc80a65e9a7aa470d63fba1ce1b29ef173d922 Binary files /dev/null and b/shared/package-files/3a/3a00bdbe1bc4959e727567c730ba51b03455ecd455f7c190c5ad14386eb79b0d/Kolkata differ diff --git a/shared/package-files/3a/3a030d0d5b4d4bf3e6843401207aa6f6f43f1424cd5284ea99254d92417a6b1a/embedding_ops.py b/shared/package-files/3a/3a030d0d5b4d4bf3e6843401207aa6f6f43f1424cd5284ea99254d92417a6b1a/embedding_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c4389a60d9b08fa264765ead9ad3f2932e141be9 --- /dev/null +++ b/shared/package-files/3a/3a030d0d5b4d4bf3e6843401207aa6f6f43f1424cd5284ea99254d92417a6b1a/embedding_ops.py @@ -0,0 +1,295 @@ +import torch +import torch.nn as nn +from torch import Tensor # noqa: F401 +from torch._jit_internal import Optional, List # noqa: F401 + +from .utils import _hide_packed_params_repr +from .utils import _quantize_weight + +__all__ = ['EmbeddingPackedParams', 'Embedding', 'EmbeddingBag'] + +class EmbeddingPackedParams(torch.nn.Module): + _version = 1 + + def __init__(self, num_embeddings, embedding_dim, dtype=torch.quint8): + super().__init__() + self.dtype = dtype + if self.dtype in [torch.quint8, torch.quint4x2]: + scales = torch.ones(num_embeddings, dtype=torch.float) + zero_points = torch.zeros(num_embeddings, dtype=torch.float) + wq = torch._empty_per_channel_affine_quantized([num_embeddings, embedding_dim], scales=scales, + zero_points=zero_points, + axis=0, dtype=self.dtype) + self.set_weight(wq) + else: + raise NotImplementedError(f'Unsupported dtype on quantized embedding! Supports quint8 and quint4x2. Got dtype: {dtype}') + + @torch.jit.export + def set_weight(self, weight: torch.Tensor) -> None: + if self.dtype in [torch.quint8, torch.quint4x2]: + self._packed_weight = torch.ops.quantized.embedding_bag_prepack(weight) + else: + raise NotImplementedError('Unsupported dtype for quantized embedding prepack! Supports quint8 and quint4x2.') + + + @torch.jit.export + def _weight(self): + if self.dtype in [torch.quint8, torch.quint4x2]: + return torch.ops.quantized.embedding_bag_unpack(self._packed_weight) + else: + raise NotImplementedError('Unsupported dtype for quantized embedding unpack! Supports quint8 and quint4x2.') + + def forward(self, x): + return x + + # Version 1 + # self + # |--- _packed_weight : Tensor representing weight of EmbeddingPackedParamsBase + # |--- dtype : torch.dtype + + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + destination[prefix + 'dtype'] = self.dtype + destination[prefix + '_packed_weight'] = self._weight() + + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs): + self.dtype = state_dict[prefix + 'dtype'] + state_dict.pop(prefix + 'dtype') + + weight = state_dict[prefix + '_packed_weight'] + state_dict.pop(prefix + '_packed_weight') + self.set_weight(weight) + + super()._load_from_state_dict(state_dict, prefix, local_metadata, False, + missing_keys, unexpected_keys, error_msgs) + + def __repr__(self): + return self._weight().__repr__() + +class Embedding(torch.nn.Module): + r""" + A quantized Embedding module with quantized packed weights as inputs. + We adopt the same interface as `torch.nn.Embedding`, please see + https://pytorch.org/docs/stable/nn.html#torch.nn.Embedding for documentation. + + Similar to :class:`~torch.nn.Embedding`, attributes will be randomly + initialized at module creation time and will be overwritten later + + Attributes: + weight (Tensor): the non-learnable quantized weights of the module of + shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`. + + Examples:: + >>> m = nn.quantized.Embedding(num_embeddings=10, embedding_dim=12) + >>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8]) + >>> output = m(indices) + >>> print(output.size()) + torch.Size([9, 12]) + + """ + _version = 1 + + def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None, + max_norm: Optional[float] = None, norm_type: float = 2., scale_grad_by_freq: bool = False, + sparse: bool = False, _weight: Optional[Tensor] = None, dtype=torch.quint8) -> None: + super().__init__() + self.num_embeddings = num_embeddings + self.embedding_dim = embedding_dim + self.dtype = dtype + + if _weight is None: + scales = torch.ones(num_embeddings, dtype=torch.float) + zero_points = torch.zeros(num_embeddings, dtype=torch.float) + qweight = torch._empty_per_channel_affine_quantized([num_embeddings, embedding_dim], + scales=scales, zero_points=zero_points, + axis=0, dtype=torch.quint8) + else: + assert list(_weight.shape) == [num_embeddings, embedding_dim], \ + 'Shape of weight does not match num_embeddings and embedding_dim' + qweight = _weight + + self._packed_params = EmbeddingPackedParams(num_embeddings, embedding_dim, dtype) + self._packed_params.set_weight(qweight) + + def forward(self, indices: Tensor) -> Tensor: + if self.dtype == torch.quint4x2: + return torch.ops.quantized.embedding_4bit(self._packed_params._packed_weight, indices) + else: + return torch.ops.quantized.embedding_byte(self._packed_params._packed_weight, indices) + + def _get_name(self): + return 'QuantizedEmbedding' + + def __repr__(self): + return _hide_packed_params_repr(self, EmbeddingPackedParams) + + def extra_repr(self): + extra_repr_str = 'num_embeddings={}, embedding_dim={}, dtype={}, qscheme={}'.format( + self.num_embeddings, self.embedding_dim, self._packed_params.dtype, self.weight().qscheme() + ) + + return extra_repr_str + + def set_weight(self, w: torch.Tensor) -> None: + self._packed_params.set_weight(w) + + def weight(self): + return self._packed_params._weight() + + @classmethod + def from_float(cls, mod): + r"""Create a quantized embedding module from a float module + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by user + """ + if hasattr(mod, 'weight_fake_quant'): + assert type(mod) == torch.ao.nn.qat.Embedding, 'nnq.' + cls.__name__ + '.from_float ' + \ + 'with fake quant only works for ' + torch.ao.nn.qat.Embedding.__name__ + weight_observer = mod.weight_fake_quant + activation_post_process = mod.activation_post_process + else: + assert type(mod) == nn.Embedding, 'nnq.' + cls.__name__ + '.from_float only works for ' + \ + nn.Embedding.__name__ + assert hasattr(mod, 'qconfig'), 'Embedding input float module must have qconfig defined' + from torch.ao.quantization import float_qparams_weight_only_qconfig + if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr] + weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator] + else: + weight_observer = float_qparams_weight_only_qconfig.weight() + + dtype = weight_observer.dtype + is_float_qparams_qconfig = weight_observer.qscheme == torch.per_channel_affine_float_qparams + assert is_float_qparams_qconfig, \ + 'Embedding quantization is only supported with float_qparams_weight_only_qconfig.' + + assert dtype == torch.quint8 or dtype == torch.quint4x2, \ + f'The only supported dtype for nnq.Embedding is torch.quint8 and torch.quint4x2, got {dtype}' + + # Run the observer to calculate qparams. + weight_observer(mod.weight) + qweight = _quantize_weight(mod.weight.float(), weight_observer) + + # Create quantized Embedding module and pass in the quantized weight + qembedding = Embedding(mod.num_embeddings, mod.embedding_dim) + qembedding.set_weight(qweight) + return qembedding + + @classmethod + def from_reference(cls, ref_embedding): + qembedding = cls( + ref_embedding.num_embeddings, + ref_embedding.embedding_dim, + ref_embedding.padding_idx, + ref_embedding.max_norm, + ref_embedding.norm_type, + ref_embedding.scale_grad_by_freq, + ref_embedding.sparse, + ref_embedding.get_quantized_weight(), + ref_embedding.weight_dtype, + ) + return qembedding + +class EmbeddingBag(Embedding): + r""" + A quantized EmbeddingBag module with quantized packed weights as inputs. + We adopt the same interface as `torch.nn.EmbeddingBag`, please see + https://pytorch.org/docs/stable/nn.html#torch.nn.EmbeddingBag for documentation. + + Similar to :class:`~torch.nn.EmbeddingBag`, attributes will be randomly + initialized at module creation time and will be overwritten later + + Attributes: + weight (Tensor): the non-learnable quantized weights of the module of + shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`. + + Examples:: + >>> m = nn.quantized.EmbeddingBag(num_embeddings=10, embedding_dim=12, include_last_offset=True, mode='sum') + >>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8, 6, 6, 9, 1, 6, 8, 8, 3, 2, 3, 6, 3, 6, 5, 7, 0, 8, 4, 6, 5, 8, 2, 3]) + >>> offsets = torch.tensor([0, 19, 20, 28, 28, 32]) + >>> output = m(indices, offsets) + >>> print(output.size()) + torch.Size([5, 12]) + + """ + _version = 1 + + def __init__(self, num_embeddings: int, embedding_dim: int, + max_norm: Optional[float] = None, norm_type: float = 2., scale_grad_by_freq: bool = False, + mode: str = 'sum', sparse: bool = False, _weight: Optional[Tensor] = None, + include_last_offset: bool = False, dtype=torch.quint8) -> None: + super().__init__(num_embeddings, embedding_dim, _weight=_weight, dtype=dtype) + + self.mode = mode + self.pruned_weights = False + self.include_last_offset = include_last_offset + self.dtype = dtype + + def forward(self, indices: Tensor, offsets: Optional[Tensor] = None, per_sample_weights: Optional[Tensor] = None, + compressed_indices_mapping: Optional[Tensor] = None) -> Tensor: + if self.dtype == torch.quint4x2: + return torch.ops.quantized.embedding_bag_4bit(self._packed_params._packed_weight, indices, offsets, False, 0, + self.pruned_weights, per_sample_weights, compressed_indices_mapping, + self.include_last_offset) + else: + return torch.ops.quantized.embedding_bag_byte(self._packed_params._packed_weight, indices, offsets, False, 0, + self.pruned_weights, per_sample_weights, compressed_indices_mapping, + self.include_last_offset) + + def _get_name(self): + return 'QuantizedEmbeddingBag' + + @classmethod + def from_float(cls, mod): + r"""Create a quantized embedding_bag module from a float module + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by user + """ + if hasattr(mod, 'weight_fake_quant'): + weight_observer = mod.weight_fake_quant + else: + assert type(mod) == nn.EmbeddingBag, 'nnq.' + cls.__name__ + '.from_float only works for ' + \ + nn.EmbeddingBag.__name__ + assert hasattr(mod, 'qconfig'), 'EmbeddingBag input float module must have qconfig defined' + from torch.ao.quantization.qconfig import float_qparams_weight_only_qconfig + if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr] + weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator] + else: + weight_observer = float_qparams_weight_only_qconfig.weight() + + dtype = weight_observer.dtype + is_float_qparams_qconfig = weight_observer.qscheme == torch.per_channel_affine_float_qparams + assert is_float_qparams_qconfig, \ + 'EmbeddingBag quantization is only supported with float_qparams_weight_only_qconfig.' + + assert dtype == torch.quint8 or dtype == torch.quint4x2, \ + f'The only supported dtype for nnq.EmbeddingBag is torch.quint8 and torch.quint4x2, got {dtype}' + + # Run the observer to calculate qparams. + weight_observer(mod.weight) + qweight = _quantize_weight(mod.weight.float(), weight_observer) + + # Create quantized EmbeddingBag module and pass in the quantized weight + qembedding_bag = EmbeddingBag(mod.num_embeddings, mod.embedding_dim, dtype=dtype) + qembedding_bag.set_weight(qweight) + return qembedding_bag + + @classmethod + def from_reference(cls, ref_embedding_bag): + qembedding_bag = cls( + ref_embedding_bag.num_embeddings, + ref_embedding_bag.embedding_dim, + ref_embedding_bag.max_norm, + ref_embedding_bag.norm_type, + ref_embedding_bag.scale_grad_by_freq, + ref_embedding_bag.mode, + ref_embedding_bag.sparse, + ref_embedding_bag.get_quantized_weight(), + ref_embedding_bag.include_last_offset, + ref_embedding_bag.weight_dtype, + ) + return qembedding_bag diff --git a/shared/package-files/3a/3a032a4748c87df750097edba9b37c5b26d0adfaebeac5e3f421af3540bf7070/layer1.pyi b/shared/package-files/3a/3a032a4748c87df750097edba9b37c5b26d0adfaebeac5e3f421af3540bf7070/layer1.pyi new file mode 100644 index 0000000000000000000000000000000000000000..86c5724533b858368cb63f05f53f28bc01e7bf88 --- /dev/null +++ b/shared/package-files/3a/3a032a4748c87df750097edba9b37c5b26d0adfaebeac5e3f421af3540bf7070/layer1.pyi @@ -0,0 +1,82 @@ +from typing import Any, Dict, List, Mapping, Optional, Type + +from boto.connection import AWSQueryConnection + +class KMSConnection(AWSQueryConnection): + APIVersion: str + DefaultRegionName: str + DefaultRegionEndpoint: str + ServiceName: str + TargetPrefix: str + ResponseError: Type[Exception] + region: Any + def __init__(self, **kwargs) -> None: ... + def create_alias(self, alias_name: str, target_key_id: str) -> Optional[Dict[str, Any]]: ... + def create_grant( + self, + key_id: str, + grantee_principal: str, + retiring_principal: Optional[str] = ..., + operations: Optional[List[str]] = ..., + constraints: Optional[Dict[str, Dict[str, str]]] = ..., + grant_tokens: Optional[List[str]] = ..., + ) -> Optional[Dict[str, Any]]: ... + def create_key( + self, policy: Optional[str] = ..., description: Optional[str] = ..., key_usage: Optional[str] = ... + ) -> Optional[Dict[str, Any]]: ... + def decrypt( + self, + ciphertext_blob: bytes, + encryption_context: Optional[Mapping[str, Any]] = ..., + grant_tokens: Optional[List[str]] = ..., + ) -> Optional[Dict[str, Any]]: ... + def delete_alias(self, alias_name: str) -> Optional[Dict[str, Any]]: ... + def describe_key(self, key_id: str) -> Optional[Dict[str, Any]]: ... + def disable_key(self, key_id: str) -> Optional[Dict[str, Any]]: ... + def disable_key_rotation(self, key_id: str) -> Optional[Dict[str, Any]]: ... + def enable_key(self, key_id: str) -> Optional[Dict[str, Any]]: ... + def enable_key_rotation(self, key_id: str) -> Optional[Dict[str, Any]]: ... + def encrypt( + self, + key_id: str, + plaintext: bytes, + encryption_context: Optional[Mapping[str, Any]] = ..., + grant_tokens: Optional[List[str]] = ..., + ) -> Optional[Dict[str, Any]]: ... + def generate_data_key( + self, + key_id: str, + encryption_context: Optional[Mapping[str, Any]] = ..., + number_of_bytes: Optional[int] = ..., + key_spec: Optional[str] = ..., + grant_tokens: Optional[List[str]] = ..., + ) -> Optional[Dict[str, Any]]: ... + def generate_data_key_without_plaintext( + self, + key_id: str, + encryption_context: Optional[Mapping[str, Any]] = ..., + key_spec: Optional[str] = ..., + number_of_bytes: Optional[int] = ..., + grant_tokens: Optional[List[str]] = ..., + ) -> Optional[Dict[str, Any]]: ... + def generate_random(self, number_of_bytes: Optional[int] = ...) -> Optional[Dict[str, Any]]: ... + def get_key_policy(self, key_id: str, policy_name: str) -> Optional[Dict[str, Any]]: ... + def get_key_rotation_status(self, key_id: str) -> Optional[Dict[str, Any]]: ... + def list_aliases(self, limit: Optional[int] = ..., marker: Optional[str] = ...) -> Optional[Dict[str, Any]]: ... + def list_grants(self, key_id: str, limit: Optional[int] = ..., marker: Optional[str] = ...) -> Optional[Dict[str, Any]]: ... + def list_key_policies( + self, key_id: str, limit: Optional[int] = ..., marker: Optional[str] = ... + ) -> Optional[Dict[str, Any]]: ... + def list_keys(self, limit: Optional[int] = ..., marker: Optional[str] = ...) -> Optional[Dict[str, Any]]: ... + def put_key_policy(self, key_id: str, policy_name: str, policy: str) -> Optional[Dict[str, Any]]: ... + def re_encrypt( + self, + ciphertext_blob: bytes, + destination_key_id: str, + source_encryption_context: Optional[Mapping[str, Any]] = ..., + destination_encryption_context: Optional[Mapping[str, Any]] = ..., + grant_tokens: Optional[List[str]] = ..., + ) -> Optional[Dict[str, Any]]: ... + def retire_grant(self, grant_token: str) -> Optional[Dict[str, Any]]: ... + def revoke_grant(self, key_id: str, grant_id: str) -> Optional[Dict[str, Any]]: ... + def update_key_description(self, key_id: str, description: str) -> Optional[Dict[str, Any]]: ... diff --git a/shared/package-files/3a/3a03a855193e4c8f6dd210ac23cd952e479b91945d37b6978da996311c34c984/_aliases.py b/shared/package-files/3a/3a03a855193e4c8f6dd210ac23cd952e479b91945d37b6978da996311c34c984/_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..90b48f059bafad6d9016e6284d5a3fb9ca18f6d6 --- /dev/null +++ b/shared/package-files/3a/3a03a855193e4c8f6dd210ac23cd952e479b91945d37b6978da996311c34c984/_aliases.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +from typing import Optional + +import cupy as cp + +from ..common import _aliases, _helpers +from ..common._typing import NestedSequence, SupportsBufferProtocol +from .._internal import get_xp +from ._info import __array_namespace_info__ +from ._typing import Array, Device, DType + +bool = cp.bool_ + +# Basic renames +acos = cp.arccos +acosh = cp.arccosh +asin = cp.arcsin +asinh = cp.arcsinh +atan = cp.arctan +atan2 = cp.arctan2 +atanh = cp.arctanh +bitwise_left_shift = cp.left_shift +bitwise_invert = cp.invert +bitwise_right_shift = cp.right_shift +concat = cp.concatenate +pow = cp.power + +arange = get_xp(cp)(_aliases.arange) +empty = get_xp(cp)(_aliases.empty) +empty_like = get_xp(cp)(_aliases.empty_like) +eye = get_xp(cp)(_aliases.eye) +full = get_xp(cp)(_aliases.full) +full_like = get_xp(cp)(_aliases.full_like) +linspace = get_xp(cp)(_aliases.linspace) +ones = get_xp(cp)(_aliases.ones) +ones_like = get_xp(cp)(_aliases.ones_like) +zeros = get_xp(cp)(_aliases.zeros) +zeros_like = get_xp(cp)(_aliases.zeros_like) +UniqueAllResult = get_xp(cp)(_aliases.UniqueAllResult) +UniqueCountsResult = get_xp(cp)(_aliases.UniqueCountsResult) +UniqueInverseResult = get_xp(cp)(_aliases.UniqueInverseResult) +unique_all = get_xp(cp)(_aliases.unique_all) +unique_counts = get_xp(cp)(_aliases.unique_counts) +unique_inverse = get_xp(cp)(_aliases.unique_inverse) +unique_values = get_xp(cp)(_aliases.unique_values) +std = get_xp(cp)(_aliases.std) +var = get_xp(cp)(_aliases.var) +cumulative_sum = get_xp(cp)(_aliases.cumulative_sum) +cumulative_prod = get_xp(cp)(_aliases.cumulative_prod) +clip = get_xp(cp)(_aliases.clip) +permute_dims = get_xp(cp)(_aliases.permute_dims) +reshape = get_xp(cp)(_aliases.reshape) +argsort = get_xp(cp)(_aliases.argsort) +sort = get_xp(cp)(_aliases.sort) +nonzero = get_xp(cp)(_aliases.nonzero) +ceil = get_xp(cp)(_aliases.ceil) +floor = get_xp(cp)(_aliases.floor) +trunc = get_xp(cp)(_aliases.trunc) +matmul = get_xp(cp)(_aliases.matmul) +matrix_transpose = get_xp(cp)(_aliases.matrix_transpose) +tensordot = get_xp(cp)(_aliases.tensordot) +sign = get_xp(cp)(_aliases.sign) +finfo = get_xp(cp)(_aliases.finfo) +iinfo = get_xp(cp)(_aliases.iinfo) + + +# asarray also adds the copy keyword, which is not present in numpy 1.0. +def asarray( + obj: ( + Array + | bool | int | float | complex + | NestedSequence[bool | int | float | complex] + | SupportsBufferProtocol + ), + /, + *, + dtype: Optional[DType] = None, + device: Optional[Device] = None, + copy: Optional[bool] = None, + **kwargs, +) -> Array: + """ + Array API compatibility wrapper for asarray(). + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + with cp.cuda.Device(device): + if copy is None: + return cp.asarray(obj, dtype=dtype, **kwargs) + else: + res = cp.array(obj, dtype=dtype, copy=copy, **kwargs) + if not copy and res is not obj: + raise ValueError("Unable to avoid copy while creating an array as requested") + return res + + +def astype( + x: Array, + dtype: DType, + /, + *, + copy: bool = True, + device: Optional[Device] = None, +) -> Array: + if device is None: + return x.astype(dtype=dtype, copy=copy) + out = _helpers.to_device(x.astype(dtype=dtype, copy=False), device) + return out.copy() if copy and out is x else out + + +# cupy.count_nonzero does not have keepdims +def count_nonzero( + x: Array, + axis=None, + keepdims=False +) -> Array: + result = cp.count_nonzero(x, axis) + if keepdims: + if axis is None: + return cp.reshape(result, [1]*x.ndim) + return cp.expand_dims(result, axis) + return result + + +# take_along_axis: axis defaults to -1 but in cupy (and numpy) axis is a required arg +def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1): + return cp.take_along_axis(x, indices, axis=axis) + + +# These functions are completely new here. If the library already has them +# (i.e., numpy 2.0), use the library version instead of our wrapper. +if hasattr(cp, 'vecdot'): + vecdot = cp.vecdot +else: + vecdot = get_xp(cp)(_aliases.vecdot) + +if hasattr(cp, 'isdtype'): + isdtype = cp.isdtype +else: + isdtype = get_xp(cp)(_aliases.isdtype) + +if hasattr(cp, 'unstack'): + unstack = cp.unstack +else: + unstack = get_xp(cp)(_aliases.unstack) + +__all__ = _aliases.__all__ + ['__array_namespace_info__', 'asarray', 'astype', + 'acos', 'acosh', 'asin', 'asinh', 'atan', + 'atan2', 'atanh', 'bitwise_left_shift', + 'bitwise_invert', 'bitwise_right_shift', + 'bool', 'concat', 'count_nonzero', 'pow', 'sign', + 'take_along_axis'] + +_all_ignore = ['cp', 'get_xp'] diff --git a/shared/package-files/3a/3a03e957db0e7f13a3ef54a9ba6acef587ff27ca2ba78f7557dab898ab803650/fill_cpu_dispatch.h b/shared/package-files/3a/3a03e957db0e7f13a3ef54a9ba6acef587ff27ca2ba78f7557dab898ab803650/fill_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6b8dd4e8a5906ce0be42b0b49045176c038b60ff --- /dev/null +++ b/shared/package-files/3a/3a03e957db0e7f13a3ef54a9ba6acef587ff27ca2ba78f7557dab898ab803650/fill_cpu_dispatch.h @@ -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 & fill_(at::Tensor & self, const at::Scalar & value); +TORCH_API at::Tensor & fill_(at::Tensor & self, const at::Tensor & value); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/3a/3a0439f1eabdcc8844b8f2b5c7ab64d25675e9cb971907046d96e200f802ae88/to_mkldnn.h b/shared/package-files/3a/3a0439f1eabdcc8844b8f2b5c7ab64d25675e9cb971907046d96e200f802ae88/to_mkldnn.h new file mode 100644 index 0000000000000000000000000000000000000000..9430f7b93d85c9fa573f80df83e18d5c6cf2c968 --- /dev/null +++ b/shared/package-files/3a/3a0439f1eabdcc8844b8f2b5c7ab64d25675e9cb971907046d96e200f802ae88/to_mkldnn.h @@ -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::to_mkldnn.out(Tensor self, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & to_mkldnn_out(at::Tensor & out, const at::Tensor & self, c10::optional dtype=c10::nullopt) { + return at::_ops::to_mkldnn_out::call(self, dtype, out); +} +// aten::to_mkldnn.out(Tensor self, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & to_mkldnn_outf(const at::Tensor & self, c10::optional dtype, at::Tensor & out) { + return at::_ops::to_mkldnn_out::call(self, dtype, out); +} + +} diff --git a/shared/package-files/3a/3a0b8e5bcd7c48e69f60af6502badf3adecdc3b3607da19cc7d111b75ac1c56a/server.pyi b/shared/package-files/3a/3a0b8e5bcd7c48e69f60af6502badf3adecdc3b3607da19cc7d111b75ac1c56a/server.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8cdcf499ac2a4e456fb5f0d09a6580ba5e96e2a9 --- /dev/null +++ b/shared/package-files/3a/3a0b8e5bcd7c48e69f60af6502badf3adecdc3b3607da19cc7d111b75ac1c56a/server.pyi @@ -0,0 +1,160 @@ +import http.server +import pydoc +import socketserver +import sys +from datetime import datetime +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Pattern, Protocol, Tuple, Type, Union +from xmlrpc.client import Fault + +_Marshallable = Union[ + None, bool, int, float, str, bytes, tuple, list, dict, datetime +] # TODO: Recursive type on tuple, list, dict + +# The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy +class _DispatchArity0(Protocol): + def __call__(self) -> _Marshallable: ... + +class _DispatchArity1(Protocol): + def __call__(self, __arg1: _Marshallable) -> _Marshallable: ... + +class _DispatchArity2(Protocol): + def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable) -> _Marshallable: ... + +class _DispatchArity3(Protocol): + def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable) -> _Marshallable: ... + +class _DispatchArity4(Protocol): + def __call__( + self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable, __arg4: _Marshallable + ) -> _Marshallable: ... + +class _DispatchArityN(Protocol): + def __call__(self, *args: _Marshallable) -> _Marshallable: ... + +_DispatchProtocol = Union[_DispatchArity0, _DispatchArity1, _DispatchArity2, _DispatchArity3, _DispatchArity4, _DispatchArityN] + +def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = ...) -> Any: ... # undocumented +def list_public_methods(obj: Any) -> List[str]: ... # undocumented + +class SimpleXMLRPCDispatcher: # undocumented + + funcs: Dict[str, _DispatchProtocol] + instance: Optional[Any] + allow_none: bool + encoding: str + use_builtin_types: bool + def __init__(self, allow_none: bool = ..., encoding: Optional[str] = ..., use_builtin_types: bool = ...) -> None: ... + def register_instance(self, instance: Any, allow_dotted_names: bool = ...) -> None: ... + if sys.version_info >= (3, 7): + def register_function( + self, function: Optional[_DispatchProtocol] = ..., name: Optional[str] = ... + ) -> Callable[..., Any]: ... + else: + def register_function(self, function: _DispatchProtocol, name: Optional[str] = ...) -> Callable[..., Any]: ... + def register_introspection_functions(self) -> None: ... + def register_multicall_functions(self) -> None: ... + def _marshaled_dispatch( + self, + data: str, + dispatch_method: Optional[ + Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]] + ] = ..., + path: Optional[Any] = ..., + ) -> str: ... # undocumented + def system_listMethods(self) -> List[str]: ... # undocumented + def system_methodSignature(self, method_name: str) -> str: ... # undocumented + def system_methodHelp(self, method_name: str) -> str: ... # undocumented + def system_multicall(self, call_list: List[Dict[str, _Marshallable]]) -> List[_Marshallable]: ... # undocumented + def _dispatch(self, method: str, params: Iterable[_Marshallable]) -> _Marshallable: ... # undocumented + +class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): + + rpc_paths: Tuple[str, str] = ... + encode_threshold: int = ... # undocumented + aepattern: Pattern[str] # undocumented + def accept_encodings(self) -> Dict[str, float]: ... + def is_rpc_path_valid(self) -> bool: ... + def do_POST(self) -> None: ... + def decode_request_content(self, data: bytes) -> Optional[bytes]: ... + def report_404(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., size: Union[int, str] = ...) -> None: ... + +class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): + + allow_reuse_address: bool = ... + _send_traceback_handler: bool = ... + def __init__( + self, + addr: Tuple[str, int], + requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = ..., + allow_none: bool = ..., + encoding: Optional[str] = ..., + bind_and_activate: bool = ..., + use_builtin_types: bool = ..., + ) -> None: ... + +class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented + + dispatchers: Dict[str, SimpleXMLRPCDispatcher] + allow_none: bool + encoding: str + def __init__( + self, + addr: Tuple[str, int], + requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = ..., + allow_none: bool = ..., + encoding: Optional[str] = ..., + bind_and_activate: bool = ..., + use_builtin_types: bool = ..., + ) -> None: ... + def add_dispatcher(self, path: str, dispatcher: SimpleXMLRPCDispatcher) -> SimpleXMLRPCDispatcher: ... + def get_dispatcher(self, path: str) -> SimpleXMLRPCDispatcher: ... + def _marshaled_dispatch( + self, + data: str, + dispatch_method: Optional[ + Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]] + ] = ..., + path: Optional[Any] = ..., + ) -> str: ... + +class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): + def __init__(self, allow_none: bool = ..., encoding: Optional[str] = ..., use_builtin_types: bool = ...) -> None: ... + def handle_xmlrpc(self, request_text: str) -> None: ... + def handle_get(self) -> None: ... + def handle_request(self, request_text: Optional[str] = ...) -> None: ... + +class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented + def docroutine(self, object: object, name: str, mod: Optional[str] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., methods: Mapping[str, str] = ..., cl: Optional[type] = ...) -> str: ... # type: ignore + def docserver(self, server_name: str, package_documentation: str, methods: Dict[str, str]) -> str: ... + +class XMLRPCDocGenerator: # undocumented + + server_name: str + server_documentation: str + server_title: str + def __init__(self) -> None: ... + def set_server_title(self, server_title: str) -> None: ... + def set_server_name(self, server_name: str) -> None: ... + def set_server_documentation(self, server_documentation: str) -> None: ... + def generate_html_documentation(self) -> str: ... + +class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): + def do_GET(self) -> None: ... + +class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): + def __init__( + self, + addr: Tuple[str, int], + requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = ..., + allow_none: bool = ..., + encoding: Optional[str] = ..., + bind_and_activate: bool = ..., + use_builtin_types: bool = ..., + ) -> None: ... + +class DocCGIXMLRPCRequestHandler(CGIXMLRPCRequestHandler, XMLRPCDocGenerator): + def __init__(self) -> None: ... diff --git a/shared/package-files/3a/3a0e7fe7b91bb0dfd038776d5480c47d03c8d552163a76fc806236cc185dc36d/__init__.py b/shared/package-files/3a/3a0e7fe7b91bb0dfd038776d5480c47d03c8d552163a76fc806236cc185dc36d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd9c627a1e423ae9f92f6cc7a43a06fbbd6976c --- /dev/null +++ b/shared/package-files/3a/3a0e7fe7b91bb0dfd038776d5480c47d03c8d552163a76fc806236cc185dc36d/__init__.py @@ -0,0 +1,20 @@ +# 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 hypothesis.extra.pandas.impl import ( + column, + columns, + data_frames, + indexes, + range_indexes, + series, +) + +__all__ = ["indexes", "range_indexes", "series", "column", "columns", "data_frames"] diff --git a/shared/package-files/3a/3a0f011019f39fcd8b64432f024d7080fe709cabb69554e7be9a4cab15a39f81/bq300-8 b/shared/package-files/3a/3a0f011019f39fcd8b64432f024d7080fe709cabb69554e7be9a4cab15a39f81/bq300-8 new file mode 100644 index 0000000000000000000000000000000000000000..7c0d8f5eee9169f5b4cc882b93aa9111026a2e2a Binary files /dev/null and b/shared/package-files/3a/3a0f011019f39fcd8b64432f024d7080fe709cabb69554e7be9a4cab15a39f81/bq300-8 differ diff --git a/shared/package-files/3a/3a0faaeb457e9ddfbcc65e550560cfb58ab119e7a6aecf2b602a0209629d8e67/test_encoding.py b/shared/package-files/3a/3a0faaeb457e9ddfbcc65e550560cfb58ab119e7a6aecf2b602a0209629d8e67/test_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd3917ba9c044962c262cac705e43b6d597599c --- /dev/null +++ b/shared/package-files/3a/3a0faaeb457e9ddfbcc65e550560cfb58ab119e7a6aecf2b602a0209629d8e67/test_encoding.py @@ -0,0 +1,337 @@ +""" +Tests encoding functionality during parsing +for all of the parsers defined in parsers.py +""" +from io import ( + BytesIO, + TextIOWrapper, +) +import os +import tempfile +import uuid + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + read_csv, +) +import pandas._testing as tm + +pytestmark = pytest.mark.filterwarnings( + "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" +) + +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") + + +def test_bytes_io_input(all_parsers): + encoding = "cp1255" + parser = all_parsers + + data = BytesIO("שלום:1234\n562:123".encode(encoding)) + result = parser.read_csv(data, sep=":", encoding=encoding) + + expected = DataFrame([[562, 123]], columns=["שלום", "1234"]) + tm.assert_frame_equal(result, expected) + + +@skip_pyarrow # CSV parse error: Empty CSV file or block +def test_read_csv_unicode(all_parsers): + parser = all_parsers + data = BytesIO("\u0141aski, Jan;1".encode()) + + result = parser.read_csv(data, sep=";", encoding="utf-8", header=None) + expected = DataFrame([["\u0141aski, Jan", 1]]) + tm.assert_frame_equal(result, expected) + + +@skip_pyarrow +@pytest.mark.parametrize("sep", [",", "\t"]) +@pytest.mark.parametrize("encoding", ["utf-16", "utf-16le", "utf-16be"]) +def test_utf16_bom_skiprows(all_parsers, sep, encoding): + # see gh-2298 + parser = all_parsers + data = """skip this +skip this too +A,B,C +1,2,3 +4,5,6""".replace( + ",", sep + ) + path = f"__{uuid.uuid4()}__.csv" + kwargs = {"sep": sep, "skiprows": 2} + utf8 = "utf-8" + + with tm.ensure_clean(path) as path: + bytes_data = data.encode(encoding) + + with open(path, "wb") as f: + f.write(bytes_data) + + with TextIOWrapper(BytesIO(data.encode(utf8)), encoding=utf8) as bytes_buffer: + result = parser.read_csv(path, encoding=encoding, **kwargs) + expected = parser.read_csv(bytes_buffer, encoding=utf8, **kwargs) + tm.assert_frame_equal(result, expected) + + +def test_utf16_example(all_parsers, csv_dir_path): + path = os.path.join(csv_dir_path, "utf16_ex.txt") + parser = all_parsers + result = parser.read_csv(path, encoding="utf-16", sep="\t") + assert len(result) == 50 + + +def test_unicode_encoding(all_parsers, csv_dir_path): + path = os.path.join(csv_dir_path, "unicode_series.csv") + parser = all_parsers + + result = parser.read_csv(path, header=None, encoding="latin-1") + result = result.set_index(0) + got = result[1][1632] + + expected = "\xc1 k\xf6ldum klaka (Cold Fever) (1994)" + assert got == expected + + +@pytest.mark.parametrize( + "data,kwargs,expected", + [ + # Basic test + ("a\n1", {}, DataFrame({"a": [1]})), + # "Regular" quoting + ('"a"\n1', {"quotechar": '"'}, DataFrame({"a": [1]})), + # Test in a data row instead of header + ("b\n1", {"names": ["a"]}, DataFrame({"a": ["b", "1"]})), + # Test in empty data row with skipping + ("\n1", {"names": ["a"], "skip_blank_lines": True}, DataFrame({"a": [1]})), + # Test in empty data row without skipping + ( + "\n1", + {"names": ["a"], "skip_blank_lines": False}, + DataFrame({"a": [np.nan, 1]}), + ), + ], +) +def test_utf8_bom(all_parsers, data, kwargs, expected, request): + # see gh-4793 + parser = all_parsers + bom = "\ufeff" + utf8 = "utf-8" + + def _encode_data_with_bom(_data): + bom_data = (bom + _data).encode(utf8) + return BytesIO(bom_data) + + if ( + parser.engine == "pyarrow" + and data == "\n1" + and kwargs.get("skip_blank_lines", True) + ): + # CSV parse error: Empty CSV file or block: cannot infer number of columns + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") + + result = parser.read_csv(_encode_data_with_bom(data), encoding=utf8, **kwargs) + tm.assert_frame_equal(result, expected) + + +def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt): + # see gh-13549 + expected = DataFrame({"mb_num": [4.8], "multibyte": ["test"]}) + parser = all_parsers + + encoding = encoding_fmt.format(utf_value) + data = "mb_num,multibyte\n4.8,test".encode(encoding) + + result = parser.read_csv(BytesIO(data), encoding=encoding) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "file_path,encoding", + [ + (("io", "data", "csv", "test1.csv"), "utf-8"), + (("io", "parser", "data", "unicode_series.csv"), "latin-1"), + (("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"), + ], +) +def test_binary_mode_file_buffers(all_parsers, file_path, encoding, datapath): + # gh-23779: Python csv engine shouldn't error on files opened in binary. + # gh-31575: Python csv engine shouldn't error on files opened in raw binary. + parser = all_parsers + + fpath = datapath(*file_path) + expected = parser.read_csv(fpath, encoding=encoding) + + with open(fpath, encoding=encoding) as fa: + result = parser.read_csv(fa) + assert not fa.closed + tm.assert_frame_equal(expected, result) + + with open(fpath, mode="rb") as fb: + result = parser.read_csv(fb, encoding=encoding) + assert not fb.closed + tm.assert_frame_equal(expected, result) + + with open(fpath, mode="rb", buffering=0) as fb: + result = parser.read_csv(fb, encoding=encoding) + assert not fb.closed + tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize("pass_encoding", [True, False]) +def test_encoding_temp_file(all_parsers, utf_value, encoding_fmt, pass_encoding): + # see gh-24130 + parser = all_parsers + encoding = encoding_fmt.format(utf_value) + + if parser.engine == "pyarrow" and pass_encoding is True and utf_value in [16, 32]: + # FIXME: this is bad! + pytest.skip("These cases freeze") + + expected = DataFrame({"foo": ["bar"]}) + + with tm.ensure_clean(mode="w+", encoding=encoding, return_filelike=True) as f: + f.write("foo\nbar") + f.seek(0) + + result = parser.read_csv(f, encoding=encoding if pass_encoding else None) + tm.assert_frame_equal(result, expected) + + +def test_encoding_named_temp_file(all_parsers): + # see gh-31819 + parser = all_parsers + encoding = "shift-jis" + + title = "てすと" + data = "こむ" + + expected = DataFrame({title: [data]}) + + with tempfile.NamedTemporaryFile() as f: + f.write(f"{title}\n{data}".encode(encoding)) + + f.seek(0) + + result = parser.read_csv(f, encoding=encoding) + tm.assert_frame_equal(result, expected) + assert not f.closed + + +@pytest.mark.parametrize( + "encoding", ["utf-8", "utf-16", "utf-16-be", "utf-16-le", "utf-32"] +) +def test_parse_encoded_special_characters(encoding): + # GH16218 Verify parsing of data with encoded special characters + # Data contains a Unicode 'FULLWIDTH COLON' (U+FF1A) at position (0,"a") + data = "a\tb\n:foo\t0\nbar\t1\nbaz\t2" # noqa: RUF001 + encoded_data = BytesIO(data.encode(encoding)) + result = read_csv(encoded_data, delimiter="\t", encoding=encoding) + + expected = DataFrame( + data=[[":foo", 0], ["bar", 1], ["baz", 2]], # noqa: RUF001 + columns=["a", "b"], + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("encoding", ["utf-8", None, "utf-16", "cp1255", "latin-1"]) +def test_encoding_memory_map(all_parsers, encoding): + # GH40986 + parser = all_parsers + expected = DataFrame( + { + "name": ["Raphael", "Donatello", "Miguel Angel", "Leonardo"], + "mask": ["red", "purple", "orange", "blue"], + "weapon": ["sai", "bo staff", "nunchunk", "katana"], + } + ) + with tm.ensure_clean() as file: + expected.to_csv(file, index=False, encoding=encoding) + + if parser.engine == "pyarrow": + msg = "The 'memory_map' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(file, encoding=encoding, memory_map=True) + return + + df = parser.read_csv(file, encoding=encoding, memory_map=True) + tm.assert_frame_equal(df, expected) + + +def test_chunk_splits_multibyte_char(all_parsers): + """ + Chunk splits a multibyte character with memory_map=True + + GH 43540 + """ + parser = all_parsers + # DEFAULT_CHUNKSIZE = 262144, defined in parsers.pyx + df = DataFrame(data=["a" * 127] * 2048) + + # Put two-bytes utf-8 encoded character "ą" at the end of chunk + # utf-8 encoding of "ą" is b'\xc4\x85' + df.iloc[2047] = "a" * 127 + "ą" + with tm.ensure_clean("bug-gh43540.csv") as fname: + df.to_csv(fname, index=False, header=False, encoding="utf-8") + + if parser.engine == "pyarrow": + msg = "The 'memory_map' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(fname, header=None, memory_map=True) + return + + dfr = parser.read_csv(fname, header=None, memory_map=True) + tm.assert_frame_equal(dfr, df) + + +def test_readcsv_memmap_utf8(all_parsers): + """ + GH 43787 + + Test correct handling of UTF-8 chars when memory_map=True and encoding is UTF-8 + """ + lines = [] + line_length = 128 + start_char = " " + end_char = "\U00010080" + # This for loop creates a list of 128-char strings + # consisting of consecutive Unicode chars + for lnum in range(ord(start_char), ord(end_char), line_length): + line = "".join([chr(c) for c in range(lnum, lnum + 0x80)]) + "\n" + try: + line.encode("utf-8") + except UnicodeEncodeError: + continue + lines.append(line) + parser = all_parsers + df = DataFrame(lines) + with tm.ensure_clean("utf8test.csv") as fname: + df.to_csv(fname, index=False, header=False, encoding="utf-8") + + if parser.engine == "pyarrow": + msg = "The 'memory_map' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(fname, header=None, memory_map=True, encoding="utf-8") + return + + dfr = parser.read_csv(fname, header=None, memory_map=True, encoding="utf-8") + tm.assert_frame_equal(df, dfr) + + +@pytest.mark.usefixtures("pyarrow_xfail") +@pytest.mark.parametrize("mode", ["w+b", "w+t"]) +def test_not_readable(all_parsers, mode): + # GH43439 + parser = all_parsers + content = b"abcd" + if "t" in mode: + content = "abcd" + with tempfile.SpooledTemporaryFile(mode=mode, encoding="utf-8") as handle: + handle.write(content) + handle.seek(0) + df = parser.read_csv(handle) + expected = DataFrame([], columns=["abcd"]) + tm.assert_frame_equal(df, expected) diff --git a/shared/package-files/3a/3a103203e4623317f5a062d93fe2dc84389ab79b78e4294d42b9cca7df2a83b0/nll_loss2d_forward_ops.h b/shared/package-files/3a/3a103203e4623317f5a062d93fe2dc84389ab79b78e4294d42b9cca7df2a83b0/nll_loss2d_forward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e74bf4e48082e615fd22150a75b91827664f8888 --- /dev/null +++ b/shared/package-files/3a/3a103203e4623317f5a062d93fe2dc84389ab79b78e4294d42b9cca7df2a83b0/nll_loss2d_forward_ops.h @@ -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 nll_loss2d_forward_output { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const c10::optional &, int64_t, c10::SymInt, 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::nll_loss2d_forward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "output") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nll_loss2d_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, at::Tensor & output, at::Tensor & total_weight); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, at::Tensor & output, at::Tensor & total_weight); +}; + +struct TORCH_API nll_loss2d_forward { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const c10::optional &, int64_t, c10::SymInt); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::nll_loss2d_forward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nll_loss2d_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight)") + static ::std::tuple call(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3a116bd1038efdb87831c45bece072fae2464cd568f1ddb9cca1d7fb85bf34a9/test_run.py b/shared/package-files/3a/3a116bd1038efdb87831c45bece072fae2464cd568f1ddb9cca1d7fb85bf34a9/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..ec4637c5ca617a9eb380d46825ee32c429520edc --- /dev/null +++ b/shared/package-files/3a/3a116bd1038efdb87831c45bece072fae2464cd568f1ddb9cca1d7fb85bf34a9/test_run.py @@ -0,0 +1,429 @@ +"Test run, coverage 54%." + +from idlelib import run +import io +import sys +from test.support import captured_output, captured_stderr +import unittest +from unittest import mock +import idlelib +from idlelib.idle_test.mock_idle import Func + +idlelib.testing = True # Use {} for executing test user code. + + +class ExceptionTest(unittest.TestCase): + + def test_print_exception_unhashable(self): + class UnhashableException(Exception): + def __eq__(self, other): + return True + + ex1 = UnhashableException('ex1') + ex2 = UnhashableException('ex2') + try: + raise ex2 from ex1 + except UnhashableException: + try: + raise ex1 + except UnhashableException: + with captured_stderr() as output: + with mock.patch.object(run, 'cleanup_traceback') as ct: + ct.side_effect = lambda t, e: t + run.print_exception() + + tb = output.getvalue().strip().splitlines() + self.assertEqual(11, len(tb)) + self.assertIn('UnhashableException: ex2', tb[3]) + self.assertIn('UnhashableException: ex1', tb[10]) + + data = (('1/0', ZeroDivisionError, "division by zero\n"), + ('abc', NameError, "name 'abc' is not defined. " + "Did you mean: 'abs'?\n"), + ('int.reel', AttributeError, + "type object 'int' has no attribute 'reel'. " + "Did you mean: 'real'?\n"), + ) + + def test_get_message(self): + for code, exc, msg in self.data: + with self.subTest(code=code): + try: + eval(compile(code, '', 'eval')) + except exc: + typ, val, tb = sys.exc_info() + actual = run.get_message_lines(typ, val, tb)[0] + expect = f'{exc.__name__}: {msg}' + self.assertEqual(actual, expect) + + @mock.patch.object(run, 'cleanup_traceback', + new_callable=lambda: (lambda t, e: None)) + def test_get_multiple_message(self, mock): + d = self.data + data2 = ((d[0], d[1]), (d[1], d[2]), (d[2], d[0])) + subtests = 0 + for (code1, exc1, msg1), (code2, exc2, msg2) in data2: + with self.subTest(codes=(code1,code2)): + try: + eval(compile(code1, '', 'eval')) + except exc1: + try: + eval(compile(code2, '', 'eval')) + except exc2: + with captured_stderr() as output: + run.print_exception() + actual = output.getvalue() + self.assertIn(msg1, actual) + self.assertIn(msg2, actual) + subtests += 1 + self.assertEqual(subtests, len(data2)) # All subtests ran? + +# StdioFile tests. + +class S(str): + def __str__(self): + return '%s:str' % type(self).__name__ + def __unicode__(self): + return '%s:unicode' % type(self).__name__ + def __len__(self): + return 3 + def __iter__(self): + return iter('abc') + def __getitem__(self, *args): + return '%s:item' % type(self).__name__ + def __getslice__(self, *args): + return '%s:slice' % type(self).__name__ + + +class MockShell: + def __init__(self): + self.reset() + def write(self, *args): + self.written.append(args) + def readline(self): + return self.lines.pop() + def close(self): + pass + def reset(self): + self.written = [] + def push(self, lines): + self.lines = list(lines)[::-1] + + +class StdInputFilesTest(unittest.TestCase): + + def test_misc(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + self.assertIsInstance(f, io.TextIOBase) + self.assertEqual(f.encoding, 'utf-8') + self.assertEqual(f.errors, 'strict') + self.assertIsNone(f.newlines) + self.assertEqual(f.name, '') + self.assertFalse(f.closed) + self.assertTrue(f.isatty()) + self.assertTrue(f.readable()) + self.assertFalse(f.writable()) + self.assertFalse(f.seekable()) + + def test_unsupported(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + self.assertRaises(OSError, f.fileno) + self.assertRaises(OSError, f.tell) + self.assertRaises(OSError, f.seek, 0) + self.assertRaises(OSError, f.write, 'x') + self.assertRaises(OSError, f.writelines, ['x']) + + def test_read(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(), 'one\ntwo\n') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(-1), 'one\ntwo\n') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(None), 'one\ntwo\n') + shell.push(['one\n', 'two\n', 'three\n', '']) + self.assertEqual(f.read(2), 'on') + self.assertEqual(f.read(3), 'e\nt') + self.assertEqual(f.read(10), 'wo\nthree\n') + + shell.push(['one\n', 'two\n']) + self.assertEqual(f.read(0), '') + self.assertRaises(TypeError, f.read, 1.5) + self.assertRaises(TypeError, f.read, '1') + self.assertRaises(TypeError, f.read, 1, 1) + + def test_readline(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', 'three\n', 'four\n']) + self.assertEqual(f.readline(), 'one\n') + self.assertEqual(f.readline(-1), 'two\n') + self.assertEqual(f.readline(None), 'three\n') + shell.push(['one\ntwo\n']) + self.assertEqual(f.readline(), 'one\n') + self.assertEqual(f.readline(), 'two\n') + shell.push(['one', 'two', 'three']) + self.assertEqual(f.readline(), 'one') + self.assertEqual(f.readline(), 'two') + shell.push(['one\n', 'two\n', 'three\n']) + self.assertEqual(f.readline(2), 'on') + self.assertEqual(f.readline(1), 'e') + self.assertEqual(f.readline(1), '\n') + self.assertEqual(f.readline(10), 'two\n') + + shell.push(['one\n', 'two\n']) + self.assertEqual(f.readline(0), '') + self.assertRaises(TypeError, f.readlines, 1.5) + self.assertRaises(TypeError, f.readlines, '1') + self.assertRaises(TypeError, f.readlines, 1, 1) + + def test_readlines(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(-1), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(None), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(0), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(3), ['one\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(4), ['one\n', 'two\n']) + + shell.push(['one\n', 'two\n', '']) + self.assertRaises(TypeError, f.readlines, 1.5) + self.assertRaises(TypeError, f.readlines, '1') + self.assertRaises(TypeError, f.readlines, 1, 1) + + def test_close(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertFalse(f.closed) + self.assertEqual(f.readline(), 'one\n') + f.close() + self.assertFalse(f.closed) + self.assertEqual(f.readline(), 'two\n') + self.assertRaises(TypeError, f.close, 1) + + +class StdOutputFilesTest(unittest.TestCase): + + def test_misc(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertIsInstance(f, io.TextIOBase) + self.assertEqual(f.encoding, 'utf-8') + self.assertEqual(f.errors, 'strict') + self.assertIsNone(f.newlines) + self.assertEqual(f.name, '') + self.assertFalse(f.closed) + self.assertTrue(f.isatty()) + self.assertFalse(f.readable()) + self.assertTrue(f.writable()) + self.assertFalse(f.seekable()) + + def test_unsupported(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertRaises(OSError, f.fileno) + self.assertRaises(OSError, f.tell) + self.assertRaises(OSError, f.seek, 0) + self.assertRaises(OSError, f.read, 0) + self.assertRaises(OSError, f.readline, 0) + + def test_write(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + f.write('test') + self.assertEqual(shell.written, [('test', 'stdout')]) + shell.reset() + f.write('t\xe8\u015b\U0001d599') + self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')]) + shell.reset() + + f.write(S('t\xe8\u015b\U0001d599')) + self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.write) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, b'test') + self.assertRaises(TypeError, f.write, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, 'test', 'spam') + self.assertEqual(shell.written, []) + + def test_write_stderr_nonencodable(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stderr', 'iso-8859-15', 'backslashreplace') + f.write('t\xe8\u015b\U0001d599\xa4') + self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')]) + shell.reset() + + f.write(S('t\xe8\u015b\U0001d599\xa4')) + self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.write) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, b'test') + self.assertRaises(TypeError, f.write, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, 'test', 'spam') + self.assertEqual(shell.written, []) + + def test_writelines(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + f.writelines([]) + self.assertEqual(shell.written, []) + shell.reset() + f.writelines(['one\n', 'two']) + self.assertEqual(shell.written, + [('one\n', 'stdout'), ('two', 'stdout')]) + shell.reset() + f.writelines(['on\xe8\n', 'tw\xf2']) + self.assertEqual(shell.written, + [('on\xe8\n', 'stdout'), ('tw\xf2', 'stdout')]) + shell.reset() + + f.writelines([S('t\xe8st')]) + self.assertEqual(shell.written, [('t\xe8st', 'stdout')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.writelines) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, [b'test']) + self.assertRaises(TypeError, f.writelines, [123]) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, [], []) + self.assertEqual(shell.written, []) + + def test_close(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertFalse(f.closed) + f.write('test') + f.close() + self.assertTrue(f.closed) + self.assertRaises(ValueError, f.write, 'x') + self.assertEqual(shell.written, [('test', 'stdout')]) + f.close() + self.assertRaises(TypeError, f.close, 1) + + +class RecursionLimitTest(unittest.TestCase): + # Test (un)install_recursionlimit_wrappers and fixdoc. + + def test_bad_setrecursionlimit_calls(self): + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + f = sys.setrecursionlimit + self.assertRaises(TypeError, f, limit=100) + self.assertRaises(TypeError, f, 100, 1000) + self.assertRaises(ValueError, f, 0) + + def test_roundtrip(self): + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + + # Check that setting the recursion limit works. + orig_reclimit = sys.getrecursionlimit() + self.addCleanup(sys.setrecursionlimit, orig_reclimit) + sys.setrecursionlimit(orig_reclimit + 3) + + # Check that the new limit is returned by sys.getrecursionlimit(). + new_reclimit = sys.getrecursionlimit() + self.assertEqual(new_reclimit, orig_reclimit + 3) + + def test_default_recursion_limit_preserved(self): + orig_reclimit = sys.getrecursionlimit() + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + new_reclimit = sys.getrecursionlimit() + self.assertEqual(new_reclimit, orig_reclimit) + + def test_fixdoc(self): + # Put here until better place for miscellaneous test. + def func(): "docstring" + run.fixdoc(func, "more") + self.assertEqual(func.__doc__, "docstring\n\nmore") + func.__doc__ = None + run.fixdoc(func, "more") + self.assertEqual(func.__doc__, "more") + + +class HandleErrorTest(unittest.TestCase): + # Method of MyRPCServer + def test_fatal_error(self): + eq = self.assertEqual + with captured_output('__stderr__') as err,\ + mock.patch('idlelib.run.thread.interrupt_main', + new_callable=Func) as func: + try: + raise EOFError + except EOFError: + run.MyRPCServer.handle_error(None, 'abc', '123') + eq(run.exit_now, True) + run.exit_now = False + eq(err.getvalue(), '') + + try: + raise IndexError + except IndexError: + run.MyRPCServer.handle_error(None, 'abc', '123') + eq(run.quitting, True) + run.quitting = False + msg = err.getvalue() + self.assertIn('abc', msg) + self.assertIn('123', msg) + self.assertIn('IndexError', msg) + eq(func.called, 2) + + +class ExecRuncodeTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.addClassCleanup(setattr,run,'print_exception',run.print_exception) + cls.prt = Func() # Need reference. + run.print_exception = cls.prt + mockrpc = mock.Mock() + mockrpc.console.getvar = Func(result=False) + cls.ex = run.Executive(mockrpc) + + @classmethod + def tearDownClass(cls): + assert sys.excepthook == sys.__excepthook__ + + def test_exceptions(self): + ex = self.ex + ex.runcode('1/0') + self.assertIs(ex.user_exc_info[0], ZeroDivisionError) + + self.addCleanup(setattr, sys, 'excepthook', sys.__excepthook__) + sys.excepthook = lambda t, e, tb: run.print_exception(t) + ex.runcode('1/0') + self.assertIs(self.prt.args[0], ZeroDivisionError) + + sys.excepthook = lambda: None + ex.runcode('1/0') + t, e, tb = ex.user_exc_info + self.assertIs(t, TypeError) + self.assertTrue(isinstance(e.__context__, ZeroDivisionError)) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/shared/package-files/3a/3a11b7bc4a52019ae41cda27dede42db668f5a9929f6341fd61d4b91861e607d/gmpy2.h b/shared/package-files/3a/3a11b7bc4a52019ae41cda27dede42db668f5a9929f6341fd61d4b91861e607d/gmpy2.h new file mode 100644 index 0000000000000000000000000000000000000000..aa2003c28d42f04fa4ae55f1bd4e66ea9f06bc43 --- /dev/null +++ b/shared/package-files/3a/3a11b7bc4a52019ae41cda27dede42db668f5a9929f6341fd61d4b91861e607d/gmpy2.h @@ -0,0 +1,591 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * gmpy2.h * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Python interface to the GMP or MPIR, MPFR, and MPC multiple precision * + * libraries. * + * * + * Copyright 2000 - 2009 Alex Martelli * + * * + * Copyright 2008 - 2022 Case Van Horsen * + * * + * This file is part of GMPY2. * + * * + * GMPY2 is free software: you can redistribute it and/or modify it under * + * the terms of the GNU Lesser General Public License as published by the * + * Free Software Foundation, either version 3 of the License, or (at your * + * option) any later version. * + * * + * GMPY2 is distributed in the hope that it will be useful, but WITHOUT * + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * + * License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with GMPY2; if not, see * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + + +/* + gmpy C API extension header file. + Part of Python's gmpy module since version 0.4 + + Created by Pearu Peterson , November 2000. + Edited by A. Martelli , December 2000. + Edited by Case Van Horsen , 2009, 2010, 2011. + + Version 1.02, February 2007. + Version 1.03, June 2008 + Version 1.04, June 2008 (no changes) + Version 1.05, February 2009 (support MPIR) + Version 1.20, January 2010 (remove obsolete MS hacks) casevh + Version 2.00, April 2010 (change to gmpy2) casevh + October 2010 (added Py_hash_t) casevh + December 2010 (added mpfr, mpc) casevh + January 2011 (add Pygmpy_context) casevh + April 2011 (split into multiple files) casevh + Version 2.10 August 2014 (reflect major rewrite during 2013/2014) casevh + */ + +#ifndef Py_GMPYMODULE_H +#define Py_GMPYMODULE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Structure of gmpy2.h + * + * Revised 17-APR-2017 casevh + * + * 1. Checks for specific Python versions. + * 2. Include headers for GMP/MPIR, MPFR, and MPC. + * 3. Define public C-API. + * 1. Define gmpy2 types. + * 2. Define the public API. + * + */ + +/* Check for minimum Python version requirements. */ + +#if PY_VERSION_HEX < 0x02060000 +# error "GMPY2 requires Python 2.6 or later." +#endif + +/* Include headers for GMP/MPIR, MPFR, and MPC. */ + +#ifdef MPIR +# include +#else +# include +#endif + +#include +#include + +/* Check MPFR and MPC versions. */ + +#if (!defined(MPC_VERSION) || (MPC_VERSION < MPC_VERSION_NUM(1,0,3))) +# error "GMPY2 requires MPC 1.0.3 or later." +#endif + +#if (defined(MPC_VERSION) && (MPC_VERSION >= MPC_VERSION_NUM(1,1,0))) +# define MPC_110 +#endif + + +#if PY_VERSION_HEX < 0x030200A4 +typedef long Py_hash_t; +typedef unsigned long Py_uhash_t; +# define _PyHASH_IMAG 1000003 +#endif + +/* GMPY2 Public API */ + +/* Types + * MPZ_Object + * XMPZ_Object (mutable version of MPZ_Object) + * MPQ_Object + * XMPQ_Object (mutable version of MPQ_Object) + * MPFR_Object + * XMPFR_Object (mutable version of MPFR_Object) + * MPC_Object + * XMPC_Object (mutable version of MPC_Object) + * CTXT_Object + * CTXT_Manager_Object + * RandomState_Object + */ + +typedef struct { + PyObject_HEAD + mpz_t z; + Py_hash_t hash_cache; +} MPZ_Object; + +typedef struct { + PyObject_HEAD + mpz_t z; +} XMPZ_Object; + +typedef struct { + PyObject_HEAD + mpq_t q; + Py_hash_t hash_cache; +} MPQ_Object; + +typedef struct { + PyObject_HEAD + mpfr_t f; + Py_hash_t hash_cache; + int rc; +} MPFR_Object; + +typedef struct { + PyObject_HEAD + mpc_t c; + Py_hash_t hash_cache; + int rc; +} MPC_Object; + +typedef struct { + PyObject_HEAD + gmp_randstate_t state; +} RandomState_Object; + +typedef struct { + mpfr_prec_t mpfr_prec; /* current precision in bits, for MPFR */ + mpfr_rnd_t mpfr_round; /* current rounding mode for float (MPFR) */ + mpfr_exp_t emax; /* maximum exponent */ + mpfr_exp_t emin; /* minimum exponent */ + int subnormalize; /* if 1, subnormalization is performed */ + int underflow; /* did an underflow occur? */ + int overflow; /* did an overflow occur? */ + int inexact; /* was the result inexact? */ + int invalid; /* invalid operation (i.e. NaN)? */ + int erange; /* did a range error occur? */ + int divzero; /* divided by zero? */ + int traps; /* if 0, do not trap any exceptions */ + /* if not 0, then raise traps per bits above */ + mpfr_prec_t real_prec; /* current precision in bits, for Re(MPC) */ + mpfr_prec_t imag_prec; /* current precision in bits, for Im(MPC) */ + mpfr_rnd_t real_round; /* current rounding mode for Re(MPC) */ + mpfr_rnd_t imag_round; /* current rounding mode for Im(MPC) */ + int allow_complex; /* if 1, allow mpfr functions to return an mpc */ + int rational_division; /* if 1, mpz/mpz returns an mpq result */ + int allow_release_gil; /* if 1, allow mpz functions to release the GIL */ +} gmpy_context; + +typedef struct { + PyObject_HEAD + gmpy_context ctx; +#ifndef WITHOUT_THREADS + PyThreadState *tstate; +#endif +} CTXT_Object; + +typedef struct { + PyObject_HEAD + CTXT_Object *new_context; /* Context that will be returned when + * __enter__ is called. */ + CTXT_Object *old_context; /* Context that will restored when + * __exit__ is called. */ +} CTXT_Manager_Object; + +#define MPZ(obj) (((MPZ_Object*)(obj))->z) +#define MPQ(obj) (((MPQ_Object*)(obj))->q) +#define MPFR(obj) (((MPFR_Object*)(obj))->f) +#define MPC(obj) (((MPC_Object*)(obj))->c) + +/* Start of the C-API definitions */ + +#define MPZ_Type_NUM 0 +#define XMPZ_Type_NUM 1 +#define MPQ_Type_NUM 2 +#define XMPQ_Type_NUM 3 +#define MPFR_Type_NUM 4 +#define XMPFR_Type_NUM 5 +#define MPC_Type_NUM 6 +#define XMPC_Type_NUM 7 +#define CTXT_Type_NUM 8 +#define CTXT_Manager_Type_NUM 9 +#define RandomState_Type_NUM 10 + +/* The following functions are found in gmpy2_cache. */ + +#define GMPy_MPZ_New_NUM 11 +#define GMPy_MPZ_New_RETURN MPZ_Object * +#define GMPy_MPZ_New_PROTO (CTXT_Object *context) + +#define GMPy_MPZ_NewInit_NUM 12 +#define GMPy_MPZ_NewInit_RETURN PyObject * +#define GMPy_MPZ_NewInit_PROTO (PyTypeObject *type, PyObject *args, PyObject *keywds) + +#define GMPy_MPZ_Dealloc_NUM 13 +#define GMPy_MPZ_Dealloc_RETURN void +#define GMPy_MPZ_Dealloc_PROTO (MPZ_Object *self) + +/* The following function is found in gmpy2_convert_gmp. */ + +#define GMPy_MPZ_ConvertArg_NUM 14 +#define GMPy_MPZ_ConvertArg_RETURN int +#define GMPy_MPZ_ConvertArg_PROTO (PyObject *arg, PyObject **ptr) + +/* The following functions are found in gmpy2_cache. */ + +#define GMPy_XMPZ_New_NUM 15 +#define GMPy_XMPZ_New_RETURN XMPZ_Object * +#define GMPy_XMPZ_New_PROTO (CTXT_Object *context) + +#define GMPy_XMPZ_NewInit_NUM 16 +#define GMPy_XMPZ_NewInit_RETURN PyObject * +#define GMPy_XMPZ_NewInit_PROTO (PyTypeObject *type, PyObject *args, PyObject *keywds) + +#define GMPy_XMPZ_Dealloc_NUM 17 +#define GMPy_XMPZ_Dealloc_RETURN void +#define GMPy_XMPZ_Dealloc_PROTO (XMPZ_Object *self) + +/* The following functions are found in gmpy2_cache. */ + +#define GMPy_MPQ_New_NUM 18 +#define GMPy_MPQ_New_RETURN MPQ_Object * +#define GMPy_MPQ_New_PROTO (CTXT_Object *context) + +#define GMPy_MPQ_NewInit_NUM 19 +#define GMPy_MPQ_NewInit_RETURN PyObject * +#define GMPy_MPQ_NewInit_PROTO (PyTypeObject *type, PyObject *args, PyObject *keywds) + +#define GMPy_MPQ_Dealloc_NUM 20 +#define GMPy_MPQ_Dealloc_RETURN void +#define GMPy_MPQ_Dealloc_PROTO (MPQ_Object *self) + +/* The following function is found in gmpy2_convert_gmp. */ + +#define GMPy_MPQ_ConvertArg_NUM 21 +#define GMPy_MPQ_ConvertArg_RETURN int +#define GMPy_MPQ_ConvertArg_PROTO (PyObject *arg, PyObject **ptr) + +/* The following functions are found in gmpy2_cache. */ + +#define GMPy_MPFR_New_NUM 22 +#define GMPy_MPFR_New_RETURN MPFR_Object * +#define GMPy_MPFR_New_PROTO (mpfr_prec_t bits, CTXT_Object *context) + +#define GMPy_MPFR_NewInit_NUM 23 +#define GMPy_MPFR_NewInit_RETURN PyObject * +#define GMPy_MPFR_NewInit_PROTO (PyTypeObject *type, PyObject *args, PyObject *keywds) + +#define GMPy_MPFR_Dealloc_NUM 24 +#define GMPy_MPFR_Dealloc_RETURN void +#define GMPy_MPFR_Dealloc_PROTO (MPFR_Object *self) + +/* The following function is found in gmpy2_convert_gmp. */ + +#define GMPy_MPFR_ConvertArg_NUM 25 +#define GMPy_MPFR_ConvertArg_RETURN int +#define GMPy_MPFR_ConvertArg_PROTO (PyObject *arg, PyObject **ptr) + +/* The following functions are found in gmpy2_cache. */ + +#define GMPy_MPC_New_NUM 26 +#define GMPy_MPC_New_RETURN MPC_Object * +#define GMPy_MPC_New_PROTO (mpfr_prec_t rprec, mpfr_prec_t iprec, CTXT_Object *context) + +#define GMPy_MPC_NewInit_NUM 27 +#define GMPy_MPC_NewInit_RETURN PyObject * +#define GMPy_MPC_NewInit_PROTO (PyTypeObject *type, PyObject *args, PyObject *keywds) + +#define GMPy_MPC_Dealloc_NUM 28 +#define GMPy_MPC_Dealloc_RETURN void +#define GMPy_MPC_Dealloc_PROTO (MPC_Object *self) + +/* The following function is found in gmpy2_convert_gmp. */ + +#define GMPy_MPC_ConvertArg_NUM 29 +#define GMPy_MPC_ConvertArg_RETURN int +#define GMPy_MPC_ConvertArg_PROTO (PyObject *arg, PyObject **ptr) + +/* Total number of C-API pointers. */ + +#define GMPy_API_pointers 30 + +/* End of C-API definitions. */ + +#ifdef GMPY2_MODULE + +/* Define various macros to deal with differences between Python 2 and 3. */ + +#if (PY_MAJOR_VERSION == 3) +#define PY3 +#define Py2or3String_FromString PyUnicode_FromString +#define Py2or3String_FromFormat PyUnicode_FromFormat +#define Py2or3String_Check PyUnicode_Check +#define Py2or3String_Format PyUnicode_Format +#define Py2or3String_Type Py_UCS4 +#define Py2or3String_1Char(obj) (PyUnicode_READY(obj) ? (Py_UCS4)0 : PyUnicode_READ_CHAR(obj, 0)) +#define PyStrOrUnicode_Check(op) (PyBytes_Check(op) || PyUnicode_Check(op)) +#define PyIntOrLong_FromLong PyLong_FromLong +#define PyIntOrLong_Check(op) (PyLong_Check(op)) +#define PyIntOrLong_CheckExact(op) PyLong_CheckExact(op) +#define PyIntOrLong_FromSize_t PyLong_FromSize_t +#define PyIntOrLong_FromSsize_t PyLong_FromSsize_t +#define PyIntOrLong_AsSsize_t PyLong_AsSsize_t +#define PyIntOrLong_AsLong PyLong_AsLong +#else +#define PY2 +#define Py2or3String_FromString PyString_FromString +#define Py2or3String_FromFormat PyString_FromFormat +#define Py2or3String_Check PyString_Check +#define Py2or3String_Format PyString_Format +#define Py2or3String_Type char +#define Py2or3String_1Char(obj) PyString_AsString(obj)[0] +#define PyStrOrUnicode_Check(op) (PyString_Check(op) || PyUnicode_Check(op)) +#define PyIntOrLong_FromLong PyInt_FromLong +#define PyIntOrLong_Check(op) (PyInt_Check(op) || PyLong_Check(op)) +#define PyIntOrLong_CheckExact(op) (PyInt_CheckExact(op) || PyLong_CheckExact(op)) +#define PyIntOrLong_FromSize_t PyInt_FromSize_t +#define PyIntOrLong_FromSsize_t PyInt_FromSsize_t +#define PyIntOrLong_AsSsize_t PyInt_AsSsize_t +#define PyIntOrLong_AsLong PyInt_AsLong +#endif + +#ifndef ABS +# define ABS(a) (((a) < 0) ? -(a) : (a)) +#endif + +#if defined(MS_WIN32) && defined(_MSC_VER) + /* so one won't need to link explicitly to gmp.lib...: */ +# if defined(MPIR) +# pragma comment(lib,"mpir.lib") +# else +# pragma comment(lib,"gmp.lib") +# endif +# define USE_ALLOCA 1 +# define inline __inline +#endif + +#ifdef __GNUC__ +# define USE_ALLOCA 1 +#endif + +#ifndef alloca +# ifdef __GNUC__ +# define alloca __builtin_alloca +# else +# ifdef _MSC_VER +# include +# define alloca _alloca +# else +# if HAVE_ALLOCA_H +# include +# else + char *alloca (); +# endif +# endif +# endif +#endif + +#define ALLOC_THRESHOLD 8192 + +#define INDEX_ERROR(msg) PyErr_SetString(PyExc_IndexError, msg) +#define TYPE_ERROR(msg) PyErr_SetString(PyExc_TypeError, msg) +#define VALUE_ERROR(msg) PyErr_SetString(PyExc_ValueError, msg) +#define ZERO_ERROR(msg) PyErr_SetString(PyExc_ZeroDivisionError, msg) +#define SYSTEM_ERROR(msg) PyErr_SetString(PyExc_SystemError, msg) +#define OVERFLOW_ERROR(msg) PyErr_SetString(PyExc_OverflowError, msg) +#define RUNTIME_ERROR(msg) PyErr_SetString(PyExc_RuntimeError, msg) + +#define GMPY_DEFAULT -1 + +/* To prevent excessive memory usage, we don't want to save very large + * numbers in the cache. The default value specified in the options + * structure is 128 words (512 bytes on 32-bit platforms, 1024 bytes on + * 64-bit platforms). + */ +#define MAX_CACHE_LIMBS 16384 + +/* The maximum number of objects that can be saved in a cache is specified + * here. The default value is 100.*/ +#define MAX_CACHE 1000 + +#ifdef USE_ALLOCA +# define TEMP_ALLOC(B, S) \ + if(S < ALLOC_THRESHOLD) { \ + B = alloca(S); \ + } else { \ + if(!(B = malloc(S))) { \ + PyErr_NoMemory(); \ + return NULL; \ + } \ + } +# define TEMP_FREE(B, S) if(S >= ALLOC_THRESHOLD) free(B) +#else +# define TEMP_ALLOC(B, S) \ + if(!(B = malloc(S))) { \ + PyErr_NoMemory(); \ + return NULL; \ + } +# define TEMP_FREE(B, S) free(B) +#endif + +/* Various defs to mask differences between Python versions. */ +#if PY_VERSION_HEX < 0x03050000 +#define Py_RETURN_NOTIMPLEMENTED \ + return Py_INCREF(Py_NotImplemented), Py_NotImplemented +#endif + +#ifndef Py_SIZE +# define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) +#endif + +#ifndef Py_TYPE +# define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) +#endif + +/* Import a collection of general purpose macros. */ + +#include "gmpy2_macros.h" + +/* Import the files that complete the definition of the types defined above. */ + +#include "gmpy2_mpz.h" +#include "gmpy2_xmpz.h" +#include "gmpy2_mpq.h" +#include "gmpy2_mpfr.h" +#include "gmpy2_mpc.h" +#include "gmpy2_context.h" +#include "gmpy2_random.h" + +/* Import the header files that provide the various functions. */ + +/* Support object caching, creation, and deletion. */ + +#include "gmpy2_cache.h" + +/* Suport for miscellaneous functions (ie. version, license, etc.). */ + +#include "gmpy2_misc.h" + +/* Support conversion to/from binary format. */ + +#include "gmpy2_binary.h" + +/* Support for mpz/xmpz specific functions. */ + +#include "gmpy2_convert.h" +#include "gmpy2_convert_utils.h" +#include "gmpy2_convert_gmp.h" +#include "gmpy2_convert_mpfr.h" +#include "gmpy2_convert_mpc.h" + +#include "gmpy2_mpz_divmod.h" +#include "gmpy2_mpz_divmod2exp.h" +#include "gmpy2_mpz_pack.h" +#include "gmpy2_mpz_bitops.h" +#include "gmpy2_mpz_misc.h" + +#include "gmpy2_xmpz_inplace.h" +#include "gmpy2_xmpz_misc.h" +#include "gmpy2_xmpz_limbs.h" + +/* Support for mpq specific functions. */ + +#include "gmpy2_mpq_misc.h" + +/* Support for mpfr specific functions. */ + +#include "gmpy2_mpfr_misc.h" + +/* Support for mpc specific functions. */ + +#include "gmpy2_mpc_misc.h" + +/* Support Lucas sequences. */ + +#include "gmpy_mpz_lucas.h" + +/* Support probable-prime tests. */ + +#include "gmpy_mpz_prp.h" + +/* Support higher-level Python methods and functions; generally not + * specific to a single type. + */ + +#include "gmpy2_abs.h" +#include "gmpy2_add.h" +#include "gmpy2_divmod.h" +#include "gmpy2_floordiv.h" +#include "gmpy2_minus.h" +#include "gmpy2_mod.h" +#include "gmpy2_mul.h" +#include "gmpy2_plus.h" +#include "gmpy2_pow.h" +#include "gmpy2_sub.h" +#include "gmpy2_truediv.h" +#include "gmpy2_math.h" +#include "gmpy2_const.h" +#include "gmpy2_square.h" +#include "gmpy2_format.h" +#include "gmpy2_hash.h" +#include "gmpy2_fused.h" +#include "gmpy2_muldiv_2exp.h" +#include "gmpy2_predicate.h" +#include "gmpy2_sign.h" +#include "gmpy2_richcompare.h" +#include "gmpy2_cmp.h" + +#ifdef VECTOR +# include "gmpy2_vector.h" +#endif /* defined(VECTOR) */ + +#else /* defined(GMPY2_MODULE) */ + +/* This section is used for other C-coded modules that use gmpy2's API. */ + +static void **GMPy_C_API; + +#define MPZ_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[MPZ_Type_NUM]) +#define XMPZ_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[XMPZ_Type_NUM]) +#define MPQ_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[MPQ_Type_NUM]) +#define XMPQ_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[XMPQ_Type_NUM]) +#define MPFR_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[MPFR_Type_NUM]) +#define XMPFR_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[XMPFR_Type_NUM]) +#define MPC_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[MPC_Type_NUM]) +#define XMPC_Check(op) ((op)->ob_type == (PyTypeObject*)GMPy_C_API[XMPC_Type_NUM]) + +#define GMPy_MPZ_New (*(GMPy_MPZ_New_RETURN (*)GMPy_MPZ_New_PROTO) GMPy_C_API[GMPy_MPZ_New_NUM]) +#define GMPy_MPZ_NewInit (*(GMPy_MPZ_NewInit_RETURN (*)GMPy_MPZ_NewInit_PROTO) GMPy_C_API[GMPy_MPZ_NewInit_NUM]) +#define GMPy_MPZ_Dealloc (*(GMPy_MPZ_Dealloc_RETURN (*)GMPy_MPZ_Dealloc_PROTO) GMPy_C_API[GMPy_MPZ_Dealloc_NUM]) +#define GMPy_MPZ_ConvertArg (*(GMPy_MPZ_ConvertArg_RETURN (*)GMPy_MPZ_ConvertArg_PROTO) GMPy_C_API[GMPy_MPZ_ConvertArg_NUM]) + +#define GMPy_XMPZ_New (*(GMPy_XMPZ_New_RETURN (*)GMPy_XMPZ_New_PROTO) GMPy_C_API[GMPy_XMPZ_New_NUM]) +#define GMPy_XMPZ_NewInit (*(GMPy_XMPZ_NewInit_RETURN (*)GMPy_XMPZ_NewInit_PROTO) GMPy_C_API[GMPy_XMPZ_NewInit_NUM]) +#define GMPy_XMPZ_Dealloc (*(GMPy_XMPZ_Dealloc_RETURN (*)GMPy_XMPZ_Dealloc_PROTO) GMPy_C_API[GMPy_XMPZ_Dealloc_NUM]) + +#define GMPy_MPQ_New (*(GMPy_MPQ_New_RETURN (*)GMPy_MPQ_New_PROTO) GMPy_C_API[GMPy_MPQ_New_NUM]) +#define GMPy_MPQ_NewInit (*(GMPy_MPQ_NewInit_RETURN (*)GMPy_MPQ_NewInit_PROTO) GMPy_C_API[GMPy_MPQ_NewInit_NUM]) +#define GMPy_MPQ_Dealloc (*(GMPy_MPQ_Dealloc_RETURN (*)GMPy_MPQ_Dealloc_PROTO) GMPy_C_API[GMPy_MPQ_Dealloc_NUM]) +#define GMPy_MPQ_ConvertArg (*(GMPy_MPQ_ConvertArg_RETURN (*)GMPy_MPQ_ConvertArg_PROTO) GMPy_C_API[GMPy_MPQ_ConvertArg_NUM]) + +#define GMPy_MPFR_New (*(GMPy_MPFR_New_RETURN (*)GMPy_MPFR_New_PROTO) GMPy_C_API[GMPy_MPFR_New_NUM]) +#define GMPy_MPFR_NewInit (*(GMPy_MPFR_NewInit_RETURN (*)GMPy_MPFR_NewInit_PROTO) GMPy_C_API[GMPy_MPFR_NewInit_NUM]) +#define GMPy_MPFR_Dealloc (*(GMPy_MPFR_Dealloc_RETURN (*)GMPy_MPFR_Dealloc_PROTO) GMPy_C_API[GMPy_MPFR_Dealloc_NUM]) +#define GMPy_MPFR_ConvertArg (*(GMPy_MPFR_ConvertArg_RETURN (*)GMPy_MPFR_ConvertArg_PROTO) GMPy_C_API[GMPy_MPFR_ConvertArg_NUM]) + +#define GMPy_MPC_New (*(GMPy_MPC_New_RETURN (*)GMPy_MPC_New_PROTO) GMPy_C_API[GMPy_MPC_New_NUM]) +#define GMPy_MPC_NewInit (*(GMPy_MPC_NewInit_RETURN (*)GMPy_MPC_NewInit_PROTO) GMPy_C_API[GMPy_MPC_NewInit_NUM]) +#define GMPy_MPC_Dealloc (*(GMPy_MPC_Dealloc_RETURN (*)GMPy_MPC_Dealloc_PROTO) GMPy_C_API[GMPy_MPC_Dealloc_NUM]) +#define GMPy_MPC_ConvertArg (*(GMPy_MPC_ConvertArg_RETURN (*)GMPy_MPC_ConvertArg_PROTO) GMPy_C_API[GMPy_MPC_ConvertArg_NUM]) + +static int +import_gmpy2(void) +{ + GMPy_C_API = (void **)PyCapsule_Import("gmpy2._C_API", 0); + return (GMPy_C_API != NULL) ? 0 : -1; +} + +#endif /* defined(GMPY2_MODULE) */ + +#ifdef __cplusplus +} +#endif /* defined(__cplusplus */ +#endif /* !defined(Py_GMPYMODULE_H */ diff --git a/shared/package-files/3a/3a11d8cad6f4afc1e8ab20cb4c51d6e7a108c247e62e53f749e900678f02af81/eye_native.h b/shared/package-files/3a/3a11d8cad6f4afc1e8ab20cb4c51d6e7a108c247e62e53f749e900678f02af81/eye_native.h new file mode 100644 index 0000000000000000000000000000000000000000..1524e9b37caeadfe3d165e83ff6e4d4d6432c549 --- /dev/null +++ b/shared/package-files/3a/3a11d8cad6f4afc1e8ab20cb4c51d6e7a108c247e62e53f749e900678f02af81/eye_native.h @@ -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 eye(int64_t n, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & eye_out_cpu(int64_t n, at::Tensor & out); +TORCH_API at::Tensor & eye_out_cuda(int64_t n, at::Tensor & out); +TORCH_API at::Tensor eye(int64_t n, int64_t m, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & eye_out_cpu(int64_t n, int64_t m, at::Tensor & out); +TORCH_API at::Tensor & eye_out_cuda(int64_t n, int64_t m, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a11de8f4bc27c28c92649d3ef222de0ec5977a38c2425e71684f7a73a94b53a/test_grid_helper_curvelinear.py b/shared/package-files/3a/3a11de8f4bc27c28c92649d3ef222de0ec5977a38c2425e71684f7a73a94b53a/test_grid_helper_curvelinear.py new file mode 100644 index 0000000000000000000000000000000000000000..1b266044bdd06d995a1df86779dac97dae8cb13e --- /dev/null +++ b/shared/package-files/3a/3a11de8f4bc27c28c92649d3ef222de0ec5977a38c2425e71684f7a73a94b53a/test_grid_helper_curvelinear.py @@ -0,0 +1,207 @@ +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib.path import Path +from matplotlib.projections import PolarAxes +from matplotlib.ticker import FuncFormatter +from matplotlib.transforms import Affine2D, Transform +from matplotlib.testing.decorators import image_comparison + +from mpl_toolkits.axisartist import SubplotHost +from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory +from mpl_toolkits.axisartist import angle_helper +from mpl_toolkits.axisartist.axislines import Axes +from mpl_toolkits.axisartist.grid_helper_curvelinear import \ + GridHelperCurveLinear + + +@image_comparison(['custom_transform.png'], style='default', tol=0.2) +def test_custom_transform(): + class MyTransform(Transform): + input_dims = output_dims = 2 + + def __init__(self, resolution): + """ + Resolution is the number of steps to interpolate between each input + line segment to approximate its path in transformed space. + """ + Transform.__init__(self) + self._resolution = resolution + + def transform(self, ll): + x, y = ll.T + return np.column_stack([x, y - x]) + + transform_non_affine = transform + + def transform_path(self, path): + ipath = path.interpolated(self._resolution) + return Path(self.transform(ipath.vertices), ipath.codes) + + transform_path_non_affine = transform_path + + def inverted(self): + return MyTransformInv(self._resolution) + + class MyTransformInv(Transform): + input_dims = output_dims = 2 + + def __init__(self, resolution): + Transform.__init__(self) + self._resolution = resolution + + def transform(self, ll): + x, y = ll.T + return np.column_stack([x, y + x]) + + def inverted(self): + return MyTransform(self._resolution) + + fig = plt.figure() + + SubplotHost = host_axes_class_factory(Axes) + + tr = MyTransform(1) + grid_helper = GridHelperCurveLinear(tr) + ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) + fig.add_subplot(ax1) + + ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal") + ax2.plot([3, 6], [5.0, 10.]) + + ax1.set_aspect(1.) + ax1.set_xlim(0, 10) + ax1.set_ylim(0, 10) + + ax1.grid(True) + + +@image_comparison(['polar_box.png'], style='default', tol=0.04) +def test_polar_box(): + fig = plt.figure(figsize=(5, 5)) + + # PolarAxes.PolarTransform takes radian. However, we want our coordinate + # system in degree + tr = (Affine2D().scale(np.pi / 180., 1.) + + PolarAxes.PolarTransform(apply_theta_transforms=False)) + + # polar projection, which involves cycle, and also has limits in + # its coordinates, needs a special method to find the extremes + # (min, max of the coordinate within the view). + extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, + lon_cycle=360, + lat_cycle=None, + lon_minmax=None, + lat_minmax=(0, np.inf)) + + grid_helper = GridHelperCurveLinear( + tr, + extreme_finder=extreme_finder, + grid_locator1=angle_helper.LocatorDMS(12), + tick_formatter1=angle_helper.FormatterDMS(), + tick_formatter2=FuncFormatter(lambda x, p: "eight" if x == 8 else f"{int(x)}"), + ) + + ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) + + ax1.axis["right"].major_ticklabels.set_visible(True) + ax1.axis["top"].major_ticklabels.set_visible(True) + + # let right axis shows ticklabels for 1st coordinate (angle) + ax1.axis["right"].get_helper().nth_coord_ticks = 0 + # let bottom axis shows ticklabels for 2nd coordinate (radius) + ax1.axis["bottom"].get_helper().nth_coord_ticks = 1 + + fig.add_subplot(ax1) + + ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1) + axis.label.set_text("Test") + axis.label.set_visible(True) + axis.get_helper().set_extremes(2, 12) + + ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1) + axis.label.set_text("Test 2") + axis.get_helper().set_extremes(-180, 90) + + # A parasite axes with given transform + ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal") + assert ax2.transData == tr + ax1.transData + # Anything you draw in ax2 will match the ticks and grids of ax1. + ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50)) + + ax1.set_aspect(1.) + ax1.set_xlim(-5, 12) + ax1.set_ylim(-5, 10) + + ax1.grid(True) + + +# Remove tol & kerning_factor when this test image is regenerated. +@image_comparison(['axis_direction.png'], style='default', tol=0.13) +def test_axis_direction(): + plt.rcParams['text.kerning_factor'] = 6 + + fig = plt.figure(figsize=(5, 5)) + + # PolarAxes.PolarTransform takes radian. However, we want our coordinate + # system in degree + tr = (Affine2D().scale(np.pi / 180., 1.) + + PolarAxes.PolarTransform(apply_theta_transforms=False)) + + # polar projection, which involves cycle, and also has limits in + # its coordinates, needs a special method to find the extremes + # (min, max of the coordinate within the view). + + # 20, 20 : number of sampling points along x, y direction + extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, + lon_cycle=360, + lat_cycle=None, + lon_minmax=None, + lat_minmax=(0, np.inf), + ) + + grid_locator1 = angle_helper.LocatorDMS(12) + tick_formatter1 = angle_helper.FormatterDMS() + + grid_helper = GridHelperCurveLinear(tr, + extreme_finder=extreme_finder, + grid_locator1=grid_locator1, + tick_formatter1=tick_formatter1) + + ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) + + for axis in ax1.axis.values(): + axis.set_visible(False) + + fig.add_subplot(ax1) + + ax1.axis["lat1"] = axis = grid_helper.new_floating_axis( + 0, 130, + axes=ax1, axis_direction="left") + axis.label.set_text("Test") + axis.label.set_visible(True) + axis.get_helper().set_extremes(0.001, 10) + + ax1.axis["lat2"] = axis = grid_helper.new_floating_axis( + 0, 50, + axes=ax1, axis_direction="right") + axis.label.set_text("Test") + axis.label.set_visible(True) + axis.get_helper().set_extremes(0.001, 10) + + ax1.axis["lon"] = axis = grid_helper.new_floating_axis( + 1, 10, + axes=ax1, axis_direction="bottom") + axis.label.set_text("Test 2") + axis.get_helper().set_extremes(50, 130) + axis.major_ticklabels.set_axis_direction("top") + axis.label.set_axis_direction("top") + + grid_helper.grid_finder.grid_locator1.set_params(nbins=5) + grid_helper.grid_finder.grid_locator2.set_params(nbins=5) + + ax1.set_aspect(1.) + ax1.set_xlim(-8, 8) + ax1.set_ylim(-4, 12) + + ax1.grid(True) diff --git a/shared/package-files/3a/3a11fa2e058787bd7b208dc3b1df5a5b68912f925cdd97ebb98ff58abe8770af/results_exact_initial_var1_R.csv b/shared/package-files/3a/3a11fa2e058787bd7b208dc3b1df5a5b68912f925cdd97ebb98ff58abe8770af/results_exact_initial_var1_R.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bbe1ddba380e95cb049643bb6a21d0b01b0c3c6 --- /dev/null +++ b/shared/package-files/3a/3a11fa2e058787bd7b208dc3b1df5a5b68912f925cdd97ebb98ff58abe8770af/results_exact_initial_var1_R.csv @@ -0,0 +1,22 @@ +"r_1","r_2","r0_1","r0_2","r1_1","r1_2","N_1","N_2","N_3","N_4","N0_1","N0_2","N0_3","N0_4","N1_1","N1_2","N1_3","N1_4","N2_1","N2_2","N2_3","N2_4","m_1","m_2","v_1","v_2","F_1","F_2","Finf_1","Finf_2","K_1","K_2","K_3","K_4","Kinf_1","Kinf_2","Kinf_3","Kinf_4","a_1","a_2","P_1","P_2","P_3","P_4","Pinf_1","Pinf_2","Pinf_3","Pinf_4","att_1","att_2","Ptt_1","Ptt_2","Ptt_3","Ptt_4","alphahat_1","alphahat_2","V_1","V_2","V_3","V_4","muhat_1","muhat_2","Vmu_1","Vmu_2","Vmu_3","Vmu_4","etahat_1","etahat_2","Veta_1","Veta_2","Veta_3","Veta_4","epshat_1","epshat_2","Veps_1","Veps_2","llf" +0,0,0,0,9.97685232655492,6.11444296625407,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,9.97685232655492,6.11444296625407,0,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,1,9.97685232655492,6.11444296625407,0,0,0,0,9.97685232655492,6.11444296625407,0,0,0,0,9.97685232655492,6.11444296625407,0,0,0,0,-7.29993989742095,-0.286756556953947,0,0,0,0,0,0,0,0,-167.431497598545 +-3.64996994871047,-0.0955855189846488,-3.64996994871047,-0.0955855189846488,0,0,0.5,0,0,0.333333333333333,0.5,0,0,0.333333333333333,0,0,0,0,0,0,0,0,6.82275905315368,4.44114765181261,-7.29993989742095,-0.286756556953947,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,6.82275905315368,4.44114765181261,2,0,0,3,NA,NA,NA,NA,-0.477180844267266,4.15439109485867,0,0,0,0,-0.477180844267266,4.15439109485867,0,0,0,0,-0.477180844267266,4.15439109485867,0,0,0,0,0.390086155424854,-1.13271589058655,0,0,0,0,0,0,0,0,NA +0.195043077712427,-0.377571963528851,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,1.00772690632397,1.56632026909001,0.390086155424854,-1.13271589058655,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,1.00772690632397,1.56632026909001,2,0,0,3,NA,NA,NA,NA,1.39781306174882,0.43360437850346,0,0,0,0,1.39781306174882,0.43360437850346,0,0,0,0,1.39781306174882,0.43360437850346,0,0,0,0,8.0470839612919,3.36065598693345,0,0,0,0,0,0,0,0,NA +4.02354198064595,1.12021866231115,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,0.828987844425448,0.453004363751148,8.0470839612919,3.36065598693345,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,0.828987844425448,0.453004363751148,2,0,0,3,NA,NA,NA,NA,8.87607180571734,3.8136603506846,0,0,0,0,8.87607180571734,3.8136603506846,0,0,0,0,8.87607180571734,3.8136603506846,0,0,0,0,-7.45595532115747,1.72829271835191,0,0,0,0,0,0,0,0,NA +-3.72797766057873,0.57609757278397,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,5.58213400806405,3.30067850141731,-7.45595532115747,1.72829271835191,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,5.58213400806405,3.30067850141731,2,0,0,3,NA,NA,NA,NA,-1.87382131309342,5.02897121976922,0,0,0,0,-1.87382131309342,5.02897121976922,0,0,0,0,-1.87382131309342,5.02897121976922,0,0,0,0,0.0813713661838733,-3.22399483259538,0,0,0,0,0,0,0,0,NA +0.0406856830919367,-1.07466494419846,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,0.571780709384058,1.636824225289,0.0813713661838733,-3.22399483259538,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,0.571780709384058,1.636824225289,2,0,0,3,NA,NA,NA,NA,0.653152075567931,-1.58717060730638,0,0,0,0,0.653152075567931,-1.58717060730638,0,0,0,0,0.653152075567931,-1.58717060730638,0,0,0,0,-5.0129688340234,1.04145111504991,0,0,0,0,0,0,0,0,NA +-2.5064844170117,0.347150371683303,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,-0.149575144407947,-0.504237827808964,-5.0129688340234,1.04145111504991,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,-0.149575144407947,-0.504237827808964,2,0,0,3,NA,NA,NA,NA,-5.16254397843134,0.537213287240945,0,0,0,0,-5.16254397843134,0.537213287240945,0,0,0,0,-5.16254397843134,0.537213287240945,0,0,0,0,4.78914450522193,0.705763528719743,0,0,0,0,0,0,0,0,NA +2.39457225261097,0.235254509573248,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,-2.42010800304339,-0.817623480789891,4.78914450522193,0.705763528719743,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,-2.42010800304339,-0.817623480789891,2,0,0,3,NA,NA,NA,NA,2.36903650217855,-0.111859952070148,0,0,0,0,2.36903650217855,-0.111859952070148,0,0,0,0,2.36903650217855,-0.111859952070148,0,0,0,0,6.26285339608913,5.47887306242224,0,0,0,0,0,0,0,0,NA +3.13142669804456,1.82629102080741,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,1.15096026546823,0.42906331960765,6.26285339608913,5.47887306242224,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,1.15096026546823,0.42906331960765,2,0,0,3,NA,NA,NA,NA,7.41381366155736,5.90793638202989,0,0,0,0,7.41381366155736,5.90793638202989,0,0,0,0,7.41381366155736,5.90793638202989,0,0,0,0,0.933367919336909,-1.91048511180284,0,0,0,0,0,0,0,0,NA +0.466683959668455,-0.636828370600947,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,5.47928774538764,3.84593728512343,0.933367919336909,-1.91048511180284,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,5.47928774538764,3.84593728512343,2,0,0,3,NA,NA,NA,NA,6.41265566472455,1.93545217332058,0,0,0,0,6.41265566472455,1.93545217332058,0,0,0,0,6.41265566472455,1.93545217332058,0,0,0,0,4.27416293440075,5.87251280053117,0,0,0,0,0,0,0,0,NA +2.13708146720037,1.95750426684372,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,3.78696348435845,2.05671200227314,4.27416293440075,5.87251280053117,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,3.78696348435845,2.05671200227314,2,0,0,3,NA,NA,NA,NA,8.0611264187592,7.92922480280431,0,0,0,0,8.0611264187592,7.92922480280431,0,0,0,0,8.0611264187592,7.92922480280431,0,0,0,0,0.701573064513568,-0.547448751859534,0,0,0,0,0,0,0,0,NA +0.350786532256784,-0.182482917286511,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,6.40933065022089,4.78391520487357,0.701573064513568,-0.547448751859534,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,6.40933065022089,4.78391520487357,2,0,0,3,NA,NA,NA,NA,7.11090371473446,4.23646645301403,0,0,0,0,7.11090371473446,4.23646645301403,0,0,0,0,7.11090371473446,4.23646645301403,0,0,0,0,-0.434185653281034,1.76972619059811,0,0,0,0,0,0,0,0,NA +-0.217092826640517,0.589908730199369,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,4.82639179327144,3.11676732415251,-0.434185653281034,1.76972619059811,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,4.82639179327144,3.11676732415251,2,0,0,3,NA,NA,NA,NA,4.39220613999041,4.88649351475061,0,0,0,0,4.39220613999041,4.88649351475061,0,0,0,0,4.39220613999041,4.88649351475061,0,0,0,0,0.019575760938082,0.391772048081691,0,0,0,0,0,0,0,0,NA +0.009787880469041,0.130590682693897,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,3.66205112442039,2.83303863389833,0.019575760938082,0.391772048081691,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,3.66205112442039,2.83303863389833,2,0,0,3,NA,NA,NA,NA,3.68162688535847,3.22481068198002,0,0,0,0,3.68162688535847,3.22481068198002,0,0,0,0,3.68162688535847,3.22481068198002,0,0,0,0,-1.83744916157586,3.60677121887832,0,0,0,0,0,0,0,0,NA +-0.918724580787931,1.20225707295944,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,2.80825664727324,2.0262496498637,-1.83744916157586,3.60677121887832,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,2.80825664727324,2.0262496498637,2,0,0,3,NA,NA,NA,NA,0.970807485697378,5.63302086874202,0,0,0,0,0.970807485697378,5.63302086874202,0,0,0,0,0.970807485697378,5.63302086874202,0,0,0,0,3.01877417793456,0.23754787829354,0,0,0,0,0,0,0,0,NA +1.50938708896728,0.0791826260978468,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,2.1753100034713,2.44736984463628,3.01877417793456,0.23754787829354,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,2.1753100034713,2.44736984463628,2,0,0,3,NA,NA,NA,NA,5.19408418140586,2.68491772292982,0,0,0,0,5.19408418140586,2.68491772292982,0,0,0,0,5.19408418140586,2.68491772292982,0,0,0,0,1.57861642966953,1.68892698731518,0,0,0,0,0,0,0,0,NA +0.789308214834765,0.562975662438395,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,3.40251740758188,2.1127839254531,1.57861642966953,1.68892698731518,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,3.40251740758188,2.1127839254531,2,0,0,3,NA,NA,NA,NA,4.98113383725141,3.80171091276829,0,0,0,0,4.98113383725141,3.80171091276829,0,0,0,0,4.98113383725141,3.80171091276829,0,0,0,0,3.83053610318196,2.88925551675078,0,0,0,0,0,0,0,0,NA +1.91526805159098,0.96308517225026,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,3.63108019245619,2.5169111325576,3.83053610318196,2.88925551675078,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,3.63108019245619,2.5169111325576,2,0,0,3,NA,NA,NA,NA,7.46161629563815,5.40616664930837,0,0,0,0,7.46161629563815,5.40616664930837,0,0,0,0,7.46161629563815,5.40616664930837,0,0,0,0,-2.32311342688014,-0.315142251463101,0,0,0,0,0,0,0,0,NA +-1.16155671344007,-0.105047417154367,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,5.35265814261159,3.65478991885098,-2.32311342688014,-0.315142251463101,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,5.35265814261159,3.65478991885098,2,0,0,3,NA,NA,NA,NA,3.02954471573145,3.33964766738788,0,0,0,0,3.02954471573145,3.33964766738788,0,0,0,0,3.02954471573145,3.33964766738788,0,0,0,0,6.36167888945586,5.87990190399452,0,0,0,0,0,0,0,0,NA +3.18083944472793,1.95996730133151,NA,NA,NA,NA,0.5,0,0,0.333333333333333,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,2.51666665808209,1.94176801010144,6.36167888945586,5.87990190399452,2,3,NA,NA,2,0,0,3,NA,NA,NA,NA,2.51666665808209,1.94176801010144,2,0,0,3,NA,NA,NA,NA,8.87834554753795,7.82166991409596,0,0,0,0,8.87834554753795,7.82166991409596,0,0,0,0,8.87834554753795,7.82166991409596,0,0,0,0,0,0,2,0,0,3,0,0,0,0,NA +0,0,NA,NA,NA,NA,0,0,0,0,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,6.78567374799776,4.90433707514597,2,0,0,3,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA diff --git a/shared/package-files/3a/3a126d0aa493114faee67d28a4154ee41bbec10cdc60fcbd4bfe9a02125780ec/Makassar b/shared/package-files/3a/3a126d0aa493114faee67d28a4154ee41bbec10cdc60fcbd4bfe9a02125780ec/Makassar new file mode 100644 index 0000000000000000000000000000000000000000..556ba866933d37f3cfcf8042045d64e209bae30f Binary files /dev/null and b/shared/package-files/3a/3a126d0aa493114faee67d28a4154ee41bbec10cdc60fcbd4bfe9a02125780ec/Makassar differ diff --git a/shared/package-files/3a/3a126d0aa493114faee67d28a4154ee41bbec10cdc60fcbd4bfe9a02125780ec/Ujung_Pandang b/shared/package-files/3a/3a126d0aa493114faee67d28a4154ee41bbec10cdc60fcbd4bfe9a02125780ec/Ujung_Pandang new file mode 100644 index 0000000000000000000000000000000000000000..556ba866933d37f3cfcf8042045d64e209bae30f Binary files /dev/null and b/shared/package-files/3a/3a126d0aa493114faee67d28a4154ee41bbec10cdc60fcbd4bfe9a02125780ec/Ujung_Pandang differ diff --git a/shared/package-files/3a/3a13d179562a86c5f6456c95af271add150672f2dbf91d5d71bc1d6e03c8bc12/grammar38.txt b/shared/package-files/3a/3a13d179562a86c5f6456c95af271add150672f2dbf91d5d71bc1d6e03c8bc12/grammar38.txt new file mode 100644 index 0000000000000000000000000000000000000000..7288d556f9b4b09154e1e002630162a0e7d0cbe2 --- /dev/null +++ b/shared/package-files/3a/3a13d179562a86c5f6456c95af271add150672f2dbf91d5d71bc1d6e03c8bc12/grammar38.txt @@ -0,0 +1,171 @@ +# Grammar for Python + +# NOTE WELL: You should also follow all the steps listed at +# https://devguide.python.org/grammar/ + +# 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) + +async_funcdef: 'async' funcdef +funcdef: 'def' NAME parameters ['->' test] ':' suite + +parameters: '(' [typedargslist] ')' +typedargslist: ( + (tfpdef ['=' test] (',' tfpdef ['=' test])* ',' '/' [',' [ tfpdef ['=' test] ( + ',' tfpdef ['=' test])* ([',' [ + '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']]]) + | '*' [tfpdef] (',' tfpdef ['=' test])* ([',' ['**' tfpdef [',']]]) + | '**' tfpdef [',']]] ) +| (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [ + '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']]] + | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']) +) +tfpdef: NAME [':' test] +varargslist: vfpdef ['=' test ](',' vfpdef ['=' test])* ',' '/' [',' [ (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [ + '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [',']]] + | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [',']) ]] | (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 ['=' (yield_expr|testlist_star_expr)] +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_star_expr] +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' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite] +while_stmt: 'while' namedexpr_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 + +namedexpr_test: test [':=' test] +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: (namedexpr_test|star_expr) ( comp_for | (',' (namedexpr_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 | + '**' 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_star_expr + +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/3a/3a1b5a2a9d3c05ff852a4f9e35cbcdba35a48725396e416f91f36450c5fc94b0/__init__.py b/shared/package-files/3a/3a1b5a2a9d3c05ff852a4f9e35cbcdba35a48725396e416f91f36450c5fc94b0/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e19378bc7aee4f9f8c6c73eef4cacd097d39d2fa --- /dev/null +++ b/shared/package-files/3a/3a1b5a2a9d3c05ff852a4f9e35cbcdba35a48725396e416f91f36450c5fc94b0/__init__.py @@ -0,0 +1,35 @@ +from torch.ao.nn.intrinsic import ConvBn1d +from torch.ao.nn.intrinsic import ConvBn2d +from torch.ao.nn.intrinsic import ConvBn3d +from torch.ao.nn.intrinsic import ConvBnReLU1d +from torch.ao.nn.intrinsic import ConvBnReLU2d +from torch.ao.nn.intrinsic import ConvBnReLU3d +from torch.ao.nn.intrinsic import ConvReLU1d +from torch.ao.nn.intrinsic import ConvReLU2d +from torch.ao.nn.intrinsic import ConvReLU3d +from torch.ao.nn.intrinsic import LinearReLU +from torch.ao.nn.intrinsic import BNReLU2d +from torch.ao.nn.intrinsic import BNReLU3d +from torch.ao.nn.intrinsic import LinearBn1d +from torch.ao.nn.intrinsic.modules.fused import _FusedModule # noqa: F401 + +# Include the subpackages in case user imports from it directly +from . import modules # noqa: F401 +from . import qat # noqa: F401 +from . import quantized # noqa: F401 + +__all__ = [ + 'ConvBn1d', + 'ConvBn2d', + 'ConvBn3d', + 'ConvBnReLU1d', + 'ConvBnReLU2d', + 'ConvBnReLU3d', + 'ConvReLU1d', + 'ConvReLU2d', + 'ConvReLU3d', + 'LinearReLU', + 'BNReLU2d', + 'BNReLU3d', + 'LinearBn1d', +] diff --git a/shared/package-files/3a/3a213808970d0c86aa77f5737664069f6f163dd4f93c14398d529fabf6517379/ed25519.pyi b/shared/package-files/3a/3a213808970d0c86aa77f5737664069f6f163dd4f93c14398d529fabf6517379/ed25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..518d2d6b9ea5edd95388b7793977ee361f6142ec --- /dev/null +++ b/shared/package-files/3a/3a213808970d0c86aa77f5737664069f6f163dd4f93c14398d529fabf6517379/ed25519.pyi @@ -0,0 +1,25 @@ +from abc import ABCMeta, abstractmethod + +from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat + +class Ed25519PrivateKey(metaclass=ABCMeta): + @classmethod + def generate(cls) -> Ed25519PrivateKey: ... + @classmethod + def from_private_bytes(cls, data: bytes) -> Ed25519PrivateKey: ... + @abstractmethod + def private_bytes( + self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption + ) -> bytes: ... + @abstractmethod + def public_key(self) -> Ed25519PublicKey: ... + @abstractmethod + def sign(self, data: bytes) -> bytes: ... + +class Ed25519PublicKey(metaclass=ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed25519PublicKey: ... + @abstractmethod + def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... + @abstractmethod + def verify(self, signature: bytes, data: bytes) -> None: ... diff --git a/shared/package-files/3a/3a22c19c4db8a827df33af2481e65eee0ea097651df0a0bdc754bd1dfc4ee710/_tensorboard_vis.py b/shared/package-files/3a/3a22c19c4db8a827df33af2481e65eee0ea097651df0a0bdc754bd1dfc4ee710/_tensorboard_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..87c325948a8b111d42409140a5d1f8150342794c --- /dev/null +++ b/shared/package-files/3a/3a22c19c4db8a827df33af2481e65eee0ea097651df0a0bdc754bd1dfc4ee710/_tensorboard_vis.py @@ -0,0 +1,142 @@ +import time +from collections import defaultdict +from functools import partial +from typing import DefaultDict + +import torch + + +# Unfortunately it doesn't seem as if there was any way to get TensorBoard to do +# anything without having TF installed, and so this file has a hard dependency on it +# as well. It really is a debugging tool, so it doesn't matter. +try: + from tensorflow.core.util import event_pb2 + from tensorflow.core.framework import graph_pb2 + from tensorflow.python.summary.writer.writer import FileWriter +except ImportError: + raise ImportError("TensorBoard visualization of GraphExecutors requires having " + "TensorFlow installed") from None + + +def dump_tensorboard_summary(graph_executor, logdir): + with FileWriter(logdir) as w: + pb_graph = visualize(graph_executor) + evt = event_pb2.Event(wall_time=time.time(), graph_def=pb_graph.SerializeToString()) + w.add_event(evt) + + +def visualize(graph, name_prefix='', pb_graph=None, executors_it=None): + """Visualizes an independent graph, or a graph executor.""" + value_map = {} + pb_graph = pb_graph or graph_pb2.GraphDef() + + if isinstance(graph, torch._C.GraphExecutorState): + visualize_graph_executor(graph, name_prefix, pb_graph, + partial(visualize, pb_graph=pb_graph)) + return pb_graph + + # Set up an input node + input_node = pb_graph.node.add(op='input', name=name_prefix + 'input') + for i, value in enumerate(graph.param_node().outputs()): + value_map[value.unique()] = name_prefix + 'input:' + str(i) + + visualize_rec(graph, value_map, name_prefix, pb_graph, executors_it) + + # Gather all outputs + return_node = pb_graph.node.add(op='output', name=name_prefix + 'output') + for value in graph.return_node().inputs(): + return_node.input.append(value_map[value.unique()]) + + return pb_graph + + +def visualize_graph_executor(state, name_prefix, pb_graph, inline_graph): + """Append the state of a given GraphExecutor to the graph protobuf. + + Args: + state (GraphExecutor or GraphExecutorState): GraphExecutor to display. + name_prefix (str): Name prefix of the containing subgraph. + pb_graph (GraphDef): graph to append to. + inline_graph (Callable): a function that handles setting up a value_map, + so that some graphs in here can be inlined. This is necessary, because + this will simply be `visualize` for the top-level GraphExecutor, + or `inline_graph` for all nested ones. + + The signature should look like (Graph, name_prefix) -> (). + It will be called exactly once. + + The strategy is to embed all different configurations as independent subgraphs, + while inlining the original graph as the one that actually produces the values. + """ + if state.autograd_fallback_graph is not None: + visualize(graph=state.autograd_fallback_graph, + name_prefix=name_prefix + 'autograd_fallback/', + pb_graph=pb_graph, + executors_it=iter(state.autograd_fallback.executors())) + + for i, (arg_spec, plan) in enumerate(state.execution_plans.items()): + subgraph_name = name_prefix + f'plan{i}/' + + # Create a disconnected node that will keep information regarding the input + # types of this trace. This is unfortunately a bit too verbose to be included + # in the subgraph name. + input_kinds = pb_graph.node.add(op='INPUT_KIND', name=subgraph_name) + input_kinds.attr['inputs'].s = repr(arg_spec).encode('ascii') + + visualize(plan.graph, subgraph_name, pb_graph, iter(plan.code.executors())) + + # Show gradient as an independent subgraph of this plan + if plan.grad_executor is not None: + grad_subgraph_name = subgraph_name + 'grad/' + visualize(plan.grad_executor, grad_subgraph_name, pb_graph) + + return inline_graph(state.graph, name_prefix + 'original/') + + +def visualize_rec(graph, value_map, name_prefix, pb_graph, executors_it=None): + """Recursive part of visualize (basically skips setting up the input and output nodes).""" + def inline_graph(subgraph, name, node): + rec_value_map = {inp.unique(): value_map[val.unique()] + for inp, val in zip(subgraph.inputs(), node.inputs())} + visualize_rec(graph=subgraph, + value_map=rec_value_map, + name_prefix=name, + pb_graph=pb_graph) + for out, val in zip(subgraph.outputs(), node.outputs()): + value_map[val.unique()] = rec_value_map[out.unique()] + + op_id_counter: DefaultDict[str, int] = defaultdict(int) + + def name_for(node): + kind = node.kind()[node.kind().index('::') + 2:] + op_id_counter[kind] += 1 + return kind, name_prefix + kind + '_' + str(op_id_counter[kind]) + + def add_fusion_group(node): + op, name = name_for(node) + inline_graph(node.g('Subgraph'), name + '/', node) + + def add_graph_executor(node): + op, name = name_for(node) + if executors_it is None: + add_node(node) + else: + ge = next(executors_it) + visualize_graph_executor(ge, name + '/', pb_graph, + partial(inline_graph, node=node)) + + def add_node(node): + if node.kind() == 'prim::FusionGroup': + return add_fusion_group(node) + elif node.kind() == 'prim::GraphExecutor': + return add_graph_executor(node) + op, name = name_for(node) + pb_node = pb_graph.node.add(op=op, name=name) + for value in node.inputs(): + pb_node.input.append(value_map[value.unique()]) + # TODO: handle attrs + for i, value in enumerate(node.outputs()): + value_map[value.unique()] = name + ':' + str(i) + + for node in graph.nodes(): + add_node(node) diff --git a/shared/package-files/3a/3a26e42392348bafcda457751c4978f1dfd1e0f456a1f528392e0761006454e7/interval_arithmetic.py b/shared/package-files/3a/3a26e42392348bafcda457751c4978f1dfd1e0f456a1f528392e0761006454e7/interval_arithmetic.py new file mode 100644 index 0000000000000000000000000000000000000000..b828ee57e529e600c12aac37b9346f91995dd89a --- /dev/null +++ b/shared/package-files/3a/3a26e42392348bafcda457751c4978f1dfd1e0f456a1f528392e0761006454e7/interval_arithmetic.py @@ -0,0 +1,412 @@ +""" +Interval Arithmetic for plotting. +This module does not implement interval arithmetic accurately and +hence cannot be used for purposes other than plotting. If you want +to use interval arithmetic, use mpmath's interval arithmetic. + +The module implements interval arithmetic using numpy and +python floating points. The rounding up and down is not handled +and hence this is not an accurate implementation of interval +arithmetic. + +The module uses numpy for speed which cannot be achieved with mpmath. +""" + +# Q: Why use numpy? Why not simply use mpmath's interval arithmetic? +# A: mpmath's interval arithmetic simulates a floating point unit +# and hence is slow, while numpy evaluations are orders of magnitude +# faster. + +# Q: Why create a separate class for intervals? Why not use SymPy's +# Interval Sets? +# A: The functionalities that will be required for plotting is quite +# different from what Interval Sets implement. + +# Q: Why is rounding up and down according to IEEE754 not handled? +# A: It is not possible to do it in both numpy and python. An external +# library has to used, which defeats the whole purpose i.e., speed. Also +# rounding is handled for very few functions in those libraries. + +# Q Will my plots be affected? +# A It will not affect most of the plots. The interval arithmetic +# module based suffers the same problems as that of floating point +# arithmetic. + +from sympy.core.logic import fuzzy_and +from sympy.simplify.simplify import nsimplify + +from .interval_membership import intervalMembership + + +class interval: + """ Represents an interval containing floating points as start and + end of the interval + The is_valid variable tracks whether the interval obtained as the + result of the function is in the domain and is continuous. + - True: Represents the interval result of a function is continuous and + in the domain of the function. + - False: The interval argument of the function was not in the domain of + the function, hence the is_valid of the result interval is False + - None: The function was not continuous over the interval or + the function's argument interval is partly in the domain of the + function + + A comparison between an interval and a real number, or a + comparison between two intervals may return ``intervalMembership`` + of two 3-valued logic values. + """ + + def __init__(self, *args, is_valid=True, **kwargs): + self.is_valid = is_valid + if len(args) == 1: + if isinstance(args[0], interval): + self.start, self.end = args[0].start, args[0].end + else: + self.start = float(args[0]) + self.end = float(args[0]) + elif len(args) == 2: + if args[0] < args[1]: + self.start = float(args[0]) + self.end = float(args[1]) + else: + self.start = float(args[1]) + self.end = float(args[0]) + + else: + raise ValueError("interval takes a maximum of two float values " + "as arguments") + + @property + def mid(self): + return (self.start + self.end) / 2.0 + + @property + def width(self): + return self.end - self.start + + def __repr__(self): + return "interval(%f, %f)" % (self.start, self.end) + + def __str__(self): + return "[%f, %f]" % (self.start, self.end) + + def __lt__(self, other): + if isinstance(other, (int, float)): + if self.end < other: + return intervalMembership(True, self.is_valid) + elif self.start > other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + + elif isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.end < other. start: + return intervalMembership(True, valid) + if self.start > other.end: + return intervalMembership(False, valid) + return intervalMembership(None, valid) + else: + return NotImplemented + + def __gt__(self, other): + if isinstance(other, (int, float)): + if self.start > other: + return intervalMembership(True, self.is_valid) + elif self.end < other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + elif isinstance(other, interval): + return other.__lt__(self) + else: + return NotImplemented + + def __eq__(self, other): + if isinstance(other, (int, float)): + if self.start == other and self.end == other: + return intervalMembership(True, self.is_valid) + if other in self: + return intervalMembership(None, self.is_valid) + else: + return intervalMembership(False, self.is_valid) + + if isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.start == other.start and self.end == other.end: + return intervalMembership(True, valid) + elif self.__lt__(other)[0] is not None: + return intervalMembership(False, valid) + else: + return intervalMembership(None, valid) + else: + return NotImplemented + + def __ne__(self, other): + if isinstance(other, (int, float)): + if self.start == other and self.end == other: + return intervalMembership(False, self.is_valid) + if other in self: + return intervalMembership(None, self.is_valid) + else: + return intervalMembership(True, self.is_valid) + + if isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.start == other.start and self.end == other.end: + return intervalMembership(False, valid) + if not self.__lt__(other)[0] is None: + return intervalMembership(True, valid) + return intervalMembership(None, valid) + else: + return NotImplemented + + def __le__(self, other): + if isinstance(other, (int, float)): + if self.end <= other: + return intervalMembership(True, self.is_valid) + if self.start > other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + + if isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.end <= other.start: + return intervalMembership(True, valid) + if self.start > other.end: + return intervalMembership(False, valid) + return intervalMembership(None, valid) + else: + return NotImplemented + + def __ge__(self, other): + if isinstance(other, (int, float)): + if self.start >= other: + return intervalMembership(True, self.is_valid) + elif self.end < other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + elif isinstance(other, interval): + return other.__le__(self) + + def __add__(self, other): + if isinstance(other, (int, float)): + if self.is_valid: + return interval(self.start + other, self.end + other) + else: + start = self.start + other + end = self.end + other + return interval(start, end, is_valid=self.is_valid) + + elif isinstance(other, interval): + start = self.start + other.start + end = self.end + other.end + valid = fuzzy_and([self.is_valid, other.is_valid]) + return interval(start, end, is_valid=valid) + else: + return NotImplemented + + __radd__ = __add__ + + def __sub__(self, other): + if isinstance(other, (int, float)): + start = self.start - other + end = self.end - other + return interval(start, end, is_valid=self.is_valid) + + elif isinstance(other, interval): + start = self.start - other.end + end = self.end - other.start + valid = fuzzy_and([self.is_valid, other.is_valid]) + return interval(start, end, is_valid=valid) + else: + return NotImplemented + + def __rsub__(self, other): + if isinstance(other, (int, float)): + start = other - self.end + end = other - self.start + return interval(start, end, is_valid=self.is_valid) + elif isinstance(other, interval): + return other.__sub__(self) + else: + return NotImplemented + + def __neg__(self): + if self.is_valid: + return interval(-self.end, -self.start) + else: + return interval(-self.end, -self.start, is_valid=self.is_valid) + + def __mul__(self, other): + if isinstance(other, interval): + if self.is_valid is False or other.is_valid is False: + return interval(-float('inf'), float('inf'), is_valid=False) + elif self.is_valid is None or other.is_valid is None: + return interval(-float('inf'), float('inf'), is_valid=None) + else: + inters = [] + inters.append(self.start * other.start) + inters.append(self.end * other.start) + inters.append(self.start * other.end) + inters.append(self.end * other.end) + start = min(inters) + end = max(inters) + return interval(start, end) + elif isinstance(other, (int, float)): + return interval(self.start*other, self.end*other, is_valid=self.is_valid) + else: + return NotImplemented + + __rmul__ = __mul__ + + def __contains__(self, other): + if isinstance(other, (int, float)): + return self.start <= other and self.end >= other + else: + return self.start <= other.start and other.end <= self.end + + def __rtruediv__(self, other): + if isinstance(other, (int, float)): + other = interval(other) + return other.__truediv__(self) + elif isinstance(other, interval): + return other.__truediv__(self) + else: + return NotImplemented + + def __truediv__(self, other): + # Both None and False are handled + if not self.is_valid: + # Don't divide as the value is not valid + return interval(-float('inf'), float('inf'), is_valid=self.is_valid) + if isinstance(other, (int, float)): + if other == 0: + # Divide by zero encountered. valid nowhere + return interval(-float('inf'), float('inf'), is_valid=False) + else: + return interval(self.start / other, self.end / other) + + elif isinstance(other, interval): + if other.is_valid is False or self.is_valid is False: + return interval(-float('inf'), float('inf'), is_valid=False) + elif other.is_valid is None or self.is_valid is None: + return interval(-float('inf'), float('inf'), is_valid=None) + else: + # denominator contains both signs, i.e. being divided by zero + # return the whole real line with is_valid = None + if 0 in other: + return interval(-float('inf'), float('inf'), is_valid=None) + + # denominator negative + this = self + if other.end < 0: + this = -this + other = -other + + # denominator positive + inters = [] + inters.append(this.start / other.start) + inters.append(this.end / other.start) + inters.append(this.start / other.end) + inters.append(this.end / other.end) + start = max(inters) + end = min(inters) + return interval(start, end) + else: + return NotImplemented + + def __pow__(self, other): + # Implements only power to an integer. + from .lib_interval import exp, log + if not self.is_valid: + return self + if isinstance(other, interval): + return exp(other * log(self)) + elif isinstance(other, (float, int)): + if other < 0: + return 1 / self.__pow__(abs(other)) + else: + if int(other) == other: + return _pow_int(self, other) + else: + return _pow_float(self, other) + else: + return NotImplemented + + def __rpow__(self, other): + if isinstance(other, (float, int)): + if not self.is_valid: + #Don't do anything + return self + elif other < 0: + if self.width > 0: + return interval(-float('inf'), float('inf'), is_valid=False) + else: + power_rational = nsimplify(self.start) + num, denom = power_rational.as_numer_denom() + if denom % 2 == 0: + return interval(-float('inf'), float('inf'), + is_valid=False) + else: + start = -abs(other)**self.start + end = start + return interval(start, end) + else: + return interval(other**self.start, other**self.end) + elif isinstance(other, interval): + return other.__pow__(self) + else: + return NotImplemented + + def __hash__(self): + return hash((self.is_valid, self.start, self.end)) + + +def _pow_float(inter, power): + """Evaluates an interval raised to a floating point.""" + power_rational = nsimplify(power) + num, denom = power_rational.as_numer_denom() + if num % 2 == 0: + start = abs(inter.start)**power + end = abs(inter.end)**power + if start < 0: + ret = interval(0, max(start, end)) + else: + ret = interval(start, end) + return ret + elif denom % 2 == 0: + if inter.end < 0: + return interval(-float('inf'), float('inf'), is_valid=False) + elif inter.start < 0: + return interval(0, inter.end**power, is_valid=None) + else: + return interval(inter.start**power, inter.end**power) + else: + if inter.start < 0: + start = -abs(inter.start)**power + else: + start = inter.start**power + + if inter.end < 0: + end = -abs(inter.end)**power + else: + end = inter.end**power + + return interval(start, end, is_valid=inter.is_valid) + + +def _pow_int(inter, power): + """Evaluates an interval raised to an integer power""" + power = int(power) + if power & 1: + return interval(inter.start**power, inter.end**power) + else: + if inter.start < 0 and inter.end > 0: + start = 0 + end = max(inter.start**power, inter.end**power) + return interval(start, end) + else: + return interval(inter.start**power, inter.end**power) diff --git a/shared/package-files/3a/3a2c79f8412fb4b10c51b660cbc4cbebef7be656788ca33581f9a2b816c3de44/loss.h b/shared/package-files/3a/3a2c79f8412fb4b10c51b660cbc4cbebef7be656788ca33581f9a2b816c3de44/loss.h new file mode 100644 index 0000000000000000000000000000000000000000..f34cfbf593340d8aa17fb701557f7bc8080f41d3 --- /dev/null +++ b/shared/package-files/3a/3a2c79f8412fb4b10c51b660cbc4cbebef7be656788ca33581f9a2b816c3de44/loss.h @@ -0,0 +1,805 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace torch { +namespace nn { + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ L1Loss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the mean absolute error (MAE) between each +/// element in the input : math :`x` and target : `y`. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.L1Loss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::L1LossOptions` class to learn what +/// constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// L1Loss model(L1LossOptions(torch::kNone)); +/// ``` +struct TORCH_API L1LossImpl : Cloneable { + explicit L1LossImpl(L1LossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `L1Loss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + L1LossOptions options; +}; + +/// A `ModuleHolder` subclass for `L1LossImpl`. +/// See the documentation for `L1LossImpl` class to learn what methods it +/// provides, and examples of how to use `L1Loss` with +/// `torch::nn::L1LossOptions`. See the documentation for `ModuleHolder` to +/// learn about PyTorch's module storage semantics. +TORCH_MODULE(L1Loss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ KLDivLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// The Kullback-Leibler divergence loss measure +/// See https://pytorch.org/docs/master/nn.html#torch.nn.KLDivLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::KLDivLossOptions` class to learn what +/// constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// KLDivLoss model(KLDivLossOptions().reduction(torch::kNone)); +/// ``` +struct TORCH_API KLDivLossImpl : Cloneable { + explicit KLDivLossImpl(KLDivLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `KLDivLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + KLDivLossOptions options; +}; + +/// A `ModuleHolder` subclass for `KLDivLossImpl`. +/// See the documentation for `KLDivLossImpl` class to learn what methods it +/// provides, and examples of how to use `KLDivLoss` with +/// `torch::nn::KLDivLossOptions`. See the documentation for `ModuleHolder` to +/// learn about PyTorch's module storage semantics. +TORCH_MODULE(KLDivLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MSELoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the mean squared error (squared L2 norm) +/// between each element in the input :math:`x` and target :math:`y`. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.MSELoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::MSELossOptions` class to learn what +/// constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// MSELoss model(MSELossOptions(torch::kNone)); +/// ``` +struct TORCH_API MSELossImpl : Cloneable { + explicit MSELossImpl(MSELossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `MSELoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + MSELossOptions options; +}; + +/// A `ModuleHolder` subclass for `MSELossImpl`. +/// See the documentation for `MSELossImpl` class to learn what methods it +/// provides, and examples of how to use `MSELoss` with +/// `torch::nn::MSELossOptions`. See the documentation for `ModuleHolder` to +/// learn about PyTorch's module storage semantics. +TORCH_MODULE(MSELoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BCELoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the Binary Cross Entropy +/// between the target and the output. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.BCELoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::BCELossOptions` class to learn what +/// constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// BCELoss model(BCELossOptions().reduction(torch::kNone).weight(weight)); +/// ``` +struct TORCH_API BCELossImpl : Cloneable { + explicit BCELossImpl(BCELossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `BCELoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + BCELossOptions options; +}; + +/// A `ModuleHolder` subclass for `BCELossImpl`. +/// See the documentation for `BCELossImpl` class to learn what methods it +/// provides, and examples of how to use `BCELoss` with +/// `torch::nn::BCELossOptions`. See the documentation for `ModuleHolder` to +/// learn about PyTorch's module storage semantics. +TORCH_MODULE(BCELoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HingeEmbeddingLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the loss given an input tensor :math:`x` +/// and a labels tensor :math:`y` (containing 1 or -1). +/// See https://pytorch.org/docs/master/nn.html#torch.nn.HingeEmbeddingLoss to +/// learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::HingeEmbeddingLossOptions` class to +/// learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// HingeEmbeddingLoss +/// model(HingeEmbeddingLossOptions().margin(4).reduction(torch::kNone)); +/// ``` +struct TORCH_API HingeEmbeddingLossImpl : Cloneable { + explicit HingeEmbeddingLossImpl(HingeEmbeddingLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `HingeEmbeddingLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + HingeEmbeddingLossOptions options; +}; + +/// A `ModuleHolder` subclass for `HingeEmbeddingLossImpl`. +/// See the documentation for `HingeEmbeddingLossImpl` class to learn what +/// methods it provides, and examples of how to use `HingeEmbeddingLoss` with +/// `torch::nn::HingeEmbeddingLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(HingeEmbeddingLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiMarginLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that optimizes a multi-class classification hinge +/// loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`) +/// and output :math:`y` (which is a 1D tensor of target class indices, :math:`0 +/// \leq y \leq \text{x.size}(1)-1`). See +/// https://pytorch.org/docs/master/nn.html#torch.nn.MultiMarginLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::MultiMarginLossOptions` class to learn +/// what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// MultiMarginLoss model(MultiMarginLossOptions().margin(2).weight(weight)); +/// ``` +struct TORCH_API MultiMarginLossImpl : public Cloneable { + explicit MultiMarginLossImpl(MultiMarginLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `MultiMarginLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + MultiMarginLossOptions options; +}; + +/// A `ModuleHolder` subclass for `MultiMarginLossImpl`. +/// See the documentation for `MultiMarginLossImpl` class to learn what methods +/// it provides, and examples of how to use `MultiMarginLoss` with +/// `torch::nn::MultiMarginLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(MultiMarginLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CosineEmbeddingLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the loss given input tensors +/// `input1`, `input2`, and a `Tensor` label `target` with values 1 or +/// -1. This is used for measuring whether two inputs are similar or +/// dissimilar, using the cosine distance, and is typically used for learning +/// nonlinear embeddings or semi-supervised learning. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.CosineEmbeddingLoss to +/// learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::CosineEmbeddingLossOptions` class to +/// learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// CosineEmbeddingLoss model(CosineEmbeddingLossOptions().margin(0.5)); +/// ``` +struct TORCH_API CosineEmbeddingLossImpl + : public Cloneable { + explicit CosineEmbeddingLossImpl(CosineEmbeddingLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `CosineEmbeddingLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward( + const Tensor& input1, + const Tensor& input2, + const Tensor& target); + + /// The options with which this `Module` was constructed. + CosineEmbeddingLossOptions options; +}; + +/// A `ModuleHolder` subclass for `CosineEmbeddingLossImpl`. +/// See the documentation for `CosineEmbeddingLossImpl` class to learn what +/// methods it provides, and examples of how to use `CosineEmbeddingLoss` with +/// `torch::nn::CosineEmbeddingLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(CosineEmbeddingLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SmoothL1Loss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that uses a squared term if the absolute +/// element-wise error falls below beta and an L1 term otherwise. +/// It is less sensitive to outliers than the `MSELoss` and in some cases +/// prevents exploding gradients (e.g. see the paper `Fast R-CNN` by Ross +/// Girshick). See https://pytorch.org/docs/master/nn.html#torch.nn.SmoothL1Loss +/// to learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::SmoothL1LossOptions` class to learn +/// what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// SmoothL1Loss model(SmoothL1LossOptions().reduction(torch::kNone).beta(0.5)); +/// ``` +struct TORCH_API SmoothL1LossImpl : public Cloneable { + explicit SmoothL1LossImpl(SmoothL1LossOptions options = {}); + + void reset() override; + + /// Pretty prints the `L1Loss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + SmoothL1LossOptions options; +}; + +/// A `ModuleHolder` subclass for `SmoothL1LossImpl`. +/// See the documentation for `SmoothL1LossImpl` class to learn what methods it +/// provides, and examples of how to use `SmoothL1Loss` with +/// `torch::nn::SmoothL1LossOptions`. See the documentation for `ModuleHolder` +/// to learn about PyTorch's module storage semantics. +TORCH_MODULE(SmoothL1Loss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HuberLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that uses a squared term if the absolute +/// element-wise error falls below delta and a delta-scaled L1 term otherwise. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.HuberLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::HuberLossOptions` class to learn what +/// constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// HuberLoss model(HuberLossOptions().reduction(torch::kNone).delta(0.5)); +/// ``` +struct TORCH_API HuberLossImpl : public Cloneable { + explicit HuberLossImpl(HuberLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `HuberLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + HuberLossOptions options; +}; + +/// A `ModuleHolder` subclass for `HuberLossImpl`. +/// See the documentation for `HuberLossImpl` class to learn what methods it +/// provides, and examples of how to use `HuberLoss` with +/// `torch::nn::HuberLossOptions`. See the documentation for `ModuleHolder` to +/// learn about PyTorch's module storage semantics. +TORCH_MODULE(HuberLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiLabelMarginLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that optimizes a multi-class multi-classification +/// hinge loss (margin-based loss) between input :math:`x` (a 2D mini-batch +/// `Tensor`) and output :math:`y` (which is a 2D `Tensor` of target class +/// indices). See +/// https://pytorch.org/docs/master/nn.html#torch.nn.MultiLabelMarginLoss to +/// learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::MultiLabelMarginLossOptions` class to +/// learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// MultiLabelMarginLoss model(MultiLabelMarginLossOptions(torch::kNone)); +/// ``` +struct TORCH_API MultiLabelMarginLossImpl + : public Cloneable { + explicit MultiLabelMarginLossImpl(MultiLabelMarginLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `L1Loss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + MultiLabelMarginLossOptions options; +}; + +/// A `ModuleHolder` subclass for `MultiLabelMarginLossImpl`. +/// See the documentation for `MultiLabelMarginLossImpl` class to learn what +/// methods it provides, and examples of how to use `MultiLabelMarginLoss` with +/// `torch::nn::MultiLabelMarginLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(MultiLabelMarginLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SoftMarginLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that optimizes a two-class classification +/// logistic loss between input tensor :math:`x` and target tensor :math:`y` +/// (containing 1 or -1). +/// See https://pytorch.org/docs/master/nn.html#torch.nn.SoftMarginLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::SoftMarginLossOptions` class to learn +/// what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// SoftMarginLoss model(SoftMarginLossOptions(torch::kNone)); +/// ``` +struct TORCH_API SoftMarginLossImpl : public Cloneable { + explicit SoftMarginLossImpl(SoftMarginLossOptions options_ = {}); + + /// Pretty prints the `SoftMarginLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + void reset() override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + SoftMarginLossOptions options; +}; + +/// A `ModuleHolder` subclass for `SoftMarginLossImpl`. +/// See the documentation for `SoftMarginLossImpl` class to learn what methods +/// it provides, and examples of how to use `SoftMarginLoss` with +/// `torch::nn::SoftMarginLossOptions`. See the documentation for `ModuleHolder` +/// to learn about PyTorch's module storage semantics. +TORCH_MODULE(SoftMarginLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiLabelSoftMarginLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that optimizes a multi-label one-versus-all +/// loss based on max-entropy, between input :math:`x` and target :math:`y` of +/// size :math:`(N, C)`. See +/// https://pytorch.org/docs/master/nn.html#torch.nn.MultiLabelSoftMarginLoss to +/// learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::MultiLabelSoftMarginLossOptions` class +/// to learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// MultiLabelSoftMarginLoss +/// model(MultiLabelSoftMarginLossOptions().reduction(torch::kNone).weight(weight)); +/// ``` +struct TORCH_API MultiLabelSoftMarginLossImpl + : public Cloneable { + explicit MultiLabelSoftMarginLossImpl( + MultiLabelSoftMarginLossOptions options_ = {}); + + /// Pretty prints the `MultiLabelSoftMarginLoss` module into the given + /// `stream`. + void pretty_print(std::ostream& stream) const override; + + void reset() override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + MultiLabelSoftMarginLossOptions options; +}; + +/// A `ModuleHolder` subclass for `MultiLabelSoftMarginLossImpl`. +/// See the documentation for `MultiLabelSoftMarginLossImpl` class to learn what +/// methods it provides, and examples of how to use `MultiLabelSoftMarginLoss` +/// with `torch::nn::MultiLabelSoftMarginLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(MultiLabelSoftMarginLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TripletMarginLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the triplet loss given an input +/// tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater +/// than :math:`0`. This is used for measuring a relative similarity between +/// samples. A triplet is composed by `a`, `p` and `n` (i.e., `anchor`, +/// `positive examples` and `negative examples` respectively). The +/// shapes of all input tensors should be :math:`(N, D)`. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.TripletMarginLoss to +/// learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::TripletMarginLossOptions` class to +/// learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// TripletMarginLoss +/// model(TripletMarginLossOptions().margin(3).p(2).eps(1e-06).swap(false)); +/// ``` +struct TORCH_API TripletMarginLossImpl + : public Cloneable { + explicit TripletMarginLossImpl(TripletMarginLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `TripletMarginLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward( + const Tensor& anchor, + const Tensor& positive, + const Tensor& negative); + + /// The options with which this `Module` was constructed. + TripletMarginLossOptions options; +}; + +/// A `ModuleHolder` subclass for `TripletMarginLossImpl`. +/// See the documentation for `TripletMarginLossImpl` class to learn what +/// methods it provides, and examples of how to use `TripletMarginLoss` with +/// `torch::nn::TripletMarginLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(TripletMarginLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TripletMarginWithDistanceLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the triplet loss given input +/// tensors :math:`a`, :math:`p`, and :math:`n` (representing anchor, +/// positive, and negative examples, respectively); and a nonnegative, +/// real-valued function +/// ("distance function") used to compute the relationships between the anchor +/// and positive example ("positive distance") and the anchor and negative +/// example ("negative distance"). +/// See +/// https://pytorch.org/docs/master/nn.html#torch.nn.TripletMarginWithDistanceLoss +/// to learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::TripletMarginWithDistanceLossOptions` +/// class to learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// TripletMarginWithDistanceLoss +/// model(TripletMarginWithDistanceLossOptions().margin(3).swap(false)); +/// ``` +struct TORCH_API TripletMarginWithDistanceLossImpl + : public Cloneable { + explicit TripletMarginWithDistanceLossImpl( + TripletMarginWithDistanceLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `TripletMarginWithDistanceLoss` module into the given + /// `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward( + const Tensor& anchor, + const Tensor& positive, + const Tensor& negative); + + /// The options with which this `Module` was constructed. + TripletMarginWithDistanceLossOptions options; +}; + +/// A `ModuleHolder` subclass for `TripletMarginWithDistanceLossImpl`. +/// See the documentation for `TripletMarginWithDistanceLossImpl` class to learn +/// what methods it provides, and examples of how to use +/// `TripletMarginWithDistanceLoss` with +/// `torch::nn::TripletMarginWithDistanceLossOptions`. +/// See the documentation for `ModuleHolder` to learn about PyTorch's +/// module storage semantics. +TORCH_MODULE(TripletMarginWithDistanceLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CTCLoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// The Connectionist Temporal Classification loss. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.CTCLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::CTCLossOptions` class to learn what +/// constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// CTCLoss +/// model(CTCLossOptions().blank(42).zero_infinity(false).reduction(torch::kSum)); +/// ``` +struct TORCH_API CTCLossImpl : public Cloneable { + explicit CTCLossImpl(CTCLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `CTCLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward( + const Tensor& log_probs, + const Tensor& targets, + const Tensor& input_lengths, + const Tensor& target_lengths); + + /// The options with which this `Module` was constructed. + CTCLossOptions options; +}; + +/// A `ModuleHolder` subclass for `CTCLossImpl`. +/// See the documentation for `CTCLossImpl` class to learn what methods it +/// provides, and examples of how to use `CTCLoss` with +/// `torch::nn::CTCLossOptions`. See the documentation for `ModuleHolder` to +/// learn about PyTorch's module storage semantics. +TORCH_MODULE(CTCLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PoissonNLLLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Negative log likelihood loss with Poisson distribution of target. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.PoissonNLLLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::PoissonNLLLossOptions` class to learn +/// what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// PoissonNLLLoss +/// model(PoissonNLLLossOptions().log_input(false).full(true).eps(0.42).reduction(torch::kSum)); +/// ``` +struct TORCH_API PoissonNLLLossImpl : public Cloneable { + explicit PoissonNLLLossImpl(PoissonNLLLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `PoissonNLLLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& log_input, const Tensor& targets); + + /// The options with which this `Module` was constructed. + PoissonNLLLossOptions options; +}; + +/// A `ModuleHolder` subclass for `PoissonNLLLossImpl`. +/// See the documentation for `PoissonNLLLossImpl` class to learn what methods +/// it provides, and examples of how to use `PoissonNLLLoss` with +/// `torch::nn::PoissonNLLLossOptions`. See the documentation for `ModuleHolder` +/// to learn about PyTorch's module storage semantics. +TORCH_MODULE(PoissonNLLLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MarginRankingLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that measures the loss given +/// inputs :math:`x1`, :math:`x2`, two 1D mini-batch `Tensors`, +/// and a label 1D mini-batch tensor :math:`y` (containing 1 or -1). +/// See https://pytorch.org/docs/master/nn.html#torch.nn.MarginRankingLoss to +/// learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::MarginRankingLossOptions` class to +/// learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// MarginRankingLoss +/// model(MarginRankingLossOptions().margin(0.5).reduction(torch::kSum)); +/// ``` +struct TORCH_API MarginRankingLossImpl + : public Cloneable { + explicit MarginRankingLossImpl(MarginRankingLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `MarginRankingLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward( + const Tensor& input1, + const Tensor& input2, + const Tensor& targets); + + /// The options with which this `Module` was constructed. + MarginRankingLossOptions options; +}; + +/// A `ModuleHolder` subclass for `MarginRankingLossImpl`. +/// See the documentation for `MarginRankingLossImpl` class to learn what +/// methods it provides, and examples of how to use `MarginRankingLoss` with +/// `torch::nn::MarginRankingLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(MarginRankingLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NLLLoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// The negative log likelihood loss. It is useful to train a classification +/// problem with `C` classes. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.NLLLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::NLLLossOptions` class to learn what +/// constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// NLLLoss model(NLLLossOptions().ignore_index(-100).reduction(torch::kMean)); +/// ``` +struct TORCH_API NLLLossImpl : public Cloneable { + explicit NLLLossImpl(NLLLossOptions options_ = {}); + + /// Pretty prints the `NLLLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + void reset() override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + NLLLossOptions options; + + /// A manual rescaling weight given to to each class. + Tensor weight; +}; + +/// A `ModuleHolder` subclass for `NLLLossImpl`. +/// See the documentation for `NLLLossImpl` class to learn what methods it +/// provides, and examples of how to use `NLLLoss` with +/// `torch::nn::NLLLossOptions`. See the documentation for `ModuleHolder` to +/// learn about PyTorch's module storage semantics. +TORCH_MODULE(NLLLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CrossEntropyLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// Creates a criterion that computes cross entropy loss between input and +/// target. See +/// https://pytorch.org/docs/master/nn.html#torch.nn.CrossEntropyLoss to learn +/// about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::CrossEntropyLossOptions` class to +/// learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// CrossEntropyLoss +/// model(CrossEntropyLossOptions().ignore_index(-100).reduction(torch::kMean)); +/// ``` +struct TORCH_API CrossEntropyLossImpl : public Cloneable { + explicit CrossEntropyLossImpl(CrossEntropyLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `CrossEntropyLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + CrossEntropyLossOptions options; + + /// A manual rescaling weight given to to each class. + Tensor weight; +}; + +/// A `ModuleHolder` subclass for `CrossEntropyLossImpl`. +/// See the documentation for `CrossEntropyLossImpl` class to learn what methods +/// it provides, and examples of how to use `CrossEntropyLoss` with +/// `torch::nn::CrossEntropyLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(CrossEntropyLoss); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BCEWithLogitsLoss +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// This loss combines a `Sigmoid` layer and the `BCELoss` in one single +/// class. This version is more numerically stable than using a plain `Sigmoid` +/// followed by a `BCELoss` as, by combining the operations into one layer, +/// we take advantage of the log-sum-exp trick for numerical stability. +/// See https://pytorch.org/docs/master/nn.html#torch.nn.BCEWithLogitsLoss to +/// learn about the exact behavior of this module. +/// +/// See the documentation for `torch::nn::BCEWithLogitsLossOptions` class to +/// learn what constructor arguments are supported for this module. +/// +/// Example: +/// ``` +/// BCEWithLogitsLoss +/// model(BCEWithLogitsLossOptions().reduction(torch::kNone).weight(weight)); +/// ``` +struct TORCH_API BCEWithLogitsLossImpl + : public Cloneable { + explicit BCEWithLogitsLossImpl(BCEWithLogitsLossOptions options_ = {}); + + void reset() override; + + /// Pretty prints the `BCEWithLogitsLoss` module into the given `stream`. + void pretty_print(std::ostream& stream) const override; + + Tensor forward(const Tensor& input, const Tensor& target); + + /// The options with which this `Module` was constructed. + BCEWithLogitsLossOptions options; + + /// A manual rescaling weight given to the loss of each batch element. + Tensor weight; + + /// A weight of positive examples. + Tensor pos_weight; +}; + +/// A `ModuleHolder` subclass for `BCEWithLogitsLossImpl`. +/// See the documentation for `BCEWithLogitsLossImpl` class to learn what +/// methods it provides, and examples of how to use `BCEWithLogitsLoss` with +/// `torch::nn::BCEWithLogitsLossOptions`. See the documentation for +/// `ModuleHolder` to learn about PyTorch's module storage semantics. +TORCH_MODULE(BCEWithLogitsLoss); + +} // namespace nn +} // namespace torch diff --git a/shared/package-files/3a/3a2caad383ded023e712f60afba32d768ed7b904fc6f59a42fb771e8ccdedd3a/_coo.py b/shared/package-files/3a/3a2caad383ded023e712f60afba32d768ed7b904fc6f59a42fb771e8ccdedd3a/_coo.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1d577f90e5cf4d585aede3f30c6caf5b8ae059 --- /dev/null +++ b/shared/package-files/3a/3a2caad383ded023e712f60afba32d768ed7b904fc6f59a42fb771e8ccdedd3a/_coo.py @@ -0,0 +1,1647 @@ +""" A sparse matrix in COOrdinate or 'triplet' format""" + +__docformat__ = "restructuredtext en" + +__all__ = ['coo_array', 'coo_matrix', 'isspmatrix_coo'] + +import math +from warnings import warn + +import numpy as np + +from .._lib._util import copy_if_needed +from ._matrix import spmatrix +from ._sparsetools import (coo_tocsr, coo_todense, coo_todense_nd, + coo_matvec, coo_matvec_nd, coo_matmat_dense, + coo_matmat_dense_nd) +from ._base import issparse, SparseEfficiencyWarning, _spbase, sparray +from ._data import _data_matrix, _minmax_mixin +from ._sputils import (upcast_char, to_native, isshape, getdtype, + getdata, downcast_intp_index, get_index_dtype, + check_shape, check_reshape_kwargs, isscalarlike, isdense) + +import operator + + +class _coo_base(_data_matrix, _minmax_mixin): + _format = 'coo' + _allow_nd = range(1, 65) + + def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): + _data_matrix.__init__(self, arg1, maxprint=maxprint) + if not copy: + copy = copy_if_needed + + if isinstance(arg1, tuple): + if isshape(arg1, allow_nd=self._allow_nd): + self._shape = check_shape(arg1, allow_nd=self._allow_nd) + idx_dtype = self._get_index_dtype(maxval=max(self._shape)) + data_dtype = getdtype(dtype, default=float) + self.coords = tuple(np.array([], dtype=idx_dtype) + for _ in range(len(self._shape))) + self.data = np.array([], dtype=data_dtype) + self.has_canonical_format = True + else: + try: + obj, coords = arg1 + except (TypeError, ValueError) as e: + raise TypeError('invalid input format') from e + + if shape is None: + if any(len(idx) == 0 for idx in coords): + raise ValueError('cannot infer dimensions from zero ' + 'sized index arrays') + shape = tuple(operator.index(np.max(idx)) + 1 + for idx in coords) + self._shape = check_shape(shape, allow_nd=self._allow_nd) + idx_dtype = self._get_index_dtype(coords, + maxval=max(self.shape), + check_contents=True) + self.coords = tuple(np.array(idx, copy=copy, dtype=idx_dtype) + for idx in coords) + self.data = getdata(obj, copy=copy, dtype=dtype) + self.has_canonical_format = False + else: + if issparse(arg1): + if arg1.format == self.format and copy: + self.coords = tuple(idx.copy() for idx in arg1.coords) + self.data = arg1.data.astype(getdtype(dtype, arg1)) # copy=True + self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd) + self.has_canonical_format = arg1.has_canonical_format + else: + coo = arg1.tocoo() + self.coords = tuple(coo.coords) + self.data = coo.data.astype(getdtype(dtype, coo), copy=False) + self._shape = check_shape(coo.shape, allow_nd=self._allow_nd) + self.has_canonical_format = False + else: + # dense argument + M = np.asarray(arg1) + if not isinstance(self, sparray): + M = np.atleast_2d(M) + if M.ndim != 2: + raise TypeError(f'expected 2D array or matrix, not {M.ndim}D') + + self._shape = check_shape(M.shape, allow_nd=self._allow_nd) + if shape is not None: + if check_shape(shape, allow_nd=self._allow_nd) != self._shape: + message = f'inconsistent shapes: {shape} != {self._shape}' + raise ValueError(message) + + index_dtype = self._get_index_dtype(maxval=max(self._shape)) + coords = M.nonzero() + self.coords = tuple(idx.astype(index_dtype, copy=False) + for idx in coords) + self.data = getdata(M[coords], copy=copy, dtype=dtype) + self.has_canonical_format = True + + if len(self._shape) > 2: + self.coords = tuple(idx.astype(np.int64, copy=False) for idx in self.coords) + + self._check() + + @property + def row(self): + if self.ndim > 1: + return self.coords[-2] + result = np.zeros_like(self.col) + result.setflags(write=False) + return result + + + @row.setter + def row(self, new_row): + if self.ndim < 2: + raise ValueError('cannot set row attribute of a 1-dimensional sparse array') + new_row = np.asarray(new_row, dtype=self.coords[-2].dtype) + self.coords = self.coords[:-2] + (new_row,) + self.coords[-1:] + + @property + def col(self): + return self.coords[-1] + + @col.setter + def col(self, new_col): + new_col = np.asarray(new_col, dtype=self.coords[-1].dtype) + self.coords = self.coords[:-1] + (new_col,) + + def reshape(self, *args, **kwargs): + shape = check_shape(args, self.shape, allow_nd=self._allow_nd) + order, copy = check_reshape_kwargs(kwargs) + + # Return early if reshape is not required + if shape == self.shape: + if copy: + return self.copy() + else: + return self + + # When reducing the number of dimensions, we need to be careful about + # index overflow. This is why we can't simply call + # `np.ravel_multi_index()` followed by `np.unravel_index()` here. + flat_coords = _ravel_coords(self.coords, self.shape, order=order) + if len(shape) == 2: + if order == 'C': + new_coords = divmod(flat_coords, shape[1]) + else: + new_coords = divmod(flat_coords, shape[0])[::-1] + else: + new_coords = np.unravel_index(flat_coords, shape, order=order) + + idx_dtype = self._get_index_dtype(self.coords, maxval=max(shape)) + new_coords = tuple(np.asarray(co, dtype=idx_dtype) for co in new_coords) + + # Handle copy here rather than passing on to the constructor so that no + # copy will be made of `new_coords` regardless. + if copy: + new_data = self.data.copy() + else: + new_data = self.data + + return self.__class__((new_data, new_coords), shape=shape, copy=False) + + reshape.__doc__ = _spbase.reshape.__doc__ + + def _getnnz(self, axis=None): + if axis is None or (axis == 0 and self.ndim == 1): + nnz = len(self.data) + if any(len(idx) != nnz for idx in self.coords): + raise ValueError('all index and data arrays must have the ' + 'same length') + + if self.data.ndim != 1 or any(idx.ndim != 1 for idx in self.coords): + raise ValueError('coordinates and data arrays must be 1-D') + + return int(nnz) + + if axis < 0: + axis += self.ndim + if axis >= self.ndim: + raise ValueError('axis out of bounds') + + return np.bincount(downcast_intp_index(self.coords[1 - axis]), + minlength=self.shape[1 - axis]) + + _getnnz.__doc__ = _spbase._getnnz.__doc__ + + def count_nonzero(self, axis=None): + self.sum_duplicates() + if axis is None: + return np.count_nonzero(self.data) + + if axis < 0: + axis += self.ndim + if axis < 0 or axis >= self.ndim: + raise ValueError('axis out of bounds') + mask = self.data != 0 + coord = self.coords[1 - axis][mask] + return np.bincount(downcast_intp_index(coord), minlength=self.shape[1 - axis]) + + count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ + + def _check(self): + """ Checks data structure for consistency """ + if self.ndim != len(self.coords): + raise ValueError('mismatching number of index arrays for shape; ' + f'got {len(self.coords)}, expected {self.ndim}') + + # index arrays should have integer data types + for i, idx in enumerate(self.coords): + if idx.dtype.kind != 'i': + warn(f'index array {i} has non-integer dtype ({idx.dtype.name})', + stacklevel=3) + + idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.shape)) + self.coords = tuple(np.asarray(idx, dtype=idx_dtype) + for idx in self.coords) + self.data = to_native(self.data) + + if self.nnz > 0: + for i, idx in enumerate(self.coords): + if idx.max() >= self.shape[i]: + raise ValueError(f'axis {i} index {idx.max()} exceeds ' + f'matrix dimension {self.shape[i]}') + if idx.min() < 0: + raise ValueError(f'negative axis {i} index: {idx.min()}') + + def transpose(self, axes=None, copy=False): + if axes is None: + axes = range(self.ndim)[::-1] + elif isinstance(self, sparray): + if not hasattr(axes, "__len__") or len(axes) != self.ndim: + raise ValueError("axes don't match matrix dimensions") + if len(set(axes)) != self.ndim: + raise ValueError("repeated axis in transpose") + elif axes != (1, 0): + raise ValueError("Sparse matrices do not support an 'axes' " + "parameter because swapping dimensions is the " + "only logical permutation.") + + permuted_shape = tuple(self._shape[i] for i in axes) + permuted_coords = tuple(self.coords[i] for i in axes) + return self.__class__((self.data, permuted_coords), + shape=permuted_shape, copy=copy) + + transpose.__doc__ = _spbase.transpose.__doc__ + + def resize(self, *shape) -> None: + shape = check_shape(shape, allow_nd=self._allow_nd) + if self.ndim > 2: + raise ValueError("only 1-D or 2-D input accepted") + if len(shape) > 2: + raise ValueError("shape argument must be 1-D or 2-D") + # Check for added dimensions. + if len(shape) > self.ndim: + flat_coords = _ravel_coords(self.coords, self.shape) + max_size = math.prod(shape) + self.coords = np.unravel_index(flat_coords[:max_size], shape) + self.data = self.data[:max_size] + self._shape = shape + return + + # Check for removed dimensions. + if len(shape) < self.ndim: + tmp_shape = ( + self._shape[:len(shape) - 1] # Original shape without last axis + + (-1,) # Last axis is used to flatten the array + + (1,) * (self.ndim - len(shape)) # Pad with ones + ) + tmp = self.reshape(tmp_shape) + self.coords = tmp.coords[:len(shape)] + self._shape = tmp.shape[:len(shape)] + + # Handle truncation of existing dimensions. + is_truncating = any(old > new for old, new in zip(self.shape, shape)) + if is_truncating: + mask = np.logical_and.reduce([ + idx < size for idx, size in zip(self.coords, shape) + ]) + if not mask.all(): + self.coords = tuple(idx[mask] for idx in self.coords) + self.data = self.data[mask] + + self._shape = shape + + resize.__doc__ = _spbase.resize.__doc__ + + def toarray(self, order=None, out=None): + B = self._process_toarray_args(order, out) + fortran = int(B.flags.f_contiguous) + if not fortran and not B.flags.c_contiguous: + raise ValueError("Output array must be C or F contiguous") + # This handles both 0D and 1D cases correctly regardless of the + # original shape. + if self.ndim == 1: + coo_todense_nd(np.array([1]), self.nnz, self.ndim, + self.coords[0], self.data, B.ravel('A'), fortran) + elif self.ndim == 2: + M, N = self.shape + coo_todense(M, N, self.nnz, self.row, self.col, self.data, + B.ravel('A'), fortran) + else: + if fortran: + strides = np.append(1, np.cumprod(self.shape[:-1])) + else: + strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1) + coords = np.concatenate(self.coords) + coo_todense_nd(strides, self.nnz, self.ndim, + coords, self.data, B.ravel('A'), fortran) + # Note: reshape() doesn't copy here, but does return a new array (view). + return B.reshape(self.shape) + + toarray.__doc__ = _spbase.toarray.__doc__ + + def tocsc(self, copy=False): + """Convert this array/matrix to Compressed Sparse Column format + + Duplicate entries will be summed together. + + Examples + -------- + >>> from numpy import array + >>> from scipy.sparse import coo_array + >>> row = array([0, 0, 1, 3, 1, 0, 0]) + >>> col = array([0, 2, 1, 3, 1, 0, 0]) + >>> data = array([1, 1, 1, 1, 1, 1, 1]) + >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsc() + >>> A.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + if self.ndim != 2: + raise ValueError(f'Cannot convert. CSC format must be 2D. Got {self.ndim}D') + if self.nnz == 0: + return self._csc_container(self.shape, dtype=self.dtype) + else: + from ._csc import csc_array + indptr, indices, data, shape = self._coo_to_compressed(csc_array._swap) + + x = self._csc_container((data, indices, indptr), shape=shape) + if not self.has_canonical_format: + x.sum_duplicates() + return x + + def tocsr(self, copy=False): + """Convert this array/matrix to Compressed Sparse Row format + + Duplicate entries will be summed together. + + Examples + -------- + >>> from numpy import array + >>> from scipy.sparse import coo_array + >>> row = array([0, 0, 1, 3, 1, 0, 0]) + >>> col = array([0, 2, 1, 3, 1, 0, 0]) + >>> data = array([1, 1, 1, 1, 1, 1, 1]) + >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsr() + >>> A.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + if self.ndim > 2: + raise ValueError(f'Cannot convert. CSR must be 1D or 2D. Got {self.ndim}D') + if self.nnz == 0: + return self._csr_container(self.shape, dtype=self.dtype) + else: + from ._csr import csr_array + arrays = self._coo_to_compressed(csr_array._swap, copy=copy) + indptr, indices, data, shape = arrays + + x = self._csr_container((data, indices, indptr), shape=self.shape) + if not self.has_canonical_format: + x.sum_duplicates() + return x + + def _coo_to_compressed(self, swap, copy=False): + """convert (shape, coords, data) to (indptr, indices, data, shape)""" + M, N = swap(self._shape_as_2d) + # convert idx_dtype intc to int32 for pythran. + # tested in scipy/optimize/tests/test__numdiff.py::test_group_columns + idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.nnz, N)) + + if self.ndim == 1: + indices = self.coords[0].copy() if copy else self.coords[0] + nnz = len(indices) + indptr = np.array([0, nnz], dtype=idx_dtype) + data = self.data.copy() if copy else self.data + return indptr, indices, data, self.shape + + # ndim == 2 + major, minor = swap(self.coords) + nnz = len(major) + major = major.astype(idx_dtype, copy=False) + minor = minor.astype(idx_dtype, copy=False) + + indptr = np.empty(M + 1, dtype=idx_dtype) + indices = np.empty_like(minor, dtype=idx_dtype) + data = np.empty_like(self.data, dtype=self.dtype) + + coo_tocsr(M, N, nnz, major, minor, self.data, indptr, indices, data) + return indptr, indices, data, self.shape + + def tocoo(self, copy=False): + if copy: + return self.copy() + else: + return self + + tocoo.__doc__ = _spbase.tocoo.__doc__ + + def todia(self, copy=False): + if self.ndim != 2: + raise ValueError(f'Cannot convert. DIA format must be 2D. Got {self.ndim}D') + self.sum_duplicates() + ks = self.col - self.row # the diagonal for each nonzero + diags, diag_idx = np.unique(ks, return_inverse=True) + + if len(diags) > 100: + # probably undesired, should todia() have a maxdiags parameter? + warn(f"Constructing a DIA matrix with {len(diags)} diagonals " + "is inefficient", + SparseEfficiencyWarning, stacklevel=2) + + #initialize and fill in data array + if self.data.size == 0: + data = np.zeros((0, 0), dtype=self.dtype) + else: + data = np.zeros((len(diags), self.col.max()+1), dtype=self.dtype) + data[diag_idx, self.col] = self.data + + return self._dia_container((data, diags), shape=self.shape) + + todia.__doc__ = _spbase.todia.__doc__ + + def todok(self, copy=False): + if self.ndim > 2: + raise ValueError(f'Cannot convert. DOK must be 1D or 2D. Got {self.ndim}D') + self.sum_duplicates() + dok = self._dok_container(self.shape, dtype=self.dtype) + # ensure that 1d coordinates are not tuples + if self.ndim == 1: + coords = self.coords[0] + else: + coords = zip(*self.coords) + + dok._dict = dict(zip(coords, self.data)) + return dok + + todok.__doc__ = _spbase.todok.__doc__ + + def diagonal(self, k=0): + if self.ndim != 2: + raise ValueError("diagonal requires two dimensions") + rows, cols = self.shape + if k <= -rows or k >= cols: + return np.empty(0, dtype=self.data.dtype) + diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), + dtype=self.dtype) + diag_mask = (self.row + k) == self.col + + if self.has_canonical_format: + row = self.row[diag_mask] + data = self.data[diag_mask] + else: + inds = tuple(idx[diag_mask] for idx in self.coords) + (row, _), data = self._sum_duplicates(inds, self.data[diag_mask]) + diag[row + min(k, 0)] = data + + return diag + + diagonal.__doc__ = _data_matrix.diagonal.__doc__ + + def _setdiag(self, values, k): + if self.ndim != 2: + raise ValueError("setting a diagonal requires two dimensions") + M, N = self.shape + if values.ndim and not len(values): + return + idx_dtype = self.row.dtype + + # Determine which triples to keep and where to put the new ones. + full_keep = self.col - self.row != k + if k < 0: + max_index = min(M+k, N) + if values.ndim: + max_index = min(max_index, len(values)) + keep = np.logical_or(full_keep, self.col >= max_index) + new_row = np.arange(-k, -k + max_index, dtype=idx_dtype) + new_col = np.arange(max_index, dtype=idx_dtype) + else: + max_index = min(M, N-k) + if values.ndim: + max_index = min(max_index, len(values)) + keep = np.logical_or(full_keep, self.row >= max_index) + new_row = np.arange(max_index, dtype=idx_dtype) + new_col = np.arange(k, k + max_index, dtype=idx_dtype) + + # Define the array of data consisting of the entries to be added. + if values.ndim: + new_data = values[:max_index] + else: + new_data = np.empty(max_index, dtype=self.dtype) + new_data[:] = values + + # Update the internal structure. + self.coords = (np.concatenate((self.row[keep], new_row)), + np.concatenate((self.col[keep], new_col))) + self.data = np.concatenate((self.data[keep], new_data)) + self.has_canonical_format = False + + # needed by _data_matrix + def _with_data(self, data, copy=True): + """Returns a matrix with the same sparsity structure as self, + but with different data. By default the index arrays are copied. + """ + if copy: + coords = tuple(idx.copy() for idx in self.coords) + else: + coords = self.coords + return self.__class__((data, coords), shape=self.shape, dtype=data.dtype) + + def sum_duplicates(self) -> None: + """Eliminate duplicate entries by adding them together + + This is an *in place* operation + """ + if self.has_canonical_format: + return + summed = self._sum_duplicates(self.coords, self.data) + self.coords, self.data = summed + self.has_canonical_format = True + + def _sum_duplicates(self, coords, data): + # Assumes coords not in canonical format. + if len(data) == 0: + return coords, data + # Sort coords w.r.t. rows, then cols. This corresponds to C-order, + # which we rely on for argmin/argmax to return the first index in the + # same way that numpy does (in the case of ties). + order = np.lexsort(coords[::-1]) + coords = tuple(idx[order] for idx in coords) + data = data[order] + unique_mask = np.logical_or.reduce([ + idx[1:] != idx[:-1] for idx in coords + ]) + unique_mask = np.append(True, unique_mask) + coords = tuple(idx[unique_mask] for idx in coords) + unique_inds, = np.nonzero(unique_mask) + data = np.add.reduceat(data, downcast_intp_index(unique_inds), dtype=self.dtype) + return coords, data + + def eliminate_zeros(self): + """Remove zero entries from the array/matrix + + This is an *in place* operation + """ + mask = self.data != 0 + self.data = self.data[mask] + self.coords = tuple(idx[mask] for idx in self.coords) + + ####################### + # Arithmetic handlers # + ####################### + + def _add_dense(self, other): + if other.shape != self.shape: + raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') + dtype = upcast_char(self.dtype.char, other.dtype.char) + result = np.array(other, dtype=dtype, copy=True) + fortran = int(result.flags.f_contiguous) + if self.ndim == 1: + coo_todense_nd(np.array([1]), self.nnz, self.ndim, + self.coords[0], self.data, result.ravel('A'), fortran) + elif self.ndim == 2: + M, N = self._shape_as_2d + coo_todense(M, N, self.nnz, self.row, self.col, self.data, + result.ravel('A'), fortran) + else: + if fortran: + strides = np.append(1, np.cumprod(self.shape[:-1])) + else: + strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1) + coords = np.concatenate(self.coords) + coo_todense_nd(strides, self.nnz, self.ndim, + coords, self.data, result.ravel('A'), fortran) + return self._container(result, copy=False) + + + def _add_sparse(self, other): + if self.ndim < 3: + return self.tocsr()._add_sparse(other) + + if other.shape != self.shape: + raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') + other = self.__class__(other) + new_data = np.concatenate((self.data, other.data)) + new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1)) + A = self.__class__((new_data, new_coords), shape=self.shape) + return A + + + def _sub_sparse(self, other): + if self.ndim < 3: + return self.tocsr()._sub_sparse(other) + + if other.shape != self.shape: + raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') + other = self.__class__(other) + new_data = np.concatenate((self.data, -other.data)) + new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1)) + A = coo_array((new_data, new_coords), shape=self.shape) + return A + + + def _matmul_vector(self, other): + if self.ndim > 2: + result = np.zeros(math.prod(self.shape[:-1]), + dtype=upcast_char(self.dtype.char, other.dtype.char)) + shape = np.array(self.shape) + strides = np.append(np.cumprod(shape[:-1][::-1])[::-1][1:], 1) + coords = np.concatenate(self.coords) + coo_matvec_nd(self.nnz, len(self.shape), strides, coords, self.data, + other, result) + + result = result.reshape(self.shape[:-1]) + return result + + # self.ndim <= 2 + result_shape = self.shape[0] if self.ndim > 1 else 1 + result = np.zeros(result_shape, + dtype=upcast_char(self.dtype.char, other.dtype.char)) + if self.ndim == 2: + col = self.col + row = self.row + elif self.ndim == 1: + col = self.coords[0] + row = np.zeros_like(col) + else: + raise NotImplementedError( + f"coo_matvec not implemented for ndim={self.ndim}") + + coo_matvec(self.nnz, row, col, self.data, other, result) + # Array semantics return a scalar here, not a single-element array. + if isinstance(self, sparray) and result_shape == 1: + return result[0] + return result + + + def _rmatmul_dispatch(self, other): + if isscalarlike(other): + return self._mul_scalar(other) + else: + # Don't use asarray unless we have to + try: + o_ndim = other.ndim + except AttributeError: + other = np.asarray(other) + o_ndim = other.ndim + perm = tuple(range(o_ndim)[:-2]) + tuple(range(o_ndim)[-2:][::-1]) + tr = other.transpose(perm) + + s_ndim = self.ndim + perm = tuple(range(s_ndim)[:-2]) + tuple(range(s_ndim)[-2:][::-1]) + ret = self.transpose(perm)._matmul_dispatch(tr) + if ret is NotImplemented: + return NotImplemented + + if s_ndim == 1 or o_ndim == 1: + perm = range(ret.ndim) + else: + perm = tuple(range(ret.ndim)[:-2]) + tuple(range(ret.ndim)[-2:][::-1]) + return ret.transpose(perm) + + + def _matmul_dispatch(self, other): + if isscalarlike(other): + return self.multiply(other) + + if not (issparse(other) or isdense(other)): + # If it's a list or whatever, treat it like an array + other_a = np.asanyarray(other) + + if other_a.ndim == 0 and other_a.dtype == np.object_: + # Not interpretable as an array; return NotImplemented so that + # other's __rmatmul__ can kick in if that's implemented. + return NotImplemented + + try: + other.shape + except AttributeError: + other = other_a + + if self.ndim < 3 and other.ndim < 3: + return _spbase._matmul_dispatch(self, other) + + N = self.shape[-1] + err_prefix = "matmul: dimension mismatch with signature" + if other.__class__ is np.ndarray: + if other.shape == (N,): + return self._matmul_vector(other) + if other.shape == (N, 1): + result = self._matmul_vector(other.ravel()) + return result.reshape(*self.shape[:-1], 1) + if other.ndim == 1: + msg = f"{err_prefix} (n,k={N}),(k={other.shape[0]},)->(n,)" + raise ValueError(msg) + if other.shape[-2] == N: + # check for batch dimensions compatibility + batch_shape_A = self.shape[:-2] + batch_shape_B = other.shape[:-2] + if batch_shape_A != batch_shape_B: + try: + # This will raise an error if the shapes are not broadcastable + np.broadcast_shapes(batch_shape_A, batch_shape_B) + except ValueError: + raise ValueError("Batch dimensions are not broadcastable") + + return self._matmul_multivector(other) + else: + raise ValueError( + f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)" + ) + + + if isscalarlike(other): + # scalar value + return self._mul_scalar(other) + + if issparse(other): + self_is_1d = self.ndim == 1 + other_is_1d = other.ndim == 1 + + # reshape to 2-D if self or other is 1-D + if self_is_1d: + self = self.reshape(self._shape_as_2d) # prepend 1 to shape + + if other_is_1d: + other = other.reshape((other.shape[0], 1)) # append 1 to shape + + # Check if the inner dimensions match for matrix multiplication + if N != other.shape[-2]: + raise ValueError( + f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)" + ) + + # If A or B has more than 2 dimensions, check for + # batch dimensions compatibility + if self.ndim > 2 or other.ndim > 2: + batch_shape_A = self.shape[:-2] + batch_shape_B = other.shape[:-2] + if batch_shape_A != batch_shape_B: + try: + # This will raise an error if the shapes are not broadcastable + np.broadcast_shapes(batch_shape_A, batch_shape_B) + except ValueError: + raise ValueError("Batch dimensions are not broadcastable") + + result = self._matmul_sparse(other) + + # reshape back if a or b were originally 1-D + if self_is_1d: + # if self was originally 1-D, reshape result accordingly + result = result.reshape(tuple(result.shape[:-2]) + + tuple(result.shape[-1:])) + if other_is_1d: + result = result.reshape(result.shape[:-1]) + return result + + + def _matmul_multivector(self, other): + result_dtype = upcast_char(self.dtype.char, other.dtype.char) + if self.ndim >= 3 or other.ndim >= 3: + # if self has shape (N,), reshape to (1,N) + if self.ndim == 1: + result = self.reshape(1, self.shape[0])._matmul_multivector(other) + return result.reshape(tuple(other.shape[:-2]) + tuple(other.shape[-1:])) + + broadcast_shape = np.broadcast_shapes(self.shape[:-2], other.shape[:-2]) + self_shape = broadcast_shape + self.shape[-2:] + other_shape = broadcast_shape + other.shape[-2:] + + self = self._broadcast_to(self_shape) + other = np.broadcast_to(other, other_shape) + result_shape = broadcast_shape + self.shape[-2:-1] + other.shape[-1:] + result = np.zeros(result_shape, dtype=result_dtype) + coo_matmat_dense_nd(self.nnz, len(self.shape), other.shape[-1], + np.array(other_shape), np.array(result_shape), + np.concatenate(self.coords), + self.data, other.ravel('C'), result) + return result + + if self.ndim == 2: + result_shape = (self.shape[0], other.shape[1]) + col = self.col + row = self.row + elif self.ndim == 1: + result_shape = (other.shape[1],) + col = self.coords[0] + row = np.zeros_like(col) + result = np.zeros(result_shape, dtype=result_dtype) + coo_matmat_dense(self.nnz, other.shape[-1], row, col, + self.data, other.ravel('C'), result) + return result.view(type=type(other)) + + + def dot(self, other): + """Return the dot product of two arrays. + + Strictly speaking a dot product involves two vectors. + But in the sense that an array with ndim >= 1 is a collection + of vectors, the function computes the collection of dot products + between each vector in the first array with each vector in the + second array. The axis upon which the sum of products is performed + is the last axis of the first array and the second to last axis of + the second array. If the second array is 1-D, the last axis is used. + + Thus, if both arrays are 1-D, the inner product is returned. + If both are 2-D, we have matrix multiplication. If `other` is 1-D, + the sum product is taken along the last axis of each array. If + `other` is N-D for N>=2, the sum product is over the last axis of + the first array and the second-to-last axis of the second array. + + Parameters + ---------- + other : array_like (dense or sparse) + Second array + + Returns + ------- + output : array (sparse or dense) + The dot product of this array with `other`. + It will be dense/sparse if `other` is dense/sparse. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import coo_array + >>> A = coo_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) + >>> v = np.array([1, 0, -1]) + >>> A.dot(v) + array([ 1, -3, -1], dtype=int64) + + For 2-D arrays it is the matrix product: + + >>> A = coo_array([[1, 0], [0, 1]]) + >>> B = coo_array([[4, 1], [2, 2]]) + >>> A.dot(B).toarray() + array([[4, 1], + [2, 2]]) + + For 3-D arrays the shape extends unused axes by other unused axes. + + >>> A = coo_array(np.arange(3*4*5*6)).reshape((3,4,5,6)) + >>> B = coo_array(np.arange(3*4*5*6)).reshape((5,4,6,3)) + >>> A.dot(B).shape + (3, 4, 5, 5, 4, 3) + """ + if not (issparse(other) or isdense(other) or isscalarlike(other)): + # If it's a list or whatever, treat it like an array + o_array = np.asanyarray(other) + + if o_array.ndim == 0 and o_array.dtype == np.object_: + raise TypeError(f"dot argument not supported type: '{type(other)}'") + try: + other.shape + except AttributeError: + other = o_array + + if self.ndim < 3 and (np.isscalar(other) or other.ndim<3): + return _spbase.dot(self, other) + # Handle scalar multiplication + if np.isscalar(other): + return self * other + if isdense(other): + return self._dense_dot(other) + elif other.format != "coo": + raise TypeError("input must be a COO matrix/array") + elif self.ndim == 1 and other.ndim == 1: + # Handle inner product of vectors (1-D arrays) + if self.shape[0] != other.shape[0]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for inner product") + return self @ other + elif self.ndim == 2 and other.ndim == 2: + # Handle matrix multiplication (2-D arrays) + if self.shape[1] != other.shape[0]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for matmul") + return self @ other + else: + return self._sparse_dot(other) + + + def _sparse_dot(self, other): + self_is_1d = self.ndim == 1 + other_is_1d = other.ndim == 1 + + # reshape to 2-D if self or other is 1-D + if self_is_1d: + self = self.reshape(self._shape_as_2d) # prepend 1 to shape + if other_is_1d: + other = other.reshape((other.shape[0], 1)) # append 1 to shape + + if self.shape[-1] != other.shape[-2]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for n-D dot") + + # Prepare the tensors for dot operation + # Ravel non-reduced axes coordinates + self_raveled_coords = _ravel_non_reduced_axes(self.coords, + self.shape, [self.ndim-1]) + other_raveled_coords = _ravel_non_reduced_axes(other.coords, + other.shape, [other.ndim-2]) + + # Get the shape of the non-reduced axes + self_nonreduced_shape = self.shape[:-1] + other_nonreduced_shape = other.shape[:-2] + other.shape[-1:] + + # Create 2D coords arrays + ravel_coords_shape_self = (math.prod(self_nonreduced_shape), self.shape[-1]) + ravel_coords_shape_other = (other.shape[-2], math.prod(other_nonreduced_shape)) + + self_2d_coords = (self_raveled_coords, self.coords[-1]) + other_2d_coords = (other.coords[-2], other_raveled_coords) + + self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self) + other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other) + + prod = (self_2d @ other_2d).tocoo() # routes via 2-D CSR + + # Combine the shapes of the non-reduced axes + combined_shape = self_nonreduced_shape + other_nonreduced_shape + + # Unravel the 2D coordinates to get multi-dimensional coordinates + shapes = (self_nonreduced_shape, other_nonreduced_shape) + prod_coords = [] + for c, s in zip(prod.coords, shapes): + prod_coords.extend(np.unravel_index(c, s)) + + prod_arr = coo_array((prod.data, prod_coords), combined_shape) + + # reshape back if a or b were originally 1-D + # TODO: Move this logic before computation of prod_coords for efficiency + if self_is_1d: + prod_arr = prod_arr.reshape(combined_shape[1:]) + if other_is_1d: + prod_arr = prod_arr.reshape(combined_shape[:-1]) + + return prod_arr + + def _dense_dot(self, other): + self_is_1d = self.ndim == 1 + other_is_1d = other.ndim == 1 + + # reshape to 2-D if self or other is 1-D + if self_is_1d: + self = self.reshape(self._shape_as_2d) # prepend 1 to shape + if other_is_1d: + other = other.reshape((other.shape[0], 1)) # append 1 to shape + + if self.shape[-1] != other.shape[-2]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for n-D dot") + + new_shape_self = ( + self.shape[:-1] + (1,) * (len(other.shape) - 1) + self.shape[-1:] + ) + new_shape_other = (1,) * (len(self.shape) - 1) + other.shape + + result_shape = self.shape[:-1] + other.shape[:-2] + other.shape[-1:] + result = self.reshape(new_shape_self) @ other.reshape(new_shape_other) + prod_arr = result.reshape(result_shape) + + # reshape back if a or b were originally 1-D + if self_is_1d: + prod_arr = prod_arr.reshape(result_shape[1:]) + if other_is_1d: + prod_arr = prod_arr.reshape(result_shape[:-1]) + + return prod_arr + + def tensordot(self, other, axes=2): + """Return the tensordot product with another array along the given axes. + + The tensordot differs from dot and matmul in that any axis can be + chosen for each of the first and second array and the sum of the + products is computed just like for matrix multiplication, only not + just for the rows of the first times the columns of the second. It + takes the dot product of the collection of vectors along the specified + axes. Here we can even take the sum of the products along two or even + more axes if desired. So, tensordot is a dot product computation + applied to arrays of any dimension >= 1. It is like matmul but over + arbitrary axes for each matrix. + + Given two tensors, `a` and `b`, and the desired axes specified as a + 2-tuple/list/array containing two sequences of axis numbers, + ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements + (components) over the axes specified by ``a_axes`` and ``b_axes``. + The `axes` input can be a single non-negative integer, ``N``; + if it is, then the last ``N`` dimensions of `a` and the first + ``N`` dimensions of `b` are summed over. + + Parameters + ---------- + a, b : array_like + Tensors to "dot". + + axes : int or (2,) array_like + * integer_like + If an int N, sum over the last N axes of `a` and the first N axes + of `b` in order. The sizes of the corresponding axes must match. + * (2,) array_like + A 2-tuple of sequences of axes to be summed over, the first applying + to `a`, the second to `b`. The sequences must be the same length. + The shape of the corresponding axes must match between `a` and `b`. + + Returns + ------- + output : coo_array + The tensor dot product of this array with `other`. + It will be dense/sparse if `other` is dense/sparse. + + See Also + -------- + dot + + Examples + -------- + >>> import numpy as np + >>> import scipy.sparse + >>> A = scipy.sparse.coo_array([[[2, 3], [0, 0]], [[0, 1], [0, 5]]]) + >>> A.shape + (2, 2, 2) + + Integer axes N are shorthand for (range(-N, 0), range(0, N)): + + >>> A.tensordot(A, axes=1).toarray() + array([[[[ 4, 9], + [ 0, 15]], + + [[ 0, 0], + [ 0, 0]]], + + + [[[ 0, 1], + [ 0, 5]], + + [[ 0, 5], + [ 0, 25]]]]) + >>> A.tensordot(A, axes=2).toarray() + array([[ 4, 6], + [ 0, 25]]) + >>> A.tensordot(A, axes=3) + array(39) + + Using tuple for axes: + + >>> a = scipy.sparse.coo_array(np.arange(60).reshape(3,4,5)) + >>> b = np.arange(24).reshape(4,3,2) + >>> c = a.tensordot(b, axes=([1,0],[0,1])) + >>> c.shape + (5, 2) + >>> c + array([[4400, 4730], + [4532, 4874], + [4664, 5018], + [4796, 5162], + [4928, 5306]]) + + """ + if not isdense(other) and not issparse(other): + # If it's a list or whatever, treat it like an array + other_array = np.asanyarray(other) + + if other_array.ndim == 0 and other_array.dtype == np.object_: + raise TypeError(f"tensordot arg not supported type: '{type(other)}'") + try: + other.shape + except AttributeError: + other = other_array + + axes_self, axes_other = _process_axes(self.ndim, other.ndim, axes) + + # Check for shape compatibility along specified axes + if any(self.shape[ax] != other.shape[bx] + for ax, bx in zip(axes_self, axes_other)): + raise ValueError("sizes of the corresponding axes must match") + + if isdense(other): + return self._dense_tensordot(other, axes_self, axes_other) + else: + return self._sparse_tensordot(other, axes_self, axes_other) + + + def _sparse_tensordot(self, other, axes_self, axes_other): + ndim_self = len(self.shape) + ndim_other = len(other.shape) + + # Prepare the tensors for tensordot operation + # Ravel non-reduced axes coordinates + self_non_red_coords = _ravel_non_reduced_axes(self.coords, self.shape, + axes_self) + self_reduced_coords = np.ravel_multi_index( + [self.coords[ax] for ax in axes_self], [self.shape[ax] for ax in axes_self]) + other_non_red_coords = _ravel_non_reduced_axes(other.coords, other.shape, + axes_other) + other_reduced_coords = np.ravel_multi_index( + [other.coords[a] for a in axes_other], [other.shape[a] for a in axes_other] + ) + # Get the shape of the non-reduced axes + self_nonreduced_shape = tuple(self.shape[ax] for ax in range(ndim_self) + if ax not in axes_self) + other_nonreduced_shape = tuple(other.shape[ax] for ax in range(ndim_other) + if ax not in axes_other) + + # Create 2D coords arrays + ravel_coords_shape_self = (math.prod(self_nonreduced_shape), + math.prod([self.shape[ax] for ax in axes_self])) + ravel_coords_shape_other = (math.prod([other.shape[ax] for ax in axes_other]), + math.prod(other_nonreduced_shape)) + + self_2d_coords = (self_non_red_coords, self_reduced_coords) + other_2d_coords = (other_reduced_coords, other_non_red_coords) + + self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self) + other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other) + + # Perform matrix multiplication (routed via 2-D CSR) + prod = (self_2d @ other_2d).tocoo() + + # Combine the shapes of the non-contracted axes + combined_shape = self_nonreduced_shape + other_nonreduced_shape + + # Unravel the 2D coordinates to get multi-dimensional coordinates + coords = [] + for c, s in zip(prod.coords, (self_nonreduced_shape, other_nonreduced_shape)): + if s: + coords.extend(np.unravel_index(c, s)) + + if coords == []: # if result is scalar + return sum(prod.data) + + # Construct the resulting COO array with combined coordinates and shape + return coo_array((prod.data, coords), shape=combined_shape) + + + def _dense_tensordot(self, other, axes_self, axes_other): + ndim_self = len(self.shape) + ndim_other = len(other.shape) + + non_reduced_axes_self = [ax for ax in range(ndim_self) if ax not in axes_self] + reduced_shape_self = [self.shape[s] for s in axes_self] + non_reduced_shape_self = [self.shape[s] for s in non_reduced_axes_self] + + non_reduced_axes_other = [ax for ax in range(ndim_other) + if ax not in axes_other] + reduced_shape_other = [other.shape[s] for s in axes_other] + non_reduced_shape_other = [other.shape[s] for s in non_reduced_axes_other] + + permute_self = non_reduced_axes_self + axes_self + permute_other = ( + non_reduced_axes_other[:-1] + axes_other + non_reduced_axes_other[-1:] + ) + self = self.transpose(permute_self) + other = np.transpose(other, permute_other) + + reshape_self = (*non_reduced_shape_self, math.prod(reduced_shape_self)) + reshape_other = (*non_reduced_shape_other[:-1], math.prod(reduced_shape_other), + *non_reduced_shape_other[-1:]) + + return self.reshape(reshape_self).dot(other.reshape(reshape_other)) + + + def _matmul_sparse(self, other): + """ + Perform sparse-sparse matrix multiplication for two n-D COO arrays. + The method converts input n-D arrays to 2-D block array format, + uses csr_matmat to multiply them, and then converts the + result back to n-D COO array. + + Parameters: + self (COO): The first n-D sparse array in COO format. + other (COO): The second n-D sparse array in COO format. + + Returns: + prod (COO): The resulting n-D sparse array after multiplication. + """ + if self.ndim < 3 and other.ndim < 3: + return _spbase._matmul_sparse(self, other) + + # Get the shapes of self and other + self_shape = self.shape + other_shape = other.shape + + # Determine the new shape to broadcast self and other + broadcast_shape = np.broadcast_shapes(self_shape[:-2], other_shape[:-2]) + self_new_shape = tuple(broadcast_shape) + self_shape[-2:] + other_new_shape = tuple(broadcast_shape) + other_shape[-2:] + + self_broadcasted = self._broadcast_to(self_new_shape) + other_broadcasted = other._broadcast_to(other_new_shape) + + # Convert n-D COO arrays to 2-D block diagonal arrays + self_block_diag = _block_diag(self_broadcasted) + other_block_diag = _block_diag(other_broadcasted) + + # Use csr_matmat to perform sparse matrix multiplication + prod_block_diag = (self_block_diag @ other_block_diag).tocoo() + + # Convert the 2-D block diagonal array back to n-D + return _extract_block_diag( + prod_block_diag, + shape=(*broadcast_shape, self.shape[-2], other.shape[-1]), + ) + + + def _broadcast_to(self, new_shape, copy=False): + if self.shape == new_shape: + return self.copy() if copy else self + + old_shape = self.shape + + # Check if the new shape is compatible for broadcasting + if len(new_shape) < len(old_shape): + raise ValueError("New shape must have at least as many dimensions" + " as the current shape") + + # Add leading ones to shape to ensure same length as `new_shape` + shape = (1,) * (len(new_shape) - len(old_shape)) + tuple(old_shape) + + # Ensure the old shape can be broadcast to the new shape + if any((o != 1 and o != n) for o, n in zip(shape, new_shape)): + raise ValueError(f"current shape {old_shape} cannot be " + "broadcast to new shape {new_shape}") + + # Reshape the COO array to match the new dimensions + self = self.reshape(shape) + + idx_dtype = get_index_dtype(self.coords, maxval=max(new_shape)) + coords = self.coords + new_data = self.data + new_coords = coords[-1:] # Copy last coordinate to start + cum_repeat = 1 # Cumulative repeat factor for broadcasting + + if shape[-1] != new_shape[-1]: # broadcasting the n-th (col) dimension + repeat_count = new_shape[-1] + cum_repeat *= repeat_count + new_data = np.tile(new_data, repeat_count) + new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), self.nnz) + new_coords = (new_dim,) + + for i in range(-2, -(len(shape)+1), -1): + if shape[i] != new_shape[i]: + repeat_count = new_shape[i] # number of times to repeat data, coords + cum_repeat *= repeat_count # update cumulative repeat factor + nnz = len(new_data) # Number of non-zero elements so far + + # Tile data and coordinates to match the new repeat count + new_data = np.tile(new_data, repeat_count) + new_coords = tuple(np.tile(new_coords[i+1:], repeat_count)) + + # Create new dimensions and stack them + new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), nnz) + new_coords = (new_dim,) + new_coords + else: + # If no broadcasting needed, tile the coordinates + new_dim = np.tile(coords[i], cum_repeat) + new_coords = (new_dim,) + new_coords + + return coo_array((new_data, new_coords), new_shape) + + +def _block_diag(self): + """ + Converts an N-D COO array into a 2-D COO array in block diagonal form. + + Parameters: + self (coo_array): An N-Dimensional COO sparse array. + + Returns: + coo_array: A 2-Dimensional COO sparse array in block diagonal form. + """ + if self.ndim<2: + raise ValueError("array must have atleast dim=2") + num_blocks = math.prod(self.shape[:-2]) + n_col = self.shape[-1] + n_row = self.shape[-2] + res_arr = self.reshape((num_blocks, n_row, n_col)) + new_coords = ( + res_arr.coords[1] + res_arr.coords[0] * res_arr.shape[1], + res_arr.coords[2] + res_arr.coords[0] * res_arr.shape[2], + ) + + new_shape = (num_blocks * n_row, num_blocks * n_col) + return coo_array((self.data, tuple(new_coords)), shape=new_shape) + + +def _extract_block_diag(self, shape): + n_row, n_col = shape[-2], shape[-1] + + # Extract data and coordinates from the block diagonal COO array + data = self.data + row, col = self.row, self.col + + # Initialize new coordinates array + new_coords = np.empty((len(shape), self.nnz), dtype=int) + + # Calculate within-block indices + new_coords[-2] = row % n_row + new_coords[-1] = col % n_col + + # Calculate coordinates for higher dimensions + temp_block_idx = row // n_row + for i in range(len(shape) - 3, -1, -1): + size = shape[i] + new_coords[i] = temp_block_idx % size + temp_block_idx = temp_block_idx // size + + # Create the new COO array with the original n-D shape + return coo_array((data, tuple(new_coords)), shape=shape) + + +def _process_axes(ndim_a, ndim_b, axes): + if isinstance(axes, int): + if axes < 1 or axes > min(ndim_a, ndim_b): + raise ValueError("axes integer is out of bounds for input arrays") + axes_a = list(range(ndim_a - axes, ndim_a)) + axes_b = list(range(axes)) + elif isinstance(axes, (tuple, list)): + if len(axes) != 2: + raise ValueError("axes must be a tuple/list of length 2") + axes_a, axes_b = axes + if len(axes_a) != len(axes_b): + raise ValueError("axes lists/tuples must be of the same length") + if any(ax >= ndim_a or ax < -ndim_a for ax in axes_a) or \ + any(bx >= ndim_b or bx < -ndim_b for bx in axes_b): + raise ValueError("axes indices are out of bounds for input arrays") + else: + raise TypeError("axes must be an integer or a tuple/list of integers") + + axes_a = [axis + ndim_a if axis < 0 else axis for axis in axes_a] + axes_b = [axis + ndim_b if axis < 0 else axis for axis in axes_b] + return axes_a, axes_b + + +def _ravel_non_reduced_axes(coords, shape, axes): + ndim = len(shape) + non_reduced_axes = [ax for ax in range(ndim) if ax not in axes] + + if not non_reduced_axes: + # Return an array with one row + return np.zeros_like(coords[0]) + + # Extract the shape of the non-reduced axes + non_reduced_shape = [shape[ax] for ax in non_reduced_axes] + + # Extract the coordinates of the non-reduced axes + non_reduced_coords = tuple(coords[idx] for idx in non_reduced_axes) + + # Ravel the coordinates into 1D + return np.ravel_multi_index(non_reduced_coords, non_reduced_shape) + + +def _ravel_coords(coords, shape, order='C'): + """Like np.ravel_multi_index, but avoids some overflow issues.""" + if len(coords) == 1: + return coords[0] + # Handle overflow as in https://github.com/scipy/scipy/pull/9132 + if len(coords) == 2: + nrows, ncols = shape + row, col = coords + if order == 'C': + maxval = (ncols * max(0, nrows - 1) + max(0, ncols - 1)) + idx_dtype = get_index_dtype(maxval=maxval) + return np.multiply(ncols, row, dtype=idx_dtype) + col + elif order == 'F': + maxval = (nrows * max(0, ncols - 1) + max(0, nrows - 1)) + idx_dtype = get_index_dtype(maxval=maxval) + return np.multiply(nrows, col, dtype=idx_dtype) + row + else: + raise ValueError("'order' must be 'C' or 'F'") + return np.ravel_multi_index(coords, shape, order=order) + + +def isspmatrix_coo(x): + """Is `x` of coo_matrix type? + + Parameters + ---------- + x + object to check for being a coo matrix + + Returns + ------- + bool + True if `x` is a coo matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import coo_array, coo_matrix, csr_matrix, isspmatrix_coo + >>> isspmatrix_coo(coo_matrix([[5]])) + True + >>> isspmatrix_coo(coo_array([[5]])) + False + >>> isspmatrix_coo(csr_matrix([[5]])) + False + """ + return isinstance(x, coo_matrix) + + +# This namespace class separates array from matrix with isinstance +class coo_array(_coo_base, sparray): + """ + A sparse array in COOrdinate format. + + Also known as the 'ijv' or 'triplet' format. + + This can be instantiated in several ways: + coo_array(D) + where D is an ndarray + + coo_array(S) + with another sparse array or matrix S (equivalent to S.tocoo()) + + coo_array(shape, [dtype]) + to construct an empty sparse array with shape `shape` + dtype is optional, defaulting to dtype='d'. + + coo_array((data, coords), [shape]) + to construct from existing data and index arrays: + 1. data[:] the entries of the sparse array, in any order + 2. coords[i][:] the axis-i coordinates of the data entries + + Where ``A[coords] = data``, and coords is a tuple of index arrays. + When shape is not specified, it is inferred from the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the sparse array + shape : tuple of integers + Shape of the sparse array + ndim : int + Number of dimensions of the sparse array + nnz + size + data + COO format data array of the sparse array + coords + COO format tuple of index arrays + has_canonical_format : bool + Whether the matrix has sorted coordinates and no duplicates + format + T + + Notes + ----- + + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the COO format + - facilitates fast conversion among sparse formats + - permits duplicate entries (see example) + - very fast conversion to and from CSR/CSC formats + + Disadvantages of the COO format + - does not directly support: + + arithmetic operations + + slicing + + Intended Usage + - COO is a fast format for constructing sparse arrays + - Once a COO array has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - By default when converting to CSR or CSC format, duplicate (i,j) + entries will be summed together. This facilitates efficient + construction of finite element matrices and the like. (see example) + + Canonical format + - Entries and coordinates sorted by row, then column. + - There are no duplicate entries (i.e. duplicate (i,j) locations) + - Data arrays MAY have explicit zeros. + + Examples + -------- + + >>> # Constructing an empty sparse array + >>> import numpy as np + >>> from scipy.sparse import coo_array + >>> coo_array((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> # Constructing a sparse array using ijv format + >>> row = np.array([0, 3, 1, 0]) + >>> col = np.array([0, 3, 1, 2]) + >>> data = np.array([4, 5, 7, 9]) + >>> coo_array((data, (row, col)), shape=(4, 4)).toarray() + array([[4, 0, 9, 0], + [0, 7, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 5]]) + + >>> # Constructing a sparse array with duplicate coordinates + >>> row = np.array([0, 0, 1, 3, 1, 0, 0]) + >>> col = np.array([0, 2, 1, 3, 1, 0, 0]) + >>> data = np.array([1, 1, 1, 1, 1, 1, 1]) + >>> coo = coo_array((data, (row, col)), shape=(4, 4)) + >>> # Duplicate coordinates are maintained until implicitly or explicitly summed + >>> np.max(coo.data) + 1 + >>> coo.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + + +class coo_matrix(spmatrix, _coo_base): + """ + A sparse matrix in COOrdinate format. + + Also known as the 'ijv' or 'triplet' format. + + This can be instantiated in several ways: + coo_matrix(D) + where D is a 2-D ndarray + + coo_matrix(S) + with another sparse array or matrix S (equivalent to S.tocoo()) + + coo_matrix((M, N), [dtype]) + to construct an empty matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + coo_matrix((data, (i, j)), [shape=(M, N)]) + to construct from three arrays: + 1. data[:] the entries of the matrix, in any order + 2. i[:] the row indices of the matrix entries + 3. j[:] the column indices of the matrix entries + + Where ``A[i[k], j[k]] = data[k]``. When shape is not + specified, it is inferred from the index arrays + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + COO format data array of the matrix + row + COO format row index array of the matrix + col + COO format column index array of the matrix + has_canonical_format : bool + Whether the matrix has sorted indices and no duplicates + format + T + + Notes + ----- + + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the COO format + - facilitates fast conversion among sparse formats + - permits duplicate entries (see example) + - very fast conversion to and from CSR/CSC formats + + Disadvantages of the COO format + - does not directly support: + + arithmetic operations + + slicing + + Intended Usage + - COO is a fast format for constructing sparse matrices + - Once a COO matrix has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - By default when converting to CSR or CSC format, duplicate (i,j) + entries will be summed together. This facilitates efficient + construction of finite element matrices and the like. (see example) + + Canonical format + - Entries and coordinates sorted by row, then column. + - There are no duplicate entries (i.e. duplicate (i,j) locations) + - Data arrays MAY have explicit zeros. + + Examples + -------- + + >>> # Constructing an empty matrix + >>> import numpy as np + >>> from scipy.sparse import coo_matrix + >>> coo_matrix((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> # Constructing a matrix using ijv format + >>> row = np.array([0, 3, 1, 0]) + >>> col = np.array([0, 3, 1, 2]) + >>> data = np.array([4, 5, 7, 9]) + >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray() + array([[4, 0, 9, 0], + [0, 7, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 5]]) + + >>> # Constructing a matrix with duplicate coordinates + >>> row = np.array([0, 0, 1, 3, 1, 0, 0]) + >>> col = np.array([0, 2, 1, 3, 1, 0, 0]) + >>> data = np.array([1, 1, 1, 1, 1, 1, 1]) + >>> coo = coo_matrix((data, (row, col)), shape=(4, 4)) + >>> # Duplicate coordinates are maintained until implicitly or explicitly summed + >>> np.max(coo.data) + 1 + >>> coo.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + + def __setstate__(self, state): + if 'coords' not in state: + # For retro-compatibility with the previous attributes + # storing nnz coordinates for 2D COO matrix. + state['coords'] = (state.pop('row'), state.pop('col')) + self.__dict__.update(state) diff --git a/shared/package-files/3a/3a33d15250fdc17af45df0619f739c6f0a5ecbb41dd07d493f21de6647afc527/gamma_functions.py b/shared/package-files/3a/3a33d15250fdc17af45df0619f739c6f0a5ecbb41dd07d493f21de6647afc527/gamma_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..284811fda2461a23ececdeee1510dc5d829cd3e1 --- /dev/null +++ b/shared/package-files/3a/3a33d15250fdc17af45df0619f739c6f0a5ecbb41dd07d493f21de6647afc527/gamma_functions.py @@ -0,0 +1,1344 @@ +from math import prod + +from sympy.core import Add, S, Dummy, expand_func +from sympy.core.expr import Expr +from sympy.core.function import Function, ArgumentIndexError, PoleError +from sympy.core.logic import fuzzy_and, fuzzy_not +from sympy.core.numbers import Rational, pi, oo, I +from sympy.core.power import Pow +from sympy.functions.special.zeta_functions import zeta +from sympy.functions.special.error_functions import erf, erfc, Ei +from sympy.functions.elementary.complexes import re, unpolarify +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.integers import ceiling, floor +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import sin, cos, cot +from sympy.functions.combinatorial.numbers import bernoulli, harmonic +from sympy.functions.combinatorial.factorials import factorial, rf, RisingFactorial +from sympy.utilities.misc import as_int + +from mpmath import mp, workprec +from mpmath.libmp.libmpf import prec_to_dps + +def intlike(n): + try: + as_int(n, strict=False) + return True + except ValueError: + return False + +############################################################################### +############################ COMPLETE GAMMA FUNCTION ########################## +############################################################################### + +class gamma(Function): + r""" + The gamma function + + .. math:: + \Gamma(x) := \int^{\infty}_{0} t^{x-1} e^{-t} \mathrm{d}t. + + Explanation + =========== + + The ``gamma`` function implements the function which passes through the + values of the factorial function (i.e., $\Gamma(n) = (n - 1)!$ when n is + an integer). More generally, $\Gamma(z)$ is defined in the whole complex + plane except at the negative integers where there are simple poles. + + Examples + ======== + + >>> from sympy import S, I, pi, gamma + >>> from sympy.abc import x + + Several special values are known: + + >>> gamma(1) + 1 + >>> gamma(4) + 6 + >>> gamma(S(3)/2) + sqrt(pi)/2 + + The ``gamma`` function obeys the mirror symmetry: + + >>> from sympy import conjugate + >>> conjugate(gamma(x)) + gamma(conjugate(x)) + + Differentiation with respect to $x$ is supported: + + >>> from sympy import diff + >>> diff(gamma(x), x) + gamma(x)*polygamma(0, x) + + Series expansion is also supported: + + >>> from sympy import series + >>> series(gamma(x), x, 0, 3) + 1/x - EulerGamma + x*(EulerGamma**2/2 + pi**2/12) + x**2*(-EulerGamma*pi**2/12 - zeta(3)/3 - EulerGamma**3/6) + O(x**3) + + We can numerically evaluate the ``gamma`` function to arbitrary precision + on the whole complex plane: + + >>> gamma(pi).evalf(40) + 2.288037795340032417959588909060233922890 + >>> gamma(1+I).evalf(20) + 0.49801566811835604271 - 0.15494982830181068512*I + + See Also + ======== + + lowergamma: Lower incomplete gamma function. + uppergamma: Upper incomplete gamma function. + polygamma: Polygamma function. + loggamma: Log Gamma function. + digamma: Digamma function. + trigamma: Trigamma function. + beta: Euler Beta function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gamma_function + .. [2] https://dlmf.nist.gov/5 + .. [3] https://mathworld.wolfram.com/GammaFunction.html + .. [4] https://functions.wolfram.com/GammaBetaErf/Gamma/ + + """ + + unbranched = True + _singularities = (S.ComplexInfinity,) + + def fdiff(self, argindex=1): + if argindex == 1: + return self.func(self.args[0])*polygamma(0, self.args[0]) + else: + raise ArgumentIndexError(self, argindex) + + @classmethod + def eval(cls, arg): + if arg.is_Number: + if arg is S.NaN: + return S.NaN + elif arg is oo: + return oo + elif intlike(arg): + if arg.is_positive: + return factorial(arg - 1) + else: + return S.ComplexInfinity + elif arg.is_Rational: + if arg.q == 2: + n = abs(arg.p) // arg.q + + if arg.is_positive: + k, coeff = n, S.One + else: + n = k = n + 1 + + if n & 1 == 0: + coeff = S.One + else: + coeff = S.NegativeOne + + coeff *= prod(range(3, 2*k, 2)) + + if arg.is_positive: + return coeff*sqrt(pi) / 2**n + else: + return 2**n*sqrt(pi) / coeff + + def _eval_expand_func(self, **hints): + arg = self.args[0] + if arg.is_Rational: + if abs(arg.p) > arg.q: + x = Dummy('x') + n = arg.p // arg.q + p = arg.p - n*arg.q + return self.func(x + n)._eval_expand_func().subs(x, Rational(p, arg.q)) + + if arg.is_Add: + coeff, tail = arg.as_coeff_add() + if coeff and coeff.q != 1: + intpart = floor(coeff) + tail = (coeff - intpart,) + tail + coeff = intpart + tail = arg._new_rawargs(*tail, reeval=False) + return self.func(tail)*RisingFactorial(tail, coeff) + + return self.func(*self.args) + + def _eval_conjugate(self): + return self.func(self.args[0].conjugate()) + + def _eval_is_real(self): + x = self.args[0] + if x.is_nonpositive and x.is_integer: + return False + if intlike(x) and x <= 0: + return False + if x.is_positive or x.is_noninteger: + return True + + def _eval_is_positive(self): + x = self.args[0] + if x.is_positive: + return True + elif x.is_noninteger: + return floor(x).is_even + + def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): + return exp(loggamma(z)) + + def _eval_rewrite_as_factorial(self, z, **kwargs): + return factorial(z - 1) + + def _eval_nseries(self, x, n, logx, cdir=0): + x0 = self.args[0].limit(x, 0) + if not (x0.is_Integer and x0 <= 0): + return super()._eval_nseries(x, n, logx) + t = self.args[0] - x0 + return (self.func(t + 1)/rf(self.args[0], -x0 + 1))._eval_nseries(x, n, logx) + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + arg = self.args[0] + x0 = arg.subs(x, 0) + + if x0.is_integer and x0.is_nonpositive: + n = -x0 + res = S.NegativeOne**n/self.func(n + 1) + return res/(arg + n).as_leading_term(x) + elif not x0.is_infinite: + return self.func(x0) + raise PoleError() + + +############################################################################### +################## LOWER and UPPER INCOMPLETE GAMMA FUNCTIONS ################# +############################################################################### + +class lowergamma(Function): + r""" + The lower incomplete gamma function. + + Explanation + =========== + + It can be defined as the meromorphic continuation of + + .. math:: + \gamma(s, x) := \int_0^x t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \Gamma(s, x). + + This can be shown to be the same as + + .. math:: + \gamma(s, x) = \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right), + + where ${}_1F_1$ is the (confluent) hypergeometric function. + + Examples + ======== + + >>> from sympy import lowergamma, S + >>> from sympy.abc import s, x + >>> lowergamma(s, x) + lowergamma(s, x) + >>> lowergamma(3, x) + -2*(x**2/2 + x + 1)*exp(-x) + 2 + >>> lowergamma(-S(1)/2, x) + -2*sqrt(pi)*erf(sqrt(x)) - 2*exp(-x)/sqrt(x) + + See Also + ======== + + gamma: Gamma function. + uppergamma: Upper incomplete gamma function. + polygamma: Polygamma function. + loggamma: Log Gamma function. + digamma: Digamma function. + trigamma: Trigamma function. + beta: Euler Beta function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Lower_incomplete_gamma_function + .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, + Section 5, Handbook of Mathematical Functions with Formulas, Graphs, + and Mathematical Tables + .. [3] https://dlmf.nist.gov/8 + .. [4] https://functions.wolfram.com/GammaBetaErf/Gamma2/ + .. [5] https://functions.wolfram.com/GammaBetaErf/Gamma3/ + + """ + + + def fdiff(self, argindex=2): + from sympy.functions.special.hyper import meijerg + if argindex == 2: + a, z = self.args + return exp(-unpolarify(z))*z**(a - 1) + elif argindex == 1: + a, z = self.args + return gamma(a)*digamma(a) - log(z)*uppergamma(a, z) \ + - meijerg([], [1, 1], [0, 0, a], [], z) + + else: + raise ArgumentIndexError(self, argindex) + + @classmethod + def eval(cls, a, x): + # For lack of a better place, we use this one to extract branching + # information. The following can be + # found in the literature (c/f references given above), albeit scattered: + # 1) For fixed x != 0, lowergamma(s, x) is an entire function of s + # 2) For fixed positive integers s, lowergamma(s, x) is an entire + # function of x. + # 3) For fixed non-positive integers s, + # lowergamma(s, exp(I*2*pi*n)*x) = + # 2*pi*I*n*(-1)**(-s)/factorial(-s) + lowergamma(s, x) + # (this follows from lowergamma(s, x).diff(x) = x**(s-1)*exp(-x)). + # 4) For fixed non-integral s, + # lowergamma(s, x) = x**s*gamma(s)*lowergamma_unbranched(s, x), + # where lowergamma_unbranched(s, x) is an entire function (in fact + # of both s and x), i.e. + # lowergamma(s, exp(2*I*pi*n)*x) = exp(2*pi*I*n*a)*lowergamma(a, x) + if x is S.Zero: + return S.Zero + nx, n = x.extract_branch_factor() + if a.is_integer and a.is_positive: + nx = unpolarify(x) + if nx != x: + return lowergamma(a, nx) + elif a.is_integer and a.is_nonpositive: + if n != 0: + return 2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + lowergamma(a, nx) + elif n != 0: + return exp(2*pi*I*n*a)*lowergamma(a, nx) + + # Special values. + if a.is_Number: + if a is S.One: + return S.One - exp(-x) + elif a is S.Half: + return sqrt(pi)*erf(sqrt(x)) + elif a.is_Integer or (2*a).is_Integer: + b = a - 1 + if b.is_positive: + if a.is_integer: + return factorial(b) - exp(-x) * factorial(b) * Add(*[x ** k / factorial(k) for k in range(a)]) + else: + return gamma(a)*(lowergamma(S.Half, x)/sqrt(pi) - exp(-x)*Add(*[x**(k - S.Half)/gamma(S.Half + k) for k in range(1, a + S.Half)])) + + if not a.is_Integer: + return S.NegativeOne**(S.Half - a)*pi*erf(sqrt(x))/gamma(1 - a) + exp(-x)*Add(*[x**(k + a - 1)*gamma(a)/gamma(a + k) for k in range(1, Rational(3, 2) - a)]) + + if x.is_zero: + return S.Zero + + def _eval_evalf(self, prec): + if all(x.is_number for x in self.args): + a = self.args[0]._to_mpmath(prec) + z = self.args[1]._to_mpmath(prec) + with workprec(prec): + res = mp.gammainc(a, 0, z) + return Expr._from_mpmath(res, prec) + else: + return self + + def _eval_conjugate(self): + x = self.args[1] + if x not in (S.Zero, S.NegativeInfinity): + return self.func(self.args[0].conjugate(), x.conjugate()) + + def _eval_is_meromorphic(self, x, a): + # By https://en.wikipedia.org/wiki/Incomplete_gamma_function#Holomorphic_extension, + # lowergamma(s, z) = z**s*gamma(s)*gammastar(s, z), + # where gammastar(s, z) is holomorphic for all s and z. + # Hence the singularities of lowergamma are z = 0 (branch + # point) and nonpositive integer values of s (poles of gamma(s)). + s, z = self.args + args_merom = fuzzy_and([z._eval_is_meromorphic(x, a), + s._eval_is_meromorphic(x, a)]) + if not args_merom: + return args_merom + z0 = z.subs(x, a) + if s.is_integer: + return fuzzy_and([s.is_positive, z0.is_finite]) + s0 = s.subs(x, a) + return fuzzy_and([s0.is_finite, z0.is_finite, fuzzy_not(z0.is_zero)]) + + def _eval_aseries(self, n, args0, x, logx): + from sympy.series.order import O + s, z = self.args + if args0[0] is oo and not z.has(x): + coeff = z**s*exp(-z) + sum_expr = sum(z**k/rf(s, k + 1) for k in range(n - 1)) + o = O(z**s*s**(-n)) + return coeff*sum_expr + o + return super()._eval_aseries(n, args0, x, logx) + + def _eval_rewrite_as_uppergamma(self, s, x, **kwargs): + return gamma(s) - uppergamma(s, x) + + def _eval_rewrite_as_expint(self, s, x, **kwargs): + from sympy.functions.special.error_functions import expint + if s.is_integer and s.is_nonpositive: + return self + return self.rewrite(uppergamma).rewrite(expint) + + def _eval_is_zero(self): + x = self.args[1] + if x.is_zero: + return True + + +class uppergamma(Function): + r""" + The upper incomplete gamma function. + + Explanation + =========== + + It can be defined as the meromorphic continuation of + + .. math:: + \Gamma(s, x) := \int_x^\infty t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \gamma(s, x). + + where $\gamma(s, x)$ is the lower incomplete gamma function, + :class:`lowergamma`. This can be shown to be the same as + + .. math:: + \Gamma(s, x) = \Gamma(s) - \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right), + + where ${}_1F_1$ is the (confluent) hypergeometric function. + + The upper incomplete gamma function is also essentially equivalent to the + generalized exponential integral: + + .. math:: + \operatorname{E}_{n}(x) = \int_{1}^{\infty}{\frac{e^{-xt}}{t^n} \, dt} = x^{n-1}\Gamma(1-n,x). + + Examples + ======== + + >>> from sympy import uppergamma, S + >>> from sympy.abc import s, x + >>> uppergamma(s, x) + uppergamma(s, x) + >>> uppergamma(3, x) + 2*(x**2/2 + x + 1)*exp(-x) + >>> uppergamma(-S(1)/2, x) + -2*sqrt(pi)*erfc(sqrt(x)) + 2*exp(-x)/sqrt(x) + >>> uppergamma(-2, x) + expint(3, x)/x**2 + + See Also + ======== + + gamma: Gamma function. + lowergamma: Lower incomplete gamma function. + polygamma: Polygamma function. + loggamma: Log Gamma function. + digamma: Digamma function. + trigamma: Trigamma function. + beta: Euler Beta function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Upper_incomplete_gamma_function + .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, + Section 5, Handbook of Mathematical Functions with Formulas, Graphs, + and Mathematical Tables + .. [3] https://dlmf.nist.gov/8 + .. [4] https://functions.wolfram.com/GammaBetaErf/Gamma2/ + .. [5] https://functions.wolfram.com/GammaBetaErf/Gamma3/ + .. [6] https://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions + + """ + + + def fdiff(self, argindex=2): + from sympy.functions.special.hyper import meijerg + if argindex == 2: + a, z = self.args + return -exp(-unpolarify(z))*z**(a - 1) + elif argindex == 1: + a, z = self.args + return uppergamma(a, z)*log(z) + meijerg([], [1, 1], [0, 0, a], [], z) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_evalf(self, prec): + if all(x.is_number for x in self.args): + a = self.args[0]._to_mpmath(prec) + z = self.args[1]._to_mpmath(prec) + with workprec(prec): + res = mp.gammainc(a, z, mp.inf) + return Expr._from_mpmath(res, prec) + return self + + @classmethod + def eval(cls, a, z): + from sympy.functions.special.error_functions import expint + if z.is_Number: + if z is S.NaN: + return S.NaN + elif z is oo: + return S.Zero + elif z.is_zero: + if re(a).is_positive: + return gamma(a) + + # We extract branching information here. C/f lowergamma. + nx, n = z.extract_branch_factor() + if a.is_integer and a.is_positive: + nx = unpolarify(z) + if z != nx: + return uppergamma(a, nx) + elif a.is_integer and a.is_nonpositive: + if n != 0: + return -2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + uppergamma(a, nx) + elif n != 0: + return gamma(a)*(1 - exp(2*pi*I*n*a)) + exp(2*pi*I*n*a)*uppergamma(a, nx) + + # Special values. + if a.is_Number: + if a is S.Zero and z.is_positive: + return -Ei(-z) + elif a is S.One: + return exp(-z) + elif a is S.Half: + return sqrt(pi)*erfc(sqrt(z)) + elif a.is_Integer or (2*a).is_Integer: + b = a - 1 + if b.is_positive: + if a.is_integer: + return exp(-z) * factorial(b) * Add(*[z**k / factorial(k) + for k in range(a)]) + else: + return (gamma(a) * erfc(sqrt(z)) + + S.NegativeOne**(a - S(3)/2) * exp(-z) * sqrt(z) + * Add(*[gamma(-S.Half - k) * (-z)**k / gamma(1-a) + for k in range(a - S.Half)])) + elif b.is_Integer: + return expint(-b, z)*unpolarify(z)**(b + 1) + + if not a.is_Integer: + return (S.NegativeOne**(S.Half - a) * pi*erfc(sqrt(z))/gamma(1-a) + - z**a * exp(-z) * Add(*[z**k * gamma(a) / gamma(a+k+1) + for k in range(S.Half - a)])) + + if a.is_zero and z.is_positive: + return -Ei(-z) + + if z.is_zero and re(a).is_positive: + return gamma(a) + + def _eval_conjugate(self): + z = self.args[1] + if z not in (S.Zero, S.NegativeInfinity): + return self.func(self.args[0].conjugate(), z.conjugate()) + + def _eval_is_meromorphic(self, x, a): + return lowergamma._eval_is_meromorphic(self, x, a) + + def _eval_rewrite_as_lowergamma(self, s, x, **kwargs): + return gamma(s) - lowergamma(s, x) + + def _eval_rewrite_as_tractable(self, s, x, **kwargs): + return exp(loggamma(s)) - lowergamma(s, x) + + def _eval_rewrite_as_expint(self, s, x, **kwargs): + from sympy.functions.special.error_functions import expint + return expint(1 - s, x)*x**s + + +############################################################################### +###################### POLYGAMMA and LOGGAMMA FUNCTIONS ####################### +############################################################################### + +class polygamma(Function): + r""" + The function ``polygamma(n, z)`` returns ``log(gamma(z)).diff(n + 1)``. + + Explanation + =========== + + It is a meromorphic function on $\mathbb{C}$ and defined as the $(n+1)$-th + derivative of the logarithm of the gamma function: + + .. math:: + \psi^{(n)} (z) := \frac{\mathrm{d}^{n+1}}{\mathrm{d} z^{n+1}} \log\Gamma(z). + + For `n` not a nonnegative integer the generalization by Espinosa and Moll [5]_ + is used: + + .. math:: \psi(s,z) = \frac{\zeta'(s+1, z) + (\gamma + \psi(-s)) \zeta(s+1, z)} + {\Gamma(-s)} + + Examples + ======== + + Several special values are known: + + >>> from sympy import S, polygamma + >>> polygamma(0, 1) + -EulerGamma + >>> polygamma(0, 1/S(2)) + -2*log(2) - EulerGamma + >>> polygamma(0, 1/S(3)) + -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) + >>> polygamma(0, 1/S(4)) + -pi/2 - log(4) - log(2) - EulerGamma + >>> polygamma(0, 2) + 1 - EulerGamma + >>> polygamma(0, 23) + 19093197/5173168 - EulerGamma + + >>> from sympy import oo, I + >>> polygamma(0, oo) + oo + >>> polygamma(0, -oo) + oo + >>> polygamma(0, I*oo) + oo + >>> polygamma(0, -I*oo) + oo + + Differentiation with respect to $x$ is supported: + + >>> from sympy import Symbol, diff + >>> x = Symbol("x") + >>> diff(polygamma(0, x), x) + polygamma(1, x) + >>> diff(polygamma(0, x), x, 2) + polygamma(2, x) + >>> diff(polygamma(0, x), x, 3) + polygamma(3, x) + >>> diff(polygamma(1, x), x) + polygamma(2, x) + >>> diff(polygamma(1, x), x, 2) + polygamma(3, x) + >>> diff(polygamma(2, x), x) + polygamma(3, x) + >>> diff(polygamma(2, x), x, 2) + polygamma(4, x) + + >>> n = Symbol("n") + >>> diff(polygamma(n, x), x) + polygamma(n + 1, x) + >>> diff(polygamma(n, x), x, 2) + polygamma(n + 2, x) + + We can rewrite ``polygamma`` functions in terms of harmonic numbers: + + >>> from sympy import harmonic + >>> polygamma(0, x).rewrite(harmonic) + harmonic(x - 1) - EulerGamma + >>> polygamma(2, x).rewrite(harmonic) + 2*harmonic(x - 1, 3) - 2*zeta(3) + >>> ni = Symbol("n", integer=True) + >>> polygamma(ni, x).rewrite(harmonic) + (-1)**(n + 1)*(-harmonic(x - 1, n + 1) + zeta(n + 1))*factorial(n) + + See Also + ======== + + gamma: Gamma function. + lowergamma: Lower incomplete gamma function. + uppergamma: Upper incomplete gamma function. + loggamma: Log Gamma function. + digamma: Digamma function. + trigamma: Trigamma function. + beta: Euler Beta function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Polygamma_function + .. [2] https://mathworld.wolfram.com/PolygammaFunction.html + .. [3] https://functions.wolfram.com/GammaBetaErf/PolyGamma/ + .. [4] https://functions.wolfram.com/GammaBetaErf/PolyGamma2/ + .. [5] O. Espinosa and V. Moll, "A generalized polygamma function", + *Integral Transforms and Special Functions* (2004), 101-115. + + """ + + @classmethod + def eval(cls, n, z): + if n is S.NaN or z is S.NaN: + return S.NaN + elif z is oo: + return oo if n.is_zero else S.Zero + elif z.is_Integer and z.is_nonpositive: + return S.ComplexInfinity + elif n is S.NegativeOne: + return loggamma(z) - log(2*pi) / 2 + elif n.is_zero: + if z is -oo or z.extract_multiplicatively(I) in (oo, -oo): + return oo + elif z.is_Integer: + return harmonic(z-1) - S.EulerGamma + elif z.is_Rational: + # TODO n == 1 also can do some rational z + p, q = z.as_numer_denom() + # only expand for small denominators to avoid creating long expressions + if q <= 6: + return expand_func(polygamma(S.Zero, z, evaluate=False)) + elif n.is_integer and n.is_nonnegative: + nz = unpolarify(z) + if z != nz: + return polygamma(n, nz) + if z.is_Integer: + return S.NegativeOne**(n+1) * factorial(n) * zeta(n+1, z) + elif z is S.Half: + return S.NegativeOne**(n+1) * factorial(n) * (2**(n+1)-1) * zeta(n+1) + + def _eval_is_real(self): + if self.args[0].is_positive and self.args[1].is_positive: + return True + + def _eval_is_complex(self): + z = self.args[1] + is_negative_integer = fuzzy_and([z.is_negative, z.is_integer]) + return fuzzy_and([z.is_complex, fuzzy_not(is_negative_integer)]) + + def _eval_is_positive(self): + n, z = self.args + if n.is_positive: + if n.is_odd and z.is_real: + return True + if n.is_even and z.is_positive: + return False + + def _eval_is_negative(self): + n, z = self.args + if n.is_positive: + if n.is_even and z.is_positive: + return True + if n.is_odd and z.is_real: + return False + + def _eval_expand_func(self, **hints): + n, z = self.args + + if n.is_Integer and n.is_nonnegative: + if z.is_Add: + coeff = z.args[0] + if coeff.is_Integer: + e = -(n + 1) + if coeff > 0: + tail = Add(*[Pow( + z - i, e) for i in range(1, int(coeff) + 1)]) + else: + tail = -Add(*[Pow( + z + i, e) for i in range(int(-coeff))]) + return polygamma(n, z - coeff) + S.NegativeOne**n*factorial(n)*tail + + elif z.is_Mul: + coeff, z = z.as_two_terms() + if coeff.is_Integer and coeff.is_positive: + tail = [polygamma(n, z + Rational( + i, coeff)) for i in range(int(coeff))] + if n == 0: + return Add(*tail)/coeff + log(coeff) + else: + return Add(*tail)/coeff**(n + 1) + z *= coeff + + if n == 0 and z.is_Rational: + p, q = z.as_numer_denom() + + # Reference: + # Values of the polygamma functions at rational arguments, J. Choi, 2007 + part_1 = -S.EulerGamma - pi * cot(p * pi / q) / 2 - log(q) + Add( + *[cos(2 * k * pi * p / q) * log(2 * sin(k * pi / q)) for k in range(1, q)]) + + if z > 0: + n = floor(z) + z0 = z - n + return part_1 + Add(*[1 / (z0 + k) for k in range(n)]) + elif z < 0: + n = floor(1 - z) + z0 = z + n + return part_1 - Add(*[1 / (z0 - 1 - k) for k in range(n)]) + + if n == -1: + return loggamma(z) - log(2*pi) / 2 + if n.is_integer is False or n.is_nonnegative is False: + s = Dummy("s") + dzt = zeta(s, z).diff(s).subs(s, n+1) + return (dzt + (S.EulerGamma + digamma(-n)) * zeta(n+1, z)) / gamma(-n) + + return polygamma(n, z) + + def _eval_rewrite_as_zeta(self, n, z, **kwargs): + if n.is_integer and n.is_positive: + return S.NegativeOne**(n + 1)*factorial(n)*zeta(n + 1, z) + + def _eval_rewrite_as_harmonic(self, n, z, **kwargs): + if n.is_integer: + if n.is_zero: + return harmonic(z - 1) - S.EulerGamma + else: + return S.NegativeOne**(n+1) * factorial(n) * (zeta(n+1) - harmonic(z-1, n+1)) + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + from sympy.series.order import Order + n, z = [a.as_leading_term(x) for a in self.args] + o = Order(z, x) + if n == 0 and o.contains(1/x): + logx = log(x) if logx is None else logx + return o.getn() * logx + else: + return self.func(n, z) + + def fdiff(self, argindex=2): + if argindex == 2: + n, z = self.args[:2] + return polygamma(n + 1, z) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_aseries(self, n, args0, x, logx): + from sympy.series.order import Order + if args0[1] != oo or not \ + (self.args[0].is_Integer and self.args[0].is_nonnegative): + return super()._eval_aseries(n, args0, x, logx) + z = self.args[1] + N = self.args[0] + + if N == 0: + # digamma function series + # Abramowitz & Stegun, p. 259, 6.3.18 + r = log(z) - 1/(2*z) + o = None + if n < 2: + o = Order(1/z, x) + else: + m = ceiling((n + 1)//2) + l = [bernoulli(2*k) / (2*k*z**(2*k)) for k in range(1, m)] + r -= Add(*l) + o = Order(1/z**n, x) + return r._eval_nseries(x, n, logx) + o + else: + # proper polygamma function + # Abramowitz & Stegun, p. 260, 6.4.10 + # We return terms to order higher than O(x**n) on purpose + # -- otherwise we would not be able to return any terms for + # quite a long time! + fac = gamma(N) + e0 = fac + N*fac/(2*z) + m = ceiling((n + 1)//2) + for k in range(1, m): + fac = fac*(2*k + N - 1)*(2*k + N - 2) / ((2*k)*(2*k - 1)) + e0 += bernoulli(2*k)*fac/z**(2*k) + o = Order(1/z**(2*m), x) + if n == 0: + o = Order(1/z, x) + elif n == 1: + o = Order(1/z**2, x) + r = e0._eval_nseries(z, n, logx) + o + return (-1 * (-1/z)**N * r)._eval_nseries(x, n, logx) + + def _eval_evalf(self, prec): + if not all(i.is_number for i in self.args): + return + s = self.args[0]._to_mpmath(prec+12) + z = self.args[1]._to_mpmath(prec+12) + if mp.isint(z) and z <= 0: + return S.ComplexInfinity + with workprec(prec+12): + if mp.isint(s) and s >= 0: + res = mp.polygamma(s, z) + else: + zt = mp.zeta(s+1, z) + dzt = mp.zeta(s+1, z, 1) + res = (dzt + (mp.euler + mp.digamma(-s)) * zt) * mp.rgamma(-s) + return Expr._from_mpmath(res, prec) + + +class loggamma(Function): + r""" + The ``loggamma`` function implements the logarithm of the + gamma function (i.e., $\log\Gamma(x)$). + + Examples + ======== + + Several special values are known. For numerical integral + arguments we have: + + >>> from sympy import loggamma + >>> loggamma(-2) + oo + >>> loggamma(0) + oo + >>> loggamma(1) + 0 + >>> loggamma(2) + 0 + >>> loggamma(3) + log(2) + + And for symbolic values: + + >>> from sympy import Symbol + >>> n = Symbol("n", integer=True, positive=True) + >>> loggamma(n) + log(gamma(n)) + >>> loggamma(-n) + oo + + For half-integral values: + + >>> from sympy import S + >>> loggamma(S(5)/2) + log(3*sqrt(pi)/4) + >>> loggamma(n/2) + log(2**(1 - n)*sqrt(pi)*gamma(n)/gamma(n/2 + 1/2)) + + And general rational arguments: + + >>> from sympy import expand_func + >>> L = loggamma(S(16)/3) + >>> expand_func(L).doit() + -5*log(3) + loggamma(1/3) + log(4) + log(7) + log(10) + log(13) + >>> L = loggamma(S(19)/4) + >>> expand_func(L).doit() + -4*log(4) + loggamma(3/4) + log(3) + log(7) + log(11) + log(15) + >>> L = loggamma(S(23)/7) + >>> expand_func(L).doit() + -3*log(7) + log(2) + loggamma(2/7) + log(9) + log(16) + + The ``loggamma`` function has the following limits towards infinity: + + >>> from sympy import oo + >>> loggamma(oo) + oo + >>> loggamma(-oo) + zoo + + The ``loggamma`` function obeys the mirror symmetry + if $x \in \mathbb{C} \setminus \{-\infty, 0\}$: + + >>> from sympy.abc import x + >>> from sympy import conjugate + >>> conjugate(loggamma(x)) + loggamma(conjugate(x)) + + Differentiation with respect to $x$ is supported: + + >>> from sympy import diff + >>> diff(loggamma(x), x) + polygamma(0, x) + + Series expansion is also supported: + + >>> from sympy import series + >>> series(loggamma(x), x, 0, 4).cancel() + -log(x) - EulerGamma*x + pi**2*x**2/12 - x**3*zeta(3)/3 + O(x**4) + + We can numerically evaluate the ``loggamma`` function + to arbitrary precision on the whole complex plane: + + >>> from sympy import I + >>> loggamma(5).evalf(30) + 3.17805383034794561964694160130 + >>> loggamma(I).evalf(20) + -0.65092319930185633889 - 1.8724366472624298171*I + + See Also + ======== + + gamma: Gamma function. + lowergamma: Lower incomplete gamma function. + uppergamma: Upper incomplete gamma function. + polygamma: Polygamma function. + digamma: Digamma function. + trigamma: Trigamma function. + beta: Euler Beta function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gamma_function + .. [2] https://dlmf.nist.gov/5 + .. [3] https://mathworld.wolfram.com/LogGammaFunction.html + .. [4] https://functions.wolfram.com/GammaBetaErf/LogGamma/ + + """ + @classmethod + def eval(cls, z): + if z.is_integer: + if z.is_nonpositive: + return oo + elif z.is_positive: + return log(gamma(z)) + elif z.is_rational: + p, q = z.as_numer_denom() + # Half-integral values: + if p.is_positive and q == 2: + return log(sqrt(pi) * 2**(1 - p) * gamma(p) / gamma((p + 1)*S.Half)) + + if z is oo: + return oo + elif abs(z) is oo: + return S.ComplexInfinity + if z is S.NaN: + return S.NaN + + def _eval_expand_func(self, **hints): + from sympy.concrete.summations import Sum + z = self.args[0] + + if z.is_Rational: + p, q = z.as_numer_denom() + # General rational arguments (u + p/q) + # Split z as n + p/q with p < q + n = p // q + p = p - n*q + if p.is_positive and q.is_positive and p < q: + k = Dummy("k") + if n.is_positive: + return loggamma(p / q) - n*log(q) + Sum(log((k - 1)*q + p), (k, 1, n)) + elif n.is_negative: + return loggamma(p / q) - n*log(q) + pi*I*n - Sum(log(k*q - p), (k, 1, -n)) + elif n.is_zero: + return loggamma(p / q) + + return self + + def _eval_nseries(self, x, n, logx=None, cdir=0): + x0 = self.args[0].limit(x, 0) + if x0.is_zero: + f = self._eval_rewrite_as_intractable(*self.args) + return f._eval_nseries(x, n, logx) + return super()._eval_nseries(x, n, logx) + + def _eval_aseries(self, n, args0, x, logx): + from sympy.series.order import Order + if args0[0] != oo: + return super()._eval_aseries(n, args0, x, logx) + z = self.args[0] + r = log(z)*(z - S.Half) - z + log(2*pi)/2 + l = [bernoulli(2*k) / (2*k*(2*k - 1)*z**(2*k - 1)) for k in range(1, n)] + o = None + if n == 0: + o = Order(1, x) + else: + o = Order(1/z**n, x) + # It is very inefficient to first add the order and then do the nseries + return (r + Add(*l))._eval_nseries(x, n, logx) + o + + def _eval_rewrite_as_intractable(self, z, **kwargs): + return log(gamma(z)) + + def _eval_is_real(self): + z = self.args[0] + if z.is_positive: + return True + elif z.is_nonpositive: + return False + + def _eval_conjugate(self): + z = self.args[0] + if z not in (S.Zero, S.NegativeInfinity): + return self.func(z.conjugate()) + + def fdiff(self, argindex=1): + if argindex == 1: + return polygamma(0, self.args[0]) + else: + raise ArgumentIndexError(self, argindex) + + +class digamma(Function): + r""" + The ``digamma`` function is the first derivative of the ``loggamma`` + function + + .. math:: + \psi(x) := \frac{\mathrm{d}}{\mathrm{d} z} \log\Gamma(z) + = \frac{\Gamma'(z)}{\Gamma(z) }. + + In this case, ``digamma(z) = polygamma(0, z)``. + + Examples + ======== + + >>> from sympy import digamma + >>> digamma(0) + zoo + >>> from sympy import Symbol + >>> z = Symbol('z') + >>> digamma(z) + polygamma(0, z) + + To retain ``digamma`` as it is: + + >>> digamma(0, evaluate=False) + digamma(0) + >>> digamma(z, evaluate=False) + digamma(z) + + See Also + ======== + + gamma: Gamma function. + lowergamma: Lower incomplete gamma function. + uppergamma: Upper incomplete gamma function. + polygamma: Polygamma function. + loggamma: Log Gamma function. + trigamma: Trigamma function. + beta: Euler Beta function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Digamma_function + .. [2] https://mathworld.wolfram.com/DigammaFunction.html + .. [3] https://functions.wolfram.com/GammaBetaErf/PolyGamma2/ + + """ + def _eval_evalf(self, prec): + z = self.args[0] + nprec = prec_to_dps(prec) + return polygamma(0, z).evalf(n=nprec) + + def fdiff(self, argindex=1): + z = self.args[0] + return polygamma(0, z).fdiff() + + def _eval_is_real(self): + z = self.args[0] + return polygamma(0, z).is_real + + def _eval_is_positive(self): + z = self.args[0] + return polygamma(0, z).is_positive + + def _eval_is_negative(self): + z = self.args[0] + return polygamma(0, z).is_negative + + def _eval_aseries(self, n, args0, x, logx): + as_polygamma = self.rewrite(polygamma) + args0 = [S.Zero,] + args0 + return as_polygamma._eval_aseries(n, args0, x, logx) + + @classmethod + def eval(cls, z): + return polygamma(0, z) + + def _eval_expand_func(self, **hints): + z = self.args[0] + return polygamma(0, z).expand(func=True) + + def _eval_rewrite_as_harmonic(self, z, **kwargs): + return harmonic(z - 1) - S.EulerGamma + + def _eval_rewrite_as_polygamma(self, z, **kwargs): + return polygamma(0, z) + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + z = self.args[0] + return polygamma(0, z).as_leading_term(x) + + + +class trigamma(Function): + r""" + The ``trigamma`` function is the second derivative of the ``loggamma`` + function + + .. math:: + \psi^{(1)}(z) := \frac{\mathrm{d}^{2}}{\mathrm{d} z^{2}} \log\Gamma(z). + + In this case, ``trigamma(z) = polygamma(1, z)``. + + Examples + ======== + + >>> from sympy import trigamma + >>> trigamma(0) + zoo + >>> from sympy import Symbol + >>> z = Symbol('z') + >>> trigamma(z) + polygamma(1, z) + + To retain ``trigamma`` as it is: + + >>> trigamma(0, evaluate=False) + trigamma(0) + >>> trigamma(z, evaluate=False) + trigamma(z) + + + See Also + ======== + + gamma: Gamma function. + lowergamma: Lower incomplete gamma function. + uppergamma: Upper incomplete gamma function. + polygamma: Polygamma function. + loggamma: Log Gamma function. + digamma: Digamma function. + beta: Euler Beta function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Trigamma_function + .. [2] https://mathworld.wolfram.com/TrigammaFunction.html + .. [3] https://functions.wolfram.com/GammaBetaErf/PolyGamma2/ + + """ + def _eval_evalf(self, prec): + z = self.args[0] + nprec = prec_to_dps(prec) + return polygamma(1, z).evalf(n=nprec) + + def fdiff(self, argindex=1): + z = self.args[0] + return polygamma(1, z).fdiff() + + def _eval_is_real(self): + z = self.args[0] + return polygamma(1, z).is_real + + def _eval_is_positive(self): + z = self.args[0] + return polygamma(1, z).is_positive + + def _eval_is_negative(self): + z = self.args[0] + return polygamma(1, z).is_negative + + def _eval_aseries(self, n, args0, x, logx): + as_polygamma = self.rewrite(polygamma) + args0 = [S.One,] + args0 + return as_polygamma._eval_aseries(n, args0, x, logx) + + @classmethod + def eval(cls, z): + return polygamma(1, z) + + def _eval_expand_func(self, **hints): + z = self.args[0] + return polygamma(1, z).expand(func=True) + + def _eval_rewrite_as_zeta(self, z, **kwargs): + return zeta(2, z) + + def _eval_rewrite_as_polygamma(self, z, **kwargs): + return polygamma(1, z) + + def _eval_rewrite_as_harmonic(self, z, **kwargs): + return -harmonic(z - 1, 2) + pi**2 / 6 + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + z = self.args[0] + return polygamma(1, z).as_leading_term(x) + + +############################################################################### +##################### COMPLETE MULTIVARIATE GAMMA FUNCTION #################### +############################################################################### + + +class multigamma(Function): + r""" + The multivariate gamma function is a generalization of the gamma function + + .. math:: + \Gamma_p(z) = \pi^{p(p-1)/4}\prod_{k=1}^p \Gamma[z + (1 - k)/2]. + + In a special case, ``multigamma(x, 1) = gamma(x)``. + + Examples + ======== + + >>> from sympy import S, multigamma + >>> from sympy import Symbol + >>> x = Symbol('x') + >>> p = Symbol('p', positive=True, integer=True) + + >>> multigamma(x, p) + pi**(p*(p - 1)/4)*Product(gamma(-_k/2 + x + 1/2), (_k, 1, p)) + + Several special values are known: + + >>> multigamma(1, 1) + 1 + >>> multigamma(4, 1) + 6 + >>> multigamma(S(3)/2, 1) + sqrt(pi)/2 + + Writing ``multigamma`` in terms of the ``gamma`` function: + + >>> multigamma(x, 1) + gamma(x) + + >>> multigamma(x, 2) + sqrt(pi)*gamma(x)*gamma(x - 1/2) + + >>> multigamma(x, 3) + pi**(3/2)*gamma(x)*gamma(x - 1)*gamma(x - 1/2) + + Parameters + ========== + + p : order or dimension of the multivariate gamma function + + See Also + ======== + + gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, + beta + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Multivariate_gamma_function + + """ + unbranched = True + + def fdiff(self, argindex=2): + from sympy.concrete.summations import Sum + if argindex == 2: + x, p = self.args + k = Dummy("k") + return self.func(x, p)*Sum(polygamma(0, x + (1 - k)/2), (k, 1, p)) + else: + raise ArgumentIndexError(self, argindex) + + @classmethod + def eval(cls, x, p): + from sympy.concrete.products import Product + if p.is_positive is False or p.is_integer is False: + raise ValueError('Order parameter p must be positive integer.') + k = Dummy("k") + return (pi**(p*(p - 1)/4)*Product(gamma(x + (1 - k)/2), + (k, 1, p))).doit() + + def _eval_conjugate(self): + x, p = self.args + return self.func(x.conjugate(), p) + + def _eval_is_real(self): + x, p = self.args + y = 2*x + if y.is_integer and (y <= (p - 1)) is True: + return False + if intlike(y) and (y <= (p - 1)): + return False + if y > (p - 1) or y.is_noninteger: + return True diff --git a/shared/package-files/3a/3a3526e915c3bb6413005fbb57f89fc0cdfb9395285e5dcb52f80f1af45c1664/sinh_ops.h b/shared/package-files/3a/3a3526e915c3bb6413005fbb57f89fc0cdfb9395285e5dcb52f80f1af45c1664/sinh_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..620dd3533f039b353694f20b084dc2079fcad2e0 --- /dev/null +++ b/shared/package-files/3a/3a3526e915c3bb6413005fbb57f89fc0cdfb9395285e5dcb52f80f1af45c1664/sinh_ops.h @@ -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 sinh { + 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::sinh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sinh(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 sinh_ { + 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::sinh_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sinh_(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 sinh_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::sinh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sinh.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/3a/3a366d3f7ac7cfb894c825fc173a6d0c8634300ab1665f7be8e3a36aade29377/special_bessel_y1_meta.h b/shared/package-files/3a/3a366d3f7ac7cfb894c825fc173a6d0c8634300ab1665f7be8e3a36aade29377/special_bessel_y1_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..4aeb2ac1e3984889b8808b62deedaae349686ccb --- /dev/null +++ b/shared/package-files/3a/3a366d3f7ac7cfb894c825fc173a6d0c8634300ab1665f7be8e3a36aade29377/special_bessel_y1_meta.h @@ -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_bessel_y1 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a391f37194dc3145101b452146f5f1bcf721151ce64c39847c8142d7d35acd2/autograd.py b/shared/package-files/3a/3a391f37194dc3145101b452146f5f1bcf721151ce64c39847c8142d7d35acd2/autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..116a4612a45ef2267109bfc6dbec6e5d4c642c7f --- /dev/null +++ b/shared/package-files/3a/3a391f37194dc3145101b452146f5f1bcf721151ce64c39847c8142d7d35acd2/autograd.py @@ -0,0 +1,274 @@ +import torch +import torch.utils._pytree as pytree +from collections import namedtuple +import functools + + +# NOTE [CustomOp autograd kernel indirection] +# We register `inner` as the autograd kernel for this custom_op. +# `inner` either calls the autograd formula registered by the user, +# or goes into an `autograd_not_implemented` kernel. +# +# The reason why this indirection exists is +# so that we can swap out the autograd kernel (the PyTorch dispatcher +# doesn't actually allow us to do this). By default, we want +# the `autograd_not_implemented` behavior, but then the user may come +# and register something that is actually a backward formula +def autograd_kernel_indirection(custom_op): + autograd_fallback = autograd_not_implemented(custom_op) + + def inner(*args, **kwargs): + if custom_op._has_impl('autograd'): + kernel = custom_op._get_impl('autograd').func + return kernel(*args, **kwargs) + # As explained in NOTE ["backward", "save_for_backward", and "autograd"], + # after the user gives us "backward" and "save_for_backward", we generate + # the "autograd" impl. If the user only provided one, then we tell + # the user they've done something wrong. + if custom_op._has_impl('save_for_backward') or custom_op._has_impl('backward'): + missing = ( + 'save_for_backward' if custom_op._has_impl('backward') + else 'backward' + ) + found = 'save_for_backward' if missing == 'backward' else 'backward' + loc = custom_op._get_impl(found).location + raise RuntimeError( + f"We found a '{found}' registration for {custom_op} at " + f"{loc} but were unable to find a '{missing}' registration. " + f"To use the CustomOp API to register a backward formula, " + f"please provide us both a backward function and a " + f"'save for backward' function via `impl_backward` and " + f"`impl_save_for_backward` respectively.") + return autograd_fallback(*args, **kwargs) + return inner + + +# TODO(#101191): Use the actual C++ autograd not implemented fallback, +# or change the default autograd fallback to the autograd not implemented fallback. +def autograd_not_implemented(custom_op): + def kernel(*args, **kwargs): + if torch.is_grad_enabled() and pytree.tree_any( + lambda x: isinstance(x, torch.Tensor) and x.requires_grad, (args, kwargs) + ): + raise RuntimeError("Autograd has not been implemented for operator") + with torch._C._AutoDispatchBelowAutograd(): + return custom_op(*args, **kwargs) + return kernel + + +def mark_non_differentiable(ctx, output, output_differentiability): + # Output types are restricted to be: + # - Tensor + # - Tensor[] + # - int, bool, Scalar, float + # See _check_can_register_backward + if output_differentiability is not None: + if not isinstance(output, tuple): + tuple_output = (output,) + else: + tuple_output = output # type: ignore[assignment] + assert len(output_differentiability) == len(tuple_output) + non_differentiable_tensors = [] + for idx, (differentiable, out) in enumerate(zip(output_differentiability, tuple_output)): + if isinstance(out, torch.Tensor): + if not differentiable: + non_differentiable_tensors.append(out) + continue + if isinstance(out, list): + if not differentiable: + non_differentiable_tensors.extend(out) + continue + if differentiable: + raise RuntimeError( + f"With output_differentiability={output_differentiability}. " + f"At idx {idx}, we received an object of type {type(out)} that " + f"is not a Tensor, so it cannot have be marked as differentiable in " + f"output_differentiability.") + if non_differentiable_tensors: + ctx.mark_non_differentiable(*non_differentiable_tensors) + + +def construct_autograd_kernel( + schema, + output_differentiability, + custom_op, + op_overload, + save_for_backward_fn, + backward_fn): + + def apply(*args): + flat_args, spec = pytree.tree_flatten(args) + out_spec = None + + def forward(ctx, *flat_args): + ctx.set_materialize_grads(True) + args = pytree.tree_unflatten(list(flat_args), spec) + with torch._C._AutoDispatchBelowAutograd(): + output = op_overload(*args) + + # We use the info about args to give better error messages in backward + args_info = namedtuple_args( + schema, pytree.tree_map(type, args)) + + save_for_backward_fn_inputs = namedtuple_args(schema, args) + to_save = save_for_backward_fn(save_for_backward_fn_inputs, output) + + save_pytree_for_backward(ctx, (to_save, args_info)) + mark_non_differentiable(ctx, output, output_differentiability) + + nonlocal out_spec + flat_output, out_spec = pytree.tree_flatten(output) + return tuple(flat_output) + + def backward(ctx, *flat_grad_output): + assert out_spec is not None + grads = pytree.tree_unflatten(list(flat_grad_output), out_spec) + saved, args_info = unpack_saved(ctx) + # There is nothing on the ctx object for now, it is just there so + # that we can add additional things in the future. + inner_ctx = object() + if not isinstance(grads, tuple): + grads = (grads,) + grad_inputs_dict = backward_fn(inner_ctx, saved, *grads) + + # Massage the grad_inputs_dict to a form acceptable by + # autograd.Function. + validate_grad_inputs_dict(grad_inputs_dict, custom_op, args_info) + return grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info) + + generated_cls = gen_autograd_function( + custom_op._opname + '_customop', forward, backward) + + flat_output = generated_cls.apply(*flat_args) + assert out_spec is not None + return pytree.tree_unflatten(list(flat_output), out_spec) + return apply + + +def gen_autograd_function(name, forward, backward): + generated_cls = type( + name, + (torch.autograd.Function,), + { + 'forward': staticmethod(forward), + 'backward': staticmethod(backward), + } + ) + return generated_cls + + +@functools.lru_cache +def namedtuple_args_cls(schema): + attribs = [arg.name for arg in schema.arguments.flat_all] + name = str(schema.name) + "_args" + # mypy doesn't support dynamic namedtuple name + tuple_cls = namedtuple(name, attribs) # type: ignore[misc] + return tuple_cls + + +def namedtuple_args(schema, args): + assert isinstance(args, tuple) + tuple_cls = namedtuple_args_cls(schema) + return tuple_cls(*args) + + +def validate_grad_inputs_dict(grad_inputs_dict, forward_op, args_info): + def error(what): + backward = forward_op._get_impl('backward') + raise RuntimeError( + f"In the backward function defined for {forward_op} at " + f"{backward.location} using the CustomOp API, {what}") + + if not isinstance(grad_inputs_dict, dict): + error(f"expected the output of the backward function to be a dict but " + f"got {type(grad_inputs_dict)}") + + expected_keys = {arg.name for arg in forward_op._schema.arguments.flat_all + if arg.type.is_tensor_like()} + actual_keys = grad_inputs_dict.keys() + if expected_keys != actual_keys: + error(f"expected the returned grad_input dict to have keys " + f"{expected_keys} but got {actual_keys}. The backward " + f"function must return a gradient (can be None) for each arg " + f"to the CustomOp that may be a Tensor or Sequence[Tensor]. " + f"Args declared to be non-Tensor-like types should not appear " + f"in the grad_input dict") + + for name, grad in grad_inputs_dict.items(): + arg_info = getattr(args_info, name) + + if isinstance(arg_info, list): + if not isinstance(grad, (tuple, list)): + error(f"for input '{name}' expected the grad_input dict to " + f"hold a list of gradients but got object of type " + f"{type(grad)}.") + if not len(grad) == len(arg_info): + error(f"for input '{name}' expected the grad_input dict to " + f"hold a list of {len(arg_info)} gradients but got " + f"{len(grad)}") + for idx, (g, info) in enumerate(zip(grad, arg_info)): + if g is None: + continue + if not isinstance(g, torch.Tensor): + error(f"for input '{name}' expected the grad_input dict to " + f"hold a list of None or Tensor gradients but got " + f"object of {type(g)} at index {idx}") + if not issubclass(info, torch.Tensor): + error(f"for input '{name}', got a Tensor as the gradient " + f"for the {idx}-th value but expected None because " + f"the {idx}-th value was not a Tensor (it was " + f"type {arg_info}") + continue + + if grad is None: + continue + if not isinstance(grad, torch.Tensor): + error(f"got object of type {type(grad)} as the gradient for input " + f"'{name}', " + f"but expected the gradient to be either None or a Tensor") + if not issubclass(arg_info, torch.Tensor): + error(f"got a Tensor as the gradient for input '{name}' but " + f"expected None as the gradient because input '{name}' " + f"was not a Tensor (it was type {arg_info}).") + + +def grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info): + result = [] + for name, arg_info in args_info._asdict().items(): + if name not in grad_inputs_dict: + result.append(pytree.tree_map(lambda x: None, arg_info)) + continue + result.append(grad_inputs_dict[name]) + return tuple(pytree.tree_leaves(result)) + +# Saves "stuff" (a pytree) onto the ctx object. Use unpack_saved to unpack it. +# autograd.Function prefers that users use ctx.save_for_backward to +# save Tensors (to avoid reference cycles) and for non-Tensors to go onto the +# ctx object. +def save_pytree_for_backward(ctx, stuff): + flat_stuff, spec = pytree.tree_flatten(stuff) + num_elts = len(flat_stuff) + tensor_idxs = [idx for idx, thing in enumerate(flat_stuff) + if isinstance(thing, torch.Tensor)] + non_tensor_idxs = [idx for idx, thing in enumerate(flat_stuff) + if not isinstance(thing, torch.Tensor)] + tensors = [thing for thing in flat_stuff if isinstance(thing, torch.Tensor)] + non_tensors = [thing for thing in flat_stuff if not isinstance(thing, torch.Tensor)] + + ctx.spec = spec + ctx.num_elts = num_elts + ctx.save_for_backward(*tensors) + ctx.tensor_idxs = tensor_idxs + ctx.saved_non_tensors = non_tensors + ctx.non_tensor_idxs = non_tensor_idxs + + +# Inverse operation to save_pytree_for_backward +def unpack_saved(ctx): + flat_stuff = [None] * ctx.num_elts + for tensor, idx in zip(ctx.saved_tensors, ctx.tensor_idxs): + flat_stuff[idx] = tensor + for non_tensor, idx in zip(ctx.saved_non_tensors, ctx.non_tensor_idxs): + flat_stuff[idx] = non_tensor + stuff = pytree.tree_unflatten(flat_stuff, ctx.spec) + return stuff diff --git a/shared/package-files/3a/3a39d2da15b6c154c4f5b12d71e1c72d80e72835dd7fd5a386137a24826cc5a4/subgraph_matcher.h b/shared/package-files/3a/3a39d2da15b6c154c4f5b12d71e1c72d80e72835dd7fd5a386137a24826cc5a4/subgraph_matcher.h new file mode 100644 index 0000000000000000000000000000000000000000..cd8d733da75549add7dbccbe90200ff38face7b2 --- /dev/null +++ b/shared/package-files/3a/3a39d2da15b6c154c4f5b12d71e1c72d80e72835dd7fd5a386137a24826cc5a4/subgraph_matcher.h @@ -0,0 +1,74 @@ +#pragma once + +#include + +#include +#include + +namespace torch { +namespace jit { + +/** + * \brief A structure describing a match of a pattern in a graph. + * + * The structure contains an anchor node, from which the match was found, and + * match-maps for nodes and values. A match-map specifies the correspondance + * between nodes in the pattern graph (match-map keys) with nodes in the actual + * graph (match-map values). We keep such maps for both nodes and values. + */ +struct Match { + Node* anchor; + std::unordered_map nodes_map; + std::unordered_map values_map; +}; + +/** + * \brief Find all matches of a \p PATTERN in a \p GRAPH. + * + * The function returns a vector of match-descriptors (see description of + * `struct Match`). + * + * Matching rules: + * - Pattern graph must contain a single block. + * - Matched subgraphs do not span across different blocks. + * - No uses outside the match are allowed, except for Param and Return nodes. + * Basically, we're matching hammocks, not arbitrary subgraphs. + * - The pattern graph must return only one value (i.e. it must have a single + * node leading to return). + * - Nodes that are not used in computation of the return value in the pattern + * graph are ignored during matching (IOW, we're essentially performing DCE on + * the pattern). + * - Pattern graph nodes cannot alias. TODO: the check not implemented yet. + * - Aliasing nodes in the graph cannot consitute a match (i.e. through all + * found matches, no nodes in the subgraph alias with each other). TODO: check + * not implemented yet. + * - The matcher will not mutate either the pattern graph or the matched graph. + * The matched graph is taken as non-const so that Match may contain non-const + * pointers. This enables clients of this API to use Match to drive mutations. + * + * Note [Multi-output Patterns] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * Subgraph matcher provides limited support for multi-output patterns. With a + * single output pattern, a single scan through the graph is sufficient to + * find all the matches: given a starting node (an "anchor"), we can + * deterministically check whether a pattern matches a subgraph corresponding to + * this anchor node. For a general case of multi-output patterns, we would have + * N anchors, which would result in M^N comparisons (M is the size of the + * graph). Clearly this is computationally prohibitive. + * + * To overcome this, we impose some constraints on the multi-output patterns + * that we accept. We require that checking whether the pattern matches a + * subgraph would still be fully determined by a single node in the graph. To + * achieve this, we designate the first output in the pattern as the "main" + * output and assume that we can traverse up from this node to match the + * entire pattern. + * + * Corrolary 1: the order of outputs in the pattern matters! + * Corollary 2: patterns cannot contain any nodes not participating in the main + * output computation. + */ +std::vector TORCH_API +findPatternMatches(const Graph& pattern, Graph& graph); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/3a/3a3c6585bcf65af1131849ea16ae171f43a2edde33620e27454dcb83203a81ec/dwarf_enums.h b/shared/package-files/3a/3a3c6585bcf65af1131849ea16ae171f43a2edde33620e27454dcb83203a81ec/dwarf_enums.h new file mode 100644 index 0000000000000000000000000000000000000000..91af24b34e1f97b02bedba2e59397495c5213719 --- /dev/null +++ b/shared/package-files/3a/3a3c6585bcf65af1131849ea16ae171f43a2edde33620e27454dcb83203a81ec/dwarf_enums.h @@ -0,0 +1,46 @@ +#pragma once + +enum { + DW_EH_PE_absptr = 0x00, + DW_EH_PE_omit = 0xff, + /* FDE data encoding. */ + DW_EH_PE_uleb128 = 0x01, + DW_EH_PE_udata2 = 0x02, + DW_EH_PE_udata4 = 0x03, + DW_EH_PE_udata8 = 0x04, + DW_EH_PE_sleb128 = 0x09, + DW_EH_PE_sdata2 = 0x0a, + DW_EH_PE_sdata4 = 0x0b, + DW_EH_PE_sdata8 = 0x0c, + DW_EH_PE_signed = 0x08, + /* FDE flags. */ + DW_EH_PE_pcrel = 0x10, + DW_EH_PE_textrel = 0x20, + DW_EH_PE_datarel = 0x30, + DW_EH_PE_funcrel = 0x40, + DW_EH_PE_aligned = 0x50, + DW_EH_PE_indirect = 0x80, +}; + +enum { + DW_CFA_nop = 0x0, + DW_CFA_advance_loc = 0x01, + DW_CFA_offset = 0x02, + DW_CFA_restore = 0x03, + DW_CFA_advance_loc1 = 0x02, + DW_CFA_advance_loc2 = 0x03, + DW_CFA_advance_loc4 = 0x04, + DW_CFA_restore_extended = 0x06, + DW_CFA_undefined = 0x07, + DW_CFA_register = 0x09, + DW_CFA_remember_state = 0x0a, + DW_CFA_restore_state = 0x0b, + DW_CFA_def_cfa = 0x0c, + DW_CFA_def_cfa_register = 0x0d, + DW_CFA_def_cfa_offset = 0x0e, + DW_CFA_def_cfa_expression = 0xf, + DW_CFA_expression = 0x10, + DW_CFA_offset_extended_sf = 0x11, + DW_CFA_GNU_args_size = 0x2e, + DW_OP_deref = 0x6, +}; diff --git a/shared/package-files/3a/3a3d71ba5882fac3c1fd0eb2697145a3d29f9685d2505ab360cc419739d81585/mlterm2 b/shared/package-files/3a/3a3d71ba5882fac3c1fd0eb2697145a3d29f9685d2505ab360cc419739d81585/mlterm2 new file mode 100644 index 0000000000000000000000000000000000000000..20b32e90e43fa6d2ec7fc4a98b12f841891e8ee4 Binary files /dev/null and b/shared/package-files/3a/3a3d71ba5882fac3c1fd0eb2697145a3d29f9685d2505ab360cc419739d81585/mlterm2 differ diff --git a/shared/package-files/3a/3a3e77bac7cd264cfc2f77d23a3984db4ae90b43548e1395cf86e6bbaf11dbcc/ArrayRef.h b/shared/package-files/3a/3a3e77bac7cd264cfc2f77d23a3984db4ae90b43548e1395cf86e6bbaf11dbcc/ArrayRef.h new file mode 100644 index 0000000000000000000000000000000000000000..0461d5953ed8a7783c82402ca4523b0b0a1ad465 --- /dev/null +++ b/shared/package-files/3a/3a3e77bac7cd264cfc2f77d23a3984db4ae90b43548e1395cf86e6bbaf11dbcc/ArrayRef.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/shared/package-files/3a/3a443f5361610c2534c27a4b5b22b87fa1ccba9f840318757ec427b3be216231/factorials.py b/shared/package-files/3a/3a443f5361610c2534c27a4b5b22b87fa1ccba9f840318757ec427b3be216231/factorials.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e2ee0223f77e14113200480708fcb94539837f --- /dev/null +++ b/shared/package-files/3a/3a443f5361610c2534c27a4b5b22b87fa1ccba9f840318757ec427b3be216231/factorials.py @@ -0,0 +1,1102 @@ +from __future__ import annotations +from functools import reduce + +from sympy.core import S, sympify, Dummy, Mod +from sympy.core.cache import cacheit +from sympy.core.function import Function, ArgumentIndexError, PoleError +from sympy.core.logic import fuzzy_and +from sympy.core.numbers import Integer, pi, I +from sympy.core.relational import Eq +from sympy.external.gmpy import HAS_GMPY, gmpy +from sympy.ntheory import sieve +from sympy.polys.polytools import Poly + +from math import factorial as _factorial, prod, sqrt as _sqrt + +class CombinatorialFunction(Function): + """Base class for combinatorial functions. """ + + def _eval_simplify(self, **kwargs): + from sympy.simplify.combsimp import combsimp + # combinatorial function with non-integer arguments is + # automatically passed to gammasimp + expr = combsimp(self) + measure = kwargs['measure'] + if measure(expr) <= kwargs['ratio']*measure(self): + return expr + return self + + +############################################################################### +######################## FACTORIAL and MULTI-FACTORIAL ######################## +############################################################################### + + +class factorial(CombinatorialFunction): + r"""Implementation of factorial function over nonnegative integers. + By convention (consistent with the gamma function and the binomial + coefficients), factorial of a negative integer is complex infinity. + + The factorial is very important in combinatorics where it gives + the number of ways in which `n` objects can be permuted. It also + arises in calculus, probability, number theory, etc. + + There is strict relation of factorial with gamma function. In + fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this + kind is very useful in case of combinatorial simplification. + + Computation of the factorial is done using two algorithms. For + small arguments a precomputed look up table is used. However for bigger + input algorithm Prime-Swing is used. It is the fastest algorithm + known and computes `n!` via prime factorization of special class + of numbers, called here the 'Swing Numbers'. + + Examples + ======== + + >>> from sympy import Symbol, factorial, S + >>> n = Symbol('n', integer=True) + + >>> factorial(0) + 1 + + >>> factorial(7) + 5040 + + >>> factorial(-2) + zoo + + >>> factorial(n) + factorial(n) + + >>> factorial(2*n) + factorial(2*n) + + >>> factorial(S(1)/2) + factorial(1/2) + + See Also + ======== + + factorial2, RisingFactorial, FallingFactorial + """ + + def fdiff(self, argindex=1): + from sympy.functions.special.gamma_functions import (gamma, polygamma) + if argindex == 1: + return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1) + else: + raise ArgumentIndexError(self, argindex) + + _small_swing = [ + 1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395, + 12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075, + 35102025, 5014575, 145422675, 9694845, 300540195, 300540195 + ] + + _small_factorials: list[int] = [] + + @classmethod + def _swing(cls, n): + if n < 33: + return cls._small_swing[n] + else: + N, primes = int(_sqrt(n)), [] + + for prime in sieve.primerange(3, N + 1): + p, q = 1, n + + while True: + q //= prime + + if q > 0: + if q & 1 == 1: + p *= prime + else: + break + + if p > 1: + primes.append(p) + + for prime in sieve.primerange(N + 1, n//3 + 1): + if (n // prime) & 1 == 1: + primes.append(prime) + + L_product = prod(sieve.primerange(n//2 + 1, n + 1)) + R_product = prod(primes) + + return L_product*R_product + + @classmethod + def _recursive(cls, n): + if n < 2: + return 1 + else: + return (cls._recursive(n//2)**2)*cls._swing(n) + + @classmethod + def eval(cls, n): + n = sympify(n) + + if n.is_Number: + if n.is_zero: + return S.One + elif n is S.Infinity: + return S.Infinity + elif n.is_Integer: + if n.is_negative: + return S.ComplexInfinity + else: + n = n.p + + if n < 20: + if not cls._small_factorials: + result = 1 + for i in range(1, 20): + result *= i + cls._small_factorials.append(result) + result = cls._small_factorials[n-1] + + # GMPY factorial is faster, use it when available + elif HAS_GMPY: + result = gmpy.fac(n) + + else: + bits = bin(n).count('1') + result = cls._recursive(n)*2**(n - bits) + + return Integer(result) + + def _facmod(self, n, q): + res, N = 1, int(_sqrt(n)) + + # Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ... + # for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m, + # occur consecutively and are grouped together in pw[m] for + # simultaneous exponentiation at a later stage + pw = [1]*N + + m = 2 # to initialize the if condition below + for prime in sieve.primerange(2, n + 1): + if m > 1: + m, y = 0, n // prime + while y: + m += y + y //= prime + if m < N: + pw[m] = pw[m]*prime % q + else: + res = res*pow(prime, m, q) % q + + for ex, bs in enumerate(pw): + if ex == 0 or bs == 1: + continue + if bs == 0: + return 0 + res = res*pow(bs, ex, q) % q + + return res + + def _eval_Mod(self, q): + n = self.args[0] + if n.is_integer and n.is_nonnegative and q.is_integer: + aq = abs(q) + d = aq - n + if d.is_nonpositive: + return S.Zero + else: + isprime = aq.is_prime + if d == 1: + # Apply Wilson's theorem (if a natural number n > 1 + # is a prime number, then (n-1)! = -1 mod n) and + # its inverse (if n > 4 is a composite number, then + # (n-1)! = 0 mod n) + if isprime: + return -1 % q + elif isprime is False and (aq - 6).is_nonnegative: + return S.Zero + elif n.is_Integer and q.is_Integer: + n, d, aq = map(int, (n, d, aq)) + if isprime and (d - 1 < n): + fc = self._facmod(d - 1, aq) + fc = pow(fc, aq - 2, aq) + if d%2: + fc = -fc + else: + fc = self._facmod(n, aq) + + return fc % q + + def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): + from sympy.functions.special.gamma_functions import gamma + return gamma(n + 1) + + def _eval_rewrite_as_Product(self, n, **kwargs): + from sympy.concrete.products import Product + if n.is_nonnegative and n.is_integer: + i = Dummy('i', integer=True) + return Product(i, (i, 1, n)) + + def _eval_is_integer(self): + if self.args[0].is_integer and self.args[0].is_nonnegative: + return True + + def _eval_is_positive(self): + if self.args[0].is_integer and self.args[0].is_nonnegative: + return True + + def _eval_is_even(self): + x = self.args[0] + if x.is_integer and x.is_nonnegative: + return (x - 2).is_nonnegative + + def _eval_is_composite(self): + x = self.args[0] + if x.is_integer and x.is_nonnegative: + return (x - 3).is_nonnegative + + def _eval_is_real(self): + x = self.args[0] + if x.is_nonnegative or x.is_noninteger: + return True + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + arg = self.args[0].as_leading_term(x) + arg0 = arg.subs(x, 0) + if arg0.is_zero: + return S.One + elif not arg0.is_infinite: + return self.func(arg) + raise PoleError("Cannot expand %s around 0" % (self)) + +class MultiFactorial(CombinatorialFunction): + pass + + +class subfactorial(CombinatorialFunction): + r"""The subfactorial counts the derangements of $n$ items and is + defined for non-negative integers as: + + .. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\ + (n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases} + + It can also be written as ``int(round(n!/exp(1)))`` but the + recursive definition with caching is implemented for this function. + + An interesting analytic expression is the following [2]_ + + .. math:: !x = \Gamma(x + 1, -1)/e + + which is valid for non-negative integers `x`. The above formula + is not very useful in case of non-integers. `\Gamma(x + 1, -1)` is + single-valued only for integral arguments `x`, elsewhere on the positive + real axis it has an infinite number of branches none of which are real. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Subfactorial + .. [2] https://mathworld.wolfram.com/Subfactorial.html + + Examples + ======== + + >>> from sympy import subfactorial + >>> from sympy.abc import n + >>> subfactorial(n + 1) + subfactorial(n + 1) + >>> subfactorial(5) + 44 + + See Also + ======== + + factorial, uppergamma, + sympy.utilities.iterables.generate_derangements + """ + + @classmethod + @cacheit + def _eval(self, n): + if not n: + return S.One + elif n == 1: + return S.Zero + else: + z1, z2 = 1, 0 + for i in range(2, n + 1): + z1, z2 = z2, (i - 1)*(z2 + z1) + return z2 + + @classmethod + def eval(cls, arg): + if arg.is_Number: + if arg.is_Integer and arg.is_nonnegative: + return cls._eval(arg) + elif arg is S.NaN: + return S.NaN + elif arg is S.Infinity: + return S.Infinity + + def _eval_is_even(self): + if self.args[0].is_odd and self.args[0].is_nonnegative: + return True + + def _eval_is_integer(self): + if self.args[0].is_integer and self.args[0].is_nonnegative: + return True + + def _eval_rewrite_as_factorial(self, arg, **kwargs): + from sympy.concrete.summations import summation + i = Dummy('i') + f = S.NegativeOne**i / factorial(i) + return factorial(arg) * summation(f, (i, 0, arg)) + + def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs): + from sympy.functions.elementary.exponential import exp + from sympy.functions.special.gamma_functions import (gamma, lowergamma) + return (S.NegativeOne**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1) + + gamma(arg + 1))*exp(-1) + + def _eval_rewrite_as_uppergamma(self, arg, **kwargs): + from sympy.functions.special.gamma_functions import uppergamma + return uppergamma(arg + 1, -1)/S.Exp1 + + def _eval_is_nonnegative(self): + if self.args[0].is_integer and self.args[0].is_nonnegative: + return True + + def _eval_is_odd(self): + if self.args[0].is_even and self.args[0].is_nonnegative: + return True + + +class factorial2(CombinatorialFunction): + r"""The double factorial `n!!`, not to be confused with `(n!)!` + + The double factorial is defined for nonnegative integers and for odd + negative integers as: + + .. math:: n!! = \begin{cases} 1 & n = 0 \\ + n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\ + n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\ + (n+2)!!/(n+2) & n\ \text{negative odd} \end{cases} + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Double_factorial + + Examples + ======== + + >>> from sympy import factorial2, var + >>> n = var('n') + >>> n + n + >>> factorial2(n + 1) + factorial2(n + 1) + >>> factorial2(5) + 15 + >>> factorial2(-1) + 1 + >>> factorial2(-5) + 1/3 + + See Also + ======== + + factorial, RisingFactorial, FallingFactorial + """ + + @classmethod + def eval(cls, arg): + # TODO: extend this to complex numbers? + + if arg.is_Number: + if not arg.is_Integer: + raise ValueError("argument must be nonnegative integer " + "or negative odd integer") + + # This implementation is faster than the recursive one + # It also avoids "maximum recursion depth exceeded" runtime error + if arg.is_nonnegative: + if arg.is_even: + k = arg / 2 + return 2**k * factorial(k) + return factorial(arg) / factorial2(arg - 1) + + + if arg.is_odd: + return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg) + raise ValueError("argument must be nonnegative integer " + "or negative odd integer") + + + def _eval_is_even(self): + # Double factorial is even for every positive even input + n = self.args[0] + if n.is_integer: + if n.is_odd: + return False + if n.is_even: + if n.is_positive: + return True + if n.is_zero: + return False + + def _eval_is_integer(self): + # Double factorial is an integer for every nonnegative input, and for + # -1 and -3 + n = self.args[0] + if n.is_integer: + if (n + 1).is_nonnegative: + return True + if n.is_odd: + return (n + 3).is_nonnegative + + def _eval_is_odd(self): + # Double factorial is odd for every odd input not smaller than -3, and + # for 0 + n = self.args[0] + if n.is_odd: + return (n + 3).is_nonnegative + if n.is_even: + if n.is_positive: + return False + if n.is_zero: + return True + + def _eval_is_positive(self): + # Double factorial is positive for every nonnegative input, and for + # every odd negative input which is of the form -1-4k for an + # nonnegative integer k + n = self.args[0] + if n.is_integer: + if (n + 1).is_nonnegative: + return True + if n.is_odd: + return ((n + 1) / 2).is_even + + def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.functions.elementary.piecewise import Piecewise + from sympy.functions.special.gamma_functions import gamma + return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)), + (sqrt(2/pi), Eq(Mod(n, 2), 1))) + + +############################################################################### +######################## RISING and FALLING FACTORIALS ######################## +############################################################################### + + +class RisingFactorial(CombinatorialFunction): + r""" + Rising factorial (also called Pochhammer symbol [1]_) is a double valued + function arising in concrete mathematics, hypergeometric functions + and series expansions. It is defined by: + + .. math:: \texttt{rf(y, k)} = (x)^k = x \cdot (x+1) \cdots (x+k-1) + + where `x` can be arbitrary expression and `k` is an integer. For + more information check "Concrete mathematics" by Graham, pp. 66 + or visit https://mathworld.wolfram.com/RisingFactorial.html page. + + When `x` is a `~.Poly` instance of degree $\ge 1$ with a single variable, + `(x)^k = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the + variable of `x`. This is as described in [2]_. + + Examples + ======== + + >>> from sympy import rf, Poly + >>> from sympy.abc import x + >>> rf(x, 0) + 1 + >>> rf(1, 5) + 120 + >>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x) + True + >>> rf(Poly(x**3, x), 2) + Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ') + + Rewriting is complicated unless the relationship between + the arguments is known, but rising factorial can + be rewritten in terms of gamma, factorial, binomial, + and falling factorial. + + >>> from sympy import Symbol, factorial, ff, binomial, gamma + >>> n = Symbol('n', integer=True, positive=True) + >>> R = rf(n, n + 2) + >>> for i in (rf, ff, factorial, binomial, gamma): + ... R.rewrite(i) + ... + RisingFactorial(n, n + 2) + FallingFactorial(2*n + 1, n + 2) + factorial(2*n + 1)/factorial(n - 1) + binomial(2*n + 1, n + 2)*factorial(n + 2) + gamma(2*n + 2)/gamma(n) + + See Also + ======== + + factorial, factorial2, FallingFactorial + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol + .. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic + Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268, + 1995. + + """ + + @classmethod + def eval(cls, x, k): + x = sympify(x) + k = sympify(k) + + if x is S.NaN or k is S.NaN: + return S.NaN + elif x is S.One: + return factorial(k) + elif k.is_Integer: + if k.is_zero: + return S.One + else: + if k.is_positive: + if x is S.Infinity: + return S.Infinity + elif x is S.NegativeInfinity: + if k.is_odd: + return S.NegativeInfinity + else: + return S.Infinity + else: + if isinstance(x, Poly): + gens = x.gens + if len(gens)!= 1: + raise ValueError("rf only defined for " + "polynomials on one generator") + else: + return reduce(lambda r, i: + r*(x.shift(i)), + range(int(k)), 1) + else: + return reduce(lambda r, i: r*(x + i), + range(int(k)), 1) + + else: + if x is S.Infinity: + return S.Infinity + elif x is S.NegativeInfinity: + return S.Infinity + else: + if isinstance(x, Poly): + gens = x.gens + if len(gens)!= 1: + raise ValueError("rf only defined for " + "polynomials on one generator") + else: + return 1/reduce(lambda r, i: + r*(x.shift(-i)), + range(1, abs(int(k)) + 1), 1) + else: + return 1/reduce(lambda r, i: + r*(x - i), + range(1, abs(int(k)) + 1), 1) + + if k.is_integer == False: + if x.is_integer and x.is_negative: + return S.Zero + + def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs): + from sympy.functions.elementary.piecewise import Piecewise + from sympy.functions.special.gamma_functions import gamma + if not piecewise: + if (x <= 0) == True: + return S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1) + return gamma(x + k) / gamma(x) + return Piecewise( + (gamma(x + k) / gamma(x), x > 0), + (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1), True)) + + def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs): + return FallingFactorial(x + k - 1, k) + + def _eval_rewrite_as_factorial(self, x, k, **kwargs): + from sympy.functions.elementary.piecewise import Piecewise + if x.is_integer and k.is_integer: + return Piecewise( + (factorial(k + x - 1)/factorial(x - 1), x > 0), + (S.NegativeOne**k*factorial(-x)/factorial(-k - x), True)) + + def _eval_rewrite_as_binomial(self, x, k, **kwargs): + if k.is_integer: + return factorial(k) * binomial(x + k - 1, k) + + def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs): + from sympy.functions.special.gamma_functions import gamma + if limitvar: + k_lim = k.subs(limitvar, S.Infinity) + if k_lim is S.Infinity: + return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x)) + elif k_lim is S.NegativeInfinity: + return (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True)) + return self.rewrite(gamma).rewrite('tractable', deep=True) + + def _eval_is_integer(self): + return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer, + self.args[1].is_nonnegative)) + + +class FallingFactorial(CombinatorialFunction): + r""" + Falling factorial (related to rising factorial) is a double valued + function arising in concrete mathematics, hypergeometric functions + and series expansions. It is defined by + + .. math:: \texttt{ff(x, k)} = (x)_k = x \cdot (x-1) \cdots (x-k+1) + + where `x` can be arbitrary expression and `k` is an integer. For + more information check "Concrete mathematics" by Graham, pp. 66 + or [1]_. + + When `x` is a `~.Poly` instance of degree $\ge 1$ with single variable, + `(x)_k = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the + variable of `x`. This is as described in + + >>> from sympy import ff, Poly, Symbol + >>> from sympy.abc import x + >>> n = Symbol('n', integer=True) + + >>> ff(x, 0) + 1 + >>> ff(5, 5) + 120 + >>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4) + True + >>> ff(Poly(x**2, x), 2) + Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ') + >>> ff(n, n) + factorial(n) + + Rewriting is complicated unless the relationship between + the arguments is known, but falling factorial can + be rewritten in terms of gamma, factorial and binomial + and rising factorial. + + >>> from sympy import factorial, rf, gamma, binomial, Symbol + >>> n = Symbol('n', integer=True, positive=True) + >>> F = ff(n, n - 2) + >>> for i in (rf, ff, factorial, binomial, gamma): + ... F.rewrite(i) + ... + RisingFactorial(3, n - 2) + FallingFactorial(n, n - 2) + factorial(n)/2 + binomial(n, n - 2)*factorial(n - 2) + gamma(n + 1)/2 + + See Also + ======== + + factorial, factorial2, RisingFactorial + + References + ========== + + .. [1] https://mathworld.wolfram.com/FallingFactorial.html + .. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic + Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268, + 1995. + + """ + + @classmethod + def eval(cls, x, k): + x = sympify(x) + k = sympify(k) + + if x is S.NaN or k is S.NaN: + return S.NaN + elif k.is_integer and x == k: + return factorial(x) + elif k.is_Integer: + if k.is_zero: + return S.One + else: + if k.is_positive: + if x is S.Infinity: + return S.Infinity + elif x is S.NegativeInfinity: + if k.is_odd: + return S.NegativeInfinity + else: + return S.Infinity + else: + if isinstance(x, Poly): + gens = x.gens + if len(gens)!= 1: + raise ValueError("ff only defined for " + "polynomials on one generator") + else: + return reduce(lambda r, i: + r*(x.shift(-i)), + range(int(k)), 1) + else: + return reduce(lambda r, i: r*(x - i), + range(int(k)), 1) + else: + if x is S.Infinity: + return S.Infinity + elif x is S.NegativeInfinity: + return S.Infinity + else: + if isinstance(x, Poly): + gens = x.gens + if len(gens)!= 1: + raise ValueError("rf only defined for " + "polynomials on one generator") + else: + return 1/reduce(lambda r, i: + r*(x.shift(i)), + range(1, abs(int(k)) + 1), 1) + else: + return 1/reduce(lambda r, i: r*(x + i), + range(1, abs(int(k)) + 1), 1) + + def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs): + from sympy.functions.elementary.piecewise import Piecewise + from sympy.functions.special.gamma_functions import gamma + if not piecewise: + if (x < 0) == True: + return S.NegativeOne**k*gamma(k - x) / gamma(-x) + return gamma(x + 1) / gamma(x - k + 1) + return Piecewise( + (gamma(x + 1) / gamma(x - k + 1), x >= 0), + (S.NegativeOne**k*gamma(k - x) / gamma(-x), True)) + + def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs): + return rf(x - k + 1, k) + + def _eval_rewrite_as_binomial(self, x, k, **kwargs): + if k.is_integer: + return factorial(k) * binomial(x, k) + + def _eval_rewrite_as_factorial(self, x, k, **kwargs): + from sympy.functions.elementary.piecewise import Piecewise + if x.is_integer and k.is_integer: + return Piecewise( + (factorial(x)/factorial(-k + x), x >= 0), + (S.NegativeOne**k*factorial(k - x - 1)/factorial(-x - 1), True)) + + def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs): + from sympy.functions.special.gamma_functions import gamma + if limitvar: + k_lim = k.subs(limitvar, S.Infinity) + if k_lim is S.Infinity: + return (S.NegativeOne**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x)) + elif k_lim is S.NegativeInfinity: + return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True)) + return self.rewrite(gamma).rewrite('tractable', deep=True) + + def _eval_is_integer(self): + return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer, + self.args[1].is_nonnegative)) + + +rf = RisingFactorial +ff = FallingFactorial + +############################################################################### +########################### BINOMIAL COEFFICIENTS ############################# +############################################################################### + + +class binomial(CombinatorialFunction): + r"""Implementation of the binomial coefficient. It can be defined + in two ways depending on its desired interpretation: + + .. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\ + \binom{n}{k} = \frac{(n)_k}{k!} + + First, in a strict combinatorial sense it defines the + number of ways we can choose `k` elements from a set of + `n` elements. In this case both arguments are nonnegative + integers and binomial is computed using an efficient + algorithm based on prime factorization. + + The other definition is generalization for arbitrary `n`, + however `k` must also be nonnegative. This case is very + useful when evaluating summations. + + For the sake of convenience, for negative integer `k` this function + will return zero no matter the other argument. + + To expand the binomial when `n` is a symbol, use either + ``expand_func()`` or ``expand(func=True)``. The former will keep + the polynomial in factored form while the latter will expand the + polynomial itself. See examples for details. + + Examples + ======== + + >>> from sympy import Symbol, Rational, binomial, expand_func + >>> n = Symbol('n', integer=True, positive=True) + + >>> binomial(15, 8) + 6435 + + >>> binomial(n, -1) + 0 + + Rows of Pascal's triangle can be generated with the binomial function: + + >>> for N in range(8): + ... print([binomial(N, i) for i in range(N + 1)]) + ... + [1] + [1, 1] + [1, 2, 1] + [1, 3, 3, 1] + [1, 4, 6, 4, 1] + [1, 5, 10, 10, 5, 1] + [1, 6, 15, 20, 15, 6, 1] + [1, 7, 21, 35, 35, 21, 7, 1] + + As can a given diagonal, e.g. the 4th diagonal: + + >>> N = -4 + >>> [binomial(N, i) for i in range(1 - N)] + [1, -4, 10, -20, 35] + + >>> binomial(Rational(5, 4), 3) + -5/128 + >>> binomial(Rational(-5, 4), 3) + -195/128 + + >>> binomial(n, 3) + binomial(n, 3) + + >>> binomial(n, 3).expand(func=True) + n**3/6 - n**2/2 + n/3 + + >>> expand_func(binomial(n, 3)) + n*(n - 2)*(n - 1)/6 + + References + ========== + + .. [1] https://www.johndcook.com/blog/binomial_coefficients/ + + """ + + def fdiff(self, argindex=1): + from sympy.functions.special.gamma_functions import polygamma + if argindex == 1: + # https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/ + n, k = self.args + return binomial(n, k)*(polygamma(0, n + 1) - \ + polygamma(0, n - k + 1)) + elif argindex == 2: + # https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/ + n, k = self.args + return binomial(n, k)*(polygamma(0, n - k + 1) - \ + polygamma(0, k + 1)) + else: + raise ArgumentIndexError(self, argindex) + + @classmethod + def _eval(self, n, k): + # n.is_Number and k.is_Integer and k != 1 and n != k + + if k.is_Integer: + if n.is_Integer and n >= 0: + n, k = int(n), int(k) + + if k > n: + return S.Zero + elif k > n // 2: + k = n - k + + if HAS_GMPY: + return Integer(gmpy.bincoef(n, k)) + + d, result = n - k, 1 + for i in range(1, k + 1): + d += 1 + result = result * d // i + return Integer(result) + else: + d, result = n - k, 1 + for i in range(1, k + 1): + d += 1 + result *= d + return result / _factorial(k) + + @classmethod + def eval(cls, n, k): + n, k = map(sympify, (n, k)) + d = n - k + n_nonneg, n_isint = n.is_nonnegative, n.is_integer + if k.is_zero or ((n_nonneg or n_isint is False) + and d.is_zero): + return S.One + if (k - 1).is_zero or ((n_nonneg or n_isint is False) + and (d - 1).is_zero): + return n + if k.is_integer: + if k.is_negative or (n_nonneg and n_isint and d.is_negative): + return S.Zero + elif n.is_number: + res = cls._eval(n, k) + return res.expand(basic=True) if res else res + elif n_nonneg is False and n_isint: + # a special case when binomial evaluates to complex infinity + return S.ComplexInfinity + elif k.is_number: + from sympy.functions.special.gamma_functions import gamma + return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) + + def _eval_Mod(self, q): + n, k = self.args + + if any(x.is_integer is False for x in (n, k, q)): + raise ValueError("Integers expected for binomial Mod") + + if all(x.is_Integer for x in (n, k, q)): + n, k = map(int, (n, k)) + aq, res = abs(q), 1 + + # handle negative integers k or n + if k < 0: + return S.Zero + if n < 0: + n = -n + k - 1 + res = -1 if k%2 else 1 + + # non negative integers k and n + if k > n: + return S.Zero + + isprime = aq.is_prime + aq = int(aq) + if isprime: + if aq < n: + # use Lucas Theorem + N, K = n, k + while N or K: + res = res*binomial(N % aq, K % aq) % aq + N, K = N // aq, K // aq + + else: + # use Factorial Modulo + d = n - k + if k > d: + k, d = d, k + kf = 1 + for i in range(2, k + 1): + kf = kf*i % aq + df = kf + for i in range(k + 1, d + 1): + df = df*i % aq + res *= df + for i in range(d + 1, n + 1): + res = res*i % aq + + res *= pow(kf*df % aq, aq - 2, aq) + res %= aq + + else: + # Binomial Factorization is performed by calculating the + # exponents of primes <= n in `n! /(k! (n - k)!)`, + # for non-negative integers n and k. As the exponent of + # prime in n! is e_p(n) = [n/p] + [n/p**2] + ... + # the exponent of prime in binomial(n, k) would be + # e_p(n) - e_p(k) - e_p(n - k) + M = int(_sqrt(n)) + for prime in sieve.primerange(2, n + 1): + if prime > n - k: + res = res*prime % aq + elif prime > n // 2: + continue + elif prime > M: + if n % prime < k % prime: + res = res*prime % aq + else: + N, K = n, k + exp = a = 0 + + while N > 0: + a = int((N % prime) < (K % prime + a)) + N, K = N // prime, K // prime + exp += a + + if exp > 0: + res *= pow(prime, exp, aq) + res %= aq + + return S(res % q) + + def _eval_expand_func(self, **hints): + """ + Function to expand binomial(n, k) when m is positive integer + Also, + n is self.args[0] and k is self.args[1] while using binomial(n, k) + """ + n = self.args[0] + if n.is_Number: + return binomial(*self.args) + + k = self.args[1] + if (n-k).is_Integer: + k = n - k + + if k.is_Integer: + if k.is_zero: + return S.One + elif k.is_negative: + return S.Zero + else: + n, result = self.args[0], 1 + for i in range(1, k + 1): + result *= n - k + i + return result / _factorial(k) + else: + return binomial(*self.args) + + def _eval_rewrite_as_factorial(self, n, k, **kwargs): + return factorial(n)/(factorial(k)*factorial(n - k)) + + def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs): + from sympy.functions.special.gamma_functions import gamma + return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) + + def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs): + return self._eval_rewrite_as_gamma(n, k).rewrite('tractable') + + def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs): + if k.is_integer: + return ff(n, k) / factorial(k) + + def _eval_is_integer(self): + n, k = self.args + if n.is_integer and k.is_integer: + return True + elif k.is_integer is False: + return False + + def _eval_is_nonnegative(self): + n, k = self.args + if n.is_integer and k.is_integer: + if n.is_nonnegative or k.is_negative or k.is_even: + return True + elif k.is_even is False: + return False + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + from sympy.functions.special.gamma_functions import gamma + return self.rewrite(gamma)._eval_as_leading_term(x, logx=logx, cdir=cdir) diff --git a/shared/package-files/3a/3a469dadc09951da772ac079ab67e14f2000096d768035f15bf03800d19c02a6/__init__.py b/shared/package-files/3a/3a469dadc09951da772ac079ab67e14f2000096d768035f15bf03800d19c02a6/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e47b9606b7744620f41e9888b7c064f9c504520 --- /dev/null +++ b/shared/package-files/3a/3a469dadc09951da772ac079ab67e14f2000096d768035f15bf03800d19c02a6/__init__.py @@ -0,0 +1,12 @@ +from typing import Final + +from dask.array import * # noqa: F403 + +# These imports may overwrite names from the import * above. +from ._aliases import * # noqa: F403 + +__array_api_version__: Final = "2024.12" + +# See the comment in the numpy __init__.py +__import__(__package__ + '.linalg') +__import__(__package__ + '.fft') diff --git a/shared/package-files/3a/3a46e683401e4886f26737fc8baf5ff24b53a0c89b339b5d5e46654b9ffebab7/Reduce.h b/shared/package-files/3a/3a46e683401e4886f26737fc8baf5ff24b53a0c89b339b5d5e46654b9ffebab7/Reduce.h new file mode 100644 index 0000000000000000000000000000000000000000..26155373be589c14a232af04397c7c85c909270b --- /dev/null +++ b/shared/package-files/3a/3a46e683401e4886f26737fc8baf5ff24b53a0c89b339b5d5e46654b9ffebab7/Reduce.h @@ -0,0 +1,314 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace at { namespace native { inline namespace CPU_CAPABILITY { + +using namespace vec; + +#define VEC_LOOP_HEADER(func_t, data) \ + using scalar_t = typename function_traits::result_type; \ + using Vec = Vectorized; \ + char* out_ptr = data[0]; \ + (void) out_ptr; + +// reduction that is contiguous over the input in dim 0 +template +static inline bool is_contiguous_reduction(const int64_t* strides) { + return strides[0] == 0 && + strides[1] == sizeof(typename traits::arg2_t); +} + +// reduction that is contiguous over the input in dim 1 +template +static inline bool is_outer_reduction(const int64_t* strides) { + return strides[0] == 0 && + strides[2] == sizeof(typename traits::result_type) && + strides[3] == sizeof(typename traits::arg2_t); +} + +template +static inline void vectorized_reduction(char** data, int64_t n, int64_t stride, + func_t op, vec_func_t vop, bool reduce) { + VEC_LOOP_HEADER(func_t, data) + const char* in1_ptr = data[1]; + Vec acc[4]; + for (const auto j : c10::irange(4)) { + acc[j] = Vec::loadu(in1_ptr + j * Vec::size() * sizeof(scalar_t)); + } + for (const auto i : c10::irange(1, n)) { + const char* ptr = in1_ptr + stride * i; + acc[0] = vop(acc[0], Vec::loadu(ptr + (0 * Vec::size() * sizeof(scalar_t)))); + acc[1] = vop(acc[1], Vec::loadu(ptr + (1 * Vec::size() * sizeof(scalar_t)))); + acc[2] = vop(acc[2], Vec::loadu(ptr + (2 * Vec::size() * sizeof(scalar_t)))); + acc[3] = vop(acc[3], Vec::loadu(ptr + (3 * Vec::size() * sizeof(scalar_t)))); + } + if (reduce) { + scalar_t buffer[Vec::size()]; + acc[0] = vop(vop(acc[0], acc[1]), vop(acc[2], acc[3])); + acc[0].store(buffer); + for (const auto j : c10::irange(1, Vec::size())) { + buffer[0] = op(buffer[0], buffer[j]); + } + auto dst = (scalar_t*)out_ptr; + *dst = op(*dst, buffer[0]); + } else { + for (const auto j : c10::irange(4)) { + auto dst = out_ptr + j * Vec::size() * sizeof(scalar_t); + acc[j] = vop(acc[j], Vec::loadu(dst)); + acc[j].store(dst); + } + } +} + +template +static inline void UNARY_OUTER_LOOP(char* data[2], const int64_t strides[2], int64_t n, F f) { + for (const auto j C10_UNUSED : c10::irange(n)) { + f(); + data[0] += strides[0]; + data[1] += strides[1]; + } +} + +// computes the reduction out = op(out, in) +template +static inline void vectorized_inner_reduction(char** data, int64_t n, func_t op, vec_func_t vop) { + VEC_LOOP_HEADER(func_t, data) + int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t); + int64_t count = n / (4 * Vec::size()); + if (count > 0) { + vectorized_reduction(data, count, vector_stride, op, vop, /*reduce=*/true); + } + char* ptrs[3] = { data[0], data[0], data[1] }; + int64_t strides[] = { 0, 0, sizeof(scalar_t) }; + basic_loop(ptrs, strides, count * 4 * Vec::size(), n, op); +} + +// computes the reduction out = op(out, in) +template +static inline void vectorized_outer_reduction(char** data, int64_t inner_stride, int64_t size0, int64_t size1, func_t op, vec_func_t vop) { + VEC_LOOP_HEADER(func_t, data) + + // reduce down each column of 4 * Vec::size() elements (128 or 256 bytes) +#if defined(CPU_CAPABILITY_AVX512) + int64_t outer_stride[2] = { 256, 256 }; +#else + int64_t outer_stride[2] = { 128, 128 }; +#endif + UNARY_OUTER_LOOP(data, outer_stride, size1 / (4 * Vec::size()), [&] { + vectorized_reduction(data, size0, inner_stride, op, vop, /*reduce=*/false); + }); + + // reduce down the remaining columns + int64_t step[] = { sizeof(scalar_t), sizeof(scalar_t) }; + int64_t remaining = size1 % (4 * Vec::size()); + UNARY_OUTER_LOOP(data, step, remaining, [&] { + char* ptrs[3] = { data[0], data[0], data[1] }; + int64_t strides[] = { 0, 0, inner_stride }; + basic_loop(ptrs, strides, 0, size0, op); + }); +} + +template +static void set_result(const int index, const res_t result, const TensorIteratorBase &iter, const int num_outputs) { + // static_assert(std::is_same::value, "data types must match"); + if (index < num_outputs) { + char *out = (char *) iter.data_ptr(index); + *(res_t *) out = result; + } +} + +template +static void set_results(const res_t result, const TensorIteratorBase &iter, const int num_outputs) { + AT_ASSERT(num_outputs == 1); + set_result(0, result, iter, num_outputs); +} + +template +static inline typename std::enable_if::type +for_each_in_tuple(const std::tuple& /*t*/, const TensorIteratorBase& /*iter*/, const int /*num_outputs*/) { + return i; +} + +template +static inline typename std::enable_if::type +for_each_in_tuple(const std::tuple& t, const TensorIteratorBase &iter, const int num_outputs) { + if (i < (size_t)num_outputs) { + set_result(i, std::get(t), iter, num_outputs); + return for_each_in_tuple(t, iter, num_outputs); + } + return i; +} + +template +static void set_results(const std::tuple& result, const TensorIteratorBase &iter, const int num_outputs) { + AT_ASSERT(num_outputs >= 1); + std::size_t result_size = for_each_in_tuple(result, iter, num_outputs); + AT_ASSERT((size_t)num_outputs == result_size); +} + +template +struct all_same : std::conjunction< + std::is_same... +> {}; + +// data_t is the input/output data type. +// acc_t is a type that contains all the necessary data +// to continue reducing. +// index_t is a one-dimensional index +// +// ops_t is such that &ops_t::reduce, &ops_t::combine, and &ops_t::project exist and satisfy +// the following. +// reduce: (acc_t, data_t, index_t) -> acc_t adds one data point to the accumulated value. +// combine: (acc_t, acc_t) -> acc_t combines two accumulated values into one. +// project: acc_t -> out_t finishes the reduction, getting the required output. +// +// Additionally, acc_t must be default-constructible: +// acc_t {} is an identity for combine, +// and project(acc_t {}) is the value of the operation on zero elements. +// +// The point of `combine` is to support parallelization - +// the idea is to one sequence of `reduce` calls per thread of execution, +// and then to combine them at the end with `combine`. +// +// If there is more than one output element, +// our parallelization strategy is to use one thread for each of them, +// which means that `combine` will never be called. +// +// If, on the other hand, there is only one, then we split the input into +// into several pieces, reduce each separately, and then combine them. + +template +void binary_kernel_reduce(TensorIteratorBase& iter, ops_t ops, init_t init) { + using rf_t = decltype(&ops_t::reduce); + using cf_t = decltype(&ops_t::combine); + using pf_t = decltype(&ops_t::project); + using r_traits = binary_function_traits; + using c_traits = binary_function_traits; + using p_traits = unary_function_traits; + using acc_t = typename p_traits::arg1_t; + using data_t = typename r_traits::arg2_t; + static_assert( + all_same< + acc_t, + init_t, + typename r_traits::arg1_t, + typename r_traits::result_type, + typename c_traits::arg1_t, + typename c_traits::arg2_t, + typename c_traits::result_type>::value, + "all accumulate types must match"); + static_assert( + std::is_default_constructible::value, + "the accumulate type must be default-constructible" + ); + const int num_outputs = iter.noutputs(); + iter.foreach_reduced_elt([&ops, &init, num_outputs](TensorIteratorBase &sub_iter) { + auto reduction_body = [&ops, &sub_iter, num_outputs](acc_t acc, int64_t begin, int64_t end) -> acc_t { + int ntensors = sub_iter.ntensors(); + sub_iter.serial_for_each([&acc, &ops, num_outputs, ntensors, begin](char** data, const int64_t* strides, int64_t size) { + AT_ASSERT(ntensors - num_outputs == 1); + char *in = data[ntensors - 1]; + int64_t stride = strides[ntensors - 1]; + for (const auto i : c10::irange(size)) { + acc = ops.reduce(acc, c10::load(in), begin + i); + in += stride; + } + }, {begin, end}); + return ops.translate_idx(acc, sub_iter.view_offsets()[0]); + }; + acc_t total_acc = init; + auto numel = sub_iter.numel(); + if (numel < at::internal::GRAIN_SIZE || at::get_num_threads() == 1 || + at::in_parallel_region()) { + total_acc = reduction_body(total_acc, 0, numel); + } else { + int max_threads = at::get_num_threads(); + AT_ASSERT(max_threads > 0); + static_assert( + !std::is_same::value, + "Concurrently modifying different references into std::vector is UB." + ); + std::vector buffer((unsigned)max_threads, init); + at::parallel_for(0, numel, internal::GRAIN_SIZE, + [&](int64_t begin, int64_t end) { + auto& acc = buffer[at::get_thread_num()]; + acc = reduction_body(acc, begin, end); + } + ); + for (const auto i : c10::irange(max_threads)) { + total_acc = ops.combine(total_acc, buffer[i]); + } + } + set_results(ops.project(total_acc), sub_iter, num_outputs); + }); +} + +template +void binary_kernel_reduce_vec(TensorIteratorBase& iter, func_t op, vec_func_t vop, double ident = 0) { + using traits = binary_function_traits; + static_assert( + all_same< + typename traits::result_type, + typename traits::arg1_t, + typename traits::arg2_t>::value, + "all types must match"); + + iter.output_base().fill_(ident); + iter.parallel_reduce([&](char** data, const int64_t* strides, int64_t size0, int64_t size1) { + int64_t outer_strides[] = { strides[2], strides[3] }; + if (is_contiguous_reduction(strides)) { + // input is contiguous in dim 0, output is reduced in dim 0 + UNARY_OUTER_LOOP(data, outer_strides, size1, [&] { + vectorized_inner_reduction(data, size0, op, vop); + }); + } else if (is_outer_reduction(strides)) { + // input and output are contiguous in dim 1 + int64_t inner_stride = strides[1]; // stride of input in dim 0 + vectorized_outer_reduction(data, inner_stride, size0, size1, op, vop); + } else { + UNARY_OUTER_LOOP(data, outer_strides, size1, [&] { + char* ptrs[3] = { data[0], data[0], data[1] }; + int64_t inner_strides[3] = { strides[0], strides[0], strides[1] }; + basic_loop(ptrs, inner_strides, 0, size0, op); + }); + } + }); +} + +// when reduction is on most inner dimension (dim 0 in TensorIterator) +// and input has contiguous most inner dimension, `binary_kernel_reduce_lastdim` +// can be used. +static inline bool is_reduce_lastdim(TensorIteratorBase& iter) { + return iter.num_reduce_dims() == 1 && iter.is_dim_reduced(0) + && iter.ninputs() == 1 && iter.strides(1)[0] == iter.element_size(1); +} + +template +void binary_kernel_reduce_lastdim(TensorIteratorBase& iter, reduce_func_t reduce_op) { + auto shape = iter.shape(); + int64_t dim_size = shape[0]; + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / dim_size); + TensorIterator sub_iter(iter); + // create sub iterator to parallel on all non-reduce-dims + sub_iter.narrow(0, 0, 1); + auto loop = [&](char** data, const int64_t* strides, int64_t size) { + char* out = data[0]; + char* in = data[1]; + for (int64_t i = 0; i < size; ++i) { + reduce_op(out, in, dim_size); + out += strides[0]; + in += strides[1]; + } + }; + sub_iter.for_each(loop, grain_size); +} + +}}} // namespace at::native:: diff --git a/shared/package-files/3a/3a48ffadeb2c6647dee84c2ffe8ec6179b68739a9609e164436707436e417551/back-symbolic.svg b/shared/package-files/3a/3a48ffadeb2c6647dee84c2ffe8ec6179b68739a9609e164436707436e417551/back-symbolic.svg new file mode 100644 index 0000000000000000000000000000000000000000..0c2d653cbe8f9047f989226d5a00f7fd74ac0695 --- /dev/null +++ b/shared/package-files/3a/3a48ffadeb2c6647dee84c2ffe8ec6179b68739a9609e164436707436e417551/back-symbolic.svg @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + diff --git a/shared/package-files/3a/3a48ffadeb2c6647dee84c2ffe8ec6179b68739a9609e164436707436e417551/back.svg b/shared/package-files/3a/3a48ffadeb2c6647dee84c2ffe8ec6179b68739a9609e164436707436e417551/back.svg new file mode 100644 index 0000000000000000000000000000000000000000..0c2d653cbe8f9047f989226d5a00f7fd74ac0695 --- /dev/null +++ b/shared/package-files/3a/3a48ffadeb2c6647dee84c2ffe8ec6179b68739a9609e164436707436e417551/back.svg @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + diff --git a/shared/package-files/3a/3a4a38743320076cfa1fe51b19a0b12a2c06d9ecdb86a8862a33e77364322403/test_forest.py b/shared/package-files/3a/3a4a38743320076cfa1fe51b19a0b12a2c06d9ecdb86a8862a33e77364322403/test_forest.py new file mode 100644 index 0000000000000000000000000000000000000000..5dec5c7ab90b2635aa58f0735859a6fdfea7d0ca --- /dev/null +++ b/shared/package-files/3a/3a4a38743320076cfa1fe51b19a0b12a2c06d9ecdb86a8862a33e77364322403/test_forest.py @@ -0,0 +1,1865 @@ +""" +Testing for the forest module (sklearn.ensemble.forest). +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import itertools +import math +import pickle +from collections import defaultdict +from functools import partial +from itertools import combinations, product +from typing import Any, Dict +from unittest.mock import patch + +import joblib +import numpy as np +import pytest +from scipy.special import comb + +import sklearn +from sklearn import clone, datasets +from sklearn.datasets import make_classification, make_hastie_10_2 +from sklearn.decomposition import TruncatedSVD +from sklearn.dummy import DummyRegressor +from sklearn.ensemble import ( + ExtraTreesClassifier, + ExtraTreesRegressor, + RandomForestClassifier, + RandomForestRegressor, + RandomTreesEmbedding, +) +from sklearn.ensemble._forest import ( + _generate_unsampled_indices, + _get_n_samples_bootstrap, +) +from sklearn.exceptions import NotFittedError +from sklearn.metrics import ( + explained_variance_score, + f1_score, + mean_poisson_deviance, + mean_squared_error, +) +from sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split +from sklearn.svm import LinearSVC +from sklearn.tree._classes import SPARSE_SPLITTERS +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + ignore_warnings, + skip_if_no_parallel, +) +from sklearn.utils.fixes import COO_CONTAINERS, CSC_CONTAINERS, CSR_CONTAINERS +from sklearn.utils.multiclass import type_of_target +from sklearn.utils.parallel import Parallel +from sklearn.utils.validation import check_random_state + +# toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y = [-1, -1, -1, 1, 1, 1] +T = [[-1, -1], [2, 2], [3, 2]] +true_result = [-1, 1, 1] + +# Larger classification sample used for testing feature importances +X_large, y_large = datasets.make_classification( + n_samples=500, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, +) + +# also load the iris dataset +# and randomly permute it +iris = datasets.load_iris() +rng = check_random_state(0) +perm = rng.permutation(iris.target.size) +iris.data = iris.data[perm] +iris.target = iris.target[perm] + +# Make regression dataset +X_reg, y_reg = datasets.make_regression(n_samples=500, n_features=10, random_state=1) + +# also make a hastie_10_2 dataset +hastie_X, hastie_y = datasets.make_hastie_10_2(n_samples=20, random_state=1) +hastie_X = hastie_X.astype(np.float32) + +# Get the default backend in joblib to test parallelism and interaction with +# different backends +DEFAULT_JOBLIB_BACKEND = joblib.parallel.get_active_backend()[0].__class__ + +FOREST_CLASSIFIERS = { + "ExtraTreesClassifier": ExtraTreesClassifier, + "RandomForestClassifier": RandomForestClassifier, +} + +FOREST_REGRESSORS = { + "ExtraTreesRegressor": ExtraTreesRegressor, + "RandomForestRegressor": RandomForestRegressor, +} + +FOREST_TRANSFORMERS = { + "RandomTreesEmbedding": RandomTreesEmbedding, +} + +FOREST_ESTIMATORS: Dict[str, Any] = dict() +FOREST_ESTIMATORS.update(FOREST_CLASSIFIERS) +FOREST_ESTIMATORS.update(FOREST_REGRESSORS) +FOREST_ESTIMATORS.update(FOREST_TRANSFORMERS) + +FOREST_CLASSIFIERS_REGRESSORS: Dict[str, Any] = FOREST_CLASSIFIERS.copy() +FOREST_CLASSIFIERS_REGRESSORS.update(FOREST_REGRESSORS) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_classification_toy(name): + """Check classification on a toy dataset.""" + ForestClassifier = FOREST_CLASSIFIERS[name] + + clf = ForestClassifier(n_estimators=10, random_state=1) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result) + assert 10 == len(clf) + + clf = ForestClassifier(n_estimators=10, max_features=1, random_state=1) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result) + assert 10 == len(clf) + + # also test apply + leaf_indices = clf.apply(X) + assert leaf_indices.shape == (len(X), clf.n_estimators) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +@pytest.mark.parametrize("criterion", ("gini", "log_loss")) +def test_iris_criterion(name, criterion): + # Check consistency on dataset iris. + ForestClassifier = FOREST_CLASSIFIERS[name] + + clf = ForestClassifier(n_estimators=10, criterion=criterion, random_state=1) + clf.fit(iris.data, iris.target) + score = clf.score(iris.data, iris.target) + assert score > 0.9, "Failed with criterion %s and score = %f" % (criterion, score) + + clf = ForestClassifier( + n_estimators=10, criterion=criterion, max_features=2, random_state=1 + ) + clf.fit(iris.data, iris.target) + score = clf.score(iris.data, iris.target) + assert score > 0.5, "Failed with criterion %s and score = %f" % (criterion, score) + + +@pytest.mark.parametrize("name", FOREST_REGRESSORS) +@pytest.mark.parametrize( + "criterion", ("squared_error", "absolute_error", "friedman_mse") +) +def test_regression_criterion(name, criterion): + # Check consistency on regression dataset. + ForestRegressor = FOREST_REGRESSORS[name] + + reg = ForestRegressor(n_estimators=5, criterion=criterion, random_state=1) + reg.fit(X_reg, y_reg) + score = reg.score(X_reg, y_reg) + assert score > 0.93, ( + "Failed with max_features=None, criterion %s and score = %f" + % ( + criterion, + score, + ) + ) + + reg = ForestRegressor( + n_estimators=5, criterion=criterion, max_features=6, random_state=1 + ) + reg.fit(X_reg, y_reg) + score = reg.score(X_reg, y_reg) + assert score > 0.92, "Failed with max_features=6, criterion %s and score = %f" % ( + criterion, + score, + ) + + +def test_poisson_vs_mse(): + """Test that random forest with poisson criterion performs better than + mse for a poisson target. + + There is a similar test for DecisionTreeRegressor. + """ + rng = np.random.RandomState(42) + n_train, n_test, n_features = 500, 500, 10 + X = datasets.make_low_rank_matrix( + n_samples=n_train + n_test, n_features=n_features, random_state=rng + ) + # We create a log-linear Poisson model and downscale coef as it will get + # exponentiated. + coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) + y = rng.poisson(lam=np.exp(X @ coef)) + X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=n_test, random_state=rng + ) + # We prevent some overfitting by setting min_samples_split=10. + forest_poi = RandomForestRegressor( + criterion="poisson", min_samples_leaf=10, max_features="sqrt", random_state=rng + ) + forest_mse = RandomForestRegressor( + criterion="squared_error", + min_samples_leaf=10, + max_features="sqrt", + random_state=rng, + ) + + forest_poi.fit(X_train, y_train) + forest_mse.fit(X_train, y_train) + dummy = DummyRegressor(strategy="mean").fit(X_train, y_train) + + for X, y, data_name in [(X_train, y_train, "train"), (X_test, y_test, "test")]: + metric_poi = mean_poisson_deviance(y, forest_poi.predict(X)) + # squared_error forest might produce non-positive predictions => clip + # If y = 0 for those, the poisson deviance gets too good. + # If we drew more samples, we would eventually get y > 0 and the + # poisson deviance would explode, i.e. be undefined. Therefore, we do + # not clip to a tiny value like 1e-15, but to 1e-6. This acts like a + # small penalty to the non-positive predictions. + metric_mse = mean_poisson_deviance( + y, np.clip(forest_mse.predict(X), 1e-6, None) + ) + metric_dummy = mean_poisson_deviance(y, dummy.predict(X)) + # As squared_error might correctly predict 0 in train set, its train + # score can be better than Poisson. This is no longer the case for the + # test set. But keep the above comment for clipping in mind. + if data_name == "test": + assert metric_poi < metric_mse + assert metric_poi < 0.8 * metric_dummy + + +@pytest.mark.parametrize("criterion", ("poisson", "squared_error")) +def test_balance_property_random_forest(criterion): + """ "Test that sum(y_pred)==sum(y_true) on the training set.""" + rng = np.random.RandomState(42) + n_train, n_test, n_features = 500, 500, 10 + X = datasets.make_low_rank_matrix( + n_samples=n_train + n_test, n_features=n_features, random_state=rng + ) + + coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) + y = rng.poisson(lam=np.exp(X @ coef)) + + reg = RandomForestRegressor( + criterion=criterion, n_estimators=10, bootstrap=False, random_state=rng + ) + reg.fit(X, y) + + assert np.sum(reg.predict(X)) == pytest.approx(np.sum(y)) + + +@pytest.mark.parametrize("name", FOREST_REGRESSORS) +def test_regressor_attributes(name): + # Regression models should not have a classes_ attribute. + r = FOREST_REGRESSORS[name](random_state=0) + assert not hasattr(r, "classes_") + assert not hasattr(r, "n_classes_") + + r.fit([[1, 2, 3], [4, 5, 6]], [1, 2]) + assert not hasattr(r, "classes_") + assert not hasattr(r, "n_classes_") + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_probability(name): + # Predict probabilities. + ForestClassifier = FOREST_CLASSIFIERS[name] + with np.errstate(divide="ignore"): + clf = ForestClassifier( + n_estimators=10, random_state=1, max_features=1, max_depth=1 + ) + clf.fit(iris.data, iris.target) + assert_array_almost_equal( + np.sum(clf.predict_proba(iris.data), axis=1), np.ones(iris.data.shape[0]) + ) + assert_array_almost_equal( + clf.predict_proba(iris.data), np.exp(clf.predict_log_proba(iris.data)) + ) + + +@pytest.mark.parametrize("dtype", (np.float64, np.float32)) +@pytest.mark.parametrize( + "name, criterion", + itertools.chain( + product(FOREST_CLASSIFIERS, ["gini", "log_loss"]), + product(FOREST_REGRESSORS, ["squared_error", "friedman_mse", "absolute_error"]), + ), +) +def test_importances(dtype, name, criterion): + tolerance = 0.01 + if name in FOREST_REGRESSORS and criterion == "absolute_error": + tolerance = 0.05 + + # cast as dtype + X = X_large.astype(dtype, copy=False) + y = y_large.astype(dtype, copy=False) + + ForestEstimator = FOREST_ESTIMATORS[name] + + est = ForestEstimator(n_estimators=10, criterion=criterion, random_state=0) + est.fit(X, y) + importances = est.feature_importances_ + + # The forest estimator can detect that only the first 3 features of the + # dataset are informative: + n_important = np.sum(importances > 0.1) + assert importances.shape[0] == 10 + assert n_important == 3 + assert np.all(importances[:3] > 0.1) + + # Check with parallel + importances = est.feature_importances_ + est.set_params(n_jobs=2) + importances_parallel = est.feature_importances_ + assert_array_almost_equal(importances, importances_parallel) + + # Check with sample weights + sample_weight = check_random_state(0).randint(1, 10, len(X)) + est = ForestEstimator(n_estimators=10, random_state=0, criterion=criterion) + est.fit(X, y, sample_weight=sample_weight) + importances = est.feature_importances_ + assert np.all(importances >= 0.0) + + for scale in [0.5, 100]: + est = ForestEstimator(n_estimators=10, random_state=0, criterion=criterion) + est.fit(X, y, sample_weight=scale * sample_weight) + importances_bis = est.feature_importances_ + assert np.abs(importances - importances_bis).mean() < tolerance + + +def test_importances_asymptotic(): + # Check whether variable importances of totally randomized trees + # converge towards their theoretical values (See Louppe et al, + # Understanding variable importances in forests of randomized trees, 2013). + + def binomial(k, n): + return 0 if k < 0 or k > n else comb(int(n), int(k), exact=True) + + def entropy(samples): + n_samples = len(samples) + entropy = 0.0 + + for count in np.bincount(samples): + p = 1.0 * count / n_samples + if p > 0: + entropy -= p * np.log2(p) + + return entropy + + def mdi_importance(X_m, X, y): + n_samples, n_features = X.shape + + features = list(range(n_features)) + features.pop(X_m) + values = [np.unique(X[:, i]) for i in range(n_features)] + + imp = 0.0 + + for k in range(n_features): + # Weight of each B of size k + coef = 1.0 / (binomial(k, n_features) * (n_features - k)) + + # For all B of size k + for B in combinations(features, k): + # For all values B=b + for b in product(*[values[B[j]] for j in range(k)]): + mask_b = np.ones(n_samples, dtype=bool) + + for j in range(k): + mask_b &= X[:, B[j]] == b[j] + + X_, y_ = X[mask_b, :], y[mask_b] + n_samples_b = len(X_) + + if n_samples_b > 0: + children = [] + + for xi in values[X_m]: + mask_xi = X_[:, X_m] == xi + children.append(y_[mask_xi]) + + imp += ( + coef + * (1.0 * n_samples_b / n_samples) # P(B=b) + * ( + entropy(y_) + - sum( + [ + entropy(c) * len(c) / n_samples_b + for c in children + ] + ) + ) + ) + + return imp + + data = np.array( + [ + [0, 0, 1, 0, 0, 1, 0, 1], + [1, 0, 1, 1, 1, 0, 1, 2], + [1, 0, 1, 1, 0, 1, 1, 3], + [0, 1, 1, 1, 0, 1, 0, 4], + [1, 1, 0, 1, 0, 1, 1, 5], + [1, 1, 0, 1, 1, 1, 1, 6], + [1, 0, 1, 0, 0, 1, 0, 7], + [1, 1, 1, 1, 1, 1, 1, 8], + [1, 1, 1, 1, 0, 1, 1, 9], + [1, 1, 1, 0, 1, 1, 1, 0], + ] + ) + + X, y = np.array(data[:, :7], dtype=bool), data[:, 7] + n_features = X.shape[1] + + # Compute true importances + true_importances = np.zeros(n_features) + + for i in range(n_features): + true_importances[i] = mdi_importance(i, X, y) + + # Estimate importances with totally randomized trees + clf = ExtraTreesClassifier( + n_estimators=500, max_features=1, criterion="log_loss", random_state=0 + ).fit(X, y) + + importances = ( + sum( + tree.tree_.compute_feature_importances(normalize=False) + for tree in clf.estimators_ + ) + / clf.n_estimators + ) + + # Check correctness + assert_almost_equal(entropy(y), sum(importances)) + assert np.abs(true_importances - importances).mean() < 0.01 + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_unfitted_feature_importances(name): + err_msg = ( + "This {} instance is not fitted yet. Call 'fit' with " + "appropriate arguments before using this estimator.".format(name) + ) + with pytest.raises(NotFittedError, match=err_msg): + getattr(FOREST_ESTIMATORS[name](), "feature_importances_") + + +@pytest.mark.parametrize("ForestClassifier", FOREST_CLASSIFIERS.values()) +@pytest.mark.parametrize("X_type", ["array", "sparse_csr", "sparse_csc"]) +@pytest.mark.parametrize( + "X, y, lower_bound_accuracy", + [ + ( + *datasets.make_classification(n_samples=300, n_classes=2, random_state=0), + 0.9, + ), + ( + *datasets.make_classification( + n_samples=1000, n_classes=3, n_informative=6, random_state=0 + ), + 0.65, + ), + ( + iris.data, + iris.target * 2 + 1, + 0.65, + ), + ( + *datasets.make_multilabel_classification(n_samples=300, random_state=0), + 0.18, + ), + ], +) +@pytest.mark.parametrize("oob_score", [True, partial(f1_score, average="micro")]) +def test_forest_classifier_oob( + ForestClassifier, X, y, X_type, lower_bound_accuracy, oob_score +): + """Check that OOB score is close to score on a test set.""" + X = _convert_container(X, constructor_name=X_type) + X_train, X_test, y_train, y_test = train_test_split( + X, + y, + test_size=0.5, + random_state=0, + ) + classifier = ForestClassifier( + n_estimators=40, + bootstrap=True, + oob_score=oob_score, + random_state=0, + ) + + assert not hasattr(classifier, "oob_score_") + assert not hasattr(classifier, "oob_decision_function_") + + classifier.fit(X_train, y_train) + if callable(oob_score): + test_score = oob_score(y_test, classifier.predict(X_test)) + else: + test_score = classifier.score(X_test, y_test) + assert classifier.oob_score_ >= lower_bound_accuracy + + abs_diff = abs(test_score - classifier.oob_score_) + assert abs_diff <= 0.11, f"{abs_diff=} is greater than 0.11" + + assert hasattr(classifier, "oob_score_") + assert not hasattr(classifier, "oob_prediction_") + assert hasattr(classifier, "oob_decision_function_") + + if y.ndim == 1: + expected_shape = (X_train.shape[0], len(set(y))) + else: + expected_shape = (X_train.shape[0], len(set(y[:, 0])), y.shape[1]) + assert classifier.oob_decision_function_.shape == expected_shape + + +@pytest.mark.parametrize("ForestRegressor", FOREST_REGRESSORS.values()) +@pytest.mark.parametrize("X_type", ["array", "sparse_csr", "sparse_csc"]) +@pytest.mark.parametrize( + "X, y, lower_bound_r2", + [ + ( + *datasets.make_regression( + n_samples=500, n_features=10, n_targets=1, random_state=0 + ), + 0.7, + ), + ( + *datasets.make_regression( + n_samples=500, n_features=10, n_targets=2, random_state=0 + ), + 0.55, + ), + ], +) +@pytest.mark.parametrize("oob_score", [True, explained_variance_score]) +def test_forest_regressor_oob(ForestRegressor, X, y, X_type, lower_bound_r2, oob_score): + """Check that forest-based regressor provide an OOB score close to the + score on a test set.""" + X = _convert_container(X, constructor_name=X_type) + X_train, X_test, y_train, y_test = train_test_split( + X, + y, + test_size=0.5, + random_state=0, + ) + regressor = ForestRegressor( + n_estimators=50, + bootstrap=True, + oob_score=oob_score, + random_state=0, + ) + + assert not hasattr(regressor, "oob_score_") + assert not hasattr(regressor, "oob_prediction_") + + regressor.fit(X_train, y_train) + if callable(oob_score): + test_score = oob_score(y_test, regressor.predict(X_test)) + else: + test_score = regressor.score(X_test, y_test) + assert regressor.oob_score_ >= lower_bound_r2 + + assert abs(test_score - regressor.oob_score_) <= 0.1 + + assert hasattr(regressor, "oob_score_") + assert hasattr(regressor, "oob_prediction_") + assert not hasattr(regressor, "oob_decision_function_") + + if y.ndim == 1: + expected_shape = (X_train.shape[0],) + else: + expected_shape = (X_train.shape[0], y.ndim) + assert regressor.oob_prediction_.shape == expected_shape + + +@pytest.mark.parametrize("ForestEstimator", FOREST_CLASSIFIERS_REGRESSORS.values()) +def test_forest_oob_warning(ForestEstimator): + """Check that a warning is raised when not enough estimator and the OOB + estimates will be inaccurate.""" + estimator = ForestEstimator( + n_estimators=1, + oob_score=True, + bootstrap=True, + random_state=0, + ) + with pytest.warns(UserWarning, match="Some inputs do not have OOB scores"): + estimator.fit(iris.data, iris.target) + + +@pytest.mark.parametrize("ForestEstimator", FOREST_CLASSIFIERS_REGRESSORS.values()) +def test_forest_oob_score_requires_bootstrap(ForestEstimator): + """Check that we raise an error if OOB score is requested without + activating bootstrapping. + """ + X = iris.data + y = iris.target + err_msg = "Out of bag estimation only available if bootstrap=True" + estimator = ForestEstimator(oob_score=True, bootstrap=False) + with pytest.raises(ValueError, match=err_msg): + estimator.fit(X, y) + + +@pytest.mark.parametrize("ForestClassifier", FOREST_CLASSIFIERS.values()) +def test_classifier_error_oob_score_multiclass_multioutput(ForestClassifier): + """Check that we raise an error with when requesting OOB score with + multiclass-multioutput classification target. + """ + rng = np.random.RandomState(42) + X = iris.data + y = rng.randint(low=0, high=5, size=(iris.data.shape[0], 2)) + y_type = type_of_target(y) + assert y_type == "multiclass-multioutput" + estimator = ForestClassifier(oob_score=True, bootstrap=True) + err_msg = "The type of target cannot be used to compute OOB estimates" + with pytest.raises(ValueError, match=err_msg): + estimator.fit(X, y) + + +@pytest.mark.parametrize("ForestRegressor", FOREST_REGRESSORS.values()) +def test_forest_multioutput_integral_regression_target(ForestRegressor): + """Check that multioutput regression with integral values is not interpreted + as a multiclass-multioutput target and OOB score can be computed. + """ + rng = np.random.RandomState(42) + X = iris.data + y = rng.randint(low=0, high=10, size=(iris.data.shape[0], 2)) + estimator = ForestRegressor( + n_estimators=30, oob_score=True, bootstrap=True, random_state=0 + ) + estimator.fit(X, y) + + n_samples_bootstrap = _get_n_samples_bootstrap(len(X), estimator.max_samples) + n_samples_test = X.shape[0] // 4 + oob_pred = np.zeros([n_samples_test, 2]) + for sample_idx, sample in enumerate(X[:n_samples_test]): + n_samples_oob = 0 + oob_pred_sample = np.zeros(2) + for tree in estimator.estimators_: + oob_unsampled_indices = _generate_unsampled_indices( + tree.random_state, len(X), n_samples_bootstrap + ) + if sample_idx in oob_unsampled_indices: + n_samples_oob += 1 + oob_pred_sample += tree.predict(sample.reshape(1, -1)).squeeze() + oob_pred[sample_idx] = oob_pred_sample / n_samples_oob + assert_allclose(oob_pred, estimator.oob_prediction_[:n_samples_test]) + + +@pytest.mark.parametrize("oob_score", [True, False]) +def test_random_trees_embedding_raise_error_oob(oob_score): + with pytest.raises(TypeError, match="got an unexpected keyword argument"): + RandomTreesEmbedding(oob_score=oob_score) + with pytest.raises(NotImplementedError, match="OOB score not supported"): + RandomTreesEmbedding()._set_oob_score_and_attributes(X, y) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_gridsearch(name): + # Check that base trees can be grid-searched. + forest = FOREST_CLASSIFIERS[name]() + clf = GridSearchCV(forest, {"n_estimators": (1, 2), "max_depth": (1, 2)}) + clf.fit(iris.data, iris.target) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_parallel(name): + """Check parallel computations in classification""" + if name in FOREST_CLASSIFIERS: + X = iris.data + y = iris.target + elif name in FOREST_REGRESSORS: + X = X_reg + y = y_reg + + ForestEstimator = FOREST_ESTIMATORS[name] + forest = ForestEstimator(n_estimators=10, n_jobs=3, random_state=0) + + forest.fit(X, y) + assert len(forest) == 10 + + forest.set_params(n_jobs=1) + y1 = forest.predict(X) + forest.set_params(n_jobs=2) + y2 = forest.predict(X) + assert_array_almost_equal(y1, y2, 3) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_pickle(name): + # Check pickability. + if name in FOREST_CLASSIFIERS: + X = iris.data[::2] + y = iris.target[::2] + elif name in FOREST_REGRESSORS: + X = X_reg[::2] + y = y_reg[::2] + + ForestEstimator = FOREST_ESTIMATORS[name] + obj = ForestEstimator(random_state=0) + obj.fit(X, y) + score = obj.score(X, y) + pickle_object = pickle.dumps(obj) + + obj2 = pickle.loads(pickle_object) + assert type(obj2) == obj.__class__ + score2 = obj2.score(X, y) + assert score == score2 + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_multioutput(name): + # Check estimators on multi-output problems. + + X_train = [ + [-2, -1], + [-1, -1], + [-1, -2], + [1, 1], + [1, 2], + [2, 1], + [-2, 1], + [-1, 1], + [-1, 2], + [2, -1], + [1, -1], + [1, -2], + ] + y_train = [ + [-1, 0], + [-1, 0], + [-1, 0], + [1, 1], + [1, 1], + [1, 1], + [-1, 2], + [-1, 2], + [-1, 2], + [1, 3], + [1, 3], + [1, 3], + ] + X_test = [[-1, -1], [1, 1], [-1, 1], [1, -1]] + y_test = [[-1, 0], [1, 1], [-1, 2], [1, 3]] + + est = FOREST_ESTIMATORS[name](random_state=0, bootstrap=False) + y_pred = est.fit(X_train, y_train).predict(X_test) + assert_array_almost_equal(y_pred, y_test) + + if name in FOREST_CLASSIFIERS: + with np.errstate(divide="ignore"): + proba = est.predict_proba(X_test) + assert len(proba) == 2 + assert proba[0].shape == (4, 2) + assert proba[1].shape == (4, 4) + + log_proba = est.predict_log_proba(X_test) + assert len(log_proba) == 2 + assert log_proba[0].shape == (4, 2) + assert log_proba[1].shape == (4, 4) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_multioutput_string(name): + # Check estimators on multi-output problems with string outputs. + + X_train = [ + [-2, -1], + [-1, -1], + [-1, -2], + [1, 1], + [1, 2], + [2, 1], + [-2, 1], + [-1, 1], + [-1, 2], + [2, -1], + [1, -1], + [1, -2], + ] + y_train = [ + ["red", "blue"], + ["red", "blue"], + ["red", "blue"], + ["green", "green"], + ["green", "green"], + ["green", "green"], + ["red", "purple"], + ["red", "purple"], + ["red", "purple"], + ["green", "yellow"], + ["green", "yellow"], + ["green", "yellow"], + ] + X_test = [[-1, -1], [1, 1], [-1, 1], [1, -1]] + y_test = [ + ["red", "blue"], + ["green", "green"], + ["red", "purple"], + ["green", "yellow"], + ] + + est = FOREST_ESTIMATORS[name](random_state=0, bootstrap=False) + y_pred = est.fit(X_train, y_train).predict(X_test) + assert_array_equal(y_pred, y_test) + + with np.errstate(divide="ignore"): + proba = est.predict_proba(X_test) + assert len(proba) == 2 + assert proba[0].shape == (4, 2) + assert proba[1].shape == (4, 4) + + log_proba = est.predict_log_proba(X_test) + assert len(log_proba) == 2 + assert log_proba[0].shape == (4, 2) + assert log_proba[1].shape == (4, 4) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_classes_shape(name): + # Test that n_classes_ and classes_ have proper shape. + ForestClassifier = FOREST_CLASSIFIERS[name] + + # Classification, single output + clf = ForestClassifier(random_state=0).fit(X, y) + + assert clf.n_classes_ == 2 + assert_array_equal(clf.classes_, [-1, 1]) + + # Classification, multi-output + _y = np.vstack((y, np.array(y) * 2)).T + clf = ForestClassifier(random_state=0).fit(X, _y) + + assert_array_equal(clf.n_classes_, [2, 2]) + assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]]) + + +def test_random_trees_dense_type(): + # Test that the `sparse_output` parameter of RandomTreesEmbedding + # works by returning a dense array. + + # Create the RTE with sparse=False + hasher = RandomTreesEmbedding(n_estimators=10, sparse_output=False) + X, y = datasets.make_circles(factor=0.5) + X_transformed = hasher.fit_transform(X) + + # Assert that type is ndarray, not scipy.sparse.csr_matrix + assert isinstance(X_transformed, np.ndarray) + + +def test_random_trees_dense_equal(): + # Test that the `sparse_output` parameter of RandomTreesEmbedding + # works by returning the same array for both argument values. + + # Create the RTEs + hasher_dense = RandomTreesEmbedding( + n_estimators=10, sparse_output=False, random_state=0 + ) + hasher_sparse = RandomTreesEmbedding( + n_estimators=10, sparse_output=True, random_state=0 + ) + X, y = datasets.make_circles(factor=0.5) + X_transformed_dense = hasher_dense.fit_transform(X) + X_transformed_sparse = hasher_sparse.fit_transform(X) + + # Assert that dense and sparse hashers have same array. + assert_array_equal(X_transformed_sparse.toarray(), X_transformed_dense) + + +def test_random_hasher(): + # test random forest hashing on circles dataset + # make sure that it is linearly separable. + # even after projected to two SVD dimensions + # Note: Not all random_states produce perfect results. + hasher = RandomTreesEmbedding(n_estimators=30, random_state=1) + X, y = datasets.make_circles(factor=0.5) + X_transformed = hasher.fit_transform(X) + + # test fit and transform: + hasher = RandomTreesEmbedding(n_estimators=30, random_state=1) + assert_array_equal(hasher.fit(X).transform(X).toarray(), X_transformed.toarray()) + + # one leaf active per data point per forest + assert X_transformed.shape[0] == X.shape[0] + assert_array_equal(X_transformed.sum(axis=1), hasher.n_estimators) + svd = TruncatedSVD(n_components=2) + X_reduced = svd.fit_transform(X_transformed) + linear_clf = LinearSVC() + linear_clf.fit(X_reduced, y) + assert linear_clf.score(X_reduced, y) == 1.0 + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_random_hasher_sparse_data(csc_container): + X, y = datasets.make_multilabel_classification(random_state=0) + hasher = RandomTreesEmbedding(n_estimators=30, random_state=1) + X_transformed = hasher.fit_transform(X) + X_transformed_sparse = hasher.fit_transform(csc_container(X)) + assert_array_equal(X_transformed_sparse.toarray(), X_transformed.toarray()) + + +def test_parallel_train(): + rng = check_random_state(12321) + n_samples, n_features = 80, 30 + X_train = rng.randn(n_samples, n_features) + y_train = rng.randint(0, 2, n_samples) + + clfs = [ + RandomForestClassifier(n_estimators=20, n_jobs=n_jobs, random_state=12345).fit( + X_train, y_train + ) + for n_jobs in [1, 2, 3, 8, 16, 32] + ] + + X_test = rng.randn(n_samples, n_features) + probas = [clf.predict_proba(X_test) for clf in clfs] + for proba1, proba2 in itertools.pairwise(probas): + assert_array_almost_equal(proba1, proba2) + + +def test_distribution(): + rng = check_random_state(12321) + + # Single variable with 4 values + X = rng.randint(0, 4, size=(1000, 1)) + y = rng.rand(1000) + n_trees = 500 + + reg = ExtraTreesRegressor(n_estimators=n_trees, random_state=42).fit(X, y) + + uniques = defaultdict(int) + for tree in reg.estimators_: + tree = "".join( + ("%d,%d/" % (f, int(t)) if f >= 0 else "-") + for f, t in zip(tree.tree_.feature, tree.tree_.threshold) + ) + + uniques[tree] += 1 + + uniques = sorted([(1.0 * count / n_trees, tree) for tree, count in uniques.items()]) + + # On a single variable problem where X_0 has 4 equiprobable values, there + # are 5 ways to build a random tree. The more compact (0,1/0,0/--0,2/--) of + # them has probability 1/3 while the 4 others have probability 1/6. + + assert len(uniques) == 5 + assert 0.20 > uniques[0][0] # Rough approximation of 1/6. + assert 0.20 > uniques[1][0] + assert 0.20 > uniques[2][0] + assert 0.20 > uniques[3][0] + assert uniques[4][0] > 0.3 + assert uniques[4][1] == "0,1/0,0/--0,2/--" + + # Two variables, one with 2 values, one with 3 values + X = np.empty((1000, 2)) + X[:, 0] = np.random.randint(0, 2, 1000) + X[:, 1] = np.random.randint(0, 3, 1000) + y = rng.rand(1000) + + reg = ExtraTreesRegressor(max_features=1, random_state=1).fit(X, y) + + uniques = defaultdict(int) + for tree in reg.estimators_: + tree = "".join( + ("%d,%d/" % (f, int(t)) if f >= 0 else "-") + for f, t in zip(tree.tree_.feature, tree.tree_.threshold) + ) + + uniques[tree] += 1 + + uniques = [(count, tree) for tree, count in uniques.items()] + assert len(uniques) == 8 + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_max_leaf_nodes_max_depth(name): + X, y = hastie_X, hastie_y + + # Test precedence of max_leaf_nodes over max_depth. + ForestEstimator = FOREST_ESTIMATORS[name] + est = ForestEstimator( + max_depth=1, max_leaf_nodes=4, n_estimators=1, random_state=0 + ).fit(X, y) + assert est.estimators_[0].get_depth() == 1 + + est = ForestEstimator(max_depth=1, n_estimators=1, random_state=0).fit(X, y) + assert est.estimators_[0].get_depth() == 1 + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_min_samples_split(name): + X, y = hastie_X, hastie_y + ForestEstimator = FOREST_ESTIMATORS[name] + + est = ForestEstimator(min_samples_split=10, n_estimators=1, random_state=0) + est.fit(X, y) + node_idx = est.estimators_[0].tree_.children_left != -1 + node_samples = est.estimators_[0].tree_.n_node_samples[node_idx] + + assert np.min(node_samples) > len(X) * 0.5 - 1, "Failed with {0}".format(name) + + est = ForestEstimator(min_samples_split=0.5, n_estimators=1, random_state=0) + est.fit(X, y) + node_idx = est.estimators_[0].tree_.children_left != -1 + node_samples = est.estimators_[0].tree_.n_node_samples[node_idx] + + assert np.min(node_samples) > len(X) * 0.5 - 1, "Failed with {0}".format(name) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_min_samples_leaf(name): + X, y = hastie_X, hastie_y + + # Test if leaves contain more than leaf_count training examples + ForestEstimator = FOREST_ESTIMATORS[name] + + est = ForestEstimator(min_samples_leaf=5, n_estimators=1, random_state=0) + est.fit(X, y) + out = est.estimators_[0].tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert np.min(leaf_count) > 4, "Failed with {0}".format(name) + + est = ForestEstimator(min_samples_leaf=0.25, n_estimators=1, random_state=0) + est.fit(X, y) + out = est.estimators_[0].tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert np.min(leaf_count) > len(X) * 0.25 - 1, "Failed with {0}".format(name) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_min_weight_fraction_leaf(name): + X, y = hastie_X, hastie_y + + # Test if leaves contain at least min_weight_fraction_leaf of the + # training set + ForestEstimator = FOREST_ESTIMATORS[name] + rng = np.random.RandomState(0) + weights = rng.rand(X.shape[0]) + total_weight = np.sum(weights) + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for frac in np.linspace(0, 0.5, 6): + est = ForestEstimator( + min_weight_fraction_leaf=frac, n_estimators=1, random_state=0 + ) + if "RandomForest" in name: + est.bootstrap = False + + est.fit(X, y, sample_weight=weights) + out = est.estimators_[0].tree_.apply(X) + node_weights = np.bincount(out, weights=weights) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf, ( + "Failed with {0} min_weight_fraction_leaf={1}".format( + name, est.min_weight_fraction_leaf + ) + ) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +@pytest.mark.parametrize( + "sparse_container", COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS +) +def test_sparse_input(name, sparse_container): + X, y = datasets.make_multilabel_classification(random_state=0, n_samples=50) + + ForestEstimator = FOREST_ESTIMATORS[name] + + dense = ForestEstimator(random_state=0, max_depth=2).fit(X, y) + sparse = ForestEstimator(random_state=0, max_depth=2).fit(sparse_container(X), y) + + assert_array_almost_equal(sparse.apply(X), dense.apply(X)) + + if name in FOREST_CLASSIFIERS or name in FOREST_REGRESSORS: + assert_array_almost_equal(sparse.predict(X), dense.predict(X)) + assert_array_almost_equal( + sparse.feature_importances_, dense.feature_importances_ + ) + + if name in FOREST_CLASSIFIERS: + assert_array_almost_equal(sparse.predict_proba(X), dense.predict_proba(X)) + assert_array_almost_equal( + sparse.predict_log_proba(X), dense.predict_log_proba(X) + ) + + if name in FOREST_TRANSFORMERS: + assert_array_almost_equal( + sparse.transform(X).toarray(), dense.transform(X).toarray() + ) + assert_array_almost_equal( + sparse.fit_transform(X).toarray(), dense.fit_transform(X).toarray() + ) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +@pytest.mark.parametrize("dtype", (np.float64, np.float32)) +def test_memory_layout(name, dtype): + # Test that it works no matter the memory layout + est = FOREST_ESTIMATORS[name](random_state=0, bootstrap=False) + + # Dense + for container, kwargs in ( + (np.asarray, {}), # Nothing + (np.asarray, {"order": "C"}), # C-order + (np.asarray, {"order": "F"}), # F-order + (np.ascontiguousarray, {}), # Contiguous + ): + X = container(iris.data, dtype=dtype, **kwargs) + y = iris.target + assert_array_almost_equal(est.fit(X, y).predict(X), y) + + # Sparse (if applicable) + if est.estimator.splitter in SPARSE_SPLITTERS: + for sparse_container in COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS: + X = sparse_container(iris.data, dtype=dtype) + y = iris.target + assert_array_almost_equal(est.fit(X, y).predict(X), y) + + # Strided + X = np.asarray(iris.data[::3], dtype=dtype) + y = iris.target[::3] + assert_array_almost_equal(est.fit(X, y).predict(X), y) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_1d_input(name): + X = iris.data[:, 0] + X_2d = iris.data[:, 0].reshape((-1, 1)) + y = iris.target + + with ignore_warnings(): + ForestEstimator = FOREST_ESTIMATORS[name] + with pytest.raises(ValueError): + ForestEstimator(n_estimators=1, random_state=0).fit(X, y) + + est = ForestEstimator(random_state=0) + est.fit(X_2d, y) + + if name in FOREST_CLASSIFIERS or name in FOREST_REGRESSORS: + with pytest.raises(ValueError): + est.predict(X) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_class_weights(name): + # Check class_weights resemble sample_weights behavior. + ForestClassifier = FOREST_CLASSIFIERS[name] + + # Iris is balanced, so no effect expected for using 'balanced' weights + clf1 = ForestClassifier(random_state=0) + clf1.fit(iris.data, iris.target) + clf2 = ForestClassifier(class_weight="balanced", random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Make a multi-output problem with three copies of Iris + iris_multi = np.vstack((iris.target, iris.target, iris.target)).T + # Create user-defined weights that should balance over the outputs + clf3 = ForestClassifier( + class_weight=[ + {0: 2.0, 1: 2.0, 2: 1.0}, + {0: 2.0, 1: 1.0, 2: 2.0}, + {0: 1.0, 1: 2.0, 2: 2.0}, + ], + random_state=0, + ) + clf3.fit(iris.data, iris_multi) + assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_) + # Check against multi-output "balanced" which should also have no effect + clf4 = ForestClassifier(class_weight="balanced", random_state=0) + clf4.fit(iris.data, iris_multi) + assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_) + + # Inflate importance of class 1, check against user-defined weights + sample_weight = np.ones(iris.target.shape) + sample_weight[iris.target == 1] *= 100 + class_weight = {0: 1.0, 1: 100.0, 2: 1.0} + clf1 = ForestClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight) + clf2 = ForestClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Check that sample_weight and class_weight are multiplicative + clf1 = ForestClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight**2) + clf2 = ForestClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target, sample_weight) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_class_weight_balanced_and_bootstrap_multi_output(name): + # Test class_weight works for multi-output""" + ForestClassifier = FOREST_CLASSIFIERS[name] + _y = np.vstack((y, np.array(y) * 2)).T + clf = ForestClassifier(class_weight="balanced", random_state=0) + clf.fit(X, _y) + clf = ForestClassifier( + class_weight=[{-1: 0.5, 1: 1.0}, {-2: 1.0, 2: 1.0}], random_state=0 + ) + clf.fit(X, _y) + # smoke test for balanced subsample + clf = ForestClassifier(class_weight="balanced_subsample", random_state=0) + clf.fit(X, _y) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_class_weight_errors(name): + # Test if class_weight raises errors and warnings when expected. + ForestClassifier = FOREST_CLASSIFIERS[name] + _y = np.vstack((y, np.array(y) * 2)).T + + # Warning warm_start with preset + clf = ForestClassifier(class_weight="balanced", warm_start=True, random_state=0) + clf.fit(X, y) + + warn_msg = ( + "Warm-start fitting without increasing n_estimators does not fit new trees." + ) + with pytest.warns(UserWarning, match=warn_msg): + clf.fit(X, _y) + + # Incorrect length list for multi-output + clf = ForestClassifier(class_weight=[{-1: 0.5, 1: 1.0}], random_state=0) + with pytest.raises(ValueError): + clf.fit(X, _y) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_warm_start(name): + # Test if fitting incrementally with warm start gives a forest of the + # right size and the same results as a normal fit. + X, y = hastie_X, hastie_y + ForestEstimator = FOREST_ESTIMATORS[name] + est_ws = None + for n_estimators in [5, 10]: + if est_ws is None: + est_ws = ForestEstimator( + n_estimators=n_estimators, random_state=42, warm_start=True + ) + else: + est_ws.set_params(n_estimators=n_estimators) + est_ws.fit(X, y) + assert len(est_ws) == n_estimators + + est_no_ws = ForestEstimator(n_estimators=10, random_state=42, warm_start=False) + est_no_ws.fit(X, y) + + assert set([tree.random_state for tree in est_ws]) == set( + [tree.random_state for tree in est_no_ws] + ) + + assert_array_equal( + est_ws.apply(X), est_no_ws.apply(X), err_msg="Failed with {0}".format(name) + ) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_warm_start_clear(name): + # Test if fit clears state and grows a new forest when warm_start==False. + X, y = hastie_X, hastie_y + ForestEstimator = FOREST_ESTIMATORS[name] + est = ForestEstimator(n_estimators=5, max_depth=1, warm_start=False, random_state=1) + est.fit(X, y) + + est_2 = ForestEstimator( + n_estimators=5, max_depth=1, warm_start=True, random_state=2 + ) + est_2.fit(X, y) # inits state + est_2.set_params(warm_start=False, random_state=1) + est_2.fit(X, y) # clears old state and equals est + + assert_array_almost_equal(est_2.apply(X), est.apply(X)) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_warm_start_smaller_n_estimators(name): + # Test if warm start second fit with smaller n_estimators raises error. + X, y = hastie_X, hastie_y + ForestEstimator = FOREST_ESTIMATORS[name] + est = ForestEstimator(n_estimators=5, max_depth=1, warm_start=True) + est.fit(X, y) + est.set_params(n_estimators=4) + with pytest.raises(ValueError): + est.fit(X, y) + + +@pytest.mark.parametrize("name", FOREST_ESTIMATORS) +def test_warm_start_equal_n_estimators(name): + # Test if warm start with equal n_estimators does nothing and returns the + # same forest and raises a warning. + X, y = hastie_X, hastie_y + ForestEstimator = FOREST_ESTIMATORS[name] + est = ForestEstimator(n_estimators=5, max_depth=3, warm_start=True, random_state=1) + est.fit(X, y) + + est_2 = ForestEstimator( + n_estimators=5, max_depth=3, warm_start=True, random_state=1 + ) + est_2.fit(X, y) + # Now est_2 equals est. + + est_2.set_params(random_state=2) + warn_msg = ( + "Warm-start fitting without increasing n_estimators does not fit new trees." + ) + with pytest.warns(UserWarning, match=warn_msg): + est_2.fit(X, y) + # If we had fit the trees again we would have got a different forest as we + # changed the random state. + assert_array_equal(est.apply(X), est_2.apply(X)) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_warm_start_oob(name): + # Test that the warm start computes oob score when asked. + X, y = hastie_X, hastie_y + ForestEstimator = FOREST_ESTIMATORS[name] + # Use 15 estimators to avoid 'some inputs do not have OOB scores' warning. + est = ForestEstimator( + n_estimators=15, + max_depth=3, + warm_start=False, + random_state=1, + bootstrap=True, + oob_score=True, + ) + est.fit(X, y) + + est_2 = ForestEstimator( + n_estimators=5, + max_depth=3, + warm_start=False, + random_state=1, + bootstrap=True, + oob_score=False, + ) + est_2.fit(X, y) + + est_2.set_params(warm_start=True, oob_score=True, n_estimators=15) + est_2.fit(X, y) + + assert hasattr(est_2, "oob_score_") + assert est.oob_score_ == est_2.oob_score_ + + # Test that oob_score is computed even if we don't need to train + # additional trees. + est_3 = ForestEstimator( + n_estimators=15, + max_depth=3, + warm_start=True, + random_state=1, + bootstrap=True, + oob_score=False, + ) + est_3.fit(X, y) + assert not hasattr(est_3, "oob_score_") + + est_3.set_params(oob_score=True) + ignore_warnings(est_3.fit)(X, y) + + assert est.oob_score_ == est_3.oob_score_ + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_oob_not_computed_twice(name): + # Check that oob_score is not computed twice when warm_start=True. + X, y = hastie_X, hastie_y + ForestEstimator = FOREST_ESTIMATORS[name] + + est = ForestEstimator( + n_estimators=10, warm_start=True, bootstrap=True, oob_score=True + ) + + with patch.object( + est, "_set_oob_score_and_attributes", wraps=est._set_oob_score_and_attributes + ) as mock_set_oob_score_and_attributes: + est.fit(X, y) + + with pytest.warns(UserWarning, match="Warm-start fitting without increasing"): + est.fit(X, y) + + mock_set_oob_score_and_attributes.assert_called_once() + + +def test_dtype_convert(n_classes=15): + classifier = RandomForestClassifier(random_state=0, bootstrap=False) + + X = np.eye(n_classes) + y = [ch for ch in "ABCDEFGHIJKLMNOPQRSTU"[:n_classes]] + + result = classifier.fit(X, y).predict(X) + assert_array_equal(classifier.classes_, y) + assert_array_equal(result, y) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_decision_path(name): + X, y = hastie_X, hastie_y + n_samples = X.shape[0] + ForestEstimator = FOREST_ESTIMATORS[name] + est = ForestEstimator(n_estimators=5, max_depth=1, warm_start=False, random_state=1) + est.fit(X, y) + indicator, n_nodes_ptr = est.decision_path(X) + + assert indicator.shape[1] == n_nodes_ptr[-1] + assert indicator.shape[0] == n_samples + assert_array_equal( + np.diff(n_nodes_ptr), [e.tree_.node_count for e in est.estimators_] + ) + + # Assert that leaves index are correct + leaves = est.apply(X) + for est_id in range(leaves.shape[1]): + leave_indicator = [ + indicator[i, n_nodes_ptr[est_id] + j] + for i, j in enumerate(leaves[:, est_id]) + ] + assert_array_almost_equal(leave_indicator, np.ones(shape=n_samples)) + + +def test_min_impurity_decrease(): + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + all_estimators = [ + RandomForestClassifier, + RandomForestRegressor, + ExtraTreesClassifier, + ExtraTreesRegressor, + ] + + for Estimator in all_estimators: + est = Estimator(min_impurity_decrease=0.1) + est.fit(X, y) + for tree in est.estimators_: + # Simply check if the parameter is passed on correctly. Tree tests + # will suffice for the actual working of this param + assert tree.min_impurity_decrease == 0.1 + + +def test_poisson_y_positive_check(): + est = RandomForestRegressor(criterion="poisson") + X = np.zeros((3, 3)) + + y = [-1, 1, 3] + err_msg = ( + r"Some value\(s\) of y are negative which is " + r"not allowed for Poisson regression." + ) + with pytest.raises(ValueError, match=err_msg): + est.fit(X, y) + + y = [0, 0, 0] + err_msg = ( + r"Sum of y is not strictly positive which " + r"is necessary for Poisson regression." + ) + with pytest.raises(ValueError, match=err_msg): + est.fit(X, y) + + +# mypy error: Variable "DEFAULT_JOBLIB_BACKEND" is not valid type +class MyBackend(DEFAULT_JOBLIB_BACKEND): # type: ignore[valid-type,misc] + def __init__(self, *args, **kwargs): + self.count = 0 + super().__init__(*args, **kwargs) + + def start_call(self): + self.count += 1 + return super().start_call() + + +joblib.register_parallel_backend("testing", MyBackend) + + +@skip_if_no_parallel +def test_backend_respected(): + clf = RandomForestClassifier(n_estimators=10, n_jobs=2) + + with joblib.parallel_backend("testing") as (ba, n_jobs): + clf.fit(X, y) + + assert ba.count > 0 + + # predict_proba requires shared memory. Ensure that's honored. + with joblib.parallel_backend("testing") as (ba, _): + clf.predict_proba(X) + + assert ba.count == 0 + + +def test_forest_feature_importances_sum(): + X, y = make_classification( + n_samples=15, n_informative=3, random_state=1, n_classes=3 + ) + clf = RandomForestClassifier( + min_samples_leaf=5, random_state=42, n_estimators=200 + ).fit(X, y) + assert math.isclose(1, clf.feature_importances_.sum(), abs_tol=1e-7) + + +def test_forest_degenerate_feature_importances(): + # build a forest of single node trees. See #13636 + X = np.zeros((10, 10)) + y = np.ones((10,)) + gbr = RandomForestRegressor(n_estimators=10).fit(X, y) + assert_array_equal(gbr.feature_importances_, np.zeros(10, dtype=np.float64)) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_max_samples_bootstrap(name): + # Check invalid `max_samples` values + est = FOREST_CLASSIFIERS_REGRESSORS[name](bootstrap=False, max_samples=0.5) + err_msg = ( + r"`max_sample` cannot be set if `bootstrap=False`. " + r"Either switch to `bootstrap=True` or set " + r"`max_sample=None`." + ) + with pytest.raises(ValueError, match=err_msg): + est.fit(X, y) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS) +def test_large_max_samples_exception(name): + # Check invalid `max_samples` + est = FOREST_CLASSIFIERS_REGRESSORS[name](bootstrap=True, max_samples=int(1e9)) + match = "`max_samples` must be <= n_samples=6 but got value 1000000000" + with pytest.raises(ValueError, match=match): + est.fit(X, y) + + +@pytest.mark.parametrize("name", FOREST_REGRESSORS) +def test_max_samples_boundary_regressors(name): + X_train, X_test, y_train, y_test = train_test_split( + X_reg, y_reg, train_size=0.7, test_size=0.3, random_state=0 + ) + + ms_1_model = FOREST_REGRESSORS[name]( + bootstrap=True, max_samples=1.0, random_state=0 + ) + ms_1_predict = ms_1_model.fit(X_train, y_train).predict(X_test) + + ms_None_model = FOREST_REGRESSORS[name]( + bootstrap=True, max_samples=None, random_state=0 + ) + ms_None_predict = ms_None_model.fit(X_train, y_train).predict(X_test) + + ms_1_ms = mean_squared_error(ms_1_predict, y_test) + ms_None_ms = mean_squared_error(ms_None_predict, y_test) + + assert ms_1_ms == pytest.approx(ms_None_ms) + + +@pytest.mark.parametrize("name", FOREST_CLASSIFIERS) +def test_max_samples_boundary_classifiers(name): + X_train, X_test, y_train, _ = train_test_split( + X_large, y_large, random_state=0, stratify=y_large + ) + + ms_1_model = FOREST_CLASSIFIERS[name]( + bootstrap=True, max_samples=1.0, random_state=0 + ) + ms_1_proba = ms_1_model.fit(X_train, y_train).predict_proba(X_test) + + ms_None_model = FOREST_CLASSIFIERS[name]( + bootstrap=True, max_samples=None, random_state=0 + ) + ms_None_proba = ms_None_model.fit(X_train, y_train).predict_proba(X_test) + + np.testing.assert_allclose(ms_1_proba, ms_None_proba) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_forest_y_sparse(csr_container): + X = [[1, 2, 3]] + y = csr_container([[4, 5, 6]]) + est = RandomForestClassifier() + msg = "sparse multilabel-indicator for y is not supported." + with pytest.raises(ValueError, match=msg): + est.fit(X, y) + + +@pytest.mark.parametrize("ForestClass", [RandomForestClassifier, RandomForestRegressor]) +def test_little_tree_with_small_max_samples(ForestClass): + rng = np.random.RandomState(1) + + X = rng.randn(10000, 2) + y = rng.randn(10000) > 0 + + # First fit with no restriction on max samples + est1 = ForestClass( + n_estimators=1, + random_state=rng, + max_samples=None, + ) + + # Second fit with max samples restricted to just 2 + est2 = ForestClass( + n_estimators=1, + random_state=rng, + max_samples=2, + ) + + est1.fit(X, y) + est2.fit(X, y) + + tree1 = est1.estimators_[0].tree_ + tree2 = est2.estimators_[0].tree_ + + msg = "Tree without `max_samples` restriction should have more nodes" + assert tree1.node_count > tree2.node_count, msg + + +@pytest.mark.parametrize("Forest", FOREST_REGRESSORS) +def test_mse_criterion_object_segfault_smoke_test(Forest): + # This is a smoke test to ensure that passing a mutable criterion + # does not cause a segfault when fitting with concurrent threads. + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/12623 + from sklearn.tree._criterion import MSE + + y = y_reg.reshape(-1, 1) + n_samples, n_outputs = y.shape + mse_criterion = MSE(n_outputs, n_samples) + est = FOREST_REGRESSORS[Forest](n_estimators=2, n_jobs=2, criterion=mse_criterion) + + est.fit(X_reg, y) + + +def test_random_trees_embedding_feature_names_out(): + """Check feature names out for Random Trees Embedding.""" + random_state = np.random.RandomState(0) + X = np.abs(random_state.randn(100, 4)) + hasher = RandomTreesEmbedding( + n_estimators=2, max_depth=2, sparse_output=False, random_state=0 + ).fit(X) + names = hasher.get_feature_names_out() + expected_names = [ + f"randomtreesembedding_{tree}_{leaf}" + # Note: nodes with indices 0, 1 and 4 are internal split nodes and + # therefore do not appear in the expected output feature names. + for tree, leaf in [ + (0, 2), + (0, 3), + (0, 5), + (0, 6), + (1, 2), + (1, 3), + (1, 5), + (1, 6), + ] + ] + assert_array_equal(expected_names, names) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_read_only_buffer(csr_container, monkeypatch): + """RandomForestClassifier must work on readonly sparse data. + + Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/25333 + """ + monkeypatch.setattr( + sklearn.ensemble._forest, + "Parallel", + partial(Parallel, max_nbytes=100), + ) + rng = np.random.RandomState(seed=0) + + X, y = make_classification(n_samples=100, n_features=200, random_state=rng) + X = csr_container(X, copy=True) + + clf = RandomForestClassifier(n_jobs=2, random_state=rng) + cross_val_score(clf, X, y, cv=2) + + +@pytest.mark.parametrize("class_weight", ["balanced_subsample", None]) +def test_round_samples_to_one_when_samples_too_low(class_weight): + """Check low max_samples works and is rounded to one. + + Non-regression test for gh-24037. + """ + X, y = datasets.load_wine(return_X_y=True) + forest = RandomForestClassifier( + n_estimators=10, max_samples=1e-4, class_weight=class_weight, random_state=0 + ) + forest.fit(X, y) + + +@pytest.mark.parametrize("seed", [None, 1]) +@pytest.mark.parametrize("bootstrap", [True, False]) +@pytest.mark.parametrize("ForestClass", FOREST_CLASSIFIERS_REGRESSORS.values()) +def test_estimators_samples(ForestClass, bootstrap, seed): + """Estimators_samples_ property should be consistent. + + Tests consistency across fits and whether or not the seed for the random generator + is set. + """ + X, y = make_hastie_10_2(n_samples=200, random_state=1) + + if bootstrap: + max_samples = 0.5 + else: + max_samples = None + est = ForestClass( + n_estimators=10, + max_samples=max_samples, + max_features=0.5, + random_state=seed, + bootstrap=bootstrap, + ) + est.fit(X, y) + + estimators_samples = est.estimators_samples_.copy() + + # Test repeated calls result in same set of indices + assert_array_equal(estimators_samples, est.estimators_samples_) + estimators = est.estimators_ + + assert isinstance(estimators_samples, list) + assert len(estimators_samples) == len(estimators) + assert estimators_samples[0].dtype == np.int32 + + for i in range(len(estimators)): + if bootstrap: + assert len(estimators_samples[i]) == len(X) // 2 + + # the bootstrap should be a resampling with replacement + assert len(np.unique(estimators_samples[i])) < len(estimators_samples[i]) + else: + assert len(set(estimators_samples[i])) == len(X) + + estimator_index = 0 + estimator_samples = estimators_samples[estimator_index] + estimator = estimators[estimator_index] + + X_train = X[estimator_samples] + y_train = y[estimator_samples] + + orig_tree_values = estimator.tree_.value + estimator = clone(estimator) + estimator.fit(X_train, y_train) + new_tree_values = estimator.tree_.value + assert_allclose(orig_tree_values, new_tree_values) + + +@pytest.mark.parametrize( + "make_data, Forest", + [ + (datasets.make_regression, RandomForestRegressor), + (datasets.make_classification, RandomForestClassifier), + (datasets.make_regression, ExtraTreesRegressor), + (datasets.make_classification, ExtraTreesClassifier), + ], +) +def test_missing_values_is_resilient(make_data, Forest): + """Check that forest can deal with missing values and has decent performance.""" + + rng = np.random.RandomState(0) + n_samples, n_features = 1000, 10 + X, y = make_data(n_samples=n_samples, n_features=n_features, random_state=rng) + + # Create dataset with missing values + X_missing = X.copy() + X_missing[rng.choice([False, True], size=X.shape, p=[0.95, 0.05])] = np.nan + assert np.isnan(X_missing).any() + + X_missing_train, X_missing_test, y_train, y_test = train_test_split( + X_missing, y, random_state=0 + ) + + # Train forest with missing values + forest_with_missing = Forest(random_state=rng, n_estimators=50) + forest_with_missing.fit(X_missing_train, y_train) + score_with_missing = forest_with_missing.score(X_missing_test, y_test) + + # Train forest without missing values + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + forest = Forest(random_state=rng, n_estimators=50) + forest.fit(X_train, y_train) + score_without_missing = forest.score(X_test, y_test) + + # Score is still 80 percent of the forest's score that had no missing values + assert score_with_missing >= 0.80 * score_without_missing + + +@pytest.mark.parametrize( + "Forest", + [ + RandomForestClassifier, + RandomForestRegressor, + ExtraTreesRegressor, + ExtraTreesClassifier, + ], +) +def test_missing_value_is_predictive(Forest): + """Check that the forest learns when missing values are only present for + a predictive feature.""" + rng = np.random.RandomState(0) + n_samples = 300 + expected_score = 0.75 + + X_non_predictive = rng.standard_normal(size=(n_samples, 10)) + y = rng.randint(0, high=2, size=n_samples) + + # Create a predictive feature using `y` and with some noise + X_random_mask = rng.choice([False, True], size=n_samples, p=[0.95, 0.05]) + y_mask = y.astype(bool) + y_mask[X_random_mask] = ~y_mask[X_random_mask] + + predictive_feature = rng.standard_normal(size=n_samples) + predictive_feature[y_mask] = np.nan + assert np.isnan(predictive_feature).any() + + X_predictive = X_non_predictive.copy() + X_predictive[:, 5] = predictive_feature + + ( + X_predictive_train, + X_predictive_test, + X_non_predictive_train, + X_non_predictive_test, + y_train, + y_test, + ) = train_test_split(X_predictive, X_non_predictive, y, random_state=0) + forest_predictive = Forest(random_state=0).fit(X_predictive_train, y_train) + forest_non_predictive = Forest(random_state=0).fit(X_non_predictive_train, y_train) + + predictive_test_score = forest_predictive.score(X_predictive_test, y_test) + + assert predictive_test_score >= expected_score + assert predictive_test_score >= forest_non_predictive.score( + X_non_predictive_test, y_test + ) + + +@pytest.mark.parametrize("Forest", FOREST_REGRESSORS.values()) +def test_non_supported_criterion_raises_error_with_missing_values(Forest): + """Raise error for unsupported criterion when there are missing values.""" + X = np.array([[0, 1, 2], [np.nan, 0, 2.0]]) + y = [0.5, 1.0] + + forest = Forest(criterion="absolute_error") + + msg = ".*does not accept missing values" + with pytest.raises(ValueError, match=msg): + forest.fit(X, y) diff --git a/shared/package-files/3a/3a4a59888ac3daeff5601edd1363499a1a6dd5466804da17d89058dead548b1a/compatibility.py b/shared/package-files/3a/3a4a59888ac3daeff5601edd1363499a1a6dd5466804da17d89058dead548b1a/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..6635c61e569cb230f8db947ebb16cca25728280a --- /dev/null +++ b/shared/package-files/3a/3a4a59888ac3daeff5601edd1363499a1a6dd5466804da17d89058dead548b1a/compatibility.py @@ -0,0 +1,1134 @@ +"""Compatibility interface between dense and sparse polys. """ + + +from sympy.polys.densearith import dup_add_term +from sympy.polys.densearith import dmp_add_term +from sympy.polys.densearith import dup_sub_term +from sympy.polys.densearith import dmp_sub_term +from sympy.polys.densearith import dup_mul_term +from sympy.polys.densearith import dmp_mul_term +from sympy.polys.densearith import dup_add_ground +from sympy.polys.densearith import dmp_add_ground +from sympy.polys.densearith import dup_sub_ground +from sympy.polys.densearith import dmp_sub_ground +from sympy.polys.densearith import dup_mul_ground +from sympy.polys.densearith import dmp_mul_ground +from sympy.polys.densearith import dup_quo_ground +from sympy.polys.densearith import dmp_quo_ground +from sympy.polys.densearith import dup_exquo_ground +from sympy.polys.densearith import dmp_exquo_ground +from sympy.polys.densearith import dup_lshift +from sympy.polys.densearith import dup_rshift +from sympy.polys.densearith import dup_abs +from sympy.polys.densearith import dmp_abs +from sympy.polys.densearith import dup_neg +from sympy.polys.densearith import dmp_neg +from sympy.polys.densearith import dup_add +from sympy.polys.densearith import dmp_add +from sympy.polys.densearith import dup_sub +from sympy.polys.densearith import dmp_sub +from sympy.polys.densearith import dup_add_mul +from sympy.polys.densearith import dmp_add_mul +from sympy.polys.densearith import dup_sub_mul +from sympy.polys.densearith import dmp_sub_mul +from sympy.polys.densearith import dup_mul +from sympy.polys.densearith import dmp_mul +from sympy.polys.densearith import dup_sqr +from sympy.polys.densearith import dmp_sqr +from sympy.polys.densearith import dup_pow +from sympy.polys.densearith import dmp_pow +from sympy.polys.densearith import dup_pdiv +from sympy.polys.densearith import dup_prem +from sympy.polys.densearith import dup_pquo +from sympy.polys.densearith import dup_pexquo +from sympy.polys.densearith import dmp_pdiv +from sympy.polys.densearith import dmp_prem +from sympy.polys.densearith import dmp_pquo +from sympy.polys.densearith import dmp_pexquo +from sympy.polys.densearith import dup_rr_div +from sympy.polys.densearith import dmp_rr_div +from sympy.polys.densearith import dup_ff_div +from sympy.polys.densearith import dmp_ff_div +from sympy.polys.densearith import dup_div +from sympy.polys.densearith import dup_rem +from sympy.polys.densearith import dup_quo +from sympy.polys.densearith import dup_exquo +from sympy.polys.densearith import dmp_div +from sympy.polys.densearith import dmp_rem +from sympy.polys.densearith import dmp_quo +from sympy.polys.densearith import dmp_exquo +from sympy.polys.densearith import dup_max_norm +from sympy.polys.densearith import dmp_max_norm +from sympy.polys.densearith import dup_l1_norm +from sympy.polys.densearith import dmp_l1_norm +from sympy.polys.densearith import dup_l2_norm_squared +from sympy.polys.densearith import dmp_l2_norm_squared +from sympy.polys.densearith import dup_expand +from sympy.polys.densearith import dmp_expand +from sympy.polys.densebasic import dup_LC +from sympy.polys.densebasic import dmp_LC +from sympy.polys.densebasic import dup_TC +from sympy.polys.densebasic import dmp_TC +from sympy.polys.densebasic import dmp_ground_LC +from sympy.polys.densebasic import dmp_ground_TC +from sympy.polys.densebasic import dup_degree +from sympy.polys.densebasic import dmp_degree +from sympy.polys.densebasic import dmp_degree_in +from sympy.polys.densebasic import dmp_to_dict +from sympy.polys.densetools import dup_integrate +from sympy.polys.densetools import dmp_integrate +from sympy.polys.densetools import dmp_integrate_in +from sympy.polys.densetools import dup_diff +from sympy.polys.densetools import dmp_diff +from sympy.polys.densetools import dmp_diff_in +from sympy.polys.densetools import dup_eval +from sympy.polys.densetools import dmp_eval +from sympy.polys.densetools import dmp_eval_in +from sympy.polys.densetools import dmp_eval_tail +from sympy.polys.densetools import dmp_diff_eval_in +from sympy.polys.densetools import dup_trunc +from sympy.polys.densetools import dmp_trunc +from sympy.polys.densetools import dmp_ground_trunc +from sympy.polys.densetools import dup_monic +from sympy.polys.densetools import dmp_ground_monic +from sympy.polys.densetools import dup_content +from sympy.polys.densetools import dmp_ground_content +from sympy.polys.densetools import dup_primitive +from sympy.polys.densetools import dmp_ground_primitive +from sympy.polys.densetools import dup_extract +from sympy.polys.densetools import dmp_ground_extract +from sympy.polys.densetools import dup_real_imag +from sympy.polys.densetools import dup_mirror +from sympy.polys.densetools import dup_scale +from sympy.polys.densetools import dup_shift +from sympy.polys.densetools import dup_transform +from sympy.polys.densetools import dup_compose +from sympy.polys.densetools import dmp_compose +from sympy.polys.densetools import dup_decompose +from sympy.polys.densetools import dmp_lift +from sympy.polys.densetools import dup_sign_variations +from sympy.polys.densetools import dup_clear_denoms +from sympy.polys.densetools import dmp_clear_denoms +from sympy.polys.densetools import dup_revert +from sympy.polys.euclidtools import dup_half_gcdex +from sympy.polys.euclidtools import dmp_half_gcdex +from sympy.polys.euclidtools import dup_gcdex +from sympy.polys.euclidtools import dmp_gcdex +from sympy.polys.euclidtools import dup_invert +from sympy.polys.euclidtools import dmp_invert +from sympy.polys.euclidtools import dup_euclidean_prs +from sympy.polys.euclidtools import dmp_euclidean_prs +from sympy.polys.euclidtools import dup_primitive_prs +from sympy.polys.euclidtools import dmp_primitive_prs +from sympy.polys.euclidtools import dup_inner_subresultants +from sympy.polys.euclidtools import dup_subresultants +from sympy.polys.euclidtools import dup_prs_resultant +from sympy.polys.euclidtools import dup_resultant +from sympy.polys.euclidtools import dmp_inner_subresultants +from sympy.polys.euclidtools import dmp_subresultants +from sympy.polys.euclidtools import dmp_prs_resultant +from sympy.polys.euclidtools import dmp_zz_modular_resultant +from sympy.polys.euclidtools import dmp_zz_collins_resultant +from sympy.polys.euclidtools import dmp_qq_collins_resultant +from sympy.polys.euclidtools import dmp_resultant +from sympy.polys.euclidtools import dup_discriminant +from sympy.polys.euclidtools import dmp_discriminant +from sympy.polys.euclidtools import dup_rr_prs_gcd +from sympy.polys.euclidtools import dup_ff_prs_gcd +from sympy.polys.euclidtools import dmp_rr_prs_gcd +from sympy.polys.euclidtools import dmp_ff_prs_gcd +from sympy.polys.euclidtools import dup_zz_heu_gcd +from sympy.polys.euclidtools import dmp_zz_heu_gcd +from sympy.polys.euclidtools import dup_qq_heu_gcd +from sympy.polys.euclidtools import dmp_qq_heu_gcd +from sympy.polys.euclidtools import dup_inner_gcd +from sympy.polys.euclidtools import dmp_inner_gcd +from sympy.polys.euclidtools import dup_gcd +from sympy.polys.euclidtools import dmp_gcd +from sympy.polys.euclidtools import dup_rr_lcm +from sympy.polys.euclidtools import dup_ff_lcm +from sympy.polys.euclidtools import dup_lcm +from sympy.polys.euclidtools import dmp_rr_lcm +from sympy.polys.euclidtools import dmp_ff_lcm +from sympy.polys.euclidtools import dmp_lcm +from sympy.polys.euclidtools import dmp_content +from sympy.polys.euclidtools import dmp_primitive +from sympy.polys.euclidtools import dup_cancel +from sympy.polys.euclidtools import dmp_cancel +from sympy.polys.factortools import dup_trial_division +from sympy.polys.factortools import dmp_trial_division +from sympy.polys.factortools import dup_zz_mignotte_bound +from sympy.polys.factortools import dmp_zz_mignotte_bound +from sympy.polys.factortools import dup_zz_hensel_step +from sympy.polys.factortools import dup_zz_hensel_lift +from sympy.polys.factortools import dup_zz_zassenhaus +from sympy.polys.factortools import dup_zz_irreducible_p +from sympy.polys.factortools import dup_cyclotomic_p +from sympy.polys.factortools import dup_zz_cyclotomic_poly +from sympy.polys.factortools import dup_zz_cyclotomic_factor +from sympy.polys.factortools import dup_zz_factor_sqf +from sympy.polys.factortools import dup_zz_factor +from sympy.polys.factortools import dmp_zz_wang_non_divisors +from sympy.polys.factortools import dmp_zz_wang_lead_coeffs +from sympy.polys.factortools import dup_zz_diophantine +from sympy.polys.factortools import dmp_zz_diophantine +from sympy.polys.factortools import dmp_zz_wang_hensel_lifting +from sympy.polys.factortools import dmp_zz_wang +from sympy.polys.factortools import dmp_zz_factor +from sympy.polys.factortools import dup_qq_i_factor +from sympy.polys.factortools import dup_zz_i_factor +from sympy.polys.factortools import dmp_qq_i_factor +from sympy.polys.factortools import dmp_zz_i_factor +from sympy.polys.factortools import dup_ext_factor +from sympy.polys.factortools import dmp_ext_factor +from sympy.polys.factortools import dup_gf_factor +from sympy.polys.factortools import dmp_gf_factor +from sympy.polys.factortools import dup_factor_list +from sympy.polys.factortools import dup_factor_list_include +from sympy.polys.factortools import dmp_factor_list +from sympy.polys.factortools import dmp_factor_list_include +from sympy.polys.factortools import dup_irreducible_p +from sympy.polys.factortools import dmp_irreducible_p +from sympy.polys.rootisolation import dup_sturm +from sympy.polys.rootisolation import dup_root_upper_bound +from sympy.polys.rootisolation import dup_root_lower_bound +from sympy.polys.rootisolation import dup_step_refine_real_root +from sympy.polys.rootisolation import dup_inner_refine_real_root +from sympy.polys.rootisolation import dup_outer_refine_real_root +from sympy.polys.rootisolation import dup_refine_real_root +from sympy.polys.rootisolation import dup_inner_isolate_real_roots +from sympy.polys.rootisolation import dup_inner_isolate_positive_roots +from sympy.polys.rootisolation import dup_inner_isolate_negative_roots +from sympy.polys.rootisolation import dup_isolate_real_roots_sqf +from sympy.polys.rootisolation import dup_isolate_real_roots +from sympy.polys.rootisolation import dup_isolate_real_roots_list +from sympy.polys.rootisolation import dup_count_real_roots +from sympy.polys.rootisolation import dup_count_complex_roots +from sympy.polys.rootisolation import dup_isolate_complex_roots_sqf +from sympy.polys.rootisolation import dup_isolate_all_roots_sqf +from sympy.polys.rootisolation import dup_isolate_all_roots + +from sympy.polys.sqfreetools import ( + dup_sqf_p, dmp_sqf_p, dup_sqf_norm, dmp_sqf_norm, dup_gf_sqf_part, dmp_gf_sqf_part, + dup_sqf_part, dmp_sqf_part, dup_gf_sqf_list, dmp_gf_sqf_list, dup_sqf_list, + dup_sqf_list_include, dmp_sqf_list, dmp_sqf_list_include, dup_gff_list, dmp_gff_list) + +from sympy.polys.galoistools import ( + gf_degree, gf_LC, gf_TC, gf_strip, gf_from_dict, + gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground, + gf_mul_ground, gf_quo_ground, gf_add, gf_sub, gf_mul, gf_sqr, gf_add_mul, gf_sub_mul, + gf_expand, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_pow, gf_pow_mod, + gf_gcd, gf_lcm, gf_cofactors, gf_gcdex, gf_monic, gf_diff, gf_eval, gf_multi_eval, + gf_compose, gf_compose_mod, gf_trace_map, gf_random, gf_irreducible, gf_irred_p_ben_or, + gf_irred_p_rabin, gf_irreducible_p, gf_sqf_p, gf_sqf_part, gf_Qmatrix, + gf_berlekamp, gf_ddf_zassenhaus, gf_edf_zassenhaus, gf_ddf_shoup, gf_edf_shoup, + gf_zassenhaus, gf_shoup, gf_factor_sqf, gf_factor) + +from sympy.utilities import public + +@public +class IPolys: + symbols = None + ngens = None + domain = None + order = None + gens = None + + def drop(self, gen): + pass + + def clone(self, symbols=None, domain=None, order=None): + pass + + def to_ground(self): + pass + + def ground_new(self, element): + pass + + def domain_new(self, element): + pass + + def from_dict(self, d): + pass + + def wrap(self, element): + from sympy.polys.rings import PolyElement + if isinstance(element, PolyElement): + if element.ring == self: + return element + else: + raise NotImplementedError("domain conversions") + else: + return self.ground_new(element) + + def to_dense(self, element): + return self.wrap(element).to_dense() + + def from_dense(self, element): + return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain)) + + def dup_add_term(self, f, c, i): + return self.from_dense(dup_add_term(self.to_dense(f), c, i, self.domain)) + def dmp_add_term(self, f, c, i): + return self.from_dense(dmp_add_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + def dup_sub_term(self, f, c, i): + return self.from_dense(dup_sub_term(self.to_dense(f), c, i, self.domain)) + def dmp_sub_term(self, f, c, i): + return self.from_dense(dmp_sub_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + def dup_mul_term(self, f, c, i): + return self.from_dense(dup_mul_term(self.to_dense(f), c, i, self.domain)) + def dmp_mul_term(self, f, c, i): + return self.from_dense(dmp_mul_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + + def dup_add_ground(self, f, c): + return self.from_dense(dup_add_ground(self.to_dense(f), c, self.domain)) + def dmp_add_ground(self, f, c): + return self.from_dense(dmp_add_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_sub_ground(self, f, c): + return self.from_dense(dup_sub_ground(self.to_dense(f), c, self.domain)) + def dmp_sub_ground(self, f, c): + return self.from_dense(dmp_sub_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_mul_ground(self, f, c): + return self.from_dense(dup_mul_ground(self.to_dense(f), c, self.domain)) + def dmp_mul_ground(self, f, c): + return self.from_dense(dmp_mul_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_quo_ground(self, f, c): + return self.from_dense(dup_quo_ground(self.to_dense(f), c, self.domain)) + def dmp_quo_ground(self, f, c): + return self.from_dense(dmp_quo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_exquo_ground(self, f, c): + return self.from_dense(dup_exquo_ground(self.to_dense(f), c, self.domain)) + def dmp_exquo_ground(self, f, c): + return self.from_dense(dmp_exquo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + + def dup_lshift(self, f, n): + return self.from_dense(dup_lshift(self.to_dense(f), n, self.domain)) + def dup_rshift(self, f, n): + return self.from_dense(dup_rshift(self.to_dense(f), n, self.domain)) + + def dup_abs(self, f): + return self.from_dense(dup_abs(self.to_dense(f), self.domain)) + def dmp_abs(self, f): + return self.from_dense(dmp_abs(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_neg(self, f): + return self.from_dense(dup_neg(self.to_dense(f), self.domain)) + def dmp_neg(self, f): + return self.from_dense(dmp_neg(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_add(self, f, g): + return self.from_dense(dup_add(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_add(self, f, g): + return self.from_dense(dmp_add(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_sub(self, f, g): + return self.from_dense(dup_sub(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_sub(self, f, g): + return self.from_dense(dmp_sub(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_add_mul(self, f, g, h): + return self.from_dense(dup_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) + def dmp_add_mul(self, f, g, h): + return self.from_dense(dmp_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) + def dup_sub_mul(self, f, g, h): + return self.from_dense(dup_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) + def dmp_sub_mul(self, f, g, h): + return self.from_dense(dmp_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) + + def dup_mul(self, f, g): + return self.from_dense(dup_mul(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_mul(self, f, g): + return self.from_dense(dmp_mul(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_sqr(self, f): + return self.from_dense(dup_sqr(self.to_dense(f), self.domain)) + def dmp_sqr(self, f): + return self.from_dense(dmp_sqr(self.to_dense(f), self.ngens-1, self.domain)) + def dup_pow(self, f, n): + return self.from_dense(dup_pow(self.to_dense(f), n, self.domain)) + def dmp_pow(self, f, n): + return self.from_dense(dmp_pow(self.to_dense(f), n, self.ngens-1, self.domain)) + + def dup_pdiv(self, f, g): + q, r = dup_pdiv(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_prem(self, f, g): + return self.from_dense(dup_prem(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_pquo(self, f, g): + return self.from_dense(dup_pquo(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_pexquo(self, f, g): + return self.from_dense(dup_pexquo(self.to_dense(f), self.to_dense(g), self.domain)) + + def dmp_pdiv(self, f, g): + q, r = dmp_pdiv(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_prem(self, f, g): + return self.from_dense(dmp_prem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_pquo(self, f, g): + return self.from_dense(dmp_pquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_pexquo(self, f, g): + return self.from_dense(dmp_pexquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_rr_div(self, f, g): + q, r = dup_rr_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_rr_div(self, f, g): + q, r = dmp_rr_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_ff_div(self, f, g): + q, r = dup_ff_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_ff_div(self, f, g): + q, r = dmp_ff_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + + def dup_div(self, f, g): + q, r = dup_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_rem(self, f, g): + return self.from_dense(dup_rem(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_quo(self, f, g): + return self.from_dense(dup_quo(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_exquo(self, f, g): + return self.from_dense(dup_exquo(self.to_dense(f), self.to_dense(g), self.domain)) + + def dmp_div(self, f, g): + q, r = dmp_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_rem(self, f, g): + return self.from_dense(dmp_rem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_quo(self, f, g): + return self.from_dense(dmp_quo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_exquo(self, f, g): + return self.from_dense(dmp_exquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_max_norm(self, f): + return dup_max_norm(self.to_dense(f), self.domain) + def dmp_max_norm(self, f): + return dmp_max_norm(self.to_dense(f), self.ngens-1, self.domain) + + def dup_l1_norm(self, f): + return dup_l1_norm(self.to_dense(f), self.domain) + def dmp_l1_norm(self, f): + return dmp_l1_norm(self.to_dense(f), self.ngens-1, self.domain) + + def dup_l2_norm_squared(self, f): + return dup_l2_norm_squared(self.to_dense(f), self.domain) + def dmp_l2_norm_squared(self, f): + return dmp_l2_norm_squared(self.to_dense(f), self.ngens-1, self.domain) + + def dup_expand(self, polys): + return self.from_dense(dup_expand(list(map(self.to_dense, polys)), self.domain)) + def dmp_expand(self, polys): + return self.from_dense(dmp_expand(list(map(self.to_dense, polys)), self.ngens-1, self.domain)) + + def dup_LC(self, f): + return dup_LC(self.to_dense(f), self.domain) + def dmp_LC(self, f): + LC = dmp_LC(self.to_dense(f), self.domain) + if isinstance(LC, list): + return self[1:].from_dense(LC) + else: + return LC + def dup_TC(self, f): + return dup_TC(self.to_dense(f), self.domain) + def dmp_TC(self, f): + TC = dmp_TC(self.to_dense(f), self.domain) + if isinstance(TC, list): + return self[1:].from_dense(TC) + else: + return TC + + def dmp_ground_LC(self, f): + return dmp_ground_LC(self.to_dense(f), self.ngens-1, self.domain) + def dmp_ground_TC(self, f): + return dmp_ground_TC(self.to_dense(f), self.ngens-1, self.domain) + + def dup_degree(self, f): + return dup_degree(self.to_dense(f)) + def dmp_degree(self, f): + return dmp_degree(self.to_dense(f), self.ngens-1) + def dmp_degree_in(self, f, j): + return dmp_degree_in(self.to_dense(f), j, self.ngens-1) + def dup_integrate(self, f, m): + return self.from_dense(dup_integrate(self.to_dense(f), m, self.domain)) + def dmp_integrate(self, f, m): + return self.from_dense(dmp_integrate(self.to_dense(f), m, self.ngens-1, self.domain)) + + def dup_diff(self, f, m): + return self.from_dense(dup_diff(self.to_dense(f), m, self.domain)) + def dmp_diff(self, f, m): + return self.from_dense(dmp_diff(self.to_dense(f), m, self.ngens-1, self.domain)) + + def dmp_diff_in(self, f, m, j): + return self.from_dense(dmp_diff_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) + def dmp_integrate_in(self, f, m, j): + return self.from_dense(dmp_integrate_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) + + def dup_eval(self, f, a): + return dup_eval(self.to_dense(f), a, self.domain) + def dmp_eval(self, f, a): + result = dmp_eval(self.to_dense(f), a, self.ngens-1, self.domain) + return self[1:].from_dense(result) + + def dmp_eval_in(self, f, a, j): + result = dmp_eval_in(self.to_dense(f), a, j, self.ngens-1, self.domain) + return self.drop(j).from_dense(result) + def dmp_diff_eval_in(self, f, m, a, j): + result = dmp_diff_eval_in(self.to_dense(f), m, a, j, self.ngens-1, self.domain) + return self.drop(j).from_dense(result) + + def dmp_eval_tail(self, f, A): + result = dmp_eval_tail(self.to_dense(f), A, self.ngens-1, self.domain) + if isinstance(result, list): + return self[:-len(A)].from_dense(result) + else: + return result + + def dup_trunc(self, f, p): + return self.from_dense(dup_trunc(self.to_dense(f), p, self.domain)) + def dmp_trunc(self, f, g): + return self.from_dense(dmp_trunc(self.to_dense(f), self[1:].to_dense(g), self.ngens-1, self.domain)) + def dmp_ground_trunc(self, f, p): + return self.from_dense(dmp_ground_trunc(self.to_dense(f), p, self.ngens-1, self.domain)) + + def dup_monic(self, f): + return self.from_dense(dup_monic(self.to_dense(f), self.domain)) + def dmp_ground_monic(self, f): + return self.from_dense(dmp_ground_monic(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_extract(self, f, g): + c, F, G = dup_extract(self.to_dense(f), self.to_dense(g), self.domain) + return (c, self.from_dense(F), self.from_dense(G)) + def dmp_ground_extract(self, f, g): + c, F, G = dmp_ground_extract(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (c, self.from_dense(F), self.from_dense(G)) + + def dup_real_imag(self, f): + p, q = dup_real_imag(self.wrap(f).drop(1).to_dense(), self.domain) + return (self.from_dense(p), self.from_dense(q)) + + def dup_mirror(self, f): + return self.from_dense(dup_mirror(self.to_dense(f), self.domain)) + def dup_scale(self, f, a): + return self.from_dense(dup_scale(self.to_dense(f), a, self.domain)) + def dup_shift(self, f, a): + return self.from_dense(dup_shift(self.to_dense(f), a, self.domain)) + def dup_transform(self, f, p, q): + return self.from_dense(dup_transform(self.to_dense(f), self.to_dense(p), self.to_dense(q), self.domain)) + + def dup_compose(self, f, g): + return self.from_dense(dup_compose(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_compose(self, f, g): + return self.from_dense(dmp_compose(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_decompose(self, f): + components = dup_decompose(self.to_dense(f), self.domain) + return list(map(self.from_dense, components)) + + def dmp_lift(self, f): + result = dmp_lift(self.to_dense(f), self.ngens-1, self.domain) + return self.to_ground().from_dense(result) + + def dup_sign_variations(self, f): + return dup_sign_variations(self.to_dense(f), self.domain) + + def dup_clear_denoms(self, f, convert=False): + c, F = dup_clear_denoms(self.to_dense(f), self.domain, convert=convert) + if convert: + ring = self.clone(domain=self.domain.get_ring()) + else: + ring = self + return (c, ring.from_dense(F)) + def dmp_clear_denoms(self, f, convert=False): + c, F = dmp_clear_denoms(self.to_dense(f), self.ngens-1, self.domain, convert=convert) + if convert: + ring = self.clone(domain=self.domain.get_ring()) + else: + ring = self + return (c, ring.from_dense(F)) + + def dup_revert(self, f, n): + return self.from_dense(dup_revert(self.to_dense(f), n, self.domain)) + + def dup_half_gcdex(self, f, g): + s, h = dup_half_gcdex(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(s), self.from_dense(h)) + def dmp_half_gcdex(self, f, g): + s, h = dmp_half_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(s), self.from_dense(h)) + def dup_gcdex(self, f, g): + s, t, h = dup_gcdex(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) + def dmp_gcdex(self, f, g): + s, t, h = dmp_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) + + def dup_invert(self, f, g): + return self.from_dense(dup_invert(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_invert(self, f, g): + return self.from_dense(dmp_invert(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_euclidean_prs(self, f, g): + prs = dup_euclidean_prs(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_euclidean_prs(self, f, g): + prs = dmp_euclidean_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + def dup_primitive_prs(self, f, g): + prs = dup_primitive_prs(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_primitive_prs(self, f, g): + prs = dmp_primitive_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + + def dup_inner_subresultants(self, f, g): + prs, sres = dup_inner_subresultants(self.to_dense(f), self.to_dense(g), self.domain) + return (list(map(self.from_dense, prs)), sres) + def dmp_inner_subresultants(self, f, g): + prs, sres = dmp_inner_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (list(map(self.from_dense, prs)), sres) + + def dup_subresultants(self, f, g): + prs = dup_subresultants(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_subresultants(self, f, g): + prs = dmp_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + + def dup_prs_resultant(self, f, g): + res, prs = dup_prs_resultant(self.to_dense(f), self.to_dense(g), self.domain) + return (res, list(map(self.from_dense, prs))) + def dmp_prs_resultant(self, f, g): + res, prs = dmp_prs_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self[1:].from_dense(res), list(map(self.from_dense, prs))) + + def dmp_zz_modular_resultant(self, f, g, p): + res = dmp_zz_modular_resultant(self.to_dense(f), self.to_dense(g), self.domain_new(p), self.ngens-1, self.domain) + return self[1:].from_dense(res) + def dmp_zz_collins_resultant(self, f, g): + res = dmp_zz_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self[1:].from_dense(res) + def dmp_qq_collins_resultant(self, f, g): + res = dmp_qq_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self[1:].from_dense(res) + + def dup_resultant(self, f, g): #, includePRS=False): + return dup_resultant(self.to_dense(f), self.to_dense(g), self.domain) #, includePRS=includePRS) + def dmp_resultant(self, f, g): #, includePRS=False): + res = dmp_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) #, includePRS=includePRS) + if isinstance(res, list): + return self[1:].from_dense(res) + else: + return res + + def dup_discriminant(self, f): + return dup_discriminant(self.to_dense(f), self.domain) + def dmp_discriminant(self, f): + disc = dmp_discriminant(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(disc, list): + return self[1:].from_dense(disc) + else: + return disc + + def dup_rr_prs_gcd(self, f, g): + H, F, G = dup_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_ff_prs_gcd(self, f, g): + H, F, G = dup_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_rr_prs_gcd(self, f, g): + H, F, G = dmp_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_ff_prs_gcd(self, f, g): + H, F, G = dmp_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_zz_heu_gcd(self, f, g): + H, F, G = dup_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_zz_heu_gcd(self, f, g): + H, F, G = dmp_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_qq_heu_gcd(self, f, g): + H, F, G = dup_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_qq_heu_gcd(self, f, g): + H, F, G = dmp_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_inner_gcd(self, f, g): + H, F, G = dup_inner_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_inner_gcd(self, f, g): + H, F, G = dmp_inner_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_gcd(self, f, g): + H = dup_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dmp_gcd(self, f, g): + H = dmp_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dup_rr_lcm(self, f, g): + H = dup_rr_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dup_ff_lcm(self, f, g): + H = dup_ff_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dup_lcm(self, f, g): + H = dup_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dmp_rr_lcm(self, f, g): + H = dmp_rr_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dmp_ff_lcm(self, f, g): + H = dmp_ff_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dmp_lcm(self, f, g): + H = dmp_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + + def dup_content(self, f): + cont = dup_content(self.to_dense(f), self.domain) + return cont + def dup_primitive(self, f): + cont, prim = dup_primitive(self.to_dense(f), self.domain) + return cont, self.from_dense(prim) + + def dmp_content(self, f): + cont = dmp_content(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(cont, list): + return self[1:].from_dense(cont) + else: + return cont + def dmp_primitive(self, f): + cont, prim = dmp_primitive(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(cont, list): + return (self[1:].from_dense(cont), self.from_dense(prim)) + else: + return (cont, self.from_dense(prim)) + + def dmp_ground_content(self, f): + cont = dmp_ground_content(self.to_dense(f), self.ngens-1, self.domain) + return cont + def dmp_ground_primitive(self, f): + cont, prim = dmp_ground_primitive(self.to_dense(f), self.ngens-1, self.domain) + return (cont, self.from_dense(prim)) + + def dup_cancel(self, f, g, include=True): + result = dup_cancel(self.to_dense(f), self.to_dense(g), self.domain, include=include) + if not include: + cf, cg, F, G = result + return (cf, cg, self.from_dense(F), self.from_dense(G)) + else: + F, G = result + return (self.from_dense(F), self.from_dense(G)) + def dmp_cancel(self, f, g, include=True): + result = dmp_cancel(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain, include=include) + if not include: + cf, cg, F, G = result + return (cf, cg, self.from_dense(F), self.from_dense(G)) + else: + F, G = result + return (self.from_dense(F), self.from_dense(G)) + + def dup_trial_division(self, f, factors): + factors = dup_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_trial_division(self, f, factors): + factors = dmp_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_zz_mignotte_bound(self, f): + return dup_zz_mignotte_bound(self.to_dense(f), self.domain) + def dmp_zz_mignotte_bound(self, f): + return dmp_zz_mignotte_bound(self.to_dense(f), self.ngens-1, self.domain) + + def dup_zz_hensel_step(self, m, f, g, h, s, t): + D = self.to_dense + G, H, S, T = dup_zz_hensel_step(m, D(f), D(g), D(h), D(s), D(t), self.domain) + return (self.from_dense(G), self.from_dense(H), self.from_dense(S), self.from_dense(T)) + def dup_zz_hensel_lift(self, p, f, f_list, l): + D = self.to_dense + polys = dup_zz_hensel_lift(p, D(f), list(map(D, f_list)), l, self.domain) + return list(map(self.from_dense, polys)) + + def dup_zz_zassenhaus(self, f): + factors = dup_zz_zassenhaus(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_zz_irreducible_p(self, f): + return dup_zz_irreducible_p(self.to_dense(f), self.domain) + def dup_cyclotomic_p(self, f, irreducible=False): + return dup_cyclotomic_p(self.to_dense(f), self.domain, irreducible=irreducible) + def dup_zz_cyclotomic_poly(self, n): + F = dup_zz_cyclotomic_poly(n, self.domain) + return self.from_dense(F) + def dup_zz_cyclotomic_factor(self, f): + result = dup_zz_cyclotomic_factor(self.to_dense(f), self.domain) + if result is None: + return result + else: + return list(map(self.from_dense, result)) + + # E: List[ZZ], cs: ZZ, ct: ZZ + def dmp_zz_wang_non_divisors(self, E, cs, ct): + return dmp_zz_wang_non_divisors(E, cs, ct, self.domain) + + # f: Poly, T: List[(Poly, int)], ct: ZZ, A: List[ZZ] + #def dmp_zz_wang_test_points(f, T, ct, A): + # dmp_zz_wang_test_points(self.to_dense(f), T, ct, A, self.ngens-1, self.domain) + + # f: Poly, T: List[(Poly, int)], cs: ZZ, E: List[ZZ], H: List[Poly], A: List[ZZ] + def dmp_zz_wang_lead_coeffs(self, f, T, cs, E, H, A): + mv = self[1:] + T = [ (mv.to_dense(t), k) for t, k in T ] + uv = self[:1] + H = list(map(uv.to_dense, H)) + f, HH, CC = dmp_zz_wang_lead_coeffs(self.to_dense(f), T, cs, E, H, A, self.ngens-1, self.domain) + return self.from_dense(f), list(map(uv.from_dense, HH)), list(map(mv.from_dense, CC)) + + # f: List[Poly], m: int, p: ZZ + def dup_zz_diophantine(self, F, m, p): + result = dup_zz_diophantine(list(map(self.to_dense, F)), m, p, self.domain) + return list(map(self.from_dense, result)) + + # f: List[Poly], c: List[Poly], A: List[ZZ], d: int, p: ZZ + def dmp_zz_diophantine(self, F, c, A, d, p): + result = dmp_zz_diophantine(list(map(self.to_dense, F)), self.to_dense(c), A, d, p, self.ngens-1, self.domain) + return list(map(self.from_dense, result)) + + # f: Poly, H: List[Poly], LC: List[Poly], A: List[ZZ], p: ZZ + def dmp_zz_wang_hensel_lifting(self, f, H, LC, A, p): + uv = self[:1] + mv = self[1:] + H = list(map(uv.to_dense, H)) + LC = list(map(mv.to_dense, LC)) + result = dmp_zz_wang_hensel_lifting(self.to_dense(f), H, LC, A, p, self.ngens-1, self.domain) + return list(map(self.from_dense, result)) + + def dmp_zz_wang(self, f, mod=None, seed=None): + factors = dmp_zz_wang(self.to_dense(f), self.ngens-1, self.domain, mod=mod, seed=seed) + return [ self.from_dense(g) for g in factors ] + + def dup_zz_factor_sqf(self, f): + coeff, factors = dup_zz_factor_sqf(self.to_dense(f), self.domain) + return (coeff, [ self.from_dense(g) for g in factors ]) + + def dup_zz_factor(self, f): + coeff, factors = dup_zz_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_zz_factor(self, f): + coeff, factors = dmp_zz_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_qq_i_factor(self, f): + coeff, factors = dup_qq_i_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_qq_i_factor(self, f): + coeff, factors = dmp_qq_i_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_zz_i_factor(self, f): + coeff, factors = dup_zz_i_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_zz_i_factor(self, f): + coeff, factors = dmp_zz_i_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_ext_factor(self, f): + coeff, factors = dup_ext_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_ext_factor(self, f): + coeff, factors = dmp_ext_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_gf_factor(self, f): + coeff, factors = dup_gf_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_gf_factor(self, f): + coeff, factors = dmp_gf_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_factor_list(self, f): + coeff, factors = dup_factor_list(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dup_factor_list_include(self, f): + factors = dup_factor_list_include(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dmp_factor_list(self, f): + coeff, factors = dmp_factor_list(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_factor_list_include(self, f): + factors = dmp_factor_list_include(self.to_dense(f), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_irreducible_p(self, f): + return dup_irreducible_p(self.to_dense(f), self.domain) + def dmp_irreducible_p(self, f): + return dmp_irreducible_p(self.to_dense(f), self.ngens-1, self.domain) + + def dup_sturm(self, f): + seq = dup_sturm(self.to_dense(f), self.domain) + return list(map(self.from_dense, seq)) + + def dup_sqf_p(self, f): + return dup_sqf_p(self.to_dense(f), self.domain) + def dmp_sqf_p(self, f): + return dmp_sqf_p(self.to_dense(f), self.ngens-1, self.domain) + + def dup_sqf_norm(self, f): + s, F, R = dup_sqf_norm(self.to_dense(f), self.domain) + return (s, self.from_dense(F), self.to_ground().from_dense(R)) + def dmp_sqf_norm(self, f): + s, F, R = dmp_sqf_norm(self.to_dense(f), self.ngens-1, self.domain) + return (s, self.from_dense(F), self.to_ground().from_dense(R)) + + def dup_gf_sqf_part(self, f): + return self.from_dense(dup_gf_sqf_part(self.to_dense(f), self.domain)) + def dmp_gf_sqf_part(self, f): + return self.from_dense(dmp_gf_sqf_part(self.to_dense(f), self.domain)) + def dup_sqf_part(self, f): + return self.from_dense(dup_sqf_part(self.to_dense(f), self.domain)) + def dmp_sqf_part(self, f): + return self.from_dense(dmp_sqf_part(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_gf_sqf_list(self, f, all=False): + coeff, factors = dup_gf_sqf_list(self.to_dense(f), self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_gf_sqf_list(self, f, all=False): + coeff, factors = dmp_gf_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_sqf_list(self, f, all=False): + coeff, factors = dup_sqf_list(self.to_dense(f), self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dup_sqf_list_include(self, f, all=False): + factors = dup_sqf_list_include(self.to_dense(f), self.domain, all=all) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_sqf_list(self, f, all=False): + coeff, factors = dmp_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_sqf_list_include(self, f, all=False): + factors = dmp_sqf_list_include(self.to_dense(f), self.ngens-1, self.domain, all=all) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_gff_list(self, f): + factors = dup_gff_list(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_gff_list(self, f): + factors = dmp_gff_list(self.to_dense(f), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_root_upper_bound(self, f): + return dup_root_upper_bound(self.to_dense(f), self.domain) + def dup_root_lower_bound(self, f): + return dup_root_lower_bound(self.to_dense(f), self.domain) + + def dup_step_refine_real_root(self, f, M, fast=False): + return dup_step_refine_real_root(self.to_dense(f), M, self.domain, fast=fast) + def dup_inner_refine_real_root(self, f, M, eps=None, steps=None, disjoint=None, fast=False, mobius=False): + return dup_inner_refine_real_root(self.to_dense(f), M, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast, mobius=mobius) + def dup_outer_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): + return dup_outer_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + def dup_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): + return dup_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + def dup_inner_isolate_real_roots(self, f, eps=None, fast=False): + return dup_inner_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, fast=fast) + def dup_inner_isolate_positive_roots(self, f, eps=None, inf=None, sup=None, fast=False, mobius=False): + return dup_inner_isolate_positive_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, mobius=mobius) + def dup_inner_isolate_negative_roots(self, f, inf=None, sup=None, eps=None, fast=False, mobius=False): + return dup_inner_isolate_negative_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, eps=eps, fast=fast, mobius=mobius) + def dup_isolate_real_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): + return dup_isolate_real_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) + def dup_isolate_real_roots(self, f, eps=None, inf=None, sup=None, basis=False, fast=False): + return dup_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, basis=basis, fast=fast) + def dup_isolate_real_roots_list(self, polys, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): + return dup_isolate_real_roots_list(list(map(self.to_dense, polys)), self.domain, eps=eps, inf=inf, sup=sup, strict=strict, basis=basis, fast=fast) + def dup_count_real_roots(self, f, inf=None, sup=None): + return dup_count_real_roots(self.to_dense(f), self.domain, inf=inf, sup=sup) + def dup_count_complex_roots(self, f, inf=None, sup=None, exclude=None): + return dup_count_complex_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, exclude=exclude) + def dup_isolate_complex_roots_sqf(self, f, eps=None, inf=None, sup=None, blackbox=False): + return dup_isolate_complex_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, blackbox=blackbox) + def dup_isolate_all_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): + return dup_isolate_all_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) + def dup_isolate_all_roots(self, f, eps=None, inf=None, sup=None, fast=False): + return dup_isolate_all_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast) + + def fateman_poly_F_1(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_1 + return tuple(map(self.from_dense, dmp_fateman_poly_F_1(self.ngens-1, self.domain))) + def fateman_poly_F_2(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_2 + return tuple(map(self.from_dense, dmp_fateman_poly_F_2(self.ngens-1, self.domain))) + def fateman_poly_F_3(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_3 + return tuple(map(self.from_dense, dmp_fateman_poly_F_3(self.ngens-1, self.domain))) + + def to_gf_dense(self, element): + return gf_strip([ self.domain.dom.convert(c, self.domain) for c in self.wrap(element).to_dense() ]) + + def from_gf_dense(self, element): + return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain.dom)) + + def gf_degree(self, f): + return gf_degree(self.to_gf_dense(f)) + + def gf_LC(self, f): + return gf_LC(self.to_gf_dense(f), self.domain.dom) + def gf_TC(self, f): + return gf_TC(self.to_gf_dense(f), self.domain.dom) + + def gf_strip(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f))) + def gf_trunc(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod)) + def gf_normal(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_from_dict(self, f): + return self.from_gf_dense(gf_from_dict(f, self.domain.mod, self.domain.dom)) + def gf_to_dict(self, f, symmetric=True): + return gf_to_dict(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) + + def gf_from_int_poly(self, f): + return self.from_gf_dense(gf_from_int_poly(f, self.domain.mod)) + def gf_to_int_poly(self, f, symmetric=True): + return gf_to_int_poly(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) + + def gf_neg(self, f): + return self.from_gf_dense(gf_neg(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_add_ground(self, f, a): + return self.from_gf_dense(gf_add_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_sub_ground(self, f, a): + return self.from_gf_dense(gf_sub_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_mul_ground(self, f, a): + return self.from_gf_dense(gf_mul_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_quo_ground(self, f, a): + return self.from_gf_dense(gf_quo_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + + def gf_add(self, f, g): + return self.from_gf_dense(gf_add(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_sub(self, f, g): + return self.from_gf_dense(gf_sub(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_mul(self, f, g): + return self.from_gf_dense(gf_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_sqr(self, f): + return self.from_gf_dense(gf_sqr(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_add_mul(self, f, g, h): + return self.from_gf_dense(gf_add_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) + def gf_sub_mul(self, f, g, h): + return self.from_gf_dense(gf_sub_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) + + def gf_expand(self, F): + return self.from_gf_dense(gf_expand(list(map(self.to_gf_dense, F)), self.domain.mod, self.domain.dom)) + + def gf_div(self, f, g): + q, r = gf_div(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) + return self.from_gf_dense(q), self.from_gf_dense(r) + def gf_rem(self, f, g): + return self.from_gf_dense(gf_rem(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_quo(self, f, g): + return self.from_gf_dense(gf_quo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_exquo(self, f, g): + return self.from_gf_dense(gf_exquo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_lshift(self, f, n): + return self.from_gf_dense(gf_lshift(self.to_gf_dense(f), n, self.domain.dom)) + def gf_rshift(self, f, n): + return self.from_gf_dense(gf_rshift(self.to_gf_dense(f), n, self.domain.dom)) + + def gf_pow(self, f, n): + return self.from_gf_dense(gf_pow(self.to_gf_dense(f), n, self.domain.mod, self.domain.dom)) + def gf_pow_mod(self, f, n, g): + return self.from_gf_dense(gf_pow_mod(self.to_gf_dense(f), n, self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_cofactors(self, f, g): + h, cff, cfg = gf_cofactors(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) + return self.from_gf_dense(h), self.from_gf_dense(cff), self.from_gf_dense(cfg) + def gf_gcd(self, f, g): + return self.from_gf_dense(gf_gcd(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_lcm(self, f, g): + return self.from_gf_dense(gf_lcm(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_gcdex(self, f, g): + return self.from_gf_dense(gf_gcdex(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_monic(self, f): + return self.from_gf_dense(gf_monic(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + def gf_diff(self, f): + return self.from_gf_dense(gf_diff(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_eval(self, f, a): + return gf_eval(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom) + def gf_multi_eval(self, f, A): + return gf_multi_eval(self.to_gf_dense(f), A, self.domain.mod, self.domain.dom) + + def gf_compose(self, f, g): + return self.from_gf_dense(gf_compose(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_compose_mod(self, g, h, f): + return self.from_gf_dense(gf_compose_mod(self.to_gf_dense(g), self.to_gf_dense(h), self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_trace_map(self, a, b, c, n, f): + a = self.to_gf_dense(a) + b = self.to_gf_dense(b) + c = self.to_gf_dense(c) + f = self.to_gf_dense(f) + U, V = gf_trace_map(a, b, c, n, f, self.domain.mod, self.domain.dom) + return self.from_gf_dense(U), self.from_gf_dense(V) + + def gf_random(self, n): + return self.from_gf_dense(gf_random(n, self.domain.mod, self.domain.dom)) + def gf_irreducible(self, n): + return self.from_gf_dense(gf_irreducible(n, self.domain.mod, self.domain.dom)) + + def gf_irred_p_ben_or(self, f): + return gf_irred_p_ben_or(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_irred_p_rabin(self, f): + return gf_irred_p_rabin(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_irreducible_p(self, f): + return gf_irreducible_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_sqf_p(self, f): + return gf_sqf_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + + def gf_sqf_part(self, f): + return self.from_gf_dense(gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + def gf_sqf_list(self, f, all=False): + coeff, factors = gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ] + + def gf_Qmatrix(self, f): + return gf_Qmatrix(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_berlekamp(self, f): + factors = gf_berlekamp(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_ddf_zassenhaus(self, f): + factors = gf_ddf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ (self.from_gf_dense(g), k) for g, k in factors ] + def gf_edf_zassenhaus(self, f, n): + factors = gf_edf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_ddf_shoup(self, f): + factors = gf_ddf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ (self.from_gf_dense(g), k) for g, k in factors ] + def gf_edf_shoup(self, f, n): + factors = gf_edf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_zassenhaus(self, f): + factors = gf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + def gf_shoup(self, f): + factors = gf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_factor_sqf(self, f, method=None): + coeff, factors = gf_factor_sqf(self.to_gf_dense(f), self.domain.mod, self.domain.dom, method=method) + return coeff, [ self.from_gf_dense(g) for g in factors ] + def gf_factor(self, f): + coeff, factors = gf_factor(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ] diff --git a/shared/package-files/3a/3a4bcf63cb39f32e860bef32175cbc432ab1640a191f17833df1c339f2579da4/connection.pyi b/shared/package-files/3a/3a4bcf63cb39f32e860bef32175cbc432ab1640a191f17833df1c339f2579da4/connection.pyi new file mode 100644 index 0000000000000000000000000000000000000000..60e456e3918d75d2ce8918ec7073cb1d34b71c66 --- /dev/null +++ b/shared/package-files/3a/3a4bcf63cb39f32e860bef32175cbc432ab1640a191f17833df1c339f2579da4/connection.pyi @@ -0,0 +1,25 @@ +from Queue import Queue +from typing import Any, List, Optional, Tuple, Type + +families: List[None] + +class Connection(object): + _in: Any + _out: Any + recv: Any + recv_bytes: Any + send: Any + send_bytes: Any + def __init__(self, _in, _out) -> None: ... + def close(self) -> None: ... + def poll(self, timeout=...) -> Any: ... + +class Listener(object): + _backlog_queue: Optional[Queue[Any]] + address: Any + def __init__(self, address=..., family=..., backlog=...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + +def Client(address) -> Connection: ... +def Pipe(duplex=...) -> Tuple[Connection, Connection]: ... diff --git a/shared/package-files/3a/3a4ee1d9ce3b0d824bd6aecd5236ed51abf604e500c9b3e732bd9bd5528d5bfe/log_sigmoid_compositeimplicitautograd_dispatch.h b/shared/package-files/3a/3a4ee1d9ce3b0d824bd6aecd5236ed51abf604e500c9b3e732bd9bd5528d5bfe/log_sigmoid_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..eb562a37cf3c1987a31471370a9b3318b384ddf7 --- /dev/null +++ b/shared/package-files/3a/3a4ee1d9ce3b0d824bd6aecd5236ed51abf604e500c9b3e732bd9bd5528d5bfe/log_sigmoid_compositeimplicitautograd_dispatch.h @@ -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 log_sigmoid(const at::Tensor & self); +TORCH_API at::Tensor & log_sigmoid_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & log_sigmoid_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/3a/3a4f69aa3c238b6a51ed640f2ed6750ab46ed16f5a85dc9bf8968fe9ce30ab97/clickjacking.pyi b/shared/package-files/3a/3a4f69aa3c238b6a51ed640f2ed6750ab46ed16f5a85dc9bf8968fe9ce30ab97/clickjacking.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f93f1ff07dc74596c23ff2f64bb18bbde9ff264a --- /dev/null +++ b/shared/package-files/3a/3a4f69aa3c238b6a51ed640f2ed6750ab46ed16f5a85dc9bf8968fe9ce30ab97/clickjacking.pyi @@ -0,0 +1,7 @@ +from typing import Callable, TypeVar, Any + +_F = TypeVar("_F", bound=Callable[..., Any]) + +def xframe_options_deny(view_func: _F) -> _F: ... +def xframe_options_sameorigin(view_func: _F) -> _F: ... +def xframe_options_exempt(view_func: _F) -> _F: ... diff --git a/shared/package-files/3a/3a50b52036c9db2fea8e9f8708511145e04e1dbd3b0e794f67794c961c0c48b0/test_partial_slicing.py b/shared/package-files/3a/3a50b52036c9db2fea8e9f8708511145e04e1dbd3b0e794f67794c961c0c48b0/test_partial_slicing.py new file mode 100644 index 0000000000000000000000000000000000000000..8b493fc61cb5873532e2e8393007533ee6cb8e4f --- /dev/null +++ b/shared/package-files/3a/3a50b52036c9db2fea8e9f8708511145e04e1dbd3b0e794f67794c961c0c48b0/test_partial_slicing.py @@ -0,0 +1,466 @@ +""" test partial slicing on Series/Frame """ + +from datetime import datetime + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + Timedelta, + Timestamp, + date_range, +) +import pandas._testing as tm + + +class TestSlicing: + def test_string_index_series_name_converted(self): + # GH#1644 + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + index=date_range("1/1/2000", periods=10), + ) + + result = df.loc["1/3/2000"] + assert result.name == df.index[2] + + result = df.T["1/3/2000"] + assert result.name == df.index[2] + + def test_stringified_slice_with_tz(self): + # GH#2658 + start = "2013-01-07" + idx = date_range(start=start, freq="1d", periods=10, tz="US/Eastern") + df = DataFrame(np.arange(10), index=idx) + df["2013-01-14 23:44:34.437768-05:00":] # no exception here + + def test_return_type_doesnt_depend_on_monotonicity(self): + # GH#24892 we get Series back regardless of whether our DTI is monotonic + dti = date_range(start="2015-5-13 23:59:00", freq="min", periods=3) + ser = Series(range(3), index=dti) + + # non-monotonic index + ser2 = Series(range(3), index=[dti[1], dti[0], dti[2]]) + + # key with resolution strictly lower than "min" + key = "2015-5-14 00" + + # monotonic increasing index + result = ser.loc[key] + expected = ser.iloc[1:] + tm.assert_series_equal(result, expected) + + # monotonic decreasing index + result = ser.iloc[::-1].loc[key] + expected = ser.iloc[::-1][:-1] + tm.assert_series_equal(result, expected) + + # non-monotonic index + result2 = ser2.loc[key] + expected2 = ser2.iloc[::2] + tm.assert_series_equal(result2, expected2) + + def test_return_type_doesnt_depend_on_monotonicity_higher_reso(self): + # GH#24892 we get Series back regardless of whether our DTI is monotonic + dti = date_range(start="2015-5-13 23:59:00", freq="min", periods=3) + ser = Series(range(3), index=dti) + + # non-monotonic index + ser2 = Series(range(3), index=[dti[1], dti[0], dti[2]]) + + # key with resolution strictly *higher) than "min" + key = "2015-5-14 00:00:00" + + # monotonic increasing index + result = ser.loc[key] + assert result == 1 + + # monotonic decreasing index + result = ser.iloc[::-1].loc[key] + assert result == 1 + + # non-monotonic index + result2 = ser2.loc[key] + assert result2 == 0 + + def test_monotone_DTI_indexing_bug(self): + # GH 19362 + # Testing accessing the first element in a monotonic descending + # partial string indexing. + + df = DataFrame(list(range(5))) + date_list = [ + "2018-01-02", + "2017-02-10", + "2016-03-10", + "2015-03-15", + "2014-03-16", + ] + date_index = DatetimeIndex(date_list) + df["date"] = date_index + expected = DataFrame({0: list(range(5)), "date": date_index}) + tm.assert_frame_equal(df, expected) + + # We get a slice because df.index's resolution is hourly and we + # are slicing with a daily-resolution string. If both were daily, + # we would get a single item back + dti = date_range("20170101 01:00:00", periods=3) + df = DataFrame({"A": [1, 2, 3]}, index=dti[::-1]) + + expected = DataFrame({"A": 1}, index=dti[-1:][::-1]) + result = df.loc["2017-01-03"] + tm.assert_frame_equal(result, expected) + + result2 = df.iloc[::-1].loc["2017-01-03"] + expected2 = expected.iloc[::-1] + tm.assert_frame_equal(result2, expected2) + + def test_slice_year(self): + dti = date_range(freq="B", start=datetime(2005, 1, 1), periods=500) + + s = Series(np.arange(len(dti)), index=dti) + result = s["2005"] + expected = s[s.index.year == 2005] + tm.assert_series_equal(result, expected) + + df = DataFrame(np.random.default_rng(2).random((len(dti), 5)), index=dti) + result = df.loc["2005"] + expected = df[df.index.year == 2005] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "partial_dtime", + [ + "2019", + "2019Q4", + "Dec 2019", + "2019-12-31", + "2019-12-31 23", + "2019-12-31 23:59", + ], + ) + def test_slice_end_of_period_resolution(self, partial_dtime): + # GH#31064 + dti = date_range("2019-12-31 23:59:55.999999999", periods=10, freq="s") + + ser = Series(range(10), index=dti) + result = ser[partial_dtime] + expected = ser.iloc[:5] + tm.assert_series_equal(result, expected) + + def test_slice_quarter(self): + dti = date_range(freq="D", start=datetime(2000, 6, 1), periods=500) + + s = Series(np.arange(len(dti)), index=dti) + assert len(s["2001Q1"]) == 90 + + df = DataFrame(np.random.default_rng(2).random((len(dti), 5)), index=dti) + assert len(df.loc["1Q01"]) == 90 + + def test_slice_month(self): + dti = date_range(freq="D", start=datetime(2005, 1, 1), periods=500) + s = Series(np.arange(len(dti)), index=dti) + assert len(s["2005-11"]) == 30 + + df = DataFrame(np.random.default_rng(2).random((len(dti), 5)), index=dti) + assert len(df.loc["2005-11"]) == 30 + + tm.assert_series_equal(s["2005-11"], s["11-2005"]) + + def test_partial_slice(self): + rng = date_range(freq="D", start=datetime(2005, 1, 1), periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s["2005-05":"2006-02"] + expected = s["20050501":"20060228"] + tm.assert_series_equal(result, expected) + + result = s["2005-05":] + expected = s["20050501":] + tm.assert_series_equal(result, expected) + + result = s[:"2006-02"] + expected = s[:"20060228"] + tm.assert_series_equal(result, expected) + + result = s["2005-1-1"] + assert result == s.iloc[0] + + with pytest.raises(KeyError, match=r"^'2004-12-31'$"): + s["2004-12-31"] + + def test_partial_slice_daily(self): + rng = date_range(freq="h", start=datetime(2005, 1, 31), periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s["2005-1-31"] + tm.assert_series_equal(result, s.iloc[:24]) + + with pytest.raises(KeyError, match=r"^'2004-12-31 00'$"): + s["2004-12-31 00"] + + def test_partial_slice_hourly(self): + rng = date_range(freq="min", start=datetime(2005, 1, 1, 20, 0, 0), periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s["2005-1-1"] + tm.assert_series_equal(result, s.iloc[: 60 * 4]) + + result = s["2005-1-1 20"] + tm.assert_series_equal(result, s.iloc[:60]) + + assert s["2005-1-1 20:00"] == s.iloc[0] + with pytest.raises(KeyError, match=r"^'2004-12-31 00:15'$"): + s["2004-12-31 00:15"] + + def test_partial_slice_minutely(self): + rng = date_range(freq="s", start=datetime(2005, 1, 1, 23, 59, 0), periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s["2005-1-1 23:59"] + tm.assert_series_equal(result, s.iloc[:60]) + + result = s["2005-1-1"] + tm.assert_series_equal(result, s.iloc[:60]) + + assert s[Timestamp("2005-1-1 23:59:00")] == s.iloc[0] + with pytest.raises(KeyError, match=r"^'2004-12-31 00:00:00'$"): + s["2004-12-31 00:00:00"] + + def test_partial_slice_second_precision(self): + rng = date_range( + start=datetime(2005, 1, 1, 0, 0, 59, microsecond=999990), + periods=20, + freq="us", + ) + s = Series(np.arange(20), rng) + + tm.assert_series_equal(s["2005-1-1 00:00"], s.iloc[:10]) + tm.assert_series_equal(s["2005-1-1 00:00:59"], s.iloc[:10]) + + tm.assert_series_equal(s["2005-1-1 00:01"], s.iloc[10:]) + tm.assert_series_equal(s["2005-1-1 00:01:00"], s.iloc[10:]) + + assert s[Timestamp("2005-1-1 00:00:59.999990")] == s.iloc[0] + with pytest.raises(KeyError, match="2005-1-1 00:00:00"): + s["2005-1-1 00:00:00"] + + def test_partial_slicing_dataframe(self): + # GH14856 + # Test various combinations of string slicing resolution vs. + # index resolution + # - If string resolution is less precise than index resolution, + # string is considered a slice + # - If string resolution is equal to or more precise than index + # resolution, string is considered an exact match + formats = [ + "%Y", + "%Y-%m", + "%Y-%m-%d", + "%Y-%m-%d %H", + "%Y-%m-%d %H:%M", + "%Y-%m-%d %H:%M:%S", + ] + resolutions = ["year", "month", "day", "hour", "minute", "second"] + for rnum, resolution in enumerate(resolutions[2:], 2): + # we check only 'day', 'hour', 'minute' and 'second' + unit = Timedelta("1 " + resolution) + middate = datetime(2012, 1, 1, 0, 0, 0) + index = DatetimeIndex([middate - unit, middate, middate + unit]) + values = [1, 2, 3] + df = DataFrame({"a": values}, index, dtype=np.int64) + assert df.index.resolution == resolution + + # Timestamp with the same resolution as index + # Should be exact match for Series (return scalar) + # and raise KeyError for Frame + for timestamp, expected in zip(index, values): + ts_string = timestamp.strftime(formats[rnum]) + # make ts_string as precise as index + result = df["a"][ts_string] + assert isinstance(result, np.int64) + assert result == expected + msg = rf"^'{ts_string}'$" + with pytest.raises(KeyError, match=msg): + df[ts_string] + + # Timestamp with resolution less precise than index + for fmt in formats[:rnum]: + for element, theslice in [[0, slice(None, 1)], [1, slice(1, None)]]: + ts_string = index[element].strftime(fmt) + + # Series should return slice + result = df["a"][ts_string] + expected = df["a"][theslice] + tm.assert_series_equal(result, expected) + + # pre-2.0 df[ts_string] was overloaded to interpret this + # as slicing along index + with pytest.raises(KeyError, match=ts_string): + df[ts_string] + + # Timestamp with resolution more precise than index + # Compatible with existing key + # Should return scalar for Series + # and raise KeyError for Frame + for fmt in formats[rnum + 1 :]: + ts_string = index[1].strftime(fmt) + result = df["a"][ts_string] + assert isinstance(result, np.int64) + assert result == 2 + msg = rf"^'{ts_string}'$" + with pytest.raises(KeyError, match=msg): + df[ts_string] + + # Not compatible with existing key + # Should raise KeyError + for fmt, res in list(zip(formats, resolutions))[rnum + 1 :]: + ts = index[1] + Timedelta("1 " + res) + ts_string = ts.strftime(fmt) + msg = rf"^'{ts_string}'$" + with pytest.raises(KeyError, match=msg): + df["a"][ts_string] + with pytest.raises(KeyError, match=msg): + df[ts_string] + + def test_partial_slicing_with_multiindex(self): + # GH 4758 + # partial string indexing with a multi-index buggy + df = DataFrame( + { + "ACCOUNT": ["ACCT1", "ACCT1", "ACCT1", "ACCT2"], + "TICKER": ["ABC", "MNP", "XYZ", "XYZ"], + "val": [1, 2, 3, 4], + }, + index=date_range("2013-06-19 09:30:00", periods=4, freq="5min"), + ) + df_multi = df.set_index(["ACCOUNT", "TICKER"], append=True) + + expected = DataFrame( + [[1]], index=Index(["ABC"], name="TICKER"), columns=["val"] + ) + result = df_multi.loc[("2013-06-19 09:30:00", "ACCT1")] + tm.assert_frame_equal(result, expected) + + expected = df_multi.loc[ + (Timestamp("2013-06-19 09:30:00", tz=None), "ACCT1", "ABC") + ] + result = df_multi.loc[("2013-06-19 09:30:00", "ACCT1", "ABC")] + tm.assert_series_equal(result, expected) + + # partial string indexing on first level, scalar indexing on the other two + result = df_multi.loc[("2013-06-19", "ACCT1", "ABC")] + expected = df_multi.iloc[:1].droplevel([1, 2]) + tm.assert_frame_equal(result, expected) + + def test_partial_slicing_with_multiindex_series(self): + # GH 4294 + # partial slice on a series mi + ser = Series( + range(250), + index=MultiIndex.from_product( + [date_range("2000-1-1", periods=50), range(5)] + ), + ) + + s2 = ser[:-1].copy() + expected = s2["2000-1-4"] + result = s2[Timestamp("2000-1-4")] + tm.assert_series_equal(result, expected) + + result = ser[Timestamp("2000-1-4")] + expected = ser["2000-1-4"] + tm.assert_series_equal(result, expected) + + df2 = DataFrame(ser) + expected = df2.xs("2000-1-4") + result = df2.loc[Timestamp("2000-1-4")] + tm.assert_frame_equal(result, expected) + + def test_partial_slice_requires_monotonicity(self): + # Disallowed since 2.0 (GH 37819) + ser = Series(np.arange(10), date_range("2014-01-01", periods=10)) + + nonmonotonic = ser.iloc[[3, 5, 4]] + timestamp = Timestamp("2014-01-10") + with pytest.raises( + KeyError, match="Value based partial slicing on non-monotonic" + ): + nonmonotonic["2014-01-10":] + + with pytest.raises(KeyError, match=r"Timestamp\('2014-01-10 00:00:00'\)"): + nonmonotonic[timestamp:] + + with pytest.raises( + KeyError, match="Value based partial slicing on non-monotonic" + ): + nonmonotonic.loc["2014-01-10":] + + with pytest.raises(KeyError, match=r"Timestamp\('2014-01-10 00:00:00'\)"): + nonmonotonic.loc[timestamp:] + + def test_loc_datetime_length_one(self): + # GH16071 + df = DataFrame( + columns=["1"], + index=date_range("2016-10-01T00:00:00", "2016-10-01T23:59:59"), + ) + result = df.loc[datetime(2016, 10, 1) :] + tm.assert_frame_equal(result, df) + + result = df.loc["2016-10-01T00:00:00":] + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize( + "start", + [ + "2018-12-02 21:50:00+00:00", + Timestamp("2018-12-02 21:50:00+00:00"), + Timestamp("2018-12-02 21:50:00+00:00").to_pydatetime(), + ], + ) + @pytest.mark.parametrize( + "end", + [ + "2018-12-02 21:52:00+00:00", + Timestamp("2018-12-02 21:52:00+00:00"), + Timestamp("2018-12-02 21:52:00+00:00").to_pydatetime(), + ], + ) + def test_getitem_with_datestring_with_UTC_offset(self, start, end): + # GH 24076 + idx = date_range( + start="2018-12-02 14:50:00-07:00", + end="2018-12-02 14:50:00-07:00", + freq="1min", + ) + df = DataFrame(1, index=idx, columns=["A"]) + result = df[start:end] + expected = df.iloc[0:3, :] + tm.assert_frame_equal(result, expected) + + # GH 16785 + start = str(start) + end = str(end) + with pytest.raises(ValueError, match="Both dates must"): + df[start : end[:-4] + "1:00"] + + with pytest.raises(ValueError, match="The index must be timezone"): + df = df.tz_localize(None) + df[start:end] + + def test_slice_reduce_to_series(self): + # GH 27516 + df = DataFrame( + {"A": range(24)}, index=date_range("2000", periods=24, freq="ME") + ) + expected = Series( + range(12), index=date_range("2000", periods=12, freq="ME"), name="A" + ) + result = df.loc["2000", "A"] + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/3a/3a54650712a5ce9e550e2d9f9e703e25d97a1b47210edf7924d0af258836733b/odrpack.py b/shared/package-files/3a/3a54650712a5ce9e550e2d9f9e703e25d97a1b47210edf7924d0af258836733b/odrpack.py new file mode 100644 index 0000000000000000000000000000000000000000..192fb3342b7957703996957c882d44656706e41b --- /dev/null +++ b/shared/package-files/3a/3a54650712a5ce9e550e2d9f9e703e25d97a1b47210edf7924d0af258836733b/odrpack.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.odr` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'odr', 'OdrWarning', 'OdrError', 'OdrStop', + 'Data', 'RealData', 'Model', 'Output', 'ODR', + 'odr_error', 'odr_stop' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="odr", module="odrpack", + private_modules=["_odrpack"], all=__all__, + attribute=name) diff --git a/shared/package-files/3a/3a55936c9b7782676b7d1172c7f573ec64e60d38ebf1d89db391c0e137c2e91d/_cythonized_array_utils.pxd b/shared/package-files/3a/3a55936c9b7782676b7d1172c7f573ec64e60d38ebf1d89db391c0e137c2e91d/_cythonized_array_utils.pxd new file mode 100644 index 0000000000000000000000000000000000000000..ccec61c078e57ba7b6a310ec57189fcf236c972d --- /dev/null +++ b/shared/package-files/3a/3a55936c9b7782676b7d1172c7f573ec64e60d38ebf1d89db391c0e137c2e91d/_cythonized_array_utils.pxd @@ -0,0 +1,40 @@ +cimport numpy as cnp + +ctypedef fused lapack_t: + float + double + (float complex) + (double complex) + +ctypedef fused lapack_cz_t: + (float complex) + (double complex) + +ctypedef fused lapack_sd_t: + float + double + +ctypedef fused np_numeric_t: + cnp.int8_t + cnp.int16_t + cnp.int32_t + cnp.int64_t + cnp.uint8_t + cnp.uint16_t + cnp.uint32_t + cnp.uint64_t + cnp.float32_t + cnp.float64_t + cnp.longdouble_t + cnp.complex64_t + cnp.complex128_t + +ctypedef fused np_complex_numeric_t: + cnp.complex64_t + cnp.complex128_t + + +cdef void swap_c_and_f_layout(lapack_t *a, lapack_t *b, int r, int c) noexcept nogil +cdef (int, int) band_check_internal_c(np_numeric_t[:, ::1]A) noexcept nogil +cdef bint is_sym_her_real_c_internal(np_numeric_t[:, ::1]A) noexcept nogil +cdef bint is_sym_her_complex_c_internal(np_complex_numeric_t[:, ::1]A) noexcept nogil diff --git a/shared/package-files/3a/3a55e0b30a876c94039e03374390b6c8f20022d2d94325ae896b136b8f66e064/type_as_native.h b/shared/package-files/3a/3a55e0b30a876c94039e03374390b6c8f20022d2d94325ae896b136b8f66e064/type_as_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ce295606e9b731f353d52f7c3f09dfcd612c417a --- /dev/null +++ b/shared/package-files/3a/3a55e0b30a876c94039e03374390b6c8f20022d2d94325ae896b136b8f66e064/type_as_native.h @@ -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 type_as(const at::Tensor & self, const at::Tensor & other); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a589442d746dad7590c96265bfc2a5387997c0136c9d65d7ebe45b4bc324b4a/_foreach_round.h b/shared/package-files/3a/3a589442d746dad7590c96265bfc2a5387997c0136c9d65d7ebe45b4bc324b4a/_foreach_round.h new file mode 100644 index 0000000000000000000000000000000000000000..dab2400b4cd0713f0096ebc9f9d0455f0ae47087 --- /dev/null +++ b/shared/package-files/3a/3a589442d746dad7590c96265bfc2a5387997c0136c9d65d7ebe45b4bc324b4a/_foreach_round.h @@ -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_round(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_round(at::TensorList self) { + return at::_ops::_foreach_round::call(self); +} + +// aten::_foreach_round_(Tensor(a!)[] self) -> () +inline void _foreach_round_(at::TensorList self) { + return at::_ops::_foreach_round_::call(self); +} + +// aten::_foreach_round.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_round_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_round_out::call(self, out); +} +// aten::_foreach_round.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_round_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_round_out::call(self, out); +} + +} diff --git a/shared/package-files/3a/3a594b3ad68f2cfa01a5b5a86d45ca4bd52b186292cbbb5f17051dafa2284792/voterank_alg.py b/shared/package-files/3a/3a594b3ad68f2cfa01a5b5a86d45ca4bd52b186292cbbb5f17051dafa2284792/voterank_alg.py new file mode 100644 index 0000000000000000000000000000000000000000..c28df583b7ec7ffb59021963e0adda9921f7d7bb --- /dev/null +++ b/shared/package-files/3a/3a594b3ad68f2cfa01a5b5a86d45ca4bd52b186292cbbb5f17051dafa2284792/voterank_alg.py @@ -0,0 +1,92 @@ +"""Algorithm to select influential nodes in a graph using VoteRank.""" + +__all__ = ["voterank"] + + +def voterank(G, number_of_nodes=None): + """Select a list of influential nodes in a graph using VoteRank algorithm + + VoteRank [1]_ computes a ranking of the nodes in a graph G based on a + voting scheme. With VoteRank, all nodes vote for each of its in-neighbours + and the node with the highest votes is elected iteratively. The voting + ability of out-neighbors of elected nodes is decreased in subsequent turns. + + Parameters + ---------- + G : graph + A NetworkX graph. + + number_of_nodes : integer, optional + Number of ranked nodes to extract (default all nodes). + + Returns + ------- + voterank : list + Ordered list of computed seeds. + Only nodes with positive number of votes are returned. + + Examples + -------- + >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 4)]) + >>> nx.voterank(G) + [0, 1] + + The algorithm can be used both for undirected and directed graphs. + However, the directed version is different in two ways: + (i) nodes only vote for their in-neighbors and + (ii) only the voting ability of elected node and its out-neighbors are updated: + + >>> G = nx.DiGraph([(0, 1), (2, 1), (2, 3), (3, 4)]) + >>> nx.voterank(G) + [2, 3] + + Notes + ----- + Each edge is treated independently in case of multigraphs. + + References + ---------- + .. [1] Zhang, J.-X. et al. (2016). + Identifying a set of influential spreaders in complex networks. + Sci. Rep. 6, 27823; doi: 10.1038/srep27823. + """ + influential_nodes = [] + vote_rank = {} + if len(G) == 0: + return influential_nodes + if number_of_nodes is None or number_of_nodes > len(G): + number_of_nodes = len(G) + if G.is_directed(): + # For directed graphs compute average out-degree + avgDegree = sum(deg for _, deg in G.out_degree()) / len(G) + else: + # For undirected graphs compute average degree + avgDegree = sum(deg for _, deg in G.degree()) / len(G) + # step 1 - initiate all nodes to (0,1) (score, voting ability) + for n in G.nodes(): + vote_rank[n] = [0, 1] + # Repeat steps 1b to 4 until num_seeds are elected. + for _ in range(number_of_nodes): + # step 1b - reset rank + for n in G.nodes(): + vote_rank[n][0] = 0 + # step 2 - vote + for n, nbr in G.edges(): + # In directed graphs nodes only vote for their in-neighbors + vote_rank[n][0] += vote_rank[nbr][1] + if not G.is_directed(): + vote_rank[nbr][0] += vote_rank[n][1] + for n in influential_nodes: + vote_rank[n][0] = 0 + # step 3 - select top node + n = max(G.nodes, key=lambda x: vote_rank[x][0]) + if vote_rank[n][0] == 0: + return influential_nodes + influential_nodes.append(n) + # weaken the selected node + vote_rank[n] = [0, 0] + # step 4 - update voterank properties + for _, nbr in G.edges(n): + vote_rank[nbr][1] -= 1 / avgDegree + vote_rank[nbr][1] = max(vote_rank[nbr][1], 0) + return influential_nodes diff --git a/shared/package-files/3a/3a5957c6e927711edaf92326745a31e5acf5c6920f3216da85086d39b9a9b833/Niue b/shared/package-files/3a/3a5957c6e927711edaf92326745a31e5acf5c6920f3216da85086d39b9a9b833/Niue new file mode 100644 index 0000000000000000000000000000000000000000..f76972f8849a7d6ed8c3e2649b02f44de891094f Binary files /dev/null and b/shared/package-files/3a/3a5957c6e927711edaf92326745a31e5acf5c6920f3216da85086d39b9a9b833/Niue differ diff --git a/shared/package-files/3a/3a5b877bbbbee1c01e57522caa1de1839ac4432b573cec11a71ba2cca79ccc87/conv.py b/shared/package-files/3a/3a5b877bbbbee1c01e57522caa1de1839ac4432b573cec11a71ba2cca79ccc87/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..4dc5ef66147c5a7d3495ea62c48cb35e38cfe1a5 --- /dev/null +++ b/shared/package-files/3a/3a5b877bbbbee1c01e57522caa1de1839ac4432b573cec11a71ba2cca79ccc87/conv.py @@ -0,0 +1,18 @@ +# flake8: noqa: F401 +r"""Quantized Dynamic Modules. + +This file is in the process of migration to `torch/ao/nn/quantized/dynamic`, +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 +appropriate file under the `torch/ao/nn/quantized/dynamic/modules`, +while adding an import statement here. +""" + +__all__ = ['Conv1d', 'Conv2d', 'Conv3d', 'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d'] + +from torch.ao.nn.quantized.dynamic.modules.conv import Conv1d +from torch.ao.nn.quantized.dynamic.modules.conv import Conv2d +from torch.ao.nn.quantized.dynamic.modules.conv import Conv3d +from torch.ao.nn.quantized.dynamic.modules.conv import ConvTranspose1d +from torch.ao.nn.quantized.dynamic.modules.conv import ConvTranspose2d +from torch.ao.nn.quantized.dynamic.modules.conv import ConvTranspose3d diff --git a/shared/package-files/3a/3a6140b7a396424bc2986c1c8fec1392c1ce4a1ec5b03d4ef9a52d7b0cf2b5fa/COPYRIGHTS.txt b/shared/package-files/3a/3a6140b7a396424bc2986c1c8fec1392c1ce4a1ec5b03d4ef9a52d7b0cf2b5fa/COPYRIGHTS.txt new file mode 100644 index 0000000000000000000000000000000000000000..200c7749eb37f0b81de43ef88e7a93ca2d707244 --- /dev/null +++ b/shared/package-files/3a/3a6140b7a396424bc2986c1c8fec1392c1ce4a1ec5b03d4ef9a52d7b0cf2b5fa/COPYRIGHTS.txt @@ -0,0 +1,5 @@ +The license of this package can be found in LICENSE.txt +This file contains a Python version of the gradient projection rotation +algorithms (GPA) developed by Bernaards, C.A. and Jennrich, R.I. +The code is based on code developed Bernaards, C.A. and Jennrich, R.I. +and is ported and made available with permission of the authors. \ No newline at end of file diff --git a/shared/package-files/3a/3a6389ac0e4cc98543709645643616860588da43906e0f86715c9f29b2afa192/_softmax_ops.h b/shared/package-files/3a/3a6389ac0e4cc98543709645643616860588da43906e0f86715c9f29b2afa192/_softmax_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..577ef30cc78b35c499f4148fcdfa6ceb5885daf9 --- /dev/null +++ b/shared/package-files/3a/3a6389ac0e4cc98543709645643616860588da43906e0f86715c9f29b2afa192/_softmax_ops.h @@ -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 _softmax { + using schema = at::Tensor (const at::Tensor &, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_softmax") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_softmax(Tensor self, int dim, bool half_to_float) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t dim, bool half_to_float); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool half_to_float); +}; + +struct TORCH_API _softmax_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, 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::_softmax") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3a6605b2914a49293addf5705763a3f16bb8661551b74ad047f13eae0fd5dd93/static_getitem.py b/shared/package-files/3a/3a6605b2914a49293addf5705763a3f16bb8661551b74ad047f13eae0fd5dd93/static_getitem.py new file mode 100644 index 0000000000000000000000000000000000000000..56343d0eac93cef756834d22c76780e228398a7d --- /dev/null +++ b/shared/package-files/3a/3a6605b2914a49293addf5705763a3f16bb8661551b74ad047f13eae0fd5dd93/static_getitem.py @@ -0,0 +1,175 @@ +from numba.core import errors, ir, types +from numba.core.rewrites import register_rewrite, Rewrite + + +@register_rewrite('before-inference') +class RewriteConstGetitems(Rewrite): + """ + Rewrite IR expressions of the kind `getitem(value=arr, index=$constXX)` + where `$constXX` is a known constant as + `static_getitem(value=arr, index=)`. + """ + + def match(self, func_ir, block, typemap, calltypes): + self.getitems = getitems = {} + self.block = block + # Detect all getitem expressions and find which ones can be + # rewritten + for expr in block.find_exprs(op='getitem'): + if expr.op == 'getitem': + try: + const = func_ir.infer_constant(expr.index) + except errors.ConstantInferenceError: + continue + getitems[expr] = const + + return len(getitems) > 0 + + def apply(self): + """ + Rewrite all matching getitems as static_getitems. + """ + new_block = self.block.copy() + new_block.clear() + for inst in self.block.body: + if isinstance(inst, ir.Assign): + expr = inst.value + if expr in self.getitems: + const = self.getitems[expr] + new_expr = ir.Expr.static_getitem(value=expr.value, + index=const, + index_var=expr.index, + loc=expr.loc) + inst = ir.Assign(value=new_expr, target=inst.target, + loc=inst.loc) + new_block.append(inst) + return new_block + + +@register_rewrite('after-inference') +class RewriteStringLiteralGetitems(Rewrite): + """ + Rewrite IR expressions of the kind `getitem(value=arr, index=$XX)` + where `$XX` is a StringLiteral value as + `static_getitem(value=arr, index=)`. + """ + + def match(self, func_ir, block, typemap, calltypes): + """ + Detect all getitem expressions and find which ones have + string literal indexes + """ + self.getitems = getitems = {} + self.block = block + self.calltypes = calltypes + for expr in block.find_exprs(op='getitem'): + if expr.op == 'getitem': + index_ty = typemap[expr.index.name] + if isinstance(index_ty, types.StringLiteral): + getitems[expr] = (expr.index, index_ty.literal_value) + + return len(getitems) > 0 + + def apply(self): + """ + Rewrite all matching getitems as static_getitems where the index + is the literal value of the string. + """ + new_block = ir.Block(self.block.scope, self.block.loc) + for inst in self.block.body: + if isinstance(inst, ir.Assign): + expr = inst.value + if expr in self.getitems: + const, lit_val = self.getitems[expr] + new_expr = ir.Expr.static_getitem(value=expr.value, + index=lit_val, + index_var=expr.index, + loc=expr.loc) + self.calltypes[new_expr] = self.calltypes[expr] + inst = ir.Assign(value=new_expr, target=inst.target, + loc=inst.loc) + new_block.append(inst) + return new_block + + +@register_rewrite('after-inference') +class RewriteStringLiteralSetitems(Rewrite): + """ + Rewrite IR expressions of the kind `setitem(value=arr, index=$XX, value=)` + where `$XX` is a StringLiteral value as + `static_setitem(value=arr, index=, value=)`. + """ + + def match(self, func_ir, block, typemap, calltypes): + """ + Detect all setitem expressions and find which ones have + string literal indexes + """ + self.setitems = setitems = {} + self.block = block + self.calltypes = calltypes + for inst in block.find_insts(ir.SetItem): + index_ty = typemap[inst.index.name] + if isinstance(index_ty, types.StringLiteral): + setitems[inst] = (inst.index, index_ty.literal_value) + + return len(setitems) > 0 + + def apply(self): + """ + Rewrite all matching setitems as static_setitems where the index + is the literal value of the string. + """ + new_block = ir.Block(self.block.scope, self.block.loc) + for inst in self.block.body: + if isinstance(inst, ir.SetItem): + if inst in self.setitems: + const, lit_val = self.setitems[inst] + new_inst = ir.StaticSetItem(target=inst.target, + index=lit_val, + index_var=inst.index, + value=inst.value, + loc=inst.loc) + self.calltypes[new_inst] = self.calltypes[inst] + inst = new_inst + new_block.append(inst) + return new_block + + +@register_rewrite('before-inference') +class RewriteConstSetitems(Rewrite): + """ + Rewrite IR statements of the kind `setitem(target=arr, index=$constXX, ...)` + where `$constXX` is a known constant as + `static_setitem(target=arr, index=, ...)`. + """ + + def match(self, func_ir, block, typemap, calltypes): + self.setitems = setitems = {} + self.block = block + # Detect all setitem statements and find which ones can be + # rewritten + for inst in block.find_insts(ir.SetItem): + try: + const = func_ir.infer_constant(inst.index) + except errors.ConstantInferenceError: + continue + setitems[inst] = const + + return len(setitems) > 0 + + def apply(self): + """ + Rewrite all matching setitems as static_setitems. + """ + new_block = self.block.copy() + new_block.clear() + for inst in self.block.body: + if inst in self.setitems: + const = self.setitems[inst] + new_inst = ir.StaticSetItem(inst.target, const, + inst.index, inst.value, inst.loc) + new_block.append(new_inst) + else: + new_block.append(inst) + return new_block diff --git a/shared/package-files/3a/3a66cbf0daea9ba529cf15cf9dfcd9e32140a957c51981b364ce2ac5d3a0260e/pytestplugin.py b/shared/package-files/3a/3a66cbf0daea9ba529cf15cf9dfcd9e32140a957c51981b364ce2ac5d3a0260e/pytestplugin.py new file mode 100644 index 0000000000000000000000000000000000000000..d21b209b41151c7466e9453e2362e09503acde23 --- /dev/null +++ b/shared/package-files/3a/3a66cbf0daea9ba529cf15cf9dfcd9e32140a957c51981b364ce2ac5d3a0260e/pytestplugin.py @@ -0,0 +1,19 @@ +# 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/. + +""" +Stub for users who manually load our pytest plugin. + +The plugin implementation is now located in a top-level module outside the main +hypothesis tree, so that Pytest can load the plugin without thereby triggering +the import of Hypothesis itself (and thus loading our own plugins). +""" + +from _hypothesis_pytestplugin import * # noqa diff --git a/shared/package-files/3a/3a6a6dba7c38fe0c9b5280d9d067c27573917b0557932ef862d03da77e03b0e2/api.py b/shared/package-files/3a/3a6a6dba7c38fe0c9b5280d9d067c27573917b0557932ef862d03da77e03b0e2/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1dab2eeb8084800458bd4e4399fbfe49ebbc75 --- /dev/null +++ b/shared/package-files/3a/3a6a6dba7c38fe0c9b5280d9d067c27573917b0557932ef862d03da77e03b0e2/api.py @@ -0,0 +1,498 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from .base.constants import DepsModifier as _DepsModifier +from .base.constants import UpdateModifier as _UpdateModifier +from .base.context import context +from .common.constants import NULL +from .core.package_cache_data import PackageCacheData as _PackageCacheData +from .core.prefix_data import PrefixData as _PrefixData +from .core.subdir_data import SubdirData as _SubdirData +from .models.channel import Channel + +DepsModifier = _DepsModifier +"""Flags to enable alternate handling of dependencies.""" + +UpdateModifier = _UpdateModifier +"""Flags to enable alternate handling for updates of existing packages in the environment.""" + + +class Solver: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + A high-level API to conda's solving logic. Three public methods are provided to access a + solution in various forms. + + * :meth:`solve_final_state` + * :meth:`solve_for_diff` + * :meth:`solve_for_transaction` + + """ + + def __init__( + self, prefix, channels, subdirs=(), specs_to_add=(), specs_to_remove=() + ): + """ + **Beta** + + Args: + prefix (str): + The conda prefix / environment location for which the :class:`Solver` + is being instantiated. + channels (Sequence[:class:`Channel`]): + A prioritized list of channels to use for the solution. + subdirs (Sequence[str]): + A prioritized list of subdirs to use for the solution. + specs_to_add (set[:class:`MatchSpec`]): + The set of package specs to add to the prefix. + specs_to_remove (set[:class:`MatchSpec`]): + The set of package specs to remove from the prefix. + + """ + solver_backend = context.plugin_manager.get_cached_solver_backend() + self._internal = solver_backend( + prefix, channels, subdirs, specs_to_add, specs_to_remove + ) + + def solve_final_state( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives the final, solved state of the environment. + + Args: + deps_modifier (DepsModifier): + An optional flag indicating special solver handling for dependencies. The + default solver behavior is to be as conservative as possible with dependency + updates (in the case the dependency already exists in the environment), while + still ensuring all dependencies are satisfied. Options include + * NO_DEPS + * ONLY_DEPS + * UPDATE_DEPS + * UPDATE_DEPS_ONLY_DEPS + * FREEZE_INSTALLED + prune (bool): + If ``True``, the solution will not contain packages that were + previously brought into the environment as dependencies but are no longer + required as dependencies and are not user-requested. + ignore_pinned (bool): + If ``True``, the solution will ignore pinned package configuration + for the prefix. + force_remove (bool): + Forces removal of a package without removing packages that depend on it. + + Returns: + tuple[PackageRef]: + In sorted dependency order from roots to leaves, the package references for + the solved state of the environment. + + """ + return self._internal.solve_final_state( + update_modifier, deps_modifier, prune, ignore_pinned, force_remove + ) + + def solve_for_diff( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=False, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives the package references to remove from an environment, followed by + the package references to add to an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + For requested specs_to_add that are already satisfied in the environment, + instructs the solver to remove the package and spec from the environment, + and then add it back--possibly with the exact package instance modified, + depending on the spec exactness. + + Returns: + tuple[PackageRef], tuple[PackageRef]: + A two-tuple of PackageRef sequences. The first is the group of packages to + remove from the environment, in sorted dependency order from leaves to roots. + The second is the group of packages to add to the environment, in sorted + dependency order from roots to leaves. + + """ + return self._internal.solve_for_diff( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + force_reinstall, + ) + + def solve_for_transaction( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=False, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives an UnlinkLinkTransaction instance that can be used to execute the solution + on an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + See :meth:`solve_for_diff`. + + Returns: + UnlinkLinkTransaction: + + """ + return self._internal.solve_for_transaction( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + force_reinstall, + ) + + +class SubdirData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of repodata.json for subdirs. + """ + + def __init__(self, channel): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + channel (str or Channel): + The target subdir for the instance. Must either be a url that includes a subdir + or a :obj:`Channel` that includes a subdir. e.g.: + * 'https://repo.anaconda.com/pkgs/main/linux-64' + * Channel('https://repo.anaconda.com/pkgs/main/linux-64') + * Channel('conda-forge/osx-64') + """ + channel = Channel(channel) + assert channel.subdir + self._internal = _SubdirData(channel) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific instance of repodata. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PackageRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + @staticmethod + def query_all(package_ref_or_match_spec, channels=None, subdirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against all repodata instances in channel/subdir matrix. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + channels (Iterable[Channel or str] or None): + An iterable of urls for channels or :obj:`Channel` objects. If None, will fall + back to context.channels. + subdirs (Iterable[str] or None): + If None, will fall back to context.subdirs. + + Returns: + tuple[PackageRecord] + + """ + return tuple( + _SubdirData.query_all(package_ref_or_match_spec, channels, subdirs) + ) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PackageRecord]: A generator over all records contained in the repodata.json + instance. Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. repodata.json) + is lazily downloaded/loaded on first use by the other methods of this class. You + should only use this method if you are *sure* you have outdated data. + + Returns: + SubdirData + + """ + self._internal = self._internal.reload() + return self + + +class PackageCacheData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of package caches. + """ + + def __init__(self, pkgs_dir): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + pkgs_dir (str): + """ + self._internal = _PackageCacheData(pkgs_dir) + + def get(self, package_ref, default=NULL): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + package_ref (PackageRef): + A :obj:`PackageRef` instance representing the key for the + :obj:`PackageCacheRecord` being sought. + default: The default value to return if the record does not exist. If not + specified and no record exists, :exc:`KeyError` is raised. + + Returns: + PackageCacheRecord + + """ + return self._internal.get(package_ref, default) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific package cache instance. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PackageCacheRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + @staticmethod + def query_all(package_ref_or_match_spec, pkgs_dirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against all package caches. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + pkgs_dirs (Iterable[str] or None): + If None, will fall back to context.pkgs_dirs. + + Returns: + tuple[PackageCacheRecord] + + """ + return tuple(_PackageCacheData.query_all(package_ref_or_match_spec, pkgs_dirs)) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PackageCacheRecord]: A generator over all records contained in the package + cache instance. Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + @property + def is_writable(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Indicates if the package cache location is writable or read-only. + + Returns: + bool + + """ + return self._internal.is_writable + + @staticmethod + def first_writable(pkgs_dirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Get an instance object for the first writable package cache. + + Args: + pkgs_dirs (Iterable[str]): + If None, will fall back to context.pkgs_dirs. + + Returns: + PackageCacheData: + An instance for the first writable package cache. + + """ + return PackageCacheData(_PackageCacheData.first_writable(pkgs_dirs).pkgs_dir) + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. contents of + the pkgs_dir) is lazily loaded on first use by the other methods of this class. You + should only use this method if you are *sure* you have outdated data. + + Returns: + PackageCacheData + + """ + self._internal = self._internal.reload() + return self + + +class PrefixData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of conda environment prefixes. + """ + + def __init__(self, prefix_path): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + prefix_path (str): + """ + self._internal = _PrefixData(prefix_path) + + def get(self, package_ref, default=NULL): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + package_ref (PackageRef): + A :obj:`PackageRef` instance representing the key for the + :obj:`PrefixRecord` being sought. + default: The default value to return if the record does not exist. If not + specified and no record exists, :exc:`KeyError` is raised. + + Returns: + PrefixRecord + + """ + return self._internal.get(package_ref.name, default) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific prefix instance. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PrefixRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PrefixRecord]: A generator over all records contained in the prefix. + Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + @property + def is_writable(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Indicates if the prefix is writable or read-only. + + Returns: + bool or None: + True if the prefix is writable. False if read-only. None if the prefix + does not exist as a conda environment. + + """ + return self._internal.is_writable + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. contents of + the conda-meta directory) is lazily loaded on first use by the other methods of this + class. You should only use this method if you are *sure* you have outdated data. + + Returns: + PrefixData + + """ + self._internal = self._internal.reload() + return self diff --git a/shared/package-files/3a/3a6e95d01c45e2e47c05df3c81073b895c97c1eb0e5b90ab175d6d9263fc81f2/_uninstall.py b/shared/package-files/3a/3a6e95d01c45e2e47c05df3c81073b895c97c1eb0e5b90ab175d6d9263fc81f2/_uninstall.py new file mode 100644 index 0000000000000000000000000000000000000000..b257904328d2f5dc3b5f07e7d6c883fb9e2055a9 --- /dev/null +++ b/shared/package-files/3a/3a6e95d01c45e2e47c05df3c81073b895c97c1eb0e5b90ab175d6d9263fc81f2/_uninstall.py @@ -0,0 +1,31 @@ +"""Basic pip uninstallation support, helper for the Windows uninstaller""" + +import argparse +import ensurepip +import sys + + +def _main(argv=None): + parser = argparse.ArgumentParser(prog="python -m ensurepip._uninstall") + parser.add_argument( + "--version", + action="version", + version="pip {}".format(ensurepip.version()), + help="Show the version of pip this will attempt to uninstall.", + ) + parser.add_argument( + "-v", "--verbose", + action="count", + default=0, + dest="verbosity", + help=("Give more output. Option is additive, and can be used up to 3 " + "times."), + ) + + args = parser.parse_args(argv) + + return ensurepip._uninstall_helper(verbosity=args.verbosity) + + +if __name__ == "__main__": + sys.exit(_main()) diff --git a/shared/package-files/3a/3a6f8405f61db8517deed817385ebcaebf3361b9e07a6f640519bd48988a2d23/cxxnodes.py b/shared/package-files/3a/3a6f8405f61db8517deed817385ebcaebf3361b9e07a6f640519bd48988a2d23/cxxnodes.py new file mode 100644 index 0000000000000000000000000000000000000000..7f7aafd01ab2de99ad0f668275889863fc73f5aa --- /dev/null +++ b/shared/package-files/3a/3a6f8405f61db8517deed817385ebcaebf3361b9e07a6f640519bd48988a2d23/cxxnodes.py @@ -0,0 +1,14 @@ +""" +AST nodes specific to C++. +""" + +from sympy.codegen.ast import Attribute, String, Token, Type, none + +class using(Token): + """ Represents a 'using' statement in C++ """ + __slots__ = _fields = ('type', 'alias') + defaults = {'alias': none} + _construct_type = Type + _construct_alias = String + +constexpr = Attribute('constexpr') diff --git a/shared/package-files/3a/3a70e0a21cad03147246f6363d07bf76fae216c72779707f4ae5db06bcacf067/LICENSE b/shared/package-files/3a/3a70e0a21cad03147246f6363d07bf76fae216c72779707f4ae5db06bcacf067/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7d19426e7a09d04cef6dbd2a2857434036362ee1 --- /dev/null +++ b/shared/package-files/3a/3a70e0a21cad03147246f6363d07bf76fae216c72779707f4ae5db06bcacf067/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2012, Anaconda, Inc. +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. +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/3a/3a71c3195aa3760870a4f561b132bb0c71254e894d4acf0cbdf007130a0bc3ca/builtins.pyi b/shared/package-files/3a/3a71c3195aa3760870a4f561b132bb0c71254e894d4acf0cbdf007130a0bc3ca/builtins.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fdaab429730b1ce2d6602016cafc89879bfbb14b --- /dev/null +++ b/shared/package-files/3a/3a71c3195aa3760870a4f561b132bb0c71254e894d4acf0cbdf007130a0bc3ca/builtins.pyi @@ -0,0 +1,1387 @@ +import sys +from _typeshed import ( + AnyPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + SupportsKeysAndGetItem, + SupportsLessThan, + SupportsLessThanT, + SupportsWrite, +) +from ast import AST, mod +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +from types import CodeType, TracebackType +from typing import ( + IO, + AbstractSet, + Any, + BinaryIO, + ByteString, + Callable, + Container, + Dict, + FrozenSet, + Generic, + ItemsView, + Iterable, + Iterator, + KeysView, + List, + Mapping, + MutableMapping, + MutableSequence, + MutableSet, + NoReturn, + Optional, + Protocol, + Reversible, + Sequence, + Set, + Sized, + SupportsAbs, + SupportsBytes, + SupportsComplex, + SupportsFloat, + SupportsInt, + SupportsRound, + Tuple, + Type, + TypeVar, + Union, + ValuesView, + overload, + runtime_checkable, +) +from typing_extensions import Literal + +if sys.version_info >= (3, 9): + from types import GenericAlias + +class _SupportsIndex(Protocol): + def __index__(self) -> int: ... + +class _SupportsTrunc(Protocol): + def __trunc__(self) -> int: ... + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_S = TypeVar("_S") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_TT = TypeVar("_TT", bound="type") +_TBE = TypeVar("_TBE", bound="BaseException") + +class object: + __doc__: Optional[str] + __dict__: Dict[str, Any] + __slots__: Union[str, Iterable[str]] + __module__: str + __annotations__: Dict[str, Any] + @property + def __class__(self: _T) -> Type[_T]: ... + @__class__.setter + def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __init__(self) -> None: ... + def __new__(cls) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __eq__(self, o: object) -> bool: ... + def __ne__(self, o: object) -> bool: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __getattribute__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __sizeof__(self) -> int: ... + def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... + def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]: ... + def __dir__(self) -> Iterable[str]: ... + def __init_subclass__(cls) -> None: ... + +class staticmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + __isabstractmethod__: bool + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class classmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + __isabstractmethod__: bool + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class type(object): + __base__: type + __bases__: Tuple[type, ...] + __basicsize__: int + __dict__: Dict[str, Any] + __dictoffset__: int + __flags__: int + __itemsize__: int + __module__: str + __mro__: Tuple[type, ...] + __name__: str + __qualname__: str + __text_signature__: Optional[str] + __weakrefoffset__: int + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + @overload + def __new__(cls, o: object) -> type: ... + @overload + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _TT) -> List[_TT]: ... + # Note: the documentation doesnt specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> List[type]: ... + def __instancecheck__(self, instance: Any) -> bool: ... + def __subclasscheck__(self, subclass: type) -> bool: ... + @classmethod + def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... + +class super(object): + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + @overload + def __init__(self) -> None: ... + +class int: + @overload + def __new__(cls: Type[_T], x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc] = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], x: Union[str, bytes, bytearray], base: int) -> _T: ... + @overload + def __init__(self, x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc] = ...) -> _T: ... + @overload + def __init__(self, x: Union[str, bytes, bytearray], base: int) -> _T: ... + if sys.version_info >= (3, 8): + def as_integer_ratio(self) -> Tuple[int, Literal[1]]: ... + @property + def real(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def conjugate(self) -> int: ... + def bit_length(self) -> int: ... + def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... + @classmethod + def from_bytes( + cls, bytes: Union[Iterable[int], SupportsBytes], byteorder: str, *, signed: bool = ... + ) -> int: ... # TODO buffer object argument + def __add__(self, x: int) -> int: ... + def __sub__(self, x: int) -> int: ... + def __mul__(self, x: int) -> int: ... + def __floordiv__(self, x: int) -> int: ... + def __truediv__(self, x: int) -> float: ... + def __mod__(self, x: int) -> int: ... + def __divmod__(self, x: int) -> Tuple[int, int]: ... + def __radd__(self, x: int) -> int: ... + def __rsub__(self, x: int) -> int: ... + def __rmul__(self, x: int) -> int: ... + def __rfloordiv__(self, x: int) -> int: ... + def __rtruediv__(self, x: int) -> float: ... + def __rmod__(self, x: int) -> int: ... + def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + @overload + def __pow__(self, __x: Literal[2], __modulo: Optional[int] = ...) -> int: ... + @overload + def __pow__(self, __x: int, __modulo: Optional[int] = ...) -> Any: ... # Return type can be int or float, depending on x. + def __rpow__(self, x: int, mod: Optional[int] = ...) -> Any: ... + def __and__(self, n: int) -> int: ... + def __or__(self, n: int) -> int: ... + def __xor__(self, n: int) -> int: ... + def __lshift__(self, n: int) -> int: ... + def __rshift__(self, n: int) -> int: ... + def __rand__(self, n: int) -> int: ... + def __ror__(self, n: int) -> int: ... + def __rxor__(self, n: int) -> int: ... + def __rlshift__(self, n: int) -> int: ... + def __rrshift__(self, n: int) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + def __trunc__(self) -> int: ... + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + def __round__(self, ndigits: Optional[int] = ...) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: int) -> bool: ... + def __le__(self, x: int) -> bool: ... + def __gt__(self, x: int) -> bool: ... + def __ge__(self, x: int) -> bool: ... + def __str__(self) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + def __index__(self) -> int: ... + +class float: + def __new__(cls: Type[_T], x: Union[SupportsFloat, _SupportsIndex, str, bytes, bytearray] = ...) -> _T: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, __s: str) -> float: ... + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + def __add__(self, x: float) -> float: ... + def __sub__(self, x: float) -> float: ... + def __mul__(self, x: float) -> float: ... + def __floordiv__(self, x: float) -> float: ... + def __truediv__(self, x: float) -> float: ... + def __mod__(self, x: float) -> float: ... + def __divmod__(self, x: float) -> Tuple[float, float]: ... + def __pow__( + self, x: float, mod: None = ... + ) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __radd__(self, x: float) -> float: ... + def __rsub__(self, x: float) -> float: ... + def __rmul__(self, x: float) -> float: ... + def __rfloordiv__(self, x: float) -> float: ... + def __rtruediv__(self, x: float) -> float: ... + def __rmod__(self, x: float) -> float: ... + def __rdivmod__(self, x: float) -> Tuple[float, float]: ... + def __rpow__(self, x: float, mod: None = ...) -> float: ... + def __getnewargs__(self) -> Tuple[float]: ... + def __trunc__(self) -> int: ... + if sys.version_info >= (3, 9): + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + @overload + def __round__(self, ndigits: None = ...) -> int: ... + @overload + def __round__(self, ndigits: int) -> float: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: float) -> bool: ... + def __le__(self, x: float) -> bool: ... + def __gt__(self, x: float) -> bool: ... + def __ge__(self, x: float) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + def __str__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + +class complex: + @overload + def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], real: Union[str, SupportsComplex, _SupportsIndex]) -> _T: ... + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> complex: ... + def __add__(self, x: complex) -> complex: ... + def __sub__(self, x: complex) -> complex: ... + def __mul__(self, x: complex) -> complex: ... + def __pow__(self, x: complex, mod: None = ...) -> complex: ... + def __truediv__(self, x: complex) -> complex: ... + def __radd__(self, x: complex) -> complex: ... + def __rsub__(self, x: complex) -> complex: ... + def __rmul__(self, x: complex) -> complex: ... + def __rpow__(self, x: complex, mod: None = ...) -> complex: ... + def __rtruediv__(self, x: complex) -> complex: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + def __str__(self) -> str: ... + def __complex__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + +class _FormatMapMapping(Protocol): + def __getitem__(self, __key: str) -> Any: ... + +class str(Sequence[str]): + @overload + def __new__(cls: Type[_T], o: object = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... + @overload + def __init__(self, o: object = ...) -> _T: ... + @overload + def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... + def capitalize(self) -> str: ... + def casefold(self) -> str: ... + def center(self, __width: int, __fillchar: str = ...) -> str: ... + def count(self, x: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... + def endswith(self, suffix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> str: ... + def format_map(self, map: _FormatMapMapping) -> str: ... + def index(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable: Iterable[str]) -> str: ... + def ljust(self, __width: int, __fillchar: str = ...) -> str: ... + def lower(self) -> str: ... + def lstrip(self, __chars: Optional[str] = ...) -> str: ... + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def replace(self, __old: str, __new: str, __count: int = ...) -> str: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: str) -> str: ... + def removesuffix(self, __suffix: str) -> str: ... + def rfind(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: str = ...) -> str: ... + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rstrip(self, __chars: Optional[str] = ...) -> str: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + def startswith(self, prefix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... + def strip(self, __chars: Optional[str] = ...) -> str: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... + def translate(self, __table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... + def upper(self) -> str: ... + def zfill(self, __width: int) -> str: ... + @staticmethod + @overload + def maketrans(__x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(__x: str, __y: str, __z: Optional[str] = ...) -> Dict[int, Union[int, None]]: ... + def __add__(self, s: str) -> str: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: str) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ge__(self, x: str) -> bool: ... + def __getitem__(self, i: Union[int, slice]) -> str: ... + def __gt__(self, x: str) -> bool: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __le__(self, x: str) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, x: str) -> bool: ... + def __mod__(self, x: Any) -> str: ... + def __mul__(self, n: int) -> str: ... + def __ne__(self, x: object) -> bool: ... + def __repr__(self) -> str: ... + def __rmul__(self, n: int) -> str: ... + def __str__(self) -> str: ... + def __getnewargs__(self) -> Tuple[str]: ... + +class bytes(ByteString): + @overload + def __new__(cls: Type[_T], ints: Iterable[int]) -> _T: ... + @overload + def __new__(cls: Type[_T], string: str, encoding: str, errors: str = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], length: int) -> _T: ... + @overload + def __new__(cls: Type[_T]) -> _T: ... + @overload + def __new__(cls: Type[_T], o: SupportsBytes) -> _T: ... + def capitalize(self) -> bytes: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytes: ... + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 8): + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + else: + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytes: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def lower(self) -> bytes: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def partition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytes: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: bytes) -> bytes: ... + def removesuffix(self, __suffix: bytes) -> bytes: ... + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def splitlines(self, keepends: bool = ...) -> List[bytes]: ... + def startswith( + self, prefix: Union[bytes, Tuple[bytes, ...]], start: Optional[int] = ..., end: Optional[int] = ... + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def swapcase(self) -> bytes: ... + def title(self) -> bytes: ... + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytes: ... + def upper(self) -> bytes: ... + def zfill(self, __width: int) -> bytes: ... + @classmethod + def fromhex(cls, __s: str) -> bytes: ... + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytes: ... + def __add__(self, s: bytes) -> bytes: ... + def __mul__(self, n: int) -> bytes: ... + def __rmul__(self, n: int) -> bytes: ... + def __mod__(self, value: Any) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + def __getnewargs__(self) -> Tuple[bytes]: ... + +class bytearray(MutableSequence[int], ByteString): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str, encoding: str, errors: str = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def count(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def copy(self) -> bytearray: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + def find(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def hex(self) -> str: ... + def index(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def insert(self, __index: int, __item: int) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: bytes) -> bytearray: ... + def removesuffix(self, __suffix: bytes) -> bytearray: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... + def rfind(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... + def startswith( + self, __prefix: Union[bytes, Tuple[bytes, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytearray: ... + def upper(self) -> bytearray: ... + def zfill(self, __width: int) -> bytearray: ... + @classmethod + def fromhex(cls, __string: str) -> bytearray: ... + @classmethod + def maketrans(cls, __frm: bytes, __to: bytes) -> bytes: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytearray: ... + @overload + def __setitem__(self, i: int, x: int) -> None: ... + @overload + def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __add__(self, s: bytes) -> bytearray: ... + def __iadd__(self, s: Iterable[int]) -> bytearray: ... + def __mul__(self, n: int) -> bytearray: ... + def __rmul__(self, n: int) -> bytearray: ... + def __imul__(self, n: int) -> bytearray: ... + def __mod__(self, value: Any) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + +class memoryview(Sized, Container[int]): + format: str + itemsize: int + shape: Optional[Tuple[int, ...]] + strides: Optional[Tuple[int, ...]] + suboffsets: Optional[Tuple[int, ...]] + readonly: bool + ndim: int + + obj: Union[bytes, bytearray] + c_contiguous: bool + f_contiguous: bool + contiguous: bool + nbytes: int + def __init__(self, obj: ReadableBuffer) -> None: ... + def __enter__(self) -> memoryview: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + def cast(self, format: str, shape: Union[List[int], Tuple[int]] = ...) -> memoryview: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> memoryview: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + def __len__(self) -> int: ... + @overload + def __setitem__(self, s: slice, o: memoryview) -> None: ... + @overload + def __setitem__(self, i: int, o: bytes) -> None: ... + @overload + def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ... + if sys.version_info >= (3, 8): + def tobytes(self, order: Optional[Literal["C", "F", "A"]] = ...) -> bytes: ... + else: + def tobytes(self) -> bytes: ... + def tolist(self) -> List[int]: ... + if sys.version_info >= (3, 8): + def toreadonly(self) -> memoryview: ... + def release(self) -> None: ... + def hex(self) -> str: ... + +class bool(int): + def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __init__(self, o: object = ...): ... + @overload + def __and__(self, x: bool) -> bool: ... + @overload + def __and__(self, x: int) -> int: ... + @overload + def __or__(self, x: bool) -> bool: ... + @overload + def __or__(self, x: int) -> int: ... + @overload + def __xor__(self, x: bool) -> bool: ... + @overload + def __xor__(self, x: int) -> int: ... + @overload + def __rand__(self, x: bool) -> bool: ... + @overload + def __rand__(self, x: int) -> int: ... + @overload + def __ror__(self, x: bool) -> bool: ... + @overload + def __ror__(self, x: int) -> int: ... + @overload + def __rxor__(self, x: bool) -> bool: ... + @overload + def __rxor__(self, x: int) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + +class slice(object): + start: Any + step: Any + stop: Any + @overload + def __init__(self, stop: Any) -> None: ... + @overload + def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... + __hash__: None # type: ignore + def indices(self, len: int) -> Tuple[int, int, int]: ... + +class tuple(Sequence[_T_co], Generic[_T_co]): + def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __init__(self, iterable: Iterable[_T_co] = ...): ... + def __len__(self) -> int: ... + def __contains__(self, x: object) -> bool: ... + @overload + def __getitem__(self, x: int) -> _T_co: ... + @overload + def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + @overload + def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + @overload + def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... + def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def count(self, __value: Any) -> int: ... + def index(self, __value: Any, __start: int = ..., __stop: int = ...) -> int: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class list(MutableSequence[_T], Generic[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + def clear(self) -> None: ... + def copy(self) -> List[_T]: ... + def append(self, __object: _T) -> None: ... + def extend(self, __iterable: Iterable[_T]) -> None: ... + def pop(self, __index: int = ...) -> _T: ... + def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... + def count(self, __value: _T) -> int: ... + def insert(self, __index: int, __object: _T) -> None: ... + def remove(self, __value: _T) -> None: ... + def reverse(self) -> None: ... + @overload + def sort(self: List[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsLessThan], reverse: bool = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> List[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __add__(self, x: List[_T]) -> List[_T]: ... + def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... + def __mul__(self, n: int) -> List[_T]: ... + def __rmul__(self, n: int) -> List[_T]: ... + def __imul__(self: _S, n: int) -> _S: ... + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, x: List[_T]) -> bool: ... + def __ge__(self, x: List[_T]) -> bool: ... + def __lt__(self, x: List[_T]) -> bool: ... + def __le__(self, x: List[_T]) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # NOTE: Keyword arguments are special. If they are used, _KT must include + # str, but we have no way of enforcing it here. + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def clear(self) -> None: ... + def copy(self) -> Dict[_KT, _VT]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, __key: _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: ... + def keys(self) -> KeysView[_KT]: ... + def values(self) -> ValuesView[_VT]: ... + def items(self) -> ItemsView[_KT, _VT]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... + def __len__(self) -> int: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + if sys.version_info >= (3, 8): + def __reversed__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __or__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... + def __ior__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... + +class set(MutableSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def add(self, element: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Set[_T]: ... + def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def issubset(self, s: Iterable[Any]) -> bool: ... + def issuperset(self, s: Iterable[Any]) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __sub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... + def __isub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + __hash__: None # type: ignore + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class frozenset(AbstractSet[_T_co], Generic[_T_co]): + def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... + def copy(self) -> FrozenSet[_T_co]: ... + def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... + def issubset(self, s: Iterable[object]) -> bool: ... + def issuperset(self, s: Iterable[object]) -> bool: ... + def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): + def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[int, _T]]: ... + def __next__(self) -> Tuple[int, _T]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class range(Sequence[int]): + start: int + stop: int + step: int + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def count(self, value: int) -> int: ... + def index(self, value: int) -> int: ... # type: ignore + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> range: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[int]: ... + +class property(object): + def __init__( + self, + fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ..., + ) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> property: ... + def setter(self, fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, fdel: Callable[[Any], None]) -> property: ... + def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... + def __set__(self, obj: Any, value: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + def fget(self) -> Any: ... + def fset(self, value: Any) -> None: ... + def fdel(self) -> None: ... + +class _NotImplementedType(Any): # type: ignore + # A little weird, but typing the __call__ as NotImplemented makes the error message + # for NotImplemented() much better + pass + +NotImplemented: _NotImplementedType + +def abs(__x: SupportsAbs[_T]) -> _T: ... +def all(__iterable: Iterable[object]) -> bool: ... +def any(__iterable: Iterable[object]) -> bool: ... +def ascii(__obj: object) -> str: ... +def bin(__number: Union[int, _SupportsIndex]) -> str: ... + +if sys.version_info >= (3, 7): + def breakpoint(*args: Any, **kws: Any) -> None: ... + +def callable(__obj: object) -> bool: ... +def chr(__i: int) -> str: ... + +# This class is to be exported as PathLike from os, +# but we define it here as _PathLike to avoid import cycle issues. +# See https://github.com/python/typeshed/pull/991#issuecomment-288160993 +_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) +@runtime_checkable +class _PathLike(Protocol[_AnyStr_co]): + def __fspath__(self) -> _AnyStr_co: ... + +if sys.version_info >= (3, 8): + def compile( + source: Union[str, bytes, mod, AST], + filename: Union[str, bytes, _PathLike[Any]], + mode: str, + flags: int = ..., + dont_inherit: int = ..., + optimize: int = ..., + *, + _feature_version: int = ..., + ) -> Any: ... + +else: + def compile( + source: Union[str, bytes, mod, AST], + filename: Union[str, bytes, _PathLike[Any]], + mode: str, + flags: int = ..., + dont_inherit: int = ..., + optimize: int = ..., + ) -> Any: ... + +def copyright() -> None: ... +def credits() -> None: ... +def delattr(__obj: Any, __name: str) -> None: ... +def dir(__o: object = ...) -> List[str]: ... + +_N2 = TypeVar("_N2", int, float) + +def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def eval( + __source: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ... +) -> Any: ... +def exec( + __source: Union[str, bytes, CodeType], + __globals: Optional[Dict[str, Any]] = ..., + __locals: Optional[Mapping[str, Any]] = ..., +) -> Any: ... +def exit(code: object = ...) -> NoReturn: ... +@overload +def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... +@overload +def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... +def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode +def getattr(__o: Any, name: str, __default: Any = ...) -> Any: ... +def globals() -> Dict[str, Any]: ... +def hasattr(__obj: Any, __name: str) -> bool: ... +def hash(__obj: object) -> int: ... +def help(*args: Any, **kwds: Any) -> None: ... +def hex(__number: Union[int, _SupportsIndex]) -> str: ... +def id(__obj: object) -> int: ... +def input(__prompt: Any = ...) -> str: ... +@overload +def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +def iter(__function: Callable[[], Optional[_T]], __sentinel: None) -> Iterator[_T]: ... +@overload +def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... +def isinstance(__obj: object, __class_or_tuple: Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]) -> bool: ... +def issubclass(__cls: type, __class_or_tuple: Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]) -> bool: ... +def len(__obj: Sized) -> int: ... +def license() -> None: ... +def locals() -> Dict[str, Any]: ... +@overload +def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Iterator[_S]: ... +@overload +def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] +) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], +) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], +) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[_S]: ... +@overload +def max( + __arg1: SupportsLessThanT, __arg2: SupportsLessThanT, *_args: SupportsLessThanT, key: None = ... +) -> SupportsLessThanT: ... +@overload +def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def max(__iterable: Iterable[SupportsLessThanT], *, key: None = ...) -> SupportsLessThanT: ... +@overload +def max(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def max(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., default: _T) -> Union[SupportsLessThanT, _T]: ... +@overload +def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsLessThanT], default: _T2) -> Union[_T1, _T2]: ... +@overload +def min( + __arg1: SupportsLessThanT, __arg2: SupportsLessThanT, *_args: SupportsLessThanT, key: None = ... +) -> SupportsLessThanT: ... +@overload +def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def min(__iterable: Iterable[SupportsLessThanT], *, key: None = ...) -> SupportsLessThanT: ... +@overload +def min(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def min(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., default: _T) -> Union[SupportsLessThanT, _T]: ... +@overload +def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsLessThanT], default: _T2) -> Union[_T1, _T2]: ... +@overload +def next(__i: Iterator[_T]) -> _T: ... +@overload +def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... +def oct(__number: Union[int, _SupportsIndex]) -> str: ... + +_OpenFile = Union[AnyPath, int] +_Opener = Callable[[str, int], int] + +# Text mode: always returns a TextIOWrapper +@overload +def open( + file: _OpenFile, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> TextIOWrapper: ... + +# Unbuffered binary mode: returns a FileIO +@overload +def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> FileIO: ... + +# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter +@overload +def open( + file: _OpenFile, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedRandom: ... +@overload +def open( + file: _OpenFile, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedWriter: ... +@overload +def open( + file: _OpenFile, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedReader: ... + +# Buffering cannot be determined: fall back to BinaryIO +@overload +def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: int, + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BinaryIO: ... + +# Fallback if mode is not specified +@overload +def open( + file: _OpenFile, + mode: str, + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> IO[Any]: ... +def ord(__c: Union[str, bytes]) -> int: ... +def print( + *values: object, + sep: Optional[str] = ..., + end: Optional[str] = ..., + file: Optional[SupportsWrite[str]] = ..., + flush: bool = ..., +) -> None: ... + +_E = TypeVar("_E", contravariant=True) +_M = TypeVar("_M", contravariant=True) + +class _SupportsPow2(Protocol[_E, _T_co]): + def __pow__(self, __other: _E) -> _T_co: ... + +class _SupportsPow3(Protocol[_E, _M, _T_co]): + def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... + +if sys.version_info >= (3, 8): + @overload + def pow(base: int, exp: int, mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative + @overload + def pow(base: int, exp: int, mod: int) -> int: ... + @overload + def pow(base: float, exp: float, mod: None = ...) -> float: ... + @overload + def pow(base: _SupportsPow2[_E, _T_co], exp: _E) -> _T_co: ... + @overload + def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... + +else: + @overload + def pow( + __base: int, __exp: int, __mod: None = ... + ) -> Any: ... # returns int or float depending on whether exp is non-negative + @overload + def pow(__base: int, __exp: int, __mod: int) -> int: ... + @overload + def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... + @overload + def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... + @overload + def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... + +def quit(code: object = ...) -> NoReturn: ... +@overload +def reversed(__sequence: Sequence[_T]) -> Iterator[_T]: ... +@overload +def reversed(__sequence: Reversible[_T]) -> Iterator[_T]: ... +def repr(__obj: object) -> str: ... +@overload +def round(number: float) -> int: ... +@overload +def round(number: float, ndigits: None) -> int: ... +@overload +def round(number: float, ndigits: int) -> float: ... +@overload +def round(number: SupportsRound[_T]) -> int: ... +@overload +def round(number: SupportsRound[_T], ndigits: None) -> int: ... +@overload +def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +def setattr(__obj: Any, __name: str, __value: Any) -> None: ... +@overload +def sorted(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> List[SupportsLessThanT]: ... +@overload +def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThan], reverse: bool = ...) -> List[_T]: ... + +if sys.version_info >= (3, 8): + @overload + def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... + @overload + def sum(__iterable: Iterable[_T], start: _S) -> Union[_T, _S]: ... + +else: + @overload + def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... + @overload + def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... + +def vars(__object: Any = ...) -> Dict[str, Any]: ... +@overload +def zip(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def zip( + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[Tuple[Any, ...]]: ... +def __import__( + name: str, + globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ..., +) -> Any: ... + +# Actually the type of Ellipsis is , but since it's +# not exposed anywhere under that name, we make it private here. +class ellipsis: ... + +Ellipsis: ellipsis + +class BaseException(object): + args: Tuple[Any, ...] + __cause__: Optional[BaseException] + __context__: Optional[BaseException] + __suppress_context__: bool + __traceback__: Optional[TracebackType] + def __init__(self, *args: object) -> None: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def with_traceback(self: _TBE, tb: Optional[TracebackType]) -> _TBE: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... + +class SystemExit(BaseException): + code: int + +class Exception(BaseException): ... + +class StopIteration(Exception): + value: Any + +_StandardError = Exception + +class OSError(Exception): + errno: int + strerror: str + # filename, filename2 are actually Union[str, bytes, None] + filename: Any + filename2: Any + +EnvironmentError = OSError +IOError = OSError + +class ArithmeticError(_StandardError): ... +class AssertionError(_StandardError): ... +class AttributeError(_StandardError): ... +class BufferError(_StandardError): ... +class EOFError(_StandardError): ... + +class ImportError(_StandardError): + def __init__(self, *args: object, name: Optional[str] = ..., path: Optional[str] = ...) -> None: ... + name: Optional[str] + path: Optional[str] + +class LookupError(_StandardError): ... +class MemoryError(_StandardError): ... +class NameError(_StandardError): ... +class ReferenceError(_StandardError): ... +class RuntimeError(_StandardError): ... + +class StopAsyncIteration(Exception): + value: Any + +class SyntaxError(_StandardError): + msg: str + lineno: Optional[int] + offset: Optional[int] + text: Optional[str] + filename: Optional[str] + +class SystemError(_StandardError): ... +class TypeError(_StandardError): ... +class ValueError(_StandardError): ... +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... +class ModuleNotFoundError(ImportError): ... +class IndexError(LookupError): ... +class KeyError(LookupError): ... +class UnboundLocalError(NameError): ... + +class WindowsError(OSError): + winerror: int + +class BlockingIOError(OSError): + characters_written: int + +class ChildProcessError(OSError): ... +class ConnectionError(OSError): ... +class BrokenPipeError(ConnectionError): ... +class ConnectionAbortedError(ConnectionError): ... +class ConnectionRefusedError(ConnectionError): ... +class ConnectionResetError(ConnectionError): ... +class FileExistsError(OSError): ... +class FileNotFoundError(OSError): ... +class InterruptedError(OSError): ... +class IsADirectoryError(OSError): ... +class NotADirectoryError(OSError): ... +class PermissionError(OSError): ... +class ProcessLookupError(OSError): ... +class TimeoutError(OSError): ... +class NotImplementedError(RuntimeError): ... +class RecursionError(RuntimeError): ... +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... +class UnicodeError(ValueError): ... + +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... + +class UnicodeEncodeError(UnicodeError): + encoding: str + object: str + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: str, __start: int, __end: int, __reason: str) -> None: ... + +class UnicodeTranslateError(UnicodeError): ... +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... +class ResourceWarning(Warning): ... diff --git a/shared/package-files/3a/3a723fdf88c0018dfadd19757142a643b01b785c6df17a50bbe21463663ab590/calltip.py b/shared/package-files/3a/3a723fdf88c0018dfadd19757142a643b01b785c6df17a50bbe21463663ab590/calltip.py new file mode 100644 index 0000000000000000000000000000000000000000..40bc5a0ad798fe3eeef6ff38f79f74747b45a21f --- /dev/null +++ b/shared/package-files/3a/3a723fdf88c0018dfadd19757142a643b01b785c6df17a50bbe21463663ab590/calltip.py @@ -0,0 +1,205 @@ +"""Pop up a reminder of how to call a function. + +Call Tips are floating windows which display function, class, and method +parameter and docstring information when you type an opening parenthesis, and +which disappear when you type a closing parenthesis. +""" +import __main__ +import inspect +import re +import sys +import textwrap +import types + +from idlelib import calltip_w +from idlelib.hyperparser import HyperParser + + +class Calltip: + + def __init__(self, editwin=None): + if editwin is None: # subprocess and test + self.editwin = None + else: + self.editwin = editwin + self.text = editwin.text + self.active_calltip = None + self._calltip_window = self._make_tk_calltip_window + + def close(self): + self._calltip_window = None + + def _make_tk_calltip_window(self): + # See __init__ for usage + return calltip_w.CalltipWindow(self.text) + + def remove_calltip_window(self, event=None): + if self.active_calltip: + self.active_calltip.hidetip() + self.active_calltip = None + + def force_open_calltip_event(self, event): + "The user selected the menu entry or hotkey, open the tip." + self.open_calltip(True) + return "break" + + def try_open_calltip_event(self, event): + """Happens when it would be nice to open a calltip, but not really + necessary, for example after an opening bracket, so function calls + won't be made. + """ + self.open_calltip(False) + + def refresh_calltip_event(self, event): + if self.active_calltip and self.active_calltip.tipwindow: + self.open_calltip(False) + + def open_calltip(self, evalfuncs): + """Maybe close an existing calltip and maybe open a new calltip. + + Called from (force_open|try_open|refresh)_calltip_event functions. + """ + hp = HyperParser(self.editwin, "insert") + sur_paren = hp.get_surrounding_brackets('(') + + # If not inside parentheses, no calltip. + if not sur_paren: + self.remove_calltip_window() + return + + # If a calltip is shown for the current parentheses, do + # nothing. + if self.active_calltip: + opener_line, opener_col = map(int, sur_paren[0].split('.')) + if ( + (opener_line, opener_col) == + (self.active_calltip.parenline, self.active_calltip.parencol) + ): + return + + hp.set_index(sur_paren[0]) + try: + expression = hp.get_expression() + except ValueError: + expression = None + if not expression: + # No expression before the opening parenthesis, e.g. + # because it's in a string or the opener for a tuple: + # Do nothing. + return + + # At this point, the current index is after an opening + # parenthesis, in a section of code, preceded by a valid + # expression. If there is a calltip shown, it's not for the + # same index and should be closed. + self.remove_calltip_window() + + # Simple, fast heuristic: If the preceding expression includes + # an opening parenthesis, it likely includes a function call. + if not evalfuncs and (expression.find('(') != -1): + return + + argspec = self.fetch_tip(expression) + if not argspec: + return + self.active_calltip = self._calltip_window() + self.active_calltip.showtip(argspec, sur_paren[0], sur_paren[1]) + + def fetch_tip(self, expression): + """Return the argument list and docstring of a function or class. + + If there is a Python subprocess, get the calltip there. Otherwise, + either this fetch_tip() is running in the subprocess or it was + called in an IDLE running without the subprocess. + + The subprocess environment is that of the most recently run script. If + two unrelated modules are being edited some calltips in the current + module may be inoperative if the module was not the last to run. + + To find methods, fetch_tip must be fed a fully qualified name. + + """ + try: + rpcclt = self.editwin.flist.pyshell.interp.rpcclt + except AttributeError: + rpcclt = None + if rpcclt: + return rpcclt.remotecall("exec", "get_the_calltip", + (expression,), {}) + else: + return get_argspec(get_entity(expression)) + + +def get_entity(expression): + """Return the object corresponding to expression evaluated + in a namespace spanning sys.modules and __main.dict__. + """ + if expression: + namespace = {**sys.modules, **__main__.__dict__} + try: + return eval(expression, namespace) # Only protect user code. + except BaseException: + # An uncaught exception closes idle, and eval can raise any + # exception, especially if user classes are involved. + return None + +# The following are used in get_argspec and some in tests +_MAX_COLS = 85 +_MAX_LINES = 5 # enough for bytes +_INDENT = ' '*4 # for wrapped signatures +_first_param = re.compile(r'(?<=\()\w*\,?\s*') +_default_callable_argspec = "See source or doc" +_invalid_method = "invalid method signature" + +def get_argspec(ob): + '''Return a string describing the signature of a callable object, or ''. + + For Python-coded functions and methods, the first line is introspected. + Delete 'self' parameter for classes (.__init__) and bound methods. + The next lines are the first lines of the doc string up to the first + empty line or _MAX_LINES. For builtins, this typically includes + the arguments in addition to the return value. + ''' + # Determine function object fob to inspect. + try: + ob_call = ob.__call__ + except BaseException: # Buggy user object could raise anything. + return '' # No popup for non-callables. + # For Get_argspecTest.test_buggy_getattr_class, CallA() & CallB(). + fob = ob_call if isinstance(ob_call, types.MethodType) else ob + + # Initialize argspec and wrap it to get lines. + try: + argspec = str(inspect.signature(fob)) + except Exception as err: + msg = str(err) + if msg.startswith(_invalid_method): + return _invalid_method + else: + argspec = '' + + if isinstance(fob, type) and argspec == '()': + # If fob has no argument, use default callable argspec. + argspec = _default_callable_argspec + + lines = (textwrap.wrap(argspec, _MAX_COLS, subsequent_indent=_INDENT) + if len(argspec) > _MAX_COLS else [argspec] if argspec else []) + + # Augment lines from docstring, if any, and join to get argspec. + doc = inspect.getdoc(ob) + if doc: + for line in doc.split('\n', _MAX_LINES)[:_MAX_LINES]: + line = line.strip() + if not line: + break + if len(line) > _MAX_COLS: + line = line[: _MAX_COLS - 3] + '...' + lines.append(line) + argspec = '\n'.join(lines) + + return argspec or _default_callable_argspec + + +if __name__ == '__main__': + from unittest import main + main('idlelib.idle_test.test_calltip', verbosity=2) diff --git a/shared/package-files/3a/3a726637893bb72a7d1b256d5ae930e02b81bc3203be95827414383f118fa894/sftp_handle.pyi b/shared/package-files/3a/3a726637893bb72a7d1b256d5ae930e02b81bc3203be95827414383f118fa894/sftp_handle.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ed08915323f7a8d20ff230382249ebaff1fadd48 --- /dev/null +++ b/shared/package-files/3a/3a726637893bb72a7d1b256d5ae930e02b81bc3203be95827414383f118fa894/sftp_handle.pyi @@ -0,0 +1,13 @@ +from typing import Union + +from paramiko.sftp_attr import SFTPAttributes +from paramiko.sftp_server import SFTPServer +from paramiko.util import ClosingContextManager + +class SFTPHandle(ClosingContextManager): + def __init__(self, flags: int = ...) -> None: ... + def close(self) -> None: ... + def read(self, offset: int, length: int) -> Union[bytes, int]: ... + def write(self, offset: int, data: bytes) -> int: ... + def stat(self) -> Union[int, SFTPAttributes]: ... + def chattr(self, attr: SFTPAttributes) -> int: ... diff --git a/shared/package-files/3a/3a77df2e4faa3d6753ff417608fe89fdf9f9b2d5616187403c0ee2229675041b/test_formula.py b/shared/package-files/3a/3a77df2e4faa3d6753ff417608fe89fdf9f9b2d5616187403c0ee2229675041b/test_formula.py new file mode 100644 index 0000000000000000000000000000000000000000..ba99ac9243f5b97b15119e7c3b81b3623ca0ad1a --- /dev/null +++ b/shared/package-files/3a/3a77df2e4faa3d6753ff417608fe89fdf9f9b2d5616187403c0ee2229675041b/test_formula.py @@ -0,0 +1,309 @@ +from statsmodels.compat.pandas import assert_series_equal + +import contextlib +from io import StringIO +import warnings + +import numpy as np +import numpy.testing as npt +import pandas as pd +import pytest + +from statsmodels.datasets import cpunish +from statsmodels.datasets.longley import load, load_pandas +import statsmodels.formula +from statsmodels.formula._manager import FormulaManager +from statsmodels.formula.api import ols +from statsmodels.formula.formulatools import make_hypotheses_matrices +from statsmodels.tools import add_constant +from statsmodels.tools.testing import assert_equal + +try: + import patsy + + PATSY_MISSING = False +except ImportError: + PATSY_MISSING = True + + +longley_formula = "TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR" + + +class CheckFormulaOLS: + @classmethod + def setup_class(cls): + cls.data = load() + + def test_endog_names(self): + assert self.model.endog_names == "TOTEMP" + + def test_exog_names(self): + assert self.model.exog_names == [ + "Intercept", + "GNPDEFL", + "GNP", + "UNEMP", + "ARMED", + "POP", + "YEAR", + ] + + def test_design(self): + npt.assert_equal(self.model.exog, add_constant(self.data.exog, prepend=True)) + + def test_endog(self): + npt.assert_equal(self.model.endog, self.data.endog) + + @pytest.mark.thread_unsafe("fit method mutates the model object") + @pytest.mark.smoke + def test_summary(self): + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "kurtosistest only valid for n>=20") + self.model.fit().summary() + + +class TestFormulaPandas(CheckFormulaOLS): + @classmethod + def setup_class(cls): + data = load_pandas().data + cls.model = ols(longley_formula, data) + super().setup_class() + + +class TestFormulaDict(CheckFormulaOLS): + @classmethod + def setup_class(cls): + data = {k: v.tolist() for k, v in load_pandas().data.items()} + with pytest.warns(DeprecationWarning, match="Using"): + cls.model = ols(longley_formula, data) + super().setup_class() + + +def test_tests(): + formula = "TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR" + dta = load_pandas().data + results = ols(formula, dta).fit() + test_formula = "(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)" + lc = make_hypotheses_matrices(results, test_formula) + r = lc.constraint_matrix + q = lc.constraint_values + npt.assert_almost_equal( + r, + [[0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1.0 / 1829]], + 8, + ) + npt.assert_array_equal(q, [[0], [2], [1]]) + test_formula = "(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)" + lc = make_hypotheses_matrices(results, test_formula) + r = lc.constraint_matrix + q = lc.constraint_values + npt.assert_almost_equal( + r, + [[0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1.0 / 1829]], + 8, + ) + npt.assert_array_equal(q, [[0], [2], [1]]) + + +def test_formula_labels(): + # make sure labels pass through patsy as expected + # data(Duncan) from car in R + dta = StringIO( + '"type","income","education","prestige"\n' + '"accountant","prof",62,86,82\n' + '"pilot","prof",72,76,83\n' + '"architect","prof",75,92,90\n' + '"author","prof",55,90,76\n' + '"chemist","prof",64,86,90\n' + '"minister","prof",21,84,87\n' + '"professor","prof",64,93,93\n' + '"dentist","prof",80,100,90\n' + '"reporter","wc",67,87,52\n' + '"engineer","prof",72,86,88\n' + '"undertaker","prof",42,74,57\n' + '"lawyer","prof",76,98,89\n' + '"physician","prof",76,97,97\n' + '"welfare.worker","prof",41,84,59\n' + '"teacher","prof",48,91,73\n' + '"conductor","wc",76,34,38\n' + '"contractor","prof",53,45,76\n' + '"factory.owner","prof",60,56,81\n' + '"store.manager","prof",42,44,45\n' + '"banker","prof",78,82,92\n' + '"bookkeeper","wc",29,72,39\n' + '"mail.carrier","wc",48,55,34\n' + '"insurance.agent","wc",55,71,41\n' + '"store.clerk","wc",29,50,16\n' + '"carpenter","bc",21,23,33\n' + '"electrician","bc",47,39,53\n' + '"RR.engineer","bc",81,28,67\n' + '"machinist","bc",36,32,57\n' + '"auto.repairman","bc",22,22,26\n' + '"plumber","bc",44,25,29\n' + '"gas.stn.attendant","bc",15,29,10\n' + '"coal.miner","bc",7,7,15\n' + '"streetcar.motorman","bc",42,26,19\n' + '"taxi.driver","bc",9,19,10\n' + '"truck.driver","bc",21,15,13\n' + '"machine.operator","bc",21,20,24\n' + '"barber","bc",16,26,20\n' + '"bartender","bc",16,28,7\n' + '"shoe.shiner","bc",9,17,3\n' + '"cook","bc",14,22,16\n' + '"soda.clerk","bc",12,30,6\n' + '"watchman","bc",17,25,11\n' + '"janitor","bc",7,20,8\n' + '"policeman","bc",34,47,41\n' + '"waiter","bc",8,32,10' + ) + from pandas import read_csv + + dta = read_csv(dta) + model = ols("prestige ~ income + education", dta).fit() + assert_equal(model.fittedvalues.index, dta.index) + + +def test_formula_predict(): + # `log` is needed in the namespace for patsy to find + from numpy import log # noqa:F401 + + formula = """TOTEMP ~ log(GNPDEFL) + log(GNP) + UNEMP + ARMED + + POP + YEAR""" + data = load_pandas() + dta = load_pandas().data + results = ols(formula, dta).fit() + npt.assert_almost_equal(results.fittedvalues.values, results.predict(data.exog), 8) + + +def test_formula_predict_series(): + data = pd.DataFrame({"y": [1, 2, 3], "x": [1, 2, 3]}, index=[5, 3, 1]) + results = ols("y ~ x", data).fit() + + result = results.predict(data) + expected = pd.Series([1.0, 2.0, 3.0], index=[5, 3, 1]) + assert_series_equal(result, expected) + + result = results.predict(data.x) + assert_series_equal(result, expected) + + result = results.predict(pd.Series([1, 2, 3], index=[1, 2, 3], name="x")) + expected = pd.Series([1.0, 2.0, 3.0], index=[1, 2, 3]) + assert_series_equal(result, expected) + + with pytest.warns(DeprecationWarning, match="Using"): + result = results.predict({"x": [1, 2, 3]}) + expected = pd.Series([1.0, 2.0, 3.0], index=[0, 1, 2]) + assert_series_equal(result, expected, check_index_type=False) + + +def test_patsy_lazy_dict(): + class LazyDict(dict): + def __init__(self, data): + self.data = data + + def __missing__(self, key): + return np.array(self.data[key]) + + data = cpunish.load_pandas().data + + if statsmodels.formula.options.formula_engine == "patsy": + data = LazyDict(data) + ctx_mgr = pytest.deprecated_call + else: + ctx_mgr = contextlib.nullcontext + + with ctx_mgr(): + res = ols("EXECUTIONS ~ SOUTH + INCOME", data=data).fit() + with ctx_mgr(): + res2 = res.predict(data) + npt.assert_allclose(res.fittedvalues, res2) + + data = cpunish.load_pandas().data + data.loc[0, "INCOME"] = np.nan + + if statsmodels.formula.options.formula_engine == "patsy": + data = LazyDict(data) + data.index = cpunish.load_pandas().data.index + with ctx_mgr(): + res = ols("EXECUTIONS ~ SOUTH + INCOME", data=data).fit() + with ctx_mgr(): + res2 = res.predict(data) + if statsmodels.formula.options.formula_engine == "patsy": + # Only happens with LazyDict input + assert_equal(res.fittedvalues, res2) # Should lose a record + assert_equal(len(res2) + 1, len(cpunish.load_pandas().data)) + else: + assert_equal(res.fittedvalues, res2.iloc[1:]) # Should lose a record + assert_equal(len(res2), len(cpunish.load_pandas().data)) + + +def test_formula_missing_data(): + # Test pandas-style first + data = cpunish.load_pandas().data + data.loc[0, "INCOME"] = np.nan + res = ols("EXECUTIONS ~ SOUTH + INCOME", data=data).fit() + res2 = res.predict(data) + # First record will be dropped during fit, but not during predict + assert_equal(res.fittedvalues, res2[1:]) + + # Non-pandas version + data = cpunish.load_pandas().data + data.loc[0, "INCOME"] = None + data = data.to_records(index=False) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + res2 = res.predict(data) + assert "ValueWarning" in repr(w[-1].message) + assert "nan values have been dropped" in repr(w[-1].message) + # First record will be dropped in both cases + assert_equal(res.fittedvalues, res2, check_index_type=False) + + +@pytest.mark.skipif(PATSY_MISSING, reason="patsy is required") +def test_eval_env_dict_is_used_in_patsy(): + data = pd.DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]}) + z = [10, 20, 30] + mgr = FormulaManager(engine="patsy") + y, X = mgr.get_matrices( + "y ~ x + z", + data=data, + eval_env={"z": z}, + pandas=True, + ) + assert "z" in X.columns + + +def test_predict_nondataframe(): + df = pd.DataFrame( + [[3, 0.030], [10, 0.060], [20, 0.120]], columns=["BSA", "Absorbance"] + ) + + model = ols("Absorbance ~ BSA", data=df) + fit = model.fit() + mgr = FormulaManager() + with pytest.raises(mgr.formula_materializer_error): + with pytest.deprecated_call(): + fit.predict([0.25]) + + +@pytest.mark.skipif(PATSY_MISSING, reason="patsy is required") +def test_formula_environment(): + df = pd.DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]}) + env = patsy.eval.EvalEnvironment([{"z": [3, 6, 9]}]) + with pytest.warns(FutureWarning, match="EvalEnvironment is deprecated"): + model = ols("y ~ x + z", eval_env=env, data=df) + assert "z" in model.exog_names + with pytest.raises(TypeError): + ols("y ~ x", eval_env="env", data=df) + + +def test_formula_predict_series_exog(): + # GH-6509 + rs = np.random.RandomState(23829137) + x = rs.standard_normal((1000, 2)) + data_full = pd.DataFrame(x, columns=["y", "x"]) + data = data_full.iloc[:500] + res = ols(formula="y ~ x", data=data).fit() + oos = data_full.iloc[500:]["x"] + prediction = res.get_prediction(oos) + assert prediction.predicted_mean.shape[0] == 500 diff --git a/shared/package-files/3a/3a7a034a934220c2e9d495d5329c4213c70b7edf0b8cdc34a21474e367db0bc9/_make_dual.h b/shared/package-files/3a/3a7a034a934220c2e9d495d5329c4213c70b7edf0b8cdc34a21474e367db0bc9/_make_dual.h new file mode 100644 index 0000000000000000000000000000000000000000..1f8e9f83873cbc4ffdd1a394c09400de9ce7529e --- /dev/null +++ b/shared/package-files/3a/3a7a034a934220c2e9d495d5329c4213c70b7edf0b8cdc34a21474e367db0bc9/_make_dual.h @@ -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::_make_dual(Tensor(a) primal, Tensor tangent, int level) -> Tensor(a) +inline at::Tensor _make_dual(const at::Tensor & primal, const at::Tensor & tangent, int64_t level) { + return at::_ops::_make_dual::call(primal, tangent, level); +} + +} diff --git a/shared/package-files/3a/3a7a29fcd4b312e7774b040b01060b592372c2d59a6e8e9997097292f0e0eaa3/_dirichlet_grad_native.h b/shared/package-files/3a/3a7a29fcd4b312e7774b040b01060b592372c2d59a6e8e9997097292f0e0eaa3/_dirichlet_grad_native.h new file mode 100644 index 0000000000000000000000000000000000000000..8d68bb931a61be557508da8972691347f5bd8413 --- /dev/null +++ b/shared/package-files/3a/3a7a29fcd4b312e7774b040b01060b592372c2d59a6e8e9997097292f0e0eaa3/_dirichlet_grad_native.h @@ -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 & _dirichlet_grad_out(const at::Tensor & x, const at::Tensor & alpha, const at::Tensor & total, at::Tensor & out); +TORCH_API at::Tensor _dirichlet_grad_cpu(const at::Tensor & x, const at::Tensor & alpha, const at::Tensor & total); +TORCH_API at::Tensor _dirichlet_grad_cuda(const at::Tensor & x, const at::Tensor & alpha, const at::Tensor & total); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a7b049cc17a79e84815d3399bb44791cf51fcb1486a11892f76c012fd6947a9/free_groups.py b/shared/package-files/3a/3a7b049cc17a79e84815d3399bb44791cf51fcb1486a11892f76c012fd6947a9/free_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..9c24abdc480c7803331435ba7453c4e0848ddb07 --- /dev/null +++ b/shared/package-files/3a/3a7b049cc17a79e84815d3399bb44791cf51fcb1486a11892f76c012fd6947a9/free_groups.py @@ -0,0 +1,1354 @@ +from __future__ import annotations + +from sympy.core import S +from sympy.core.expr import Expr +from sympy.core.symbol import Symbol, symbols as _symbols +from sympy.core.sympify import CantSympify +from sympy.printing.defaults import DefaultPrinting +from sympy.utilities import public +from sympy.utilities.iterables import flatten, is_sequence +from sympy.utilities.magic import pollute +from sympy.utilities.misc import as_int + + +@public +def free_group(symbols): + """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1))``. + + Parameters + ========== + + symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y, z = free_group("x, y, z") + >>> F + + >>> x**2*y**-1 + x**2*y**-1 + >>> type(_) + + + """ + _free_group = FreeGroup(symbols) + return (_free_group,) + tuple(_free_group.generators) + +@public +def xfree_group(symbols): + """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1)))``. + + Parameters + ========== + + symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) + + Examples + ======== + + >>> from sympy.combinatorics.free_groups import xfree_group + >>> F, (x, y, z) = xfree_group("x, y, z") + >>> F + + >>> y**2*x**-2*z**-1 + y**2*x**-2*z**-1 + >>> type(_) + + + """ + _free_group = FreeGroup(symbols) + return (_free_group, _free_group.generators) + +@public +def vfree_group(symbols): + """Construct a free group and inject ``f_0, f_1, ..., f_(n-1)`` as symbols + into the global namespace. + + Parameters + ========== + + symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) + + Examples + ======== + + >>> from sympy.combinatorics.free_groups import vfree_group + >>> vfree_group("x, y, z") + + >>> x**2*y**-2*z # noqa: F821 + x**2*y**-2*z + >>> type(_) + + + """ + _free_group = FreeGroup(symbols) + pollute([sym.name for sym in _free_group.symbols], _free_group.generators) + return _free_group + + +def _parse_symbols(symbols): + if not symbols: + return () + if isinstance(symbols, str): + return _symbols(symbols, seq=True) + elif isinstance(symbols, (Expr, FreeGroupElement)): + return (symbols,) + elif is_sequence(symbols): + if all(isinstance(s, str) for s in symbols): + return _symbols(symbols) + elif all(isinstance(s, Expr) for s in symbols): + return symbols + raise ValueError("The type of `symbols` must be one of the following: " + "a str, Symbol/Expr or a sequence of " + "one of these types") + + +############################################################################## +# FREE GROUP # +############################################################################## + +_free_group_cache: dict[int, FreeGroup] = {} + +class FreeGroup(DefaultPrinting): + """ + Free group with finite or infinite number of generators. Its input API + is that of a str, Symbol/Expr or a sequence of one of + these types (which may be empty) + + See Also + ======== + + sympy.polys.rings.PolyRing + + References + ========== + + .. [1] https://www.gap-system.org/Manuals/doc/ref/chap37.html + + .. [2] https://en.wikipedia.org/wiki/Free_group + + """ + is_associative = True + is_group = True + is_FreeGroup = True + is_PermutationGroup = False + relators: list[Expr] = [] + + def __new__(cls, symbols): + symbols = tuple(_parse_symbols(symbols)) + rank = len(symbols) + _hash = hash((cls.__name__, symbols, rank)) + obj = _free_group_cache.get(_hash) + + if obj is None: + obj = object.__new__(cls) + obj._hash = _hash + obj._rank = rank + # dtype method is used to create new instances of FreeGroupElement + obj.dtype = type("FreeGroupElement", (FreeGroupElement,), {"group": obj}) + obj.symbols = symbols + obj.generators = obj._generators() + obj._gens_set = set(obj.generators) + for symbol, generator in zip(obj.symbols, obj.generators): + if isinstance(symbol, Symbol): + name = symbol.name + if hasattr(obj, name): + setattr(obj, name, generator) + + _free_group_cache[_hash] = obj + + return obj + + def _generators(group): + """Returns the generators of the FreeGroup. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y, z = free_group("x, y, z") + >>> F.generators + (x, y, z) + + """ + gens = [] + for sym in group.symbols: + elm = ((sym, 1),) + gens.append(group.dtype(elm)) + return tuple(gens) + + def clone(self, symbols=None): + return self.__class__(symbols or self.symbols) + + def __contains__(self, i): + """Return True if ``i`` is contained in FreeGroup.""" + if not isinstance(i, FreeGroupElement): + return False + group = i.group + return self == group + + def __hash__(self): + return self._hash + + def __len__(self): + return self.rank + + def __str__(self): + if self.rank > 30: + str_form = "" % self.rank + else: + str_form = "" + return str_form + + __repr__ = __str__ + + def __getitem__(self, index): + symbols = self.symbols[index] + return self.clone(symbols=symbols) + + def __eq__(self, other): + """No ``FreeGroup`` is equal to any "other" ``FreeGroup``. + """ + return self is other + + def index(self, gen): + """Return the index of the generator `gen` from ``(f_0, ..., f_(n-1))``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> F.index(y) + 1 + >>> F.index(x) + 0 + + """ + if isinstance(gen, self.dtype): + return self.generators.index(gen) + else: + raise ValueError("expected a generator of Free Group %s, got %s" % (self, gen)) + + def order(self): + """Return the order of the free group. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> F.order() + oo + + >>> free_group("")[0].order() + 1 + + """ + if self.rank == 0: + return S.One + else: + return S.Infinity + + @property + def elements(self): + """ + Return the elements of the free group. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> (z,) = free_group("") + >>> z.elements + {} + + """ + if self.rank == 0: + # A set containing Identity element of `FreeGroup` self is returned + return {self.identity} + else: + raise ValueError("Group contains infinitely many elements" + ", hence cannot be represented") + + @property + def rank(self): + r""" + In group theory, the `rank` of a group `G`, denoted `G.rank`, + can refer to the smallest cardinality of a generating set + for G, that is + + \operatorname{rank}(G)=\min\{ |X|: X\subseteq G, \left\langle X\right\rangle =G\}. + + """ + return self._rank + + @property + def is_abelian(self): + """Returns if the group is Abelian. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> f.is_abelian + False + + """ + return self.rank in (0, 1) + + @property + def identity(self): + """Returns the identity element of free group.""" + return self.dtype() + + def contains(self, g): + """Tests if Free Group element ``g`` belong to self, ``G``. + + In mathematical terms any linear combination of generators + of a Free Group is contained in it. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> f.contains(x**3*y**2) + True + + """ + if not isinstance(g, FreeGroupElement): + return False + elif self != g.group: + return False + else: + return True + + def center(self): + """Returns the center of the free group `self`.""" + return {self.identity} + + +############################################################################ +# FreeGroupElement # +############################################################################ + + +class FreeGroupElement(CantSympify, DefaultPrinting, tuple): + """Used to create elements of FreeGroup. It cannot be used directly to + create a free group element. It is called by the `dtype` method of the + `FreeGroup` class. + + """ + is_assoc_word = True + + def new(self, init): + return self.__class__(init) + + _hash = None + + def __hash__(self): + _hash = self._hash + if _hash is None: + self._hash = _hash = hash((self.group, frozenset(tuple(self)))) + return _hash + + def copy(self): + return self.new(self) + + @property + def is_identity(self): + if self.array_form == (): + return True + else: + return False + + @property + def array_form(self): + """ + SymPy provides two different internal kinds of representation + of associative words. The first one is called the `array_form` + which is a tuple containing `tuples` as its elements, where the + size of each tuple is two. At the first position the tuple + contains the `symbol-generator`, while at the second position + of tuple contains the exponent of that generator at the position. + Since elements (i.e. words) do not commute, the indexing of tuple + makes that property to stay. + + The structure in ``array_form`` of ``FreeGroupElement`` is of form: + + ``( ( symbol_of_gen, exponent ), ( , ), ... ( , ) )`` + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> (x*z).array_form + ((x, 1), (z, 1)) + >>> (x**2*z*y*x**2).array_form + ((x, 2), (z, 1), (y, 1), (x, 2)) + + See Also + ======== + + letter_repr + + """ + return tuple(self) + + @property + def letter_form(self): + """ + The letter representation of a ``FreeGroupElement`` is a tuple + of generator symbols, with each entry corresponding to a group + generator. Inverses of the generators are represented by + negative generator symbols. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b, c, d = free_group("a b c d") + >>> (a**3).letter_form + (a, a, a) + >>> (a**2*d**-2*a*b**-4).letter_form + (a, a, -d, -d, a, -b, -b, -b, -b) + >>> (a**-2*b**3*d).letter_form + (-a, -a, b, b, b, d) + + See Also + ======== + + array_form + + """ + return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j) + for i, j in self.array_form])) + + def __getitem__(self, i): + group = self.group + r = self.letter_form[i] + if r.is_Symbol: + return group.dtype(((r, 1),)) + else: + return group.dtype(((-r, -1),)) + + def index(self, gen): + if len(gen) != 1: + raise ValueError() + return (self.letter_form).index(gen.letter_form[0]) + + @property + def letter_form_elm(self): + """ + """ + group = self.group + r = self.letter_form + return [group.dtype(((elm,1),)) if elm.is_Symbol \ + else group.dtype(((-elm,-1),)) for elm in r] + + @property + def ext_rep(self): + """This is called the External Representation of ``FreeGroupElement`` + """ + return tuple(flatten(self.array_form)) + + def __contains__(self, gen): + return gen.array_form[0][0] in tuple([r[0] for r in self.array_form]) + + def __str__(self): + if self.is_identity: + return "" + + str_form = "" + array_form = self.array_form + for i in range(len(array_form)): + if i == len(array_form) - 1: + if array_form[i][1] == 1: + str_form += str(array_form[i][0]) + else: + str_form += str(array_form[i][0]) + \ + "**" + str(array_form[i][1]) + else: + if array_form[i][1] == 1: + str_form += str(array_form[i][0]) + "*" + else: + str_form += str(array_form[i][0]) + \ + "**" + str(array_form[i][1]) + "*" + return str_form + + __repr__ = __str__ + + def __pow__(self, n): + n = as_int(n) + group = self.group + if n == 0: + return group.identity + + if n < 0: + n = -n + return (self.inverse())**n + + result = self + for i in range(n - 1): + result = result*self + # this method can be improved instead of just returning the + # multiplication of elements + return result + + def __mul__(self, other): + """Returns the product of elements belonging to the same ``FreeGroup``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> x*y**2*y**-4 + x*y**-2 + >>> z*y**-2 + z*y**-2 + >>> x**2*y*y**-1*x**-2 + + + """ + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be multiplied") + if self.is_identity: + return other + if other.is_identity: + return self + r = list(self.array_form + other.array_form) + zero_mul_simp(r, len(self.array_form) - 1) + return group.dtype(tuple(r)) + + def __truediv__(self, other): + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be multiplied") + return self*(other.inverse()) + + def __rtruediv__(self, other): + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be multiplied") + return other*(self.inverse()) + + def __add__(self, other): + return NotImplemented + + def inverse(self): + """ + Returns the inverse of a ``FreeGroupElement`` element + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> x.inverse() + x**-1 + >>> (x*y).inverse() + y**-1*x**-1 + + """ + group = self.group + r = tuple([(i, -j) for i, j in self.array_form[::-1]]) + return group.dtype(r) + + def order(self): + """Find the order of a ``FreeGroupElement``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y = free_group("x y") + >>> (x**2*y*y**-1*x**-2).order() + 1 + + """ + if self.is_identity: + return S.One + else: + return S.Infinity + + def commutator(self, other): + """ + Return the commutator of `self` and `x`: ``~x*~self*x*self`` + + """ + group = self.group + if not isinstance(other, group.dtype): + raise ValueError("commutator of only FreeGroupElement of the same " + "FreeGroup exists") + else: + return self.inverse()*other.inverse()*self*other + + def eliminate_words(self, words, _all=False, inverse=True): + ''' + Replace each subword from the dictionary `words` by words[subword]. + If words is a list, replace the words by the identity. + + ''' + again = True + new = self + if isinstance(words, dict): + while again: + again = False + for sub in words: + prev = new + new = new.eliminate_word(sub, words[sub], _all=_all, inverse=inverse) + if new != prev: + again = True + else: + while again: + again = False + for sub in words: + prev = new + new = new.eliminate_word(sub, _all=_all, inverse=inverse) + if new != prev: + again = True + return new + + def eliminate_word(self, gen, by=None, _all=False, inverse=True): + """ + For an associative word `self`, a subword `gen`, and an associative + word `by` (identity by default), return the associative word obtained by + replacing each occurrence of `gen` in `self` by `by`. If `_all = True`, + the occurrences of `gen` that may appear after the first substitution will + also be replaced and so on until no occurrences are found. This might not + always terminate (e.g. `(x).eliminate_word(x, x**2, _all=True)`). + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y = free_group("x y") + >>> w = x**5*y*x**2*y**-4*x + >>> w.eliminate_word( x, x**2 ) + x**10*y*x**4*y**-4*x**2 + >>> w.eliminate_word( x, y**-1 ) + y**-11 + >>> w.eliminate_word(x**5) + y*x**2*y**-4*x + >>> w.eliminate_word(x*y, y) + x**4*y*x**2*y**-4*x + + See Also + ======== + substituted_word + + """ + if by is None: + by = self.group.identity + if self.is_independent(gen) or gen == by: + return self + if gen == self: + return by + if gen**-1 == by: + _all = False + word = self + l = len(gen) + + try: + i = word.subword_index(gen) + k = 1 + except ValueError: + if not inverse: + return word + try: + i = word.subword_index(gen**-1) + k = -1 + except ValueError: + return word + + word = word.subword(0, i)*by**k*word.subword(i+l, len(word)).eliminate_word(gen, by) + + if _all: + return word.eliminate_word(gen, by, _all=True, inverse=inverse) + else: + return word + + def __len__(self): + """ + For an associative word `self`, returns the number of letters in it. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> len(w) + 13 + >>> len(a**17) + 17 + >>> len(w**0) + 0 + + """ + return sum(abs(j) for (i, j) in self) + + def __eq__(self, other): + """ + Two associative words are equal if they are words over the + same alphabet and if they are sequences of the same letters. + This is equivalent to saying that the external representations + of the words are equal. + There is no "universal" empty word, every alphabet has its own + empty word. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") + >>> f + + >>> g, swap0, swap1 = free_group("swap0 swap1") + >>> g + + + >>> swapnil0 == swapnil1 + False + >>> swapnil0*swapnil1 == swapnil1/swapnil1*swapnil0*swapnil1 + True + >>> swapnil0*swapnil1 == swapnil1*swapnil0 + False + >>> swapnil1**0 == swap0**0 + False + + """ + group = self.group + if not isinstance(other, group.dtype): + return False + return tuple.__eq__(self, other) + + def __lt__(self, other): + """ + The ordering of associative words is defined by length and + lexicography (this ordering is called short-lex ordering), that + is, shorter words are smaller than longer words, and words of the + same length are compared w.r.t. the lexicographical ordering induced + by the ordering of generators. Generators are sorted according + to the order in which they were created. If the generators are + invertible then each generator `g` is larger than its inverse `g^{-1}`, + and `g^{-1}` is larger than every generator that is smaller than `g`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> b < a + False + >>> a < a.inverse() + False + + """ + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be compared") + l = len(self) + m = len(other) + # implement lenlex order + if l < m: + return True + elif l > m: + return False + for i in range(l): + a = self[i].array_form[0] + b = other[i].array_form[0] + p = group.symbols.index(a[0]) + q = group.symbols.index(b[0]) + if p < q: + return True + elif p > q: + return False + elif a[1] < b[1]: + return True + elif a[1] > b[1]: + return False + return False + + def __le__(self, other): + return (self == other or self < other) + + def __gt__(self, other): + """ + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> y**2 > x**2 + True + >>> y*z > z*y + False + >>> x > x.inverse() + True + + """ + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be compared") + return not self <= other + + def __ge__(self, other): + return not self < other + + def exponent_sum(self, gen): + """ + For an associative word `self` and a generator or inverse of generator + `gen`, ``exponent_sum`` returns the number of times `gen` appears in + `self` minus the number of times its inverse appears in `self`. If + neither `gen` nor its inverse occur in `self` then 0 is returned. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w = x**2*y**3 + >>> w.exponent_sum(x) + 2 + >>> w.exponent_sum(x**-1) + -2 + >>> w = x**2*y**4*x**-3 + >>> w.exponent_sum(x) + -1 + + See Also + ======== + + generator_count + + """ + if len(gen) != 1: + raise ValueError("gen must be a generator or inverse of a generator") + s = gen.array_form[0] + return s[1]*sum([i[1] for i in self.array_form if i[0] == s[0]]) + + def generator_count(self, gen): + """ + For an associative word `self` and a generator `gen`, + ``generator_count`` returns the multiplicity of generator + `gen` in `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w = x**2*y**3 + >>> w.generator_count(x) + 2 + >>> w = x**2*y**4*x**-3 + >>> w.generator_count(x) + 5 + + See Also + ======== + + exponent_sum + + """ + if len(gen) != 1 or gen.array_form[0][1] < 0: + raise ValueError("gen must be a generator") + s = gen.array_form[0] + return s[1]*sum([abs(i[1]) for i in self.array_form if i[0] == s[0]]) + + def subword(self, from_i, to_j, strict=True): + """ + For an associative word `self` and two positive integers `from_i` and + `to_j`, `subword` returns the subword of `self` that begins at position + `from_i` and ends at `to_j - 1`, indexing is done with origin 0. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.subword(2, 6) + a**3*b + + """ + group = self.group + if not strict: + from_i = max(from_i, 0) + to_j = min(len(self), to_j) + if from_i < 0 or to_j > len(self): + raise ValueError("`from_i`, `to_j` must be positive and no greater than " + "the length of associative word") + if to_j <= from_i: + return group.identity + else: + letter_form = self.letter_form[from_i: to_j] + array_form = letter_form_to_array_form(letter_form, group) + return group.dtype(array_form) + + def subword_index(self, word, start = 0): + ''' + Find the index of `word` in `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**2*b*a*b**3 + >>> w.subword_index(a*b*a*b) + 1 + + ''' + l = len(word) + self_lf = self.letter_form + word_lf = word.letter_form + index = None + for i in range(start,len(self_lf)-l+1): + if self_lf[i:i+l] == word_lf: + index = i + break + if index is not None: + return index + else: + raise ValueError("The given word is not a subword of self") + + def is_dependent(self, word): + """ + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**4*y**-3).is_dependent(x**4*y**-2) + True + >>> (x**2*y**-1).is_dependent(x*y) + False + >>> (x*y**2*x*y**2).is_dependent(x*y**2) + True + >>> (x**12).is_dependent(x**-4) + True + + See Also + ======== + + is_independent + + """ + try: + return self.subword_index(word) is not None + except ValueError: + pass + try: + return self.subword_index(word**-1) is not None + except ValueError: + return False + + def is_independent(self, word): + """ + + See Also + ======== + + is_dependent + + """ + return not self.is_dependent(word) + + def contains_generators(self): + """ + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y, z = free_group("x, y, z") + >>> (x**2*y**-1).contains_generators() + {x, y} + >>> (x**3*z).contains_generators() + {x, z} + + """ + group = self.group + gens = set() + for syllable in self.array_form: + gens.add(group.dtype(((syllable[0], 1),))) + return set(gens) + + def cyclic_subword(self, from_i, to_j): + group = self.group + l = len(self) + letter_form = self.letter_form + period1 = int(from_i/l) + if from_i >= l: + from_i -= l*period1 + to_j -= l*period1 + diff = to_j - from_i + word = letter_form[from_i: to_j] + period2 = int(to_j/l) - 1 + word += letter_form*period2 + letter_form[:diff-l+from_i-l*period2] + word = letter_form_to_array_form(word, group) + return group.dtype(word) + + def cyclic_conjugates(self): + """Returns a words which are cyclic to the word `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w = x*y*x*y*x + >>> w.cyclic_conjugates() + {x*y*x**2*y, x**2*y*x*y, y*x*y*x**2, y*x**2*y*x, x*y*x*y*x} + >>> s = x*y*x**2*y*x + >>> s.cyclic_conjugates() + {x**2*y*x**2*y, y*x**2*y*x**2, x*y*x**2*y*x} + + References + ========== + + .. [1] https://planetmath.org/cyclicpermutation + + """ + return {self.cyclic_subword(i, i+len(self)) for i in range(len(self))} + + def is_cyclic_conjugate(self, w): + """ + Checks whether words ``self``, ``w`` are cyclic conjugates. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w1 = x**2*y**5 + >>> w2 = x*y**5*x + >>> w1.is_cyclic_conjugate(w2) + True + >>> w3 = x**-1*y**5*x**-1 + >>> w3.is_cyclic_conjugate(w2) + False + + """ + l1 = len(self) + l2 = len(w) + if l1 != l2: + return False + w1 = self.identity_cyclic_reduction() + w2 = w.identity_cyclic_reduction() + letter1 = w1.letter_form + letter2 = w2.letter_form + str1 = ' '.join(map(str, letter1)) + str2 = ' '.join(map(str, letter2)) + if len(str1) != len(str2): + return False + + return str1 in str2 + ' ' + str2 + + def number_syllables(self): + """Returns the number of syllables of the associative word `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") + >>> (swapnil1**3*swapnil0*swapnil1**-1).number_syllables() + 3 + + """ + return len(self.array_form) + + def exponent_syllable(self, i): + """ + Returns the exponent of the `i`-th syllable of the associative word + `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.exponent_syllable( 2 ) + 2 + + """ + return self.array_form[i][1] + + def generator_syllable(self, i): + """ + Returns the symbol of the generator that is involved in the + i-th syllable of the associative word `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.generator_syllable( 3 ) + b + + """ + return self.array_form[i][0] + + def sub_syllables(self, from_i, to_j): + """ + `sub_syllables` returns the subword of the associative word `self` that + consists of syllables from positions `from_to` to `to_j`, where + `from_to` and `to_j` must be positive integers and indexing is done + with origin 0. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a, b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.sub_syllables(1, 2) + b + >>> w.sub_syllables(3, 3) + + + """ + if not isinstance(from_i, int) or not isinstance(to_j, int): + raise ValueError("both arguments should be integers") + group = self.group + if to_j <= from_i: + return group.identity + else: + r = tuple(self.array_form[from_i: to_j]) + return group.dtype(r) + + def substituted_word(self, from_i, to_j, by): + """ + Returns the associative word obtained by replacing the subword of + `self` that begins at position `from_i` and ends at position `to_j - 1` + by the associative word `by`. `from_i` and `to_j` must be positive + integers, indexing is done with origin 0. In other words, + `w.substituted_word(w, from_i, to_j, by)` is the product of the three + words: `w.subword(0, from_i)`, `by`, and + `w.subword(to_j len(w))`. + + See Also + ======== + + eliminate_word + + """ + lw = len(self) + if from_i >= to_j or from_i > lw or to_j > lw: + raise ValueError("values should be within bounds") + + # otherwise there are four possibilities + + # first if from=1 and to=lw then + if from_i == 0 and to_j == lw: + return by + elif from_i == 0: # second if from_i=1 (and to_j < lw) then + return by*self.subword(to_j, lw) + elif to_j == lw: # third if to_j=1 (and from_i > 1) then + return self.subword(0, from_i)*by + else: # finally + return self.subword(0, from_i)*by*self.subword(to_j, lw) + + def is_cyclically_reduced(self): + r"""Returns whether the word is cyclically reduced or not. + A word is cyclically reduced if by forming the cycle of the + word, the word is not reduced, i.e a word w = `a_1 ... a_n` + is called cyclically reduced if `a_1 \ne a_n^{-1}`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**2*y**-1*x**-1).is_cyclically_reduced() + False + >>> (y*x**2*y**2).is_cyclically_reduced() + True + + """ + if not self: + return True + return self[0] != self[-1]**-1 + + def identity_cyclic_reduction(self): + """Return a unique cyclically reduced version of the word. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**2*y**2*x**-1).identity_cyclic_reduction() + x*y**2 + >>> (x**-3*y**-1*x**5).identity_cyclic_reduction() + x**2*y**-1 + + References + ========== + + .. [1] https://planetmath.org/cyclicallyreduced + + """ + word = self.copy() + group = self.group + while not word.is_cyclically_reduced(): + exp1 = word.exponent_syllable(0) + exp2 = word.exponent_syllable(-1) + r = exp1 + exp2 + if r == 0: + rep = word.array_form[1: word.number_syllables() - 1] + else: + rep = ((word.generator_syllable(0), exp1 + exp2),) + \ + word.array_form[1: word.number_syllables() - 1] + word = group.dtype(rep) + return word + + def cyclic_reduction(self, removed=False): + """Return a cyclically reduced version of the word. Unlike + `identity_cyclic_reduction`, this will not cyclically permute + the reduced word - just remove the "unreduced" bits on either + side of it. Compare the examples with those of + `identity_cyclic_reduction`. + + When `removed` is `True`, return a tuple `(word, r)` where + self `r` is such that before the reduction the word was either + `r*word*r**-1`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**2*y**2*x**-1).cyclic_reduction() + x*y**2 + >>> (x**-3*y**-1*x**5).cyclic_reduction() + y**-1*x**2 + >>> (x**-3*y**-1*x**5).cyclic_reduction(removed=True) + (y**-1*x**2, x**-3) + + """ + word = self.copy() + g = self.group.identity + while not word.is_cyclically_reduced(): + exp1 = abs(word.exponent_syllable(0)) + exp2 = abs(word.exponent_syllable(-1)) + exp = min(exp1, exp2) + start = word[0]**abs(exp) + end = word[-1]**abs(exp) + word = start**-1*word*end**-1 + g = g*start + if removed: + return word, g + return word + + def power_of(self, other): + ''' + Check if `self == other**n` for some integer n. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> ((x*y)**2).power_of(x*y) + True + >>> (x**-3*y**-2*x**3).power_of(x**-3*y*x**3) + True + + ''' + if self.is_identity: + return True + + l = len(other) + if l == 1: + # self has to be a power of one generator + gens = self.contains_generators() + s = other in gens or other**-1 in gens + return len(gens) == 1 and s + + # if self is not cyclically reduced and it is a power of other, + # other isn't cyclically reduced and the parts removed during + # their reduction must be equal + reduced, r1 = self.cyclic_reduction(removed=True) + if not r1.is_identity: + other, r2 = other.cyclic_reduction(removed=True) + if r1 == r2: + return reduced.power_of(other) + return False + + if len(self) < l or len(self) % l: + return False + + prefix = self.subword(0, l) + if prefix == other or prefix**-1 == other: + rest = self.subword(l, len(self)) + return rest.power_of(other) + return False + + +def letter_form_to_array_form(array_form, group): + """ + This method converts a list given with possible repetitions of elements in + it. It returns a new list such that repetitions of consecutive elements is + removed and replace with a tuple element of size two such that the first + index contains `value` and the second index contains the number of + consecutive repetitions of `value`. + + """ + a = list(array_form[:]) + new_array = [] + n = 1 + symbols = group.symbols + for i in range(len(a)): + if i == len(a) - 1: + if a[i] == a[i - 1]: + if (-a[i]) in symbols: + new_array.append((-a[i], -n)) + else: + new_array.append((a[i], n)) + else: + if (-a[i]) in symbols: + new_array.append((-a[i], -1)) + else: + new_array.append((a[i], 1)) + return new_array + elif a[i] == a[i + 1]: + n += 1 + else: + if (-a[i]) in symbols: + new_array.append((-a[i], -n)) + else: + new_array.append((a[i], n)) + n = 1 + + +def zero_mul_simp(l, index): + """Used to combine two reduced words.""" + while index >=0 and index < len(l) - 1 and l[index][0] == l[index + 1][0]: + exp = l[index][1] + l[index + 1][1] + base = l[index][0] + l[index] = (base, exp) + del l[index + 1] + if l[index][1] == 0: + del l[index] + index -= 1 diff --git a/shared/package-files/3a/3a857a28d639212b5675eb5944aeb3e1002c08e2d26e7f2f510d2e2b56360863/MTIAHooksInterface.h b/shared/package-files/3a/3a857a28d639212b5675eb5944aeb3e1002c08e2d26e7f2f510d2e2b56360863/MTIAHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..c843ca52c2b41d3f7a80d46ffb77b5aa5341cc8a --- /dev/null +++ b/shared/package-files/3a/3a857a28d639212b5675eb5944aeb3e1002c08e2d26e7f2f510d2e2b56360863/MTIAHooksInterface.h @@ -0,0 +1,61 @@ +#pragma once + +#include + +#include + +#include + +#include + +namespace at { +class Context; +} + +namespace at { + +constexpr const char* MTIA_HELP = + "The MTIA backend requires MTIA extension for PyTorch;" + "this error has occurred because you are trying " + "to use some MTIA's functionality without MTIA extension included."; + +struct TORCH_API MTIAHooksInterface : AcceleratorHooksInterface { + virtual ~MTIAHooksInterface() override = default; + + virtual void initMTIA() const { + TORCH_CHECK( + false, + "Cannot initialize MTIA without MTIA Extension for PyTorch.", + MTIA_HELP); + } + + virtual bool hasMTIA() const { + return false; + } + + virtual std::string showConfig() const { + TORCH_CHECK( + false, + "Cannot query detailed MTIA version without MTIA Extension for PyTorch.", + MTIA_HELP); + } + + virtual bool hasPrimaryContext(DeviceIndex device_index) const override { + TORCH_CHECK( + false, + "Cannot check MTIA primary context without MTIA Extension for PyTorch.", + MTIA_HELP); + } + +}; + +struct TORCH_API MTIAHooksArgs {}; + +C10_DECLARE_REGISTRY(MTIAHooksRegistry, MTIAHooksInterface, MTIAHooksArgs); +#define REGISTER_MTIA_HOOKS(clsname) \ + C10_REGISTER_CLASS(MTIAHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const MTIAHooksInterface& getMTIAHooks(); +} // namespace detail +} // namespace at diff --git a/shared/package-files/3a/3a87611a95f1efc7fdd265e1b43eec7ad21ebe8047cf5a5a3365ffafe940c6ad/history.py b/shared/package-files/3a/3a87611a95f1efc7fdd265e1b43eec7ad21ebe8047cf5a5a3365ffafe940c6ad/history.py new file mode 100644 index 0000000000000000000000000000000000000000..621c5812fc25c98deae7c34d267b76c9ed7390f5 --- /dev/null +++ b/shared/package-files/3a/3a87611a95f1efc7fdd265e1b43eec7ad21ebe8047cf5a5a3365ffafe940c6ad/history.py @@ -0,0 +1,106 @@ +"Implement Idle Shell history mechanism with History class" + +from idlelib.config import idleConf + + +class History: + ''' Implement Idle Shell history mechanism. + + store - Store source statement (called from pyshell.resetoutput). + fetch - Fetch stored statement matching prefix already entered. + history_next - Bound to <> event (default Alt-N). + history_prev - Bound to <> event (default Alt-P). + ''' + def __init__(self, text): + '''Initialize data attributes and bind event methods. + + .text - Idle wrapper of tk Text widget, with .bell(). + .history - source statements, possibly with multiple lines. + .prefix - source already entered at prompt; filters history list. + .pointer - index into history. + .cyclic - wrap around history list (or not). + ''' + self.text = text + self.history = [] + self.prefix = None + self.pointer = None + self.cyclic = idleConf.GetOption("main", "History", "cyclic", 1, "bool") + text.bind("<>", self.history_prev) + text.bind("<>", self.history_next) + + def history_next(self, event): + "Fetch later statement; start with ealiest if cyclic." + self.fetch(reverse=False) + return "break" + + def history_prev(self, event): + "Fetch earlier statement; start with most recent." + self.fetch(reverse=True) + return "break" + + def fetch(self, reverse): + '''Fetch statement and replace current line in text widget. + + Set prefix and pointer as needed for successive fetches. + Reset them to None, None when returning to the start line. + Sound bell when return to start line or cannot leave a line + because cyclic is False. + ''' + nhist = len(self.history) + pointer = self.pointer + prefix = self.prefix + if pointer is not None and prefix is not None: + if self.text.compare("insert", "!=", "end-1c") or \ + self.text.get("iomark", "end-1c") != self.history[pointer]: + pointer = prefix = None + self.text.mark_set("insert", "end-1c") # != after cursor move + if pointer is None or prefix is None: + prefix = self.text.get("iomark", "end-1c") + if reverse: + pointer = nhist # will be decremented + else: + if self.cyclic: + pointer = -1 # will be incremented + else: # abort history_next + self.text.bell() + return + nprefix = len(prefix) + while True: + pointer += -1 if reverse else 1 + if pointer < 0 or pointer >= nhist: + self.text.bell() + if not self.cyclic and pointer < 0: # abort history_prev + return + else: + if self.text.get("iomark", "end-1c") != prefix: + self.text.delete("iomark", "end-1c") + self.text.insert("iomark", prefix, "stdin") + pointer = prefix = None + break + item = self.history[pointer] + if item[:nprefix] == prefix and len(item) > nprefix: + self.text.delete("iomark", "end-1c") + self.text.insert("iomark", item, "stdin") + break + self.text.see("insert") + self.text.tag_remove("sel", "1.0", "end") + self.pointer = pointer + self.prefix = prefix + + def store(self, source): + "Store Shell input statement into history list." + source = source.strip() + if len(source) > 2: + # avoid duplicates + try: + self.history.remove(source) + except ValueError: + pass + self.history.append(source) + self.pointer = None + self.prefix = None + + +if __name__ == "__main__": + from unittest import main + main('idlelib.idle_test.test_history', verbosity=2, exit=False) diff --git a/shared/package-files/3a/3a8917da6df8e89fc2d0be378e137143c4982a9229cd3623ca097e27f6c52e60/lowering.py b/shared/package-files/3a/3a8917da6df8e89fc2d0be378e137143c4982a9229cd3623ca097e27f6c52e60/lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..ae5c6fe03192ed4ac022e525c3a1247ef04ed41c --- /dev/null +++ b/shared/package-files/3a/3a8917da6df8e89fc2d0be378e137143c4982a9229cd3623ca097e27f6c52e60/lowering.py @@ -0,0 +1,1654 @@ +from collections import namedtuple, defaultdict +import operator +import warnings +from functools import partial + +import llvmlite.ir +from llvmlite.ir import Constant, IRBuilder + +from numba.core import (typing, utils, types, ir, debuginfo, funcdesc, + generators, config, ir_utils, cgutils, + targetconfig) +from numba.core.errors import (LoweringError, new_error_context, TypingError, + LiteralTypingError, UnsupportedError, + NumbaDebugInfoWarning) +from numba.core.funcdesc import default_mangler +from numba.core.environment import Environment +from numba.core.analysis import compute_use_defs, must_use_alloca +from numba.misc.firstlinefinder import get_func_body_first_lineno +from numba.misc.coverage_support import get_registered_loc_notify + + +_VarArgItem = namedtuple("_VarArgItem", ("vararg", "index")) + + +class BaseLower(object): + """ + Lower IR to LLVM + """ + + def __init__(self, context, library, fndesc, func_ir, metadata=None): + self.library = library + self.fndesc = fndesc + self.blocks = utils.SortedMap(func_ir.blocks.items()) + self.func_ir = func_ir + self.generator_info = func_ir.generator_info + self.metadata = metadata + self.flags = targetconfig.ConfigStack.top_or_none() + + # Initialize LLVM + self.module = self.library.create_ir_module(self.fndesc.unique_name) + + # Python execution environment (will be available to the compiled + # function). + self.env = Environment.from_fndesc(self.fndesc) + + # Internal states + self.blkmap = {} + self.pending_phis = {} + self.varmap = {} + self.firstblk = min(self.blocks.keys()) + self.loc = -1 + + # Specializes the target context as seen inside the Lowerer + # This adds: + # - environment: the python execution environment + self.context = context.subtarget(environment=self.env, + fndesc=self.fndesc) + + # Debuginfo + dibuildercls = (self.context.DIBuilder + if self.context.enable_debuginfo + else debuginfo.DummyDIBuilder) + + # debuginfo def location + self.defn_loc = self._compute_def_location() + + directives_only = self.flags.dbg_directives_only + self.debuginfo = dibuildercls(module=self.module, + filepath=func_ir.loc.filename, + cgctx=context, + directives_only=directives_only) + + # Loc notify objects + self._loc_notify_registry = get_registered_loc_notify() + + # Subclass initialization + self.init() + + @property + def call_conv(self): + return self.context.call_conv + + def init(self): + pass + + def init_pyapi(self): + """ + Init the Python API and Environment Manager for the function being + lowered. + """ + if self.pyapi is not None: + return + self.pyapi = self.context.get_python_api(self.builder) + + # Store environment argument for later use + self.env_manager = self.context.get_env_manager(self.builder) + self.env_body = self.env_manager.env_body + self.envarg = self.env_manager.env_ptr + + def _compute_def_location(self): + # Debuginfo requires source to be accurate. Find it and warn if not + # found. If it's not found, use the func_ir line + 1, this assumes that + # the function definition is decorated with a 1 line jit decorator. + defn_loc = self.func_ir.loc.with_lineno(self.func_ir.loc.line + 1) + if self.context.enable_debuginfo: + fn = self.func_ir.func_id.func + optional_lno = get_func_body_first_lineno(fn) + if optional_lno is not None: + # -1 as lines start at 1 and this is an offset. + offset = optional_lno - 1 + defn_loc = self.func_ir.loc.with_lineno(offset) + else: + msg = ("Could not find source for function: " + f"{self.func_ir.func_id.func}. Debug line information " + "may be inaccurate.") + warnings.warn(NumbaDebugInfoWarning(msg)) + return defn_loc + + def pre_lower(self): + """ + Called before lowering all blocks. + """ + # A given Lower object can be used for several LL functions + # (for generators) and it's important to use a new API and + # EnvironmentManager. + self.pyapi = None + self.debuginfo.mark_subprogram(function=self.builder.function, + qualname=self.fndesc.qualname, + argnames=self.fndesc.args, + argtypes=self.fndesc.argtypes, + line=self.defn_loc.line) + + # When full debug info is enabled, disable inlining where possible, to + # improve the quality of the debug experience. 'alwaysinline' functions + # cannot have inlining disabled. + attributes = self.builder.function.attributes + full_debug = self.flags.debuginfo and not self.flags.dbg_directives_only + if full_debug and 'alwaysinline' not in attributes: + attributes.add('noinline') + + def post_lower(self): + """ + Called after all blocks are lowered + """ + self.debuginfo.finalize() + for notify in self._loc_notify_registry: + notify.close() + + def pre_block(self, block): + """ + Called before lowering a block. + """ + + def post_block(self, block): + """ + Called after lowering a block. + """ + + def return_dynamic_exception(self, exc_class, exc_args, nb_types, loc=None): + self.call_conv.return_dynamic_user_exc( + self.builder, exc_class, exc_args, nb_types, + loc=loc, func_name=self.func_ir.func_id.func_name, + ) + + def return_exception(self, exc_class, exc_args=None, loc=None): + """Propagate exception to the caller. + """ + self.call_conv.return_user_exc( + self.builder, exc_class, exc_args, + loc=loc, func_name=self.func_ir.func_id.func_name, + ) + + def set_exception(self, exc_class, exc_args=None, loc=None): + """Set exception state in the current function. + """ + self.call_conv.set_static_user_exc( + self.builder, exc_class, exc_args, + loc=loc, func_name=self.func_ir.func_id.func_name, + ) + + def emit_environment_object(self): + """Emit a pointer to hold the Environment object. + """ + # Define global for the environment and initialize it to NULL + envname = self.context.get_env_name(self.fndesc) + self.context.declare_env_global(self.module, envname) + + def lower(self): + # Emit the Env into the module + self.emit_environment_object() + if self.generator_info is None: + self.genlower = None + self.lower_normal_function(self.fndesc) + else: + self.genlower = self.GeneratorLower(self) + self.gentype = self.genlower.gentype + + self.genlower.lower_init_func(self) + self.genlower.lower_next_func(self) + if self.gentype.has_finalizer: + self.genlower.lower_finalize_func(self) + + if config.DUMP_LLVM: + utils.dump_llvm(self.fndesc, self.module) + + # Run target specific post lowering transformation + self.context.post_lowering(self.module, self.library) + + # Materialize LLVM Module + self.library.add_ir_module(self.module) + + def extract_function_arguments(self): + self.fnargs = self.call_conv.decode_arguments(self.builder, + self.fndesc.argtypes, + self.function) + return self.fnargs + + def lower_normal_function(self, fndesc): + """ + Lower non-generator *fndesc*. + """ + self.setup_function(fndesc) + + # Init argument values + self.extract_function_arguments() + entry_block_tail = self.lower_function_body() + + # Close tail of entry block, do not emit debug metadata else the + # unconditional jump gets associated with the metadata from the function + # body end. + with debuginfo.suspend_emission(self.builder): + self.builder.position_at_end(entry_block_tail) + self.builder.branch(self.blkmap[self.firstblk]) + + def lower_function_body(self): + """ + Lower the current function's body, and return the entry block. + """ + # Init Python blocks + for offset in self.blocks: + bname = "B%s" % offset + self.blkmap[offset] = self.function.append_basic_block(bname) + + self.pre_lower() + # pre_lower() may have changed the current basic block + entry_block_tail = self.builder.basic_block + + self.debug_print("# function begin: {0}".format( + self.fndesc.unique_name)) + + # Lower all blocks + for offset, block in sorted(self.blocks.items()): + bb = self.blkmap[offset] + self.builder.position_at_end(bb) + self.debug_print(f"# lower block: {offset}") + self.lower_block(block) + self.post_lower() + return entry_block_tail + + def lower_block(self, block): + """ + Lower the given block. + """ + self.pre_block(block) + for inst in block.body: + self.loc = inst.loc + defaulterrcls = partial(LoweringError, loc=self.loc) + with new_error_context('lowering "{inst}" at {loc}', inst=inst, + loc=self.loc, errcls_=defaulterrcls): + self.lower_inst(inst) + self.post_block(block) + + def create_cpython_wrapper(self, release_gil=False): + """ + Create CPython wrapper(s) around this function (or generator). + """ + if self.genlower: + self.context.create_cpython_wrapper(self.library, + self.genlower.gendesc, + self.env, self.call_helper, + release_gil=release_gil) + self.context.create_cpython_wrapper(self.library, self.fndesc, + self.env, self.call_helper, + release_gil=release_gil) + + def create_cfunc_wrapper(self): + """ + Create C wrapper around this function. + """ + if self.genlower: + raise UnsupportedError('generator as a first-class function type') + self.context.create_cfunc_wrapper(self.library, self.fndesc, + self.env, self.call_helper) + + def setup_function(self, fndesc): + # Setup function + self.function = self.context.declare_function(self.module, fndesc) + if self.flags.dbg_optnone: + attrset = self.function.attributes + if "alwaysinline" not in attrset: + attrset.add("optnone") + attrset.add("noinline") + self.entry_block = self.function.append_basic_block('entry') + self.builder = IRBuilder(self.entry_block) + self.call_helper = self.call_conv.init_call_helper(self.builder) + + def typeof(self, varname): + return self.fndesc.typemap[varname] + + def notify_loc(self, loc: ir.Loc) -> None: + """Called when a new instruction with the given `loc` is about to be + lowered. + """ + for notify_obj in self._loc_notify_registry: + notify_obj.notify(loc) + + def debug_print(self, msg): + if config.DEBUG_JIT: + self.context.debug_print( + self.builder, f"DEBUGJIT [{self.fndesc.qualname}]: {msg}") + + def print_variable(self, msg, varname): + """Helper to emit ``print(msg, varname)`` for debugging. + + Parameters + ---------- + msg : str + Literal string to be printed. + varname : str + A variable name whose value will be printed. + """ + argtys = ( + types.literal(msg), + self.fndesc.typemap[varname] + ) + args = ( + self.context.get_dummy_value(), + self.loadvar(varname), + ) + sig = typing.signature(types.none, *argtys) + + impl = self.context.get_function(print, sig) + impl(self.builder, args) + + +class Lower(BaseLower): + GeneratorLower = generators.GeneratorLower + + def init(self): + super().init() + # find all singly assigned variables + self._find_singly_assigned_variable() + + @property + def _disable_sroa_like_opt(self): + """Flags that the SROA like optimisation that Numba performs (which + prevent alloca and subsequent load/store for locals) should be disabled. + Currently, this is conditional solely on the presence of a request for + the emission of debug information.""" + if self.flags is None: + return False + + return self.flags.debuginfo and not self.flags.dbg_directives_only + + def _find_singly_assigned_variable(self): + func_ir = self.func_ir + blocks = func_ir.blocks + + sav = set() + + if not self.func_ir.func_id.is_generator: + use_defs = compute_use_defs(blocks) + alloca_vars = must_use_alloca(blocks) + + # Compute where variables are defined + var_assign_map = defaultdict(set) + for blk, vl in use_defs.defmap.items(): + for var in vl: + var_assign_map[var].add(blk) + + # Compute where variables are used + var_use_map = defaultdict(set) + for blk, vl in use_defs.usemap.items(): + for var in vl: + var_use_map[var].add(blk) + + # Compute number of assignments per variable per block so these + # can be accessed efficiently in next loop + assigns_by_defblk = {k: v.find_insts(ir.Assign) + for k,v in self.blocks.items()} + num_assigns_by_defblk_and_var = {} + for defblk, assign_stmts in assigns_by_defblk.items(): + num_assigns_for_blk = defaultdict(int) + for stmt in assign_stmts: + num_assigns_for_blk[stmt.target.name] += 1 + num_assigns_by_defblk_and_var[defblk] = num_assigns_for_blk + + # Keep only variables that are defined locally and used locally + for var in var_assign_map: + if var not in alloca_vars and len(var_assign_map[var]) == 1: + # Usemap does not keep locally defined variables. + if len(var_use_map[var]) == 0: + [defblk] = var_assign_map[var] + # Ensure that the variable is not defined multiple + # times in the block + if num_assigns_by_defblk_and_var[defblk][var] == 1: + sav.add(var) + + self._singly_assigned_vars = sav + self._blk_local_varmap = {} + + def pre_block(self, block): + from numba.core.unsafe import eh + + super(Lower, self).pre_block(block) + self._cur_ir_block = block + + if block == self.firstblk: + # create slots for all the vars, irrespective of whether they are + # initialized, SSA will pick this up and warn users about using + # uninitialized variables. Slots are added as alloca in the first + # block + bb = self.blkmap[self.firstblk] + self.builder.position_at_end(bb) + all_names = set() + for block in self.blocks.values(): + for x in block.find_insts(ir.Del): + if x.value not in all_names: + all_names.add(x.value) + for name in all_names: + fetype = self.typeof(name) + self._alloca_var(name, fetype) + + # Detect if we are in a TRY block by looking for a call to + # `eh.exception_check`. + for call in block.find_exprs(op='call'): + defn = ir_utils.guard( + ir_utils.get_definition, self.func_ir, call.func, + ) + if defn is not None and isinstance(defn, ir.Global): + if defn.value is eh.exception_check: + if isinstance(block.terminator, ir.Branch): + targetblk = self.blkmap[block.terminator.truebr] + # NOTE: This hacks in an attribute for call_conv to + # pick up. This hack is no longer needed when + # all old-style implementations are gone. + self.builder._in_try_block = {'target': targetblk} + break + + def post_block(self, block): + # Clean-up + try: + del self.builder._in_try_block + except AttributeError: + pass + + def lower_inst(self, inst): + # Set debug location for all subsequent LL instructions + self.debuginfo.mark_location(self.builder, self.loc.line) + self.notify_loc(self.loc) + self.debug_print(str(inst)) + if isinstance(inst, ir.Assign): + ty = self.typeof(inst.target.name) + val = self.lower_assign(ty, inst) + argidx = None + # If this is a store from an arg, like x = arg.x then tell debuginfo + # that this is the arg + if isinstance(inst.value, ir.Arg): + # NOTE: debug location is the `def ` line + self.debuginfo.mark_location(self.builder, self.defn_loc.line) + argidx = inst.value.index + 1 # args start at 1 + self.storevar(val, inst.target.name, argidx=argidx) + + elif isinstance(inst, ir.Branch): + cond = self.loadvar(inst.cond.name) + tr = self.blkmap[inst.truebr] + fl = self.blkmap[inst.falsebr] + + condty = self.typeof(inst.cond.name) + pred = self.context.cast(self.builder, cond, condty, types.boolean) + assert pred.type == llvmlite.ir.IntType(1),\ + ("cond is not i1: %s" % pred.type) + self.builder.cbranch(pred, tr, fl) + + elif isinstance(inst, ir.Jump): + target = self.blkmap[inst.target] + self.builder.branch(target) + + elif isinstance(inst, ir.Return): + if self.generator_info: + # StopIteration + self.genlower.return_from_generator(self) + return + val = self.loadvar(inst.value.name) + oty = self.typeof(inst.value.name) + ty = self.fndesc.restype + if isinstance(ty, types.Optional): + # If returning an optional type + self.call_conv.return_optional_value(self.builder, ty, oty, val) + return + assert ty == oty, ( + "type '{}' does not match return type '{}'".format(oty, ty)) + retval = self.context.get_return_value(self.builder, ty, val) + self.call_conv.return_value(self.builder, retval) + + elif isinstance(inst, ir.PopBlock): + pass # this is just a marker + + elif isinstance(inst, ir.StaticSetItem): + signature = self.fndesc.calltypes[inst] + assert signature is not None + try: + impl = self.context.get_function('static_setitem', signature) + except NotImplementedError: + return self.lower_setitem(inst.target, inst.index_var, + inst.value, signature) + else: + target = self.loadvar(inst.target.name) + value = self.loadvar(inst.value.name) + valuety = self.typeof(inst.value.name) + value = self.context.cast(self.builder, value, valuety, + signature.args[2]) + return impl(self.builder, (target, inst.index, value)) + + elif isinstance(inst, ir.Print): + self.lower_print(inst) + + elif isinstance(inst, ir.SetItem): + signature = self.fndesc.calltypes[inst] + assert signature is not None + return self.lower_setitem(inst.target, inst.index, inst.value, + signature) + + elif isinstance(inst, ir.StoreMap): + signature = self.fndesc.calltypes[inst] + assert signature is not None + return self.lower_setitem(inst.dct, inst.key, inst.value, signature) + + elif isinstance(inst, ir.DelItem): + target = self.loadvar(inst.target.name) + index = self.loadvar(inst.index.name) + + targetty = self.typeof(inst.target.name) + indexty = self.typeof(inst.index.name) + + signature = self.fndesc.calltypes[inst] + assert signature is not None + + op = operator.delitem + fnop = self.context.typing_context.resolve_value_type(op) + callsig = fnop.get_call_type( + self.context.typing_context, signature.args, {}, + ) + impl = self.context.get_function(fnop, callsig) + + assert targetty == signature.args[0] + index = self.context.cast(self.builder, index, indexty, + signature.args[1]) + + return impl(self.builder, (target, index)) + + elif isinstance(inst, ir.Del): + self.delvar(inst.value) + + elif isinstance(inst, ir.SetAttr): + target = self.loadvar(inst.target.name) + value = self.loadvar(inst.value.name) + signature = self.fndesc.calltypes[inst] + + targetty = self.typeof(inst.target.name) + valuety = self.typeof(inst.value.name) + assert signature is not None + assert signature.args[0] == targetty + impl = self.context.get_setattr(inst.attr, signature) + + # Convert argument to match + value = self.context.cast(self.builder, value, valuety, + signature.args[1]) + + return impl(self.builder, (target, value)) + + elif isinstance(inst, ir.DynamicRaise): + self.lower_dynamic_raise(inst) + + elif isinstance(inst, ir.DynamicTryRaise): + self.lower_try_dynamic_raise(inst) + + elif isinstance(inst, ir.StaticRaise): + self.lower_static_raise(inst) + + elif isinstance(inst, ir.StaticTryRaise): + self.lower_static_try_raise(inst) + + else: + raise NotImplementedError(type(inst)) + + def lower_setitem(self, target_var, index_var, value_var, signature): + target = self.loadvar(target_var.name) + value = self.loadvar(value_var.name) + index = self.loadvar(index_var.name) + + targetty = self.typeof(target_var.name) + valuety = self.typeof(value_var.name) + indexty = self.typeof(index_var.name) + + op = operator.setitem + fnop = self.context.typing_context.resolve_value_type(op) + callsig = fnop.get_call_type( + self.context.typing_context, signature.args, {}, + ) + impl = self.context.get_function(fnop, callsig) + + # Convert argument to match + if isinstance(targetty, types.Optional): + target = self.context.cast(self.builder, target, targetty, + targetty.type) + else: + ul = types.unliteral + assert ul(targetty) == ul(signature.args[0]) + + index = self.context.cast(self.builder, index, indexty, + signature.args[1]) + value = self.context.cast(self.builder, value, valuety, + signature.args[2]) + + return impl(self.builder, (target, index, value)) + + def lower_try_dynamic_raise(self, inst): + # Numba is a bit limited in what it can do with exceptions in a try + # block. Thus, it is safe to use the same code as the static try raise. + self.lower_static_try_raise(inst) + + def lower_dynamic_raise(self, inst): + exc_args = inst.exc_args + args = [] + nb_types = [] + for exc_arg in exc_args: + if isinstance(exc_arg, ir.Var): + # dynamic values + typ = self.typeof(exc_arg.name) + val = self.loadvar(exc_arg.name) + self.incref(typ, val) + else: + typ = None + val = exc_arg + nb_types.append(typ) + args.append(val) + + self.return_dynamic_exception(inst.exc_class, tuple(args), + tuple(nb_types), loc=self.loc) + + def lower_static_raise(self, inst): + if inst.exc_class is None: + # Reraise + self.return_exception(None, loc=self.loc) + else: + self.return_exception(inst.exc_class, inst.exc_args, loc=self.loc) + + def lower_static_try_raise(self, inst): + if inst.exc_class is None: + # Reraise + self.set_exception(None, loc=self.loc) + else: + self.set_exception(inst.exc_class, inst.exc_args, loc=self.loc) + + def lower_assign(self, ty, inst): + value = inst.value + # In nopython mode, closure vars are frozen like globals + if isinstance(value, (ir.Const, ir.Global, ir.FreeVar)): + res = self.context.get_constant_generic(self.builder, ty, + value.value) + self.incref(ty, res) + return res + + elif isinstance(value, ir.Expr): + return self.lower_expr(ty, value) + + elif isinstance(value, ir.Var): + val = self.loadvar(value.name) + oty = self.typeof(value.name) + res = self.context.cast(self.builder, val, oty, ty) + self.incref(ty, res) + return res + + elif isinstance(value, ir.Arg): + # Suspend debug info else all the arg repacking ends up being + # associated with some line or other and it's actually just a detail + # of Numba's CC. + with debuginfo.suspend_emission(self.builder): + # Cast from the argument type to the local variable type + # (note the "arg.FOO" convention as used in typeinfer) + argty = self.typeof("arg." + value.name) + if isinstance(argty, types.Omitted): + pyval = argty.value + tyctx = self.context.typing_context + valty = tyctx.resolve_value_type_prefer_literal(pyval) + # use the type of the constant value + const = self.context.get_constant_generic( + self.builder, valty, pyval, + ) + # cast it to the variable type + res = self.context.cast(self.builder, const, valty, ty) + else: + val = self.fnargs[value.index] + res = self.context.cast(self.builder, val, argty, ty) + self.incref(ty, res) + return res + + elif isinstance(value, ir.Yield): + res = self.lower_yield(ty, value) + self.incref(ty, res) + return res + + raise NotImplementedError(type(value), value) + + def lower_yield(self, retty, inst): + yp = self.generator_info.yield_points[inst.index] + assert yp.inst is inst + y = generators.LowerYield(self, yp, yp.live_vars) + y.lower_yield_suspend() + # Yield to caller + val = self.loadvar(inst.value.name) + typ = self.typeof(inst.value.name) + actual_rettyp = self.gentype.yield_type + + # cast the local val to the type yielded + yret = self.context.cast(self.builder, val, typ, actual_rettyp) + + # get the return repr of yielded value + retval = self.context.get_return_value( + self.builder, actual_rettyp, yret, + ) + + # return + self.call_conv.return_value(self.builder, retval) + + # Resumption point + y.lower_yield_resume() + # None is returned by the yield expression + return self.context.get_constant_generic(self.builder, retty, None) + + def lower_binop(self, resty, expr, op): + # if op in utils.OPERATORS_TO_BUILTINS: + # map operator.the_op => the corresponding types.Function() + # TODO: is this looks dodgy ... + op = self.context.typing_context.resolve_value_type(op) + + lhs = expr.lhs + rhs = expr.rhs + static_lhs = expr.static_lhs + static_rhs = expr.static_rhs + lty = self.typeof(lhs.name) + rty = self.typeof(rhs.name) + lhs = self.loadvar(lhs.name) + rhs = self.loadvar(rhs.name) + + # Convert argument to match + signature = self.fndesc.calltypes[expr] + lhs = self.context.cast(self.builder, lhs, lty, signature.args[0]) + rhs = self.context.cast(self.builder, rhs, rty, signature.args[1]) + + def cast_result(res): + return self.context.cast(self.builder, res, + signature.return_type, resty) + + # First try with static operands, if known + def try_static_impl(tys, args): + if any(a is ir.UNDEFINED for a in args): + return None + try: + if isinstance(op, types.Function): + static_sig = op.get_call_type(self.context.typing_context, + tys, {}) + else: + static_sig = typing.signature(signature.return_type, *tys) + except TypingError: + return None + try: + static_impl = self.context.get_function(op, static_sig) + return static_impl(self.builder, args) + except NotImplementedError: + return None + + res = try_static_impl( + (_lit_or_omitted(static_lhs), _lit_or_omitted(static_rhs)), + (static_lhs, static_rhs), + ) + if res is not None: + return cast_result(res) + + res = try_static_impl( + (_lit_or_omitted(static_lhs), rty), + (static_lhs, rhs), + ) + if res is not None: + return cast_result(res) + + res = try_static_impl( + (lty, _lit_or_omitted(static_rhs)), + (lhs, static_rhs), + ) + if res is not None: + return cast_result(res) + + # Normal implementation for generic arguments + + sig = op.get_call_type(self.context.typing_context, signature.args, {}) + impl = self.context.get_function(op, sig) + res = impl(self.builder, (lhs, rhs)) + return cast_result(res) + + def lower_getitem(self, resty, expr, value, index, signature): + baseval = self.loadvar(value.name) + indexval = self.loadvar(index.name) + # Get implementation of getitem + op = operator.getitem + fnop = self.context.typing_context.resolve_value_type(op) + callsig = fnop.get_call_type( + self.context.typing_context, signature.args, {}, + ) + impl = self.context.get_function(fnop, callsig) + + argvals = (baseval, indexval) + argtyps = (self.typeof(value.name), + self.typeof(index.name)) + castvals = [self.context.cast(self.builder, av, at, ft) + for av, at, ft in zip(argvals, argtyps, + signature.args)] + res = impl(self.builder, castvals) + return self.context.cast(self.builder, res, + signature.return_type, + resty) + + def _cast_var(self, var, ty): + """ + Cast a Numba IR variable to the given Numba type, returning a + low-level value. + """ + if isinstance(var, _VarArgItem): + varty = self.typeof(var.vararg.name)[var.index] + val = self.builder.extract_value(self.loadvar(var.vararg.name), + var.index) + else: + varty = self.typeof(var.name) + val = self.loadvar(var.name) + return self.context.cast(self.builder, val, varty, ty) + + def fold_call_args(self, fnty, signature, pos_args, vararg, kw_args): + if vararg: + # Inject *args from function call + # The lowering will be done in _cast_var() above. + tp_vararg = self.typeof(vararg.name) + assert isinstance(tp_vararg, types.BaseTuple) + pos_args = pos_args + [_VarArgItem(vararg, i) + for i in range(len(tp_vararg))] + + # Fold keyword arguments and resolve default argument values + pysig = signature.pysig + if pysig is None: + if kw_args: + raise NotImplementedError("unsupported keyword arguments " + "when calling %s" % (fnty,)) + argvals = [self._cast_var(var, sigty) + for var, sigty in zip(pos_args, signature.args)] + else: + def normal_handler(index, param, var): + return self._cast_var(var, signature.args[index]) + + def default_handler(index, param, default): + return self.context.get_constant_generic( + self.builder, signature.args[index], default) + + def stararg_handler(index, param, vars): + stararg_ty = signature.args[index] + assert isinstance(stararg_ty, types.BaseTuple), stararg_ty + values = [self._cast_var(var, sigty) + for var, sigty in zip(vars, stararg_ty)] + return cgutils.make_anonymous_struct(self.builder, values) + + argvals = typing.fold_arguments(pysig, + pos_args, dict(kw_args), + normal_handler, + default_handler, + stararg_handler) + return argvals + + def lower_print(self, inst): + """ + Lower a ir.Print() + """ + # We handle this, as far as possible, as a normal call to built-in + # print(). This will make it easy to undo the special ir.Print + # rewrite when it becomes unnecessary (e.g. when we have native + # strings). + sig = self.fndesc.calltypes[inst] + assert sig.return_type == types.none + fnty = self.context.typing_context.resolve_value_type(print) + + # Fix the call signature to inject any constant-inferred + # string argument + pos_tys = list(sig.args) + pos_args = list(inst.args) + for i in range(len(pos_args)): + if i in inst.consts: + pyval = inst.consts[i] + if isinstance(pyval, str): + pos_tys[i] = types.literal(pyval) + + fixed_sig = typing.signature(sig.return_type, *pos_tys) + fixed_sig = fixed_sig.replace(pysig=sig.pysig) + + argvals = self.fold_call_args(fnty, sig, pos_args, inst.vararg, {}) + impl = self.context.get_function(print, fixed_sig) + impl(self.builder, argvals) + + def lower_call(self, resty, expr): + signature = self.fndesc.calltypes[expr] + self.debug_print("# lower_call: expr = {0}".format(expr)) + if isinstance(signature.return_type, types.Phantom): + return self.context.get_dummy_value() + + fnty = self.typeof(expr.func.name) + + if isinstance(fnty, types.ObjModeDispatcher): + res = self._lower_call_ObjModeDispatcher(fnty, expr, signature) + + elif isinstance(fnty, types.ExternalFunction): + res = self._lower_call_ExternalFunction(fnty, expr, signature) + + elif isinstance(fnty, types.ExternalFunctionPointer): + res = self._lower_call_ExternalFunctionPointer( + fnty, expr, signature) + + elif isinstance(fnty, types.RecursiveCall): + res = self._lower_call_RecursiveCall(fnty, expr, signature) + + elif isinstance(fnty, types.FunctionType): + res = self._lower_call_FunctionType(fnty, expr, signature) + + else: + res = self._lower_call_normal(fnty, expr, signature) + + # If lowering the call returned None, interpret that as returning dummy + # value if the return type of the function is void, otherwise there is + # a problem + if res is None: + if signature.return_type == types.void: + res = self.context.get_dummy_value() + else: + raise LoweringError( + msg="non-void function returns None from implementation", + loc=self.loc + ) + + return self.context.cast(self.builder, res, signature.return_type, + resty) + + def _lower_call_ObjModeDispatcher(self, fnty, expr, signature): + from numba.core.pythonapi import ObjModeUtils + + self.init_pyapi() + # Acquire the GIL + gil_state = self.pyapi.gil_ensure() + # Fix types + argnames = [a.name for a in expr.args] + argtypes = [self.typeof(a) for a in argnames] + argvalues = [self.loadvar(a) for a in argnames] + for v, ty in zip(argvalues, argtypes): + # Because .from_native_value steal the reference + self.incref(ty, v) + + argobjs = [self.pyapi.from_native_value(atyp, aval, + self.env_manager) + for atyp, aval in zip(argtypes, argvalues)] + + # Load objmode dispatcher + callee = ObjModeUtils(self.pyapi).load_dispatcher(fnty, argtypes) + # Make Call + ret_obj = self.pyapi.call_function_objargs(callee, argobjs) + has_exception = cgutils.is_null(self.builder, ret_obj) + with self. builder.if_else(has_exception) as (then, orelse): + # Handles exception + # This branch must exit the function + with then: + # Clean arg + for obj in argobjs: + self.pyapi.decref(obj) + + # Release the GIL + self.pyapi.gil_release(gil_state) + + # Return and signal exception + self.call_conv.return_exc(self.builder) + + # Handles normal return + with orelse: + # Fix output value + native = self.pyapi.to_native_value( + fnty.dispatcher.output_types, + ret_obj, + ) + output = native.value + + # Release objs + self.pyapi.decref(ret_obj) + for obj in argobjs: + self.pyapi.decref(obj) + + # cleanup output + if callable(native.cleanup): + native.cleanup() + + # Release the GIL + self.pyapi.gil_release(gil_state) + + # Error during unboxing + with self.builder.if_then(native.is_error): + self.call_conv.return_exc(self.builder) + + return output + + def _lower_call_ExternalFunction(self, fnty, expr, signature): + # Handle a named external function + self.debug_print("# external function") + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + fndesc = funcdesc.ExternalFunctionDescriptor( + fnty.symbol, fnty.sig.return_type, fnty.sig.args) + func = self.context.declare_external_function( + self.builder.module, fndesc) + return self.context.call_external_function( + self.builder, func, fndesc.argtypes, argvals, + ) + + def _lower_call_ExternalFunctionPointer(self, fnty, expr, signature): + # Handle a C function pointer + self.debug_print("# calling external function pointer") + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + pointer = self.loadvar(expr.func.name) + # If the external function pointer uses libpython + if fnty.requires_gil: + self.init_pyapi() + # Acquire the GIL + gil_state = self.pyapi.gil_ensure() + # Make PyObjects + newargvals = [] + pyvals = [] + for exptyp, gottyp, aval in zip(fnty.sig.args, signature.args, + argvals): + # Adjust argument values to pyobjects + if exptyp == types.ffi_forced_object: + self.incref(gottyp, aval) + obj = self.pyapi.from_native_value( + gottyp, aval, self.env_manager, + ) + newargvals.append(obj) + pyvals.append(obj) + else: + newargvals.append(aval) + + # Call external function + res = self.context.call_function_pointer( + self.builder, pointer, newargvals, fnty.cconv, + ) + # Release PyObjects + for obj in pyvals: + self.pyapi.decref(obj) + + # Release the GIL + self.pyapi.gil_release(gil_state) + # If the external function pointer does NOT use libpython + else: + res = self.context.call_function_pointer( + self.builder, pointer, argvals, fnty.cconv, + ) + return res + + def _lower_call_RecursiveCall(self, fnty, expr, signature): + # Recursive call + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + rec_ov = fnty.get_overloads(signature.args) + mangler = self.context.mangler or default_mangler + abi_tags = self.fndesc.abi_tags + mangled_name = mangler(rec_ov.qualname, signature.args, + abi_tags=abi_tags, uid=rec_ov.uid) + # special case self recursion + if self.builder.function.name.startswith(mangled_name): + res = self.context.call_internal( + self.builder, self.fndesc, signature, argvals, + ) + else: + res = self.context.call_unresolved( + self.builder, mangled_name, signature, argvals, + ) + return res + + def _lower_call_FunctionType(self, fnty, expr, signature): + self.debug_print("# calling first-class function type") + sig = types.unliteral(signature) + if not fnty.check_signature(signature): + # value dependent polymorphism? + raise UnsupportedError( + f'mismatch of function types:' + f' expected {fnty} but got {types.FunctionType(sig)}') + argvals = self.fold_call_args( + fnty, sig, expr.args, expr.vararg, expr.kws, + ) + return self.__call_first_class_function_pointer( + fnty.ftype, expr.func.name, sig, argvals, + ) + + def __call_first_class_function_pointer(self, ftype, fname, sig, argvals): + """ + Calls a first-class function pointer. + + This function is responsible for calling a first-class function pointer, + which can either be a JIT-compiled function or a Python function. It + determines if a JIT address is available, and if so, calls the function + using the JIT address. Otherwise, it calls the function using a function + pointer obtained from the `__get_first_class_function_pointer` method. + + Args: + ftype: The type of the function. + fname: The name of the function. + sig: The signature of the function. + argvals: The argument values to pass to the function. + + Returns: + The result of calling the function. + """ + context = self.context + builder = self.builder + # Determine if jit address is available + fstruct = self.loadvar(fname) + struct = cgutils.create_struct_proxy(self.typeof(fname))( + context, builder, value=fstruct + ) + jit_addr = struct.jit_addr + jit_addr.name = f'jit_addr_of_{fname}' + + ctx = context + res_slot = cgutils.alloca_once(builder, + ctx.get_value_type(sig.return_type)) + + if_jit_addr_is_null = builder.if_else( + cgutils.is_null(builder, jit_addr), + likely=False + ) + with if_jit_addr_is_null as (then, orelse): + with then: + func_ptr = self.__get_first_class_function_pointer( + ftype, fname, sig) + res = builder.call(func_ptr, argvals) + builder.store(res, res_slot) + + with orelse: + llty = ctx.call_conv.get_function_type( + sig.return_type, + sig.args + ).as_pointer() + func_ptr = builder.bitcast(jit_addr, llty) + # call + status, res = ctx.call_conv.call_function( + builder, func_ptr, sig.return_type, sig.args, argvals + ) + with cgutils.if_unlikely(builder, status.is_error): + context.call_conv.return_status_propagate(builder, status) + builder.store(res, res_slot) + return builder.load(res_slot) + + def __get_first_class_function_pointer(self, ftype, fname, sig): + from numba.experimental.function_type import lower_get_wrapper_address + + llty = self.context.get_value_type(ftype) + fstruct = self.loadvar(fname) + addr = self.builder.extract_value(fstruct, 0, + name='addr_of_%s' % (fname)) + + fptr = cgutils.alloca_once(self.builder, llty, + name="fptr_of_%s" % (fname)) + with self.builder.if_else( + cgutils.is_null(self.builder, addr), + likely=False) as (then, orelse): + with then: + self.init_pyapi() + # Acquire the GIL + gil_state = self.pyapi.gil_ensure() + pyaddr = self.builder.extract_value( + fstruct, 1, + name='pyaddr_of_%s' % (fname)) + # try to recover the function address, see + # test_zero_address BadToGood example in + # test_function_type.py + addr1 = lower_get_wrapper_address( + self.context, self.builder, pyaddr, sig, + failure_mode='ignore') + with self.builder.if_then( + cgutils.is_null(self.builder, addr1), likely=False): + self.return_exception( + RuntimeError, + exc_args=(f"{ftype} function address is null",), + loc=self.loc) + addr2 = self.pyapi.long_as_voidptr(addr1) + self.builder.store(self.builder.bitcast(addr2, llty), fptr) + self.pyapi.decref(addr1) + self.pyapi.gil_release(gil_state) + with orelse: + self.builder.store(self.builder.bitcast(addr, llty), fptr) + return self.builder.load(fptr) + + def _lower_call_normal(self, fnty, expr, signature): + # Normal function resolution + self.debug_print("# calling normal function: {0}".format(fnty)) + self.debug_print("# signature: {0}".format(signature)) + if isinstance(fnty, types.ObjModeDispatcher): + argvals = expr.func.args + else: + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + tname = expr.target + if tname is not None: + from numba.core.target_extension import resolve_dispatcher_from_str + disp = resolve_dispatcher_from_str(tname) + hw_ctx = disp.targetdescr.target_context + impl = hw_ctx.get_function(fnty, signature) + else: + impl = self.context.get_function(fnty, signature) + if signature.recvr: + # The "self" object is passed as the function object + # for bounded function + the_self = self.loadvar(expr.func.name) + # Prepend the self reference + argvals = [the_self] + list(argvals) + + res = impl(self.builder, argvals, self.loc) + return res + + def lower_expr(self, resty, expr): + if expr.op == 'binop': + return self.lower_binop(resty, expr, expr.fn) + elif expr.op == 'inplace_binop': + lty = self.typeof(expr.lhs.name) + if lty.mutable: + return self.lower_binop(resty, expr, expr.fn) + else: + # inplace operators on non-mutable types reuse the same + # definition as the corresponding copying operators.) + return self.lower_binop(resty, expr, expr.immutable_fn) + elif expr.op == 'unary': + val = self.loadvar(expr.value.name) + typ = self.typeof(expr.value.name) + func_ty = self.context.typing_context.resolve_value_type(expr.fn) + # Get function + signature = self.fndesc.calltypes[expr] + impl = self.context.get_function(func_ty, signature) + # Convert argument to match + val = self.context.cast(self.builder, val, typ, signature.args[0]) + res = impl(self.builder, [val]) + res = self.context.cast(self.builder, res, + signature.return_type, resty) + return res + + elif expr.op == 'call': + res = self.lower_call(resty, expr) + return res + + elif expr.op == 'pair_first': + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + res = self.context.pair_first(self.builder, val, ty) + self.incref(resty, res) + return res + + elif expr.op == 'pair_second': + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + res = self.context.pair_second(self.builder, val, ty) + self.incref(resty, res) + return res + + elif expr.op in ('getiter', 'iternext'): + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + signature = self.fndesc.calltypes[expr] + impl = self.context.get_function(expr.op, signature) + [fty] = signature.args + castval = self.context.cast(self.builder, val, ty, fty) + res = impl(self.builder, (castval,)) + res = self.context.cast(self.builder, res, signature.return_type, + resty) + return res + + elif expr.op == 'exhaust_iter': + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + # Unpack optional + if isinstance(ty, types.Optional): + val = self.context.cast(self.builder, val, ty, ty.type) + ty = ty.type + + # If we have a tuple, we needn't do anything + # (and we can't iterate over the heterogeneous ones). + if isinstance(ty, types.BaseTuple): + assert ty == resty + self.incref(ty, val) + return val + + itemty = ty.iterator_type.yield_type + tup = self.context.get_constant_undef(resty) + pairty = types.Pair(itemty, types.boolean) + getiter_sig = typing.signature(ty.iterator_type, ty) + getiter_impl = self.context.get_function('getiter', + getiter_sig) + iternext_sig = typing.signature(pairty, ty.iterator_type) + iternext_impl = self.context.get_function('iternext', + iternext_sig) + iterobj = getiter_impl(self.builder, (val,)) + # We call iternext() as many times as desired (`expr.count`). + for i in range(expr.count): + pair = iternext_impl(self.builder, (iterobj,)) + is_valid = self.context.pair_second(self.builder, + pair, pairty) + with cgutils.if_unlikely(self.builder, + self.builder.not_(is_valid)): + self.return_exception(ValueError, loc=self.loc) + item = self.context.pair_first(self.builder, + pair, pairty) + tup = self.builder.insert_value(tup, item, i) + + # Call iternext() once more to check that the iterator + # is exhausted. + pair = iternext_impl(self.builder, (iterobj,)) + is_valid = self.context.pair_second(self.builder, + pair, pairty) + with cgutils.if_unlikely(self.builder, is_valid): + self.return_exception(ValueError, loc=self.loc) + + self.decref(ty.iterator_type, iterobj) + return tup + + elif expr.op == "getattr": + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + + if isinstance(resty, types.BoundFunction): + # if we are getting out a method, assume we have typed this + # properly and just build a bound function object + casted = self.context.cast(self.builder, val, ty, resty.this) + res = self.context.get_bound_function(self.builder, casted, + resty.this) + self.incref(resty, res) + return res + else: + impl = self.context.get_getattr(ty, expr.attr) + attrty = self.context.typing_context.resolve_getattr(ty, + expr.attr) + + if impl is None: + # ignore the attribute + return self.context.get_dummy_value() + else: + res = impl(self.context, self.builder, ty, val, expr.attr) + + # Cast the attribute type to the expected output type + res = self.context.cast(self.builder, res, attrty, resty) + return res + + elif expr.op == "static_getitem": + signature = typing.signature( + resty, + self.typeof(expr.value.name), + _lit_or_omitted(expr.index), + ) + try: + # Both get_function() and the returned implementation can + # raise NotImplementedError if the types aren't supported + impl = self.context.get_function("static_getitem", signature) + return impl(self.builder, + (self.loadvar(expr.value.name), expr.index)) + except NotImplementedError: + if expr.index_var is None: + raise + # Fall back on the generic getitem() implementation + # for this type. + signature = self.fndesc.calltypes[expr] + return self.lower_getitem(resty, expr, expr.value, + expr.index_var, signature) + elif expr.op == "typed_getitem": + signature = typing.signature( + resty, + self.typeof(expr.value.name), + self.typeof(expr.index.name), + ) + impl = self.context.get_function("typed_getitem", signature) + return impl(self.builder, (self.loadvar(expr.value.name), + self.loadvar(expr.index.name))) + elif expr.op == "getitem": + signature = self.fndesc.calltypes[expr] + return self.lower_getitem(resty, expr, expr.value, expr.index, + signature) + + elif expr.op == "build_tuple": + itemvals = [self.loadvar(i.name) for i in expr.items] + itemtys = [self.typeof(i.name) for i in expr.items] + castvals = [self.context.cast(self.builder, val, fromty, toty) + for val, toty, fromty in zip(itemvals, resty, itemtys)] + tup = self.context.make_tuple(self.builder, resty, castvals) + self.incref(resty, tup) + return tup + + elif expr.op == "build_list": + itemvals = [self.loadvar(i.name) for i in expr.items] + itemtys = [self.typeof(i.name) for i in expr.items] + if isinstance(resty, types.LiteralList): + castvals = [self.context.cast(self.builder, val, fromty, toty) + for val, toty, fromty in zip(itemvals, resty.types, + itemtys)] + tup = self.context.make_tuple(self.builder, + types.Tuple(resty.types), + castvals) + self.incref(resty, tup) + return tup + else: + castvals = [self.context.cast(self.builder, val, fromty, + resty.dtype) + for val, fromty in zip(itemvals, itemtys)] + return self.context.build_list(self.builder, resty, castvals) + + elif expr.op == "build_set": + # Insert in reverse order, as Python does + items = expr.items[::-1] + itemvals = [self.loadvar(i.name) for i in items] + itemtys = [self.typeof(i.name) for i in items] + castvals = [self.context.cast(self.builder, val, fromty, + resty.dtype) + for val, fromty in zip(itemvals, itemtys)] + return self.context.build_set(self.builder, resty, castvals) + + elif expr.op == "build_map": + items = expr.items + keys, values = [], [] + key_types, value_types = [], [] + for k, v in items: + key = self.loadvar(k.name) + keytype = self.typeof(k.name) + val = self.loadvar(v.name) + valtype = self.typeof(v.name) + keys.append(key) + values.append(val) + key_types.append(keytype) + value_types.append(valtype) + return self.context.build_map(self.builder, resty, + list(zip(key_types, value_types)), + list(zip(keys, values))) + + elif expr.op == "cast": + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + castval = self.context.cast(self.builder, val, ty, resty) + self.incref(resty, castval) + return castval + + elif expr.op == "phi": + raise LoweringError("PHI not stripped") + + elif expr.op == 'null': + return self.context.get_constant_null(resty) + + elif expr.op == 'undef': + # Numba does not raise an UnboundLocalError for undefined variables. + # The variable is set to zero. + return self.context.get_constant_null(resty) + + elif expr.op in self.context.special_ops: + res = self.context.special_ops[expr.op](self, expr) + return res + + raise NotImplementedError(expr) + + def _alloca_var(self, name, fetype): + """ + Ensure the given variable has an allocated stack slot (if needed). + """ + if name in self.varmap: + # quit early + return + + # If the name is used in multiple blocks or lowering with debuginfo... + if ((name not in self._singly_assigned_vars) or + self._disable_sroa_like_opt): + # If not already defined, allocate it + ptr = self.alloca(name, fetype) + # Remember the pointer + self.varmap[name] = ptr + + def getvar(self, name): + """ + Get a pointer to the given variable's slot. + """ + if not self._disable_sroa_like_opt: + assert name not in self._blk_local_varmap + assert name not in self._singly_assigned_vars + if name not in self.varmap: + # Allocate undefined variable as needed. + # NOTE: Py3.12 use of LOAD_FAST_AND_CLEAR will allow variable be + # referenced before it is defined. + self._alloca_var(name, self.typeof(name)) + return self.varmap[name] + + def loadvar(self, name): + """ + Load the given variable's value. + """ + if name in self._blk_local_varmap and not self._disable_sroa_like_opt: + return self._blk_local_varmap[name] + ptr = self.getvar(name) + + # Don't associate debuginfo with the load for a function arg else it + # creates instructions ahead of the first source line of the + # function which then causes problems with breaking on the function + # symbol (it hits the symbol, not the first line). + if name in self.func_ir.arg_names: + with debuginfo.suspend_emission(self.builder): + return self.builder.load(ptr) + else: + return self.builder.load(ptr) + + def storevar(self, value, name, argidx=None): + """ + Store the value into the given variable. + """ + fetype = self.typeof(name) + # Define if not already + self._alloca_var(name, fetype) + + # Store variable + if (name in self._singly_assigned_vars and + not self._disable_sroa_like_opt): + self._blk_local_varmap[name] = value + else: + if argidx is None: + # Clean up existing value stored in the variable, not needed + # if it's an arg + old = self.loadvar(name) + self.decref(fetype, old) + + # stack stored variable + ptr = self.getvar(name) + if value.type != ptr.type.pointee: + msg = ("Storing {value.type} to ptr of {ptr.type.pointee} " + "('{name}'). FE type {fetype}").format(value=value, + ptr=ptr, + fetype=fetype, + name=name) + raise AssertionError(msg) + + # If this store is associated with an argument to the function (i.e. + # store following reassemble from CC splatting structs as many args + # to the function) then mark this variable as such. + if argidx is not None: + with debuginfo.suspend_emission(self.builder): + self.builder.store(value, ptr) + loc = self.defn_loc # the line with `def ` + lltype = self.context.get_value_type(fetype) + sizeof = self.context.get_abi_sizeof(lltype) + datamodel = self.context.data_model_manager[fetype] + self.debuginfo.mark_variable(self.builder, ptr, name=name, + lltype=lltype, size=sizeof, + line=loc.line, datamodel=datamodel, + argidx=argidx) + else: + self.builder.store(value, ptr) + + def delvar(self, name): + """ + Delete the given variable. + """ + fetype = self.typeof(name) + + # Out-of-order + if (name not in self._blk_local_varmap and + not self._disable_sroa_like_opt): + if name in self._singly_assigned_vars: + self._singly_assigned_vars.discard(name) + + # Define if not already (may happen if the variable is deleted + # at the beginning of a loop, but only set later in the loop) + self._alloca_var(name, fetype) + + if name in self._blk_local_varmap and not self._disable_sroa_like_opt: + llval = self._blk_local_varmap[name] + self.decref(fetype, llval) + else: + ptr = self.getvar(name) + self.decref(fetype, self.builder.load(ptr)) + # Zero-fill variable to avoid double frees on subsequent dels + self.builder.store(Constant(ptr.type.pointee, None), ptr) + + def alloca(self, name, type): + lltype = self.context.get_value_type(type) + datamodel = self.context.data_model_manager[type] + return self.alloca_lltype(name, lltype, datamodel=datamodel) + + def alloca_lltype(self, name, lltype, datamodel=None): + # Is user variable? + is_uservar = not name.startswith('$') + # Allocate space for variable + aptr = cgutils.alloca_once(self.builder, lltype, + name=name, zfill=False) + + # Emit debug info for user variable + if is_uservar: + # Don't associate debuginfo with the alloca for a function arg, this + # is handled by the first store to the alloca so that repacking the + # splatted args from the CC is dealt with. + if name not in self.func_ir.arg_names: + sizeof = self.context.get_abi_sizeof(lltype) + self.debuginfo.mark_variable(self.builder, aptr, name=name, + lltype=lltype, size=sizeof, + line=self.loc.line, + datamodel=datamodel,) + return aptr + + def incref(self, typ, val): + if not self.context.enable_nrt: + return + + self.context.nrt.incref(self.builder, typ, val) + + def decref(self, typ, val): + if not self.context.enable_nrt: + return + + # do not associate decref with "use", it creates "jumpy" line info as + # the decrefs are usually where the ir.Del nodes are, which is at the + # end of the block. + with debuginfo.suspend_emission(self.builder): + self.context.nrt.decref(self.builder, typ, val) + + +def _lit_or_omitted(value): + """Returns a Literal instance if the type of value is supported; + otherwise, return `Omitted(value)`. + """ + try: + return types.literal(value) + except LiteralTypingError: + return types.Omitted(value) diff --git a/shared/package-files/3a/3a8954dea06c4c9ba9426725e34eec15391ea7167b81d50ee718b58b58814312/ScanUtils.cuh b/shared/package-files/3a/3a8954dea06c4c9ba9426725e34eec15391ea7167b81d50ee718b58b58814312/ScanUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..fd8b9e91d48815761e7234b0d6fbcaab7f62fcee --- /dev/null +++ b/shared/package-files/3a/3a8954dea06c4c9ba9426725e34eec15391ea7167b81d50ee718b58b58814312/ScanUtils.cuh @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include + +// Collection of in-kernel scan / prefix sum utilities + +namespace at::cuda { + +// Inclusive prefix sum for binary vars using intra-warp voting + +// shared memory +template +__device__ void inclusiveBinaryPrefixScan(T* smem, bool in, T* out, BinaryFunction binop) { + // Within-warp, we use warp voting. +#if defined (USE_ROCM) + unsigned long long int vote = WARP_BALLOT(in); + T index = __popcll(getLaneMaskLe() & vote); + T carry = __popcll(vote); +#else + T vote = WARP_BALLOT(in); + T index = __popc(getLaneMaskLe() & vote); + T carry = __popc(vote); +#endif + + int warp = threadIdx.x / C10_WARP_SIZE; + + // Per each warp, write out a value + if (getLaneId() == 0) { + smem[warp] = carry; + } + + __syncthreads(); + + // Sum across warps in one thread. This appears to be faster than a + // warp shuffle scan for CC 3.0+ + if (threadIdx.x == 0) { + int current = 0; + for (int i = 0; i < blockDim.x / C10_WARP_SIZE; ++i) { + T v = smem[i]; + smem[i] = binop(smem[i], current); + current = binop(current, v); + } + } + + __syncthreads(); + + // load the carry from the preceding warp + if (warp >= 1) { + index = binop(index, smem[warp - 1]); + } + + *out = index; + + if (KillWARDependency) { + __syncthreads(); + } +} + +// Exclusive prefix sum for binary vars using intra-warp voting + +// shared memory +template +__device__ void exclusiveBinaryPrefixScan(T* smem, bool in, T* out, T* carry, BinaryFunction binop) { + inclusiveBinaryPrefixScan(smem, in, out, binop); + + // Inclusive to exclusive + *out -= (T) in; + + // The outgoing carry for all threads is the last warp's sum + *carry = smem[at::ceil_div(blockDim.x, C10_WARP_SIZE) - 1]; + + if (KillWARDependency) { + __syncthreads(); + } +} + +} // namespace at::cuda diff --git a/shared/package-files/3a/3a8c1ecf7e9490ec095e44d1ab8ad5b89451af5f08b419f3fd80e3800985095f/main.py b/shared/package-files/3a/3a8c1ecf7e9490ec095e44d1ab8ad5b89451af5f08b419f3fd80e3800985095f/main.py new file mode 100644 index 0000000000000000000000000000000000000000..e5534e98d69ad4151bf1eedaadf67289d8c6278d --- /dev/null +++ b/shared/package-files/3a/3a8c1ecf7e9490ec095e44d1ab8ad5b89451af5f08b419f3fd80e3800985095f/main.py @@ -0,0 +1,1072 @@ +"""Core implementation of the testing process: init, session, runtest loop.""" + +from __future__ import annotations + +import argparse +import dataclasses +import fnmatch +import functools +import importlib +import importlib.util +import os +from pathlib import Path +import sys +from typing import AbstractSet +from typing import Callable +from typing import Dict +from typing import final +from typing import Iterable +from typing import Iterator +from typing import Literal +from typing import overload +from typing import Sequence +from typing import TYPE_CHECKING +import warnings + +import pluggy + +from _pytest import nodes +import _pytest._code +from _pytest.config import Config +from _pytest.config import directory_arg +from _pytest.config import ExitCode +from _pytest.config import hookimpl +from _pytest.config import PytestPluginManager +from _pytest.config import UsageError +from _pytest.config.argparsing import Parser +from _pytest.config.compat import PathAwareHookProxy +from _pytest.outcomes import exit +from _pytest.pathlib import absolutepath +from _pytest.pathlib import bestrelpath +from _pytest.pathlib import fnmatch_ex +from _pytest.pathlib import safe_exists +from _pytest.pathlib import scandir +from _pytest.reports import CollectReport +from _pytest.reports import TestReport +from _pytest.runner import collect_one_node +from _pytest.runner import SetupState +from _pytest.warning_types import PytestWarning + + +if TYPE_CHECKING: + from typing_extensions import Self + + from _pytest.fixtures import FixtureManager + + +def pytest_addoption(parser: Parser) -> None: + parser.addini( + "norecursedirs", + "Directory patterns to avoid for recursion", + type="args", + default=[ + "*.egg", + ".*", + "_darcs", + "build", + "CVS", + "dist", + "node_modules", + "venv", + "{arch}", + ], + ) + parser.addini( + "testpaths", + "Directories to search for tests when no files or directories are given on the " + "command line", + type="args", + default=[], + ) + group = parser.getgroup("general", "Running and selection options") + group._addoption( + "-x", + "--exitfirst", + action="store_const", + dest="maxfail", + const=1, + help="Exit instantly on first error or failed test", + ) + group = parser.getgroup("pytest-warnings") + group.addoption( + "-W", + "--pythonwarnings", + action="append", + help="Set which warnings to report, see -W option of Python itself", + ) + parser.addini( + "filterwarnings", + type="linelist", + help="Each line specifies a pattern for " + "warnings.filterwarnings. " + "Processed after -W/--pythonwarnings.", + ) + group._addoption( + "--maxfail", + metavar="num", + action="store", + type=int, + dest="maxfail", + default=0, + help="Exit after first num failures or errors", + ) + group._addoption( + "--strict-config", + action="store_true", + help="Any warnings encountered while parsing the `pytest` section of the " + "configuration file raise errors", + ) + group._addoption( + "--strict-markers", + action="store_true", + help="Markers not registered in the `markers` section of the configuration " + "file raise errors", + ) + group._addoption( + "--strict", + action="store_true", + help="(Deprecated) alias to --strict-markers", + ) + group._addoption( + "-c", + "--config-file", + metavar="FILE", + type=str, + dest="inifilename", + help="Load configuration from `FILE` instead of trying to locate one of the " + "implicit configuration files.", + ) + group._addoption( + "--continue-on-collection-errors", + action="store_true", + default=False, + dest="continue_on_collection_errors", + help="Force test execution even if collection errors occur", + ) + group._addoption( + "--rootdir", + action="store", + dest="rootdir", + help="Define root directory for tests. Can be relative path: 'root_dir', './root_dir', " + "'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: " + "'$HOME/root_dir'.", + ) + + group = parser.getgroup("collect", "collection") + group.addoption( + "--collectonly", + "--collect-only", + "--co", + action="store_true", + help="Only collect tests, don't execute them", + ) + group.addoption( + "--pyargs", + action="store_true", + help="Try to interpret all arguments as Python packages", + ) + group.addoption( + "--ignore", + action="append", + metavar="path", + help="Ignore path during collection (multi-allowed)", + ) + group.addoption( + "--ignore-glob", + action="append", + metavar="path", + help="Ignore path pattern during collection (multi-allowed)", + ) + group.addoption( + "--deselect", + action="append", + metavar="nodeid_prefix", + help="Deselect item (via node id prefix) during collection (multi-allowed)", + ) + group.addoption( + "--confcutdir", + dest="confcutdir", + default=None, + metavar="dir", + type=functools.partial(directory_arg, optname="--confcutdir"), + help="Only load conftest.py's relative to specified dir", + ) + group.addoption( + "--noconftest", + action="store_true", + dest="noconftest", + default=False, + help="Don't load any conftest.py files", + ) + group.addoption( + "--keepduplicates", + "--keep-duplicates", + action="store_true", + dest="keepduplicates", + default=False, + help="Keep duplicate tests", + ) + group.addoption( + "--collect-in-virtualenv", + action="store_true", + dest="collect_in_virtualenv", + default=False, + help="Don't ignore tests in a local virtualenv directory", + ) + group.addoption( + "--import-mode", + default="prepend", + choices=["prepend", "append", "importlib"], + dest="importmode", + help="Prepend/append to sys.path when importing test modules and conftest " + "files. Default: prepend.", + ) + parser.addini( + "consider_namespace_packages", + type="bool", + default=False, + help="Consider namespace packages when resolving module names during import", + ) + + group = parser.getgroup("debugconfig", "test session debugging and configuration") + group.addoption( + "--basetemp", + dest="basetemp", + default=None, + type=validate_basetemp, + metavar="dir", + help=( + "Base temporary directory for this test run. " + "(Warning: this directory is removed if it exists.)" + ), + ) + + +def validate_basetemp(path: str) -> str: + # GH 7119 + msg = "basetemp must not be empty, the current working directory or any parent directory of it" + + # empty path + if not path: + raise argparse.ArgumentTypeError(msg) + + def is_ancestor(base: Path, query: Path) -> bool: + """Return whether query is an ancestor of base.""" + if base == query: + return True + return query in base.parents + + # check if path is an ancestor of cwd + if is_ancestor(Path.cwd(), Path(path).absolute()): + raise argparse.ArgumentTypeError(msg) + + # check symlinks for ancestors + if is_ancestor(Path.cwd().resolve(), Path(path).resolve()): + raise argparse.ArgumentTypeError(msg) + + return path + + +def wrap_session( + config: Config, doit: Callable[[Config, Session], int | ExitCode | None] +) -> int | ExitCode: + """Skeleton command line program.""" + session = Session.from_config(config) + session.exitstatus = ExitCode.OK + initstate = 0 + try: + try: + config._do_configure() + initstate = 1 + config.hook.pytest_sessionstart(session=session) + initstate = 2 + session.exitstatus = doit(config, session) or 0 + except UsageError: + session.exitstatus = ExitCode.USAGE_ERROR + raise + except Failed: + session.exitstatus = ExitCode.TESTS_FAILED + except (KeyboardInterrupt, exit.Exception): + excinfo = _pytest._code.ExceptionInfo.from_current() + exitstatus: int | ExitCode = ExitCode.INTERRUPTED + if isinstance(excinfo.value, exit.Exception): + if excinfo.value.returncode is not None: + exitstatus = excinfo.value.returncode + if initstate < 2: + sys.stderr.write(f"{excinfo.typename}: {excinfo.value.msg}\n") + config.hook.pytest_keyboard_interrupt(excinfo=excinfo) + session.exitstatus = exitstatus + except BaseException: + session.exitstatus = ExitCode.INTERNAL_ERROR + excinfo = _pytest._code.ExceptionInfo.from_current() + try: + config.notify_exception(excinfo, config.option) + except exit.Exception as exc: + if exc.returncode is not None: + session.exitstatus = exc.returncode + sys.stderr.write(f"{type(exc).__name__}: {exc}\n") + else: + if isinstance(excinfo.value, SystemExit): + sys.stderr.write("mainloop: caught unexpected SystemExit!\n") + + finally: + # Explicitly break reference cycle. + excinfo = None # type: ignore + os.chdir(session.startpath) + if initstate >= 2: + try: + config.hook.pytest_sessionfinish( + session=session, exitstatus=session.exitstatus + ) + except exit.Exception as exc: + if exc.returncode is not None: + session.exitstatus = exc.returncode + sys.stderr.write(f"{type(exc).__name__}: {exc}\n") + config._ensure_unconfigure() + return session.exitstatus + + +def pytest_cmdline_main(config: Config) -> int | ExitCode: + return wrap_session(config, _main) + + +def _main(config: Config, session: Session) -> int | ExitCode | None: + """Default command line protocol for initialization, session, + running tests and reporting.""" + config.hook.pytest_collection(session=session) + config.hook.pytest_runtestloop(session=session) + + if session.testsfailed: + return ExitCode.TESTS_FAILED + elif session.testscollected == 0: + return ExitCode.NO_TESTS_COLLECTED + return None + + +def pytest_collection(session: Session) -> None: + session.perform_collect() + + +def pytest_runtestloop(session: Session) -> bool: + if session.testsfailed and not session.config.option.continue_on_collection_errors: + raise session.Interrupted( + "%d error%s during collection" + % (session.testsfailed, "s" if session.testsfailed != 1 else "") + ) + + if session.config.option.collectonly: + return True + + for i, item in enumerate(session.items): + nextitem = session.items[i + 1] if i + 1 < len(session.items) else None + item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) + if session.shouldfail: + raise session.Failed(session.shouldfail) + if session.shouldstop: + raise session.Interrupted(session.shouldstop) + return True + + +def _in_venv(path: Path) -> bool: + """Attempt to detect if ``path`` is the root of a Virtual Environment by + checking for the existence of the pyvenv.cfg file. + + [https://peps.python.org/pep-0405/] + + For regression protection we also check for conda environments that do not include pyenv.cfg yet -- + https://github.com/conda/conda/issues/13337 is the conda issue tracking adding pyenv.cfg. + + Checking for the `conda-meta/history` file per https://github.com/pytest-dev/pytest/issues/12652#issuecomment-2246336902. + + """ + try: + return ( + path.joinpath("pyvenv.cfg").is_file() + or path.joinpath("conda-meta", "history").is_file() + ) + except OSError: + return False + + +def pytest_ignore_collect(collection_path: Path, config: Config) -> bool | None: + if collection_path.name == "__pycache__": + return True + + ignore_paths = config._getconftest_pathlist( + "collect_ignore", path=collection_path.parent + ) + ignore_paths = ignore_paths or [] + excludeopt = config.getoption("ignore") + if excludeopt: + ignore_paths.extend(absolutepath(x) for x in excludeopt) + + if collection_path in ignore_paths: + return True + + ignore_globs = config._getconftest_pathlist( + "collect_ignore_glob", path=collection_path.parent + ) + ignore_globs = ignore_globs or [] + excludeglobopt = config.getoption("ignore_glob") + if excludeglobopt: + ignore_globs.extend(absolutepath(x) for x in excludeglobopt) + + if any(fnmatch.fnmatch(str(collection_path), str(glob)) for glob in ignore_globs): + return True + + allow_in_venv = config.getoption("collect_in_virtualenv") + if not allow_in_venv and _in_venv(collection_path): + return True + + if collection_path.is_dir(): + norecursepatterns = config.getini("norecursedirs") + if any(fnmatch_ex(pat, collection_path) for pat in norecursepatterns): + return True + + return None + + +def pytest_collect_directory( + path: Path, parent: nodes.Collector +) -> nodes.Collector | None: + return Dir.from_parent(parent, path=path) + + +def pytest_collection_modifyitems(items: list[nodes.Item], config: Config) -> None: + deselect_prefixes = tuple(config.getoption("deselect") or []) + if not deselect_prefixes: + return + + remaining = [] + deselected = [] + for colitem in items: + if colitem.nodeid.startswith(deselect_prefixes): + deselected.append(colitem) + else: + remaining.append(colitem) + + if deselected: + config.hook.pytest_deselected(items=deselected) + items[:] = remaining + + +class FSHookProxy: + def __init__( + self, + pm: PytestPluginManager, + remove_mods: AbstractSet[object], + ) -> None: + self.pm = pm + self.remove_mods = remove_mods + + def __getattr__(self, name: str) -> pluggy.HookCaller: + x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods) + self.__dict__[name] = x + return x + + +class Interrupted(KeyboardInterrupt): + """Signals that the test run was interrupted.""" + + __module__ = "builtins" # For py3. + + +class Failed(Exception): + """Signals a stop as failed test run.""" + + +@dataclasses.dataclass +class _bestrelpath_cache(Dict[Path, str]): + __slots__ = ("path",) + + path: Path + + def __missing__(self, path: Path) -> str: + r = bestrelpath(self.path, path) + self[path] = r + return r + + +@final +class Dir(nodes.Directory): + """Collector of files in a file system directory. + + .. versionadded:: 8.0 + + .. note:: + + Python directories with an `__init__.py` file are instead collected by + :class:`~pytest.Package` by default. Both are :class:`~pytest.Directory` + collectors. + """ + + @classmethod + def from_parent( # type: ignore[override] + cls, + parent: nodes.Collector, + *, + path: Path, + ) -> Self: + """The public constructor. + + :param parent: The parent collector of this Dir. + :param path: The directory's path. + :type path: pathlib.Path + """ + return super().from_parent(parent=parent, path=path) + + def collect(self) -> Iterable[nodes.Item | nodes.Collector]: + config = self.config + col: nodes.Collector | None + cols: Sequence[nodes.Collector] + ihook = self.ihook + for direntry in scandir(self.path): + if direntry.is_dir(): + path = Path(direntry.path) + if not self.session.isinitpath(path, with_parents=True): + if ihook.pytest_ignore_collect(collection_path=path, config=config): + continue + col = ihook.pytest_collect_directory(path=path, parent=self) + if col is not None: + yield col + + elif direntry.is_file(): + path = Path(direntry.path) + if not self.session.isinitpath(path): + if ihook.pytest_ignore_collect(collection_path=path, config=config): + continue + cols = ihook.pytest_collect_file(file_path=path, parent=self) + yield from cols + + +@final +class Session(nodes.Collector): + """The root of the collection tree. + + ``Session`` collects the initial paths given as arguments to pytest. + """ + + Interrupted = Interrupted + Failed = Failed + # Set on the session by runner.pytest_sessionstart. + _setupstate: SetupState + # Set on the session by fixtures.pytest_sessionstart. + _fixturemanager: FixtureManager + exitstatus: int | ExitCode + + def __init__(self, config: Config) -> None: + super().__init__( + name="", + path=config.rootpath, + fspath=None, + parent=None, + config=config, + session=self, + nodeid="", + ) + self.testsfailed = 0 + self.testscollected = 0 + self._shouldstop: bool | str = False + self._shouldfail: bool | str = False + self.trace = config.trace.root.get("collection") + self._initialpaths: frozenset[Path] = frozenset() + self._initialpaths_with_parents: frozenset[Path] = frozenset() + self._notfound: list[tuple[str, Sequence[nodes.Collector]]] = [] + self._initial_parts: list[CollectionArgument] = [] + self._collection_cache: dict[nodes.Collector, CollectReport] = {} + self.items: list[nodes.Item] = [] + + self._bestrelpathcache: dict[Path, str] = _bestrelpath_cache(config.rootpath) + + self.config.pluginmanager.register(self, name="session") + + @classmethod + def from_config(cls, config: Config) -> Session: + session: Session = cls._create(config=config) + return session + + def __repr__(self) -> str: + return "<%s %s exitstatus=%r testsfailed=%d testscollected=%d>" % ( + self.__class__.__name__, + self.name, + getattr(self, "exitstatus", ""), + self.testsfailed, + self.testscollected, + ) + + @property + def shouldstop(self) -> bool | str: + return self._shouldstop + + @shouldstop.setter + def shouldstop(self, value: bool | str) -> None: + # The runner checks shouldfail and assumes that if it is set we are + # definitely stopping, so prevent unsetting it. + if value is False and self._shouldstop: + warnings.warn( + PytestWarning( + "session.shouldstop cannot be unset after it has been set; ignoring." + ), + stacklevel=2, + ) + return + self._shouldstop = value + + @property + def shouldfail(self) -> bool | str: + return self._shouldfail + + @shouldfail.setter + def shouldfail(self, value: bool | str) -> None: + # The runner checks shouldfail and assumes that if it is set we are + # definitely stopping, so prevent unsetting it. + if value is False and self._shouldfail: + warnings.warn( + PytestWarning( + "session.shouldfail cannot be unset after it has been set; ignoring." + ), + stacklevel=2, + ) + return + self._shouldfail = value + + @property + def startpath(self) -> Path: + """The path from which pytest was invoked. + + .. versionadded:: 7.0.0 + """ + return self.config.invocation_params.dir + + def _node_location_to_relpath(self, node_path: Path) -> str: + # bestrelpath is a quite slow function. + return self._bestrelpathcache[node_path] + + @hookimpl(tryfirst=True) + def pytest_collectstart(self) -> None: + if self.shouldfail: + raise self.Failed(self.shouldfail) + if self.shouldstop: + raise self.Interrupted(self.shouldstop) + + @hookimpl(tryfirst=True) + def pytest_runtest_logreport(self, report: TestReport | CollectReport) -> None: + if report.failed and not hasattr(report, "wasxfail"): + self.testsfailed += 1 + maxfail = self.config.getvalue("maxfail") + if maxfail and self.testsfailed >= maxfail: + self.shouldfail = "stopping after %d failures" % (self.testsfailed) + + pytest_collectreport = pytest_runtest_logreport + + def isinitpath( + self, + path: str | os.PathLike[str], + *, + with_parents: bool = False, + ) -> bool: + """Is path an initial path? + + An initial path is a path explicitly given to pytest on the command + line. + + :param with_parents: + If set, also return True if the path is a parent of an initial path. + + .. versionchanged:: 8.0 + Added the ``with_parents`` parameter. + """ + # Optimization: Path(Path(...)) is much slower than isinstance. + path_ = path if isinstance(path, Path) else Path(path) + if with_parents: + return path_ in self._initialpaths_with_parents + else: + return path_ in self._initialpaths + + def gethookproxy(self, fspath: os.PathLike[str]) -> pluggy.HookRelay: + # Optimization: Path(Path(...)) is much slower than isinstance. + path = fspath if isinstance(fspath, Path) else Path(fspath) + pm = self.config.pluginmanager + # Check if we have the common case of running + # hooks with all conftest.py files. + my_conftestmodules = pm._getconftestmodules(path) + remove_mods = pm._conftest_plugins.difference(my_conftestmodules) + proxy: pluggy.HookRelay + if remove_mods: + # One or more conftests are not in use at this path. + proxy = PathAwareHookProxy(FSHookProxy(pm, remove_mods)) # type: ignore[arg-type,assignment] + else: + # All plugins are active for this fspath. + proxy = self.config.hook + return proxy + + def _collect_path( + self, + path: Path, + path_cache: dict[Path, Sequence[nodes.Collector]], + ) -> Sequence[nodes.Collector]: + """Create a Collector for the given path. + + `path_cache` makes it so the same Collectors are returned for the same + path. + """ + if path in path_cache: + return path_cache[path] + + if path.is_dir(): + ihook = self.gethookproxy(path.parent) + col: nodes.Collector | None = ihook.pytest_collect_directory( + path=path, parent=self + ) + cols: Sequence[nodes.Collector] = (col,) if col is not None else () + + elif path.is_file(): + ihook = self.gethookproxy(path) + cols = ihook.pytest_collect_file(file_path=path, parent=self) + + else: + # Broken symlink or invalid/missing file. + cols = () + + path_cache[path] = cols + return cols + + @overload + def perform_collect( + self, args: Sequence[str] | None = ..., genitems: Literal[True] = ... + ) -> Sequence[nodes.Item]: ... + + @overload + def perform_collect( + self, args: Sequence[str] | None = ..., genitems: bool = ... + ) -> Sequence[nodes.Item | nodes.Collector]: ... + + def perform_collect( + self, args: Sequence[str] | None = None, genitems: bool = True + ) -> Sequence[nodes.Item | nodes.Collector]: + """Perform the collection phase for this session. + + This is called by the default :hook:`pytest_collection` hook + implementation; see the documentation of this hook for more details. + For testing purposes, it may also be called directly on a fresh + ``Session``. + + This function normally recursively expands any collectors collected + from the session to their items, and only items are returned. For + testing purposes, this may be suppressed by passing ``genitems=False``, + in which case the return value contains these collectors unexpanded, + and ``session.items`` is empty. + """ + if args is None: + args = self.config.args + + self.trace("perform_collect", self, args) + self.trace.root.indent += 1 + + hook = self.config.hook + + self._notfound = [] + self._initial_parts = [] + self._collection_cache = {} + self.items = [] + items: Sequence[nodes.Item | nodes.Collector] = self.items + try: + initialpaths: list[Path] = [] + initialpaths_with_parents: list[Path] = [] + for arg in args: + collection_argument = resolve_collection_argument( + self.config.invocation_params.dir, + arg, + as_pypath=self.config.option.pyargs, + ) + self._initial_parts.append(collection_argument) + initialpaths.append(collection_argument.path) + initialpaths_with_parents.append(collection_argument.path) + initialpaths_with_parents.extend(collection_argument.path.parents) + self._initialpaths = frozenset(initialpaths) + self._initialpaths_with_parents = frozenset(initialpaths_with_parents) + + rep = collect_one_node(self) + self.ihook.pytest_collectreport(report=rep) + self.trace.root.indent -= 1 + if self._notfound: + errors = [] + for arg, collectors in self._notfound: + if collectors: + errors.append( + f"not found: {arg}\n(no match in any of {collectors!r})" + ) + else: + errors.append(f"found no collectors for {arg}") + + raise UsageError(*errors) + + if not genitems: + items = rep.result + else: + if rep.passed: + for node in rep.result: + self.items.extend(self.genitems(node)) + + self.config.pluginmanager.check_pending() + hook.pytest_collection_modifyitems( + session=self, config=self.config, items=items + ) + finally: + self._notfound = [] + self._initial_parts = [] + self._collection_cache = {} + hook.pytest_collection_finish(session=self) + + if genitems: + self.testscollected = len(items) + + return items + + def _collect_one_node( + self, + node: nodes.Collector, + handle_dupes: bool = True, + ) -> tuple[CollectReport, bool]: + if node in self._collection_cache and handle_dupes: + rep = self._collection_cache[node] + return rep, True + else: + rep = collect_one_node(node) + self._collection_cache[node] = rep + return rep, False + + def collect(self) -> Iterator[nodes.Item | nodes.Collector]: + # This is a cache for the root directories of the initial paths. + # We can't use collection_cache for Session because of its special + # role as the bootstrapping collector. + path_cache: dict[Path, Sequence[nodes.Collector]] = {} + + pm = self.config.pluginmanager + + for collection_argument in self._initial_parts: + self.trace("processing argument", collection_argument) + self.trace.root.indent += 1 + + argpath = collection_argument.path + names = collection_argument.parts + module_name = collection_argument.module_name + + # resolve_collection_argument() ensures this. + if argpath.is_dir(): + assert not names, f"invalid arg {(argpath, names)!r}" + + paths = [argpath] + # Add relevant parents of the path, from the root, e.g. + # /a/b/c.py -> [/, /a, /a/b, /a/b/c.py] + if module_name is None: + # Paths outside of the confcutdir should not be considered. + for path in argpath.parents: + if not pm._is_in_confcutdir(path): + break + paths.insert(0, path) + else: + # For --pyargs arguments, only consider paths matching the module + # name. Paths beyond the package hierarchy are not included. + module_name_parts = module_name.split(".") + for i, path in enumerate(argpath.parents, 2): + if i > len(module_name_parts) or path.stem != module_name_parts[-i]: + break + paths.insert(0, path) + + # Start going over the parts from the root, collecting each level + # and discarding all nodes which don't match the level's part. + any_matched_in_initial_part = False + notfound_collectors = [] + work: list[tuple[nodes.Collector | nodes.Item, list[Path | str]]] = [ + (self, [*paths, *names]) + ] + while work: + matchnode, matchparts = work.pop() + + # Pop'd all of the parts, this is a match. + if not matchparts: + yield matchnode + any_matched_in_initial_part = True + continue + + # Should have been matched by now, discard. + if not isinstance(matchnode, nodes.Collector): + continue + + # Collect this level of matching. + # Collecting Session (self) is done directly to avoid endless + # recursion to this function. + subnodes: Sequence[nodes.Collector | nodes.Item] + if isinstance(matchnode, Session): + assert isinstance(matchparts[0], Path) + subnodes = matchnode._collect_path(matchparts[0], path_cache) + else: + # For backward compat, files given directly multiple + # times on the command line should not be deduplicated. + handle_dupes = not ( + len(matchparts) == 1 + and isinstance(matchparts[0], Path) + and matchparts[0].is_file() + ) + rep, duplicate = self._collect_one_node(matchnode, handle_dupes) + if not duplicate and not rep.passed: + # Report collection failures here to avoid failing to + # run some test specified in the command line because + # the module could not be imported (#134). + matchnode.ihook.pytest_collectreport(report=rep) + if not rep.passed: + continue + subnodes = rep.result + + # Prune this level. + any_matched_in_collector = False + for node in reversed(subnodes): + # Path part e.g. `/a/b/` in `/a/b/test_file.py::TestIt::test_it`. + if isinstance(matchparts[0], Path): + is_match = node.path == matchparts[0] + if sys.platform == "win32" and not is_match: + # In case the file paths do not match, fallback to samefile() to + # account for short-paths on Windows (#11895). + same_file = os.path.samefile(node.path, matchparts[0]) + # We don't want to match links to the current node, + # otherwise we would match the same file more than once (#12039). + is_match = same_file and ( + os.path.islink(node.path) + == os.path.islink(matchparts[0]) + ) + + # Name part e.g. `TestIt` in `/a/b/test_file.py::TestIt::test_it`. + else: + # TODO: Remove parametrized workaround once collection structure contains + # parametrization. + is_match = ( + node.name == matchparts[0] + or node.name.split("[")[0] == matchparts[0] + ) + if is_match: + work.append((node, matchparts[1:])) + any_matched_in_collector = True + + if not any_matched_in_collector: + notfound_collectors.append(matchnode) + + if not any_matched_in_initial_part: + report_arg = "::".join((str(argpath), *names)) + self._notfound.append((report_arg, notfound_collectors)) + + self.trace.root.indent -= 1 + + def genitems(self, node: nodes.Item | nodes.Collector) -> Iterator[nodes.Item]: + self.trace("genitems", node) + if isinstance(node, nodes.Item): + node.ihook.pytest_itemcollected(item=node) + yield node + else: + assert isinstance(node, nodes.Collector) + keepduplicates = self.config.getoption("keepduplicates") + # For backward compat, dedup only applies to files. + handle_dupes = not (keepduplicates and isinstance(node, nodes.File)) + rep, duplicate = self._collect_one_node(node, handle_dupes) + if duplicate and not keepduplicates: + return + if rep.passed: + for subnode in rep.result: + yield from self.genitems(subnode) + if not duplicate: + node.ihook.pytest_collectreport(report=rep) + + +def search_pypath(module_name: str) -> str | None: + """Search sys.path for the given a dotted module name, and return its file + system path if found.""" + try: + spec = importlib.util.find_spec(module_name) + # AttributeError: looks like package module, but actually filename + # ImportError: module does not exist + # ValueError: not a module name + except (AttributeError, ImportError, ValueError): + return None + if spec is None or spec.origin is None or spec.origin == "namespace": + return None + elif spec.submodule_search_locations: + return os.path.dirname(spec.origin) + else: + return spec.origin + + +@dataclasses.dataclass(frozen=True) +class CollectionArgument: + """A resolved collection argument.""" + + path: Path + parts: Sequence[str] + module_name: str | None + + +def resolve_collection_argument( + invocation_path: Path, arg: str, *, as_pypath: bool = False +) -> CollectionArgument: + """Parse path arguments optionally containing selection parts and return (fspath, names). + + Command-line arguments can point to files and/or directories, and optionally contain + parts for specific tests selection, for example: + + "pkg/tests/test_foo.py::TestClass::test_foo" + + This function ensures the path exists, and returns a resolved `CollectionArgument`: + + CollectionArgument( + path=Path("/full/path/to/pkg/tests/test_foo.py"), + parts=["TestClass", "test_foo"], + module_name=None, + ) + + When as_pypath is True, expects that the command-line argument actually contains + module paths instead of file-system paths: + + "pkg.tests.test_foo::TestClass::test_foo" + + In which case we search sys.path for a matching module, and then return the *path* to the + found module, which may look like this: + + CollectionArgument( + path=Path("/home/u/myvenv/lib/site-packages/pkg/tests/test_foo.py"), + parts=["TestClass", "test_foo"], + module_name="pkg.tests.test_foo", + ) + + If the path doesn't exist, raise UsageError. + If the path is a directory and selection parts are present, raise UsageError. + """ + base, squacket, rest = str(arg).partition("[") + strpath, *parts = base.split("::") + if parts: + parts[-1] = f"{parts[-1]}{squacket}{rest}" + module_name = None + if as_pypath: + pyarg_strpath = search_pypath(strpath) + if pyarg_strpath is not None: + module_name = strpath + strpath = pyarg_strpath + fspath = invocation_path / strpath + fspath = absolutepath(fspath) + if not safe_exists(fspath): + msg = ( + "module or package not found: {arg} (missing __init__.py?)" + if as_pypath + else "file or directory not found: {arg}" + ) + raise UsageError(msg.format(arg=arg)) + if parts and fspath.is_dir(): + msg = ( + "package argument cannot contain :: selection parts: {arg}" + if as_pypath + else "directory argument cannot contain :: selection parts: {arg}" + ) + raise UsageError(msg.format(arg=arg)) + return CollectionArgument( + path=fspath, + parts=parts, + module_name=module_name, + ) diff --git a/shared/package-files/3a/3a8cfb2b308c93b7714bff74e5ed6e0f759f6d140e58d7d8ce73b767ef240fbe/avatar0 b/shared/package-files/3a/3a8cfb2b308c93b7714bff74e5ed6e0f759f6d140e58d7d8ce73b767ef240fbe/avatar0 new file mode 100644 index 0000000000000000000000000000000000000000..4a3f7f95d6c0c0922a02cf576143c92bc3317898 Binary files /dev/null and b/shared/package-files/3a/3a8cfb2b308c93b7714bff74e5ed6e0f759f6d140e58d7d8ce73b767ef240fbe/avatar0 differ diff --git a/shared/package-files/3a/3a8e0ceff719bcc5b8a7796bcf04155dc817aa19bdda99909e76fcef7065e617/functional.py b/shared/package-files/3a/3a8e0ceff719bcc5b8a7796bcf04155dc817aa19bdda99909e76fcef7065e617/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..26ef5b307bd52b7c764270ee02365e780fd32349 --- /dev/null +++ b/shared/package-files/3a/3a8e0ceff719bcc5b8a7796bcf04155dc817aa19bdda99909e76fcef7065e617/functional.py @@ -0,0 +1,187 @@ +import weakref + +import torch +import torch.utils._pytree as pytree +from torch._C import _ExcludeDispatchKeyGuard, DispatchKey, DispatchKeySet +from torch._ops import OpOverload +from torch.library import Library +from torchgen.model import ( + BaseTy, + BaseType, + FunctionSchema, + OperatorName, + OptionalType, + SchemaKind, +) + +from .autograd import autograd_not_implemented + + +def register_functional_op( + lib: Library, + new_op_name: str, + mutable_op: OpOverload, +) -> None: + """Given a mutable operator, registers the functional variant. + + This API also correctly links the functional variant with the mutable + operator for the purposes of functionalization. + + All of the new registrations are performed on the ``lib`` passed in. + + Arguments: + lib (Library): Should be a torch.library.Library object that has + the same namespace as ``mutable_op``'s namespace. + lib will be used to register the new functional op as well + as a functionalization kernel for the ``mutable_op`` + If you don't have a library handy, use + ``torch.library.Library(ns, 'FRAGMENT')`` to construct one. + new_op_name (str): The name of the functional operator (without the + namespace). If no namespace, the new functional variant will be + accessible under ``torch.ops.{lib.ns}.new_op_name``. + mutable_op (OpOverload): The mutable custom operator. Note + that you may need to add a `.default` to it, like + `torch.ops.aten.abs_.default`. + + """ + validate(mutable_op) + schema = functional_schema(new_op_name, mutable_op) + lib.define(schema) + + functional_impl = construct_functional_impl(mutable_op) + lib.impl(new_op_name, functional_impl, 'CompositeExplicitAutograd') + + functional_op = getattr(getattr(torch.ops, lib.ns), new_op_name).default + + # There's no easy way for us to generate the autograd kernel, so we + # use autograd_not_implemented. Also, this makes it so that the user + # is unable to register an autograd formula themselves. This shouldn't + # be a problem if the user doesn't use the functional op direclty + # in their program, but we may need to revist this in the future. + lib.impl(new_op_name, autograd_not_implemented(functional_op), 'Autograd') + + f_kernel = construct_functionalization_kernel(weakref.proxy(mutable_op), functional_op) + + lib.impl(mutable_op, f_kernel, 'Functionalize') + + +def construct_functional_impl(mutable_op): + def functional_impl(*args): + # Strategy: + # - clone args that would have been mutated + # - run mutable_op + # - return the cloned args as additional outputs + new_args = [] + extra_rets = [] + for is_write, arg in zip(mutable_args(mutable_op), args): + if is_write: + cloned = arg.clone() if arg is not None else None + new_args.append(cloned) + extra_rets.append(cloned) + else: + new_args.append(arg) + result = mutable_op(*new_args) + if result is None: + return tuple(extra_rets) + if isinstance(result, tuple): + return (*result, *extra_rets) + return (result, *extra_rets) + return functional_impl + + +def construct_functionalization_kernel(mutable_op, functional_op): + def kernel(*args): + # There's nothing to be functionalized! + # We can still end up here because DispatchKey::Functionalize is a mode key + if pytree.tree_all_only(torch.Tensor, lambda x: not torch._is_functional_tensor(x), args): + with _ExcludeDispatchKeyGuard(DispatchKeySet(DispatchKey.Functionalize)): + return mutable_op(*args) + + # NB: This differs from the codegen -- codegen handles cases where there + # are mixed FunctionalTensorWrapper and non-FunctionalTensorWrapper. + # This only really matters for XLA (mixed CPU-XLA tensors) and + # running functionalization without the PT2 stack (which guarantees to us that + # all tensors are FunctionalTensorWrapper). + if not pytree.tree_all_only(torch.Tensor, torch._is_functional_tensor, args): + raise RuntimeError("{mutable_op}: expected all args to be FunctionalTensorWrapper") + + unwrapped_args = [] + for arg in args: + if isinstance(arg, torch.Tensor) and torch._is_functional_tensor(arg): + torch._sync(arg) + unwrapped = torch._from_functional_tensor(arg) + unwrapped_args.append(unwrapped) + else: + unwrapped_args.append(arg) + + with _ExcludeDispatchKeyGuard(DispatchKeySet(DispatchKey.Functionalize)): + output = functional_op(*unwrapped_args) + + num_actual_output = len(mutable_op._schema.returns) + actual_output = pytree.tree_map( + torch._to_functional_tensor, output[:num_actual_output]) + + new_values_to_propagate = output[num_actual_output:] + inputs_to_replace = [arg for is_write, arg in zip(mutable_args(mutable_op), args) + if is_write] + assert len(new_values_to_propagate) == len(inputs_to_replace) + for new_value, arg in zip(new_values_to_propagate, inputs_to_replace): + if (arg is None and new_value is None) or (arg is not None and new_value is not None): + continue + torch._C._propagate_xla_data(arg, new_value) + torch._C._replace_(arg, new_value) + torch._C._commit_update(arg) + torch._sync(arg) + + if len(actual_output) == 1: + return actual_output[0] + elif len(actual_output) == 0: + return None + return actual_output + + return kernel + + +def validate(mutable_op: OpOverload): + if not isinstance(mutable_op, OpOverload): + raise TypeError( + f"register_functional_op(mutable_op): expected mutable_op to be instance of " + f"OpOverload but got {type(mutable_op)}") + + # There are generally three types of "in-place" or "mutable" ops. + # Each of them have their own conventions: + # - inplace (first input modified in-place and returned as only output) + # - out= (some args modified in-place and returned as outputs) + # - mutable (some args modified in-place but none of those returned as outputs) + # In theory we can support all three, but we'll just support the last + # option right now for simplicity. + schema = FunctionSchema.parse(str(mutable_op._schema)) + if not schema.kind() == SchemaKind.mutable: + raise RuntimeError("Expected op to be mutable (as opposed to functional, inplace or out)") + for ret in schema.returns: + # construct_functionalization_kernel assumes this for simplicity + if ret.annotation is not None: + raise NotImplementedError( + "NYI: register_functional_op(op) where op returns a mutated or aliased value. " + "Please file an issue (and as a workaround, modify your operator to " + "not return the mutated value or aliases)") + for arg in schema.arguments.flat_all: + # construct_functionalization_kernel assumes this for simplicity + if arg.type.is_tensor_like() and ( + arg.type != BaseType(BaseTy.Tensor) + and arg.type != OptionalType(BaseType(BaseTy.Tensor)) + ): + raise NotImplementedError( + "NYI: register_functional_op(op) where op has a List[Tensor] input." + "Please file an issue.") + + +def functional_schema(new_op_name, op: OpOverload): + schema = FunctionSchema.parse(str(op._schema)) + schema = schema.signature().with_name(OperatorName.parse(new_op_name)) + return str(schema) + + +def mutable_args(op: OpOverload): + return tuple(False if arg.alias_info is None else arg.alias_info.is_write + for arg in op._schema.arguments) diff --git a/shared/package-files/3a/3a8fa2f5276465b0c98169f920d4787abcbcd3e7a5ebeb99048b699a6fc65392/atanh_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/3a/3a8fa2f5276465b0c98169f920d4787abcbcd3e7a5ebeb99048b699a6fc65392/atanh_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6fe4d216cdb3e2014fb950d3197472900ce3fa3a --- /dev/null +++ b/shared/package-files/3a/3a8fa2f5276465b0c98169f920d4787abcbcd3e7a5ebeb99048b699a6fc65392/atanh_compositeexplicitautogradnonfunctional_dispatch.h @@ -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 atanh(const at::Tensor & self); +TORCH_API at::Tensor & atanh_(at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/3a/3a9133d8e4b00a2d15bff90b79d7d3ca17761907eb0a621c2c2e16413641bcd3/mkldnn_rnn_layer.h b/shared/package-files/3a/3a9133d8e4b00a2d15bff90b79d7d3ca17761907eb0a621c2c2e16413641bcd3/mkldnn_rnn_layer.h new file mode 100644 index 0000000000000000000000000000000000000000..9ef7321e75a6fb59ab97378c8217ceec9757d23f --- /dev/null +++ b/shared/package-files/3a/3a9133d8e4b00a2d15bff90b79d7d3ca17761907eb0a621c2c2e16413641bcd3/mkldnn_rnn_layer.h @@ -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::mkldnn_rnn_layer(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) -> (Tensor, Tensor, Tensor, Tensor) +inline ::std::tuple mkldnn_rnn_layer(const at::Tensor & input, const at::Tensor & weight0, const at::Tensor & weight1, const at::Tensor & weight2, const at::Tensor & weight3, const at::Tensor & hx_, const at::Tensor & cx_, bool reverse, at::IntArrayRef batch_sizes, int64_t mode, int64_t hidden_size, int64_t num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) { + return at::_ops::mkldnn_rnn_layer::call(input, weight0, weight1, weight2, weight3, hx_, cx_, reverse, batch_sizes, mode, hidden_size, num_layers, has_biases, bidirectional, batch_first, train); +} + +// aten::mkldnn_rnn_layer.out(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!)) +inline ::std::tuple mkldnn_rnn_layer_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, const at::Tensor & input, const at::Tensor & weight0, const at::Tensor & weight1, const at::Tensor & weight2, const at::Tensor & weight3, const at::Tensor & hx_, const at::Tensor & cx_, bool reverse, at::IntArrayRef batch_sizes, int64_t mode, int64_t hidden_size, int64_t num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) { + return at::_ops::mkldnn_rnn_layer_out::call(input, weight0, weight1, weight2, weight3, hx_, cx_, reverse, batch_sizes, mode, hidden_size, num_layers, has_biases, bidirectional, batch_first, train, out0, out1, out2, out3); +} +// aten::mkldnn_rnn_layer.out(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!)) +inline ::std::tuple mkldnn_rnn_layer_outf(const at::Tensor & input, const at::Tensor & weight0, const at::Tensor & weight1, const at::Tensor & weight2, const at::Tensor & weight3, const at::Tensor & hx_, const at::Tensor & cx_, bool reverse, at::IntArrayRef batch_sizes, int64_t mode, int64_t hidden_size, int64_t num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3) { + return at::_ops::mkldnn_rnn_layer_out::call(input, weight0, weight1, weight2, weight3, hx_, cx_, reverse, batch_sizes, mode, hidden_size, num_layers, has_biases, bidirectional, batch_first, train, out0, out1, out2, out3); +} + +} diff --git a/shared/package-files/3a/3a91757d4bd1c177505d45e826cdf7a133f8291316645d39c7066390bbba8b27/langbulgarianmodel.pyi b/shared/package-files/3a/3a91757d4bd1c177505d45e826cdf7a133f8291316645d39c7066390bbba8b27/langbulgarianmodel.pyi new file mode 100644 index 0000000000000000000000000000000000000000..de07cfa7b1b40e4b07f9095145021e5935dc71d3 --- /dev/null +++ b/shared/package-files/3a/3a91757d4bd1c177505d45e826cdf7a133f8291316645d39c7066390bbba8b27/langbulgarianmodel.pyi @@ -0,0 +1,9 @@ +from typing import Tuple + +from . import _LangModelType + +Latin5_BulgarianCharToOrderMap: Tuple[int, ...] +win1251BulgarianCharToOrderMap: Tuple[int, ...] +BulgarianLangModel: Tuple[int, ...] +Latin5BulgarianModel: _LangModelType +Win1251BulgarianModel: _LangModelType diff --git a/shared/package-files/3a/3a9282c9db5e6d8f9da9047a1a323ff0af39662f5949234115ec9471a7d38d1c/_miobase.py b/shared/package-files/3a/3a9282c9db5e6d8f9da9047a1a323ff0af39662f5949234115ec9471a7d38d1c/_miobase.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad7fd7395bb67cc2926b03ed7a6002dc4f9e3f6 --- /dev/null +++ b/shared/package-files/3a/3a9282c9db5e6d8f9da9047a1a323ff0af39662f5949234115ec9471a7d38d1c/_miobase.py @@ -0,0 +1,432 @@ +# Authors: Travis Oliphant, Matthew Brett + +""" +Base classes for MATLAB file stream reading. + +MATLAB is a registered trademark of the Mathworks inc. +""" + +from typing import Final + +import numpy as np +from scipy._lib import doccer + +from . import _byteordercodes as boc + +__all__ = [ + 'MatReadError', 'MatReadWarning', 'MatWriteError', +] + +class MatReadError(Exception): + """Exception indicating a read issue.""" + + +class MatWriteError(Exception): + """Exception indicating a write issue.""" + + +class MatReadWarning(UserWarning): + """Warning class for read issues.""" + + +doc_dict = \ + {'file_arg': + '''file_name : str + Name of the mat file (do not need .mat extension if + appendmat==True) Can also pass open file-like object.''', + 'append_arg': + '''appendmat : bool, optional + True to append the .mat extension to the end of the given + filename, if not already present. Default is True.''', + 'load_args': + '''byte_order : str or None, optional + None by default, implying byte order guessed from mat + file. Otherwise can be one of ('native', '=', 'little', '<', + 'BIG', '>'). +mat_dtype : bool, optional + If True, return arrays in same dtype as would be loaded into + MATLAB (instead of the dtype with which they are saved). +squeeze_me : bool, optional + Whether to squeeze unit matrix dimensions or not. +chars_as_strings : bool, optional + Whether to convert char arrays to string arrays. +matlab_compatible : bool, optional + Returns matrices as would be loaded by MATLAB (implies + squeeze_me=False, chars_as_strings=False, mat_dtype=True, + struct_as_record=True).''', + 'struct_arg': + '''struct_as_record : bool, optional + Whether to load MATLAB structs as NumPy record arrays, or as + old-style NumPy arrays with dtype=object. Setting this flag to + False replicates the behavior of SciPy version 0.7.x (returning + numpy object arrays). The default setting is True, because it + allows easier round-trip load and save of MATLAB files.''', + 'matstream_arg': + '''mat_stream : file-like + Object with file API, open for reading.''', + 'long_fields': + '''long_field_names : bool, optional + * False - maximum field name length in a structure is 31 characters + which is the documented maximum length. This is the default. + * True - maximum field name length in a structure is 63 characters + which works for MATLAB 7.6''', + 'do_compression': + '''do_compression : bool, optional + Whether to compress matrices on write. Default is False.''', + 'oned_as': + '''oned_as : {'row', 'column'}, optional + If 'column', write 1-D NumPy arrays as column vectors. + If 'row', write 1D NumPy arrays as row vectors.''', + 'unicode_strings': + '''unicode_strings : bool, optional + If True, write strings as Unicode, else MATLAB usual encoding.'''} + +docfiller: Final = doccer.filldoc(doc_dict) + +''' + + Note on architecture +====================== + +There are three sets of parameters relevant for reading files. The +first are *file read parameters* - containing options that are common +for reading the whole file, and therefore every variable within that +file. At the moment these are: + +* mat_stream +* dtypes (derived from byte code) +* byte_order +* chars_as_strings +* squeeze_me +* struct_as_record (MATLAB 5 files) +* class_dtypes (derived from order code, MATLAB 5 files) +* codecs (MATLAB 5 files) +* uint16_codec (MATLAB 5 files) + +Another set of parameters are those that apply only to the current +variable being read - the *header*: + +* header related variables (different for v4 and v5 mat files) +* is_complex +* mclass +* var_stream + +With the header, we need ``next_position`` to tell us where the next +variable in the stream is. + +Then, for each element in a matrix, there can be *element read +parameters*. An element is, for example, one element in a MATLAB cell +array. At the moment, these are: + +* mat_dtype + +The file-reading object contains the *file read parameters*. The +*header* is passed around as a data object, or may be read and discarded +in a single function. The *element read parameters* - the mat_dtype in +this instance, is passed into a general post-processing function - see +``mio_utils`` for details. +''' + + +def convert_dtypes(dtype_template, order_code): + ''' Convert dtypes in mapping to given order + + Parameters + ---------- + dtype_template : mapping + mapping with values returning numpy dtype from ``np.dtype(val)`` + order_code : str + an order code suitable for using in ``dtype.newbyteorder()`` + + Returns + ------- + dtypes : mapping + mapping where values have been replaced by + ``np.dtype(val).newbyteorder(order_code)`` + + ''' + dtypes = dtype_template.copy() + for k in dtypes: + dtypes[k] = np.dtype(dtypes[k]).newbyteorder(order_code) + return dtypes + + +def read_dtype(mat_stream, a_dtype): + """ + Generic get of byte stream data of known type + + Parameters + ---------- + mat_stream : file_like object + MATLAB (tm) mat file stream + a_dtype : dtype + dtype of array to read. `a_dtype` is assumed to be correct + endianness. + + Returns + ------- + arr : ndarray + Array of dtype `a_dtype` read from stream. + + """ + num_bytes = a_dtype.itemsize + arr = np.ndarray(shape=(), + dtype=a_dtype, + buffer=mat_stream.read(num_bytes), + order='F') + return arr + + +def matfile_version(file_name, *, appendmat=True): + """ + Return major, minor tuple depending on apparent mat file type + + Where: + + #. 0,x -> version 4 format mat files + #. 1,x -> version 5 format mat files + #. 2,x -> version 7.3 format mat files (HDF format) + + Parameters + ---------- + file_name : str + Name of the mat file (do not need .mat extension if + appendmat==True). Can also pass open file-like object. + appendmat : bool, optional + True to append the .mat extension to the end of the given + filename, if not already present. Default is True. + + Returns + ------- + major_version : {0, 1, 2} + major MATLAB File format version + minor_version : int + minor MATLAB file format version + + Raises + ------ + MatReadError + If the file is empty. + ValueError + The matfile version is unknown. + + Notes + ----- + Has the side effect of setting the file read pointer to 0 + """ + from ._mio import _open_file_context + with _open_file_context(file_name, appendmat=appendmat) as fileobj: + return _get_matfile_version(fileobj) + + +get_matfile_version = matfile_version + + +_HDR_N_BYTES = 20 + + +def _get_matfile_version(fileobj): + # Mat4 files have a zero somewhere in first 4 bytes + fileobj.seek(0) + hdr_bytes = fileobj.read(_HDR_N_BYTES) + if len(hdr_bytes) < _HDR_N_BYTES: + raise MatReadError("Mat file appears to be truncated") + if hdr_bytes.count(0) == _HDR_N_BYTES: + raise MatReadError("Mat file appears to be corrupt " + f"(first {_HDR_N_BYTES} bytes == 0)") + mopt_ints = np.ndarray(shape=(4,), dtype=np.uint8, buffer=hdr_bytes[:4]) + if 0 in mopt_ints: + fileobj.seek(0) + return (0,0) + # For 5 format or 7.3 format we need to read an integer in the + # header. Bytes 124 through 128 contain a version integer and an + # endian test string + fileobj.seek(124) + tst_str = fileobj.read(4) + fileobj.seek(0) + maj_ind = int(tst_str[2] == b'I'[0]) + maj_val = int(tst_str[maj_ind]) + min_val = int(tst_str[1 - maj_ind]) + ret = (maj_val, min_val) + if maj_val in (1, 2): + return ret + raise ValueError('Unknown mat file type, version {}, {}'.format(*ret)) + + +def matdims(arr, oned_as='column'): + """ + Determine equivalent MATLAB dimensions for given array + + Parameters + ---------- + arr : ndarray + Input array + oned_as : {'column', 'row'}, optional + Whether 1-D arrays are returned as MATLAB row or column matrices. + Default is 'column'. + + Returns + ------- + dims : tuple + Shape tuple, in the form MATLAB expects it. + + Notes + ----- + We had to decide what shape a 1 dimensional array would be by + default. ``np.atleast_2d`` thinks it is a row vector. The + default for a vector in MATLAB (e.g., ``>> 1:12``) is a row vector. + + Versions of scipy up to and including 0.11 resulted (accidentally) + in 1-D arrays being read as column vectors. For the moment, we + maintain the same tradition here. + + Examples + -------- + >>> import numpy as np + >>> from scipy.io.matlab._miobase import matdims + >>> matdims(np.array(1)) # NumPy scalar + (1, 1) + >>> matdims(np.array([1])) # 1-D array, 1 element + (1, 1) + >>> matdims(np.array([1,2])) # 1-D array, 2 elements + (2, 1) + >>> matdims(np.array([[2],[3]])) # 2-D array, column vector + (2, 1) + >>> matdims(np.array([[2,3]])) # 2-D array, row vector + (1, 2) + >>> matdims(np.array([[[2,3]]])) # 3-D array, rowish vector + (1, 1, 2) + >>> matdims(np.array([])) # empty 1-D array + (0, 0) + >>> matdims(np.array([[]])) # empty 2-D array + (0, 0) + >>> matdims(np.array([[[]]])) # empty 3-D array + (0, 0, 0) + + Optional argument flips 1-D shape behavior. + + >>> matdims(np.array([1,2]), 'row') # 1-D array, 2 elements + (1, 2) + + The argument has to make sense though + + >>> matdims(np.array([1,2]), 'bizarre') + Traceback (most recent call last): + ... + ValueError: 1-D option "bizarre" is strange + + """ + shape = arr.shape + if shape == (): # scalar + return (1, 1) + if len(shape) == 1: # 1D + if shape[0] == 0: + return (0, 0) + elif oned_as == 'column': + return shape + (1,) + elif oned_as == 'row': + return (1,) + shape + else: + raise ValueError(f'1-D option "{oned_as}" is strange') + return shape + + +class MatVarReader: + ''' Abstract class defining required interface for var readers''' + def __init__(self, file_reader): + pass + + def read_header(self): + ''' Returns header ''' + pass + + def array_from_header(self, header): + ''' Reads array given header ''' + pass + + +class MatFileReader: + """ Base object for reading mat files + + To make this class functional, you will need to override the + following methods: + + matrix_getter_factory - gives object to fetch next matrix from stream + guess_byte_order - guesses file byte order from file + """ + + @docfiller + def __init__(self, mat_stream, + byte_order=None, + mat_dtype=False, + squeeze_me=False, + chars_as_strings=True, + matlab_compatible=False, + struct_as_record=True, + verify_compressed_data_integrity=True, + simplify_cells=False): + ''' + Initializer for mat file reader + + mat_stream : file-like + object with file API, open for reading + %(load_args)s + ''' + # Initialize stream + self.mat_stream = mat_stream + self.dtypes = {} + if not byte_order: + byte_order = self.guess_byte_order() + else: + byte_order = boc.to_numpy_code(byte_order) + self.byte_order = byte_order + self.struct_as_record = struct_as_record + if matlab_compatible: + self.set_matlab_compatible() + else: + self.squeeze_me = squeeze_me + self.chars_as_strings = chars_as_strings + self.mat_dtype = mat_dtype + self.verify_compressed_data_integrity = verify_compressed_data_integrity + self.simplify_cells = simplify_cells + if simplify_cells: + self.squeeze_me = True + self.struct_as_record = False + + def set_matlab_compatible(self): + ''' Sets options to return arrays as MATLAB loads them ''' + self.mat_dtype = True + self.squeeze_me = False + self.chars_as_strings = False + + def guess_byte_order(self): + ''' As we do not know what file type we have, assume native ''' + return boc.native_code + + def end_of_stream(self): + b = self.mat_stream.read(1) + curpos = self.mat_stream.tell() + self.mat_stream.seek(curpos-1) + return len(b) == 0 + + +def arr_dtype_number(arr, num): + ''' Return dtype for given number of items per element''' + return np.dtype(arr.dtype.str[:2] + str(num)) + + +def arr_to_chars(arr): + ''' Convert string array to char array ''' + dims = list(arr.shape) + if not dims: + dims = [1] + dims.append(int(arr.dtype.str[2:])) + arr = np.ndarray(shape=dims, + dtype=arr_dtype_number(arr, 1), + buffer=arr) + empties = [arr == np.array('', dtype=arr.dtype)] + if not np.any(empties): + return arr + arr = arr.copy() + arr[tuple(empties)] = ' ' + return arr diff --git a/shared/package-files/3a/3a929d255e27955181bfc1bc94379e2dd40f6c3cda256b67f932664bc37d379c/elm.py b/shared/package-files/3a/3a929d255e27955181bfc1bc94379e2dd40f6c3cda256b67f932664bc37d379c/elm.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc12d303d0413cb7d85ddd870a70332b932225a --- /dev/null +++ b/shared/package-files/3a/3a929d255e27955181bfc1bc94379e2dd40f6c3cda256b67f932664bc37d379c/elm.py @@ -0,0 +1,124 @@ +""" + pygments.lexers.elm + ~~~~~~~~~~~~~~~~~~~ + + Lexer for the Elm programming language. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, words, include, bygroups +from pygments.token import Comment, Keyword, Name, Number, Punctuation, \ + String, Whitespace + +__all__ = ['ElmLexer'] + + +class ElmLexer(RegexLexer): + """ + For Elm source code. + + .. versionadded:: 2.1 + """ + + name = 'Elm' + url = 'http://elm-lang.org/' + aliases = ['elm'] + filenames = ['*.elm'] + mimetypes = ['text/x-elm'] + + validName = r'[a-z_][a-zA-Z0-9_\']*' + + specialName = r'^main ' + + builtinOps = ( + '~', '||', '|>', '|', '`', '^', '\\', '\'', '>>', '>=', '>', '==', + '=', '<~', '<|', '<=', '<<', '<-', '<', '::', ':', '/=', '//', '/', + '..', '.', '->', '-', '++', '+', '*', '&&', '%', + ) + + reservedWords = words(( + 'alias', 'as', 'case', 'else', 'if', 'import', 'in', + 'let', 'module', 'of', 'port', 'then', 'type', 'where', + ), suffix=r'\b') + + tokens = { + 'root': [ + + # Comments + (r'\{-', Comment.Multiline, 'comment'), + (r'--.*', Comment.Single), + + # Whitespace + (r'\s+', Whitespace), + + # Strings + (r'"', String, 'doublequote'), + + # Modules + (r'^(\s*)(module)(\s*)', bygroups(Whitespace, Keyword.Namespace, + Whitespace), 'imports'), + + # Imports + (r'^(\s*)(import)(\s*)', bygroups(Whitespace, Keyword.Namespace, + Whitespace), 'imports'), + + # Shaders + (r'\[glsl\|.*', Name.Entity, 'shader'), + + # Keywords + (reservedWords, Keyword.Reserved), + + # Types + (r'[A-Z][a-zA-Z0-9_]*', Keyword.Type), + + # Main + (specialName, Keyword.Reserved), + + # Prefix Operators + (words((builtinOps), prefix=r'\(', suffix=r'\)'), Name.Function), + + # Infix Operators + (words(builtinOps), Name.Function), + + # Numbers + include('numbers'), + + # Variable Names + (validName, Name.Variable), + + # Parens + (r'[,()\[\]{}]', Punctuation), + + ], + + 'comment': [ + (r'-(?!\})', Comment.Multiline), + (r'\{-', Comment.Multiline, 'comment'), + (r'[^-}]', Comment.Multiline), + (r'-\}', Comment.Multiline, '#pop'), + ], + + 'doublequote': [ + (r'\\u[0-9a-fA-F]{4}', String.Escape), + (r'\\[nrfvb\\"]', String.Escape), + (r'[^"]', String), + (r'"', String, '#pop'), + ], + + 'imports': [ + (r'\w+(\.\w+)*', Name.Class, '#pop'), + ], + + 'numbers': [ + (r'_?\d+\.(?=\d+)', Number.Float), + (r'_?\d+', Number.Integer), + ], + + 'shader': [ + (r'\|(?!\])', Name.Entity), + (r'\|\]', Name.Entity, '#pop'), + (r'(.*)(\n)', bygroups(Name.Entity, Whitespace)), + ], + } diff --git a/shared/package-files/3a/3a92d4ea321fc2f18947824f55564b9547efa3ba0067462fb2369f336aad3e59/cpu_vx.c b/shared/package-files/3a/3a92d4ea321fc2f18947824f55564b9547efa3ba0067462fb2369f336aad3e59/cpu_vx.c new file mode 100644 index 0000000000000000000000000000000000000000..18fb7ef94a248d0de890bafa9cae67a5559e47f9 --- /dev/null +++ b/shared/package-files/3a/3a92d4ea321fc2f18947824f55564b9547efa3ba0067462fb2369f336aad3e59/cpu_vx.c @@ -0,0 +1,16 @@ +#if (__VEC__ < 10301) || (__ARCH__ < 11) + #error VX not supported +#endif + +#include +int main(int argc, char **argv) +{ + __vector double x = vec_abs(vec_xl(argc, (double*)argv)); + __vector double y = vec_load_len((double*)argv, (unsigned int)argc); + + x = vec_round(vec_ceil(x) + vec_floor(y)); + __vector bool long long m = vec_cmpge(x, y); + __vector long long i = vec_signed(vec_sel(x, y, m)); + + return (int)vec_extract(i, 0); +} diff --git a/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Belgrade b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Belgrade new file mode 100644 index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9 Binary files /dev/null and b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Belgrade differ diff --git a/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Ljubljana b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Ljubljana new file mode 100644 index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9 Binary files /dev/null and b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Ljubljana differ diff --git a/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Podgorica b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Podgorica new file mode 100644 index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9 Binary files /dev/null and b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Podgorica differ diff --git a/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Sarajevo b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Sarajevo new file mode 100644 index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9 Binary files /dev/null and b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Sarajevo differ diff --git a/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Skopje b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Skopje new file mode 100644 index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9 Binary files /dev/null and b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Skopje differ diff --git a/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Zagreb b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Zagreb new file mode 100644 index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9 Binary files /dev/null and b/shared/package-files/3a/3a95adb06156044fd2fa662841c0268c2b5af47c1b19000d9d299563d387093a/Zagreb differ diff --git a/shared/package-files/3a/3a960337d7577fe1433f21588083ca9030f82e4d24d1176835e30638735c4645/test_withlifting.py b/shared/package-files/3a/3a960337d7577fe1433f21588083ca9030f82e4d24d1176835e30638735c4645/test_withlifting.py new file mode 100644 index 0000000000000000000000000000000000000000..e95295be22a4bcac2f566a50a0d3bd5a434681f2 --- /dev/null +++ b/shared/package-files/3a/3a960337d7577fe1433f21588083ca9030f82e4d24d1176835e30638735c4645/test_withlifting.py @@ -0,0 +1,1223 @@ +import copy +import warnings +import numpy as np + +import numba +from numba.core.transforms import find_setupwiths, with_lifting +from numba.core.withcontexts import bypass_context, call_context, objmode_context +from numba.core.bytecode import FunctionIdentity, ByteCode +from numba.core.interpreter import Interpreter +from numba.core import errors +from numba.core.registry import cpu_target +from numba.core.compiler import compile_ir, DEFAULT_FLAGS +from numba import njit, typeof, objmode, types +from numba.core.extending import overload +from numba.tests.support import (MemoryLeak, TestCase, captured_stdout, + skip_unless_scipy, linux_only, + strace_supported, strace, + expected_failure_py311, + expected_failure_py312, + expected_failure_py313, + expected_failure_py314, + expected_failure_py315, + ) +from numba.core.utils import PYVERSION +from numba.experimental import jitclass +import unittest + + +def get_func_ir(func): + func_id = FunctionIdentity.from_function(func) + bc = ByteCode(func_id=func_id) + interp = Interpreter(func_id) + func_ir = interp.interpret(bc) + return func_ir + + +def lift1(): + print("A") + with bypass_context: + print("B") + b() + print("C") + + +def lift2(): + x = 1 + print("A", x) + x = 1 + with bypass_context: + print("B", x) + x += 100 + b() + x += 1 + with bypass_context: + print("C", x) + b() + x += 10 + x += 1 + print("D", x) + + +def lift3(): + x = 1 + y = 100 + print("A", x, y) + with bypass_context: + print("B") + b() + x += 100 + with bypass_context: + print("C") + y += 100000 + b() + x += 1 + y += 1 + print("D", x, y) + + +def lift4(): + x = 0 + print("A", x) + x += 10 + with bypass_context: + print("B") + b() + x += 1 + for i in range(10): + with bypass_context: + print("C") + b() + x += i + with bypass_context: + print("D") + b() + if x: + x *= 10 + x += 1 + print("E", x) + + +def lift5(): + print("A") + + +def liftcall1(): + x = 1 + print("A", x) + with call_context: + x += 1 + print("B", x) + return x + + +def liftcall2(): + x = 1 + print("A", x) + with call_context: + x += 1 + print("B", x) + with call_context: + x += 10 + print("C", x) + return x + + +def liftcall3(): + x = 1 + print("A", x) + with call_context: + if x > 0: + x += 1 + print("B", x) + with call_context: + for i in range(10): + x += i + print("C", x) + return x + + +def liftcall4(): + with call_context: + with call_context: + pass + + +def liftcall5(): + for i in range(10): + with call_context: + print(i) + if i == 5: + print("A") + break + return i + + +def lift_undefiend(): + with undefined_global_var: + pass + + +bogus_contextmanager = object() + + +def lift_invalid(): + with bogus_contextmanager: + pass + + +gv_type = types.intp + + +class TestWithFinding(TestCase): + def check_num_of_with(self, func, expect_count): + the_ir = get_func_ir(func) + ct = len(find_setupwiths(the_ir)[0]) + self.assertEqual(ct, expect_count) + + def test_lift1(self): + self.check_num_of_with(lift1, expect_count=1) + + def test_lift2(self): + self.check_num_of_with(lift2, expect_count=2) + + def test_lift3(self): + self.check_num_of_with(lift3, expect_count=1) + + def test_lift4(self): + self.check_num_of_with(lift4, expect_count=2) + + def test_lift5(self): + self.check_num_of_with(lift5, expect_count=0) + + +class BaseTestWithLifting(TestCase): + def setUp(self): + super(BaseTestWithLifting, self).setUp() + self.typingctx = cpu_target.typing_context + self.targetctx = cpu_target.target_context + self.flags = DEFAULT_FLAGS + + def check_extracted_with(self, func, expect_count, expected_stdout): + the_ir = get_func_ir(func) + new_ir, extracted = with_lifting( + the_ir, self.typingctx, self.targetctx, self.flags, + locals={}, + ) + self.assertEqual(len(extracted), expect_count) + cres = self.compile_ir(new_ir) + + with captured_stdout() as out: + cres.entry_point() + + self.assertEqual(out.getvalue(), expected_stdout) + + def compile_ir(self, the_ir, args=(), return_type=None): + typingctx = self.typingctx + targetctx = self.targetctx + flags = self.flags + return compile_ir(typingctx, targetctx, the_ir, args, + return_type, flags, locals={}) + + +class TestLiftByPass(BaseTestWithLifting): + + def test_lift1(self): + self.check_extracted_with(lift1, expect_count=1, + expected_stdout="A\nC\n") + + def test_lift2(self): + self.check_extracted_with(lift2, expect_count=2, + expected_stdout="A 1\nD 3\n") + + def test_lift3(self): + self.check_extracted_with(lift3, expect_count=1, + expected_stdout="A 1 100\nD 2 101\n") + + def test_lift4(self): + self.check_extracted_with(lift4, expect_count=2, + expected_stdout="A 0\nE 11\n") + + def test_lift5(self): + self.check_extracted_with(lift5, expect_count=0, + expected_stdout="A\n") + + +class TestLiftCall(BaseTestWithLifting): + + def check_same_semantic(self, func): + """Ensure same semantic with non-jitted code + """ + jitted = njit(func) + with captured_stdout() as got: + jitted() + + with captured_stdout() as expect: + func() + + self.assertEqual(got.getvalue(), expect.getvalue()) + + def test_liftcall1(self): + self.check_extracted_with(liftcall1, expect_count=1, + expected_stdout="A 1\nB 2\n") + self.check_same_semantic(liftcall1) + + def test_liftcall2(self): + self.check_extracted_with(liftcall2, expect_count=2, + expected_stdout="A 1\nB 2\nC 12\n") + self.check_same_semantic(liftcall2) + + def test_liftcall3(self): + self.check_extracted_with(liftcall3, expect_count=2, + expected_stdout="A 1\nB 2\nC 47\n") + self.check_same_semantic(liftcall3) + + def test_liftcall4(self): + accept = (errors.TypingError, errors.NumbaRuntimeError, + errors.NumbaValueError, errors.CompilerError) + with self.assertRaises(accept) as raises: + njit(liftcall4)() + # Known error. We only support one context manager per function + # for body that are lifted. + msg = ("compiler re-entrant to the same function signature") + self.assertIn(msg, str(raises.exception)) + + @expected_failure_py311 + @expected_failure_py312 + @expected_failure_py313 + @expected_failure_py314 + @expected_failure_py315 + def test_liftcall5(self): + self.check_extracted_with(liftcall5, expect_count=1, + expected_stdout="0\n1\n2\n3\n4\n5\nA\n") + self.check_same_semantic(liftcall5) + + +def expected_failure_for_list_arg(fn): + def core(self, *args, **kwargs): + with self.assertRaises(errors.TypingError) as raises: + fn(self, *args, **kwargs) + self.assertIn('Does not support list type', + str(raises.exception)) + return core + + +def expected_failure_for_function_arg(fn): + def core(self, *args, **kwargs): + with self.assertRaises(errors.TypingError) as raises: + fn(self, *args, **kwargs) + self.assertIn('Does not support function type', + str(raises.exception)) + return core + + +class TestLiftObj(MemoryLeak, TestCase): + + def setUp(self): + warnings.simplefilter("error", errors.NumbaWarning) + + def tearDown(self): + warnings.resetwarnings() + + def assert_equal_return_and_stdout(self, pyfunc, *args): + py_args = copy.deepcopy(args) + c_args = copy.deepcopy(args) + cfunc = njit(pyfunc) + + with captured_stdout() as stream: + expect_res = pyfunc(*py_args) + expect_out = stream.getvalue() + + # avoid compiling during stdout-capturing for easier print-debugging + cfunc.compile(tuple(map(typeof, c_args))) + with captured_stdout() as stream: + got_res = cfunc(*c_args) + got_out = stream.getvalue() + + self.assertEqual(expect_out, got_out) + self.assertPreciseEqual(expect_res, got_res) + + def test_lift_objmode_basic(self): + def bar(ival): + print("ival =", {'ival': ival // 2}) + + def foo(ival): + ival += 1 + with objmode_context: + bar(ival) + return ival + 1 + + def foo_nonglobal(ival): + ival += 1 + with numba.objmode: + bar(ival) + return ival + 1 + + self.assert_equal_return_and_stdout(foo, 123) + self.assert_equal_return_and_stdout(foo_nonglobal, 123) + + def test_lift_objmode_array_in(self): + def bar(arr): + print({'arr': arr // 2}) + # arr is modified. the effect is visible outside. + arr *= 2 + + def foo(nelem): + arr = np.arange(nelem).astype(np.int64) + with objmode_context: + # arr is modified inplace inside bar() + bar(arr) + return arr + 1 + + nelem = 10 + self.assert_equal_return_and_stdout(foo, nelem) + + def test_lift_objmode_define_new_unused(self): + def bar(y): + print(y) + + def foo(x): + with objmode_context(): + y = 2 + x # defined but unused outside + a = np.arange(y) # defined but unused outside + bar(a) + return x + + arg = 123 + self.assert_equal_return_and_stdout(foo, arg) + + def test_lift_objmode_return_simple(self): + def inverse(x): + print(x) + return 1 / x + + def foo(x): + with objmode_context(y="float64"): + y = inverse(x) + return x, y + + def foo_nonglobal(x): + with numba.objmode(y="float64"): + y = inverse(x) + return x, y + + arg = 123 + self.assert_equal_return_and_stdout(foo, arg) + self.assert_equal_return_and_stdout(foo_nonglobal, arg) + + def test_lift_objmode_return_array(self): + def inverse(x): + print(x) + return 1 / x + + def foo(x): + with objmode_context(y="float64[:]", z="int64"): + y = inverse(x) + z = int(y[0]) + return x, y, z + + arg = np.arange(1, 10, dtype=np.float64) + self.assert_equal_return_and_stdout(foo, arg) + + @expected_failure_for_list_arg + def test_lift_objmode_using_list(self): + def foo(x): + with objmode_context(y="float64[:]"): + print(x) + x[0] = 4 + print(x) + y = [1, 2, 3] + x + y = np.asarray([1 / i for i in y]) + return x, y + + arg = [1, 2, 3] + self.assert_equal_return_and_stdout(foo, arg) + + def test_lift_objmode_var_redef(self): + def foo(x): + for x in range(x): + pass + if x: + x += 1 + with objmode_context(x="intp"): + print(x) + x -= 1 + print(x) + for i in range(x): + x += i + print(x) + return x + + arg = 123 + self.assert_equal_return_and_stdout(foo, arg) + + @expected_failure_for_list_arg + def test_case01_mutate_list_ahead_of_ctx(self): + def foo(x, z): + x[2] = z + + with objmode_context(): + # should print [1, 2, 15] but prints [1, 2, 3] + print(x) + + with objmode_context(): + x[2] = 2 * z + # should print [1, 2, 30] but prints [1, 2, 15] + print(x) + + return x + + self.assert_equal_return_and_stdout(foo, [1, 2, 3], 15) + + def test_case02_mutate_array_ahead_of_ctx(self): + def foo(x, z): + x[2] = z + + with objmode_context(): + # should print [1, 2, 15] + print(x) + + with objmode_context(): + x[2] = 2 * z + # should print [1, 2, 30] + print(x) + + return x + + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x, 15) + + @expected_failure_for_list_arg + def test_case03_create_and_mutate(self): + def foo(x): + with objmode_context(y='List(int64)'): + y = [1, 2, 3] + with objmode_context(): + y[2] = 10 + return y + self.assert_equal_return_and_stdout(foo, 1) + + def test_case04_bogus_variable_type_info(self): + + def foo(x): + # should specifying nonsense type info be considered valid? + with objmode_context(k="float64[:]"): + print(x) + return x + + x = np.array([1, 2, 3]) + cfoo = njit(foo) + with self.assertRaises(errors.TypingError) as raises: + cfoo(x) + self.assertIn( + "Invalid type annotation on non-outgoing variables", + str(raises.exception), + ) + + def test_case05_bogus_type_info(self): + def foo(x): + # should specifying the wrong type info be considered valid? + # z is complex. + # Note: for now, we will coerce for scalar and raise for array + with objmode_context(z="float64[:]"): + z = x + 1.j + return z + + x = np.array([1, 2, 3]) + cfoo = njit(foo) + with self.assertRaises(TypeError) as raises: + got = cfoo(x) + self.assertIn( + ("can't unbox array from PyObject into native value." + " The object maybe of a different type"), + str(raises.exception), + ) + + def test_case06_double_objmode(self): + def foo(x): + # would nested ctx in the same scope ever make sense? Is this + # pattern useful? + with objmode_context(): + #with npmmode_context(): not implemented yet + with objmode_context(): + print(x) + return x + + with self.assertRaises(errors.TypingError) as raises: + njit(foo)(123) + # Check that an error occurred in with-lifting in objmode + pat = ("During: resolving callee type: " + r"type\(ObjModeLiftedWith\(<.*>\)\)") + self.assertRegex(str(raises.exception), pat) + + def test_case07_mystery_key_error(self): + # this raises a key error + def foo(x): + with objmode_context(): + t = {'a': x} + u = 3 + return x, t, u + x = np.array([1, 2, 3]) + cfoo = njit(foo) + + with self.assertRaises(errors.TypingError) as raises: + cfoo(x) + + exstr = str(raises.exception) + self.assertIn("Missing type annotation on outgoing variable(s): " + "['t', 'u']", + exstr) + self.assertIn("Example code: with objmode" + "(t='')", + exstr) + + def test_case08_raise_from_external(self): + # this segfaults, expect its because the dict needs to raise as '2' is + # not in the keys until a later loop (looking for `d['0']` works fine). + d = dict() + + def foo(x): + for i in range(len(x)): + with objmode_context(): + k = str(i) + v = x[i] + d[k] = v + print(d['2']) + return x + + x = np.array([1, 2, 3]) + cfoo = njit(foo) + with self.assertRaises(KeyError) as raises: + cfoo(x) + self.assertEqual(str(raises.exception), "'2'") + + def test_case09_explicit_raise(self): + def foo(x): + with objmode_context(): + raise ValueError() + return x + + x = np.array([1, 2, 3]) + cfoo = njit(foo) + with self.assertRaises(errors.CompilerError) as raises: + cfoo(x) + self.assertIn( + ('unsupported control flow due to raise statements inside ' + 'with block'), + str(raises.exception), + ) + + @expected_failure_for_list_arg + def test_case10_mutate_across_contexts(self): + # This shouldn't work due to using List as input. + def foo(x): + with objmode_context(y='List(int64)'): + y = [1, 2, 3] + with objmode_context(): + y[2] = 10 + return y + + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + def test_case10_mutate_array_across_contexts(self): + # Sub-case of case-10. + def foo(x): + with objmode_context(y='int64[:]'): + y = np.asarray([1, 2, 3], dtype='int64') + with objmode_context(): + # Note: `y` is not an output. + y[2] = 10 + return y + + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + def test_case11_define_function_in_context(self): + # should this work? no, global name 'bar' is not defined + def foo(x): + with objmode_context(): + def bar(y): + return y + 1 + return x + + x = np.array([1, 2, 3]) + cfoo = njit(foo) + with self.assertRaises(NameError) as raises: + cfoo(x) + self.assertIn( + "global name 'bar' is not defined", + str(raises.exception), + ) + + def test_case12_njit_inside_a_objmode_ctx(self): + # TODO: is this still the cases? + # this works locally but not inside this test, probably due to the way + # compilation is being done + def bar(y): + return y + 1 + + def foo(x): + with objmode_context(y='int64[:]'): + y = njit(bar)(x).astype('int64') + return x + y + + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + def test_case14_return_direct_from_objmode_ctx(self): + def foo(x): + with objmode_context(x='int64[:]'): + x += 1 + return x + + result = foo(np.array([1, 2, 3])) + np.testing.assert_array_equal(np.array([2, 3, 4]), result) + + # No easy way to handle this yet. + @unittest.expectedFailure + def test_case15_close_over_objmode_ctx(self): + # Fails with Unsupported constraint encountered: enter_with $phi8.1 + def foo(x): + j = 10 + + def bar(x): + with objmode_context(x='int64[:]'): + print(x) + return x + j + return bar(x) + 2 + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + @skip_unless_scipy + def test_case16_scipy_call_in_objmode_ctx(self): + from scipy import sparse as sp + + def foo(x): + with objmode_context(k='int64'): + print(x) + spx = sp.csr_matrix(x) + # the np.int64 call is pointless, works around: + # https://github.com/scipy/scipy/issues/10206 + # which hit the SciPy 1.3 release. + k = np.int64(spx[0, 0]) + return k + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + def test_case17_print_own_bytecode(self): + import dis + + def foo(x): + with objmode_context(): + dis.dis(foo) + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + @expected_failure_for_function_arg + def test_case18_njitfunc_passed_to_objmode_ctx(self): + def foo(func, x): + with objmode_context(): + func(x[0]) + + x = np.array([1, 2, 3]) + fn = njit(lambda z: z + 5) + self.assert_equal_return_and_stdout(foo, fn, x) + + @expected_failure_py311 + @expected_failure_py312 + @expected_failure_py313 + @expected_failure_py314 + @expected_failure_py315 + def test_case19_recursion(self): + def foo(x): + with objmode_context(): + if x == 0: + return 7 + ret = foo(x - 1) + return ret + with self.assertRaises((errors.TypingError, errors.CompilerError)) as raises: + cfoo = njit(foo) + cfoo(np.array([1, 2, 3])) + msg = "Untyped global name 'foo'" + self.assertIn(msg, str(raises.exception)) + + @unittest.expectedFailure + def test_case20_rng_works_ok(self): + def foo(x): + np.random.seed(0) + y = np.random.rand() + with objmode_context(z="float64"): + # It's known that the random state does not sync + z = np.random.rand() + return x + z + y + + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + def test_case21_rng_seed_works_ok(self): + def foo(x): + np.random.seed(0) + y = np.random.rand() + with objmode_context(z="float64"): + # Similar to test_case20_rng_works_ok but call seed + np.random.seed(0) + z = np.random.rand() + return x + z + y + + x = np.array([1, 2, 3]) + self.assert_equal_return_and_stdout(foo, x) + + def test_example01(self): + # Example from _ObjModeContextType.__doc__ + def bar(x): + return np.asarray(list(reversed(x.tolist()))) + + @njit + def foo(): + x = np.arange(5) + with objmode(y='intp[:]'): # annotate return type + # this region is executed by object-mode. + y = x + bar(x) + return y + + self.assertPreciseEqual(foo(), foo.py_func()) + self.assertIs(objmode, objmode_context) + + def test_objmode_in_overload(self): + def foo(s): + pass + + @overload(foo) + def foo_overload(s): + def impl(s): + with objmode(out='intp'): + out = s + 3 + return out + return impl + + @numba.njit + def f(): + return foo(1) + + self.assertEqual(f(), 1 + 3) + + def test_objmode_gv_variable(self): + @njit + def global_var(): + with objmode(val=gv_type): + val = 12.3 + return val + + ret = global_var() + # the result is truncated because of the intp return-type + self.assertIsInstance(ret, int) + self.assertEqual(ret, 12) + + def test_objmode_gv_variable_error(self): + @njit + def global_var(): + with objmode(val=gv_type2): + val = 123 + return val + + with self.assertRaisesRegex( + errors.CompilerError, + ("Error handling objmode argument 'val'. " + r"Global 'gv_type2' is not defined.") + ): + global_var() + + def test_objmode_gv_mod_attr(self): + @njit + def modattr1(): + with objmode(val=types.intp): + val = 12.3 + return val + + @njit + def modattr2(): + with objmode(val=numba.types.intp): + val = 12.3 + return val + + for fn in (modattr1, modattr2): + with self.subTest(fn=str(fn)): + ret = fn() + # the result is truncated because of the intp return-type + self.assertIsInstance(ret, int) + self.assertEqual(ret, 12) + + def test_objmode_gv_mod_attr_error(self): + @njit + def moderror(): + with objmode(val=types.THIS_DOES_NOT_EXIST): + val = 12.3 + return val + with self.assertRaisesRegex( + errors.CompilerError, + ("Error handling objmode argument 'val'. " + "Getattr cannot be resolved at compile-time"), + ): + moderror() + + def test_objmode_gv_mod_attr_error_multiple(self): + @njit + def moderror(): + with objmode(v1=types.intp, v2=types.THIS_DOES_NOT_EXIST, + v3=types.float32): + v1 = 12.3 + v2 = 12.3 + v3 = 12.3 + return val + with self.assertRaisesRegex( + errors.CompilerError, + ("Error handling objmode argument 'v2'. " + "Getattr cannot be resolved at compile-time"), + ): + moderror() + + def test_objmode_closure_type_in_overload(self): + def foo(): + pass + + @overload(foo) + def foo_overload(): + shrubbery = types.float64[:] + def impl(): + with objmode(out=shrubbery): + out = np.arange(10).astype(np.float64) + return out + return impl + + @njit + def bar(): + return foo() + + self.assertPreciseEqual(bar(), np.arange(10).astype(np.float64)) + + def test_objmode_closure_type_in_overload_error(self): + def foo(): + pass + + @overload(foo) + def foo_overload(): + shrubbery = types.float64[:] + def impl(): + with objmode(out=shrubbery): + out = np.arange(10).astype(np.float64) + return out + # Remove closure var. + # Otherwise, it will "shrubbery" will be a global + del shrubbery + return impl + + @njit + def bar(): + return foo() + + with self.assertRaisesRegex( + errors.TypingError, + ("Error handling objmode argument 'out'. " + "Freevar 'shrubbery' is not defined"), + ): + bar() + + def test_objmode_invalid_use(self): + @njit + def moderror(): + with objmode(bad=1 + 1): + out = 1 + return val + with self.assertRaisesRegex( + errors.CompilerError, + ("Error handling objmode argument 'bad'. " + "The value must be a compile-time constant either as " + "a non-local variable or a getattr expression that " + "refers to a Numba type."), + ): + moderror() + + def test_objmode_multi_type_args(self): + array_ty = types.int32[:] + @njit + def foo(): + # t1 is a string + # t2 is a global type + # t3 is a non-local/freevar + with objmode(t1="float64", t2=gv_type, t3=array_ty): + t1 = 793856.5 + t2 = t1 # to observe truncation + t3 = np.arange(5).astype(np.int32) + return t1, t2, t3 + + t1, t2, t3 = foo() + self.assertPreciseEqual(t1, 793856.5) + self.assertPreciseEqual(t2, 793856) + self.assertPreciseEqual(t3, np.arange(5).astype(np.int32)) + + def test_objmode_jitclass(self): + spec = [ + ('value', types.int32), # a simple scalar field + ('array', types.float32[:]), # an array field + ] + + @jitclass(spec) + class Bag(object): + def __init__(self, value): + self.value = value + self.array = np.zeros(value, dtype=np.float32) + + @property + def size(self): + return self.array.size + + def increment(self, val): + for i in range(self.size): + self.array[i] += val + return self.array + + @staticmethod + def add(x, y): + return x + y + + n = 21 + mybag = Bag(n) + + def foo(): + pass + + @overload(foo) + def foo_overload(): + shrubbery = mybag._numba_type_ + def impl(): + with objmode(out=shrubbery): + out = Bag(123) + out.increment(3) + return out + return impl + + @njit + def bar(): + return foo() + + z = bar() + self.assertIsInstance(z, Bag) + self.assertEqual(z.add(2, 3), 2 + 3) + exp_array = np.zeros(123, dtype=np.float32) + 3 + self.assertPreciseEqual(z.array, exp_array) + + + @staticmethod + def case_objmode_cache(x): + with objmode(output='float64'): + output = x / 10 + return output + + def test_objmode_reflected_list(self): + ret_type = typeof([1, 2, 3, 4, 5]) + @njit + def test2(): + with objmode(out=ret_type): + out = [1, 2, 3, 4, 5] + return out + + with self.assertRaises(errors.CompilerError) as raises: + test2() + self.assertRegex( + str(raises.exception), + (r"Objmode context failed. " + r"Argument 'out' is declared as an unsupported type: " + r"reflected list\(int(32|64)\). " + r"Reflected types are not supported."), + ) + + def test_objmode_reflected_set(self): + ret_type = typeof({1, 2, 3, 4, 5}) + @njit + def test2(): + with objmode(result=ret_type): + result = {1, 2, 3, 4, 5} + return result + + with self.assertRaises(errors.CompilerError) as raises: + test2() + self.assertRegex( + str(raises.exception), + (r"Objmode context failed. " + r"Argument 'result' is declared as an unsupported type: " + r"reflected set\(int(32|64)\). " + r"Reflected types are not supported."), + ) + + def test_objmode_typed_dict(self): + ret_type = types.DictType(types.unicode_type, types.int64) + @njit + def test4(): + with objmode(res=ret_type): + res = {'A': 1, 'B': 2} + return res + + with self.assertRaises(TypeError) as raises: + test4() + self.assertIn( + ("can't unbox a " + "as a "), + str(raises.exception), + ) + + def test_objmode_typed_list(self): + ret_type = types.ListType(types.int64) + @njit + def test4(): + with objmode(res=ret_type): + res = [1, 2] + return res + + with self.assertRaises(TypeError) as raises: + test4() + self.assertRegex( + str(raises.exception), + (r"can't unbox a " + r"as a ()?"), + ) + + def test_objmode_use_of_view(self): + # See issue #7158, npm functionality should only be validated if in + # npm. + @njit + def foo(x): + with numba.objmode(y="int64[::1]"): + y = x.view("int64") + return y + + a = np.ones(1, np.int64).view('float64') + expected = foo.py_func(a) + got = foo(a) + self.assertPreciseEqual(expected, got) + + +def case_inner_pyfunc(x): + return x / 10 + + +def case_objmode_cache(x): + with objmode(output='float64'): + output = case_inner_pyfunc(x) + return output + + +class TestLiftObjCaching(MemoryLeak, TestCase): + # Warnings in this test class are converted to errors + + def setUp(self): + warnings.simplefilter("error", errors.NumbaWarning) + + def tearDown(self): + warnings.resetwarnings() + + def check(self, py_func): + first = njit(cache=True)(py_func) + self.assertEqual(first(123), 12.3) + + second = njit(cache=True)(py_func) + self.assertFalse(second._cache_hits) + self.assertEqual(second(123), 12.3) + self.assertTrue(second._cache_hits) + + def test_objmode_caching_basic(self): + def pyfunc(x): + with objmode(output='float64'): + output = x / 10 + return output + + self.check(pyfunc) + + def test_objmode_caching_call_closure_bad(self): + def other_pyfunc(x): + return x / 10 + + def pyfunc(x): + with objmode(output='float64'): + output = other_pyfunc(x) + return output + + self.check(pyfunc) + + def test_objmode_caching_call_closure_good(self): + self.check(case_objmode_cache) + + +class TestBogusContext(BaseTestWithLifting): + + def test_undefined_global(self): + the_ir = get_func_ir(lift_undefiend) + with self.assertRaises(errors.CompilerError) as raises: + with_lifting( + the_ir, self.typingctx, self.targetctx, self.flags, locals={}, + ) + self.assertIn( + "Undefined variable used as context manager", + str(raises.exception), + ) + + def test_invalid(self): + the_ir = get_func_ir(lift_invalid) + with self.assertRaises(errors.CompilerError) as raises: + with_lifting( + the_ir, self.typingctx, self.targetctx, self.flags, locals={}, + ) + self.assertIn( + "Unsupported context manager in use", + str(raises.exception), + ) + + def test_with_as_fails_gracefully(self): + @njit + def foo(): + with bypass_context as bp: + pass + + with self.assertRaises(errors.UnsupportedBytecodeError) as raises: + foo() + + excstr = str(raises.exception) + msg = ("The 'with (context manager) as (variable):' construct is not " + "supported.") + self.assertIn(msg, excstr) + + +class TestMisc(TestCase): + # Tests for miscellaneous objmode issues. Run serially. + + _numba_parallel_test_ = False + + @linux_only + @TestCase.run_test_in_subprocess + def test_no_fork_in_compilation(self): + # Checks that there is no fork/clone/execve during compilation, see + # issue #7881. This needs running in a subprocess as the offending fork + # call that triggered #7881 occurs on the first call to uuid1 as it's + # part if the initialisation process for that function (gets hardware + # address of machine). + + if not strace_supported(): + # Needs strace support. + self.skipTest("strace support missing") + + def force_compile(): + @njit('void()') # force compilation + def f(): + with numba.objmode(): + pass + + # capture these syscalls: + syscalls = ['fork', 'clone', 'execve'] + + # check that compilation does not trigger fork, clone or execve + strace_data = strace(force_compile, syscalls) + self.assertFalse(strace_data) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/3a/3a99e539a991e605f54bb315b59146c676edd457a6ff0587d48adce5aaa476ae/test_is_monotonic.py b/shared/package-files/3a/3a99e539a991e605f54bb315b59146c676edd457a6ff0587d48adce5aaa476ae/test_is_monotonic.py new file mode 100644 index 0000000000000000000000000000000000000000..3428fc90f6e51a0bde0aba9c8ea08ebf414e5556 --- /dev/null +++ b/shared/package-files/3a/3a99e539a991e605f54bb315b59146c676edd457a6ff0587d48adce5aaa476ae/test_is_monotonic.py @@ -0,0 +1,78 @@ +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Index, + Series, +) +import pandas._testing as tm + + +@pytest.mark.parametrize( + "in_vals, out_vals", + [ + # Basics: strictly increasing (T), strictly decreasing (F), + # abs val increasing (F), non-strictly increasing (T) + ([1, 2, 5, 3, 2, 0, 4, 5, -6, 1, 1], [True, False, False, True]), + # Test with inf vals + ( + [1, 2.1, np.inf, 3, 2, np.inf, -np.inf, 5, 11, 1, -np.inf], + [True, False, True, False], + ), + # Test with nan vals; should always be False + ( + [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan], + [False, False, False, False], + ), + ], +) +def test_is_monotonic_increasing(in_vals, out_vals): + # GH 17015 + source_dict = { + "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], + "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"], + "C": in_vals, + } + df = DataFrame(source_dict) + result = df.groupby("B").C.is_monotonic_increasing + index = Index(list("abcd"), name="B") + expected = Series(index=index, data=out_vals, name="C") + tm.assert_series_equal(result, expected) + + # Also check result equal to manually taking x.is_monotonic_increasing. + expected = df.groupby(["B"]).C.apply(lambda x: x.is_monotonic_increasing) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "in_vals, out_vals", + [ + # Basics: strictly decreasing (T), strictly increasing (F), + # abs val decreasing (F), non-strictly increasing (T) + ([10, 9, 7, 3, 4, 5, -3, 2, 0, 1, 1], [True, False, False, True]), + # Test with inf vals + ( + [np.inf, 1, -np.inf, np.inf, 2, -3, -np.inf, 5, -3, -np.inf, -np.inf], + [True, True, False, True], + ), + # Test with nan vals; should always be False + ( + [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan], + [False, False, False, False], + ), + ], +) +def test_is_monotonic_decreasing(in_vals, out_vals): + # GH 17015 + source_dict = { + "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], + "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"], + "C": in_vals, + } + + df = DataFrame(source_dict) + result = df.groupby("B").C.is_monotonic_decreasing + index = Index(list("abcd"), name="B") + expected = Series(index=index, data=out_vals, name="C") + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/3a/3a9a4166a4c06626fd1d8ed4f400be25abceee6e8dc4f194b547cf40097da016/Tongatapu b/shared/package-files/3a/3a9a4166a4c06626fd1d8ed4f400be25abceee6e8dc4f194b547cf40097da016/Tongatapu new file mode 100644 index 0000000000000000000000000000000000000000..c8824ab5434985650f33e12eace1981f8b116207 Binary files /dev/null and b/shared/package-files/3a/3a9a4166a4c06626fd1d8ed4f400be25abceee6e8dc4f194b547cf40097da016/Tongatapu differ diff --git a/shared/package-files/3a/3a9afcedfd6d63cca9fc6ec6398f28b8596547feef7df37fa24ecd75ff7c8e81/string.tpl b/shared/package-files/3a/3a9afcedfd6d63cca9fc6ec6398f28b8596547feef7df37fa24ecd75ff7c8e81/string.tpl new file mode 100644 index 0000000000000000000000000000000000000000..06aeb2b4e413c61a912b535056c19c794d4b9c85 --- /dev/null +++ b/shared/package-files/3a/3a9afcedfd6d63cca9fc6ec6398f28b8596547feef7df37fa24ecd75ff7c8e81/string.tpl @@ -0,0 +1,12 @@ +{% for r in head %} +{% for c in r %}{% if c["is_visible"] %} +{{ c["display_value"] }}{% if not loop.last %}{{ delimiter }}{% endif %} +{% endif %}{% endfor %} + +{% endfor %} +{% for r in body %} +{% for c in r %}{% if c["is_visible"] %} +{{ c["display_value"] }}{% if not loop.last %}{{ delimiter }}{% endif %} +{% endif %}{% endfor %} + +{% endfor %} diff --git a/shared/package-files/3a/3aa03d8ad4b6a2c4013fe9a9f2324af51259269b3854fb1322f405097e046c63/inference.py b/shared/package-files/3a/3aa03d8ad4b6a2c4013fe9a9f2324af51259269b3854fb1322f405097e046c63/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..f551716772f61455a330bdb308cee830bd54fb03 --- /dev/null +++ b/shared/package-files/3a/3aa03d8ad4b6a2c4013fe9a9f2324af51259269b3854fb1322f405097e046c63/inference.py @@ -0,0 +1,437 @@ +""" basic inference routines """ + +from __future__ import annotations + +from collections import abc +from numbers import Number +import re +from re import Pattern +from typing import TYPE_CHECKING + +import numpy as np + +from pandas._libs import lib + +if TYPE_CHECKING: + from collections.abc import Hashable + + from pandas._typing import TypeGuard + +is_bool = lib.is_bool + +is_integer = lib.is_integer + +is_float = lib.is_float + +is_complex = lib.is_complex + +is_scalar = lib.is_scalar + +is_decimal = lib.is_decimal + +is_interval = lib.is_interval + +is_list_like = lib.is_list_like + +is_iterator = lib.is_iterator + + +def is_number(obj) -> TypeGuard[Number | np.number]: + """ + Check if the object is a number. + + Returns True when the object is a number, and False if is not. + + Parameters + ---------- + obj : any type + The object to check if is a number. + + Returns + ------- + bool + Whether `obj` is a number or not. + + See Also + -------- + api.types.is_integer: Checks a subgroup of numbers. + + Examples + -------- + >>> from pandas.api.types import is_number + >>> is_number(1) + True + >>> is_number(7.15) + True + + Booleans are valid because they are int subclass. + + >>> is_number(False) + True + + >>> is_number("foo") + False + >>> is_number("5") + False + """ + return isinstance(obj, (Number, np.number)) + + +def iterable_not_string(obj) -> bool: + """ + Check if the object is an iterable but not a string. + + Parameters + ---------- + obj : The object to check. + + Returns + ------- + is_iter_not_string : bool + Whether `obj` is a non-string iterable. + + Examples + -------- + >>> iterable_not_string([1, 2, 3]) + True + >>> iterable_not_string("foo") + False + >>> iterable_not_string(1) + False + """ + return isinstance(obj, abc.Iterable) and not isinstance(obj, str) + + +def is_file_like(obj) -> bool: + """ + Check if the object is a file-like object. + + For objects to be considered file-like, they must + be an iterator AND have either a `read` and/or `write` + method as an attribute. + + Note: file-like objects must be iterable, but + iterable objects need not be file-like. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + bool + Whether `obj` has file-like properties. + + Examples + -------- + >>> import io + >>> from pandas.api.types import is_file_like + >>> buffer = io.StringIO("data") + >>> is_file_like(buffer) + True + >>> is_file_like([1, 2, 3]) + False + """ + if not (hasattr(obj, "read") or hasattr(obj, "write")): + return False + + return bool(hasattr(obj, "__iter__")) + + +def is_re(obj) -> TypeGuard[Pattern]: + """ + Check if the object is a regex pattern instance. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + bool + Whether `obj` is a regex pattern. + + Examples + -------- + >>> from pandas.api.types import is_re + >>> import re + >>> is_re(re.compile(".*")) + True + >>> is_re("foo") + False + """ + return isinstance(obj, Pattern) + + +def is_re_compilable(obj) -> bool: + """ + Check if the object can be compiled into a regex pattern instance. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + bool + Whether `obj` can be compiled as a regex pattern. + + Examples + -------- + >>> from pandas.api.types import is_re_compilable + >>> is_re_compilable(".*") + True + >>> is_re_compilable(1) + False + """ + try: + re.compile(obj) + except TypeError: + return False + else: + return True + + +def is_array_like(obj) -> bool: + """ + Check if the object is array-like. + + For an object to be considered array-like, it must be list-like and + have a `dtype` attribute. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_array_like : bool + Whether `obj` has array-like properties. + + Examples + -------- + >>> is_array_like(np.array([1, 2, 3])) + True + >>> is_array_like(pd.Series(["a", "b"])) + True + >>> is_array_like(pd.Index(["2016-01-01"])) + True + >>> is_array_like([1, 2, 3]) + False + >>> is_array_like(("a", "b")) + False + """ + return is_list_like(obj) and hasattr(obj, "dtype") + + +def is_nested_list_like(obj) -> bool: + """ + Check if the object is list-like, and that all of its elements + are also list-like. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_list_like : bool + Whether `obj` has list-like properties. + + Examples + -------- + >>> is_nested_list_like([[1, 2, 3]]) + True + >>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}]) + True + >>> is_nested_list_like(["foo"]) + False + >>> is_nested_list_like([]) + False + >>> is_nested_list_like([[1, 2, 3], 1]) + False + + Notes + ----- + This won't reliably detect whether a consumable iterator (e. g. + a generator) is a nested-list-like without consuming the iterator. + To avoid consuming it, we always return False if the outer container + doesn't define `__len__`. + + See Also + -------- + is_list_like + """ + return ( + is_list_like(obj) + and hasattr(obj, "__len__") + and len(obj) > 0 + and all(is_list_like(item) for item in obj) + ) + + +def is_dict_like(obj) -> bool: + """ + Check if the object is dict-like. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + bool + Whether `obj` has dict-like properties. + + Examples + -------- + >>> from pandas.api.types import is_dict_like + >>> is_dict_like({1: 2}) + True + >>> is_dict_like([1, 2, 3]) + False + >>> is_dict_like(dict) + False + >>> is_dict_like(dict()) + True + """ + dict_like_attrs = ("__getitem__", "keys", "__contains__") + return ( + all(hasattr(obj, attr) for attr in dict_like_attrs) + # [GH 25196] exclude classes + and not isinstance(obj, type) + ) + + +def is_named_tuple(obj) -> bool: + """ + Check if the object is a named tuple. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + bool + Whether `obj` is a named tuple. + + Examples + -------- + >>> from collections import namedtuple + >>> from pandas.api.types import is_named_tuple + >>> Point = namedtuple("Point", ["x", "y"]) + >>> p = Point(1, 2) + >>> + >>> is_named_tuple(p) + True + >>> is_named_tuple((1, 2)) + False + """ + return isinstance(obj, abc.Sequence) and hasattr(obj, "_fields") + + +def is_hashable(obj) -> TypeGuard[Hashable]: + """ + Return True if hash(obj) will succeed, False otherwise. + + Some types will pass a test against collections.abc.Hashable but fail when + they are actually hashed with hash(). + + Distinguish between these and other types by trying the call to hash() and + seeing if they raise TypeError. + + Returns + ------- + bool + + Examples + -------- + >>> import collections + >>> from pandas.api.types import is_hashable + >>> a = ([],) + >>> isinstance(a, collections.abc.Hashable) + True + >>> is_hashable(a) + False + """ + # Unfortunately, we can't use isinstance(obj, collections.abc.Hashable), + # which can be faster than calling hash. That is because numpy scalars + # fail this test. + + # Reconsider this decision once this numpy bug is fixed: + # https://github.com/numpy/numpy/issues/5562 + + try: + hash(obj) + except TypeError: + return False + else: + return True + + +def is_sequence(obj) -> bool: + """ + Check if the object is a sequence of objects. + String types are not included as sequences here. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_sequence : bool + Whether `obj` is a sequence of objects. + + Examples + -------- + >>> l = [1, 2, 3] + >>> + >>> is_sequence(l) + True + >>> is_sequence(iter(l)) + False + """ + try: + iter(obj) # Can iterate over it. + len(obj) # Has a length associated with it. + return not isinstance(obj, (str, bytes)) + except (TypeError, AttributeError): + return False + + +def is_dataclass(item) -> bool: + """ + Checks if the object is a data-class instance + + Parameters + ---------- + item : object + + Returns + -------- + is_dataclass : bool + True if the item is an instance of a data-class, + will return false if you pass the data class itself + + Examples + -------- + >>> from dataclasses import dataclass + >>> @dataclass + ... class Point: + ... x: int + ... y: int + + >>> is_dataclass(Point) + False + >>> is_dataclass(Point(0,2)) + True + + """ + try: + import dataclasses + + return dataclasses.is_dataclass(item) and not isinstance(item, type) + except ImportError: + return False diff --git a/shared/package-files/3a/3aa1a051d703757ab81dd1d65bd9e2af444e4a701e5399a6bed18947e316a75b/extensions.py b/shared/package-files/3a/3aa1a051d703757ab81dd1d65bd9e2af444e4a701e5399a6bed18947e316a75b/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..e7806ad8146d7c7f22e9553804127128e8b1fd02 --- /dev/null +++ b/shared/package-files/3a/3aa1a051d703757ab81dd1d65bd9e2af444e4a701e5399a6bed18947e316a75b/extensions.py @@ -0,0 +1,11 @@ +""" +NumPy extensions. +""" +from numba.np.numpy_support import numpy_version + +if numpy_version < (2, 5): + from numba.np.arraymath import cross2d + + __all__ = [ + 'cross2d' + ] diff --git a/shared/package-files/3a/3aa1baa56416fd27743d2ade5b808607ca1aafd10dbeca7e14c692f7d0b4d634/as_strided_copy_native.h b/shared/package-files/3a/3aa1baa56416fd27743d2ade5b808607ca1aafd10dbeca7e14c692f7d0b4d634/as_strided_copy_native.h new file mode 100644 index 0000000000000000000000000000000000000000..37b1a6ea327e4cff03bf29f93aa35368bc32f195 --- /dev/null +++ b/shared/package-files/3a/3aa1baa56416fd27743d2ade5b808607ca1aafd10dbeca7e14c692f7d0b4d634/as_strided_copy_native.h @@ -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 & as_strided_copy_out_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset, at::Tensor & out); +TORCH_API at::Tensor as_strided_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3aa3b74e82a9de74d47933cfabb0c674956a8dca468f557a7c2c0915a2fe3c9b/multi_margin_loss.h b/shared/package-files/3a/3aa3b74e82a9de74d47933cfabb0c674956a8dca468f557a7c2c0915a2fe3c9b/multi_margin_loss.h new file mode 100644 index 0000000000000000000000000000000000000000..4912a69e9b048feccb16d754211bbdd10ffb9f3e --- /dev/null +++ b/shared/package-files/3a/3aa3b74e82a9de74d47933cfabb0c674956a8dca468f557a7c2c0915a2fe3c9b/multi_margin_loss.h @@ -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::multi_margin_loss.out(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & multi_margin_loss_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const at::Scalar & p=1, const at::Scalar & margin=1, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean) { + return at::_ops::multi_margin_loss_out::call(self, target, p, margin, weight, reduction, out); +} +// aten::multi_margin_loss.out(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & multi_margin_loss_outf(const at::Tensor & self, const at::Tensor & target, const at::Scalar & p, const at::Scalar & margin, const c10::optional & weight, int64_t reduction, at::Tensor & out) { + return at::_ops::multi_margin_loss_out::call(self, target, p, margin, weight, reduction, out); +} + +// aten::multi_margin_loss(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean) -> Tensor +inline at::Tensor multi_margin_loss(const at::Tensor & self, const at::Tensor & target, const at::Scalar & p=1, const at::Scalar & margin=1, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean) { + return at::_ops::multi_margin_loss::call(self, target, p, margin, weight, reduction); +} + +} diff --git a/shared/package-files/3a/3aa7d617b62e2d001da22119afbcd296a1cecd5f2849e0f3f7769109a4d3e50b/_prediction_inference.py b/shared/package-files/3a/3aa7d617b62e2d001da22119afbcd296a1cecd5f2849e0f3f7769109a4d3e50b/_prediction_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..3c70bd2a64d49390bef7fd22ee177cbadb855a17 --- /dev/null +++ b/shared/package-files/3a/3aa7d617b62e2d001da22119afbcd296a1cecd5f2849e0f3f7769109a4d3e50b/_prediction_inference.py @@ -0,0 +1,955 @@ +""" +Created on Fri Dec 19 11:29:18 2014 + +Author: Josef Perktold +License: BSD-3 + +""" + +import numpy as np +import pandas as pd +from scipy import stats + +from statsmodels.tools.validation import string_like + + +# this is similar to ContrastResults after t_test, partially copied, adjusted +class PredictionResultsBase: + """Base class for get_prediction results""" + + def __init__( + self, + predicted, + var_pred, + func=None, + deriv=None, + df=None, + dist=None, + row_labels=None, + **kwds, + ): + self.predicted = predicted + self.var_pred = var_pred + self.func = func + self.deriv = deriv + self.df = df + self.row_labels = row_labels + self.__dict__.update(kwds) + + if dist is None or dist == "norm": + self.dist = stats.norm + self.dist_args = () + elif dist == "t": + self.dist = stats.t + self.dist_args = (self.df,) + else: + self.dist = dist + self.dist_args = () + + @property + def se(self): + return np.sqrt(self.var_pred) + + @property + def tvalues(self): + return self.predicted / self.se + + def t_test(self, value=0, alternative="two-sided"): + """z- or t-test for hypothesis that mean is equal to value + + Parameters + ---------- + value : array_like, optional + Value under the null hypothesis. + alternative : str, optional + 'two-sided', 'larger', 'smaller'. + + Returns + ------- + stat : ndarray + The test statistic. + pvalue : ndarray + The p-value of the hypothesis test, the distribution is given by + the attribute of the instance, specified in `__init__`. Default + if not specified is the normal distribution. + """ + alternative = string_like( + alternative, + "alternative", + options=("two-sided", "larger", "smaller"), + lower=False, + deprecated={ + "2-sided": "two-sided", + "2s": "two-sided", + "l": "larger", + "s": "smaller", + }, + removed_after="0.16", + ) + # assumes symmetric distribution + stat = (self.predicted - value) / self.se + + if alternative == "two-sided": + pvalue = self.dist.sf(np.abs(stat), *self.dist_args) * 2 + elif alternative == "larger": + pvalue = self.dist.sf(stat, *self.dist_args) + elif alternative == "smaller": + pvalue = self.dist.cdf(stat, *self.dist_args) + return stat, pvalue + + def _conf_int_generic(self, center, se, alpha, dist_args=None): + """internal function to avoid code duplication""" + if dist_args is None: + dist_args = () + + q = self.dist.ppf(1 - alpha / 2.0, *dist_args) + lower = center - q * se + upper = center + q * se + ci = np.column_stack((lower, upper)) + # if we want to stack at a new last axis, for lower.ndim > 1 + # np.concatenate((lower[..., None], upper[..., None]), axis=-1) + return ci + + def conf_int(self, *, alpha=0.05, **kwds): + """Confidence interval for the predicted value + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + kwds : extra keyword arguments + Ignored in base class, only for compatibility, consistent signature + with subclasses. + + Returns + ------- + ci : ndarray, (k_constraints, 2) + The array has the lower and the upper limit of the confidence + interval in the columns. + """ + + ci = self._conf_int_generic( + self.predicted, self.se, alpha, dist_args=self.dist_args + ) + return ci + + def summary_frame(self, alpha=0.05): + """Summary frame + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + + Returns + ------- + DataFrame + A DataFrame with columns 'predicted', 'se', 'ci_lower', 'ci_upper'. + """ + ci = self.conf_int(alpha=alpha) + to_include = {} + to_include["predicted"] = self.predicted + to_include["se"] = self.se + to_include["ci_lower"] = ci[:, 0] + to_include["ci_upper"] = ci[:, 1] + + self.table = to_include + # pandas dict does not handle 2d_array + # data = np.column_stack(list(to_include.values())) + # names = .... + res = pd.DataFrame(to_include, index=self.row_labels, columns=to_include.keys()) + return res + + +class PredictionResultsMonotonic(PredictionResultsBase): + + def __init__( + self, + predicted, + var_pred, + linpred=None, + linpred_se=None, + func=None, + deriv=None, + df=None, + dist=None, + row_labels=None, + ): + # TODO: is var_resid used? drop from arguments? + self.predicted = predicted + self.var_pred = var_pred + self.linpred = linpred + self.linpred_se = linpred_se + self.func = func + self.deriv = deriv + self.df = df + self.row_labels = row_labels + + if dist is None or dist == "norm": + self.dist = stats.norm + self.dist_args = () + elif dist == "t": + self.dist = stats.t + self.dist_args = (self.df,) + else: + self.dist = dist + self.dist_args = () + + def _conf_int_generic(self, center, se, alpha, dist_args=None): + """internal function to avoid code duplication""" + if dist_args is None: + dist_args = () + + q = self.dist.ppf(1 - alpha / 2.0, *dist_args) + lower = center - q * se + upper = center + q * se + ci = np.column_stack((lower, upper)) + # if we want to stack at a new last axis, for lower.ndim > 1 + # np.concatenate((lower[..., None], upper[..., None]), axis=-1) + return ci + + def conf_int(self, method="endpoint", alpha=0.05, **kwds): + """Confidence interval for the predicted value + + This is currently only available for t and z tests. + + Parameters + ---------- + method : {"endpoint", "delta"}, optional + Method for confidence interval. + If method is "endpoint", then the confidence interval of the + linear predictor is transformed by the prediction function. + If method is "delta", then the delta-method is used. The confidence + interval in this case might reach outside the range of the + prediction, for example probabilities larger than one or smaller + than zero. + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + kwds : extra keyword arguments + Currently ignored, only for compatibility, consistent signature. + + Returns + ------- + ci : ndarray, (k_constraints, 2) + The array has the lower and the upper limit of the confidence + interval in the columns. + """ + method = string_like( + method, "method", options=("endpoint", "delta"), lower=False + ) + tmp = np.linspace(0, 1, 6) + # TODO: drop check? + is_linear = (self.func(tmp) == tmp).all() + if method == "endpoint" and not is_linear: + ci_linear = self._conf_int_generic( + self.linpred, self.linpred_se, alpha, dist_args=self.dist_args + ) + ci = self.func(ci_linear) + elif method == "delta" or is_linear: + ci = self._conf_int_generic( + self.predicted, self.se, alpha, dist_args=self.dist_args + ) + + return ci + + +class PredictionResultsDelta(PredictionResultsBase): + """Prediction results based on delta method""" + + def __init__(self, results_delta, **kwds): + + predicted = results_delta.predicted() + var_pred = results_delta.var() + + super().__init__(predicted, var_pred, **kwds) + + +class PredictionResultsMean(PredictionResultsBase): + """Prediction results for GLM + + This results class is used for backwards compatibility for + `get_prediction` with GLM. The new PredictionResults classes dropped the + `_mean` post fix in the attribute names. + """ + + def __init__( + self, + predicted_mean, + var_pred_mean, + var_resid=None, + df=None, + dist=None, + row_labels=None, + linpred=None, + link=None, + ): + # TODO: is var_resid used? drop from arguments? + self.predicted = predicted_mean + self.var_pred = var_pred_mean + self.df = df + self.var_resid = var_resid + self.row_labels = row_labels + self.linpred = linpred + self.link = link + + if dist is None or dist == "norm": + self.dist = stats.norm + self.dist_args = () + elif dist == "t": + self.dist = stats.t + self.dist_args = (self.df,) + else: + self.dist = dist + self.dist_args = () + + @property + def predicted_mean(self): + # alias for backwards compatibility + return self.predicted + + @property + def var_pred_mean(self): + # alias for backwards compatibility + return self.var_pred + + @property + def se_mean(self): + # alias for backwards compatibility + return self.se + + def conf_int(self, method="endpoint", alpha=0.05, **kwds): + """Confidence interval for the predicted value + + This is currently only available for t and z tests. + + Parameters + ---------- + method : {"endpoint", "delta"}, optional + Method for confidence interval. + If method is "endpoint", then the confidence interval of the + linear predictor is transformed by the prediction function. + If method is "delta", then the delta-method is used. The confidence + interval in this case might reach outside the range of the + prediction, for example probabilities larger than one or smaller + than zero. + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + kwds : extra keyword arguments + Currently ignored, only for compatibility, consistent signature. + + Returns + ------- + ci : ndarray, (k_constraints, 2) + The array has the lower and the upper limit of the confidence + interval in the columns. + """ + method = string_like( + method, "method", options=("endpoint", "delta"), lower=False + ) + tmp = np.linspace(0, 1, 6) + is_linear = (self.link.inverse(tmp) == tmp).all() + if method == "endpoint" and not is_linear: + ci_linear = self.linpred.conf_int(alpha=alpha, obs=False) + ci = self.link.inverse(ci_linear) + elif method == "delta" or is_linear: + se = self.se_mean + q = self.dist.ppf(1 - alpha / 2.0, *self.dist_args) + lower = self.predicted_mean - q * se + upper = self.predicted_mean + q * se + ci = np.column_stack((lower, upper)) + # if we want to stack at a new last axis, for lower.ndim > 1 + # np.concatenate((lower[..., None], upper[..., None]), axis=-1) + + return ci + + def summary_frame(self, alpha=0.05): + """Summary frame + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + + Returns + ------- + DataFrame + A DataFrame with columns 'mean', 'mean_se', 'mean_ci_lower', + 'mean_ci_upper'. + """ + # TODO: finish and cleanup + ci_mean = self.conf_int(alpha=alpha) + to_include = {} + to_include["mean"] = self.predicted_mean + to_include["mean_se"] = self.se_mean + to_include["mean_ci_lower"] = ci_mean[:, 0] + to_include["mean_ci_upper"] = ci_mean[:, 1] + + self.table = to_include + # pandas dict does not handle 2d_array + # data = np.column_stack(list(to_include.values())) + # names = .... + res = pd.DataFrame(to_include, index=self.row_labels, columns=to_include.keys()) + return res + + +def _get_exog_predict(self, exog=None, transform=True, row_labels=None): + """Prepare or transform exog for prediction + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str, optional + If row_labels are provided, then they will replace the generated + labels. + + Returns + ------- + exog : ndarray + Prediction exog + row_labels : list of str or None + Labels or pandas index for rows of prediction + """ + + # prepare exog and row_labels, based on base Results.predict + if transform and hasattr(self.model, "formula") and exog is not None: + from statsmodels.formula._manager import FormulaManager + + mgr = FormulaManager() + if isinstance(exog, pd.Series): + exog = pd.DataFrame(exog) + exog = mgr.get_matrices(self.model.data.model_spec, exog) + + if exog is not None: + if row_labels is None: + row_labels = getattr(exog, "index", None) + if callable(row_labels): + row_labels = None + + exog = np.asarray(exog) + if exog.ndim == 1 and ( + self.model.exog.ndim == 1 or self.model.exog.shape[1] == 1 + ): + exog = exog[:, None] + exog = np.atleast_2d(exog) # needed in count model shape[1] + else: + exog = self.model.exog + + if row_labels is None: + row_labels = getattr(self.model.data, "row_labels", None) + return exog, row_labels + + +def get_prediction_glm( + self, + exog=None, + transform=True, + row_labels=None, + linpred=None, + link=None, + pred_kwds=None, +): + """ + Compute prediction results for GLM compatible models. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str, optional + If row_labels are provided, then they will replace the generated + labels. + linpred : linear prediction instance, optional + Instance of linear prediction results used for confidence intervals + based on endpoint transformation. + link : instance of link function, optional + If no link function is provided, then the `model.family.link` is used. + pred_kwds : dict, optional + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. See the predict method of the + model for the details. + + Returns + ------- + prediction_results : PredictionResultsMean + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction of the mean and of new observations. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + + if pred_kwds is None: + pred_kwds = {} + + predicted_mean = self.model.predict(self.params, exog, **pred_kwds) + + covb = self.cov_params() + + link_deriv = self.model.family.link.inverse_deriv(linpred.predicted_mean) + var_pred_mean = link_deriv**2 * (exog * np.dot(covb, exog.T).T).sum(1) + var_resid = self.scale # self.mse_resid / weights + + # TODO: check that we have correct scale, Refactor scale #??? + # special case for now: + if self.cov_type == "fixed scale": + var_resid = self.cov_kwds["scale"] + + dist = ["norm", "t"][self.use_t] + if linpred is None: + linpred = self.get_prediction_linear( + exog=exog, transform=transform, row_labels=row_labels, pred_kwds=pred_kwds + ) + + return PredictionResultsMean( + predicted_mean, + var_pred_mean, + var_resid, + df=self.df_resid, + dist=dist, + row_labels=row_labels, + linpred=linpred, + link=link, + ) + + +def get_prediction_linear( + self, exog=None, transform=True, row_labels=None, pred_kwds=None, index=None +): + """ + Compute prediction results for linear prediction. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str, optional + If row_labels are provided, then they will replace the generated + labels. + pred_kwds : dict, optional + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. + See the predict method of the model for the details. + index : slice or array-index, optional + Is used to select rows and columns of cov_params, if the prediction + function only depends on a subset of parameters. + + Returns + ------- + prediction_results : PredictionResultsBase + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + + if pred_kwds is None: + pred_kwds = {} + + k1 = exog.shape[1] + if len(self.params) > k1: + # TODO: we allow endpoint transformation only for the first link + index = np.arange(k1) + else: + index = None + # get linear prediction and standard errors + covb = self.cov_params(column=index) + var_pred = (exog * np.dot(covb, exog.T).T).sum(1) + pred_kwds_linear = pred_kwds.copy() + pred_kwds_linear["which"] = "linear" + predicted = self.model.predict(self.params, exog, **pred_kwds_linear) + + dist = ["norm", "t"][self.use_t] + res = PredictionResultsBase( + predicted, var_pred, df=self.df_resid, dist=dist, row_labels=row_labels + ) + return res + + +def get_prediction_monotonic( + self, + exog=None, + transform=True, + row_labels=None, + link=None, + pred_kwds=None, + index=None, +): + """ + Compute prediction results when endpoint transformation is valid. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str, optional + If row_labels are provided, then they will replace the generated + labels. + link : instance of link function, optional + If no link function is provided, then the `model.family.link` is + used. + pred_kwds : dict, optional + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. + See the predict method of the model for the details. + index : slice or array-index, optional + Is used to select rows and columns of cov_params, if the prediction + function only depends on a subset of parameters. + + Returns + ------- + prediction_results : PredictionResultsMonotonic + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + + if pred_kwds is None: + pred_kwds = {} + + if link is None: + link = self.model.family.link + + func_deriv = link.inverse_deriv + + # get linear prediction and standard errors + covb = self.cov_params(column=index) + linpred_var = (exog * np.dot(covb, exog.T).T).sum(1) + pred_kwds_linear = pred_kwds.copy() + pred_kwds_linear["which"] = "linear" + linpred = self.model.predict(self.params, exog, **pred_kwds_linear) + + predicted = self.model.predict(self.params, exog, **pred_kwds) + link_deriv = func_deriv(linpred) + var_pred = link_deriv**2 * linpred_var + + dist = ["norm", "t"][self.use_t] + res = PredictionResultsMonotonic( + predicted, + var_pred, + df=self.df_resid, + dist=dist, + row_labels=row_labels, + linpred=linpred, + linpred_se=np.sqrt(linpred_var), + func=link.inverse, + deriv=func_deriv, + ) + return res + + +def get_prediction_delta( + self, + exog=None, + which="mean", + average=False, + agg_weights=None, + transform=True, + row_labels=None, + pred_kwds=None, +): + """ + Compute prediction results + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + which : str, optional + The statistic that is prediction. Which statistics are available + depends on the model.predict method. + average : bool, optional + If average is True, then the mean prediction is computed, that is, + predictions are computed for individual exog and then them mean over + observation is used. + If average is False, then the results are the predictions for all + observations, i.e., same length as ``exog``. + agg_weights : ndarray, optional + Aggregation weights, only used if average is True. + The weights are not normalized. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str, optional + If row_labels are provided, then they will replace the generated + labels. + pred_kwds : dict, optional + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. + See the predict method of the model for the details. + + Returns + ------- + prediction_results : PredictionResultsDelta + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction of the mean and of new observations. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + if agg_weights is None: + agg_weights = np.array(1.0) + + def f_pred(p): + """Prediction function as function of params""" + pred = self.model.predict(p, exog, which=which, **pred_kwds) + if average: + # using `.T` which should work if aggweights is 1-dim + pred = (pred.T * agg_weights.T).mean(-1).T + return pred + + nlpm = self._get_wald_nonlinear(f_pred) + # TODO: currently returns NonlinearDeltaCov + res = PredictionResultsDelta(nlpm) + return res + + +def get_prediction( + self, + exog=None, + transform=True, + which="mean", + row_labels=None, + average=False, + agg_weights=None, + pred_kwds=None, +): + """ + Compute prediction results when endpoint transformation is valid. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + which : str, optional + Which statistic is to be predicted. Default is "mean". + The available statistics and options depend on the model. + See the model.predict docstring. + row_labels : list of str, optional + If row_labels are provided, then they will replace the generated + labels. + average : bool, optional + If average is True, then the mean prediction is computed, that is, + predictions are computed for individual exog and then the average + over observation is used. + If average is False, then the results are the predictions for all + observations, i.e., same length as ``exog``. + agg_weights : ndarray, optional + Aggregation weights, only used if average is True. + The weights are not normalized. + pred_kwds : dict, optional + Some models can take additional keyword arguments, such as offset, + exposure or additional exog in multi-part models like zero inflated + models. + See the predict method of the model for the details. + + Returns + ------- + prediction_results : PredictionResultsBase + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and + summary dataframe for the prediction. + + Notes + ----- + Status: new in 0.14, experimental + """ + use_endpoint = getattr(self.model, "_use_endpoint", True) + + if which == "linear": + res = get_prediction_linear( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + pred_kwds=pred_kwds, + ) + + elif (which == "mean") and (use_endpoint is True) and (average is False): + # endpoint transformation + k1 = self.model.exog.shape[1] + if len(self.params) > k1: + # TODO: we allow endpoint transformation only for the first link + index = np.arange(k1) + else: + index = None + + pred_kwds["which"] = which + # TODO: add link or ilink to all link based models (except zi + link = getattr(self.model, "link", None) + if link is None: + # GLM + if hasattr(self.model, "family"): + link = getattr(self.model.family, "link", None) + if link is None: + # defaulting to log link for count models + import warnings + + warnings.warn("using default log-link in get_prediction", stacklevel=2) + from statsmodels.genmod.families import links + + link = links.Log() + res = get_prediction_monotonic( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + link=link, + pred_kwds=pred_kwds, + index=index, + ) + + else: + # which is not mean or linear, or we need averaging + res = get_prediction_delta( + self, + exog=exog, + which=which, + average=average, + agg_weights=agg_weights, + pred_kwds=pred_kwds, + ) + + return res + + +def params_transform_univariate( + params, cov_params, link=None, transform=None, row_labels=None +): + """ + Results for univariate, nonlinear, monotonically transformed parameters + + This provides transformed values, standard errors and confidence interval + for transformations of parameters, for example in calculating rates with + `exp(params)` in the case of Poisson or other models with exponential + mean function. + + Parameters + ---------- + params : array_like + Estimated model parameters. + cov_params : ndarray + Covariance matrix of the parameter estimates. + link : instance of link function, optional + The link function used to transform the parameters. If neither + link nor transform are provided, the log link is used. + transform : instance of link function, optional + Alias for `link`. Not used if `link` is provided. + row_labels : list of str, optional + If row_labels are provided, then they will replace the generated + labels. + + Returns + ------- + PredictionResultsMean + The transformed prediction results instance that can be used to + calculate confidence intervals for the transformed parameters. + """ + + from statsmodels.genmod.families import links + + if link is None and transform is None: + link = links.Log() + + if row_labels is None and hasattr(params, "index"): + row_labels = params.index + + params = np.asarray(params) + + predicted_mean = link.inverse(params) + link_deriv = link.inverse_deriv(params) + var_pred_mean = link_deriv**2 * np.diag(cov_params) + # TODO: do we want covariance also, or just var/se + + dist = stats.norm + + # TODO: need ci for linear prediction, method of `lin_pred + linpred = PredictionResultsMean( + params, + np.diag(cov_params), + dist=dist, + row_labels=row_labels, + link=links.Identity(), + ) + + res = PredictionResultsMean( + predicted_mean, + var_pred_mean, + dist=dist, + row_labels=row_labels, + linpred=linpred, + link=link, + ) + + return res diff --git a/shared/package-files/3a/3aa856c8e1159966f386bd897e268c9f57e50bce2953a9072f9bd8655d5b8543/test_common.h b/shared/package-files/3a/3aa856c8e1159966f386bd897e268c9f57e50bce2953a9072f9bd8655d5b8543/test_common.h new file mode 100644 index 0000000000000000000000000000000000000000..ba28836695cf615bbe86cca99548501acb978471 --- /dev/null +++ b/shared/package-files/3a/3aa856c8e1159966f386bd897e268c9f57e50bce2953a9072f9bd8655d5b8543/test_common.h @@ -0,0 +1,93 @@ +// 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/testing/gtest_util.h" +#include "arrow/util/iterator.h" + +namespace arrow { + +struct TestInt { + TestInt(); + TestInt(int i); // NOLINT runtime/explicit + int value; + + bool operator==(const TestInt& other) const; + + friend std::ostream& operator<<(std::ostream& os, const TestInt& v); +}; + +template <> +struct IterationTraits { + static TestInt End() { return TestInt(); } + static bool IsEnd(const TestInt& val) { return val == IterationTraits::End(); } +}; + +struct TestStr { + TestStr(); + TestStr(const std::string& s); // NOLINT runtime/explicit + TestStr(const char* s); // NOLINT runtime/explicit + explicit TestStr(const TestInt& test_int); + std::string value; + + bool operator==(const TestStr& other) const; + + friend std::ostream& operator<<(std::ostream& os, const TestStr& v); +}; + +template <> +struct IterationTraits { + static TestStr End() { return TestStr(); } + static bool IsEnd(const TestStr& val) { return val == IterationTraits::End(); } +}; + +std::vector RangeVector(unsigned int max, unsigned int step = 1); + +template +inline Iterator VectorIt(std::vector v) { + return MakeVectorIterator(std::move(v)); +} + +template +inline Iterator PossiblySlowVectorIt(std::vector v, bool slow = false) { + auto iterator = MakeVectorIterator(std::move(v)); + if (slow) { + return MakeTransformedIterator(std::move(iterator), + [](T item) -> Result> { + SleepABit(); + return TransformYield(item); + }); + } else { + return iterator; + } +} + +template +inline void AssertIteratorExhausted(Iterator& it) { + ASSERT_OK_AND_ASSIGN(T next, it.Next()); + ASSERT_TRUE(IsIterationEnd(next)); +} + +Transformer MakeFilter(std::function filter); + +// Assert equal contents of a memory area and a vector of bytes +void AssertBytesEqual(const uint8_t* left, const std::vector& right); + +} // namespace arrow diff --git a/shared/package-files/3a/3aaaa326d9c45e115d87e9e52874b1acd766cb4c578cecad667177d50849034c/_aix.py b/shared/package-files/3a/3aaaa326d9c45e115d87e9e52874b1acd766cb4c578cecad667177d50849034c/_aix.py new file mode 100644 index 0000000000000000000000000000000000000000..fc3e95cbcc88a530f08da216145675df65ff8864 --- /dev/null +++ b/shared/package-files/3a/3aaaa326d9c45e115d87e9e52874b1acd766cb4c578cecad667177d50849034c/_aix.py @@ -0,0 +1,331 @@ +""" +Lib/ctypes.util.find_library() support for AIX +Similar approach as done for Darwin support by using separate files +but unlike Darwin - no extension such as ctypes.macholib.* + +dlopen() is an interface to AIX initAndLoad() - primary documentation at: +https://www.ibm.com/support/knowledgecenter/en/ssw_aix_61/com.ibm.aix.basetrf1/dlopen.htm +https://www.ibm.com/support/knowledgecenter/en/ssw_aix_61/com.ibm.aix.basetrf1/load.htm + +AIX supports two styles for dlopen(): svr4 (System V Release 4) which is common on posix +platforms, but also a BSD style - aka SVR3. + +From AIX 5.3 Difference Addendum (December 2004) +2.9 SVR4 linking affinity +Nowadays, there are two major object file formats used by the operating systems: +XCOFF: The COFF enhanced by IBM and others. The original COFF (Common +Object File Format) was the base of SVR3 and BSD 4.2 systems. +ELF: Executable and Linking Format that was developed by AT&T and is a +base for SVR4 UNIX. + +While the shared library content is identical on AIX - one is located as a filepath name +(svr4 style) and the other is located as a member of an archive (and the archive +is located as a filepath name). + +The key difference arises when supporting multiple abi formats (i.e., 32 and 64 bit). +For svr4 either only one ABI is supported, or there are two directories, or there +are different file names. The most common solution for multiple ABI is multiple +directories. + +For the XCOFF (aka AIX) style - one directory (one archive file) is sufficient +as multiple shared libraries can be in the archive - even sharing the same name. +In documentation the archive is also referred to as the "base" and the shared +library object is referred to as the "member". + +For dlopen() on AIX (read initAndLoad()) the calls are similar. +Default activity occurs when no path information is provided. When path +information is provided dlopen() does not search any other directories. + +For SVR4 - the shared library name is the name of the file expected: libFOO.so +For AIX - the shared library is expressed as base(member). The search is for the +base (e.g., libFOO.a) and once the base is found the shared library - identified by +member (e.g., libFOO.so, or shr.o) is located and loaded. + +The mode bit RTLD_MEMBER tells initAndLoad() that it needs to use the AIX (SVR3) +naming style. +""" +__author__ = "Michael Felt " + +import re +from os import environ, path +from sys import executable +from ctypes import c_void_p, sizeof +from subprocess import Popen, PIPE, DEVNULL + +# Executable bit size - 32 or 64 +# Used to filter the search in an archive by size, e.g., -X64 +AIX_ABI = sizeof(c_void_p) * 8 + + +from sys import maxsize +def _last_version(libnames, sep): + def _num_version(libname): + # "libxyz.so.MAJOR.MINOR" => [MAJOR, MINOR] + parts = libname.split(sep) + nums = [] + try: + while parts: + nums.insert(0, int(parts.pop())) + except ValueError: + pass + return nums or [maxsize] + return max(reversed(libnames), key=_num_version) + +def get_ld_header(p): + # "nested-function, but placed at module level + ld_header = None + for line in p.stdout: + if line.startswith(('/', './', '../')): + ld_header = line + elif "INDEX" in line: + return ld_header.rstrip('\n') + return None + +def get_ld_header_info(p): + # "nested-function, but placed at module level + # as an ld_header was found, return known paths, archives and members + # these lines start with a digit + info = [] + for line in p.stdout: + if re.match("[0-9]", line): + info.append(line) + else: + # blank line (separator), consume line and end for loop + break + return info + +def get_ld_headers(file): + """ + Parse the header of the loader section of executable and archives + This function calls /usr/bin/dump -H as a subprocess + and returns a list of (ld_header, ld_header_info) tuples. + """ + # get_ld_headers parsing: + # 1. Find a line that starts with /, ./, or ../ - set as ld_header + # 2. If "INDEX" in occurs in a following line - return ld_header + # 3. get info (lines starting with [0-9]) + ldr_headers = [] + p = Popen(["/usr/bin/dump", f"-X{AIX_ABI}", "-H", file], + universal_newlines=True, stdout=PIPE, stderr=DEVNULL) + # be sure to read to the end-of-file - getting all entries + while True: + ld_header = get_ld_header(p) + if ld_header: + ldr_headers.append((ld_header, get_ld_header_info(p))) + else: + break + p.stdout.close() + p.wait() + return ldr_headers + +def get_shared(ld_headers): + """ + extract the shareable objects from ld_headers + character "[" is used to strip off the path information. + Note: the "[" and "]" characters that are part of dump -H output + are not removed here. + """ + shared = [] + for (line, _) in ld_headers: + # potential member lines contain "[" + # otherwise, no processing needed + if "[" in line: + # Strip off trailing colon (:) + shared.append(line[line.index("["):-1]) + return shared + +def get_one_match(expr, lines): + """ + Must be only one match, otherwise result is None. + When there is a match, strip leading "[" and trailing "]" + """ + # member names in the ld_headers output are between square brackets + expr = rf'\[({expr})\]' + matches = list(filter(None, (re.search(expr, line) for line in lines))) + if len(matches) == 1: + return matches[0].group(1) + else: + return None + +# additional processing to deal with AIX legacy names for 64-bit members +def get_legacy(members): + """ + This routine provides historical aka legacy naming schemes started + in AIX4 shared library support for library members names. + e.g., in /usr/lib/libc.a the member name shr.o for 32-bit binary and + shr_64.o for 64-bit binary. + """ + if AIX_ABI == 64: + # AIX 64-bit member is one of shr64.o, shr_64.o, or shr4_64.o + expr = r'shr4?_?64\.o' + member = get_one_match(expr, members) + if member: + return member + else: + # 32-bit legacy names - both shr.o and shr4.o exist. + # shr.o is the preferred name so we look for shr.o first + # i.e., shr4.o is returned only when shr.o does not exist + for name in ['shr.o', 'shr4.o']: + member = get_one_match(re.escape(name), members) + if member: + return member + return None + +def get_version(name, members): + """ + Sort list of members and return highest numbered version - if it exists. + This function is called when an unversioned libFOO.a(libFOO.so) has + not been found. + + Versioning for the member name is expected to follow + GNU LIBTOOL conventions: the highest version (x, then X.y, then X.Y.z) + * find [libFoo.so.X] + * find [libFoo.so.X.Y] + * find [libFoo.so.X.Y.Z] + + Before the GNU convention became the standard scheme regardless of + binary size AIX packagers used GNU convention "as-is" for 32-bit + archive members but used an "distinguishing" name for 64-bit members. + This scheme inserted either 64 or _64 between libFOO and .so + - generally libFOO_64.so, but occasionally libFOO64.so + """ + # the expression ending for versions must start as + # '.so.[0-9]', i.e., *.so.[at least one digit] + # while multiple, more specific expressions could be specified + # to search for .so.X, .so.X.Y and .so.X.Y.Z + # after the first required 'dot' digit + # any combination of additional 'dot' digits pairs are accepted + # anything more than libFOO.so.digits.digits.digits + # should be seen as a member name outside normal expectations + exprs = [rf'lib{name}\.so\.[0-9]+[0-9.]*', + rf'lib{name}_?64\.so\.[0-9]+[0-9.]*'] + for expr in exprs: + versions = [] + for line in members: + m = re.search(expr, line) + if m: + versions.append(m.group(0)) + if versions: + return _last_version(versions, '.') + return None + +def get_member(name, members): + """ + Return an archive member matching the request in name. + Name is the library name without any prefix like lib, suffix like .so, + or version number. + Given a list of members find and return the most appropriate result + Priority is given to generic libXXX.so, then a versioned libXXX.so.a.b.c + and finally, legacy AIX naming scheme. + """ + # look first for a generic match - prepend lib and append .so + expr = rf'lib{name}\.so' + member = get_one_match(expr, members) + if member: + return member + elif AIX_ABI == 64: + expr = rf'lib{name}64\.so' + member = get_one_match(expr, members) + if member: + return member + # since an exact match with .so as suffix was not found + # look for a versioned name + # If a versioned name is not found, look for AIX legacy member name + member = get_version(name, members) + if member: + return member + else: + return get_legacy(members) + +def get_libpaths(): + """ + On AIX, the buildtime searchpath is stored in the executable. + as "loader header information". + The command /usr/bin/dump -H extracts this info. + Prefix searched libraries with LD_LIBRARY_PATH (preferred), + or LIBPATH if defined. These paths are appended to the paths + to libraries the python executable is linked with. + This mimics AIX dlopen() behavior. + """ + libpaths = environ.get("LD_LIBRARY_PATH") + if libpaths is None: + libpaths = environ.get("LIBPATH") + if libpaths is None: + libpaths = [] + else: + libpaths = libpaths.split(":") + objects = get_ld_headers(executable) + for (_, lines) in objects: + for line in lines: + # the second (optional) argument is PATH if it includes a / + path = line.split()[1] + if "/" in path: + libpaths.extend(path.split(":")) + return libpaths + +def find_shared(paths, name): + """ + paths is a list of directories to search for an archive. + name is the abbreviated name given to find_library(). + Process: search "paths" for archive, and if an archive is found + return the result of get_member(). + If an archive is not found then return None + """ + for dir in paths: + # /lib is a symbolic link to /usr/lib, skip it + if dir == "/lib": + continue + # "lib" is prefixed to emulate compiler name resolution, + # e.g., -lc to libc + base = f'lib{name}.a' + archive = path.join(dir, base) + if path.exists(archive): + members = get_shared(get_ld_headers(archive)) + member = get_member(re.escape(name), members) + if member is not None: + return (base, member) + else: + return (None, None) + return (None, None) + +def find_library(name): + """AIX implementation of ctypes.util.find_library() + Find an archive member that will dlopen(). If not available, + also search for a file (or link) with a .so suffix. + + AIX supports two types of schemes that can be used with dlopen(). + The so-called SystemV Release4 (svr4) format is commonly suffixed + with .so while the (default) AIX scheme has the library (archive) + ending with the suffix .a + As an archive has multiple members (e.g., 32-bit and 64-bit) in one file + the argument passed to dlopen must include both the library and + the member names in a single string. + + find_library() looks first for an archive (.a) with a suitable member. + If no archive+member pair is found, look for a .so file. + """ + + libpaths = get_libpaths() + (base, member) = find_shared(libpaths, name) + if base is not None: + return f"{base}({member})" + + # To get here, a member in an archive has not been found + # In other words, either: + # a) a .a file was not found + # b) a .a file did not have a suitable member + # So, look for a .so file + # Check libpaths for .so file + # Note, the installation must prepare a link from a .so + # to a versioned file + # This is common practice by GNU libtool on other platforms + soname = f"lib{name}.so" + for dir in libpaths: + # /lib is a symbolic link to /usr/lib, skip it + if dir == "/lib": + continue + shlib = path.join(dir, soname) + if path.exists(shlib): + return soname + # if we are here, we have not found anything plausible + return None diff --git a/shared/package-files/3a/3aabb71c9078b688dc26df6075d0b4363e45ef652b1125ebe09fb07defc0223e/avt-ns b/shared/package-files/3a/3aabb71c9078b688dc26df6075d0b4363e45ef652b1125ebe09fb07defc0223e/avt-ns new file mode 100644 index 0000000000000000000000000000000000000000..67312e8ab6bf43efae9fd535c71a6ede58b77505 Binary files /dev/null and b/shared/package-files/3a/3aabb71c9078b688dc26df6075d0b4363e45ef652b1125ebe09fb07defc0223e/avt-ns differ diff --git a/shared/package-files/3a/3aabf260cb4ab4f1020ce71f9226949e32ae2216ead7362e09758c54d8e8c974/experiments.py b/shared/package-files/3a/3aabf260cb4ab4f1020ce71f9226949e32ae2216ead7362e09758c54d8e8c974/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..48f346ec47cb8a59411cee44bf22a6e0f03f58c1 --- /dev/null +++ b/shared/package-files/3a/3aabf260cb4ab4f1020ce71f9226949e32ae2216ead7362e09758c54d8e8c974/experiments.py @@ -0,0 +1,428 @@ +import copy +import itertools +import os +import pickle +import random +import subprocess +import sys +import time +from multiprocessing import Pool + +from .. import __version__, datasets +from . import metrics, models + +try: + from queue import Queue +except ImportError: + from Queue import Queue +from threading import Lock, Thread + +regression_metrics = [ + "local_accuracy", + "consistency_guarantees", + "keep_positive_mask", + "keep_positive_resample", + # "keep_positive_impute", + "keep_negative_mask", + "keep_negative_resample", + # "keep_negative_impute", + "keep_absolute_mask__r2", + "keep_absolute_resample__r2", + # "keep_absolute_impute__r2", + "remove_positive_mask", + "remove_positive_resample", + # "remove_positive_impute", + "remove_negative_mask", + "remove_negative_resample", + # "remove_negative_impute", + "remove_absolute_mask__r2", + "remove_absolute_resample__r2", + # "remove_absolute_impute__r2" + "runtime", +] + +binary_classification_metrics = [ + "local_accuracy", + "consistency_guarantees", + "keep_positive_mask", + "keep_positive_resample", + # "keep_positive_impute", + "keep_negative_mask", + "keep_negative_resample", + # "keep_negative_impute", + "keep_absolute_mask__roc_auc", + "keep_absolute_resample__roc_auc", + # "keep_absolute_impute__roc_auc", + "remove_positive_mask", + "remove_positive_resample", + # "remove_positive_impute", + "remove_negative_mask", + "remove_negative_resample", + # "remove_negative_impute", + "remove_absolute_mask__roc_auc", + "remove_absolute_resample__roc_auc", + # "remove_absolute_impute__roc_auc" + "runtime", +] + +human_metrics = [ + "human_and_00", + "human_and_01", + "human_and_11", + "human_or_00", + "human_or_01", + "human_or_11", + "human_xor_00", + "human_xor_01", + "human_xor_11", + "human_sum_00", + "human_sum_01", + "human_sum_11", +] + +linear_regress_methods = [ + "linear_shap_corr", + "linear_shap_ind", + "coef", + "random", + "kernel_shap_1000_meanref", + # "kernel_shap_100_meanref", + # "sampling_shap_10000", + "sampling_shap_1000", + "lime_tabular_regression_1000", + # "sampling_shap_100" +] + +linear_classify_methods = [ + # NEED LIME + "linear_shap_corr", + "linear_shap_ind", + "coef", + "random", + "kernel_shap_1000_meanref", + # "kernel_shap_100_meanref", + # "sampling_shap_10000", + "sampling_shap_1000", + # "lime_tabular_regression_1000" + # "sampling_shap_100" +] + +tree_regress_methods = [ + # NEED tree_shap_ind + # NEED split_count? + "tree_shap_tree_path_dependent", + "tree_shap_independent_200", + "saabas", + "random", + "tree_gain", + "kernel_shap_1000_meanref", + "mean_abs_tree_shap", + # "kernel_shap_100_meanref", + # "sampling_shap_10000", + "sampling_shap_1000", + "lime_tabular_regression_1000", + "maple", + # "sampling_shap_100" +] + +rf_regress_methods = [ # methods that only support random forest models + "tree_maple" +] + +tree_classify_methods = [ + # NEED tree_shap_ind + # NEED split_count? + "tree_shap_tree_path_dependent", + "tree_shap_independent_200", + "saabas", + "random", + "tree_gain", + "kernel_shap_1000_meanref", + "mean_abs_tree_shap", + # "kernel_shap_100_meanref", + # "sampling_shap_10000", + "sampling_shap_1000", + "lime_tabular_classification_1000", + "maple", + # "sampling_shap_100" +] + +deep_regress_methods = [ + "deep_shap", + "expected_gradients", + "random", + "kernel_shap_1000_meanref", + "sampling_shap_1000", + # "lime_tabular_regression_1000" +] + +deep_classify_methods = [ + "deep_shap", + "expected_gradients", + "random", + "kernel_shap_1000_meanref", + "sampling_shap_1000", + # "lime_tabular_regression_1000" +] + +_experiments = [] +_experiments += [["corrgroups60", "lasso", m, s] for s in regression_metrics for m in linear_regress_methods] +_experiments += [["corrgroups60", "ridge", m, s] for s in regression_metrics for m in linear_regress_methods] +_experiments += [["corrgroups60", "decision_tree", m, s] for s in regression_metrics for m in tree_regress_methods] +_experiments += [ + ["corrgroups60", "random_forest", m, s] + for s in regression_metrics + for m in (tree_regress_methods + rf_regress_methods) +] +_experiments += [["corrgroups60", "gbm", m, s] for s in regression_metrics for m in tree_regress_methods] +_experiments += [["corrgroups60", "ffnn", m, s] for s in regression_metrics for m in deep_regress_methods] + +_experiments += [["independentlinear60", "lasso", m, s] for s in regression_metrics for m in linear_regress_methods] +_experiments += [["independentlinear60", "ridge", m, s] for s in regression_metrics for m in linear_regress_methods] +_experiments += [ + ["independentlinear60", "decision_tree", m, s] for s in regression_metrics for m in tree_regress_methods +] +_experiments += [ + ["independentlinear60", "random_forest", m, s] + for s in regression_metrics + for m in (tree_regress_methods + rf_regress_methods) +] +_experiments += [["independentlinear60", "gbm", m, s] for s in regression_metrics for m in tree_regress_methods] +_experiments += [["independentlinear60", "ffnn", m, s] for s in regression_metrics for m in deep_regress_methods] + +_experiments += [["cric", "lasso", m, s] for s in binary_classification_metrics for m in linear_classify_methods] +_experiments += [["cric", "ridge", m, s] for s in binary_classification_metrics for m in linear_classify_methods] +_experiments += [["cric", "decision_tree", m, s] for s in binary_classification_metrics for m in tree_classify_methods] +_experiments += [["cric", "random_forest", m, s] for s in binary_classification_metrics for m in tree_classify_methods] +_experiments += [["cric", "gbm", m, s] for s in binary_classification_metrics for m in tree_classify_methods] +_experiments += [["cric", "ffnn", m, s] for s in binary_classification_metrics for m in deep_classify_methods] + +_experiments += [["human", "decision_tree", m, s] for s in human_metrics for m in tree_regress_methods] + + +def experiments(dataset=None, model=None, method=None, metric=None): + for experiment in _experiments: + if dataset is not None and dataset != experiment[0]: + continue + if model is not None and model != experiment[1]: + continue + if method is not None and method != experiment[2]: + continue + if metric is not None and metric != experiment[3]: + continue + yield experiment + + +def run_experiment(experiment, use_cache=True, cache_dir="/tmp"): + dataset_name, model_name, method_name, metric_name = experiment + + # see if we have a cached version + cache_id = __gen_cache_id(experiment) + cache_file = os.path.join(cache_dir, cache_id + ".pickle") + if use_cache and os.path.isfile(cache_file): + with open(cache_file, "rb") as f: + # print(cache_id.replace("__", " ") + " ...loaded from cache.") + return pickle.load(f) + + # compute the scores + print(cache_id.replace("__", " ", 4) + " ...") + sys.stdout.flush() + start = time.time() + X, y = getattr(datasets, dataset_name)() + score = getattr(metrics, metric_name)(X, y, getattr(models, dataset_name + "__" + model_name), method_name) + print("...took %f seconds.\n" % (time.time() - start)) + + # cache the scores + with open(cache_file, "wb") as f: + pickle.dump(score, f) + + return score + + +def run_experiments_helper(args): + experiment, cache_dir = args + return run_experiment(experiment, cache_dir=cache_dir) + + +def run_experiments(dataset=None, model=None, method=None, metric=None, cache_dir="/tmp", nworkers=1): + experiments_arr = list(experiments(dataset=dataset, model=model, method=method, metric=metric)) + if nworkers == 1: + out = list(map(run_experiments_helper, zip(experiments_arr, itertools.repeat(cache_dir)))) + else: + with Pool(nworkers) as pool: + out = pool.map(run_experiments_helper, zip(experiments_arr, itertools.repeat(cache_dir))) + return list(zip(experiments_arr, out)) + + +nexperiments = 0 +total_sent = 0 +total_done = 0 +total_failed = 0 +host_records = {} +worker_lock = Lock() +ssh_conn_per_min_limit = 0 # set as an argument to run_remote_experiments + + +def __thread_worker(q, host): + global total_sent, total_done + hostname, python_binary = host.split(":") + while True: + # make sure we are not sending too many ssh connections to the host + # (if we send too many connections ssh thottling will lock us out) + while True: + all_clear = False + + worker_lock.acquire() + try: + if hostname not in host_records: + host_records[hostname] = [] + + if len(host_records[hostname]) < ssh_conn_per_min_limit: + all_clear = True + elif time.time() - host_records[hostname][-ssh_conn_per_min_limit] > 61: + all_clear = True + finally: + worker_lock.release() + + # if we are clear to send a new ssh connection then break + if all_clear: + break + + # if we are not clear then we sleep and try again + time.sleep(5) + + experiment = q.get() + + # if we are not loading from the cache then we note that we have called the host + cache_dir = "/tmp" + cache_file = os.path.join(cache_dir, __gen_cache_id(experiment) + ".pickle") + if not os.path.isfile(cache_file): + worker_lock.acquire() + try: + host_records[hostname].append(time.time()) + finally: + worker_lock.release() + + # record how many we have sent off for execution + worker_lock.acquire() + try: + total_sent += 1 + __print_status() + finally: + worker_lock.release() + + __run_remote_experiment(experiment, hostname, cache_dir=cache_dir, python_binary=python_binary) + + # record how many are finished + worker_lock.acquire() + try: + total_done += 1 + __print_status() + finally: + worker_lock.release() + + q.task_done() + + +def __print_status(): + print( + f"Benchmark task {total_done} of {nexperiments} done ({total_failed} failed, {total_sent - total_done} running)", + end="\r", + ) + sys.stdout.flush() + + +def run_remote_experiments(experiments, thread_hosts, rate_limit=10): + """Use ssh to run the experiments on remote machines in parallel. + + Parameters + ---------- + experiments : iterable + Output of shap.benchmark.experiments(...). + + thread_hosts : list of strings + Each host has the format "host_name:path_to_python_binary" and can appear multiple times + in the list (one for each parallel execution you want on that machine). + + rate_limit : int + How many ssh connections we make per minute to each host (to avoid throttling issues). + + """ + global ssh_conn_per_min_limit + ssh_conn_per_min_limit = rate_limit + + # first we kill any remaining workers from previous runs + # note we don't check_call because pkill kills our ssh call as well + thread_hosts = copy.copy(thread_hosts) + random.shuffle(thread_hosts) + for host in set(thread_hosts): + hostname, _ = host.split(":") + try: + subprocess.run(["ssh", hostname, "pkill -f shap.benchmark.run_experiment"], timeout=15) + except subprocess.TimeoutExpired: + print("Failed to connect to", hostname, "after 15 seconds! Exiting.") + return + + experiments = copy.copy(list(experiments)) + random.shuffle(experiments) # this way all the hard experiments don't get put on one machine + global nexperiments, total_sent, total_done, total_failed, host_records + nexperiments = len(experiments) + total_sent = 0 + total_done = 0 + total_failed = 0 + host_records = {} + + q = Queue() + + for host in thread_hosts: + worker = Thread(target=__thread_worker, args=(q, host)) + worker.daemon = True + worker.start() + + for experiment in experiments: + q.put(experiment) + + q.join() + + +def __run_remote_experiment(experiment, remote, cache_dir="/tmp", python_binary="python"): + global total_failed + dataset_name, model_name, method_name, metric_name = experiment + + # see if we have a cached version + cache_id = __gen_cache_id(experiment) + cache_file = os.path.join(cache_dir, cache_id + ".pickle") + if os.path.isfile(cache_file): + with open(cache_file, "rb") as f: + return pickle.load(f) + + # this is just so we don't dump everything at once on a machine + time.sleep(random.uniform(0, 5)) + + # run the benchmark on the remote machine + # start = time.time() + func = f"shap.benchmark.run_experiment(['{dataset_name}', '{model_name}', '{method_name}', '{metric_name}'], cache_dir='{cache_dir}')" + cmd = 'CUDA_VISIBLE_DEVICES="" ' + python_binary + f' -c "import shap; {func}" &> {cache_dir}/{cache_id}.output' + try: + subprocess.check_output(["ssh", remote, cmd]) + except subprocess.CalledProcessError as e: + print(f"The following command failed on {remote}:", file=sys.stderr) + print(cmd, file=sys.stderr) + total_failed += 1 + print(e) + return + + # copy the results back + subprocess.check_output(["scp", remote + ":" + cache_file, cache_file]) + + if os.path.isfile(cache_file): + with open(cache_file, "rb") as f: + # print(cache_id.replace("__", " ") + " ...loaded from remote after %f seconds" % (time.time() - start)) + return pickle.load(f) + else: + raise FileNotFoundError("Remote benchmark call finished but no local file was found!") + + +def __gen_cache_id(experiment): + dataset_name, model_name, method_name, metric_name = experiment + return "v" + "__".join([__version__, dataset_name, model_name, method_name, metric_name]) diff --git a/shared/package-files/3a/3aad360fb03c6855ebd00d5fe481bcbd46b96ab5721a22c9c08d41dac161a489/TensorInfo.cuh b/shared/package-files/3a/3aad360fb03c6855ebd00d5fe481bcbd46b96ab5721a22c9c08d41dac161a489/TensorInfo.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a320000ae881faa7416bae6ed1f37793f357a73a --- /dev/null +++ b/shared/package-files/3a/3aad360fb03c6855ebd00d5fe481bcbd46b96ab5721a22c9c08d41dac161a489/TensorInfo.cuh @@ -0,0 +1,116 @@ +#pragma once + +#include + +namespace at::cuda::detail { + +#define MAX_TENSORINFO_DIMS 25 + +// CUDA kernel argument that defines tensor layout +template +struct TensorInfo { + TensorInfo(); + TensorInfo(T* p, + int dim, + IndexType sz[MAX_TENSORINFO_DIMS], + IndexType st[MAX_TENSORINFO_DIMS]); + + // Set the size of the given dimension to 1, as if it were a + // reduction dim (allows you to calculate offsets of the reduction + // slice) + void reduceDim(int dim); + + // See note on [collapse dims]. + int collapseDims(const int excludeDim = -1); + + // Contiguous tensors of more than one dimension are collapsed down + // to one tensor + __host__ __device__ inline bool isContiguous() const { + return (dims == 1 && strides[0] == 1); + } + + T* data; + IndexType sizes[MAX_TENSORINFO_DIMS]; + IndexType strides[MAX_TENSORINFO_DIMS]; + int dims; +}; + +template +TensorInfo::TensorInfo() { + data = nullptr; + dims = 0; +} + +template +TensorInfo::TensorInfo(T* p, + int dim, + IndexType sz[MAX_TENSORINFO_DIMS], + IndexType st[MAX_TENSORINFO_DIMS]) { + data = p; + dims = dim; + TORCH_CHECK(dims < MAX_TENSORINFO_DIMS, "CUDA Tensors cannot have more than 25 dimensions"); + + for (int i = 0; i < dim; ++i) { + sizes[i] = sz[i]; + strides[i] = st[i]; + } +} + +template +void +TensorInfo::reduceDim(int dim) { + TORCH_CHECK(dim < dims && dim >= 0, "expected dim between 0 and dims - 1"); + sizes[dim] = 1; +} + +template +int +TensorInfo::collapseDims(const int excludeDim) { + auto result = at::collapse_dims(sizes, strides, dims, excludeDim); + dims = std::get<1>(result); + return std::get<0>(result); +} + +// Translate a linear index for the apply to a T* offset; +// specialized on `Dims` to reduce nvcc compilation time +template +struct IndexToOffset { + static __host__ __device__ IndexType get( + IndexType linearId, + const TensorInfo& info) { + + IndexType offset = 0; + + // Uses static dims + for (int i = Dims - 1; i > 0; --i) { + IndexType curDimIndex = linearId % info.sizes[i]; + IndexType curDimOffset = curDimIndex * info.strides[i]; + offset += curDimOffset; + linearId /= info.sizes[i]; + } + + return offset + linearId * info.strides[0]; + } +}; + +// Uses dynamic (runtime) instead of static (compiletime) dims +template +struct IndexToOffset { + static inline __host__ __device__ IndexType get( + IndexType linearId, + const TensorInfo& info) { + + IndexType offset = 0; + + for (int i = info.dims - 1; i > 0; --i) { + IndexType curDimIndex = linearId % info.sizes[i]; + IndexType curDimOffset = curDimIndex * info.strides[i]; + offset += curDimOffset; + linearId /= info.sizes[i]; + } + + return offset + linearId * info.strides[0]; + } +}; + +} // namespace at::cuda::detail diff --git a/shared/package-files/3a/3aae5b1607ff85c38bc6204b8733c0ad4157820dd475eff1a5e28f0b783e1c32/rust.py b/shared/package-files/3a/3aae5b1607ff85c38bc6204b8733c0ad4157820dd475eff1a5e28f0b783e1c32/rust.py new file mode 100644 index 0000000000000000000000000000000000000000..db68bb3461480fa1e5a1f2cc026b1f0e46c18ceb --- /dev/null +++ b/shared/package-files/3a/3aae5b1607ff85c38bc6204b8733c0ad4157820dd475eff1a5e28f0b783e1c32/rust.py @@ -0,0 +1,223 @@ +""" + pygments.lexers.rust + ~~~~~~~~~~~~~~~~~~~~ + + Lexers for the Rust language. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, include, bygroups, words, default +from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ + Number, Punctuation, Whitespace + +__all__ = ['RustLexer'] + + +class RustLexer(RegexLexer): + """ + Lexer for the Rust programming language (version 1.47). + + .. versionadded:: 1.6 + """ + name = 'Rust' + url = 'https://www.rust-lang.org/' + filenames = ['*.rs', '*.rs.in'] + aliases = ['rust', 'rs'] + mimetypes = ['text/rust', 'text/x-rust'] + + keyword_types = (words(( + 'u8', 'u16', 'u32', 'u64', 'u128', 'i8', 'i16', 'i32', 'i64', 'i128', + 'usize', 'isize', 'f32', 'f64', 'char', 'str', 'bool', + ), suffix=r'\b'), Keyword.Type) + + builtin_funcs_types = (words(( + 'Copy', 'Send', 'Sized', 'Sync', 'Unpin', + 'Drop', 'Fn', 'FnMut', 'FnOnce', 'drop', + 'Box', 'ToOwned', 'Clone', + 'PartialEq', 'PartialOrd', 'Eq', 'Ord', + 'AsRef', 'AsMut', 'Into', 'From', 'Default', + 'Iterator', 'Extend', 'IntoIterator', 'DoubleEndedIterator', + 'ExactSizeIterator', + 'Option', 'Some', 'None', + 'Result', 'Ok', 'Err', + 'String', 'ToString', 'Vec', + ), suffix=r'\b'), Name.Builtin) + + builtin_macros = (words(( + 'asm', 'assert', 'assert_eq', 'assert_ne', 'cfg', 'column', + 'compile_error', 'concat', 'concat_idents', 'dbg', 'debug_assert', + 'debug_assert_eq', 'debug_assert_ne', 'env', 'eprint', 'eprintln', + 'file', 'format', 'format_args', 'format_args_nl', 'global_asm', + 'include', 'include_bytes', 'include_str', + 'is_aarch64_feature_detected', + 'is_arm_feature_detected', + 'is_mips64_feature_detected', + 'is_mips_feature_detected', + 'is_powerpc64_feature_detected', + 'is_powerpc_feature_detected', + 'is_x86_feature_detected', + 'line', 'llvm_asm', 'log_syntax', 'macro_rules', 'matches', + 'module_path', 'option_env', 'panic', 'print', 'println', 'stringify', + 'thread_local', 'todo', 'trace_macros', 'unimplemented', 'unreachable', + 'vec', 'write', 'writeln', + ), suffix=r'!'), Name.Function.Magic) + + tokens = { + 'root': [ + # rust allows a file to start with a shebang, but if the first line + # starts with #![ then it's not a shebang but a crate attribute. + (r'#![^[\r\n].*$', Comment.Preproc), + default('base'), + ], + 'base': [ + # Whitespace and Comments + (r'\n', Whitespace), + (r'\s+', Whitespace), + (r'//!.*?\n', String.Doc), + (r'///(\n|[^/].*?\n)', String.Doc), + (r'//(.*?)\n', Comment.Single), + (r'/\*\*(\n|[^/*])', String.Doc, 'doccomment'), + (r'/\*!', String.Doc, 'doccomment'), + (r'/\*', Comment.Multiline, 'comment'), + + # Macro parameters + (r"""\$([a-zA-Z_]\w*|\(,?|\),?|,?)""", Comment.Preproc), + # Keywords + (words(('as', 'async', 'await', 'box', 'const', 'crate', 'dyn', + 'else', 'extern', 'for', 'if', 'impl', 'in', 'loop', + 'match', 'move', 'mut', 'pub', 'ref', 'return', 'static', + 'super', 'trait', 'unsafe', 'use', 'where', 'while'), + suffix=r'\b'), Keyword), + (words(('abstract', 'become', 'do', 'final', 'macro', 'override', + 'priv', 'typeof', 'try', 'unsized', 'virtual', 'yield'), + suffix=r'\b'), Keyword.Reserved), + (r'(true|false)\b', Keyword.Constant), + (r'self\b', Name.Builtin.Pseudo), + (r'mod\b', Keyword, 'modname'), + (r'let\b', Keyword.Declaration), + (r'fn\b', Keyword, 'funcname'), + (r'(struct|enum|type|union)\b', Keyword, 'typename'), + (r'(default)(\s+)(type|fn)\b', bygroups(Keyword, Text, Keyword)), + keyword_types, + (r'[sS]elf\b', Name.Builtin.Pseudo), + # Prelude (taken from Rust's src/libstd/prelude.rs) + builtin_funcs_types, + builtin_macros, + # Path separators, so types don't catch them. + (r'::\b', Text), + # Types in positions. + (r'(?::|->)', Text, 'typename'), + # Labels + (r'(break|continue)(\b\s*)(\'[A-Za-z_]\w*)?', + bygroups(Keyword, Text.Whitespace, Name.Label)), + + # Character literals + (r"""'(\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0""" + r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""", + String.Char), + (r"""b'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\0""" + r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""", + String.Char), + + # Binary literals + (r'0b[01_]+', Number.Bin, 'number_lit'), + # Octal literals + (r'0o[0-7_]+', Number.Oct, 'number_lit'), + # Hexadecimal literals + (r'0[xX][0-9a-fA-F_]+', Number.Hex, 'number_lit'), + # Decimal literals + (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|' + r'\.[0-9_]*(?!\.)|[eE][+\-]?[0-9_]+)', Number.Float, + 'number_lit'), + (r'[0-9][0-9_]*', Number.Integer, 'number_lit'), + + # String literals + (r'b"', String, 'bytestring'), + (r'"', String, 'string'), + (r'(?s)b?r(#*)".*?"\1', String), + + # Lifetime names + (r"'", Operator, 'lifetime'), + + # Operators and Punctuation + (r'\.\.=?', Operator), + (r'[{}()\[\],.;]', Punctuation), + (r'[+\-*/%&|<>^!~@=:?]', Operator), + + # Identifiers + (r'[a-zA-Z_]\w*', Name), + # Raw identifiers + (r'r#[a-zA-Z_]\w*', Name), + + # Attributes + (r'#!?\[', Comment.Preproc, 'attribute['), + + # Misc + # Lone hashes: not used in Rust syntax, but allowed in macro + # arguments, most famously for quote::quote!() + (r'#', Text), + ], + 'comment': [ + (r'[^*/]+', Comment.Multiline), + (r'/\*', Comment.Multiline, '#push'), + (r'\*/', Comment.Multiline, '#pop'), + (r'[*/]', Comment.Multiline), + ], + 'doccomment': [ + (r'[^*/]+', String.Doc), + (r'/\*', String.Doc, '#push'), + (r'\*/', String.Doc, '#pop'), + (r'[*/]', String.Doc), + ], + 'modname': [ + (r'\s+', Text), + (r'[a-zA-Z_]\w*', Name.Namespace, '#pop'), + default('#pop'), + ], + 'funcname': [ + (r'\s+', Text), + (r'[a-zA-Z_]\w*', Name.Function, '#pop'), + default('#pop'), + ], + 'typename': [ + (r'\s+', Text), + (r'&', Keyword.Pseudo), + (r"'", Operator, 'lifetime'), + builtin_funcs_types, + keyword_types, + (r'[a-zA-Z_]\w*', Name.Class, '#pop'), + default('#pop'), + ], + 'lifetime': [ + (r"(static|_)", Name.Builtin), + (r"[a-zA-Z_]+\w*", Name.Attribute), + default('#pop'), + ], + 'number_lit': [ + (r'[ui](8|16|32|64|size)', Keyword, '#pop'), + (r'f(32|64)', Keyword, '#pop'), + default('#pop'), + ], + 'string': [ + (r'"', String, '#pop'), + (r"""\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0""" + r"""|\\u\{[0-9a-fA-F]{1,6}\}""", String.Escape), + (r'[^\\"]+', String), + (r'\\', String), + ], + 'bytestring': [ + (r"""\\x[89a-fA-F][0-9a-fA-F]""", String.Escape), + include('string'), + ], + 'attribute_common': [ + (r'"', String, 'string'), + (r'\[', Comment.Preproc, 'attribute['), + ], + 'attribute[': [ + include('attribute_common'), + (r'\]', Comment.Preproc, '#pop'), + (r'[^"\]\[]+', Comment.Preproc), + ], + } diff --git a/shared/package-files/3a/3aaee0c4cbdb951541ad0db790cc5cf224f46c79c258a83d104e19ab36c96ce0/umath-validation-set-tan.csv b/shared/package-files/3a/3aaee0c4cbdb951541ad0db790cc5cf224f46c79c258a83d104e19ab36c96ce0/umath-validation-set-tan.csv new file mode 100644 index 0000000000000000000000000000000000000000..083cdb2fbc51686ccb4736e5563baff1e6186759 --- /dev/null +++ b/shared/package-files/3a/3aaee0c4cbdb951541ad0db790cc5cf224f46c79c258a83d104e19ab36c96ce0/umath-validation-set-tan.csv @@ -0,0 +1,1429 @@ +dtype,input,output,ulperrortol +np.float32,0xfd97ece0,0xc11186e9,4 +np.float32,0x8013bb34,0x8013bb34,4 +np.float32,0x316389,0x316389,4 +np.float32,0x7f7fffff,0xbf1c9eca,4 +np.float32,0x3f7674bb,0x3fb7e450,4 +np.float32,0x80800000,0x80800000,4 +np.float32,0x7f5995e8,0xbf94106c,4 +np.float32,0x74527,0x74527,4 +np.float32,0x7f08caea,0xbeceddb6,4 +np.float32,0x2d49b2,0x2d49b2,4 +np.float32,0x3f74e5e4,0x3fb58695,4 +np.float32,0x3f3fcd51,0x3f6e1e81,4 +np.float32,0xbf4f3608,0xbf864d3d,4 +np.float32,0xbed974a0,0xbee78c70,4 +np.float32,0xff5f483c,0x3ecf3cb2,4 +np.float32,0x7f4532f4,0xc0b96f7b,4 +np.float32,0x3f0a4f7c,0x3f198cc0,4 +np.float32,0x210193,0x210193,4 +np.float32,0xfeebad7a,0xbf92eba8,4 +np.float32,0xfed29f74,0xc134cab6,4 +np.float32,0x803433a0,0x803433a0,4 +np.float32,0x64eb46,0x64eb46,4 +np.float32,0xbf54ef22,0xbf8c757b,4 +np.float32,0x3f3d5fdd,0x3f69a17b,4 +np.float32,0x80000001,0x80000001,4 +np.float32,0x800a837a,0x800a837a,4 +np.float32,0x6ff0be,0x6ff0be,4 +np.float32,0xfe8f1186,0x3f518820,4 +np.float32,0x804963e5,0x804963e5,4 +np.float32,0xfebaa59a,0x3fa1dbb0,4 +np.float32,0x637970,0x637970,4 +np.float32,0x3e722a6b,0x3e76c89a,4 +np.float32,0xff2b0478,0xbddccb5f,4 +np.float32,0xbf7bd85b,0xbfc06821,4 +np.float32,0x3ec33600,0x3ecd4126,4 +np.float32,0x3e0a43b9,0x3e0b1c69,4 +np.float32,0x7f7511b6,0xbe427083,4 +np.float32,0x3f28c114,0x3f465a73,4 +np.float32,0x3f179e1c,0x3f2c3e7c,4 +np.float32,0x7b2963,0x7b2963,4 +np.float32,0x3f423d06,0x3f72b442,4 +np.float32,0x3f5a24c6,0x3f925508,4 +np.float32,0xff18c834,0xbf79b5c8,4 +np.float32,0x3f401ece,0x3f6eb6ac,4 +np.float32,0x7b8a3013,0xbffab968,4 +np.float32,0x80091ff0,0x80091ff0,4 +np.float32,0x3f389c51,0x3f610b47,4 +np.float32,0x5ea174,0x5ea174,4 +np.float32,0x807a9eb2,0x807a9eb2,4 +np.float32,0x806ce61e,0x806ce61e,4 +np.float32,0xbe956acc,0xbe99cefc,4 +np.float32,0x7e60e247,0xbf5e64a5,4 +np.float32,0x7f398e24,0x404d12ed,4 +np.float32,0x3d9049f8,0x3d908735,4 +np.float32,0x7db17ffc,0xbf5b3d87,4 +np.float32,0xff453f78,0xc0239c9f,4 +np.float32,0x3f024aac,0x3f0ed802,4 +np.float32,0xbe781c30,0xbe7d1508,4 +np.float32,0x3f77962a,0x3fb9a28e,4 +np.float32,0xff7fffff,0x3f1c9eca,4 +np.float32,0x3f7152e3,0x3fb03f9d,4 +np.float32,0xff7cb167,0x3f9ce831,4 +np.float32,0x3e763e30,0x3e7b1a10,4 +np.float32,0xbf126527,0xbf24c253,4 +np.float32,0x803f6660,0x803f6660,4 +np.float32,0xbf79de38,0xbfbd38b1,4 +np.float32,0x8046c2f0,0x8046c2f0,4 +np.float32,0x6dc74e,0x6dc74e,4 +np.float32,0xbec9c45e,0xbed4e768,4 +np.float32,0x3f0eedb6,0x3f1fe610,4 +np.float32,0x7e031999,0xbcc13026,4 +np.float32,0x7efc2fd7,0x41e4b284,4 +np.float32,0xbeab7454,0xbeb22a1b,4 +np.float32,0x805ee67b,0x805ee67b,4 +np.float32,0x7f76e58e,0xc2436659,4 +np.float32,0xbe62b024,0xbe667718,4 +np.float32,0x3eea0808,0x3efbd182,4 +np.float32,0xbf7fd00c,0xbfc70719,4 +np.float32,0x7f27b640,0xbf0d97e0,4 +np.float32,0x3f1b58a4,0x3f31b6f4,4 +np.float32,0x252a9f,0x252a9f,4 +np.float32,0x7f65f95a,0xbead5de3,4 +np.float32,0xfc6ea780,0x42d15801,4 +np.float32,0x7eac4c52,0xc0682424,4 +np.float32,0xbe8a3f5a,0xbe8db54d,4 +np.float32,0xbf1644e2,0xbf2a4abd,4 +np.float32,0x3fc96a,0x3fc96a,4 +np.float32,0x7f38c0e4,0x3cc04af8,4 +np.float32,0x3f623d75,0x3f9c065d,4 +np.float32,0x3ee6a51a,0x3ef7a058,4 +np.float32,0x3dd11020,0x3dd1cacf,4 +np.float32,0xb6918,0xb6918,4 +np.float32,0xfdd7a540,0x3f22f081,4 +np.float32,0x80798563,0x80798563,4 +np.float32,0x3e9a8b7a,0x3e9f6a7e,4 +np.float32,0xbea515d4,0xbeab0df5,4 +np.float32,0xbea9b9f4,0xbeb03abe,4 +np.float32,0xbf11a5fa,0xbf23b478,4 +np.float32,0xfd6cadf0,0xbfa2a878,4 +np.float32,0xbf6edd07,0xbfacbb78,4 +np.float32,0xff5c5328,0x3e2d1552,4 +np.float32,0xbea2f788,0xbea8b3f5,4 +np.float32,0x802efaeb,0x802efaeb,4 +np.float32,0xff1c85e5,0x41f8560e,4 +np.float32,0x3f53b123,0x3f8b18e1,4 +np.float32,0xff798c4a,0x4092e66f,4 +np.float32,0x7f2e6fe7,0xbdcbd58f,4 +np.float32,0xfe8a8196,0x3fd7fc56,4 +np.float32,0x5e7ad4,0x5e7ad4,4 +np.float32,0xbf23a02d,0xbf3e4533,4 +np.float32,0x3f31c55c,0x3f5531bf,4 +np.float32,0x80331be3,0x80331be3,4 +np.float32,0x8056960a,0x8056960a,4 +np.float32,0xff1c06ae,0xbfd26992,4 +np.float32,0xbe0cc4b0,0xbe0da96c,4 +np.float32,0x7e925ad5,0xbf8dba54,4 +np.float32,0x2c8cec,0x2c8cec,4 +np.float32,0x8011951e,0x8011951e,4 +np.float32,0x3f2caf84,0x3f4cb89f,4 +np.float32,0xbd32c220,0xbd32df33,4 +np.float32,0xbec358d6,0xbecd6996,4 +np.float32,0x3f6e4930,0x3fabeb92,4 +np.float32,0xbf6a3afd,0xbfa65a3a,4 +np.float32,0x80067764,0x80067764,4 +np.float32,0x3d8df1,0x3d8df1,4 +np.float32,0x7ee51cf2,0x409e4061,4 +np.float32,0x435f5d,0x435f5d,4 +np.float32,0xbf5b17f7,0xbf936ebe,4 +np.float32,0x3ecaacb5,0x3ed5f81f,4 +np.float32,0x807b0aa5,0x807b0aa5,4 +np.float32,0x52b40b,0x52b40b,4 +np.float32,0x146a97,0x146a97,4 +np.float32,0x7f42b952,0xbfdcb413,4 +np.float32,0xbf1a1af2,0xbf2fe1bb,4 +np.float32,0x3f312034,0x3f541aa2,4 +np.float32,0x3f281d60,0x3f4554f9,4 +np.float32,0x50e451,0x50e451,4 +np.float32,0xbe45838c,0xbe480016,4 +np.float32,0xff7d0aeb,0x3eb0746e,4 +np.float32,0x7f32a489,0xbf96af6d,4 +np.float32,0xbf1b4e27,0xbf31a769,4 +np.float32,0x3f242936,0x3f3f1a44,4 +np.float32,0xbf7482ff,0xbfb4f201,4 +np.float32,0x4bda38,0x4bda38,4 +np.float32,0xbf022208,0xbf0ea2bb,4 +np.float32,0x7d08ca95,0xbe904602,4 +np.float32,0x7ed2f356,0xc02b55ad,4 +np.float32,0xbf131204,0xbf25b734,4 +np.float32,0xff3464b4,0x3fb23706,4 +np.float32,0x5a97cf,0x5a97cf,4 +np.float32,0xbe52db70,0xbe55e388,4 +np.float32,0x3f52934f,0x3f89e2aa,4 +np.float32,0xfeea866a,0x40a2b33f,4 +np.float32,0x80333925,0x80333925,4 +np.float32,0xfef5d13e,0xc00139ec,4 +np.float32,0x3f4750ab,0x3f7c87ad,4 +np.float32,0x3e41bfdd,0x3e44185a,4 +np.float32,0xbf5b0572,0xbf935935,4 +np.float32,0xbe93c9da,0xbe9808d8,4 +np.float32,0x7f501f33,0xc0f9973c,4 +np.float32,0x800af035,0x800af035,4 +np.float32,0x3f29faf8,0x3f4852a8,4 +np.float32,0xbe1e4c20,0xbe1f920c,4 +np.float32,0xbf7e8616,0xbfc4d79d,4 +np.float32,0x43ffbf,0x43ffbf,4 +np.float32,0x7f28e8a9,0xbfa1ac24,4 +np.float32,0xbf1f9f92,0xbf3820bc,4 +np.float32,0x3f07e004,0x3f1641c4,4 +np.float32,0x3ef7ea7f,0x3f06a64a,4 +np.float32,0x7e013101,0x3f6080e6,4 +np.float32,0x7f122a4f,0xbf0a796f,4 +np.float32,0xfe096960,0x3ed7273a,4 +np.float32,0x3f06abf1,0x3f14a4b2,4 +np.float32,0x3e50ded3,0x3e53d0f1,4 +np.float32,0x7f50b346,0x3eabb536,4 +np.float32,0xff5adb0f,0xbd441972,4 +np.float32,0xbecefe46,0xbedb0f66,4 +np.float32,0x7da70bd4,0xbec66273,4 +np.float32,0x169811,0x169811,4 +np.float32,0xbee4dfee,0xbef5721a,4 +np.float32,0x3efbeae3,0x3f0936e6,4 +np.float32,0x8031bd61,0x8031bd61,4 +np.float32,0x8048e443,0x8048e443,4 +np.float32,0xff209aa6,0xbeb364cb,4 +np.float32,0xff477499,0x3c1b0041,4 +np.float32,0x803fe929,0x803fe929,4 +np.float32,0x3f70158b,0x3fae7725,4 +np.float32,0x7f795723,0x3e8e850a,4 +np.float32,0x3cba99,0x3cba99,4 +np.float32,0x80588d2a,0x80588d2a,4 +np.float32,0x805d1f05,0x805d1f05,4 +np.float32,0xff4ac09a,0xbefe614d,4 +np.float32,0x804af084,0x804af084,4 +np.float32,0x7c64ae63,0xc1a8b563,4 +np.float32,0x8078d793,0x8078d793,4 +np.float32,0x7f3e2436,0xbf8bf9d3,4 +np.float32,0x7ccec1,0x7ccec1,4 +np.float32,0xbf6462c7,0xbf9eb830,4 +np.float32,0x3f1002ca,0x3f216843,4 +np.float32,0xfe878ca6,0x409e73a5,4 +np.float32,0x3bd841d9,0x3bd842a7,4 +np.float32,0x7d406f41,0xbd9dcfa3,4 +np.float32,0x7c6d6,0x7c6d6,4 +np.float32,0x3f4ef360,0x3f86074b,4 +np.float32,0x805f534a,0x805f534a,4 +np.float32,0x1,0x1,4 +np.float32,0x3f739ee2,0x3fb39db2,4 +np.float32,0x3d0c2352,0x3d0c3153,4 +np.float32,0xfe8a4f2c,0x3edd8add,4 +np.float32,0x3e52eaa0,0x3e55f362,4 +np.float32,0x7bde9758,0xbf5ba5cf,4 +np.float32,0xff422654,0xbf41e487,4 +np.float32,0x385e5b,0x385e5b,4 +np.float32,0x5751dd,0x5751dd,4 +np.float32,0xff6c671c,0xc03e2d6d,4 +np.float32,0x1458be,0x1458be,4 +np.float32,0x80153d4d,0x80153d4d,4 +np.float32,0x7efd2adb,0x3e25458f,4 +np.float32,0xbe161880,0xbe172e12,4 +np.float32,0x7ecea1aa,0x40a66d79,4 +np.float32,0xbf5b02a2,0xbf9355f0,4 +np.float32,0x15d9ab,0x15d9ab,4 +np.float32,0x2dc7c7,0x2dc7c7,4 +np.float32,0xfebbf81a,0x4193f6e6,4 +np.float32,0xfe8e3594,0xc00a6695,4 +np.float32,0x185aa8,0x185aa8,4 +np.float32,0x3daea156,0x3daf0e00,4 +np.float32,0x3e071688,0x3e07e08e,4 +np.float32,0x802db9e6,0x802db9e6,4 +np.float32,0x7f7be2c4,0x3f1363dd,4 +np.float32,0x7eba3f5e,0xc13eb497,4 +np.float32,0x3de04a00,0x3de130a9,4 +np.float32,0xbf1022bc,0xbf2194eb,4 +np.float32,0xbf5b547e,0xbf93b53b,4 +np.float32,0x3e867bd6,0x3e89aa10,4 +np.float32,0xbea5eb5c,0xbeabfb73,4 +np.float32,0x7f1efae9,0x3ffca038,4 +np.float32,0xff5d0344,0xbe55dbbb,4 +np.float32,0x805167e7,0x805167e7,4 +np.float32,0xbdb3a020,0xbdb41667,4 +np.float32,0xbedea6b4,0xbeedd5fd,4 +np.float32,0x8053b45c,0x8053b45c,4 +np.float32,0x7ed370e9,0x3d90eba5,4 +np.float32,0xbefcd7da,0xbf09cf91,4 +np.float32,0x78b9ac,0x78b9ac,4 +np.float32,0xbf2f6dc0,0xbf5141ef,4 +np.float32,0x802d3a7b,0x802d3a7b,4 +np.float32,0xfd45d120,0x3fec31cc,4 +np.float32,0xbf7e7020,0xbfc4b2af,4 +np.float32,0xf04da,0xf04da,4 +np.float32,0xbe9819d4,0xbe9cbd35,4 +np.float32,0x8075ab35,0x8075ab35,4 +np.float32,0xbf052fdc,0xbf12aa2c,4 +np.float32,0x3f1530d0,0x3f28bd9f,4 +np.float32,0x80791881,0x80791881,4 +np.float32,0x67f309,0x67f309,4 +np.float32,0x3f12f16a,0x3f2588f5,4 +np.float32,0x3ecdac47,0x3ed97ff8,4 +np.float32,0xbf297fb7,0xbf478c39,4 +np.float32,0x8069fa80,0x8069fa80,4 +np.float32,0x807f940e,0x807f940e,4 +np.float32,0xbf648dc8,0xbf9eeecb,4 +np.float32,0x3de873b0,0x3de9748d,4 +np.float32,0x3f1aa645,0x3f30af1f,4 +np.float32,0xff227a62,0x3d8283cc,4 +np.float32,0xbf37187d,0xbf5e5f4c,4 +np.float32,0x803b1b1f,0x803b1b1f,4 +np.float32,0x3f58142a,0x3f8ff8da,4 +np.float32,0x8004339e,0x8004339e,4 +np.float32,0xbf0f5654,0xbf2077a4,4 +np.float32,0x3f17e509,0x3f2ca598,4 +np.float32,0x3f800000,0x3fc75923,4 +np.float32,0xfdf79980,0x42f13047,4 +np.float32,0x7f111381,0x3f13c4c9,4 +np.float32,0xbea40c70,0xbea9e724,4 +np.float32,0x110520,0x110520,4 +np.float32,0x60490d,0x60490d,4 +np.float32,0x3f6703ec,0x3fa21951,4 +np.float32,0xbf098256,0xbf187652,4 +np.float32,0x658951,0x658951,4 +np.float32,0x3f53bf16,0x3f8b2818,4 +np.float32,0xff451811,0xc0026068,4 +np.float32,0x80777ee0,0x80777ee0,4 +np.float32,0x3e4fcc19,0x3e52b286,4 +np.float32,0x7f387ee0,0x3ce93eb6,4 +np.float32,0xff51181f,0xbfca3ee4,4 +np.float32,0xbf5655ae,0xbf8e0304,4 +np.float32,0xff2f1dcd,0x40025471,4 +np.float32,0x7f6e58e5,0xbe9930d5,4 +np.float32,0x7adf11,0x7adf11,4 +np.float32,0xbe9a2bc2,0xbe9f0185,4 +np.float32,0x8065d3a0,0x8065d3a0,4 +np.float32,0x3ed6e826,0x3ee47c45,4 +np.float32,0x80598ea0,0x80598ea0,4 +np.float32,0x7f10b90a,0x40437bd0,4 +np.float32,0x27b447,0x27b447,4 +np.float32,0x7ecd861c,0x3fce250f,4 +np.float32,0x0,0x0,4 +np.float32,0xbeba82d6,0xbec3394c,4 +np.float32,0xbf4958b0,0xbf8048ea,4 +np.float32,0x7c643e,0x7c643e,4 +np.float32,0x580770,0x580770,4 +np.float32,0x805bf54a,0x805bf54a,4 +np.float32,0x7f1f3cee,0xbe1a54d6,4 +np.float32,0xfefefdea,0x3fa84576,4 +np.float32,0x7f007b7a,0x3e8a6d25,4 +np.float32,0xbf177959,0xbf2c0919,4 +np.float32,0xbf30fda0,0xbf53e058,4 +np.float32,0x3f0576be,0x3f130861,4 +np.float32,0x3f49380e,0x3f80283a,4 +np.float32,0xebc56,0xebc56,4 +np.float32,0x654e3b,0x654e3b,4 +np.float32,0x14a4d8,0x14a4d8,4 +np.float32,0xff69b3cb,0xbf822a88,4 +np.float32,0xbe9b6c1c,0xbea06109,4 +np.float32,0xbefddd7e,0xbf0a787b,4 +np.float32,0x4c4ebb,0x4c4ebb,4 +np.float32,0x7d0a74,0x7d0a74,4 +np.float32,0xbebb5f80,0xbec43635,4 +np.float32,0x7ee79723,0xc1c7f3f3,4 +np.float32,0x7f2be4c7,0xbfa6c693,4 +np.float32,0x805bc7d5,0x805bc7d5,4 +np.float32,0x8042f12c,0x8042f12c,4 +np.float32,0x3ef91be8,0x3f07697b,4 +np.float32,0x3cf37ac0,0x3cf38d1c,4 +np.float32,0x800000,0x800000,4 +np.float32,0xbe1ebf4c,0xbe200806,4 +np.float32,0x7f380862,0xbeb512e8,4 +np.float32,0xbe320064,0xbe33d0fc,4 +np.float32,0xff300b0c,0xbfadb805,4 +np.float32,0x308a06,0x308a06,4 +np.float32,0xbf084f6e,0xbf16d7b6,4 +np.float32,0xff47cab6,0x3f892b65,4 +np.float32,0xbed99f4a,0xbee7bfd5,4 +np.float32,0xff7d74c0,0x3ee88c9a,4 +np.float32,0x3c3d23,0x3c3d23,4 +np.float32,0x8074bde8,0x8074bde8,4 +np.float32,0x80042164,0x80042164,4 +np.float32,0x3e97c92a,0x3e9c6500,4 +np.float32,0x3b80e0,0x3b80e0,4 +np.float32,0xbf16646a,0xbf2a783d,4 +np.float32,0x7f3b4cb1,0xc01339be,4 +np.float32,0xbf31f36e,0xbf557fd0,4 +np.float32,0x7f540618,0xbe5f6fc1,4 +np.float32,0x7eee47d0,0x40a27e94,4 +np.float32,0x7f12f389,0xbebed654,4 +np.float32,0x56cff5,0x56cff5,4 +np.float32,0x8056032b,0x8056032b,4 +np.float32,0x3ed34e40,0x3ee02e38,4 +np.float32,0x7d51a908,0xbf19a90e,4 +np.float32,0x80000000,0x80000000,4 +np.float32,0xfdf73fd0,0xbf0f8cad,4 +np.float32,0x7ee4fe6d,0xbf1ea7e4,4 +np.float32,0x1f15ba,0x1f15ba,4 +np.float32,0xd18c3,0xd18c3,4 +np.float32,0x80797705,0x80797705,4 +np.float32,0x7ef07091,0x3f2f3b9a,4 +np.float32,0x7f552f41,0x3faf608c,4 +np.float32,0x3f779977,0x3fb9a7ad,4 +np.float32,0xfe1a7a50,0xbdadc4d1,4 +np.float32,0xbf449cf0,0xbf7740db,4 +np.float32,0xbe44e620,0xbe475cad,4 +np.float32,0x3f63a098,0x3f9dc2b5,4 +np.float32,0xfed40a12,0x4164533a,4 +np.float32,0x7a2bbb,0x7a2bbb,4 +np.float32,0xff7f7b9e,0xbeee8740,4 +np.float32,0x7ee27f8b,0x4233f53b,4 +np.float32,0xbf044c06,0xbf117c28,4 +np.float32,0xbeffde54,0xbf0bc49f,4 +np.float32,0xfeaef2e8,0x3ff258fe,4 +np.float32,0x527451,0x527451,4 +np.float32,0xbcef8d00,0xbcef9e7c,4 +np.float32,0xbf0e20c0,0xbf1ec9b2,4 +np.float32,0x8024afda,0x8024afda,4 +np.float32,0x7ef6cb3e,0x422cad0b,4 +np.float32,0x3c120,0x3c120,4 +np.float32,0xbf125c8f,0xbf24b62c,4 +np.float32,0x7e770a93,0x402c9d86,4 +np.float32,0xbd30a4e0,0xbd30c0ee,4 +np.float32,0xbf4d3388,0xbf843530,4 +np.float32,0x3f529072,0x3f89df92,4 +np.float32,0xff0270b1,0xbf81be9a,4 +np.float32,0x5e07e7,0x5e07e7,4 +np.float32,0x7bec32,0x7bec32,4 +np.float32,0x7fc00000,0x7fc00000,4 +np.float32,0x3e3ba5e0,0x3e3dc6e9,4 +np.float32,0x3ecb62d4,0x3ed6ce2c,4 +np.float32,0x3eb3dde8,0x3ebba68f,4 +np.float32,0x8063f952,0x8063f952,4 +np.float32,0x7f204aeb,0x3e88614e,4 +np.float32,0xbeae1ddc,0xbeb5278e,4 +np.float32,0x6829e9,0x6829e9,4 +np.float32,0xbf361a99,0xbf5ca354,4 +np.float32,0xbf24fbe6,0xbf406326,4 +np.float32,0x3f329d41,0x3f56a061,4 +np.float32,0xfed6d666,0x3e8f71a5,4 +np.float32,0x337f92,0x337f92,4 +np.float32,0xbe1c4970,0xbe1d8305,4 +np.float32,0xbe6b7e18,0xbe6fbbde,4 +np.float32,0x3f2267b9,0x3f3c61da,4 +np.float32,0xbee1ee94,0xbef1d628,4 +np.float32,0x7ecffc1a,0x3f02987e,4 +np.float32,0xbe9b1306,0xbe9fff3b,4 +np.float32,0xbeffacae,0xbf0ba468,4 +np.float32,0x7f800000,0xffc00000,4 +np.float32,0xfefc9aa8,0xc19de2a3,4 +np.float32,0x7d7185bb,0xbf9090ec,4 +np.float32,0x7edfbafd,0x3fe9352f,4 +np.float32,0x4ef2ec,0x4ef2ec,4 +np.float32,0x7f4cab2e,0xbff4e5dd,4 +np.float32,0xff3b1788,0x3e3c22e9,4 +np.float32,0x4e15ee,0x4e15ee,4 +np.float32,0xbf5451e6,0xbf8bc8a7,4 +np.float32,0x3f7f6d2e,0x3fc65e8b,4 +np.float32,0xbf1d9184,0xbf35071b,4 +np.float32,0xbf3a81cf,0xbf646d9b,4 +np.float32,0xbe71acc4,0xbe7643ab,4 +np.float32,0x528b7d,0x528b7d,4 +np.float32,0x2cb1d0,0x2cb1d0,4 +np.float32,0x3f324bf8,0x3f56161a,4 +np.float32,0x80709a21,0x80709a21,4 +np.float32,0x4bc448,0x4bc448,4 +np.float32,0x3e8bd600,0x3e8f6b7a,4 +np.float32,0xbeb97d30,0xbec20dd6,4 +np.float32,0x2a5669,0x2a5669,4 +np.float32,0x805f2689,0x805f2689,4 +np.float32,0xfe569f50,0x3fc51952,4 +np.float32,0x1de44c,0x1de44c,4 +np.float32,0x3ec7036c,0x3ed1ae67,4 +np.float32,0x8052b8e5,0x8052b8e5,4 +np.float32,0xff740a6b,0x3f4981a8,4 +np.float32,0xfee9bb70,0xc05e23be,4 +np.float32,0xff4e12c9,0x4002b4ad,4 +np.float32,0x803de0c2,0x803de0c2,4 +np.float32,0xbf433a07,0xbf74966f,4 +np.float32,0x803e60ca,0x803e60ca,4 +np.float32,0xbf19ee98,0xbf2fa07a,4 +np.float32,0x92929,0x92929,4 +np.float32,0x7f709c27,0x4257ba2d,4 +np.float32,0x803167c6,0x803167c6,4 +np.float32,0xbf095ead,0xbf184607,4 +np.float32,0x617060,0x617060,4 +np.float32,0x2d85b3,0x2d85b3,4 +np.float32,0x53d20b,0x53d20b,4 +np.float32,0x3e046838,0x3e052666,4 +np.float32,0xbe7c5fdc,0xbe80ce4b,4 +np.float32,0x3d18d060,0x3d18e289,4 +np.float32,0x804dc031,0x804dc031,4 +np.float32,0x3f224166,0x3f3c26cd,4 +np.float32,0x7d683e3c,0xbea24f25,4 +np.float32,0xbf3a92aa,0xbf648be4,4 +np.float32,0x8072670b,0x8072670b,4 +np.float32,0xbe281aec,0xbe29a1bc,4 +np.float32,0x7f09d918,0xc0942490,4 +np.float32,0x7ca9fd07,0x4018b990,4 +np.float32,0x7d36ac5d,0x3cf57184,4 +np.float32,0x8039b62f,0x8039b62f,4 +np.float32,0x6cad7b,0x6cad7b,4 +np.float32,0x3c0fd9ab,0x3c0fda9d,4 +np.float32,0x80299883,0x80299883,4 +np.float32,0x3c2d0e3e,0x3c2d0fe4,4 +np.float32,0x8002cf62,0x8002cf62,4 +np.float32,0x801dde97,0x801dde97,4 +np.float32,0x80411856,0x80411856,4 +np.float32,0x6ebce8,0x6ebce8,4 +np.float32,0x7b7d1a,0x7b7d1a,4 +np.float32,0x8031d3de,0x8031d3de,4 +np.float32,0x8005c4ab,0x8005c4ab,4 +np.float32,0xbf7dd803,0xbfc3b3ef,4 +np.float32,0x8017ae60,0x8017ae60,4 +np.float32,0xfe9316ce,0xbfe0544a,4 +np.float32,0x3f136bfe,0x3f2636ff,4 +np.float32,0x3df87b80,0x3df9b57d,4 +np.float32,0xff44c356,0xbf11c7ad,4 +np.float32,0x4914ae,0x4914ae,4 +np.float32,0x80524c21,0x80524c21,4 +np.float32,0x805c7dc8,0x805c7dc8,4 +np.float32,0xfed3c0aa,0xbff0c0ab,4 +np.float32,0x7eb2bfbb,0xbf4600bc,4 +np.float32,0xfec8df84,0x3f5bd350,4 +np.float32,0x3e5431a4,0x3e5748c3,4 +np.float32,0xbee6a3a0,0xbef79e86,4 +np.float32,0xbf6cc9b2,0xbfa9d61a,4 +np.float32,0x3f132bd5,0x3f25dbd9,4 +np.float32,0x7e6d2e48,0x3f9d025b,4 +np.float32,0x3edf430c,0x3eee942d,4 +np.float32,0x3f0d1b8a,0x3f1d60e1,4 +np.float32,0xbdf2f688,0xbdf41bfb,4 +np.float32,0xbe47a284,0xbe4a33ff,4 +np.float32,0x3eaa9fbc,0x3eb13be7,4 +np.float32,0xfe98d45e,0x3eb84517,4 +np.float32,0x7efc23b3,0x3dcc1c99,4 +np.float32,0x3ca36242,0x3ca367ce,4 +np.float32,0x3f76a944,0x3fb834e3,4 +np.float32,0xbf45207c,0xbf783f9b,4 +np.float32,0x3e7c1220,0x3e80a4f8,4 +np.float32,0x3f018200,0x3f0dd14e,4 +np.float32,0x3f53cdde,0x3f8b3839,4 +np.float32,0xbdbacb58,0xbdbb5063,4 +np.float32,0x804af68d,0x804af68d,4 +np.float32,0x3e2c12fc,0x3e2db65b,4 +np.float32,0x3f039433,0x3f10895a,4 +np.float32,0x7ef5193d,0x3f4115f7,4 +np.float32,0x8030afbe,0x8030afbe,4 +np.float32,0x3f06fa2a,0x3f150d5d,4 +np.float32,0x3f124442,0x3f2493d2,4 +np.float32,0xbeb5b792,0xbebdc090,4 +np.float32,0xbedc90a4,0xbeeb4de9,4 +np.float32,0x3f3ff8,0x3f3ff8,4 +np.float32,0x3ee75bc5,0x3ef881e4,4 +np.float32,0xfe80e3de,0xbf5cd535,4 +np.float32,0xf52eb,0xf52eb,4 +np.float32,0x80660ee8,0x80660ee8,4 +np.float32,0x3e173a58,0x3e185648,4 +np.float32,0xfe49520c,0xbf728d7c,4 +np.float32,0xbecbb8ec,0xbed73373,4 +np.float32,0xbf027ae0,0xbf0f173e,4 +np.float32,0xbcab6740,0xbcab6da8,4 +np.float32,0xbf2a15e2,0xbf487e11,4 +np.float32,0x3b781b,0x3b781b,4 +np.float32,0x44f559,0x44f559,4 +np.float32,0xff6a0ca6,0xc174d7c3,4 +np.float32,0x6460ef,0x6460ef,4 +np.float32,0xfe58009c,0x3ee2bb30,4 +np.float32,0xfec3c038,0x3e30d617,4 +np.float32,0x7f0687c0,0xbf62c820,4 +np.float32,0xbf44655e,0xbf76d589,4 +np.float32,0xbf42968c,0xbf735e78,4 +np.float32,0x80385503,0x80385503,4 +np.float32,0xbea7e3a2,0xbeae2d59,4 +np.float32,0x3dd0b770,0x3dd17131,4 +np.float32,0xbf4bc185,0xbf82b907,4 +np.float32,0xfefd7d64,0xbee05650,4 +np.float32,0xfaac3c00,0xbff23bc9,4 +np.float32,0xbf562f0d,0xbf8dd7f4,4 +np.float32,0x7fa00000,0x7fe00000,4 +np.float32,0x3e01bdb8,0x3e027098,4 +np.float32,0x3e2868ab,0x3e29f19e,4 +np.float32,0xfec55f2e,0x3f39f304,4 +np.float32,0xed4e,0xed4e,4 +np.float32,0x3e2b7330,0x3e2d11fa,4 +np.float32,0x7f738542,0x40cbbe16,4 +np.float32,0x3f123521,0x3f247e71,4 +np.float32,0x73572c,0x73572c,4 +np.float32,0x804936c8,0x804936c8,4 +np.float32,0x803b80d8,0x803b80d8,4 +np.float32,0x7f566c57,0xbee2855a,4 +np.float32,0xff0e3bd8,0xbff0543f,4 +np.float32,0x7d2b2fe7,0xbf94ba4c,4 +np.float32,0xbf0da470,0xbf1e1dc2,4 +np.float32,0xbd276500,0xbd277ce0,4 +np.float32,0xfcd15dc0,0x403ccc2a,4 +np.float32,0x80071e59,0x80071e59,4 +np.float32,0xbe9b0c34,0xbe9ff7be,4 +np.float32,0x3f4f9069,0x3f86ac50,4 +np.float32,0x80042a95,0x80042a95,4 +np.float32,0x7de28e39,0x3bc9b7f4,4 +np.float32,0xbf641935,0xbf9e5af8,4 +np.float32,0x8034f068,0x8034f068,4 +np.float32,0xff33a3d2,0xbf408e75,4 +np.float32,0xbcc51540,0xbcc51efc,4 +np.float32,0xff6d1ddf,0x3ef58f0e,4 +np.float32,0xbf64dfc4,0xbf9f5725,4 +np.float32,0xff068a06,0x3eea8987,4 +np.float32,0xff01c0af,0x3f24cdfe,4 +np.float32,0x3f4def7e,0x3f84f802,4 +np.float32,0xbf1b4ae7,0xbf31a299,4 +np.float32,0x8077df2d,0x8077df2d,4 +np.float32,0x3f0155c5,0x3f0d9785,4 +np.float32,0x5a54b2,0x5a54b2,4 +np.float32,0x7f271f9e,0x3efb2ef3,4 +np.float32,0xbf0ff2ec,0xbf215217,4 +np.float32,0x7f500130,0xbf8a7fdd,4 +np.float32,0xfed9891c,0xbf65c872,4 +np.float32,0xfecbfaae,0x403bdbc2,4 +np.float32,0x3f3a5aba,0x3f642772,4 +np.float32,0x7ebc681e,0xbd8df059,4 +np.float32,0xfe05e400,0xbfe35d74,4 +np.float32,0xbf295ace,0xbf4750ea,4 +np.float32,0x7ea055b2,0x3f62d6be,4 +np.float32,0xbd00b520,0xbd00bff9,4 +np.float32,0xbf7677aa,0xbfb7e8cf,4 +np.float32,0x3e83f788,0x3e86f816,4 +np.float32,0x801f6710,0x801f6710,4 +np.float32,0x801133cc,0x801133cc,4 +np.float32,0x41da2a,0x41da2a,4 +np.float32,0xff1622fd,0x3f023650,4 +np.float32,0x806c7a72,0x806c7a72,4 +np.float32,0x3f10779c,0x3f220bb4,4 +np.float32,0xbf08cf94,0xbf17848d,4 +np.float32,0xbecb55b4,0xbed6bebd,4 +np.float32,0xbf0a1528,0xbf193d7b,4 +np.float32,0x806a16bd,0x806a16bd,4 +np.float32,0xc222a,0xc222a,4 +np.float32,0x3930de,0x3930de,4 +np.float32,0x3f5c3588,0x3f94bca2,4 +np.float32,0x1215ad,0x1215ad,4 +np.float32,0x3ed15030,0x3eddcf67,4 +np.float32,0x7da83b2e,0x3fce0d39,4 +np.float32,0x32b0a8,0x32b0a8,4 +np.float32,0x805aed6b,0x805aed6b,4 +np.float32,0x3ef8e02f,0x3f074346,4 +np.float32,0xbdeb6780,0xbdec7250,4 +np.float32,0x3f6e3cec,0x3fabda61,4 +np.float32,0xfefd467a,0x3ef7821a,4 +np.float32,0xfef090fe,0x3bb752a2,4 +np.float32,0x8019c538,0x8019c538,4 +np.float32,0x3e8cf284,0x3e909e81,4 +np.float32,0xbe6c6618,0xbe70b0a2,4 +np.float32,0x7f50a539,0x3f367be1,4 +np.float32,0x8019fe2f,0x8019fe2f,4 +np.float32,0x800c3f48,0x800c3f48,4 +np.float32,0xfd054cc0,0xc0f52802,4 +np.float32,0x3d0cca20,0x3d0cd853,4 +np.float32,0xbf4a7c44,0xbf816e74,4 +np.float32,0x3f46fc40,0x3f7be153,4 +np.float32,0x807c5849,0x807c5849,4 +np.float32,0xd7e41,0xd7e41,4 +np.float32,0x70589b,0x70589b,4 +np.float32,0x80357b95,0x80357b95,4 +np.float32,0x3de239f0,0x3de326a5,4 +np.float32,0x800b08e3,0x800b08e3,4 +np.float32,0x807ec946,0x807ec946,4 +np.float32,0x3e2e4b83,0x3e2fff76,4 +np.float32,0x3f198e0f,0x3f2f12a6,4 +np.float32,0xbecb1aca,0xbed67979,4 +np.float32,0x80134082,0x80134082,4 +np.float32,0x3f3a269f,0x3f63ca05,4 +np.float32,0x3f1381e4,0x3f265622,4 +np.float32,0xff293080,0xbf10be6f,4 +np.float32,0xff800000,0xffc00000,4 +np.float32,0x37d196,0x37d196,4 +np.float32,0x7e57eea7,0x3e7d8138,4 +np.float32,0x804b1dae,0x804b1dae,4 +np.float32,0x7d9508f9,0xc1075b35,4 +np.float32,0x3f7bf468,0x3fc095e0,4 +np.float32,0x55472c,0x55472c,4 +np.float32,0x3ecdcd86,0x3ed9a738,4 +np.float32,0x3ed9be0f,0x3ee7e4e9,4 +np.float32,0x3e7e0ddb,0x3e81b2fe,4 +np.float32,0x7ee6c1d3,0x3f850634,4 +np.float32,0x800f6fad,0x800f6fad,4 +np.float32,0xfefb3bd6,0xbff68ecc,4 +np.float32,0x8013d6e2,0x8013d6e2,4 +np.float32,0x3f3a2cb6,0x3f63d4ee,4 +np.float32,0xff383c84,0x3e7854bb,4 +np.float32,0x3f21946e,0x3f3b1cea,4 +np.float32,0xff322ea2,0x3fb22f31,4 +np.float32,0x8065a024,0x8065a024,4 +np.float32,0x7f395e30,0xbefe0de1,4 +np.float32,0x5b52db,0x5b52db,4 +np.float32,0x7f7caea7,0x3dac8ded,4 +np.float32,0xbf0431f8,0xbf1159b2,4 +np.float32,0x7f15b25b,0xc02a3833,4 +np.float32,0x80131abc,0x80131abc,4 +np.float32,0x7e829d81,0xbeb2e93d,4 +np.float32,0x3f2c64d7,0x3f4c3e4d,4 +np.float32,0x7f228d48,0xc1518c74,4 +np.float32,0xfc3c6f40,0xbf00d585,4 +np.float32,0x7f754f0f,0x3e2152f5,4 +np.float32,0xff65d32b,0xbe8bd56c,4 +np.float32,0xfea6b8c0,0x41608655,4 +np.float32,0x3f7d4b05,0x3fc2c96a,4 +np.float32,0x3f463230,0x3f7a54da,4 +np.float32,0x805117bb,0x805117bb,4 +np.float32,0xbf2ad4f7,0xbf49b30e,4 +np.float32,0x3eaa01ff,0x3eb08b56,4 +np.float32,0xff7a02bb,0x3f095f73,4 +np.float32,0x759176,0x759176,4 +np.float32,0x803c18d5,0x803c18d5,4 +np.float32,0xbe0722d8,0xbe07ed16,4 +np.float32,0x3f4b4a99,0x3f823fc6,4 +np.float32,0x3f7d0451,0x3fc25463,4 +np.float32,0xfee31e40,0xbfb41091,4 +np.float32,0xbf733d2c,0xbfb30cf1,4 +np.float32,0x7ed81015,0x417c380c,4 +np.float32,0x7daafc3e,0xbe2a37ed,4 +np.float32,0x3e44f82b,0x3e476f67,4 +np.float32,0x7c8d99,0x7c8d99,4 +np.float32,0x3f7aec5a,0x3fbee991,4 +np.float32,0xff09fd55,0x3e0709d3,4 +np.float32,0xff4ba4df,0x4173c01f,4 +np.float32,0x3f43d944,0x3f75c7bd,4 +np.float32,0xff6a9106,0x40a10eff,4 +np.float32,0x3bc8341c,0x3bc834bf,4 +np.float32,0x3eea82,0x3eea82,4 +np.float32,0xfea36a3c,0x435729b2,4 +np.float32,0x7dcc1fb0,0x3e330053,4 +np.float32,0x3f616ae6,0x3f9b01ae,4 +np.float32,0x8030963f,0x8030963f,4 +np.float32,0x10d1e2,0x10d1e2,4 +np.float32,0xfeb9a8a6,0x40e6daac,4 +np.float32,0xbe1aba00,0xbe1bea3a,4 +np.float32,0x3cb6b4ea,0x3cb6bcac,4 +np.float32,0x3d8b0b64,0x3d8b422f,4 +np.float32,0x7b6894,0x7b6894,4 +np.float32,0x3e89dcde,0x3e8d4b4b,4 +np.float32,0x3f12b952,0x3f253974,4 +np.float32,0x1c316c,0x1c316c,4 +np.float32,0x7e2da535,0x3f95fe6b,4 +np.float32,0x3ae9a494,0x3ae9a4a4,4 +np.float32,0xbc5f5500,0xbc5f588b,4 +np.float32,0x3e7850fc,0x3e7d4d0e,4 +np.float32,0xbf800000,0xbfc75923,4 +np.float32,0x3e652d69,0x3e691502,4 +np.float32,0xbf6bdd26,0xbfa89129,4 +np.float32,0x3f441cfc,0x3f764a02,4 +np.float32,0x7f5445ff,0xc0906191,4 +np.float32,0x807b2ee3,0x807b2ee3,4 +np.float32,0xbeb6cab8,0xbebef9c0,4 +np.float32,0xff737277,0xbf327011,4 +np.float32,0xfc832aa0,0x402fd52e,4 +np.float32,0xbf0c7538,0xbf1c7c0f,4 +np.float32,0x7e1301c7,0xbf0ee63e,4 +np.float64,0xbfe0ef7df7a1defc,0xbfe2b76a8d8aeb35,4 +np.float64,0x7fdd9c2eae3b385c,0xbfc00d6885485039,4 +np.float64,0xbfb484c710290990,0xbfb4900e0a527555,4 +np.float64,0x7fe73e5d6cee7cba,0x3fefbf70a56b60d3,4 +np.float64,0x800a110aa8d42216,0x800a110aa8d42216,4 +np.float64,0xffedd4f3f3bba9e7,0xbff076f8c4124919,4 +np.float64,0x800093407f812682,0x800093407f812682,4 +np.float64,0x800a23150e54462a,0x800a23150e54462a,4 +np.float64,0xbfb1076864220ed0,0xbfb10dd95a74b733,4 +np.float64,0x3fed1f8b37fa3f16,0x3ff496100985211f,4 +np.float64,0x3fdf762f84beec5f,0x3fe1223eb04a17e0,4 +np.float64,0x53fd4e0aa7faa,0x53fd4e0aa7faa,4 +np.float64,0x3fdbd283bdb7a507,0x3fddb7ec9856a546,4 +np.float64,0xbfe43f449d687e89,0xbfe77724a0d3072b,4 +np.float64,0x618b73bcc316f,0x618b73bcc316f,4 +np.float64,0x67759424ceeb3,0x67759424ceeb3,4 +np.float64,0xbfe4b6f7d9a96df0,0xbfe831371f3bd7a8,4 +np.float64,0x800a531b8b74a637,0x800a531b8b74a637,4 +np.float64,0xffeeffd5c37dffab,0x3fea140cbc2c3726,4 +np.float64,0x3fe648e2002c91c4,0x3feac1b8816f972a,4 +np.float64,0x800f16242a1e2c48,0x800f16242a1e2c48,4 +np.float64,0xffeeff8e1dbdff1b,0xc000b555f117dce7,4 +np.float64,0x3fdf1cf73fbe39f0,0x3fe0e9032401135b,4 +np.float64,0x7fe19c388b633870,0x3fd5271b69317d5b,4 +np.float64,0x918f226d231e5,0x918f226d231e5,4 +np.float64,0x4cc19ab499834,0x4cc19ab499834,4 +np.float64,0xbd3121d57a624,0xbd3121d57a624,4 +np.float64,0xbfd145d334a28ba6,0xbfd1b468866124d6,4 +np.float64,0x8bdbf41517b7f,0x8bdbf41517b7f,4 +np.float64,0x3fd1b8cb3ea37198,0x3fd2306b13396cae,4 +np.float64,0xbfd632a959ac6552,0xbfd7220fcfb5ef78,4 +np.float64,0x1cdaafc639b57,0x1cdaafc639b57,4 +np.float64,0x3febdcce1577b99c,0x3ff2fe076195a2bc,4 +np.float64,0x7fca6e945934dd28,0x3ff43040df7024e8,4 +np.float64,0x3fbe08e78e3c11cf,0x3fbe2c60e6b48f75,4 +np.float64,0x7fc1ed0d0523da19,0x3ff55f8dcad9440f,4 +np.float64,0xbfdc729b8cb8e538,0xbfde7b6e15dd60c4,4 +np.float64,0x3fd219404f243281,0x3fd298d7b3546531,4 +np.float64,0x3fe715c3f56e2b88,0x3fec255b5a59456e,4 +np.float64,0x7fe8b88e74b1711c,0x3ff60efd2c81d13d,4 +np.float64,0xa1d2b9fd43a57,0xa1d2b9fd43a57,4 +np.float64,0xffc1818223230304,0xbfb85c6c1e8018e7,4 +np.float64,0x3fde38ac8b3c7159,0x3fe0580c7e228576,4 +np.float64,0x8008faf7b491f5f0,0x8008faf7b491f5f0,4 +np.float64,0xffe7a1d751af43ae,0xbf7114cd7bbcd981,4 +np.float64,0xffec2db1b4b85b62,0xbff5cae759667f83,4 +np.float64,0x7fefce1ae27f9c35,0x3ff4b8b88f4876cf,4 +np.float64,0x7fd1ff56a523feac,0xbff342ce192f14dd,4 +np.float64,0x80026b3e3f84d67d,0x80026b3e3f84d67d,4 +np.float64,0xffedee5879bbdcb0,0xc02fae11508b2be0,4 +np.float64,0x8003c0dc822781ba,0x8003c0dc822781ba,4 +np.float64,0xffe38a79eca714f4,0xc008aa23b7a63980,4 +np.float64,0xbfda70411eb4e082,0xbfdc0d7e29c89010,4 +np.float64,0x800a5e34f574bc6a,0x800a5e34f574bc6a,4 +np.float64,0x3fc19fac6e233f59,0x3fc1bc66ac0d73d4,4 +np.float64,0x3a8a61ea7514d,0x3a8a61ea7514d,4 +np.float64,0x3fb57b536e2af6a0,0x3fb588451f72f44c,4 +np.float64,0x7fd68c6d082d18d9,0xc032ac926b665c9a,4 +np.float64,0xd5b87cfdab710,0xd5b87cfdab710,4 +np.float64,0xfe80b20bfd017,0xfe80b20bfd017,4 +np.float64,0x3fef8781e37f0f04,0x3ff8215fe2c1315a,4 +np.float64,0xffedddbb9c3bbb76,0x3fd959b82258a32a,4 +np.float64,0x3fc7d41f382fa83e,0x3fc81b94c3a091ba,4 +np.float64,0xffc3275dcf264ebc,0x3fb2b3d4985c6078,4 +np.float64,0x7fe34d2b7ba69a56,0x40001f3618e3c7c9,4 +np.float64,0x3fd64ae35fac95c7,0x3fd73d77e0b730f8,4 +np.float64,0x800e53bf6b3ca77f,0x800e53bf6b3ca77f,4 +np.float64,0xbfddf7c9083bef92,0xbfe02f392744d2d1,4 +np.float64,0x1c237cc038471,0x1c237cc038471,4 +np.float64,0x3fe4172beea82e58,0x3fe739b4bf16bc7e,4 +np.float64,0xfa950523f52a1,0xfa950523f52a1,4 +np.float64,0xffc839a2c5307344,0xbff70ff8a3c9247f,4 +np.float64,0x264f828c4c9f1,0x264f828c4c9f1,4 +np.float64,0x148a650a2914e,0x148a650a2914e,4 +np.float64,0x3fe8d255c0b1a4ac,0x3fef623c3ea8d6e3,4 +np.float64,0x800f4fbb28be9f76,0x800f4fbb28be9f76,4 +np.float64,0x7fdca57bcfb94af7,0x3ff51207563fb6cb,4 +np.float64,0x3fe4944107692882,0x3fe7fad593235364,4 +np.float64,0x800119b4f1a2336b,0x800119b4f1a2336b,4 +np.float64,0xbfe734075e6e680e,0xbfec5b35381069f2,4 +np.float64,0xffeb3c00db767801,0xbfbbd7d22df7b4b3,4 +np.float64,0xbfe95c658cb2b8cb,0xbff03ad5e0bc888a,4 +np.float64,0xffeefeb58fbdfd6a,0xbfd5c9264deb0e11,4 +np.float64,0x7fccc80fde39901f,0xc012c60f914f3ca2,4 +np.float64,0x3fe5da289c2bb451,0x3fea07ad00a0ca63,4 +np.float64,0x800e364b0a5c6c96,0x800e364b0a5c6c96,4 +np.float64,0x3fcf9ea7d23f3d50,0x3fd023b72e8c9dcf,4 +np.float64,0x800a475cfc948eba,0x800a475cfc948eba,4 +np.float64,0xffd4e0d757a9c1ae,0xbfa89d573352e011,4 +np.float64,0xbfd4dbec8229b7da,0xbfd5a165f12c7c40,4 +np.float64,0xffe307ab51260f56,0x3fe6b1639da58c3f,4 +np.float64,0xbfe6955a546d2ab4,0xbfeb44ae2183fee9,4 +np.float64,0xbfca1f18f5343e30,0xbfca7d804ccccdf4,4 +np.float64,0xe9f4dfebd3e9c,0xe9f4dfebd3e9c,4 +np.float64,0xfff0000000000000,0xfff8000000000000,4 +np.float64,0x8008e69c0fb1cd38,0x8008e69c0fb1cd38,4 +np.float64,0xbfead1ccf975a39a,0xbff1c84b3db8ca93,4 +np.float64,0x25a982424b531,0x25a982424b531,4 +np.float64,0x8010000000000000,0x8010000000000000,4 +np.float64,0x80056204ea0ac40b,0x80056204ea0ac40b,4 +np.float64,0x800d1442d07a2886,0x800d1442d07a2886,4 +np.float64,0xbfaef3dadc3de7b0,0xbfaefd85ae6205f0,4 +np.float64,0x7fe969ce4b32d39c,0xbff3c4364fc6778f,4 +np.float64,0x7fe418bac0a83175,0x402167d16b1efe0b,4 +np.float64,0x3fd7c82a25af9054,0x3fd8f0c701315672,4 +np.float64,0x80013782a7826f06,0x80013782a7826f06,4 +np.float64,0x7fc031c7ee20638f,0x400747ab705e6904,4 +np.float64,0x3fe8cf327ff19e65,0x3fef5c14f8aafa89,4 +np.float64,0xbfe331a416a66348,0xbfe5e2290a098dd4,4 +np.float64,0x800607b2116c0f65,0x800607b2116c0f65,4 +np.float64,0x7fb40448f0280891,0xbfd43d4f0ffa1d64,4 +np.float64,0x7fefffffffffffff,0xbf74530cfe729484,4 +np.float64,0x3fe39b5444a736a9,0x3fe67eaa0b6acf27,4 +np.float64,0x3fee4733c4fc8e68,0x3ff631eabeef9696,4 +np.float64,0xbfec840f3b79081e,0xbff3cc8563ab2e74,4 +np.float64,0xbfc8f6854c31ed0c,0xbfc948caacb3bba0,4 +np.float64,0xffbcf754a639eea8,0xbfc88d17cad3992b,4 +np.float64,0x8000bd3163417a64,0x8000bd3163417a64,4 +np.float64,0x3fe766d0eaeecda2,0x3fecb660882f7024,4 +np.float64,0xb6cc30156d986,0xb6cc30156d986,4 +np.float64,0xffc0161f9f202c40,0x3fe19bdefe5cf8b1,4 +np.float64,0xffe1e462caa3c8c5,0x3fe392c47feea17b,4 +np.float64,0x30a36a566146e,0x30a36a566146e,4 +np.float64,0x3fa996f580332deb,0x3fa99c6b4f2abebe,4 +np.float64,0x3fba71716e34e2e0,0x3fba899f35edba1d,4 +np.float64,0xbfe8f7e5e971efcc,0xbfefac431a0e3d55,4 +np.float64,0xf48f1803e91e3,0xf48f1803e91e3,4 +np.float64,0x7fe3edc0a127db80,0xc03d1a579a5d74a8,4 +np.float64,0xffeba82056375040,0x3fdfd701308700db,4 +np.float64,0xbfeb5a924cf6b524,0xbff2640de7cd107f,4 +np.float64,0xfa4cd1a9f499a,0xfa4cd1a9f499a,4 +np.float64,0x800de1be7b9bc37d,0x800de1be7b9bc37d,4 +np.float64,0xffd44e56ad289cae,0x3fdf4b8085db9b67,4 +np.float64,0xbfe4fb3aea69f676,0xbfe89d2cc46fcc50,4 +np.float64,0xbfe596495d6b2c92,0xbfe997a589a1f632,4 +np.float64,0x6f55a2b8deab5,0x6f55a2b8deab5,4 +np.float64,0x7fe72dc4712e5b88,0x4039c4586b28c2bc,4 +np.float64,0x89348bd712692,0x89348bd712692,4 +np.float64,0xffe062156120c42a,0x4005f0580973bc77,4 +np.float64,0xbfeabc714d7578e2,0xbff1b07e2fa57dc0,4 +np.float64,0x8003a56b3e874ad7,0x8003a56b3e874ad7,4 +np.float64,0x800eeadfb85dd5c0,0x800eeadfb85dd5c0,4 +np.float64,0x46d77a4c8daf0,0x46d77a4c8daf0,4 +np.float64,0x8000c06e7dc180de,0x8000c06e7dc180de,4 +np.float64,0x3fe428d211e851a4,0x3fe754b1c00a89bc,4 +np.float64,0xc5be11818b7c2,0xc5be11818b7c2,4 +np.float64,0x7fefc244893f8488,0x401133dc54f52de5,4 +np.float64,0x3fde30eee93c61de,0x3fe0532b827543a6,4 +np.float64,0xbfd447f48b288fea,0xbfd4fd0654f90718,4 +np.float64,0xbfde98dc7b3d31b8,0xbfe094df12f84a06,4 +np.float64,0x3fed2c1a1dfa5834,0x3ff4a6c4f3470a65,4 +np.float64,0xbfe992165073242d,0xbff071ab039c9177,4 +np.float64,0x3fd0145d1b2028ba,0x3fd06d3867b703dc,4 +np.float64,0x3fe179457362f28b,0x3fe3722f1d045fda,4 +np.float64,0x800e28964fbc512d,0x800e28964fbc512d,4 +np.float64,0x8004a5d785294bb0,0x8004a5d785294bb0,4 +np.float64,0xbfd652f2272ca5e4,0xbfd7469713125120,4 +np.float64,0x7fe61f49036c3e91,0xbf9b6ccdf2d87e70,4 +np.float64,0xffb7d47dd02fa8f8,0xc004449a82320b13,4 +np.float64,0x3feb82f996b705f3,0x3ff29336c738a4c5,4 +np.float64,0x3fbb7fceea36ffa0,0x3fbb9b02c8ad7f93,4 +np.float64,0x80004519fb208a35,0x80004519fb208a35,4 +np.float64,0xbfe0539114e0a722,0xbfe1e86dc5aa039c,4 +np.float64,0x0,0x0,4 +np.float64,0xbfe99d1125f33a22,0xbff07cf8ec04300f,4 +np.float64,0xffd4fbeecc29f7de,0x3ffab76775a8455f,4 +np.float64,0xbfbf1c618e3e38c0,0xbfbf43d2764a8333,4 +np.float64,0x800cae02a9d95c06,0x800cae02a9d95c06,4 +np.float64,0x3febc47d3bf788fa,0x3ff2e0d7cf8ef509,4 +np.float64,0x3fef838f767f071f,0x3ff81aeac309bca0,4 +np.float64,0xbfd5e70716abce0e,0xbfd6ccb033ef7a35,4 +np.float64,0x3f9116fa60222df5,0x3f9117625f008e0b,4 +np.float64,0xffe02b1e5f20563c,0xbfe6b2ec293520b7,4 +np.float64,0xbf9b5aec3036b5e0,0xbf9b5c96c4c7f951,4 +np.float64,0xfdb0169bfb603,0xfdb0169bfb603,4 +np.float64,0x7fcdd1d51c3ba3a9,0x401f0e12fa0b7570,4 +np.float64,0xbfd088103fa11020,0xbfd0e8c4a333ffb2,4 +np.float64,0x3fe22df82ee45bf0,0x3fe46d03a7c14de2,4 +np.float64,0xbfd57b0c28aaf618,0xbfd65349a6191de5,4 +np.float64,0x3fe0a42f50a1485f,0x3fe252e26775d9a4,4 +np.float64,0x800fab4e363f569c,0x800fab4e363f569c,4 +np.float64,0xffe9f0ed63f3e1da,0xbfe278c341b171d5,4 +np.float64,0x7fe26c244664d848,0xbfb325269dad1996,4 +np.float64,0xffe830410bf06081,0xc00181a39f606e96,4 +np.float64,0x800c548a0c78a914,0x800c548a0c78a914,4 +np.float64,0x800f94761ebf28ec,0x800f94761ebf28ec,4 +np.float64,0x3fe5984845eb3091,0x3fe99aeb653c666d,4 +np.float64,0x7fe93e5bf8f27cb7,0xc010d159fa27396a,4 +np.float64,0xffefffffffffffff,0x3f74530cfe729484,4 +np.float64,0x4c83f1269907f,0x4c83f1269907f,4 +np.float64,0x3fde0065a8bc00cc,0x3fe034a1cdf026d4,4 +np.float64,0x800743810d6e8703,0x800743810d6e8703,4 +np.float64,0x80040662d5280cc6,0x80040662d5280cc6,4 +np.float64,0x3fed20b2c5ba4166,0x3ff497988519d7aa,4 +np.float64,0xffe8fa15e5f1f42b,0x3fff82ca76d797b4,4 +np.float64,0xbb72e22f76e5d,0xbb72e22f76e5d,4 +np.float64,0x7fc18ffa7c231ff4,0xbff4b8b4c3315026,4 +np.float64,0xbfe8d1ac44f1a358,0xbfef60efc4f821e3,4 +np.float64,0x3fd38c1fe8271840,0x3fd42dc37ff7262b,4 +np.float64,0xe577bee5caef8,0xe577bee5caef8,4 +np.float64,0xbff0000000000000,0xbff8eb245cbee3a6,4 +np.float64,0xffcb3a9dd436753c,0x3fcd1a3aff1c3fc7,4 +np.float64,0x7fe44bf2172897e3,0x3ff60bfe82a379f4,4 +np.float64,0x8009203823924071,0x8009203823924071,4 +np.float64,0x7fef8e0abc7f1c14,0x3fe90e4962d47ce5,4 +np.float64,0xffda50004434a000,0x3fb50dee03e1418b,4 +np.float64,0x7fe2ff276ea5fe4e,0xc0355b7d2a0a8d9d,4 +np.float64,0x3fd0711ba5a0e238,0x3fd0d03823d2d259,4 +np.float64,0xe7625b03cec4c,0xe7625b03cec4c,4 +np.float64,0xbfd492c8d7a92592,0xbfd55006cde8d300,4 +np.float64,0x8001fee99f23fdd4,0x8001fee99f23fdd4,4 +np.float64,0x7ff4000000000000,0x7ffc000000000000,4 +np.float64,0xfa15df97f42bc,0xfa15df97f42bc,4 +np.float64,0xbfec3fdca9787fb9,0xbff377164b13c7a9,4 +np.float64,0xbcec10e579d82,0xbcec10e579d82,4 +np.float64,0xbfc3b4e2132769c4,0xbfc3dd1fcc7150a6,4 +np.float64,0x80045b149ee8b62a,0x80045b149ee8b62a,4 +np.float64,0xffe044554c2088aa,0xbff741436d558785,4 +np.float64,0xffcc65f09f38cbe0,0xc0172b4adc2d317d,4 +np.float64,0xf68b2d3bed166,0xf68b2d3bed166,4 +np.float64,0x7fc7f44c572fe898,0x3fec69f3b1eca790,4 +np.float64,0x3fac51f61438a3ec,0x3fac595d34156002,4 +np.float64,0xbfeaa9f256f553e5,0xbff19bfdf5984326,4 +np.float64,0x800e4742149c8e84,0x800e4742149c8e84,4 +np.float64,0xbfc493df132927c0,0xbfc4c1ba4268ead9,4 +np.float64,0xbfbf0c56383e18b0,0xbfbf3389fcf50c72,4 +np.float64,0xbf978a0e082f1420,0xbf978b1dd1da3d3c,4 +np.float64,0xbfe04375356086ea,0xbfe1d34c57314dd1,4 +np.float64,0x3feaeeb29b75dd65,0x3ff1e8b772374979,4 +np.float64,0xbfe15e42c3a2bc86,0xbfe34d45d56c5c15,4 +np.float64,0x3fe507429a6a0e85,0x3fe8b058176b3225,4 +np.float64,0x3feee2b26c3dc565,0x3ff71b73203de921,4 +np.float64,0xbfd496577aa92cae,0xbfd553fa7fe15a5f,4 +np.float64,0x7fe2c10953e58212,0x3fc8ead6a0d14bbf,4 +np.float64,0x800035b77aa06b70,0x800035b77aa06b70,4 +np.float64,0x2329201e46525,0x2329201e46525,4 +np.float64,0xbfe6225c9a6c44b9,0xbfea80861590fa02,4 +np.float64,0xbfd6925030ad24a0,0xbfd78e70b1c2215d,4 +np.float64,0xbfd82225c4b0444c,0xbfd958a60f845b39,4 +np.float64,0xbb03d8a17609,0xbb03d8a17609,4 +np.float64,0x7fc33967b12672ce,0x40001e00c9af4002,4 +np.float64,0xff9373c6d026e780,0xbff308654a459d3d,4 +np.float64,0x3feab1f9c5f563f4,0x3ff1a4e0fd2f093d,4 +np.float64,0xbf993ef768327de0,0xbf994046b64e308b,4 +np.float64,0xffb87382fc30e708,0xbfde0accb83c891b,4 +np.float64,0x800bb3a118176743,0x800bb3a118176743,4 +np.float64,0x800c810250d90205,0x800c810250d90205,4 +np.float64,0xbfd2c4eb9ba589d8,0xbfd3539508b4a4a8,4 +np.float64,0xbee1f5437dc3f,0xbee1f5437dc3f,4 +np.float64,0x3fc07aeab520f5d8,0x3fc0926272f9d8e2,4 +np.float64,0xbfe23747a3246e90,0xbfe47a20a6e98687,4 +np.float64,0x3fde1296debc252c,0x3fe0401143ff6b5c,4 +np.float64,0xbfcec8c2f73d9184,0xbfcf644e25ed3b74,4 +np.float64,0xff9314f2c82629e0,0x40559a0f9099dfd1,4 +np.float64,0xbfe27487afa4e910,0xbfe4d0e01200bde6,4 +np.float64,0xffb3d6637627acc8,0x3fe326d4b1e1834f,4 +np.float64,0xffe6f84d642df09a,0x3fc73fa9f57c3acb,4 +np.float64,0xffe67cf76fecf9ee,0xc01cf48c97937ef9,4 +np.float64,0x7fdc73fc12b8e7f7,0xbfcfcecde9331104,4 +np.float64,0xffdcf8789239f0f2,0x3fe345e3b8e28776,4 +np.float64,0x800a70af5314e15f,0x800a70af5314e15f,4 +np.float64,0xffc862300730c460,0x3fc4e9ea813beca7,4 +np.float64,0xbfcc6961bd38d2c4,0xbfcce33bfa6c6bd1,4 +np.float64,0xbfc9b76bbf336ed8,0xbfca117456ac37e5,4 +np.float64,0x7fb86e829430dd04,0x400a5bd7a18e302d,4 +np.float64,0x7fb9813ef833027d,0xbfe5a6494f143625,4 +np.float64,0x8005085e2c2a10bd,0x8005085e2c2a10bd,4 +np.float64,0xffe5af099d6b5e12,0x40369bbe31e03e06,4 +np.float64,0xffde03b1fd3c0764,0x3ff061120aa1f52a,4 +np.float64,0x7fa4eb6cdc29d6d9,0x3fe9defbe9010322,4 +np.float64,0x800803f4b11007ea,0x800803f4b11007ea,4 +np.float64,0x7febd50f6df7aa1e,0xbffcf540ccf220dd,4 +np.float64,0x7fed454f08fa8a9d,0xbffc2a8b81079403,4 +np.float64,0xbfed7e8c69bafd19,0xbff5161e51ba6634,4 +np.float64,0xffef92e78eff25ce,0xbffefeecddae0ad3,4 +np.float64,0x7fe5b9b413ab7367,0xbfc681ba29704176,4 +np.float64,0x29284e805252,0x29284e805252,4 +np.float64,0xffed3955bcfa72ab,0xbfc695acb5f468de,4 +np.float64,0x3fe464ee1ca8c9dc,0x3fe7b140ce50fdca,4 +np.float64,0xffe522ae4bea455c,0x3feb957c146e66ef,4 +np.float64,0x8000000000000000,0x8000000000000000,4 +np.float64,0x3fd0c353a2a186a8,0x3fd1283aaa43a411,4 +np.float64,0x3fdb30a749b6614f,0x3fdcf40df006ed10,4 +np.float64,0x800109213cc21243,0x800109213cc21243,4 +np.float64,0xbfe72aa0c5ee5542,0xbfec4a713f513bc5,4 +np.float64,0x800865344ad0ca69,0x800865344ad0ca69,4 +np.float64,0x7feb7df60eb6fbeb,0x3fb1df06a67aa22f,4 +np.float64,0x3fe83a5dd93074bc,0x3fee3d63cda72636,4 +np.float64,0xbfde70e548bce1ca,0xbfe07b8e19c9dac6,4 +np.float64,0xbfeea38d537d471b,0xbff6bb18c230c0be,4 +np.float64,0x3fefeebbc47fdd78,0x3ff8cdaa53b7c7b4,4 +np.float64,0x7fe6512e20eca25b,0xbff623cee44a22b5,4 +np.float64,0xf8fa5ca3f1f4c,0xf8fa5ca3f1f4c,4 +np.float64,0x7fd12d00ed225a01,0xbfe90d518ea61faf,4 +np.float64,0x80027db43504fb69,0x80027db43504fb69,4 +np.float64,0xffc10a01aa221404,0x3fcc2065b3d0157b,4 +np.float64,0xbfef8286e87f050e,0xbff8193a54449b59,4 +np.float64,0xbfc73178092e62f0,0xbfc7735072ba4593,4 +np.float64,0x3fc859d70630b3ae,0x3fc8a626522af1c0,4 +np.float64,0x3fe4654c4268ca99,0x3fe7b1d2913eda1a,4 +np.float64,0xbfce93cd843d279c,0xbfcf2c2ef16a0957,4 +np.float64,0xffbcaa16d4395430,0xbfd511ced032d784,4 +np.float64,0xbfe91f980e723f30,0xbfeffb39cf8c7746,4 +np.float64,0x800556fb6f0aadf8,0x800556fb6f0aadf8,4 +np.float64,0xffd009cde520139c,0x3fe4fa83b1e93d28,4 +np.float64,0x7febc0675e3780ce,0x3feb53930c004dae,4 +np.float64,0xbfe7f975bdeff2ec,0xbfedc36e6729b010,4 +np.float64,0x45aff57c8b5ff,0x45aff57c8b5ff,4 +np.float64,0xbfec7ebd0138fd7a,0xbff3c5cab680aae0,4 +np.float64,0x8009448003b28900,0x8009448003b28900,4 +np.float64,0x3fca4b992d349732,0x3fcaabebcc86aa9c,4 +np.float64,0x3fca069161340d20,0x3fca63ecc742ff3a,4 +np.float64,0x80063bc80bec7791,0x80063bc80bec7791,4 +np.float64,0xbfe1764bffe2ec98,0xbfe36e1cb30cec94,4 +np.float64,0xffd0dba72f21b74e,0x3fb1834964d57ef6,4 +np.float64,0xbfe31848fc263092,0xbfe5bd066445cbc3,4 +np.float64,0xbfd1fb227323f644,0xbfd278334e27f02d,4 +np.float64,0xffdc59069fb8b20e,0xbfdfc363f559ea2c,4 +np.float64,0x3fdea52a52bd4a55,0x3fe09cada4e5344c,4 +np.float64,0x3f715e55a022bd00,0x3f715e5c72a2809e,4 +np.float64,0x1d1ac6023a35a,0x1d1ac6023a35a,4 +np.float64,0x7feacc71627598e2,0x400486b82121da19,4 +np.float64,0xa0287fa340510,0xa0287fa340510,4 +np.float64,0xffe352c5abe6a58b,0xc002623346060543,4 +np.float64,0x7fed577a23baaef3,0x3fda19bc8fa3b21f,4 +np.float64,0x3fde8dd5263d1baa,0x3fe08de0fedf7029,4 +np.float64,0x3feddd3be2bbba78,0x3ff599b2f3e018cc,4 +np.float64,0xc7a009f58f401,0xc7a009f58f401,4 +np.float64,0xbfef03d5a4fe07ab,0xbff74ee08681f47b,4 +np.float64,0x7fe2cf60eea59ec1,0x3fe905fb44f8cc60,4 +np.float64,0xbfe498fcab6931fa,0xbfe8023a6ff8becf,4 +np.float64,0xbfef7142acfee285,0xbff7fd196133a595,4 +np.float64,0xd214ffdba42a0,0xd214ffdba42a0,4 +np.float64,0x8006de7d78cdbcfc,0x8006de7d78cdbcfc,4 +np.float64,0xb247d34f648fb,0xb247d34f648fb,4 +np.float64,0xbfdd5bece6bab7da,0xbfdf9ba63ca2c5b2,4 +np.float64,0x7fe874650af0e8c9,0x3fe74204e122c10f,4 +np.float64,0x800768c49baed18a,0x800768c49baed18a,4 +np.float64,0x3fb4c0a192298140,0x3fb4cc4c8aa43300,4 +np.float64,0xbfa740531c2e80a0,0xbfa7446b7c74ae8e,4 +np.float64,0x7fe10d6edf221add,0x3fedbcd2eae26657,4 +np.float64,0xbfe9175d0f722eba,0xbfefeaca7f32c6e3,4 +np.float64,0x953e11d32a7c2,0x953e11d32a7c2,4 +np.float64,0x80032df90c465bf3,0x80032df90c465bf3,4 +np.float64,0xffec5b799638b6f2,0xbfe95cd2c69be12c,4 +np.float64,0xffe0c3cfa9a1879f,0x3fe20b99b0c108ce,4 +np.float64,0x3fb610d8e22c21b2,0x3fb61ee0d6c16df8,4 +np.float64,0xffe16bb39962d766,0xc016d370381b6b42,4 +np.float64,0xbfdc72edb238e5dc,0xbfde7bd2de10717a,4 +np.float64,0xffed52dee3baa5bd,0xc01994c08899129a,4 +np.float64,0xffa92aab08325550,0xbff2b881ce363cbd,4 +np.float64,0x7fe028282de0504f,0xc0157ff96c69a9c7,4 +np.float64,0xbfdb2151bf3642a4,0xbfdce196fcc35857,4 +np.float64,0x3fcffbd13c3ff7a2,0x3fd0554b5f0371ac,4 +np.float64,0x800d206bff1a40d8,0x800d206bff1a40d8,4 +np.float64,0x458f818c8b1f1,0x458f818c8b1f1,4 +np.float64,0x800a7b56a234f6ae,0x800a7b56a234f6ae,4 +np.float64,0xffe3d86161e7b0c2,0xbff58d0dbde9f188,4 +np.float64,0xe8ed82e3d1db1,0xe8ed82e3d1db1,4 +np.float64,0x3fe234e0176469c0,0x3fe476bd36b96a75,4 +np.float64,0xbfc7cb9c132f9738,0xbfc812c46e185e0b,4 +np.float64,0xbfeba116c1f7422e,0xbff2b6b7563ad854,4 +np.float64,0x7fe7041de62e083b,0x3f5d2b42aca47274,4 +np.float64,0xbfcf60f4ff3ec1e8,0xbfd002eb83406436,4 +np.float64,0xbfc06067a520c0d0,0xbfc0776e5839ecda,4 +np.float64,0x4384965a87093,0x4384965a87093,4 +np.float64,0xd2ed9d01a5db4,0xd2ed9d01a5db4,4 +np.float64,0x3fbea88cb63d5119,0x3fbece49cc34a379,4 +np.float64,0x3fe7e982ebefd306,0x3feda5bd4c435d43,4 +np.float64,0xffdb60a3e036c148,0xbfcb7ed21e7a8f49,4 +np.float64,0x7fdba9231eb75245,0xbfd750cab1536398,4 +np.float64,0x800d593534dab26b,0x800d593534dab26b,4 +np.float64,0xffdf15fb683e2bf6,0x3fb3aaea23357f06,4 +np.float64,0xbfd6f8a2e5adf146,0xbfd802e509d67c67,4 +np.float64,0x3feeaa31513d5463,0x3ff6c52147dc053c,4 +np.float64,0xf2f6dfd3e5edc,0xf2f6dfd3e5edc,4 +np.float64,0x7fd58d8279ab1b04,0x403243f23d02af2a,4 +np.float64,0x8000000000000001,0x8000000000000001,4 +np.float64,0x3fdffb8e0ebff71c,0x3fe1786cb0a6b0f3,4 +np.float64,0xc999826b93331,0xc999826b93331,4 +np.float64,0xffc4966f19292ce0,0x3ff0836c75c56cc7,4 +np.float64,0x7fef95a4b2ff2b48,0xbfbbe2c27c78154f,4 +np.float64,0xb8f1307f71e26,0xb8f1307f71e26,4 +np.float64,0x3fe807bc7eb00f79,0x3fedde19f2d3c42d,4 +np.float64,0x5e4b6580bc98,0x5e4b6580bc98,4 +np.float64,0xffe19353576326a6,0xc0278c51fee07d36,4 +np.float64,0xbfb0ca6f3e2194e0,0xbfb0d09be673fa72,4 +np.float64,0x3fea724211b4e484,0x3ff15ee06f0a0a13,4 +np.float64,0xbfda21e1c4b443c4,0xbfdbb041f3c86832,4 +np.float64,0x8008082b24901057,0x8008082b24901057,4 +np.float64,0xbfd031aa4ea06354,0xbfd08c77729634bb,4 +np.float64,0xbfc407e153280fc4,0xbfc432275711df5f,4 +np.float64,0xbb4fa4b5769f5,0xbb4fa4b5769f5,4 +np.float64,0x7fed6d1daffada3a,0xc037a14bc7b41fab,4 +np.float64,0xffeee589943dcb12,0x3ff2abfe47037778,4 +np.float64,0x301379d260270,0x301379d260270,4 +np.float64,0xbfec2fefc2b85fe0,0xbff36362c0363e06,4 +np.float64,0xbfe0b1c82e216390,0xbfe264f503f7c22c,4 +np.float64,0xbfea2bce78f4579d,0xbff112d6f07935ea,4 +np.float64,0x18508ef230a13,0x18508ef230a13,4 +np.float64,0x800667a74d6ccf4f,0x800667a74d6ccf4f,4 +np.float64,0x79ce5c8cf39cc,0x79ce5c8cf39cc,4 +np.float64,0x3feda61c8efb4c39,0x3ff54c9ade076f54,4 +np.float64,0x3fe27e06b0e4fc0d,0x3fe4de665c1dc3ca,4 +np.float64,0xbfd15fea2722bfd4,0xbfd1d081c55813b0,4 +np.float64,0xbfe5222c4cea4458,0xbfe8db62deb7d2ad,4 +np.float64,0xbfe8a16c33b142d8,0xbfef02d5831592a8,4 +np.float64,0x3fdb60e7c4b6c1d0,0x3fdd2e4265c4c3b6,4 +np.float64,0x800076d62b60edad,0x800076d62b60edad,4 +np.float64,0xbfec8f1527791e2a,0xbff3da7ed3641e8d,4 +np.float64,0x2af03bfe55e08,0x2af03bfe55e08,4 +np.float64,0xa862ee0950c5e,0xa862ee0950c5e,4 +np.float64,0x7fea5a7c1eb4b4f7,0xbffa6f07d28ef211,4 +np.float64,0x90e118fb21c23,0x90e118fb21c23,4 +np.float64,0xbfead0721bf5a0e4,0xbff1c6c7a771a128,4 +np.float64,0x3f63f4a4c027e94a,0x3f63f4a75665da67,4 +np.float64,0x3fece0efa579c1e0,0x3ff443bec52f021e,4 +np.float64,0xbfdbe743b737ce88,0xbfddd129bff89c15,4 +np.float64,0x3fd48c9b8fa91938,0x3fd5492a630a8cb5,4 +np.float64,0x3ff0000000000000,0x3ff8eb245cbee3a6,4 +np.float64,0xbfd51ea33baa3d46,0xbfd5ebd5dc710204,4 +np.float64,0x3fcfbab0183f7560,0x3fd032a054580b00,4 +np.float64,0x8007abce13cf579d,0x8007abce13cf579d,4 +np.float64,0xbfef0f4723be1e8e,0xbff760c7008e8913,4 +np.float64,0x8006340f524c681f,0x8006340f524c681f,4 +np.float64,0x87b7d7010f71,0x87b7d7010f71,4 +np.float64,0x3fe9422da9b2845b,0x3ff02052e6148c45,4 +np.float64,0x7fddd259b93ba4b2,0xc000731aa33d84b6,4 +np.float64,0x3fe0156d12202ada,0x3fe1972ba309cb29,4 +np.float64,0x8004f1264b89e24d,0x8004f1264b89e24d,4 +np.float64,0x3fececdcacb9d9b9,0x3ff4534d5861f731,4 +np.float64,0x3fd1790ab822f215,0x3fd1eb97b1bb6fb4,4 +np.float64,0xffce5d11863cba24,0xbfcb4f38c17210da,4 +np.float64,0x800a30c32a546187,0x800a30c32a546187,4 +np.float64,0x3fa58cc61c2b198c,0x3fa59008add7233e,4 +np.float64,0xbfe0ac77d62158f0,0xbfe25de3dba0bc4a,4 +np.float64,0xeb8c5753d718b,0xeb8c5753d718b,4 +np.float64,0x3fee5438dafca872,0x3ff644fef7e7adb5,4 +np.float64,0x3faad1eb2c35a3e0,0x3faad83499f94057,4 +np.float64,0x3fe39152c46722a6,0x3fe66fba0b96ab6e,4 +np.float64,0xffd6fd17712dfa2e,0xc010d697d1ab8731,4 +np.float64,0x5214a888a4296,0x5214a888a4296,4 +np.float64,0x8000127a5da024f5,0x8000127a5da024f5,4 +np.float64,0x7feb3a366cb6746c,0x3fbe49bd8d5f213a,4 +np.float64,0xca479501948f3,0xca479501948f3,4 +np.float64,0x7fe7c799ce6f8f33,0xbfd796cd98dc620c,4 +np.float64,0xffe20bcf30a4179e,0xbff8ca5453fa088f,4 +np.float64,0x3fe624638a6c48c7,0x3fea83f123832c3c,4 +np.float64,0xbfe5f1377c6be26f,0xbfea2e143a2d522c,4 +np.float64,0x7fd193f9f8a327f3,0xbfb04ee2602574d4,4 +np.float64,0xbfe7419d2fee833a,0xbfec737f140d363d,4 +np.float64,0x1,0x1,4 +np.float64,0x7fe2ac246c655848,0x3fd14fee3237727a,4 +np.float64,0xa459b42948b37,0xa459b42948b37,4 +np.float64,0x3fb26155ae24c2ab,0x3fb2696fc446d4c6,4 +np.float64,0xbfdd7b332e3af666,0xbfdfc296c21f1aa8,4 +np.float64,0xbfe00dbda4a01b7c,0xbfe18d2b060f0506,4 +np.float64,0x8003bb22d3e77646,0x8003bb22d3e77646,4 +np.float64,0x3fee21b0a57c4361,0x3ff5fb6a21dc911c,4 +np.float64,0x80ca69270194d,0x80ca69270194d,4 +np.float64,0xbfd6d80350adb006,0xbfd7ddb501edbde0,4 +np.float64,0xd2f8b801a5f2,0xd2f8b801a5f2,4 +np.float64,0xbfe856b3f170ad68,0xbfee7334fdc49296,4 +np.float64,0x3fed5c1b20bab836,0x3ff4e73ee5d5c7f3,4 +np.float64,0xbfd58085a5ab010c,0xbfd6596ddc381ffa,4 +np.float64,0x3fe4f0134b29e027,0x3fe88b70602fbd21,4 +np.float64,0xffc9098fdc321320,0x4011c334a74a92cf,4 +np.float64,0x794749bef28ea,0x794749bef28ea,4 +np.float64,0xbfc86b547f30d6a8,0xbfc8b84a4fafe0af,4 +np.float64,0x7fe1356b9da26ad6,0x3fd270bca208d899,4 +np.float64,0x7fca0ef1aa341de2,0xbff851044c0734fa,4 +np.float64,0x80064cb8b62c9972,0x80064cb8b62c9972,4 +np.float64,0xffd3a09a83a74136,0x3ffb66dae0accdf5,4 +np.float64,0x800e301aa15c6035,0x800e301aa15c6035,4 +np.float64,0x800e51f323bca3e6,0x800e51f323bca3e6,4 +np.float64,0x7ff0000000000000,0xfff8000000000000,4 +np.float64,0x800c4278c87884f2,0x800c4278c87884f2,4 +np.float64,0xbfe8481649f0902c,0xbfee576772695096,4 +np.float64,0xffe2344e3fa4689c,0x3fb10442ec0888de,4 +np.float64,0xbfeada313d75b462,0xbff1d1aee3fab3a9,4 +np.float64,0x8009ddfb1333bbf7,0x8009ddfb1333bbf7,4 +np.float64,0x7fed3314c93a6629,0x3ff7a9b12dc1cd37,4 +np.float64,0x3fd55c26da2ab84e,0x3fd630a7b8aac78a,4 +np.float64,0x800cdb5203f9b6a4,0x800cdb5203f9b6a4,4 +np.float64,0xffd04a875da0950e,0x4009a13810ab121d,4 +np.float64,0x800f1acb527e3597,0x800f1acb527e3597,4 +np.float64,0xbf9519bf282a3380,0xbf951a82e9b955ff,4 +np.float64,0x3fcd7a42fa3af486,0x3fce028f3c51072d,4 +np.float64,0xbfdd3e21b73a7c44,0xbfdf769f2ff2480b,4 +np.float64,0xffd4361e2aa86c3c,0xbfc211ce8e9f792c,4 +np.float64,0x7fccf97f6939f2fe,0xbff8464bad830f06,4 +np.float64,0x800ce47fb939c900,0x800ce47fb939c900,4 +np.float64,0xffe9e51df173ca3b,0xbfceaf990d652c4e,4 +np.float64,0x3fe05bba5b20b775,0x3fe1f326e4455442,4 +np.float64,0x800a29b4b134536a,0x800a29b4b134536a,4 +np.float64,0xe6f794b7cdef3,0xe6f794b7cdef3,4 +np.float64,0xffb5b688ce2b6d10,0x3ff924bb97ae2f6d,4 +np.float64,0x7fa74105d82e820b,0x3fd49643aaa9eee4,4 +np.float64,0x80020d15f7a41a2d,0x80020d15f7a41a2d,4 +np.float64,0x3fd6a983d5ad5308,0x3fd7a8cc8835b5b8,4 +np.float64,0x7fcd9798f03b2f31,0x3fc534c2f7bf4721,4 +np.float64,0xffdd31873a3a630e,0xbfe3171fcdffb3f7,4 +np.float64,0x80075183234ea307,0x80075183234ea307,4 +np.float64,0x82f3132505e63,0x82f3132505e63,4 +np.float64,0x3febfd9cb837fb39,0x3ff325bbf812515d,4 +np.float64,0xbfb4630fda28c620,0xbfb46e1f802ec278,4 +np.float64,0x3feeed7c89fddafa,0x3ff72c20ce5a9ee4,4 +np.float64,0x7fd3dcb3c127b967,0x40123d27ec9ec31d,4 +np.float64,0xbfe923450c72468a,0xbff00149c5742725,4 +np.float64,0x7fdef7f91abdeff1,0xbfe02ceb21f7923d,4 +np.float64,0x7fdd70d28fbae1a4,0xbfefcc5c9d10cdfd,4 +np.float64,0x800ca445a8d9488c,0x800ca445a8d9488c,4 +np.float64,0x7fec2754e1f84ea9,0x40173f6c1c97f825,4 +np.float64,0x7fcbca31f7379463,0x401e26bd2667075b,4 +np.float64,0x8003fa1d0847f43b,0x8003fa1d0847f43b,4 +np.float64,0xffe95cf85932b9f0,0xc01308e60278aa11,4 +np.float64,0x8009c53948f38a73,0x8009c53948f38a73,4 +np.float64,0x3fdcca9226b99524,0x3fdee7a008f75d41,4 +np.float64,0xbfe9ee241f33dc48,0xbff0d16bfff6c8e9,4 +np.float64,0xbfb3365058266ca0,0xbfb33f9176ebb51d,4 +np.float64,0x7fa98e10f4331c21,0x3fdee04ffd31314e,4 +np.float64,0xbfe1a11aea634236,0xbfe3a8e3d84fda38,4 +np.float64,0xbfd8df051131be0a,0xbfda342805d1948b,4 +np.float64,0x3d49a2407a935,0x3d49a2407a935,4 +np.float64,0xfc51eefff8a3e,0xfc51eefff8a3e,4 +np.float64,0xda63950bb4c73,0xda63950bb4c73,4 +np.float64,0x80050f3d4fea1e7b,0x80050f3d4fea1e7b,4 +np.float64,0x3fcdbd6e453b7ae0,0x3fce497478c28e77,4 +np.float64,0x7ebd4932fd7aa,0x7ebd4932fd7aa,4 +np.float64,0x7fa3904eac27209c,0xc0015f3125efc151,4 +np.float64,0x7fc59f956b2b3f2a,0xc00c012e7a2c281f,4 +np.float64,0xbfd436d716a86dae,0xbfd4ea13533a942b,4 +np.float64,0x9347ae3d268f6,0x9347ae3d268f6,4 +np.float64,0xffd001764d2002ec,0xbffab3462e515623,4 +np.float64,0x3fe6f406662de80d,0x3febe9bac3954999,4 +np.float64,0x3f943ecaf8287d96,0x3f943f77dee5e77f,4 +np.float64,0x3fd6250efcac4a1c,0x3fd712afa947d56f,4 +np.float64,0xbfe849ff777093ff,0xbfee5b089d03391f,4 +np.float64,0xffd3b8ef8f2771e0,0x4000463ff7f29214,4 +np.float64,0xbfc3bae9252775d4,0xbfc3e34c133f1933,4 +np.float64,0xbfea93943df52728,0xbff18355e4fc341d,4 +np.float64,0x3fc4d922ad29b245,0x3fc508d66869ef29,4 +np.float64,0x4329694a8652e,0x4329694a8652e,4 +np.float64,0x8834f1a71069e,0x8834f1a71069e,4 +np.float64,0xe0e5be8dc1cb8,0xe0e5be8dc1cb8,4 +np.float64,0x7fef4d103afe9a1f,0xc0047b88b94554fe,4 +np.float64,0x3fe9b57af4f36af6,0x3ff0963831d51c3f,4 +np.float64,0x3fe081e2fa6103c6,0x3fe22572e41be655,4 +np.float64,0x3fd78cf7b42f19ef,0x3fd8acafa1ad776a,4 +np.float64,0x7fbffd58d43ffab1,0x3fb16092c7de6036,4 +np.float64,0xbfe1e8bfae23d180,0xbfe40c1c6277dd52,4 +np.float64,0x800a9f59fb153eb4,0x800a9f59fb153eb4,4 +np.float64,0xffebe14e33b7c29c,0x3fe0ec532f4deedd,4 +np.float64,0xffc36ca00426d940,0xc000806a712d6e83,4 +np.float64,0xbfcc2be82d3857d0,0xbfcca2a7d372ec64,4 +np.float64,0x800c03b908780772,0x800c03b908780772,4 +np.float64,0xf315a64be62b5,0xf315a64be62b5,4 +np.float64,0xbfe644043cec8808,0xbfeab974d3dc6d80,4 +np.float64,0x3fedb7de3cbb6fbc,0x3ff56549a5acd324,4 +np.float64,0xbfb1a875522350e8,0xbfb1afa41dee338d,4 +np.float64,0xffee8d4a407d1a94,0x3fead1749a636ff6,4 +np.float64,0x8004061c13080c39,0x8004061c13080c39,4 +np.float64,0x3fe650ae7feca15c,0x3feacefb8bc25f64,4 +np.float64,0x3fda8340e6b50682,0x3fdc24275cab1df8,4 +np.float64,0x8009084344321087,0x8009084344321087,4 +np.float64,0x7fdd19cb823a3396,0xbfd1d8fb35d89e3f,4 +np.float64,0xbfe893172571262e,0xbfeee716b592b93c,4 +np.float64,0x8ff5acc11fec,0x8ff5acc11fec,4 +np.float64,0xbfdca0c57cb9418a,0xbfdeb42465a1b59e,4 +np.float64,0xffd77bd2a3aef7a6,0x4012cd69e85b82d8,4 +np.float64,0xbfe6ea78982dd4f1,0xbfebd8ec61fb9e1f,4 +np.float64,0x7fe14b1d80a2963a,0xc02241642102cf71,4 +np.float64,0x3fe712bf286e257e,0x3fec20012329a7fb,4 +np.float64,0x7fcb6fa4d636df49,0x400b899d14a886b3,4 +np.float64,0x3fb82cb39a305960,0x3fb83f29c5f0822e,4 +np.float64,0x7fed694c8b3ad298,0xbfe2724373c69808,4 +np.float64,0xbfcd21229f3a4244,0xbfcda497fc3e1245,4 +np.float64,0x564d3770ac9a8,0x564d3770ac9a8,4 +np.float64,0xf4409e13e8814,0xf4409e13e8814,4 +np.float64,0x80068dca9a8d1b96,0x80068dca9a8d1b96,4 +np.float64,0xbfe13f82afe27f06,0xbfe3236ddded353f,4 +np.float64,0x80023f8114647f03,0x80023f8114647f03,4 +np.float64,0xeafba7dfd5f75,0xeafba7dfd5f75,4 +np.float64,0x3feca74ddeb94e9c,0x3ff3f95dcce5a227,4 +np.float64,0x10000000000000,0x10000000000000,4 +np.float64,0xbfebdb4141f7b682,0xbff2fc29823ac64a,4 +np.float64,0xbfcd75ee2f3aebdc,0xbfcdfdfd87cc6a29,4 +np.float64,0x7fc010cda420219a,0x3fae4ca2cf1f2657,4 +np.float64,0x1a90209e35205,0x1a90209e35205,4 +np.float64,0x8008057d01900afa,0x8008057d01900afa,4 +np.float64,0x3f9cb5f280396be5,0x3f9cb7dfb4e4be4e,4 +np.float64,0xffe1bbb60b63776c,0xc00011b1ffcb2561,4 +np.float64,0xffda883f6fb5107e,0x4044238ef4e2a198,4 +np.float64,0x3fc07c0b4a20f817,0x3fc09387de9eebcf,4 +np.float64,0x8003a9ebc0c753d8,0x8003a9ebc0c753d8,4 +np.float64,0x1d7fd5923affc,0x1d7fd5923affc,4 +np.float64,0xbfe9cd8cf9b39b1a,0xbff0af43e567ba4a,4 +np.float64,0x11285cb42250c,0x11285cb42250c,4 +np.float64,0xffe81ae1ccb035c3,0xbfe038be7eb563a6,4 +np.float64,0xbfe56473b1eac8e8,0xbfe94654d8ab9e75,4 +np.float64,0x3fee904619fd208c,0x3ff69e198152fe17,4 +np.float64,0xbfeeb9a2cbfd7346,0xbff6dc8d96da78cd,4 +np.float64,0x8006cdfa59ed9bf5,0x8006cdfa59ed9bf5,4 +np.float64,0x8008f2366d31e46d,0x8008f2366d31e46d,4 +np.float64,0x8008d5f91e31abf3,0x8008d5f91e31abf3,4 +np.float64,0x3fe85886f8b0b10e,0x3fee76af16f5a126,4 +np.float64,0x3fefb9b2b73f7365,0x3ff8745128fa3e3b,4 +np.float64,0x7fdf3e721f3e7ce3,0xbfb19381541ca2a8,4 +np.float64,0x3fd2768c41a4ed18,0x3fd2fe2f85a3f3a6,4 +np.float64,0xbfcabe3c6a357c78,0xbfcb239fb88bc260,4 +np.float64,0xffdffb6a3dbff6d4,0xbff7af4759fd557c,4 +np.float64,0x800817f75f302fef,0x800817f75f302fef,4 +np.float64,0xbfe6a1d1762d43a3,0xbfeb5a399a095ef3,4 +np.float64,0x7fd6f32f912de65e,0x40016dedc51aabd0,4 +np.float64,0x3fc6cb26652d964d,0x3fc7099f047d924a,4 +np.float64,0x3fe8b975d67172ec,0x3fef31946123c0e7,4 +np.float64,0xffe44a09d1e89413,0x3fdee9e5eac6e540,4 +np.float64,0xbfece76d4cb9cedb,0xbff44c34849d07ba,4 +np.float64,0x7feb76027036ec04,0x3fe08595a5e263ac,4 +np.float64,0xffe194f591a329ea,0x3fbe5bd626400a70,4 +np.float64,0xbfc170698122e0d4,0xbfc18c3de8b63565,4 +np.float64,0x3fc82b2c0f305658,0x3fc875c3b5fbcd08,4 +np.float64,0x3fd5015634aa02ac,0x3fd5cb1df07213c3,4 +np.float64,0x7fe640884b6c8110,0xbff66255a420abb5,4 +np.float64,0x5a245206b448b,0x5a245206b448b,4 +np.float64,0xffe9d9fa2f73b3f4,0xc0272b0dd34ab9bf,4 +np.float64,0x3fd990e8aab321d0,0x3fdb04cd3a29bcc3,4 +np.float64,0xde9dda8bbd3bc,0xde9dda8bbd3bc,4 +np.float64,0xbfe81b32b4703666,0xbfee029937fa9f5a,4 +np.float64,0xbfe68116886d022d,0xbfeb21c62081cb73,4 +np.float64,0x3fb8da191231b432,0x3fb8ee28c71507d3,4 +np.float64,0x3fb111395a222273,0x3fb117b57de3dea4,4 +np.float64,0xffbafadc6a35f5b8,0x3ffcc6d2370297b9,4 +np.float64,0x8002ca475b05948f,0x8002ca475b05948f,4 +np.float64,0xbfeafef57875fdeb,0xbff1fb1315676f24,4 +np.float64,0x7fcda427d73b484f,0xbff9f70212694d17,4 +np.float64,0xffe2517b3ba4a2f6,0xc029ca6707305bf4,4 +np.float64,0x7fc5ee156b2bdc2a,0xbff8384b59e9056e,4 +np.float64,0xbfec22af3278455e,0xbff3530fe25816b4,4 +np.float64,0x6b5a8c2cd6b52,0x6b5a8c2cd6b52,4 +np.float64,0xffdaf6c4b935ed8a,0x4002f00ce58affcf,4 +np.float64,0x800a41813c748303,0x800a41813c748303,4 +np.float64,0xbfd09a1269213424,0xbfd0fc0a0c5de8eb,4 +np.float64,0x7fa2cb74d42596e9,0x3fc3d40e000fa69d,4 +np.float64,0x7ff8000000000000,0x7ff8000000000000,4 +np.float64,0x3fbfbf8ed63f7f1e,0x3fbfe97bcad9f53a,4 +np.float64,0x7fe0ebba65a1d774,0x401b0f17b28618df,4 +np.float64,0x3fd02c3a25a05874,0x3fd086aa55b19c9c,4 +np.float64,0xec628f95d8c52,0xec628f95d8c52,4 +np.float64,0x3fd319329fa63264,0x3fd3afb04e0dec63,4 +np.float64,0x180e0ade301c2,0x180e0ade301c2,4 +np.float64,0xbfe8d78324f1af06,0xbfef6c66153064ee,4 +np.float64,0xffb89fa200313f48,0xbfeb96ff2d9358dc,4 +np.float64,0x7fe6abcf86ed579e,0xc0269f4de86365ec,4 +np.float64,0x7fdff8cd65bff19a,0xbfd0f7c6b9052c9a,4 +np.float64,0xbfd2e3a53d25c74a,0xbfd37520cda5f6b2,4 +np.float64,0x7fe844b096708960,0x3ff696a6182e5a7a,4 +np.float64,0x7fdce0c7a3b9c18e,0x3fd42875d69ed379,4 +np.float64,0xffba5a91cc34b520,0x4001b571e8991951,4 +np.float64,0xffe78fe4a6ef1fc9,0x3ff4507b31f5b3bc,4 +np.float64,0xbfd7047493ae08ea,0xbfd810618a53fffb,4 +np.float64,0xc6559def8cab4,0xc6559def8cab4,4 +np.float64,0x3fe75d67a76ebacf,0x3feca56817de65e4,4 +np.float64,0xffd24adbd6a495b8,0xc012c491addf2df5,4 +np.float64,0x7fed35e28dba6bc4,0x403a0fa555ff7ec6,4 +np.float64,0x80078c4afa0f1897,0x80078c4afa0f1897,4 +np.float64,0xa6ec39114dd87,0xa6ec39114dd87,4 +np.float64,0x7fb1bd33ba237a66,0x4010092bb6810fd4,4 +np.float64,0x800ecf215edd9e43,0x800ecf215edd9e43,4 +np.float64,0x3fb7c169242f82d2,0x3fb7d2ed30c462e6,4 +np.float64,0xbf71b46d60236900,0xbf71b4749a10c112,4 +np.float64,0x800d7851787af0a3,0x800d7851787af0a3,4 +np.float64,0x3fcb4a45e7369488,0x3fcbb61701a1bcec,4 +np.float64,0x3fd4e3682429c6d0,0x3fd5a9bcb916eb94,4 +np.float64,0x800497564c292ead,0x800497564c292ead,4 +np.float64,0xbfca3737a1346e70,0xbfca96a86ae5d687,4 +np.float64,0x19aa87e03356,0x19aa87e03356,4 +np.float64,0xffb2593fe624b280,0xc05fedb99b467ced,4 +np.float64,0xbfdd8748fbbb0e92,0xbfdfd1a7df17252c,4 +np.float64,0x8004c7afc7098f60,0x8004c7afc7098f60,4 +np.float64,0x7fde48b2bf3c9164,0xbfe36ef1158ed420,4 +np.float64,0xbfec8e0eb0f91c1d,0xbff3d9319705a602,4 +np.float64,0xffea1be204f437c3,0xc0144f67298c3e6f,4 +np.float64,0x7fdb906b593720d6,0xbfce99233396eda7,4 +np.float64,0x3fef0f114ffe1e22,0x3ff76072a258a51b,4 +np.float64,0x3fe3e284c8e7c50a,0x3fe6e9b05e17c999,4 +np.float64,0xbfbda9eef23b53e0,0xbfbdcc1abb443597,4 +np.float64,0x3feb6454d4f6c8aa,0x3ff26f65a85baba4,4 +np.float64,0x3fea317439f462e8,0x3ff118e2187ef33f,4 +np.float64,0x376ad0646ed5b,0x376ad0646ed5b,4 +np.float64,0x7fdd461a1c3a8c33,0x3f7ba20fb79e785f,4 +np.float64,0xebc520a3d78a4,0xebc520a3d78a4,4 +np.float64,0x3fca90fe53352200,0x3fcaf45c7fae234d,4 +np.float64,0xbfe80dd1de701ba4,0xbfede97e12cde9de,4 +np.float64,0x3fd242b00ea48560,0x3fd2c5cf9bf69a31,4 +np.float64,0x7fe46c057828d80a,0xbfe2f76837488f94,4 +np.float64,0x3fc162bea322c580,0x3fc17e517c958867,4 +np.float64,0xffebf0452ff7e08a,0x3ffc3fd95c257b54,4 +np.float64,0xffd88043c6310088,0x4008b05598d0d95f,4 +np.float64,0x800d8c49da5b1894,0x800d8c49da5b1894,4 +np.float64,0xbfed33b487ba6769,0xbff4b0ea941f8a6a,4 +np.float64,0x16b881e22d711,0x16b881e22d711,4 +np.float64,0x288bae0051177,0x288bae0051177,4 +np.float64,0xffc83a0fe8307420,0x4006eff03da17f86,4 +np.float64,0x3fc7868b252f0d18,0x3fc7cb4954290324,4 +np.float64,0xbfe195514b232aa2,0xbfe398aae6c8ed76,4 +np.float64,0x800c001ae7f80036,0x800c001ae7f80036,4 +np.float64,0x7feb82abe7370557,0xbff1e13fe6fad23c,4 +np.float64,0xffecf609cdf9ec13,0xc0112aa1805ae59e,4 +np.float64,0xffddd654f63bacaa,0x3fe46cce899f710d,4 +np.float64,0x3fe2163138642c62,0x3fe44b9c760acd4c,4 +np.float64,0x4e570dc09cae2,0x4e570dc09cae2,4 +np.float64,0x7fe9e8d091f3d1a0,0xc000fe20f8e9a4b5,4 +np.float64,0x7fe60042952c0084,0x3fd0aa740f394c2a,4 diff --git a/shared/package-files/3a/3ab2b90b12dba69c22397d8bf96861f61ec60bd5d7b9e3645a1845e4e0da0a70/test_c.py b/shared/package-files/3a/3ab2b90b12dba69c22397d8bf96861f61ec60bd5d7b9e3645a1845e4e0da0a70/test_c.py new file mode 100644 index 0000000000000000000000000000000000000000..029294d6c3191b5555df7acb25b133a313bbb05e --- /dev/null +++ b/shared/package-files/3a/3ab2b90b12dba69c22397d8bf96861f61ec60bd5d7b9e3645a1845e4e0da0a70/test_c.py @@ -0,0 +1,875 @@ +from sympy.core import ( + S, pi, oo, Symbol, symbols, Rational, Integer, Float, Function, Mod, GoldenRatio, EulerGamma, Catalan, + Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr +) +from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) +from sympy.functions import ( + Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf, + erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh, + sqrt, tan, tanh, fibonacci, lucas +) +from sympy.sets import Range +from sympy.logic import ITE, Implies, Equivalent +from sympy.codegen import For, aug_assign, Assignment +from sympy.testing.pytest import raises, XFAIL +from sympy.printing.c import C89CodePrinter, C99CodePrinter, get_math_macros +from sympy.codegen.ast import ( + AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const, + While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return, + real, float32, float64, float80, float128, intc, Comment, CodeBlock +) +from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt +from sympy.codegen.cnodes import restrict +from sympy.utilities.lambdify import implemented_function +from sympy.tensor import IndexedBase, Idx +from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix + +from sympy.printing.codeprinter import ccode + +x, y, z = symbols('x,y,z') + + +def test_printmethod(): + class fabs(Abs): + def _ccode(self, printer): + return "fabs(%s)" % printer._print(self.args[0]) + + assert ccode(fabs(x)) == "fabs(x)" + + +def test_ccode_sqrt(): + assert ccode(sqrt(x)) == "sqrt(x)" + assert ccode(x**0.5) == "sqrt(x)" + assert ccode(sqrt(x)) == "sqrt(x)" + + +def test_ccode_Pow(): + assert ccode(x**3) == "pow(x, 3)" + assert ccode(x**(y**3)) == "pow(x, pow(y, 3))" + g = implemented_function('g', Lambda(x, 2*x)) + assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ + "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)" + assert ccode(x**-1.0) == '1.0/x' + assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)' + assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)' + _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"), + (lambda base, exp: not exp.is_integer, "pow")] + assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)' + assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)' + assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)' + _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp), + (lambda base, exp: base != 2, 'pow')] + # Related to gh-11353 + assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)' + assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)' + # For issue 14160 + assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), + evaluate=False)) == '-2*x/(y*y)' + + +def test_ccode_Max(): + # Test for gh-11926 + assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))' + + +def test_ccode_Min_performance(): + #Shouldn't take more than a few seconds + big_min = Min(*symbols('a[0:50]')) + for curr_standard in ('c89', 'c99', 'c11'): + output = ccode(big_min, standard=curr_standard) + assert output.count('(') == output.count(')') + + +def test_ccode_constants_mathh(): + assert ccode(exp(1)) == "M_E" + assert ccode(pi) == "M_PI" + assert ccode(oo, standard='c89') == "HUGE_VAL" + assert ccode(-oo, standard='c89') == "-HUGE_VAL" + assert ccode(oo) == "INFINITY" + assert ccode(-oo, standard='c99') == "-INFINITY" + assert ccode(pi, type_aliases={real: float80}) == "M_PIl" + + +def test_ccode_constants_other(): + assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) + assert ccode( + 2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17) + assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17) + + +def test_ccode_Rational(): + assert ccode(Rational(3, 7)) == "3.0/7.0" + assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L" + assert ccode(Rational(18, 9)) == "2" + assert ccode(Rational(3, -7)) == "-3.0/7.0" + assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L" + assert ccode(Rational(-3, -7)) == "3.0/7.0" + assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L" + assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0" + assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L" + assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x" + assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x" + + +def test_ccode_Integer(): + assert ccode(Integer(67)) == "67" + assert ccode(Integer(-1)) == "-1" + + +def test_ccode_functions(): + assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" + + +def test_ccode_inline_function(): + x = symbols('x') + g = implemented_function('g', Lambda(x, 2*x)) + assert ccode(g(x)) == "2*x" + g = implemented_function('g', Lambda(x, 2*x/Catalan)) + assert ccode( + g(x)) == "const double Catalan = %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 ccode(g(A[i]), assign_to=A[i]) == ( + "for (int i=0; i y" + assert ccode(Ge(x, y)) == "x >= y" + + +def test_ccode_Piecewise(): + expr = Piecewise((x, x < 1), (x**2, True)) + assert ccode(expr) == ( + "((x < 1) ? (\n" + " x\n" + ")\n" + ": (\n" + " pow(x, 2)\n" + "))") + assert ccode(expr, assign_to="c") == ( + "if (x < 1) {\n" + " c = x;\n" + "}\n" + "else {\n" + " c = pow(x, 2);\n" + "}") + expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)) + assert ccode(expr) == ( + "((x < 1) ? (\n" + " x\n" + ")\n" + ": ((x < 2) ? (\n" + " x + 1\n" + ")\n" + ": (\n" + " pow(x, 2)\n" + ")))") + assert ccode(expr, assign_to='c') == ( + "if (x < 1) {\n" + " c = x;\n" + "}\n" + "else if (x < 2) {\n" + " c = x + 1;\n" + "}\n" + "else {\n" + " c = pow(x, 2);\n" + "}") + # 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: ccode(expr)) + + +def test_ccode_sinc(): + from sympy.functions.elementary.trigonometric import sinc + expr = sinc(x) + assert ccode(expr) == ( + "((x != 0) ? (\n" + " sin(x)/x\n" + ")\n" + ": (\n" + " 1\n" + "))") + + +def test_ccode_Piecewise_deep(): + p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))) + assert p == ( + "2*((x < 1) ? (\n" + " x\n" + ")\n" + ": ((x < 2) ? (\n" + " x + 1\n" + ")\n" + ": (\n" + " pow(x, 2)\n" + ")))") + expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1 + assert ccode(expr) == ( + "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" + " 0\n" + ")\n" + ": (\n" + " 1\n" + ")) + cos(z) - 1") + assert ccode(expr, assign_to='c') == ( + "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" + " 0\n" + ")\n" + ": (\n" + " 1\n" + ")) + cos(z) - 1;") + + +def test_ccode_ITE(): + expr = ITE(x < 1, y, z) + assert ccode(expr) == ( + "((x < 1) ? (\n" + " y\n" + ")\n" + ": (\n" + " z\n" + "))") + + +def test_ccode_settings(): + raises(TypeError, lambda: ccode(sin(x), method="garbage")) + + +def test_ccode_Indexed(): + s, n, m, o = symbols('s n m o', integer=True) + i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) + + x = IndexedBase('x')[j] + A = IndexedBase('A')[i, j] + B = IndexedBase('B')[i, j, k] + + p = C99CodePrinter() + + assert p._print_Indexed(x) == 'x[j]' + assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) + assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) + + A = IndexedBase('A', shape=(5,3))[i, j] + assert p._print_Indexed(A) == 'A[%s]' % (3*i + j) + + A = IndexedBase('A', shape=(5,3), strides='F')[i, j] + assert ccode(A) == 'A[%s]' % (i + 5*j) + + A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j] + assert ccode(A) == 'A[o + s*j + i]' + + Abase = IndexedBase('A', strides=(s, m, n), offset=o) + assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]' + assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]' + + +def test_Element(): + assert ccode(Element('x', 'ij')) == 'x[i][j]' + assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]' + assert ccode(Element('x', (3,))) == 'x[3]' + assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]' + + +def test_ccode_Indexed_without_looking_for_contraction(): + len_y = 5 + y = IndexedBase('y', shape=(len_y,)) + x = IndexedBase('x', shape=(len_y,)) + Dy = IndexedBase('Dy', shape=(len_y-1,)) + i = Idx('i', len_y-1) + e = Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) + code0 = ccode(e.rhs, assign_to=e.lhs, contract=False) + assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1) + + +def test_ccode_loops_matrix_vector(): + n, m = symbols('n m', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + + s = ( + 'for (int i=0; i0), (y, True)), sin(z)]) + A = MatrixSymbol('A', 3, 1) + assert ccode(mat, A) == ( + "A[0] = x*y;\n" + "if (y > 0) {\n" + " A[1] = x + 2;\n" + "}\n" + "else {\n" + " A[1] = y;\n" + "}\n" + "A[2] = sin(z);") + # Test using MatrixElements in expressions + expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] + assert ccode(expr) == ( + "((x > 0) ? (\n" + " 2*A[2]\n" + ")\n" + ": (\n" + " A[2]\n" + ")) + sin(A[1]) + A[0]") + # Test using MatrixElements in a Matrix + q = MatrixSymbol('q', 5, 1) + M = MatrixSymbol('M', 3, 3) + m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], + [q[1,0] + q[2,0], q[3, 0], 5], + [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) + assert ccode(m, M) == ( + "M[0] = sin(q[1]);\n" + "M[1] = 0;\n" + "M[2] = cos(q[2]);\n" + "M[3] = q[1] + q[2];\n" + "M[4] = q[3];\n" + "M[5] = 5;\n" + "M[6] = 2*q[4]/q[1];\n" + "M[7] = sqrt(q[0]) + 4;\n" + "M[8] = 0;") + + +def test_sparse_matrix(): + # gh-15791 + assert 'Not supported in C' in ccode(SparseMatrix([[1, 2, 3]])) + + +def test_ccode_reserved_words(): + x, y = symbols('x, if') + with raises(ValueError): + ccode(y**2, error_on_reserved=True, standard='C99') + assert ccode(y**2) == 'pow(if_, 2)' + assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x' + assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)' + + +def test_ccode_sign(): + expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))' + expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))' + expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))' + assert ccode(expr1) == ref1 + assert ccode(expr1, 'z') == 'z = %s;' % ref1 + assert ccode(expr2) == ref2 + assert ccode(expr3) == ref3 + +def test_ccode_Assignment(): + assert ccode(Assignment(x, y + z)) == 'x = y + z;' + assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;' + + +def test_ccode_For(): + f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)]) + assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n" + " y *= x;\n" + "}") + +def test_ccode_Max_Min(): + assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)' + assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)' + assert ccode(Min(x, 0, sqrt(x)), standard='c89') == ( + '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))' + ) + +def test_ccode_standard(): + assert ccode(expm1(x), standard='c99') == 'expm1(x)' + assert ccode(nan, standard='c99') == 'NAN' + assert ccode(float('nan'), standard='c99') == 'NAN' + + +def test_C89CodePrinter(): + c89printer = C89CodePrinter() + assert c89printer.language == 'C' + assert c89printer.standard == 'C89' + assert 'void' in c89printer.reserved_words + assert 'template' not in c89printer.reserved_words + + +def test_C99CodePrinter(): + assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)' + assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)' + assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)' + assert C99CodePrinter().doprint(log2(x)) == 'log2(x)' + assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)' + assert C99CodePrinter().doprint(log10(x)) == 'log10(x)' + assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)' # note Cbrt due to cbrt already taken. + assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)' + assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)' + assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))' + assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)' + c99printer = C99CodePrinter() + assert c99printer.language == 'C' + assert c99printer.standard == 'C99' + assert 'restrict' in c99printer.reserved_words + assert 'using' not in c99printer.reserved_words + + +@XFAIL +def test_C99CodePrinter__precision_f80(): + f80_printer = C99CodePrinter({"type_aliases": {real: float80}}) + assert f80_printer.doprint(sin(x+Float('2.1'))) == 'sinl(x + 2.1L)' + + +def test_C99CodePrinter__precision(): + n = symbols('n', integer=True) + p = symbols('p', integer=True, positive=True) + f32_printer = C99CodePrinter({"type_aliases": {real: float32}}) + f64_printer = C99CodePrinter({"type_aliases": {real: float64}}) + f80_printer = C99CodePrinter({"type_aliases": {real: float80}}) + assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)' + assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)' + assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)' + + for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']): + def check(expr, ref): + assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) + check(Abs(n), 'abs(n)') + check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})') + check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))') + check(exp(x*8.0), 'exp{s}(8.0{S}*x)') + check(exp2(x), 'exp2{s}(x)') + check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)') + check(Mod(p, 2), 'p % 2') + check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 5)') + check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})') + check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})') + check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)') + check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)') + check(log2(x*8.0), 'log2{s}(8.0{S}*x)') + check(log1p(x), 'log1p{s}(x)') + check(2**x, 'pow{s}(2, x)') + check(2.0**x, 'pow{s}(2.0{S}, x)') + check(x**3, 'pow{s}(x, 3)') + check(x**4.0, 'pow{s}(x, 4.0{S})') + check(sqrt(3+x), 'sqrt{s}(x + 3)') + check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})') + check(hypot(x, y), 'hypot{s}(x, y)') + check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})') + check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})') + check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})') + check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})') + check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})') + check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})') + check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)') + + check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})') + check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})') + check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})') + check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})') + check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})') + check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})') + check(erf(42.*x), 'erf{s}(42.0{S}*x)') + check(erfc(42.*x), 'erfc{s}(42.0{S}*x)') + check(gamma(x), 'tgamma{s}(x)') + check(loggamma(x), 'lgamma{s}(x)') + + check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})") + check(floor(x + 2.), "floor{s}(x + 2.0{S})") + check(fma(x, y, -z), 'fma{s}(x, y, -z)') + check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))') + check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)') + + +def test_get_math_macros(): + macros = get_math_macros() + assert macros[exp(1)] == 'M_E' + assert macros[1/Sqrt(2)] == 'M_SQRT1_2' + + +def test_ccode_Declaration(): + i = symbols('i', integer=True) + var1 = Variable(i, type=Type.from_expr(i)) + dcl1 = Declaration(var1) + assert ccode(dcl1) == 'int i' + + var2 = Variable(x, type=float32, attrs={value_const}) + dcl2a = Declaration(var2) + assert ccode(dcl2a) == 'const float x' + dcl2b = var2.as_Declaration(value=pi) + assert ccode(dcl2b) == 'const float x = M_PI' + + var3 = Variable(y, type=Type('bool')) + dcl3 = Declaration(var3) + printer = C89CodePrinter() + assert 'stdbool.h' not in printer.headers + assert printer.doprint(dcl3) == 'bool y' + assert 'stdbool.h' in printer.headers + + u = symbols('u', real=True) + ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict}) + dcl4 = Declaration(ptr4) + assert ccode(dcl4) == 'double * const restrict u' + + var5 = Variable(x, Type('__float128'), attrs={value_const}) + dcl5a = Declaration(var5) + assert ccode(dcl5a) == 'const __float128 x' + var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs) + dcl5b = Declaration(var5b) + assert ccode(dcl5b) == 'const __float128 x = M_PI' + + +def test_C99CodePrinter_custom_type(): + # We will look at __float128 (new in glibc 2.26) + f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp) + p128 = C99CodePrinter({ + "type_aliases": {real: f128}, + "type_literal_suffixes": {f128: 'Q'}, + "type_func_suffixes": {f128: 'f128'}, + "type_math_macro_suffixes": { + real: 'f128', + f128: 'f128' + }, + "type_macros": { + f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',) + } + }) + assert p128.doprint(x) == 'x' + assert not p128.headers + assert not p128.libraries + assert not p128.macros + assert p128.doprint(2.0) == '2.0Q' + assert not p128.headers + assert not p128.libraries + assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'} + + assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q' + assert p128.doprint(sin(x)) == 'sinf128(x)' + assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)' + assert p128.doprint(x**-1.0) == '1.0Q/x' + + var5 = Variable(x, f128, attrs={value_const}) + + dcl5a = Declaration(var5) + assert ccode(dcl5a) == 'const _Float128 x' + var5b = Variable(x, f128, pi, attrs={value_const}) + dcl5b = Declaration(var5b) + assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128' + var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const}) + dcl5c = Declaration(var5b) + assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig) + + +def test_MatrixElement_printing(): + # test cases for issue #11821 + A = MatrixSymbol("A", 1, 3) + B = MatrixSymbol("B", 1, 3) + C = MatrixSymbol("C", 1, 3) + + assert(ccode(A[0, 0]) == "A[0]") + assert(ccode(3 * A[0, 0]) == "3*A[0]") + + F = C[0, 0].subs(C, A - B) + assert(ccode(F) == "(A - B)[0]") + +def test_ccode_math_macros(): + assert ccode(z + exp(1)) == 'z + M_E' + assert ccode(z + log2(exp(1))) == 'z + M_LOG2E' + assert ccode(z + 1/log(2)) == 'z + M_LOG2E' + assert ccode(z + log(2)) == 'z + M_LN2' + assert ccode(z + log(10)) == 'z + M_LN10' + assert ccode(z + pi) == 'z + M_PI' + assert ccode(z + pi/2) == 'z + M_PI_2' + assert ccode(z + pi/4) == 'z + M_PI_4' + assert ccode(z + 1/pi) == 'z + M_1_PI' + assert ccode(z + 2/pi) == 'z + M_2_PI' + assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI' + assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI' + assert ccode(z + sqrt(2)) == 'z + M_SQRT2' + assert ccode(z + Sqrt(2)) == 'z + M_SQRT2' + assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2' + assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2' + + +def test_ccode_Type(): + assert ccode(Type('float')) == 'float' + assert ccode(intc) == 'int' + + +def test_ccode_codegen_ast(): + # Note that C only allows comments of the form /* ... */, double forward + # slash is not standard C, and some C compilers will grind to a halt upon + # encountering them. + assert ccode(Comment("this is a comment")) == "/* this is a comment */" # not // + assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == ( + 'while (fabs(x) > 1) {\n' + ' x -= 1;\n' + '}' + ) + assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == ( + '{\n' + ' x += 1;\n' + '}' + ) + inp_x = Declaration(Variable(x, type=real)) + assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)' + assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == ( + 'double pwer(double x){\n' + ' x = pow(x, 2);\n' + '}' + ) + + # Elements of CodeBlock are formatted as statements: + block = CodeBlock( + x, + Print([x, y], "%d %d"), + FunctionCall('pwer', [x]), + Return(x), + ) + assert ccode(block) == '\n'.join([ + 'x;', + 'printf("%d %d", x, y);', + 'pwer(x);', + 'return x;', + ]) + +def test_ccode_UnevaluatedExpr(): + assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y" + assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)" # gh-21955 + w = symbols('w') + assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)" + + p, q, r = symbols("p q r", real=True) + q_r = UnevaluatedExpr(q + r) + expr = abs(exp(p+q_r)) + assert ccode(expr) == "exp(p + (q + r))" + + +def test_ccode_array_like_containers(): + assert ccode([2,3,4]) == "{2, 3, 4}" + assert ccode((2,3,4)) == "{2, 3, 4}" diff --git a/shared/package-files/3a/3ab3cc4364e2b2e46cc8b2931f2340c658c71236918e7d08e0b743d994cf4b66/tws2103 b/shared/package-files/3a/3ab3cc4364e2b2e46cc8b2931f2340c658c71236918e7d08e0b743d994cf4b66/tws2103 new file mode 100644 index 0000000000000000000000000000000000000000..213d40fd7cda69568ce0c0e223ef9ca9af002a57 Binary files /dev/null and b/shared/package-files/3a/3ab3cc4364e2b2e46cc8b2931f2340c658c71236918e7d08e0b743d994cf4b66/tws2103 differ diff --git a/shared/package-files/3a/3ab3cc4364e2b2e46cc8b2931f2340c658c71236918e7d08e0b743d994cf4b66/xdku b/shared/package-files/3a/3ab3cc4364e2b2e46cc8b2931f2340c658c71236918e7d08e0b743d994cf4b66/xdku new file mode 100644 index 0000000000000000000000000000000000000000..213d40fd7cda69568ce0c0e223ef9ca9af002a57 Binary files /dev/null and b/shared/package-files/3a/3ab3cc4364e2b2e46cc8b2931f2340c658c71236918e7d08e0b743d994cf4b66/xdku differ diff --git a/shared/package-files/3a/3ab5243d35c4ea04587aba65f9ae22ad6b1a9cdd5e3917a62cf1ca0f901bbb8f/cuda_env.py b/shared/package-files/3a/3ab5243d35c4ea04587aba65f9ae22ad6b1a9cdd5e3917a62cf1ca0f901bbb8f/cuda_env.py new file mode 100644 index 0000000000000000000000000000000000000000..6171921173e9717853eafa9497292a7dbdaaf903 --- /dev/null +++ b/shared/package-files/3a/3ab5243d35c4ea04587aba65f9ae22ad6b1a9cdd5e3917a62cf1ca0f901bbb8f/cuda_env.py @@ -0,0 +1,45 @@ +import functools +import logging +from typing import Optional + +import torch + +from ... import config + +log = logging.getLogger(__name__) + + +def get_cuda_arch() -> Optional[str]: + try: + cuda_arch = config.cuda.arch + if cuda_arch is None: + # Get Compute Capability of the first Visible device + major, minor = torch.cuda.get_device_capability(0) + return str(major * 10 + minor) + return str(cuda_arch) + except Exception as e: + log.error("Error getting cuda arch: %s", e) + return None + + +def get_cuda_version() -> Optional[str]: + try: + cuda_version = config.cuda.version + if cuda_version is None: + cuda_version = torch.version.cuda + return cuda_version + except Exception as e: + log.error("Error getting cuda version: %s", e) + return None + + +@functools.lru_cache(None) +def nvcc_exist(nvcc_path: str = "nvcc") -> bool: + if nvcc_path is None: + return False + import subprocess + + res = subprocess.call( + ["which", nvcc_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + return res == 0 diff --git a/shared/package-files/3a/3ab568437295066c91017ced399c27731cfa85ca2624360ac2776c24060645fb/generic_math.h b/shared/package-files/3a/3ab568437295066c91017ced399c27731cfa85ca2624360ac2776c24060645fb/generic_math.h new file mode 100644 index 0000000000000000000000000000000000000000..adfdbfd9955c00659799163e83742ed55f73f5a0 --- /dev/null +++ b/shared/package-files/3a/3ab568437295066c91017ced399c27731cfa85ca2624360ac2776c24060645fb/generic_math.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include + +#if defined(__CUDA_ARCH__) +#include +#define C10_COMPAT_COPYSIGN c10::cuda::compat::copysign +#elif defined(__HIPCC__) +#include +#define C10_COMPAT_COPYSIGN c10::hip::compat::copysign +#else +#include +#define C10_COMPAT_COPYSIGN c10::copysign +#endif + +// The functions in this file should be header-only as it is used under +// ABI-compatibility mode. + +namespace c10 { + +// NOTE: [Floor Division in Python] +// Python's __floordiv__ operator is more complicated than just floor(a / b). +// It aims to maintain the property: a == (a // b) * b + remainder(a, b) +// which can otherwise fail due to rounding errors in the remainder. +// So, instead it is calculated as: a // b = (a - remainder(a, b)) / b +// With some additional fix-ups added to the result. +// +// For reference, see CPython's implementation: +// https://github.com/python/cpython/blob/ace008c531dd685a30c1dd68f9b5ba35f20171cf/Objects/floatobject.c#L636 + +template +inline C10_HOST_DEVICE scalar_t div_floor_floating(scalar_t a, scalar_t b) + __ubsan_ignore_float_divide_by_zero__ { + if (C10_UNLIKELY(b == 0)) { + // Divide by zero: return standard IEEE result + return a / b; + } + + auto mod = std::fmod(a, b); + auto div = (a - mod) / b; + if ((mod != 0) && (b < 0) != (mod < 0)) { + div -= scalar_t(1); + } + + scalar_t floordiv; + if (div != 0) { + floordiv = std::floor(div); + if (div - floordiv > scalar_t(0.5)) { + floordiv += scalar_t(1.0); + } + } else { + floordiv = C10_COMPAT_COPYSIGN(scalar_t(0), a / b); + } + return floordiv; +} + +template +inline C10_HOST_DEVICE scalar_t div_floor_integer(scalar_t a, scalar_t b) { + if (c10::signs_differ(a, b)) { + // Subtracts one from the results of truncation division if the + // divisor and dividend have different sign(bit)s and the remainder of + // the division is nonzero + const auto quot = a / b; + const auto rem = a % b; + return rem ? quot - 1 : quot; + } + return a / b; +} + +} // namespace c10 diff --git a/shared/package-files/3a/3ab62f5b41eee97eec3a1dfb154e7c80d9200bbeca56961c95ec2ffc04463001/dop853_coefficients.py b/shared/package-files/3a/3ab62f5b41eee97eec3a1dfb154e7c80d9200bbeca56961c95ec2ffc04463001/dop853_coefficients.py new file mode 100644 index 0000000000000000000000000000000000000000..f39f2f3650d321e2c475d4e220f9769139118a5e --- /dev/null +++ b/shared/package-files/3a/3ab62f5b41eee97eec3a1dfb154e7c80d9200bbeca56961c95ec2ffc04463001/dop853_coefficients.py @@ -0,0 +1,193 @@ +import numpy as np + +N_STAGES = 12 +N_STAGES_EXTENDED = 16 +INTERPOLATOR_POWER = 7 + +C = np.array([0.0, + 0.526001519587677318785587544488e-01, + 0.789002279381515978178381316732e-01, + 0.118350341907227396726757197510, + 0.281649658092772603273242802490, + 0.333333333333333333333333333333, + 0.25, + 0.307692307692307692307692307692, + 0.651282051282051282051282051282, + 0.6, + 0.857142857142857142857142857142, + 1.0, + 1.0, + 0.1, + 0.2, + 0.777777777777777777777777777778]) + +A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED)) +A[1, 0] = 5.26001519587677318785587544488e-2 + +A[2, 0] = 1.97250569845378994544595329183e-2 +A[2, 1] = 5.91751709536136983633785987549e-2 + +A[3, 0] = 2.95875854768068491816892993775e-2 +A[3, 2] = 8.87627564304205475450678981324e-2 + +A[4, 0] = 2.41365134159266685502369798665e-1 +A[4, 2] = -8.84549479328286085344864962717e-1 +A[4, 3] = 9.24834003261792003115737966543e-1 + +A[5, 0] = 3.7037037037037037037037037037e-2 +A[5, 3] = 1.70828608729473871279604482173e-1 +A[5, 4] = 1.25467687566822425016691814123e-1 + +A[6, 0] = 3.7109375e-2 +A[6, 3] = 1.70252211019544039314978060272e-1 +A[6, 4] = 6.02165389804559606850219397283e-2 +A[6, 5] = -1.7578125e-2 + +A[7, 0] = 3.70920001185047927108779319836e-2 +A[7, 3] = 1.70383925712239993810214054705e-1 +A[7, 4] = 1.07262030446373284651809199168e-1 +A[7, 5] = -1.53194377486244017527936158236e-2 +A[7, 6] = 8.27378916381402288758473766002e-3 + +A[8, 0] = 6.24110958716075717114429577812e-1 +A[8, 3] = -3.36089262944694129406857109825 +A[8, 4] = -8.68219346841726006818189891453e-1 +A[8, 5] = 2.75920996994467083049415600797e1 +A[8, 6] = 2.01540675504778934086186788979e1 +A[8, 7] = -4.34898841810699588477366255144e1 + +A[9, 0] = 4.77662536438264365890433908527e-1 +A[9, 3] = -2.48811461997166764192642586468 +A[9, 4] = -5.90290826836842996371446475743e-1 +A[9, 5] = 2.12300514481811942347288949897e1 +A[9, 6] = 1.52792336328824235832596922938e1 +A[9, 7] = -3.32882109689848629194453265587e1 +A[9, 8] = -2.03312017085086261358222928593e-2 + +A[10, 0] = -9.3714243008598732571704021658e-1 +A[10, 3] = 5.18637242884406370830023853209 +A[10, 4] = 1.09143734899672957818500254654 +A[10, 5] = -8.14978701074692612513997267357 +A[10, 6] = -1.85200656599969598641566180701e1 +A[10, 7] = 2.27394870993505042818970056734e1 +A[10, 8] = 2.49360555267965238987089396762 +A[10, 9] = -3.0467644718982195003823669022 + +A[11, 0] = 2.27331014751653820792359768449 +A[11, 3] = -1.05344954667372501984066689879e1 +A[11, 4] = -2.00087205822486249909675718444 +A[11, 5] = -1.79589318631187989172765950534e1 +A[11, 6] = 2.79488845294199600508499808837e1 +A[11, 7] = -2.85899827713502369474065508674 +A[11, 8] = -8.87285693353062954433549289258 +A[11, 9] = 1.23605671757943030647266201528e1 +A[11, 10] = 6.43392746015763530355970484046e-1 + +A[12, 0] = 5.42937341165687622380535766363e-2 +A[12, 5] = 4.45031289275240888144113950566 +A[12, 6] = 1.89151789931450038304281599044 +A[12, 7] = -5.8012039600105847814672114227 +A[12, 8] = 3.1116436695781989440891606237e-1 +A[12, 9] = -1.52160949662516078556178806805e-1 +A[12, 10] = 2.01365400804030348374776537501e-1 +A[12, 11] = 4.47106157277725905176885569043e-2 + +A[13, 0] = 5.61675022830479523392909219681e-2 +A[13, 6] = 2.53500210216624811088794765333e-1 +A[13, 7] = -2.46239037470802489917441475441e-1 +A[13, 8] = -1.24191423263816360469010140626e-1 +A[13, 9] = 1.5329179827876569731206322685e-1 +A[13, 10] = 8.20105229563468988491666602057e-3 +A[13, 11] = 7.56789766054569976138603589584e-3 +A[13, 12] = -8.298e-3 + +A[14, 0] = 3.18346481635021405060768473261e-2 +A[14, 5] = 2.83009096723667755288322961402e-2 +A[14, 6] = 5.35419883074385676223797384372e-2 +A[14, 7] = -5.49237485713909884646569340306e-2 +A[14, 10] = -1.08347328697249322858509316994e-4 +A[14, 11] = 3.82571090835658412954920192323e-4 +A[14, 12] = -3.40465008687404560802977114492e-4 +A[14, 13] = 1.41312443674632500278074618366e-1 + +A[15, 0] = -4.28896301583791923408573538692e-1 +A[15, 5] = -4.69762141536116384314449447206 +A[15, 6] = 7.68342119606259904184240953878 +A[15, 7] = 4.06898981839711007970213554331 +A[15, 8] = 3.56727187455281109270669543021e-1 +A[15, 12] = -1.39902416515901462129418009734e-3 +A[15, 13] = 2.9475147891527723389556272149 +A[15, 14] = -9.15095847217987001081870187138 + + +B = A[N_STAGES, :N_STAGES] + +E3 = np.zeros(N_STAGES + 1) +E3[:-1] = B.copy() +E3[0] -= 0.244094488188976377952755905512 +E3[8] -= 0.733846688281611857341361741547 +E3[11] -= 0.220588235294117647058823529412e-1 + +E5 = np.zeros(N_STAGES + 1) +E5[0] = 0.1312004499419488073250102996e-1 +E5[5] = -0.1225156446376204440720569753e+1 +E5[6] = -0.4957589496572501915214079952 +E5[7] = 0.1664377182454986536961530415e+1 +E5[8] = -0.3503288487499736816886487290 +E5[9] = 0.3341791187130174790297318841 +E5[10] = 0.8192320648511571246570742613e-1 +E5[11] = -0.2235530786388629525884427845e-1 + +# First 3 coefficients are computed separately. +D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED)) +D[0, 0] = -0.84289382761090128651353491142e+1 +D[0, 5] = 0.56671495351937776962531783590 +D[0, 6] = -0.30689499459498916912797304727e+1 +D[0, 7] = 0.23846676565120698287728149680e+1 +D[0, 8] = 0.21170345824450282767155149946e+1 +D[0, 9] = -0.87139158377797299206789907490 +D[0, 10] = 0.22404374302607882758541771650e+1 +D[0, 11] = 0.63157877876946881815570249290 +D[0, 12] = -0.88990336451333310820698117400e-1 +D[0, 13] = 0.18148505520854727256656404962e+2 +D[0, 14] = -0.91946323924783554000451984436e+1 +D[0, 15] = -0.44360363875948939664310572000e+1 + +D[1, 0] = 0.10427508642579134603413151009e+2 +D[1, 5] = 0.24228349177525818288430175319e+3 +D[1, 6] = 0.16520045171727028198505394887e+3 +D[1, 7] = -0.37454675472269020279518312152e+3 +D[1, 8] = -0.22113666853125306036270938578e+2 +D[1, 9] = 0.77334326684722638389603898808e+1 +D[1, 10] = -0.30674084731089398182061213626e+2 +D[1, 11] = -0.93321305264302278729567221706e+1 +D[1, 12] = 0.15697238121770843886131091075e+2 +D[1, 13] = -0.31139403219565177677282850411e+2 +D[1, 14] = -0.93529243588444783865713862664e+1 +D[1, 15] = 0.35816841486394083752465898540e+2 + +D[2, 0] = 0.19985053242002433820987653617e+2 +D[2, 5] = -0.38703730874935176555105901742e+3 +D[2, 6] = -0.18917813819516756882830838328e+3 +D[2, 7] = 0.52780815920542364900561016686e+3 +D[2, 8] = -0.11573902539959630126141871134e+2 +D[2, 9] = 0.68812326946963000169666922661e+1 +D[2, 10] = -0.10006050966910838403183860980e+1 +D[2, 11] = 0.77771377980534432092869265740 +D[2, 12] = -0.27782057523535084065932004339e+1 +D[2, 13] = -0.60196695231264120758267380846e+2 +D[2, 14] = 0.84320405506677161018159903784e+2 +D[2, 15] = 0.11992291136182789328035130030e+2 + +D[3, 0] = -0.25693933462703749003312586129e+2 +D[3, 5] = -0.15418974869023643374053993627e+3 +D[3, 6] = -0.23152937917604549567536039109e+3 +D[3, 7] = 0.35763911791061412378285349910e+3 +D[3, 8] = 0.93405324183624310003907691704e+2 +D[3, 9] = -0.37458323136451633156875139351e+2 +D[3, 10] = 0.10409964950896230045147246184e+3 +D[3, 11] = 0.29840293426660503123344363579e+2 +D[3, 12] = -0.43533456590011143754432175058e+2 +D[3, 13] = 0.96324553959188282948394950600e+2 +D[3, 14] = -0.39177261675615439165231486172e+2 +D[3, 15] = -0.14972683625798562581422125276e+3 diff --git a/shared/package-files/3a/3aba86dbf87f069f19fcc78bac0196191386f8cb529681aa79a27bf6a61b266d/base.py b/shared/package-files/3a/3aba86dbf87f069f19fcc78bac0196191386f8cb529681aa79a27bf6a61b266d/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a443597347283887deb9cbd3eafb5f6d3bb6d9a6 --- /dev/null +++ b/shared/package-files/3a/3aba86dbf87f069f19fcc78bac0196191386f8cb529681aa79a27bf6a61b266d/base.py @@ -0,0 +1,121 @@ +""" +Provide basic components for groupby. +""" +from __future__ import annotations + +import dataclasses +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Hashable + + +@dataclasses.dataclass(order=True, frozen=True) +class OutputKey: + label: Hashable + position: int + + +# special case to prevent duplicate plots when catching exceptions when +# forwarding methods from NDFrames +plotting_methods = frozenset(["plot", "hist"]) + +# cythonized transformations or canned "agg+broadcast", which do not +# require postprocessing of the result by transform. +cythonized_kernels = frozenset(["cumprod", "cumsum", "shift", "cummin", "cummax"]) + +# List of aggregation/reduction functions. +# These map each group to a single numeric value +reduction_kernels = frozenset( + [ + "all", + "any", + "corrwith", + "count", + "first", + "idxmax", + "idxmin", + "last", + "max", + "mean", + "median", + "min", + "nunique", + "prod", + # as long as `quantile`'s signature accepts only + # a single quantile value, it's a reduction. + # GH#27526 might change that. + "quantile", + "sem", + "size", + "skew", + "std", + "sum", + "var", + ] +) + +# List of transformation functions. +# a transformation is a function that, for each group, +# produces a result that has the same shape as the group. + + +transformation_kernels = frozenset( + [ + "bfill", + "cumcount", + "cummax", + "cummin", + "cumprod", + "cumsum", + "diff", + "ffill", + "fillna", + "ngroup", + "pct_change", + "rank", + "shift", + ] +) + +# these are all the public methods on Grouper which don't belong +# in either of the above lists +groupby_other_methods = frozenset( + [ + "agg", + "aggregate", + "apply", + "boxplot", + # corr and cov return ngroups*ncolumns rows, so they + # are neither a transformation nor a reduction + "corr", + "cov", + "describe", + "dtypes", + "expanding", + "ewm", + "filter", + "get_group", + "groups", + "head", + "hist", + "indices", + "ndim", + "ngroups", + "nth", + "ohlc", + "pipe", + "plot", + "resample", + "rolling", + "tail", + "take", + "transform", + "sample", + "value_counts", + ] +) +# Valid values of `name` for `groupby.transform(name)` +# NOTE: do NOT edit this directly. New additions should be inserted +# into the appropriate list above. +transform_kernel_allowlist = reduction_kernels | transformation_kernels diff --git a/shared/package-files/3a/3ac225402cdab034645f8d5f4b442bbf8a7269c81ccfffb5d7263d40dd1640df/_linalg_eigh.h b/shared/package-files/3a/3ac225402cdab034645f8d5f4b442bbf8a7269c81ccfffb5d7263d40dd1640df/_linalg_eigh.h new file mode 100644 index 0000000000000000000000000000000000000000..e478b690d98de2ea6570b81e0a01cd8b87c03e1a --- /dev/null +++ b/shared/package-files/3a/3ac225402cdab034645f8d5f4b442bbf8a7269c81ccfffb5d7263d40dd1640df/_linalg_eigh.h @@ -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_eigh(Tensor A, str UPLO="L", bool compute_v=True) -> (Tensor eigenvalues, Tensor eigenvectors) +inline ::std::tuple _linalg_eigh(const at::Tensor & A, c10::string_view UPLO="L", bool compute_v=true) { + return at::_ops::_linalg_eigh::call(A, UPLO, compute_v); +} + +// aten::_linalg_eigh.eigenvalues(Tensor A, str UPLO="L", bool compute_v=True, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) +inline ::std::tuple _linalg_eigh_out(at::Tensor & eigenvalues, at::Tensor & eigenvectors, const at::Tensor & A, c10::string_view UPLO="L", bool compute_v=true) { + return at::_ops::_linalg_eigh_eigenvalues::call(A, UPLO, compute_v, eigenvalues, eigenvectors); +} +// aten::_linalg_eigh.eigenvalues(Tensor A, str UPLO="L", bool compute_v=True, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) +inline ::std::tuple _linalg_eigh_outf(const at::Tensor & A, c10::string_view UPLO, bool compute_v, at::Tensor & eigenvalues, at::Tensor & eigenvectors) { + return at::_ops::_linalg_eigh_eigenvalues::call(A, UPLO, compute_v, eigenvalues, eigenvectors); +} + +} diff --git a/shared/package-files/3a/3acbaa2b5c6252712738b3cac1f9bd5fea574da5d13250c8923de5c066f68202/level_conversion.h b/shared/package-files/3a/3acbaa2b5c6252712738b3cac1f9bd5fea574da5d13250c8923de5c066f68202/level_conversion.h new file mode 100644 index 0000000000000000000000000000000000000000..31de95be41c473814c52cd9d2f5902d63f1b944b --- /dev/null +++ b/shared/package-files/3a/3acbaa2b5c6252712738b3cac1f9bd5fea574da5d13250c8923de5c066f68202/level_conversion.h @@ -0,0 +1,216 @@ +// 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/endian.h" +#include "parquet/platform.h" +#include "parquet/schema.h" + +namespace parquet::internal { + +struct PARQUET_EXPORT LevelInfo { + LevelInfo() + : null_slot_usage(1), def_level(0), rep_level(0), repeated_ancestor_def_level(0) {} + LevelInfo(int32_t null_slots, int32_t definition_level, int32_t repetition_level, + int32_t repeated_ancestor_definition_level) + : null_slot_usage(null_slots), + def_level(static_cast(definition_level)), + rep_level(static_cast(repetition_level)), + repeated_ancestor_def_level( + static_cast(repeated_ancestor_definition_level)) {} + + bool operator==(const LevelInfo& b) const { + return null_slot_usage == b.null_slot_usage && def_level == b.def_level && + rep_level == b.rep_level && + repeated_ancestor_def_level == b.repeated_ancestor_def_level; + } + + bool HasNullableValues() const { return repeated_ancestor_def_level < def_level; } + + // How many slots an undefined but present (i.e. null) element in + // parquet consumes when decoding to Arrow. + // "Slot" is used in the same context as the Arrow specification + // (i.e. a value holder). + // This is only ever >1 for descendents of FixedSizeList. + int32_t null_slot_usage = 1; + + // The definition level at which the value for the field + // is considered not null (definition levels greater than + // or equal to this value indicate a not-null + // value for the field). For list fields definition levels + // greater than or equal to this field indicate a present, + // possibly null, child value. + int16_t def_level = 0; + + // The repetition level corresponding to this element + // or the closest repeated ancestor. Any repetition + // level less than this indicates either a new list OR + // an empty list (which is determined in conjunction + // with definition levels). + int16_t rep_level = 0; + + // The definition level indicating the level at which the closest + // repeated ancestor is not empty. This is used to discriminate + // between a value less than |def_level| being null or excluded entirely. + // For instance if we have an arrow schema like: + // list(struct(f0: int)). Then then there are the following + // definition levels: + // 0 = null list + // 1 = present but empty list. + // 2 = a null value in the list + // 3 = a non null struct but null integer. + // 4 = a present integer. + // When reconstructing, the struct and integer arrays' + // repeated_ancestor_def_level would be 2. Any + // def_level < 2 indicates that there isn't a corresponding + // child value in the list. + // i.e. [null, [], [null], [{f0: null}], [{f0: 1}]] + // has the def levels [0, 1, 2, 3, 4]. The actual + // struct array is only of length 3: [not-set, set, set] and + // the int array is also of length 3: [N/A, null, 1]. + // + int16_t repeated_ancestor_def_level = 0; + + /// Increments levels according to the cardinality of node. + void Increment(const schema::Node& node) { + if (node.is_repeated()) { + IncrementRepeated(); + return; + } + if (node.is_optional()) { + IncrementOptional(); + return; + } + } + + /// Increments level for a optional node. + void IncrementOptional() { def_level++; } + + /// Increments levels for the repeated node. Returns + /// the previous ancestor_list_def_level. + int16_t IncrementRepeated() { + int16_t last_repeated_ancestor = repeated_ancestor_def_level; + + // Repeated fields add both a repetition and definition level. This is used + // to distinguish between an empty list and a list with an item in it. + ++rep_level; + ++def_level; + // For levels >= repeated_ancestor_def_level it indicates the list was + // non-null and had at least one element. This is important + // for later decoding because we need to add a slot for these + // values. for levels < current_def_level no slots are added + // to arrays. + repeated_ancestor_def_level = def_level; + return last_repeated_ancestor; + } + + // Calculates and returns LevelInfo for a column descriptor. + static LevelInfo ComputeLevelInfo(const ColumnDescriptor* descr) { + LevelInfo level_info; + level_info.def_level = descr->max_definition_level(); + level_info.rep_level = descr->max_repetition_level(); + + int16_t min_spaced_def_level = descr->max_definition_level(); + const ::parquet::schema::Node* node = descr->schema_node().get(); + while (node && !node->is_repeated()) { + if (node->is_optional()) { + min_spaced_def_level--; + } + node = node->parent(); + } + level_info.repeated_ancestor_def_level = min_spaced_def_level; + return level_info; + } + + friend std::ostream& operator<<(std::ostream& os, const LevelInfo& levels) { + // This print method is to silence valgrind issues. What's printed + // is not important because all asserts happen directly on + // members. + os << "{def=" << levels.def_level << ", rep=" << levels.rep_level + << ", repeated_ancestor_def=" << levels.repeated_ancestor_def_level; + if (levels.null_slot_usage > 1) { + os << ", null_slot_usage=" << levels.null_slot_usage; + } + os << "}"; + return os; + } +}; + +// Input/Output structure for reconstructed validity bitmaps. +struct PARQUET_EXPORT ValidityBitmapInputOutput { + // Input only. + // The maximum number of values_read expected (actual + // values read must be less than or equal to this value). + // If this number is exceeded methods will throw a + // ParquetException. Exceeding this limit indicates + // either a corrupt or incorrectly written file. + int64_t values_read_upper_bound = 0; + // Output only. The number of values added to the encountered + // (this is logically the count of the number of elements + // for an Arrow array). + int64_t values_read = 0; + // Input/Output. The number of nulls encountered. + int64_t null_count = 0; + // Output only. The validity bitmap to populate. Maybe be null only + // for DefRepLevelsToListInfo (if all that is needed is list offsets). + uint8_t* valid_bits = NULLPTR; + // Input only, offset into valid_bits to start at. + int64_t valid_bits_offset = 0; +}; + +// Converts def_levels to validity bitmaps for non-list arrays and structs that have +// at least one member that is not a list and has no list descendents. +// For lists use DefRepLevelsToList and structs where all descendants contain +// a list use DefRepLevelsToBitmap. +void PARQUET_EXPORT DefLevelsToBitmap(const int16_t* def_levels, int64_t num_def_levels, + LevelInfo level_info, + ValidityBitmapInputOutput* output); + +// Reconstructs a validity bitmap and list offsets for a list arrays based on +// def/rep levels. The first element of offsets will not be modified if rep_levels +// starts with a new list. The first element of offsets will be used when calculating +// the next offset. See documentation onf DefLevelsToBitmap for when to use this +// method vs the other ones in this file for reconstruction. +// +// Offsets must be sized to 1 + values_read_upper_bound. +void PARQUET_EXPORT DefRepLevelsToList(const int16_t* def_levels, + const int16_t* rep_levels, int64_t num_def_levels, + LevelInfo level_info, + ValidityBitmapInputOutput* output, + int32_t* offsets); +void PARQUET_EXPORT DefRepLevelsToList(const int16_t* def_levels, + const int16_t* rep_levels, int64_t num_def_levels, + LevelInfo level_info, + ValidityBitmapInputOutput* output, + int64_t* offsets); + +// Reconstructs a validity bitmap for a struct every member is a list or has +// a list descendant. See documentation on DefLevelsToBitmap for when more +// details on this method compared to the other ones defined above. +void PARQUET_EXPORT DefRepLevelsToBitmap(const int16_t* def_levels, + const int16_t* rep_levels, + int64_t num_def_levels, LevelInfo level_info, + ValidityBitmapInputOutput* output); + +// This is exposed to ensure we can properly test a software simulated pext function +// (i.e. it isn't hidden by runtime dispatch). +uint64_t PARQUET_EXPORT TestOnlyExtractBitsSoftware(uint64_t bitmap, uint64_t selection); + +} // namespace parquet::internal diff --git a/shared/package-files/3a/3acd408e03e2b5ca8c3ed35ef42c1eed8a23b9d1198e0bab01a19a67820a97e3/summary.py b/shared/package-files/3a/3acd408e03e2b5ca8c3ed35ef42c1eed8a23b9d1198e0bab01a19a67820a97e3/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..8211f6e0c80241bebacd19ea5824c5b338018849 --- /dev/null +++ b/shared/package-files/3a/3acd408e03e2b5ca8c3ed35ef42c1eed8a23b9d1198e0bab01a19a67820a97e3/summary.py @@ -0,0 +1,983 @@ +import json +import logging +import os +import struct + +from typing import Any, List, Optional + +import torch +import numpy as np + +from google.protobuf import struct_pb2 + +from tensorboard.compat.proto.summary_pb2 import ( + HistogramProto, + Summary, + SummaryMetadata, +) +from tensorboard.compat.proto.tensor_pb2 import TensorProto +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto +from tensorboard.plugins.custom_scalar import layout_pb2 +from tensorboard.plugins.pr_curve.plugin_data_pb2 import PrCurvePluginData +from tensorboard.plugins.text.plugin_data_pb2 import TextPluginData + +from ._convert_np import make_np +from ._utils import _prepare_video, convert_to_HWC + +__all__ = [ + "half_to_int", + "int_to_half", + "hparams", + "scalar", + "histogram_raw", + "histogram", + "make_histogram", + "image", + "image_boxes", + "draw_boxes", + "make_image", + "video", + "make_video", + "audio", + "custom_scalars", + "text", + "tensor_proto", + "pr_curve_raw", + "pr_curve", + "compute_curve", + "mesh", +] + +logger = logging.getLogger(__name__) + +def half_to_int(f: float) -> int: + """Casts a half-precision float value into an integer. + + Converts a half precision floating point value, such as `torch.half` or + `torch.bfloat16`, into an integer value which can be written into the + half_val field of a TensorProto for storage. + + To undo the effects of this conversion, use int_to_half(). + + """ + buf = struct.pack("f", f) + return struct.unpack("i", buf)[0] + +def int_to_half(i: int) -> float: + """Casts an integer value to a half-precision float. + + Converts an integer value obtained from half_to_int back into a floating + point value. + + """ + buf = struct.pack("i", i) + return struct.unpack("f", buf)[0] + +def _tensor_to_half_val(t: torch.Tensor) -> List[int]: + return [half_to_int(x) for x in t.flatten().tolist()] + +def _tensor_to_complex_val(t: torch.Tensor) -> List[float]: + return torch.view_as_real(t).flatten().tolist() + +def _tensor_to_list(t: torch.Tensor) -> List[Any]: + return t.flatten().tolist() + +# type maps: torch.Tensor type -> (protobuf type, protobuf val field) +_TENSOR_TYPE_MAP = { + torch.half: ("DT_HALF", "half_val", _tensor_to_half_val), + torch.float16: ("DT_HALF", "half_val", _tensor_to_half_val), + torch.bfloat16: ("DT_BFLOAT16", "half_val", _tensor_to_half_val), + torch.float32: ("DT_FLOAT", "float_val", _tensor_to_list), + torch.float: ("DT_FLOAT", "float_val", _tensor_to_list), + torch.float64: ("DT_DOUBLE", "double_val", _tensor_to_list), + torch.double: ("DT_DOUBLE", "double_val", _tensor_to_list), + torch.int8: ("DT_INT8", "int_val", _tensor_to_list), + torch.uint8: ("DT_UINT8", "int_val", _tensor_to_list), + torch.qint8: ("DT_UINT8", "int_val", _tensor_to_list), + torch.int16: ("DT_INT16", "int_val", _tensor_to_list), + torch.short: ("DT_INT16", "int_val", _tensor_to_list), + torch.int: ("DT_INT32", "int_val", _tensor_to_list), + torch.int32: ("DT_INT32", "int_val", _tensor_to_list), + torch.qint32: ("DT_INT32", "int_val", _tensor_to_list), + torch.int64: ("DT_INT64", "int64_val", _tensor_to_list), + torch.complex32: ("DT_COMPLEX32", "scomplex_val", _tensor_to_complex_val), + torch.chalf: ("DT_COMPLEX32", "scomplex_val", _tensor_to_complex_val), + torch.complex64: ("DT_COMPLEX64", "scomplex_val", _tensor_to_complex_val), + torch.cfloat: ("DT_COMPLEX64", "scomplex_val", _tensor_to_complex_val), + torch.bool: ("DT_BOOL", "bool_val", _tensor_to_list), + torch.complex128: ("DT_COMPLEX128", "dcomplex_val", _tensor_to_complex_val), + torch.cdouble: ("DT_COMPLEX128", "dcomplex_val", _tensor_to_complex_val), + torch.uint8: ("DT_UINT8", "uint32_val", _tensor_to_list), + torch.quint8: ("DT_UINT8", "uint32_val", _tensor_to_list), + torch.quint4x2: ("DT_UINT8", "uint32_val", _tensor_to_list), +} + + +def _calc_scale_factor(tensor): + converted = tensor.numpy() if not isinstance(tensor, np.ndarray) else tensor + return 1 if converted.dtype == np.uint8 else 255 + + +def _draw_single_box( + image, + xmin, + ymin, + xmax, + ymax, + display_str, + color="black", + color_text="black", + thickness=2, +): + from PIL import ImageDraw, ImageFont + + font = ImageFont.load_default() + draw = ImageDraw.Draw(image) + (left, right, top, bottom) = (xmin, xmax, ymin, ymax) + draw.line( + [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], + width=thickness, + fill=color, + ) + if display_str: + text_bottom = bottom + # Reverse list and print from bottom to top. + text_width, text_height = font.getsize(display_str) + margin = np.ceil(0.05 * text_height) + draw.rectangle( + [ + (left, text_bottom - text_height - 2 * margin), + (left + text_width, text_bottom), + ], + fill=color, + ) + draw.text( + (left + margin, text_bottom - text_height - margin), + display_str, + fill=color_text, + font=font, + ) + return image + + +def hparams(hparam_dict=None, metric_dict=None, hparam_domain_discrete=None): + """Output three `Summary` protocol buffers needed by hparams plugin. + + `Experiment` keeps the metadata of an experiment, such as the name of the + hyperparameters and the name of the metrics. + `SessionStartInfo` keeps key-value pairs of the hyperparameters + `SessionEndInfo` describes status of the experiment e.g. STATUS_SUCCESS + + Args: + hparam_dict: A dictionary that contains names of the hyperparameters + and their values. + metric_dict: A dictionary that contains names of the metrics + and their values. + hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that + contains names of the hyperparameters and all discrete values they can hold + + Returns: + The `Summary` protobufs for Experiment, SessionStartInfo and + SessionEndInfo + """ + import torch + from tensorboard.plugins.hparams.api_pb2 import ( + DataType, + Experiment, + HParamInfo, + MetricInfo, + MetricName, + Status, + ) + from tensorboard.plugins.hparams.metadata import ( + EXPERIMENT_TAG, + PLUGIN_DATA_VERSION, + PLUGIN_NAME, + SESSION_END_INFO_TAG, + SESSION_START_INFO_TAG, + ) + from tensorboard.plugins.hparams.plugin_data_pb2 import ( + HParamsPluginData, + SessionEndInfo, + SessionStartInfo, + ) + + # TODO: expose other parameters in the future. + # hp = HParamInfo(name='lr',display_name='learning rate', + # type=DataType.DATA_TYPE_FLOAT64, domain_interval=Interval(min_value=10, + # max_value=100)) + # mt = MetricInfo(name=MetricName(tag='accuracy'), display_name='accuracy', + # description='', dataset_type=DatasetType.DATASET_VALIDATION) + # exp = Experiment(name='123', description='456', time_created_secs=100.0, + # hparam_infos=[hp], metric_infos=[mt], user='tw') + + if not isinstance(hparam_dict, dict): + logger.warning("parameter: hparam_dict should be a dictionary, nothing logged.") + raise TypeError( + "parameter: hparam_dict should be a dictionary, nothing logged." + ) + if not isinstance(metric_dict, dict): + logger.warning("parameter: metric_dict should be a dictionary, nothing logged.") + raise TypeError( + "parameter: metric_dict should be a dictionary, nothing logged." + ) + + hparam_domain_discrete = hparam_domain_discrete or {} + if not isinstance(hparam_domain_discrete, dict): + raise TypeError( + "parameter: hparam_domain_discrete should be a dictionary, nothing logged." + ) + for k, v in hparam_domain_discrete.items(): + if ( + k not in hparam_dict + or not isinstance(v, list) + or not all(isinstance(d, type(hparam_dict[k])) for d in v) + ): + raise TypeError( + f"parameter: hparam_domain_discrete[{k}] should be a list of same type as hparam_dict[{k}]." + ) + hps = [] + + ssi = SessionStartInfo() + for k, v in hparam_dict.items(): + if v is None: + continue + if isinstance(v, (int, float)): + ssi.hparams[k].number_value = v + + if k in hparam_domain_discrete: + domain_discrete: Optional[struct_pb2.ListValue] = struct_pb2.ListValue( + values=[ + struct_pb2.Value(number_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_FLOAT64"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, str): + ssi.hparams[k].string_value = v + + if k in hparam_domain_discrete: + domain_discrete = struct_pb2.ListValue( + values=[ + struct_pb2.Value(string_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_STRING"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, bool): + ssi.hparams[k].bool_value = v + + if k in hparam_domain_discrete: + domain_discrete = struct_pb2.ListValue( + values=[ + struct_pb2.Value(bool_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_BOOL"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, torch.Tensor): + v = make_np(v)[0] + ssi.hparams[k].number_value = v + hps.append(HParamInfo(name=k, type=DataType.Value("DATA_TYPE_FLOAT64"))) + continue + raise ValueError( + "value should be one of int, float, str, bool, or torch.Tensor" + ) + + content = HParamsPluginData(session_start_info=ssi, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + ssi = Summary(value=[Summary.Value(tag=SESSION_START_INFO_TAG, metadata=smd)]) + + mts = [MetricInfo(name=MetricName(tag=k)) for k in metric_dict.keys()] + + exp = Experiment(hparam_infos=hps, metric_infos=mts) + + content = HParamsPluginData(experiment=exp, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + exp = Summary(value=[Summary.Value(tag=EXPERIMENT_TAG, metadata=smd)]) + + sei = SessionEndInfo(status=Status.Value("STATUS_SUCCESS")) + content = HParamsPluginData(session_end_info=sei, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + sei = Summary(value=[Summary.Value(tag=SESSION_END_INFO_TAG, metadata=smd)]) + + return exp, ssi, sei + + +def scalar(name, tensor, collections=None, new_style=False, double_precision=False): + """Output a `Summary` protocol buffer containing a single scalar value. + + The generated Summary has a Tensor.proto containing the input Tensor. + Args: + name: A name for the generated node. Will also serve as the series name in + TensorBoard. + tensor: A real numeric Tensor containing a single value. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + new_style: Whether to use new style (tensor field) or old style (simple_value + field). New style could lead to faster data loading. + Returns: + A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf. + Raises: + ValueError: If tensor has the wrong shape or type. + """ + tensor = make_np(tensor).squeeze() + assert ( + tensor.ndim == 0 + ), f"Tensor should contain one element (0 dimensions). Was given size: {tensor.size} and {tensor.ndim} dimensions." + # python float is double precision in numpy + scalar = float(tensor) + if new_style: + tensor_proto = TensorProto(float_val=[scalar], dtype="DT_FLOAT") + if double_precision: + tensor_proto = TensorProto(double_val=[scalar], dtype="DT_DOUBLE") + + plugin_data = SummaryMetadata.PluginData(plugin_name="scalars") + smd = SummaryMetadata(plugin_data=plugin_data) + return Summary( + value=[ + Summary.Value( + tag=name, + tensor=tensor_proto, + metadata=smd, + ) + ] + ) + else: + return Summary(value=[Summary.Value(tag=name, simple_value=scalar)]) + + +def tensor_proto(tag, tensor): + """Outputs a `Summary` protocol buffer containing the full tensor. + The generated Summary has a Tensor.proto containing the input Tensor. + Args: + name: A name for the generated node. Will also serve as the series name in + TensorBoard. + tensor: Tensor to be converted to protobuf + Returns: + A tensor protobuf in a `Summary` protobuf. + Raises: + ValueError: If tensor is too big to be converted to protobuf, or + tensor data type is not supported + """ + if tensor.numel() * tensor.itemsize >= (1 << 31): + raise ValueError( + "tensor is bigger than protocol buffer's hard limit of 2GB in size" + ) + + if tensor.dtype in _TENSOR_TYPE_MAP: + dtype, field_name, conversion_fn = _TENSOR_TYPE_MAP[tensor.dtype] + tensor_proto = TensorProto( + **{ + "dtype": dtype, + "tensor_shape": TensorShapeProto( + dim=[TensorShapeProto.Dim(size=x) for x in tensor.shape] + ), + field_name: conversion_fn(tensor), + }, + ) + else: + raise ValueError(f"{tag} has unsupported tensor dtype {tensor.dtype}") + + plugin_data = SummaryMetadata.PluginData(plugin_name="tensor") + smd = SummaryMetadata(plugin_data=plugin_data) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor_proto)]) + + +def histogram_raw(name, min, max, num, sum, sum_squares, bucket_limits, bucket_counts): + # pylint: disable=line-too-long + """Output a `Summary` protocol buffer with a histogram. + + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + min: A float or int min value + max: A float or int max value + num: Int number of values + sum: Float or int sum of all values + sum_squares: Float or int sum of squares for all values + bucket_limits: A numeric `Tensor` with upper value per bucket + bucket_counts: A numeric `Tensor` with number of values per bucket + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + hist = HistogramProto( + min=min, + max=max, + num=num, + sum=sum, + sum_squares=sum_squares, + bucket_limit=bucket_limits, + bucket=bucket_counts, + ) + return Summary(value=[Summary.Value(tag=name, histo=hist)]) + + +def histogram(name, values, bins, max_bins=None): + # pylint: disable=line-too-long + """Output a `Summary` protocol buffer with a histogram. + + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + This op reports an `InvalidArgument` error if any value is not finite. + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + values: A real numeric `Tensor`. Any shape. Values to use to + build the histogram. + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + values = make_np(values) + hist = make_histogram(values.astype(float), bins, max_bins) + return Summary(value=[Summary.Value(tag=name, histo=hist)]) + + +def make_histogram(values, bins, max_bins=None): + """Convert values into a histogram proto using logic from histogram.cc.""" + if values.size == 0: + raise ValueError("The input has no element.") + values = values.reshape(-1) + counts, limits = np.histogram(values, bins=bins) + num_bins = len(counts) + if max_bins is not None and num_bins > max_bins: + subsampling = num_bins // max_bins + subsampling_remainder = num_bins % subsampling + if subsampling_remainder != 0: + counts = np.pad( + counts, + pad_width=[[0, subsampling - subsampling_remainder]], + mode="constant", + constant_values=0, + ) + counts = counts.reshape(-1, subsampling).sum(axis=-1) + new_limits = np.empty((counts.size + 1,), limits.dtype) + new_limits[:-1] = limits[:-1:subsampling] + new_limits[-1] = limits[-1] + limits = new_limits + + # Find the first and the last bin defining the support of the histogram: + + cum_counts = np.cumsum(np.greater(counts, 0)) + start, end = np.searchsorted(cum_counts, [0, cum_counts[-1] - 1], side="right") + start = int(start) + end = int(end) + 1 + del cum_counts + + # TensorBoard only includes the right bin limits. To still have the leftmost limit + # included, we include an empty bin left. + # If start == 0, we need to add an empty one left, otherwise we can just include the bin left to the + # first nonzero-count bin: + counts = ( + counts[start - 1 : end] if start > 0 else np.concatenate([[0], counts[:end]]) + ) + limits = limits[start : end + 1] + + if counts.size == 0 or limits.size == 0: + raise ValueError("The histogram is empty, please file a bug report.") + + sum_sq = values.dot(values) + return HistogramProto( + min=values.min(), + max=values.max(), + num=len(values), + sum=values.sum(), + sum_squares=sum_sq, + bucket_limit=limits.tolist(), + bucket=counts.tolist(), + ) + + +def image(tag, tensor, rescale=1, dataformats="NCHW"): + """Output a `Summary` protocol buffer with images. + + The summary has up to `max_images` summary values containing images. The + images are built from `tensor` which must be 3-D with shape `[height, width, + channels]` and where `channels` can be: + * 1: `tensor` is interpreted as Grayscale. + * 3: `tensor` is interpreted as RGB. + * 4: `tensor` is interpreted as RGBA. + The `name` in the outputted Summary.Value protobufs is generated based on the + name, with a suffix depending on the max_outputs setting: + * If `max_outputs` is 1, the summary value tag is '*name*/image'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*name*/image/0', '*name*/image/1', etc. + Args: + tag: A name for the generated node. Will also serve as a series name in + TensorBoard. + tensor: A 3-D `uint8` or `float32` `Tensor` of shape `[height, width, + channels]` where `channels` is 1, 3, or 4. + 'tensor' can either have values in [0, 1] (float32) or [0, 255] (uint8). + The image() function will scale the image values to [0, 255] by applying + a scale factor of either 1 (uint8) or 255 (float32). Out-of-range values + will be clipped. + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + tensor = make_np(tensor) + tensor = convert_to_HWC(tensor, dataformats) + # Do not assume that user passes in values in [0, 255], use data type to detect + scale_factor = _calc_scale_factor(tensor) + tensor = tensor.astype(np.float32) + tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8) + image = make_image(tensor, rescale=rescale) + return Summary(value=[Summary.Value(tag=tag, image=image)]) + + +def image_boxes( + tag, tensor_image, tensor_boxes, rescale=1, dataformats="CHW", labels=None +): + """Output a `Summary` protocol buffer with images.""" + tensor_image = make_np(tensor_image) + tensor_image = convert_to_HWC(tensor_image, dataformats) + tensor_boxes = make_np(tensor_boxes) + tensor_image = tensor_image.astype(np.float32) * _calc_scale_factor(tensor_image) + image = make_image( + tensor_image.clip(0, 255).astype(np.uint8), + rescale=rescale, + rois=tensor_boxes, + labels=labels, + ) + return Summary(value=[Summary.Value(tag=tag, image=image)]) + + +def draw_boxes(disp_image, boxes, labels=None): + # xyxy format + num_boxes = boxes.shape[0] + list_gt = range(num_boxes) + for i in list_gt: + disp_image = _draw_single_box( + disp_image, + boxes[i, 0], + boxes[i, 1], + boxes[i, 2], + boxes[i, 3], + display_str=None if labels is None else labels[i], + color="Red", + ) + return disp_image + + +def make_image(tensor, rescale=1, rois=None, labels=None): + """Convert a numpy representation of an image to Image protobuf.""" + from PIL import Image + + height, width, channel = tensor.shape + scaled_height = int(height * rescale) + scaled_width = int(width * rescale) + image = Image.fromarray(tensor) + if rois is not None: + image = draw_boxes(image, rois, labels=labels) + try: + ANTIALIAS = Image.Resampling.LANCZOS + except AttributeError: + ANTIALIAS = Image.ANTIALIAS + image = image.resize((scaled_width, scaled_height), ANTIALIAS) + import io + + output = io.BytesIO() + image.save(output, format="PNG") + image_string = output.getvalue() + output.close() + return Summary.Image( + height=height, + width=width, + colorspace=channel, + encoded_image_string=image_string, + ) + + +def video(tag, tensor, fps=4): + tensor = make_np(tensor) + tensor = _prepare_video(tensor) + # If user passes in uint8, then we don't need to rescale by 255 + scale_factor = _calc_scale_factor(tensor) + tensor = tensor.astype(np.float32) + tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8) + video = make_video(tensor, fps) + return Summary(value=[Summary.Value(tag=tag, image=video)]) + + +def make_video(tensor, fps): + try: + import moviepy # noqa: F401 + except ImportError: + print("add_video needs package moviepy") + return + try: + from moviepy import editor as mpy + except ImportError: + print( + "moviepy is installed, but can't import moviepy.editor.", + "Some packages could be missing [imageio, requests]", + ) + return + import tempfile + + t, h, w, c = tensor.shape + + # encode sequence of images into gif string + clip = mpy.ImageSequenceClip(list(tensor), fps=fps) + + filename = tempfile.NamedTemporaryFile(suffix=".gif", delete=False).name + try: # newer version of moviepy use logger instead of progress_bar argument. + clip.write_gif(filename, verbose=False, logger=None) + except TypeError: + try: # older version of moviepy does not support progress_bar argument. + clip.write_gif(filename, verbose=False, progress_bar=False) + except TypeError: + clip.write_gif(filename, verbose=False) + + with open(filename, "rb") as f: + tensor_string = f.read() + + try: + os.remove(filename) + except OSError: + logger.warning("The temporary file used by moviepy cannot be deleted.") + + return Summary.Image( + height=h, width=w, colorspace=c, encoded_image_string=tensor_string + ) + + +def audio(tag, tensor, sample_rate=44100): + array = make_np(tensor) + array = array.squeeze() + if abs(array).max() > 1: + print("warning: audio amplitude out of range, auto clipped.") + array = array.clip(-1, 1) + assert array.ndim == 1, "input tensor should be 1 dimensional." + array = (array * np.iinfo(np.int16).max).astype(" 127: # weird, value > 127 breaks protobuf + num_thresholds = 127 + data = np.stack((tp, fp, tn, fn, precision, recall)) + pr_curve_plugin_data = PrCurvePluginData( + version=0, num_thresholds=num_thresholds + ).SerializeToString() + plugin_data = SummaryMetadata.PluginData( + plugin_name="pr_curves", content=pr_curve_plugin_data + ) + smd = SummaryMetadata(plugin_data=plugin_data) + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=data.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=data.shape[0]), + TensorShapeProto.Dim(size=data.shape[1]), + ] + ), + ) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) + + +def pr_curve(tag, labels, predictions, num_thresholds=127, weights=None): + # weird, value > 127 breaks protobuf + num_thresholds = min(num_thresholds, 127) + data = compute_curve( + labels, predictions, num_thresholds=num_thresholds, weights=weights + ) + pr_curve_plugin_data = PrCurvePluginData( + version=0, num_thresholds=num_thresholds + ).SerializeToString() + plugin_data = SummaryMetadata.PluginData( + plugin_name="pr_curves", content=pr_curve_plugin_data + ) + smd = SummaryMetadata(plugin_data=plugin_data) + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=data.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=data.shape[0]), + TensorShapeProto.Dim(size=data.shape[1]), + ] + ), + ) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) + + +# https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/summary.py +def compute_curve(labels, predictions, num_thresholds=None, weights=None): + _MINIMUM_COUNT = 1e-7 + + if weights is None: + weights = 1.0 + + # Compute bins of true positives and false positives. + bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1))) + float_labels = labels.astype(np.float64) + histogram_range = (0, num_thresholds - 1) + tp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=float_labels * weights, + ) + fp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=(1.0 - float_labels) * weights, + ) + + # Obtain the reverse cumulative sum. + tp = np.cumsum(tp_buckets[::-1])[::-1] + fp = np.cumsum(fp_buckets[::-1])[::-1] + tn = fp[0] - fp + fn = tp[0] - tp + precision = tp / np.maximum(_MINIMUM_COUNT, tp + fp) + recall = tp / np.maximum(_MINIMUM_COUNT, tp + fn) + return np.stack((tp, fp, tn, fn, precision, recall)) + + +def _get_tensor_summary( + name, display_name, description, tensor, content_type, components, json_config +): + """Create a tensor summary with summary metadata. + + Args: + name: Uniquely identifiable name of the summary op. Could be replaced by + combination of name and type to make it unique even outside of this + summary. + display_name: Will be used as the display name in TensorBoard. + Defaults to `name`. + description: A longform readable description of the summary data. Markdown + is supported. + tensor: Tensor to display in summary. + content_type: Type of content inside the Tensor. + components: Bitmask representing present parts (vertices, colors, etc.) that + belong to the summary. + json_config: A string, JSON-serialized dictionary of ThreeJS classes + configuration. + + Returns: + Tensor summary with metadata. + """ + import torch + from tensorboard.plugins.mesh import metadata + + tensor = torch.as_tensor(tensor) + + tensor_metadata = metadata.create_summary_metadata( + name, + display_name, + content_type, + components, + tensor.shape, + description, + json_config=json_config, + ) + + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=tensor.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=tensor.shape[0]), + TensorShapeProto.Dim(size=tensor.shape[1]), + TensorShapeProto.Dim(size=tensor.shape[2]), + ] + ), + ) + + tensor_summary = Summary.Value( + tag=metadata.get_instance_name(name, content_type), + tensor=tensor, + metadata=tensor_metadata, + ) + + return tensor_summary + + +def _get_json_config(config_dict): + """Parse and returns JSON string from python dictionary.""" + json_config = "{}" + if config_dict is not None: + json_config = json.dumps(config_dict, sort_keys=True) + return json_config + + +# https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/mesh/summary.py +def mesh( + tag, vertices, colors, faces, config_dict, display_name=None, description=None +): + """Output a merged `Summary` protocol buffer with a mesh/point cloud. + + Args: + tag: A name for this summary operation. + vertices: Tensor of shape `[dim_1, ..., dim_n, 3]` representing the 3D + coordinates of vertices. + faces: Tensor of shape `[dim_1, ..., dim_n, 3]` containing indices of + vertices within each triangle. + colors: Tensor of shape `[dim_1, ..., dim_n, 3]` containing colors for each + vertex. + display_name: If set, will be used as the display name in TensorBoard. + Defaults to `name`. + description: A longform readable description of the summary data. Markdown + is supported. + config_dict: Dictionary with ThreeJS classes names and configuration. + + Returns: + Merged summary for mesh/point cloud representation. + """ + from tensorboard.plugins.mesh import metadata + from tensorboard.plugins.mesh.plugin_data_pb2 import MeshPluginData + + json_config = _get_json_config(config_dict) + + summaries = [] + tensors = [ + (vertices, MeshPluginData.VERTEX), + (faces, MeshPluginData.FACE), + (colors, MeshPluginData.COLOR), + ] + tensors = [tensor for tensor in tensors if tensor[0] is not None] + components = metadata.get_components_bitmask( + [content_type for (tensor, content_type) in tensors] + ) + + for tensor, content_type in tensors: + summaries.append( + _get_tensor_summary( + tag, + display_name, + description, + tensor, + content_type, + components, + json_config, + ) + ) + + return Summary(value=summaries) diff --git a/shared/package-files/3a/3aceaa5661909de14e2861d864443b8472460ce39b99cce5c6965346d47aa5ac/iso2022_jp_3.py b/shared/package-files/3a/3aceaa5661909de14e2861d864443b8472460ce39b99cce5c6965346d47aa5ac/iso2022_jp_3.py new file mode 100644 index 0000000000000000000000000000000000000000..346e08beccbbafd347371743ec89333370d3b083 --- /dev/null +++ b/shared/package-files/3a/3aceaa5661909de14e2861d864443b8472460ce39b99cce5c6965346d47aa5ac/iso2022_jp_3.py @@ -0,0 +1,39 @@ +# +# iso2022_jp_3.py: Python Unicode Codec for ISO2022_JP_3 +# +# Written by Hye-Shik Chang +# + +import _codecs_iso2022, codecs +import _multibytecodec as mbc + +codec = _codecs_iso2022.getcodec('iso2022_jp_3') + +class Codec(codecs.Codec): + encode = codec.encode + decode = codec.decode + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, + codecs.IncrementalEncoder): + codec = codec + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, + codecs.IncrementalDecoder): + codec = codec + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): + codec = codec + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec = codec + +def getregentry(): + return codecs.CodecInfo( + name='iso2022_jp_3', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) diff --git a/shared/package-files/3a/3acf3609195eb7f56eadb7b50a3bab7e6d1626a60cc6c2e59dad69ffc7ff2e04/svd.h b/shared/package-files/3a/3acf3609195eb7f56eadb7b50a3bab7e6d1626a60cc6c2e59dad69ffc7ff2e04/svd.h new file mode 100644 index 0000000000000000000000000000000000000000..ae1689e723d4f200c78528aa33ab732434ed7bef --- /dev/null +++ b/shared/package-files/3a/3acf3609195eb7f56eadb7b50a3bab7e6d1626a60cc6c2e59dad69ffc7ff2e04/svd.h @@ -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::svd.U(Tensor self, bool some=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) +inline ::std::tuple svd_out(at::Tensor & U, at::Tensor & S, at::Tensor & V, const at::Tensor & self, bool some=true, bool compute_uv=true) { + return at::_ops::svd_U::call(self, some, compute_uv, U, S, V); +} +// aten::svd.U(Tensor self, bool some=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) +inline ::std::tuple svd_outf(const at::Tensor & self, bool some, bool compute_uv, at::Tensor & U, at::Tensor & S, at::Tensor & V) { + return at::_ops::svd_U::call(self, some, compute_uv, U, S, V); +} + +// aten::svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V) +inline ::std::tuple svd(const at::Tensor & self, bool some=true, bool compute_uv=true) { + return at::_ops::svd::call(self, some, compute_uv); +} + +} diff --git a/shared/package-files/3a/3ad18bca384d6357ef916d46bcb27f155f59a2a0bd027ca3afbab79314dbccdb/tests.py b/shared/package-files/3a/3ad18bca384d6357ef916d46bcb27f155f59a2a0bd027ca3afbab79314dbccdb/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..e12c10d033026f09cf97b81d29555e12aae8c762 --- /dev/null +++ b/shared/package-files/3a/3ad18bca384d6357ef916d46bcb27f155f59a2a0bd027ca3afbab79314dbccdb/tests.py @@ -0,0 +1,153 @@ +# coding: utf-8 +""" + + webencodings.tests + ~~~~~~~~~~~~~~~~~~ + + A basic test suite for Encoding. + + :copyright: Copyright 2012 by Simon Sapin + :license: BSD, see LICENSE for details. + +""" + +from __future__ import unicode_literals + +from . import (lookup, LABELS, decode, encode, iter_decode, iter_encode, + IncrementalDecoder, IncrementalEncoder, UTF8) + + +def assert_raises(exception, function, *args, **kwargs): + try: + function(*args, **kwargs) + except exception: + return + else: # pragma: no cover + raise AssertionError('Did not raise %s.' % exception) + + +def test_labels(): + assert lookup('utf-8').name == 'utf-8' + assert lookup('Utf-8').name == 'utf-8' + assert lookup('UTF-8').name == 'utf-8' + assert lookup('utf8').name == 'utf-8' + assert lookup('utf8').name == 'utf-8' + assert lookup('utf8 ').name == 'utf-8' + assert lookup(' \r\nutf8\t').name == 'utf-8' + assert lookup('u8') is None # Python label. + assert lookup('utf-8 ') is None # Non-ASCII white space. + + assert lookup('US-ASCII').name == 'windows-1252' + assert lookup('iso-8859-1').name == 'windows-1252' + assert lookup('latin1').name == 'windows-1252' + assert lookup('LATIN1').name == 'windows-1252' + assert lookup('latin-1') is None + assert lookup('LATİN1') is None # ASCII-only case insensitivity. + + +def test_all_labels(): + for label in LABELS: + assert decode(b'', label) == ('', lookup(label)) + assert encode('', label) == b'' + for repeat in [0, 1, 12]: + output, _ = iter_decode([b''] * repeat, label) + assert list(output) == [] + assert list(iter_encode([''] * repeat, label)) == [] + decoder = IncrementalDecoder(label) + assert decoder.decode(b'') == '' + assert decoder.decode(b'', final=True) == '' + encoder = IncrementalEncoder(label) + assert encoder.encode('') == b'' + assert encoder.encode('', final=True) == b'' + # All encoding names are valid labels too: + for name in set(LABELS.values()): + assert lookup(name).name == name + + +def test_invalid_label(): + assert_raises(LookupError, decode, b'\xEF\xBB\xBF\xc3\xa9', 'invalid') + assert_raises(LookupError, encode, 'é', 'invalid') + assert_raises(LookupError, iter_decode, [], 'invalid') + assert_raises(LookupError, iter_encode, [], 'invalid') + assert_raises(LookupError, IncrementalDecoder, 'invalid') + assert_raises(LookupError, IncrementalEncoder, 'invalid') + + +def test_decode(): + assert decode(b'\x80', 'latin1') == ('€', lookup('latin1')) + assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1')) + assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8')) + assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8')) + assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii')) + assert decode(b'\xEF\xBB\xBF\xc3\xa9', 'ascii') == ('é', lookup('utf8')) # UTF-8 with BOM + + assert decode(b'\xFE\xFF\x00\xe9', 'ascii') == ('é', lookup('utf-16be')) # UTF-16-BE with BOM + assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le')) # UTF-16-LE with BOM + assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be')) + assert decode(b'\xFF\xFE\x00\xe9', 'ascii') == ('\ue900', lookup('utf-16le')) + + assert decode(b'\x00\xe9', 'UTF-16BE') == ('é', lookup('utf-16be')) + assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le')) + assert decode(b'\xe9\x00', 'UTF-16') == ('é', lookup('utf-16le')) + + assert decode(b'\xe9\x00', 'UTF-16BE') == ('\ue900', lookup('utf-16be')) + assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le')) + assert decode(b'\x00\xe9', 'UTF-16') == ('\ue900', lookup('utf-16le')) + + +def test_encode(): + assert encode('é', 'latin1') == b'\xe9' + assert encode('é', 'utf8') == b'\xc3\xa9' + assert encode('é', 'utf8') == b'\xc3\xa9' + assert encode('é', 'utf-16') == b'\xe9\x00' + assert encode('é', 'utf-16le') == b'\xe9\x00' + assert encode('é', 'utf-16be') == b'\x00\xe9' + + +def test_iter_decode(): + def iter_decode_to_string(input, fallback_encoding): + output, _encoding = iter_decode(input, fallback_encoding) + return ''.join(output) + assert iter_decode_to_string([], 'latin1') == '' + assert iter_decode_to_string([b''], 'latin1') == '' + assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é' + assert iter_decode_to_string([b'hello'], 'latin1') == 'hello' + assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello' + assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello' + assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é' + assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é' + assert iter_decode_to_string([ + b'\xEF\xBB\xBF', b'\xc3', b'\xa9'], 'latin1') == 'é' + assert iter_decode_to_string([ + b'\xEF\xBB\xBF', b'a', b'\xc3'], 'latin1') == 'a\uFFFD' + assert iter_decode_to_string([ + b'', b'\xEF', b'', b'', b'\xBB\xBF\xc3', b'\xa9'], 'latin1') == 'é' + assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == '' + assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»' + assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é' + assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é' + assert iter_decode_to_string([ + b'', b'\xFF', b'', b'', b'\xFE\xe9', b'\x00'], 'latin1') == 'é' + assert iter_decode_to_string([ + b'', b'h\xe9', b'llo'], 'x-user-defined') == 'h\uF7E9llo' + + +def test_iter_encode(): + assert b''.join(iter_encode([], 'latin1')) == b'' + assert b''.join(iter_encode([''], 'latin1')) == b'' + assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9' + assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9' + assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00' + assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00' + assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9' + assert b''.join(iter_encode([ + '', 'h\uF7E9', '', 'llo'], 'x-user-defined')) == b'h\xe9llo' + + +def test_x_user_defined(): + encoded = b'2,\x0c\x0b\x1aO\xd9#\xcb\x0f\xc9\xbbt\xcf\xa8\xca' + decoded = '2,\x0c\x0b\x1aO\uf7d9#\uf7cb\x0f\uf7c9\uf7bbt\uf7cf\uf7a8\uf7ca' + encoded = b'aa' + decoded = 'aa' + assert decode(encoded, 'x-user-defined') == (decoded, lookup('x-user-defined')) + assert encode(decoded, 'x-user-defined') == encoded diff --git a/shared/package-files/3a/3ad1d4bbee922e4c38aa92dc18668fe86d27330e3d0dd214347edacce78edb33/pandas.py b/shared/package-files/3a/3ad1d4bbee922e4c38aa92dc18668fe86d27330e3d0dd214347edacce78edb33/pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..bc3650da813eab64b69388d27ed71aba20c922a1 --- /dev/null +++ b/shared/package-files/3a/3ad1d4bbee922e4c38aa92dc18668fe86d27330e3d0dd214347edacce78edb33/pandas.py @@ -0,0 +1,342 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from contextlib import contextmanager +import string +from typing import TYPE_CHECKING, Any, TypeVar + +import numpy as np +from packaging.version import Version, parse +import pandas as pd +from pandas import testing +from pandas.api.types import is_numeric_dtype +from pandas.tseries import offsets as frequencies +from pandas.util._decorators import ( + cache_readonly, + deprecate_kwarg as pd_deprecate_kwarg, +) + +from statsmodels.tools.docstring_helpers import Appender, Substitution + +if TYPE_CHECKING: + from typing import TypeAlias + + +FuncType: TypeAlias = Callable[..., Any] +F = TypeVar("F", bound=FuncType) +__all__ = [ + "FUTURE_STACK", + "MONTH_END", + "PD_LT_2", + "PD_LT_3", + "PD_LT_3_1_0", + "QUARTER_END", + "YEAR_END", + "Appender", + "Substitution", + "assert_frame_equal", + "assert_index_equal", + "assert_series_equal", + "cache_readonly", + "call_cached_func", + "data_klasses", + "deprecate_kwarg", + "frequencies", + "get_cached_doc", + "get_cached_func", + "is_float_index", + "is_int_index", + "is_numeric_dtype", + "make_dataframe", + "testing", + "to_numpy", +] + +version = parse(pd.__version__) + +PD_LT_3_1_0 = version < Version("3.0.99") +PD_LT_2_2_0 = version < Version("2.1.99") +PD_LT_2_1_0 = version < Version("2.0.99") +PD_LT_2 = version < Version("1.99.99") +PD_LT_3 = version < Version("2.99.99") + +data_klasses = (pd.Series, pd.DataFrame) + +assert_frame_equal = testing.assert_frame_equal +assert_index_equal = testing.assert_index_equal +assert_series_equal = testing.assert_series_equal + + +@contextmanager +def _infer_freq_returns_offset(): + """Context manager that requests offset return values from infer_freq""" + # pandas 3.1 changes the return value of infer_freq + try: + with pd.option_context("future.infer_freq_returns_offset", True): + yield + except pd.errors.OptionError: + # in older versions the option is not available and a str is returned + yield + + +def infer_freq(index) -> str | None: + """ + Infer the frequency string of a datetime index + + Parameters + ---------- + index : pd.Index + An index to infer the frequency of. + + Returns + ------- + str or None + The inferred frequency string, or None if it cannot be inferred. + """ + # pandas 3.1 changes the return value of infer_freq + with _infer_freq_returns_offset(): + freq = pd.infer_freq(index) + + # new pandas versions returns BaseOffset + if not isinstance(freq, str) and freq is not None: + return freq.freqstr + return freq + + +def is_int_index(index: pd.Index) -> bool: + """ + Check if an index is integral + + Parameters + ---------- + index : pd.Index + Any numeric index + + Returns + ------- + bool + True if is an index with a standard integral type + """ + return ( + isinstance(index, pd.Index) + and isinstance(index.dtype, np.dtype) + and np.issubdtype(index.dtype, np.integer) + ) + + +def is_float_index(index: pd.Index) -> bool: + """ + Check if an index is floating + + Parameters + ---------- + index : pd.Index + Any numeric index + + Returns + ------- + bool + True if an index with a standard numpy floating dtype + """ + return ( + isinstance(index, pd.Index) + and isinstance(index.dtype, np.dtype) + and np.issubdtype(index.dtype, np.floating) + ) + + +def rands_array(generator=None, nchars=10, size=10, dtype="O"): + """ + Generate an array of byte strings + + Parameters + ---------- + generator : numpy.random.Generator, optional + A NumPy random generator. If None, ``np.random.default_rng()`` is + used. + nchars : int, optional + The number of characters in each string. + size : int or tuple[int, ...], optional + The shape of the output array. + dtype : str or None, optional + The dtype to cast the output to. If None, the raw string array is + returned. + + Returns + ------- + ndarray + An array of random strings. + """ + if generator is None: + generator = np.random.default_rng() + rands_chars = np.array( + list(string.ascii_letters + string.digits), dtype=(np.str_, 1) + ) + retval = ( + generator.choice(rands_chars, size=nchars * np.prod(size)) + .view((np.str_, nchars)) + .reshape(size) + ) + if dtype is None: + return retval + else: + return retval.astype(dtype) + + +def make_dataframe(generator=None): + """ + Simple version of pandas._testing.makeDataFrame + + Parameters + ---------- + generator : numpy.random.Generator, optional + A NumPy random generator. If None, ``np.random.default_rng()`` is + used. + + Returns + ------- + DataFrame + A DataFrame with 30 rows and 4 columns of standard normal data. + """ + if generator is None: + generator = np.random.default_rng() + n = 30 + k = 4 + index = pd.Index(rands_array(generator=generator, nchars=10, size=n), name=None) + data = { + c: pd.Series(generator.standard_normal(n), index=index) + for c in string.ascii_uppercase[:k] + } + + return pd.DataFrame(data) + + +def to_numpy(po: pd.DataFrame) -> np.ndarray: + """ + Workaround legacy pandas lacking to_numpy + + Parameters + ---------- + po : DataFrame + A pandas object. + + Returns + ------- + ndarray + A numpy array + """ + try: + return po.to_numpy() + except AttributeError: + return po.values + + +def get_cached_func(cached_prop): + """ + Get the underlying function of a cached property + + Parameters + ---------- + cached_prop : cache_readonly + A cached property instance. + + Returns + ------- + callable + The wrapped function. + """ + try: + return cached_prop.fget + except AttributeError: + return cached_prop.func + + +def call_cached_func(cached_prop, *args, **kwargs): + """ + Call the underlying function of a cached property + + Parameters + ---------- + cached_prop : cache_readonly + A cached property instance. + *args + Positional arguments passed to the underlying function. + **kwargs + Keyword arguments passed to the underlying function. + + Returns + ------- + object + The result of calling the underlying function. + """ + f = get_cached_func(cached_prop) + return f(*args, **kwargs) + + +def get_cached_doc(cached_prop) -> str | None: + """ + Get the docstring of the underlying function of a cached property + + Parameters + ---------- + cached_prop : cache_readonly + A cached property instance. + + Returns + ------- + str or None + The docstring of the underlying function. + """ + return get_cached_func(cached_prop).__doc__ + + +MONTH_END = "M" if PD_LT_2_2_0 else "ME" +QUARTER_END = "Q" if PD_LT_2_2_0 else "QE" +YEAR_END = "Y" if PD_LT_2_2_0 else "YE" +FUTURE_STACK = {} if PD_LT_2_1_0 else {"future_stack": True} + + +def deprecate_kwarg( + old_arg_name: str, + new_arg_name: str | None, + mapping: Mapping[Any, Any] | Callable[[Any], Any] | None = None, + stacklevel: int = 2, +) -> Callable[[F], F]: + """ + Decorator to deprecate a keyword argument of a function + + Parameters + ---------- + old_arg_name : str + Name of argument in function to deprecate. + new_arg_name : str or None + Name of preferred argument in function. Use None to raise warning + that ``old_arg_name`` keyword is deprecated. + mapping : dict or callable, optional + If mapping is present, use it to translate old arguments to + new arguments. A callable must do its own value checking; + values not found in a dict will be raised as-is. + stacklevel : int, optional + How far up the stack the warning is to be logged. + + Returns + ------- + callable + A decorator that wraps the decorated function to warn on use of + the deprecated keyword. + """ + if PD_LT_3: + return pd_deprecate_kwarg( + old_arg_name=old_arg_name, + new_arg_name=new_arg_name, + mapping=mapping, + stacklevel=stacklevel, + ) + else: + return pd_deprecate_kwarg( + klass=FutureWarning, + old_arg_name=old_arg_name, + new_arg_name=new_arg_name, + mapping=mapping, + stacklevel=stacklevel, + ) diff --git a/shared/package-files/3a/3ad2ed400d295c3f0b4bed11827590fd2eecbba7080754cef59799ced7a082c4/pdist_native.h b/shared/package-files/3a/3ad2ed400d295c3f0b4bed11827590fd2eecbba7080754cef59799ced7a082c4/pdist_native.h new file mode 100644 index 0000000000000000000000000000000000000000..5c35c4710c3c2c1d059542a061c0193216ccf4a1 --- /dev/null +++ b/shared/package-files/3a/3ad2ed400d295c3f0b4bed11827590fd2eecbba7080754cef59799ced7a082c4/pdist_native.h @@ -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 pdist(const at::Tensor & self, double p=2); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3ad47abb4b78f9fcd23bf187cb2b8aa5cb2001cfd8427df2a6b3be617b18f410/keypoint_rcnn.py b/shared/package-files/3a/3ad47abb4b78f9fcd23bf187cb2b8aa5cb2001cfd8427df2a6b3be617b18f410/keypoint_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..987df6603b8704beb87274a185f8ad1b28bd6e7d --- /dev/null +++ b/shared/package-files/3a/3ad47abb4b78f9fcd23bf187cb2b8aa5cb2001cfd8427df2a6b3be617b18f410/keypoint_rcnn.py @@ -0,0 +1,471 @@ +from typing import Any, Optional + +import torch +from torch import nn +from torchvision.ops import MultiScaleRoIAlign + +from ...ops import misc as misc_nn_ops +from ...transforms._presets import ObjectDetection +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from ._utils import overwrite_eps +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .faster_rcnn import FasterRCNN + + +__all__ = [ + "KeypointRCNN", + "KeypointRCNN_ResNet50_FPN_Weights", + "keypointrcnn_resnet50_fpn", +] + + +class KeypointRCNN(FasterRCNN): + """ + Implements Keypoint R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + - keypoints (FloatTensor[N, K, 3]): the K keypoints location for each of the N instances, in the + format [x, y, visibility], where visibility=0 means that the keypoint is not visible. + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the keypoint loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores or each prediction + - keypoints (FloatTensor[N, K, 3]): the locations of the predicted keypoints, in [x, y, v] format. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or and OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + If box_predictor is specified, num_classes should be None. + min_size (int): minimum size of the image to be rescaled before feeding it to the backbone + max_size (int): maximum size of the image to be rescaled before feeding it to the backbone + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN + rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training + rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing + rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training + rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing + rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh + box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes + box_head (nn.Module): module that takes the cropped feature maps as input + box_predictor (nn.Module): module that takes the output of box_head and returns the + classification logits and box regression deltas. + box_score_thresh (float): during inference, only return proposals with a classification score + greater than box_score_thresh + box_nms_thresh (float): NMS threshold for the prediction head. Used during inference + box_detections_per_img (int): maximum number of detections per image, for all classes. + box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be + considered as positive during training of the classification head + box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be + considered as negative during training of the classification head + box_batch_size_per_image (int): number of proposals that are sampled during training of the + classification head + box_positive_fraction (float): proportion of positive proposals in a mini-batch during training + of the classification head + bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the + bounding boxes + keypoint_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes, which will be used for the keypoint head. + keypoint_head (nn.Module): module that takes the cropped feature maps as input + keypoint_predictor (nn.Module): module that takes the output of the keypoint_head and returns the + heatmap logits + + Example:: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import KeypointRCNN + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # KeypointRCNN needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the RPN generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),)) + >>> + >>> # let's define what are the feature maps that we will + >>> # use to perform the region of interest cropping, as well as + >>> # the size of the crop after rescaling. + >>> # if your backbone returns a Tensor, featmap_names is expected to + >>> # be ['0']. More generally, the backbone should return an + >>> # OrderedDict[Tensor], and in featmap_names you can choose which + >>> # feature maps to use. + >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=7, + >>> sampling_ratio=2) + >>> + >>> keypoint_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=14, + >>> sampling_ratio=2) + >>> # put the pieces together inside a KeypointRCNN model + >>> model = KeypointRCNN(backbone, + >>> num_classes=2, + >>> rpn_anchor_generator=anchor_generator, + >>> box_roi_pool=roi_pooler, + >>> keypoint_roi_pool=keypoint_roi_pooler) + >>> model.eval() + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + def __init__( + self, + backbone, + num_classes=None, + # transform parameters + min_size=None, + max_size=1333, + image_mean=None, + image_std=None, + # RPN parameters + rpn_anchor_generator=None, + rpn_head=None, + rpn_pre_nms_top_n_train=2000, + rpn_pre_nms_top_n_test=1000, + rpn_post_nms_top_n_train=2000, + rpn_post_nms_top_n_test=1000, + rpn_nms_thresh=0.7, + rpn_fg_iou_thresh=0.7, + rpn_bg_iou_thresh=0.3, + rpn_batch_size_per_image=256, + rpn_positive_fraction=0.5, + rpn_score_thresh=0.0, + # Box parameters + box_roi_pool=None, + box_head=None, + box_predictor=None, + box_score_thresh=0.05, + box_nms_thresh=0.5, + box_detections_per_img=100, + box_fg_iou_thresh=0.5, + box_bg_iou_thresh=0.5, + box_batch_size_per_image=512, + box_positive_fraction=0.25, + bbox_reg_weights=None, + # keypoint parameters + keypoint_roi_pool=None, + keypoint_head=None, + keypoint_predictor=None, + num_keypoints=None, + **kwargs, + ): + + if not isinstance(keypoint_roi_pool, (MultiScaleRoIAlign, type(None))): + raise TypeError( + "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}" + ) + if min_size is None: + min_size = (640, 672, 704, 736, 768, 800) + + if num_keypoints is not None: + if keypoint_predictor is not None: + raise ValueError("num_keypoints should be None when keypoint_predictor is specified") + else: + num_keypoints = 17 + + out_channels = backbone.out_channels + + if keypoint_roi_pool is None: + keypoint_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2) + + if keypoint_head is None: + keypoint_layers = tuple(512 for _ in range(8)) + keypoint_head = KeypointRCNNHeads(out_channels, keypoint_layers) + + if keypoint_predictor is None: + keypoint_dim_reduced = 512 # == keypoint_layers[-1] + keypoint_predictor = KeypointRCNNPredictor(keypoint_dim_reduced, num_keypoints) + + super().__init__( + backbone, + num_classes, + # transform parameters + min_size, + max_size, + image_mean, + image_std, + # RPN-specific parameters + rpn_anchor_generator, + rpn_head, + rpn_pre_nms_top_n_train, + rpn_pre_nms_top_n_test, + rpn_post_nms_top_n_train, + rpn_post_nms_top_n_test, + rpn_nms_thresh, + rpn_fg_iou_thresh, + rpn_bg_iou_thresh, + rpn_batch_size_per_image, + rpn_positive_fraction, + rpn_score_thresh, + # Box parameters + box_roi_pool, + box_head, + box_predictor, + box_score_thresh, + box_nms_thresh, + box_detections_per_img, + box_fg_iou_thresh, + box_bg_iou_thresh, + box_batch_size_per_image, + box_positive_fraction, + bbox_reg_weights, + **kwargs, + ) + + self.roi_heads.keypoint_roi_pool = keypoint_roi_pool + self.roi_heads.keypoint_head = keypoint_head + self.roi_heads.keypoint_predictor = keypoint_predictor + + +class KeypointRCNNHeads(nn.Sequential): + def __init__(self, in_channels, layers): + d = [] + next_feature = in_channels + for out_channels in layers: + d.append(nn.Conv2d(next_feature, out_channels, 3, stride=1, padding=1)) + d.append(nn.ReLU(inplace=True)) + next_feature = out_channels + super().__init__(*d) + for m in self.children(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + nn.init.constant_(m.bias, 0) + + +class KeypointRCNNPredictor(nn.Module): + def __init__(self, in_channels, num_keypoints): + super().__init__() + input_features = in_channels + deconv_kernel = 4 + self.kps_score_lowres = nn.ConvTranspose2d( + input_features, + num_keypoints, + deconv_kernel, + stride=2, + padding=deconv_kernel // 2 - 1, + ) + nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu") + nn.init.constant_(self.kps_score_lowres.bias, 0) + self.up_scale = 2 + self.out_channels = num_keypoints + + def forward(self, x): + x = self.kps_score_lowres(x) + return torch.nn.functional.interpolate( + x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False + ) + + +_COMMON_META = { + "categories": _COCO_PERSON_CATEGORIES, + "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES, + "min_size": (1, 1), +} + + +class KeypointRCNN_ResNet50_FPN_Weights(WeightsEnum): + COCO_LEGACY = Weights( + url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-9f466800.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 59137258, + "recipe": "https://github.com/pytorch/vision/issues/1606", + "_metrics": { + "COCO-val2017": { + "box_map": 50.6, + "kp_map": 61.1, + } + }, + "_ops": 133.924, + "_file_size": 226.054, + "_docs": """ + These weights were produced by following a similar training recipe as on the paper but use a checkpoint + from an early epoch. + """, + }, + ) + COCO_V1 = Weights( + url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-fc266e95.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 59137258, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#keypoint-r-cnn", + "_metrics": { + "COCO-val2017": { + "box_map": 54.6, + "kp_map": 65.0, + } + }, + "_ops": 137.42, + "_file_size": 226.054, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: KeypointRCNN_ResNet50_FPN_Weights.COCO_LEGACY + if kwargs["pretrained"] == "legacy" + else KeypointRCNN_ResNet50_FPN_Weights.COCO_V1, + ), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def keypointrcnn_resnet50_fpn( + *, + weights: Optional[KeypointRCNN_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + num_keypoints: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> KeypointRCNN: + """ + Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `Mask R-CNN `__. + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the + format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible. + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the keypoint loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detected instances: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each instance + - scores (``Tensor[N]``): the scores or each instance + - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format. + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size. + + Example:: + + >>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(weights=KeypointRCNN_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + >>> + >>> # optionally, if you want to export the model to ONNX: + >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11) + + Args: + weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr + num_classes (int, optional): number of output classes of the model (including the background) + num_keypoints (int, optional): number of keypoints + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 3. + + .. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights + :members: + """ + weights = KeypointRCNN_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_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"])) + num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"])) + else: + if num_classes is None: + num_classes = 2 + if num_keypoints is None: + num_keypoints = 17 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers) + model = KeypointRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == KeypointRCNN_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model diff --git a/shared/package-files/3a/3ad5d60627477a60939ee44fc1bb3a05dbe8fb52f0f75039b8f5d8f1a278b981/_compression.py b/shared/package-files/3a/3ad5d60627477a60939ee44fc1bb3a05dbe8fb52f0f75039b8f5d8f1a278b981/_compression.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b70aa0a3e6806c0f2b60ffaf9944291abcf4c4 --- /dev/null +++ b/shared/package-files/3a/3ad5d60627477a60939ee44fc1bb3a05dbe8fb52f0f75039b8f5d8f1a278b981/_compression.py @@ -0,0 +1,162 @@ +"""Internal classes used by the gzip, lzma and bz2 modules""" + +import io +import sys + +BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE # Compressed data read chunk size + + +class BaseStream(io.BufferedIOBase): + """Mode-checking helper functions.""" + + def _check_not_closed(self): + if self.closed: + raise ValueError("I/O operation on closed file") + + def _check_can_read(self): + if not self.readable(): + raise io.UnsupportedOperation("File not open for reading") + + def _check_can_write(self): + if not self.writable(): + raise io.UnsupportedOperation("File not open for writing") + + def _check_can_seek(self): + if not self.readable(): + raise io.UnsupportedOperation("Seeking is only supported " + "on files open for reading") + if not self.seekable(): + raise io.UnsupportedOperation("The underlying file object " + "does not support seeking") + + +class DecompressReader(io.RawIOBase): + """Adapts the decompressor API to a RawIOBase reader API""" + + def readable(self): + return True + + def __init__(self, fp, decomp_factory, trailing_error=(), **decomp_args): + self._fp = fp + self._eof = False + self._pos = 0 # Current offset in decompressed stream + + # Set to size of decompressed stream once it is known, for SEEK_END + self._size = -1 + + # Save the decompressor factory and arguments. + # If the file contains multiple compressed streams, each + # stream will need a separate decompressor object. A new decompressor + # object is also needed when implementing a backwards seek(). + self._decomp_factory = decomp_factory + self._decomp_args = decomp_args + self._decompressor = self._decomp_factory(**self._decomp_args) + + # Exception class to catch from decompressor signifying invalid + # trailing data to ignore + self._trailing_error = trailing_error + + def close(self): + self._decompressor = None + return super().close() + + def seekable(self): + return self._fp.seekable() + + def readinto(self, b): + with memoryview(b) as view, view.cast("B") as byte_view: + data = self.read(len(byte_view)) + byte_view[:len(data)] = data + return len(data) + + def read(self, size=-1): + if size < 0: + return self.readall() + + if not size or self._eof: + return b"" + data = None # Default if EOF is encountered + # Depending on the input data, our call to the decompressor may not + # return any data. In this case, try again after reading another block. + while True: + if self._decompressor.eof: + rawblock = (self._decompressor.unused_data or + self._fp.read(BUFFER_SIZE)) + if not rawblock: + break + # Continue to next stream. + self._decompressor = self._decomp_factory( + **self._decomp_args) + try: + data = self._decompressor.decompress(rawblock, size) + except self._trailing_error: + # Trailing data isn't a valid compressed stream; ignore it. + break + else: + if self._decompressor.needs_input: + rawblock = self._fp.read(BUFFER_SIZE) + if not rawblock: + raise EOFError("Compressed file ended before the " + "end-of-stream marker was reached") + else: + rawblock = b"" + data = self._decompressor.decompress(rawblock, size) + if data: + break + if not data: + self._eof = True + self._size = self._pos + return b"" + self._pos += len(data) + return data + + def readall(self): + chunks = [] + # sys.maxsize means the max length of output buffer is unlimited, + # so that the whole input buffer can be decompressed within one + # .decompress() call. + while data := self.read(sys.maxsize): + chunks.append(data) + + return b"".join(chunks) + + # Rewind the file to the beginning of the data stream. + def _rewind(self): + self._fp.seek(0) + self._eof = False + self._pos = 0 + self._decompressor = self._decomp_factory(**self._decomp_args) + + def seek(self, offset, whence=io.SEEK_SET): + # Recalculate offset as an absolute file position. + if whence == io.SEEK_SET: + pass + elif whence == io.SEEK_CUR: + offset = self._pos + offset + elif whence == io.SEEK_END: + # Seeking relative to EOF - we need to know the file's size. + if self._size < 0: + while self.read(io.DEFAULT_BUFFER_SIZE): + pass + offset = self._size + offset + else: + raise ValueError("Invalid value for whence: {}".format(whence)) + + # Make it so that offset is the number of bytes to skip forward. + if offset < self._pos: + self._rewind() + else: + offset -= self._pos + + # Read and discard data until we reach the desired position. + while offset > 0: + data = self.read(min(io.DEFAULT_BUFFER_SIZE, offset)) + if not data: + break + offset -= len(data) + + return self._pos + + def tell(self): + """Return the current file position.""" + return self._pos diff --git a/shared/package-files/3a/3ad7ffaf9731b49f98c70484451a8c774ab0b52ffb9e611435c63b6f1d48c366/hp2626-s b/shared/package-files/3a/3ad7ffaf9731b49f98c70484451a8c774ab0b52ffb9e611435c63b6f1d48c366/hp2626-s new file mode 100644 index 0000000000000000000000000000000000000000..4563ad938e88d27182fe4b9f2eb1e06bd13f467f Binary files /dev/null and b/shared/package-files/3a/3ad7ffaf9731b49f98c70484451a8c774ab0b52ffb9e611435c63b6f1d48c366/hp2626-s differ diff --git a/shared/package-files/3a/3ad90dbc16be1bfb54ad32e7ebfca24cbd99feac71d786c1a7dee8575a54f05d/libdeflate-config-version.cmake b/shared/package-files/3a/3ad90dbc16be1bfb54ad32e7ebfca24cbd99feac71d786c1a7dee8575a54f05d/libdeflate-config-version.cmake new file mode 100644 index 0000000000000000000000000000000000000000..eebcde3bbd9b66728fc6731e032e1ef437184b62 --- /dev/null +++ b/shared/package-files/3a/3ad90dbc16be1bfb54ad32e7ebfca24cbd99feac71d786c1a7dee8575a54f05d/libdeflate-config-version.cmake @@ -0,0 +1,43 @@ +# This is a basic version file for the Config-mode of find_package(). +# It is used by write_basic_package_version_file() as input file for configure_file() +# to create a version-file which can be installed along a config.cmake file. +# +# The created file sets PACKAGE_VERSION_EXACT if the current version string and +# the requested version string are exactly the same and it sets +# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version. +# The variable CVF_VERSION must be set before calling configure_file(). + +set(PACKAGE_VERSION "1.17") + +if (PACKAGE_FIND_VERSION_RANGE) + # Package version must be in the requested version range + if ((PACKAGE_FIND_VERSION_RANGE_MIN STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN) + OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_GREATER PACKAGE_FIND_VERSION_MAX) + OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_GREATER_EQUAL PACKAGE_FIND_VERSION_MAX))) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + endif() +else() + if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) + endif() + endif() +endif() + + +# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: +if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "") + return() +endif() + +# check that the installed version has the same 32/64bit-ness as the one which is currently searching: +if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8") + math(EXPR installedBits "8 * 8") + set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") + set(PACKAGE_VERSION_UNSUITABLE TRUE) +endif() diff --git a/shared/package-files/3a/3ad97027dcd90efc2064e81b798fe889d58f3949a28bf2410820691e72f0f2eb/test_isin.py b/shared/package-files/3a/3ad97027dcd90efc2064e81b798fe889d58f3949a28bf2410820691e72f0f2eb/test_isin.py new file mode 100644 index 0000000000000000000000000000000000000000..68fdf25359f1bbada24f6a2403d5a04331bee84c --- /dev/null +++ b/shared/package-files/3a/3ad97027dcd90efc2064e81b798fe889d58f3949a28bf2410820691e72f0f2eb/test_isin.py @@ -0,0 +1,103 @@ +import numpy as np +import pytest + +from pandas import MultiIndex +import pandas._testing as tm + + +def test_isin_nan(): + idx = MultiIndex.from_arrays([["foo", "bar"], [1.0, np.nan]]) + tm.assert_numpy_array_equal(idx.isin([("bar", np.nan)]), np.array([False, True])) + tm.assert_numpy_array_equal( + idx.isin([("bar", float("nan"))]), np.array([False, True]) + ) + + +def test_isin_missing(nulls_fixture): + # GH48905 + mi1 = MultiIndex.from_tuples([(1, nulls_fixture)]) + mi2 = MultiIndex.from_tuples([(1, 1), (1, 2)]) + result = mi2.isin(mi1) + expected = np.array([False, False]) + tm.assert_numpy_array_equal(result, expected) + + +def test_isin(): + values = [("foo", 2), ("bar", 3), ("quux", 4)] + + idx = MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)]) + result = idx.isin(values) + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(result, expected) + + # empty, return dtype bool + idx = MultiIndex.from_arrays([[], []]) + result = idx.isin(values) + assert len(result) == 0 + assert result.dtype == np.bool_ + + +def test_isin_level_kwarg(): + idx = MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)]) + + vals_0 = ["foo", "bar", "quux"] + vals_1 = [2, 3, 10] + + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=0)) + tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=-2)) + + tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=1)) + tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=-1)) + + msg = "Too many levels: Index has only 2 levels, not 6" + with pytest.raises(IndexError, match=msg): + idx.isin(vals_0, level=5) + msg = "Too many levels: Index has only 2 levels, -5 is not a valid level number" + with pytest.raises(IndexError, match=msg): + idx.isin(vals_0, level=-5) + + with pytest.raises(KeyError, match=r"'Level 1\.0 not found'"): + idx.isin(vals_0, level=1.0) + with pytest.raises(KeyError, match=r"'Level -1\.0 not found'"): + idx.isin(vals_1, level=-1.0) + with pytest.raises(KeyError, match="'Level A not found'"): + idx.isin(vals_1, level="A") + + idx.names = ["A", "B"] + tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level="A")) + tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level="B")) + + with pytest.raises(KeyError, match="'Level C not found'"): + idx.isin(vals_1, level="C") + + +@pytest.mark.parametrize( + "labels,expected,level", + [ + ([("b", np.nan)], np.array([False, False, True]), None), + ([np.nan, "a"], np.array([True, True, False]), 0), + (["d", np.nan], np.array([False, True, True]), 1), + ], +) +def test_isin_multi_index_with_missing_value(labels, expected, level): + # GH 19132 + midx = MultiIndex.from_arrays([[np.nan, "a", "b"], ["c", "d", np.nan]]) + result = midx.isin(labels, level=level) + tm.assert_numpy_array_equal(result, expected) + + +def test_isin_empty(): + # GH#51599 + midx = MultiIndex.from_arrays([[1, 2], [3, 4]]) + result = midx.isin([]) + expected = np.array([False, False]) + tm.assert_numpy_array_equal(result, expected) + + +def test_isin_generator(): + # GH#52568 + midx = MultiIndex.from_tuples([(1, 2)]) + result = midx.isin(x for x in [(1, 2)]) + expected = np.array([True]) + tm.assert_numpy_array_equal(result, expected) diff --git a/shared/package-files/3a/3ada62421934dcfe0cf42c6fee58a1c9ceec4cd904bdb8322520b21f3c21d5d0/LegacyTypeDispatch.h b/shared/package-files/3a/3ada62421934dcfe0cf42c6fee58a1c9ceec4cd904bdb8322520b21f3c21d5d0/LegacyTypeDispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3efe5e0f7b87b66a1cf22ef1d5fb0f93e2f78494 --- /dev/null +++ b/shared/package-files/3a/3ada62421934dcfe0cf42c6fee58a1c9ceec4cd904bdb8322520b21f3c21d5d0/LegacyTypeDispatch.h @@ -0,0 +1,111 @@ +#pragma once + +// The legacy mechanism for dispatching operators in ATen is a Type +// object, which is essentially a giant virtual dispatch table +// for every operation we support dynamically dispatching over. +// +// This has been deprecated in favor of ATenDispatch, and in the future, +// c10 dispatcher. +// TODO: Clean up what remains here + +#include + +namespace at { + +// A RAII, thread local (!) guard that will disable dispatch to variable +// handler. +// +// NOTE [ Treating Variables as non-Variables in type dispatch ] +// +// What exactly does AutoDispatchBelowAutograd do? The short answer is, it causes +// dispatches on ATen functions to go to the non-variable implementation, +// bypassing autograd handling (and also profiling and tracing). +// +// To understand why this guard exists, it's helpful to understand the history +// behind how Variable was implemented. Previously, Variables were implemented +// as a wrapper on Tensors; so the act of processing a Variable involved +// unwrapping the underlying Tensor, and then calling the underlying base +// operation on /that/ operation +// +// However, after the Variable/Tensor merge, there is no concept of unwrapping +// a tensor anymore. If you just call the operation on the same variable +// again inside your VariableType handler, you'll dispatch back to +// VariableType, which is not what we want. +// +// The solution to the above problem is to add `at::AutoDispatchBelowAutograd`, which +// when enabled will cause `legacyTensorType()` and `getType()` to always return +// non-Variable type, even if the tensor being called on is a variable. + +/* Note [AutoDispatchBelowAutograd] + * AutoDispatchBelowAutograd is **INTERNAL ONLY** that it should be used + * for kernel implementations and customized C++ kernels. + * If you are looking for a guard to run workload in inference mode, please use + * c10::InferenceMode RAII which is user facing API. + * In the past AutoDispatchBelowAutograd(or its old version AutoNonVariableTypeMode) + * was used in the user code for inference-only workload, this was under risk of + * producing wrong results silently in some edge cases. For example: + * ``` + * torch::Tensor s = torch::ones({1, 2, 3}).set_requires_grad(true); + * torch::Tensor out = s * s; + * { + * at::AutoDispatchBelowAutograd guard; + * s.add_(1); // Skips version bump on `s`. + * } + * // WRONG GRADIENT! s.grad() are now computed using `s` value after the + * // inplace update. + * out.backward(torch::ones_like(out)); + * ``` + * Users should use `c10::InferenceMode` here so that it'll properly throw an + * error saying "one of the variables needed for gradient computation has be modified." + */ +struct TORCH_API AutoDispatchBelowAutograd { + AutoDispatchBelowAutograd() : + autograd_guard_(c10::autograd_dispatch_keyset) { + } + + // disable all autograd dispatch keys + c10::impl::ExcludeDispatchKeyGuard autograd_guard_; +}; + +// TODO: AutoNonVariableTypeMode should be removed in release 1.10. +struct TORCH_API AutoNonVariableTypeMode { + AutoNonVariableTypeMode(bool enabled = true) : + autograd_guard_(c10::autograd_dispatch_keyset) { + TORCH_WARN_ONCE("AutoNonVariableTypeMode is deprecated and will be removed in 1.10 release. " + "For kernel implementations please use AutoDispatchBelowADInplaceOrView instead, " + "If you are looking for a user facing API to enable running your inference-only " + "workload, please use c10::InferenceMode. Using AutoDispatchBelowADInplaceOrView in user code " + "is under risk of producing silent wrong result in some edge cases. " + "See Note [AutoDispatchBelowAutograd] for more details."); + TORCH_INTERNAL_ASSERT(enabled); + } + + // disable all autograd dispatch keys + c10::impl::ExcludeDispatchKeyGuard autograd_guard_; +}; + +struct TORCH_API AutoDispatchSkipFunctionalize { + AutoDispatchSkipFunctionalize() : + dispatch_key_guard_(c10::DispatchKeySet(c10::DispatchKey::Functionalize)) { + } + c10::impl::ExcludeDispatchKeyGuard dispatch_key_guard_; +}; + +/* Note [AutoDispatchBelowADInplaceOrView] + * AutoDispatchBelowADInplaceOrView is equivalent to AutoNonVariableTypeMode + * before we split inplace & view ops out of VariableType kernel. + * Note this guard is used in VariableType kernels for functional ops + * as well as ADInplaceOrView kernels for inplace/view ops to enforce the + * Invariant: + * Once you are in VariableType/ADInplaceOrView kernel for an op, + * you never go back to a kernel on same dispatch key until + * you finish the current op. + */ +struct TORCH_API AutoDispatchBelowADInplaceOrView { + AutoDispatchBelowADInplaceOrView() : + dispatch_key_guard_(c10::autograd_dispatch_keyset_with_ADInplaceOrView) { + } + // disable Autograd & ADInplaceOrView dispatch keys + c10::impl::ExcludeDispatchKeyGuard dispatch_key_guard_; +}; +} // namespace at diff --git a/shared/package-files/3a/3adac5a8bd663a6b25b414dd3372093788a7709157c45b372f29ace790f58820/special_modified_bessel_k0.h b/shared/package-files/3a/3adac5a8bd663a6b25b414dd3372093788a7709157c45b372f29ace790f58820/special_modified_bessel_k0.h new file mode 100644 index 0000000000000000000000000000000000000000..421187889d91d626b9a2e184d2bf82098d70100a --- /dev/null +++ b/shared/package-files/3a/3adac5a8bd663a6b25b414dd3372093788a7709157c45b372f29ace790f58820/special_modified_bessel_k0.h @@ -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::special_modified_bessel_k0(Tensor self) -> Tensor +inline at::Tensor special_modified_bessel_k0(const at::Tensor & self) { + return at::_ops::special_modified_bessel_k0::call(self); +} + +// aten::special_modified_bessel_k0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_modified_bessel_k0_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_modified_bessel_k0_out::call(self, out); +} +// aten::special_modified_bessel_k0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_modified_bessel_k0_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_modified_bessel_k0_out::call(self, out); +} + +} diff --git a/shared/package-files/3a/3adc974a2b92cbca3fefcc3740d4118cc2e9bef37211d0b468cb31e93faf4715/_pytesttester.pyi b/shared/package-files/3a/3adc974a2b92cbca3fefcc3740d4118cc2e9bef37211d0b468cb31e93faf4715/_pytesttester.pyi new file mode 100644 index 0000000000000000000000000000000000000000..67ac87b33de164c710a25110d45545e24a06d42e --- /dev/null +++ b/shared/package-files/3a/3adc974a2b92cbca3fefcc3740d4118cc2e9bef37211d0b468cb31e93faf4715/_pytesttester.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable +from typing import Literal as L + +__all__: list[str] + +class PytestTester: + module_name: str + def __init__(self, module_name: str) -> None: ... + def __call__( + self, + label: L["fast", "full"] = ..., + verbose: int = ..., + extra_argv: None | Iterable[str] = ..., + doctests: L[False] = ..., + coverage: bool = ..., + durations: int = ..., + tests: None | Iterable[str] = ..., + ) -> bool: ... diff --git a/shared/package-files/3a/3ade63db30c7613adae242ae4f0c58a7b5f94ec37083f709b986bb071990cfe0/cm.pyi b/shared/package-files/3a/3ade63db30c7613adae242ae4f0c58a7b5f94ec37083f709b986bb071990cfe0/cm.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c3c62095684aaa7b7a59490412889096b3cded61 --- /dev/null +++ b/shared/package-files/3a/3ade63db30c7613adae242ae4f0c58a7b5f94ec37083f709b986bb071990cfe0/cm.pyi @@ -0,0 +1,24 @@ +from collections.abc import Iterator, Mapping +from matplotlib import colors +from matplotlib.colorizer import _ScalarMappable + + +class ColormapRegistry(Mapping[str, colors.Colormap]): + def __init__(self, cmaps: Mapping[str, colors.Colormap]) -> None: ... + def __getitem__(self, item: str) -> colors.Colormap: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __call__(self) -> list[str]: ... + def register( + self, cmap: colors.Colormap, *, name: str | None = ..., force: bool = ... + ) -> None: ... + def unregister(self, name: str) -> None: ... + def get_cmap(self, cmap: str | colors.Colormap) -> colors.Colormap: ... + +_colormaps: ColormapRegistry = ... +_multivar_colormaps: ColormapRegistry = ... +_bivar_colormaps: ColormapRegistry = ... + +def get_cmap(name: str | colors.Colormap | None = ..., lut: int | None = ...) -> colors.Colormap: ... + +ScalarMappable = _ScalarMappable diff --git a/shared/package-files/3a/3adff278c22c8d2c706053247acfd444fd8e959ab345e3d57986826e742bfaa2/_random.pyi b/shared/package-files/3a/3adff278c22c8d2c706053247acfd444fd8e959ab345e3d57986826e742bfaa2/_random.pyi new file mode 100644 index 0000000000000000000000000000000000000000..aa09693420cac1b1beb9b25d0fcd55063cdf8678 --- /dev/null +++ b/shared/package-files/3a/3adff278c22c8d2c706053247acfd444fd8e959ab345e3d57986826e742bfaa2/_random.pyi @@ -0,0 +1,15 @@ +import sys +from typing import Tuple + +# Actually Tuple[(int,) * 625] +_State = Tuple[int, ...] + +class Random(object): + def __init__(self, seed: object = ...) -> None: ... + def seed(self, __n: object = ...) -> None: ... + def getstate(self) -> _State: ... + def setstate(self, __state: _State) -> None: ... + def random(self) -> float: ... + def getrandbits(self, __k: int) -> int: ... + if sys.version_info < (3,): + def jumpahead(self, i: int) -> None: ... diff --git a/shared/package-files/3a/3ae1cbf694d189f6a060ebbb83a8947c540c26b7a826874e59d15b80f55c25b9/asin_cpu_dispatch.h b/shared/package-files/3a/3ae1cbf694d189f6a060ebbb83a8947c540c26b7a826874e59d15b80f55c25b9/asin_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..70012b262494c2d6edf2f941592a90a5aa572105 --- /dev/null +++ b/shared/package-files/3a/3ae1cbf694d189f6a060ebbb83a8947c540c26b7a826874e59d15b80f55c25b9/asin_cpu_dispatch.h @@ -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 asin(const at::Tensor & self); +TORCH_API at::Tensor & asin_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & asin_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & asin_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/3a/3ae4a760f1fe8c8338519454290f4d171c5df0eb751c43fb280dff6693d7dcab/test_join.py b/shared/package-files/3a/3ae4a760f1fe8c8338519454290f4d171c5df0eb751c43fb280dff6693d7dcab/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..918d5052167356b1d51018434c03e6682f828872 --- /dev/null +++ b/shared/package-files/3a/3ae4a760f1fe8c8338519454290f4d171c5df0eb751c43fb280dff6693d7dcab/test_join.py @@ -0,0 +1,380 @@ +import numpy as np +import pytest + +import pandas._testing as tm +from pandas.core.indexes.api import Index + + +class TestJoinInt64Index: + def test_join_non_unique(self): + left = Index([4, 4, 3, 3]) + + joined, lidx, ridx = left.join(left, return_indexers=True) + + exp_joined = Index([4, 4, 4, 4, 3, 3, 3, 3]) + tm.assert_index_equal(joined, exp_joined) + + exp_lidx = np.array([0, 0, 1, 1, 2, 2, 3, 3], dtype=np.intp) + tm.assert_numpy_array_equal(lidx, exp_lidx) + + exp_ridx = np.array([0, 1, 0, 1, 2, 3, 2, 3], dtype=np.intp) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + def test_join_inner(self): + index = Index(range(0, 20, 2), dtype=np.int64) + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64) + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64) + + # not monotonic + res, lidx, ridx = index.join(other, how="inner", return_indexers=True) + + # no guarantee of sortedness, so sort for comparison purposes + ind = res.argsort() + res = res.take(ind) + lidx = lidx.take(ind) + ridx = ridx.take(ind) + + eres = Index([2, 12], dtype=np.int64) + elidx = np.array([1, 6], dtype=np.intp) + eridx = np.array([4, 1], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index.join(other_mono, how="inner", return_indexers=True) + + res2 = index.intersection(other_mono) + tm.assert_index_equal(res, res2) + + elidx = np.array([1, 6], dtype=np.intp) + eridx = np.array([1, 4], dtype=np.intp) + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_left(self): + index = Index(range(0, 20, 2), dtype=np.int64) + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64) + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64) + + # not monotonic + res, lidx, ridx = index.join(other, how="left", return_indexers=True) + eres = index + eridx = np.array([-1, 4, -1, -1, -1, -1, 1, -1, -1, -1], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index.join(other_mono, how="left", return_indexers=True) + eridx = np.array([-1, 1, -1, -1, -1, -1, 4, -1, -1, -1], dtype=np.intp) + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # non-unique + idx = Index([1, 1, 2, 5]) + idx2 = Index([1, 2, 5, 7, 9]) + res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True) + eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2 + eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_right(self): + index = Index(range(0, 20, 2), dtype=np.int64) + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64) + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64) + + # not monotonic + res, lidx, ridx = index.join(other, how="right", return_indexers=True) + eres = other + elidx = np.array([-1, 6, -1, -1, 1, -1], dtype=np.intp) + + assert isinstance(other, Index) and other.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + assert ridx is None + + # monotonic + res, lidx, ridx = index.join(other_mono, how="right", return_indexers=True) + eres = other_mono + elidx = np.array([-1, 1, -1, -1, 6, -1], dtype=np.intp) + assert isinstance(other, Index) and other.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + assert ridx is None + + # non-unique + idx = Index([1, 1, 2, 5]) + idx2 = Index([1, 2, 5, 7, 9]) + res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True) + eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2 + elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_non_int_index(self): + index = Index(range(0, 20, 2), dtype=np.int64) + other = Index([3, 6, 7, 8, 10], dtype=object) + + outer = index.join(other, how="outer") + outer2 = other.join(index, how="outer") + expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18]) + tm.assert_index_equal(outer, outer2) + tm.assert_index_equal(outer, expected) + + inner = index.join(other, how="inner") + inner2 = other.join(index, how="inner") + expected = Index([6, 8, 10]) + tm.assert_index_equal(inner, inner2) + tm.assert_index_equal(inner, expected) + + left = index.join(other, how="left") + tm.assert_index_equal(left, index.astype(object)) + + left2 = other.join(index, how="left") + tm.assert_index_equal(left2, other) + + right = index.join(other, how="right") + tm.assert_index_equal(right, other) + + right2 = other.join(index, how="right") + tm.assert_index_equal(right2, index.astype(object)) + + def test_join_outer(self): + index = Index(range(0, 20, 2), dtype=np.int64) + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64) + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64) + + # not monotonic + # guarantee of sortedness + res, lidx, ridx = index.join(other, how="outer", return_indexers=True) + noidx_res = index.join(other, how="outer") + tm.assert_index_equal(res, noidx_res) + + eres = Index([0, 1, 2, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 25], dtype=np.int64) + elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp) + eridx = np.array( + [-1, 3, 4, -1, 5, -1, 0, -1, -1, 1, -1, -1, -1, 2], dtype=np.intp + ) + + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index.join(other_mono, how="outer", return_indexers=True) + noidx_res = index.join(other_mono, how="outer") + tm.assert_index_equal(res, noidx_res) + + elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp) + eridx = np.array( + [-1, 0, 1, -1, 2, -1, 3, -1, -1, 4, -1, -1, -1, 5], dtype=np.intp + ) + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + +class TestJoinUInt64Index: + @pytest.fixture + def index_large(self): + # large values used in TestUInt64Index where no compat needed with int64/float64 + large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25] + return Index(large, dtype=np.uint64) + + def test_join_inner(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + res, lidx, ridx = index_large.join(other, how="inner", return_indexers=True) + + # no guarantee of sortedness, so sort for comparison purposes + ind = res.argsort() + res = res.take(ind) + lidx = lidx.take(ind) + ridx = ridx.take(ind) + + eres = Index(2**63 + np.array([10, 25], dtype="uint64")) + elidx = np.array([1, 4], dtype=np.intp) + eridx = np.array([5, 2], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index_large.join( + other_mono, how="inner", return_indexers=True + ) + + res2 = index_large.intersection(other_mono) + tm.assert_index_equal(res, res2) + + elidx = np.array([1, 4], dtype=np.intp) + eridx = np.array([3, 5], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_left(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + res, lidx, ridx = index_large.join(other, how="left", return_indexers=True) + eres = index_large + eridx = np.array([-1, 5, -1, -1, 2], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index_large.join(other_mono, how="left", return_indexers=True) + eridx = np.array([-1, 3, -1, -1, 5], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # non-unique + idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64")) + idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64")) + res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True) + + # 1 is in idx2, so it should be x2 + eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64")) + eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_right(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + res, lidx, ridx = index_large.join(other, how="right", return_indexers=True) + eres = other + elidx = np.array([-1, -1, 4, -1, -1, 1], dtype=np.intp) + + tm.assert_numpy_array_equal(lidx, elidx) + assert isinstance(other, Index) and other.dtype == np.uint64 + tm.assert_index_equal(res, eres) + assert ridx is None + + # monotonic + res, lidx, ridx = index_large.join( + other_mono, how="right", return_indexers=True + ) + eres = other_mono + elidx = np.array([-1, -1, -1, 1, -1, 4], dtype=np.intp) + + assert isinstance(other, Index) and other.dtype == np.uint64 + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_index_equal(res, eres) + assert ridx is None + + # non-unique + idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64")) + idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64")) + res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True) + + # 1 is in idx2, so it should be x2 + eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64")) + elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_non_int_index(self, index_large): + other = Index( + 2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object + ) + + outer = index_large.join(other, how="outer") + outer2 = other.join(index_large, how="outer") + expected = Index( + 2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64") + ) + tm.assert_index_equal(outer, outer2) + tm.assert_index_equal(outer, expected) + + inner = index_large.join(other, how="inner") + inner2 = other.join(index_large, how="inner") + expected = Index(2**63 + np.array([10, 20], dtype="uint64")) + tm.assert_index_equal(inner, inner2) + tm.assert_index_equal(inner, expected) + + left = index_large.join(other, how="left") + tm.assert_index_equal(left, index_large.astype(object)) + + left2 = other.join(index_large, how="left") + tm.assert_index_equal(left2, other) + + right = index_large.join(other, how="right") + tm.assert_index_equal(right, other) + + right2 = other.join(index_large, how="right") + tm.assert_index_equal(right2, index_large.astype(object)) + + def test_join_outer(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + # guarantee of sortedness + res, lidx, ridx = index_large.join(other, how="outer", return_indexers=True) + noidx_res = index_large.join(other, how="outer") + tm.assert_index_equal(res, noidx_res) + + eres = Index( + 2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64") + ) + elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp) + eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index_large.join( + other_mono, how="outer", return_indexers=True + ) + noidx_res = index_large.join(other_mono, how="outer") + tm.assert_index_equal(res, noidx_res) + + elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp) + eridx = np.array([-1, 0, 1, 2, 3, 4, -1, -1, 5], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) diff --git a/shared/package-files/3a/3ae95d0bb3b2f729f8d9addc44f8a4af13cdb8513eda23bcc269b07a3f36a433/nll_loss_nd.h b/shared/package-files/3a/3ae95d0bb3b2f729f8d9addc44f8a4af13cdb8513eda23bcc269b07a3f36a433/nll_loss_nd.h new file mode 100644 index 0000000000000000000000000000000000000000..152564027803e09cccdf4917684957a4a5de6803 --- /dev/null +++ b/shared/package-files/3a/3ae95d0bb3b2f729f8d9addc44f8a4af13cdb8513eda23bcc269b07a3f36a433/nll_loss_nd.h @@ -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::nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor +inline at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean, int64_t ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); +} +namespace symint { + template ::value>> + at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean, int64_t ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); + } +} + +// aten::nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor +inline at::Tensor nll_loss_nd_symint(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); +} +namespace symint { + template ::value>> + at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); + } +} + +} diff --git a/shared/package-files/3a/3aea6dc795a3012a8ffa32c3b07f20988bc183cffb6703c9f7843487be3c8bf7/linux-lat b/shared/package-files/3a/3aea6dc795a3012a8ffa32c3b07f20988bc183cffb6703c9f7843487be3c8bf7/linux-lat new file mode 100644 index 0000000000000000000000000000000000000000..80804c82d39a901ac28c04214193d626c5a9f0ed Binary files /dev/null and b/shared/package-files/3a/3aea6dc795a3012a8ffa32c3b07f20988bc183cffb6703c9f7843487be3c8bf7/linux-lat differ diff --git a/shared/package-files/3a/3aedaf3eb49769282daef1eaedfd4fa1c31fe5eebeff67fe2307c89dc2e2fd80/utf_16_le.py b/shared/package-files/3a/3aedaf3eb49769282daef1eaedfd4fa1c31fe5eebeff67fe2307c89dc2e2fd80/utf_16_le.py new file mode 100644 index 0000000000000000000000000000000000000000..ec454142eedf251e31eab481a1cbea6424273a0a --- /dev/null +++ b/shared/package-files/3a/3aedaf3eb49769282daef1eaedfd4fa1c31fe5eebeff67fe2307c89dc2e2fd80/utf_16_le.py @@ -0,0 +1,42 @@ +""" Python 'utf-16-le' Codec + + +Written by Marc-Andre Lemburg (mal@lemburg.com). + +(c) Copyright CNRI, All Rights Reserved. NO WARRANTY. + +""" +import codecs + +### Codec APIs + +encode = codecs.utf_16_le_encode + +def decode(input, errors='strict'): + return codecs.utf_16_le_decode(input, errors, True) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.utf_16_le_encode(input, self.errors)[0] + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + _buffer_decode = codecs.utf_16_le_decode + +class StreamWriter(codecs.StreamWriter): + encode = codecs.utf_16_le_encode + +class StreamReader(codecs.StreamReader): + decode = codecs.utf_16_le_decode + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='utf-16-le', + encode=encode, + decode=decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) diff --git a/shared/package-files/3a/3aee0e9dcad968d5c2582c90fadd526a259608393f6e8111177c05c8325cfbaa/combinations_ops.h b/shared/package-files/3a/3aee0e9dcad968d5c2582c90fadd526a259608393f6e8111177c05c8325cfbaa/combinations_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..742b8de204b24bd59791f571744bd30615a5b3be --- /dev/null +++ b/shared/package-files/3a/3aee0e9dcad968d5c2582c90fadd526a259608393f6e8111177c05c8325cfbaa/combinations_ops.h @@ -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 combinations { + using schema = at::Tensor (const at::Tensor &, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::combinations") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "combinations(Tensor self, int r=2, bool with_replacement=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t r, bool with_replacement); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t r, bool with_replacement); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3aef0d8f111e28c51e9c4c5daa01feee28eb79cf9b90a23c43fdb549c2828f33/meson.build b/shared/package-files/3a/3aef0d8f111e28c51e9c4c5daa01feee28eb79cf9b90a23c43fdb549c2828f33/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..75b67a46981f4e394b73332980b4088087d6bc23 --- /dev/null +++ b/shared/package-files/3a/3aef0d8f111e28c51e9c4c5daa01feee28eb79cf9b90a23c43fdb549c2828f33/meson.build @@ -0,0 +1,14 @@ +py.extension_module( + '_online_lda_fast', + [cython_gen.process('_online_lda_fast.pyx'), utils_cython_tree], + subdir: 'sklearn/decomposition', + install: true +) + +py.extension_module( + '_cdnmf_fast', + cython_gen.process('_cdnmf_fast.pyx'), + dependencies: [np_dep], + subdir: 'sklearn/decomposition', + install: true +) diff --git a/shared/package-files/3a/3aef887821726e26d9bb27288a7e60510cf30be8b2e726a76459abaaf746b7a4/test_random_sequence.py b/shared/package-files/3a/3aef887821726e26d9bb27288a7e60510cf30be8b2e726a76459abaaf746b7a4/test_random_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1b95799f75aa668801a5af482bee36fdb8d837 --- /dev/null +++ b/shared/package-files/3a/3aef887821726e26d9bb27288a7e60510cf30be8b2e726a76459abaaf746b7a4/test_random_sequence.py @@ -0,0 +1,38 @@ +import pytest + +from networkx.utils import ( + powerlaw_sequence, + random_weighted_sample, + weighted_choice, + zipf_rv, +) + + +def test_degree_sequences(): + seq = powerlaw_sequence(10, seed=1) + seq = powerlaw_sequence(10) + assert len(seq) == 10 + + +def test_zipf_rv(): + r = zipf_rv(2.3, xmin=2, seed=1) + r = zipf_rv(2.3, 2, 1) + r = zipf_rv(2.3) + assert type(r), int + pytest.raises(ValueError, zipf_rv, 0.5) + pytest.raises(ValueError, zipf_rv, 2, xmin=0) + + +def test_random_weighted_sample(): + mapping = {"a": 10, "b": 20} + s = random_weighted_sample(mapping, 2, seed=1) + s = random_weighted_sample(mapping, 2) + assert sorted(s) == sorted(mapping.keys()) + pytest.raises(ValueError, random_weighted_sample, mapping, 3) + + +def test_random_weighted_choice(): + mapping = {"a": 10, "b": 0} + c = weighted_choice(mapping, seed=1) + c = weighted_choice(mapping) + assert c == "a" diff --git a/shared/package-files/3a/3aef8fbd28f9fb60a2e58fdb1fc392a17adb6d3b7cb313b9a4945a800ce56147/version.py b/shared/package-files/3a/3aef8fbd28f9fb60a2e58fdb1fc392a17adb6d3b7cb313b9a4945a800ce56147/version.py new file mode 100644 index 0000000000000000000000000000000000000000..112ac0cca01bb2df99cd1dbd624c58c6bf6686a2 --- /dev/null +++ b/shared/package-files/3a/3aef8fbd28f9fb60a2e58fdb1fc392a17adb6d3b7cb313b9a4945a800ce56147/version.py @@ -0,0 +1,6 @@ +""" +Expose version +""" + +__version__ = "2.0.4" +VERSION = __version__.split('.') diff --git a/shared/package-files/3a/3af14298ca88ef80d6220a37d94579e5d3f59f3bc5bd8052c987262897acf692/_mvt.py b/shared/package-files/3a/3af14298ca88ef80d6220a37d94579e5d3f59f3bc5bd8052c987262897acf692/_mvt.py new file mode 100644 index 0000000000000000000000000000000000000000..c346d0daded4b6e734718742cc8950b84ed333f7 --- /dev/null +++ b/shared/package-files/3a/3af14298ca88ef80d6220a37d94579e5d3f59f3bc5bd8052c987262897acf692/_mvt.py @@ -0,0 +1,171 @@ +import math +import numpy as np +from scipy import special +from scipy.stats._qmc import primes_from_2_to + + +def _primes(n): + # Defined to facilitate comparison between translation and source + # In Matlab, primes(10.5) -> first four primes, primes(11.5) -> first five + return primes_from_2_to(math.ceil(n)) + + +def _gaminv(a, b): + # Defined to facilitate comparison between translation and source + # Matlab's `gaminv` is like `special.gammaincinv` but args are reversed + return special.gammaincinv(b, a) + + +def _qsimvtv(m, nu, sigma, a, b, rng): + """Estimates the multivariate t CDF using randomized QMC + + Parameters + ---------- + m : int + The number of points + nu : float + Degrees of freedom + sigma : ndarray + A 2D positive semidefinite covariance matrix + a : ndarray + Lower integration limits + b : ndarray + Upper integration limits. + rng : Generator + Pseudorandom number generator + + Returns + ------- + p : float + The estimated CDF. + e : float + An absolute error estimate. + + """ + # _qsimvtv is a Python translation of the Matlab function qsimvtv, + # semicolons and all. + # + # This function uses an algorithm given in the paper + # "Comparison of Methods for the Numerical Computation of + # Multivariate t Probabilities", in + # J. of Computational and Graphical Stat., 11(2002), pp. 950-971, by + # Alan Genz and Frank Bretz + # + # The primary references for the numerical integration are + # "On a Number-Theoretical Integration Method" + # H. Niederreiter, Aequationes Mathematicae, 8(1972), pp. 304-11. + # and + # "Randomization of Number Theoretic Methods for Multiple Integration" + # R. Cranley & T.N.L. Patterson, SIAM J Numer Anal, 13(1976), pp. 904-14. + # + # Alan Genz is the author of this function and following Matlab functions. + # Alan Genz, WSU Math, PO Box 643113, Pullman, WA 99164-3113 + # Email : alangenz@wsu.edu + # + # Copyright (C) 2013, Alan Genz, All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided 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 contributor name(s) 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 USE + # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + # Initialization + sn = max(1, math.sqrt(nu)); ch, az, bz = _chlrps(sigma, a/sn, b/sn) + n = len(sigma); N = 10; P = math.ceil(m/N); on = np.ones(P); p = 0; e = 0 + ps = np.sqrt(_primes(5*n*math.log(n+4)/4)); q = ps[:, np.newaxis] # Richtmyer gens. + + # Randomization loop for ns samples + c = None; dc = None + for S in range(N): + vp = on.copy(); s = np.zeros((n, P)) + for i in range(n): + x = np.abs(2*np.mod(q[i]*np.arange(1, P+1) + rng.random(), 1)-1) # periodizing transform + if i == 0: + r = on + if nu > 0: + r = np.sqrt(2*_gaminv(x, nu/2)) + else: + y = _Phinv(c + x*dc) + s[i:] += ch[i:, i-1:i] * y + si = s[i, :]; c = on.copy(); ai = az[i]*r - si; d = on.copy(); bi = bz[i]*r - si + c[ai <= -9] = 0; tl = abs(ai) < 9; c[tl] = _Phi(ai[tl]) + d[bi <= -9] = 0; tl = abs(bi) < 9; d[tl] = _Phi(bi[tl]) + dc = d - c; vp = vp * dc + d = (np.mean(vp) - p)/(S + 1); p = p + d; e = (S - 1)*e/(S + 1) + d**2 + e = math.sqrt(e) # error estimate is 3 times std error with N samples. + return p, e + + +# Standard statistical normal distribution functions +def _Phi(z): + return special.ndtr(z) + + +def _Phinv(p): + return special.ndtri(p) + + +def _chlrps(R, a, b): + """ + Computes permuted and scaled lower Cholesky factor c for R which may be + singular, also permuting and scaling integration limit vectors a and b. + """ + ep = 1e-10 # singularity tolerance + eps = np.finfo(R.dtype).eps + + n = len(R); c = R.copy(); ap = a.copy(); bp = b.copy(); d = np.sqrt(np.maximum(np.diag(c), 0)) + for i in range(n): + if d[i] > 0: + c[:, i] /= d[i]; c[i, :] /= d[i] + ap[i] /= d[i]; bp[i] /= d[i] + y = np.zeros((n, 1)); sqtp = math.sqrt(2*math.pi) + + for k in range(n): + im = k; ckk = 0; dem = 1; s = 0 + for i in range(k, n): + if c[i, i] > eps: + cii = math.sqrt(max(c[i, i], 0)) + if i > 0: s = c[i, :k] @ y[:k] + ai = (ap[i]-s)/cii; bi = (bp[i]-s)/cii; de = _Phi(bi)-_Phi(ai) + if de <= dem: + ckk = cii; dem = de; am = ai; bm = bi; im = i + if im > k: + ap[[im, k]] = ap[[k, im]]; bp[[im, k]] = bp[[k, im]]; c[im, im] = c[k, k] + t = c[im, :k].copy(); c[im, :k] = c[k, :k]; c[k, :k] = t + t = c[im+1:, im].copy(); c[im+1:, im] = c[im+1:, k]; c[im+1:, k] = t + t = c[k+1:im, k].copy(); c[k+1:im, k] = c[im, k+1:im].T; c[im, k+1:im] = t.T + if ckk > ep*(k+1): + c[k, k] = ckk; c[k, k+1:] = 0 + for i in range(k+1, n): + c[i, k] = c[i, k]/ckk; c[i, k+1:i+1] = c[i, k+1:i+1] - c[i, k]*c[k+1:i+1, k].T + if abs(dem) > ep: + y[k] = (np.exp(-am**2/2) - np.exp(-bm**2/2)) / (sqtp*dem) + else: + y[k] = (am + bm) / 2 + if am < -10: + y[k] = bm + elif bm > 10: + y[k] = am + c[k, :k+1] /= ckk; ap[k] /= ckk; bp[k] /= ckk + else: + c[k:, k] = 0; y[k] = (ap[k] + bp[k])/2 + pass + return c, ap, bp diff --git a/shared/package-files/3a/3af23a29191caf7ce2f0e9548bf3d2b913bc81683bbe31e465fb76002ca7b97f/special_modified_bessel_i0_meta.h b/shared/package-files/3a/3af23a29191caf7ce2f0e9548bf3d2b913bc81683bbe31e465fb76002ca7b97f/special_modified_bessel_i0_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..da22683ca6c330bb7a8b9c030671075e5f7071e8 --- /dev/null +++ b/shared/package-files/3a/3af23a29191caf7ce2f0e9548bf3d2b913bc81683bbe31e465fb76002ca7b97f/special_modified_bessel_i0_meta.h @@ -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_modified_bessel_i0 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3af5cc6bab5ec7d1a8836c3368766aa0c7750d81c4a74dbe51baf3d9ccd75b21/metaestimators.py b/shared/package-files/3a/3af5cc6bab5ec7d1a8836c3368766aa0c7750d81c4a74dbe51baf3d9ccd75b21/metaestimators.py new file mode 100644 index 0000000000000000000000000000000000000000..dced64f2fe3926623d9bc5a874e1036602d54548 --- /dev/null +++ b/shared/package-files/3a/3af5cc6bab5ec7d1a8836c3368766aa0c7750d81c4a74dbe51baf3d9ccd75b21/metaestimators.py @@ -0,0 +1,163 @@ +"""Utilities for meta-estimators.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from abc import ABCMeta, abstractmethod +from contextlib import suppress +from typing import Any, List + +import numpy as np + +from ..base import BaseEstimator +from ..utils import _safe_indexing +from ..utils._tags import get_tags +from ._available_if import available_if + +__all__ = ["available_if"] + + +class _BaseComposition(BaseEstimator, metaclass=ABCMeta): + """Handles parameter management for classifiers composed of named estimators.""" + + steps: List[Any] + + @abstractmethod + def __init__(self): + pass + + def _get_params(self, attr, deep=True): + out = super().get_params(deep=deep) + if not deep: + return out + + estimators = getattr(self, attr) + try: + out.update(estimators) + except (TypeError, ValueError): + # Ignore TypeError for cases where estimators is not a list of + # (name, estimator) and ignore ValueError when the list is not + # formatted correctly. This is to prevent errors when calling + # `set_params`. `BaseEstimator.set_params` calls `get_params` which + # can error for invalid values for `estimators`. + return out + + for name, estimator in estimators: + if hasattr(estimator, "get_params"): + for key, value in estimator.get_params(deep=True).items(): + out["%s__%s" % (name, key)] = value + return out + + def _set_params(self, attr, **params): + # Ensure strict ordering of parameter setting: + # 1. All steps + if attr in params: + setattr(self, attr, params.pop(attr)) + # 2. Replace items with estimators in params + items = getattr(self, attr) + if isinstance(items, list) and items: + # Get item names used to identify valid names in params + # `zip` raises a TypeError when `items` does not contains + # elements of length 2 + with suppress(TypeError): + item_names, _ = zip(*items) + for name in list(params.keys()): + if "__" not in name and name in item_names: + self._replace_estimator(attr, name, params.pop(name)) + + # 3. Step parameters and other initialisation arguments + super().set_params(**params) + return self + + def _replace_estimator(self, attr, name, new_val): + # assumes `name` is a valid estimator name + new_estimators = list(getattr(self, attr)) + for i, (estimator_name, _) in enumerate(new_estimators): + if estimator_name == name: + new_estimators[i] = (name, new_val) + break + setattr(self, attr, new_estimators) + + def _validate_names(self, names): + if len(set(names)) != len(names): + raise ValueError("Names provided are not unique: {0!r}".format(list(names))) + invalid_names = set(names).intersection(self.get_params(deep=False)) + if invalid_names: + raise ValueError( + "Estimator names conflict with constructor arguments: {0!r}".format( + sorted(invalid_names) + ) + ) + invalid_names = [name for name in names if "__" in name] + if invalid_names: + raise ValueError( + "Estimator names must not contain __: got {0!r}".format(invalid_names) + ) + + +def _safe_split(estimator, X, y, indices, train_indices=None): + """Create subset of dataset and properly handle kernels. + + Slice X, y according to indices for cross-validation, but take care of + precomputed kernel-matrices or pairwise affinities / distances. + + If ``estimator._pairwise is True``, X needs to be square and + we slice rows and columns. If ``train_indices`` is not None, + we slice rows using ``indices`` (assumed the test set) and columns + using ``train_indices``, indicating the training set. + + Labels y will always be indexed only along the first axis. + + Parameters + ---------- + estimator : object + Estimator to determine whether we should slice only rows or rows and + columns. + + X : array-like, sparse matrix or iterable + Data to be indexed. If ``estimator._pairwise is True``, + this needs to be a square array-like or sparse matrix. + + y : array-like, sparse matrix or iterable + Targets to be indexed. + + indices : array of int + Rows to select from X and y. + If ``estimator._pairwise is True`` and ``train_indices is None`` + then ``indices`` will also be used to slice columns. + + train_indices : array of int or None, default=None + If ``estimator._pairwise is True`` and ``train_indices is not None``, + then ``train_indices`` will be use to slice the columns of X. + + Returns + ------- + X_subset : array-like, sparse matrix or list + Indexed data. + + y_subset : array-like, sparse matrix or list + Indexed targets. + + """ + if get_tags(estimator).input_tags.pairwise: + if not hasattr(X, "shape"): + raise ValueError( + "Precomputed kernels or affinity matrices have " + "to be passed as arrays or sparse matrices." + ) + # X is a precomputed square kernel matrix + if X.shape[0] != X.shape[1]: + raise ValueError("X should be a square kernel matrix") + if train_indices is None: + X_subset = X[np.ix_(indices, indices)] + else: + X_subset = X[np.ix_(indices, train_indices)] + else: + X_subset = _safe_indexing(X, indices) + + if y is not None: + y_subset = _safe_indexing(y, indices) + else: + y_subset = None + + return X_subset, y_subset diff --git a/shared/package-files/3a/3af8ac59ddc4e8217badd1511afe3a1d639f265c876a53084ede6224fcc4f0b2/_page_trend_test.py b/shared/package-files/3a/3af8ac59ddc4e8217badd1511afe3a1d639f265c876a53084ede6224fcc4f0b2/_page_trend_test.py new file mode 100644 index 0000000000000000000000000000000000000000..87a4d0d17c07ce609cc575fc7dc61af75d2b9c51 --- /dev/null +++ b/shared/package-files/3a/3af8ac59ddc4e8217badd1511afe3a1d639f265c876a53084ede6224fcc4f0b2/_page_trend_test.py @@ -0,0 +1,479 @@ +from itertools import permutations +import numpy as np +import math +from ._continuous_distns import norm +import scipy.stats +from dataclasses import dataclass + + +@dataclass +class PageTrendTestResult: + statistic: float + pvalue: float + method: str + + +def page_trend_test(data, ranked=False, predicted_ranks=None, method='auto'): + r""" + Perform Page's Test, a measure of trend in observations between treatments. + + Page's Test (also known as Page's :math:`L` test) is useful when: + + * there are :math:`n \geq 3` treatments, + * :math:`m \geq 2` subjects are observed for each treatment, and + * the observations are hypothesized to have a particular order. + + Specifically, the test considers the null hypothesis that + + .. math:: + + m_1 = m_2 = m_3 \cdots = m_n, + + where :math:`m_j` is the mean of the observed quantity under treatment + :math:`j`, against the alternative hypothesis that + + .. math:: + + m_1 \leq m_2 \leq m_3 \leq \cdots \leq m_n, + + where at least one inequality is strict. + + As noted by [4]_, Page's :math:`L` test has greater statistical power than + the Friedman test against the alternative that there is a difference in + trend, as Friedman's test only considers a difference in the means of the + observations without considering their order. Whereas Spearman :math:`\rho` + considers the correlation between the ranked observations of two variables + (e.g. the airspeed velocity of a swallow vs. the weight of the coconut it + carries), Page's :math:`L` is concerned with a trend in an observation + (e.g. the airspeed velocity of a swallow) across several distinct + treatments (e.g. carrying each of five coconuts of different weight) even + as the observation is repeated with multiple subjects (e.g. one European + swallow and one African swallow). + + Parameters + ---------- + data : array-like + A :math:`m \times n` array; the element in row :math:`i` and + column :math:`j` is the observation corresponding with subject + :math:`i` and treatment :math:`j`. By default, the columns are + assumed to be arranged in order of increasing predicted mean. + + ranked : boolean, optional + By default, `data` is assumed to be observations rather than ranks; + it will be ranked with `scipy.stats.rankdata` along ``axis=1``. If + `data` is provided in the form of ranks, pass argument ``True``. + + predicted_ranks : array-like, optional + The predicted ranks of the column means. If not specified, + the columns are assumed to be arranged in order of increasing + predicted mean, so the default `predicted_ranks` are + :math:`[1, 2, \dots, n-1, n]`. + + method : {'auto', 'asymptotic', 'exact'}, optional + Selects the method used to calculate the *p*-value. The following + options are available. + + * 'auto': selects between 'exact' and 'asymptotic' to + achieve reasonably accurate results in reasonable time (default) + * 'asymptotic': compares the standardized test statistic against + the normal distribution + * 'exact': computes the exact *p*-value by comparing the observed + :math:`L` statistic against those realized by all possible + permutations of ranks (under the null hypothesis that each + permutation is equally likely) + + Returns + ------- + res : PageTrendTestResult + An object containing attributes: + + statistic : float + Page's :math:`L` test statistic. + pvalue : float + The associated *p*-value + method : {'asymptotic', 'exact'} + The method used to compute the *p*-value + + See Also + -------- + rankdata, friedmanchisquare, spearmanr + + Notes + ----- + As noted in [1]_, "the :math:`n` 'treatments' could just as well represent + :math:`n` objects or events or performances or persons or trials ranked." + Similarly, the :math:`m` 'subjects' could equally stand for :math:`m` + "groupings by ability or some other control variable, or judges doing + the ranking, or random replications of some other sort." + + The procedure for calculating the :math:`L` statistic, adapted from + [1]_, is: + + 1. "Predetermine with careful logic the appropriate hypotheses + concerning the predicted ordering of the experimental results. + If no reasonable basis for ordering any treatments is known, the + :math:`L` test is not appropriate." + 2. "As in other experiments, determine at what level of confidence + you will reject the null hypothesis that there is no agreement of + experimental results with the monotonic hypothesis." + 3. "Cast the experimental material into a two-way table of :math:`n` + columns (treatments, objects ranked, conditions) and :math:`m` + rows (subjects, replication groups, levels of control variables)." + 4. "When experimental observations are recorded, rank them across each + row", e.g. ``ranks = scipy.stats.rankdata(data, axis=1)``. + 5. "Add the ranks in each column", e.g. + ``colsums = np.sum(ranks, axis=0)``. + 6. "Multiply each sum of ranks by the predicted rank for that same + column", e.g. ``products = predicted_ranks * colsums``. + 7. "Sum all such products", e.g. ``L = products.sum()``. + + [1]_ continues by suggesting use of the standardized statistic + + .. math:: + + \chi_L^2 = \frac{\left[12L-3mn(n+1)^2\right]^2}{mn^2(n^2-1)(n+1)} + + "which is distributed approximately as chi-square with 1 degree of + freedom. The ordinary use of :math:`\chi^2` tables would be + equivalent to a two-sided test of agreement. If a one-sided test + is desired, *as will almost always be the case*, the probability + discovered in the chi-square table should be *halved*." + + However, this standardized statistic does not distinguish between the + observed values being well correlated with the predicted ranks and being + _anti_-correlated with the predicted ranks. Instead, we follow [2]_ + and calculate the standardized statistic + + .. math:: + + \Lambda = \frac{L - E_0}{\sqrt{V_0}}, + + where :math:`E_0 = \frac{1}{4} mn(n+1)^2` and + :math:`V_0 = \frac{1}{144} mn^2(n+1)(n^2-1)`, "which is asymptotically + normal under the null hypothesis". + + The *p*-value for ``method='exact'`` is generated by comparing the observed + value of :math:`L` against the :math:`L` values generated for all + :math:`(n!)^m` possible permutations of ranks. The calculation is performed + using the recursive method of [5]. + + The *p*-values are not adjusted for the possibility of ties. When + ties are present, the reported ``'exact'`` *p*-values may be somewhat + larger (i.e. more conservative) than the true *p*-value [2]_. The + ``'asymptotic'``` *p*-values, however, tend to be smaller (i.e. less + conservative) than the ``'exact'`` *p*-values. + + References + ---------- + .. [1] Ellis Batten Page, "Ordered hypotheses for multiple treatments: + a significant test for linear ranks", *Journal of the American + Statistical Association* 58(301), p. 216--230, 1963. + + .. [2] Markus Neuhauser, *Nonparametric Statistical Test: A computational + approach*, CRC Press, p. 150--152, 2012. + + .. [3] Statext LLC, "Page's L Trend Test - Easy Statistics", *Statext - + Statistics Study*, https://www.statext.com/practice/PageTrendTest03.php, + Accessed July 12, 2020. + + .. [4] "Page's Trend Test", *Wikipedia*, WikimediaFoundation, + https://en.wikipedia.org/wiki/Page%27s_trend_test, + Accessed July 12, 2020. + + .. [5] Robert E. Odeh, "The exact distribution of Page's L-statistic in + the two-way layout", *Communications in Statistics - Simulation and + Computation*, 6(1), p. 49--61, 1977. + + Examples + -------- + We use the example from [3]_: 10 students are asked to rate three + teaching methods - tutorial, lecture, and seminar - on a scale of 1-5, + with 1 being the lowest and 5 being the highest. We have decided that + a confidence level of 99% is required to reject the null hypothesis in + favor of our alternative: that the seminar will have the highest ratings + and the tutorial will have the lowest. Initially, the data have been + tabulated with each row representing an individual student's ratings of + the three methods in the following order: tutorial, lecture, seminar. + + >>> table = [[3, 4, 3], + ... [2, 2, 4], + ... [3, 3, 5], + ... [1, 3, 2], + ... [2, 3, 2], + ... [2, 4, 5], + ... [1, 2, 4], + ... [3, 4, 4], + ... [2, 4, 5], + ... [1, 3, 4]] + + Because the tutorial is hypothesized to have the lowest ratings, the + column corresponding with tutorial rankings should be first; the seminar + is hypothesized to have the highest ratings, so its column should be last. + Since the columns are already arranged in this order of increasing + predicted mean, we can pass the table directly into `page_trend_test`. + + >>> from scipy.stats import page_trend_test + >>> res = page_trend_test(table) + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822, + method='exact') + + This *p*-value indicates that there is a 0.1819% chance that + the :math:`L` statistic would reach such an extreme value under the null + hypothesis. Because 0.1819% is less than 1%, we have evidence to reject + the null hypothesis in favor of our alternative at a 99% confidence level. + + The value of the :math:`L` statistic is 133.5. To check this manually, + we rank the data such that high scores correspond with high ranks, settling + ties with an average rank: + + >>> from scipy.stats import rankdata + >>> ranks = rankdata(table, axis=1) + >>> ranks + array([[1.5, 3. , 1.5], + [1.5, 1.5, 3. ], + [1.5, 1.5, 3. ], + [1. , 3. , 2. ], + [1.5, 3. , 1.5], + [1. , 2. , 3. ], + [1. , 2. , 3. ], + [1. , 2.5, 2.5], + [1. , 2. , 3. ], + [1. , 2. , 3. ]]) + + We add the ranks within each column, multiply the sums by the + predicted ranks, and sum the products. + + >>> import numpy as np + >>> m, n = ranks.shape + >>> predicted_ranks = np.arange(1, n+1) + >>> L = (predicted_ranks * np.sum(ranks, axis=0)).sum() + >>> res.statistic == L + True + + As presented in [3]_, the asymptotic approximation of the *p*-value is the + survival function of the normal distribution evaluated at the standardized + test statistic: + + >>> from scipy.stats import norm + >>> E0 = (m*n*(n+1)**2)/4 + >>> V0 = (m*n**2*(n+1)*(n**2-1))/144 + >>> Lambda = (L-E0)/np.sqrt(V0) + >>> p = norm.sf(Lambda) + >>> p + 0.0012693433690751756 + + This does not precisely match the *p*-value reported by `page_trend_test` + above. The asymptotic distribution is not very accurate, nor conservative, + for :math:`m \leq 12` and :math:`n \leq 8`, so `page_trend_test` chose to + use ``method='exact'`` based on the dimensions of the table and the + recommendations in Page's original paper [1]_. To override + `page_trend_test`'s choice, provide the `method` argument. + + >>> res = page_trend_test(table, method="asymptotic") + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0012693433690751756, + method='asymptotic') + + If the data are already ranked, we can pass in the ``ranks`` instead of + the ``table`` to save computation time. + + >>> res = page_trend_test(ranks, # ranks of data + ... ranked=True, # data is already ranked + ... ) + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822, + method='exact') + + Suppose the raw data had been tabulated in an order different from the + order of predicted means, say lecture, seminar, tutorial. + + >>> table = np.asarray(table)[:, [1, 2, 0]] + + Since the arrangement of this table is not consistent with the assumed + ordering, we can either rearrange the table or provide the + `predicted_ranks`. Remembering that the lecture is predicted + to have the middle rank, the seminar the highest, and tutorial the lowest, + we pass: + + >>> res = page_trend_test(table, # data as originally tabulated + ... predicted_ranks=[2, 3, 1], # our predicted order + ... ) + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822, + method='exact') + + """ + + # Possible values of the method parameter and the corresponding function + # used to evaluate the p value + methods = {"asymptotic": _l_p_asymptotic, + "exact": _l_p_exact, + "auto": None} + if method not in methods: + raise ValueError(f"`method` must be in {set(methods)}") + + ranks = np.asarray(data) + if ranks.ndim != 2: # TODO: relax this to accept 3d arrays? + raise ValueError("`data` must be a 2d array.") + + m, n = ranks.shape + if m < 2 or n < 3: + raise ValueError("Page's L is only appropriate for data with two " + "or more rows and three or more columns.") + + if np.any(np.isnan(data)): + raise ValueError("`data` contains NaNs, which cannot be ranked " + "meaningfully") + + # ensure NumPy array and rank the data if it's not already ranked + if ranked: + # Only a basic check on whether data is ranked. Checking that the data + # is properly ranked could take as much time as ranking it. + if not (ranks.min() >= 1 and ranks.max() <= ranks.shape[1]): + raise ValueError("`data` is not properly ranked. Rank the data or " + "pass `ranked=False`.") + else: + ranks = scipy.stats.rankdata(data, axis=-1) + + # generate predicted ranks if not provided, ensure valid NumPy array + if predicted_ranks is None: + predicted_ranks = np.arange(1, n+1) + else: + predicted_ranks = np.asarray(predicted_ranks) + if (predicted_ranks.ndim < 1 or + (set(predicted_ranks) != set(range(1, n+1)) or + len(predicted_ranks) != n)): + raise ValueError(f"`predicted_ranks` must include each integer " + f"from 1 to {n} (the number of columns in " + f"`data`) exactly once.") + + if not isinstance(ranked, bool): + raise TypeError("`ranked` must be boolean.") + + # Calculate the L statistic + L = _l_vectorized(ranks, predicted_ranks) + + # Calculate the p-value + if method == "auto": + method = _choose_method(ranks) + p_fun = methods[method] # get the function corresponding with the method + p = p_fun(L, m, n) + + page_result = PageTrendTestResult(statistic=L, pvalue=p, method=method) + return page_result + + +def _choose_method(ranks): + '''Choose method for computing p-value automatically''' + m, n = ranks.shape + if n > 8 or (m > 12 and n > 3) or m > 20: # as in [1], [4] + method = "asymptotic" + else: + method = "exact" + return method + + +def _l_vectorized(ranks, predicted_ranks): + '''Calculate's Page's L statistic for each page of a 3d array''' + colsums = ranks.sum(axis=-2, keepdims=True) + products = predicted_ranks * colsums + Ls = products.sum(axis=-1) + Ls = Ls[0] if Ls.size == 1 else Ls.ravel() + return Ls + + +def _l_p_asymptotic(L, m, n): + '''Calculate the p-value of Page's L from the asymptotic distribution''' + # Using [1] as a reference, the asymptotic p-value would be calculated as: + # chi_L = (12*L - 3*m*n*(n+1)**2)**2/(m*n**2*(n**2-1)*(n+1)) + # p = chi2.sf(chi_L, df=1, loc=0, scale=1)/2 + # but this is insensitive to the direction of the hypothesized ranking + + # See [2] page 151 + E0 = (m*n*(n+1)**2)/4 + V0 = (m*n**2*(n+1)*(n**2-1))/144 + Lambda = (L-E0)/np.sqrt(V0) + # This is a one-sided "greater" test - calculate the probability that the + # L statistic under H0 would be greater than the observed L statistic + p = norm.sf(Lambda) + return p + + +def _l_p_exact(L, m, n): + '''Calculate the p-value of Page's L exactly''' + # [1] uses m, n; [5] uses n, k. + # Switch convention here because exact calculation code references [5]. + L, n, k = int(L), int(m), int(n) + _pagel_state.set_k(k) + return _pagel_state.sf(L, n) + + +class _PageL: + '''Maintains state between `page_trend_test` executions''' + + def __init__(self): + '''Lightweight initialization''' + self.all_pmfs = {} + + def set_k(self, k): + '''Calculate lower and upper limits of L for single row''' + self.k = k + # See [5] top of page 52 + self.a, self.b = (k*(k+1)*(k+2))//6, (k*(k+1)*(2*k+1))//6 + + def sf(self, l, n): + '''Survival function of Page's L statistic''' + ps = [self.pmf(l, n) for l in range(l, n*self.b + 1)] + return np.sum(ps) + + def p_l_k_1(self): + '''Relative frequency of each L value over all possible single rows''' + + # See [5] Equation (6) + ranks = range(1, self.k+1) + # generate all possible rows of length k + rank_perms = np.array(list(permutations(ranks))) + # compute Page's L for all possible rows + Ls = (ranks*rank_perms).sum(axis=1) + # count occurrences of each L value + counts = np.histogram(Ls, np.arange(self.a-0.5, self.b+1.5))[0] + # factorial(k) is number of possible permutations + return counts/math.factorial(self.k) + + def pmf(self, l, n): + '''Recursive function to evaluate p(l, k, n); see [5] Equation 1''' + + if n not in self.all_pmfs: + self.all_pmfs[n] = {} + if self.k not in self.all_pmfs[n]: + self.all_pmfs[n][self.k] = {} + + # Cache results to avoid repeating calculation. Initially this was + # written with lru_cache, but this seems faster? Also, we could add + # an option to save this for future lookup. + if l in self.all_pmfs[n][self.k]: + return self.all_pmfs[n][self.k][l] + + if n == 1: + ps = self.p_l_k_1() # [5] Equation 6 + ls = range(self.a, self.b+1) + # not fast, but we'll only be here once + self.all_pmfs[n][self.k] = {l: p for l, p in zip(ls, ps)} + return self.all_pmfs[n][self.k][l] + + p = 0 + low = max(l-(n-1)*self.b, self.a) # [5] Equation 2 + high = min(l-(n-1)*self.a, self.b) + + # [5] Equation 1 + for t in range(low, high+1): + p1 = self.pmf(l-t, n-1) + p2 = self.pmf(t, 1) + p += p1*p2 + self.all_pmfs[n][self.k][l] = p + return p + + +# Maintain state for faster repeat calls to page_trend_test w/ method='exact' +_pagel_state = _PageL() diff --git a/shared/package-files/3a/3af8ca1cde717c4a061cbca05b06b2c9e0744689472fa6072cd78e30afb9e0b5/win32_pipe.py b/shared/package-files/3a/3af8ca1cde717c4a061cbca05b06b2c9e0744689472fa6072cd78e30afb9e0b5/win32_pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..0bafa49eab71547708feaf1bc8ee41e061c52340 --- /dev/null +++ b/shared/package-files/3a/3af8ca1cde717c4a061cbca05b06b2c9e0744689472fa6072cd78e30afb9e0b5/win32_pipe.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import sys + +assert sys.platform == "win32" + +from contextlib import contextmanager +from ctypes import windll +from ctypes.wintypes import HANDLE +from typing import Callable, ContextManager, Iterator + +from prompt_toolkit.eventloop.win32 import create_win32_event + +from ..key_binding import KeyPress +from ..utils import DummyContext +from .base import PipeInput +from .vt100_parser import Vt100Parser +from .win32 import _Win32InputBase, attach_win32_input, detach_win32_input + +__all__ = ["Win32PipeInput"] + + +class Win32PipeInput(_Win32InputBase, PipeInput): + """ + This is an input pipe that works on Windows. + Text or bytes can be feed into the pipe, and key strokes can be read from + the pipe. This is useful if we want to send the input programmatically into + the application. Mostly useful for unit testing. + + Notice that even though it's Windows, we use vt100 escape sequences over + the pipe. + + Usage:: + + input = Win32PipeInput() + input.send_text('inputdata') + """ + + _id = 0 + + def __init__(self, _event: HANDLE) -> None: + super().__init__() + # Event (handle) for registering this input in the event loop. + # This event is set when there is data available to read from the pipe. + # Note: We use this approach instead of using a regular pipe, like + # returned from `os.pipe()`, because making such a regular pipe + # non-blocking is tricky and this works really well. + self._event = create_win32_event() + + self._closed = False + + # Parser for incoming keys. + self._buffer: list[KeyPress] = [] # Buffer to collect the Key objects. + self.vt100_parser = Vt100Parser(lambda key: self._buffer.append(key)) + + # Identifier for every PipeInput for the hash. + self.__class__._id += 1 + self._id = self.__class__._id + + @classmethod + @contextmanager + def create(cls) -> Iterator[Win32PipeInput]: + event = create_win32_event() + try: + yield Win32PipeInput(_event=event) + finally: + windll.kernel32.CloseHandle(event) + + @property + def closed(self) -> bool: + return self._closed + + def fileno(self) -> int: + """ + The windows pipe doesn't depend on the file handle. + """ + raise NotImplementedError + + @property + def handle(self) -> HANDLE: + "The handle used for registering this pipe in the event loop." + return self._event + + def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]: + """ + Return a context manager that makes this input active in the current + event loop. + """ + return attach_win32_input(self, input_ready_callback) + + def detach(self) -> ContextManager[None]: + """ + Return a context manager that makes sure that this input is not active + in the current event loop. + """ + return detach_win32_input(self) + + def read_keys(self) -> list[KeyPress]: + "Read list of KeyPress." + + # Return result. + result = self._buffer + self._buffer = [] + + # Reset event. + if not self._closed: + # (If closed, the event should not reset.) + windll.kernel32.ResetEvent(self._event) + + return result + + def flush_keys(self) -> list[KeyPress]: + """ + Flush pending keys and return them. + (Used for flushing the 'escape' key.) + """ + # Flush all pending keys. (This is most important to flush the vt100 + # 'Escape' key early when nothing else follows.) + self.vt100_parser.flush() + + # Return result. + result = self._buffer + self._buffer = [] + return result + + def send_bytes(self, data: bytes) -> None: + "Send bytes to the input." + self.send_text(data.decode("utf-8", "ignore")) + + def send_text(self, text: str) -> None: + "Send text to the input." + if self._closed: + raise ValueError("Attempt to write into a closed pipe.") + + # Pass it through our vt100 parser. + self.vt100_parser.feed(text) + + # Set event. + windll.kernel32.SetEvent(self._event) + + def raw_mode(self) -> ContextManager[None]: + return DummyContext() + + def cooked_mode(self) -> ContextManager[None]: + return DummyContext() + + def close(self) -> None: + "Close write-end of the pipe." + self._closed = True + windll.kernel32.SetEvent(self._event) + + def typeahead_hash(self) -> str: + """ + This needs to be unique for every `PipeInput`. + """ + return f"pipe-input-{self._id}" diff --git a/shared/package-files/3a/3afb844ce4af952eafee2095789dc8747d8283bd67dce268132881dfe87abe11/lexer.py b/shared/package-files/3a/3afb844ce4af952eafee2095789dc8747d8283bd67dce268132881dfe87abe11/lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..706b21bbb19717a32025e505c3ae4a2e5f2154ec --- /dev/null +++ b/shared/package-files/3a/3afb844ce4af952eafee2095789dc8747d8283bd67dce268132881dfe87abe11/lexer.py @@ -0,0 +1,99 @@ +from fontTools.voltLib.error import VoltLibError + + +class Lexer(object): + NUMBER = "NUMBER" + STRING = "STRING" + NAME = "NAME" + NEWLINE = "NEWLINE" + + CHAR_WHITESPACE_ = " \t" + CHAR_NEWLINE_ = "\r\n" + CHAR_DIGIT_ = "0123456789" + CHAR_UC_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + CHAR_LC_LETTER_ = "abcdefghijklmnopqrstuvwxyz" + CHAR_UNDERSCORE_ = "_" + CHAR_PERIOD_ = "." + CHAR_NAME_START_ = ( + CHAR_UC_LETTER_ + CHAR_LC_LETTER_ + CHAR_PERIOD_ + CHAR_UNDERSCORE_ + ) + CHAR_NAME_CONTINUATION_ = CHAR_NAME_START_ + CHAR_DIGIT_ + + def __init__(self, text, filename): + self.filename_ = filename + self.line_ = 1 + self.pos_ = 0 + self.line_start_ = 0 + self.text_ = text + self.text_length_ = len(text) + + def __iter__(self): + return self + + def next(self): # Python 2 + return self.__next__() + + def __next__(self): # Python 3 + while True: + token_type, token, location = self.next_() + if token_type not in {Lexer.NEWLINE}: + return (token_type, token, location) + + def location_(self): + column = self.pos_ - self.line_start_ + 1 + return (self.filename_ or "", self.line_, column) + + def next_(self): + self.scan_over_(Lexer.CHAR_WHITESPACE_) + location = self.location_() + start = self.pos_ + text = self.text_ + limit = len(text) + if start >= limit: + raise StopIteration() + cur_char = text[start] + next_char = text[start + 1] if start + 1 < limit else None + + if cur_char == "\n": + self.pos_ += 1 + self.line_ += 1 + self.line_start_ = self.pos_ + return (Lexer.NEWLINE, None, location) + if cur_char == "\r": + self.pos_ += 2 if next_char == "\n" else 1 + self.line_ += 1 + self.line_start_ = self.pos_ + return (Lexer.NEWLINE, None, location) + if cur_char == '"': + self.pos_ += 1 + self.scan_until_('"\r\n') + if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': + self.pos_ += 1 + return (Lexer.STRING, text[start + 1 : self.pos_ - 1], location) + else: + raise VoltLibError("Expected '\"' to terminate string", location) + if cur_char in Lexer.CHAR_NAME_START_: + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) + token = text[start : self.pos_] + return (Lexer.NAME, token, location) + if cur_char in Lexer.CHAR_DIGIT_: + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) + if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) + raise VoltLibError("Unexpected character: '%s'" % cur_char, location) + + def scan_over_(self, valid): + p = self.pos_ + while p < self.text_length_ and self.text_[p] in valid: + p += 1 + self.pos_ = p + + def scan_until_(self, stop_at): + p = self.pos_ + while p < self.text_length_ and self.text_[p] not in stop_at: + p += 1 + self.pos_ = p diff --git a/shared/package-files/3a/3afd5bb4b348e3b867d18100dc2b368e10645c9cf0cca165b310a511bd7ba850/_scaled_dot_product_efficient_attention_native.h b/shared/package-files/3a/3afd5bb4b348e3b867d18100dc2b368e10645c9cf0cca165b310a511bd7ba850/_scaled_dot_product_efficient_attention_native.h new file mode 100644 index 0000000000000000000000000000000000000000..a89a127bc055f8752f0bfc9f56d603a7fe711290 --- /dev/null +++ b/shared/package-files/3a/3afd5bb4b348e3b867d18100dc2b368e10645c9cf0cca165b310a511bd7ba850/_scaled_dot_product_efficient_attention_native.h @@ -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_efficient_attention_cuda(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & attn_bias, bool compute_log_sumexp, double dropout_p=0.0, bool is_causal=false, c10::optional scale=c10::nullopt); +TORCH_API ::std::tuple _scaled_dot_product_efficient_attention_nestedtensor_cuda(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & attn_bias, bool compute_log_sumexp, double dropout_p=0.0, bool is_causal=false, c10::optional scale=c10::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/3c/3c0254e6196fe391dfe7848d70dd99d5165e9bfeeed2073370d6005ace2d06c7/_weight_norm_interface_backward_cuda_dispatch.h b/shared/package-files/3c/3c0254e6196fe391dfe7848d70dd99d5165e9bfeeed2073370d6005ace2d06c7/_weight_norm_interface_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4d0f12a3d040af148407c30630901ca4f5742ad4 --- /dev/null +++ b/shared/package-files/3c/3c0254e6196fe391dfe7848d70dd99d5165e9bfeeed2073370d6005ace2d06c7/_weight_norm_interface_backward_cuda_dispatch.h @@ -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_backward(const at::Tensor & grad_w, const at::Tensor & saved_v, const at::Tensor & saved_g, const at::Tensor & saved_norms, int64_t dim); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/3c/3c02983315b843a258d25f132e6c11ec1f74c72f086273174dfedee80b6883fc/smartif.pyi b/shared/package-files/3c/3c02983315b843a258d25f132e6c11ec1f74c72f086273174dfedee80b6883fc/smartif.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a60d2fa3329d7a4630af80ae96f3e582cb995b7c --- /dev/null +++ b/shared/package-files/3c/3c02983315b843a258d25f132e6c11ec1f74c72f086273174dfedee80b6883fc/smartif.pyi @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Optional, Union + +from django.template.defaulttags import TemplateLiteral + +_Token = Union[List[int], int, str] + +class TokenBase: + id: Any = ... + value: Any = ... + first: Any = ... + second: Any = ... + def nud(self, parser: Any) -> None: ... + def led(self, left: Any, parser: Any) -> None: ... + def display(self): ... + +def infix(bp: Any, func: Any): ... +def prefix(bp: Any, func: Any): ... + +OPERATORS: Any + +class Literal(TokenBase): + id: str = ... + lbp: int = ... + value: Optional[_Token] = ... + def __init__(self, value: Optional[_Token]) -> None: ... + def display(self): ... + def eval(self, context: Dict[Any, Any]) -> Optional[_Token]: ... + +class EndToken(TokenBase): + lbp: int = ... + def nud(self, parser: Any) -> None: ... + +class IfParser: + error_class: Any = ... + tokens: Any = ... + pos: int = ... + current_token: Any = ... + def __init__(self, tokens: List[Optional[_Token]]) -> None: ... + def translate_token(self, token: Optional[_Token]) -> Literal: ... + def next_token(self) -> Literal: ... + def parse(self) -> TemplateLiteral: ... + def expression(self, rbp: int = ...) -> Literal: ... + def create_var(self, value: Optional[_Token]) -> Literal: ... diff --git a/shared/package-files/3c/3c04cd27dd94726fc739c8b54f5dc95186c77b30429a09268ad2469cb3619f75/avg_pool2d_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/3c/3c04cd27dd94726fc739c8b54f5dc95186c77b30429a09268ad2469cb3619f75/avg_pool2d_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b83a42904042d396533d39816ab5cbaf6c04cb60 --- /dev/null +++ b/shared/package-files/3c/3c04cd27dd94726fc739c8b54f5dc95186c77b30429a09268ad2469cb3619f75/avg_pool2d_compositeexplicitautogradnonfunctional_dispatch.h @@ -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 avg_pool2d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, bool ceil_mode=false, bool count_include_pad=true, c10::optional divisor_override=c10::nullopt); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/3c/3c0789ed8b7c914a9b0e0bc16b3fd97d415983ec3ebdfd603c2d073ba828fd32/time_dependent.py b/shared/package-files/3c/3c0789ed8b7c914a9b0e0bc16b3fd97d415983ec3ebdfd603c2d073ba828fd32/time_dependent.py new file mode 100644 index 0000000000000000000000000000000000000000..d67cdcf0b8eaecdef8497c77edd3144e96501173 --- /dev/null +++ b/shared/package-files/3c/3c0789ed8b7c914a9b0e0bc16b3fd97d415983ec3ebdfd603c2d073ba828fd32/time_dependent.py @@ -0,0 +1,142 @@ +"""Time dependent algorithms.""" + +import networkx as nx +from networkx.utils import not_implemented_for + +__all__ = ["cd_index"] + + +@not_implemented_for("undirected") +@not_implemented_for("multigraph") +@nx._dispatchable(node_attrs={"time": None, "weight": 1}) +def cd_index(G, node, time_delta, *, time="time", weight=None): + r"""Compute the CD index for `node` within the graph `G`. + + Calculates the CD index for the given node of the graph, + considering only its predecessors who have the `time` attribute + smaller than or equal to the `time` attribute of the `node` + plus `time_delta`. + + Parameters + ---------- + G : graph + A directed networkx graph whose nodes have `time` attributes and optionally + `weight` attributes (if a weight is not given, it is considered 1). + node : node + The node for which the CD index is calculated. + time_delta : numeric or timedelta + Amount of time after the `time` attribute of the `node`. The value of + `time_delta` must support comparison with the `time` node attribute. For + example, if the `time` attribute of the nodes are `datetime.datetime` + objects, then `time_delta` should be a `datetime.timedelta` object. + time : string (Optional, default is "time") + The name of the node attribute that will be used for the calculations. + weight : string (Optional, default is None) + The name of the node attribute used as weight. + + Returns + ------- + float + The CD index calculated for the node `node` within the graph `G`. + + Raises + ------ + NetworkXError + If not all nodes have a `time` attribute or + `time_delta` and `time` attribute types are not compatible or + `n` equals 0. + + NetworkXNotImplemented + If `G` is a non-directed graph or a multigraph. + + Examples + -------- + >>> from datetime import datetime, timedelta + >>> G = nx.DiGraph() + >>> nodes = { + ... 1: {"time": datetime(2015, 1, 1)}, + ... 2: {"time": datetime(2012, 1, 1), "weight": 4}, + ... 3: {"time": datetime(2010, 1, 1)}, + ... 4: {"time": datetime(2008, 1, 1)}, + ... 5: {"time": datetime(2014, 1, 1)}, + ... } + >>> G.add_nodes_from([(n, nodes[n]) for n in nodes]) + >>> edges = [(1, 3), (1, 4), (2, 3), (3, 4), (3, 5)] + >>> G.add_edges_from(edges) + >>> delta = timedelta(days=5 * 365) + >>> nx.cd_index(G, 3, time_delta=delta, time="time") + 0.5 + >>> nx.cd_index(G, 3, time_delta=delta, time="time", weight="weight") + 0.12 + + Integers can also be used for the time values: + >>> node_times = {1: 2015, 2: 2012, 3: 2010, 4: 2008, 5: 2014} + >>> nx.set_node_attributes(G, node_times, "new_time") + >>> nx.cd_index(G, 3, time_delta=4, time="new_time") + 0.5 + >>> nx.cd_index(G, 3, time_delta=4, time="new_time", weight="weight") + 0.12 + + Notes + ----- + This method implements the algorithm for calculating the CD index, + as described in the paper by Funk and Owen-Smith [1]_. The CD index + is used in order to check how consolidating or destabilizing a patent + is, hence the nodes of the graph represent patents and the edges show + the citations between these patents. The mathematical model is given + below: + + .. math:: + CD_{t}=\frac{1}{n_{t}}\sum_{i=1}^{n}\frac{-2f_{it}b_{it}+f_{it}}{w_{it}}, + + where `f_{it}` equals 1 if `i` cites the focal patent else 0, `b_{it}` equals + 1 if `i` cites any of the focal patents successors else 0, `n_{t}` is the number + of forward citations in `i` and `w_{it}` is a matrix of weight for patent `i` + at time `t`. + + The `datetime.timedelta` package can lead to off-by-one issues when converting + from years to days. In the example above `timedelta(days=5 * 365)` looks like + 5 years, but it isn't because of leap year days. So it gives the same result + as `timedelta(days=4 * 365)`. But using `timedelta(days=5 * 365 + 1)` gives + a 5 year delta **for this choice of years** but may not if the 5 year gap has + more than 1 leap year. To avoid these issues, use integers to represent years, + or be very careful when you convert units of time. + + References + ---------- + .. [1] Funk, Russell J., and Jason Owen-Smith. + "A dynamic network measure of technological change." + Management science 63, no. 3 (2017): 791-817. + http://russellfunk.org/cdindex/static/papers/funk_ms_2017.pdf + + """ + if not all(time in G.nodes[n] for n in G): + raise nx.NetworkXError("Not all nodes have a 'time' attribute.") + + try: + # get target_date + target_date = G.nodes[node][time] + time_delta + # keep the predecessors that existed before the target date + pred = {i for i in G.pred[node] if G.nodes[i][time] <= target_date} + except: + raise nx.NetworkXError( + "Addition and comparison are not supported between 'time_delta' " + "and 'time' types." + ) + + # -1 if any edge between node's predecessors and node's successors, else 1 + b = [-1 if any(j in G[i] for j in G[node]) else 1 for i in pred] + + # n is size of the union of the focal node's predecessors and its successors' predecessors + n = len(pred.union(*(G.pred[s].keys() - {node} for s in G[node]))) + if n == 0: + raise nx.NetworkXError("The cd index cannot be defined.") + + # calculate cd index + if weight is None: + return round(sum(bi for bi in b) / n, 2) + else: + # If a node has the specified weight attribute, its weight is used in the calculation + # otherwise, a weight of 1 is assumed for that node + weights = [G.nodes[i].get(weight, 1) for i in pred] + return round(sum(bi / wt for bi, wt in zip(b, weights)) / n, 2) diff --git a/shared/package-files/3c/3c0a9f208929e293789013f17c1302cd4ffac96f6906235b6f7137321022ea4e/series.py b/shared/package-files/3c/3c0a9f208929e293789013f17c1302cd4ffac96f6906235b6f7137321022ea4e/series.py new file mode 100644 index 0000000000000000000000000000000000000000..30a4715ddc10c56bf91bf39dd4901f5b0554aa42 --- /dev/null +++ b/shared/package-files/3c/3c0a9f208929e293789013f17c1302cd4ffac96f6906235b6f7137321022ea4e/series.py @@ -0,0 +1,2991 @@ +from __future__ import annotations + +import math +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from functools import partial +from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, cast, overload + +from narwhals._expression_parsing import ExprKind, ExprNode +from narwhals._utils import ( + NO_DEFAULT, + Implementation, + Version, + _Implementation, + _resolve_sample_size, + _validate_rolling_arguments, + ensure_type, + generate_repr, + is_compliant_series, + is_eager_allowed, + is_index_selector, + qualified_type_name, + supports_arrow_c_stream, + unstable, +) +from narwhals.dependencies import is_numpy_array, is_numpy_array_1d, is_numpy_scalar +from narwhals.dtypes import _validate_dtype, _validate_into_dtype +from narwhals.exceptions import ComputeError, InvalidOperationError +from narwhals.expr import Expr +from narwhals.functions import col +from narwhals.series_cat import SeriesCatNamespace +from narwhals.series_dt import SeriesDateTimeNamespace +from narwhals.series_list import SeriesListNamespace +from narwhals.series_str import SeriesStringNamespace +from narwhals.series_struct import SeriesStructNamespace +from narwhals.translate import to_native +from narwhals.typing import IntoSeriesT + +if TYPE_CHECKING: + from types import ModuleType + from typing import NoReturn + + import pandas as pd + import polars as pl + import pyarrow as pa + from typing_extensions import Self + + from narwhals._compliant import CompliantSeries + from narwhals._typing import EagerAllowed, IntoBackend, NoDefault, PluginName + from narwhals.dataframe import DataFrame, MultiIndexSelector + from narwhals.dtypes import DType + from narwhals.typing import ( + ClosedInterval, + FillNullStrategy, + IntoDType, + ModeKeepStrategy, + NonNestedLiteral, + NumericLiteral, + PythonLiteral, + RankMethod, + RollingInterpolationMethod, + SingleIndexSelector, + TemporalLiteral, + _1DArray, + ) + + +class Series(Generic[IntoSeriesT]): + """Narwhals Series, backed by a native series. + + Warning: + This class is not meant to be instantiated directly - instead: + + - If the native object is a series from one of the supported backend (e.g. + pandas.Series, polars.Series, pyarrow.ChunkedArray), you can use + [`narwhals.from_native`][]: + ```py + narwhals.from_native(native_series, allow_series=True) + narwhals.from_native(native_series, series_only=True) + ``` + + - If the object is a generic sequence (e.g. a list or a tuple of values), you can + create a series via [`narwhals.new_series`][], e.g.: + ```py + narwhals.new_series(name="price", values=[10.5, 9.4, 1.2], backend="pandas") + ``` + """ + + _version: ClassVar[Version] = Version.MAIN + + @property + def _compliant(self) -> CompliantSeries[IntoSeriesT]: + return self._compliant_series + + @property + def _dataframe(self) -> type[DataFrame[Any]]: + from narwhals.dataframe import DataFrame + + return DataFrame + + def _to_expr(self) -> Expr: + return Expr( + ExprNode(ExprKind.SERIES, "_expr._from_series", series=self._compliant) + ) + + def __init__( + self, series: Any, *, level: Literal["full", "lazy", "interchange"] + ) -> None: + self._level: Literal["full", "lazy", "interchange"] = level + if is_compliant_series(series): + self._compliant_series: CompliantSeries[IntoSeriesT] = ( + series.__narwhals_series__() + ) + else: # pragma: no cover + msg = f"Expected Polars Series or an object which implements `__narwhals_series__`, got: {type(series)}." + raise AssertionError(msg) + + @classmethod + def from_numpy( + cls, + name: str, + values: _1DArray, + dtype: IntoDType | None = None, + *, + backend: IntoBackend[EagerAllowed | PluginName], + ) -> Series[Any]: + """Construct a Series from a NumPy ndarray. + + Arguments: + name: Name of resulting Series. + values: One-dimensional data represented as a NumPy ndarray. + dtype: (Narwhals) dtype. If not provided, the native library + may auto-infer it from `values`. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import numpy as np + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> arr = np.arange(5, 10) + >>> nw.Series.from_numpy("arr", arr, dtype=nw.Int8, backend="polars") + ┌──────────────────┐ + | Narwhals Series | + |------------------| + |shape: (5,) | + |Series: 'arr' [i8]| + |[ | + | 5 | + | 6 | + | 7 | + | 8 | + | 9 | + |] | + └──────────────────┘ + """ + if not is_numpy_array_1d(values): + msg = "`from_numpy` only accepts 1D numpy arrays" + raise ValueError(msg) + if dtype: + _validate_into_dtype(dtype) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + compliant = ns.from_numpy(values).alias(name) + if dtype: + return cls(compliant.cast(dtype), level="full") + return cls(compliant, level="full") + msg = ( # pragma: no cover + f"{implementation} support in Narwhals is lazy-only, but `Series.from_numpy` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.Series.from_numpy(arr, backend='pyarrow').to_frame().lazy('{implementation}')" + ) + raise ValueError(msg) # pragma: no cover + + @classmethod + def from_iterable( + cls, + name: str, + values: Iterable[Any], + dtype: IntoDType | None = None, + *, + backend: IntoBackend[EagerAllowed | PluginName], + ) -> Series[Any]: + """Construct a Series from an iterable. + + Arguments: + name: Name of resulting Series. + values: One-dimensional data represented as an iterable. + dtype: (Narwhals) dtype. If not provided, the native library + may auto-infer it from `values`. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> values = [4, 1, 3, 2] + >>> nw.Series.from_iterable("a", values, dtype=nw.UInt32, backend="pandas") + ┌──────────────────────┐ + | Narwhals Series | + |----------------------| + |0 4 | + |1 1 | + |2 3 | + |3 2 | + |Name: a, dtype: uint32| + └──────────────────────┘ + """ + if is_numpy_array(values): + return cls.from_numpy(name, values, dtype, backend=backend) + if dtype: + _validate_into_dtype(dtype) + if not isinstance(values, Iterable): + msg = f"Expected values to be an iterable, got: {qualified_type_name(values)!r}." + raise TypeError(msg) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + compliant = ns._series.from_iterable( + values, context=ns, name=name, dtype=dtype + ) + return cls(compliant, level="full") + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `Series.from_iterable` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.Series.from_iterable('a', [1,2,3], backend='pyarrow').to_frame().lazy('{implementation}')" + ) + raise ValueError(msg) + + implementation: _Implementation = _Implementation() + """Return [`narwhals.Implementation`][] of native Series. + + This can be useful when you need to use special-casing for features outside of + Narwhals' scope - for example, when dealing with pandas' Period Dtype. + + Examples: + >>> import narwhals as nw + >>> import pandas as pd + >>> s_native = pd.Series([1, 2, 3]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.implementation + + >>> s.implementation.is_pandas() + True + >>> s.implementation.is_pandas_like() + True + >>> s.implementation.is_polars() + False + """ + + def __bool__(self) -> NoReturn: + msg = ( + "the truth value of a Series is ambiguous" + "\n\n" + "Here are some things you might want to try:\n" + "- instead of `if s`, use `if not s.is_empty()`\n" + "- instead of `s1 and s2`, use `s1 & s2`\n" + "- instead of `s1 or s2`, use `s1 | s2`\n" + "- instead of `s in [y, z]`, use `s.is_in([y, z])`\n" + ) + raise TypeError(msg) + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> _1DArray: # noqa: FBT001 + return self._compliant_series.__array__(dtype=dtype, copy=copy) + + @overload + def __getitem__(self, idx: SingleIndexSelector) -> Any: ... + + @overload + def __getitem__(self, idx: MultiIndexSelector) -> Self: ... + + def __getitem__(self, idx: SingleIndexSelector | MultiIndexSelector) -> Any | Self: + """Retrieve elements from the object using integer indexing or slicing. + + Arguments: + idx: The index, slice, or sequence of indices to retrieve. + + - If `idx` is an integer, a single element is returned. + - If `idx` is a slice, a sequence of integers, or another Series + (with integer values) a subset of the Series is returned. + + Returns: + A single element if `idx` is an integer, else a subset of the Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True)[0] + 1 + + >>> nw.from_native(s_native, series_only=True)[ + ... :2 + ... ].to_native() # doctest:+ELLIPSIS + + [ + [ + 1, + 2 + ] + ] + """ + if isinstance(idx, int) or ( + is_numpy_scalar(idx) and idx.dtype.kind in {"i", "u"} + ): + idx = int(idx) if not isinstance(idx, int) else idx + return self._compliant_series.item(idx) + + if isinstance(idx, self.to_native().__class__): + idx = self._with_compliant(self._compliant_series._with_native(idx)) + + if not is_index_selector(idx): + msg = ( + f"Unexpected type for `Series.__getitem__`: {type(idx)}.\n\n" + "Hints:\n" + "- use `s.item` to select a single item.\n" + "- Use `s[indices]` to select rows positionally.\n" + "- Use `s.filter(mask)` to filter rows based on a boolean mask." + ) + raise TypeError(msg) + if isinstance(idx, Series): + return self._with_compliant(self._compliant_series[idx._compliant_series]) + assert not isinstance(idx, int) # noqa: S101 # help mypy + return self._with_compliant(self._compliant_series[idx]) + + def __native_namespace__(self) -> ModuleType: + return self._compliant_series.__native_namespace__() + + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export a Series via the Arrow PyCapsule Interface. + + Narwhals doesn't implement anything itself here: + + - if the underlying series implements the interface, it'll return that + - else, it'll call `to_arrow` and then defer to PyArrow's implementation + + See [PyCapsule Interface](https://arrow.apache.org/docs/dev/format/CDataInterface/PyCapsuleInterface.html) + for more. + """ + native_series = self._compliant_series.native + if supports_arrow_c_stream(native_series): + return native_series.__arrow_c_stream__(requested_schema=requested_schema) + try: + pa_version = Implementation.PYARROW._backend_version() + except ModuleNotFoundError as exc: + msg = f"'pyarrow>=16.0.0' is required for `Series.__arrow_c_stream__` for object of type {type(native_series)}" + raise ModuleNotFoundError(msg) from exc + if pa_version < (16, 0): # pragma: no cover + msg = f"'pyarrow>=16.0.0' is required for `Series.__arrow_c_stream__` for object of type {type(native_series)}" + raise ModuleNotFoundError(msg) + from narwhals._arrow.utils import chunked_array + + ca = chunked_array(self.to_arrow()) + return ca.__arrow_c_stream__(requested_schema=requested_schema) + + def to_native(self) -> IntoSeriesT: + """Convert Narwhals series to native series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 1 + 2 + ] + """ + return self._compliant_series.native + + def scatter( + self, + indices: Self | Iterable[int] | int, + values: Self | Iterable[PythonLiteral] | PythonLiteral, + ) -> Self: + """Set value(s) at the given index location(s). + + Arguments: + indices: Integer(s) representing the index location(s). + values: Replacement values. + + Note: + This method always returns a new Series, without modifying the original one. + Using this function in a for-loop is an anti-pattern, we recommend building + up your positions and values beforehand and doing an update in one go. + + For example, instead of + + ```python + for i in [1, 3, 2]: + value = some_function(i) + s = s.scatter(i, value) + ``` + + prefer + + ```python + positions = [1, 3, 2] + values = [some_function(x) for x in positions] + s = s.scatter(positions, values) + ``` + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> df_native = pa.table({"a": [1, 2, 3], "b": [4, 5, 6]}) + >>> df_nw = nw.from_native(df_native) + >>> df_nw.with_columns(df_nw["a"].scatter([0, 1], [999, 888])).to_native() + pyarrow.Table + a: int64 + b: int64 + ---- + a: [[999,888,3]] + b: [[4,5,6]] + """ + into_series = partial( + type(self).from_iterable, name="", backend=self.implementation + ) + + if not isinstance(indices, Series): + if not isinstance(indices, Iterable): + indices = [indices] + dtypes = self._version.dtypes + indices = into_series(values=indices, dtype=dtypes.Int64) + + if indices.is_empty(): + return self + + if not isinstance(values, Series): + if not isinstance(values, Iterable) or isinstance(values, str): + values = [values] + values = into_series(values=values) + + result = self._compliant.scatter(indices._compliant, values._compliant) + return self._with_compliant(result) + + @property + def shape(self) -> tuple[int]: + """Get the shape of the Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).shape + (3,) + """ + return (self._compliant_series.len(),) + + def _extract_native(self, arg: Any) -> Any: + if isinstance(arg, Series): + return arg._compliant_series + return arg + + def _with_compliant(self, series: Any) -> Self: + return self.__class__(series, level=self._level) + + def pipe(self, function: Callable[[Any], Self], *args: Any, **kwargs: Any) -> Self: + """Pipe function call. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([1, 2, 3]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.pipe(lambda x: x + 2).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [i64] + [ + 3 + 4 + 5 + ] + """ + return function(self, *args, **kwargs) + + def __repr__(self) -> str: # pragma: no cover + return generate_repr("Narwhals Series", self.to_native().__repr__()) + + def __len__(self) -> int: + return len(self._compliant_series) + + def len(self) -> int: + r"""Return the number of elements in the Series. + + Null values count towards the total. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> nw.from_native(s_native, series_only=True).len() + 3 + """ + return len(self._compliant_series) + + @property + def dtype(self) -> DType: + """Get the data type of the Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).dtype + Int64 + """ + return self._compliant_series.dtype + + @property + def name(self) -> str: + """Get the name of the Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("foo", [1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).name + 'foo' + """ + return self._compliant_series.name + + def ewm_mean( + self, + *, + com: float | None = None, + span: float | None = None, + half_life: float | None = None, + alpha: float | None = None, + adjust: bool = True, + min_samples: int = 1, + ignore_nulls: bool = False, + ) -> Self: + r"""Compute exponentially-weighted moving average. + + Arguments: + com: Specify decay in terms of center of mass, $\gamma$, with
$\alpha = \frac{1}{1+\gamma}\forall\gamma\geq0$ + span: Specify decay in terms of span, $\theta$, with
$\alpha = \frac{2}{\theta + 1} \forall \theta \geq 1$ + half_life: Specify decay in terms of half-life, $\tau$, with
$\alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \tau } \right\} \forall \tau > 0$ + alpha: Specify smoothing factor alpha directly, $0 < \alpha \leq 1$. + adjust: Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings + + - When `adjust=True` (the default) the EW function is calculated + using weights $w_i = (1 - \alpha)^i$ + - When `adjust=False` the EW function is calculated recursively by + $$ + y_0=x_0 + $$ + $$ + y_t = (1 - \alpha)y_{t - 1} + \alpha x_t + $$ + min_samples: Minimum number of observations in window required to have a value (otherwise result is null). + ignore_nulls: Ignore missing values when calculating weights. + + - When `ignore_nulls=False` (default), weights are based on absolute + positions. + For example, the weights of $x_0$ and $x_2$ used in + calculating the final weighted average of $[x_0, None, x_2]$ are + $(1-\alpha)^2$ and $1$ if `adjust=True`, and + $(1-\alpha)^2$ and $\alpha$ if `adjust=False`. + - When `ignore_nulls=True`, weights are based + on relative positions. For example, the weights of + $x_0$ and $x_2$ used in calculating the final weighted + average of $[x_0, None, x_2]$ are + $1-\alpha$ and $1$ if `adjust=True`, + and $1-\alpha$ and $\alpha$ if `adjust=False`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series(name="a", data=[1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).ewm_mean( + ... com=1, ignore_nulls=False + ... ).to_native() + 0 1.000000 + 1 1.666667 + 2 2.428571 + Name: a, dtype: float64 + """ + return self._with_compliant( + self._compliant_series.ewm_mean( + com=com, + span=span, + half_life=half_life, + alpha=alpha, + adjust=adjust, + min_samples=min_samples, + ignore_nulls=ignore_nulls, + ) + ) + + def cast(self, dtype: IntoDType) -> Self: + """Cast between data types. + + Arguments: + dtype: Data type that the object will be cast into. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[True, False, True]]) + >>> nw.from_native(s_native, series_only=True).cast(nw.Int64).to_native() + + [ + [ + 1, + 0, + 1 + ] + ] + """ + _validate_dtype(dtype) + return self._with_compliant(self._compliant_series.cast(dtype)) + + def to_frame(self) -> DataFrame[Any]: + """Convert to dataframe. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("a", [1, 2]) + >>> nw.from_native(s_native, series_only=True).to_frame().to_native() + shape: (2, 1) + ┌─────┐ + │ a │ + │ --- │ + │ i64 │ + ╞═════╡ + │ 1 │ + │ 2 │ + └─────┘ + """ + return self._dataframe(self._compliant_series.to_frame(), level=self._level) + + def to_list(self) -> list[Any]: + """Convert to list. + + Notes: + This function converts to Python scalars. It's typically + more efficient to keep your data in the format native to + your original dataframe, so we recommend only calling this + when you absolutely need to. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).to_list() + [1, 2, 3] + """ + return self._compliant_series.to_list() + + def mean(self) -> float: + """Reduce this Series to the mean value. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1.2, 4.2]) + >>> nw.from_native(s_native, series_only=True).mean() + np.float64(2.7) + """ + return self._compliant_series.mean() + + def median(self) -> float: + """Reduce this Series to the median value. + + Notes: + Results might slightly differ across backends due to differences in the underlying algorithms used to compute the median. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[5, 3, 8]]) + >>> nw.from_native(s_native, series_only=True).median() + 5.0 + """ + return self._compliant_series.median() + + def skew(self) -> float | None: + """Calculate the sample skewness of the Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 1, 2, 10, 100]) + >>> nw.from_native(s_native, series_only=True).skew() + 1.4724267269058975 + + Notes: + The skewness is a measure of the asymmetry of the probability distribution. + A perfectly symmetric distribution has a skewness of 0. + """ + return self._compliant_series.skew() + + def kurtosis(self) -> float | None: + """Compute the kurtosis (Fisher's definition) without bias correction. + + Kurtosis is the fourth central moment divided by the square of the variance. + The Fisher's definition is used where 3.0 is subtracted from the result to give 0.0 for a normal distribution. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 1, 2, 10, 100]) + >>> nw.from_native(s_native, series_only=True).kurtosis() + 0.2106571340718002 + """ + return self._compliant_series.kurtosis() + + def count(self) -> int: + """Returns the number of non-null elements in the Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> nw.from_native(s_native, series_only=True).count() + 2 + """ + return self._compliant_series.count() + + def any(self) -> bool: + """Return whether any of the values in the Series are True. + + If there are no non-null elements, the result is `False`. + + Notes: + Only works on Series of data type Boolean. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([False, True, False]) + >>> nw.from_native(s_native, series_only=True).any() + np.True_ + """ + return self._compliant_series.any() + + def all(self) -> bool: + """Return whether all values in the Series are True. + + If there are no non-null elements, the result is `True`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[False, True, False]]) + >>> nw.from_native(s_native, series_only=True).all() + False + """ + return self._compliant_series.all() + + def min(self) -> Any: + """Get the minimal value in this Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).min() + 1 + """ + return self._compliant_series.min() + + def max(self) -> Any: + """Get the maximum value in this Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).max() + np.int64(3) + """ + return self._compliant_series.max() + + def arg_min(self) -> int: + """Returns the index of the minimum value. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).arg_min() + 0 + """ + return self._compliant_series.arg_min() + + def arg_max(self) -> int: + """Returns the index of the maximum value. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).arg_max() + 2 + """ + return self._compliant_series.arg_max() + + def sum(self) -> float: + """Reduce this Series to the sum value. + + If there are no non-null elements, the result is zero. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).sum() + 6 + """ + return self._compliant_series.sum() + + def std(self, *, ddof: int = 1) -> float: + """Get the standard deviation of this Series. + + Arguments: + ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, + where N represents the number of elements. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).std() + 1.0 + """ + return self._compliant_series.std(ddof=ddof) + + def var(self, *, ddof: int = 1) -> float: + """Get the variance of this Series. + + Arguments: + ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, + where N represents the number of elements. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).var() + 1.0 + """ + return self._compliant_series.var(ddof=ddof) + + def clip( + self, + lower_bound: Self | NumericLiteral | TemporalLiteral | None = None, + upper_bound: Self | NumericLiteral | TemporalLiteral | None = None, + ) -> Self: + r"""Clip values in the Series. + + Arguments: + lower_bound: Lower bound value. + upper_bound: Upper bound value. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([-1, 1, -3, 3, -5, 5]) + >>> nw.from_native(s_native, series_only=True).clip(-1, 3).to_native() + 0 -1 + 1 1 + 2 -1 + 3 3 + 4 -1 + 5 3 + dtype: int64 + """ + if lower_bound is None: + return self._with_compliant( + self._compliant_series.clip_upper( + upper_bound=self._extract_native(upper_bound) + ) + ) + if upper_bound is None: + return self._with_compliant( + self._compliant_series.clip_lower( + lower_bound=self._extract_native(lower_bound) + ) + ) + return self._with_compliant( + self._compliant_series.clip( + lower_bound=self._extract_native(lower_bound), + upper_bound=self._extract_native(upper_bound), + ) + ) + + def first(self) -> PythonLiteral: + """Get the first element of the Series. + + Returns: + A scalar value or `None` if the Series is empty. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> s_nw.first() + 1 + >>> s_nw.filter(s_nw > 5).first() is None + True + """ + return self._compliant_series.first() + + def last(self) -> PythonLiteral: + """Get the last element of the Series. + + Returns: + A scalar value or `None` if the Series is empty. + + Notes: + Null values are preserved, unless `self` is backed by a non-nullable pandas Series + (which does not support missing values). See [boolean columns](../concepts/boolean.md) for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> s_nw.last() + 3 + >>> s_nw.filter(s_nw > 5).last() is None + True + """ + return self._compliant_series.last() + + def is_in(self, other: Any) -> Self: + """Check if the elements of this Series are in the other sequence. + + Arguments: + other: Sequence of primitive type. + + Warning: + Backends disagree on how to compare values against a Series of a + different dtype: `polars>=2.0` raises an `InvalidOperationError` unless + the operands can be coerced losslessly (so looking for floats in an + integer Series raises), whereas every other backend coerces silently. + Cast one of the operands if you need this to behave the same everywhere. + See [Polars' upgrade guide](https://docs.pola.rs/releases/upgrade/2/#make-coercion-casts-for-is_in-strict-instead-of-lossy) + for details. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.is_in([3, 2, 8]).to_native() # doctest: +ELLIPSIS + + [ + [ + false, + true, + true + ] + ] + """ + return self._with_compliant( + self._compliant_series.is_in(to_native(other, pass_through=True)) + ) + + def arg_true(self) -> Self: + """Find elements where boolean Series is True. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, None, None, 2]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_null().arg_true().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [u32] + [ + 1 + 2 + ] + """ + return self._with_compliant(self._compliant_series.arg_true()) + + def drop_nulls(self) -> Self: + """Drop null values. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md) for reference. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([2, 4, None, 3, 5]) + >>> nw.from_native(s_native, series_only=True).drop_nulls().to_native() + 0 2.0 + 1 4.0 + 3 3.0 + 4 5.0 + dtype: float64 + """ + return self._with_compliant(self._compliant_series.drop_nulls()) + + def abs(self) -> Self: + """Calculate the absolute value of each element. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[2, -4, 3]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).abs().to_native() # doctest: +ELLIPSIS + + [ + [ + 2, + 4, + 3 + ] + ] + """ + return self._with_compliant(self._compliant_series.abs()) + + def cum_sum(self, *, reverse: bool = False) -> Self: + """Calculate the cumulative sum. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([2, 4, 3]) + >>> nw.from_native(s_native, series_only=True).cum_sum().to_native() + 0 2 + 1 6 + 2 9 + dtype: int64 + """ + return self._with_compliant(self._compliant_series.cum_sum(reverse=reverse)) + + def unique(self, *, maintain_order: bool = False) -> Self: + """Returns unique values of the series. + + Arguments: + maintain_order: Keep the same order as the original series. This may be more + expensive to compute. Settings this to `True` blocks the possibility + to run on the streaming engine for Polars. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([2, 4, 4, 6]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.unique( + ... maintain_order=True + ... ).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [i64] + [ + 2 + 4 + 6 + ] + """ + return self._with_compliant( + self._compliant_series.unique(maintain_order=maintain_order) + ) + + def diff(self) -> Self: + """Calculate the difference with the previous element, for each element. + + Notes: + pandas may change the dtype here, for example when introducing missing + values in an integer column. To ensure, that the dtype doesn't change, + you may want to use `fill_null` and `cast`. For example, to calculate + the diff and fill missing values with `0` in a Int64 column, you could + do: + + s.diff().fill_null(0).cast(nw.Int64) + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[2, 4, 3]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).diff().to_native() # doctest: +ELLIPSIS + + [ + [ + null, + 2, + -1 + ] + ] + """ + return self._with_compliant(self._compliant_series.diff()) + + def shift(self, n: int) -> Self: + """Shift values by `n` positions. + + Arguments: + n: Number of indices to shift forward. If a negative value is passed, + values are shifted in the opposite direction instead. + + Notes: + pandas may change the dtype here, for example when introducing missing + values in an integer column. To ensure, that the dtype doesn't change, + you may want to use `fill_null` and `cast`. For example, to shift + and fill missing values with `0` in a Int64 column, you could + do: + + s.shift(1).fill_null(0).cast(nw.Int64) + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([2, 4, 3]) + >>> nw.from_native(s_native, series_only=True).shift(1).to_native() + 0 NaN + 1 2.0 + 2 4.0 + dtype: float64 + """ + ensure_type(n, int, param_name="n") + + return self._with_compliant(self._compliant_series.shift(n)) + + def sample( + self, + n: int | None = None, + *, + fraction: float | None = None, + with_replacement: bool = False, + seed: int | None = None, + ) -> Self: + """Sample randomly from this Series. + + Arguments: + n: Number of items to return. Cannot be used with fraction. + fraction: Fraction of items to return. Cannot be used with n. + with_replacement: Allow values to be sampled more than once. + seed: Seed for the random number generator. If set to None (default), a random + seed is generated for each sample operation. + + Notes: + The `sample` method returns a Series with a specified number of + randomly selected items chosen from this Series. + The results are not consistent across libraries. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3, 4]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sample( + ... fraction=1.0, with_replacement=True + ... ).to_native() # doctest: +SKIP + shape: (4,) + Series: '' [i64] + [ + 1 + 4 + 3 + 4 + ] + """ + size = _resolve_sample_size( + n=n, fraction=fraction, height=len(self), with_replacement=with_replacement + ) + return self._with_compliant( + self._compliant_series.sample( + n=size, with_replacement=with_replacement, seed=seed + ) + ) + + def alias(self, name: str) -> Self: + """Rename the Series. + + Notes: + This method is very cheap, but does not guarantee that data + will be copied. For example: + + ```python + s1: nw.Series + s2 = s1.alias("foo") + arr = s2.to_numpy() + arr[0] = 999 + ``` + + may (depending on the backend, and on the version) result in + `s1`'s data being modified. We recommend: + + - if you need to alias an object and don't need the original + one around any more, just use `alias` without worrying about it. + - if you were expecting `alias` to copy data, then explicitly call + `.clone` before calling `alias`. + + Arguments: + name: The new name. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3], name="foo") + >>> nw.from_native(s_native, series_only=True).alias("bar").to_native() + 0 1 + 1 2 + 2 3 + Name: bar, dtype: int64 + """ + return self._with_compliant(self._compliant_series.alias(name=name)) + + def rename(self, name: str) -> Self: + """Rename the Series. + + Alias for `Series.alias()`. + + Notes: + This method is very cheap, but does not guarantee that data + will be copied. For example: + + ```python + s1: nw.Series + s2 = s1.rename("foo") + arr = s2.to_numpy() + arr[0] = 999 + ``` + + may (depending on the backend, and on the version) result in + `s1`'s data being modified. We recommend: + + - if you need to rename an object and don't need the original + one around any more, just use `rename` without worrying about it. + - if you were expecting `rename` to copy data, then explicitly call + `.clone` before calling `rename`. + + Arguments: + name: The new name. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("foo", [1, 2, 3]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.rename("bar").to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: 'bar' [i64] + [ + 1 + 2 + 3 + ] + """ + return self.alias(name=name) + + def replace_strict( + self, + old: Sequence[Any] | Mapping[Any, Any], + new: Sequence[Any] | None = None, + *, + default: Any | NoDefault = NO_DEFAULT, + return_dtype: IntoDType | None = None, + ) -> Self: + """Replace all values by different values. + + Arguments: + old: Sequence of values to replace. It also accepts a mapping of values to + their replacement as syntactic sugar for + `replace_strict(old=list(mapping.keys()), new=list(mapping.values()))`. + new: Sequence of values to replace by. Length must match the length of `old`. + default: Set values that were not replaced to this value. If no default is + specified, (default), an error is raised if any values were not replaced. + Accepts expression input. Non-expression inputs are parsed as literals. + return_dtype: The data type of the resulting expression. If set to `None` + (default), the data type is determined automatically based on the other + inputs. + + Raises: + InvalidOperationError: If any non-null values in the original column were not + replaced, and no default was specified. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([3, 0, 1, 2], name="a") + >>> nw.from_native(s_native, series_only=True).replace_strict( + ... [0, 1, 2, 3], ["zero", "one", "two", "three"], return_dtype=nw.String + ... ).to_native() + 0 three + 1 zero + 2 one + 3 two + Name: a, dtype: str + + Replace values and set a default for values not in the mapping: + + >>> s_native = pd.Series([1, 2, 3, 4], name="a") + >>> s_default = pd.Series(["beluga", "narwhal", "orca", "vaquita"]) + >>> nw.from_native(s_native, series_only=True).replace_strict( + ... {1: "one", 2: "two"}, + ... default=nw.from_native(s_default, series_only=True), + ... return_dtype=nw.String, + ... ).to_native() + 0 one + 1 two + 2 orca + 3 vaquita + Name: a, dtype: str + """ + if new is None: + if not isinstance(old, Mapping): + msg = "`new` argument is required if `old` argument is not a Mapping type" + raise TypeError(msg) + + new = list(old.values()) + old = list(old.keys()) + + assert isinstance(new, Sequence) # noqa: S101, help mypy + assert isinstance(old, Sequence) # noqa: S101, help mypy + + return self._with_compliant( + self._compliant_series.replace_strict( + old=old, + new=new, + default=self._extract_native(default), + return_dtype=return_dtype, + ) + ) + + def sort(self, *, descending: bool = False, nulls_last: bool = False) -> Self: + """Sort this Series. Place null values first. + + Arguments: + descending: Sort in descending order. + nulls_last: Place null values last instead of first. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([5, None, 1, 2]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sort(descending=True).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [i64] + [ + null + 5 + 2 + 1 + ] + """ + return self._with_compliant( + self._compliant_series.sort(descending=descending, nulls_last=nulls_last) + ) + + def is_null(self) -> Self: + """Returns a boolean Series indicating which values are null. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md) for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_null().to_native() # doctest:+ELLIPSIS + + [ + [ + false, + false, + true + ] + ] + """ + return self._with_compliant(self._compliant_series.is_null()) + + def is_nan(self) -> Self: + """Returns a boolean Series indicating which values are NaN. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md) for reference. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([0.0, None, 2.0], dtype="Float64") + >>> nw.from_native(s_native, series_only=True).is_nan().to_native() + 0 False + 1 + 2 False + dtype: boolean + """ + return self._with_compliant(self._compliant_series.is_nan()) + + def fill_null( + self, + value: Self | NonNestedLiteral = None, + strategy: FillNullStrategy | None = None, + limit: int | None = None, + ) -> Self: + """Fill null values using the specified value. + + Arguments: + value: Value used to fill null values. + strategy: Strategy used to fill null values. + limit: Number of consecutive null values to fill when using the 'forward' or 'backward' strategy. + + Notes: + - pandas handles null values differently from other libraries. + See [null_handling](../concepts/null_handling.md) + for reference. + - For pandas Series of `object` dtype, `fill_null` will not automatically change the + Series' dtype as pandas used to do. Explicitly call `cast` if you want the dtype to change. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, None]) + >>> + >>> nw.from_native(s_native, series_only=True).fill_null(5).to_native() + 0 1.0 + 1 2.0 + 2 5.0 + dtype: float64 + + Or using a strategy: + + >>> nw.from_native(s_native, series_only=True).fill_null( + ... strategy="forward", limit=1 + ... ).to_native() + 0 1.0 + 1 2.0 + 2 2.0 + dtype: float64 + """ + if value is not None and strategy is not None: + msg = "cannot specify both `value` and `strategy`" + raise ValueError(msg) + if value is None and strategy is None: + msg = "must specify either a fill `value` or `strategy`" + raise ValueError(msg) + if strategy is not None and strategy not in {"forward", "backward"}: + msg = f"strategy not supported: {strategy}" + raise ValueError(msg) + return self._with_compliant( + self._compliant_series.fill_null( + value=self._extract_native(value), strategy=strategy, limit=limit + ) + ) + + def fill_nan(self, value: float | None) -> Self: + """Fill floating point NaN values with given value. + + Arguments: + value: Value used to fill NaN values. + + Notes: + This function only fills `'NaN'` values, not null ones, except for pandas + which doesn't distinguish between them. + See [null_handling](../concepts/null_handling.md) for reference. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([1.0, 2.0, float("nan"), None]) + >>> result = nw.from_native(s_native, series_only=True).fill_nan(0) + >>> result.to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [f64] + [ + 1.0 + 2.0 + 0.0 + null + ] + """ + return self._with_compliant( + self._compliant_series.fill_nan(value=self._extract_native(value)) + ) + + def is_between( + self, + lower_bound: Any | Self, + upper_bound: Any | Self, + closed: ClosedInterval = "both", + ) -> Self: + """Get a boolean mask of the values that are between the given lower/upper bounds. + + Arguments: + lower_bound: Lower bound value. + upper_bound: Upper bound value. + closed: Define which sides of the interval are closed (inclusive). Options are {"left", "right", "none", "both"}. + + Notes: + If the value of the `lower_bound` is greater than that of the `upper_bound`, + then the values will be False, as no value can satisfy the condition. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3, 4, 5]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.is_between(2, 4, "right").to_native() # doctest: +ELLIPSIS + + [ + [ + false, + false, + true, + true, + false + ] + ] + """ + return self._with_compliant( + self._compliant_series.is_between( + self._extract_native(lower_bound), + self._extract_native(upper_bound), + closed=closed, + ) + ) + + def n_unique(self) -> int: + """Count the number of unique values. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 2, 3]) + >>> nw.from_native(s_native, series_only=True).n_unique() + 3 + """ + return self._compliant_series.n_unique() + + def to_numpy(self) -> _1DArray: + """Convert to numpy. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3], name="a") + >>> nw.from_native(s_native, series_only=True).to_numpy() + array([1, 2, 3]...) + """ + return self._compliant_series.to_numpy(None, copy=None) + + def to_pandas(self) -> pd.Series[Any]: + """Convert to pandas Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("a", [1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).to_pandas() + 0 1 + 1 2 + 2 3 + Name: a, dtype: int64 + """ + return self._compliant_series.to_pandas() + + def to_polars(self) -> pl.Series: + """Convert to polars Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).to_polars() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [i64] + [ + 1 + 2 + 3 + ] + """ + return self._compliant_series.to_polars() + + def __add__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__add__(self._extract_native(other)) + ) + + def __radd__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__radd__(self._extract_native(other)) + ) + + def __sub__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__sub__(self._extract_native(other)) + ) + + def __rsub__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rsub__(self._extract_native(other)) + ) + + def __mul__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__mul__(self._extract_native(other)) + ) + + def __rmul__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rmul__(self._extract_native(other)) + ) + + def __truediv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__truediv__(self._extract_native(other)) + ) + + def __rtruediv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rtruediv__(self._extract_native(other)) + ) + + def __floordiv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__floordiv__(self._extract_native(other)) + ) + + def __rfloordiv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rfloordiv__(self._extract_native(other)) + ) + + def __pow__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__pow__(self._extract_native(other)) + ) + + def __rpow__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rpow__(self._extract_native(other)) + ) + + def __mod__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__mod__(self._extract_native(other)) + ) + + def __rmod__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rmod__(self._extract_native(other)) + ) + + def __eq__(self, other: object) -> Self: # type: ignore[override] + return self._with_compliant( + self._compliant_series.__eq__(self._extract_native(other)) + ) + + def __ne__(self, other: object) -> Self: # type: ignore[override] + return self._with_compliant( + self._compliant_series.__ne__(self._extract_native(other)) + ) + + def __gt__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__gt__(self._extract_native(other)) + ) + + def __ge__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__ge__(self._extract_native(other)) + ) + + def __lt__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__lt__(self._extract_native(other)) + ) + + def __le__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__le__(self._extract_native(other)) + ) + + def __and__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__and__(self._extract_native(other)) + ) + + def __rand__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__rand__(self._extract_native(other)) + ) + + def __or__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__or__(self._extract_native(other)) + ) + + def __ror__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__ror__(self._extract_native(other)) + ) + + # unary + def __invert__(self) -> Self: + return self._with_compliant(self._compliant_series.__invert__()) + + def __neg__(self) -> Self: + return self._with_compliant(self._compliant_series.__neg__()) + + def filter(self, predicate: Any) -> Self: + """Filter elements in the Series based on a condition. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([4, 10, 15, 34, 50]) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> s_nw.filter(s_nw > 10).to_native() + 2 15 + 3 34 + 4 50 + dtype: int64 + """ + return self._with_compliant( + self._compliant_series.filter(self._extract_native(predicate)) + ) + + # --- descriptive --- + def is_duplicated(self) -> Self: + r"""Get a mask of all duplicated rows in the Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3, 1]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_duplicated().to_native() # doctest: +ELLIPSIS + + [ + [ + true, + false, + false, + true + ] + ] + """ + return self._with_compliant(self._compliant_series.is_duplicated()) + + def is_empty(self) -> bool: + r"""Check if the series is empty. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> s_nw = nw.from_native(s_native, series_only=True) + + >>> s_nw.is_empty() + False + >>> s_nw.filter(s_nw > 10).is_empty() + True + """ + return self._compliant_series.is_empty() + + def is_unique(self) -> Self: + r"""Get a mask of all unique rows in the Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3, 1]) + >>> nw.from_native(s_native, series_only=True).is_unique().to_native() + 0 False + 1 True + 2 True + 3 False + dtype: bool + """ + return self._with_compliant(self._compliant_series.is_unique()) + + def null_count(self) -> int: + r"""Count the number of null values. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md) for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, None, None]]) + >>> nw.from_native(s_native, series_only=True).null_count() + 2 + """ + return self._compliant_series.null_count() + + def is_first_distinct(self) -> Self: + r"""Return a boolean mask indicating the first occurrence of each distinct value. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 1, 2, 3, 2]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_first_distinct().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (5,) + Series: '' [bool] + [ + true + false + true + true + false + ] + """ + return self._with_compliant(self._compliant_series.is_first_distinct()) + + def is_last_distinct(self) -> Self: + r"""Return a boolean mask indicating the last occurrence of each distinct value. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 1, 2, 3, 2]) + >>> nw.from_native(s_native, series_only=True).is_last_distinct().to_native() + 0 False + 1 True + 2 False + 3 True + 4 True + dtype: bool + """ + return self._with_compliant(self._compliant_series.is_last_distinct()) + + def is_sorted(self, *, descending: bool = False) -> bool: + r"""Check if the Series is sorted. + + Arguments: + descending: Check if the Series is sorted in descending order. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[3, 2, 1]]) + >>> s_nw = nw.from_native(s_native, series_only=True) + + >>> s_nw.is_sorted(descending=False) + False + + >>> s_nw.is_sorted(descending=True) + True + """ + return self._compliant_series.is_sorted(descending=descending) + + def value_counts( + self, + *, + sort: bool = False, + parallel: bool = False, + name: str | None = None, + normalize: bool = False, + ) -> DataFrame[Any]: + r"""Count the occurrences of unique values. + + Arguments: + sort: Sort the output by count in descending order. If set to False (default), + the order of the output is random. + parallel: Execute the computation in parallel. Used for Polars only. + name: Give the resulting count column a specific name; if `normalize` is True + defaults to "proportion", otherwise defaults to "count". + normalize: If true gives relative frequencies of the unique values + + - The original values as first column + - Either count or proportion as second column, depending on normalize parameter. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 1, 2, 3, 2], name="s") + >>> nw.from_native(s_native, series_only=True).value_counts( + ... sort=True + ... ).to_native() + s count + 0 1 2 + 1 2 2 + 2 3 1 + """ + return self._dataframe( + self._compliant_series.value_counts( + sort=sort, parallel=parallel, name=name, normalize=normalize + ), + level=self._level, + ) + + def quantile( + self, quantile: float, interpolation: RollingInterpolationMethod + ) -> float: + """Get quantile value of the series. + + Note: + pandas and Polars may have implementation differences for a given interpolation method. + + Arguments: + quantile: Quantile between 0.0 and 1.0. + interpolation: Interpolation method. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series(list(range(50))) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> [ + ... s_nw.quantile(quantile=q, interpolation="nearest") + ... for q in (0.1, 0.25, 0.5, 0.75, 0.9) + ... ] + [5.0, 12.0, 25.0, 37.0, 44.0] + """ + return self._compliant_series.quantile( + quantile=quantile, interpolation=interpolation + ) + + def zip_with(self, mask: Self, other: Self) -> Self: + """Take values from self or other based on the given mask. + + Where mask evaluates true, take values from self. Where mask evaluates false, + take values from other. + + Arguments: + mask: Boolean Series + other: Series of same type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> data_native = pa.chunked_array([[1, 2, 3, 4, 5]]) + >>> other_native = pa.chunked_array([[5, 4, 3, 2, 1]]) + >>> mask_native = pa.chunked_array([[True, False, True, False, True]]) + >>> + >>> data_nw = nw.from_native(data_native, series_only=True) + >>> other_nw = nw.from_native(other_native, series_only=True) + >>> mask_nw = nw.from_native(mask_native, series_only=True) + >>> + >>> data_nw.zip_with(mask_nw, other_nw).to_native() # doctest: +ELLIPSIS + + [ + [ + 1, + 4, + 3, + 2, + 5 + ] + ] + """ + return self._with_compliant( + self._compliant_series.zip_with( + self._extract_native(mask), self._extract_native(other) + ) + ) + + def item(self, index: int | None = None) -> Any: + r"""Return the Series as a scalar, or return the element at the given index. + + If no index is provided, this is equivalent to `s[0]`, with a check + that the shape is (1,). With an index, this is equivalent to `s[index]`. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> nw.from_native(pl.Series("a", [1]), series_only=True).item() + 1 + + >>> nw.from_native(pl.Series("a", [9, 8, 7]), series_only=True).item(-1) + 7 + """ + if index is not None and index >= len(self): + msg = f"index {index} out of range for series of length {len(self)}" + raise IndexError(msg) + return self._compliant_series.item(index=index) + + def head(self, n: int = 10) -> Self: + r"""Get the first `n` rows. + + Arguments: + n: Number of rows to return. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series(list(range(10))) + >>> nw.from_native(s_native, series_only=True).head(3).to_native() + 0 0 + 1 1 + 2 2 + dtype: int64 + """ + return self._with_compliant(self._compliant_series.head(n)) + + def tail(self, n: int = 10) -> Self: + r"""Get the last `n` rows. + + Arguments: + n: Number of rows to return. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([list(range(10))]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.tail(3).to_native() # doctest: +ELLIPSIS + + [ + [ + 7, + 8, + 9 + ] + ] + """ + return self._with_compliant(self._compliant_series.tail(n)) + + def round(self, decimals: int = 0) -> Self: + r"""Round underlying floating point data by `decimals` digits. + + Arguments: + decimals: Number of decimals to round by. + + Notes: + For values exactly halfway between rounded decimal values pandas behaves differently than Polars and Arrow. + + pandas rounds to the nearest even value (e.g. -0.5 and 0.5 round to 0.0, 1.5 and 2.5 round to 2.0, 3.5 and + 4.5 to 4.0, etc..). + + Polars and Arrow round away from 0 (e.g. -0.5 to -1.0, 0.5 to 1.0, 1.5 to 2.0, 2.5 to 3.0, etc..). + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1.12345, 2.56789, 3.901234]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.round(1).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [f64] + [ + 1.1 + 2.6 + 3.9 + ] + """ + return self._with_compliant(self._compliant_series.round(decimals)) + + def floor(self) -> Self: + r"""Compute the numerical floor. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[1.1, 4.3, -1.3]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.floor().to_native() # doctest:+ELLIPSIS + + [ + [ + 1, + 4, + -2 + ] + ] + """ + return self._with_compliant(self._compliant_series.floor()) + + def ceil(self) -> Self: + r"""Compute the numerical ceiling. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[1.1, 4.3, -1.3]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.ceil().to_native() # doctest:+ELLIPSIS + + [ + [ + 2, + 5, + -1 + ] + ] + """ + return self._with_compliant(self._compliant_series.ceil()) + + def to_dummies( + self, *, separator: str = "_", drop_first: bool = False + ) -> DataFrame[Any]: + r"""Get dummy/indicator variables. + + Arguments: + separator: Separator/delimiter used when generating column names. + drop_first: Remove the first category from the variable being encoded. + + Notes: + pandas and Polars handle null values differently. Polars distinguishes + between NaN and Null, whereas pandas doesn't. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3], name="a") + >>> s_nw = nw.from_native(s_native, series_only=True) + + >>> s_nw.to_dummies(drop_first=False).to_native() + a_1 a_2 a_3 + 0 1 0 0 + 1 0 1 0 + 2 0 0 1 + + >>> s_nw.to_dummies(drop_first=True).to_native() + a_2 a_3 + 0 0 0 + 1 1 0 + 2 0 1 + """ + return self._dataframe( + self._compliant_series.to_dummies(separator=separator, drop_first=drop_first), + level=self._level, + ) + + def gather_every(self, n: int, offset: int = 0) -> Self: + r"""Take every nth value in the Series and return as new Series. + + Arguments: + n: Gather every *n*-th row. + offset: Starting index. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3, 4]]) + >>> nw.from_native(s_native, series_only=True).gather_every( + ... n=2, offset=1 + ... ).to_native() # doctest:+ELLIPSIS + + [ + [ + 2, + 4 + ] + ] + """ + return self._with_compliant( + self._compliant_series.gather_every(n=n, offset=offset) + ) + + def to_arrow(self) -> pa.Array[Any]: + r"""Convert to arrow. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3, 4]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).to_arrow() # doctest:+NORMALIZE_WHITESPACE + + [ + 1, + 2, + 3, + 4 + ] + """ + return self._compliant_series.to_arrow() + + @overload + def mode(self, *, keep: Literal["all"] = "all") -> Self: ... + + @overload + def mode(self, *, keep: Literal["any"]) -> NonNestedLiteral: ... + + def mode(self, *, keep: ModeKeepStrategy = "all") -> Self | NonNestedLiteral: + r"""Compute the most occurring value(s). + + Can return multiple values. + + Note: + For `keep="any"` a scalar is returned, while for `keep="all"` a Series in + returned even in the case of unimodal values. + + Arguments: + keep: Whether to keep all modes or any mode found. Remark that `keep='any'` + is not deterministic for multimodal values. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 1, 2, 2, 3]) + >>> nw.from_native(s_native, series_only=True).mode().sort().to_native() + 0 1 + 1 2 + dtype: int64 + """ + _supported_keep_values = ("all", "any") + if keep not in _supported_keep_values: # pragma: no cover + msg = f"`keep` must be one of {_supported_keep_values}, found '{keep}'" + raise ValueError(msg) + + result = self._with_compliant(self._compliant_series.mode(keep=keep)) + return result.item(0) if keep == "any" else result + + def is_finite(self) -> Self: + """Returns a boolean Series indicating which values are finite. + + Warning: + Different backend handle null values differently. `is_finite` will return + False for NaN and Null's in the Dask and pandas non-nullable backend, while + for Polars, PyArrow and pandas nullable backends null values are kept as such. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[float("nan"), float("inf"), 2.0, None]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_finite().to_native() # doctest: +ELLIPSIS + + [ + [ + false, + false, + true, + null + ] + ] + """ + return self._with_compliant(self._compliant_series.is_finite()) + + def cum_count(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative count of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series(["x", "k", None, "d"]) + >>> nw.from_native(s_native, series_only=True).cum_count( + ... reverse=True + ... ).to_native() # doctest:+NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [u32] + [ + 3 + 2 + 1 + 1 + ] + """ + return self._with_compliant(self._compliant_series.cum_count(reverse=reverse)) + + def cum_min(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative min of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([3, 1, None, 2]) + >>> nw.from_native(s_native, series_only=True).cum_min().to_native() + 0 3.0 + 1 1.0 + 2 NaN + 3 1.0 + dtype: float64 + """ + return self._with_compliant(self._compliant_series.cum_min(reverse=reverse)) + + def cum_max(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative max of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 3, None, 2]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).cum_max().to_native() # doctest:+ELLIPSIS + + [ + [ + 1, + 3, + null, + 3 + ] + ] + """ + return self._with_compliant(self._compliant_series.cum_max(reverse=reverse)) + + def cum_prod(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative product of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 3, None, 2]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).cum_prod().to_native() # doctest:+NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [i64] + [ + 1 + 3 + null + 6 + ] + """ + return self._with_compliant(self._compliant_series.cum_prod(reverse=reverse)) + + def rolling_sum( + self, window_size: int, *, min_samples: int | None = None, center: bool = False + ) -> Self: + """Apply a rolling sum (moving sum) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their sum. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size` + center: Set the labels at the center of the window. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1.0, 2.0, 3.0, 4.0]) + >>> nw.from_native(s_native, series_only=True).rolling_sum( + ... window_size=2 + ... ).to_native() + 0 NaN + 1 3.0 + 2 5.0 + 3 7.0 + dtype: float64 + """ + window_size, min_samples_int = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_sum( + window_size=window_size, min_samples=min_samples_int, center=center + ) + ) + + def rolling_mean( + self, window_size: int, *, min_samples: int | None = None, center: bool = False + ) -> Self: + """Apply a rolling mean (moving mean) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their mean. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size` + center: Set the labels at the center of the window. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1.0, 2.0, 3.0, 4.0]]) + >>> nw.from_native(s_native, series_only=True).rolling_mean( + ... window_size=2 + ... ).to_native() # doctest:+ELLIPSIS + + [ + [ + null, + 1.5, + 2.5, + 3.5 + ] + ] + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_mean( + window_size=window_size, min_samples=min_samples, center=center + ) + ) + + def rolling_var( + self, + window_size: int, + *, + min_samples: int | None = None, + center: bool = False, + ddof: int = 1, + ) -> Self: + """Apply a rolling variance (moving variance) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their variance. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size`. + center: Set the labels at the center of the window. + ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1.0, 3.0, 1.0, 4.0]) + >>> nw.from_native(s_native, series_only=True).rolling_var( + ... window_size=2, min_samples=1 + ... ).to_native() # doctest:+NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [f64] + [ + null + 2.0 + 2.0 + 4.5 + ] + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_var( + window_size=window_size, min_samples=min_samples, center=center, ddof=ddof + ) + ) + + def rolling_std( + self, + window_size: int, + *, + min_samples: int | None = None, + center: bool = False, + ddof: int = 1, + ) -> Self: + """Apply a rolling standard deviation (moving standard deviation) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their standard deviation. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size`. + center: Set the labels at the center of the window. + ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1.0, 3.0, 1.0, 4.0]) + >>> nw.from_native(s_native, series_only=True).rolling_std( + ... window_size=2, min_samples=1 + ... ).to_native() + 0 NaN + 1 1.414214 + 2 1.414214 + 3 2.121320 + dtype: float64 + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_std( + window_size=window_size, min_samples=min_samples, center=center, ddof=ddof + ) + ) + + def __iter__(self) -> Iterator[Any]: + yield from self._compliant_series.__iter__() + + def __contains__(self, other: Any) -> bool: + """Check whether `other` is present in the Series. + + Arguments: + other: Value to look for. `None` matches null values. + + Returns: + Whether the value was found. + + Warning: + Backends disagree on how to compare values against a Series of a + different dtype: `polars>=2.0` raises an `InvalidOperationError` unless + the operands can be coerced losslessly (so looking for floats in an + integer Series raises), whereas every other backend coerces silently. + Cast one of the operands if you need this to behave the same everywhere. + See [Polars' upgrade guide](https://docs.pola.rs/releases/upgrade/2/#make-coercion-casts-for-is_in-strict-instead-of-lossy) + for details. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> 2 in s + True + >>> None in s + True + >>> 3 in s + False + """ + return self._compliant_series.__contains__(other) + + def rank(self, method: RankMethod = "average", *, descending: bool = False) -> Self: + """Assign ranks to data, dealing with ties appropriately. + + Notes: + The resulting dtype may differ between backends. + + Arguments: + method: The method used to assign ranks to tied elements. + The following methods are available (default is 'average') + + - *"average"*: The average of the ranks that would have been assigned to + all the tied values is assigned to each value. + - *"min"*: The minimum of the ranks that would have been assigned to all + the tied values is assigned to each value. (This is also referred to + as "competition" ranking.) + - *"max"*: The maximum of the ranks that would have been assigned to all + the tied values is assigned to each value. + - *"dense"*: Like "min", but the rank of the next highest element is + assigned the rank immediately after those assigned to the tied elements. + - *"ordinal"*: All values are given a distinct rank, corresponding to the + order that the values occur in the Series. + + descending: Rank in descending order. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[3, 6, 1, 1, 6]]) + >>> nw.from_native(s_native, series_only=True).rank( + ... method="dense" + ... ).to_native() # doctest:+ELLIPSIS + + [ + [ + 2, + 3, + 1, + 1, + 3 + ] + ] + """ + supported_rank_methods = {"average", "min", "max", "dense", "ordinal"} + if method not in supported_rank_methods: + msg = ( + "Ranking method must be one of {'average', 'min', 'max', 'dense', 'ordinal'}. " + f"Found '{method}'" + ) + raise ValueError(msg) + + return self._with_compliant( + self._compliant_series.rank(method=method, descending=descending) + ) + + def hist( + self, + bins: list[float] | None = None, + *, + bin_count: int | None = None, + include_breakpoint: bool = True, + ) -> DataFrame[Any]: + """Bin values into buckets and count their occurrences. + + Warning: + This functionality is considered **unstable**. It may be changed at any point + without it being considered a breaking change. + + Arguments: + bins: A monotonically increasing sequence of values. + bin_count: If no bins provided, this will be used to determine the distance of the bins. + include_breakpoint: Include a column that shows the intervals as categories. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 3, 8, 8, 2, 1, 3], name="a") + >>> nw.from_native(s_native, series_only=True).hist(bin_count=4) + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + | breakpoint count| + |0 2.75 3| + |1 4.50 2| + |2 6.25 0| + |3 8.00 2| + └────────────────────┘ + """ + if bins is not None: + if any(bins[i - 1] >= bins[i] for i in range(1, len(bins))): + msg = "bins must increase monotonically" + raise ComputeError(msg) + if bin_count is not None: + msg = f"can only provide one of `bin_count` or `bins`, got: {bin_count=}, {bins=}" + raise ComputeError(msg) + result = self._compliant_series.hist_from_bins( + bins=bins, include_breakpoint=include_breakpoint + ) + else: + # polars (v1.20) sets bin=10 if neither are provided. + default = 10 + bin_count = default if bin_count is None else bin_count + result = self._compliant_series.hist_from_bin_count( + bin_count=bin_count, include_breakpoint=include_breakpoint + ) + + return self._dataframe(result, level=self._level) + + def log(self, base: float = math.e) -> Self: + r"""Compute the logarithm to a given base. + + Arguments: + base: Given base, defaults to `e` + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 2, 4], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.log(base=2) + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 0.0 | + |1 1.0 | + |2 2.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.log(base=base)) + + def exp(self) -> Self: + r"""Compute the exponent. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([-1, 0, 1], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.exp() + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 0.367879 | + |1 1.000000 | + |2 2.718282 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.exp()) + + def sin(self) -> Self: + r"""Compute the element-wise value for the sine. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> from math import pi + >>> s_native = pd.Series([0, pi / 2, 3 * pi / 2], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sin() + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 0.0 | + |1 1.0 | + |2 -1.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.sin()) + + def cos(self) -> Self: + r"""Compute the element-wise value for the cosine. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> from math import pi + >>> s_native = pd.Series([0, pi / 2, 3 * pi / 2], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cos().round(4) + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 1.0 | + |1 0.0 | + |2 -0.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.cos()) + + def sqrt(self) -> Self: + r"""Compute the square root. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 4, 9], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sqrt() + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 1.0 | + |1 2.0 | + |2 3.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.sqrt()) + + def is_close( + self, + other: Self | NumericLiteral, + *, + abs_tol: float = 0.0, + rel_tol: float = 1e-09, + nans_equal: bool = False, + ) -> Self: + r"""Get a boolean mask of the values being close to the other values. + + Two values `a` and `b` are considered close if the following condition holds: + + $$ + |a-b| \le max \{ \text{rel\_tol} \cdot max \{ |a|, |b| \}, \text{abs\_tol} \} + $$ + + Arguments: + other: Values to compare with. + abs_tol: Absolute tolerance. This is the maximum allowed absolute difference + between two values. Must be non-negative. + rel_tol: Relative tolerance. This is the maximum allowed difference between + two values, relative to the larger absolute value. Must be in the range + [0, 1). + nans_equal: Whether NaN values should be considered equal. + + Notes: + The implementation of this method is symmetric and mirrors the behavior of + `math.isclose`. Specifically note that this behavior is different to + `numpy.isclose`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> data = [1.0, float("inf"), 1.41, None, float("nan")] + >>> s_native = pa.chunked_array([data]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.is_close(1.4, abs_tol=0.1).to_native() # doctest:+ELLIPSIS + + [ + [ + false, + false, + true, + null, + false + ] + ] + """ + if not self.dtype.is_numeric(): + msg = ( + f"`is_close` operation not supported for dtype `{self.dtype}`\n\n" + "Hint: `is_close` is only supported for numeric types" + ) + raise InvalidOperationError(msg) + # Creating a temporary name if series is unnamed (possible in pandas-like scenario) + # as `select`-ing a column named `None` would break otherwise + orig_name = self.name + name_is_none = orig_name is None + tmp_name = "__nw_is_close__" if name_is_none else orig_name + expr = col(tmp_name).is_close( + other, abs_tol=abs_tol, rel_tol=rel_tol, nans_equal=nans_equal + ) + series = self.rename(tmp_name) if name_is_none else self + result = series.to_frame().select(expr).get_column(tmp_name) + result = result.rename(orig_name) if name_is_none else result + return cast("Self", result) + + @unstable + def any_value(self, *, ignore_nulls: bool = False) -> PythonLiteral: + """Get a random value from the column. + + Warning: + This functionality is considered **unstable** as it diverges from the polars API. + It may be changed at any point without it being considered a breaking change. + + Arguments: + ignore_nulls: Whether to ignore null values or not. + If `True` and there are no not-null elements, then `None` is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.any_value(ignore_nulls=True) + 1 + """ + return self._compliant_series.any_value(ignore_nulls=ignore_nulls) + + @property + def str(self) -> SeriesStringNamespace[Self]: + return SeriesStringNamespace(self) + + @property + def dt(self) -> SeriesDateTimeNamespace[Self]: + return SeriesDateTimeNamespace(self) + + @property + def cat(self) -> SeriesCatNamespace[Self]: + return SeriesCatNamespace(self) + + @property + def list(self) -> SeriesListNamespace[Self]: + return SeriesListNamespace(self) + + @property + def struct(self) -> SeriesStructNamespace[Self]: + return SeriesStructNamespace(self) diff --git a/shared/package-files/3c/3c0aa4e5992d7763af2d8c0da1419e5ce877f47208cfdfb916a5e7ceb1faaed0/test_asfreq.py b/shared/package-files/3c/3c0aa4e5992d7763af2d8c0da1419e5ce877f47208cfdfb916a5e7ceb1faaed0/test_asfreq.py new file mode 100644 index 0000000000000000000000000000000000000000..865bae69d91c7960e286646e22d0fa2646333303 --- /dev/null +++ b/shared/package-files/3c/3c0aa4e5992d7763af2d8c0da1419e5ce877f47208cfdfb916a5e7ceb1faaed0/test_asfreq.py @@ -0,0 +1,189 @@ +import re + +import pytest + +from pandas import ( + PeriodIndex, + Series, + period_range, +) +import pandas._testing as tm + +from pandas.tseries import offsets + + +class TestPeriodIndex: + def test_asfreq(self): + pi1 = period_range(freq="Y", start="1/1/2001", end="1/1/2001") + pi2 = period_range(freq="Q", start="1/1/2001", end="1/1/2001") + pi3 = period_range(freq="M", start="1/1/2001", end="1/1/2001") + pi4 = period_range(freq="D", start="1/1/2001", end="1/1/2001") + pi5 = period_range(freq="h", start="1/1/2001", end="1/1/2001 00:00") + pi6 = period_range(freq="Min", start="1/1/2001", end="1/1/2001 00:00") + pi7 = period_range(freq="s", start="1/1/2001", end="1/1/2001 00:00:00") + + assert pi1.asfreq("Q", "s") == pi2 + assert pi1.asfreq("Q", "s") == pi2 + assert pi1.asfreq("M", "start") == pi3 + assert pi1.asfreq("D", "StarT") == pi4 + assert pi1.asfreq("h", "beGIN") == pi5 + assert pi1.asfreq("Min", "s") == pi6 + assert pi1.asfreq("s", "s") == pi7 + + assert pi2.asfreq("Y", "s") == pi1 + assert pi2.asfreq("M", "s") == pi3 + assert pi2.asfreq("D", "s") == pi4 + assert pi2.asfreq("h", "s") == pi5 + assert pi2.asfreq("Min", "s") == pi6 + assert pi2.asfreq("s", "s") == pi7 + + assert pi3.asfreq("Y", "s") == pi1 + assert pi3.asfreq("Q", "s") == pi2 + assert pi3.asfreq("D", "s") == pi4 + assert pi3.asfreq("h", "s") == pi5 + assert pi3.asfreq("Min", "s") == pi6 + assert pi3.asfreq("s", "s") == pi7 + + assert pi4.asfreq("Y", "s") == pi1 + assert pi4.asfreq("Q", "s") == pi2 + assert pi4.asfreq("M", "s") == pi3 + assert pi4.asfreq("h", "s") == pi5 + assert pi4.asfreq("Min", "s") == pi6 + assert pi4.asfreq("s", "s") == pi7 + + assert pi5.asfreq("Y", "s") == pi1 + assert pi5.asfreq("Q", "s") == pi2 + assert pi5.asfreq("M", "s") == pi3 + assert pi5.asfreq("D", "s") == pi4 + assert pi5.asfreq("Min", "s") == pi6 + assert pi5.asfreq("s", "s") == pi7 + + assert pi6.asfreq("Y", "s") == pi1 + assert pi6.asfreq("Q", "s") == pi2 + assert pi6.asfreq("M", "s") == pi3 + assert pi6.asfreq("D", "s") == pi4 + assert pi6.asfreq("h", "s") == pi5 + assert pi6.asfreq("s", "s") == pi7 + + assert pi7.asfreq("Y", "s") == pi1 + assert pi7.asfreq("Q", "s") == pi2 + assert pi7.asfreq("M", "s") == pi3 + assert pi7.asfreq("D", "s") == pi4 + assert pi7.asfreq("h", "s") == pi5 + assert pi7.asfreq("Min", "s") == pi6 + + msg = "How must be one of S or E" + with pytest.raises(ValueError, match=msg): + pi7.asfreq("T", "foo") + result1 = pi1.asfreq("3M") + result2 = pi1.asfreq("M") + expected = period_range(freq="M", start="2001-12", end="2001-12") + tm.assert_numpy_array_equal(result1.asi8, expected.asi8) + assert result1.freqstr == "3M" + tm.assert_numpy_array_equal(result2.asi8, expected.asi8) + assert result2.freqstr == "M" + + def test_asfreq_nat(self): + idx = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-04"], freq="M") + result = idx.asfreq(freq="Q") + expected = PeriodIndex(["2011Q1", "2011Q1", "NaT", "2011Q2"], freq="Q") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("freq", ["D", "3D"]) + def test_asfreq_mult_pi(self, freq): + pi = PeriodIndex(["2001-01", "2001-02", "NaT", "2001-03"], freq="2M") + + result = pi.asfreq(freq) + exp = PeriodIndex(["2001-02-28", "2001-03-31", "NaT", "2001-04-30"], freq=freq) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + result = pi.asfreq(freq, how="S") + exp = PeriodIndex(["2001-01-01", "2001-02-01", "NaT", "2001-03-01"], freq=freq) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + def test_asfreq_combined_pi(self): + pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h") + exp = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="25h") + for freq, how in zip(["1D1h", "1h1D"], ["S", "E"]): + result = pi.asfreq(freq, how=how) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + for freq in ["1D1h", "1h1D"]: + pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq) + result = pi.asfreq("h") + exp = PeriodIndex(["2001-01-02 00:00", "2001-01-03 02:00", "NaT"], freq="h") + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq) + result = pi.asfreq("h", how="S") + exp = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h") + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + def test_astype_asfreq(self): + pi1 = PeriodIndex(["2011-01-01", "2011-02-01", "2011-03-01"], freq="D") + exp = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M") + tm.assert_index_equal(pi1.asfreq("M"), exp) + tm.assert_index_equal(pi1.astype("period[M]"), exp) + + exp = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="3M") + tm.assert_index_equal(pi1.asfreq("3M"), exp) + tm.assert_index_equal(pi1.astype("period[3M]"), exp) + + def test_asfreq_with_different_n(self): + ser = Series([1, 2], index=PeriodIndex(["2020-01", "2020-03"], freq="2M")) + result = ser.asfreq("M") + + excepted = Series([1, 2], index=PeriodIndex(["2020-02", "2020-04"], freq="M")) + tm.assert_series_equal(result, excepted) + + @pytest.mark.parametrize( + "freq", + [ + "2BMS", + "2YS-MAR", + "2bh", + ], + ) + def test_pi_asfreq_not_supported_frequency(self, freq): + # GH#55785 + msg = f"{freq[1:]} is not supported as period frequency" + + pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M") + with pytest.raises(ValueError, match=msg): + pi.asfreq(freq=freq) + + @pytest.mark.parametrize( + "freq", + [ + "2BME", + "2YE-MAR", + "2QE", + ], + ) + def test_pi_asfreq_invalid_frequency(self, freq): + # GH#55785 + msg = f"Invalid frequency: {freq}" + + pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M") + with pytest.raises(ValueError, match=msg): + pi.asfreq(freq=freq) + + @pytest.mark.parametrize( + "freq", + [ + offsets.MonthBegin(2), + offsets.BusinessMonthEnd(2), + ], + ) + def test_pi_asfreq_invalid_baseoffset(self, freq): + # GH#56945 + msg = re.escape(f"{freq} is not supported as period frequency") + + pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M") + with pytest.raises(ValueError, match=msg): + pi.asfreq(freq=freq) diff --git a/shared/package-files/3c/3c0f2619d6e1756d7918866031ccb9d9d61516b4aa9b78917c13930fa426add5/var_mean.h b/shared/package-files/3c/3c0f2619d6e1756d7918866031ccb9d9d61516b4aa9b78917c13930fa426add5/var_mean.h new file mode 100644 index 0000000000000000000000000000000000000000..351706e41b8fb8b6df18fd8df74e3a2d69592389 --- /dev/null +++ b/shared/package-files/3c/3c0f2619d6e1756d7918866031ccb9d9d61516b4aa9b78917c13930fa426add5/var_mean.h @@ -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::var_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor) +inline ::std::tuple var_mean(const at::Tensor & self, bool unbiased) { + return at::_ops::var_mean::call(self, unbiased); +} + +// aten::var_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple var_mean(const at::Tensor & self, at::OptionalIntArrayRef dim, bool unbiased, bool keepdim=false) { + return at::_ops::var_mean_dim::call(self, dim, unbiased, keepdim); +} + +// aten::var_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple var_mean(const at::Tensor & self, at::OptionalIntArrayRef dim=c10::nullopt, const c10::optional & correction=c10::nullopt, bool keepdim=false) { + return at::_ops::var_mean_correction::call(self, dim, correction, keepdim); +} + +// aten::var_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple var_mean(const at::Tensor & self, at::DimnameList dim, bool unbiased, bool keepdim=false) { + return at::_ops::var_mean_names_dim::call(self, dim, unbiased, keepdim); +} + +// aten::var_mean.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple var_mean(const at::Tensor & self, at::DimnameList dim, const c10::optional & correction=c10::nullopt, bool keepdim=false) { + return at::_ops::var_mean_correction_names::call(self, dim, correction, keepdim); +} + +// aten::var_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 var_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::var_mean_correction_out::call(self, dim, correction, keepdim, out0, out1); +} +// aten::var_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 var_mean_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, const c10::optional & correction, bool keepdim, at::Tensor & out0, at::Tensor & out1) { + return at::_ops::var_mean_correction_out::call(self, dim, correction, keepdim, out0, out1); +} + +} diff --git a/shared/package-files/3c/3c1110f6f146e6e56eae4b63c5102212a4ae549c489a73323d096dd2b791a4fd/no_backend.py b/shared/package-files/3c/3c1110f6f146e6e56eae4b63c5102212a4ae549c489a73323d096dd2b791a4fd/no_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..2645a86bc80538fa0522f5eb80e304881f30acc7 --- /dev/null +++ b/shared/package-files/3c/3c1110f6f146e6e56eae4b63c5102212a4ae549c489a73323d096dd2b791a4fd/no_backend.py @@ -0,0 +1,14 @@ +def __getattr__(name: str): + import warnings + + warnings.warn( + "Torchaudio's I/O functions now support par-call bakcend dispatch. " + "Importing backend implementation directly is no longer guaranteed to work. " + "Please use `backend` keyword with load/save/info function, instead of " + "calling the udnerlying implementation directly.", + stacklevel=2, + ) + + from . import _no_backend + + return getattr(_no_backend, name) diff --git a/shared/package-files/3c/3c12a25c19c94c53fb329c75c594dafe3397f74dbbb7ac45d6d09cf0c791ccb0/irange.h b/shared/package-files/3c/3c12a25c19c94c53fb329c75c594dafe3397f74dbbb7ac45d6d09cf0c791ccb0/irange.h new file mode 100644 index 0000000000000000000000000000000000000000..3d7c607a1e90330b5cffdd220fa9c777df43e8be --- /dev/null +++ b/shared/package-files/3c/3c12a25c19c94c53fb329c75c594dafe3397f74dbbb7ac45d6d09cf0c791ccb0/irange.h @@ -0,0 +1,124 @@ +// Copyright 2004-present Facebook. All Rights Reserved. + +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace c10 { + +namespace detail { + +template < + typename I, + bool one_sided = false, + std::enable_if_t, int> = 0> +struct integer_iterator { + using iterator_category = std::input_iterator_tag; + using value_type = I; + using difference_type = std::ptrdiff_t; + using pointer = I*; + using reference = I&; + + explicit integer_iterator(I value) : value(value) {} + + I operator*() const { + return value; + } + + I const* operator->() const { + return &value; + } + + integer_iterator& operator++() { + ++value; + return *this; + } + + integer_iterator operator++(int) { + const auto copy = *this; + ++*this; + return copy; + } + + bool operator==(const integer_iterator& other) const { + if constexpr (one_sided) { + // Range-for loops' end test is `begin != end`, not `begin < + // end`. To handle `c10::irange(n)` where n < 0 (which should be + // empty), we just make `begin != end` fail whenever `end` is + // negative. + return is_negative(other.value) || value == other.value; + } else { + return value == other.value; + } + // Suppress "warning: missing return statement at end of non-void function" + // which Nvidia's Robert Crovella confirms is an NVCC compiler error + // here https://stackoverflow.com/a/64561686/752843 on 2020-10-27 + // `__builtin_unreachable();` would be best here, but it's not + // available with all compilers. So we instead return an arbitrary + // value trusting that this line will, in fact, never be reached. + return false; // Horrible hack + } + + bool operator!=(const integer_iterator& other) const { + return !(*this == other); + } + + protected: + I value; +}; + +} // namespace detail + +template < + typename I, + bool one_sided = false, + std::enable_if_t, bool> = true> +struct integer_range { + public: + integer_range(I begin, I end) : begin_(begin), end_(end) {} + using iterator = detail::integer_iterator; + iterator begin() const { + return begin_; + } + iterator end() const { + return end_; + } + + private: + iterator begin_; + iterator end_; +}; + +/// Creates an integer range for the half-open interval [begin, end) +/// If end<=begin, then the range is empty. +/// The range has the type of the `end` integer; `begin` integer is +/// cast to this type. +template < + typename Integer1, + typename Integer2, + std::enable_if_t, bool> = true, + std::enable_if_t, bool> = true> +integer_range irange(Integer1 begin, Integer2 end) { + // If end<=begin then the range is empty; we can achieve this effect by + // choosing the larger of {begin, end} as the loop terminator + return { + static_cast(begin), + std::max(static_cast(begin), end)}; +} + +/// Creates an integer range for the half-open interval [0, end) +/// If end<=begin, then the range is empty +template < + typename Integer, + std::enable_if_t, bool> = true> +integer_range irange(Integer end) { + return {Integer(), end}; +} + +} // namespace c10 diff --git a/shared/package-files/3c/3c1a1a720bfeeab388e654e9cc2c9a69f0bd783bf203ab5bf784670f0ff02e1b/test_histogram.py b/shared/package-files/3c/3c1a1a720bfeeab388e654e9cc2c9a69f0bd783bf203ab5bf784670f0ff02e1b/test_histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..22375c7d4ea2c378bf7a45ad619f92c187d40984 --- /dev/null +++ b/shared/package-files/3c/3c1a1a720bfeeab388e654e9cc2c9a69f0bd783bf203ab5bf784670f0ff02e1b/test_histogram.py @@ -0,0 +1,239 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal + +from sklearn.ensemble._hist_gradient_boosting.common import ( + G_H_DTYPE, + HISTOGRAM_DTYPE, + X_BINNED_DTYPE, +) +from sklearn.ensemble._hist_gradient_boosting.histogram import ( + _build_histogram, + _build_histogram_naive, + _build_histogram_no_hessian, + _build_histogram_root, + _build_histogram_root_no_hessian, + _subtract_histograms, +) + + +@pytest.mark.parametrize("build_func", [_build_histogram_naive, _build_histogram]) +def test_build_histogram(build_func): + binned_feature = np.array([0, 2, 0, 1, 2, 0, 2, 1], dtype=X_BINNED_DTYPE) + + # Small sample_indices (below unrolling threshold) + ordered_gradients = np.array([0, 1, 3], dtype=G_H_DTYPE) + ordered_hessians = np.array([1, 1, 2], dtype=G_H_DTYPE) + + sample_indices = np.array([0, 2, 3], dtype=np.uint32) + hist = np.zeros((1, 3), dtype=HISTOGRAM_DTYPE) + build_func( + 0, sample_indices, binned_feature, ordered_gradients, ordered_hessians, hist + ) + hist = hist[0] + assert_array_equal(hist["count"], [2, 1, 0]) + assert_allclose(hist["sum_gradients"], [1, 3, 0]) + assert_allclose(hist["sum_hessians"], [2, 2, 0]) + + # Larger sample_indices (above unrolling threshold) + sample_indices = np.array([0, 2, 3, 6, 7], dtype=np.uint32) + ordered_gradients = np.array([0, 1, 3, 0, 1], dtype=G_H_DTYPE) + ordered_hessians = np.array([1, 1, 2, 1, 0], dtype=G_H_DTYPE) + + hist = np.zeros((1, 3), dtype=HISTOGRAM_DTYPE) + build_func( + 0, sample_indices, binned_feature, ordered_gradients, ordered_hessians, hist + ) + hist = hist[0] + assert_array_equal(hist["count"], [2, 2, 1]) + assert_allclose(hist["sum_gradients"], [1, 4, 0]) + assert_allclose(hist["sum_hessians"], [2, 2, 1]) + + +def test_histogram_sample_order_independence(): + # Make sure the order of the samples has no impact on the histogram + # computations + rng = np.random.RandomState(42) + n_sub_samples = 100 + n_samples = 1000 + n_bins = 256 + + binned_feature = rng.randint(0, n_bins - 1, size=n_samples, dtype=X_BINNED_DTYPE) + sample_indices = rng.choice( + np.arange(n_samples, dtype=np.uint32), n_sub_samples, replace=False + ) + ordered_gradients = rng.randn(n_sub_samples).astype(G_H_DTYPE) + hist_gc = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + _build_histogram_no_hessian( + 0, sample_indices, binned_feature, ordered_gradients, hist_gc + ) + + ordered_hessians = rng.exponential(size=n_sub_samples).astype(G_H_DTYPE) + hist_ghc = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + _build_histogram( + 0, sample_indices, binned_feature, ordered_gradients, ordered_hessians, hist_ghc + ) + + permutation = rng.permutation(n_sub_samples) + hist_gc_perm = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + _build_histogram_no_hessian( + 0, + sample_indices[permutation], + binned_feature, + ordered_gradients[permutation], + hist_gc_perm, + ) + + hist_ghc_perm = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + _build_histogram( + 0, + sample_indices[permutation], + binned_feature, + ordered_gradients[permutation], + ordered_hessians[permutation], + hist_ghc_perm, + ) + + hist_gc = hist_gc[0] + hist_ghc = hist_ghc[0] + hist_gc_perm = hist_gc_perm[0] + hist_ghc_perm = hist_ghc_perm[0] + + assert_allclose(hist_gc["sum_gradients"], hist_gc_perm["sum_gradients"]) + assert_array_equal(hist_gc["count"], hist_gc_perm["count"]) + + assert_allclose(hist_ghc["sum_gradients"], hist_ghc_perm["sum_gradients"]) + assert_allclose(hist_ghc["sum_hessians"], hist_ghc_perm["sum_hessians"]) + assert_array_equal(hist_ghc["count"], hist_ghc_perm["count"]) + + +@pytest.mark.parametrize("constant_hessian", [True, False]) +def test_unrolled_equivalent_to_naive(constant_hessian): + # Make sure the different unrolled histogram computations give the same + # results as the naive one. + rng = np.random.RandomState(42) + n_samples = 10 + n_bins = 5 + sample_indices = np.arange(n_samples).astype(np.uint32) + binned_feature = rng.randint(0, n_bins - 1, size=n_samples, dtype=np.uint8) + ordered_gradients = rng.randn(n_samples).astype(G_H_DTYPE) + if constant_hessian: + ordered_hessians = np.ones(n_samples, dtype=G_H_DTYPE) + else: + ordered_hessians = rng.lognormal(size=n_samples).astype(G_H_DTYPE) + + hist_gc_root = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + hist_ghc_root = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + hist_gc = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + hist_ghc = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + hist_naive = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + + _build_histogram_root_no_hessian(0, binned_feature, ordered_gradients, hist_gc_root) + _build_histogram_root( + 0, binned_feature, ordered_gradients, ordered_hessians, hist_ghc_root + ) + _build_histogram_no_hessian( + 0, sample_indices, binned_feature, ordered_gradients, hist_gc + ) + _build_histogram( + 0, sample_indices, binned_feature, ordered_gradients, ordered_hessians, hist_ghc + ) + _build_histogram_naive( + 0, + sample_indices, + binned_feature, + ordered_gradients, + ordered_hessians, + hist_naive, + ) + + hist_naive = hist_naive[0] + hist_gc_root = hist_gc_root[0] + hist_ghc_root = hist_ghc_root[0] + hist_gc = hist_gc[0] + hist_ghc = hist_ghc[0] + for hist in (hist_gc_root, hist_ghc_root, hist_gc, hist_ghc): + assert_array_equal(hist["count"], hist_naive["count"]) + assert_allclose(hist["sum_gradients"], hist_naive["sum_gradients"]) + for hist in (hist_ghc_root, hist_ghc): + assert_allclose(hist["sum_hessians"], hist_naive["sum_hessians"]) + for hist in (hist_gc_root, hist_gc): + assert_array_equal(hist["sum_hessians"], np.zeros(n_bins)) + + +@pytest.mark.parametrize("constant_hessian", [True, False]) +def test_hist_subtraction(constant_hessian): + # Make sure the histogram subtraction trick gives the same result as the + # classical method. + rng = np.random.RandomState(42) + n_samples = 10 + n_bins = 5 + sample_indices = np.arange(n_samples).astype(np.uint32) + binned_feature = rng.randint(0, n_bins - 1, size=n_samples, dtype=np.uint8) + ordered_gradients = rng.randn(n_samples).astype(G_H_DTYPE) + if constant_hessian: + ordered_hessians = np.ones(n_samples, dtype=G_H_DTYPE) + else: + ordered_hessians = rng.lognormal(size=n_samples).astype(G_H_DTYPE) + + hist_parent = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + if constant_hessian: + _build_histogram_no_hessian( + 0, sample_indices, binned_feature, ordered_gradients, hist_parent + ) + else: + _build_histogram( + 0, + sample_indices, + binned_feature, + ordered_gradients, + ordered_hessians, + hist_parent, + ) + + mask = rng.randint(0, 2, n_samples).astype(bool) + + sample_indices_left = sample_indices[mask] + ordered_gradients_left = ordered_gradients[mask] + ordered_hessians_left = ordered_hessians[mask] + hist_left = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + if constant_hessian: + _build_histogram_no_hessian( + 0, sample_indices_left, binned_feature, ordered_gradients_left, hist_left + ) + else: + _build_histogram( + 0, + sample_indices_left, + binned_feature, + ordered_gradients_left, + ordered_hessians_left, + hist_left, + ) + + sample_indices_right = sample_indices[~mask] + ordered_gradients_right = ordered_gradients[~mask] + ordered_hessians_right = ordered_hessians[~mask] + hist_right = np.zeros((1, n_bins), dtype=HISTOGRAM_DTYPE) + if constant_hessian: + _build_histogram_no_hessian( + 0, sample_indices_right, binned_feature, ordered_gradients_right, hist_right + ) + else: + _build_histogram( + 0, + sample_indices_right, + binned_feature, + ordered_gradients_right, + ordered_hessians_right, + hist_right, + ) + + hist_left_sub = np.copy(hist_parent) + hist_right_sub = np.copy(hist_parent) + _subtract_histograms(0, n_bins, hist_left_sub, hist_right) + _subtract_histograms(0, n_bins, hist_right_sub, hist_left) + + for key in ("count", "sum_hessians", "sum_gradients"): + assert_allclose(hist_left[key], hist_left_sub[key], rtol=1e-6) + assert_allclose(hist_right[key], hist_right_sub[key], rtol=1e-6) diff --git a/shared/package-files/3c/3c1a34a6857adb1b93e0226d26b8bf8f586ead8b2152ec34c76ae836242e716f/alacritty+common b/shared/package-files/3c/3c1a34a6857adb1b93e0226d26b8bf8f586ead8b2152ec34c76ae836242e716f/alacritty+common new file mode 100644 index 0000000000000000000000000000000000000000..5b327d028f787dba425af372046268484c68edcd Binary files /dev/null and b/shared/package-files/3c/3c1a34a6857adb1b93e0226d26b8bf8f586ead8b2152ec34c76ae836242e716f/alacritty+common differ diff --git a/shared/package-files/3c/3c1aebe94a47becfc5b58b130ffcb68eb7b6b5835caa778e1b0926d68998da39/polynomials.py b/shared/package-files/3c/3c1aebe94a47becfc5b58b130ffcb68eb7b6b5835caa778e1b0926d68998da39/polynomials.py new file mode 100644 index 0000000000000000000000000000000000000000..7c09dbb272820857a0295172648127caff4470f7 --- /dev/null +++ b/shared/package-files/3c/3c1aebe94a47becfc5b58b130ffcb68eb7b6b5835caa778e1b0926d68998da39/polynomials.py @@ -0,0 +1,1447 @@ +""" +This module mainly implements special orthogonal polynomials. + +See also functions.combinatorial.numbers which contains some +combinatorial polynomials. + +""" + +from sympy.core import Rational +from sympy.core.function import Function, ArgumentIndexError +from sympy.core.singleton import S +from sympy.core.symbol import Dummy +from sympy.functions.combinatorial.factorials import binomial, factorial, RisingFactorial +from sympy.functions.elementary.complexes import re +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.integers import floor +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import cos, sec +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.hyper import hyper +from sympy.polys.orthopolys import (chebyshevt_poly, chebyshevu_poly, + gegenbauer_poly, hermite_poly, hermite_prob_poly, + jacobi_poly, laguerre_poly, legendre_poly) + +_x = Dummy('x') + + +class OrthogonalPolynomial(Function): + """Base class for orthogonal polynomials. + """ + + @classmethod + def _eval_at_order(cls, n, x): + if n.is_integer and n >= 0: + return cls._ortho_poly(int(n), _x).subs(_x, x) + + def _eval_conjugate(self): + return self.func(self.args[0], self.args[1].conjugate()) + +#---------------------------------------------------------------------------- +# Jacobi polynomials +# + + +class jacobi(OrthogonalPolynomial): + r""" + Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$. + + Explanation + =========== + + ``jacobi(n, alpha, beta, x)`` gives the $n$th Jacobi polynomial + in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$. + + The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect + to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$. + + Examples + ======== + + >>> from sympy import jacobi, S, conjugate, diff + >>> from sympy.abc import a, b, n, x + + >>> jacobi(0, a, b, x) + 1 + >>> jacobi(1, a, b, x) + a/2 - b/2 + x*(a/2 + b/2 + 1) + >>> jacobi(2, a, b, x) + a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 + x**2*(a**2/8 + a*b/4 + 7*a/8 + b**2/8 + 7*b/8 + 3/2) + x*(a**2/4 + 3*a/4 - b**2/4 - 3*b/4) - 1/2 + + >>> jacobi(n, a, b, x) + jacobi(n, a, b, x) + + >>> jacobi(n, a, a, x) + RisingFactorial(a + 1, n)*gegenbauer(n, + a + 1/2, x)/RisingFactorial(2*a + 1, n) + + >>> jacobi(n, 0, 0, x) + legendre(n, x) + + >>> jacobi(n, S(1)/2, S(1)/2, x) + RisingFactorial(3/2, n)*chebyshevu(n, x)/factorial(n + 1) + + >>> jacobi(n, -S(1)/2, -S(1)/2, x) + RisingFactorial(1/2, n)*chebyshevt(n, x)/factorial(n) + + >>> jacobi(n, a, b, -x) + (-1)**n*jacobi(n, b, a, x) + + >>> jacobi(n, a, b, 0) + gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(2**n*factorial(n)*gamma(a + 1)) + >>> jacobi(n, a, b, 1) + RisingFactorial(a + 1, n)/factorial(n) + + >>> conjugate(jacobi(n, a, b, x)) + jacobi(n, conjugate(a), conjugate(b), conjugate(x)) + + >>> diff(jacobi(n,a,b,x), x) + (a/2 + b/2 + n/2 + 1/2)*jacobi(n - 1, a + 1, b + 1, x) + + See Also + ======== + + gegenbauer, + chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly, + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials + .. [2] https://mathworld.wolfram.com/JacobiPolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/JacobiP/ + + """ + + @classmethod + def eval(cls, n, a, b, x): + # Simplify to other polynomials + # P^{a, a}_n(x) + if a == b: + if a == Rational(-1, 2): + return RisingFactorial(S.Half, n) / factorial(n) * chebyshevt(n, x) + elif a.is_zero: + return legendre(n, x) + elif a == S.Half: + return RisingFactorial(3*S.Half, n) / factorial(n + 1) * chebyshevu(n, x) + else: + return RisingFactorial(a + 1, n) / RisingFactorial(2*a + 1, n) * gegenbauer(n, a + S.Half, x) + elif b == -a: + # P^{a, -a}_n(x) + return gamma(n + a + 1) / gamma(n + 1) * (1 + x)**(a/2) / (1 - x)**(a/2) * assoc_legendre(n, -a, x) + + if not n.is_Number: + # Symbolic result P^{a,b}_n(x) + # P^{a,b}_n(-x) ---> (-1)**n * P^{b,a}_n(-x) + if x.could_extract_minus_sign(): + return S.NegativeOne**n * jacobi(n, b, a, -x) + # We can evaluate for some special values of x + if x.is_zero: + return (2**(-n) * gamma(a + n + 1) / (gamma(a + 1) * factorial(n)) * + hyper([-b - n, -n], [a + 1], -1)) + if x == S.One: + return RisingFactorial(a + 1, n) / factorial(n) + elif x is S.Infinity: + if n.is_positive: + # Make sure a+b+2*n \notin Z + if (a + b + 2*n).is_integer: + raise ValueError("Error. a + b + 2*n should not be an integer.") + return RisingFactorial(a + b + n + 1, n) * S.Infinity + else: + # n is a given fixed integer, evaluate into polynomial + return jacobi_poly(n, a, b, x) + + def fdiff(self, argindex=4): + from sympy.concrete.summations import Sum + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt a + n, a, b, x = self.args + k = Dummy("k") + f1 = 1 / (a + b + n + k + 1) + f2 = ((a + b + 2*k + 1) * RisingFactorial(b + k + 1, n - k) / + ((n - k) * RisingFactorial(a + b + k + 1, n - k))) + return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1)) + elif argindex == 3: + # Diff wrt b + n, a, b, x = self.args + k = Dummy("k") + f1 = 1 / (a + b + n + k + 1) + f2 = (-1)**(n - k) * ((a + b + 2*k + 1) * RisingFactorial(a + k + 1, n - k) / + ((n - k) * RisingFactorial(a + b + k + 1, n - k))) + return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1)) + elif argindex == 4: + # Diff wrt x + n, a, b, x = self.args + return S.Half * (a + b + n + 1) * jacobi(n - 1, a + 1, b + 1, x) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, a, b, x, **kwargs): + from sympy.concrete.summations import Sum + # Make sure n \in N + if n.is_negative or n.is_integer is False: + raise ValueError("Error: n should be a non-negative integer.") + k = Dummy("k") + kern = (RisingFactorial(-n, k) * RisingFactorial(a + b + n + 1, k) * RisingFactorial(a + k + 1, n - k) / + factorial(k) * ((1 - x)/2)**k) + return 1 / factorial(n) * Sum(kern, (k, 0, n)) + + def _eval_rewrite_as_polynomial(self, n, a, b, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, a, b, x, **kwargs) + + def _eval_conjugate(self): + n, a, b, x = self.args + return self.func(n, a.conjugate(), b.conjugate(), x.conjugate()) + + +def jacobi_normalized(n, a, b, x): + r""" + Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$. + + Explanation + =========== + + ``jacobi_normalized(n, alpha, beta, x)`` gives the $n$th + Jacobi polynomial in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$. + + The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect + to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$. + + This functions returns the polynomials normilzed: + + .. math:: + + \int_{-1}^{1} + P_m^{\left(\alpha, \beta\right)}(x) + P_n^{\left(\alpha, \beta\right)}(x) + (1-x)^{\alpha} (1+x)^{\beta} \mathrm{d}x + = \delta_{m,n} + + Examples + ======== + + >>> from sympy import jacobi_normalized + >>> from sympy.abc import n,a,b,x + + >>> jacobi_normalized(n, a, b, x) + jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)/((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1))) + + Parameters + ========== + + n : integer degree of polynomial + + a : alpha value + + b : beta value + + x : symbol + + See Also + ======== + + gegenbauer, + chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly, + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials + .. [2] https://mathworld.wolfram.com/JacobiPolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/JacobiP/ + + """ + nfactor = (S(2)**(a + b + 1) * (gamma(n + a + 1) * gamma(n + b + 1)) + / (2*n + a + b + 1) / (factorial(n) * gamma(n + a + b + 1))) + + return jacobi(n, a, b, x) / sqrt(nfactor) + + +#---------------------------------------------------------------------------- +# Gegenbauer polynomials +# + + +class gegenbauer(OrthogonalPolynomial): + r""" + Gegenbauer polynomial $C_n^{\left(\alpha\right)}(x)$. + + Explanation + =========== + + ``gegenbauer(n, alpha, x)`` gives the $n$th Gegenbauer polynomial + in $x$, $C_n^{\left(\alpha\right)}(x)$. + + The Gegenbauer polynomials are orthogonal on $[-1, 1]$ with + respect to the weight $\left(1-x^2\right)^{\alpha-\frac{1}{2}}$. + + Examples + ======== + + >>> from sympy import gegenbauer, conjugate, diff + >>> from sympy.abc import n,a,x + >>> gegenbauer(0, a, x) + 1 + >>> gegenbauer(1, a, x) + 2*a*x + >>> gegenbauer(2, a, x) + -a + x**2*(2*a**2 + 2*a) + >>> gegenbauer(3, a, x) + x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a) + + >>> gegenbauer(n, a, x) + gegenbauer(n, a, x) + >>> gegenbauer(n, a, -x) + (-1)**n*gegenbauer(n, a, x) + + >>> gegenbauer(n, a, 0) + 2**n*sqrt(pi)*gamma(a + n/2)/(gamma(a)*gamma(1/2 - n/2)*gamma(n + 1)) + >>> gegenbauer(n, a, 1) + gamma(2*a + n)/(gamma(2*a)*gamma(n + 1)) + + >>> conjugate(gegenbauer(n, a, x)) + gegenbauer(n, conjugate(a), conjugate(x)) + + >>> diff(gegenbauer(n, a, x), x) + 2*a*gegenbauer(n - 1, a + 1, x) + + See Also + ======== + + jacobi, + chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gegenbauer_polynomials + .. [2] https://mathworld.wolfram.com/GegenbauerPolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/GegenbauerC3/ + + """ + + @classmethod + def eval(cls, n, a, x): + # For negative n the polynomials vanish + # See https://functions.wolfram.com/Polynomials/GegenbauerC3/03/01/03/0012/ + if n.is_negative: + return S.Zero + + # Some special values for fixed a + if a == S.Half: + return legendre(n, x) + elif a == S.One: + return chebyshevu(n, x) + elif a == S.NegativeOne: + return S.Zero + + if not n.is_Number: + # Handle this before the general sign extraction rule + if x == S.NegativeOne: + if (re(a) > S.Half) == True: + return S.ComplexInfinity + else: + return (cos(S.Pi*(a+n)) * sec(S.Pi*a) * gamma(2*a+n) / + (gamma(2*a) * gamma(n+1))) + + # Symbolic result C^a_n(x) + # C^a_n(-x) ---> (-1)**n * C^a_n(x) + if x.could_extract_minus_sign(): + return S.NegativeOne**n * gegenbauer(n, a, -x) + # We can evaluate for some special values of x + if x.is_zero: + return (2**n * sqrt(S.Pi) * gamma(a + S.Half*n) / + (gamma((1 - n)/2) * gamma(n + 1) * gamma(a)) ) + if x == S.One: + return gamma(2*a + n) / (gamma(2*a) * gamma(n + 1)) + elif x is S.Infinity: + if n.is_positive: + return RisingFactorial(a, n) * S.Infinity + else: + # n is a given fixed integer, evaluate into polynomial + return gegenbauer_poly(n, a, x) + + def fdiff(self, argindex=3): + from sympy.concrete.summations import Sum + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt a + n, a, x = self.args + k = Dummy("k") + factor1 = 2 * (1 + (-1)**(n - k)) * (k + a) / ((k + + n + 2*a) * (n - k)) + factor2 = 2*(k + 1) / ((k + 2*a) * (2*k + 2*a + 1)) + \ + 2 / (k + n + 2*a) + kern = factor1*gegenbauer(k, a, x) + factor2*gegenbauer(n, a, x) + return Sum(kern, (k, 0, n - 1)) + elif argindex == 3: + # Diff wrt x + n, a, x = self.args + return 2*a*gegenbauer(n - 1, a + 1, x) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, a, x, **kwargs): + from sympy.concrete.summations import Sum + k = Dummy("k") + kern = ((-1)**k * RisingFactorial(a, n - k) * (2*x)**(n - 2*k) / + (factorial(k) * factorial(n - 2*k))) + return Sum(kern, (k, 0, floor(n/2))) + + def _eval_rewrite_as_polynomial(self, n, a, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, a, x, **kwargs) + + def _eval_conjugate(self): + n, a, x = self.args + return self.func(n, a.conjugate(), x.conjugate()) + +#---------------------------------------------------------------------------- +# Chebyshev polynomials of first and second kind +# + + +class chebyshevt(OrthogonalPolynomial): + r""" + Chebyshev polynomial of the first kind, $T_n(x)$. + + Explanation + =========== + + ``chebyshevt(n, x)`` gives the $n$th Chebyshev polynomial (of the first + kind) in $x$, $T_n(x)$. + + The Chebyshev polynomials of the first kind are orthogonal on + $[-1, 1]$ with respect to the weight $\frac{1}{\sqrt{1-x^2}}$. + + Examples + ======== + + >>> from sympy import chebyshevt, diff + >>> from sympy.abc import n,x + >>> chebyshevt(0, x) + 1 + >>> chebyshevt(1, x) + x + >>> chebyshevt(2, x) + 2*x**2 - 1 + + >>> chebyshevt(n, x) + chebyshevt(n, x) + >>> chebyshevt(n, -x) + (-1)**n*chebyshevt(n, x) + >>> chebyshevt(-n, x) + chebyshevt(n, x) + + >>> chebyshevt(n, 0) + cos(pi*n/2) + >>> chebyshevt(n, -1) + (-1)**n + + >>> diff(chebyshevt(n, x), x) + n*chebyshevu(n - 1, x) + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial + .. [2] https://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html + .. [3] https://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html + .. [4] https://functions.wolfram.com/Polynomials/ChebyshevT/ + .. [5] https://functions.wolfram.com/Polynomials/ChebyshevU/ + + """ + + _ortho_poly = staticmethod(chebyshevt_poly) + + @classmethod + def eval(cls, n, x): + if not n.is_Number: + # Symbolic result T_n(x) + # T_n(-x) ---> (-1)**n * T_n(x) + if x.could_extract_minus_sign(): + return S.NegativeOne**n * chebyshevt(n, -x) + # T_{-n}(x) ---> T_n(x) + if n.could_extract_minus_sign(): + return chebyshevt(-n, x) + # We can evaluate for some special values of x + if x.is_zero: + return cos(S.Half * S.Pi * n) + if x == S.One: + return S.One + elif x is S.Infinity: + return S.Infinity + else: + # n is a given fixed integer, evaluate into polynomial + if n.is_negative: + # T_{-n}(x) == T_n(x) + return cls._eval_at_order(-n, x) + else: + return cls._eval_at_order(n, x) + + def fdiff(self, argindex=2): + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt x + n, x = self.args + return n * chebyshevu(n - 1, x) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, x, **kwargs): + from sympy.concrete.summations import Sum + k = Dummy("k") + kern = binomial(n, 2*k) * (x**2 - 1)**k * x**(n - 2*k) + return Sum(kern, (k, 0, floor(n/2))) + + def _eval_rewrite_as_polynomial(self, n, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, x, **kwargs) + + +class chebyshevu(OrthogonalPolynomial): + r""" + Chebyshev polynomial of the second kind, $U_n(x)$. + + Explanation + =========== + + ``chebyshevu(n, x)`` gives the $n$th Chebyshev polynomial of the second + kind in x, $U_n(x)$. + + The Chebyshev polynomials of the second kind are orthogonal on + $[-1, 1]$ with respect to the weight $\sqrt{1-x^2}$. + + Examples + ======== + + >>> from sympy import chebyshevu, diff + >>> from sympy.abc import n,x + >>> chebyshevu(0, x) + 1 + >>> chebyshevu(1, x) + 2*x + >>> chebyshevu(2, x) + 4*x**2 - 1 + + >>> chebyshevu(n, x) + chebyshevu(n, x) + >>> chebyshevu(n, -x) + (-1)**n*chebyshevu(n, x) + >>> chebyshevu(-n, x) + -chebyshevu(n - 2, x) + + >>> chebyshevu(n, 0) + cos(pi*n/2) + >>> chebyshevu(n, 1) + n + 1 + + >>> diff(chebyshevu(n, x), x) + (-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1) + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevt_root, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial + .. [2] https://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html + .. [3] https://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html + .. [4] https://functions.wolfram.com/Polynomials/ChebyshevT/ + .. [5] https://functions.wolfram.com/Polynomials/ChebyshevU/ + + """ + + _ortho_poly = staticmethod(chebyshevu_poly) + + @classmethod + def eval(cls, n, x): + if not n.is_Number: + # Symbolic result U_n(x) + # U_n(-x) ---> (-1)**n * U_n(x) + if x.could_extract_minus_sign(): + return S.NegativeOne**n * chebyshevu(n, -x) + # U_{-n}(x) ---> -U_{n-2}(x) + if n.could_extract_minus_sign(): + if n == S.NegativeOne: + # n can not be -1 here + return S.Zero + elif not (-n - 2).could_extract_minus_sign(): + return -chebyshevu(-n - 2, x) + # We can evaluate for some special values of x + if x.is_zero: + return cos(S.Half * S.Pi * n) + if x == S.One: + return S.One + n + elif x is S.Infinity: + return S.Infinity + else: + # n is a given fixed integer, evaluate into polynomial + if n.is_negative: + # U_{-n}(x) ---> -U_{n-2}(x) + if n == S.NegativeOne: + return S.Zero + else: + return -cls._eval_at_order(-n - 2, x) + else: + return cls._eval_at_order(n, x) + + def fdiff(self, argindex=2): + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt x + n, x = self.args + return ((n + 1) * chebyshevt(n + 1, x) - x * chebyshevu(n, x)) / (x**2 - 1) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, x, **kwargs): + from sympy.concrete.summations import Sum + k = Dummy("k") + kern = S.NegativeOne**k * factorial( + n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k)) + return Sum(kern, (k, 0, floor(n/2))) + + def _eval_rewrite_as_polynomial(self, n, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, x, **kwargs) + + +class chebyshevt_root(Function): + r""" + ``chebyshev_root(n, k)`` returns the $k$th root (indexed from zero) of + the $n$th Chebyshev polynomial of the first kind; that is, if + $0 \le k < n$, ``chebyshevt(n, chebyshevt_root(n, k)) == 0``. + + Examples + ======== + + >>> from sympy import chebyshevt, chebyshevt_root + >>> chebyshevt_root(3, 2) + -sqrt(3)/2 + >>> chebyshevt(3, chebyshevt_root(3, 2)) + 0 + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + """ + + @classmethod + def eval(cls, n, k): + if not ((0 <= k) and (k < n)): + raise ValueError("must have 0 <= k < n, " + "got k = %s and n = %s" % (k, n)) + return cos(S.Pi*(2*k + 1)/(2*n)) + + +class chebyshevu_root(Function): + r""" + ``chebyshevu_root(n, k)`` returns the $k$th root (indexed from zero) of the + $n$th Chebyshev polynomial of the second kind; that is, if $0 \le k < n$, + ``chebyshevu(n, chebyshevu_root(n, k)) == 0``. + + Examples + ======== + + >>> from sympy import chebyshevu, chebyshevu_root + >>> chebyshevu_root(3, 2) + -sqrt(2)/2 + >>> chebyshevu(3, chebyshevu_root(3, 2)) + 0 + + See Also + ======== + + chebyshevt, chebyshevt_root, chebyshevu, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + """ + + + @classmethod + def eval(cls, n, k): + if not ((0 <= k) and (k < n)): + raise ValueError("must have 0 <= k < n, " + "got k = %s and n = %s" % (k, n)) + return cos(S.Pi*(k + 1)/(n + 1)) + +#---------------------------------------------------------------------------- +# Legendre polynomials and Associated Legendre polynomials +# + + +class legendre(OrthogonalPolynomial): + r""" + ``legendre(n, x)`` gives the $n$th Legendre polynomial of $x$, $P_n(x)$ + + Explanation + =========== + + The Legendre polynomials are orthogonal on $[-1, 1]$ with respect to + the constant weight 1. They satisfy $P_n(1) = 1$ for all $n$; further, + $P_n$ is odd for odd $n$ and even for even $n$. + + Examples + ======== + + >>> from sympy import legendre, diff + >>> from sympy.abc import x, n + >>> legendre(0, x) + 1 + >>> legendre(1, x) + x + >>> legendre(2, x) + 3*x**2/2 - 1/2 + >>> legendre(n, x) + legendre(n, x) + >>> diff(legendre(n,x), x) + n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1) + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, + assoc_legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Legendre_polynomial + .. [2] https://mathworld.wolfram.com/LegendrePolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/LegendreP/ + .. [4] https://functions.wolfram.com/Polynomials/LegendreP2/ + + """ + + _ortho_poly = staticmethod(legendre_poly) + + @classmethod + def eval(cls, n, x): + if not n.is_Number: + # Symbolic result L_n(x) + # L_n(-x) ---> (-1)**n * L_n(x) + if x.could_extract_minus_sign(): + return S.NegativeOne**n * legendre(n, -x) + # L_{-n}(x) ---> L_{n-1}(x) + if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign(): + return legendre(-n - S.One, x) + # We can evaluate for some special values of x + if x.is_zero: + return sqrt(S.Pi)/(gamma(S.Half - n/2)*gamma(S.One + n/2)) + elif x == S.One: + return S.One + elif x is S.Infinity: + return S.Infinity + else: + # n is a given fixed integer, evaluate into polynomial; + # L_{-n}(x) ---> L_{n-1}(x) + if n.is_negative: + n = -n - S.One + return cls._eval_at_order(n, x) + + def fdiff(self, argindex=2): + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt x + # Find better formula, this is unsuitable for x = +/-1 + # https://www.autodiff.org/ad16/Oral/Buecker_Legendre.pdf says + # at x = 1: + # n*(n + 1)/2 , m = 0 + # oo , m = 1 + # -(n-1)*n*(n+1)*(n+2)/4 , m = 2 + # 0 , m = 3, 4, ..., n + # + # at x = -1 + # (-1)**(n+1)*n*(n + 1)/2 , m = 0 + # (-1)**n*oo , m = 1 + # (-1)**n*(n-1)*n*(n+1)*(n+2)/4 , m = 2 + # 0 , m = 3, 4, ..., n + n, x = self.args + return n/(x**2 - 1)*(x*legendre(n, x) - legendre(n - 1, x)) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, x, **kwargs): + from sympy.concrete.summations import Sum + k = Dummy("k") + kern = S.NegativeOne**k*binomial(n, k)**2*((1 + x)/2)**(n - k)*((1 - x)/2)**k + return Sum(kern, (k, 0, n)) + + def _eval_rewrite_as_polynomial(self, n, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, x, **kwargs) + + +class assoc_legendre(Function): + r""" + ``assoc_legendre(n, m, x)`` gives $P_n^m(x)$, where $n$ and $m$ are + the degree and order or an expression which is related to the nth + order Legendre polynomial, $P_n(x)$ in the following manner: + + .. math:: + P_n^m(x) = (-1)^m (1 - x^2)^{\frac{m}{2}} + \frac{\mathrm{d}^m P_n(x)}{\mathrm{d} x^m} + + Explanation + =========== + + Associated Legendre polynomials are orthogonal on $[-1, 1]$ with: + + - weight $= 1$ for the same $m$ and different $n$. + - weight $= \frac{1}{1-x^2}$ for the same $n$ and different $m$. + + Examples + ======== + + >>> from sympy import assoc_legendre + >>> from sympy.abc import x, m, n + >>> assoc_legendre(0,0, x) + 1 + >>> assoc_legendre(1,0, x) + x + >>> assoc_legendre(1,1, x) + -sqrt(1 - x**2) + >>> assoc_legendre(n,m,x) + assoc_legendre(n, m, x) + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, + hermite, hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Associated_Legendre_polynomials + .. [2] https://mathworld.wolfram.com/LegendrePolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/LegendreP/ + .. [4] https://functions.wolfram.com/Polynomials/LegendreP2/ + + """ + + @classmethod + def _eval_at_order(cls, n, m): + P = legendre_poly(n, _x, polys=True).diff((_x, m)) + return S.NegativeOne**m * (1 - _x**2)**Rational(m, 2) * P.as_expr() + + @classmethod + def eval(cls, n, m, x): + if m.could_extract_minus_sign(): + # P^{-m}_n ---> F * P^m_n + return S.NegativeOne**(-m) * (factorial(m + n)/factorial(n - m)) * assoc_legendre(n, -m, x) + if m == 0: + # P^0_n ---> L_n + return legendre(n, x) + if x == 0: + return 2**m*sqrt(S.Pi) / (gamma((1 - m - n)/2)*gamma(1 - (m - n)/2)) + if n.is_Number and m.is_Number and n.is_integer and m.is_integer: + if n.is_negative: + raise ValueError("%s : 1st index must be nonnegative integer (got %r)" % (cls, n)) + if abs(m) > n: + raise ValueError("%s : abs('2nd index') must be <= '1st index' (got %r, %r)" % (cls, n, m)) + return cls._eval_at_order(int(n), abs(int(m))).subs(_x, x) + + def fdiff(self, argindex=3): + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt m + raise ArgumentIndexError(self, argindex) + elif argindex == 3: + # Diff wrt x + # Find better formula, this is unsuitable for x = 1 + n, m, x = self.args + return 1/(x**2 - 1)*(x*n*assoc_legendre(n, m, x) - (m + n)*assoc_legendre(n - 1, m, x)) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, m, x, **kwargs): + from sympy.concrete.summations import Sum + k = Dummy("k") + kern = factorial(2*n - 2*k)/(2**n*factorial(n - k)*factorial( + k)*factorial(n - 2*k - m))*S.NegativeOne**k*x**(n - m - 2*k) + return (1 - x**2)**(m/2) * Sum(kern, (k, 0, floor((n - m)*S.Half))) + + def _eval_rewrite_as_polynomial(self, n, m, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, m, x, **kwargs) + + def _eval_conjugate(self): + n, m, x = self.args + return self.func(n, m.conjugate(), x.conjugate()) + +#---------------------------------------------------------------------------- +# Hermite polynomials +# + + +class hermite(OrthogonalPolynomial): + r""" + ``hermite(n, x)`` gives the $n$th Hermite polynomial in $x$, $H_n(x)$. + + Explanation + =========== + + The Hermite polynomials are orthogonal on $(-\infty, \infty)$ + with respect to the weight $\exp\left(-x^2\right)$. + + Examples + ======== + + >>> from sympy import hermite, diff + >>> from sympy.abc import x, n + >>> hermite(0, x) + 1 + >>> hermite(1, x) + 2*x + >>> hermite(2, x) + 4*x**2 - 2 + >>> hermite(n, x) + hermite(n, x) + >>> diff(hermite(n,x), x) + 2*n*hermite(n - 1, x) + >>> hermite(n, -x) + (-1)**n*hermite(n, x) + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite_prob, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Hermite_polynomial + .. [2] https://mathworld.wolfram.com/HermitePolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/HermiteH/ + + """ + + _ortho_poly = staticmethod(hermite_poly) + + @classmethod + def eval(cls, n, x): + if not n.is_Number: + # Symbolic result H_n(x) + # H_n(-x) ---> (-1)**n * H_n(x) + if x.could_extract_minus_sign(): + return S.NegativeOne**n * hermite(n, -x) + # We can evaluate for some special values of x + if x.is_zero: + return 2**n * sqrt(S.Pi) / gamma((S.One - n)/2) + elif x is S.Infinity: + return S.Infinity + else: + # n is a given fixed integer, evaluate into polynomial + if n.is_negative: + raise ValueError( + "The index n must be nonnegative integer (got %r)" % n) + else: + return cls._eval_at_order(n, x) + + def fdiff(self, argindex=2): + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt x + n, x = self.args + return 2*n*hermite(n - 1, x) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, x, **kwargs): + from sympy.concrete.summations import Sum + k = Dummy("k") + kern = S.NegativeOne**k / (factorial(k)*factorial(n - 2*k)) * (2*x)**(n - 2*k) + return factorial(n)*Sum(kern, (k, 0, floor(n/2))) + + def _eval_rewrite_as_polynomial(self, n, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, x, **kwargs) + + def _eval_rewrite_as_hermite_prob(self, n, x, **kwargs): + return sqrt(2)**n * hermite_prob(n, x*sqrt(2)) + + +class hermite_prob(OrthogonalPolynomial): + r""" + ``hermite_prob(n, x)`` gives the $n$th probabilist's Hermite polynomial + in $x$, $He_n(x)$. + + Explanation + =========== + + The probabilist's Hermite polynomials are orthogonal on $(-\infty, \infty)$ + with respect to the weight $\exp\left(-\frac{x^2}{2}\right)$. They are monic + polynomials, related to the plain Hermite polynomials (:py:class:`~.hermite`) by + + .. math :: He_n(x) = 2^{-n/2} H_n(x/\sqrt{2}) + + Examples + ======== + + >>> from sympy import hermite_prob, diff, I + >>> from sympy.abc import x, n + >>> hermite_prob(1, x) + x + >>> hermite_prob(5, x) + x**5 - 10*x**3 + 15*x + >>> diff(hermite_prob(n,x), x) + n*hermite_prob(n - 1, x) + >>> hermite_prob(n, -x) + (-1)**n*hermite_prob(n, x) + + The sum of absolute values of coefficients of $He_n(x)$ is the number of + matchings in the complete graph $K_n$ or telephone number, A000085 in the OEIS: + + >>> [hermite_prob(n,I) / I**n for n in range(11)] + [1, 1, 2, 4, 10, 26, 76, 232, 764, 2620, 9496] + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, + laguerre, assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Hermite_polynomial + .. [2] https://mathworld.wolfram.com/HermitePolynomial.html + """ + + _ortho_poly = staticmethod(hermite_prob_poly) + + @classmethod + def eval(cls, n, x): + if not n.is_Number: + if x.could_extract_minus_sign(): + return S.NegativeOne**n * hermite_prob(n, -x) + if x.is_zero: + return sqrt(S.Pi) / gamma((S.One-n) / 2) + elif x is S.Infinity: + return S.Infinity + else: + if n.is_negative: + ValueError("n must be a nonnegative integer, not %r" % n) + else: + return cls._eval_at_order(n, x) + + def fdiff(self, argindex=2): + if argindex == 2: + n, x = self.args + return n*hermite_prob(n-1, x) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, x, **kwargs): + from sympy.concrete.summations import Sum + k = Dummy("k") + kern = (-S.Half)**k * x**(n-2*k) / (factorial(k) * factorial(n-2*k)) + return factorial(n)*Sum(kern, (k, 0, floor(n/2))) + + def _eval_rewrite_as_polynomial(self, n, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, x, **kwargs) + + def _eval_rewrite_as_hermite(self, n, x, **kwargs): + return sqrt(2)**(-n) * hermite(n, x/sqrt(2)) + + +#---------------------------------------------------------------------------- +# Laguerre polynomials +# + + +class laguerre(OrthogonalPolynomial): + r""" + Returns the $n$th Laguerre polynomial in $x$, $L_n(x)$. + + Examples + ======== + + >>> from sympy import laguerre, diff + >>> from sympy.abc import x, n + >>> laguerre(0, x) + 1 + >>> laguerre(1, x) + 1 - x + >>> laguerre(2, x) + x**2/2 - 2*x + 1 + >>> laguerre(3, x) + -x**3/6 + 3*x**2/2 - 3*x + 1 + + >>> laguerre(n, x) + laguerre(n, x) + + >>> diff(laguerre(n, x), x) + -assoc_laguerre(n - 1, 1, x) + + Parameters + ========== + + n : int + Degree of Laguerre polynomial. Must be `n \ge 0`. + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + assoc_laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial + .. [2] https://mathworld.wolfram.com/LaguerrePolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/LaguerreL/ + .. [4] https://functions.wolfram.com/Polynomials/LaguerreL3/ + + """ + + _ortho_poly = staticmethod(laguerre_poly) + + @classmethod + def eval(cls, n, x): + if n.is_integer is False: + raise ValueError("Error: n should be an integer.") + if not n.is_Number: + # Symbolic result L_n(x) + # L_{n}(-x) ---> exp(-x) * L_{-n-1}(x) + # L_{-n}(x) ---> exp(x) * L_{n-1}(-x) + if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign(): + return exp(x)*laguerre(-n - 1, -x) + # We can evaluate for some special values of x + if x.is_zero: + return S.One + elif x is S.NegativeInfinity: + return S.Infinity + elif x is S.Infinity: + return S.NegativeOne**n * S.Infinity + else: + if n.is_negative: + return exp(x)*laguerre(-n - 1, -x) + else: + return cls._eval_at_order(n, x) + + def fdiff(self, argindex=2): + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt x + n, x = self.args + return -assoc_laguerre(n - 1, 1, x) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, x, **kwargs): + from sympy.concrete.summations import Sum + # Make sure n \in N_0 + if n.is_negative: + return exp(x) * self._eval_rewrite_as_Sum(-n - 1, -x, **kwargs) + if n.is_integer is False: + raise ValueError("Error: n should be an integer.") + k = Dummy("k") + kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k + return Sum(kern, (k, 0, n)) + + def _eval_rewrite_as_polynomial(self, n, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, x, **kwargs) + + +class assoc_laguerre(OrthogonalPolynomial): + r""" + Returns the $n$th generalized Laguerre polynomial in $x$, $L_n(x)$. + + Examples + ======== + + >>> from sympy import assoc_laguerre, diff + >>> from sympy.abc import x, n, a + >>> assoc_laguerre(0, a, x) + 1 + >>> assoc_laguerre(1, a, x) + a - x + 1 + >>> assoc_laguerre(2, a, x) + a**2/2 + 3*a/2 + x**2/2 + x*(-a - 2) + 1 + >>> assoc_laguerre(3, a, x) + a**3/6 + a**2 + 11*a/6 - x**3/6 + x**2*(a/2 + 3/2) + + x*(-a**2/2 - 5*a/2 - 3) + 1 + + >>> assoc_laguerre(n, a, 0) + binomial(a + n, a) + + >>> assoc_laguerre(n, a, x) + assoc_laguerre(n, a, x) + + >>> assoc_laguerre(n, 0, x) + laguerre(n, x) + + >>> diff(assoc_laguerre(n, a, x), x) + -assoc_laguerre(n - 1, a + 1, x) + + >>> diff(assoc_laguerre(n, a, x), a) + Sum(assoc_laguerre(_k, a, x)/(-a + n), (_k, 0, n - 1)) + + Parameters + ========== + + n : int + Degree of Laguerre polynomial. Must be `n \ge 0`. + + alpha : Expr + Arbitrary expression. For ``alpha=0`` regular Laguerre + polynomials will be generated. + + See Also + ======== + + jacobi, gegenbauer, + chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, + legendre, assoc_legendre, + hermite, hermite_prob, + laguerre, + sympy.polys.orthopolys.jacobi_poly + sympy.polys.orthopolys.gegenbauer_poly + sympy.polys.orthopolys.chebyshevt_poly + sympy.polys.orthopolys.chebyshevu_poly + sympy.polys.orthopolys.hermite_poly + sympy.polys.orthopolys.hermite_prob_poly + sympy.polys.orthopolys.legendre_poly + sympy.polys.orthopolys.laguerre_poly + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials + .. [2] https://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html + .. [3] https://functions.wolfram.com/Polynomials/LaguerreL/ + .. [4] https://functions.wolfram.com/Polynomials/LaguerreL3/ + + """ + + @classmethod + def eval(cls, n, alpha, x): + # L_{n}^{0}(x) ---> L_{n}(x) + if alpha.is_zero: + return laguerre(n, x) + + if not n.is_Number: + # We can evaluate for some special values of x + if x.is_zero: + return binomial(n + alpha, alpha) + elif x is S.Infinity and n > 0: + return S.NegativeOne**n * S.Infinity + elif x is S.NegativeInfinity and n > 0: + return S.Infinity + else: + # n is a given fixed integer, evaluate into polynomial + if n.is_negative: + raise ValueError( + "The index n must be nonnegative integer (got %r)" % n) + else: + return laguerre_poly(n, x, alpha) + + def fdiff(self, argindex=3): + from sympy.concrete.summations import Sum + if argindex == 1: + # Diff wrt n + raise ArgumentIndexError(self, argindex) + elif argindex == 2: + # Diff wrt alpha + n, alpha, x = self.args + k = Dummy("k") + return Sum(assoc_laguerre(k, alpha, x) / (n - alpha), (k, 0, n - 1)) + elif argindex == 3: + # Diff wrt x + n, alpha, x = self.args + return -assoc_laguerre(n - 1, alpha + 1, x) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_rewrite_as_Sum(self, n, alpha, x, **kwargs): + from sympy.concrete.summations import Sum + # Make sure n \in N_0 + if n.is_negative or n.is_integer is False: + raise ValueError("Error: n should be a non-negative integer.") + k = Dummy("k") + kern = RisingFactorial( + -n, k) / (gamma(k + alpha + 1) * factorial(k)) * x**k + return gamma(n + alpha + 1) / factorial(n) * Sum(kern, (k, 0, n)) + + def _eval_rewrite_as_polynomial(self, n, alpha, x, **kwargs): + # This function is just kept for backwards compatibility + # but should not be used + return self._eval_rewrite_as_Sum(n, alpha, x, **kwargs) + + def _eval_conjugate(self): + n, alpha, x = self.args + return self.func(n, alpha.conjugate(), x.conjugate()) diff --git a/shared/package-files/3c/3c21f445580d72ff46639211a7ff833c16b812703f3b7b8a1eb776f53b5f1476/cfa_tvpvar_vi0.csv b/shared/package-files/3c/3c21f445580d72ff46639211a7ff833c16b812703f3b7b8a1eb776f53b5f1476/cfa_tvpvar_vi0.csv new file mode 100644 index 0000000000000000000000000000000000000000..3d845e8893e76591466afedb5271c6877d9b22a6 --- /dev/null +++ b/shared/package-files/3c/3c21f445580d72ff46639211a7ff833c16b812703f3b7b8a1eb776f53b5f1476/cfa_tvpvar_vi0.csv @@ -0,0 +1 @@ +7,7 diff --git a/shared/package-files/3c/3c28593f394905b79e20f3c5daca0055b1fb199eb9dc264c3e5ee539ed35e94d/configs.py b/shared/package-files/3c/3c28593f394905b79e20f3c5daca0055b1fb199eb9dc264c3e5ee539ed35e94d/configs.py new file mode 100644 index 0000000000000000000000000000000000000000..178421509168a2f476d772cd5762faae6751c5e2 --- /dev/null +++ b/shared/package-files/3c/3c28593f394905b79e20f3c5daca0055b1fb199eb9dc264c3e5ee539ed35e94d/configs.py @@ -0,0 +1,1190 @@ +""" + pygments.lexers.configs + ~~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for configuration file formats. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.lexer import ExtendedRegexLexer, RegexLexer, default, words, \ + bygroups, include, using, line_re +from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ + Number, Punctuation, Whitespace, Literal, Error, Generic +from pygments.lexers.shell import BashLexer +from pygments.lexers.data import JsonLexer + +__all__ = ['IniLexer', 'RegeditLexer', 'PropertiesLexer', 'KconfigLexer', + 'Cfengine3Lexer', 'ApacheConfLexer', 'SquidConfLexer', + 'NginxConfLexer', 'LighttpdConfLexer', 'DockerLexer', + 'TerraformLexer', 'TermcapLexer', 'TerminfoLexer', + 'PkgConfigLexer', 'PacmanConfLexer', 'AugeasLexer', 'TOMLLexer', + 'NestedTextLexer', 'SingularityLexer', 'UnixConfigLexer'] + + +class IniLexer(RegexLexer): + """ + Lexer for configuration files in INI style. + """ + + name = 'INI' + aliases = ['ini', 'cfg', 'dosini'] + filenames = [ + '*.ini', '*.cfg', '*.inf', '.editorconfig', + # systemd unit files + # https://www.freedesktop.org/software/systemd/man/systemd.unit.html + '*.service', '*.socket', '*.device', '*.mount', '*.automount', + '*.swap', '*.target', '*.path', '*.timer', '*.slice', '*.scope', + ] + mimetypes = ['text/x-ini', 'text/inf'] + + tokens = { + 'root': [ + (r'\s+', Whitespace), + (r'[;#].*', Comment.Single), + (r'(\[.*?\])([ \t]*)$', bygroups(Keyword, Whitespace)), + (r'(.*?)([  \t]*)([=:])([ \t]*)([^;#\n]*)(\\)(\s+)', + bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, + Text, Whitespace), + "value"), + (r'(.*?)([ \t]*)([=:])([  \t]*)([^ ;#\n]*(?: +[^ ;#\n]+)*)', + bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), + # standalone option, supported by some INI parsers + (r'(.+?)$', Name.Attribute), + ], + 'value': [ # line continuation + (r'\s+', Whitespace), + (r'(\s*)(.*)(\\)([ \t]*)', + bygroups(Whitespace, String, Text, Whitespace)), + (r'.*$', String, "#pop"), + ], + } + + def analyse_text(text): + npos = text.find('\n') + if npos < 3: + return False + return text[0] == '[' and text[npos-1] == ']' + + +class RegeditLexer(RegexLexer): + """ + Lexer for Windows Registry files produced by regedit. + + .. versionadded:: 1.6 + """ + + name = 'reg' + url = 'http://en.wikipedia.org/wiki/Windows_Registry#.REG_files' + aliases = ['registry'] + filenames = ['*.reg'] + mimetypes = ['text/x-windows-registry'] + + tokens = { + 'root': [ + (r'Windows Registry Editor.*', Text), + (r'\s+', Whitespace), + (r'[;#].*', Comment.Single), + (r'(\[)(-?)(HKEY_[A-Z_]+)(.*?\])$', + bygroups(Keyword, Operator, Name.Builtin, Keyword)), + # String keys, which obey somewhat normal escaping + (r'("(?:\\"|\\\\|[^"])+")([ \t]*)(=)([ \t]*)', + bygroups(Name.Attribute, Whitespace, Operator, Whitespace), + 'value'), + # Bare keys (includes @) + (r'(.*?)([ \t]*)(=)([ \t]*)', + bygroups(Name.Attribute, Whitespace, Operator, Whitespace), + 'value'), + ], + 'value': [ + (r'-', Operator, '#pop'), # delete value + (r'(dword|hex(?:\([0-9a-fA-F]\))?)(:)([0-9a-fA-F,]+)', + bygroups(Name.Variable, Punctuation, Number), '#pop'), + # As far as I know, .reg files do not support line continuation. + (r'.+', String, '#pop'), + default('#pop'), + ] + } + + def analyse_text(text): + return text.startswith('Windows Registry Editor') + + +class PropertiesLexer(RegexLexer): + """ + Lexer for configuration files in Java's properties format. + + Note: trailing whitespace counts as part of the value as per spec + + .. versionadded:: 1.4 + """ + + name = 'Properties' + aliases = ['properties', 'jproperties'] + filenames = ['*.properties'] + mimetypes = ['text/x-java-properties'] + + tokens = { + 'root': [ + # comments + (r'[!#].*|/{2}.*', Comment.Single), + # ending a comment or whitespace-only line + (r'\n', Whitespace), + # eat whitespace at the beginning of a line + (r'^[^\S\n]+', Whitespace), + # start lexing a key + default('key'), + ], + 'key': [ + # non-escaped key characters + (r'[^\\:=\s]+', Name.Attribute), + # escapes + include('escapes'), + # separator is the first non-escaped whitespace or colon or '=' on the line; + # if it's whitespace, = and : are gobbled after it + (r'([^\S\n]*)([:=])([^\S\n]*)', + bygroups(Whitespace, Operator, Whitespace), + ('#pop', 'value')), + (r'[^\S\n]+', Whitespace, ('#pop', 'value')), + # maybe we got no value after all + (r'\n', Whitespace, '#pop'), + ], + 'value': [ + # non-escaped value characters + (r'[^\\\n]+', String), + # escapes + include('escapes'), + # end the value on an unescaped newline + (r'\n', Whitespace, '#pop'), + ], + 'escapes': [ + # line continuations; these gobble whitespace at the beginning of the next line + (r'(\\\n)([^\S\n]*)', bygroups(String.Escape, Whitespace)), + # other escapes + (r'\\(.|\n)', String.Escape), + ], + } + + +def _rx_indent(level): + # Kconfig *always* interprets a tab as 8 spaces, so this is the default. + # Edit this if you are in an environment where KconfigLexer gets expanded + # input (tabs expanded to spaces) and the expansion tab width is != 8, + # e.g. in connection with Trac (trac.ini, [mimeviewer], tab_width). + # Value range here is 2 <= {tab_width} <= 8. + tab_width = 8 + # Regex matching a given indentation {level}, assuming that indentation is + # a multiple of {tab_width}. In other cases there might be problems. + if tab_width == 2: + space_repeat = '+' + else: + space_repeat = '{1,%d}' % (tab_width - 1) + if level == 1: + level_repeat = '' + else: + level_repeat = '{%s}' % level + return r'(?:\t| %s\t| {%s})%s.*\n' % (space_repeat, tab_width, level_repeat) + + +class KconfigLexer(RegexLexer): + """ + For Linux-style Kconfig files. + + .. versionadded:: 1.6 + """ + + name = 'Kconfig' + aliases = ['kconfig', 'menuconfig', 'linux-config', 'kernel-config'] + # Adjust this if new kconfig file names appear in your environment + filenames = ['Kconfig*', '*Config.in*', 'external.in*', + 'standard-modules.in'] + mimetypes = ['text/x-kconfig'] + # No re.MULTILINE, indentation-aware help text needs line-by-line handling + flags = 0 + + def call_indent(level): + # If indentation >= {level} is detected, enter state 'indent{level}' + return (_rx_indent(level), String.Doc, 'indent%s' % level) + + def do_indent(level): + # Print paragraphs of indentation level >= {level} as String.Doc, + # ignoring blank lines. Then return to 'root' state. + return [ + (_rx_indent(level), String.Doc), + (r'\s*\n', Text), + default('#pop:2') + ] + + tokens = { + 'root': [ + (r'\s+', Whitespace), + (r'#.*?\n', Comment.Single), + (words(( + 'mainmenu', 'config', 'menuconfig', 'choice', 'endchoice', + 'comment', 'menu', 'endmenu', 'visible if', 'if', 'endif', + 'source', 'prompt', 'select', 'depends on', 'default', + 'range', 'option'), suffix=r'\b'), + Keyword), + (r'(---help---|help)[\t ]*\n', Keyword, 'help'), + (r'(bool|tristate|string|hex|int|defconfig_list|modules|env)\b', + Name.Builtin), + (r'[!=&|]', Operator), + (r'[()]', Punctuation), + (r'[0-9]+', Number.Integer), + (r"'(''|[^'])*'", String.Single), + (r'"(""|[^"])*"', String.Double), + (r'\S+', Text), + ], + # Help text is indented, multi-line and ends when a lower indentation + # level is detected. + 'help': [ + # Skip blank lines after help token, if any + (r'\s*\n', Text), + # Determine the first help line's indentation level heuristically(!). + # Attention: this is not perfect, but works for 99% of "normal" + # indentation schemes up to a max. indentation level of 7. + call_indent(7), + call_indent(6), + call_indent(5), + call_indent(4), + call_indent(3), + call_indent(2), + call_indent(1), + default('#pop'), # for incomplete help sections without text + ], + # Handle text for indentation levels 7 to 1 + 'indent7': do_indent(7), + 'indent6': do_indent(6), + 'indent5': do_indent(5), + 'indent4': do_indent(4), + 'indent3': do_indent(3), + 'indent2': do_indent(2), + 'indent1': do_indent(1), + } + + +class Cfengine3Lexer(RegexLexer): + """ + Lexer for CFEngine3 policy files. + + .. versionadded:: 1.5 + """ + + name = 'CFEngine3' + url = 'http://cfengine.org' + aliases = ['cfengine3', 'cf3'] + filenames = ['*.cf'] + mimetypes = [] + + tokens = { + 'root': [ + (r'#.*?\n', Comment), + (r'(body)(\s+)(\S+)(\s+)(control)', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), + (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)(\()', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function, Punctuation), + 'arglist'), + (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function)), + (r'(")([^"]+)(")(\s+)(string|slist|int|real)(\s*)(=>)(\s*)', + bygroups(Punctuation, Name.Variable, Punctuation, + Whitespace, Keyword.Type, Whitespace, Operator, Whitespace)), + (r'(\S+)(\s*)(=>)(\s*)', + bygroups(Keyword.Reserved, Whitespace, Operator, Text)), + (r'"', String, 'string'), + (r'(\w+)(\()', bygroups(Name.Function, Punctuation)), + (r'([\w.!&|()]+)(::)', bygroups(Name.Class, Punctuation)), + (r'(\w+)(:)', bygroups(Keyword.Declaration, Punctuation)), + (r'@[{(][^)}]+[})]', Name.Variable), + (r'[(){},;]', Punctuation), + (r'=>', Operator), + (r'->', Operator), + (r'\d+\.\d+', Number.Float), + (r'\d+', Number.Integer), + (r'\w+', Name.Function), + (r'\s+', Whitespace), + ], + 'string': [ + (r'\$[{(]', String.Interpol, 'interpol'), + (r'\\.', String.Escape), + (r'"', String, '#pop'), + (r'\n', String), + (r'.', String), + ], + 'interpol': [ + (r'\$[{(]', String.Interpol, '#push'), + (r'[})]', String.Interpol, '#pop'), + (r'[^${()}]+', String.Interpol), + ], + 'arglist': [ + (r'\)', Punctuation, '#pop'), + (r',', Punctuation), + (r'\w+', Name.Variable), + (r'\s+', Whitespace), + ], + } + + +class ApacheConfLexer(RegexLexer): + """ + Lexer for configuration files following the Apache config file + format. + + .. versionadded:: 0.6 + """ + + name = 'ApacheConf' + aliases = ['apacheconf', 'aconf', 'apache'] + filenames = ['.htaccess', 'apache.conf', 'apache2.conf'] + mimetypes = ['text/x-apacheconf'] + flags = re.MULTILINE | re.IGNORECASE + + tokens = { + 'root': [ + (r'\s+', Whitespace), + (r'#(.*\\\n)+.*$|(#.*?)$', Comment), + (r'(<[^\s>/][^\s>]*)(?:(\s+)(.*))?(>)', + bygroups(Name.Tag, Whitespace, String, Name.Tag)), + (r'(]+)(>)', + bygroups(Name.Tag, Name.Tag)), + (r'[a-z]\w*', Name.Builtin, 'value'), + (r'\.+', Text), + ], + 'value': [ + (r'\\\n', Text), + (r'\n+', Whitespace, '#pop'), + (r'\\', Text), + (r'[^\S\n]+', Whitespace), + (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), + (r'\d+', Number), + (r'/([*a-z0-9][*\w./-]+)', String.Other), + (r'(on|off|none|any|all|double|email|dns|min|minimal|' + r'os|productonly|full|emerg|alert|crit|error|warn|' + r'notice|info|debug|registry|script|inetd|standalone|' + r'user|group)\b', Keyword), + (r'"([^"\\]*(?:\\(.|\n)[^"\\]*)*)"', String.Double), + (r'[^\s"\\]+', Text) + ], + } + + +class SquidConfLexer(RegexLexer): + """ + Lexer for squid configuration files. + + .. versionadded:: 0.9 + """ + + name = 'SquidConf' + url = 'http://www.squid-cache.org/' + aliases = ['squidconf', 'squid.conf', 'squid'] + filenames = ['squid.conf'] + mimetypes = ['text/x-squidconf'] + flags = re.IGNORECASE + + keywords = ( + "access_log", "acl", "always_direct", "announce_host", + "announce_period", "announce_port", "announce_to", "anonymize_headers", + "append_domain", "as_whois_server", "auth_param_basic", + "authenticate_children", "authenticate_program", "authenticate_ttl", + "broken_posts", "buffered_logs", "cache_access_log", "cache_announce", + "cache_dir", "cache_dns_program", "cache_effective_group", + "cache_effective_user", "cache_host", "cache_host_acl", + "cache_host_domain", "cache_log", "cache_mem", "cache_mem_high", + "cache_mem_low", "cache_mgr", "cachemgr_passwd", "cache_peer", + "cache_peer_access", "cache_replacement_policy", "cache_stoplist", + "cache_stoplist_pattern", "cache_store_log", "cache_swap", + "cache_swap_high", "cache_swap_log", "cache_swap_low", "client_db", + "client_lifetime", "client_netmask", "connect_timeout", "coredump_dir", + "dead_peer_timeout", "debug_options", "delay_access", "delay_class", + "delay_initial_bucket_level", "delay_parameters", "delay_pools", + "deny_info", "dns_children", "dns_defnames", "dns_nameservers", + "dns_testnames", "emulate_httpd_log", "err_html_text", + "fake_user_agent", "firewall_ip", "forwarded_for", "forward_snmpd_port", + "fqdncache_size", "ftpget_options", "ftpget_program", "ftp_list_width", + "ftp_passive", "ftp_user", "half_closed_clients", "header_access", + "header_replace", "hierarchy_stoplist", "high_response_time_warning", + "high_page_fault_warning", "hosts_file", "htcp_port", "http_access", + "http_anonymizer", "httpd_accel", "httpd_accel_host", + "httpd_accel_port", "httpd_accel_uses_host_header", + "httpd_accel_with_proxy", "http_port", "http_reply_access", + "icp_access", "icp_hit_stale", "icp_port", "icp_query_timeout", + "ident_lookup", "ident_lookup_access", "ident_timeout", + "incoming_http_average", "incoming_icp_average", "inside_firewall", + "ipcache_high", "ipcache_low", "ipcache_size", "local_domain", + "local_ip", "logfile_rotate", "log_fqdn", "log_icp_queries", + "log_mime_hdrs", "maximum_object_size", "maximum_single_addr_tries", + "mcast_groups", "mcast_icp_query_timeout", "mcast_miss_addr", + "mcast_miss_encode_key", "mcast_miss_port", "memory_pools", + "memory_pools_limit", "memory_replacement_policy", "mime_table", + "min_http_poll_cnt", "min_icp_poll_cnt", "minimum_direct_hops", + "minimum_object_size", "minimum_retry_timeout", "miss_access", + "negative_dns_ttl", "negative_ttl", "neighbor_timeout", + "neighbor_type_domain", "netdb_high", "netdb_low", "netdb_ping_period", + "netdb_ping_rate", "never_direct", "no_cache", "passthrough_proxy", + "pconn_timeout", "pid_filename", "pinger_program", "positive_dns_ttl", + "prefer_direct", "proxy_auth", "proxy_auth_realm", "query_icmp", + "quick_abort", "quick_abort_max", "quick_abort_min", + "quick_abort_pct", "range_offset_limit", "read_timeout", + "redirect_children", "redirect_program", + "redirect_rewrites_host_header", "reference_age", + "refresh_pattern", "reload_into_ims", "request_body_max_size", + "request_size", "request_timeout", "shutdown_lifetime", + "single_parent_bypass", "siteselect_timeout", "snmp_access", + "snmp_incoming_address", "snmp_port", "source_ping", "ssl_proxy", + "store_avg_object_size", "store_objects_per_bucket", + "strip_query_terms", "swap_level1_dirs", "swap_level2_dirs", + "tcp_incoming_address", "tcp_outgoing_address", "tcp_recv_bufsize", + "test_reachability", "udp_hit_obj", "udp_hit_obj_size", + "udp_incoming_address", "udp_outgoing_address", "unique_hostname", + "unlinkd_program", "uri_whitespace", "useragent_log", + "visible_hostname", "wais_relay", "wais_relay_host", "wais_relay_port", + ) + + opts = ( + "proxy-only", "weight", "ttl", "no-query", "default", "round-robin", + "multicast-responder", "on", "off", "all", "deny", "allow", "via", + "parent", "no-digest", "heap", "lru", "realm", "children", "q1", "q2", + "credentialsttl", "none", "disable", "offline_toggle", "diskd", + ) + + actions = ( + "shutdown", "info", "parameter", "server_list", "client_list", + r'squid.conf', + ) + + actions_stats = ( + "objects", "vm_objects", "utilization", "ipcache", "fqdncache", "dns", + "redirector", "io", "reply_headers", "filedescriptors", "netdb", + ) + + actions_log = ("status", "enable", "disable", "clear") + + acls = ( + "url_regex", "urlpath_regex", "referer_regex", "port", "proto", + "req_mime_type", "rep_mime_type", "method", "browser", "user", "src", + "dst", "time", "dstdomain", "ident", "snmp_community", + ) + + ip_re = ( + r'(?:(?:(?:[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}|0x0*[0-9a-f]{1,2}|' + r'0+[1-3]?[0-7]{0,2})(?:\.(?:[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}|' + r'0x0*[0-9a-f]{1,2}|0+[1-3]?[0-7]{0,2})){3})|(?!.*::.*::)(?:(?!:)|' + r':(?=:))(?:[0-9a-f]{0,4}(?:(?<=::)|(?|=~|\+=|==|=|\+', Operator), + (r'\$[A-Z]+', Name.Builtin), + (r'[(){}\[\],]', Punctuation), + (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double), + (r'\s+', Whitespace), + ], + + } + + +class DockerLexer(RegexLexer): + """ + Lexer for Docker configuration files. + + .. versionadded:: 2.0 + """ + name = 'Docker' + url = 'http://docker.io' + aliases = ['docker', 'dockerfile'] + filenames = ['Dockerfile', '*.docker'] + mimetypes = ['text/x-dockerfile-config'] + + _keywords = (r'(?:MAINTAINER|EXPOSE|WORKDIR|USER|STOPSIGNAL)') + _bash_keywords = (r'(?:RUN|CMD|ENTRYPOINT|ENV|ARG|LABEL|ADD|COPY)') + _lb = r'(?:\s*\\?\s*)' # dockerfile line break regex + flags = re.IGNORECASE | re.MULTILINE + + tokens = { + 'root': [ + (r'#.*', Comment), + (r'(FROM)([ \t]*)(\S*)([ \t]*)(?:(AS)([ \t]*)(\S*))?', + bygroups(Keyword, Whitespace, String, Whitespace, Keyword, Whitespace, String)), + (r'(ONBUILD)(\s+)(%s)' % (_lb,), bygroups(Keyword, Whitespace, using(BashLexer))), + (r'(HEALTHCHECK)(\s+)((%s--\w+=\w+%s)*)' % (_lb, _lb), + bygroups(Keyword, Whitespace, using(BashLexer))), + (r'(VOLUME|ENTRYPOINT|CMD|SHELL)(\s+)(%s)(\[.*?\])' % (_lb,), + bygroups(Keyword, Whitespace, using(BashLexer), using(JsonLexer))), + (r'(LABEL|ENV|ARG)(\s+)((%s\w+=\w+%s)*)' % (_lb, _lb), + bygroups(Keyword, Whitespace, using(BashLexer))), + (r'(%s|VOLUME)\b(\s+)(.*)' % (_keywords), bygroups(Keyword, Whitespace, String)), + (r'(%s)(\s+)' % (_bash_keywords,), bygroups(Keyword, Whitespace)), + (r'(.*\\\n)*.+', using(BashLexer)), + ] + } + + +class TerraformLexer(ExtendedRegexLexer): + """ + Lexer for terraformi ``.tf`` files. + + .. versionadded:: 2.1 + """ + + name = 'Terraform' + url = 'https://www.terraform.io/' + aliases = ['terraform', 'tf', 'hcl'] + filenames = ['*.tf', '*.hcl'] + mimetypes = ['application/x-tf', 'application/x-terraform'] + + classes = ('backend', 'data', 'module', 'output', 'provider', + 'provisioner', 'resource', 'variable') + classes_re = "({})".format(('|').join(classes)) + + types = ('string', 'number', 'bool', 'list', 'tuple', 'map', 'set', 'object', 'null') + + numeric_functions = ('abs', 'ceil', 'floor', 'log', 'max', + 'mix', 'parseint', 'pow', 'signum') + + string_functions = ('chomp', 'format', 'formatlist', 'indent', + 'join', 'lower', 'regex', 'regexall', 'replace', + 'split', 'strrev', 'substr', 'title', 'trim', + 'trimprefix', 'trimsuffix', 'trimspace', 'upper' + ) + + collection_functions = ('alltrue', 'anytrue', 'chunklist', 'coalesce', + 'coalescelist', 'compact', 'concat', 'contains', + 'distinct', 'element', 'flatten', 'index', 'keys', + 'length', 'list', 'lookup', 'map', 'matchkeys', + 'merge', 'range', 'reverse', 'setintersection', + 'setproduct', 'setsubtract', 'setunion', 'slice', + 'sort', 'sum', 'transpose', 'values', 'zipmap' + ) + + encoding_functions = ('base64decode', 'base64encode', 'base64gzip', + 'csvdecode', 'jsondecode', 'jsonencode', 'textdecodebase64', + 'textencodebase64', 'urlencode', 'yamldecode', 'yamlencode') + + filesystem_functions = ('abspath', 'dirname', 'pathexpand', 'basename', + 'file', 'fileexists', 'fileset', 'filebase64', 'templatefile') + + date_time_functions = ('formatdate', 'timeadd', 'timestamp') + + hash_crypto_functions = ('base64sha256', 'base64sha512', 'bcrypt', 'filebase64sha256', + 'filebase64sha512', 'filemd5', 'filesha1', 'filesha256', 'filesha512', + 'md5', 'rsadecrypt', 'sha1', 'sha256', 'sha512', 'uuid', 'uuidv5') + + ip_network_functions = ('cidrhost', 'cidrnetmask', 'cidrsubnet', 'cidrsubnets') + + type_conversion_functions = ('can', 'defaults', 'tobool', 'tolist', 'tomap', + 'tonumber', 'toset', 'tostring', 'try') + + builtins = numeric_functions + string_functions + collection_functions + encoding_functions +\ + filesystem_functions + date_time_functions + hash_crypto_functions + ip_network_functions +\ + type_conversion_functions + builtins_re = "({})".format(('|').join(builtins)) + + def heredoc_callback(self, match, ctx): + # Parse a terraform heredoc + # match: 1 = <<[-]?, 2 = name 3 = rest of line + + start = match.start(1) + yield start, Operator, match.group(1) # <<[-]? + yield match.start(2), String.Delimiter, match.group(2) # heredoc name + + ctx.pos = match.start(3) + ctx.end = match.end(3) + yield ctx.pos, String.Heredoc, match.group(3) + ctx.pos = match.end() + + hdname = match.group(2) + tolerant = True # leading whitespace is always accepted + + lines = [] + + for match in line_re.finditer(ctx.text, ctx.pos): + if tolerant: + check = match.group().strip() + else: + check = match.group().rstrip() + if check == hdname: + for amatch in lines: + yield amatch.start(), String.Heredoc, amatch.group() + yield match.start(), String.Delimiter, match.group() + ctx.pos = match.end() + break + else: + lines.append(match) + else: + # end of heredoc not found -- error! + for amatch in lines: + yield amatch.start(), Error, amatch.group() + ctx.end = len(ctx.text) + + tokens = { + 'root': [ + include('basic'), + include('whitespace'), + + # Strings + (r'(".*")', bygroups(String.Double)), + + # Constants + (words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Name.Constant), + + # Types + (words(types, prefix=r'\b', suffix=r'\b'), Keyword.Type), + + include('identifier'), + include('punctuation'), + (r'[0-9]+', Number), + ], + 'basic': [ + (r'\s*/\*', Comment.Multiline, 'comment'), + (r'\s*(#|//).*\n', Comment.Single), + include('whitespace'), + + # e.g. terraform { + # e.g. egress { + (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=?)(\s*)(\{)', + bygroups(Whitespace, Name.Builtin, Whitespace, Operator, Whitespace, Punctuation)), + + # Assignment with attributes, e.g. something = ... + (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=)(\s*)', + bygroups(Whitespace, Name.Attribute, Whitespace, Operator, Whitespace)), + + # Assignment with environment variables and similar, e.g. "something" = ... + # or key value assignment, e.g. "SlotName" : ... + (r'(\s*)("\S+")(\s*)([=:])(\s*)', + bygroups(Whitespace, Literal.String.Double, Whitespace, Operator, Whitespace)), + + # Functions, e.g. jsonencode(element("value")) + (builtins_re + r'(\()', bygroups(Name.Function, Punctuation)), + + # List of attributes, e.g. ignore_changes = [last_modified, filename] + (r'(\[)([a-z_,\s]+)(\])', bygroups(Punctuation, Name.Builtin, Punctuation)), + + # e.g. resource "aws_security_group" "allow_tls" { + # e.g. backend "consul" { + (classes_re + r'(\s+)("[0-9a-zA-Z-_]+")?(\s*)("[0-9a-zA-Z-_]+")(\s+)(\{)', + bygroups(Keyword.Reserved, Whitespace, Name.Class, Whitespace, Name.Variable, Whitespace, Punctuation)), + + # here-doc style delimited strings + (r'(<<-?)\s*([a-zA-Z_]\w*)(.*?\n)', heredoc_callback), + ], + 'identifier': [ + (r'\b(var\.[0-9a-zA-Z-_\.\[\]]+)\b', bygroups(Name.Variable)), + (r'\b([0-9a-zA-Z-_\[\]]+\.[0-9a-zA-Z-_\.\[\]]+)\b', + bygroups(Name.Variable)), + ], + 'punctuation': [ + (r'[\[\]()\{\},.?:!=]', Punctuation), + ], + 'comment': [ + (r'[^*/]', Comment.Multiline), + (r'/\*', Comment.Multiline, '#push'), + (r'\*/', Comment.Multiline, '#pop'), + (r'[*/]', Comment.Multiline) + ], + 'whitespace': [ + (r'\n', Whitespace), + (r'\s+', Whitespace), + (r'(\\)(\n)', bygroups(Text, Whitespace)), + ], + } + + +class TermcapLexer(RegexLexer): + """ + Lexer for termcap database source. + + This is very simple and minimal. + + .. versionadded:: 2.1 + """ + name = 'Termcap' + aliases = ['termcap'] + filenames = ['termcap', 'termcap.src'] + mimetypes = [] + + # NOTE: + # * multiline with trailing backslash + # * separator is ':' + # * to embed colon as data, we must use \072 + # * space after separator is not allowed (mayve) + tokens = { + 'root': [ + (r'^#.*', Comment), + (r'^[^\s#:|]+', Name.Tag, 'names'), + (r'\s+', Whitespace), + ], + 'names': [ + (r'\n', Whitespace, '#pop'), + (r':', Punctuation, 'defs'), + (r'\|', Punctuation), + (r'[^:|]+', Name.Attribute), + ], + 'defs': [ + (r'(\\)(\n[ \t]*)', bygroups(Text, Whitespace)), + (r'\n[ \t]*', Whitespace, '#pop:2'), + (r'(#)([0-9]+)', bygroups(Operator, Number)), + (r'=', Operator, 'data'), + (r':', Punctuation), + (r'[^\s:=#]+', Name.Class), + ], + 'data': [ + (r'\\072', Literal), + (r':', Punctuation, '#pop'), + (r'[^:\\]+', Literal), # for performance + (r'.', Literal), + ], + } + + +class TerminfoLexer(RegexLexer): + """ + Lexer for terminfo database source. + + This is very simple and minimal. + + .. versionadded:: 2.1 + """ + name = 'Terminfo' + aliases = ['terminfo'] + filenames = ['terminfo', 'terminfo.src'] + mimetypes = [] + + # NOTE: + # * multiline with leading whitespace + # * separator is ',' + # * to embed comma as data, we can use \, + # * space after separator is allowed + tokens = { + 'root': [ + (r'^#.*$', Comment), + (r'^[^\s#,|]+', Name.Tag, 'names'), + (r'\s+', Whitespace), + ], + 'names': [ + (r'\n', Whitespace, '#pop'), + (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), 'defs'), + (r'\|', Punctuation), + (r'[^,|]+', Name.Attribute), + ], + 'defs': [ + (r'\n[ \t]+', Whitespace), + (r'\n', Whitespace, '#pop:2'), + (r'(#)([0-9]+)', bygroups(Operator, Number)), + (r'=', Operator, 'data'), + (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace)), + (r'[^\s,=#]+', Name.Class), + ], + 'data': [ + (r'\\[,\\]', Literal), + (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), '#pop'), + (r'[^\\,]+', Literal), # for performance + (r'.', Literal), + ], + } + + +class PkgConfigLexer(RegexLexer): + """ + Lexer for pkg-config + (see also `manual page `_). + + .. versionadded:: 2.1 + """ + + name = 'PkgConfig' + url = 'http://www.freedesktop.org/wiki/Software/pkg-config/' + aliases = ['pkgconfig'] + filenames = ['*.pc'] + mimetypes = [] + + tokens = { + 'root': [ + (r'#.*$', Comment.Single), + + # variable definitions + (r'^(\w+)(=)', bygroups(Name.Attribute, Operator)), + + # keyword lines + (r'^([\w.]+)(:)', + bygroups(Name.Tag, Punctuation), 'spvalue'), + + # variable references + include('interp'), + + # fallback + (r'\s+', Whitespace), + (r'[^${}#=:\n.]+', Text), + (r'.', Text), + ], + 'interp': [ + # you can escape literal "$" as "$$" + (r'\$\$', Text), + + # variable references + (r'\$\{', String.Interpol, 'curly'), + ], + 'curly': [ + (r'\}', String.Interpol, '#pop'), + (r'\w+', Name.Attribute), + ], + 'spvalue': [ + include('interp'), + + (r'#.*$', Comment.Single, '#pop'), + (r'\n', Whitespace, '#pop'), + + # fallback + (r'\s+', Whitespace), + (r'[^${}#\n\s]+', Text), + (r'.', Text), + ], + } + + +class PacmanConfLexer(RegexLexer): + """ + Lexer for pacman.conf. + + Actually, IniLexer works almost fine for this format, + but it yield error token. It is because pacman.conf has + a form without assignment like: + + UseSyslog + Color + TotalDownload + CheckSpace + VerbosePkgLists + + These are flags to switch on. + + .. versionadded:: 2.1 + """ + + name = 'PacmanConf' + url = 'https://www.archlinux.org/pacman/pacman.conf.5.html' + aliases = ['pacmanconf'] + filenames = ['pacman.conf'] + mimetypes = [] + + tokens = { + 'root': [ + # comment + (r'#.*$', Comment.Single), + + # section header + (r'^(\s*)(\[.*?\])(\s*)$', bygroups(Whitespace, Keyword, Whitespace)), + + # variable definitions + # (Leading space is allowed...) + (r'(\w+)(\s*)(=)', + bygroups(Name.Attribute, Whitespace, Operator)), + + # flags to on + (r'^(\s*)(\w+)(\s*)$', + bygroups(Whitespace, Name.Attribute, Whitespace)), + + # built-in special values + (words(( + '$repo', # repository + '$arch', # architecture + '%o', # outfile + '%u', # url + ), suffix=r'\b'), + Name.Variable), + + # fallback + (r'\s+', Whitespace), + (r'.', Text), + ], + } + + +class AugeasLexer(RegexLexer): + """ + Lexer for Augeas. + + .. versionadded:: 2.4 + """ + name = 'Augeas' + url = 'http://augeas.net' + aliases = ['augeas'] + filenames = ['*.aug'] + + tokens = { + 'root': [ + (r'(module)(\s*)([^\s=]+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), + (r'(let)(\s*)([^\s=]+)', bygroups(Keyword.Declaration, Whitespace, Name.Variable)), + (r'(del|store|value|counter|seq|key|label|autoload|incl|excl|transform|test|get|put)(\s+)', bygroups(Name.Builtin, Whitespace)), + (r'(\()([^:]+)(\:)(unit|string|regexp|lens|tree|filter)(\))', bygroups(Punctuation, Name.Variable, Punctuation, Keyword.Type, Punctuation)), + (r'\(\*', Comment.Multiline, 'comment'), + (r'[*+\-.;=?|]', Operator), + (r'[()\[\]{}]', Operator), + (r'"', String.Double, 'string'), + (r'\/', String.Regex, 'regex'), + (r'([A-Z]\w*)(\.)(\w+)', bygroups(Name.Namespace, Punctuation, Name.Variable)), + (r'.', Name.Variable), + (r'\s+', Whitespace), + ], + 'string': [ + (r'\\.', String.Escape), + (r'[^"]', String.Double), + (r'"', String.Double, '#pop'), + ], + 'regex': [ + (r'\\.', String.Escape), + (r'[^/]', String.Regex), + (r'\/', String.Regex, '#pop'), + ], + 'comment': [ + (r'[^*)]', Comment.Multiline), + (r'\(\*', Comment.Multiline, '#push'), + (r'\*\)', Comment.Multiline, '#pop'), + (r'[)*]', Comment.Multiline) + ], + } + + +class TOMLLexer(RegexLexer): + """ + Lexer for TOML, a simple language + for config files. + + .. versionadded:: 2.4 + """ + + name = 'TOML' + url = 'https://github.com/toml-lang/toml' + aliases = ['toml'] + filenames = ['*.toml', 'Pipfile', 'poetry.lock'] + + tokens = { + 'root': [ + # Table + (r'^(\s*)(\[.*?\])$', bygroups(Whitespace, Keyword)), + + # Basics, comments, strings + (r'[ \t]+', Whitespace), + (r'\n', Whitespace), + (r'#.*?$', Comment.Single), + # Basic string + (r'"(\\\\|\\[^\\]|[^"\\])*"', String), + # Literal string + (r'\'\'\'(.*)\'\'\'', String), + (r'\'[^\']*\'', String), + (r'(true|false)$', Keyword.Constant), + (r'[a-zA-Z_][\w\-]*', Name), + + # Datetime + # TODO this needs to be expanded, as TOML is rather flexible: + # https://github.com/toml-lang/toml#offset-date-time + (r'\d{4}-\d{2}-\d{2}(?:T| )\d{2}:\d{2}:\d{2}(?:Z|[-+]\d{2}:\d{2})', Number.Integer), + + # Numbers + (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float), + (r'\d+[eE][+-]?[0-9]+j?', Number.Float), + # Handle +-inf, +-infinity, +-nan + (r'[+-]?(?:(inf(?:inity)?)|nan)', Number.Float), + (r'[+-]?\d+', Number.Integer), + + # Punctuation + (r'[]{}:(),;[]', Punctuation), + (r'\.', Punctuation), + + # Operators + (r'=', Operator) + + ] + } + +class NestedTextLexer(RegexLexer): + """ + Lexer for NextedText, a human-friendly data + format. + + .. versionadded:: 2.9 + """ + + name = 'NestedText' + url = 'https://nestedtext.org' + aliases = ['nestedtext', 'nt'] + filenames = ['*.nt'] + + _quoted_dict_item = r'^(\s*)({0})(.*?)({0}: ?)(.*?)(\s*)$' + + tokens = { + 'root': [ + (r'^(\s*)(#.*?)$', bygroups(Whitespace, Comment)), + (r'^(\s*)(>)( ?)(.*?)(\s*)$', bygroups(Whitespace, Punctuation, Whitespace, String, Whitespace)), + (r'^(\s*)(-)( ?)(.*?)(\s*)$', bygroups(Whitespace, Punctuation, Whitespace, String, Whitespace)), + (_quoted_dict_item.format("'"), bygroups(Whitespace, Punctuation, Name, Punctuation, String, Whitespace)), + (_quoted_dict_item.format('"'), bygroups(Whitespace, Punctuation, Name, Punctuation, String, Whitespace)), + (r'^(\s*)(.*?)(:)( ?)(.*?)(\s*)$', bygroups(Whitespace, Name, Punctuation, Whitespace, String, Whitespace)), + ], + } + + +class SingularityLexer(RegexLexer): + """ + Lexer for Singularity definition files. + + .. versionadded:: 2.6 + """ + + name = 'Singularity' + url = 'https://www.sylabs.io/guides/3.0/user-guide/definition_files.html' + aliases = ['singularity'] + filenames = ['*.def', 'Singularity'] + flags = re.IGNORECASE | re.MULTILINE | re.DOTALL + + _headers = r'^(\s*)(bootstrap|from|osversion|mirrorurl|include|registry|namespace|includecmd)(:)' + _section = r'^(%(?:pre|post|setup|environment|help|labels|test|runscript|files|startscript))(\s*)' + _appsect = r'^(%app(?:install|help|run|labels|env|test|files))(\s*)' + + tokens = { + 'root': [ + (_section, bygroups(Generic.Heading, Whitespace), 'script'), + (_appsect, bygroups(Generic.Heading, Whitespace), 'script'), + (_headers, bygroups(Whitespace, Keyword, Text)), + (r'\s*#.*?\n', Comment), + (r'\b(([0-9]+\.?[0-9]*)|(\.[0-9]+))\b', Number), + (r'[ \t]+', Whitespace), + (r'(?!^\s*%).', Text), + ], + 'script': [ + (r'(.+?(?=^\s*%))|(.*)', using(BashLexer), '#pop'), + ], + } + + def analyse_text(text): + """This is a quite simple script file, but there are a few keywords + which seem unique to this language.""" + result = 0 + if re.search(r'\b(?:osversion|includecmd|mirrorurl)\b', text, re.IGNORECASE): + result += 0.5 + + if re.search(SingularityLexer._section[1:], text): + result += 0.49 + + return result + + +class UnixConfigLexer(RegexLexer): + """ + Lexer for Unix/Linux config files using colon-separated values, e.g. + + * ``/etc/group`` + * ``/etc/passwd`` + * ``/etc/shadow`` + + .. versionadded:: 2.12 + """ + + name = 'Unix/Linux config files' + aliases = ['unixconfig', 'linuxconfig'] + filenames = [] + + tokens = { + 'root': [ + (r'^#.*', Comment), + (r'\n', Whitespace), + (r':', Punctuation), + (r'[0-9]+', Number), + (r'((?!\n)[a-zA-Z0-9\_\-\s\(\),]){2,}', Text), + (r'[^:\n]+', String), + ], + } diff --git a/shared/package-files/3c/3c29a87cd0ea7fb5f1374b9f551b25c13464e16af2ea129a66afd0877e68e263/cons25-iso-m b/shared/package-files/3c/3c29a87cd0ea7fb5f1374b9f551b25c13464e16af2ea129a66afd0877e68e263/cons25-iso-m new file mode 100644 index 0000000000000000000000000000000000000000..fead95f85ecb687d141fdc30536ee5ba0c7691dc Binary files /dev/null and b/shared/package-files/3c/3c29a87cd0ea7fb5f1374b9f551b25c13464e16af2ea129a66afd0877e68e263/cons25-iso-m differ diff --git a/shared/package-files/3c/3c2ba385b5738da61e7affd32e6e7e38d7ad511942269d66076c7cd0d0399f43/jit.py b/shared/package-files/3c/3c2ba385b5738da61e7affd32e6e7e38d7ad511942269d66076c7cd0d0399f43/jit.py new file mode 100644 index 0000000000000000000000000000000000000000..e571166d288a9837b9e9a18938ed358c1571b0bc --- /dev/null +++ b/shared/package-files/3c/3c2ba385b5738da61e7affd32e6e7e38d7ad511942269d66076c7cd0d0399f43/jit.py @@ -0,0 +1,635 @@ +from __future__ import annotations, division + +import ast +import functools +import hashlib +import inspect +import os +import textwrap +from collections import defaultdict, namedtuple +from functools import cached_property +from typing import Callable, Generic, Iterable, List, Optional, TypeVar, Union, cast, overload + +from .._C.libtriton.triton import TMAInfos +from ..common.backend import get_backend, get_cuda_version_key +from .interpreter import InterpretedFunction +from ..runtime.driver import driver + +T = TypeVar("T") + +# ----------------------------------------------------------------------------- +# Dependencies Finder +# ----------------------------------------------------------------------------- + + +class DependenciesFinder(ast.NodeVisitor): + """ + This AST visitor is used to find dependencies of a JITFunction. This can + be used to invalidate a JITFunction's hash when its source code -- or + that of its dependencies -- changes. + """ + + def __init__(self, globals, src) -> None: + super().__init__() + self.ret = hashlib.sha1(src.encode("utf-8")).hexdigest() + self.globals = globals + + def visit_Name(self, node): + return self.globals.get(node.id, None) + + def visit_Attribute(self, node): + lhs = self.visit(node.value) + while isinstance(lhs, ast.Attribute): + lhs = self.visit(lhs.value) + if lhs is None or (getattr(lhs, "__name__", "") == "triton" + or getattr(lhs, "__name__", "").endswith(".triton")): + return None + return getattr(lhs, node.attr) + + def visit_Call(self, node): + func = self.visit(node.func) + if func is None: + return + if inspect.isbuiltin(func): + return + if func.__module__ and (func.__module__.startswith("triton.") or ".triton." in func.__module__): + return + assert isinstance( + func, JITFunction + ), f'Function "{func.__name__}" is being called from a Triton function but is not a Triton function itself. Decorate it with @triton.jit to fix this' + func_cache_key = func.cache_key + noinline = str(getattr(func, "noinline", False)) + self.ret = (self.ret + func_cache_key + noinline).encode("utf-8") + self.ret = hashlib.sha1(self.ret).hexdigest() + + +# ----------------------------------------------------------------------------- +# JITFunction +# ----------------------------------------------------------------------------- + + +def _normalize_ty(ty) -> str: + if isinstance(ty, type): + return ty.__name__ + elif isinstance(ty, str): + return ty + return repr(ty) + + +class KernelParam: + """Represents a parameter to a @jit'ed function. + + A parameter is just the name plus metadata; a parameter plus a value is a + KernelArg. + """ + + def __init__(self, num: int, param: inspect.Parameter, do_not_specialize: bool): + self.num = num + self._param = param + self.do_not_specialize = do_not_specialize + + @cached_property + def name(self): + return self._param.name + + @cached_property + def annotation(self): + if not self._param.annotation or self._param.annotation == inspect.Parameter.empty: + return "" + return _normalize_ty(self._param.annotation) + + @cached_property + def is_constexpr(self): + return "constexpr" in self.annotation + + @property + def default(self): + return self._param.default + + @property + def has_default(self): + return self._param.default != inspect.Parameter.empty + + +class KernelArg: + """Represents an argument to a @jit'ed function. + + An argument is a parameter plus a value. + """ + + def __init__(self, value, param): + self.value = value + self.param = param + + @property + def name(self): + return self.param.name + + def signature_key(self): + annotation = self.param.annotation + if "Tensor" in annotation: + return self.value.dtype + elif annotation == "bool": + return "i1" + elif annotation == "float": + return "fp32" + else: + return JITFunction._key_of(self.value) + + def specialization_key(self): + assert not self.param.do_not_specialize + + try: + return (self.value.data_ptr() % JITFunction.divisibility == 0, ) + except AttributeError: + pass + + if isinstance(self.value, int): + # bool is a subclass of int, so we don't check explicitly above. + return ( + self.value % JITFunction.divisibility == 0, + self.value % JITFunction.divisibility_8 == 0, + self.value == 1, + ) + + return (False, ) + + +class KernelInterface(Generic[T]): + run: T + + def __getitem__(self, grid) -> T: + """ + A JIT function is launched with: fn[grid](*args, **kwargs). + Hence JITFunction.__getitem__ returns a callable proxy that + memorizes the grid. + """ + return lambda *args, **kwargs: self.run(grid=grid, warmup=False, *args, **kwargs) + # return cast(T, functools.partial(cast(Callable, self.run), grid=grid)) + + +class JITFunction(KernelInterface[T]): + # Hook for inspecting compiled functions and modules + cache_hook = None + divisibility = 16 + # As Hopper TMA load and store primitive requires the tensor stride to be 16-byte aligned. + # And we only support WGMMA with float16 dtype on Hopper for now. + # So whether the LoadOp and StoreOp will lowering into TMA copy depend on whether the tensor stride is divisible by 8. + # TODO: Make it more reasonable to handle multiple dtypes. + divisibility_8 = 8 + + @staticmethod + def _key_of(arg): + if hasattr(arg, "dtype"): + return arg.dtype + elif isinstance(arg, bool): + return "i1" + elif isinstance(arg, int): + if -(2**31) <= arg and arg <= 2**31 - 1: + return "i32" + elif 2**63 <= arg and arg <= 2**64 - 1: + return "u64" + else: + return "i64" + elif isinstance(arg, float): + return "fp32" + elif arg is None: + return None + else: + raise TypeError(f"Unsupported type {type(arg)} for {arg}") + + @staticmethod + def _device_of(arg): + try: + return arg.device.type + except AttributeError: + return "" + + @staticmethod + def _pinned_memory_of(arg): + try: + return arg.is_pinned() + except (AttributeError, TypeError): + return False + + @staticmethod + def _spec_of(arg): + if hasattr(arg, "data_ptr"): + return arg.data_ptr() % JITFunction.divisibility == 0 + elif isinstance(arg, int): + return (arg % 16 == 0, arg == 1) + return (arg is None, ) + + # TODO(jlebar): Fold this into the KernelArg class. + def _get_config(self, *args): + from ..compiler import AttrsDescriptor + + def is_divisible_by_16(x): + if hasattr(x, "data_ptr"): + return x.data_ptr() % JITFunction.divisibility == 0 + elif isinstance(x, int): + return x % JITFunction.divisibility == 0 + if x is None: + return True + return False + + def is_divisible_by_8(x): + if isinstance(x, int): + return x % JITFunction.divisibility_8 == 0 + if x is None: + return True + return False + + divisible_by_16 = { + param.num + for param, arg in zip(self.params, args) + if is_divisible_by_16(arg) and not param.do_not_specialize + } + divisible_by_8 = { + param.num + for param, arg in zip(self.params, args) + if is_divisible_by_8(arg) and not param.do_not_specialize + } + equal_to_1 = { + param.num + for param, arg in zip(self.params, args) + if isinstance(arg, int) and not isinstance(arg, bool) and arg == 1 and not param.do_not_specialize + } + # folded equal_to_1 and None + # TODO: method to collect all folded args + none_args = {param.num for param, arg in zip(self.params, args) if arg is None and not param.do_not_specialize} + ids_of_folded_args = equal_to_1 | none_args + return AttrsDescriptor(tuple(divisible_by_16), tuple(equal_to_1), tuple(ids_of_folded_args), + tuple(divisible_by_8)) + # return _triton.code_gen.instance_descriptor(divisible_by_16, + # equal_to_1) + + @staticmethod + def _type_of(key): + # `None` is nullptr. Implicitly convert to *i8. + if key is None: + return "*i8" + dtype_str = str(key).split(".")[-1] + tys = { + "bool": "i1", + "float8e4nv": "fp8e4nv", + "float8e5": "fp8e5", + "float8e4b15": "fp8e4b15", + "float8e4b15x4": "fp8e4b15x4", + "float8_e4m3fn": "fp8e4nv", + "float8_e5m2": "fp8e5", + "float16": "fp16", + "bfloat16": "bf16", + "float32": "fp32", + "float64": "fp64", + "int8": "i8", + "int16": "i16", + "int32": "i32", + "int64": "i64", + "uint8": "u8", + "uint16": "u16", + "uint32": "u32", + "uint64": "u64", + } + # reinterpret can create triton type + for v in list(tys.values()): + tys[v] = v + return key if isinstance(key, str) else f"*{tys[dtype_str]}" + + def _make_constants(self, constexpr_key): + constants = dict(zip(self.constexprs, constexpr_key)) + return constants + + def _call_hook( + self, + key, + signature, + device, + constants, + num_warps, + num_ctas, + num_stages, + enable_warp_specialization, + enable_fp_fusion, + extern_libs, + configs, + ): + if JITFunction.cache_hook is None: + return False + + name = self.fn.__name__ + module = self.fn.__module__ + arg_reprs = ", ".join([f"{param.name}: {ty}" for param, ty in zip(self.params, key[1])]) + repr = f"{name}[num_warps={num_warps}, num_ctas={num_ctas}, num_stages={num_stages}, enable_warp_specialization={enable_warp_specialization}, enable_fp_fusion={enable_fp_fusion}]({arg_reprs})" + key = str(key) + + class LegacyCompiler: + + def __init__(self, module, name): + self.module = module + self.name = name + pass + + kwargs = dict( + signature=signature, + device=device, + constants=constants, + num_warps=num_warps, + num_ctas=num_ctas, + num_stages=num_stages, + enable_warp_specialization=enable_warp_specialization, + enable_fp_fusion=enable_fp_fusion, + extern_libs=extern_libs, + configs=configs, + ) + + return JITFunction.cache_hook( + key=key, + repr=repr, + fn=LegacyCompiler(module, name), + compile={"key": key, **kwargs}, + is_manual_warmup=False, + already_compiled=False, + ) + + def run(self, *args, grid, warmup, **kwargs): + from ..compiler import CompiledKernel, compile, ASTSource + from ..compiler.backends.cuda import CUDABackend + # deprecated arguments + assert "device_type" not in kwargs, "device_type option is deprecated; current target will be used" + assert "device" not in kwargs, "device option is deprecated; current device will be used" + assert "stream" not in kwargs, "stream option is deprecated; current stream will be used" + # parse options + device = driver.get_current_device() + stream = driver.get_current_stream(device) + target = driver.get_current_target() + backend = CUDABackend(target) + kwargs["debug"] = self.debug + options = backend.parse_options(kwargs) + # bind non-reserved keyword args and set defaults + kwargs = {k: v for k, v in kwargs.items() if not k in options.__dict__} + bound_args = self.signature.bind(*args, **kwargs) + bound_args.apply_defaults() + assert len(bound_args.arguments) == len(self.params) + # canonicalize grid + assert grid is not None + if callable(grid): + # Arguments are passed as a dict to `grid`, by contract. + # TODO(jlebar): In the new launch API, pass the compiler flags as a + # second parameter to `grid`. + grid = grid(dict(bound_args.arguments)) + grid_size = len(grid) + grid_0 = grid[0] + grid_1 = grid[1] if grid_size > 1 else 1 + grid_2 = grid[2] if grid_size > 2 else 1 + # compute cache key + args = [KernelArg(arg_value, param) for (_, arg_value), param in zip(bound_args.arguments.items(), self.params)] + sig_key = tuple(arg.signature_key() for arg in args if not arg.param.is_constexpr) + spec_key = tuple(arg.specialization_key() for arg in args if not arg.param.do_not_specialize) + constexpr_key = tuple(arg.value for arg in args if arg.param.is_constexpr) + key = (get_cuda_version_key(), sig_key, constexpr_key, spec_key, options) + # Kernel is not cached; we have to compile. + if key not in self.cache[device]: + configs = (self._get_config(*[arg.value for arg in args]), ) + constants = { + arg.param.num: arg.value + for arg in args + if arg.param.is_constexpr or arg.param.num in configs[0].equal_to_1 or arg.value is None + } + for i, arg in constants.items(): + if callable(arg): + raise TypeError(f"Callable constexpr at index {i} is not supported") + + # Build kernel signature -- doesn't include constexpr arguments. + signature = { + arg.param.num: self._type_of(self._key_of(arg.value)) + for arg in args + if not arg.param.is_constexpr + } + + if self._call_hook(key, signature, device, constants, options.num_warps, options.num_ctas, + options.num_stages, options.enable_warp_specialization, options.enable_fp_fusion, + options.extern_libs, configs): + return None + # compile the kernel + src = ASTSource(self, signature, constants, configs[0]) + self.cache[device][key] = compile( + src, + target=target, + options=options.__dict__, + ) + + kernel = self.cache[device][key] + if not warmup: + args = [arg.value for arg in args if not arg.param.is_constexpr] + kernel.run(grid_0, grid_1, grid_2, kernel.num_warps, kernel.num_ctas, # number of warps/ctas per instance + kernel.cluster_dims[0], kernel.cluster_dims[1], kernel.cluster_dims[2], # cluster + kernel.shared, stream, kernel.function, CompiledKernel.launch_enter_hook, + CompiledKernel.launch_exit_hook, kernel, + *driver.assemble_tensormap_to_arg(kernel.metadata["tensormaps_info"], args)) + return kernel + + def __init__(self, fn, version=None, do_not_specialize=None, debug=None, noinline=None): + do_not_specialize = do_not_specialize if do_not_specialize else [] + + self.fn = fn + self.module = fn.__module__ + self.version = version + self.signature = inspect.signature(fn) + self.do_not_specialize = do_not_specialize + self.starting_line_number = inspect.getsourcelines(fn)[1] + + self.params = [] + for i, param in enumerate(self.signature.parameters.values()): + dns = do_not_specialize and (i in do_not_specialize or param.name in do_not_specialize) + self.params.append(KernelParam(i, param, dns)) + + # function source code (without decorators) + self.src = textwrap.dedent(inspect.getsource(fn)) + self.src = self.src[self.src.find("def"):] + # cache of just-in-time compiled kernels + self.cache = defaultdict(dict) + self.hash = None + # JITFunction can be instantiated as kernel + # when called with a grid using __getitem__ + self.kernel = None + self.debug = True if os.environ.get("TRITON_DEBUG", "0") == "1" else debug + self.noinline = noinline + + # tma info + self.tensormaps_info = TMAInfos() + + # TODO(jlebar): Remove uses of these fields outside this file, then + # remove the fields here. + self.arg_names = [p.name for p in self.params] + self.constexprs = [p.num for p in self.params if p.is_constexpr] + + # re-use docs of wrapped function + self.__doc__ = fn.__doc__ + self.__name__ = fn.__name__ + self.__globals__ = fn.__globals__ + self.__module__ = fn.__module__ + + @property + def cache_key(self): + # TODO : hash should be attribute of `self` + if self.hash is None: + dependencies_finder = DependenciesFinder(globals=self.__globals__, src=self.src) + dependencies_finder.visit(self.parse()) + self.hash = dependencies_finder.ret + str(self.starting_line_number) + return self.hash + + def warmup(self, *args, grid, **kwargs): + return self.run(grid=grid, warmup=True, *map(MockTensor.wrap_dtype, args), **kwargs) + + # we do not parse `src` in the constructor because + # the user might want to monkey-patch self.src dynamically. + # Our unit tests do this, for example. + def parse(self): + tree = ast.parse(self.src) + assert isinstance(tree, ast.Module) + assert len(tree.body) == 1 + assert isinstance(tree.body[0], ast.FunctionDef) + return tree + + def __call__(self, *args, **kwargs): + raise RuntimeError("Cannot call @triton.jit'd outside of the scope of a kernel") + + def __setattr__(self, name, value): + super(JITFunction, self).__setattr__(name, value) + # - when `.src` attribute is set, cache path needs + # to be reinitialized + if name == "src": + self.hash = None + + def __repr__(self): + return f"JITFunction({self.module}:{self.fn.__name__})" + + +# ----------------------------------------------------------------------------- +# `jit` decorator +# ----------------------------------------------------------------------------- + + +@overload +def jit(fn: T) -> JITFunction[T]: + ... + + +@overload +def jit( + *, + version=None, + do_not_specialize: Optional[Iterable[int]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> Callable[[T], JITFunction[T]]: + ... + + +def jit( + fn: Optional[T] = None, + *, + version=None, + do_not_specialize: Optional[Iterable[int]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> Union[JITFunction[T], Callable[[T], JITFunction[T]]]: + """ + Decorator for JIT-compiling a function using the Triton compiler. + + :note: When a jit'd function is called, arguments are + implicitly converted to pointers if they have a :code:`.data_ptr()` method + and a `.dtype` attribute. + + :note: This function will be compiled and run on the GPU. It will only have access to: + + * python primitives, + * builtins within the triton package, + * arguments to this function, + * other jit'd functions + + :param fn: the function to be jit-compiled + :type fn: Callable + """ + + def decorator(fn: T) -> JITFunction[T]: + assert callable(fn) + if os.getenv("TRITON_INTERPRET", "0") == "1": + return InterpretedFunction(fn) + else: + return JITFunction( + fn, + version=version, + do_not_specialize=do_not_specialize, + debug=debug, + noinline=noinline, + ) + + if fn is not None: + return decorator(fn) + + else: + return decorator + + +# ----------------------------------------------------------------------------- +# Utilities for mocking tensors +# ----------------------------------------------------------------------------- + + +class MockTensor: + """ + Can be used in place of real tensors when calling: + kernel.warmup(MockTensor(torch.float32), ...) + """ + + @staticmethod + def wrap_dtype(arg): + if arg.__class__.__name__ == "dtype" and arg.__module__ == "torch": + return MockTensor(arg) + return arg + + def __init__(self, dtype): + self.dtype = dtype + + @staticmethod + def data_ptr(): + return 0 # optimistically assumes multiple of 16 + + +class TensorWrapper: + + def __init__(self, base, dtype): + self.dtype = dtype + self.base = base + self.is_cuda = base.is_cuda + self.device = base.device + self.shape = self.base.shape + + def data_ptr(self): + return self.base.data_ptr() + + def stride(self, i): + return self.base.stride(i) + + def __str__(self) -> str: + return f"TensorWrapper[{self.dtype}]({self.base})" + + def element_size(self): + return self.base.element_size() + + +def reinterpret(tensor, dtype): + if isinstance(tensor, TensorWrapper): + if dtype == tensor.base.dtype: + # Reinterpreting to the original interpretation; return the base. + return tensor.base + else: + # Reinterpreting a wrapped tensor to a different type. + return TensorWrapper(tensor.base, dtype) + elif hasattr(tensor, "data_ptr"): + # A new wrapper is needed around an unwrapped tensor. + return TensorWrapper(tensor, dtype) + else: + raise TypeError(f"Cannot reinterpret a {type(tensor)}.") diff --git a/shared/package-files/3c/3c2d4d2f0f404c1ac237bcc742ccf16ef1d5bcc1cbd71505a55d689fde1433a4/linux-rhel7-ivybridge b/shared/package-files/3c/3c2d4d2f0f404c1ac237bcc742ccf16ef1d5bcc1cbd71505a55d689fde1433a4/linux-rhel7-ivybridge new file mode 100644 index 0000000000000000000000000000000000000000..7d6cfe4daaed77956694e9c14bd43a3bd739d86f --- /dev/null +++ b/shared/package-files/3c/3c2d4d2f0f404c1ac237bcc742ccf16ef1d5bcc1cbd71505a55d689fde1433a4/linux-rhel7-ivybridge @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 62 +model name : Intel(R) Xeon(R) CPU E5-2650 v2 @ 2.60GHz +stepping : 4 +microcode : 0x42c +cpu MHz : 1862.554 +cache size : 20480 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 8 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt ibpb ibrs stibp dtherm ida arat pln pts spec_ctrl intel_stibp +bogomips : 5200.15 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/shared/package-files/3c/3c31621e634be2e978034c2248b0e963d252ac34bbdd132e96bd56f5a3445bcb/xxhash.h b/shared/package-files/3c/3c31621e634be2e978034c2248b0e963d252ac34bbdd132e96bd56f5a3445bcb/xxhash.h new file mode 100644 index 0000000000000000000000000000000000000000..9c819f93b79dfb03301206578377da96469c1ebe --- /dev/null +++ b/shared/package-files/3c/3c31621e634be2e978034c2248b0e963d252ac34bbdd132e96bd56f5a3445bcb/xxhash.h @@ -0,0 +1,7487 @@ +/* + * xxHash - Extremely Fast Hash algorithm + * Header File + * Copyright (C) 2012-2023 Yann Collet + * + * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php) + * + * 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. + * + * 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. + * + * You can contact the author at: + * - xxHash homepage: https://www.xxhash.com + * - xxHash source repository: https://github.com/Cyan4973/xxHash + */ + +/*! + * @mainpage xxHash + * + * xxHash is an extremely fast non-cryptographic hash algorithm, working at RAM speed + * limits. + * + * It is proposed in four flavors, in three families: + * 1. @ref XXH32_family + * - Classic 32-bit hash function. Simple, compact, and runs on almost all + * 32-bit and 64-bit systems. + * 2. @ref XXH64_family + * - Classic 64-bit adaptation of XXH32. Just as simple, and runs well on most + * 64-bit systems (but _not_ 32-bit systems). + * 3. @ref XXH3_family + * - Modern 64-bit and 128-bit hash function family which features improved + * strength and performance across the board, especially on smaller data. + * It benefits greatly from SIMD and 64-bit without requiring it. + * + * Benchmarks + * --- + * The reference system uses an Intel i7-9700K CPU, and runs Ubuntu x64 20.04. + * The open source benchmark program is compiled with clang v10.0 using -O3 flag. + * + * | Hash Name | ISA ext | Width | Large Data Speed | Small Data Velocity | + * | -------------------- | ------- | ----: | ---------------: | ------------------: | + * | XXH3_64bits() | @b AVX2 | 64 | 59.4 GB/s | 133.1 | + * | MeowHash | AES-NI | 128 | 58.2 GB/s | 52.5 | + * | XXH3_128bits() | @b AVX2 | 128 | 57.9 GB/s | 118.1 | + * | CLHash | PCLMUL | 64 | 37.1 GB/s | 58.1 | + * | XXH3_64bits() | @b SSE2 | 64 | 31.5 GB/s | 133.1 | + * | XXH3_128bits() | @b SSE2 | 128 | 29.6 GB/s | 118.1 | + * | RAM sequential read | | N/A | 28.0 GB/s | N/A | + * | ahash | AES-NI | 64 | 22.5 GB/s | 107.2 | + * | City64 | | 64 | 22.0 GB/s | 76.6 | + * | T1ha2 | | 64 | 22.0 GB/s | 99.0 | + * | City128 | | 128 | 21.7 GB/s | 57.7 | + * | FarmHash | AES-NI | 64 | 21.3 GB/s | 71.9 | + * | XXH64() | | 64 | 19.4 GB/s | 71.0 | + * | SpookyHash | | 64 | 19.3 GB/s | 53.2 | + * | Mum | | 64 | 18.0 GB/s | 67.0 | + * | CRC32C | SSE4.2 | 32 | 13.0 GB/s | 57.9 | + * | XXH32() | | 32 | 9.7 GB/s | 71.9 | + * | City32 | | 32 | 9.1 GB/s | 66.0 | + * | Blake3* | @b AVX2 | 256 | 4.4 GB/s | 8.1 | + * | Murmur3 | | 32 | 3.9 GB/s | 56.1 | + * | SipHash* | | 64 | 3.0 GB/s | 43.2 | + * | Blake3* | @b SSE2 | 256 | 2.4 GB/s | 8.1 | + * | HighwayHash | | 64 | 1.4 GB/s | 6.0 | + * | FNV64 | | 64 | 1.2 GB/s | 62.7 | + * | Blake2* | | 256 | 1.1 GB/s | 5.1 | + * | SHA1* | | 160 | 0.8 GB/s | 5.6 | + * | MD5* | | 128 | 0.6 GB/s | 7.8 | + * @note + * - Hashes which require a specific ISA extension are noted. SSE2 is also noted, + * even though it is mandatory on x64. + * - Hashes with an asterisk are cryptographic. Note that MD5 is non-cryptographic + * by modern standards. + * - Small data velocity is a rough average of algorithm's efficiency for small + * data. For more accurate information, see the wiki. + * - More benchmarks and strength tests are found on the wiki: + * https://github.com/Cyan4973/xxHash/wiki + * + * Usage + * ------ + * All xxHash variants use a similar API. Changing the algorithm is a trivial + * substitution. + * + * @pre + * For functions which take an input and length parameter, the following + * requirements are assumed: + * - The range from [`input`, `input + length`) is valid, readable memory. + * - The only exception is if the `length` is `0`, `input` may be `NULL`. + * - For C++, the objects must have the *TriviallyCopyable* property, as the + * functions access bytes directly as if it was an array of `unsigned char`. + * + * @anchor single_shot_example + * **Single Shot** + * + * These functions are stateless functions which hash a contiguous block of memory, + * immediately returning the result. They are the easiest and usually the fastest + * option. + * + * XXH32(), XXH64(), XXH3_64bits(), XXH3_128bits() + * + * @code{.c} + * #include + * #include "xxhash.h" + * + * // Example for a function which hashes a null terminated string with XXH32(). + * XXH32_hash_t hash_string(const char* string, XXH32_hash_t seed) + * { + * // NULL pointers are only valid if the length is zero + * size_t length = (string == NULL) ? 0 : strlen(string); + * return XXH32(string, length, seed); + * } + * @endcode + * + * + * @anchor streaming_example + * **Streaming** + * + * These groups of functions allow incremental hashing of unknown size, even + * more than what would fit in a size_t. + * + * XXH32_reset(), XXH64_reset(), XXH3_64bits_reset(), XXH3_128bits_reset() + * + * @code{.c} + * #include + * #include + * #include "xxhash.h" + * // Example for a function which hashes a FILE incrementally with XXH3_64bits(). + * XXH64_hash_t hashFile(FILE* f) + * { + * // Allocate a state struct. Do not just use malloc() or new. + * XXH3_state_t* state = XXH3_createState(); + * assert(state != NULL && "Out of memory!"); + * // Reset the state to start a new hashing session. + * XXH3_64bits_reset(state); + * char buffer[4096]; + * size_t count; + * // Read the file in chunks + * while ((count = fread(buffer, 1, sizeof(buffer), f)) != 0) { + * // Run update() as many times as necessary to process the data + * XXH3_64bits_update(state, buffer, count); + * } + * // Retrieve the finalized hash. This will not change the state. + * XXH64_hash_t result = XXH3_64bits_digest(state); + * // Free the state. Do not use free(). + * XXH3_freeState(state); + * return result; + * } + * @endcode + * + * Streaming functions generate the xxHash value from an incremental input. + * This method is slower than single-call functions, due to state management. + * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized. + * + * An XXH state must first be allocated using `XXH*_createState()`. + * + * Start a new hash by initializing the state with a seed using `XXH*_reset()`. + * + * Then, feed the hash state by calling `XXH*_update()` as many times as necessary. + * + * The function returns an error code, with 0 meaning OK, and any other value + * meaning there is an error. + * + * Finally, a hash value can be produced anytime, by using `XXH*_digest()`. + * This function returns the nn-bits hash as an int or long long. + * + * It's still possible to continue inserting input into the hash state after a + * digest, and generate new hash values later on by invoking `XXH*_digest()`. + * + * When done, release the state using `XXH*_freeState()`. + * + * + * @anchor canonical_representation_example + * **Canonical Representation** + * + * The default return values from XXH functions are unsigned 32, 64 and 128 bit + * integers. + * This the simplest and fastest format for further post-processing. + * + * However, this leaves open the question of what is the order on the byte level, + * since little and big endian conventions will store the same number differently. + * + * The canonical representation settles this issue by mandating big-endian + * convention, the same convention as human-readable numbers (large digits first). + * + * When writing hash values to storage, sending them over a network, or printing + * them, it's highly recommended to use the canonical representation to ensure + * portability across a wider range of systems, present and future. + * + * The following functions allow transformation of hash values to and from + * canonical format. + * + * XXH32_canonicalFromHash(), XXH32_hashFromCanonical(), + * XXH64_canonicalFromHash(), XXH64_hashFromCanonical(), + * XXH128_canonicalFromHash(), XXH128_hashFromCanonical(), + * + * @code{.c} + * #include + * #include "xxhash.h" + * + * // Example for a function which prints XXH32_hash_t in human readable format + * void printXxh32(XXH32_hash_t hash) + * { + * XXH32_canonical_t cano; + * XXH32_canonicalFromHash(&cano, hash); + * size_t i; + * for(i = 0; i < sizeof(cano.digest); ++i) { + * printf("%02x", cano.digest[i]); + * } + * printf("\n"); + * } + * + * // Example for a function which converts XXH32_canonical_t to XXH32_hash_t + * XXH32_hash_t convertCanonicalToXxh32(XXH32_canonical_t cano) + * { + * XXH32_hash_t hash = XXH32_hashFromCanonical(&cano); + * return hash; + * } + * @endcode + * + * + * @file xxhash.h + * xxHash prototypes and implementation + */ + +#if defined(__cplusplus) && !defined(XXH_NO_EXTERNC_GUARD) +extern "C" { +#endif + +/* **************************** + * INLINE mode + ******************************/ +/*! + * @defgroup public Public API + * Contains details on the public xxHash functions. + * @{ + */ +#ifdef XXH_DOXYGEN +/*! + * @brief Gives access to internal state declaration, required for static allocation. + * + * Incompatible with dynamic linking, due to risks of ABI changes. + * + * Usage: + * @code{.c} + * #define XXH_STATIC_LINKING_ONLY + * #include "xxhash.h" + * @endcode + */ +# define XXH_STATIC_LINKING_ONLY +/* Do not undef XXH_STATIC_LINKING_ONLY for Doxygen */ + +/*! + * @brief Gives access to internal definitions. + * + * Usage: + * @code{.c} + * #define XXH_STATIC_LINKING_ONLY + * #define XXH_IMPLEMENTATION + * #include "xxhash.h" + * @endcode + */ +# define XXH_IMPLEMENTATION +/* Do not undef XXH_IMPLEMENTATION for Doxygen */ + +/*! + * @brief Exposes the implementation and marks all functions as `inline`. + * + * Use these build macros to inline xxhash into the target unit. + * Inlining improves performance on small inputs, especially when the length is + * expressed as a compile-time constant: + * + * https://fastcompression.blogspot.com/2018/03/xxhash-for-small-keys-impressive-power.html + * + * It also keeps xxHash symbols private to the unit, so they are not exported. + * + * Usage: + * @code{.c} + * #define XXH_INLINE_ALL + * #include "xxhash.h" + * @endcode + * Do not compile and link xxhash.o as a separate object, as it is not useful. + */ +# define XXH_INLINE_ALL +# undef XXH_INLINE_ALL +/*! + * @brief Exposes the implementation without marking functions as inline. + */ +# define XXH_PRIVATE_API +# undef XXH_PRIVATE_API +/*! + * @brief Emulate a namespace by transparently prefixing all symbols. + * + * If you want to include _and expose_ xxHash functions from within your own + * library, but also want to avoid symbol collisions with other libraries which + * may also include xxHash, you can use @ref XXH_NAMESPACE to automatically prefix + * any public symbol from xxhash library with the value of @ref XXH_NAMESPACE + * (therefore, avoid empty or numeric values). + * + * Note that no change is required within the calling program as long as it + * includes `xxhash.h`: Regular symbol names will be automatically translated + * by this header. + */ +# define XXH_NAMESPACE /* YOUR NAME HERE */ +# undef XXH_NAMESPACE +#endif + +#if (defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)) \ + && !defined(XXH_INLINE_ALL_31684351384) + /* this section should be traversed only once */ +# define XXH_INLINE_ALL_31684351384 + /* give access to the advanced API, required to compile implementations */ +# undef XXH_STATIC_LINKING_ONLY /* avoid macro redef */ +# define XXH_STATIC_LINKING_ONLY + /* make all functions private */ +# undef XXH_PUBLIC_API +# if defined(__GNUC__) +# define XXH_PUBLIC_API static __inline __attribute__((__unused__)) +# elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define XXH_PUBLIC_API static inline +# elif defined(_MSC_VER) +# define XXH_PUBLIC_API static __inline +# else + /* note: this version may generate warnings for unused static functions */ +# define XXH_PUBLIC_API static +# endif + + /* + * This part deals with the special case where a unit wants to inline xxHash, + * but "xxhash.h" has previously been included without XXH_INLINE_ALL, + * such as part of some previously included *.h header file. + * Without further action, the new include would just be ignored, + * and functions would effectively _not_ be inlined (silent failure). + * The following macros solve this situation by prefixing all inlined names, + * avoiding naming collision with previous inclusions. + */ + /* Before that, we unconditionally #undef all symbols, + * in case they were already defined with XXH_NAMESPACE. + * They will then be redefined for XXH_INLINE_ALL + */ +# undef XXH_versionNumber + /* XXH32 */ +# undef XXH32 +# undef XXH32_createState +# undef XXH32_freeState +# undef XXH32_reset +# undef XXH32_update +# undef XXH32_digest +# undef XXH32_copyState +# undef XXH32_canonicalFromHash +# undef XXH32_hashFromCanonical + /* XXH64 */ +# undef XXH64 +# undef XXH64_createState +# undef XXH64_freeState +# undef XXH64_reset +# undef XXH64_update +# undef XXH64_digest +# undef XXH64_copyState +# undef XXH64_canonicalFromHash +# undef XXH64_hashFromCanonical + /* XXH3_64bits */ +# undef XXH3_64bits +# undef XXH3_64bits_withSecret +# undef XXH3_64bits_withSeed +# undef XXH3_64bits_withSecretandSeed +# undef XXH3_createState +# undef XXH3_freeState +# undef XXH3_copyState +# undef XXH3_64bits_reset +# undef XXH3_64bits_reset_withSeed +# undef XXH3_64bits_reset_withSecret +# undef XXH3_64bits_update +# undef XXH3_64bits_digest +# undef XXH3_generateSecret + /* XXH3_128bits */ +# undef XXH128 +# undef XXH3_128bits +# undef XXH3_128bits_withSeed +# undef XXH3_128bits_withSecret +# undef XXH3_128bits_reset +# undef XXH3_128bits_reset_withSeed +# undef XXH3_128bits_reset_withSecret +# undef XXH3_128bits_reset_withSecretandSeed +# undef XXH3_128bits_update +# undef XXH3_128bits_digest +# undef XXH128_isEqual +# undef XXH128_cmp +# undef XXH128_canonicalFromHash +# undef XXH128_hashFromCanonical + /* Finally, free the namespace itself */ +# undef XXH_NAMESPACE + + /* employ the namespace for XXH_INLINE_ALL */ +# define XXH_NAMESPACE XXH_INLINE_ + /* + * Some identifiers (enums, type names) are not symbols, + * but they must nonetheless be renamed to avoid redeclaration. + * Alternative solution: do not redeclare them. + * However, this requires some #ifdefs, and has a more dispersed impact. + * Meanwhile, renaming can be achieved in a single place. + */ +# define XXH_IPREF(Id) XXH_NAMESPACE ## Id +# define XXH_OK XXH_IPREF(XXH_OK) +# define XXH_ERROR XXH_IPREF(XXH_ERROR) +# define XXH_errorcode XXH_IPREF(XXH_errorcode) +# define XXH32_canonical_t XXH_IPREF(XXH32_canonical_t) +# define XXH64_canonical_t XXH_IPREF(XXH64_canonical_t) +# define XXH128_canonical_t XXH_IPREF(XXH128_canonical_t) +# define XXH32_state_s XXH_IPREF(XXH32_state_s) +# define XXH32_state_t XXH_IPREF(XXH32_state_t) +# define XXH64_state_s XXH_IPREF(XXH64_state_s) +# define XXH64_state_t XXH_IPREF(XXH64_state_t) +# define XXH3_state_s XXH_IPREF(XXH3_state_s) +# define XXH3_state_t XXH_IPREF(XXH3_state_t) +# define XXH128_hash_t XXH_IPREF(XXH128_hash_t) + /* Ensure the header is parsed again, even if it was previously included */ +# undef XXHASH_H_5627135585666179 +# undef XXHASH_H_STATIC_13879238742 +#endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */ + +/* **************************************************************** + * Stable API + *****************************************************************/ +#ifndef XXHASH_H_5627135585666179 +#define XXHASH_H_5627135585666179 1 + +/*! @brief Marks a global symbol. */ +#if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API) +# if defined(_WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT)) +# ifdef XXH_EXPORT +# define XXH_PUBLIC_API __declspec(dllexport) +# elif XXH_IMPORT +# define XXH_PUBLIC_API __declspec(dllimport) +# endif +# else +# define XXH_PUBLIC_API /* do nothing */ +# endif +#endif + +#ifdef XXH_NAMESPACE +# define XXH_CAT(A,B) A##B +# define XXH_NAME2(A,B) XXH_CAT(A,B) +# define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber) +/* XXH32 */ +# define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32) +# define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState) +# define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState) +# define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset) +# define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update) +# define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest) +# define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState) +# define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash) +# define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical) +/* XXH64 */ +# define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64) +# define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState) +# define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState) +# define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset) +# define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update) +# define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest) +# define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState) +# define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash) +# define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical) +/* XXH3_64bits */ +# define XXH3_64bits XXH_NAME2(XXH_NAMESPACE, XXH3_64bits) +# define XXH3_64bits_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSecret) +# define XXH3_64bits_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSeed) +# define XXH3_64bits_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSecretandSeed) +# define XXH3_createState XXH_NAME2(XXH_NAMESPACE, XXH3_createState) +# define XXH3_freeState XXH_NAME2(XXH_NAMESPACE, XXH3_freeState) +# define XXH3_copyState XXH_NAME2(XXH_NAMESPACE, XXH3_copyState) +# define XXH3_64bits_reset XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset) +# define XXH3_64bits_reset_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSeed) +# define XXH3_64bits_reset_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSecret) +# define XXH3_64bits_reset_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSecretandSeed) +# define XXH3_64bits_update XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_update) +# define XXH3_64bits_digest XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_digest) +# define XXH3_generateSecret XXH_NAME2(XXH_NAMESPACE, XXH3_generateSecret) +# define XXH3_generateSecret_fromSeed XXH_NAME2(XXH_NAMESPACE, XXH3_generateSecret_fromSeed) +/* XXH3_128bits */ +# define XXH128 XXH_NAME2(XXH_NAMESPACE, XXH128) +# define XXH3_128bits XXH_NAME2(XXH_NAMESPACE, XXH3_128bits) +# define XXH3_128bits_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSeed) +# define XXH3_128bits_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSecret) +# define XXH3_128bits_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSecretandSeed) +# define XXH3_128bits_reset XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset) +# define XXH3_128bits_reset_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSeed) +# define XXH3_128bits_reset_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSecret) +# define XXH3_128bits_reset_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSecretandSeed) +# define XXH3_128bits_update XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_update) +# define XXH3_128bits_digest XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_digest) +# define XXH128_isEqual XXH_NAME2(XXH_NAMESPACE, XXH128_isEqual) +# define XXH128_cmp XXH_NAME2(XXH_NAMESPACE, XXH128_cmp) +# define XXH128_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH128_canonicalFromHash) +# define XXH128_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH128_hashFromCanonical) +#endif + + +/* ************************************* +* Compiler specifics +***************************************/ + +/* specific declaration modes for Windows */ +#if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API) +# if defined(_WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT)) +# ifdef XXH_EXPORT +# define XXH_PUBLIC_API __declspec(dllexport) +# elif XXH_IMPORT +# define XXH_PUBLIC_API __declspec(dllimport) +# endif +# else +# define XXH_PUBLIC_API /* do nothing */ +# endif +#endif + +#if defined (__GNUC__) +# define XXH_CONSTF __attribute__((__const__)) +# define XXH_PUREF __attribute__((__pure__)) +# define XXH_MALLOCF __attribute__((__malloc__)) +#else +# define XXH_CONSTF /* disable */ +# define XXH_PUREF +# define XXH_MALLOCF +#endif + +/* ************************************* +* Version +***************************************/ +#define XXH_VERSION_MAJOR 0 +#define XXH_VERSION_MINOR 8 +#define XXH_VERSION_RELEASE 3 +/*! @brief Version number, encoded as two digits each */ +#define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE) + +/*! + * @brief Obtains the xxHash version. + * + * This is mostly useful when xxHash is compiled as a shared library, + * since the returned value comes from the library, as opposed to header file. + * + * @return @ref XXH_VERSION_NUMBER of the invoked library. + */ +XXH_PUBLIC_API XXH_CONSTF unsigned XXH_versionNumber (void); + + +/* **************************** +* Common basic types +******************************/ +#include /* size_t */ +/*! + * @brief Exit code for the streaming API. + */ +typedef enum { + XXH_OK = 0, /*!< OK */ + XXH_ERROR /*!< Error */ +} XXH_errorcode; + + +/*-********************************************************************** +* 32-bit hash +************************************************************************/ +#if defined(XXH_DOXYGEN) /* Don't show include */ +/*! + * @brief An unsigned 32-bit integer. + * + * Not necessarily defined to `uint32_t` but functionally equivalent. + */ +typedef uint32_t XXH32_hash_t; + +#elif !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# ifdef _AIX +# include +# else +# include +# endif + typedef uint32_t XXH32_hash_t; + +#else +# include +# if UINT_MAX == 0xFFFFFFFFUL + typedef unsigned int XXH32_hash_t; +# elif ULONG_MAX == 0xFFFFFFFFUL + typedef unsigned long XXH32_hash_t; +# else +# error "unsupported platform: need a 32-bit type" +# endif +#endif + +/*! + * @} + * + * @defgroup XXH32_family XXH32 family + * @ingroup public + * Contains functions used in the classic 32-bit xxHash algorithm. + * + * @note + * XXH32 is useful for older platforms, with no or poor 64-bit performance. + * Note that the @ref XXH3_family provides competitive speed for both 32-bit + * and 64-bit systems, and offers true 64/128 bit hash results. + * + * @see @ref XXH64_family, @ref XXH3_family : Other xxHash families + * @see @ref XXH32_impl for implementation details + * @{ + */ + +/*! + * @brief Calculates the 32-bit hash of @p input using xxHash32. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * @param seed The 32-bit seed to alter the hash's output predictably. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 32-bit xxHash32 value. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32 (const void* input, size_t length, XXH32_hash_t seed); + +#ifndef XXH_NO_STREAM +/*! + * @typedef struct XXH32_state_s XXH32_state_t + * @brief The opaque state struct for the XXH32 streaming API. + * + * @see XXH32_state_s for details. + * @see @ref streaming_example "Streaming Example" + */ +typedef struct XXH32_state_s XXH32_state_t; + +/*! + * @brief Allocates an @ref XXH32_state_t. + * + * @return An allocated pointer of @ref XXH32_state_t on success. + * @return `NULL` on failure. + * + * @note Must be freed with XXH32_freeState(). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_MALLOCF XXH32_state_t* XXH32_createState(void); +/*! + * @brief Frees an @ref XXH32_state_t. + * + * @param statePtr A pointer to an @ref XXH32_state_t allocated with @ref XXH32_createState(). + * + * @return @ref XXH_OK. + * + * @note @p statePtr must be allocated with XXH32_createState(). + * + * @see @ref streaming_example "Streaming Example" + * + */ +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); +/*! + * @brief Copies one @ref XXH32_state_t to another. + * + * @param dst_state The state to copy to. + * @param src_state The state to copy from. + * @pre + * @p dst_state and @p src_state must not be `NULL` and must not overlap. + */ +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state); + +/*! + * @brief Resets an @ref XXH32_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 32-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note This function resets and seeds a state. Call it before @ref XXH32_update(). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, XXH32_hash_t seed); + +/*! + * @brief Consumes a block of @p input to an @ref XXH32_state_t. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note Call this to incrementally consume blocks of data. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); + +/*! + * @brief Returns the calculated hash value from an @ref XXH32_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated 32-bit xxHash32 value from that state. + * + * @note + * Calling XXH32_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ + +/******* Canonical representation *******/ + +/*! + * @brief Canonical (big endian) representation of @ref XXH32_hash_t. + */ +typedef struct { + unsigned char digest[4]; /*!< Hash bytes, big endian */ +} XXH32_canonical_t; + +/*! + * @brief Converts an @ref XXH32_hash_t to a big endian @ref XXH32_canonical_t. + * + * @param dst The @ref XXH32_canonical_t pointer to be stored to. + * @param hash The @ref XXH32_hash_t to be converted. + * + * @pre + * @p dst must not be `NULL`. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash); + +/*! + * @brief Converts an @ref XXH32_canonical_t to a native @ref XXH32_hash_t. + * + * @param src The @ref XXH32_canonical_t to convert. + * + * @pre + * @p src must not be `NULL`. + * + * @return The converted hash. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src); + + +/*! @cond Doxygen ignores this part */ +#ifdef __has_attribute +# define XXH_HAS_ATTRIBUTE(x) __has_attribute(x) +#else +# define XXH_HAS_ATTRIBUTE(x) 0 +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +/* C-language Attributes are added in C23. */ +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L) && defined(__has_c_attribute) +# define XXH_HAS_C_ATTRIBUTE(x) __has_c_attribute(x) +#else +# define XXH_HAS_C_ATTRIBUTE(x) 0 +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +#if defined(__cplusplus) && defined(__has_cpp_attribute) +# define XXH_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define XXH_HAS_CPP_ATTRIBUTE(x) 0 +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +/* + * Define XXH_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute + * introduced in CPP17 and C23. + * CPP17 : https://en.cppreference.com/w/cpp/language/attributes/fallthrough + * C23 : https://en.cppreference.com/w/c/language/attributes/fallthrough + */ +#if XXH_HAS_C_ATTRIBUTE(fallthrough) || XXH_HAS_CPP_ATTRIBUTE(fallthrough) +# define XXH_FALLTHROUGH [[fallthrough]] +#elif XXH_HAS_ATTRIBUTE(__fallthrough__) +# define XXH_FALLTHROUGH __attribute__ ((__fallthrough__)) +#else +# define XXH_FALLTHROUGH /* fallthrough */ +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +/* + * Define XXH_NOESCAPE for annotated pointers in public API. + * https://clang.llvm.org/docs/AttributeReference.html#noescape + * As of writing this, only supported by clang. + */ +#if XXH_HAS_ATTRIBUTE(noescape) +# define XXH_NOESCAPE __attribute__((__noescape__)) +#else +# define XXH_NOESCAPE +#endif +/*! @endcond */ + + +/*! + * @} + * @ingroup public + * @{ + */ + +#ifndef XXH_NO_LONG_LONG +/*-********************************************************************** +* 64-bit hash +************************************************************************/ +#if defined(XXH_DOXYGEN) /* don't include */ +/*! + * @brief An unsigned 64-bit integer. + * + * Not necessarily defined to `uint64_t` but functionally equivalent. + */ +typedef uint64_t XXH64_hash_t; +#elif !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# ifdef _AIX +# include +# else +# include +# endif + typedef uint64_t XXH64_hash_t; +#else +# include +# if defined(__LP64__) && ULONG_MAX == 0xFFFFFFFFFFFFFFFFULL + /* LP64 ABI says uint64_t is unsigned long */ + typedef unsigned long XXH64_hash_t; +# else + /* the following type must have a width of 64-bit */ + typedef unsigned long long XXH64_hash_t; +# endif +#endif + +/*! + * @} + * + * @defgroup XXH64_family XXH64 family + * @ingroup public + * @{ + * Contains functions used in the classic 64-bit xxHash algorithm. + * + * @note + * XXH3 provides competitive speed for both 32-bit and 64-bit systems, + * and offers true 64/128 bit hash results. + * It provides better speed for systems with vector processing capabilities. + */ + +/*! + * @brief Calculates the 64-bit hash of @p input using xxHash64. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * @param seed The 64-bit seed to alter the hash's output predictably. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 64-bit xxHash64 value. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed); + +/******* Streaming *******/ +#ifndef XXH_NO_STREAM +/*! + * @brief The opaque state struct for the XXH64 streaming API. + * + * @see XXH64_state_s for details. + * @see @ref streaming_example "Streaming Example" + */ +typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */ + +/*! + * @brief Allocates an @ref XXH64_state_t. + * + * @return An allocated pointer of @ref XXH64_state_t on success. + * @return `NULL` on failure. + * + * @note Must be freed with XXH64_freeState(). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_MALLOCF XXH64_state_t* XXH64_createState(void); + +/*! + * @brief Frees an @ref XXH64_state_t. + * + * @param statePtr A pointer to an @ref XXH64_state_t allocated with @ref XXH64_createState(). + * + * @return @ref XXH_OK. + * + * @note @p statePtr must be allocated with XXH64_createState(). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); + +/*! + * @brief Copies one @ref XXH64_state_t to another. + * + * @param dst_state The state to copy to. + * @param src_state The state to copy from. + * @pre + * @p dst_state and @p src_state must not be `NULL` and must not overlap. + */ +XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t* dst_state, const XXH64_state_t* src_state); + +/*! + * @brief Resets an @ref XXH64_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note This function resets and seeds a state. Call it before @ref XXH64_update(). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH_NOESCAPE XXH64_state_t* statePtr, XXH64_hash_t seed); + +/*! + * @brief Consumes a block of @p input to an @ref XXH64_state_t. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note Call this to incrementally consume blocks of data. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH_NOESCAPE XXH64_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Returns the calculated hash value from an @ref XXH64_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated 64-bit xxHash64 value from that state. + * + * @note + * Calling XXH64_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_digest (XXH_NOESCAPE const XXH64_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ +/******* Canonical representation *******/ + +/*! + * @brief Canonical (big endian) representation of @ref XXH64_hash_t. + */ +typedef struct { unsigned char digest[sizeof(XXH64_hash_t)]; } XXH64_canonical_t; + +/*! + * @brief Converts an @ref XXH64_hash_t to a big endian @ref XXH64_canonical_t. + * + * @param dst The @ref XXH64_canonical_t pointer to be stored to. + * @param hash The @ref XXH64_hash_t to be converted. + * + * @pre + * @p dst must not be `NULL`. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t* dst, XXH64_hash_t hash); + +/*! + * @brief Converts an @ref XXH64_canonical_t to a native @ref XXH64_hash_t. + * + * @param src The @ref XXH64_canonical_t to convert. + * + * @pre + * @p src must not be `NULL`. + * + * @return The converted hash. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t* src); + +#ifndef XXH_NO_XXH3 + +/*! + * @} + * ************************************************************************ + * @defgroup XXH3_family XXH3 family + * @ingroup public + * @{ + * + * XXH3 is a more recent hash algorithm featuring: + * - Improved speed for both small and large inputs + * - True 64-bit and 128-bit outputs + * - SIMD acceleration + * - Improved 32-bit viability + * + * Speed analysis methodology is explained here: + * + * https://fastcompression.blogspot.com/2019/03/presenting-xxh3.html + * + * Compared to XXH64, expect XXH3 to run approximately + * ~2x faster on large inputs and >3x faster on small ones, + * exact differences vary depending on platform. + * + * XXH3's speed benefits greatly from SIMD and 64-bit arithmetic, + * but does not require it. + * Most 32-bit and 64-bit targets that can run XXH32 smoothly can run XXH3 + * at competitive speeds, even without vector support. Further details are + * explained in the implementation. + * + * XXH3 has a fast scalar implementation, but it also includes accelerated SIMD + * implementations for many common platforms: + * - AVX512 + * - AVX2 + * - SSE2 + * - ARM NEON + * - WebAssembly SIMD128 + * - POWER8 VSX + * - s390x ZVector + * This can be controlled via the @ref XXH_VECTOR macro, but it automatically + * selects the best version according to predefined macros. For the x86 family, an + * automatic runtime dispatcher is included separately in @ref xxh_x86dispatch.c. + * + * XXH3 implementation is portable: + * it has a generic C90 formulation that can be compiled on any platform, + * all implementations generate exactly the same hash value on all platforms. + * Starting from v0.8.0, it's also labelled "stable", meaning that + * any future version will also generate the same hash value. + * + * XXH3 offers 2 variants, _64bits and _128bits. + * + * When only 64 bits are needed, prefer invoking the _64bits variant, as it + * reduces the amount of mixing, resulting in faster speed on small inputs. + * It's also generally simpler to manipulate a scalar return type than a struct. + * + * The API supports one-shot hashing, streaming mode, and custom secrets. + */ + +/*! + * @ingroup tuning + * @brief Possible values for @ref XXH_VECTOR. + * + * Unless set explicitly, determined automatically. + */ +# define XXH_SCALAR 0 /*!< Portable scalar version */ +# define XXH_SSE2 1 /*!< SSE2 for Pentium 4, Opteron, all x86_64. */ +# define XXH_AVX2 2 /*!< AVX2 for Haswell and Bulldozer */ +# define XXH_AVX512 3 /*!< AVX512 for Skylake and Icelake */ +# define XXH_NEON 4 /*!< NEON for most ARMv7-A, all AArch64, and WASM SIMD128 */ +# define XXH_VSX 5 /*!< VSX and ZVector for POWER8/z13 (64-bit) */ +# define XXH_SVE 6 /*!< SVE for some ARMv8-A and ARMv9-A */ +# define XXH_LSX 7 /*!< LSX (128-bit SIMD) for LoongArch64 */ +# define XXH_LASX 8 /*!< LASX (256-bit SIMD) for LoongArch64 */ +# define XXH_RVV 9 /*!< RVV (RISC-V Vector) for RISC-V */ + +/*-********************************************************************** +* XXH3 64-bit variant +************************************************************************/ + +/*! + * @brief Calculates 64-bit unseeded variant of XXH3 hash of @p input. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 64-bit XXH3 hash value. + * + * @note + * This is equivalent to @ref XXH3_64bits_withSeed() with a seed of `0`, however + * it may have slightly better performance due to constant propagation of the + * defaults. + * + * @see + * XXH3_64bits_withSeed(), XXH3_64bits_withSecret(): other seeding variants + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Calculates 64-bit seeded variant of XXH3 hash of @p input. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 64-bit XXH3 hash value. + * + * @note + * seed == 0 produces the same results as @ref XXH3_64bits(). + * + * This variant generates a custom secret on the fly based on default secret + * altered using the @p seed value. + * + * While this operation is decently fast, note that it's not completely free. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSeed(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed); + +/*! + * The bare minimum size for a custom secret. + * + * @see + * XXH3_64bits_withSecret(), XXH3_64bits_reset_withSecret(), + * XXH3_128bits_withSecret(), XXH3_128bits_reset_withSecret(). + */ +#define XXH3_SECRET_SIZE_MIN 136 + +/*! + * @brief Calculates 64-bit variant of XXH3 with a custom "secret". + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @return The calculated 64-bit XXH3 hash value. + * + * @pre + * The memory between @p data and @p data + @p len must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p data may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * It's possible to provide any blob of bytes as a "secret" to generate the hash. + * This makes it more difficult for an external actor to prepare an intentional collision. + * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN). + * However, the quality of the secret impacts the dispersion of the hash algorithm. + * Therefore, the secret _must_ look like a bunch of random bytes. + * Avoid "trivial" or structured data such as repeated sequences or a text document. + * Whenever in doubt about the "randomness" of the blob of bytes, + * consider employing @ref XXH3_generateSecret() instead (see below). + * It will generate a proper high entropy secret derived from the blob of bytes. + * Another advantage of using XXH3_generateSecret() is that + * it guarantees that all bits within the initial blob of bytes + * will impact every bit of the output. + * This is not necessarily the case when using the blob of bytes directly + * because, when hashing _small_ inputs, only a portion of the secret is employed. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSecret(XXH_NOESCAPE const void* data, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize); + + +/******* Streaming *******/ +#ifndef XXH_NO_STREAM +/* + * Streaming requires state maintenance. + * This operation costs memory and CPU. + * As a consequence, streaming is slower than one-shot hashing. + * For better performance, prefer one-shot functions whenever applicable. + */ + +/*! + * @brief The opaque state struct for the XXH3 streaming API. + * + * @see XXH3_state_s for details. + * @see @ref streaming_example "Streaming Example" + */ +typedef struct XXH3_state_s XXH3_state_t; +XXH_PUBLIC_API XXH_MALLOCF XXH3_state_t* XXH3_createState(void); +XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr); + +/*! + * @brief Copies one @ref XXH3_state_t to another. + * + * @param dst_state The state to copy to. + * @param src_state The state to copy from. + * @pre + * @p dst_state and @p src_state must not be `NULL` and must not overlap. + */ +XXH_PUBLIC_API void XXH3_copyState(XXH_NOESCAPE XXH3_state_t* dst_state, XXH_NOESCAPE const XXH3_state_t* src_state); + +/*! + * @brief Resets an @ref XXH3_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret with default parameters. + * - Call this function before @ref XXH3_64bits_update(). + * - Digest will be equivalent to `XXH3_64bits()`. + * + * @see @ref streaming_example "Streaming Example" + * + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr); + +/*! + * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret from `seed`. + * - Call this function before @ref XXH3_64bits_update(). + * - Digest will be equivalent to `XXH3_64bits_withSeed()`. + * + * @see @ref streaming_example "Streaming Example" + * + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed); + +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * `secret` is referenced, it _must outlive_ the hash streaming session. + * + * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN, + * and the quality of produced hash values depends on secret's entropy + * (secret's content should look like a bunch of random bytes). + * When in doubt about the randomness of a candidate `secret`, + * consider employing `XXH3_generateSecret()` instead (see below). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize); + +/*! + * @brief Consumes a block of @p input to an @ref XXH3_state_t. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note Call this to incrementally consume blocks of data. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update (XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Returns the calculated XXH3 64-bit hash value from an @ref XXH3_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated XXH3 64-bit hash value from that state. + * + * @note + * Calling XXH3_64bits_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_digest (XXH_NOESCAPE const XXH3_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ + +/* note : canonical representation of XXH3 is the same as XXH64 + * since they both produce XXH64_hash_t values */ + + +/*-********************************************************************** +* XXH3 128-bit variant +************************************************************************/ + +/*! + * @brief The return value from 128-bit hashes. + * + * Stored in little endian order, although the fields themselves are in native + * endianness. + */ +typedef struct { + XXH64_hash_t low64; /*!< `value & 0xFFFFFFFFFFFFFFFF` */ + XXH64_hash_t high64; /*!< `value >> 64` */ +} XXH128_hash_t; + +/*! + * @brief Calculates 128-bit unseeded variant of XXH3 of @p data. + * + * @param data The block of data to be hashed, at least @p length bytes in size. + * @param len The length of @p data, in bytes. + * + * @return The calculated 128-bit variant of XXH3 value. + * + * The 128-bit variant of XXH3 has more strength, but it has a bit of overhead + * for shorter inputs. + * + * This is equivalent to @ref XXH3_128bits_withSeed() with a seed of `0`, however + * it may have slightly better performance due to constant propagation of the + * defaults. + * + * @see XXH3_128bits_withSeed(), XXH3_128bits_withSecret(): other seeding variants + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void* data, size_t len); +/*! @brief Calculates 128-bit seeded variant of XXH3 hash of @p data. + * + * @param data The block of data to be hashed, at least @p length bytes in size. + * @param len The length of @p data, in bytes. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @return The calculated 128-bit variant of XXH3 value. + * + * @note + * seed == 0 produces the same results as @ref XXH3_64bits(). + * + * This variant generates a custom secret on the fly based on default secret + * altered using the @p seed value. + * + * While this operation is decently fast, note that it's not completely free. + * + * @see XXH3_128bits(), XXH3_128bits_withSecret(): other seeding variants + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSeed(XXH_NOESCAPE const void* data, size_t len, XXH64_hash_t seed); +/*! + * @brief Calculates 128-bit variant of XXH3 with a custom "secret". + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @return The calculated 128-bit variant of XXH3 value. + * + * It's possible to provide any blob of bytes as a "secret" to generate the hash. + * This makes it more difficult for an external actor to prepare an intentional collision. + * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN). + * However, the quality of the secret impacts the dispersion of the hash algorithm. + * Therefore, the secret _must_ look like a bunch of random bytes. + * Avoid "trivial" or structured data such as repeated sequences or a text document. + * Whenever in doubt about the "randomness" of the blob of bytes, + * consider employing @ref XXH3_generateSecret() instead (see below). + * It will generate a proper high entropy secret derived from the blob of bytes. + * Another advantage of using XXH3_generateSecret() is that + * it guarantees that all bits within the initial blob of bytes + * will impact every bit of the output. + * This is not necessarily the case when using the blob of bytes directly + * because, when hashing _small_ inputs, only a portion of the secret is employed. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSecret(XXH_NOESCAPE const void* data, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize); + +/******* Streaming *******/ +#ifndef XXH_NO_STREAM +/* + * Streaming requires state maintenance. + * This operation costs memory and CPU. + * As a consequence, streaming is slower than one-shot hashing. + * For better performance, prefer one-shot functions whenever applicable. + * + * XXH3_128bits uses the same XXH3_state_t as XXH3_64bits(). + * Use already declared XXH3_createState() and XXH3_freeState(). + * + * All reset and streaming functions have same meaning as their 64-bit counterpart. + */ + +/*! + * @brief Resets an @ref XXH3_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret with default parameters. + * - Call it before @ref XXH3_128bits_update(). + * - Digest will be equivalent to `XXH3_128bits()`. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr); + +/*! + * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret from `seed`. + * - Call it before @ref XXH3_128bits_update(). + * - Digest will be equivalent to `XXH3_128bits_withSeed()`. + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed); +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * `secret` is referenced, it _must outlive_ the hash streaming session. + * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN, + * and the quality of produced hash values depends on secret's entropy + * (secret's content should look like a bunch of random bytes). + * When in doubt about the randomness of a candidate `secret`, + * consider employing `XXH3_generateSecret()` instead (see below). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize); + +/*! + * @brief Consumes a block of @p input to an @ref XXH3_state_t. + * + * Call this to incrementally consume blocks of data. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update (XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Returns the calculated XXH3 128-bit hash value from an @ref XXH3_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated XXH3 128-bit hash value from that state. + * + * @note + * Calling XXH3_128bits_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + * + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_digest (XXH_NOESCAPE const XXH3_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ + +/* Following helper functions make it possible to compare XXH128_hast_t values. + * Since XXH128_hash_t is a structure, this capability is not offered by the language. + * Note: For better performance, these functions can be inlined using XXH_INLINE_ALL */ + +/*! + * @brief Check equality of two XXH128_hash_t values + * + * @param h1 The 128-bit hash value. + * @param h2 Another 128-bit hash value. + * + * @return `1` if `h1` and `h2` are equal. + * @return `0` if they are not. + */ +XXH_PUBLIC_API XXH_PUREF int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2); + +/*! + * @brief Compares two @ref XXH128_hash_t + * + * This comparator is compatible with stdlib's `qsort()`/`bsearch()`. + * + * @param h128_1 Left-hand side value + * @param h128_2 Right-hand side value + * + * @return >0 if @p h128_1 > @p h128_2 + * @return =0 if @p h128_1 == @p h128_2 + * @return <0 if @p h128_1 < @p h128_2 + */ +XXH_PUBLIC_API XXH_PUREF int XXH128_cmp(XXH_NOESCAPE const void* h128_1, XXH_NOESCAPE const void* h128_2); + + +/******* Canonical representation *******/ +typedef struct { unsigned char digest[sizeof(XXH128_hash_t)]; } XXH128_canonical_t; + + +/*! + * @brief Converts an @ref XXH128_hash_t to a big endian @ref XXH128_canonical_t. + * + * @param dst The @ref XXH128_canonical_t pointer to be stored to. + * @param hash The @ref XXH128_hash_t to be converted. + * + * @pre + * @p dst must not be `NULL`. + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t* dst, XXH128_hash_t hash); + +/*! + * @brief Converts an @ref XXH128_canonical_t to a native @ref XXH128_hash_t. + * + * @param src The @ref XXH128_canonical_t to convert. + * + * @pre + * @p src must not be `NULL`. + * + * @return The converted hash. + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t* src); + + +#endif /* !XXH_NO_XXH3 */ +#endif /* XXH_NO_LONG_LONG */ + +/*! + * @} + */ +#endif /* XXHASH_H_5627135585666179 */ + + + +#if defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742) +#define XXHASH_H_STATIC_13879238742 +/* **************************************************************************** + * This section contains declarations which are not guaranteed to remain stable. + * They may change in future versions, becoming incompatible with a different + * version of the library. + * These declarations should only be used with static linking. + * Never use them in association with dynamic linking! + ***************************************************************************** */ + +/* + * These definitions are only present to allow static allocation + * of XXH states, on stack or in a struct, for example. + * Never **ever** access their members directly. + */ + +/*! + * @internal + * @brief Structure for XXH32 streaming API. + * + * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY, + * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is + * an opaque type. This allows fields to safely be changed. + * + * Typedef'd to @ref XXH32_state_t. + * Do not access the members of this struct directly. + * @see XXH64_state_s, XXH3_state_s + */ +struct XXH32_state_s { + XXH32_hash_t total_len_32; /*!< Total length hashed, modulo 2^32 */ + XXH32_hash_t large_len; /*!< Whether the hash is >= 16 (handles @ref total_len_32 overflow) */ + XXH32_hash_t acc[4]; /*!< Accumulator lanes */ + unsigned char buffer[16]; /*!< Internal buffer for partial reads. */ + XXH32_hash_t bufferedSize; /*!< Amount of data in @ref buffer */ + XXH32_hash_t reserved; /*!< Reserved field. Do not read nor write to it. */ +}; /* typedef'd to XXH32_state_t */ + + +#ifndef XXH_NO_LONG_LONG /* defined when there is no 64-bit support */ + +/*! + * @internal + * @brief Structure for XXH64 streaming API. + * + * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY, + * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is + * an opaque type. This allows fields to safely be changed. + * + * Typedef'd to @ref XXH64_state_t. + * Do not access the members of this struct directly. + * @see XXH32_state_s, XXH3_state_s + */ +struct XXH64_state_s { + XXH64_hash_t total_len; /*!< Total length hashed. This is always 64-bit. */ + XXH64_hash_t acc[4]; /*!< Accumulator lanes */ + unsigned char buffer[32]; /*!< Internal buffer for partial reads.. */ + XXH32_hash_t bufferedSize; /*!< Amount of data in @ref buffer */ + XXH32_hash_t reserved32; /*!< Reserved field, needed for padding anyways*/ + XXH64_hash_t reserved64; /*!< Reserved field. Do not read or write to it. */ +}; /* typedef'd to XXH64_state_t */ + +#ifndef XXH_NO_XXH3 + +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* >= C11 */ +# define XXH_ALIGN(n) _Alignas(n) +#elif defined(__cplusplus) && (__cplusplus >= 201103L) /* >= C++11 */ +/* In C++ alignas() is a keyword */ +# define XXH_ALIGN(n) alignas(n) +#elif defined(__GNUC__) +# define XXH_ALIGN(n) __attribute__ ((aligned(n))) +#elif defined(_MSC_VER) +# define XXH_ALIGN(n) __declspec(align(n)) +#else +# define XXH_ALIGN(n) /* disabled */ +#endif + +/* Old GCC versions only accept the attribute after the type in structures. */ +#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) /* C11+ */ \ + && ! (defined(__cplusplus) && (__cplusplus >= 201103L)) /* >= C++11 */ \ + && defined(__GNUC__) +# define XXH_ALIGN_MEMBER(align, type) type XXH_ALIGN(align) +#else +# define XXH_ALIGN_MEMBER(align, type) XXH_ALIGN(align) type +#endif + +/*! + * @internal + * @brief The size of the internal XXH3 buffer. + * + * This is the optimal update size for incremental hashing. + * + * @see XXH3_64b_update(), XXH3_128b_update(). + */ +#define XXH3_INTERNALBUFFER_SIZE 256 + +/*! + * @def XXH3_SECRET_DEFAULT_SIZE + * @brief Default Secret's size + * + * This is the size of internal XXH3_kSecret + * and is needed by XXH3_generateSecret_fromSeed(). + * + * Not to be confused with @ref XXH3_SECRET_SIZE_MIN. + */ +#define XXH3_SECRET_DEFAULT_SIZE 192 + +/*! + * @internal + * @brief Structure for XXH3 streaming API. + * + * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY, + * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. + * Otherwise it is an opaque type. + * Never use this definition in combination with dynamic library. + * This allows fields to safely be changed in the future. + * + * @note ** This structure has a strict alignment requirement of 64 bytes!! ** + * Do not allocate this with `malloc()` or `new`, + * it will not be sufficiently aligned. + * Use @ref XXH3_createState() and @ref XXH3_freeState(), or stack allocation. + * + * Typedef'd to @ref XXH3_state_t. + * Do never access the members of this struct directly. + * + * @see XXH3_INITSTATE() for stack initialization. + * @see XXH3_createState(), XXH3_freeState(). + * @see XXH32_state_s, XXH64_state_s + */ +struct XXH3_state_s { + XXH_ALIGN_MEMBER(64, XXH64_hash_t acc[8]); + /*!< The 8 accumulators. See @ref XXH32_state_s::acc and @ref XXH64_state_s::acc */ + XXH_ALIGN_MEMBER(64, unsigned char customSecret[XXH3_SECRET_DEFAULT_SIZE]); + /*!< Used to store a custom secret generated from a seed. */ + XXH_ALIGN_MEMBER(64, unsigned char buffer[XXH3_INTERNALBUFFER_SIZE]); + /*!< The internal buffer. @see XXH32_state_s::mem32 */ + XXH32_hash_t bufferedSize; + /*!< The amount of memory in @ref buffer, @see XXH32_state_s::memsize */ + XXH32_hash_t useSeed; + /*!< Reserved field. Needed for padding on 64-bit. */ + size_t nbStripesSoFar; + /*!< Number or stripes processed. */ + XXH64_hash_t totalLen; + /*!< Total length hashed. 64-bit even on 32-bit targets. */ + size_t nbStripesPerBlock; + /*!< Number of stripes per block. */ + size_t secretLimit; + /*!< Size of @ref customSecret or @ref extSecret */ + XXH64_hash_t seed; + /*!< Seed for _withSeed variants. Must be zero otherwise, @see XXH3_INITSTATE() */ + XXH64_hash_t reserved64; + /*!< Reserved field. */ + const unsigned char* extSecret; + /*!< Reference to an external secret for the _withSecret variants, NULL + * for other variants. */ + /* note: there may be some padding at the end due to alignment on 64 bytes */ +}; /* typedef'd to XXH3_state_t */ + +#undef XXH_ALIGN_MEMBER + +/*! + * @brief Initializes a stack-allocated `XXH3_state_s`. + * + * When the @ref XXH3_state_t structure is merely emplaced on stack, + * it should be initialized with XXH3_INITSTATE() or a memset() + * in case its first reset uses XXH3_NNbits_reset_withSeed(). + * This init can be omitted if the first reset uses default or _withSecret mode. + * This operation isn't necessary when the state is created with XXH3_createState(). + * Note that this doesn't prepare the state for a streaming operation, + * it's still necessary to use XXH3_NNbits_reset*() afterwards. + */ +#define XXH3_INITSTATE(XXH3_state_ptr) \ + do { \ + XXH3_state_t* tmp_xxh3_state_ptr = (XXH3_state_ptr); \ + tmp_xxh3_state_ptr->seed = 0; \ + tmp_xxh3_state_ptr->extSecret = NULL; \ + } while(0) + + +/*! + * @brief Calculates the 128-bit hash of @p data using XXH3. + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param seed The 64-bit seed to alter the hash's output predictably. + * + * @pre + * The memory between @p data and @p data + @p len must be valid, + * readable, contiguous memory. However, if @p len is `0`, @p data may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 128-bit XXH3 value. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128(XXH_NOESCAPE const void* data, size_t len, XXH64_hash_t seed); + + +/* === Experimental API === */ +/* Symbols defined below must be considered tied to a specific library version. */ + +/*! + * @brief Derive a high-entropy secret from any user-defined content, named customSeed. + * + * @param secretBuffer A writable buffer for derived high-entropy secret data. + * @param secretSize Size of secretBuffer, in bytes. Must be >= XXH3_SECRET_SIZE_MIN. + * @param customSeed A user-defined content. + * @param customSeedSize Size of customSeed, in bytes. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * The generated secret can be used in combination with `*_withSecret()` functions. + * The `_withSecret()` variants are useful to provide a higher level of protection + * than 64-bit seed, as it becomes much more difficult for an external actor to + * guess how to impact the calculation logic. + * + * The function accepts as input a custom seed of any length and any content, + * and derives from it a high-entropy secret of length @p secretSize into an + * already allocated buffer @p secretBuffer. + * + * The generated secret can then be used with any `*_withSecret()` variant. + * The functions @ref XXH3_128bits_withSecret(), @ref XXH3_64bits_withSecret(), + * @ref XXH3_128bits_reset_withSecret() and @ref XXH3_64bits_reset_withSecret() + * are part of this list. They all accept a `secret` parameter + * which must be large enough for implementation reasons (>= @ref XXH3_SECRET_SIZE_MIN) + * _and_ feature very high entropy (consist of random-looking bytes). + * These conditions can be a high bar to meet, so @ref XXH3_generateSecret() can + * be employed to ensure proper quality. + * + * @p customSeed can be anything. It can have any size, even small ones, + * and its content can be anything, even "poor entropy" sources such as a bunch + * of zeroes. The resulting `secret` will nonetheless provide all required qualities. + * + * @pre + * - @p secretSize must be >= @ref XXH3_SECRET_SIZE_MIN + * - When @p customSeedSize > 0, supplying NULL as customSeed is undefined behavior. + * + * Example code: + * @code{.c} + * #include + * #include + * #include + * #define XXH_STATIC_LINKING_ONLY // expose unstable API + * #include "xxhash.h" + * // Hashes argv[2] using the entropy from argv[1]. + * int main(int argc, char* argv[]) + * { + * char secret[XXH3_SECRET_SIZE_MIN]; + * if (argv != 3) { return 1; } + * XXH3_generateSecret(secret, sizeof(secret), argv[1], strlen(argv[1])); + * XXH64_hash_t h = XXH3_64bits_withSecret( + * argv[2], strlen(argv[2]), + * secret, sizeof(secret) + * ); + * printf("%016llx\n", (unsigned long long) h); + * } + * @endcode + */ +XXH_PUBLIC_API XXH_errorcode XXH3_generateSecret(XXH_NOESCAPE void* secretBuffer, size_t secretSize, XXH_NOESCAPE const void* customSeed, size_t customSeedSize); + +/*! + * @brief Generate the same secret as the _withSeed() variants. + * + * @param secretBuffer A writable buffer of @ref XXH3_SECRET_DEFAULT_SIZE bytes + * @param seed The 64-bit seed to alter the hash result predictably. + * + * The generated secret can be used in combination with + *`*_withSecret()` and `_withSecretandSeed()` variants. + * + * Example C++ `std::string` hash class: + * @code{.cpp} + * #include + * #define XXH_STATIC_LINKING_ONLY // expose unstable API + * #include "xxhash.h" + * // Slow, seeds each time + * class HashSlow { + * XXH64_hash_t seed; + * public: + * HashSlow(XXH64_hash_t s) : seed{s} {} + * size_t operator()(const std::string& x) const { + * return size_t{XXH3_64bits_withSeed(x.c_str(), x.length(), seed)}; + * } + * }; + * // Fast, caches the seeded secret for future uses. + * class HashFast { + * unsigned char secret[XXH3_SECRET_DEFAULT_SIZE]; + * public: + * HashFast(XXH64_hash_t s) { + * XXH3_generateSecret_fromSeed(secret, seed); + * } + * size_t operator()(const std::string& x) const { + * return size_t{ + * XXH3_64bits_withSecret(x.c_str(), x.length(), secret, sizeof(secret)) + * }; + * } + * }; + * @endcode + */ +XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed); + +/*! + * @brief Maximum size of "short" key in bytes. + */ +#define XXH3_MIDSIZE_MAX 240 + +/*! + * @brief Calculates 64/128-bit seeded variant of XXH3 hash of @p data. + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * These variants generate hash values using either: + * - @p seed for "short" keys (< @ref XXH3_MIDSIZE_MAX = 240 bytes) + * - @p secret for "large" keys (>= @ref XXH3_MIDSIZE_MAX). + * + * This generally benefits speed, compared to `_withSeed()` or `_withSecret()`. + * `_withSeed()` has to generate the secret on the fly for "large" keys. + * It's fast, but can be perceptible for "not so large" keys (< 1 KB). + * `_withSecret()` has to generate the masks on the fly for "small" keys, + * which requires more instructions than _withSeed() variants. + * Therefore, _withSecretandSeed variant combines the best of both worlds. + * + * When @p secret has been generated by XXH3_generateSecret_fromSeed(), + * this variant produces *exactly* the same results as `_withSeed()` variant, + * hence offering only a pure speed benefit on "large" input, + * by skipping the need to regenerate the secret for every large input. + * + * Another usage scenario is to hash the secret to a 64-bit hash value, + * for example with XXH3_64bits(), which then becomes the seed, + * and then employ both the seed and the secret in _withSecretandSeed(). + * On top of speed, an added benefit is that each bit in the secret + * has a 50% chance to swap each bit in the output, via its impact to the seed. + * + * This is not guaranteed when using the secret directly in "small data" scenarios, + * because only portions of the secret are employed for small data. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t +XXH3_64bits_withSecretandSeed(XXH_NOESCAPE const void* data, size_t len, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed); + +/*! + * @brief Calculates 128-bit seeded variant of XXH3 hash of @p data. + * + * @param input The memory segment to be hashed, at least @p len bytes in size. + * @param length The length of @p data, in bytes. + * @param secret The secret used to alter hash result predictably. + * @param secretSize The length of @p secret, in bytes (must be >= XXH3_SECRET_SIZE_MIN) + * @param seed64 The 64-bit seed to alter the hash result predictably. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @see XXH3_64bits_withSecretandSeed(): contract is the same. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t +XXH3_128bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t length, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed64); + +#ifndef XXH_NO_STREAM +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState(). + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * @param seed64 The 64-bit seed to alter the hash result predictably. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @see XXH3_64bits_withSecretandSeed(). Contract is identical. + */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed64); + +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState(). + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * @param seed64 The 64-bit seed to alter the hash result predictably. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @see XXH3_64bits_withSecretandSeed(). Contract is identical. + * + * Note: there was a bug in an earlier version of this function (<= v0.8.2) + * that would make it generate an incorrect hash value + * when @p seed == 0 and @p length < XXH3_MIDSIZE_MAX + * and @p secret is different from XXH3_generateSecret_fromSeed(). + * As stated in the contract, the correct hash result must be + * the same as XXH3_128bits_withSeed() when @p length <= XXH3_MIDSIZE_MAX. + * Results generated by this older version are wrong, hence not comparable. + */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed64); + +#endif /* !XXH_NO_STREAM */ + +#endif /* !XXH_NO_XXH3 */ +#endif /* XXH_NO_LONG_LONG */ +#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) +# define XXH_IMPLEMENTATION +#endif + +#endif /* defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742) */ + + +/* ======================================================================== */ +/* ======================================================================== */ +/* ======================================================================== */ + + +/*-********************************************************************** + * xxHash implementation + *-********************************************************************** + * xxHash's implementation used to be hosted inside xxhash.c. + * + * However, inlining requires implementation to be visible to the compiler, + * hence be included alongside the header. + * Previously, implementation was hosted inside xxhash.c, + * which was then #included when inlining was activated. + * This construction created issues with a few build and install systems, + * as it required xxhash.c to be stored in /include directory. + * + * xxHash implementation is now directly integrated within xxhash.h. + * As a consequence, xxhash.c is no longer needed in /include. + * + * xxhash.c is still available and is still useful. + * In a "normal" setup, when xxhash is not inlined, + * xxhash.h only exposes the prototypes and public symbols, + * while xxhash.c can be built into an object file xxhash.o + * which can then be linked into the final binary. + ************************************************************************/ + +#if ( defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) \ + || defined(XXH_IMPLEMENTATION) ) && !defined(XXH_IMPLEM_13a8737387) +# define XXH_IMPLEM_13a8737387 + +/* ************************************* +* Tuning parameters +***************************************/ + +/*! + * @defgroup tuning Tuning parameters + * @{ + * + * Various macros to control xxHash's behavior. + */ +#ifdef XXH_DOXYGEN +/*! + * @brief Define this to disable 64-bit code. + * + * Useful if only using the @ref XXH32_family and you have a strict C90 compiler. + */ +# define XXH_NO_LONG_LONG +# undef XXH_NO_LONG_LONG /* don't actually */ +/*! + * @brief Controls how unaligned memory is accessed. + * + * By default, access to unaligned memory is controlled by `memcpy()`, which is + * safe and portable. + * + * Unfortunately, on some target/compiler combinations, the generated assembly + * is sub-optimal. + * + * The below switch allow selection of a different access method + * in the search for improved performance. + * + * @par Possible options: + * + * - `XXH_FORCE_MEMORY_ACCESS=0` (default): `memcpy` + * @par + * Use `memcpy()`. Safe and portable. Note that most modern compilers will + * eliminate the function call and treat it as an unaligned access. + * + * - `XXH_FORCE_MEMORY_ACCESS=1`: `__attribute__((aligned(1)))` + * @par + * Depends on compiler extensions and is therefore not portable. + * This method is safe _if_ your compiler supports it, + * and *generally* as fast or faster than `memcpy`. + * + * - `XXH_FORCE_MEMORY_ACCESS=2`: Direct cast + * @par + * Casts directly and dereferences. This method doesn't depend on the + * compiler, but it violates the C standard as it directly dereferences an + * unaligned pointer. It can generate buggy code on targets which do not + * support unaligned memory accesses, but in some circumstances, it's the + * only known way to get the most performance. + * + * - `XXH_FORCE_MEMORY_ACCESS=3`: Byteshift + * @par + * Also portable. This can generate the best code on old compilers which don't + * inline small `memcpy()` calls, and it might also be faster on big-endian + * systems which lack a native byteswap instruction. However, some compilers + * will emit literal byteshifts even if the target supports unaligned access. + * + * + * @warning + * Methods 1 and 2 rely on implementation-defined behavior. Use these with + * care, as what works on one compiler/platform/optimization level may cause + * another to read garbage data or even crash. + * + * See https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html for details. + * + * Prefer these methods in priority order (0 > 3 > 1 > 2) + */ +# define XXH_FORCE_MEMORY_ACCESS 0 + +/*! + * @def XXH_SIZE_OPT + * @brief Controls how much xxHash optimizes for size. + * + * xxHash, when compiled, tends to result in a rather large binary size. This + * is mostly due to heavy usage to forced inlining and constant folding of the + * @ref XXH3_family to increase performance. + * + * However, some developers prefer size over speed. This option can + * significantly reduce the size of the generated code. When using the `-Os` + * or `-Oz` options on GCC or Clang, this is defined to 1 by default, + * otherwise it is defined to 0. + * + * Most of these size optimizations can be controlled manually. + * + * This is a number from 0-2. + * - `XXH_SIZE_OPT` == 0: Default. xxHash makes no size optimizations. Speed + * comes first. + * - `XXH_SIZE_OPT` == 1: Default for `-Os` and `-Oz`. xxHash is more + * conservative and disables hacks that increase code size. It implies the + * options @ref XXH_NO_INLINE_HINTS == 1, @ref XXH_FORCE_ALIGN_CHECK == 0, + * and @ref XXH3_NEON_LANES == 8 if they are not already defined. + * - `XXH_SIZE_OPT` == 2: xxHash tries to make itself as small as possible. + * Performance may cry. For example, the single shot functions just use the + * streaming API. + */ +# define XXH_SIZE_OPT 0 + +/*! + * @def XXH_FORCE_ALIGN_CHECK + * @brief If defined to non-zero, adds a special path for aligned inputs (XXH32() + * and XXH64() only). + * + * This is an important performance trick for architectures without decent + * unaligned memory access performance. + * + * It checks for input alignment, and when conditions are met, uses a "fast + * path" employing direct 32-bit/64-bit reads, resulting in _dramatically + * faster_ read speed. + * + * The check costs one initial branch per hash, which is generally negligible, + * but not zero. + * + * Moreover, it's not useful to generate an additional code path if memory + * access uses the same instruction for both aligned and unaligned + * addresses (e.g. x86 and aarch64). + * + * In these cases, the alignment check can be removed by setting this macro to 0. + * Then the code will always use unaligned memory access. + * Align check is automatically disabled on x86, x64, ARM64, and some ARM chips + * which are platforms known to offer good unaligned memory accesses performance. + * + * It is also disabled by default when @ref XXH_SIZE_OPT >= 1. + * + * This option does not affect XXH3 (only XXH32 and XXH64). + */ +# define XXH_FORCE_ALIGN_CHECK 0 + +/*! + * @def XXH_NO_INLINE_HINTS + * @brief When non-zero, sets all functions to `static`. + * + * By default, xxHash tries to force the compiler to inline almost all internal + * functions. + * + * This can usually improve performance due to reduced jumping and improved + * constant folding, but significantly increases the size of the binary which + * might not be favorable. + * + * Additionally, sometimes the forced inlining can be detrimental to performance, + * depending on the architecture. + * + * XXH_NO_INLINE_HINTS marks all internal functions as static, giving the + * compiler full control on whether to inline or not. + * + * When not optimizing (-O0), using `-fno-inline` with GCC or Clang, or if + * @ref XXH_SIZE_OPT >= 1, this will automatically be defined. + */ +# define XXH_NO_INLINE_HINTS 0 + +/*! + * @def XXH3_INLINE_SECRET + * @brief Determines whether to inline the XXH3 withSecret code. + * + * When the secret size is known, the compiler can improve the performance + * of XXH3_64bits_withSecret() and XXH3_128bits_withSecret(). + * + * However, if the secret size is not known, it doesn't have any benefit. This + * happens when xxHash is compiled into a global symbol. Therefore, if + * @ref XXH_INLINE_ALL is *not* defined, this will be defined to 0. + * + * Additionally, this defaults to 0 on GCC 12+, which has an issue with function pointers + * that are *sometimes* force inline on -Og, and it is impossible to automatically + * detect this optimization level. + */ +# define XXH3_INLINE_SECRET 0 + +/*! + * @def XXH32_ENDJMP + * @brief Whether to use a jump for `XXH32_finalize`. + * + * For performance, `XXH32_finalize` uses multiple branches in the finalizer. + * This is generally preferable for performance, + * but depending on exact architecture, a jmp may be preferable. + * + * This setting is only possibly making a difference for very small inputs. + */ +# define XXH32_ENDJMP 0 + +/*! + * @internal + * @brief Redefines old internal names. + * + * For compatibility with code that uses xxHash's internals before the names + * were changed to improve namespacing. There is no other reason to use this. + */ +# define XXH_OLD_NAMES +# undef XXH_OLD_NAMES /* don't actually use, it is ugly. */ + +/*! + * @def XXH_NO_STREAM + * @brief Disables the streaming API. + * + * When xxHash is not inlined and the streaming functions are not used, disabling + * the streaming functions can improve code size significantly, especially with + * the @ref XXH3_family which tends to make constant folded copies of itself. + */ +# define XXH_NO_STREAM +# undef XXH_NO_STREAM /* don't actually */ +#endif /* XXH_DOXYGEN */ +/*! + * @} + */ + +#ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ + /* prefer __packed__ structures (method 1) for GCC + * < ARMv7 with unaligned access (e.g. Raspbian armhf) still uses byte shifting, so we use memcpy + * which for some reason does unaligned loads. */ +# if defined(__GNUC__) && !(defined(__ARM_ARCH) && __ARM_ARCH < 7 && defined(__ARM_FEATURE_UNALIGNED)) +# define XXH_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +#ifndef XXH_SIZE_OPT + /* default to 1 for -Os or -Oz */ +# if (defined(__GNUC__) || defined(__clang__)) && defined(__OPTIMIZE_SIZE__) +# define XXH_SIZE_OPT 1 +# else +# define XXH_SIZE_OPT 0 +# endif +#endif + +#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ + /* don't check on sizeopt, x86, aarch64, or arm when unaligned access is available */ +# if XXH_SIZE_OPT >= 1 || \ + defined(__i386) || defined(__x86_64__) || defined(__aarch64__) || defined(__ARM_FEATURE_UNALIGNED) \ + || defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM64) || defined(_M_ARM) /* visual */ +# define XXH_FORCE_ALIGN_CHECK 0 +# else +# define XXH_FORCE_ALIGN_CHECK 1 +# endif +#endif + +#ifndef XXH_NO_INLINE_HINTS +# if XXH_SIZE_OPT >= 1 || defined(__NO_INLINE__) /* -O0, -fno-inline */ +# define XXH_NO_INLINE_HINTS 1 +# else +# define XXH_NO_INLINE_HINTS 0 +# endif +#endif + +#ifndef XXH3_INLINE_SECRET +# if (defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 12) \ + || !defined(XXH_INLINE_ALL) +# define XXH3_INLINE_SECRET 0 +# else +# define XXH3_INLINE_SECRET 1 +# endif +#endif + +#ifndef XXH32_ENDJMP +/* generally preferable for performance */ +# define XXH32_ENDJMP 0 +#endif + +/*! + * @defgroup impl Implementation + * @{ + */ + + +/* ************************************* +* Includes & Memory related functions +***************************************/ +#if defined(XXH_NO_STREAM) +/* nothing */ +#elif defined(XXH_NO_STDLIB) + +/* When requesting to disable any mention of stdlib, + * the library loses the ability to invoked malloc / free. + * In practice, it means that functions like `XXH*_createState()` + * will always fail, and return NULL. + * This flag is useful in situations where + * xxhash.h is integrated into some kernel, embedded or limited environment + * without access to dynamic allocation. + */ + +static XXH_CONSTF void* XXH_malloc(size_t s) { (void)s; return NULL; } +static void XXH_free(void* p) { (void)p; } + +#else + +/* + * Modify the local functions below should you wish to use + * different memory routines for malloc() and free() + */ +#include + +/*! + * @internal + * @brief Modify this function to use a different routine than malloc(). + */ +static XXH_MALLOCF void* XXH_malloc(size_t s) { return malloc(s); } + +/*! + * @internal + * @brief Modify this function to use a different routine than free(). + */ +static void XXH_free(void* p) { free(p); } + +#endif /* XXH_NO_STDLIB */ + +#ifndef XXH_memcpy +/*! + * @internal + * @brief XXH_memcpy() macro can be redirected at compile time + */ +# include +# define XXH_memcpy memcpy +#endif + +#ifndef XXH_memset +/*! + * @internal + * @brief XXH_memset() macro can be redirected at compile time + */ +# include +# define XXH_memset memset +#endif + +#ifndef XXH_memcmp +/*! + * @internal + * @brief XXH_memcmp() macro can be redirected at compile time + * Note: only needed by XXH128. + */ +# include +# define XXH_memcmp memcmp +#endif + + + +#include /* ULLONG_MAX */ + + +/* ************************************* +* Compiler Specific Options +***************************************/ +#ifdef _MSC_VER /* Visual Studio warning fix */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +#endif + +#if XXH_NO_INLINE_HINTS /* disable inlining hints */ +# if defined(__GNUC__) || defined(__clang__) +# define XXH_FORCE_INLINE static __attribute__((__unused__)) +# else +# define XXH_FORCE_INLINE static +# endif +# define XXH_NO_INLINE static +/* enable inlining hints */ +#elif defined(__GNUC__) || defined(__clang__) +# define XXH_FORCE_INLINE static __inline__ __attribute__((__always_inline__, __unused__)) +# define XXH_NO_INLINE static __attribute__((__noinline__)) +#elif defined(_MSC_VER) /* Visual Studio */ +# define XXH_FORCE_INLINE static __forceinline +# define XXH_NO_INLINE static __declspec(noinline) +#elif defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) /* C99 */ +# define XXH_FORCE_INLINE static inline +# define XXH_NO_INLINE static +#else +# define XXH_FORCE_INLINE static +# define XXH_NO_INLINE static +#endif + +#if defined(XXH_INLINE_ALL) +# define XXH_STATIC XXH_FORCE_INLINE +#else +# define XXH_STATIC static +#endif + +#if XXH3_INLINE_SECRET +# define XXH3_WITH_SECRET_INLINE XXH_FORCE_INLINE +#else +# define XXH3_WITH_SECRET_INLINE XXH_NO_INLINE +#endif + +#if ((defined(sun) || defined(__sun)) && __cplusplus) /* Solaris includes __STDC_VERSION__ with C++. Tested with GCC 5.5 */ +# define XXH_RESTRICT /* disable */ +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* >= C99 */ +# define XXH_RESTRICT restrict +#elif (defined (__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) \ + || (defined (__clang__)) \ + || (defined (_MSC_VER) && (_MSC_VER >= 1400)) \ + || (defined (__INTEL_COMPILER) && (__INTEL_COMPILER >= 1300)) +/* + * There are a LOT more compilers that recognize __restrict but this + * covers the major ones. + */ +# define XXH_RESTRICT __restrict +#else +# define XXH_RESTRICT /* disable */ +#endif + +/* ************************************* +* Debug +***************************************/ +/*! + * @ingroup tuning + * @def XXH_DEBUGLEVEL + * @brief Sets the debugging level. + * + * XXH_DEBUGLEVEL is expected to be defined externally, typically via the + * compiler's command line options. The value must be a number. + */ +#ifndef XXH_DEBUGLEVEL +# ifdef DEBUGLEVEL /* backwards compat */ +# define XXH_DEBUGLEVEL DEBUGLEVEL +# else +# define XXH_DEBUGLEVEL 0 +# endif +#endif + +#if (XXH_DEBUGLEVEL>=1) +# include /* note: can still be disabled with NDEBUG */ +# define XXH_ASSERT(c) assert(c) +#else +# if defined(__INTEL_COMPILER) +# define XXH_ASSERT(c) XXH_ASSUME((unsigned char) (c)) +# else +# define XXH_ASSERT(c) XXH_ASSUME(c) +# endif +#endif + +/* note: use after variable declarations */ +#ifndef XXH_STATIC_ASSERT +# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ +# define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { _Static_assert((c),m); } while(0) +# elif defined(__cplusplus) && (__cplusplus >= 201103L) /* C++11 */ +# define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { static_assert((c),m); } while(0) +# else +# define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { struct xxh_sa { char x[(c) ? 1 : -1]; }; } while(0) +# endif +# define XXH_STATIC_ASSERT(c) XXH_STATIC_ASSERT_WITH_MESSAGE((c),#c) +#endif + +/*! + * @internal + * @def XXH_COMPILER_GUARD(var) + * @brief Used to prevent unwanted optimizations for @p var. + * + * It uses an empty GCC inline assembly statement with a register constraint + * which forces @p var into a general purpose register (eg eax, ebx, ecx + * on x86) and marks it as modified. + * + * This is used in a few places to avoid unwanted autovectorization (e.g. + * XXH32_round()). All vectorization we want is explicit via intrinsics, + * and _usually_ isn't wanted elsewhere. + * + * We also use it to prevent unwanted constant folding for AArch64 in + * XXH3_initCustomSecret_scalar(). + */ +#if defined(__GNUC__) || defined(__clang__) +# define XXH_COMPILER_GUARD(var) __asm__("" : "+r" (var)) +#else +# define XXH_COMPILER_GUARD(var) ((void)0) +#endif + +/* Specifically for NEON vectors which use the "w" constraint, on + * Clang. */ +#if defined(__clang__) && defined(__ARM_ARCH) && !defined(__wasm__) +# define XXH_COMPILER_GUARD_CLANG_NEON(var) __asm__("" : "+w" (var)) +#else +# define XXH_COMPILER_GUARD_CLANG_NEON(var) ((void)0) +#endif + +/* ************************************* +* Basic Types +***************************************/ +#if !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# ifdef _AIX +# include +# else +# include +# endif + typedef uint8_t xxh_u8; +#else + typedef unsigned char xxh_u8; +#endif +typedef XXH32_hash_t xxh_u32; + +#ifdef XXH_OLD_NAMES +# warning "XXH_OLD_NAMES is planned to be removed starting v0.9. If the program depends on it, consider moving away from it by employing newer type names directly" +# define BYTE xxh_u8 +# define U8 xxh_u8 +# define U32 xxh_u32 +#endif + +/* *** Memory access *** */ + +/*! + * @internal + * @fn xxh_u32 XXH_read32(const void* ptr) + * @brief Reads an unaligned 32-bit integer from @p ptr in native endianness. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * + * @param ptr The pointer to read from. + * @return The 32-bit native endian integer from the bytes at @p ptr. + */ + +/*! + * @internal + * @fn xxh_u32 XXH_readLE32(const void* ptr) + * @brief Reads an unaligned 32-bit little endian integer from @p ptr. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * + * @param ptr The pointer to read from. + * @return The 32-bit little endian integer from the bytes at @p ptr. + */ + +/*! + * @internal + * @fn xxh_u32 XXH_readBE32(const void* ptr) + * @brief Reads an unaligned 32-bit big endian integer from @p ptr. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * + * @param ptr The pointer to read from. + * @return The 32-bit big endian integer from the bytes at @p ptr. + */ + +/*! + * @internal + * @fn xxh_u32 XXH_readLE32_align(const void* ptr, XXH_alignment align) + * @brief Like @ref XXH_readLE32(), but has an option for aligned reads. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * Note that when @ref XXH_FORCE_ALIGN_CHECK == 0, the @p align parameter is + * always @ref XXH_alignment::XXH_unaligned. + * + * @param ptr The pointer to read from. + * @param align Whether @p ptr is aligned. + * @pre + * If @p align == @ref XXH_alignment::XXH_aligned, @p ptr must be 4 byte + * aligned. + * @return The 32-bit little endian integer from the bytes at @p ptr. + */ + +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) +/* + * Manual byteshift. Best for old compilers which don't inline memcpy. + * We actually directly use XXH_readLE32 and XXH_readBE32. + */ +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) + +/* + * Force direct memory access. Only works on CPU which support unaligned memory + * access in hardware. + */ +static xxh_u32 XXH_read32(const void* memPtr) { return *(const xxh_u32*) memPtr; } + +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) + +/* + * __attribute__((aligned(1))) is supported by gcc and clang. Originally the + * documentation claimed that it only increased the alignment, but actually it + * can decrease it on gcc, clang, and icc: + * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502, + * https://gcc.godbolt.org/z/xYez1j67Y. + */ +#ifdef XXH_OLD_NAMES +typedef union { xxh_u32 u32; } __attribute__((__packed__)) unalign; +#endif +static xxh_u32 XXH_read32(const void* ptr) +{ + typedef __attribute__((__aligned__(1))) __attribute__((__may_alias__)) xxh_u32 xxh_unalign32; + return *((const xxh_unalign32*)ptr); +} + +#else + +/* + * Portable and safe solution. Generally efficient. + * see: https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html + */ +static xxh_u32 XXH_read32(const void* memPtr) +{ + xxh_u32 val; + XXH_memcpy(&val, memPtr, sizeof(val)); + return val; +} + +#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ + + +/* *** Endianness *** */ + +/*! + * @ingroup tuning + * @def XXH_CPU_LITTLE_ENDIAN + * @brief Whether the target is little endian. + * + * Defined to 1 if the target is little endian, or 0 if it is big endian. + * It can be defined externally, for example on the compiler command line. + * + * If it is not defined, + * a runtime check (which is usually constant folded) is used instead. + * + * @note + * This is not necessarily defined to an integer constant. + * + * @see XXH_isLittleEndian() for the runtime check. + */ +#ifndef XXH_CPU_LITTLE_ENDIAN +/* + * Try to detect endianness automatically, to avoid the nonstandard behavior + * in `XXH_isLittleEndian()` + */ +# if defined(_WIN32) /* Windows is always little endian */ \ + || defined(__LITTLE_ENDIAN__) \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +# define XXH_CPU_LITTLE_ENDIAN 1 +# elif defined(__BIG_ENDIAN__) \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +# define XXH_CPU_LITTLE_ENDIAN 0 +# else +/*! + * @internal + * @brief Runtime check for @ref XXH_CPU_LITTLE_ENDIAN. + * + * Most compilers will constant fold this. + */ +static int XXH_isLittleEndian(void) +{ + /* + * Portable and well-defined behavior. + * Don't use static: it is detrimental to performance. + */ + const union { xxh_u32 u; xxh_u8 c[4]; } one = { 1 }; + return one.c[0]; +} +# define XXH_CPU_LITTLE_ENDIAN XXH_isLittleEndian() +# endif +#endif + + + + +/* **************************************** +* Compiler-specific Functions and Macros +******************************************/ +#define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) + +#ifdef __has_builtin +# define XXH_HAS_BUILTIN(x) __has_builtin(x) +#else +# define XXH_HAS_BUILTIN(x) 0 +#endif + + + +/* + * C23 and future versions have standard "unreachable()". + * Once it has been implemented reliably we can add it as an + * additional case: + * + * ``` + * #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L) + * # include + * # ifdef unreachable + * # define XXH_UNREACHABLE() unreachable() + * # endif + * #endif + * ``` + * + * Note C++23 also has std::unreachable() which can be detected + * as follows: + * ``` + * #if defined(__cpp_lib_unreachable) && (__cpp_lib_unreachable >= 202202L) + * # include + * # define XXH_UNREACHABLE() std::unreachable() + * #endif + * ``` + * NB: `__cpp_lib_unreachable` is defined in the `` header. + * We don't use that as including `` in `extern "C"` blocks + * doesn't work on GCC12 + */ + +#if XXH_HAS_BUILTIN(__builtin_unreachable) +# define XXH_UNREACHABLE() __builtin_unreachable() + +#elif defined(_MSC_VER) +# define XXH_UNREACHABLE() __assume(0) + +#else +# define XXH_UNREACHABLE() +#endif + +#if XXH_HAS_BUILTIN(__builtin_assume) +# define XXH_ASSUME(c) __builtin_assume(c) +#else +# define XXH_ASSUME(c) if (!(c)) { XXH_UNREACHABLE(); } +#endif + +/*! + * @internal + * @def XXH_rotl32(x,r) + * @brief 32-bit rotate left. + * + * @param x The 32-bit integer to be rotated. + * @param r The number of bits to rotate. + * @pre + * @p r > 0 && @p r < 32 + * @note + * @p x and @p r may be evaluated multiple times. + * @return The rotated result. + */ +#if !defined(NO_CLANG_BUILTIN) && XXH_HAS_BUILTIN(__builtin_rotateleft32) \ + && XXH_HAS_BUILTIN(__builtin_rotateleft64) +# define XXH_rotl32 __builtin_rotateleft32 +# define XXH_rotl64 __builtin_rotateleft64 +#elif XXH_HAS_BUILTIN(__builtin_stdc_rotate_left) +# define XXH_rotl32 __builtin_stdc_rotate_left +# define XXH_rotl64 __builtin_stdc_rotate_left +/* Note: although _rotl exists for minGW (GCC under windows), performance seems poor */ +#elif defined(_MSC_VER) +# define XXH_rotl32(x,r) _rotl(x,r) +# define XXH_rotl64(x,r) _rotl64(x,r) +#else +# define XXH_rotl32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) +# define XXH_rotl64(x,r) (((x) << (r)) | ((x) >> (64 - (r)))) +#endif + +/*! + * @internal + * @fn xxh_u32 XXH_swap32(xxh_u32 x) + * @brief A 32-bit byteswap. + * + * @param x The 32-bit integer to byteswap. + * @return @p x, byteswapped. + */ +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap32 _byteswap_ulong +#elif XXH_GCC_VERSION >= 403 +# define XXH_swap32 __builtin_bswap32 +#else +static xxh_u32 XXH_swap32 (xxh_u32 x) +{ + return ((x << 24) & 0xff000000 ) | + ((x << 8) & 0x00ff0000 ) | + ((x >> 8) & 0x0000ff00 ) | + ((x >> 24) & 0x000000ff ); +} +#endif + + +/* *************************** +* Memory reads +*****************************/ + +/*! + * @internal + * @brief Enum to indicate whether a pointer is aligned. + */ +typedef enum { + XXH_aligned, /*!< Aligned */ + XXH_unaligned /*!< Possibly unaligned */ +} XXH_alignment; + +/* + * XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load. + * + * This is ideal for older compilers which don't inline memcpy. + */ +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) + +XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[0] + | ((xxh_u32)bytePtr[1] << 8) + | ((xxh_u32)bytePtr[2] << 16) + | ((xxh_u32)bytePtr[3] << 24); +} + +XXH_FORCE_INLINE xxh_u32 XXH_readBE32(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[3] + | ((xxh_u32)bytePtr[2] << 8) + | ((xxh_u32)bytePtr[1] << 16) + | ((xxh_u32)bytePtr[0] << 24); +} + +#else +XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); +} + +static xxh_u32 XXH_readBE32(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); +} +#endif + +XXH_FORCE_INLINE xxh_u32 +XXH_readLE32_align(const void* ptr, XXH_alignment align) +{ + if (align==XXH_unaligned) { + return XXH_readLE32(ptr); + } else { + return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u32*)ptr : XXH_swap32(*(const xxh_u32*)ptr); + } +} + + +/* ************************************* +* Misc +***************************************/ +/*! @ingroup public */ +XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; } + + +/* ******************************************************************* +* 32-bit hash functions +*********************************************************************/ +/*! + * @} + * @defgroup XXH32_impl XXH32 implementation + * @ingroup impl + * + * Details on the XXH32 implementation. + * @{ + */ + /* #define instead of static const, to be used as initializers */ +#define XXH_PRIME32_1 0x9E3779B1U /*!< 0b10011110001101110111100110110001 */ +#define XXH_PRIME32_2 0x85EBCA77U /*!< 0b10000101111010111100101001110111 */ +#define XXH_PRIME32_3 0xC2B2AE3DU /*!< 0b11000010101100101010111000111101 */ +#define XXH_PRIME32_4 0x27D4EB2FU /*!< 0b00100111110101001110101100101111 */ +#define XXH_PRIME32_5 0x165667B1U /*!< 0b00010110010101100110011110110001 */ + +#ifdef XXH_OLD_NAMES +# define PRIME32_1 XXH_PRIME32_1 +# define PRIME32_2 XXH_PRIME32_2 +# define PRIME32_3 XXH_PRIME32_3 +# define PRIME32_4 XXH_PRIME32_4 +# define PRIME32_5 XXH_PRIME32_5 +#endif + +/*! + * @internal + * @brief Normal stripe processing routine. + * + * This shuffles the bits so that any bit from @p input impacts several bits in + * @p acc. + * + * @param acc The accumulator lane. + * @param input The stripe of input to mix. + * @return The mixed accumulator lane. + */ +static xxh_u32 XXH32_round(xxh_u32 acc, xxh_u32 input) +{ + acc += input * XXH_PRIME32_2; + acc = XXH_rotl32(acc, 13); + acc *= XXH_PRIME32_1; +#if (defined(__SSE4_1__) || defined(__aarch64__) || defined(__wasm_simd128__)) && !defined(XXH_ENABLE_AUTOVECTORIZE) + /* + * UGLY HACK: + * A compiler fence is used to prevent GCC and Clang from + * autovectorizing the XXH32 loop (pragmas and attributes don't work for some + * reason) without globally disabling SSE4.1. + * + * The reason we want to avoid vectorization is because despite working on + * 4 integers at a time, there are multiple factors slowing XXH32 down on + * SSE4: + * - There's a ridiculous amount of lag from pmulld (10 cycles of latency on + * newer chips!) making it slightly slower to multiply four integers at + * once compared to four integers independently. Even when pmulld was + * fastest, Sandy/Ivy Bridge, it is still not worth it to go into SSE + * just to multiply unless doing a long operation. + * + * - Four instructions are required to rotate, + * movqda tmp, v // not required with VEX encoding + * pslld tmp, 13 // tmp <<= 13 + * psrld v, 19 // x >>= 19 + * por v, tmp // x |= tmp + * compared to one for scalar: + * roll v, 13 // reliably fast across the board + * shldl v, v, 13 // Sandy Bridge and later prefer this for some reason + * + * - Instruction level parallelism is actually more beneficial here because + * the SIMD actually serializes this operation: While v1 is rotating, v2 + * can load data, while v3 can multiply. SSE forces them to operate + * together. + * + * This is also enabled on AArch64, as Clang is *very aggressive* in vectorizing + * the loop. NEON is only faster on the A53, and with the newer cores, it is less + * than half the speed. + * + * Additionally, this is used on WASM SIMD128 because it JITs to the same + * SIMD instructions and has the same issue. + */ + XXH_COMPILER_GUARD(acc); +#endif + return acc; +} + +/*! + * @internal + * @brief Mixes all bits to finalize the hash. + * + * The final mix ensures that all input bits have a chance to impact any bit in + * the output digest, resulting in an unbiased distribution. + * + * @param hash The hash to avalanche. + * @return The avalanched hash. + */ +static xxh_u32 XXH32_avalanche(xxh_u32 hash) +{ + hash ^= hash >> 15; + hash *= XXH_PRIME32_2; + hash ^= hash >> 13; + hash *= XXH_PRIME32_3; + hash ^= hash >> 16; + return hash; +} + +#define XXH_get32bits(p) XXH_readLE32_align(p, align) + +/*! + * @internal + * @brief Sets up the initial accumulator state for XXH32(). + */ +XXH_FORCE_INLINE void +XXH32_initAccs(xxh_u32 *acc, xxh_u32 seed) +{ + XXH_ASSERT(acc != NULL); + acc[0] = seed + XXH_PRIME32_1 + XXH_PRIME32_2; + acc[1] = seed + XXH_PRIME32_2; + acc[2] = seed + 0; + acc[3] = seed - XXH_PRIME32_1; +} + +/*! + * @internal + * @brief Consumes a block of data for XXH32(). + * + * @return the end input pointer. + */ +XXH_FORCE_INLINE const xxh_u8 * +XXH32_consumeLong( + xxh_u32 *XXH_RESTRICT acc, + xxh_u8 const *XXH_RESTRICT input, + size_t len, + XXH_alignment align +) +{ + const xxh_u8* const bEnd = input + len; + const xxh_u8* const limit = bEnd - 15; + XXH_ASSERT(acc != NULL); + XXH_ASSERT(input != NULL); + XXH_ASSERT(len >= 16); + do { + acc[0] = XXH32_round(acc[0], XXH_get32bits(input)); input += 4; + acc[1] = XXH32_round(acc[1], XXH_get32bits(input)); input += 4; + acc[2] = XXH32_round(acc[2], XXH_get32bits(input)); input += 4; + acc[3] = XXH32_round(acc[3], XXH_get32bits(input)); input += 4; + } while (input < limit); + + return input; +} + +/*! + * @internal + * @brief Merges the accumulator lanes together for XXH32() + */ +XXH_FORCE_INLINE XXH_PUREF xxh_u32 +XXH32_mergeAccs(const xxh_u32 *acc) +{ + XXH_ASSERT(acc != NULL); + return XXH_rotl32(acc[0], 1) + XXH_rotl32(acc[1], 7) + + XXH_rotl32(acc[2], 12) + XXH_rotl32(acc[3], 18); +} + +/*! + * @internal + * @brief Processes the last 0-15 bytes of @p ptr. + * + * There may be up to 15 bytes remaining to consume from the input. + * This final stage will digest them to ensure that all input bytes are present + * in the final mix. + * + * @param hash The hash to finalize. + * @param ptr The pointer to the remaining input. + * @param len The remaining length, modulo 16. + * @param align Whether @p ptr is aligned. + * @return The finalized hash. + * @see XXH64_finalize(). + */ +static XXH_PUREF xxh_u32 +XXH32_finalize(xxh_u32 hash, const xxh_u8* ptr, size_t len, XXH_alignment align) +{ +#define XXH_PROCESS1 do { \ + hash += (*ptr++) * XXH_PRIME32_5; \ + hash = XXH_rotl32(hash, 11) * XXH_PRIME32_1; \ +} while (0) + +#define XXH_PROCESS4 do { \ + hash += XXH_get32bits(ptr) * XXH_PRIME32_3; \ + ptr += 4; \ + hash = XXH_rotl32(hash, 17) * XXH_PRIME32_4; \ +} while (0) + + if (ptr==NULL) XXH_ASSERT(len == 0); + + /* Compact rerolled version; generally faster */ + if (!XXH32_ENDJMP) { + len &= 15; + while (len >= 4) { + XXH_PROCESS4; + len -= 4; + } + while (len > 0) { + XXH_PROCESS1; + --len; + } + return XXH32_avalanche(hash); + } else { + switch(len&15) /* or switch(bEnd - p) */ { + case 12: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 8: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 4: XXH_PROCESS4; + return XXH32_avalanche(hash); + + case 13: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 9: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 5: XXH_PROCESS4; + XXH_PROCESS1; + return XXH32_avalanche(hash); + + case 14: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 10: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 6: XXH_PROCESS4; + XXH_PROCESS1; + XXH_PROCESS1; + return XXH32_avalanche(hash); + + case 15: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 11: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 7: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 3: XXH_PROCESS1; + XXH_FALLTHROUGH; /* fallthrough */ + case 2: XXH_PROCESS1; + XXH_FALLTHROUGH; /* fallthrough */ + case 1: XXH_PROCESS1; + XXH_FALLTHROUGH; /* fallthrough */ + case 0: return XXH32_avalanche(hash); + } + XXH_ASSERT(0); + return hash; /* reaching this point is deemed impossible */ + } +} + +#ifdef XXH_OLD_NAMES +# define PROCESS1 XXH_PROCESS1 +# define PROCESS4 XXH_PROCESS4 +#else +# undef XXH_PROCESS1 +# undef XXH_PROCESS4 +#endif + +/*! + * @internal + * @brief The implementation for @ref XXH32(). + * + * @param input , len , seed Directly passed from @ref XXH32(). + * @param align Whether @p input is aligned. + * @return The calculated hash. + */ +XXH_FORCE_INLINE XXH_PUREF xxh_u32 +XXH32_endian_align(const xxh_u8* input, size_t len, xxh_u32 seed, XXH_alignment align) +{ + xxh_u32 h32; + + if (input==NULL) XXH_ASSERT(len == 0); + + if (len>=16) { + xxh_u32 acc[4]; + XXH32_initAccs(acc, seed); + + input = XXH32_consumeLong(acc, input, len, align); + + h32 = XXH32_mergeAccs(acc); + } else { + h32 = seed + XXH_PRIME32_5; + } + + h32 += (xxh_u32)len; + + return XXH32_finalize(h32, input, len&15, align); +} + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t len, XXH32_hash_t seed) +{ +#if !defined(XXH_NO_STREAM) && XXH_SIZE_OPT >= 2 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH32_state_t state; + XXH32_reset(&state, seed); + XXH32_update(&state, (const xxh_u8*)input, len); + return XXH32_digest(&state); +#else + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ + return XXH32_endian_align((const xxh_u8*)input, len, seed, XXH_aligned); + } } + + return XXH32_endian_align((const xxh_u8*)input, len, seed, XXH_unaligned); +#endif +} + + + +/******* Hash streaming *******/ +#ifndef XXH_NO_STREAM +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) +{ + return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); +} +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState) +{ + XXH_memcpy(dstState, srcState, sizeof(*dstState)); +} + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, XXH32_hash_t seed) +{ + XXH_ASSERT(statePtr != NULL); + XXH_memset(statePtr, 0, sizeof(*statePtr)); + XXH32_initAccs(statePtr->acc, seed); + return XXH_OK; +} + + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH_errorcode +XXH32_update(XXH32_state_t* state, const void* input, size_t len) +{ + if (input==NULL) { + XXH_ASSERT(len == 0); + return XXH_OK; + } + + state->total_len_32 += (XXH32_hash_t)len; + state->large_len |= (XXH32_hash_t)((len>=16) | (state->total_len_32>=16)); + + XXH_ASSERT(state->bufferedSize < sizeof(state->buffer)); + if (len < sizeof(state->buffer) - state->bufferedSize) { /* fill in tmp buffer */ + XXH_memcpy(state->buffer + state->bufferedSize, input, len); + state->bufferedSize += (XXH32_hash_t)len; + return XXH_OK; + } + + { const xxh_u8* xinput = (const xxh_u8*)input; + const xxh_u8* const bEnd = xinput + len; + + if (state->bufferedSize) { /* non-empty buffer: complete first */ + XXH_memcpy(state->buffer + state->bufferedSize, xinput, sizeof(state->buffer) - state->bufferedSize); + xinput += sizeof(state->buffer) - state->bufferedSize; + /* then process one round */ + (void)XXH32_consumeLong(state->acc, state->buffer, sizeof(state->buffer), XXH_aligned); + state->bufferedSize = 0; + } + + XXH_ASSERT(xinput <= bEnd); + if ((size_t)(bEnd - xinput) >= sizeof(state->buffer)) { + /* Process the remaining data */ + xinput = XXH32_consumeLong(state->acc, xinput, (size_t)(bEnd - xinput), XXH_unaligned); + } + + if (xinput < bEnd) { + /* Copy the leftover to the tmp buffer */ + XXH_memcpy(state->buffer, xinput, (size_t)(bEnd-xinput)); + state->bufferedSize = (unsigned)(bEnd-xinput); + } + } + + return XXH_OK; +} + + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_hash_t XXH32_digest(const XXH32_state_t* state) +{ + xxh_u32 h32; + + if (state->large_len) { + h32 = XXH32_mergeAccs(state->acc); + } else { + h32 = state->acc[2] /* == seed */ + XXH_PRIME32_5; + } + + h32 += state->total_len_32; + + return XXH32_finalize(h32, state->buffer, state->bufferedSize, XXH_aligned); +} +#endif /* !XXH_NO_STREAM */ + +/******* Canonical representation *******/ + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); + XXH_memcpy(dst, &hash, sizeof(*dst)); +} +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) +{ + return XXH_readBE32(src); +} + + +#ifndef XXH_NO_LONG_LONG + +/* ******************************************************************* +* 64-bit hash functions +*********************************************************************/ +/*! + * @} + * @ingroup impl + * @{ + */ +/******* Memory access *******/ + +typedef XXH64_hash_t xxh_u64; + +#ifdef XXH_OLD_NAMES +# define U64 xxh_u64 +#endif + +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) +/* + * Manual byteshift. Best for old compilers which don't inline memcpy. + * We actually directly use XXH_readLE64 and XXH_readBE64. + */ +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) + +/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ +static xxh_u64 XXH_read64(const void* memPtr) +{ + return *(const xxh_u64*) memPtr; +} + +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) + +/* + * __attribute__((aligned(1))) is supported by gcc and clang. Originally the + * documentation claimed that it only increased the alignment, but actually it + * can decrease it on gcc, clang, and icc: + * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502, + * https://gcc.godbolt.org/z/xYez1j67Y. + */ +#ifdef XXH_OLD_NAMES +typedef union { xxh_u32 u32; xxh_u64 u64; } __attribute__((__packed__)) unalign64; +#endif +static xxh_u64 XXH_read64(const void* ptr) +{ + typedef __attribute__((__aligned__(1))) __attribute__((__may_alias__)) xxh_u64 xxh_unalign64; + return *((const xxh_unalign64*)ptr); +} + +#else + +/* + * Portable and safe solution. Generally efficient. + * see: https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html + */ +static xxh_u64 XXH_read64(const void* memPtr) +{ + xxh_u64 val; + XXH_memcpy(&val, memPtr, sizeof(val)); + return val; +} + +#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ + +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap64 _byteswap_uint64 +#elif XXH_GCC_VERSION >= 403 +# define XXH_swap64 __builtin_bswap64 +#else +static xxh_u64 XXH_swap64(xxh_u64 x) +{ + return ((x << 56) & 0xff00000000000000ULL) | + ((x << 40) & 0x00ff000000000000ULL) | + ((x << 24) & 0x0000ff0000000000ULL) | + ((x << 8) & 0x000000ff00000000ULL) | + ((x >> 8) & 0x00000000ff000000ULL) | + ((x >> 24) & 0x0000000000ff0000ULL) | + ((x >> 40) & 0x000000000000ff00ULL) | + ((x >> 56) & 0x00000000000000ffULL); +} +#endif + + +/* XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load. */ +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) + +XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[0] + | ((xxh_u64)bytePtr[1] << 8) + | ((xxh_u64)bytePtr[2] << 16) + | ((xxh_u64)bytePtr[3] << 24) + | ((xxh_u64)bytePtr[4] << 32) + | ((xxh_u64)bytePtr[5] << 40) + | ((xxh_u64)bytePtr[6] << 48) + | ((xxh_u64)bytePtr[7] << 56); +} + +XXH_FORCE_INLINE xxh_u64 XXH_readBE64(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[7] + | ((xxh_u64)bytePtr[6] << 8) + | ((xxh_u64)bytePtr[5] << 16) + | ((xxh_u64)bytePtr[4] << 24) + | ((xxh_u64)bytePtr[3] << 32) + | ((xxh_u64)bytePtr[2] << 40) + | ((xxh_u64)bytePtr[1] << 48) + | ((xxh_u64)bytePtr[0] << 56); +} + +#else +XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); +} + +static xxh_u64 XXH_readBE64(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); +} +#endif + +XXH_FORCE_INLINE xxh_u64 +XXH_readLE64_align(const void* ptr, XXH_alignment align) +{ + if (align==XXH_unaligned) + return XXH_readLE64(ptr); + else + return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u64*)ptr : XXH_swap64(*(const xxh_u64*)ptr); +} + + +/******* xxh64 *******/ +/*! + * @} + * @defgroup XXH64_impl XXH64 implementation + * @ingroup impl + * + * Details on the XXH64 implementation. + * @{ + */ +/* #define rather that static const, to be used as initializers */ +#define XXH_PRIME64_1 0x9E3779B185EBCA87ULL /*!< 0b1001111000110111011110011011000110000101111010111100101010000111 */ +#define XXH_PRIME64_2 0xC2B2AE3D27D4EB4FULL /*!< 0b1100001010110010101011100011110100100111110101001110101101001111 */ +#define XXH_PRIME64_3 0x165667B19E3779F9ULL /*!< 0b0001011001010110011001111011000110011110001101110111100111111001 */ +#define XXH_PRIME64_4 0x85EBCA77C2B2AE63ULL /*!< 0b1000010111101011110010100111011111000010101100101010111001100011 */ +#define XXH_PRIME64_5 0x27D4EB2F165667C5ULL /*!< 0b0010011111010100111010110010111100010110010101100110011111000101 */ + +#ifdef XXH_OLD_NAMES +# define PRIME64_1 XXH_PRIME64_1 +# define PRIME64_2 XXH_PRIME64_2 +# define PRIME64_3 XXH_PRIME64_3 +# define PRIME64_4 XXH_PRIME64_4 +# define PRIME64_5 XXH_PRIME64_5 +#endif + +/*! @copydoc XXH32_round */ +static xxh_u64 XXH64_round(xxh_u64 acc, xxh_u64 input) +{ + acc += input * XXH_PRIME64_2; + acc = XXH_rotl64(acc, 31); + acc *= XXH_PRIME64_1; +#if (defined(__AVX512F__)) && !defined(XXH_ENABLE_AUTOVECTORIZE) + /* + * DISABLE AUTOVECTORIZATION: + * A compiler fence is used to prevent GCC and Clang from + * autovectorizing the XXH64 loop (pragmas and attributes don't work for some + * reason) without globally disabling AVX512. + * + * Autovectorization of XXH64 tends to be detrimental, + * though the exact outcome may change depending on exact cpu and compiler version. + * For information, it has been reported as detrimental for Skylake-X, + * but possibly beneficial for Zen4. + * + * The default is to disable auto-vectorization, + * but you can select to enable it instead using `XXH_ENABLE_AUTOVECTORIZE` build variable. + */ + XXH_COMPILER_GUARD(acc); +#endif + return acc; +} + +static xxh_u64 XXH64_mergeRound(xxh_u64 acc, xxh_u64 val) +{ + val = XXH64_round(0, val); + acc ^= val; + acc = acc * XXH_PRIME64_1 + XXH_PRIME64_4; + return acc; +} + +/*! @copydoc XXH32_avalanche */ +static xxh_u64 XXH64_avalanche(xxh_u64 hash) +{ + hash ^= hash >> 33; + hash *= XXH_PRIME64_2; + hash ^= hash >> 29; + hash *= XXH_PRIME64_3; + hash ^= hash >> 32; + return hash; +} + + +#define XXH_get64bits(p) XXH_readLE64_align(p, align) + +/*! + * @internal + * @brief Sets up the initial accumulator state for XXH64(). + */ +XXH_FORCE_INLINE void +XXH64_initAccs(xxh_u64 *acc, xxh_u64 seed) +{ + XXH_ASSERT(acc != NULL); + acc[0] = seed + XXH_PRIME64_1 + XXH_PRIME64_2; + acc[1] = seed + XXH_PRIME64_2; + acc[2] = seed + 0; + acc[3] = seed - XXH_PRIME64_1; +} + +/*! + * @internal + * @brief Consumes a block of data for XXH64(). + * + * @return the end input pointer. + */ +XXH_FORCE_INLINE const xxh_u8 * +XXH64_consumeLong( + xxh_u64 *XXH_RESTRICT acc, + xxh_u8 const *XXH_RESTRICT input, + size_t len, + XXH_alignment align +) +{ + const xxh_u8* const bEnd = input + len; + const xxh_u8* const limit = bEnd - 31; + XXH_ASSERT(acc != NULL); + XXH_ASSERT(input != NULL); + XXH_ASSERT(len >= 32); + do { + /* reroll on 32-bit */ + if (sizeof(void *) < sizeof(xxh_u64)) { + size_t i; + for (i = 0; i < 4; i++) { + acc[i] = XXH64_round(acc[i], XXH_get64bits(input)); + input += 8; + } + } else { + acc[0] = XXH64_round(acc[0], XXH_get64bits(input)); input += 8; + acc[1] = XXH64_round(acc[1], XXH_get64bits(input)); input += 8; + acc[2] = XXH64_round(acc[2], XXH_get64bits(input)); input += 8; + acc[3] = XXH64_round(acc[3], XXH_get64bits(input)); input += 8; + } + } while (input < limit); + + return input; +} + +/*! + * @internal + * @brief Merges the accumulator lanes together for XXH64() + */ +XXH_FORCE_INLINE XXH_PUREF xxh_u64 +XXH64_mergeAccs(const xxh_u64 *acc) +{ + XXH_ASSERT(acc != NULL); + { + xxh_u64 h64 = XXH_rotl64(acc[0], 1) + XXH_rotl64(acc[1], 7) + + XXH_rotl64(acc[2], 12) + XXH_rotl64(acc[3], 18); + /* reroll on 32-bit */ + if (sizeof(void *) < sizeof(xxh_u64)) { + size_t i; + for (i = 0; i < 4; i++) { + h64 = XXH64_mergeRound(h64, acc[i]); + } + } else { + h64 = XXH64_mergeRound(h64, acc[0]); + h64 = XXH64_mergeRound(h64, acc[1]); + h64 = XXH64_mergeRound(h64, acc[2]); + h64 = XXH64_mergeRound(h64, acc[3]); + } + return h64; + } +} + +/*! + * @internal + * @brief Processes the last 0-31 bytes of @p ptr. + * + * There may be up to 31 bytes remaining to consume from the input. + * This final stage will digest them to ensure that all input bytes are present + * in the final mix. + * + * @param hash The hash to finalize. + * @param ptr The pointer to the remaining input. + * @param len The remaining length, modulo 32. + * @param align Whether @p ptr is aligned. + * @return The finalized hash + * @see XXH32_finalize(). + */ +XXH_STATIC XXH_PUREF xxh_u64 +XXH64_finalize(xxh_u64 hash, const xxh_u8* ptr, size_t len, XXH_alignment align) +{ + if (ptr==NULL) XXH_ASSERT(len == 0); + len &= 31; + while (len >= 8) { + xxh_u64 const k1 = XXH64_round(0, XXH_get64bits(ptr)); + ptr += 8; + hash ^= k1; + hash = XXH_rotl64(hash,27) * XXH_PRIME64_1 + XXH_PRIME64_4; + len -= 8; + } + if (len >= 4) { + hash ^= (xxh_u64)(XXH_get32bits(ptr)) * XXH_PRIME64_1; + ptr += 4; + hash = XXH_rotl64(hash, 23) * XXH_PRIME64_2 + XXH_PRIME64_3; + len -= 4; + } + while (len > 0) { + hash ^= (*ptr++) * XXH_PRIME64_5; + hash = XXH_rotl64(hash, 11) * XXH_PRIME64_1; + --len; + } + return XXH64_avalanche(hash); +} + +#ifdef XXH_OLD_NAMES +# define PROCESS1_64 XXH_PROCESS1_64 +# define PROCESS4_64 XXH_PROCESS4_64 +# define PROCESS8_64 XXH_PROCESS8_64 +#else +# undef XXH_PROCESS1_64 +# undef XXH_PROCESS4_64 +# undef XXH_PROCESS8_64 +#endif + +/*! + * @internal + * @brief The implementation for @ref XXH64(). + * + * @param input , len , seed Directly passed from @ref XXH64(). + * @param align Whether @p input is aligned. + * @return The calculated hash. + */ +XXH_FORCE_INLINE XXH_PUREF xxh_u64 +XXH64_endian_align(const xxh_u8* input, size_t len, xxh_u64 seed, XXH_alignment align) +{ + xxh_u64 h64; + if (input==NULL) XXH_ASSERT(len == 0); + + if (len>=32) { /* Process a large block of data */ + xxh_u64 acc[4]; + XXH64_initAccs(acc, seed); + + input = XXH64_consumeLong(acc, input, len, align); + + h64 = XXH64_mergeAccs(acc); + } else { + h64 = seed + XXH_PRIME64_5; + } + + h64 += (xxh_u64) len; + + return XXH64_finalize(h64, input, len, align); +} + + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH64_hash_t XXH64 (XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed) +{ +#if !defined(XXH_NO_STREAM) && XXH_SIZE_OPT >= 2 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH64_state_t state; + XXH64_reset(&state, seed); + XXH64_update(&state, (const xxh_u8*)input, len); + return XXH64_digest(&state); +#else + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */ + return XXH64_endian_align((const xxh_u8*)input, len, seed, XXH_aligned); + } } + + return XXH64_endian_align((const xxh_u8*)input, len, seed, XXH_unaligned); + +#endif +} + +/******* Hash Streaming *******/ +#ifndef XXH_NO_STREAM +/*! @ingroup XXH64_family*/ +XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) +{ + return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); +} +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t* dstState, const XXH64_state_t* srcState) +{ + XXH_memcpy(dstState, srcState, sizeof(*dstState)); +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH_NOESCAPE XXH64_state_t* statePtr, XXH64_hash_t seed) +{ + XXH_ASSERT(statePtr != NULL); + XXH_memset(statePtr, 0, sizeof(*statePtr)); + XXH64_initAccs(statePtr->acc, seed); + return XXH_OK; +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH_errorcode +XXH64_update (XXH_NOESCAPE XXH64_state_t* state, XXH_NOESCAPE const void* input, size_t len) +{ + if (input==NULL) { + XXH_ASSERT(len == 0); + return XXH_OK; + } + + state->total_len += len; + + XXH_ASSERT(state->bufferedSize <= sizeof(state->buffer)); + if (len < sizeof(state->buffer) - state->bufferedSize) { /* fill in tmp buffer */ + XXH_memcpy(state->buffer + state->bufferedSize, input, len); + state->bufferedSize += (XXH32_hash_t)len; + return XXH_OK; + } + + { const xxh_u8* xinput = (const xxh_u8*)input; + const xxh_u8* const bEnd = xinput + len; + + if (state->bufferedSize) { /* non-empty buffer => complete first */ + XXH_memcpy(state->buffer + state->bufferedSize, xinput, sizeof(state->buffer) - state->bufferedSize); + xinput += sizeof(state->buffer) - state->bufferedSize; + /* and process one round */ + (void)XXH64_consumeLong(state->acc, state->buffer, sizeof(state->buffer), XXH_aligned); + state->bufferedSize = 0; + } + + XXH_ASSERT(xinput <= bEnd); + if ((size_t)(bEnd - xinput) >= sizeof(state->buffer)) { + /* Process the remaining data */ + xinput = XXH64_consumeLong(state->acc, xinput, (size_t)(bEnd - xinput), XXH_unaligned); + } + + if (xinput < bEnd) { + /* Copy the leftover to the tmp buffer */ + XXH_memcpy(state->buffer, xinput, (size_t)(bEnd-xinput)); + state->bufferedSize = (unsigned)(bEnd-xinput); + } + } + + return XXH_OK; +} + + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH64_hash_t XXH64_digest(XXH_NOESCAPE const XXH64_state_t* state) +{ + xxh_u64 h64; + + if (state->total_len >= 32) { + h64 = XXH64_mergeAccs(state->acc); + } else { + h64 = state->acc[2] /*seed*/ + XXH_PRIME64_5; + } + + h64 += (xxh_u64) state->total_len; + + return XXH64_finalize(h64, state->buffer, (size_t)state->total_len, XXH_aligned); +} +#endif /* !XXH_NO_STREAM */ + +/******* Canonical representation *******/ + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t* dst, XXH64_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); + XXH_memcpy(dst, &hash, sizeof(*dst)); +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t* src) +{ + return XXH_readBE64(src); +} + +#ifndef XXH_NO_XXH3 + +/* ********************************************************************* +* XXH3 +* New generation hash designed for speed on small keys and vectorization +************************************************************************ */ +/*! + * @} + * @defgroup XXH3_impl XXH3 implementation + * @ingroup impl + * @{ + */ + +/* === Compiler specifics === */ + + +#if (defined(__GNUC__) && (__GNUC__ >= 3)) \ + || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) \ + || defined(__clang__) +# define XXH_likely(x) __builtin_expect(x, 1) +# define XXH_unlikely(x) __builtin_expect(x, 0) +#else +# define XXH_likely(x) (x) +# define XXH_unlikely(x) (x) +#endif + +#ifndef XXH_HAS_INCLUDE +# ifdef __has_include +/* + * Not defined as XXH_HAS_INCLUDE(x) (function-like) because + * this causes segfaults in Apple Clang 4.2 (on Mac OS X 10.7 Lion) + */ +# define XXH_HAS_INCLUDE __has_include +# else +# define XXH_HAS_INCLUDE(x) 0 +# endif +#endif + +#if defined(__GNUC__) || defined(__clang__) +# if defined(__ARM_FEATURE_SVE) +# include +# endif +# if defined(__ARM_NEON__) || defined(__ARM_NEON) \ + || (defined(_M_ARM) && _M_ARM >= 7) \ + || defined(_M_ARM64) || defined(_M_ARM64EC) \ + || (defined(__wasm_simd128__) && XXH_HAS_INCLUDE()) /* WASM SIMD128 via SIMDe */ +# define inline __inline__ /* circumvent a clang bug */ +# include +# undef inline +# elif defined(__AVX2__) +# include +# elif defined(__SSE2__) +# include +# elif defined(__loongarch_asx) +# include +# include +# elif defined(__loongarch_sx) +# include +# elif defined(__riscv_vector) +# include +# endif +#endif + +#if defined(_MSC_VER) +# include +#endif + +/* + * One goal of XXH3 is to make it fast on both 32-bit and 64-bit, while + * remaining a true 64-bit/128-bit hash function. + * + * This is done by prioritizing a subset of 64-bit operations that can be + * emulated without too many steps on the average 32-bit machine. + * + * For example, these two lines seem similar, and run equally fast on 64-bit: + * + * xxh_u64 x; + * x ^= (x >> 47); // good + * x ^= (x >> 13); // bad + * + * However, to a 32-bit machine, there is a major difference. + * + * x ^= (x >> 47) looks like this: + * + * x.lo ^= (x.hi >> (47 - 32)); + * + * while x ^= (x >> 13) looks like this: + * + * // note: funnel shifts are not usually cheap. + * x.lo ^= (x.lo >> 13) | (x.hi << (32 - 13)); + * x.hi ^= (x.hi >> 13); + * + * The first one is significantly faster than the second, simply because the + * shift is larger than 32. This means: + * - All the bits we need are in the upper 32 bits, so we can ignore the lower + * 32 bits in the shift. + * - The shift result will always fit in the lower 32 bits, and therefore, + * we can ignore the upper 32 bits in the xor. + * + * Thanks to this optimization, XXH3 only requires these features to be efficient: + * + * - Usable unaligned access + * - A 32-bit or 64-bit ALU + * - If 32-bit, a decent ADC instruction + * - A 32 or 64-bit multiply with a 64-bit result + * - For the 128-bit variant, a decent byteswap helps short inputs. + * + * The first two are already required by XXH32, and almost all 32-bit and 64-bit + * platforms which can run XXH32 can run XXH3 efficiently. + * + * Thumb-1, the classic 16-bit only subset of ARM's instruction set, is one + * notable exception. + * + * First of all, Thumb-1 lacks support for the UMULL instruction which + * performs the important long multiply. This means numerous __aeabi_lmul + * calls. + * + * Second of all, the 8 functional registers are just not enough. + * Setup for __aeabi_lmul, byteshift loads, pointers, and all arithmetic need + * Lo registers, and this shuffling results in thousands more MOVs than A32. + * + * A32 and T32 don't have this limitation. They can access all 14 registers, + * do a 32->64 multiply with UMULL, and the flexible operand allowing free + * shifts is helpful, too. + * + * Therefore, we do a quick sanity check. + * + * If compiling Thumb-1 for a target which supports ARM instructions, we will + * emit a warning, as it is not a "sane" platform to compile for. + * + * Usually, if this happens, it is because of an accident and you probably need + * to specify -march, as you likely meant to compile for a newer architecture. + * + * Credit: large sections of the vectorial and asm source code paths + * have been contributed by @easyaspi314 + */ +#if defined(__thumb__) && !defined(__thumb2__) && defined(__ARM_ARCH_ISA_ARM) +# warning "XXH3 is highly inefficient without ARM or Thumb-2." +#endif + +/* ========================================== + * Vectorization detection + * ========================================== */ + +#ifdef XXH_DOXYGEN +/*! + * @ingroup tuning + * @brief Overrides the vectorization implementation chosen for XXH3. + * + * Can be defined to 0 to disable SIMD, + * or any other authorized value of @ref XXH_VECTOR. + * + * If this is not defined, it uses predefined macros to determine the best + * implementation. + */ +# define XXH_VECTOR XXH_SCALAR +/*! + * @ingroup tuning + * @brief Selects the minimum alignment for XXH3's accumulators. + * + * When using SIMD, this should match the alignment required for said vector + * type, so, for example, 32 for AVX2. + * + * Default: Auto detected. + */ +# define XXH_ACC_ALIGN 8 +#endif + +/* Actual definition */ +#ifndef XXH_DOXYGEN +#endif + +#ifndef XXH_VECTOR /* can be defined on command line */ +# if ( \ + defined(__ARM_NEON__) || defined(__ARM_NEON) /* gcc */ \ + || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) /* msvc */ \ + || (defined(__wasm_simd128__) && XXH_HAS_INCLUDE()) /* wasm simd128 via SIMDe */ \ + ) && ( \ + defined(_WIN32) || defined(__LITTLE_ENDIAN__) /* little endian only */ \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) \ + ) +# define XXH_VECTOR XXH_NEON +# elif defined(__ARM_FEATURE_SVE) +# define XXH_VECTOR XXH_SVE +# elif defined(__AVX512F__) +# define XXH_VECTOR XXH_AVX512 +# elif defined(__AVX2__) +# define XXH_VECTOR XXH_AVX2 +# elif defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2)) +# define XXH_VECTOR XXH_SSE2 +# elif (defined(__PPC64__) && defined(__POWER8_VECTOR__)) \ + || (defined(__s390x__) && defined(__VEC__)) \ + && defined(__GNUC__) /* TODO: IBM XL */ +# define XXH_VECTOR XXH_VSX +# elif defined(__loongarch_asx) +# define XXH_VECTOR XXH_LASX +# elif defined(__loongarch_sx) +# define XXH_VECTOR XXH_LSX +# elif defined(__riscv_vector) +# define XXH_VECTOR XXH_RVV +# else +# define XXH_VECTOR XXH_SCALAR +# endif +#endif + +/* __ARM_FEATURE_SVE is only supported by GCC & Clang. */ +#if (XXH_VECTOR == XXH_SVE) && !defined(__ARM_FEATURE_SVE) +# ifdef _MSC_VER +# pragma warning(once : 4606) +# else +# warning "__ARM_FEATURE_SVE isn't supported. Use SCALAR instead." +# endif +# undef XXH_VECTOR +# define XXH_VECTOR XXH_SCALAR +#endif + +/* + * Controls the alignment of the accumulator, + * for compatibility with aligned vector loads, which are usually faster. + */ +#ifndef XXH_ACC_ALIGN +# if defined(XXH_X86DISPATCH) +# define XXH_ACC_ALIGN 64 /* for compatibility with avx512 */ +# elif XXH_VECTOR == XXH_SCALAR /* scalar */ +# define XXH_ACC_ALIGN 8 +# elif XXH_VECTOR == XXH_SSE2 /* sse2 */ +# define XXH_ACC_ALIGN 16 +# elif XXH_VECTOR == XXH_AVX2 /* avx2 */ +# define XXH_ACC_ALIGN 32 +# elif XXH_VECTOR == XXH_NEON /* neon */ +# define XXH_ACC_ALIGN 16 +# elif XXH_VECTOR == XXH_VSX /* vsx */ +# define XXH_ACC_ALIGN 16 +# elif XXH_VECTOR == XXH_AVX512 /* avx512 */ +# define XXH_ACC_ALIGN 64 +# elif XXH_VECTOR == XXH_SVE /* sve */ +# define XXH_ACC_ALIGN 64 +# elif XXH_VECTOR == XXH_LASX /* lasx */ +# define XXH_ACC_ALIGN 64 +# elif XXH_VECTOR == XXH_LSX /* lsx */ +# define XXH_ACC_ALIGN 64 +# elif XXH_VECTOR == XXH_RVV /* rvv */ +# define XXH_ACC_ALIGN 64 +# endif +#endif + +#if defined(XXH_X86DISPATCH) || XXH_VECTOR == XXH_SSE2 \ + || XXH_VECTOR == XXH_AVX2 || XXH_VECTOR == XXH_AVX512 +# define XXH_SEC_ALIGN XXH_ACC_ALIGN +#elif XXH_VECTOR == XXH_SVE +# define XXH_SEC_ALIGN XXH_ACC_ALIGN +#elif XXH_VECTOR == XXH_RVV +# define XXH_SEC_ALIGN XXH_ACC_ALIGN +#else +# define XXH_SEC_ALIGN 8 +#endif + +#if defined(__GNUC__) || defined(__clang__) +# define XXH_ALIASING __attribute__((__may_alias__)) +#else +# define XXH_ALIASING /* nothing */ +#endif + +/* + * UGLY HACK: + * GCC usually generates the best code with -O3 for xxHash. + * + * However, when targeting AVX2, it is overzealous in its unrolling resulting + * in code roughly 3/4 the speed of Clang. + * + * There are other issues, such as GCC splitting _mm256_loadu_si256 into + * _mm_loadu_si128 + _mm256_inserti128_si256. This is an optimization which + * only applies to Sandy and Ivy Bridge... which don't even support AVX2. + * + * That is why when compiling the AVX2 version, it is recommended to use either + * -O2 -mavx2 -march=haswell + * or + * -O2 -mavx2 -mno-avx256-split-unaligned-load + * for decent performance, or to use Clang instead. + * + * Fortunately, we can control the first one with a pragma that forces GCC into + * -O2, but the other one we can't control without "failed to inline always + * inline function due to target mismatch" warnings. + */ +#if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \ + && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \ + && defined(__OPTIMIZE__) && XXH_SIZE_OPT <= 0 /* respect -O0 and -Os */ +# pragma GCC push_options +# pragma GCC optimize("-O2") +#endif + +#if XXH_VECTOR == XXH_NEON + +/* + * UGLY HACK: While AArch64 GCC on Linux does not seem to care, on macOS, GCC -O3 + * optimizes out the entire hashLong loop because of the aliasing violation. + * + * However, GCC is also inefficient at load-store optimization with vld1q/vst1q, + * so the only option is to mark it as aliasing. + */ +typedef uint64x2_t xxh_aliasing_uint64x2_t XXH_ALIASING; + +/*! + * @internal + * @brief `vld1q_u64` but faster and alignment-safe. + * + * On AArch64, unaligned access is always safe, but on ARMv7-a, it is only + * *conditionally* safe (`vld1` has an alignment bit like `movdq[ua]` in x86). + * + * GCC for AArch64 sees `vld1q_u8` as an intrinsic instead of a load, so it + * prohibits load-store optimizations. Therefore, a direct dereference is used. + * + * Otherwise, `vld1q_u8` is used with `vreinterpretq_u8_u64` to do a safe + * unaligned load. + */ +#if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__) +XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const* ptr) /* silence -Wcast-align */ +{ + return *(xxh_aliasing_uint64x2_t const *)ptr; +} +#else +XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const* ptr) +{ + return vreinterpretq_u64_u8(vld1q_u8((uint8_t const*)ptr)); +} +#endif + +/*! + * @internal + * @brief `vmlal_u32` on low and high halves of a vector. + * + * This is a workaround for AArch64 GCC < 11 which implemented arm_neon.h with + * inline assembly and were therefore incapable of merging the `vget_{low, high}_u32` + * with `vmlal_u32`. + */ +#if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 11 +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + /* Inline assembly is the only way */ + __asm__("umlal %0.2d, %1.2s, %2.2s" : "+w" (acc) : "w" (lhs), "w" (rhs)); + return acc; +} +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + /* This intrinsic works as expected */ + return vmlal_high_u32(acc, lhs, rhs); +} +#else +/* Portable intrinsic versions */ +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + return vmlal_u32(acc, vget_low_u32(lhs), vget_low_u32(rhs)); +} +/*! @copydoc XXH_vmlal_low_u32 + * Assume the compiler converts this to vmlal_high_u32 on aarch64 */ +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + return vmlal_u32(acc, vget_high_u32(lhs), vget_high_u32(rhs)); +} +#endif + +/*! + * @ingroup tuning + * @brief Controls the NEON to scalar ratio for XXH3 + * + * This can be set to 2, 4, 6, or 8. + * + * ARM Cortex CPUs are _very_ sensitive to how their pipelines are used. + * + * For example, the Cortex-A73 can dispatch 3 micro-ops per cycle, but only 2 of those + * can be NEON. If you are only using NEON instructions, you are only using 2/3 of the CPU + * bandwidth. + * + * This is even more noticeable on the more advanced cores like the Cortex-A76 which + * can dispatch 8 micro-ops per cycle, but still only 2 NEON micro-ops at once. + * + * Therefore, to make the most out of the pipeline, it is beneficial to run 6 NEON lanes + * and 2 scalar lanes, which is chosen by default. + * + * This does not apply to Apple processors or 32-bit processors, which run better with + * full NEON. These will default to 8. Additionally, size-optimized builds run 8 lanes. + * + * This change benefits CPUs with large micro-op buffers without negatively affecting + * most other CPUs: + * + * | Chipset | Dispatch type | NEON only | 6:2 hybrid | Diff. | + * |:----------------------|:--------------------|----------:|-----------:|------:| + * | Snapdragon 730 (A76) | 2 NEON/8 micro-ops | 8.8 GB/s | 10.1 GB/s | ~16% | + * | Snapdragon 835 (A73) | 2 NEON/3 micro-ops | 5.1 GB/s | 5.3 GB/s | ~5% | + * | Marvell PXA1928 (A53) | In-order dual-issue | 1.9 GB/s | 1.9 GB/s | 0% | + * | Apple M1 | 4 NEON/8 micro-ops | 37.3 GB/s | 36.1 GB/s | ~-3% | + * + * It also seems to fix some bad codegen on GCC, making it almost as fast as clang. + * + * When using WASM SIMD128, if this is 2 or 6, SIMDe will scalarize 2 of the lanes meaning + * it effectively becomes worse 4. + * + * @see XXH3_accumulate_512_neon() + */ +# ifndef XXH3_NEON_LANES +# if (defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) || defined(_M_ARM64EC)) \ + && !defined(__APPLE__) && XXH_SIZE_OPT <= 0 +# define XXH3_NEON_LANES 6 +# else +# define XXH3_NEON_LANES XXH_ACC_NB +# endif +# endif +#endif /* XXH_VECTOR == XXH_NEON */ + +/* + * VSX and Z Vector helpers. + * + * This is very messy, and any pull requests to clean this up are welcome. + * + * There are a lot of problems with supporting VSX and s390x, due to + * inconsistent intrinsics, spotty coverage, and multiple endiannesses. + */ +#if XXH_VECTOR == XXH_VSX +/* Annoyingly, these headers _may_ define three macros: `bool`, `vector`, + * and `pixel`. This is a problem for obvious reasons. + * + * These keywords are unnecessary; the spec literally says they are + * equivalent to `__bool`, `__vector`, and `__pixel` and may be undef'd + * after including the header. + * + * We use pragma push_macro/pop_macro to keep the namespace clean. */ +# pragma push_macro("bool") +# pragma push_macro("vector") +# pragma push_macro("pixel") +/* silence potential macro redefined warnings */ +# undef bool +# undef vector +# undef pixel + +# if defined(__s390x__) +# include +# else +# include +# endif + +/* Restore the original macro values, if applicable. */ +# pragma pop_macro("pixel") +# pragma pop_macro("vector") +# pragma pop_macro("bool") + +typedef __vector unsigned long long xxh_u64x2; +typedef __vector unsigned char xxh_u8x16; +typedef __vector unsigned xxh_u32x4; + +/* + * UGLY HACK: Similar to aarch64 macOS GCC, s390x GCC has the same aliasing issue. + */ +typedef xxh_u64x2 xxh_aliasing_u64x2 XXH_ALIASING; + +# ifndef XXH_VSX_BE +# if defined(__BIG_ENDIAN__) \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +# define XXH_VSX_BE 1 +# elif defined(__VEC_ELEMENT_REG_ORDER__) && __VEC_ELEMENT_REG_ORDER__ == __ORDER_BIG_ENDIAN__ +# warning "-maltivec=be is not recommended. Please use native endianness." +# define XXH_VSX_BE 1 +# else +# define XXH_VSX_BE 0 +# endif +# endif /* !defined(XXH_VSX_BE) */ + +# if XXH_VSX_BE +# if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__)) +# define XXH_vec_revb vec_revb +# else +/*! + * A polyfill for POWER9's vec_revb(). + */ +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val) +{ + xxh_u8x16 const vByteSwap = { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, + 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08 }; + return vec_perm(val, val, vByteSwap); +} +# endif +# endif /* XXH_VSX_BE */ + +/*! + * Performs an unaligned vector load and byte swaps it on big endian. + */ +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_loadu(const void *ptr) +{ + xxh_u64x2 ret; + XXH_memcpy(&ret, ptr, sizeof(xxh_u64x2)); +# if XXH_VSX_BE + ret = XXH_vec_revb(ret); +# endif + return ret; +} + +/* + * vec_mulo and vec_mule are very problematic intrinsics on PowerPC + * + * These intrinsics weren't added until GCC 8, despite existing for a while, + * and they are endian dependent. Also, their meaning swap depending on version. + * */ +# if defined(__s390x__) + /* s390x is always big endian, no issue on this platform */ +# define XXH_vec_mulo vec_mulo +# define XXH_vec_mule vec_mule +# elif defined(__clang__) && XXH_HAS_BUILTIN(__builtin_altivec_vmuleuw) && !defined(__ibmxl__) +/* Clang has a better way to control this, we can just use the builtin which doesn't swap. */ + /* The IBM XL Compiler (which defined __clang__) only implements the vec_* operations */ +# define XXH_vec_mulo __builtin_altivec_vmulouw +# define XXH_vec_mule __builtin_altivec_vmuleuw +# else +/* gcc needs inline assembly */ +/* Adapted from https://github.com/google/highwayhash/blob/master/highwayhash/hh_vsx.h. */ +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mulo(xxh_u32x4 a, xxh_u32x4 b) +{ + xxh_u64x2 result; + __asm__("vmulouw %0, %1, %2" : "=v" (result) : "v" (a), "v" (b)); + return result; +} +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b) +{ + xxh_u64x2 result; + __asm__("vmuleuw %0, %1, %2" : "=v" (result) : "v" (a), "v" (b)); + return result; +} +# endif /* XXH_vec_mulo, XXH_vec_mule */ +#endif /* XXH_VECTOR == XXH_VSX */ + +#if XXH_VECTOR == XXH_SVE +#define ACCRND(acc, offset) \ +do { \ + svuint64_t input_vec = svld1_u64(mask, xinput + offset); \ + svuint64_t secret_vec = svld1_u64(mask, xsecret + offset); \ + svuint64_t mixed = sveor_u64_x(mask, secret_vec, input_vec); \ + svuint64_t swapped = svtbl_u64(input_vec, kSwap); \ + svuint64_t mixed_lo = svextw_u64_x(mask, mixed); \ + svuint64_t mixed_hi = svlsr_n_u64_x(mask, mixed, 32); \ + svuint64_t mul = svmad_u64_x(mask, mixed_lo, mixed_hi, swapped); \ + acc = svadd_u64_x(mask, acc, mul); \ +} while (0) +#endif /* XXH_VECTOR == XXH_SVE */ + +/* prefetch + * can be disabled, by declaring XXH_NO_PREFETCH build macro */ +#if defined(XXH_NO_PREFETCH) +# define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */ +#else +# if XXH_SIZE_OPT >= 1 +# define XXH_PREFETCH(ptr) (void)(ptr) +# elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) /* _mm_prefetch() not defined outside of x86/x64 */ +# include /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */ +# define XXH_PREFETCH(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0) +# elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) ) +# define XXH_PREFETCH(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */) +# else +# define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */ +# endif +#endif /* XXH_NO_PREFETCH */ + + +/* ========================================== + * XXH3 default settings + * ========================================== */ + +#define XXH_SECRET_DEFAULT_SIZE 192 /* minimum XXH3_SECRET_SIZE_MIN */ + +#if (XXH_SECRET_DEFAULT_SIZE < XXH3_SECRET_SIZE_MIN) +# error "default keyset is not large enough" +#endif + +/*! + * @internal + * @def XXH3_kSecret + * @brief Pseudorandom secret taken directly from FARSH. */ +XXH_ALIGN(64) static const xxh_u8 XXH3_kSecret[XXH_SECRET_DEFAULT_SIZE] = { + 0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c, + 0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f, + 0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21, + 0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c, + 0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3, + 0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, 0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8, + 0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d, + 0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64, + 0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb, + 0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e, + 0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce, + 0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e, +}; + +static const xxh_u64 PRIME_MX1 = 0x165667919E3779F9ULL; /*!< 0b0001011001010110011001111001000110011110001101110111100111111001 */ +static const xxh_u64 PRIME_MX2 = 0x9FB21C651E98DF25ULL; /*!< 0b1001111110110010000111000110010100011110100110001101111100100101 */ + +#ifdef XXH_OLD_NAMES +# define kSecret XXH3_kSecret +#endif + +#ifdef XXH_DOXYGEN +/*! + * @brief Calculates a 32-bit to 64-bit long multiply. + * + * Implemented as a macro. + * + * Wraps `__emulu` on MSVC x86 because it tends to call `__allmul` when it doesn't + * need to (but it shouldn't need to anyways, it is about 7 instructions to do + * a 64x64 multiply...). Since we know that this will _always_ emit `MULL`, we + * use that instead of the normal method. + * + * If you are compiling for platforms like Thumb-1 and don't have a better option, + * you may also want to write your own long multiply routine here. + * + * @param x, y Numbers to be multiplied + * @return 64-bit product of the low 32 bits of @p x and @p y. + */ +XXH_FORCE_INLINE xxh_u64 +XXH_mult32to64(xxh_u64 x, xxh_u64 y) +{ + return (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF); +} +#elif defined(_MSC_VER) && defined(_M_IX86) +# define XXH_mult32to64(x, y) __emulu((unsigned)(x), (unsigned)(y)) +#else +/* + * Downcast + upcast is usually better than masking on older compilers like + * GCC 4.2 (especially 32-bit ones), all without affecting newer compilers. + * + * The other method, (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF), will AND both operands + * and perform a full 64x64 multiply -- entirely redundant on 32-bit. + */ +# define XXH_mult32to64(x, y) ((xxh_u64)(xxh_u32)(x) * (xxh_u64)(xxh_u32)(y)) +#endif + +/*! + * @brief Calculates a 64->128-bit long multiply. + * + * Uses `__uint128_t` and `_umul128` if available, otherwise uses a scalar + * version. + * + * @param lhs , rhs The 64-bit integers to be multiplied + * @return The 128-bit result represented in an @ref XXH128_hash_t. + */ +static XXH128_hash_t +XXH_mult64to128(xxh_u64 lhs, xxh_u64 rhs) +{ + /* + * GCC/Clang __uint128_t method. + * + * On most 64-bit targets, GCC and Clang define a __uint128_t type. + * This is usually the best way as it usually uses a native long 64-bit + * multiply, such as MULQ on x86_64 or MUL + UMULH on aarch64. + * + * Usually. + * + * Despite being a 32-bit platform, Clang (and emscripten) define this type + * despite not having the arithmetic for it. This results in a laggy + * compiler builtin call which calculates a full 128-bit multiply. + * In that case it is best to use the portable one. + * https://github.com/Cyan4973/xxHash/issues/211#issuecomment-515575677 + */ +#if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) \ + && defined(__SIZEOF_INT128__) \ + || (defined(_INTEGRAL_MAX_BITS) && _INTEGRAL_MAX_BITS >= 128) + + __uint128_t const product = (__uint128_t)lhs * (__uint128_t)rhs; + XXH128_hash_t r128; + r128.low64 = (xxh_u64)(product); + r128.high64 = (xxh_u64)(product >> 64); + return r128; + + /* + * MSVC for x64's _umul128 method. + * + * xxh_u64 _umul128(xxh_u64 Multiplier, xxh_u64 Multiplicand, xxh_u64 *HighProduct); + * + * This compiles to single operand MUL on x64. + */ +#elif (defined(_M_X64) || defined(_M_IA64)) && !defined(_M_ARM64EC) + +#ifndef _MSC_VER +# pragma intrinsic(_umul128) +#endif + xxh_u64 product_high; + xxh_u64 const product_low = _umul128(lhs, rhs, &product_high); + XXH128_hash_t r128; + r128.low64 = product_low; + r128.high64 = product_high; + return r128; + + /* + * MSVC for ARM64's __umulh method. + * + * This compiles to the same MUL + UMULH as GCC/Clang's __uint128_t method. + */ +#elif defined(_M_ARM64) || defined(_M_ARM64EC) + +#ifndef _MSC_VER +# pragma intrinsic(__umulh) +#endif + XXH128_hash_t r128; + r128.low64 = lhs * rhs; + r128.high64 = __umulh(lhs, rhs); + return r128; + +#else + /* + * Portable scalar method. Optimized for 32-bit and 64-bit ALUs. + * + * This is a fast and simple grade school multiply, which is shown below + * with base 10 arithmetic instead of base 0x100000000. + * + * 9 3 // D2 lhs = 93 + * x 7 5 // D2 rhs = 75 + * ---------- + * 1 5 // D2 lo_lo = (93 % 10) * (75 % 10) = 15 + * 4 5 | // D2 hi_lo = (93 / 10) * (75 % 10) = 45 + * 2 1 | // D2 lo_hi = (93 % 10) * (75 / 10) = 21 + * + 6 3 | | // D2 hi_hi = (93 / 10) * (75 / 10) = 63 + * --------- + * 2 7 | // D2 cross = (15 / 10) + (45 % 10) + 21 = 27 + * + 6 7 | | // D2 upper = (27 / 10) + (45 / 10) + 63 = 67 + * --------- + * 6 9 7 5 // D4 res = (27 * 10) + (15 % 10) + (67 * 100) = 6975 + * + * The reasons for adding the products like this are: + * 1. It avoids manual carry tracking. Just like how + * (9 * 9) + 9 + 9 = 99, the same applies with this for UINT64_MAX. + * This avoids a lot of complexity. + * + * 2. It hints for, and on Clang, compiles to, the powerful UMAAL + * instruction available in ARM's Digital Signal Processing extension + * in 32-bit ARMv6 and later, which is shown below: + * + * void UMAAL(xxh_u32 *RdLo, xxh_u32 *RdHi, xxh_u32 Rn, xxh_u32 Rm) + * { + * xxh_u64 product = (xxh_u64)*RdLo * (xxh_u64)*RdHi + Rn + Rm; + * *RdLo = (xxh_u32)(product & 0xFFFFFFFF); + * *RdHi = (xxh_u32)(product >> 32); + * } + * + * This instruction was designed for efficient long multiplication, and + * allows this to be calculated in only 4 instructions at speeds + * comparable to some 64-bit ALUs. + * + * 3. It isn't terrible on other platforms. Usually this will be a couple + * of 32-bit ADD/ADCs. + */ + + /* First calculate all of the cross products. */ + xxh_u64 const lo_lo = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs & 0xFFFFFFFF); + xxh_u64 const hi_lo = XXH_mult32to64(lhs >> 32, rhs & 0xFFFFFFFF); + xxh_u64 const lo_hi = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs >> 32); + xxh_u64 const hi_hi = XXH_mult32to64(lhs >> 32, rhs >> 32); + + /* Now add the products together. These will never overflow. */ + xxh_u64 const cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi; + xxh_u64 const upper = (hi_lo >> 32) + (cross >> 32) + hi_hi; + xxh_u64 const lower = (cross << 32) | (lo_lo & 0xFFFFFFFF); + + XXH128_hash_t r128; + r128.low64 = lower; + r128.high64 = upper; + return r128; +#endif +} + +/*! + * @brief Calculates a 64-bit to 128-bit multiply, then XOR folds it. + * + * The reason for the separate function is to prevent passing too many structs + * around by value. This will hopefully inline the multiply, but we don't force it. + * + * @param lhs , rhs The 64-bit integers to multiply + * @return The low 64 bits of the product XOR'd by the high 64 bits. + * @see XXH_mult64to128() + */ +static xxh_u64 +XXH3_mul128_fold64(xxh_u64 lhs, xxh_u64 rhs) +{ + XXH128_hash_t product = XXH_mult64to128(lhs, rhs); + return product.low64 ^ product.high64; +} + +/*! Seems to produce slightly better code on GCC for some reason. */ +XXH_FORCE_INLINE XXH_CONSTF xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift) +{ + XXH_ASSERT(0 <= shift && shift < 64); + return v64 ^ (v64 >> shift); +} + +/* + * This is a fast avalanche stage, + * suitable when input bits are already partially mixed + */ +static XXH64_hash_t XXH3_avalanche(xxh_u64 h64) +{ + h64 = XXH_xorshift64(h64, 37); + h64 *= PRIME_MX1; + h64 = XXH_xorshift64(h64, 32); + return h64; +} + +/* + * This is a stronger avalanche, + * inspired by Pelle Evensen's rrmxmx + * preferable when input has not been previously mixed + */ +static XXH64_hash_t XXH3_rrmxmx(xxh_u64 h64, xxh_u64 len) +{ + /* this mix is inspired by Pelle Evensen's rrmxmx */ + h64 ^= XXH_rotl64(h64, 49) ^ XXH_rotl64(h64, 24); + h64 *= PRIME_MX2; + h64 ^= (h64 >> 35) + len ; + h64 *= PRIME_MX2; + return XXH_xorshift64(h64, 28); +} + + +/* ========================================== + * Short keys + * ========================================== + * One of the shortcomings of XXH32 and XXH64 was that their performance was + * sub-optimal on short lengths. It used an iterative algorithm which strongly + * favored lengths that were a multiple of 4 or 8. + * + * Instead of iterating over individual inputs, we use a set of single shot + * functions which piece together a range of lengths and operate in constant time. + * + * Additionally, the number of multiplies has been significantly reduced. This + * reduces latency, especially when emulating 64-bit multiplies on 32-bit. + * + * Depending on the platform, this may or may not be faster than XXH32, but it + * is almost guaranteed to be faster than XXH64. + */ + +/* + * At very short lengths, there isn't enough input to fully hide secrets, or use + * the entire secret. + * + * There is also only a limited amount of mixing we can do before significantly + * impacting performance. + * + * Therefore, we use different sections of the secret and always mix two secret + * samples with an XOR. This should have no effect on performance on the + * seedless or withSeed variants because everything _should_ be constant folded + * by modern compilers. + * + * The XOR mixing hides individual parts of the secret and increases entropy. + * + * This adds an extra layer of strength for custom secrets. + */ +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_1to3_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(1 <= len && len <= 3); + XXH_ASSERT(secret != NULL); + /* + * len = 1: combined = { input[0], 0x01, input[0], input[0] } + * len = 2: combined = { input[1], 0x02, input[0], input[1] } + * len = 3: combined = { input[2], 0x03, input[0], input[1] } + */ + { xxh_u8 const c1 = input[0]; + xxh_u8 const c2 = input[len >> 1]; + xxh_u8 const c3 = input[len - 1]; + xxh_u32 const combined = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) + | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8); + xxh_u64 const bitflip = (XXH_readLE32(secret) ^ XXH_readLE32(secret+4)) + seed; + xxh_u64 const keyed = (xxh_u64)combined ^ bitflip; + return XXH64_avalanche(keyed); + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_4to8_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(4 <= len && len <= 8); + seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32; + { xxh_u32 const input1 = XXH_readLE32(input); + xxh_u32 const input2 = XXH_readLE32(input + len - 4); + xxh_u64 const bitflip = (XXH_readLE64(secret+8) ^ XXH_readLE64(secret+16)) - seed; + xxh_u64 const input64 = input2 + (((xxh_u64)input1) << 32); + xxh_u64 const keyed = input64 ^ bitflip; + return XXH3_rrmxmx(keyed, len); + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_9to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(9 <= len && len <= 16); + { xxh_u64 const bitflip1 = (XXH_readLE64(secret+24) ^ XXH_readLE64(secret+32)) + seed; + xxh_u64 const bitflip2 = (XXH_readLE64(secret+40) ^ XXH_readLE64(secret+48)) - seed; + xxh_u64 const input_lo = XXH_readLE64(input) ^ bitflip1; + xxh_u64 const input_hi = XXH_readLE64(input + len - 8) ^ bitflip2; + xxh_u64 const acc = len + + XXH_swap64(input_lo) + input_hi + + XXH3_mul128_fold64(input_lo, input_hi); + return XXH3_avalanche(acc); + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_0to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(len <= 16); + { if (XXH_likely(len > 8)) return XXH3_len_9to16_64b(input, len, secret, seed); + if (XXH_likely(len >= 4)) return XXH3_len_4to8_64b(input, len, secret, seed); + if (len) return XXH3_len_1to3_64b(input, len, secret, seed); + return XXH64_avalanche(seed ^ (XXH_readLE64(secret+56) ^ XXH_readLE64(secret+64))); + } +} + +/* + * DISCLAIMER: There are known *seed-dependent* multicollisions here due to + * multiplication by zero, affecting hashes of lengths 17 to 240. + * + * However, they are very unlikely. + * + * Keep this in mind when using the unseeded XXH3_64bits() variant: As with all + * unseeded non-cryptographic hashes, it does not attempt to defend itself + * against specially crafted inputs, only random inputs. + * + * Compared to classic UMAC where a 1 in 2^31 chance of 4 consecutive bytes + * cancelling out the secret is taken an arbitrary number of times (addressed + * in XXH3_accumulate_512), this collision is very unlikely with random inputs + * and/or proper seeding: + * + * This only has a 1 in 2^63 chance of 8 consecutive bytes cancelling out, in a + * function that is only called up to 16 times per hash with up to 240 bytes of + * input. + * + * This is not too bad for a non-cryptographic hash function, especially with + * only 64 bit outputs. + * + * The 128-bit variant (which trades some speed for strength) is NOT affected + * by this, although it is always a good idea to use a proper seed if you care + * about strength. + */ +XXH_FORCE_INLINE xxh_u64 XXH3_mix16B(const xxh_u8* XXH_RESTRICT input, + const xxh_u8* XXH_RESTRICT secret, xxh_u64 seed64) +{ +#if defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \ + && defined(__i386__) && defined(__SSE2__) /* x86 + SSE2 */ \ + && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable like XXH32 hack */ + /* + * UGLY HACK: + * GCC for x86 tends to autovectorize the 128-bit multiply, resulting in + * slower code. + * + * By forcing seed64 into a register, we disrupt the cost model and + * cause it to scalarize. See `XXH32_round()` + * + * FIXME: Clang's output is still _much_ faster -- On an AMD Ryzen 3600, + * XXH3_64bits @ len=240 runs at 4.6 GB/s with Clang 9, but 3.3 GB/s on + * GCC 9.2, despite both emitting scalar code. + * + * GCC generates much better scalar code than Clang for the rest of XXH3, + * which is why finding a more optimal codepath is an interest. + */ + XXH_COMPILER_GUARD(seed64); +#endif + { xxh_u64 const input_lo = XXH_readLE64(input); + xxh_u64 const input_hi = XXH_readLE64(input+8); + return XXH3_mul128_fold64( + input_lo ^ (XXH_readLE64(secret) + seed64), + input_hi ^ (XXH_readLE64(secret+8) - seed64) + ); + } +} + +/* For mid range keys, XXH3 uses a Mum-hash variant. */ +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(16 < len && len <= 128); + + { xxh_u64 acc = len * XXH_PRIME64_1; +#if XXH_SIZE_OPT >= 1 + /* Smaller and cleaner, but slightly slower. */ + unsigned int i = (unsigned int)(len - 1) / 32; + do { + acc += XXH3_mix16B(input+16 * i, secret+32*i, seed); + acc += XXH3_mix16B(input+len-16*(i+1), secret+32*i+16, seed); + } while (i-- != 0); +#else + if (len > 32) { + if (len > 64) { + if (len > 96) { + acc += XXH3_mix16B(input+48, secret+96, seed); + acc += XXH3_mix16B(input+len-64, secret+112, seed); + } + acc += XXH3_mix16B(input+32, secret+64, seed); + acc += XXH3_mix16B(input+len-48, secret+80, seed); + } + acc += XXH3_mix16B(input+16, secret+32, seed); + acc += XXH3_mix16B(input+len-32, secret+48, seed); + } + acc += XXH3_mix16B(input+0, secret+0, seed); + acc += XXH3_mix16B(input+len-16, secret+16, seed); +#endif + return XXH3_avalanche(acc); + } +} + +XXH_NO_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); + + #define XXH3_MIDSIZE_STARTOFFSET 3 + #define XXH3_MIDSIZE_LASTOFFSET 17 + + { xxh_u64 acc = len * XXH_PRIME64_1; + xxh_u64 acc_end; + unsigned int const nbRounds = (unsigned int)len / 16; + unsigned int i; + XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); + for (i=0; i<8; i++) { + acc += XXH3_mix16B(input+(16*i), secret+(16*i), seed); + } + /* last bytes */ + acc_end = XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed); + XXH_ASSERT(nbRounds >= 8); + acc = XXH3_avalanche(acc); +#if defined(__clang__) /* Clang */ \ + && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \ + && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */ + /* + * UGLY HACK: + * Clang for ARMv7-A tries to vectorize this loop, similar to GCC x86. + * In everywhere else, it uses scalar code. + * + * For 64->128-bit multiplies, even if the NEON was 100% optimal, it + * would still be slower than UMAAL (see XXH_mult64to128). + * + * Unfortunately, Clang doesn't handle the long multiplies properly and + * converts them to the nonexistent "vmulq_u64" intrinsic, which is then + * scalarized into an ugly mess of VMOV.32 instructions. + * + * This mess is difficult to avoid without turning autovectorization + * off completely, but they are usually relatively minor and/or not + * worth it to fix. + * + * This loop is the easiest to fix, as unlike XXH32, this pragma + * _actually works_ because it is a loop vectorization instead of an + * SLP vectorization. + */ + #pragma clang loop vectorize(disable) +#endif + for (i=8 ; i < nbRounds; i++) { + /* + * Prevents clang for unrolling the acc loop and interleaving with this one. + */ + XXH_COMPILER_GUARD(acc); + acc_end += XXH3_mix16B(input+(16*i), secret+(16*(i-8)) + XXH3_MIDSIZE_STARTOFFSET, seed); + } + return XXH3_avalanche(acc + acc_end); + } +} + + +/* ======= Long Keys ======= */ + +#define XXH_STRIPE_LEN 64 +#define XXH_SECRET_CONSUME_RATE 8 /* nb of secret bytes consumed at each accumulation */ +#define XXH_ACC_NB (XXH_STRIPE_LEN / sizeof(xxh_u64)) + +#ifdef XXH_OLD_NAMES +# define STRIPE_LEN XXH_STRIPE_LEN +# define ACC_NB XXH_ACC_NB +#endif + +#ifndef XXH_PREFETCH_DIST +# ifdef __clang__ +# define XXH_PREFETCH_DIST 320 +# else +# if (XXH_VECTOR == XXH_AVX512) +# define XXH_PREFETCH_DIST 512 +# else +# define XXH_PREFETCH_DIST 384 +# endif +# endif /* __clang__ */ +#endif /* XXH_PREFETCH_DIST */ + +/* + * These macros are to generate an XXH3_accumulate() function. + * The two arguments select the name suffix and target attribute. + * + * The name of this symbol is XXH3_accumulate_() and it calls + * XXH3_accumulate_512_(). + * + * It may be useful to hand implement this function if the compiler fails to + * optimize the inline function. + */ +#define XXH3_ACCUMULATE_TEMPLATE(name) \ +void \ +XXH3_accumulate_##name(xxh_u64* XXH_RESTRICT acc, \ + const xxh_u8* XXH_RESTRICT input, \ + const xxh_u8* XXH_RESTRICT secret, \ + size_t nbStripes) \ +{ \ + size_t n; \ + for (n = 0; n < nbStripes; n++ ) { \ + const xxh_u8* const in = input + n*XXH_STRIPE_LEN; \ + XXH_PREFETCH(in + XXH_PREFETCH_DIST); \ + XXH3_accumulate_512_##name( \ + acc, \ + in, \ + secret + n*XXH_SECRET_CONSUME_RATE); \ + } \ +} + + +XXH_FORCE_INLINE void XXH_writeLE64(void* dst, xxh_u64 v64) +{ + if (!XXH_CPU_LITTLE_ENDIAN) v64 = XXH_swap64(v64); + XXH_memcpy(dst, &v64, sizeof(v64)); +} + +/* Several intrinsic functions below are supposed to accept __int64 as argument, + * as documented in https://software.intel.com/sites/landingpage/IntrinsicsGuide/ . + * However, several environments do not define __int64 type, + * requiring a workaround. + */ +#if !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) + typedef int64_t xxh_i64; +#else + /* the following type must have a width of 64-bit */ + typedef long long xxh_i64; +#endif + + +/* + * XXH3_accumulate_512 is the tightest loop for long inputs, and it is the most optimized. + * + * It is a hardened version of UMAC, based off of FARSH's implementation. + * + * This was chosen because it adapts quite well to 32-bit, 64-bit, and SIMD + * implementations, and it is ridiculously fast. + * + * We harden it by mixing the original input to the accumulators as well as the product. + * + * This means that in the (relatively likely) case of a multiply by zero, the + * original input is preserved. + * + * On 128-bit inputs, we swap 64-bit pairs when we add the input to improve + * cross-pollination, as otherwise the upper and lower halves would be + * essentially independent. + * + * This doesn't matter on 64-bit hashes since they all get merged together in + * the end, so we skip the extra step. + * + * Both XXH3_64bits and XXH3_128bits use this subroutine. + */ + +#if (XXH_VECTOR == XXH_AVX512) \ + || (defined(XXH_DISPATCH_AVX512) && XXH_DISPATCH_AVX512 != 0) + +#ifndef XXH_TARGET_AVX512 +# define XXH_TARGET_AVX512 /* disable attribute target */ +#endif + +XXH_FORCE_INLINE XXH_TARGET_AVX512 void +XXH3_accumulate_512_avx512(void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + __m512i* const xacc = (__m512i *) acc; + XXH_ASSERT((((size_t)acc) & 63) == 0); + XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i)); + + { + /* data_vec = input[0]; */ + __m512i const data_vec = _mm512_loadu_si512 (input); + /* key_vec = secret[0]; */ + __m512i const key_vec = _mm512_loadu_si512 (secret); + /* data_key = data_vec ^ key_vec; */ + __m512i const data_key = _mm512_xor_si512 (data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m512i const data_key_lo = _mm512_srli_epi64 (data_key, 32); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m512i const product = _mm512_mul_epu32 (data_key, data_key_lo); + /* xacc[0] += swap(data_vec); */ + __m512i const data_swap = _mm512_shuffle_epi32(data_vec, (_MM_PERM_ENUM)_MM_SHUFFLE(1, 0, 3, 2)); + __m512i const sum = _mm512_add_epi64(*xacc, data_swap); + /* xacc[0] += product; */ + *xacc = _mm512_add_epi64(product, sum); + } +} +XXH_FORCE_INLINE XXH_TARGET_AVX512 XXH3_ACCUMULATE_TEMPLATE(avx512) + +/* + * XXH3_scrambleAcc: Scrambles the accumulators to improve mixing. + * + * Multiplication isn't perfect, as explained by Google in HighwayHash: + * + * // Multiplication mixes/scrambles bytes 0-7 of the 64-bit result to + * // varying degrees. In descending order of goodness, bytes + * // 3 4 2 5 1 6 0 7 have quality 228 224 164 160 100 96 36 32. + * // As expected, the upper and lower bytes are much worse. + * + * Source: https://github.com/google/highwayhash/blob/0aaf66b/highwayhash/hh_avx2.h#L291 + * + * Since our algorithm uses a pseudorandom secret to add some variance into the + * mix, we don't need to (or want to) mix as often or as much as HighwayHash does. + * + * This isn't as tight as XXH3_accumulate, but still written in SIMD to avoid + * extraction. + * + * Both XXH3_64bits and XXH3_128bits use this subroutine. + */ + +XXH_FORCE_INLINE XXH_TARGET_AVX512 void +XXH3_scrambleAcc_avx512(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 63) == 0); + XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i)); + { __m512i* const xacc = (__m512i*) acc; + const __m512i prime32 = _mm512_set1_epi32((int)XXH_PRIME32_1); + + /* xacc[0] ^= (xacc[0] >> 47) */ + __m512i const acc_vec = *xacc; + __m512i const shifted = _mm512_srli_epi64 (acc_vec, 47); + /* xacc[0] ^= secret; */ + __m512i const key_vec = _mm512_loadu_si512 (secret); + __m512i const data_key = _mm512_ternarylogic_epi32(key_vec, acc_vec, shifted, 0x96 /* key_vec ^ acc_vec ^ shifted */); + + /* xacc[0] *= XXH_PRIME32_1; */ + __m512i const data_key_hi = _mm512_srli_epi64 (data_key, 32); + __m512i const prod_lo = _mm512_mul_epu32 (data_key, prime32); + __m512i const prod_hi = _mm512_mul_epu32 (data_key_hi, prime32); + *xacc = _mm512_add_epi64(prod_lo, _mm512_slli_epi64(prod_hi, 32)); + } +} + +XXH_FORCE_INLINE XXH_TARGET_AVX512 void +XXH3_initCustomSecret_avx512(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 63) == 0); + XXH_STATIC_ASSERT(XXH_SEC_ALIGN == 64); + XXH_ASSERT(((size_t)customSecret & 63) == 0); + (void)(&XXH_writeLE64); + { int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m512i); + __m512i const seed_pos = _mm512_set1_epi64((xxh_i64)seed64); + __m512i const seed = _mm512_mask_sub_epi64(seed_pos, 0xAA, _mm512_set1_epi8(0), seed_pos); + + const __m512i* const src = (const __m512i*) ((const void*) XXH3_kSecret); + __m512i* const dest = ( __m512i*) customSecret; + int i; + XXH_ASSERT(((size_t)src & 63) == 0); /* control alignment */ + XXH_ASSERT(((size_t)dest & 63) == 0); + for (i=0; i < nbRounds; ++i) { + dest[i] = _mm512_add_epi64(_mm512_load_si512(src + i), seed); + } } +} + +#endif + +#if (XXH_VECTOR == XXH_AVX2) \ + || (defined(XXH_DISPATCH_AVX2) && XXH_DISPATCH_AVX2 != 0) + +#ifndef XXH_TARGET_AVX2 +# define XXH_TARGET_AVX2 /* disable attribute target */ +#endif + +XXH_FORCE_INLINE XXH_TARGET_AVX2 void +XXH3_accumulate_512_avx2( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 31) == 0); + { __m256i* const xacc = (__m256i *) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ + const __m256i* const xinput = (const __m256i *) input; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ + const __m256i* const xsecret = (const __m256i *) secret; + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m256i); i++) { + /* data_vec = xinput[i]; */ + __m256i const data_vec = _mm256_loadu_si256 (xinput+i); + /* key_vec = xsecret[i]; */ + __m256i const key_vec = _mm256_loadu_si256 (xsecret+i); + /* data_key = data_vec ^ key_vec; */ + __m256i const data_key = _mm256_xor_si256 (data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m256i const data_key_lo = _mm256_srli_epi64 (data_key, 32); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m256i const product = _mm256_mul_epu32 (data_key, data_key_lo); + /* xacc[i] += swap(data_vec); */ + __m256i const data_swap = _mm256_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2)); + __m256i const sum = _mm256_add_epi64(xacc[i], data_swap); + /* xacc[i] += product; */ + xacc[i] = _mm256_add_epi64(product, sum); + } } +} +XXH_FORCE_INLINE XXH_TARGET_AVX2 XXH3_ACCUMULATE_TEMPLATE(avx2) + +XXH_FORCE_INLINE XXH_TARGET_AVX2 void +XXH3_scrambleAcc_avx2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 31) == 0); + { __m256i* const xacc = (__m256i*) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ + const __m256i* const xsecret = (const __m256i *) secret; + const __m256i prime32 = _mm256_set1_epi32((int)XXH_PRIME32_1); + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m256i); i++) { + /* xacc[i] ^= (xacc[i] >> 47) */ + __m256i const acc_vec = xacc[i]; + __m256i const shifted = _mm256_srli_epi64 (acc_vec, 47); + __m256i const data_vec = _mm256_xor_si256 (acc_vec, shifted); + /* xacc[i] ^= xsecret; */ + __m256i const key_vec = _mm256_loadu_si256 (xsecret+i); + __m256i const data_key = _mm256_xor_si256 (data_vec, key_vec); + + /* xacc[i] *= XXH_PRIME32_1; */ + __m256i const data_key_hi = _mm256_srli_epi64 (data_key, 32); + __m256i const prod_lo = _mm256_mul_epu32 (data_key, prime32); + __m256i const prod_hi = _mm256_mul_epu32 (data_key_hi, prime32); + xacc[i] = _mm256_add_epi64(prod_lo, _mm256_slli_epi64(prod_hi, 32)); + } + } +} + +XXH_FORCE_INLINE XXH_TARGET_AVX2 void XXH3_initCustomSecret_avx2(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 31) == 0); + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE / sizeof(__m256i)) == 6); + XXH_STATIC_ASSERT(XXH_SEC_ALIGN <= 64); + (void)(&XXH_writeLE64); + XXH_PREFETCH(customSecret); + { __m256i const seed = _mm256_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64, (xxh_i64)(0U - seed64), (xxh_i64)seed64); + + const __m256i* const src = (const __m256i*) ((const void*) XXH3_kSecret); + __m256i* dest = ( __m256i*) customSecret; + +# if defined(__GNUC__) || defined(__clang__) + /* + * On GCC & Clang, marking 'dest' as modified will cause the compiler: + * - do not extract the secret from sse registers in the internal loop + * - use less common registers, and avoid pushing these reg into stack + */ + XXH_COMPILER_GUARD(dest); +# endif + XXH_ASSERT(((size_t)src & 31) == 0); /* control alignment */ + XXH_ASSERT(((size_t)dest & 31) == 0); + + /* GCC -O2 need unroll loop manually */ + dest[0] = _mm256_add_epi64(_mm256_load_si256(src+0), seed); + dest[1] = _mm256_add_epi64(_mm256_load_si256(src+1), seed); + dest[2] = _mm256_add_epi64(_mm256_load_si256(src+2), seed); + dest[3] = _mm256_add_epi64(_mm256_load_si256(src+3), seed); + dest[4] = _mm256_add_epi64(_mm256_load_si256(src+4), seed); + dest[5] = _mm256_add_epi64(_mm256_load_si256(src+5), seed); + } +} + +#endif + +/* x86dispatch always generates SSE2 */ +#if (XXH_VECTOR == XXH_SSE2) || defined(XXH_X86DISPATCH) + +#ifndef XXH_TARGET_SSE2 +# define XXH_TARGET_SSE2 /* disable attribute target */ +#endif + +XXH_FORCE_INLINE XXH_TARGET_SSE2 void +XXH3_accumulate_512_sse2( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + /* SSE2 is just a half-scale version of the AVX2 version. */ + XXH_ASSERT((((size_t)acc) & 15) == 0); + { __m128i* const xacc = (__m128i *) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ + const __m128i* const xinput = (const __m128i *) input; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ + const __m128i* const xsecret = (const __m128i *) secret; + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m128i); i++) { + /* data_vec = xinput[i]; */ + __m128i const data_vec = _mm_loadu_si128 (xinput+i); + /* key_vec = xsecret[i]; */ + __m128i const key_vec = _mm_loadu_si128 (xsecret+i); + /* data_key = data_vec ^ key_vec; */ + __m128i const data_key = _mm_xor_si128 (data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m128i const data_key_lo = _mm_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1)); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m128i const product = _mm_mul_epu32 (data_key, data_key_lo); + /* xacc[i] += swap(data_vec); */ + __m128i const data_swap = _mm_shuffle_epi32(data_vec, _MM_SHUFFLE(1,0,3,2)); + __m128i const sum = _mm_add_epi64(xacc[i], data_swap); + /* xacc[i] += product; */ + xacc[i] = _mm_add_epi64(product, sum); + } } +} +XXH_FORCE_INLINE XXH_TARGET_SSE2 XXH3_ACCUMULATE_TEMPLATE(sse2) + +XXH_FORCE_INLINE XXH_TARGET_SSE2 void +XXH3_scrambleAcc_sse2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + { __m128i* const xacc = (__m128i*) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ + const __m128i* const xsecret = (const __m128i *) secret; + const __m128i prime32 = _mm_set1_epi32((int)XXH_PRIME32_1); + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m128i); i++) { + /* xacc[i] ^= (xacc[i] >> 47) */ + __m128i const acc_vec = xacc[i]; + __m128i const shifted = _mm_srli_epi64 (acc_vec, 47); + __m128i const data_vec = _mm_xor_si128 (acc_vec, shifted); + /* xacc[i] ^= xsecret[i]; */ + __m128i const key_vec = _mm_loadu_si128 (xsecret+i); + __m128i const data_key = _mm_xor_si128 (data_vec, key_vec); + + /* xacc[i] *= XXH_PRIME32_1; */ + __m128i const data_key_hi = _mm_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1)); + __m128i const prod_lo = _mm_mul_epu32 (data_key, prime32); + __m128i const prod_hi = _mm_mul_epu32 (data_key_hi, prime32); + xacc[i] = _mm_add_epi64(prod_lo, _mm_slli_epi64(prod_hi, 32)); + } + } +} + +XXH_FORCE_INLINE XXH_TARGET_SSE2 void XXH3_initCustomSecret_sse2(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0); + (void)(&XXH_writeLE64); + { int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m128i); + +# if defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER <= 1900 + /* MSVC 32bit mode does not support _mm_set_epi64x before 2015 + * and some specific variants of 2015 may also lack it */ + /* Cast to unsigned 64-bit first to avoid signed arithmetic issues */ + xxh_u64 const seed64_unsigned = (xxh_u64)seed64; + xxh_u64 const neg_seed64 = (xxh_u64)(0ULL - seed64_unsigned); + __m128i const seed = _mm_set_epi32( + (int)(neg_seed64 >> 32), /* high 32 bits of negated seed */ + (int)(neg_seed64), /* low 32 bits of negated seed */ + (int)(seed64_unsigned >> 32), /* high 32 bits of original seed */ + (int)(seed64_unsigned) /* low 32 bits of original seed */ + ); +# else + __m128i const seed = _mm_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64); +# endif + int i; + + const void* const src16 = XXH3_kSecret; + __m128i* dst16 = (__m128i*) customSecret; +# if defined(__GNUC__) || defined(__clang__) + /* + * On GCC & Clang, marking 'dest' as modified will cause the compiler: + * - do not extract the secret from sse registers in the internal loop + * - use less common registers, and avoid pushing these reg into stack + */ + XXH_COMPILER_GUARD(dst16); +# endif + XXH_ASSERT(((size_t)src16 & 15) == 0); /* control alignment */ + XXH_ASSERT(((size_t)dst16 & 15) == 0); + + for (i=0; i < nbRounds; ++i) { + dst16[i] = _mm_add_epi64(_mm_load_si128((const __m128i *)src16+i), seed); + } } +} + +#endif + +#if (XXH_VECTOR == XXH_NEON) + +/* forward declarations for the scalar routines */ +XXH_FORCE_INLINE void +XXH3_scalarRound(void* XXH_RESTRICT acc, void const* XXH_RESTRICT input, + void const* XXH_RESTRICT secret, size_t lane); + +XXH_FORCE_INLINE void +XXH3_scalarScrambleRound(void* XXH_RESTRICT acc, + void const* XXH_RESTRICT secret, size_t lane); + +/*! + * @internal + * @brief The bulk processing loop for NEON and WASM SIMD128. + * + * The NEON code path is actually partially scalar when running on AArch64. This + * is to optimize the pipelining and can have up to 15% speedup depending on the + * CPU, and it also mitigates some GCC codegen issues. + * + * @see XXH3_NEON_LANES for configuring this and details about this optimization. + * + * NEON's 32-bit to 64-bit long multiply takes a half vector of 32-bit + * integers instead of the other platforms which mask full 64-bit vectors, + * so the setup is more complicated than just shifting right. + * + * Additionally, there is an optimization for 4 lanes at once noted below. + * + * Since, as stated, the most optimal amount of lanes for Cortexes is 6, + * there needs to be *three* versions of the accumulate operation used + * for the remaining 2 lanes. + * + * WASM's SIMD128 uses SIMDe's arm_neon.h polyfill because the intrinsics overlap + * nearly perfectly. + */ + +XXH_FORCE_INLINE void +XXH3_accumulate_512_neon( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + XXH_STATIC_ASSERT(XXH3_NEON_LANES > 0 && XXH3_NEON_LANES <= XXH_ACC_NB && XXH3_NEON_LANES % 2 == 0); + { /* GCC for darwin arm64 does not like aliasing here */ + xxh_aliasing_uint64x2_t* const xacc = (xxh_aliasing_uint64x2_t*) acc; + /* We don't use a uint32x4_t pointer because it causes bus errors on ARMv7. */ + uint8_t const* xinput = (const uint8_t *) input; + uint8_t const* xsecret = (const uint8_t *) secret; + + size_t i; +#ifdef __wasm_simd128__ + /* + * On WASM SIMD128, Clang emits direct address loads when XXH3_kSecret + * is constant propagated, which results in it converting it to this + * inside the loop: + * + * a = v128.load(XXH3_kSecret + 0 + $secret_offset, offset = 0) + * b = v128.load(XXH3_kSecret + 16 + $secret_offset, offset = 0) + * ... + * + * This requires a full 32-bit address immediate (and therefore a 6 byte + * instruction) as well as an add for each offset. + * + * Putting an asm guard prevents it from folding (at the cost of losing + * the alignment hint), and uses the free offset in `v128.load` instead + * of adding secret_offset each time which overall reduces code size by + * about a kilobyte and improves performance. + */ + XXH_COMPILER_GUARD(xsecret); +#endif + /* Scalar lanes use the normal scalarRound routine */ + for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) { + XXH3_scalarRound(acc, input, secret, i); + } + i = 0; + /* 4 NEON lanes at a time. */ + for (; i+1 < XXH3_NEON_LANES / 2; i+=2) { + /* data_vec = xinput[i]; */ + uint64x2_t data_vec_1 = XXH_vld1q_u64(xinput + (i * 16)); + uint64x2_t data_vec_2 = XXH_vld1q_u64(xinput + ((i+1) * 16)); + /* key_vec = xsecret[i]; */ + uint64x2_t key_vec_1 = XXH_vld1q_u64(xsecret + (i * 16)); + uint64x2_t key_vec_2 = XXH_vld1q_u64(xsecret + ((i+1) * 16)); + /* data_swap = swap(data_vec) */ + uint64x2_t data_swap_1 = vextq_u64(data_vec_1, data_vec_1, 1); + uint64x2_t data_swap_2 = vextq_u64(data_vec_2, data_vec_2, 1); + /* data_key = data_vec ^ key_vec; */ + uint64x2_t data_key_1 = veorq_u64(data_vec_1, key_vec_1); + uint64x2_t data_key_2 = veorq_u64(data_vec_2, key_vec_2); + + /* + * If we reinterpret the 64x2 vectors as 32x4 vectors, we can use a + * de-interleave operation for 4 lanes in 1 step with `vuzpq_u32` to + * get one vector with the low 32 bits of each lane, and one vector + * with the high 32 bits of each lane. + * + * The intrinsic returns a double vector because the original ARMv7-a + * instruction modified both arguments in place. AArch64 and SIMD128 emit + * two instructions from this intrinsic. + * + * [ dk11L | dk11H | dk12L | dk12H ] -> [ dk11L | dk12L | dk21L | dk22L ] + * [ dk21L | dk21H | dk22L | dk22H ] -> [ dk11H | dk12H | dk21H | dk22H ] + */ + uint32x4x2_t unzipped = vuzpq_u32( + vreinterpretq_u32_u64(data_key_1), + vreinterpretq_u32_u64(data_key_2) + ); + /* data_key_lo = data_key & 0xFFFFFFFF */ + uint32x4_t data_key_lo = unzipped.val[0]; + /* data_key_hi = data_key >> 32 */ + uint32x4_t data_key_hi = unzipped.val[1]; + /* + * Then, we can split the vectors horizontally and multiply which, as for most + * widening intrinsics, have a variant that works on both high half vectors + * for free on AArch64. A similar instruction is available on SIMD128. + * + * sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi + */ + uint64x2_t sum_1 = XXH_vmlal_low_u32(data_swap_1, data_key_lo, data_key_hi); + uint64x2_t sum_2 = XXH_vmlal_high_u32(data_swap_2, data_key_lo, data_key_hi); + /* + * Clang reorders + * a += b * c; // umlal swap.2d, dkl.2s, dkh.2s + * c += a; // add acc.2d, acc.2d, swap.2d + * to + * c += a; // add acc.2d, acc.2d, swap.2d + * c += b * c; // umlal acc.2d, dkl.2s, dkh.2s + * + * While it would make sense in theory since the addition is faster, + * for reasons likely related to umlal being limited to certain NEON + * pipelines, this is worse. A compiler guard fixes this. + */ + XXH_COMPILER_GUARD_CLANG_NEON(sum_1); + XXH_COMPILER_GUARD_CLANG_NEON(sum_2); + /* xacc[i] = acc_vec + sum; */ + xacc[i] = vaddq_u64(xacc[i], sum_1); + xacc[i+1] = vaddq_u64(xacc[i+1], sum_2); + } + /* Operate on the remaining NEON lanes 2 at a time. */ + for (; i < XXH3_NEON_LANES / 2; i++) { + /* data_vec = xinput[i]; */ + uint64x2_t data_vec = XXH_vld1q_u64(xinput + (i * 16)); + /* key_vec = xsecret[i]; */ + uint64x2_t key_vec = XXH_vld1q_u64(xsecret + (i * 16)); + /* acc_vec_2 = swap(data_vec) */ + uint64x2_t data_swap = vextq_u64(data_vec, data_vec, 1); + /* data_key = data_vec ^ key_vec; */ + uint64x2_t data_key = veorq_u64(data_vec, key_vec); + /* For two lanes, just use VMOVN and VSHRN. */ + /* data_key_lo = data_key & 0xFFFFFFFF; */ + uint32x2_t data_key_lo = vmovn_u64(data_key); + /* data_key_hi = data_key >> 32; */ + uint32x2_t data_key_hi = vshrn_n_u64(data_key, 32); + /* sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi; */ + uint64x2_t sum = vmlal_u32(data_swap, data_key_lo, data_key_hi); + /* Same Clang workaround as before */ + XXH_COMPILER_GUARD_CLANG_NEON(sum); + /* xacc[i] = acc_vec + sum; */ + xacc[i] = vaddq_u64 (xacc[i], sum); + } + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(neon) + +XXH_FORCE_INLINE void +XXH3_scrambleAcc_neon(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + + { xxh_aliasing_uint64x2_t* xacc = (xxh_aliasing_uint64x2_t*) acc; + uint8_t const* xsecret = (uint8_t const*) secret; + + size_t i; + /* WASM uses operator overloads and doesn't need these. */ +#ifndef __wasm_simd128__ + /* { prime32_1, prime32_1 } */ + uint32x2_t const kPrimeLo = vdup_n_u32(XXH_PRIME32_1); + /* { 0, prime32_1, 0, prime32_1 } */ + uint32x4_t const kPrimeHi = vreinterpretq_u32_u64(vdupq_n_u64((xxh_u64)XXH_PRIME32_1 << 32)); +#endif + + /* AArch64 uses both scalar and neon at the same time */ + for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) { + XXH3_scalarScrambleRound(acc, secret, i); + } + for (i=0; i < XXH3_NEON_LANES / 2; i++) { + /* xacc[i] ^= (xacc[i] >> 47); */ + uint64x2_t acc_vec = xacc[i]; + uint64x2_t shifted = vshrq_n_u64(acc_vec, 47); + uint64x2_t data_vec = veorq_u64(acc_vec, shifted); + + /* xacc[i] ^= xsecret[i]; */ + uint64x2_t key_vec = XXH_vld1q_u64(xsecret + (i * 16)); + uint64x2_t data_key = veorq_u64(data_vec, key_vec); + /* xacc[i] *= XXH_PRIME32_1 */ +#ifdef __wasm_simd128__ + /* SIMD128 has multiply by u64x2, use it instead of expanding and scalarizing */ + xacc[i] = data_key * XXH_PRIME32_1; +#else + /* + * Expanded version with portable NEON intrinsics + * + * lo(x) * lo(y) + (hi(x) * lo(y) << 32) + * + * prod_hi = hi(data_key) * lo(prime) << 32 + * + * Since we only need 32 bits of this multiply a trick can be used, reinterpreting the vector + * as a uint32x4_t and multiplying by { 0, prime, 0, prime } to cancel out the unwanted bits + * and avoid the shift. + */ + uint32x4_t prod_hi = vmulq_u32 (vreinterpretq_u32_u64(data_key), kPrimeHi); + /* Extract low bits for vmlal_u32 */ + uint32x2_t data_key_lo = vmovn_u64(data_key); + /* xacc[i] = prod_hi + lo(data_key) * XXH_PRIME32_1; */ + xacc[i] = vmlal_u32(vreinterpretq_u64_u32(prod_hi), data_key_lo, kPrimeLo); +#endif + } + } +} +#endif + +#if (XXH_VECTOR == XXH_VSX) + +XXH_FORCE_INLINE void +XXH3_accumulate_512_vsx( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + /* presumed aligned */ + xxh_aliasing_u64x2* const xacc = (xxh_aliasing_u64x2*) acc; + xxh_u8 const* const xinput = (xxh_u8 const*) input; /* no alignment restriction */ + xxh_u8 const* const xsecret = (xxh_u8 const*) secret; /* no alignment restriction */ + xxh_u64x2 const v32 = { 32, 32 }; + size_t i; + for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) { + /* data_vec = xinput[i]; */ + xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + 16*i); + /* key_vec = xsecret[i]; */ + xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + 16*i); + xxh_u64x2 const data_key = data_vec ^ key_vec; + /* shuffled = (data_key << 32) | (data_key >> 32); */ + xxh_u32x4 const shuffled = (xxh_u32x4)vec_rl(data_key, v32); + /* product = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)shuffled & 0xFFFFFFFF); */ + xxh_u64x2 const product = XXH_vec_mulo((xxh_u32x4)data_key, shuffled); + /* acc_vec = xacc[i]; */ + xxh_u64x2 acc_vec = xacc[i]; + acc_vec += product; + + /* swap high and low halves */ +#ifdef __s390x__ + acc_vec += vec_permi(data_vec, data_vec, 2); +#else + acc_vec += vec_xxpermdi(data_vec, data_vec, 2); +#endif + xacc[i] = acc_vec; + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(vsx) + +XXH_FORCE_INLINE void +XXH3_scrambleAcc_vsx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + + { xxh_aliasing_u64x2* const xacc = (xxh_aliasing_u64x2*) acc; + const xxh_u8* const xsecret = (const xxh_u8*) secret; + /* constants */ + xxh_u64x2 const v32 = { 32, 32 }; + xxh_u64x2 const v47 = { 47, 47 }; + xxh_u32x4 const prime = { XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1 }; + size_t i; + for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) { + /* xacc[i] ^= (xacc[i] >> 47); */ + xxh_u64x2 const acc_vec = xacc[i]; + xxh_u64x2 const data_vec = acc_vec ^ (acc_vec >> v47); + + /* xacc[i] ^= xsecret[i]; */ + xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + 16*i); + xxh_u64x2 const data_key = data_vec ^ key_vec; + + /* xacc[i] *= XXH_PRIME32_1 */ + /* prod_lo = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)prime & 0xFFFFFFFF); */ + xxh_u64x2 const prod_even = XXH_vec_mule((xxh_u32x4)data_key, prime); + /* prod_hi = ((xxh_u64x2)data_key >> 32) * ((xxh_u64x2)prime >> 32); */ + xxh_u64x2 const prod_odd = XXH_vec_mulo((xxh_u32x4)data_key, prime); + xacc[i] = prod_odd + (prod_even << v32); + } } +} + +#endif + +#if (XXH_VECTOR == XXH_SVE) + +XXH_FORCE_INLINE void +XXH3_accumulate_512_sve( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + uint64_t *xacc = (uint64_t *)acc; + const uint64_t *xinput = (const uint64_t *)(const void *)input; + const uint64_t *xsecret = (const uint64_t *)(const void *)secret; + svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1); + uint64_t element_count = svcntd(); + if (element_count >= 8) { + svbool_t mask = svptrue_pat_b64(SV_VL8); + svuint64_t vacc = svld1_u64(mask, xacc); + ACCRND(vacc, 0); + svst1_u64(mask, xacc, vacc); + } else if (element_count == 2) { /* sve128 */ + svbool_t mask = svptrue_pat_b64(SV_VL2); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 2); + svuint64_t acc2 = svld1_u64(mask, xacc + 4); + svuint64_t acc3 = svld1_u64(mask, xacc + 6); + ACCRND(acc0, 0); + ACCRND(acc1, 2); + ACCRND(acc2, 4); + ACCRND(acc3, 6); + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 2, acc1); + svst1_u64(mask, xacc + 4, acc2); + svst1_u64(mask, xacc + 6, acc3); + } else { + svbool_t mask = svptrue_pat_b64(SV_VL4); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 4); + ACCRND(acc0, 0); + ACCRND(acc1, 4); + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 4, acc1); + } +} + +XXH_FORCE_INLINE void +XXH3_accumulate_sve(xxh_u64* XXH_RESTRICT acc, + const xxh_u8* XXH_RESTRICT input, + const xxh_u8* XXH_RESTRICT secret, + size_t nbStripes) +{ + if (nbStripes != 0) { + uint64_t *xacc = (uint64_t *)acc; + const uint64_t *xinput = (const uint64_t *)(const void *)input; + const uint64_t *xsecret = (const uint64_t *)(const void *)secret; + svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1); + uint64_t element_count = svcntd(); + if (element_count >= 8) { + svbool_t mask = svptrue_pat_b64(SV_VL8); + svuint64_t vacc = svld1_u64(mask, xacc + 0); + do { + /* svprfd(svbool_t, void *, enum svfprop); */ + svprfd(mask, xinput + 128, SV_PLDL1STRM); + ACCRND(vacc, 0); + xinput += 8; + xsecret += 1; + nbStripes--; + } while (nbStripes != 0); + + svst1_u64(mask, xacc + 0, vacc); + } else if (element_count == 2) { /* sve128 */ + svbool_t mask = svptrue_pat_b64(SV_VL2); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 2); + svuint64_t acc2 = svld1_u64(mask, xacc + 4); + svuint64_t acc3 = svld1_u64(mask, xacc + 6); + do { + svprfd(mask, xinput + 128, SV_PLDL1STRM); + ACCRND(acc0, 0); + ACCRND(acc1, 2); + ACCRND(acc2, 4); + ACCRND(acc3, 6); + xinput += 8; + xsecret += 1; + nbStripes--; + } while (nbStripes != 0); + + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 2, acc1); + svst1_u64(mask, xacc + 4, acc2); + svst1_u64(mask, xacc + 6, acc3); + } else { + svbool_t mask = svptrue_pat_b64(SV_VL4); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 4); + do { + svprfd(mask, xinput + 128, SV_PLDL1STRM); + ACCRND(acc0, 0); + ACCRND(acc1, 4); + xinput += 8; + xsecret += 1; + nbStripes--; + } while (nbStripes != 0); + + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 4, acc1); + } + } +} + +#endif + +#if (XXH_VECTOR == XXH_LSX) +#define _LSX_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w)) + +XXH_FORCE_INLINE void +XXH3_accumulate_512_lsx( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + { + __m128i* const xacc = (__m128i *) acc; + const __m128i* const xinput = (const __m128i *) input; + const __m128i* const xsecret = (const __m128i *) secret; + + for (size_t i = 0; i < XXH_STRIPE_LEN / sizeof(__m128i); i++) { + /* data_vec = xinput[i]; */ + __m128i const data_vec = __lsx_vld(xinput + i, 0); + /* key_vec = xsecret[i]; */ + __m128i const key_vec = __lsx_vld(xsecret + i, 0); + /* data_key = data_vec ^ key_vec; */ + __m128i const data_key = __lsx_vxor_v(data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m128i const data_key_lo = __lsx_vsrli_d(data_key, 32); + // __m128i const data_key_lo = __lsx_vsrli_d(data_key, 32); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m128i const product = __lsx_vmulwev_d_wu(data_key, data_key_lo); + /* xacc[i] += swap(data_vec); */ + __m128i const data_swap = __lsx_vshuf4i_w(data_vec, _LSX_SHUFFLE(1, 0, 3, 2)); + __m128i const sum = __lsx_vadd_d(xacc[i], data_swap); + /* xacc[i] += product; */ + xacc[i] = __lsx_vadd_d(product, sum); + } + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(lsx) + +XXH_FORCE_INLINE void +XXH3_scrambleAcc_lsx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + { + __m128i* const xacc = (__m128i*) acc; + const __m128i* const xsecret = (const __m128i *) secret; + const __m128i prime32 = __lsx_vreplgr2vr_d(XXH_PRIME32_1); + + for (size_t i = 0; i < XXH_STRIPE_LEN / sizeof(__m128i); i++) { + /* xacc[i] ^= (xacc[i] >> 47) */ + __m128i const acc_vec = xacc[i]; + __m128i const shifted = __lsx_vsrli_d(acc_vec, 47); + __m128i const data_vec = __lsx_vxor_v(acc_vec, shifted); + /* xacc[i] ^= xsecret[i]; */ + __m128i const key_vec = __lsx_vld(xsecret + i, 0); + __m128i const data_key = __lsx_vxor_v(data_vec, key_vec); + + /* xacc[i] *= XXH_PRIME32_1; */ + xacc[i] = __lsx_vmul_d(data_key, prime32); + } + } +} + +#endif + +#if (XXH_VECTOR == XXH_LASX) +#define _LASX_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w)) + +XXH_FORCE_INLINE void +XXH3_accumulate_512_lasx( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 31) == 0); + { + __m256i* const xacc = (__m256i *) acc; + const __m256i* const xinput = (const __m256i *) input; + const __m256i* const xsecret = (const __m256i *) secret; + + for (size_t i = 0; i < XXH_STRIPE_LEN / sizeof(__m256i); i++) { + /* data_vec = xinput[i]; */ + __m256i const data_vec = __lasx_xvld(xinput + i, 0); + /* key_vec = xsecret[i]; */ + __m256i const key_vec = __lasx_xvld(xsecret + i, 0); + /* data_key = data_vec ^ key_vec; */ + __m256i const data_key = __lasx_xvxor_v(data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m256i const data_key_lo = __lasx_xvsrli_d(data_key, 32); + // __m256i const data_key_lo = __lasx_xvsrli_d(data_key, 32); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m256i const product = __lasx_xvmulwev_d_wu(data_key, data_key_lo); + /* xacc[i] += swap(data_vec); */ + __m256i const data_swap = __lasx_xvshuf4i_w(data_vec, _LASX_SHUFFLE(1, 0, 3, 2)); + __m256i const sum = __lasx_xvadd_d(xacc[i], data_swap); + /* xacc[i] += product; */ + xacc[i] = __lasx_xvadd_d(product, sum); + } + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(lasx) + +XXH_FORCE_INLINE void +XXH3_scrambleAcc_lasx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 31) == 0); + { + __m256i* const xacc = (__m256i*) acc; + const __m256i* const xsecret = (const __m256i *) secret; + const __m256i prime32 = __lasx_xvreplgr2vr_d(XXH_PRIME32_1); + + for (size_t i = 0; i < XXH_STRIPE_LEN / sizeof(__m256i); i++) { + /* xacc[i] ^= (xacc[i] >> 47) */ + __m256i const acc_vec = xacc[i]; + __m256i const shifted = __lasx_xvsrli_d(acc_vec, 47); + __m256i const data_vec = __lasx_xvxor_v(acc_vec, shifted); + /* xacc[i] ^= xsecret[i]; */ + __m256i const key_vec = __lasx_xvld(xsecret + i, 0); + __m256i const data_key = __lasx_xvxor_v(data_vec, key_vec); + + /* xacc[i] *= XXH_PRIME32_1; */ + xacc[i] = __lasx_xvmul_d(data_key, prime32); + } + } +} + +#endif + +#if (XXH_VECTOR == XXH_RVV) +#if ((defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 13) || \ + (defined(__clang__) && __clang_major__ < 16)) + #define RVV_OP(op) op +#else + #define concat2(X, Y) X ## Y + #define concat(X, Y) concat2(X, Y) + #define RVV_OP(op) concat(__riscv_, op) +#endif +XXH_FORCE_INLINE void +XXH3_accumulate_512_rvv( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 63) == 0); + { + // Try to set vector lenght to 512 bits. + // If this length is unavailable, then maximum available will be used + size_t vl = RVV_OP(vsetvl_e64m2)(8); + + uint64_t* const xacc = (uint64_t*) acc; + const uint64_t* const xinput = (const uint64_t*) input; + const uint64_t* const xsecret = (const uint64_t*) secret; + uint64_t swap_mask[16] = {1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14}; + vuint64m2_t xswap_mask = RVV_OP(vle64_v_u64m2)(swap_mask, vl); + + // vuint64m1_t is sizeless. + // But we can assume that vl can be only 4(vlen=128) or 8(vlen=256,512) + for(size_t i = 0; i < XXH_STRIPE_LEN/(8 * vl); i++){ + /* data_vec = input[i]; */ + vuint64m2_t data_vec = RVV_OP(vreinterpret_v_u8m2_u64m2)(RVV_OP(vle8_v_u8m2)((const uint8_t*)(xinput + vl * i), vl * 8)); + /* key_vec = secret[i]; */ + vuint64m2_t key_vec = RVV_OP(vreinterpret_v_u8m2_u64m2)(RVV_OP(vle8_v_u8m2)((const uint8_t*)(xsecret + vl * i), vl * 8)); + /* data_key = data_vec ^ key_vec; */ + vuint64m2_t data_key = RVV_OP(vxor_vv_u64m2)(data_vec, key_vec, vl); + /* data_key_lo = data_key >> 32; */ + vuint64m2_t data_key_lo = RVV_OP(vsrl_vx_u64m2)(data_key, 32, vl); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + vuint64m2_t product = RVV_OP(vmul_vv_u64m2)(RVV_OP(vand_vx_u64m2)(data_key, 0xffffffff, vl), RVV_OP(vand_vx_u64m2)(data_key_lo, 0xffffffff, vl), vl); + /* acc_vec = xacc[i]; */ + vuint64m2_t acc_vec = RVV_OP(vle64_v_u64m2)(xacc + vl * i, vl); + acc_vec = RVV_OP(vadd_vv_u64m2)(acc_vec, product, vl); + { + /* swap high and low halves */ + vuint64m2_t data_swap = RVV_OP(vrgather_vv_u64m2)(data_vec, xswap_mask, vl); + acc_vec = RVV_OP(vadd_vv_u64m2)(acc_vec, data_swap, vl); + } + RVV_OP(vse64_v_u64m2)(xacc + vl * i, acc_vec, vl); + } + } +} + +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(rvv) + +XXH_FORCE_INLINE void +XXH3_scrambleAcc_rvv(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 63) == 0); + { + // Try to set vector lenght to 512 bits. + // If this length is unavailable, then maximum available will be used + size_t vl = RVV_OP(vsetvl_e64m2)(8); + uint64_t* const xacc = (uint64_t*) acc; + const uint64_t* const xsecret = (const uint64_t*) secret; + + uint64_t prime[16] = {XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1,\ + XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1}; + vuint64m2_t vprime = RVV_OP(vle64_v_u64m2)(prime, vl); + + // vuint64m2_t is sizeless. + // But we can assume that vl can be only 4(vlen=128) or 8(vlen=256,512) + for(size_t i = 0; i < XXH_STRIPE_LEN/(8 * vl); i++){ + /* xacc[i] ^= (xacc[i] >> 47) */ + vuint64m2_t acc_vec = RVV_OP(vle64_v_u64m2)(xacc + vl * i, vl); + vuint64m2_t shifted = RVV_OP(vsrl_vx_u64m2)(acc_vec, 47, vl); + vuint64m2_t data_vec = RVV_OP(vxor_vv_u64m2)(acc_vec, shifted, vl); + /* xacc[i] ^= xsecret[i]; */ + vuint64m2_t key_vec = RVV_OP(vreinterpret_v_u8m2_u64m2)(RVV_OP(vle8_v_u8m2)((const uint8_t*)(xsecret + vl * i), vl * 8)); + vuint64m2_t data_key = RVV_OP(vxor_vv_u64m2)(data_vec, key_vec, vl); + + /* xacc[i] *= XXH_PRIME32_1; */ + vuint64m2_t prod_even = RVV_OP(vmul_vv_u64m2)(RVV_OP(vand_vx_u64m2)(data_key, 0xffffffff, vl), vprime, vl); + vuint64m2_t prod_odd = RVV_OP(vmul_vv_u64m2)(RVV_OP(vsrl_vx_u64m2)(data_key, 32, vl), vprime, vl); + vuint64m2_t prod = RVV_OP(vadd_vv_u64m2)(prod_even, RVV_OP(vsll_vx_u64m2)(prod_odd, 32, vl), vl); + RVV_OP(vse64_v_u64m2)(xacc + vl * i, prod, vl); + } + } +} + +XXH_FORCE_INLINE void +XXH3_initCustomSecret_rvv(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 63) == 0); + XXH_STATIC_ASSERT(XXH_SEC_ALIGN == 64); + XXH_ASSERT(((size_t)customSecret & 63) == 0); + { + uint64_t* const xcustomSecret = (uint64_t*)customSecret; + + (void)(&XXH_writeLE64); + { + // Calculate the number of 64-bit elements in the `XXH3_kSecret` secret + size_t XXH3_kSecret_64b_len = XXH_SECRET_DEFAULT_SIZE / 8; + // Create an array of repeated seed values, alternating between seed64 and -seed64. + uint64_t seed_pos[16] = {seed64, (uint64_t)(-(int64_t)seed64), \ + seed64, (uint64_t)(-(int64_t)seed64), \ + seed64, (uint64_t)(-(int64_t)seed64), \ + seed64, (uint64_t)(-(int64_t)seed64), \ + seed64, (uint64_t)(-(int64_t)seed64), \ + seed64, (uint64_t)(-(int64_t)seed64), \ + seed64, (uint64_t)(-(int64_t)seed64), \ + seed64, (uint64_t)(-(int64_t)seed64)}; + // Cast the default secret to a signed 64-bit pointer for vectorized access + const int64_t* const xXXH3_kSecret = (const int64_t*)((const void*)XXH3_kSecret); + size_t vl = 0; + for (size_t i=0; i < XXH3_kSecret_64b_len; i += vl) { + + vl = RVV_OP(vsetvl_e64m2)(XXH3_kSecret_64b_len - i); + { + vint64m2_t seed = RVV_OP(vle64_v_i64m2)((int64_t*)seed_pos, vl); + vint64m2_t src = RVV_OP(vle64_v_i64m2)((const int64_t*)&xXXH3_kSecret[i], vl); + vint64m2_t res = RVV_OP(vadd_vv_i64m2)(src, seed, vl); + RVV_OP(vse64_v_i64m2)((int64_t*)&xcustomSecret[i], res, vl); + } + } + } + } +} +#endif + + +/* scalar variants - universal */ + +#if defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__)) +/* + * In XXH3_scalarRound(), GCC and Clang have a similar codegen issue, where they + * emit an excess mask and a full 64-bit multiply-add (MADD X-form). + * + * While this might not seem like much, as AArch64 is a 64-bit architecture, only + * big Cortex designs have a full 64-bit multiplier. + * + * On the little cores, the smaller 32-bit multiplier is used, and full 64-bit + * multiplies expand to 2-3 multiplies in microcode. This has a major penalty + * of up to 4 latency cycles and 2 stall cycles in the multiply pipeline. + * + * Thankfully, AArch64 still provides the 32-bit long multiply-add (UMADDL) which does + * not have this penalty and does the mask automatically. + */ +XXH_FORCE_INLINE xxh_u64 +XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc) +{ + xxh_u64 ret; + /* note: %x = 64-bit register, %w = 32-bit register */ + __asm__("umaddl %x0, %w1, %w2, %x3" : "=r" (ret) : "r" (lhs), "r" (rhs), "r" (acc)); + return ret; +} +#else +XXH_FORCE_INLINE xxh_u64 +XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc) +{ + return XXH_mult32to64((xxh_u32)lhs, (xxh_u32)rhs) + acc; +} +#endif + +/*! + * @internal + * @brief Scalar round for @ref XXH3_accumulate_512_scalar(). + * + * This is extracted to its own function because the NEON path uses a combination + * of NEON and scalar. + */ +XXH_FORCE_INLINE void +XXH3_scalarRound(void* XXH_RESTRICT acc, + void const* XXH_RESTRICT input, + void const* XXH_RESTRICT secret, + size_t lane) +{ + xxh_u64* xacc = (xxh_u64*) acc; + xxh_u8 const* xinput = (xxh_u8 const*) input; + xxh_u8 const* xsecret = (xxh_u8 const*) secret; + XXH_ASSERT(lane < XXH_ACC_NB); + XXH_ASSERT(((size_t)acc & (XXH_ACC_ALIGN-1)) == 0); + { + xxh_u64 const data_val = XXH_readLE64(xinput + lane * 8); + xxh_u64 const data_key = data_val ^ XXH_readLE64(xsecret + lane * 8); + xacc[lane ^ 1] += data_val; /* swap adjacent lanes */ + xacc[lane] = XXH_mult32to64_add64(data_key /* & 0xFFFFFFFF */, data_key >> 32, xacc[lane]); + } +} + +/*! + * @internal + * @brief Processes a 64 byte block of data using the scalar path. + */ +XXH_FORCE_INLINE void +XXH3_accumulate_512_scalar(void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + size_t i; + /* ARM GCC refuses to unroll this loop, resulting in a 24% slowdown on ARMv6. */ +#if defined(__GNUC__) && !defined(__clang__) \ + && (defined(__arm__) || defined(__thumb2__)) \ + && defined(__ARM_FEATURE_UNALIGNED) /* no unaligned access just wastes bytes */ \ + && XXH_SIZE_OPT <= 0 +# pragma GCC unroll 8 +#endif + for (i=0; i < XXH_ACC_NB; i++) { + XXH3_scalarRound(acc, input, secret, i); + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(scalar) + +/*! + * @internal + * @brief Scalar scramble step for @ref XXH3_scrambleAcc_scalar(). + * + * This is extracted to its own function because the NEON path uses a combination + * of NEON and scalar. + */ +XXH_FORCE_INLINE void +XXH3_scalarScrambleRound(void* XXH_RESTRICT acc, + void const* XXH_RESTRICT secret, + size_t lane) +{ + xxh_u64* const xacc = (xxh_u64*) acc; /* presumed aligned */ + const xxh_u8* const xsecret = (const xxh_u8*) secret; /* no alignment restriction */ + XXH_ASSERT((((size_t)acc) & (XXH_ACC_ALIGN-1)) == 0); + XXH_ASSERT(lane < XXH_ACC_NB); + { + xxh_u64 const key64 = XXH_readLE64(xsecret + lane * 8); + xxh_u64 acc64 = xacc[lane]; + acc64 = XXH_xorshift64(acc64, 47); + acc64 ^= key64; + acc64 *= XXH_PRIME32_1; + xacc[lane] = acc64; + } +} + +/*! + * @internal + * @brief Scrambles the accumulators after a large chunk has been read + */ +XXH_FORCE_INLINE void +XXH3_scrambleAcc_scalar(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + size_t i; + for (i=0; i < XXH_ACC_NB; i++) { + XXH3_scalarScrambleRound(acc, secret, i); + } +} + +XXH_FORCE_INLINE void +XXH3_initCustomSecret_scalar(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + /* + * We need a separate pointer for the hack below, + * which requires a non-const pointer. + * Any decent compiler will optimize this out otherwise. + */ + const xxh_u8* kSecretPtr = XXH3_kSecret; + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0); + +#if defined(__GNUC__) && defined(__aarch64__) + /* + * UGLY HACK: + * GCC and Clang generate a bunch of MOV/MOVK pairs for aarch64, and they are + * placed sequentially, in order, at the top of the unrolled loop. + * + * While MOVK is great for generating constants (2 cycles for a 64-bit + * constant compared to 4 cycles for LDR), it fights for bandwidth with + * the arithmetic instructions. + * + * I L S + * MOVK + * MOVK + * MOVK + * MOVK + * ADD + * SUB STR + * STR + * By forcing loads from memory (as the asm line causes the compiler to assume + * that XXH3_kSecretPtr has been changed), the pipelines are used more + * efficiently: + * I L S + * LDR + * ADD LDR + * SUB STR + * STR + * + * See XXH3_NEON_LANES for details on the pipeline. + * + * XXH3_64bits_withSeed, len == 256, Snapdragon 835 + * without hack: 2654.4 MB/s + * with hack: 3202.9 MB/s + */ + XXH_COMPILER_GUARD(kSecretPtr); +#endif + { int const nbRounds = XXH_SECRET_DEFAULT_SIZE / 16; + int i; + for (i=0; i < nbRounds; i++) { + /* + * The asm hack causes the compiler to assume that kSecretPtr aliases with + * customSecret, and on aarch64, this prevented LDP from merging two + * loads together for free. Putting the loads together before the stores + * properly generates LDP. + */ + xxh_u64 lo = XXH_readLE64(kSecretPtr + 16*i) + seed64; + xxh_u64 hi = XXH_readLE64(kSecretPtr + 16*i + 8) - seed64; + XXH_writeLE64((xxh_u8*)customSecret + 16*i, lo); + XXH_writeLE64((xxh_u8*)customSecret + 16*i + 8, hi); + } } +} + + +typedef void (*XXH3_f_accumulate)(xxh_u64* XXH_RESTRICT, const xxh_u8* XXH_RESTRICT, const xxh_u8* XXH_RESTRICT, size_t); +typedef void (*XXH3_f_scrambleAcc)(void* XXH_RESTRICT, const void*); +typedef void (*XXH3_f_initCustomSecret)(void* XXH_RESTRICT, xxh_u64); + + +#if (XXH_VECTOR == XXH_AVX512) + +#define XXH3_accumulate_512 XXH3_accumulate_512_avx512 +#define XXH3_accumulate XXH3_accumulate_avx512 +#define XXH3_scrambleAcc XXH3_scrambleAcc_avx512 +#define XXH3_initCustomSecret XXH3_initCustomSecret_avx512 + +#elif (XXH_VECTOR == XXH_AVX2) + +#define XXH3_accumulate_512 XXH3_accumulate_512_avx2 +#define XXH3_accumulate XXH3_accumulate_avx2 +#define XXH3_scrambleAcc XXH3_scrambleAcc_avx2 +#define XXH3_initCustomSecret XXH3_initCustomSecret_avx2 + +#elif (XXH_VECTOR == XXH_SSE2) + +#define XXH3_accumulate_512 XXH3_accumulate_512_sse2 +#define XXH3_accumulate XXH3_accumulate_sse2 +#define XXH3_scrambleAcc XXH3_scrambleAcc_sse2 +#define XXH3_initCustomSecret XXH3_initCustomSecret_sse2 + +#elif (XXH_VECTOR == XXH_NEON) + +#define XXH3_accumulate_512 XXH3_accumulate_512_neon +#define XXH3_accumulate XXH3_accumulate_neon +#define XXH3_scrambleAcc XXH3_scrambleAcc_neon +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#elif (XXH_VECTOR == XXH_VSX) + +#define XXH3_accumulate_512 XXH3_accumulate_512_vsx +#define XXH3_accumulate XXH3_accumulate_vsx +#define XXH3_scrambleAcc XXH3_scrambleAcc_vsx +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#elif (XXH_VECTOR == XXH_SVE) +#define XXH3_accumulate_512 XXH3_accumulate_512_sve +#define XXH3_accumulate XXH3_accumulate_sve +#define XXH3_scrambleAcc XXH3_scrambleAcc_scalar +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#elif (XXH_VECTOR == XXH_LASX) +#define XXH3_accumulate_512 XXH3_accumulate_512_lasx +#define XXH3_accumulate XXH3_accumulate_lasx +#define XXH3_scrambleAcc XXH3_scrambleAcc_lasx +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#elif (XXH_VECTOR == XXH_LSX) +#define XXH3_accumulate_512 XXH3_accumulate_512_lsx +#define XXH3_accumulate XXH3_accumulate_lsx +#define XXH3_scrambleAcc XXH3_scrambleAcc_lsx +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#elif (XXH_VECTOR == XXH_RVV) +#define XXH3_accumulate_512 XXH3_accumulate_512_rvv +#define XXH3_accumulate XXH3_accumulate_rvv +#define XXH3_scrambleAcc XXH3_scrambleAcc_rvv +#define XXH3_initCustomSecret XXH3_initCustomSecret_rvv + +#else /* scalar */ + +#define XXH3_accumulate_512 XXH3_accumulate_512_scalar +#define XXH3_accumulate XXH3_accumulate_scalar +#define XXH3_scrambleAcc XXH3_scrambleAcc_scalar +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#endif + +#if XXH_SIZE_OPT >= 1 /* don't do SIMD for initialization */ +# undef XXH3_initCustomSecret +# define XXH3_initCustomSecret XXH3_initCustomSecret_scalar +#endif + +XXH_FORCE_INLINE void +XXH3_hashLong_internal_loop(xxh_u64* XXH_RESTRICT acc, + const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + size_t const nbStripesPerBlock = (secretSize - XXH_STRIPE_LEN) / XXH_SECRET_CONSUME_RATE; + size_t const block_len = XXH_STRIPE_LEN * nbStripesPerBlock; + size_t const nb_blocks = (len - 1) / block_len; + + size_t n; + + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); + + for (n = 0; n < nb_blocks; n++) { + f_acc(acc, input + n*block_len, secret, nbStripesPerBlock); + f_scramble(acc, secret + secretSize - XXH_STRIPE_LEN); + } + + /* last partial block */ + XXH_ASSERT(len > XXH_STRIPE_LEN); + { size_t const nbStripes = ((len - 1) - (block_len * nb_blocks)) / XXH_STRIPE_LEN; + XXH_ASSERT(nbStripes <= (secretSize / XXH_SECRET_CONSUME_RATE)); + f_acc(acc, input + nb_blocks*block_len, secret, nbStripes); + + /* last stripe */ + { const xxh_u8* const p = input + len - XXH_STRIPE_LEN; +#define XXH_SECRET_LASTACC_START 7 /* not aligned on 8, last secret is different from acc & scrambler */ + XXH3_accumulate_512(acc, p, secret + secretSize - XXH_STRIPE_LEN - XXH_SECRET_LASTACC_START); + } } +} + +XXH_FORCE_INLINE xxh_u64 +XXH3_mix2Accs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret) +{ + return XXH3_mul128_fold64( + acc[0] ^ XXH_readLE64(secret), + acc[1] ^ XXH_readLE64(secret+8) ); +} + +static XXH_PUREF XXH64_hash_t +XXH3_mergeAccs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret, xxh_u64 start) +{ + xxh_u64 result64 = start; + size_t i = 0; + + for (i = 0; i < 4; i++) { + result64 += XXH3_mix2Accs(acc+2*i, secret + 16*i); +#if defined(__clang__) /* Clang */ \ + && (defined(__arm__) || defined(__thumb__)) /* ARMv7 */ \ + && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \ + && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */ + /* + * UGLY HACK: + * Prevent autovectorization on Clang ARMv7-a. Exact same problem as + * the one in XXH3_len_129to240_64b. Speeds up shorter keys > 240b. + * XXH3_64bits, len == 256, Snapdragon 835: + * without hack: 2063.7 MB/s + * with hack: 2560.7 MB/s + */ + XXH_COMPILER_GUARD(result64); +#endif + } + + return XXH3_avalanche(result64); +} + +/* do not align on 8, so that the secret is different from the accumulator */ +#define XXH_SECRET_MERGEACCS_START 11 + +static XXH_PUREF XXH64_hash_t +XXH3_finalizeLong_64b(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret, xxh_u64 len) +{ + return XXH3_mergeAccs(acc, secret + XXH_SECRET_MERGEACCS_START, len * XXH_PRIME64_1); +} + +#define XXH3_INIT_ACC { XXH_PRIME32_3, XXH_PRIME64_1, XXH_PRIME64_2, XXH_PRIME64_3, \ + XXH_PRIME64_4, XXH_PRIME32_2, XXH_PRIME64_5, XXH_PRIME32_1 } + +XXH_FORCE_INLINE XXH64_hash_t +XXH3_hashLong_64b_internal(const void* XXH_RESTRICT input, size_t len, + const void* XXH_RESTRICT secret, size_t secretSize, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC; + + XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, f_acc, f_scramble); + + /* converge into final hash */ + XXH_STATIC_ASSERT(sizeof(acc) == 64); + XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); + return XXH3_finalizeLong_64b(acc, (const xxh_u8*)secret, (xxh_u64)len); +} + +/* + * It's important for performance to transmit secret's size (when it's static) + * so that the compiler can properly optimize the vectorized loop. + * This makes a big performance difference for "medium" keys (<1 KB) when using AVX instruction set. + * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE + * breaks -Og, this is XXH_NO_INLINE. + */ +XXH3_WITH_SECRET_INLINE XXH64_hash_t +XXH3_hashLong_64b_withSecret(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; + return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate, XXH3_scrambleAcc); +} + +/* + * It's preferable for performance that XXH3_hashLong is not inlined, + * as it results in a smaller function for small data, easier to the instruction cache. + * Note that inside this no_inline function, we do inline the internal loop, + * and provide a statically defined secret size to allow optimization of vector loop. + */ +XXH_NO_INLINE XXH_PUREF XXH64_hash_t +XXH3_hashLong_64b_default(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; (void)secret; (void)secretLen; + return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate, XXH3_scrambleAcc); +} + +/* + * XXH3_hashLong_64b_withSeed(): + * Generate a custom key based on alteration of default XXH3_kSecret with the seed, + * and then use this key for long mode hashing. + * + * This operation is decently fast but nonetheless costs a little bit of time. + * Try to avoid it whenever possible (typically when seed==0). + * + * It's important for performance that XXH3_hashLong is not inlined. Not sure + * why (uop cache maybe?), but the difference is large and easily measurable. + */ +XXH_FORCE_INLINE XXH64_hash_t +XXH3_hashLong_64b_withSeed_internal(const void* input, size_t len, + XXH64_hash_t seed, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble, + XXH3_f_initCustomSecret f_initSec) +{ +#if XXH_SIZE_OPT <= 0 + if (seed == 0) + return XXH3_hashLong_64b_internal(input, len, + XXH3_kSecret, sizeof(XXH3_kSecret), + f_acc, f_scramble); +#endif + { XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE]; + f_initSec(secret, seed); + return XXH3_hashLong_64b_internal(input, len, secret, sizeof(secret), + f_acc, f_scramble); + } +} + +/* + * It's important for performance that XXH3_hashLong is not inlined. + */ +XXH_NO_INLINE XXH64_hash_t +XXH3_hashLong_64b_withSeed(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed, const xxh_u8* XXH_RESTRICT secret, size_t secretLen) +{ + (void)secret; (void)secretLen; + return XXH3_hashLong_64b_withSeed_internal(input, len, seed, + XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret); +} + + +typedef XXH64_hash_t (*XXH3_hashLong64_f)(const void* XXH_RESTRICT, size_t, + XXH64_hash_t, const xxh_u8* XXH_RESTRICT, size_t); + +XXH_FORCE_INLINE XXH64_hash_t +XXH3_64bits_internal(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen, + XXH3_hashLong64_f f_hashLong) +{ + XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN); + /* + * If an action is to be taken if `secretLen` condition is not respected, + * it should be done here. + * For now, it's a contract pre-condition. + * Adding a check and a branch here would cost performance at every hash. + * Also, note that function signature doesn't offer room to return an error. + */ + if (len <= 16) + return XXH3_len_0to16_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, seed64); + if (len <= 128) + return XXH3_len_17to128_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + if (len <= XXH3_MIDSIZE_MAX) + return XXH3_len_129to240_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + return f_hashLong(input, len, seed64, (const xxh_u8*)secret, secretLen); +} + + +/* === Public entry point === */ + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void* input, size_t length) +{ + return XXH3_64bits_internal(input, length, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_default); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t +XXH3_64bits_withSecret(XXH_NOESCAPE const void* input, size_t length, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + return XXH3_64bits_internal(input, length, 0, secret, secretSize, XXH3_hashLong_64b_withSecret); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t +XXH3_64bits_withSeed(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed) +{ + return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed); +} + +XXH_PUBLIC_API XXH64_hash_t +XXH3_64bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t length, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed) +{ + if (length <= XXH3_MIDSIZE_MAX) + return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL); + return XXH3_hashLong_64b_withSecret(input, length, seed, (const xxh_u8*)secret, secretSize); +} + + +/* === XXH3 streaming === */ +#ifndef XXH_NO_STREAM +/* + * Malloc's a pointer that is always aligned to @align. + * + * This must be freed with `XXH_alignedFree()`. + * + * malloc typically guarantees 16 byte alignment on 64-bit systems and 8 byte + * alignment on 32-bit. This isn't enough for the 32 byte aligned loads in AVX2 + * or on 32-bit, the 16 byte aligned loads in SSE2 and NEON. + * + * This underalignment previously caused a rather obvious crash which went + * completely unnoticed due to XXH3_createState() not actually being tested. + * Credit to RedSpah for noticing this bug. + * + * The alignment is done manually: Functions like posix_memalign or _mm_malloc + * are avoided: To maintain portability, we would have to write a fallback + * like this anyways, and besides, testing for the existence of library + * functions without relying on external build tools is impossible. + * + * The method is simple: Overallocate, manually align, and store the offset + * to the original behind the returned pointer. + * + * Align must be a power of 2 and 8 <= align <= 128. + */ +static XXH_MALLOCF void* XXH_alignedMalloc(size_t s, size_t align) +{ + XXH_ASSERT(align <= 128 && align >= 8); /* range check */ + XXH_ASSERT((align & (align-1)) == 0); /* power of 2 */ + XXH_ASSERT(s != 0 && s < (s + align)); /* empty/overflow */ + { /* Overallocate to make room for manual realignment and an offset byte */ + xxh_u8* base = (xxh_u8*)XXH_malloc(s + align); + if (base != NULL) { + /* + * Get the offset needed to align this pointer. + * + * Even if the returned pointer is aligned, there will always be + * at least one byte to store the offset to the original pointer. + */ + size_t offset = align - ((size_t)base & (align - 1)); /* base % align */ + /* Add the offset for the now-aligned pointer */ + xxh_u8* ptr = base + offset; + + XXH_ASSERT((size_t)ptr % align == 0); + + /* Store the offset immediately before the returned pointer. */ + ptr[-1] = (xxh_u8)offset; + return ptr; + } + return NULL; + } +} +/* + * Frees an aligned pointer allocated by XXH_alignedMalloc(). Don't pass + * normal malloc'd pointers, XXH_alignedMalloc has a specific data layout. + */ +static void XXH_alignedFree(void* p) +{ + if (p != NULL) { + xxh_u8* ptr = (xxh_u8*)p; + /* Get the offset byte we added in XXH_malloc. */ + xxh_u8 offset = ptr[-1]; + /* Free the original malloc'd pointer */ + xxh_u8* base = ptr - offset; + XXH_free(base); + } +} +/*! @ingroup XXH3_family */ +/*! + * @brief Allocate an @ref XXH3_state_t. + * + * @return An allocated pointer of @ref XXH3_state_t on success. + * @return `NULL` on failure. + * + * @note Must be freed with XXH3_freeState(). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void) +{ + XXH3_state_t* const state = (XXH3_state_t*)XXH_alignedMalloc(sizeof(XXH3_state_t), 64); + if (state==NULL) return NULL; + XXH3_INITSTATE(state); + return state; +} + +/*! @ingroup XXH3_family */ +/*! + * @brief Frees an @ref XXH3_state_t. + * + * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState(). + * + * @return @ref XXH_OK. + * + * @note Must be allocated with XXH3_createState(). + * + * @see @ref streaming_example "Streaming Example" + */ +XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr) +{ + XXH_alignedFree(statePtr); + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API void +XXH3_copyState(XXH_NOESCAPE XXH3_state_t* dst_state, XXH_NOESCAPE const XXH3_state_t* src_state) +{ + XXH_memcpy(dst_state, src_state, sizeof(*dst_state)); +} + +static void +XXH3_reset_internal(XXH3_state_t* statePtr, + XXH64_hash_t seed, + const void* secret, size_t secretSize) +{ + size_t const initStart = offsetof(XXH3_state_t, bufferedSize); + size_t const initLength = offsetof(XXH3_state_t, nbStripesPerBlock) - initStart; + XXH_ASSERT(offsetof(XXH3_state_t, nbStripesPerBlock) > initStart); + XXH_ASSERT(statePtr != NULL); + /* set members from bufferedSize to nbStripesPerBlock (excluded) to 0 */ + XXH_memset((char*)statePtr + initStart, 0, initLength); + statePtr->acc[0] = XXH_PRIME32_3; + statePtr->acc[1] = XXH_PRIME64_1; + statePtr->acc[2] = XXH_PRIME64_2; + statePtr->acc[3] = XXH_PRIME64_3; + statePtr->acc[4] = XXH_PRIME64_4; + statePtr->acc[5] = XXH_PRIME32_2; + statePtr->acc[6] = XXH_PRIME64_5; + statePtr->acc[7] = XXH_PRIME32_1; + statePtr->seed = seed; + statePtr->useSeed = (seed != 0); + statePtr->extSecret = (const unsigned char*)secret; + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); + statePtr->secretLimit = secretSize - XXH_STRIPE_LEN; + statePtr->nbStripesPerBlock = statePtr->secretLimit / XXH_SECRET_CONSUME_RATE; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr) +{ + if (statePtr == NULL) return XXH_ERROR; + XXH3_reset_internal(statePtr, 0, XXH3_kSecret, XXH_SECRET_DEFAULT_SIZE); + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + if (statePtr == NULL) return XXH_ERROR; + XXH3_reset_internal(statePtr, 0, secret, secretSize); + if (secret == NULL) return XXH_ERROR; + if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed) +{ + if (statePtr == NULL) return XXH_ERROR; + if (seed==0) return XXH3_64bits_reset(statePtr); + if ((seed != statePtr->seed) || (statePtr->extSecret != NULL)) + XXH3_initCustomSecret(statePtr->customSecret, seed); + XXH3_reset_internal(statePtr, seed, NULL, XXH_SECRET_DEFAULT_SIZE); + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed64) +{ + if (statePtr == NULL) return XXH_ERROR; + if (secret == NULL) return XXH_ERROR; + if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; + XXH3_reset_internal(statePtr, seed64, secret, secretSize); + statePtr->useSeed = 1; /* always, even if seed64==0 */ + return XXH_OK; +} + +/*! + * @internal + * @brief Processes a large input for XXH3_update() and XXH3_digest_long(). + * + * Unlike XXH3_hashLong_internal_loop(), this can process data that overlaps a block. + * + * @param acc Pointer to the 8 accumulator lanes + * @param nbStripesSoFarPtr In/out pointer to the number of leftover stripes in the block* + * @param nbStripesPerBlock Number of stripes in a block + * @param input Input pointer + * @param nbStripes Number of stripes to process + * @param secret Secret pointer + * @param secretLimit Offset of the last block in @p secret + * @param f_acc Pointer to an XXH3_accumulate implementation + * @param f_scramble Pointer to an XXH3_scrambleAcc implementation + * @return Pointer past the end of @p input after processing + */ +XXH_FORCE_INLINE const xxh_u8 * +XXH3_consumeStripes(xxh_u64* XXH_RESTRICT acc, + size_t* XXH_RESTRICT nbStripesSoFarPtr, size_t nbStripesPerBlock, + const xxh_u8* XXH_RESTRICT input, size_t nbStripes, + const xxh_u8* XXH_RESTRICT secret, size_t secretLimit, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + const xxh_u8* initialSecret = secret + *nbStripesSoFarPtr * XXH_SECRET_CONSUME_RATE; + /* Process full blocks */ + if (nbStripes >= (nbStripesPerBlock - *nbStripesSoFarPtr)) { + /* Process the initial partial block... */ + size_t nbStripesThisIter = nbStripesPerBlock - *nbStripesSoFarPtr; + + do { + /* Accumulate and scramble */ + f_acc(acc, input, initialSecret, nbStripesThisIter); + f_scramble(acc, secret + secretLimit); + input += nbStripesThisIter * XXH_STRIPE_LEN; + nbStripes -= nbStripesThisIter; + /* Then continue the loop with the full block size */ + nbStripesThisIter = nbStripesPerBlock; + initialSecret = secret; + } while (nbStripes >= nbStripesPerBlock); + *nbStripesSoFarPtr = 0; + } + /* Process a partial block */ + if (nbStripes > 0) { + f_acc(acc, input, initialSecret, nbStripes); + input += nbStripes * XXH_STRIPE_LEN; + *nbStripesSoFarPtr += nbStripes; + } + /* Return end pointer */ + return input; +} + +#ifndef XXH3_STREAM_USE_STACK +# if XXH_SIZE_OPT <= 0 && !defined(__clang__) /* clang doesn't need additional stack space */ +# define XXH3_STREAM_USE_STACK 1 +# endif +#endif +/* This function accepts f_acc and f_scramble as function pointers, + * making it possible to implement multiple variants with different acc & scramble stages. + * This is notably useful to implement multiple vector variants with different intrinsics. + */ +XXH_FORCE_INLINE XXH_errorcode +XXH3_update(XXH3_state_t* XXH_RESTRICT const state, + const xxh_u8* XXH_RESTRICT input, size_t len, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + if (input==NULL) { + XXH_ASSERT(len == 0); + return XXH_OK; + } + + XXH_ASSERT(state != NULL); + state->totalLen += len; + + /* small input : just fill in tmp buffer */ + XXH_ASSERT(state->bufferedSize <= XXH3_INTERNALBUFFER_SIZE); + if (len <= XXH3_INTERNALBUFFER_SIZE - state->bufferedSize) { + XXH_memcpy(state->buffer + state->bufferedSize, input, len); + state->bufferedSize += (XXH32_hash_t)len; + return XXH_OK; + } + + { const xxh_u8* const bEnd = input + len; + const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret; +#if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1 + /* For some reason, gcc and MSVC seem to suffer greatly + * when operating accumulators directly into state. + * Operating into stack space seems to enable proper optimization. + * clang, on the other hand, doesn't seem to need this trick */ + XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[8]; + XXH_memcpy(acc, state->acc, sizeof(acc)); +#else + xxh_u64* XXH_RESTRICT const acc = state->acc; +#endif + + /* total input is now > XXH3_INTERNALBUFFER_SIZE */ + #define XXH3_INTERNALBUFFER_STRIPES (XXH3_INTERNALBUFFER_SIZE / XXH_STRIPE_LEN) + XXH_STATIC_ASSERT(XXH3_INTERNALBUFFER_SIZE % XXH_STRIPE_LEN == 0); /* clean multiple */ + + /* + * Internal buffer is partially filled (always, except at beginning) + * Complete it, then consume it. + */ + if (state->bufferedSize) { + size_t const loadSize = XXH3_INTERNALBUFFER_SIZE - state->bufferedSize; + XXH_memcpy(state->buffer + state->bufferedSize, input, loadSize); + input += loadSize; + XXH3_consumeStripes(acc, + &state->nbStripesSoFar, state->nbStripesPerBlock, + state->buffer, XXH3_INTERNALBUFFER_STRIPES, + secret, state->secretLimit, + f_acc, f_scramble); + state->bufferedSize = 0; + } + XXH_ASSERT(input < bEnd); + if (bEnd - input > XXH3_INTERNALBUFFER_SIZE) { + size_t nbStripes = (size_t)(bEnd - 1 - input) / XXH_STRIPE_LEN; + input = XXH3_consumeStripes(acc, + &state->nbStripesSoFar, state->nbStripesPerBlock, + input, nbStripes, + secret, state->secretLimit, + f_acc, f_scramble); + XXH_memcpy(state->buffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN); + + } + /* Some remaining input (always) : buffer it */ + XXH_ASSERT(input < bEnd); + XXH_ASSERT(bEnd - input <= XXH3_INTERNALBUFFER_SIZE); + XXH_ASSERT(state->bufferedSize == 0); + XXH_memcpy(state->buffer, input, (size_t)(bEnd-input)); + state->bufferedSize = (XXH32_hash_t)(bEnd-input); +#if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1 + /* save stack accumulators into state */ + XXH_memcpy(state->acc, acc, sizeof(acc)); +#endif + } + + return XXH_OK; +} + +/* + * Both XXH3_64bits_update and XXH3_128bits_update use this routine. + */ +XXH_NO_INLINE XXH_errorcode +XXH3_update_regular(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len) +{ + return XXH3_update(state, (const xxh_u8*)input, len, + XXH3_accumulate, XXH3_scrambleAcc); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_update(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len) +{ + return XXH3_update_regular(state, input, len); +} + + +XXH_FORCE_INLINE void +XXH3_digest_long (XXH64_hash_t* acc, + const XXH3_state_t* state, + const unsigned char* secret) +{ + xxh_u8 lastStripe[XXH_STRIPE_LEN]; + const xxh_u8* lastStripePtr; + + /* + * Digest on a local copy. This way, the state remains unaltered, and it can + * continue ingesting more input afterwards. + */ + XXH_memcpy(acc, state->acc, sizeof(state->acc)); + if (state->bufferedSize >= XXH_STRIPE_LEN) { + /* Consume remaining stripes then point to remaining data in buffer */ + size_t const nbStripes = (state->bufferedSize - 1) / XXH_STRIPE_LEN; + size_t nbStripesSoFar = state->nbStripesSoFar; + XXH3_consumeStripes(acc, + &nbStripesSoFar, state->nbStripesPerBlock, + state->buffer, nbStripes, + secret, state->secretLimit, + XXH3_accumulate, XXH3_scrambleAcc); + lastStripePtr = state->buffer + state->bufferedSize - XXH_STRIPE_LEN; + } else { /* bufferedSize < XXH_STRIPE_LEN */ + /* Copy to temp buffer */ + size_t const catchupSize = XXH_STRIPE_LEN - state->bufferedSize; + XXH_ASSERT(state->bufferedSize > 0); /* there is always some input buffered */ + XXH_memcpy(lastStripe, state->buffer + sizeof(state->buffer) - catchupSize, catchupSize); + XXH_memcpy(lastStripe + catchupSize, state->buffer, state->bufferedSize); + lastStripePtr = lastStripe; + } + /* Last stripe */ + XXH3_accumulate_512(acc, + lastStripePtr, + secret + state->secretLimit - XXH_SECRET_LASTACC_START); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest (XXH_NOESCAPE const XXH3_state_t* state) +{ + const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret; + if (state->totalLen > XXH3_MIDSIZE_MAX) { + XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB]; + XXH3_digest_long(acc, state, secret); + return XXH3_finalizeLong_64b(acc, secret, (xxh_u64)state->totalLen); + } + /* totalLen <= XXH3_MIDSIZE_MAX: digesting a short input */ + if (state->useSeed) + return XXH3_64bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed); + return XXH3_64bits_withSecret(state->buffer, (size_t)(state->totalLen), + secret, state->secretLimit + XXH_STRIPE_LEN); +} +#endif /* !XXH_NO_STREAM */ + + +/* ========================================== + * XXH3 128 bits (a.k.a XXH128) + * ========================================== + * XXH3's 128-bit variant has better mixing and strength than the 64-bit variant, + * even without counting the significantly larger output size. + * + * For example, extra steps are taken to avoid the seed-dependent collisions + * in 17-240 byte inputs (See XXH3_mix16B and XXH128_mix32B). + * + * This strength naturally comes at the cost of some speed, especially on short + * lengths. Note that longer hashes are about as fast as the 64-bit version + * due to it using only a slight modification of the 64-bit loop. + * + * XXH128 is also more oriented towards 64-bit machines. It is still extremely + * fast for a _128-bit_ hash on 32-bit (it usually clears XXH64). + */ + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_1to3_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + /* A doubled version of 1to3_64b with different constants. */ + XXH_ASSERT(input != NULL); + XXH_ASSERT(1 <= len && len <= 3); + XXH_ASSERT(secret != NULL); + /* + * len = 1: combinedl = { input[0], 0x01, input[0], input[0] } + * len = 2: combinedl = { input[1], 0x02, input[0], input[1] } + * len = 3: combinedl = { input[2], 0x03, input[0], input[1] } + */ + { xxh_u8 const c1 = input[0]; + xxh_u8 const c2 = input[len >> 1]; + xxh_u8 const c3 = input[len - 1]; + xxh_u32 const combinedl = ((xxh_u32)c1 <<16) | ((xxh_u32)c2 << 24) + | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8); + xxh_u32 const combinedh = XXH_rotl32(XXH_swap32(combinedl), 13); + xxh_u64 const bitflipl = (XXH_readLE32(secret) ^ XXH_readLE32(secret+4)) + seed; + xxh_u64 const bitfliph = (XXH_readLE32(secret+8) ^ XXH_readLE32(secret+12)) - seed; + xxh_u64 const keyed_lo = (xxh_u64)combinedl ^ bitflipl; + xxh_u64 const keyed_hi = (xxh_u64)combinedh ^ bitfliph; + XXH128_hash_t h128; + h128.low64 = XXH64_avalanche(keyed_lo); + h128.high64 = XXH64_avalanche(keyed_hi); + return h128; + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_4to8_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(4 <= len && len <= 8); + seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32; + { xxh_u32 const input_lo = XXH_readLE32(input); + xxh_u32 const input_hi = XXH_readLE32(input + len - 4); + xxh_u64 const input_64 = input_lo + ((xxh_u64)input_hi << 32); + xxh_u64 const bitflip = (XXH_readLE64(secret+16) ^ XXH_readLE64(secret+24)) + seed; + xxh_u64 const keyed = input_64 ^ bitflip; + + /* Shift len to the left to ensure it is even, this avoids even multiplies. */ + XXH128_hash_t m128 = XXH_mult64to128(keyed, XXH_PRIME64_1 + (len << 2)); + + m128.high64 += (m128.low64 << 1); + m128.low64 ^= (m128.high64 >> 3); + + m128.low64 = XXH_xorshift64(m128.low64, 35); + m128.low64 *= PRIME_MX2; + m128.low64 = XXH_xorshift64(m128.low64, 28); + m128.high64 = XXH3_avalanche(m128.high64); + return m128; + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_9to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(9 <= len && len <= 16); + { xxh_u64 const bitflipl = (XXH_readLE64(secret+32) ^ XXH_readLE64(secret+40)) - seed; + xxh_u64 const bitfliph = (XXH_readLE64(secret+48) ^ XXH_readLE64(secret+56)) + seed; + xxh_u64 const input_lo = XXH_readLE64(input); + xxh_u64 input_hi = XXH_readLE64(input + len - 8); + XXH128_hash_t m128 = XXH_mult64to128(input_lo ^ input_hi ^ bitflipl, XXH_PRIME64_1); + /* + * Put len in the middle of m128 to ensure that the length gets mixed to + * both the low and high bits in the 128x64 multiply below. + */ + m128.low64 += (xxh_u64)(len - 1) << 54; + input_hi ^= bitfliph; + /* + * Add the high 32 bits of input_hi to the high 32 bits of m128, then + * add the long product of the low 32 bits of input_hi and XXH_PRIME32_2 to + * the high 64 bits of m128. + * + * The best approach to this operation is different on 32-bit and 64-bit. + */ + if (sizeof(void *) < sizeof(xxh_u64)) { /* 32-bit */ + /* + * 32-bit optimized version, which is more readable. + * + * On 32-bit, it removes an ADC and delays a dependency between the two + * halves of m128.high64, but it generates an extra mask on 64-bit. + */ + m128.high64 += (input_hi & 0xFFFFFFFF00000000ULL) + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2); + } else { + /* + * 64-bit optimized (albeit more confusing) version. + * + * Uses some properties of addition and multiplication to remove the mask: + * + * Let: + * a = input_hi.lo = (input_hi & 0x00000000FFFFFFFF) + * b = input_hi.hi = (input_hi & 0xFFFFFFFF00000000) + * c = XXH_PRIME32_2 + * + * a + (b * c) + * Inverse Property: x + y - x == y + * a + (b * (1 + c - 1)) + * Distributive Property: x * (y + z) == (x * y) + (x * z) + * a + (b * 1) + (b * (c - 1)) + * Identity Property: x * 1 == x + * a + b + (b * (c - 1)) + * + * Substitute a, b, and c: + * input_hi.hi + input_hi.lo + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1)) + * + * Since input_hi.hi + input_hi.lo == input_hi, we get this: + * input_hi + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1)) + */ + m128.high64 += input_hi + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2 - 1); + } + /* m128 ^= XXH_swap64(m128 >> 64); */ + m128.low64 ^= XXH_swap64(m128.high64); + + { /* 128x64 multiply: h128 = m128 * XXH_PRIME64_2; */ + XXH128_hash_t h128 = XXH_mult64to128(m128.low64, XXH_PRIME64_2); + h128.high64 += m128.high64 * XXH_PRIME64_2; + + h128.low64 = XXH3_avalanche(h128.low64); + h128.high64 = XXH3_avalanche(h128.high64); + return h128; + } } +} + +/* + * Assumption: `secret` size is >= XXH3_SECRET_SIZE_MIN + */ +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_0to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(len <= 16); + { if (len > 8) return XXH3_len_9to16_128b(input, len, secret, seed); + if (len >= 4) return XXH3_len_4to8_128b(input, len, secret, seed); + if (len) return XXH3_len_1to3_128b(input, len, secret, seed); + { XXH128_hash_t h128; + xxh_u64 const bitflipl = XXH_readLE64(secret+64) ^ XXH_readLE64(secret+72); + xxh_u64 const bitfliph = XXH_readLE64(secret+80) ^ XXH_readLE64(secret+88); + h128.low64 = XXH64_avalanche(seed ^ bitflipl); + h128.high64 = XXH64_avalanche( seed ^ bitfliph); + return h128; + } } +} + +/* + * A bit slower than XXH3_mix16B, but handles multiply by zero better. + */ +XXH_FORCE_INLINE XXH128_hash_t +XXH128_mix32B(XXH128_hash_t acc, const xxh_u8* input_1, const xxh_u8* input_2, + const xxh_u8* secret, XXH64_hash_t seed) +{ + acc.low64 += XXH3_mix16B (input_1, secret+0, seed); + acc.low64 ^= XXH_readLE64(input_2) + XXH_readLE64(input_2 + 8); + acc.high64 += XXH3_mix16B (input_2, secret+16, seed); + acc.high64 ^= XXH_readLE64(input_1) + XXH_readLE64(input_1 + 8); + return acc; +} + + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(16 < len && len <= 128); + + { XXH128_hash_t acc; + acc.low64 = len * XXH_PRIME64_1; + acc.high64 = 0; + +#if XXH_SIZE_OPT >= 1 + { + /* Smaller, but slightly slower. */ + unsigned int i = (unsigned int)(len - 1) / 32; + do { + acc = XXH128_mix32B(acc, input+16*i, input+len-16*(i+1), secret+32*i, seed); + } while (i-- != 0); + } +#else + if (len > 32) { + if (len > 64) { + if (len > 96) { + acc = XXH128_mix32B(acc, input+48, input+len-64, secret+96, seed); + } + acc = XXH128_mix32B(acc, input+32, input+len-48, secret+64, seed); + } + acc = XXH128_mix32B(acc, input+16, input+len-32, secret+32, seed); + } + acc = XXH128_mix32B(acc, input, input+len-16, secret, seed); +#endif + { XXH128_hash_t h128; + h128.low64 = acc.low64 + acc.high64; + h128.high64 = (acc.low64 * XXH_PRIME64_1) + + (acc.high64 * XXH_PRIME64_4) + + ((len - seed) * XXH_PRIME64_2); + h128.low64 = XXH3_avalanche(h128.low64); + h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64); + return h128; + } + } +} + +XXH_NO_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); + + { XXH128_hash_t acc; + unsigned i; + acc.low64 = len * XXH_PRIME64_1; + acc.high64 = 0; + /* + * We set as `i` as offset + 32. We do this so that unchanged + * `len` can be used as upper bound. This reaches a sweet spot + * where both x86 and aarch64 get simple agen and good codegen + * for the loop. + */ + for (i = 32; i < 160; i += 32) { + acc = XXH128_mix32B(acc, + input + i - 32, + input + i - 16, + secret + i - 32, + seed); + } + acc.low64 = XXH3_avalanche(acc.low64); + acc.high64 = XXH3_avalanche(acc.high64); + /* + * NB: `i <= len` will duplicate the last 32-bytes if + * len % 32 was zero. This is an unfortunate necessity to keep + * the hash result stable. + */ + for (i=160; i <= len; i += 32) { + acc = XXH128_mix32B(acc, + input + i - 32, + input + i - 16, + secret + XXH3_MIDSIZE_STARTOFFSET + i - 160, + seed); + } + /* last bytes */ + acc = XXH128_mix32B(acc, + input + len - 16, + input + len - 32, + secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET - 16, + (XXH64_hash_t)0 - seed); + + { XXH128_hash_t h128; + h128.low64 = acc.low64 + acc.high64; + h128.high64 = (acc.low64 * XXH_PRIME64_1) + + (acc.high64 * XXH_PRIME64_4) + + ((len - seed) * XXH_PRIME64_2); + h128.low64 = XXH3_avalanche(h128.low64); + h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64); + return h128; + } + } +} + +static XXH_PUREF XXH128_hash_t +XXH3_finalizeLong_128b(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, xxh_u64 len) +{ + XXH128_hash_t h128; + h128.low64 = XXH3_finalizeLong_64b(acc, secret, len); + h128.high64 = XXH3_mergeAccs(acc, secret + secretSize + - XXH_STRIPE_LEN - XXH_SECRET_MERGEACCS_START, + ~(len * XXH_PRIME64_2)); + return h128; +} + +XXH_FORCE_INLINE XXH128_hash_t +XXH3_hashLong_128b_internal(const void* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC; + + XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, secret, secretSize, f_acc, f_scramble); + + /* converge into final hash */ + XXH_STATIC_ASSERT(sizeof(acc) == 64); + XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); + return XXH3_finalizeLong_128b(acc, secret, secretSize, (xxh_u64)len); +} + +/* + * It's important for performance that XXH3_hashLong() is not inlined. + */ +XXH_NO_INLINE XXH_PUREF XXH128_hash_t +XXH3_hashLong_128b_default(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, + const void* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; (void)secret; (void)secretLen; + return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), + XXH3_accumulate, XXH3_scrambleAcc); +} + +/* + * It's important for performance to pass @p secretLen (when it's static) + * to the compiler, so that it can properly optimize the vectorized loop. + * + * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE + * breaks -Og, this is XXH_NO_INLINE. + */ +XXH3_WITH_SECRET_INLINE XXH128_hash_t +XXH3_hashLong_128b_withSecret(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, + const void* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; + return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen, + XXH3_accumulate, XXH3_scrambleAcc); +} + +XXH_FORCE_INLINE XXH128_hash_t +XXH3_hashLong_128b_withSeed_internal(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble, + XXH3_f_initCustomSecret f_initSec) +{ + if (seed64 == 0) + return XXH3_hashLong_128b_internal(input, len, + XXH3_kSecret, sizeof(XXH3_kSecret), + f_acc, f_scramble); + { XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE]; + f_initSec(secret, seed64); + return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, sizeof(secret), + f_acc, f_scramble); + } +} + +/* + * It's important for performance that XXH3_hashLong is not inlined. + */ +XXH_NO_INLINE XXH128_hash_t +XXH3_hashLong_128b_withSeed(const void* input, size_t len, + XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen) +{ + (void)secret; (void)secretLen; + return XXH3_hashLong_128b_withSeed_internal(input, len, seed64, + XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret); +} + +typedef XXH128_hash_t (*XXH3_hashLong128_f)(const void* XXH_RESTRICT, size_t, + XXH64_hash_t, const void* XXH_RESTRICT, size_t); + +XXH_FORCE_INLINE XXH128_hash_t +XXH3_128bits_internal(const void* input, size_t len, + XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen, + XXH3_hashLong128_f f_hl128) +{ + XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN); + /* + * If an action is to be taken if `secret` conditions are not respected, + * it should be done here. + * For now, it's a contract pre-condition. + * Adding a check and a branch here would cost performance at every hash. + */ + if (len <= 16) + return XXH3_len_0to16_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, seed64); + if (len <= 128) + return XXH3_len_17to128_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + if (len <= XXH3_MIDSIZE_MAX) + return XXH3_len_129to240_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + return f_hl128(input, len, seed64, secret, secretLen); +} + + +/* === Public XXH128 API === */ + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void* input, size_t len) +{ + return XXH3_128bits_internal(input, len, 0, + XXH3_kSecret, sizeof(XXH3_kSecret), + XXH3_hashLong_128b_default); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH3_128bits_withSecret(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + return XXH3_128bits_internal(input, len, 0, + (const xxh_u8*)secret, secretSize, + XXH3_hashLong_128b_withSecret); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH3_128bits_withSeed(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed) +{ + return XXH3_128bits_internal(input, len, seed, + XXH3_kSecret, sizeof(XXH3_kSecret), + XXH3_hashLong_128b_withSeed); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH3_128bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed) +{ + if (len <= XXH3_MIDSIZE_MAX) + return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL); + return XXH3_hashLong_128b_withSecret(input, len, seed, secret, secretSize); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH128(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed) +{ + return XXH3_128bits_withSeed(input, len, seed); +} + + +/* === XXH3 128-bit streaming === */ +#ifndef XXH_NO_STREAM +/* + * All initialization and update functions are identical to 64-bit streaming variant. + * The only difference is the finalization routine. + */ + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr) +{ + return XXH3_64bits_reset(statePtr); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + return XXH3_64bits_reset_withSecret(statePtr, secret, secretSize); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed) +{ + return XXH3_64bits_reset_withSeed(statePtr, seed); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed) +{ + return XXH3_64bits_reset_withSecretandSeed(statePtr, secret, secretSize, seed); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_update(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len) +{ + return XXH3_update_regular(state, input, len); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (XXH_NOESCAPE const XXH3_state_t* state) +{ + const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret; + if (state->totalLen > XXH3_MIDSIZE_MAX) { + XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB]; + XXH3_digest_long(acc, state, secret); + XXH_ASSERT(state->secretLimit + XXH_STRIPE_LEN >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); + return XXH3_finalizeLong_128b(acc, secret, state->secretLimit + XXH_STRIPE_LEN, (xxh_u64)state->totalLen); + } + /* len <= XXH3_MIDSIZE_MAX : short code */ + if (state->useSeed) + return XXH3_128bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed); + return XXH3_128bits_withSecret(state->buffer, (size_t)(state->totalLen), + secret, state->secretLimit + XXH_STRIPE_LEN); +} +#endif /* !XXH_NO_STREAM */ +/* 128-bit utility functions */ + +/* return : 1 is equal, 0 if different */ +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2) +{ + /* note : XXH128_hash_t is compact, it has no padding byte */ + return !(XXH_memcmp(&h1, &h2, sizeof(h1))); +} + +/* This prototype is compatible with stdlib's qsort(). + * @return : >0 if *h128_1 > *h128_2 + * <0 if *h128_1 < *h128_2 + * =0 if *h128_1 == *h128_2 */ +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API int XXH128_cmp(XXH_NOESCAPE const void* h128_1, XXH_NOESCAPE const void* h128_2) +{ + XXH128_hash_t const h1 = *(const XXH128_hash_t*)h128_1; + XXH128_hash_t const h2 = *(const XXH128_hash_t*)h128_2; + int const hcmp = (h1.high64 > h2.high64) - (h2.high64 > h1.high64); + /* note : bets that, in most cases, hash values are different */ + if (hcmp) return hcmp; + return (h1.low64 > h2.low64) - (h2.low64 > h1.low64); +} + + +/*====== Canonical representation ======*/ +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API void +XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t* dst, XXH128_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH128_canonical_t) == sizeof(XXH128_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) { + hash.high64 = XXH_swap64(hash.high64); + hash.low64 = XXH_swap64(hash.low64); + } + XXH_memcpy(dst, &hash.high64, sizeof(hash.high64)); + XXH_memcpy((char*)dst + sizeof(hash.high64), &hash.low64, sizeof(hash.low64)); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t* src) +{ + XXH128_hash_t h; + h.high64 = XXH_readBE64(src); + h.low64 = XXH_readBE64(src->digest + 8); + return h; +} + + + +/* ========================================== + * Secret generators + * ========================================== + */ +#define XXH_MIN(x, y) (((x) > (y)) ? (y) : (x)) + +XXH_FORCE_INLINE void XXH3_combine16(void* dst, XXH128_hash_t h128) +{ + XXH_writeLE64( dst, XXH_readLE64(dst) ^ h128.low64 ); + XXH_writeLE64( (char*)dst+8, XXH_readLE64((char*)dst+8) ^ h128.high64 ); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_generateSecret(XXH_NOESCAPE void* secretBuffer, size_t secretSize, XXH_NOESCAPE const void* customSeed, size_t customSeedSize) +{ +#if (XXH_DEBUGLEVEL >= 1) + XXH_ASSERT(secretBuffer != NULL); + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); +#else + /* production mode, assert() are disabled */ + if (secretBuffer == NULL) return XXH_ERROR; + if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; +#endif + + if (customSeedSize == 0) { + customSeed = XXH3_kSecret; + customSeedSize = XXH_SECRET_DEFAULT_SIZE; + } +#if (XXH_DEBUGLEVEL >= 1) + XXH_ASSERT(customSeed != NULL); +#else + if (customSeed == NULL) return XXH_ERROR; +#endif + + /* Fill secretBuffer with a copy of customSeed - repeat as needed */ + { size_t pos = 0; + while (pos < secretSize) { + size_t const toCopy = XXH_MIN((secretSize - pos), customSeedSize); + XXH_memcpy((char*)secretBuffer + pos, customSeed, toCopy); + pos += toCopy; + } } + + { size_t const nbSeg16 = secretSize / 16; + size_t n; + XXH128_canonical_t scrambler; + XXH128_canonicalFromHash(&scrambler, XXH128(customSeed, customSeedSize, 0)); + for (n=0; n`. + + To be able to save a module, it must not make any calls to native Python + functions. This means that all submodules must be subclasses of + :class:`ScriptModule` as well. + + .. DANGER:: + All modules, no matter their device, are always loaded onto the CPU + during loading. This is different from :func:`torch.load`'s semantics + and may change in the future. + + Args: + m: A :class:`ScriptModule` to save. + f: A file-like object (has to implement write and flush) or a string + containing a file name. + _extra_files: Map from filename to contents which will be stored as part of `f`. + + .. note:: + torch.jit.save attempts to preserve the behavior of some operators + across versions. For example, dividing two integer tensors in + PyTorch 1.5 performed floor division, and if the module + containing that code is saved in PyTorch 1.5 and loaded in PyTorch 1.6 + its division behavior will be preserved. The same module saved in + PyTorch 1.6 will fail to load in PyTorch 1.5, however, since the + behavior of division changed in 1.6, and 1.5 does not know how to + replicate the 1.6 behavior. + + Example: + .. testcode:: + + import torch + import io + + class MyModule(torch.nn.Module): + def forward(self, x): + return x + 10 + + m = torch.jit.script(MyModule()) + + # Save to file + torch.jit.save(m, 'scriptmodule.pt') + # This line is equivalent to the previous + m.save("scriptmodule.pt") + + # Save to io.BytesIO buffer + buffer = io.BytesIO() + torch.jit.save(m, buffer) + + # Save with extra files + extra_files = {'foo.txt': b'bar'} + torch.jit.save(m, 'scriptmodule.pt', _extra_files=extra_files) + """ + if _extra_files is None: + _extra_files = {} + if isinstance(f, (str, os.PathLike)): + m.save(f, _extra_files=_extra_files) + else: + ret = m.save_to_buffer(_extra_files=_extra_files) + f.write(ret) + + +def load(f, map_location=None, _extra_files=None, _restore_shapes=False): + r""" + Load a :class:`ScriptModule` or :class:`ScriptFunction` previously saved with :func:`torch.jit.save `. + + All previously saved modules, no matter their device, are first loaded onto CPU, + and then are moved to the devices they were saved from. If this fails (e.g. + because the run time system doesn't have certain devices), an exception is + raised. + + Args: + f: a file-like object (has to implement read, readline, tell, and seek), + or a string containing a file name + map_location (string or torch.device): A simplified version of + ``map_location`` in `torch.jit.save` used to dynamically remap + storages to an alternative set of devices. + _extra_files (dictionary of filename to content): The extra + filenames given in the map would be loaded and their content + would be stored in the provided map. + _restore_shapes (bool): Whether or not to retrace the module on load using stored inputs + + Returns: + A :class:`ScriptModule` object. + + Example: + .. testcode:: + + import torch + import io + + torch.jit.load('scriptmodule.pt') + + # Load ScriptModule from io.BytesIO object + with open('scriptmodule.pt', 'rb') as f: + buffer = io.BytesIO(f.read()) + + # Load all tensors to the original device + torch.jit.load(buffer) + + # Load all tensors onto CPU, using a device + buffer.seek(0) + torch.jit.load(buffer, map_location=torch.device('cpu')) + + # Load all tensors onto CPU, using a string + buffer.seek(0) + torch.jit.load(buffer, map_location='cpu') + + # Load with extra files. + extra_files = {'foo.txt': ''} # values will be replaced with data + torch.jit.load('scriptmodule.pt', _extra_files=extra_files) + print(extra_files['foo.txt']) + + .. testoutput:: + :hide: + + ... + + .. testcleanup:: + + import os + os.remove("scriptmodule.pt") + """ + if isinstance(f, (str, os.PathLike)): + if not os.path.exists(f): # type: ignore[type-var] + raise ValueError(f"The provided filename {f} does not exist") # type: ignore[str-bytes-safe] + if os.path.isdir(f): + raise ValueError(f"The provided filename {f} is a directory") # type: ignore[str-bytes-safe] + + map_location = validate_map_location(map_location) + if _extra_files is None: + _extra_files = {} + + cu = torch._C.CompilationUnit() + if isinstance(f, (str, os.PathLike)): + cpp_module = torch._C.import_ir_module(cu, os.fspath(f), map_location, _extra_files, _restore_shapes) # type: ignore[call-arg] + else: + cpp_module = torch._C.import_ir_module_from_buffer( + cu, f.read(), map_location, _extra_files, _restore_shapes + ) # type: ignore[call-arg] + + # TODO: Pretty sure this approach loses ConstSequential status and such + return wrap_cpp_module(cpp_module) + + +def validate_map_location(map_location=None): + if isinstance(map_location, str): + map_location = torch.device(map_location) + elif not (map_location is None or isinstance(map_location, torch.device)): + raise ValueError( + "map_location should be either None, string or torch.device, " + "but got type: " + str(type(map_location)) + ) + + if str(map_location).startswith("cuda"): + validate_cuda_device(map_location) + + return map_location + + +def jit_module_from_flatbuffer(f): + if isinstance(f, (str, os.PathLike)): + f = os.fspath(f) + return wrap_cpp_module(torch._C._load_jit_module_from_file(f)) + else: + return wrap_cpp_module(torch._C._load_jit_module_from_bytes(f.read())) + + +def save_jit_module_to_flatbuffer(m, f, _extra_files=None): + r""" + Save an offline version of this module for use in a separate process. + + The saved module serializes all of the methods, submodules, parameters, and + attributes of this module. It can be loaded into the C++ API using + ``torch::jit::load_jit_module_from_file(filename)`` or into the Python API with + :func:`torch.jit.jit_module_from_flatbuffer`. + + To be able to save a module, it must not make any calls to native Python + functions. This means that all submodules must be subclasses of + :class:`ScriptModule` as well. + + .. DANGER:: + All modules, no matter their device, are always loaded onto the CPU + during loading. This is different from :func:`torch.load`'s semantics + and may change in the future. + + Args: + m: A :class:`ScriptModule` to save. + f: A string for file path + + + Example: + .. testcode:: + + import torch + import io + + class MyModule(torch.nn.Module): + def forward(self, x): + return x + 10 + + m = torch.jit.script(MyModule()) + + # Save to file + torch.jit.save_jit_module_to_flatbuffer(m, 'scriptmodule.ff') + """ + extra_files = _extra_files + if extra_files is None: + extra_files = {} + + if isinstance(f, (str, os.PathLike)): + f = os.fspath(f) + torch._C._save_jit_module(m._c, f, extra_files) + else: + s = torch._C._save_jit_module_to_bytes(m._c, extra_files) + f.write(s) + + +def get_flatbuffer_module_info(path_or_file): + r"""Get some information regarding a model file in flatbuffer format. + + Args: + path_or_file: Either str, Path or file like object (BytesIO OK). + If it's str or Path, we will read the file referenced by that + path as Bytes. + + Returns: + A dict with metadata on what that file contains, currently looks like + this: + { + 'bytecode_version': 4, # int + 'operator_version': 4, # int + 'function_names': { + '__torch__.___torch_mangle_0.Foo.forward'}, # set + 'type_names': set(), # set + 'opname_to_num_args': {'aten::linear': 3} # Dict[str, int] + } + """ + if isinstance(path_or_file, (str, os.PathLike)): + with open(path_or_file, "rb") as f: + all_bytes = f.read() + else: + all_bytes = path_or_file.read() + return torch._C._get_module_info_from_flatbuffer(all_bytes) diff --git a/shared/package-files/3c/3c52cb628d0159ac697cd3fab743baaf470b63d297652cc742655840a61b06d2/_isfinite.pyx b/shared/package-files/3c/3c52cb628d0159ac697cd3fab743baaf470b63d297652cc742655840a61b06d2/_isfinite.pyx new file mode 100644 index 0000000000000000000000000000000000000000..f3918eeacb5c467f78ae06b04a9f5c3e587f6174 --- /dev/null +++ b/shared/package-files/3c/3c52cb628d0159ac697cd3fab743baaf470b63d297652cc742655840a61b06d2/_isfinite.pyx @@ -0,0 +1,51 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from libc.math cimport isnan, isinf +from cython cimport floating + + +cpdef enum FiniteStatus: + all_finite = 0 + has_nan = 1 + has_infinite = 2 + + +def cy_isfinite(floating[::1] a, bint allow_nan=False): + cdef FiniteStatus result + with nogil: + result = _isfinite(a, allow_nan) + return result + + +cdef inline FiniteStatus _isfinite(floating[::1] a, bint allow_nan) noexcept nogil: + cdef floating* a_ptr = &a[0] + cdef Py_ssize_t length = len(a) + if allow_nan: + return _isfinite_allow_nan(a_ptr, length) + else: + return _isfinite_disable_nan(a_ptr, length) + + +cdef inline FiniteStatus _isfinite_allow_nan(floating* a_ptr, + Py_ssize_t length) noexcept nogil: + cdef Py_ssize_t i + cdef floating v + for i in range(length): + v = a_ptr[i] + if isinf(v): + return FiniteStatus.has_infinite + return FiniteStatus.all_finite + + +cdef inline FiniteStatus _isfinite_disable_nan(floating* a_ptr, + Py_ssize_t length) noexcept nogil: + cdef Py_ssize_t i + cdef floating v + for i in range(length): + v = a_ptr[i] + if isnan(v): + return FiniteStatus.has_nan + elif isinf(v): + return FiniteStatus.has_infinite + return FiniteStatus.all_finite diff --git a/shared/package-files/3c/3c53a0810d7480ff7257324b9acf96eada874abcbfea1db5190808b785e795b6/newhp b/shared/package-files/3c/3c53a0810d7480ff7257324b9acf96eada874abcbfea1db5190808b785e795b6/newhp new file mode 100644 index 0000000000000000000000000000000000000000..430b5e450f9fbbd253b9da5d71558a741fc5d85a Binary files /dev/null and b/shared/package-files/3c/3c53a0810d7480ff7257324b9acf96eada874abcbfea1db5190808b785e795b6/newhp differ diff --git a/shared/package-files/3c/3c54bc7634ea88d6c654c8e0ecf68f8c47f09a3c9955f8a85e2455ceaa80dc4d/__init__.py b/shared/package-files/3c/3c54bc7634ea88d6c654c8e0ecf68f8c47f09a3c9955f8a85e2455ceaa80dc4d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af862653f3ce0eeb67f7764e16c32f3466e87024 --- /dev/null +++ b/shared/package-files/3c/3c54bc7634ea88d6c654c8e0ecf68f8c47f09a3c9955f8a85e2455ceaa80dc4d/__init__.py @@ -0,0 +1,18 @@ +""" +A module to implement logical predicates and assumption system. +""" + +from .assume import ( + AppliedPredicate, Predicate, AssumptionsContext, assuming, + global_assumptions +) +from .ask import Q, ask, register_handler, remove_handler +from .refine import refine +from .relation import BinaryRelation, AppliedBinaryRelation + +__all__ = [ + 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', + 'global_assumptions', 'Q', 'ask', 'register_handler', 'remove_handler', + 'refine', + 'BinaryRelation', 'AppliedBinaryRelation' +] diff --git a/shared/package-files/3c/3c6bb1b519cc6f10f18b6ad81468731769215869204a95ee5029d324b17facc9/pcvt40w b/shared/package-files/3c/3c6bb1b519cc6f10f18b6ad81468731769215869204a95ee5029d324b17facc9/pcvt40w new file mode 100644 index 0000000000000000000000000000000000000000..70763597e2de3e4a24a0d3a6de0f5818e3e9bb00 Binary files /dev/null and b/shared/package-files/3c/3c6bb1b519cc6f10f18b6ad81468731769215869204a95ee5029d324b17facc9/pcvt40w differ diff --git a/shared/package-files/3c/3c768cc0231a5eedef023843a59302db1b7984aa2825755e31f7e1a03cd3c4d7/buffered.h b/shared/package-files/3c/3c768cc0231a5eedef023843a59302db1b7984aa2825755e31f7e1a03cd3c4d7/buffered.h new file mode 100644 index 0000000000000000000000000000000000000000..22ea7520a5050e53a5acf83c13943923595daf5b --- /dev/null +++ b/shared/package-files/3c/3c768cc0231a5eedef023843a59302db1b7984aa2825755e31f7e1a03cd3c4d7/buffered.h @@ -0,0 +1,168 @@ +// 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. + +// Buffered stream implementations + +#pragma once + +#include +#include +#include + +#include "arrow/io/concurrency.h" +#include "arrow/io/interfaces.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class Buffer; +class MemoryPool; +class Status; + +namespace io { + +class ARROW_EXPORT BufferedOutputStream : public OutputStream { + public: + ~BufferedOutputStream() override; + + /// \brief Create a buffered output stream wrapping the given output stream. + /// \param[in] buffer_size the size of the temporary write buffer + /// \param[in] pool a MemoryPool to use for allocations + /// \param[in] raw another OutputStream + /// \return the created BufferedOutputStream + static Result> Create( + int64_t buffer_size, MemoryPool* pool, std::shared_ptr raw); + + /// \brief Resize internal buffer + /// \param[in] new_buffer_size the new buffer size + /// \return Status + Status SetBufferSize(int64_t new_buffer_size); + + /// \brief Return the current size of the internal buffer + int64_t buffer_size() const; + + /// \brief Return the number of remaining bytes that have not been flushed to + /// the raw OutputStream + int64_t bytes_buffered() const; + + /// \brief Flush any buffered writes and release the raw + /// OutputStream. Further operations on this object are invalid + /// \return the underlying OutputStream + Result> Detach(); + + // OutputStream interface + + /// \brief Close the buffered output stream. This implicitly closes the + /// underlying raw output stream. + Status Close() override; + Status Abort() override; + bool closed() const override; + + Result Tell() const override; + // Write bytes to the stream. Thread-safe + Status Write(const void* data, int64_t nbytes) override; + Status Write(const std::shared_ptr& data) override; + + Status Flush() override; + + /// \brief Return the underlying raw output stream. + std::shared_ptr raw() const; + + private: + explicit BufferedOutputStream(std::shared_ptr raw, MemoryPool* pool); + + class ARROW_NO_EXPORT Impl; + std::unique_ptr impl_; +}; + +/// \class BufferedInputStream +/// \brief An InputStream that performs buffered reads from an unbuffered +/// InputStream, which can mitigate the overhead of many small reads in some +/// cases +class ARROW_EXPORT BufferedInputStream + : public internal::InputStreamConcurrencyWrapper { + public: + ~BufferedInputStream() override; + + /// \brief Create a BufferedInputStream from a raw InputStream + /// \param[in] buffer_size the size of the temporary read buffer + /// \param[in] pool a MemoryPool to use for allocations + /// \param[in] raw a raw InputStream + /// \param[in] raw_read_bound a bound on the maximum number of bytes + /// to read from the raw input stream. The default -1 indicates that + /// it is unbounded + /// \return the created BufferedInputStream + static Result> Create( + int64_t buffer_size, MemoryPool* pool, std::shared_ptr raw, + int64_t raw_read_bound = -1); + + /// \brief Resize internal read buffer; calls to Read(...) will read at least + /// this many bytes from the raw InputStream if possible. + /// \param[in] new_buffer_size the new read buffer size + /// \return Status + Status SetBufferSize(int64_t new_buffer_size); + + /// \brief Return the number of remaining bytes in the read buffer + int64_t bytes_buffered() const; + + /// \brief Return the current size of the internal buffer + int64_t buffer_size() const; + + /// \brief Release the raw InputStream. Any data buffered will be + /// discarded. Further operations on this object are invalid + /// \return raw the underlying InputStream + std::shared_ptr Detach(); + + /// \brief Return the unbuffered InputStream + std::shared_ptr raw() const; + + // InputStream APIs + + bool closed() const override; + Result> ReadMetadata() override; + Future> ReadMetadataAsync( + const IOContext& io_context) override; + + private: + friend InputStreamConcurrencyWrapper; + + explicit BufferedInputStream(std::shared_ptr raw, MemoryPool* pool, + int64_t raw_total_bytes_bound); + + Status DoClose(); + Status DoAbort() override; + + /// \brief Returns the position of the buffered stream, though the position + /// of the unbuffered stream may be further advanced. + Result DoTell() const; + + Result DoRead(int64_t nbytes, void* out); + + /// \brief Read into buffer. + Result> DoRead(int64_t nbytes); + + /// \brief Return a zero-copy string view referencing buffered data, + /// but do not advance the position of the stream. Buffers data and + /// expands the buffer size if necessary + Result DoPeek(int64_t nbytes) override; + + class ARROW_NO_EXPORT Impl; + std::unique_ptr impl_; +}; + +} // namespace io +} // namespace arrow diff --git a/shared/package-files/3c/3c7ef15a1fa25b998d38c92132378635955aadedc1dcf3e40e63dc0098f6b8f7/README.txt b/shared/package-files/3c/3c7ef15a1fa25b998d38c92132378635955aadedc1dcf3e40e63dc0098f6b8f7/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..e699e7d6836e608df0a5220c9c2e3685cafd37dd --- /dev/null +++ b/shared/package-files/3c/3c7ef15a1fa25b998d38c92132378635955aadedc1dcf3e40e63dc0098f6b8f7/README.txt @@ -0,0 +1,18 @@ +Image: china.jpg +Released under a creative commons license. [1] +Attribution: Some rights reserved by danielbuechele [2] +Retrieved 21st August, 2011 from [3] by Robert Layton + +[1] https://creativecommons.org/licenses/by/2.0/ +[2] https://www.flickr.com/photos/danielbuechele/ +[3] https://www.flickr.com/photos/danielbuechele/6061409035/sizes/z/in/photostream/ + + +Image: flower.jpg +Released under a creative commons license. [1] +Attribution: Some rights reserved by danielbuechele [2] +Retrieved 21st August, 2011 from [3] by Robert Layton + +[1] https://creativecommons.org/licenses/by/2.0/ +[2] https://www.flickr.com/photos/vultilion/ +[3] https://www.flickr.com/photos/vultilion/6056698931/sizes/z/in/photostream/ diff --git a/shared/package-files/3c/3c81842f4ff5d92ef7fb1a77cd46635adf3b2d8d7996ee721df99afabf3e135e/isin_cpu_dispatch.h b/shared/package-files/3c/3c81842f4ff5d92ef7fb1a77cd46635adf3b2d8d7996ee721df99afabf3e135e/isin_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..bd02933656f4ecfdb3a19f02cc78303158f93ef1 --- /dev/null +++ b/shared/package-files/3c/3c81842f4ff5d92ef7fb1a77cd46635adf3b2d8d7996ee721df99afabf3e135e/isin_cpu_dispatch.h @@ -0,0 +1,31 @@ +#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 isin(const at::Tensor & elements, const at::Tensor & test_elements, bool assume_unique=false, bool invert=false); +TORCH_API at::Tensor & isin_out(at::Tensor & out, const at::Tensor & elements, const at::Tensor & test_elements, bool assume_unique=false, bool invert=false); +TORCH_API at::Tensor & isin_outf(const at::Tensor & elements, const at::Tensor & test_elements, bool assume_unique, bool invert, at::Tensor & out); +TORCH_API at::Tensor isin(const at::Tensor & elements, const at::Scalar & test_element, bool assume_unique=false, bool invert=false); +TORCH_API at::Tensor & isin_out(at::Tensor & out, const at::Tensor & elements, const at::Scalar & test_element, bool assume_unique=false, bool invert=false); +TORCH_API at::Tensor & isin_outf(const at::Tensor & elements, const at::Scalar & test_element, bool assume_unique, bool invert, at::Tensor & out); +TORCH_API at::Tensor isin(const at::Scalar & element, const at::Tensor & test_elements, bool assume_unique=false, bool invert=false); +TORCH_API at::Tensor & isin_out(at::Tensor & out, const at::Scalar & element, const at::Tensor & test_elements, bool assume_unique=false, bool invert=false); +TORCH_API at::Tensor & isin_outf(const at::Scalar & element, const at::Tensor & test_elements, bool assume_unique, bool invert, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/3c/3c8204b6b2cacb3440ba95dcf41692f42aaaaafa5c6cdc0c20a4462cd61d9a81/wyse30-mc b/shared/package-files/3c/3c8204b6b2cacb3440ba95dcf41692f42aaaaafa5c6cdc0c20a4462cd61d9a81/wyse30-mc new file mode 100644 index 0000000000000000000000000000000000000000..cdf6b657204df73029446ea9c128d9f82d2698c4 Binary files /dev/null and b/shared/package-files/3c/3c8204b6b2cacb3440ba95dcf41692f42aaaaafa5c6cdc0c20a4462cd61d9a81/wyse30-mc differ diff --git a/shared/package-files/3c/3c82dfa2ce959672cae9f38531f2c852188a977a35749a3d4f81c95de47b5791/converter.h b/shared/package-files/3c/3c82dfa2ce959672cae9f38531f2c852188a977a35749a3d4f81c95de47b5791/converter.h new file mode 100644 index 0000000000000000000000000000000000000000..c23d6ccd9886e4539d52d537abb85da1dcc93385 --- /dev/null +++ b/shared/package-files/3c/3c82dfa2ce959672cae9f38531f2c852188a977a35749a3d4f81c95de47b5791/converter.h @@ -0,0 +1,411 @@ +// 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. + +#include +#include +#include +#include + +#include "arrow/array.h" +#include "arrow/chunked_array.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/checked_cast.h" +#include "arrow/visit_type_inline.h" + +namespace arrow { +namespace internal { + +template class ConverterTrait> +static Result> MakeConverter( + std::shared_ptr type, typename BaseConverter::OptionsType options, + MemoryPool* pool); + +template +class Converter { + public: + using Self = Converter; + using InputType = Input; + using OptionsType = Options; + + virtual ~Converter() = default; + + Status Construct(std::shared_ptr type, OptionsType options, + MemoryPool* pool) { + type_ = std::move(type); + options_ = std::move(options); + return Init(pool); + } + + virtual Status Append(InputType value) { return Status::NotImplemented("Append"); } + + virtual Status Extend(InputType values, int64_t size, int64_t offset = 0) { + return Status::NotImplemented("Extend"); + } + + virtual Status ExtendMasked(InputType values, InputType mask, int64_t size, + int64_t offset = 0) { + return Status::NotImplemented("ExtendMasked"); + } + + const std::shared_ptr& builder() const { return builder_; } + + const std::shared_ptr& type() const { return type_; } + + OptionsType options() const { return options_; } + + bool may_overflow() const { return may_overflow_; } + + bool rewind_on_overflow() const { return rewind_on_overflow_; } + + virtual Status Reserve(int64_t additional_capacity) { + return builder_->Reserve(additional_capacity); + } + + Status AppendNull() { return builder_->AppendNull(); } + + virtual Result> ToArray() { return builder_->Finish(); } + + virtual Result> ToArray(int64_t length) { + ARROW_ASSIGN_OR_RAISE(auto arr, this->ToArray()); + return arr->Slice(0, length); + } + + virtual Result> ToChunkedArray() { + ARROW_ASSIGN_OR_RAISE(auto array, ToArray()); + std::vector> chunks = {std::move(array)}; + return std::make_shared(chunks); + } + + protected: + virtual Status Init(MemoryPool* pool) { return Status::OK(); } + + std::shared_ptr type_; + std::shared_ptr builder_; + OptionsType options_; + bool may_overflow_ = false; + bool rewind_on_overflow_ = false; +}; + +template +class PrimitiveConverter : public BaseConverter { + public: + using BuilderType = typename TypeTraits::BuilderType; + + protected: + Status Init(MemoryPool* pool) override { + this->builder_ = std::make_shared(this->type_, pool); + // Narrow variable-sized binary types may overflow + this->may_overflow_ = is_binary_like(this->type_->id()); + primitive_type_ = checked_cast(this->type_.get()); + primitive_builder_ = checked_cast(this->builder_.get()); + return Status::OK(); + } + + const ArrowType* primitive_type_; + BuilderType* primitive_builder_; +}; + +template class ConverterTrait> +class ListConverter : public BaseConverter { + public: + using BuilderType = typename TypeTraits::BuilderType; + using ConverterType = typename ConverterTrait::type; + + protected: + Status Init(MemoryPool* pool) override { + list_type_ = checked_cast(this->type_.get()); + ARROW_ASSIGN_OR_RAISE(value_converter_, + (MakeConverter( + list_type_->value_type(), this->options_, pool))); + this->builder_ = + std::make_shared(pool, value_converter_->builder(), this->type_); + list_builder_ = checked_cast(this->builder_.get()); + // Narrow list types may overflow + this->may_overflow_ = this->rewind_on_overflow_ = + sizeof(typename ArrowType::offset_type) < sizeof(int64_t); + return Status::OK(); + } + + const ArrowType* list_type_; + BuilderType* list_builder_; + std::unique_ptr value_converter_; +}; + +template class ConverterTrait> +class StructConverter : public BaseConverter { + public: + using ConverterType = typename ConverterTrait::type; + + Status Reserve(int64_t additional_capacity) override { + ARROW_RETURN_NOT_OK(this->builder_->Reserve(additional_capacity)); + for (const auto& child : children_) { + ARROW_RETURN_NOT_OK(child->Reserve(additional_capacity)); + } + return Status::OK(); + } + + protected: + Status Init(MemoryPool* pool) override { + std::unique_ptr child_converter; + std::vector> child_builders; + + struct_type_ = checked_cast(this->type_.get()); + for (const auto& field : struct_type_->fields()) { + ARROW_ASSIGN_OR_RAISE(child_converter, + (MakeConverter( + field->type(), this->options_, pool))); + this->may_overflow_ |= child_converter->may_overflow(); + this->rewind_on_overflow_ = this->may_overflow_; + child_builders.push_back(child_converter->builder()); + children_.push_back(std::move(child_converter)); + } + + this->builder_ = + std::make_shared(this->type_, pool, std::move(child_builders)); + struct_builder_ = checked_cast(this->builder_.get()); + + return Status::OK(); + } + + const StructType* struct_type_; + StructBuilder* struct_builder_; + std::vector> children_; +}; + +template +class DictionaryConverter : public BaseConverter { + public: + using BuilderType = DictionaryBuilder; + + protected: + Status Init(MemoryPool* pool) override { + std::unique_ptr builder; + ARROW_RETURN_NOT_OK(MakeDictionaryBuilder(pool, this->type_, NULLPTR, &builder)); + this->builder_ = std::move(builder); + this->may_overflow_ = false; + dict_type_ = checked_cast(this->type_.get()); + value_type_ = checked_cast(dict_type_->value_type().get()); + value_builder_ = checked_cast(this->builder_.get()); + return Status::OK(); + } + + const DictionaryType* dict_type_; + const ValueType* value_type_; + BuilderType* value_builder_; +}; + +template class ConverterTrait> +struct MakeConverterImpl { + template ::type> + Status Visit(const T&) { + out.reset(new ConverterType()); + return out->Construct(std::move(type), std::move(options), pool); + } + + Status Visit(const DictionaryType& t) { + switch (t.value_type()->id()) { +#define DICTIONARY_CASE(TYPE) \ + case TYPE::type_id: \ + out = std::make_unique< \ + typename ConverterTrait::template dictionary_type>(); \ + break; + DICTIONARY_CASE(BooleanType); + DICTIONARY_CASE(Int8Type); + DICTIONARY_CASE(Int16Type); + DICTIONARY_CASE(Int32Type); + DICTIONARY_CASE(Int64Type); + DICTIONARY_CASE(UInt8Type); + DICTIONARY_CASE(UInt16Type); + DICTIONARY_CASE(UInt32Type); + DICTIONARY_CASE(UInt64Type); + DICTIONARY_CASE(FloatType); + DICTIONARY_CASE(DoubleType); + DICTIONARY_CASE(BinaryType); + DICTIONARY_CASE(StringType); + DICTIONARY_CASE(FixedSizeBinaryType); +#undef DICTIONARY_CASE + default: + return Status::NotImplemented("DictionaryArray converter for type ", t.ToString(), + " not implemented"); + } + return out->Construct(std::move(type), std::move(options), pool); + } + + Status Visit(const DataType& t) { return Status::NotImplemented(t.name()); } + + std::shared_ptr type; + typename BaseConverter::OptionsType options; + MemoryPool* pool; + std::unique_ptr out; +}; + +template class ConverterTrait> +static Result> MakeConverter( + std::shared_ptr type, typename BaseConverter::OptionsType options, + MemoryPool* pool) { + MakeConverterImpl visitor{ + std::move(type), std::move(options), pool, NULLPTR}; + ARROW_RETURN_NOT_OK(VisitTypeInline(*visitor.type, &visitor)); + return std::move(visitor.out); +} + +template +class Chunker { + public: + using InputType = typename Converter::InputType; + + explicit Chunker(std::unique_ptr converter) + : converter_(std::move(converter)) {} + + Status Reserve(int64_t additional_capacity) { + ARROW_RETURN_NOT_OK(converter_->Reserve(additional_capacity)); + reserved_ += additional_capacity; + return Status::OK(); + } + + Status AppendNull() { + auto status = converter_->AppendNull(); + if (ARROW_PREDICT_FALSE(status.IsCapacityError())) { + if (converter_->builder()->length() == 0) { + // Builder length == 0 means the individual element is too large to append. + // In this case, no need to try again. + return status; + } + ARROW_RETURN_NOT_OK(FinishChunk()); + return converter_->AppendNull(); + } + ++length_; + return status; + } + + Status Append(InputType value) { + auto status = converter_->Append(value); + if (ARROW_PREDICT_FALSE(status.IsCapacityError())) { + if (converter_->builder()->length() == 0) { + return status; + } + ARROW_RETURN_NOT_OK(FinishChunk()); + return Append(value); + } + ++length_; + return status; + } + + Status Extend(InputType values, int64_t size, int64_t offset = 0) { + while (offset < size) { + auto length_before = converter_->builder()->length(); + auto status = converter_->Extend(values, size, offset); + auto length_after = converter_->builder()->length(); + auto num_converted = length_after - length_before; + + offset += num_converted; + length_ += num_converted; + + if (status.IsCapacityError()) { + if (converter_->builder()->length() == 0) { + // Builder length == 0 means the individual element is too large to append. + // In this case, no need to try again. + return status; + } else if (converter_->rewind_on_overflow()) { + // The list-like and binary-like conversion paths may raise a capacity error, + // we need to handle them differently. While the binary-like converters check + // the capacity before append/extend the list-like converters just check after + // append/extend. Thus depending on the implementation semantics we may need + // to rewind (slice) the output chunk by one. + length_ -= 1; + offset -= 1; + } + ARROW_RETURN_NOT_OK(FinishChunk()); + } else if (!status.ok()) { + return status; + } + } + return Status::OK(); + } + + Status ExtendMasked(InputType values, InputType mask, int64_t size, + int64_t offset = 0) { + while (offset < size) { + auto length_before = converter_->builder()->length(); + auto status = converter_->ExtendMasked(values, mask, size, offset); + auto length_after = converter_->builder()->length(); + auto num_converted = length_after - length_before; + + offset += num_converted; + length_ += num_converted; + + if (status.IsCapacityError()) { + if (converter_->builder()->length() == 0) { + // Builder length == 0 means the individual element is too large to append. + // In this case, no need to try again. + return status; + } else if (converter_->rewind_on_overflow()) { + // The list-like and binary-like conversion paths may raise a capacity error, + // we need to handle them differently. While the binary-like converters check + // the capacity before append/extend the list-like converters just check after + // append/extend. Thus depending on the implementation semantics we may need + // to rewind (slice) the output chunk by one. + length_ -= 1; + offset -= 1; + } + ARROW_RETURN_NOT_OK(FinishChunk()); + } else if (!status.ok()) { + return status; + } + } + return Status::OK(); + } + + Status FinishChunk() { + ARROW_ASSIGN_OR_RAISE(auto chunk, converter_->ToArray(length_)); + chunks_.push_back(chunk); + // Reserve space for the remaining items. + // Besides being an optimization, it is also required if the converter's + // implementation relies on unsafe builder methods in converter->Append(). + auto remaining = reserved_ - length_; + Reset(); + return Reserve(remaining); + } + + Result> ToChunkedArray() { + ARROW_RETURN_NOT_OK(FinishChunk()); + return std::make_shared(chunks_); + } + + protected: + void Reset() { + converter_->builder()->Reset(); + length_ = 0; + reserved_ = 0; + } + + int64_t length_ = 0; + int64_t reserved_ = 0; + std::unique_ptr converter_; + std::vector> chunks_; +}; + +template +static Result>> MakeChunker(std::unique_ptr converter) { + return std::make_unique>(std::move(converter)); +} + +} // namespace internal +} // namespace arrow diff --git a/shared/package-files/3c/3c8389694dc8bd47bd88beba673b65909f91ef4bf661256e14878ce6f8954b1d/__init__.py b/shared/package-files/3c/3c8389694dc8bd47bd88beba673b65909f91ef4bf661256e14878ce6f8954b1d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..838b6affd283633c2269cb91db4bf9eaebda318e --- /dev/null +++ b/shared/package-files/3c/3c8389694dc8bd47bd88beba673b65909f91ef4bf661256e14878ce6f8954b1d/__init__.py @@ -0,0 +1,57 @@ +""" +pandas._config is considered explicitly upstream of everything else in pandas, +should have no intra-pandas dependencies. + +importing `dates` and `display` ensures that keys needed by _libs +are initialized. +""" +__all__ = [ + "config", + "detect_console_encoding", + "get_option", + "set_option", + "reset_option", + "describe_option", + "option_context", + "options", + "using_copy_on_write", + "warn_copy_on_write", +] +from pandas._config import config +from pandas._config import dates # pyright: ignore[reportUnusedImport] # noqa: F401 +from pandas._config.config import ( + _global_config, + describe_option, + get_option, + option_context, + options, + reset_option, + set_option, +) +from pandas._config.display import detect_console_encoding + + +def using_copy_on_write() -> bool: + _mode_options = _global_config["mode"] + return ( + _mode_options["copy_on_write"] is True + and _mode_options["data_manager"] == "block" + ) + + +def warn_copy_on_write() -> bool: + _mode_options = _global_config["mode"] + return ( + _mode_options["copy_on_write"] == "warn" + and _mode_options["data_manager"] == "block" + ) + + +def using_nullable_dtypes() -> bool: + _mode_options = _global_config["mode"] + return _mode_options["nullable_dtypes"] + + +def using_string_dtype() -> bool: + _mode_options = _global_config["future"] + return _mode_options["infer_string"] diff --git a/shared/package-files/3c/3c90ae8f4db8929162cc9bce5ab7a6070836c6b11c905b992fda79e3ba8f54e3/pairwise_distance_compositeimplicitautograd_dispatch.h b/shared/package-files/3c/3c90ae8f4db8929162cc9bce5ab7a6070836c6b11c905b992fda79e3ba8f54e3/pairwise_distance_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..cb5d0d1487c0babb782167f6ab08a691eac1e875 --- /dev/null +++ b/shared/package-files/3c/3c90ae8f4db8929162cc9bce5ab7a6070836c6b11c905b992fda79e3ba8f54e3/pairwise_distance_compositeimplicitautograd_dispatch.h @@ -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 pairwise_distance(const at::Tensor & x1, const at::Tensor & x2, double p=2, double eps=1e-06, bool keepdim=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/3c/3c9cd87512d2b6510eaa69d0b35631962ccfac9a23de34d9b9495e4449fa0084/compiler.py b/shared/package-files/3c/3c9cd87512d2b6510eaa69d0b35631962ccfac9a23de34d9b9495e4449fa0084/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..ff95c807b0bab10991df53f82de2c94a0db7edc8 --- /dev/null +++ b/shared/package-files/3c/3c9cd87512d2b6510eaa69d0b35631962ccfac9a23de34d9b9495e4449fa0084/compiler.py @@ -0,0 +1,1956 @@ +"""Compiles nodes from the parser into Python code.""" +import typing as t +from contextlib import contextmanager +from functools import update_wrapper +from io import StringIO +from itertools import chain +from keyword import iskeyword as is_python_keyword + +from markupsafe import escape +from markupsafe import Markup + +from . import nodes +from .exceptions import TemplateAssertionError +from .idtracking import Symbols +from .idtracking import VAR_LOAD_ALIAS +from .idtracking import VAR_LOAD_PARAMETER +from .idtracking import VAR_LOAD_RESOLVE +from .idtracking import VAR_LOAD_UNDEFINED +from .nodes import EvalContext +from .optimizer import Optimizer +from .utils import _PassArg +from .utils import concat +from .visitor import NodeVisitor + +if t.TYPE_CHECKING: + import typing_extensions as te + from .environment import Environment + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + +operators = { + "eq": "==", + "ne": "!=", + "gt": ">", + "gteq": ">=", + "lt": "<", + "lteq": "<=", + "in": "in", + "notin": "not in", +} + + +def optimizeconst(f: F) -> F: + def new_func( + self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any + ) -> t.Any: + # Only optimize if the frame is not volatile + if self.optimizer is not None and not frame.eval_ctx.volatile: + new_node = self.optimizer.visit(node, frame.eval_ctx) + + if new_node != node: + return self.visit(new_node, frame) + + return f(self, node, frame, **kwargs) + + return update_wrapper(t.cast(F, new_func), f) + + +def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed + and op in self.environment.intercepted_binops # type: ignore + ): + self.write(f"environment.call_binop(context, {op!r}, ") + self.visit(node.left, frame) + self.write(", ") + self.visit(node.right, frame) + else: + self.write("(") + self.visit(node.left, frame) + self.write(f" {op} ") + self.visit(node.right, frame) + + self.write(")") + + return visitor + + +def _make_unop( + op: str, +) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed + and op in self.environment.intercepted_unops # type: ignore + ): + self.write(f"environment.call_unop(context, {op!r}, ") + self.visit(node.node, frame) + else: + self.write("(" + op) + self.visit(node.node, frame) + + self.write(")") + + return visitor + + +def generate( + node: nodes.Template, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, +) -> t.Optional[str]: + """Generate the python source for a node tree.""" + if not isinstance(node, nodes.Template): + raise TypeError("Can't compile non template nodes") + + generator = environment.code_generator_class( + environment, name, filename, stream, defer_init, optimized + ) + generator.visit(node) + + if stream is None: + return generator.stream.getvalue() # type: ignore + + return None + + +def has_safe_repr(value: t.Any) -> bool: + """Does the node have a safe representation?""" + if value is None or value is NotImplemented or value is Ellipsis: + return True + + if type(value) in {bool, int, float, complex, range, str, Markup}: + return True + + if type(value) in {tuple, list, set, frozenset}: + return all(has_safe_repr(v) for v in value) + + if type(value) is dict: + return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items()) + + return False + + +def find_undeclared( + nodes: t.Iterable[nodes.Node], names: t.Iterable[str] +) -> t.Set[str]: + """Check if the names passed are accessed undeclared. The return value + is a set of all the undeclared names from the sequence of names found. + """ + visitor = UndeclaredNameVisitor(names) + try: + for node in nodes: + visitor.visit(node) + except VisitorExit: + pass + return visitor.undeclared + + +class MacroRef: + def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: + self.node = node + self.accesses_caller = False + self.accesses_kwargs = False + self.accesses_varargs = False + + +class Frame: + """Holds compile time information for us.""" + + def __init__( + self, + eval_ctx: EvalContext, + parent: t.Optional["Frame"] = None, + level: t.Optional[int] = None, + ) -> None: + self.eval_ctx = eval_ctx + + # the parent of this frame + self.parent = parent + + if parent is None: + self.symbols = Symbols(level=level) + + # in some dynamic inheritance situations the compiler needs to add + # write tests around output statements. + self.require_output_check = False + + # inside some tags we are using a buffer rather than yield statements. + # this for example affects {% filter %} or {% macro %}. If a frame + # is buffered this variable points to the name of the list used as + # buffer. + self.buffer: t.Optional[str] = None + + # the name of the block we're in, otherwise None. + self.block: t.Optional[str] = None + + else: + self.symbols = Symbols(parent.symbols, level=level) + self.require_output_check = parent.require_output_check + self.buffer = parent.buffer + self.block = parent.block + + # a toplevel frame is the root + soft frames such as if conditions. + self.toplevel = False + + # the root frame is basically just the outermost frame, so no if + # conditions. This information is used to optimize inheritance + # situations. + self.rootlevel = False + + # variables set inside of loops and blocks should not affect outer frames, + # but they still needs to be kept track of as part of the active context. + self.loop_frame = False + self.block_frame = False + + # track whether the frame is being used in an if-statement or conditional + # expression as it determines which errors should be raised during runtime + # or compile time. + self.soft_frame = False + + def copy(self) -> "Frame": + """Create a copy of the current one.""" + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.symbols = self.symbols.copy() + return rv + + def inner(self, isolated: bool = False) -> "Frame": + """Return an inner frame.""" + if isolated: + return Frame(self.eval_ctx, level=self.symbols.level + 1) + return Frame(self.eval_ctx, self) + + def soft(self) -> "Frame": + """Return a soft frame. A soft frame may not be modified as + standalone thing as it shares the resources with the frame it + was created of, but it's not a rootlevel frame any longer. + + This is only used to implement if-statements and conditional + expressions. + """ + rv = self.copy() + rv.rootlevel = False + rv.soft_frame = True + return rv + + __copy__ = copy + + +class VisitorExit(RuntimeError): + """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" + + +class DependencyFinderVisitor(NodeVisitor): + """A visitor that collects filter and test calls.""" + + def __init__(self) -> None: + self.filters: t.Set[str] = set() + self.tests: t.Set[str] = set() + + def visit_Filter(self, node: nodes.Filter) -> None: + self.generic_visit(node) + self.filters.add(node.name) + + def visit_Test(self, node: nodes.Test) -> None: + self.generic_visit(node) + self.tests.add(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting at blocks.""" + + +class UndeclaredNameVisitor(NodeVisitor): + """A visitor that checks if a name is accessed without being + declared. This is different from the frame visitor as it will + not stop at closure frames. + """ + + def __init__(self, names: t.Iterable[str]) -> None: + self.names = set(names) + self.undeclared: t.Set[str] = set() + + def visit_Name(self, node: nodes.Name) -> None: + if node.ctx == "load" and node.name in self.names: + self.undeclared.add(node.name) + if self.undeclared == self.names: + raise VisitorExit() + else: + self.names.discard(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting a blocks.""" + + +class CompilerExit(Exception): + """Raised if the compiler encountered a situation where it just + doesn't make sense to further process the code. Any block that + raises such an exception is not further processed. + """ + + +class CodeGenerator(NodeVisitor): + def __init__( + self, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, + ) -> None: + if stream is None: + stream = StringIO() + self.environment = environment + self.name = name + self.filename = filename + self.stream = stream + self.created_block_context = False + self.defer_init = defer_init + self.optimizer: t.Optional[Optimizer] = None + + if optimized: + self.optimizer = Optimizer(environment) + + # aliases for imports + self.import_aliases: t.Dict[str, str] = {} + + # a registry for all blocks. Because blocks are moved out + # into the global python scope they are registered here + self.blocks: t.Dict[str, nodes.Block] = {} + + # the number of extends statements so far + self.extends_so_far = 0 + + # some templates have a rootlevel extends. In this case we + # can safely assume that we're a child template and do some + # more optimizations. + self.has_known_extends = False + + # the current line number + self.code_lineno = 1 + + # registry of all filters and tests (global, not block local) + self.tests: t.Dict[str, str] = {} + self.filters: t.Dict[str, str] = {} + + # the debug information + self.debug_info: t.List[t.Tuple[int, int]] = [] + self._write_debug_info: t.Optional[int] = None + + # the number of new lines before the next write() + self._new_lines = 0 + + # the line number of the last written statement + self._last_line = 0 + + # true if nothing was written so far. + self._first_write = True + + # used by the `temporary_identifier` method to get new + # unique, temporary identifier + self._last_identifier = 0 + + # the current indentation + self._indentation = 0 + + # Tracks toplevel assignments + self._assign_stack: t.List[t.Set[str]] = [] + + # Tracks parameter definition blocks + self._param_def_block: t.List[t.Set[str]] = [] + + # Tracks the current context. + self._context_reference_stack = ["context"] + + @property + def optimized(self) -> bool: + return self.optimizer is not None + + # -- Various compilation helpers + + def fail(self, msg: str, lineno: int) -> "te.NoReturn": + """Fail with a :exc:`TemplateAssertionError`.""" + raise TemplateAssertionError(msg, lineno, self.name, self.filename) + + def temporary_identifier(self) -> str: + """Get a new unique identifier.""" + self._last_identifier += 1 + return f"t_{self._last_identifier}" + + def buffer(self, frame: Frame) -> None: + """Enable buffering for the frame from that point onwards.""" + frame.buffer = self.temporary_identifier() + self.writeline(f"{frame.buffer} = []") + + def return_buffer_contents( + self, frame: Frame, force_unescaped: bool = False + ) -> None: + """Return the buffer contents of the frame.""" + if not force_unescaped: + if frame.eval_ctx.volatile: + self.writeline("if context.eval_ctx.autoescape:") + self.indent() + self.writeline(f"return Markup(concat({frame.buffer}))") + self.outdent() + self.writeline("else:") + self.indent() + self.writeline(f"return concat({frame.buffer})") + self.outdent() + return + elif frame.eval_ctx.autoescape: + self.writeline(f"return Markup(concat({frame.buffer}))") + return + self.writeline(f"return concat({frame.buffer})") + + def indent(self) -> None: + """Indent by one.""" + self._indentation += 1 + + def outdent(self, step: int = 1) -> None: + """Outdent by step.""" + self._indentation -= step + + def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None: + """Yield or write into the frame buffer.""" + if frame.buffer is None: + self.writeline("yield ", node) + else: + self.writeline(f"{frame.buffer}.append(", node) + + def end_write(self, frame: Frame) -> None: + """End the writing process started by `start_write`.""" + if frame.buffer is not None: + self.write(")") + + def simple_write( + self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None + ) -> None: + """Simple shortcut for start_write + write + end_write.""" + self.start_write(frame, node) + self.write(s) + self.end_write(frame) + + def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None: + """Visit a list of nodes as block in a frame. If the current frame + is no buffer a dummy ``if 0: yield None`` is written automatically. + """ + try: + self.writeline("pass") + for node in nodes: + self.visit(node, frame) + except CompilerExit: + pass + + def write(self, x: str) -> None: + """Write a string into the output stream.""" + if self._new_lines: + if not self._first_write: + self.stream.write("\n" * self._new_lines) + self.code_lineno += self._new_lines + if self._write_debug_info is not None: + self.debug_info.append((self._write_debug_info, self.code_lineno)) + self._write_debug_info = None + self._first_write = False + self.stream.write(" " * self._indentation) + self._new_lines = 0 + self.stream.write(x) + + def writeline( + self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 + ) -> None: + """Combination of newline and write.""" + self.newline(node, extra) + self.write(x) + + def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None: + """Add one or more newlines before the next write.""" + self._new_lines = max(self._new_lines, 1 + extra) + if node is not None and node.lineno != self._last_line: + self._write_debug_info = node.lineno + self._last_line = node.lineno + + def signature( + self, + node: t.Union[nodes.Call, nodes.Filter, nodes.Test], + frame: Frame, + extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + ) -> None: + """Writes a function call to the stream for the current node. + A leading comma is added automatically. The extra keyword + arguments may not include python keywords otherwise a syntax + error could occur. The extra keyword arguments should be given + as python dict. + """ + # if any of the given keyword arguments is a python keyword + # we have to make sure that no invalid call is created. + kwarg_workaround = any( + is_python_keyword(t.cast(str, k)) + for k in chain((x.key for x in node.kwargs), extra_kwargs or ()) + ) + + for arg in node.args: + self.write(", ") + self.visit(arg, frame) + + if not kwarg_workaround: + for kwarg in node.kwargs: + self.write(", ") + self.visit(kwarg, frame) + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f", {key}={value}") + if node.dyn_args: + self.write(", *") + self.visit(node.dyn_args, frame) + + if kwarg_workaround: + if node.dyn_kwargs is not None: + self.write(", **dict({") + else: + self.write(", **{") + for kwarg in node.kwargs: + self.write(f"{kwarg.key!r}: ") + self.visit(kwarg.value, frame) + self.write(", ") + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f"{key!r}: {value}, ") + if node.dyn_kwargs is not None: + self.write("}, **") + self.visit(node.dyn_kwargs, frame) + self.write(")") + else: + self.write("}") + + elif node.dyn_kwargs is not None: + self.write(", **") + self.visit(node.dyn_kwargs, frame) + + def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None: + """Find all filter and test names used in the template and + assign them to variables in the compiled namespace. Checking + that the names are registered with the environment is done when + compiling the Filter and Test nodes. If the node is in an If or + CondExpr node, the check is done at runtime instead. + + .. versionchanged:: 3.0 + Filters and tests in If and CondExpr nodes are checked at + runtime instead of compile time. + """ + visitor = DependencyFinderVisitor() + + for node in nodes: + visitor.visit(node) + + for id_map, names, dependency in (self.filters, visitor.filters, "filters"), ( + self.tests, + visitor.tests, + "tests", + ): + for name in sorted(names): + if name not in id_map: + id_map[name] = self.temporary_identifier() + + # add check during runtime that dependencies used inside of executed + # blocks are defined, as this step may be skipped during compile time + self.writeline("try:") + self.indent() + self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]") + self.outdent() + self.writeline("except KeyError:") + self.indent() + self.writeline("@internalcode") + self.writeline(f"def {id_map[name]}(*unused):") + self.indent() + self.writeline( + f'raise TemplateRuntimeError("No {dependency[:-1]}' + f' named {name!r} found.")' + ) + self.outdent() + self.outdent() + + def enter_frame(self, frame: Frame) -> None: + undefs = [] + for target, (action, param) in frame.symbols.loads.items(): + if action == VAR_LOAD_PARAMETER: + pass + elif action == VAR_LOAD_RESOLVE: + self.writeline(f"{target} = {self.get_resolve_func()}({param!r})") + elif action == VAR_LOAD_ALIAS: + self.writeline(f"{target} = {param}") + elif action == VAR_LOAD_UNDEFINED: + undefs.append(target) + else: + raise NotImplementedError("unknown load instruction") + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None: + if not with_python_scope: + undefs = [] + for target in frame.symbols.loads: + undefs.append(target) + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str: + return async_value if self.environment.is_async else sync_value + + def func(self, name: str) -> str: + return f"{self.choose_async()}def {name}" + + def macro_body( + self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame + ) -> t.Tuple[Frame, MacroRef]: + """Dump the function def of a macro or call block.""" + frame = frame.inner() + frame.symbols.analyze_node(node) + macro_ref = MacroRef(node) + + explicit_caller = None + skip_special_params = set() + args = [] + + for idx, arg in enumerate(node.args): + if arg.name == "caller": + explicit_caller = idx + if arg.name in ("kwargs", "varargs"): + skip_special_params.add(arg.name) + args.append(frame.symbols.ref(arg.name)) + + undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs")) + + if "caller" in undeclared: + # In older Jinja versions there was a bug that allowed caller + # to retain the special behavior even if it was mentioned in + # the argument list. However thankfully this was only really + # working if it was the last argument. So we are explicitly + # checking this now and error out if it is anywhere else in + # the argument list. + if explicit_caller is not None: + try: + node.defaults[explicit_caller - len(node.args)] + except IndexError: + self.fail( + "When defining macros or call blocks the " + 'special "caller" argument must be omitted ' + "or be given a default.", + node.lineno, + ) + else: + args.append(frame.symbols.declare_parameter("caller")) + macro_ref.accesses_caller = True + if "kwargs" in undeclared and "kwargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("kwargs")) + macro_ref.accesses_kwargs = True + if "varargs" in undeclared and "varargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("varargs")) + macro_ref.accesses_varargs = True + + # macros are delayed, they never require output checks + frame.require_output_check = False + frame.symbols.analyze_node(node) + self.writeline(f"{self.func('macro')}({', '.join(args)}):", node) + self.indent() + + self.buffer(frame) + self.enter_frame(frame) + + self.push_parameter_definitions(frame) + for idx, arg in enumerate(node.args): + ref = frame.symbols.ref(arg.name) + self.writeline(f"if {ref} is missing:") + self.indent() + try: + default = node.defaults[idx - len(node.args)] + except IndexError: + self.writeline( + f'{ref} = undefined("parameter {arg.name!r} was not provided",' + f" name={arg.name!r})" + ) + else: + self.writeline(f"{ref} = ") + self.visit(default, frame) + self.mark_parameter_stored(ref) + self.outdent() + self.pop_parameter_definitions() + + self.blockvisit(node.body, frame) + self.return_buffer_contents(frame, force_unescaped=True) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + return frame, macro_ref + + def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None: + """Dump the macro definition for the def created by macro_body.""" + arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args) + name = getattr(macro_ref.node, "name", None) + if len(macro_ref.node.args) == 1: + arg_tuple += "," + self.write( + f"Macro(environment, macro, {name!r}, ({arg_tuple})," + f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r}," + f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)" + ) + + def position(self, node: nodes.Node) -> str: + """Return a human readable position for the node.""" + rv = f"line {node.lineno}" + if self.name is not None: + rv = f"{rv} in {self.name!r}" + return rv + + def dump_local_context(self, frame: Frame) -> str: + items_kv = ", ".join( + f"{name!r}: {target}" + for name, target in frame.symbols.dump_stores().items() + ) + return f"{{{items_kv}}}" + + def write_commons(self) -> None: + """Writes a common preamble that is used by root and block functions. + Primarily this sets up common local helpers and enforces a generator + through a dead branch. + """ + self.writeline("resolve = context.resolve_or_missing") + self.writeline("undefined = environment.undefined") + self.writeline("concat = environment.concat") + # always use the standard Undefined class for the implicit else of + # conditional expressions + self.writeline("cond_expr_undefined = Undefined") + self.writeline("if 0: yield None") + + def push_parameter_definitions(self, frame: Frame) -> None: + """Pushes all parameter targets from the given frame into a local + stack that permits tracking of yet to be assigned parameters. In + particular this enables the optimization from `visit_Name` to skip + undefined expressions for parameters in macros as macros can reference + otherwise unbound parameters. + """ + self._param_def_block.append(frame.symbols.dump_param_targets()) + + def pop_parameter_definitions(self) -> None: + """Pops the current parameter definitions set.""" + self._param_def_block.pop() + + def mark_parameter_stored(self, target: str) -> None: + """Marks a parameter in the current parameter definitions as stored. + This will skip the enforced undefined checks. + """ + if self._param_def_block: + self._param_def_block[-1].discard(target) + + def push_context_reference(self, target: str) -> None: + self._context_reference_stack.append(target) + + def pop_context_reference(self) -> None: + self._context_reference_stack.pop() + + def get_context_ref(self) -> str: + return self._context_reference_stack[-1] + + def get_resolve_func(self) -> str: + target = self._context_reference_stack[-1] + if target == "context": + return "resolve" + return f"{target}.resolve" + + def derive_context(self, frame: Frame) -> str: + return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})" + + def parameter_is_undeclared(self, target: str) -> bool: + """Checks if a given target is an undeclared parameter.""" + if not self._param_def_block: + return False + return target in self._param_def_block[-1] + + def push_assign_tracking(self) -> None: + """Pushes a new layer for assignment tracking.""" + self._assign_stack.append(set()) + + def pop_assign_tracking(self, frame: Frame) -> None: + """Pops the topmost level for assignment tracking and updates the + context variables if necessary. + """ + vars = self._assign_stack.pop() + if ( + not frame.block_frame + and not frame.loop_frame + and not frame.toplevel + or not vars + ): + return + public_names = [x for x in vars if x[:1] != "_"] + if len(vars) == 1: + name = next(iter(vars)) + ref = frame.symbols.ref(name) + if frame.loop_frame: + self.writeline(f"_loop_vars[{name!r}] = {ref}") + return + if frame.block_frame: + self.writeline(f"_block_vars[{name!r}] = {ref}") + return + self.writeline(f"context.vars[{name!r}] = {ref}") + else: + if frame.loop_frame: + self.writeline("_loop_vars.update({") + elif frame.block_frame: + self.writeline("_block_vars.update({") + else: + self.writeline("context.vars.update({") + for idx, name in enumerate(vars): + if idx: + self.write(", ") + ref = frame.symbols.ref(name) + self.write(f"{name!r}: {ref}") + self.write("})") + if not frame.block_frame and not frame.loop_frame and public_names: + if len(public_names) == 1: + self.writeline(f"context.exported_vars.add({public_names[0]!r})") + else: + names_str = ", ".join(map(repr, public_names)) + self.writeline(f"context.exported_vars.update(({names_str}))") + + # -- Statement Visitors + + def visit_Template( + self, node: nodes.Template, frame: t.Optional[Frame] = None + ) -> None: + assert frame is None, "no root frame allowed" + eval_ctx = EvalContext(self.environment, self.name) + + from .runtime import exported, async_exported + + if self.environment.is_async: + exported_names = sorted(exported + async_exported) + else: + exported_names = sorted(exported) + + self.writeline("from jinja2.runtime import " + ", ".join(exported_names)) + + # if we want a deferred initialization we cannot move the + # environment into a local name + envenv = "" if self.defer_init else ", environment=environment" + + # do we have an extends tag at all? If not, we can save some + # overhead by just not processing any inheritance code. + have_extends = node.find(nodes.Extends) is not None + + # find all blocks + for block in node.find_all(nodes.Block): + if block.name in self.blocks: + self.fail(f"block {block.name!r} defined twice", block.lineno) + self.blocks[block.name] = block + + # find all imports and import them + for import_ in node.find_all(nodes.ImportedName): + if import_.importname not in self.import_aliases: + imp = import_.importname + self.import_aliases[imp] = alias = self.temporary_identifier() + if "." in imp: + module, obj = imp.rsplit(".", 1) + self.writeline(f"from {module} import {obj} as {alias}") + else: + self.writeline(f"import {imp} as {alias}") + + # add the load name + self.writeline(f"name = {self.name!r}") + + # generate the root render function. + self.writeline( + f"{self.func('root')}(context, missing=missing{envenv}):", extra=1 + ) + self.indent() + self.write_commons() + + # process the root + frame = Frame(eval_ctx) + if "self" in find_undeclared(node.body, ("self",)): + ref = frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + frame.symbols.analyze_node(node) + frame.toplevel = frame.rootlevel = True + frame.require_output_check = have_extends and not self.has_known_extends + if have_extends: + self.writeline("parent_template = None") + self.enter_frame(frame) + self.pull_dependencies(node.body) + self.blockvisit(node.body, frame) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + # make sure that the parent root is called. + if have_extends: + if not self.has_known_extends: + self.indent() + self.writeline("if parent_template is not None:") + self.indent() + if not self.environment.is_async: + self.writeline("yield from parent_template.root_render_func(context)") + else: + self.writeline( + "async for event in parent_template.root_render_func(context):" + ) + self.indent() + self.writeline("yield event") + self.outdent() + self.outdent(1 + (not self.has_known_extends)) + + # at this point we now have the blocks collected and can visit them too. + for name, block in self.blocks.items(): + self.writeline( + f"{self.func('block_' + name)}(context, missing=missing{envenv}):", + block, + 1, + ) + self.indent() + self.write_commons() + # It's important that we do not make this frame a child of the + # toplevel template. This would cause a variety of + # interesting issues with identifier tracking. + block_frame = Frame(eval_ctx) + block_frame.block_frame = True + undeclared = find_undeclared(block.body, ("self", "super")) + if "self" in undeclared: + ref = block_frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + if "super" in undeclared: + ref = block_frame.symbols.declare_parameter("super") + self.writeline(f"{ref} = context.super({name!r}, block_{name})") + block_frame.symbols.analyze_node(block) + block_frame.block = name + self.writeline("_block_vars = {}") + self.enter_frame(block_frame) + self.pull_dependencies(block.body) + self.blockvisit(block.body, block_frame) + self.leave_frame(block_frame, with_python_scope=True) + self.outdent() + + blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks) + self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1) + debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info) + self.writeline(f"debug_info = {debug_kv_str!r}") + + def visit_Block(self, node: nodes.Block, frame: Frame) -> None: + """Call a block and register it for the template.""" + level = 0 + if frame.toplevel: + # if we know that we are a child template, there is no need to + # check if we are one + if self.has_known_extends: + return + if self.extends_so_far > 0: + self.writeline("if parent_template is None:") + self.indent() + level += 1 + + if node.scoped: + context = self.derive_context(frame) + else: + context = self.get_context_ref() + + if node.required: + self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node) + self.indent() + self.writeline( + f'raise TemplateRuntimeError("Required block {node.name!r} not found")', + node, + ) + self.outdent() + + if not self.environment.is_async and frame.buffer is None: + self.writeline( + f"yield from context.blocks[{node.name!r}][0]({context})", node + ) + else: + self.writeline( + f"{self.choose_async()}for event in" + f" context.blocks[{node.name!r}][0]({context}):", + node, + ) + self.indent() + self.simple_write("event", frame) + self.outdent() + + self.outdent(level) + + def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None: + """Calls the extender.""" + if not frame.toplevel: + self.fail("cannot use extend from a non top-level scope", node.lineno) + + # if the number of extends statements in general is zero so + # far, we don't have to add a check if something extended + # the template before this one. + if self.extends_so_far > 0: + # if we have a known extends we just add a template runtime + # error into the generated code. We could catch that at compile + # time too, but i welcome it not to confuse users by throwing the + # same error at different times just "because we can". + if not self.has_known_extends: + self.writeline("if parent_template is not None:") + self.indent() + self.writeline('raise TemplateRuntimeError("extended multiple times")') + + # if we have a known extends already we don't need that code here + # as we know that the template execution will end here. + if self.has_known_extends: + raise CompilerExit() + else: + self.outdent() + + self.writeline("parent_template = environment.get_template(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + self.writeline("for name, parent_block in parent_template.blocks.items():") + self.indent() + self.writeline("context.blocks.setdefault(name, []).append(parent_block)") + self.outdent() + + # if this extends statement was in the root level we can take + # advantage of that information and simplify the generated code + # in the top level from this point onwards + if frame.rootlevel: + self.has_known_extends = True + + # and now we have one more + self.extends_so_far += 1 + + def visit_Include(self, node: nodes.Include, frame: Frame) -> None: + """Handles includes.""" + if node.ignore_missing: + self.writeline("try:") + self.indent() + + func_name = "get_or_select_template" + if isinstance(node.template, nodes.Const): + if isinstance(node.template.value, str): + func_name = "get_template" + elif isinstance(node.template.value, (tuple, list)): + func_name = "select_template" + elif isinstance(node.template, (nodes.Tuple, nodes.List)): + func_name = "select_template" + + self.writeline(f"template = environment.{func_name}(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + if node.ignore_missing: + self.outdent() + self.writeline("except TemplateNotFound:") + self.indent() + self.writeline("pass") + self.outdent() + self.writeline("else:") + self.indent() + + skip_event_yield = False + if node.with_context: + self.writeline( + f"{self.choose_async()}for event in template.root_render_func(" + "template.new_context(context.get_all(), True," + f" {self.dump_local_context(frame)})):" + ) + elif self.environment.is_async: + self.writeline( + "for event in (await template._get_default_module_async())" + "._body_stream:" + ) + else: + self.writeline("yield from template._get_default_module()._body_stream") + skip_event_yield = True + + if not skip_event_yield: + self.indent() + self.simple_write("event", frame) + self.outdent() + + if node.ignore_missing: + self.outdent() + + def _import_common( + self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame + ) -> None: + self.write(f"{self.choose_async('await ')}environment.get_template(") + self.visit(node.template, frame) + self.write(f", {self.name!r}).") + + if node.with_context: + f_name = f"make_module{self.choose_async('_async')}" + self.write( + f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" + ) + else: + self.write(f"_get_default_module{self.choose_async('_async')}(context)") + + def visit_Import(self, node: nodes.Import, frame: Frame) -> None: + """Visit regular imports.""" + self.writeline(f"{frame.symbols.ref(node.target)} = ", node) + if frame.toplevel: + self.write(f"context.vars[{node.target!r}] = ") + + self._import_common(node, frame) + + if frame.toplevel and not node.target.startswith("_"): + self.writeline(f"context.exported_vars.discard({node.target!r})") + + def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None: + """Visit named imports.""" + self.newline(node) + self.write("included_template = ") + self._import_common(node, frame) + var_names = [] + discarded_names = [] + for name in node.names: + if isinstance(name, tuple): + name, alias = name + else: + alias = name + self.writeline( + f"{frame.symbols.ref(alias)} =" + f" getattr(included_template, {name!r}, missing)" + ) + self.writeline(f"if {frame.symbols.ref(alias)} is missing:") + self.indent() + message = ( + "the template {included_template.__name__!r}" + f" (imported on {self.position(node)})" + f" does not export the requested name {name!r}" + ) + self.writeline( + f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})" + ) + self.outdent() + if frame.toplevel: + var_names.append(alias) + if not alias.startswith("_"): + discarded_names.append(alias) + + if var_names: + if len(var_names) == 1: + name = var_names[0] + self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}") + else: + names_kv = ", ".join( + f"{name!r}: {frame.symbols.ref(name)}" for name in var_names + ) + self.writeline(f"context.vars.update({{{names_kv}}})") + if discarded_names: + if len(discarded_names) == 1: + self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})") + else: + names_str = ", ".join(map(repr, discarded_names)) + self.writeline( + f"context.exported_vars.difference_update(({names_str}))" + ) + + def visit_For(self, node: nodes.For, frame: Frame) -> None: + loop_frame = frame.inner() + loop_frame.loop_frame = True + test_frame = frame.inner() + else_frame = frame.inner() + + # try to figure out if we have an extended loop. An extended loop + # is necessary if the loop is in recursive mode if the special loop + # variable is accessed in the body if the body is a scoped block. + extended_loop = ( + node.recursive + or "loop" + in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",)) + or any(block.scoped for block in node.find_all(nodes.Block)) + ) + + loop_ref = None + if extended_loop: + loop_ref = loop_frame.symbols.declare_parameter("loop") + + loop_frame.symbols.analyze_node(node, for_branch="body") + if node.else_: + else_frame.symbols.analyze_node(node, for_branch="else") + + if node.test: + loop_filter_func = self.temporary_identifier() + test_frame.symbols.analyze_node(node, for_branch="test") + self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test) + self.indent() + self.enter_frame(test_frame) + self.writeline(self.choose_async("async for ", "for ")) + self.visit(node.target, loop_frame) + self.write(" in ") + self.write(self.choose_async("auto_aiter(fiter)", "fiter")) + self.write(":") + self.indent() + self.writeline("if ", node.test) + self.visit(node.test, test_frame) + self.write(":") + self.indent() + self.writeline("yield ") + self.visit(node.target, loop_frame) + self.outdent(3) + self.leave_frame(test_frame, with_python_scope=True) + + # if we don't have an recursive loop we have to find the shadowed + # variables at that point. Because loops can be nested but the loop + # variable is a special one we have to enforce aliasing for it. + if node.recursive: + self.writeline( + f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node + ) + self.indent() + self.buffer(loop_frame) + + # Use the same buffer for the else frame + else_frame.buffer = loop_frame.buffer + + # make sure the loop variable is a special one and raise a template + # assertion error if a loop tries to write to loop + if extended_loop: + self.writeline(f"{loop_ref} = missing") + + for name in node.find_all(nodes.Name): + if name.ctx == "store" and name.name == "loop": + self.fail( + "Can't assign to special loop variable in for-loop target", + name.lineno, + ) + + if node.else_: + iteration_indicator = self.temporary_identifier() + self.writeline(f"{iteration_indicator} = 1") + + self.writeline(self.choose_async("async for ", "for "), node) + self.visit(node.target, loop_frame) + if extended_loop: + self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(") + else: + self.write(" in ") + + if node.test: + self.write(f"{loop_filter_func}(") + if node.recursive: + self.write("reciter") + else: + if self.environment.is_async and not extended_loop: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async and not extended_loop: + self.write(")") + if node.test: + self.write(")") + + if node.recursive: + self.write(", undefined, loop_render_func, depth):") + else: + self.write(", undefined):" if extended_loop else ":") + + self.indent() + self.enter_frame(loop_frame) + + self.writeline("_loop_vars = {}") + self.blockvisit(node.body, loop_frame) + if node.else_: + self.writeline(f"{iteration_indicator} = 0") + self.outdent() + self.leave_frame( + loop_frame, with_python_scope=node.recursive and not node.else_ + ) + + if node.else_: + self.writeline(f"if {iteration_indicator}:") + self.indent() + self.enter_frame(else_frame) + self.blockvisit(node.else_, else_frame) + self.leave_frame(else_frame) + self.outdent() + + # if the node was recursive we have to return the buffer contents + # and start the iteration code + if node.recursive: + self.return_buffer_contents(loop_frame) + self.outdent() + self.start_write(frame, node) + self.write(f"{self.choose_async('await ')}loop(") + if self.environment.is_async: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async: + self.write(")") + self.write(", loop)") + self.end_write(frame) + + # at the end of the iteration, clear any assignments made in the + # loop from the top level + if self._assign_stack: + self._assign_stack[-1].difference_update(loop_frame.symbols.stores) + + def visit_If(self, node: nodes.If, frame: Frame) -> None: + if_frame = frame.soft() + self.writeline("if ", node) + self.visit(node.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(node.body, if_frame) + self.outdent() + for elif_ in node.elif_: + self.writeline("elif ", elif_) + self.visit(elif_.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(elif_.body, if_frame) + self.outdent() + if node.else_: + self.writeline("else:") + self.indent() + self.blockvisit(node.else_, if_frame) + self.outdent() + + def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None: + macro_frame, macro_ref = self.macro_body(node, frame) + self.newline() + if frame.toplevel: + if not node.name.startswith("_"): + self.write(f"context.exported_vars.add({node.name!r})") + self.writeline(f"context.vars[{node.name!r}] = ") + self.write(f"{frame.symbols.ref(node.name)} = ") + self.macro_def(macro_ref, macro_frame) + + def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None: + call_frame, macro_ref = self.macro_body(node, frame) + self.writeline("caller = ") + self.macro_def(macro_ref, call_frame) + self.start_write(frame, node) + self.visit_Call(node.call, frame, forward_caller=True) + self.end_write(frame) + + def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None: + filter_frame = frame.inner() + filter_frame.symbols.analyze_node(node) + self.enter_frame(filter_frame) + self.buffer(filter_frame) + self.blockvisit(node.body, filter_frame) + self.start_write(frame, node) + self.visit_Filter(node.filter, filter_frame) + self.end_write(frame) + self.leave_frame(filter_frame) + + def visit_With(self, node: nodes.With, frame: Frame) -> None: + with_frame = frame.inner() + with_frame.symbols.analyze_node(node) + self.enter_frame(with_frame) + for target, expr in zip(node.targets, node.values): + self.newline() + self.visit(target, with_frame) + self.write(" = ") + self.visit(expr, frame) + self.blockvisit(node.body, with_frame) + self.leave_frame(with_frame) + + def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None: + self.newline(node) + self.visit(node.node, frame) + + class _FinalizeInfo(t.NamedTuple): + const: t.Optional[t.Callable[..., str]] + src: t.Optional[str] + + @staticmethod + def _default_finalize(value: t.Any) -> t.Any: + """The default finalize function if the environment isn't + configured with one. Or, if the environment has one, this is + called on that function's output for constants. + """ + return str(value) + + _finalize: t.Optional[_FinalizeInfo] = None + + def _make_finalize(self) -> _FinalizeInfo: + """Build the finalize function to be used on constants and at + runtime. Cached so it's only created once for all output nodes. + + Returns a ``namedtuple`` with the following attributes: + + ``const`` + A function to finalize constant data at compile time. + + ``src`` + Source code to output around nodes to be evaluated at + runtime. + """ + if self._finalize is not None: + return self._finalize + + finalize: t.Optional[t.Callable[..., t.Any]] + finalize = default = self._default_finalize + src = None + + if self.environment.finalize: + src = "environment.finalize(" + env_finalize = self.environment.finalize + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(env_finalize) # type: ignore + ) + finalize = None + + if pass_arg is None: + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(value)) + + else: + src = f"{src}{pass_arg}, " + + if pass_arg == "environment": + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(self.environment, value)) + + self._finalize = self._FinalizeInfo(finalize, src) + return self._finalize + + def _output_const_repr(self, group: t.Iterable[t.Any]) -> str: + """Given a group of constant values converted from ``Output`` + child nodes, produce a string to write to the template module + source. + """ + return repr(concat(group)) + + def _output_child_to_const( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> str: + """Try to optimize a child of an ``Output`` node by trying to + convert it to constant, finalized data at compile time. + + If :exc:`Impossible` is raised, the node is not constant and + will be evaluated at runtime. Any other exception will also be + evaluated at runtime for easier debugging. + """ + const = node.as_const(frame.eval_ctx) + + if frame.eval_ctx.autoescape: + const = escape(const) + + # Template data doesn't go through finalize. + if isinstance(node, nodes.TemplateData): + return str(const) + + return finalize.const(const) # type: ignore + + def _output_child_pre( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code before visiting a child of an + ``Output`` node. + """ + if frame.eval_ctx.volatile: + self.write("(escape if context.eval_ctx.autoescape else str)(") + elif frame.eval_ctx.autoescape: + self.write("escape(") + else: + self.write("str(") + + if finalize.src is not None: + self.write(finalize.src) + + def _output_child_post( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code after visiting a child of an + ``Output`` node. + """ + self.write(")") + + if finalize.src is not None: + self.write(")") + + def visit_Output(self, node: nodes.Output, frame: Frame) -> None: + # If an extends is active, don't render outside a block. + if frame.require_output_check: + # A top-level extends is known to exist at compile time. + if self.has_known_extends: + return + + self.writeline("if parent_template is None:") + self.indent() + + finalize = self._make_finalize() + body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = [] + + # Evaluate constants at compile time if possible. Each item in + # body will be either a list of static data or a node to be + # evaluated at runtime. + for child in node.nodes: + try: + if not ( + # If the finalize function requires runtime context, + # constants can't be evaluated at compile time. + finalize.const + # Unless it's basic template data that won't be + # finalized anyway. + or isinstance(child, nodes.TemplateData) + ): + raise nodes.Impossible() + + const = self._output_child_to_const(child, frame, finalize) + except (nodes.Impossible, Exception): + # The node was not constant and needs to be evaluated at + # runtime. Or another error was raised, which is easier + # to debug at runtime. + body.append(child) + continue + + if body and isinstance(body[-1], list): + body[-1].append(const) + else: + body.append([const]) + + if frame.buffer is not None: + if len(body) == 1: + self.writeline(f"{frame.buffer}.append(") + else: + self.writeline(f"{frame.buffer}.extend((") + + self.indent() + + for item in body: + if isinstance(item, list): + # A group of constant data to join and output. + val = self._output_const_repr(item) + + if frame.buffer is None: + self.writeline("yield " + val) + else: + self.writeline(val + ",") + else: + if frame.buffer is None: + self.writeline("yield ", item) + else: + self.newline(item) + + # A node to be evaluated at runtime. + self._output_child_pre(item, frame, finalize) + self.visit(item, frame) + self._output_child_post(item, frame, finalize) + + if frame.buffer is not None: + self.write(",") + + if frame.buffer is not None: + self.outdent() + self.writeline(")" if len(body) == 1 else "))") + + if frame.require_output_check: + self.outdent() + + def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None: + self.push_assign_tracking() + self.newline(node) + self.visit(node.target, frame) + self.write(" = ") + self.visit(node.node, frame) + self.pop_assign_tracking(frame) + + def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None: + self.push_assign_tracking() + block_frame = frame.inner() + # This is a special case. Since a set block always captures we + # will disable output checks. This way one can use set blocks + # toplevel even in extended templates. + block_frame.require_output_check = False + block_frame.symbols.analyze_node(node) + self.enter_frame(block_frame) + self.buffer(block_frame) + self.blockvisit(node.body, block_frame) + self.newline(node) + self.visit(node.target, frame) + self.write(" = (Markup if context.eval_ctx.autoescape else identity)(") + if node.filter is not None: + self.visit_Filter(node.filter, block_frame) + else: + self.write(f"concat({block_frame.buffer})") + self.write(")") + self.pop_assign_tracking(frame) + self.leave_frame(block_frame) + + # -- Expression Visitors + + def visit_Name(self, node: nodes.Name, frame: Frame) -> None: + if node.ctx == "store" and ( + frame.toplevel or frame.loop_frame or frame.block_frame + ): + if self._assign_stack: + self._assign_stack[-1].add(node.name) + ref = frame.symbols.ref(node.name) + + # If we are looking up a variable we might have to deal with the + # case where it's undefined. We can skip that case if the load + # instruction indicates a parameter which are always defined. + if node.ctx == "load": + load = frame.symbols.find_load(ref) + if not ( + load is not None + and load[0] == VAR_LOAD_PARAMETER + and not self.parameter_is_undeclared(ref) + ): + self.write( + f"(undefined(name={node.name!r}) if {ref} is missing else {ref})" + ) + return + + self.write(ref) + + def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None: + # NSRefs can only be used to store values; since they use the normal + # `foo.bar` notation they will be parsed as a normal attribute access + # when used anywhere but in a `set` context + ref = frame.symbols.ref(node.name) + self.writeline(f"if not isinstance({ref}, Namespace):") + self.indent() + self.writeline( + "raise TemplateRuntimeError" + '("cannot assign attribute on non-namespace object")' + ) + self.outdent() + self.writeline(f"{ref}[{node.attr!r}]") + + def visit_Const(self, node: nodes.Const, frame: Frame) -> None: + val = node.as_const(frame.eval_ctx) + if isinstance(val, float): + self.write(str(val)) + else: + self.write(repr(val)) + + def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None: + try: + self.write(repr(node.as_const(frame.eval_ctx))) + except nodes.Impossible: + self.write( + f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})" + ) + + def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None: + self.write("(") + idx = -1 + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write(",)" if idx == 0 else ")") + + def visit_List(self, node: nodes.List, frame: Frame) -> None: + self.write("[") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write("]") + + def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None: + self.write("{") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item.key, frame) + self.write(": ") + self.visit(item.value, frame) + self.write("}") + + visit_Add = _make_binop("+") + visit_Sub = _make_binop("-") + visit_Mul = _make_binop("*") + visit_Div = _make_binop("/") + visit_FloorDiv = _make_binop("//") + visit_Pow = _make_binop("**") + visit_Mod = _make_binop("%") + visit_And = _make_binop("and") + visit_Or = _make_binop("or") + visit_Pos = _make_unop("+") + visit_Neg = _make_unop("-") + visit_Not = _make_unop("not ") + + @optimizeconst + def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None: + if frame.eval_ctx.volatile: + func_name = "(markup_join if context.eval_ctx.volatile else str_join)" + elif frame.eval_ctx.autoescape: + func_name = "markup_join" + else: + func_name = "str_join" + self.write(f"{func_name}((") + for arg in node.nodes: + self.visit(arg, frame) + self.write(", ") + self.write("))") + + @optimizeconst + def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None: + self.write("(") + self.visit(node.expr, frame) + for op in node.ops: + self.visit(op, frame) + self.write(")") + + def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None: + self.write(f" {operators[node.op]} ") + self.visit(node.expr, frame) + + @optimizeconst + def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getattr(") + self.visit(node.node, frame) + self.write(f", {node.attr!r})") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None: + # slices bypass the environment getitem method. + if isinstance(node.arg, nodes.Slice): + self.visit(node.node, frame) + self.write("[") + self.visit(node.arg, frame) + self.write("]") + else: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getitem(") + self.visit(node.node, frame) + self.write(", ") + self.visit(node.arg, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None: + if node.start is not None: + self.visit(node.start, frame) + self.write(":") + if node.stop is not None: + self.visit(node.stop, frame) + if node.step is not None: + self.write(":") + self.visit(node.step, frame) + + @contextmanager + def _filter_test_common( + self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool + ) -> t.Iterator[None]: + if self.environment.is_async: + self.write("(await auto_await(") + + if is_filter: + self.write(f"{self.filters[node.name]}(") + func = self.environment.filters.get(node.name) + else: + self.write(f"{self.tests[node.name]}(") + func = self.environment.tests.get(node.name) + + # When inside an If or CondExpr frame, allow the filter to be + # undefined at compile time and only raise an error if it's + # actually called at runtime. See pull_dependencies. + if func is None and not frame.soft_frame: + type_name = "filter" if is_filter else "test" + self.fail(f"No {type_name} named {node.name!r}.", node.lineno) + + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(func) # type: ignore + ) + + if pass_arg is not None: + self.write(f"{pass_arg}, ") + + # Back to the visitor function to handle visiting the target of + # the filter or test. + yield + + self.signature(node, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None: + with self._filter_test_common(node, frame, True): + # if the filter node is None we are inside a filter block + # and want to write to the current buffer + if node.node is not None: + self.visit(node.node, frame) + elif frame.eval_ctx.volatile: + self.write( + f"(Markup(concat({frame.buffer}))" + f" if context.eval_ctx.autoescape else concat({frame.buffer}))" + ) + elif frame.eval_ctx.autoescape: + self.write(f"Markup(concat({frame.buffer}))") + else: + self.write(f"concat({frame.buffer})") + + @optimizeconst + def visit_Test(self, node: nodes.Test, frame: Frame) -> None: + with self._filter_test_common(node, frame, False): + self.visit(node.node, frame) + + @optimizeconst + def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None: + frame = frame.soft() + + def write_expr2() -> None: + if node.expr2 is not None: + self.visit(node.expr2, frame) + return + + self.write( + f'cond_expr_undefined("the inline if-expression on' + f" {self.position(node)} evaluated to false and no else" + f' section was defined.")' + ) + + self.write("(") + self.visit(node.expr1, frame) + self.write(" if ") + self.visit(node.test, frame) + self.write(" else ") + write_expr2() + self.write(")") + + @optimizeconst + def visit_Call( + self, node: nodes.Call, frame: Frame, forward_caller: bool = False + ) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + if self.environment.sandboxed: + self.write("environment.call(context, ") + else: + self.write("context.call(") + self.visit(node.node, frame) + extra_kwargs = {"caller": "caller"} if forward_caller else None + loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {} + block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {} + if extra_kwargs: + extra_kwargs.update(loop_kwargs, **block_kwargs) + elif loop_kwargs or block_kwargs: + extra_kwargs = dict(loop_kwargs, **block_kwargs) + self.signature(node, frame, extra_kwargs) + self.write(")") + if self.environment.is_async: + self.write("))") + + def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None: + self.write(node.key + "=") + self.visit(node.value, frame) + + # -- Unused nodes for extensions + + def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None: + self.write("Markup(") + self.visit(node.expr, frame) + self.write(")") + + def visit_MarkSafeIfAutoescape( + self, node: nodes.MarkSafeIfAutoescape, frame: Frame + ) -> None: + self.write("(Markup if context.eval_ctx.autoescape else identity)(") + self.visit(node.expr, frame) + self.write(")") + + def visit_EnvironmentAttribute( + self, node: nodes.EnvironmentAttribute, frame: Frame + ) -> None: + self.write("environment." + node.name) + + def visit_ExtensionAttribute( + self, node: nodes.ExtensionAttribute, frame: Frame + ) -> None: + self.write(f"environment.extensions[{node.identifier!r}].{node.name}") + + def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None: + self.write(self.import_aliases[node.importname]) + + def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None: + self.write(node.name) + + def visit_ContextReference( + self, node: nodes.ContextReference, frame: Frame + ) -> None: + self.write("context") + + def visit_DerivedContextReference( + self, node: nodes.DerivedContextReference, frame: Frame + ) -> None: + self.write(self.derive_context(frame)) + + def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None: + self.writeline("continue", node) + + def visit_Break(self, node: nodes.Break, frame: Frame) -> None: + self.writeline("break", node) + + def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None: + scope_frame = frame.inner() + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + + def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None: + ctx = self.temporary_identifier() + self.writeline(f"{ctx} = {self.derive_context(frame)}") + self.writeline(f"{ctx}.vars = ") + self.visit(node.context, frame) + self.push_context_reference(ctx) + + scope_frame = frame.inner(isolated=True) + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + self.pop_context_reference() + + def visit_EvalContextModifier( + self, node: nodes.EvalContextModifier, frame: Frame + ) -> None: + for keyword in node.options: + self.writeline(f"context.eval_ctx.{keyword.key} = ") + self.visit(keyword.value, frame) + try: + val = keyword.value.as_const(frame.eval_ctx) + except nodes.Impossible: + frame.eval_ctx.volatile = True + else: + setattr(frame.eval_ctx, keyword.key, val) + + def visit_ScopedEvalContextModifier( + self, node: nodes.ScopedEvalContextModifier, frame: Frame + ) -> None: + old_ctx_name = self.temporary_identifier() + saved_ctx = frame.eval_ctx.save() + self.writeline(f"{old_ctx_name} = context.eval_ctx.save()") + self.visit_EvalContextModifier(node, frame) + for child in node.body: + self.visit(child, frame) + frame.eval_ctx.revert(saved_ctx) + self.writeline(f"context.eval_ctx.revert({old_ctx_name})") diff --git a/shared/package-files/3c/3c9e2cd7dc222866144e53b9c291cdae83361f989f75d62c3e23e922088a36ff/test_funcdesc.py b/shared/package-files/3c/3c9e2cd7dc222866144e53b9c291cdae83361f989f75d62c3e23e922088a36ff/test_funcdesc.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e899bfe45fb22df60c2037332c67d1fa004199 --- /dev/null +++ b/shared/package-files/3c/3c9e2cd7dc222866144e53b9c291cdae83361f989f75d62c3e23e922088a36ff/test_funcdesc.py @@ -0,0 +1,61 @@ + +import unittest + +from numba import njit +from numba.core.funcdesc import PythonFunctionDescriptor, default_mangler +from numba.core.compiler import run_frontend +from numba.core.itanium_mangler import mangle_abi_tag + + +class TestModule(unittest.TestCase): + def test_module_not_in_namespace(self): + """ Test of trying to run a compiled function + where the module from which the function is being compiled + doesn't exist in the namespace. + """ + filename = 'test.py' + name = 'mypackage' + code = """ +def f(x): + return x +""" + + objs = dict(__file__=filename, __name__=name) + compiled = compile(code, filename, 'exec') + exec(compiled, objs) + + compiled_f = njit(objs['f']) + self.assertEqual(compiled_f(3), 3) + + +class TestFuncDescMangledName(unittest.TestCase): + def test_mangling_abi_tags(self): + """ + This is a minimal test for the abi-tags support in the mangler. + """ + def udt(): + pass + + # run minimal frontend to create a function descriptor + func_ir = run_frontend(udt) + typemap = {} + restype = None + calltypes = () + mangler = default_mangler + inline = False + noalias = False + + abi_tags = ("Shrubbery", "Herring") + + fd = PythonFunctionDescriptor.from_specialized_function( + func_ir, typemap, restype, calltypes, mangler, inline, noalias, + abi_tags=abi_tags, + ) + + # mangled tag must exist in the mangled name + self.assertIn("".join([mangle_abi_tag(x) for x in abi_tags]), + fd.mangled_name) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/3c/3ca0415f79fa01222de48b99629f05e1f59e7b974add14cd57232b24a81f12b0/_loss.pyx.tp b/shared/package-files/3c/3ca0415f79fa01222de48b99629f05e1f59e7b974add14cd57232b24a81f12b0/_loss.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..44d5acd530a7f60ac6e08174c5e5197f3fb00735 --- /dev/null +++ b/shared/package-files/3c/3ca0415f79fa01222de48b99629f05e1f59e7b974add14cd57232b24a81f12b0/_loss.pyx.tp @@ -0,0 +1,1505 @@ +{{py: + +""" +Template file to easily generate loops over samples using Tempita +(https://github.com/cython/cython/blob/master/Cython/Tempita/_tempita.py). + +Generated file: _loss.pyx + +Each loss class is generated by a cdef functions on single samples. +The keywords between double braces are substituted during the build. +""" + +doc_HalfSquaredError = ( + """Half Squared Error with identity link. + + Domain: + y_true and y_pred all real numbers + + Link: + y_pred = raw_prediction + """ +) + +doc_AbsoluteError = ( + """Absolute Error with identity link. + + Domain: + y_true and y_pred all real numbers + + Link: + y_pred = raw_prediction + """ +) + +doc_PinballLoss = ( + """Quantile Loss aka Pinball Loss with identity link. + + Domain: + y_true and y_pred all real numbers + quantile in (0, 1) + + Link: + y_pred = raw_prediction + + Note: 2 * cPinballLoss(quantile=0.5) equals cAbsoluteError() + """ +) + +doc_HuberLoss = ( + """Huber Loss with identity link. + + Domain: + y_true and y_pred all real numbers + delta in positive real numbers + + Link: + y_pred = raw_prediction + """ +) + +doc_HalfPoissonLoss = ( + """Half Poisson deviance loss with log-link. + + Domain: + y_true in non-negative real numbers + y_pred in positive real numbers + + Link: + y_pred = exp(raw_prediction) + + Half Poisson deviance with log-link is + y_true * log(y_true/y_pred) + y_pred - y_true + = y_true * log(y_true) - y_true * raw_prediction + + exp(raw_prediction) - y_true + + Dropping constant terms, this gives: + exp(raw_prediction) - y_true * raw_prediction + """ +) + +doc_HalfGammaLoss = ( + """Half Gamma deviance loss with log-link. + + Domain: + y_true and y_pred in positive real numbers + + Link: + y_pred = exp(raw_prediction) + + Half Gamma deviance with log-link is + log(y_pred/y_true) + y_true/y_pred - 1 + = raw_prediction - log(y_true) + y_true * exp(-raw_prediction) - 1 + + Dropping constant terms, this gives: + raw_prediction + y_true * exp(-raw_prediction) + """ +) + +doc_HalfTweedieLoss = ( + """Half Tweedie deviance loss with log-link. + + Domain: + y_true in real numbers if p <= 0 + y_true in non-negative real numbers if 0 < p < 2 + y_true in positive real numbers if p >= 2 + y_pred and power in positive real numbers + + Link: + y_pred = exp(raw_prediction) + + Half Tweedie deviance with log-link and p=power is + max(y_true, 0)**(2-p) / (1-p) / (2-p) + - y_true * y_pred**(1-p) / (1-p) + + y_pred**(2-p) / (2-p) + = max(y_true, 0)**(2-p) / (1-p) / (2-p) + - y_true * exp((1-p) * raw_prediction) / (1-p) + + exp((2-p) * raw_prediction) / (2-p) + + Dropping constant terms, this gives: + exp((2-p) * raw_prediction) / (2-p) + - y_true * exp((1-p) * raw_prediction) / (1-p) + + Notes: + - Poisson with p=1 and Gamma with p=2 have different terms dropped such + that cHalfTweedieLoss is not continuous in p=power at p=1 and p=2. + - While the Tweedie distribution only exists for p<=0 or p>=1, the range + 0= 2 + y_pred and power in positive real numbers, y_pred may be negative for p=0. + + Link: + y_pred = raw_prediction + + Half Tweedie deviance with identity link and p=power is + max(y_true, 0)**(2-p) / (1-p) / (2-p) + - y_true * y_pred**(1-p) / (1-p) + + y_pred**(2-p) / (2-p) + + Notes: + - Here, we do not drop constant terms in contrast to the version with log-link. + """ +) + +doc_HalfBinomialLoss = ( + """Half Binomial deviance loss with logit link. + + Domain: + y_true in [0, 1] + y_pred in (0, 1), i.e. boundaries excluded + + Link: + y_pred = expit(raw_prediction) + """ +) + +doc_ExponentialLoss = ( + """"Exponential loss with (half) logit link + + Domain: + y_true in [0, 1] + y_pred in (0, 1), i.e. boundaries excluded + + Link: + y_pred = expit(2 * raw_prediction) + """ +) + +# loss class name, docstring, param, +# cy_loss, cy_loss_grad, +# cy_grad, cy_grad_hess, +class_list = [ + ("CyHalfSquaredError", doc_HalfSquaredError, None, + "closs_half_squared_error", None, + "cgradient_half_squared_error", "cgrad_hess_half_squared_error"), + ("CyAbsoluteError", doc_AbsoluteError, None, + "closs_absolute_error", None, + "cgradient_absolute_error", "cgrad_hess_absolute_error"), + ("CyPinballLoss", doc_PinballLoss, "quantile", + "closs_pinball_loss", None, + "cgradient_pinball_loss", "cgrad_hess_pinball_loss"), + ("CyHuberLoss", doc_HuberLoss, "delta", + "closs_huber_loss", None, + "cgradient_huber_loss", "cgrad_hess_huber_loss"), + ("CyHalfPoissonLoss", doc_HalfPoissonLoss, None, + "closs_half_poisson", "closs_grad_half_poisson", + "cgradient_half_poisson", "cgrad_hess_half_poisson"), + ("CyHalfGammaLoss", doc_HalfGammaLoss, None, + "closs_half_gamma", "closs_grad_half_gamma", + "cgradient_half_gamma", "cgrad_hess_half_gamma"), + ("CyHalfTweedieLoss", doc_HalfTweedieLoss, "power", + "closs_half_tweedie", "closs_grad_half_tweedie", + "cgradient_half_tweedie", "cgrad_hess_half_tweedie"), + ("CyHalfTweedieLossIdentity", doc_HalfTweedieLossIdentity, "power", + "closs_half_tweedie_identity", "closs_grad_half_tweedie_identity", + "cgradient_half_tweedie_identity", "cgrad_hess_half_tweedie_identity"), + ("CyHalfBinomialLoss", doc_HalfBinomialLoss, None, + "closs_half_binomial", "closs_grad_half_binomial", + "cgradient_half_binomial", "cgrad_hess_half_binomial"), + ("CyExponentialLoss", doc_ExponentialLoss, None, + "closs_exponential", "closs_grad_exponential", + "cgradient_exponential", "cgrad_hess_exponential"), +] +}} + +# Design: +# See https://github.com/scikit-learn/scikit-learn/issues/15123 for reasons. +# a) Merge link functions into loss functions for speed and numerical +# stability, i.e. use raw_prediction instead of y_pred in signature. +# b) Pure C functions (nogil) calculate single points (single sample) +# c) Wrap C functions in a loop to get Python functions operating on ndarrays. +# - Write loops manually---use Tempita for this. +# Reason: There is still some performance overhead when using a wrapper +# function "wrap" that carries out the loop and gets as argument a function +# pointer to one of the C functions from b), e.g. +# wrap(closs_half_poisson, y_true, ...) +# - Pass n_threads as argument to prange and propagate option to all callers. +# d) Provide classes (Cython extension types) per loss (names start with Cy) in +# order to have semantical structured objects. +# - Member functions for single points just call the C function from b). +# These are used e.g. in SGD `_plain_sgd`. +# - Member functions operating on ndarrays, see c), looping over calls to C +# functions from b). +# e) Provide convenience Python classes that compose from these extension types +# elsewhere (see loss.py) +# - Example: loss.gradient calls CyLoss.gradient but does some input +# checking like None -> np.empty(). +# +# Note: We require 1-dim ndarrays to be contiguous. + +from cython.parallel import parallel, prange +import numpy as np + +from libc.math cimport exp, fabs, log, log1p, pow +from libc.stdlib cimport malloc, free + + +# ------------------------------------- +# Helper functions +# ------------------------------------- +# Numerically stable version of log(1 + exp(x)) for double precision, see Eq. (10) of +# https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf +# Note: The only important cutoff is at x = 18. All others are to save computation +# time. Compared to the reference, we add the additional case distinction x <= -2 in +# order to use log instead of log1p for improved performance. As with the other +# cutoffs, this is accurate within machine precision of double. +cdef inline double log1pexp(double x) noexcept nogil: + if x <= -37: + return exp(x) + elif x <= -2: + return log1p(exp(x)) + elif x <= 18: + return log(1. + exp(x)) + elif x <= 33.3: + return x + exp(-x) + else: + return x + + +cdef inline double_pair sum_exp_minus_max( + const int i, + const floating_in[:, :] raw_prediction, # IN + floating_out *p # OUT +) noexcept nogil: + # Thread local buffers are used to store part of the results via p. + # The results are stored as follows: + # p[k] = exp(raw_prediction_i_k - max_value) for k = 0 to n_classes-1 + # return.val1 = max_value = max(raw_prediction_i_k, k = 0 to n_classes-1) + # return.val2 = sum_exps = sum(p[k], k = 0 to n_classes-1) = sum of exponentials + # len(p) must be n_classes + # Notes: + # - We return the max value and sum of exps (stored in p) as a double_pair. + # - i needs to be passed (and stays constant) because otherwise Cython does + # not generate optimal code, see + # https://github.com/scikit-learn/scikit-learn/issues/17299 + # - We do not normalize p by calculating p[k] = p[k] / sum_exps. + # This helps to save one loop over k. + cdef: + int k + int n_classes = raw_prediction.shape[1] + double_pair max_value_and_sum_exps # val1 = max_value, val2 = sum_exps + + max_value_and_sum_exps.val1 = raw_prediction[i, 0] + max_value_and_sum_exps.val2 = 0 + for k in range(1, n_classes): + # Compute max value of array for numerical stability + if max_value_and_sum_exps.val1 < raw_prediction[i, k]: + max_value_and_sum_exps.val1 = raw_prediction[i, k] + + for k in range(n_classes): + p[k] = exp(raw_prediction[i, k] - max_value_and_sum_exps.val1) + max_value_and_sum_exps.val2 += p[k] + + return max_value_and_sum_exps + + +# ------------------------------------- +# Single point inline C functions +# ------------------------------------- +# Half Squared Error +cdef inline double closs_half_squared_error( + double y_true, + double raw_prediction +) noexcept nogil: + return 0.5 * (raw_prediction - y_true) * (raw_prediction - y_true) + + +cdef inline double cgradient_half_squared_error( + double y_true, + double raw_prediction +) noexcept nogil: + return raw_prediction - y_true + + +cdef inline double_pair cgrad_hess_half_squared_error( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair gh + gh.val1 = raw_prediction - y_true # gradient + gh.val2 = 1. # hessian + return gh + + +# Absolute Error +cdef inline double closs_absolute_error( + double y_true, + double raw_prediction +) noexcept nogil: + return fabs(raw_prediction - y_true) + + +cdef inline double cgradient_absolute_error( + double y_true, + double raw_prediction +) noexcept nogil: + return 1. if raw_prediction > y_true else -1. + + +cdef inline double_pair cgrad_hess_absolute_error( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair gh + # Note that exact hessian = 0 almost everywhere. Optimization routines like + # in HGBT, however, need a hessian > 0. Therefore, we assign 1. + gh.val1 = 1. if raw_prediction > y_true else -1. # gradient + gh.val2 = 1. # hessian + return gh + + +# Quantile Loss / Pinball Loss +cdef inline double closs_pinball_loss( + double y_true, + double raw_prediction, + double quantile +) noexcept nogil: + return (quantile * (y_true - raw_prediction) if y_true >= raw_prediction + else (1. - quantile) * (raw_prediction - y_true)) + + +cdef inline double cgradient_pinball_loss( + double y_true, + double raw_prediction, + double quantile +) noexcept nogil: + return -quantile if y_true >=raw_prediction else 1. - quantile + + +cdef inline double_pair cgrad_hess_pinball_loss( + double y_true, + double raw_prediction, + double quantile +) noexcept nogil: + cdef double_pair gh + # Note that exact hessian = 0 almost everywhere. Optimization routines like + # in HGBT, however, need a hessian > 0. Therefore, we assign 1. + gh.val1 = -quantile if y_true >=raw_prediction else 1. - quantile # gradient + gh.val2 = 1. # hessian + return gh + + +# Huber Loss +cdef inline double closs_huber_loss( + double y_true, + double raw_prediction, + double delta, +) noexcept nogil: + cdef double abserr = fabs(y_true - raw_prediction) + if abserr <= delta: + return 0.5 * abserr**2 + else: + return delta * (abserr - 0.5 * delta) + + +cdef inline double cgradient_huber_loss( + double y_true, + double raw_prediction, + double delta, +) noexcept nogil: + cdef double res = raw_prediction - y_true + if fabs(res) <= delta: + return res + else: + return delta if res >=0 else -delta + + +cdef inline double_pair cgrad_hess_huber_loss( + double y_true, + double raw_prediction, + double delta, +) noexcept nogil: + cdef double_pair gh + gh.val2 = raw_prediction - y_true # used as temporary + if fabs(gh.val2) <= delta: + gh.val1 = gh.val2 # gradient + gh.val2 = 1 # hessian + else: + gh.val1 = delta if gh.val2 >=0 else -delta # gradient + gh.val2 = 0 # hessian + return gh + + +# Half Poisson Deviance with Log-Link, dropping constant terms +cdef inline double closs_half_poisson( + double y_true, + double raw_prediction +) noexcept nogil: + return exp(raw_prediction) - y_true * raw_prediction + + +cdef inline double cgradient_half_poisson( + double y_true, + double raw_prediction +) noexcept nogil: + # y_pred - y_true + return exp(raw_prediction) - y_true + + +cdef inline double_pair closs_grad_half_poisson( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair lg + lg.val2 = exp(raw_prediction) # used as temporary + lg.val1 = lg.val2 - y_true * raw_prediction # loss + lg.val2 -= y_true # gradient + return lg + + +cdef inline double_pair cgrad_hess_half_poisson( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair gh + gh.val2 = exp(raw_prediction) # hessian + gh.val1 = gh.val2 - y_true # gradient + return gh + + +# Half Gamma Deviance with Log-Link, dropping constant terms +cdef inline double closs_half_gamma( + double y_true, + double raw_prediction +) noexcept nogil: + return raw_prediction + y_true * exp(-raw_prediction) + + +cdef inline double cgradient_half_gamma( + double y_true, + double raw_prediction +) noexcept nogil: + return 1. - y_true * exp(-raw_prediction) + + +cdef inline double_pair closs_grad_half_gamma( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair lg + lg.val2 = exp(-raw_prediction) # used as temporary + lg.val1 = raw_prediction + y_true * lg.val2 # loss + lg.val2 = 1. - y_true * lg.val2 # gradient + return lg + + +cdef inline double_pair cgrad_hess_half_gamma( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair gh + gh.val2 = exp(-raw_prediction) # used as temporary + gh.val1 = 1. - y_true * gh.val2 # gradient + gh.val2 *= y_true # hessian + return gh + + +# Half Tweedie Deviance with Log-Link, dropping constant terms +# Note that by dropping constants this is no longer continuous in parameter power. +cdef inline double closs_half_tweedie( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + if power == 0.: + return closs_half_squared_error(y_true, exp(raw_prediction)) + elif power == 1.: + return closs_half_poisson(y_true, raw_prediction) + elif power == 2.: + return closs_half_gamma(y_true, raw_prediction) + else: + return (exp((2. - power) * raw_prediction) / (2. - power) + - y_true * exp((1. - power) * raw_prediction) / (1. - power)) + + +cdef inline double cgradient_half_tweedie( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + cdef double exp1 + if power == 0.: + exp1 = exp(raw_prediction) + return exp1 * (exp1 - y_true) + elif power == 1.: + return cgradient_half_poisson(y_true, raw_prediction) + elif power == 2.: + return cgradient_half_gamma(y_true, raw_prediction) + else: + return (exp((2. - power) * raw_prediction) + - y_true * exp((1. - power) * raw_prediction)) + + +cdef inline double_pair closs_grad_half_tweedie( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + cdef double_pair lg + cdef double exp1, exp2 + if power == 0.: + exp1 = exp(raw_prediction) + lg.val1 = closs_half_squared_error(y_true, exp1) # loss + lg.val2 = exp1 * (exp1 - y_true) # gradient + elif power == 1.: + return closs_grad_half_poisson(y_true, raw_prediction) + elif power == 2.: + return closs_grad_half_gamma(y_true, raw_prediction) + else: + exp1 = exp((1. - power) * raw_prediction) + exp2 = exp((2. - power) * raw_prediction) + lg.val1 = exp2 / (2. - power) - y_true * exp1 / (1. - power) # loss + lg.val2 = exp2 - y_true * exp1 # gradient + return lg + + +cdef inline double_pair cgrad_hess_half_tweedie( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + cdef double_pair gh + cdef double exp1, exp2 + if power == 0.: + exp1 = exp(raw_prediction) + gh.val1 = exp1 * (exp1 - y_true) # gradient + gh.val2 = exp1 * (2 * exp1 - y_true) # hessian + elif power == 1.: + return cgrad_hess_half_poisson(y_true, raw_prediction) + elif power == 2.: + return cgrad_hess_half_gamma(y_true, raw_prediction) + else: + exp1 = exp((1. - power) * raw_prediction) + exp2 = exp((2. - power) * raw_prediction) + gh.val1 = exp2 - y_true * exp1 # gradient + gh.val2 = (2. - power) * exp2 - (1. - power) * y_true * exp1 # hessian + return gh + + +# Half Tweedie Deviance with identity link, without dropping constant terms! +# Therefore, best loss value is zero. +cdef inline double closs_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + cdef double tmp + if power == 0.: + return closs_half_squared_error(y_true, raw_prediction) + elif power == 1.: + if y_true == 0: + return raw_prediction + else: + return y_true * log(y_true/raw_prediction) + raw_prediction - y_true + elif power == 2.: + return log(raw_prediction/y_true) + y_true/raw_prediction - 1. + else: + tmp = pow(raw_prediction, 1. - power) + tmp = raw_prediction * tmp / (2. - power) - y_true * tmp / (1. - power) + if y_true > 0: + tmp += pow(y_true, 2. - power) / ((1. - power) * (2. - power)) + return tmp + + +cdef inline double cgradient_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + if power == 0.: + return raw_prediction - y_true + elif power == 1.: + return 1. - y_true / raw_prediction + elif power == 2.: + return (raw_prediction - y_true) / (raw_prediction * raw_prediction) + else: + return pow(raw_prediction, -power) * (raw_prediction - y_true) + + +cdef inline double_pair closs_grad_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + cdef double_pair lg + cdef double tmp + if power == 0.: + lg.val2 = raw_prediction - y_true # gradient + lg.val1 = 0.5 * lg.val2 * lg.val2 # loss + elif power == 1.: + if y_true == 0: + lg.val1 = raw_prediction + else: + lg.val1 = (y_true * log(y_true/raw_prediction) # loss + + raw_prediction - y_true) + lg.val2 = 1. - y_true / raw_prediction # gradient + elif power == 2.: + lg.val1 = log(raw_prediction/y_true) + y_true/raw_prediction - 1. # loss + tmp = raw_prediction * raw_prediction + lg.val2 = (raw_prediction - y_true) / tmp # gradient + else: + tmp = pow(raw_prediction, 1. - power) + lg.val1 = (raw_prediction * tmp / (2. - power) # loss + - y_true * tmp / (1. - power)) + if y_true > 0: + lg.val1 += (pow(y_true, 2. - power) + / ((1. - power) * (2. - power))) + lg.val2 = tmp * (1. - y_true / raw_prediction) # gradient + return lg + + +cdef inline double_pair cgrad_hess_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) noexcept nogil: + cdef double_pair gh + cdef double tmp + if power == 0.: + gh.val1 = raw_prediction - y_true # gradient + gh.val2 = 1. # hessian + elif power == 1.: + gh.val1 = 1. - y_true / raw_prediction # gradient + gh.val2 = y_true / (raw_prediction * raw_prediction) # hessian + elif power == 2.: + tmp = raw_prediction * raw_prediction + gh.val1 = (raw_prediction - y_true) / tmp # gradient + gh.val2 = (-1. + 2. * y_true / raw_prediction) / tmp # hessian + else: + tmp = pow(raw_prediction, -power) + gh.val1 = tmp * (raw_prediction - y_true) # gradient + gh.val2 = tmp * ((1. - power) + power * y_true / raw_prediction) # hessian + return gh + + +# Half Binomial deviance with logit-link, aka log-loss or binary cross entropy +cdef inline double closs_half_binomial( + double y_true, + double raw_prediction +) noexcept nogil: + # log1p(exp(raw_prediction)) - y_true * raw_prediction + return log1pexp(raw_prediction) - y_true * raw_prediction + + +cdef inline double cgradient_half_binomial( + double y_true, + double raw_prediction +) noexcept nogil: + # gradient = y_pred - y_true = expit(raw_prediction) - y_true + # Numerically more stable, see http://fa.bianp.net/blog/2019/evaluate_logistic/ + # if raw_prediction < 0: + # exp_tmp = exp(raw_prediction) + # return ((1 - y_true) * exp_tmp - y_true) / (1 + exp_tmp) + # else: + # exp_tmp = exp(-raw_prediction) + # return ((1 - y_true) - y_true * exp_tmp) / (1 + exp_tmp) + # Note that optimal speed would be achieved, at the cost of precision, by + # return expit(raw_prediction) - y_true + # i.e. no "if else" and an own inline implementation of expit instead of + # from scipy.special.cython_special cimport expit + # The case distinction raw_prediction < 0 in the stable implementation does not + # provide significant better precision apart from protecting overflow of exp(..). + # The branch (if else), however, can incur runtime costs of up to 30%. + # Instead, we help branch prediction by almost always ending in the first if clause + # and making the second branch (else) a bit simpler. This has the exact same + # precision but is faster than the stable implementation. + # As branching criteria, we use the same cutoff as in log1pexp. Note that the + # maximal value to get gradient = -1 with y_true = 1 is -37.439198610162731 + # (based on mpmath), and scipy.special.logit(np.finfo(float).eps) ~ -36.04365. + cdef double exp_tmp + if raw_prediction > -37: + exp_tmp = exp(-raw_prediction) + return ((1 - y_true) - y_true * exp_tmp) / (1 + exp_tmp) + else: + # expit(raw_prediction) = exp(raw_prediction) for raw_prediction <= -37 + return exp(raw_prediction) - y_true + + +cdef inline double_pair closs_grad_half_binomial( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair lg + # Same if else conditions as in log1pexp. + if raw_prediction <= -37: + lg.val2 = exp(raw_prediction) # used as temporary + lg.val1 = lg.val2 - y_true * raw_prediction # loss + lg.val2 -= y_true # gradient + elif raw_prediction <= -2: + lg.val2 = exp(raw_prediction) # used as temporary + lg.val1 = log1p(lg.val2) - y_true * raw_prediction # loss + lg.val2 = ((1 - y_true) * lg.val2 - y_true) / (1 + lg.val2) # gradient + elif raw_prediction <= 18: + lg.val2 = exp(-raw_prediction) # used as temporary + # log1p(exp(x)) = log(1 + exp(x)) = x + log1p(exp(-x)) + lg.val1 = log1p(lg.val2) + (1 - y_true) * raw_prediction # loss + lg.val2 = ((1 - y_true) - y_true * lg.val2) / (1 + lg.val2) # gradient + else: + lg.val2 = exp(-raw_prediction) # used as temporary + lg.val1 = lg.val2 + (1 - y_true) * raw_prediction # loss + lg.val2 = ((1 - y_true) - y_true * lg.val2) / (1 + lg.val2) # gradient + return lg + + +cdef inline double_pair cgrad_hess_half_binomial( + double y_true, + double raw_prediction +) noexcept nogil: + # with y_pred = expit(raw) + # hessian = y_pred * (1 - y_pred) = exp( raw) / (1 + exp( raw))**2 + # = exp(-raw) / (1 + exp(-raw))**2 + cdef double_pair gh + # See comment in cgradient_half_binomial. + if raw_prediction > -37: + gh.val2 = exp(-raw_prediction) # used as temporary + gh.val1 = ((1 - y_true) - y_true * gh.val2) / (1 + gh.val2) # gradient + gh.val2 = gh.val2 / (1 + gh.val2)**2 # hessian + else: + gh.val2 = exp(raw_prediction) # = 1. order Taylor in exp(raw_prediction) + gh.val1 = gh.val2 - y_true + return gh + + +# Exponential loss with (half) logit-link, aka boosting loss +cdef inline double closs_exponential( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double tmp = exp(raw_prediction) + return y_true / tmp + (1 - y_true) * tmp + + +cdef inline double cgradient_exponential( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double tmp = exp(raw_prediction) + return -y_true / tmp + (1 - y_true) * tmp + + +cdef inline double_pair closs_grad_exponential( + double y_true, + double raw_prediction +) noexcept nogil: + cdef double_pair lg + lg.val2 = exp(raw_prediction) # used as temporary + + lg.val1 = y_true / lg.val2 + (1 - y_true) * lg.val2 # loss + lg.val2 = -y_true / lg.val2 + (1 - y_true) * lg.val2 # gradient + return lg + + +cdef inline double_pair cgrad_hess_exponential( + double y_true, + double raw_prediction +) noexcept nogil: + # Note that hessian = loss + cdef double_pair gh + gh.val2 = exp(raw_prediction) # used as temporary + + gh.val1 = -y_true / gh.val2 + (1 - y_true) * gh.val2 # gradient + gh.val2 = y_true / gh.val2 + (1 - y_true) * gh.val2 # hessian + return gh + + +# --------------------------------------------------- +# Extension Types for Loss Functions of 1-dim targets +# --------------------------------------------------- +cdef class CyLossFunction: + """Base class for convex loss functions.""" + + def __reduce__(self): + return (self.__class__, ()) + + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil: + """Compute the loss for a single sample. + + Parameters + ---------- + y_true : double + Observed, true target value. + raw_prediction : double + Raw prediction value (in link space). + + Returns + ------- + double + The loss evaluated at `y_true` and `raw_prediction`. + """ + pass + + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil: + """Compute gradient of loss w.r.t. raw_prediction for a single sample. + + Parameters + ---------- + y_true : double + Observed, true target value. + raw_prediction : double + Raw prediction value (in link space). + + Returns + ------- + double + The derivative of the loss function w.r.t. `raw_prediction`. + """ + pass + + cdef double_pair cy_grad_hess( + self, double y_true, double raw_prediction + ) noexcept nogil: + """Compute gradient and hessian. + + Gradient and hessian of loss w.r.t. raw_prediction for a single sample. + + This is usually diagonal in raw_prediction_i and raw_prediction_j. + Therefore, we return the diagonal element i=j. + + For a loss with a non-canonical link, this might implement the diagonal + of the Fisher matrix (=expected hessian) instead of the hessian. + + Parameters + ---------- + y_true : double + Observed, true target value. + raw_prediction : double + Raw prediction value (in link space). + + Returns + ------- + double_pair + Gradient and hessian of the loss function w.r.t. `raw_prediction`. + """ + pass + + def loss( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] loss_out, # OUT + int n_threads=1 + ): + """Compute the point-wise loss value for each input. + + The point-wise loss is written to `loss_out` and no array is returned. + + Parameters + ---------- + y_true : array of shape (n_samples,) + Observed, true target values. + raw_prediction : array of shape (n_samples,) + Raw prediction values (in link space). + sample_weight : array of shape (n_samples,) or None + Sample weights. + loss_out : array of shape (n_samples,) + A location into which the result is stored. + n_threads : int + Number of threads used by OpenMP (if any). + """ + pass + + def gradient( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] gradient_out, # OUT + int n_threads=1 + ): + """Compute gradient of loss w.r.t raw_prediction for each input. + + The gradient is written to `gradient_out` and no array is returned. + + Parameters + ---------- + y_true : array of shape (n_samples,) + Observed, true target values. + raw_prediction : array of shape (n_samples,) + Raw prediction values (in link space). + sample_weight : array of shape (n_samples,) or None + Sample weights. + gradient_out : array of shape (n_samples,) + A location into which the result is stored. + n_threads : int + Number of threads used by OpenMP (if any). + """ + pass + + def loss_gradient( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] loss_out, # OUT + floating_out[::1] gradient_out, # OUT + int n_threads=1 + ): + """Compute loss and gradient of loss w.r.t raw_prediction. + + The loss and gradient are written to `loss_out` and `gradient_out` and no arrays + are returned. + + Parameters + ---------- + y_true : array of shape (n_samples,) + Observed, true target values. + raw_prediction : array of shape (n_samples,) + Raw prediction values (in link space). + sample_weight : array of shape (n_samples,) or None + Sample weights. + loss_out : array of shape (n_samples,) or None + A location into which the element-wise loss is stored. + gradient_out : array of shape (n_samples,) + A location into which the gradient is stored. + n_threads : int + Number of threads used by OpenMP (if any). + """ + self.loss(y_true, raw_prediction, sample_weight, loss_out, n_threads) + self.gradient(y_true, raw_prediction, sample_weight, gradient_out, n_threads) + + def gradient_hessian( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] gradient_out, # OUT + floating_out[::1] hessian_out, # OUT + int n_threads=1 + ): + """Compute gradient and hessian of loss w.r.t raw_prediction. + + The gradient and hessian are written to `gradient_out` and `hessian_out` and no + arrays are returned. + + Parameters + ---------- + y_true : array of shape (n_samples,) + Observed, true target values. + raw_prediction : array of shape (n_samples,) + Raw prediction values (in link space). + sample_weight : array of shape (n_samples,) or None + Sample weights. + gradient_out : array of shape (n_samples,) + A location into which the gradient is stored. + hessian_out : array of shape (n_samples,) + A location into which the hessian is stored. + n_threads : int + Number of threads used by OpenMP (if any). + """ + pass + + +{{for name, docstring, param, closs, closs_grad, cgrad, cgrad_hess, in class_list}} +{{py: +if param is None: + with_param = "" +else: + with_param = ", self." + param +}} + +cdef class {{name}}(CyLossFunction): + """{{docstring}}""" + + {{if param is not None}} + def __init__(self, {{param}}): + self.{{param}} = {{param}} + {{endif}} + + {{if param is not None}} + def __reduce__(self): + return (self.__class__, (self.{{param}},)) + {{endif}} + + cdef inline double cy_loss(self, double y_true, double raw_prediction) noexcept nogil: + return {{closs}}(y_true, raw_prediction{{with_param}}) + + cdef inline double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil: + return {{cgrad}}(y_true, raw_prediction{{with_param}}) + + cdef inline double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil: + return {{cgrad_hess}}(y_true, raw_prediction{{with_param}}) + + def loss( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] loss_out, # OUT + int n_threads=1 + ): + cdef: + int i + int n_samples = y_true.shape[0] + + if sample_weight is None: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + loss_out[i] = {{closs}}(y_true[i], raw_prediction[i]{{with_param}}) + else: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + loss_out[i] = sample_weight[i] * {{closs}}(y_true[i], raw_prediction[i]{{with_param}}) + + {{if closs_grad is not None}} + def loss_gradient( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] loss_out, # OUT + floating_out[::1] gradient_out, # OUT + int n_threads=1 + ): + cdef: + int i + int n_samples = y_true.shape[0] + double_pair dbl2 + + if sample_weight is None: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + dbl2 = {{closs_grad}}(y_true[i], raw_prediction[i]{{with_param}}) + loss_out[i] = dbl2.val1 + gradient_out[i] = dbl2.val2 + else: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + dbl2 = {{closs_grad}}(y_true[i], raw_prediction[i]{{with_param}}) + loss_out[i] = sample_weight[i] * dbl2.val1 + gradient_out[i] = sample_weight[i] * dbl2.val2 + + {{endif}} + + def gradient( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] gradient_out, # OUT + int n_threads=1 + ): + cdef: + int i + int n_samples = y_true.shape[0] + + if sample_weight is None: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + gradient_out[i] = {{cgrad}}(y_true[i], raw_prediction[i]{{with_param}}) + else: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + gradient_out[i] = sample_weight[i] * {{cgrad}}(y_true[i], raw_prediction[i]{{with_param}}) + + def gradient_hessian( + self, + const floating_in[::1] y_true, # IN + const floating_in[::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] gradient_out, # OUT + floating_out[::1] hessian_out, # OUT + int n_threads=1 + ): + cdef: + int i + int n_samples = y_true.shape[0] + double_pair dbl2 + + if sample_weight is None: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + dbl2 = {{cgrad_hess}}(y_true[i], raw_prediction[i]{{with_param}}) + gradient_out[i] = dbl2.val1 + hessian_out[i] = dbl2.val2 + else: + for i in prange( + n_samples, schedule='static', nogil=True, num_threads=n_threads + ): + dbl2 = {{cgrad_hess}}(y_true[i], raw_prediction[i]{{with_param}}) + gradient_out[i] = sample_weight[i] * dbl2.val1 + hessian_out[i] = sample_weight[i] * dbl2.val2 + +{{endfor}} + + +# The multinomial deviance loss is also known as categorical cross-entropy or +# multinomial log-likelihood. +# Here, we do not inherit from CyLossFunction as its cy_gradient method deviates +# from the API. +cdef class CyHalfMultinomialLoss(): + """Half Multinomial deviance loss with multinomial logit link. + + Domain: + y_true in {0, 1, 2, 3, .., n_classes - 1} + y_pred in (0, 1)**n_classes, i.e. interval with boundaries excluded + + Link: + y_pred = softmax(raw_prediction) + + Note: Label encoding is built-in, i.e. {0, 1, 2, 3, .., n_classes - 1} is + mapped to (y_true == k) for k = 0 .. n_classes - 1 which is either 0 or 1. + """ + + # Here we deviate from the CyLossFunction API. SAG/SAGA needs direct access to + # sample-wise gradients which we provide here. + cdef inline void cy_gradient( + self, + const floating_in y_true, + const floating_in[::1] raw_prediction, # IN + const floating_in sample_weight, + floating_out[::1] gradient_out, # OUT + ) noexcept nogil: + """Compute gradient of loss w.r.t. `raw_prediction` for a single sample. + + The gradient of the multinomial logistic loss with respect to a class k, + and for one sample is: + grad_k = - sw * (p[k] - (y==k)) + + where: + p[k] = proba[k] = exp(raw_prediction[k] - logsumexp(raw_prediction)) + sw = sample_weight + + Parameters + ---------- + y_true : double + Observed, true target value. + raw_prediction : array of shape (n_classes,) + Raw prediction values (in link space). + sample_weight : double + Sample weight. + gradient_out : array of shape (n_classs,) + A location into which the gradient is stored. + + Returns + ------- + gradient : double + The derivative of the loss function w.r.t. `raw_prediction`. + """ + cdef: + int k + int n_classes = raw_prediction.shape[0] + double_pair max_value_and_sum_exps + const floating_in[:, :] raw = raw_prediction[None, :] + + max_value_and_sum_exps = sum_exp_minus_max(0, raw, &gradient_out[0]) + for k in range(n_classes): + # gradient_out[k] = p_k = y_pred_k = prob of class k + gradient_out[k] /= max_value_and_sum_exps.val2 + # gradient_k = (p_k - (y_true == k)) * sw + gradient_out[k] = (gradient_out[k] - (y_true == k)) * sample_weight + + def _test_cy_gradient( + self, + const floating_in[::1] y_true, # IN + const floating_in[:, ::1] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + ): + """For testing only.""" + cdef: + int i, k + int n_samples = y_true.shape[0] + int n_classes = raw_prediction.shape[1] + floating_in [:, ::1] gradient_out + gradient = np.empty((n_samples, n_classes), dtype=np.float64) + gradient_out = gradient + + for i in range(n_samples): + self.cy_gradient( + y_true=y_true[i], + raw_prediction=raw_prediction[i, :], + sample_weight=1.0 if sample_weight is None else sample_weight[i], + gradient_out=gradient_out[i, :], + ) + return gradient + + # Note that we do not assume memory alignment/contiguity of 2d arrays. + # There seems to be little benefit in doing so. Benchmarks proofing the + # opposite are welcome. + def loss( + self, + const floating_in[::1] y_true, # IN + const floating_in[:, :] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] loss_out, # OUT + int n_threads=1 + ): + cdef: + int i, k + int n_samples = y_true.shape[0] + int n_classes = raw_prediction.shape[1] + floating_in max_value, sum_exps + floating_in* p # temporary buffer + double_pair max_value_and_sum_exps + + # We assume n_samples > n_classes. In this case having the inner loop + # over n_classes is a good default. + # TODO: If every memoryview is contiguous and raw_prediction is + # f-contiguous, can we write a better algo (loops) to improve + # performance? + if sample_weight is None: + # inner loop over n_classes + with nogil, parallel(num_threads=n_threads): + # Define private buffer variables as each thread might use its + # own. + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + max_value = max_value_and_sum_exps.val1 + sum_exps = max_value_and_sum_exps.val2 + loss_out[i] = log(sum_exps) + max_value + + # label encoded y_true + k = int(y_true[i]) + loss_out[i] -= raw_prediction[i, k] + + free(p) + else: + with nogil, parallel(num_threads=n_threads): + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + max_value = max_value_and_sum_exps.val1 + sum_exps = max_value_and_sum_exps.val2 + loss_out[i] = log(sum_exps) + max_value + + # label encoded y_true + k = int(y_true[i]) + loss_out[i] -= raw_prediction[i, k] + + loss_out[i] *= sample_weight[i] + + free(p) + + def loss_gradient( + self, + const floating_in[::1] y_true, # IN + const floating_in[:, :] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[::1] loss_out, # OUT + floating_out[:, :] gradient_out, # OUT + int n_threads=1 + ): + cdef: + int i, k + int n_samples = y_true.shape[0] + int n_classes = raw_prediction.shape[1] + floating_in max_value, sum_exps + floating_in* p # temporary buffer + double_pair max_value_and_sum_exps + + if sample_weight is None: + # inner loop over n_classes + with nogil, parallel(num_threads=n_threads): + # Define private buffer variables as each thread might use its + # own. + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + max_value = max_value_and_sum_exps.val1 + sum_exps = max_value_and_sum_exps.val2 + loss_out[i] = log(sum_exps) + max_value + + for k in range(n_classes): + # label decode y_true + if y_true[i] == k: + loss_out[i] -= raw_prediction[i, k] + p[k] /= sum_exps # p_k = y_pred_k = prob of class k + # gradient_k = p_k - (y_true == k) + gradient_out[i, k] = p[k] - (y_true[i] == k) + + free(p) + else: + with nogil, parallel(num_threads=n_threads): + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + max_value = max_value_and_sum_exps.val1 + sum_exps = max_value_and_sum_exps.val2 + loss_out[i] = log(sum_exps) + max_value + + for k in range(n_classes): + # label decode y_true + if y_true[i] == k: + loss_out[i] -= raw_prediction[i, k] + p[k] /= sum_exps # p_k = y_pred_k = prob of class k + # gradient_k = (p_k - (y_true == k)) * sw + gradient_out[i, k] = (p[k] - (y_true[i] == k)) * sample_weight[i] + + loss_out[i] *= sample_weight[i] + + free(p) + + def gradient( + self, + const floating_in[::1] y_true, # IN + const floating_in[:, :] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[:, :] gradient_out, # OUT + int n_threads=1 + ): + cdef: + int i, k + int n_samples = y_true.shape[0] + int n_classes = raw_prediction.shape[1] + floating_in sum_exps + floating_in* p # temporary buffer + double_pair max_value_and_sum_exps + + if sample_weight is None: + # inner loop over n_classes + with nogil, parallel(num_threads=n_threads): + # Define private buffer variables as each thread might use its + # own. + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + sum_exps = max_value_and_sum_exps.val2 + + for k in range(n_classes): + p[k] /= sum_exps # p_k = y_pred_k = prob of class k + # gradient_k = y_pred_k - (y_true == k) + gradient_out[i, k] = p[k] - (y_true[i] == k) + + free(p) + else: + with nogil, parallel(num_threads=n_threads): + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + sum_exps = max_value_and_sum_exps.val2 + + for k in range(n_classes): + p[k] /= sum_exps # p_k = y_pred_k = prob of class k + # gradient_k = (p_k - (y_true == k)) * sw + gradient_out[i, k] = (p[k] - (y_true[i] == k)) * sample_weight[i] + + free(p) + + def gradient_hessian( + self, + const floating_in[::1] y_true, # IN + const floating_in[:, :] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[:, :] gradient_out, # OUT + floating_out[:, :] hessian_out, # OUT + int n_threads=1 + ): + cdef: + int i, k + int n_samples = y_true.shape[0] + int n_classes = raw_prediction.shape[1] + floating_in sum_exps + floating_in* p # temporary buffer + double_pair max_value_and_sum_exps + + if sample_weight is None: + # inner loop over n_classes + with nogil, parallel(num_threads=n_threads): + # Define private buffer variables as each thread might use its + # own. + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + sum_exps = max_value_and_sum_exps.val2 + + for k in range(n_classes): + p[k] /= sum_exps # p_k = y_pred_k = prob of class k + # hessian_k = p_k * (1 - p_k) + # gradient_k = p_k - (y_true == k) + gradient_out[i, k] = p[k] - (y_true[i] == k) + hessian_out[i, k] = p[k] * (1. - p[k]) + + free(p) + else: + with nogil, parallel(num_threads=n_threads): + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + sum_exps = max_value_and_sum_exps.val2 + + for k in range(n_classes): + p[k] /= sum_exps # p_k = y_pred_k = prob of class k + # gradient_k = (p_k - (y_true == k)) * sw + # hessian_k = p_k * (1 - p_k) * sw + gradient_out[i, k] = (p[k] - (y_true[i] == k)) * sample_weight[i] + hessian_out[i, k] = (p[k] * (1. - p[k])) * sample_weight[i] + + free(p) + + # This method simplifies the implementation of hessp in linear models, + # i.e. the matrix-vector product of the full hessian, not only of the + # diagonal (in the classes) approximation as implemented above. + def gradient_proba( + self, + const floating_in[::1] y_true, # IN + const floating_in[:, :] raw_prediction, # IN + const floating_in[::1] sample_weight, # IN + floating_out[:, :] gradient_out, # OUT + floating_out[:, :] proba_out, # OUT + int n_threads=1 + ): + cdef: + int i, k + int n_samples = y_true.shape[0] + int n_classes = raw_prediction.shape[1] + floating_in sum_exps + floating_in* p # temporary buffer + double_pair max_value_and_sum_exps + + if sample_weight is None: + # inner loop over n_classes + with nogil, parallel(num_threads=n_threads): + # Define private buffer variables as each thread might use its + # own. + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + sum_exps = max_value_and_sum_exps.val2 + + for k in range(n_classes): + proba_out[i, k] = p[k] / sum_exps # y_pred_k = prob of class k + # gradient_k = y_pred_k - (y_true == k) + gradient_out[i, k] = proba_out[i, k] - (y_true[i] == k) + + free(p) + else: + with nogil, parallel(num_threads=n_threads): + p = malloc(sizeof(floating_in) * (n_classes)) + + for i in prange(n_samples, schedule='static'): + max_value_and_sum_exps = sum_exp_minus_max(i, raw_prediction, p) + sum_exps = max_value_and_sum_exps.val2 + + for k in range(n_classes): + proba_out[i, k] = p[k] / sum_exps # y_pred_k = prob of class k + # gradient_k = (p_k - (y_true == k)) * sw + gradient_out[i, k] = (proba_out[i, k] - (y_true[i] == k)) * sample_weight[i] + + free(p) diff --git a/shared/package-files/3c/3ca9099300d8d452ae99bce22f1c4d37f4deaa395d407c62739e1dd7f87e5799/test_file_handling.py b/shared/package-files/3c/3ca9099300d8d452ae99bce22f1c4d37f4deaa395d407c62739e1dd7f87e5799/test_file_handling.py new file mode 100644 index 0000000000000000000000000000000000000000..100a55e6e346d4ff585c517ef7aa79881ec2d95c --- /dev/null +++ b/shared/package-files/3c/3ca9099300d8d452ae99bce22f1c4d37f4deaa395d407c62739e1dd7f87e5799/test_file_handling.py @@ -0,0 +1,517 @@ +import os + +import numpy as np +import pytest + +from pandas.compat import ( + PY311, + is_ci_environment, + is_platform_linux, + is_platform_little_endian, +) +from pandas.errors import ( + ClosedFileError, + PossibleDataLossError, +) + +from pandas import ( + DataFrame, + HDFStore, + Index, + Series, + _testing as tm, + date_range, + read_hdf, +) +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_store, + tables, +) + +from pandas.io import pytables +from pandas.io.pytables import Term + +pytestmark = [pytest.mark.single_cpu] + + +@pytest.mark.parametrize("mode", ["r", "r+", "a", "w"]) +def test_mode(setup_path, tmp_path, mode, using_infer_string): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + msg = r"[\S]* does not exist" + path = tmp_path / setup_path + + # constructor + if mode in ["r", "r+"]: + with pytest.raises(OSError, match=msg): + HDFStore(path, mode=mode) + + else: + with HDFStore(path, mode=mode) as store: + assert store._handle.mode == mode + + path = tmp_path / setup_path + + # context + if mode in ["r", "r+"]: + with pytest.raises(OSError, match=msg): + with HDFStore(path, mode=mode) as store: + pass + else: + with HDFStore(path, mode=mode) as store: + assert store._handle.mode == mode + + path = tmp_path / setup_path + + # conv write + if mode in ["r", "r+"]: + with pytest.raises(OSError, match=msg): + df.to_hdf(path, key="df", mode=mode) + df.to_hdf(path, key="df", mode="w") + else: + df.to_hdf(path, key="df", mode=mode) + + # conv read + if mode in ["w"]: + msg = ( + "mode w is not allowed while performing a read. " + r"Allowed modes are r, r\+ and a." + ) + with pytest.raises(ValueError, match=msg): + read_hdf(path, "df", mode=mode) + else: + result = read_hdf(path, "df", mode=mode) + if using_infer_string: + df.columns = df.columns.astype("str") + tm.assert_frame_equal(result, df) + + +def test_default_mode(tmp_path, setup_path, using_infer_string): + # read_hdf uses default mode + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + path = tmp_path / setup_path + df.to_hdf(path, key="df", mode="w") + result = read_hdf(path, "df") + expected = df.copy() + if using_infer_string: + expected.columns = expected.columns.astype("str") + tm.assert_frame_equal(result, expected) + + +def test_reopen_handle(tmp_path, setup_path): + path = tmp_path / setup_path + + store = HDFStore(path, mode="a") + store["a"] = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + + msg = ( + r"Re-opening the file \[[\S]*\] with mode \[a\] will delete the " + "current file!" + ) + # invalid mode change + with pytest.raises(PossibleDataLossError, match=msg): + store.open("w") + + store.close() + assert not store.is_open + + # truncation ok here + store.open("w") + assert store.is_open + assert len(store) == 0 + store.close() + assert not store.is_open + + store = HDFStore(path, mode="a") + store["a"] = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + + # reopen as read + store.open("r") + assert store.is_open + assert len(store) == 1 + assert store._mode == "r" + store.close() + assert not store.is_open + + # reopen as append + store.open("a") + assert store.is_open + assert len(store) == 1 + assert store._mode == "a" + store.close() + assert not store.is_open + + # reopen as append (again) + store.open("a") + assert store.is_open + assert len(store) == 1 + assert store._mode == "a" + store.close() + assert not store.is_open + + +def test_open_args(setup_path, using_infer_string): + with tm.ensure_clean(setup_path) as path: + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + + # create an in memory store + store = HDFStore( + path, mode="a", driver="H5FD_CORE", driver_core_backing_store=0 + ) + store["df"] = df + store.append("df2", df) + + expected = df.copy() + if using_infer_string: + expected.index = expected.index.astype("str") + expected.columns = expected.columns.astype("str") + + tm.assert_frame_equal(store["df"], expected) + tm.assert_frame_equal(store["df2"], expected) + + store.close() + + # the file should not have actually been written + assert not os.path.exists(path) + + +def test_flush(setup_path): + with ensure_clean_store(setup_path) as store: + store["a"] = Series(range(5)) + store.flush() + store.flush(fsync=True) + + +def test_complibs_default_settings(tmp_path, setup_path, using_infer_string): + # GH15943 + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + + # Set complevel and check if complib is automatically set to + # default value + tmpfile = tmp_path / setup_path + df.to_hdf(tmpfile, key="df", complevel=9) + result = read_hdf(tmpfile, "df") + expected = df.copy() + if using_infer_string: + expected.index = expected.index.astype("str") + expected.columns = expected.columns.astype("str") + tm.assert_frame_equal(result, expected) + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 9 + assert node.filters.complib == "zlib" + + # Set complib and check to see if compression is disabled + tmpfile = tmp_path / setup_path + df.to_hdf(tmpfile, key="df", complib="zlib") + result = read_hdf(tmpfile, "df") + expected = df.copy() + if using_infer_string: + expected.index = expected.index.astype("str") + expected.columns = expected.columns.astype("str") + tm.assert_frame_equal(result, expected) + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 0 + assert node.filters.complib is None + + # Check if not setting complib or complevel results in no compression + tmpfile = tmp_path / setup_path + df.to_hdf(tmpfile, key="df") + result = read_hdf(tmpfile, "df") + expected = df.copy() + if using_infer_string: + expected.index = expected.index.astype("str") + expected.columns = expected.columns.astype("str") + tm.assert_frame_equal(result, expected) + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 0 + assert node.filters.complib is None + + +def test_complibs_default_settings_override(tmp_path, setup_path): + # Check if file-defaults can be overridden on a per table basis + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + tmpfile = tmp_path / setup_path + store = HDFStore(tmpfile) + store.append("dfc", df, complevel=9, complib="blosc") + store.append("df", df) + store.close() + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 0 + assert node.filters.complib is None + for node in h5file.walk_nodes(where="/dfc", classname="Leaf"): + assert node.filters.complevel == 9 + assert node.filters.complib == "blosc" + + +@pytest.mark.parametrize("lvl", range(10)) +@pytest.mark.parametrize("lib", tables.filters.all_complibs) +@pytest.mark.filterwarnings("ignore:object name is not a valid") +@pytest.mark.skipif( + not PY311 and is_ci_environment() and is_platform_linux(), + reason="Segfaulting in a CI environment" + # with xfail, would sometimes raise UnicodeDecodeError + # invalid state byte +) +def test_complibs(tmp_path, lvl, lib, request): + # GH14478 + if PY311 and is_platform_linux() and lib == "blosc2" and lvl != 0: + request.applymarker( + pytest.mark.xfail(reason=f"Fails for {lib} on Linux and PY > 3.11") + ) + df = DataFrame( + np.ones((30, 4)), columns=list("ABCD"), index=np.arange(30).astype(np.str_) + ) + + # Remove lzo if its not available on this platform + if not tables.which_lib_version("lzo"): + pytest.skip("lzo not available") + # Remove bzip2 if its not available on this platform + if not tables.which_lib_version("bzip2"): + pytest.skip("bzip2 not available") + + tmpfile = tmp_path / f"{lvl}_{lib}.h5" + gname = f"{lvl}_{lib}" + + # Write and read file to see if data is consistent + df.to_hdf(tmpfile, key=gname, complib=lib, complevel=lvl) + result = read_hdf(tmpfile, gname) + tm.assert_frame_equal(result, df) + + # Open file and check metadata for correct amount of compression + with tables.open_file(tmpfile, mode="r") as h5table: + for node in h5table.walk_nodes(where="/" + gname, classname="Leaf"): + assert node.filters.complevel == lvl + if lvl == 0: + assert node.filters.complib is None + else: + assert node.filters.complib == lib + + +@pytest.mark.skipif( + not is_platform_little_endian(), reason="reason platform is not little endian" +) +def test_encoding(setup_path): + with ensure_clean_store(setup_path) as store: + df = DataFrame({"A": "foo", "B": "bar"}, index=range(5)) + df.loc[2, "A"] = np.nan + df.loc[3, "B"] = np.nan + _maybe_remove(store, "df") + store.append("df", df, encoding="ascii") + tm.assert_frame_equal(store["df"], df) + + expected = df.reindex(columns=["A"]) + result = store.select("df", Term("columns=A", encoding="ascii")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "val", + [ + [b"E\xc9, 17", b"", b"a", b"b", b"c"], + [b"E\xc9, 17", b"a", b"b", b"c"], + [b"EE, 17", b"", b"a", b"b", b"c"], + [b"E\xc9, 17", b"\xf8\xfc", b"a", b"b", b"c"], + [b"", b"a", b"b", b"c"], + [b"\xf8\xfc", b"a", b"b", b"c"], + [b"A\xf8\xfc", b"", b"a", b"b", b"c"], + [np.nan, b"", b"b", b"c"], + [b"A\xf8\xfc", np.nan, b"", b"b", b"c"], + ], +) +@pytest.mark.parametrize("dtype", ["category", None]) +def test_latin_encoding(tmp_path, setup_path, dtype, val): + enc = "latin-1" + nan_rep = "" + key = "data" + + val = [x.decode(enc) if isinstance(x, bytes) else x for x in val] + ser = Series(val, dtype=dtype) + + store = tmp_path / setup_path + ser.to_hdf(store, key=key, format="table", encoding=enc, nan_rep=nan_rep) + retr = read_hdf(store, key) + + # TODO:(3.0): once Categorical replace deprecation is enforced, + # we may be able to re-simplify the construction of s_nan + if dtype == "category": + if nan_rep in ser.cat.categories: + s_nan = ser.cat.remove_categories([nan_rep]) + else: + s_nan = ser + else: + s_nan = ser.replace(nan_rep, np.nan) + + tm.assert_series_equal(s_nan, retr) + + +def test_multiple_open_close(tmp_path, setup_path): + # gh-4409: open & close multiple times + + path = tmp_path / setup_path + + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + df.to_hdf(path, key="df", mode="w", format="table") + + # single + store = HDFStore(path) + assert "CLOSED" not in store.info() + assert store.is_open + + store.close() + assert "CLOSED" in store.info() + assert not store.is_open + + path = tmp_path / setup_path + + if pytables._table_file_open_policy_is_strict: + # multiples + store1 = HDFStore(path) + msg = ( + r"The file [\S]* is already opened\. Please close it before " + r"reopening in write mode\." + ) + with pytest.raises(ValueError, match=msg): + HDFStore(path) + + store1.close() + else: + # multiples + store1 = HDFStore(path) + store2 = HDFStore(path) + + assert "CLOSED" not in store1.info() + assert "CLOSED" not in store2.info() + assert store1.is_open + assert store2.is_open + + store1.close() + assert "CLOSED" in store1.info() + assert not store1.is_open + assert "CLOSED" not in store2.info() + assert store2.is_open + + store2.close() + assert "CLOSED" in store1.info() + assert "CLOSED" in store2.info() + assert not store1.is_open + assert not store2.is_open + + # nested close + store = HDFStore(path, mode="w") + store.append("df", df) + + store2 = HDFStore(path) + store2.append("df2", df) + store2.close() + assert "CLOSED" in store2.info() + assert not store2.is_open + + store.close() + assert "CLOSED" in store.info() + assert not store.is_open + + # double closing + store = HDFStore(path, mode="w") + store.append("df", df) + + store2 = HDFStore(path) + store.close() + assert "CLOSED" in store.info() + assert not store.is_open + + store2.close() + assert "CLOSED" in store2.info() + assert not store2.is_open + + # ops on a closed store + path = tmp_path / setup_path + + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + df.to_hdf(path, key="df", mode="w", format="table") + + store = HDFStore(path) + store.close() + + msg = r"[\S]* file is not open!" + with pytest.raises(ClosedFileError, match=msg): + store.keys() + + with pytest.raises(ClosedFileError, match=msg): + "df" in store + + with pytest.raises(ClosedFileError, match=msg): + len(store) + + with pytest.raises(ClosedFileError, match=msg): + store["df"] + + with pytest.raises(ClosedFileError, match=msg): + store.select("df") + + with pytest.raises(ClosedFileError, match=msg): + store.get("df") + + with pytest.raises(ClosedFileError, match=msg): + store.append("df2", df) + + with pytest.raises(ClosedFileError, match=msg): + store.put("df3", df) + + with pytest.raises(ClosedFileError, match=msg): + store.get_storer("df2") + + with pytest.raises(ClosedFileError, match=msg): + store.remove("df2") + + with pytest.raises(ClosedFileError, match=msg): + store.select("df") + + msg = "'HDFStore' object has no attribute 'df'" + with pytest.raises(AttributeError, match=msg): + store.df + + +def test_fspath(): + with tm.ensure_clean("foo.h5") as path: + with HDFStore(path) as store: + assert os.fspath(store) == str(path) diff --git a/shared/package-files/3c/3ca96c4116878774108eccc2fda1f2706bcd25fcf2e8af98014658d88a3be796/minitel1b-nb b/shared/package-files/3c/3ca96c4116878774108eccc2fda1f2706bcd25fcf2e8af98014658d88a3be796/minitel1b-nb new file mode 100644 index 0000000000000000000000000000000000000000..405db818c7e73e0509c2c1e2c740961b1e76ba4b Binary files /dev/null and b/shared/package-files/3c/3ca96c4116878774108eccc2fda1f2706bcd25fcf2e8af98014658d88a3be796/minitel1b-nb differ diff --git a/shared/package-files/3c/3caf9f5a5d67066d81a49c1decf32cc136000a05a6e356c7864561f42353801c/packer.py b/shared/package-files/3c/3caf9f5a5d67066d81a49c1decf32cc136000a05a6e356c7864561f42353801c/packer.py new file mode 100644 index 0000000000000000000000000000000000000000..9efc51449bc3699b67e2cef8035bbdb93c3dabde --- /dev/null +++ b/shared/package-files/3c/3caf9f5a5d67066d81a49c1decf32cc136000a05a6e356c7864561f42353801c/packer.py @@ -0,0 +1,213 @@ +from collections import deque + +from numba.core import types, cgutils + + + +class DataPacker(object): + """ + A helper to pack a number of typed arguments into a data structure. + Omitted arguments (i.e. values with the type `Omitted`) are automatically + skipped. + """ + # XXX should DataPacker be a model for a dedicated type? + + def __init__(self, dmm, fe_types): + self._dmm = dmm + self._fe_types = fe_types + self._models = [dmm.lookup(ty) for ty in fe_types] + + self._pack_map = [] + self._be_types = [] + for i, ty in enumerate(fe_types): + if not isinstance(ty, types.Omitted): + self._pack_map.append(i) + self._be_types.append(self._models[i].get_data_type()) + + def as_data(self, builder, values): + """ + Return the given values packed as a data structure. + """ + elems = [self._models[i].as_data(builder, values[i]) + for i in self._pack_map] + return cgutils.make_anonymous_struct(builder, elems) + + def _do_load(self, builder, ptr, formal_list=None): + res = [] + for i, i_formal in enumerate(self._pack_map): + elem_ptr = cgutils.gep_inbounds(builder, ptr, 0, i) + val = self._models[i_formal].load_from_data_pointer(builder, elem_ptr) + if formal_list is None: + res.append((self._fe_types[i_formal], val)) + else: + formal_list[i_formal] = val + return res + + def load(self, builder, ptr): + """ + Load the packed values and return a (type, value) tuples. + """ + return self._do_load(builder, ptr) + + def load_into(self, builder, ptr, formal_list): + """ + Load the packed values into a sequence indexed by formal + argument number (skipping any Omitted position). + """ + self._do_load(builder, ptr, formal_list) + + +class ArgPacker(object): + """ + Compute the position for each high-level typed argument. + It flattens every composite argument into primitive types. + It maintains a position map for unflattening the arguments. + + Since struct (esp. nested struct) have specific ABI requirements (e.g. + alignment, pointer address-space, ...) in different architecture (e.g. + OpenCL, CUDA), flattening composite argument types simplifes the call + setup from the Python side. Functions are receiving simple primitive + types and there are only a handful of these. + """ + + def __init__(self, dmm, fe_args): + self._dmm = dmm + self._fe_args = fe_args + self._nargs = len(fe_args) + + self._dm_args = [] + argtys = [] + for ty in fe_args: + dm = self._dmm.lookup(ty) + self._dm_args.append(dm) + argtys.append(dm.get_argument_type()) + self._unflattener = _Unflattener(argtys) + self._be_args = list(_flatten(argtys)) + + def as_arguments(self, builder, values): + """Flatten all argument values + """ + if len(values) != self._nargs: + raise TypeError("invalid number of args: expected %d, got %d" + % (self._nargs, len(values))) + + if not values: + return () + + args = [dm.as_argument(builder, val) + for dm, val in zip(self._dm_args, values) + ] + + args = tuple(_flatten(args)) + return args + + def from_arguments(self, builder, args): + """Unflatten all argument values + """ + + valtree = self._unflattener.unflatten(args) + values = [dm.from_argument(builder, val) + for dm, val in zip(self._dm_args, valtree) + ] + + return values + + def assign_names(self, args, names): + """Assign names for each flattened argument values. + """ + + valtree = self._unflattener.unflatten(args) + for aval, aname in zip(valtree, names): + self._assign_names(aval, aname) + + def _assign_names(self, val_or_nested, name, depth=()): + if isinstance(val_or_nested, (tuple, list)): + for pos, aval in enumerate(val_or_nested): + self._assign_names(aval, name, depth=depth + (pos,)) + else: + postfix = '.'.join(map(str, depth)) + parts = [name, postfix] + val_or_nested.name = '.'.join(filter(bool, parts)) + + @property + def argument_types(self): + """Return a list of LLVM types that are results of flattening + composite types. + """ + return tuple(ty for ty in self._be_args if ty != ()) + + +def _flatten(iterable): + """ + Flatten nested iterable of (tuple, list). + """ + def rec(iterable): + for i in iterable: + if isinstance(i, (tuple, list)): + for j in rec(i): + yield j + else: + yield i + return rec(iterable) + + +_PUSH_LIST = 1 +_APPEND_NEXT_VALUE = 2 +_APPEND_EMPTY_TUPLE = 3 +_POP = 4 + +class _Unflattener(object): + """ + An object used to unflatten nested sequences after a given pattern + (an arbitrarily nested sequence). + The pattern shows the nested sequence shape desired when unflattening; + the values it contains are irrelevant. + """ + + def __init__(self, pattern): + self._code = self._build_unflatten_code(pattern) + + def _build_unflatten_code(self, iterable): + """Build the unflatten opcode sequence for the given *iterable* structure + (an iterable of nested sequences). + """ + code = [] + def rec(iterable): + for i in iterable: + if isinstance(i, (tuple, list)): + if len(i) > 0: + code.append(_PUSH_LIST) + rec(i) + code.append(_POP) + else: + code.append(_APPEND_EMPTY_TUPLE) + else: + code.append(_APPEND_NEXT_VALUE) + + rec(iterable) + return code + + def unflatten(self, flatiter): + """Rebuild a nested tuple structure. + """ + vals = deque(flatiter) + + res = [] + cur = res + stack = [] + for op in self._code: + if op is _PUSH_LIST: + stack.append(cur) + cur.append([]) + cur = cur[-1] + elif op is _APPEND_NEXT_VALUE: + cur.append(vals.popleft()) + elif op is _APPEND_EMPTY_TUPLE: + cur.append(()) + elif op is _POP: + cur = stack.pop() + + assert not stack, stack + assert not vals, vals + + return res diff --git a/shared/package-files/3c/3cb6f1d1fb4e71f317c20c163d4539a4728f169b85a3b6eeb0f1785a6731bd70/nonzero_static_cpu_dispatch.h b/shared/package-files/3c/3cb6f1d1fb4e71f317c20c163d4539a4728f169b85a3b6eeb0f1785a6731bd70/nonzero_static_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9690c07494ae12e7afdad1cc7de61e9c09d1ec3b --- /dev/null +++ b/shared/package-files/3c/3cb6f1d1fb4e71f317c20c163d4539a4728f169b85a3b6eeb0f1785a6731bd70/nonzero_static_cpu_dispatch.h @@ -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 nonzero_static(const at::Tensor & self, int64_t size, int64_t fill_value=-1); +TORCH_API at::Tensor & nonzero_static_out(at::Tensor & out, const at::Tensor & self, int64_t size, int64_t fill_value=-1); +TORCH_API at::Tensor & nonzero_static_outf(const at::Tensor & self, int64_t size, int64_t fill_value, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/3c/3cbb9289c0619eca4295389278a08980a775372534a8190346f40caf09bf80b7/test_codegen.py b/shared/package-files/3c/3cbb9289c0619eca4295389278a08980a775372534a8190346f40caf09bf80b7/test_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..f90d5eaa68b34d056e36e2e10242d6818abd7d8d --- /dev/null +++ b/shared/package-files/3c/3cbb9289c0619eca4295389278a08980a775372534a8190346f40caf09bf80b7/test_codegen.py @@ -0,0 +1,1613 @@ +from io import StringIO + +from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy +from sympy.core.relational import Equality +from sympy.core.symbol import Symbol +from sympy.functions.special.error_functions import erf +from sympy.integrals.integrals import Integral +from sympy.matrices import Matrix, MatrixSymbol +from sympy.utilities.codegen import ( + codegen, make_routine, CCodeGen, C89CodeGen, C99CodeGen, InputArgument, + CodeGenError, FCodeGen, CodeGenArgumentListError, OutputArgument, + InOutArgument) +from sympy.testing.pytest import raises +from sympy.utilities.lambdify import implemented_function + +#FIXME: Fails due to circular import in with core +# from sympy import codegen + + +def get_string(dump_fn, routines, prefix="file", header=False, empty=False): + """Wrapper for dump_fn. dump_fn writes its results to a stream object and + this wrapper returns the contents of that stream as a string. This + auxiliary function is used by many tests below. + + The header and the empty lines are not generated to facilitate the + testing of the output. + """ + output = StringIO() + dump_fn(routines, output, prefix, header, empty) + source = output.getvalue() + output.close() + return source + + +def test_Routine_argument_order(): + a, x, y, z = symbols('a x y z') + expr = (x + y)*z + raises(CodeGenArgumentListError, lambda: make_routine("test", expr, + argument_sequence=[z, x])) + raises(CodeGenArgumentListError, lambda: make_routine("test", Eq(a, + expr), argument_sequence=[z, x, y])) + r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y]) + assert [ arg.name for arg in r.arguments ] == [z, x, a, y] + assert [ type(arg) for arg in r.arguments ] == [ + InputArgument, InputArgument, OutputArgument, InputArgument ] + r = make_routine('test', Eq(z, expr), argument_sequence=[z, x, y]) + assert [ type(arg) for arg in r.arguments ] == [ + InOutArgument, InputArgument, InputArgument ] + + from sympy.tensor import IndexedBase, Idx + A, B = map(IndexedBase, ['A', 'B']) + m = symbols('m', integer=True) + i = Idx('i', m) + r = make_routine('test', Eq(A[i], B[i]), argument_sequence=[B, A, m]) + assert [ arg.name for arg in r.arguments ] == [B.label, A.label, m] + + expr = Integral(x*y*z, (x, 1, 2), (y, 1, 3)) + r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y]) + assert [ arg.name for arg in r.arguments ] == [z, x, a, y] + + +def test_empty_c_code(): + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, []) + assert source == "#include \"file.h\"\n#include \n" + + +def test_empty_c_code_with_comment(): + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [], header=True) + assert source[:82] == ( + "/******************************************************************************\n *" + ) + # " Code generated with SymPy 0.7.2-git " + assert source[158:] == ( "*\n" + " * *\n" + " * See http://www.sympy.org/ for more information. *\n" + " * *\n" + " * This file is part of 'project' *\n" + " ******************************************************************************/\n" + "#include \"file.h\"\n" + "#include \n" + ) + + +def test_empty_c_header(): + code_gen = C99CodeGen() + source = get_string(code_gen.dump_h, []) + assert source == "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n#endif\n" + + +def test_simple_c_code(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test(double x, double y, double z) {\n" + " double test_result;\n" + " test_result = z*(x + y);\n" + " return test_result;\n" + "}\n" + ) + assert source == expected + + +def test_c_code_reserved_words(): + x, y, z = symbols('if, typedef, while') + expr = (x + y) * z + routine = make_routine("test", expr) + code_gen = C99CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test(double if_, double typedef_, double while_) {\n" + " double test_result;\n" + " test_result = while_*(if_ + typedef_);\n" + " return test_result;\n" + "}\n" + ) + assert source == expected + + +def test_numbersymbol_c_code(): + routine = make_routine("test", pi**Catalan) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test() {\n" + " double test_result;\n" + " double const Catalan = %s;\n" + " test_result = pow(M_PI, Catalan);\n" + " return test_result;\n" + "}\n" + ) % Catalan.evalf(17) + assert source == expected + + +def test_c_code_argument_order(): + x, y, z = symbols('x,y,z') + expr = x + y + routine = make_routine("test", expr, argument_sequence=[z, x, y]) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test(double z, double x, double y) {\n" + " double test_result;\n" + " test_result = x + y;\n" + " return test_result;\n" + "}\n" + ) + assert source == expected + + +def test_simple_c_header(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_h, [routine]) + expected = ( + "#ifndef PROJECT__FILE__H\n" + "#define PROJECT__FILE__H\n" + "double test(double x, double y, double z);\n" + "#endif\n" + ) + assert source == expected + + +def test_simple_c_codegen(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + expected = [ + ("file.c", + "#include \"file.h\"\n" + "#include \n" + "double test(double x, double y, double z) {\n" + " double test_result;\n" + " test_result = z*(x + y);\n" + " return test_result;\n" + "}\n"), + ("file.h", + "#ifndef PROJECT__FILE__H\n" + "#define PROJECT__FILE__H\n" + "double test(double x, double y, double z);\n" + "#endif\n") + ] + result = codegen(("test", expr), "C", "file", header=False, empty=False) + assert result == expected + + +def test_multiple_results_c(): + x, y, z = symbols('x,y,z') + expr1 = (x + y)*z + expr2 = (x - y)*z + routine = make_routine( + "test", + [expr1, expr2] + ) + code_gen = C99CodeGen() + raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) + + +def test_no_results_c(): + raises(ValueError, lambda: make_routine("test", [])) + + +def test_ansi_math1_codegen(): + # not included: log10 + from sympy.functions.elementary.complexes import Abs + from sympy.functions.elementary.exponential import log + from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) + from sympy.functions.elementary.integers import (ceiling, floor) + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) + x = symbols('x') + name_expr = [ + ("test_fabs", Abs(x)), + ("test_acos", acos(x)), + ("test_asin", asin(x)), + ("test_atan", atan(x)), + ("test_ceil", ceiling(x)), + ("test_cos", cos(x)), + ("test_cosh", cosh(x)), + ("test_floor", floor(x)), + ("test_log", log(x)), + ("test_ln", log(x)), + ("test_sin", sin(x)), + ("test_sinh", sinh(x)), + ("test_sqrt", sqrt(x)), + ("test_tan", tan(x)), + ("test_tanh", tanh(x)), + ] + result = codegen(name_expr, "C89", "file", header=False, empty=False) + assert result[0][0] == "file.c" + assert result[0][1] == ( + '#include "file.h"\n#include \n' + 'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n' + 'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n' + 'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n' + 'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n' + 'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n' + 'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n' + 'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n' + 'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n' + 'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n' + 'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n' + 'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n' + 'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n' + 'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n' + 'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n' + 'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n' + ) + assert result[1][0] == "file.h" + assert result[1][1] == ( + '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' + 'double test_fabs(double x);\ndouble test_acos(double x);\n' + 'double test_asin(double x);\ndouble test_atan(double x);\n' + 'double test_ceil(double x);\ndouble test_cos(double x);\n' + 'double test_cosh(double x);\ndouble test_floor(double x);\n' + 'double test_log(double x);\ndouble test_ln(double x);\n' + 'double test_sin(double x);\ndouble test_sinh(double x);\n' + 'double test_sqrt(double x);\ndouble test_tan(double x);\n' + 'double test_tanh(double x);\n#endif\n' + ) + + +def test_ansi_math2_codegen(): + # not included: frexp, ldexp, modf, fmod + from sympy.functions.elementary.trigonometric import atan2 + x, y = symbols('x,y') + name_expr = [ + ("test_atan2", atan2(x, y)), + ("test_pow", x**y), + ] + result = codegen(name_expr, "C89", "file", header=False, empty=False) + assert result[0][0] == "file.c" + assert result[0][1] == ( + '#include "file.h"\n#include \n' + 'double test_atan2(double x, double y) {\n double test_atan2_result;\n test_atan2_result = atan2(x, y);\n return test_atan2_result;\n}\n' + 'double test_pow(double x, double y) {\n double test_pow_result;\n test_pow_result = pow(x, y);\n return test_pow_result;\n}\n' + ) + assert result[1][0] == "file.h" + assert result[1][1] == ( + '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' + 'double test_atan2(double x, double y);\n' + 'double test_pow(double x, double y);\n' + '#endif\n' + ) + + +def test_complicated_codegen(): + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + x, y, z = symbols('x,y,z') + name_expr = [ + ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), + ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), + ] + result = codegen(name_expr, "C89", "file", header=False, empty=False) + assert result[0][0] == "file.c" + assert result[0][1] == ( + '#include "file.h"\n#include \n' + 'double test1(double x, double y, double z) {\n' + ' double test1_result;\n' + ' test1_result = ' + 'pow(sin(x), 7) + ' + '7*pow(sin(x), 6)*cos(y) + ' + '7*pow(sin(x), 6)*tan(z) + ' + '21*pow(sin(x), 5)*pow(cos(y), 2) + ' + '42*pow(sin(x), 5)*cos(y)*tan(z) + ' + '21*pow(sin(x), 5)*pow(tan(z), 2) + ' + '35*pow(sin(x), 4)*pow(cos(y), 3) + ' + '105*pow(sin(x), 4)*pow(cos(y), 2)*tan(z) + ' + '105*pow(sin(x), 4)*cos(y)*pow(tan(z), 2) + ' + '35*pow(sin(x), 4)*pow(tan(z), 3) + ' + '35*pow(sin(x), 3)*pow(cos(y), 4) + ' + '140*pow(sin(x), 3)*pow(cos(y), 3)*tan(z) + ' + '210*pow(sin(x), 3)*pow(cos(y), 2)*pow(tan(z), 2) + ' + '140*pow(sin(x), 3)*cos(y)*pow(tan(z), 3) + ' + '35*pow(sin(x), 3)*pow(tan(z), 4) + ' + '21*pow(sin(x), 2)*pow(cos(y), 5) + ' + '105*pow(sin(x), 2)*pow(cos(y), 4)*tan(z) + ' + '210*pow(sin(x), 2)*pow(cos(y), 3)*pow(tan(z), 2) + ' + '210*pow(sin(x), 2)*pow(cos(y), 2)*pow(tan(z), 3) + ' + '105*pow(sin(x), 2)*cos(y)*pow(tan(z), 4) + ' + '21*pow(sin(x), 2)*pow(tan(z), 5) + ' + '7*sin(x)*pow(cos(y), 6) + ' + '42*sin(x)*pow(cos(y), 5)*tan(z) + ' + '105*sin(x)*pow(cos(y), 4)*pow(tan(z), 2) + ' + '140*sin(x)*pow(cos(y), 3)*pow(tan(z), 3) + ' + '105*sin(x)*pow(cos(y), 2)*pow(tan(z), 4) + ' + '42*sin(x)*cos(y)*pow(tan(z), 5) + ' + '7*sin(x)*pow(tan(z), 6) + ' + 'pow(cos(y), 7) + ' + '7*pow(cos(y), 6)*tan(z) + ' + '21*pow(cos(y), 5)*pow(tan(z), 2) + ' + '35*pow(cos(y), 4)*pow(tan(z), 3) + ' + '35*pow(cos(y), 3)*pow(tan(z), 4) + ' + '21*pow(cos(y), 2)*pow(tan(z), 5) + ' + '7*cos(y)*pow(tan(z), 6) + ' + 'pow(tan(z), 7);\n' + ' return test1_result;\n' + '}\n' + 'double test2(double x, double y, double z) {\n' + ' double test2_result;\n' + ' test2_result = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n' + ' return test2_result;\n' + '}\n' + ) + assert result[1][0] == "file.h" + assert result[1][1] == ( + '#ifndef PROJECT__FILE__H\n' + '#define PROJECT__FILE__H\n' + 'double test1(double x, double y, double z);\n' + 'double test2(double x, double y, double z);\n' + '#endif\n' + ) + + +def test_loops_c(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m = symbols('n m', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False) + + assert f1 == 'file.c' + expected = ( + '#include "file.h"\n' + '#include \n' + 'void matrix_vector(double *A, int m, int n, double *x, double *y) {\n' + ' for (int i=0; i\n' + 'void test_dummies(int m_%(mno)i, double *x, double *y) {\n' + ' for (int i_%(ino)i=0; i_%(ino)i\n' + 'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y) {\n' + ' for (int i=o; i<%(upperi)s; i++){\n' + ' y[i] = 0;\n' + ' }\n' + ' for (int i=o; i<%(upperi)s; i++){\n' + ' for (int j=0; j\n' + 'double foo(double x, double *y) {\n' + ' (*y) = sin(x);\n' + ' double foo_result;\n' + ' foo_result = cos(x);\n' + ' return foo_result;\n' + '}\n' + ) + assert result[0][1] == expected + + +def test_output_arg_c_reserved_words(): + from sympy.core.relational import Equality + from sympy.functions.elementary.trigonometric import (cos, sin) + x, y, z = symbols("if, while, z") + r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) + c = C89CodeGen() + result = c.write([r], "test", header=False, empty=False) + assert result[0][0] == "test.c" + expected = ( + '#include "test.h"\n' + '#include \n' + 'double foo(double if_, double *while_) {\n' + ' (*while_) = sin(if_);\n' + ' double foo_result;\n' + ' foo_result = cos(if_);\n' + ' return foo_result;\n' + '}\n' + ) + assert result[0][1] == expected + + +def test_multidim_c_argument_cse(): + A_sym = MatrixSymbol('A', 3, 3) + b_sym = MatrixSymbol('b', 3, 1) + A = Matrix(A_sym) + b = Matrix(b_sym) + c = A*b + cgen = CCodeGen(project="test", cse=True) + r = cgen.routine("c", c) + r.arguments[-1].result_var = "out" + r.arguments[-1]._name = "out" + code = get_string(cgen.dump_c, [r], prefix="test") + expected = ( + '#include "test.h"\n' + "#include \n" + "void c(double *A, double *b, double *out) {\n" + " out[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2];\n" + " out[1] = A[3]*b[0] + A[4]*b[1] + A[5]*b[2];\n" + " out[2] = A[6]*b[0] + A[7]*b[1] + A[8]*b[2];\n" + "}\n" + ) + assert code == expected + + +def test_ccode_results_named_ordered(): + x, y, z = symbols('x,y,z') + B, C = symbols('B,C') + A = MatrixSymbol('A', 1, 3) + expr1 = Equality(A, Matrix([[1, 2, x]])) + expr2 = Equality(C, (x + y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + expected = ( + '#include "test.h"\n' + '#include \n' + 'void test(double x, double *C, double z, double y, double *A, double *B) {\n' + ' (*C) = z*(x + y);\n' + ' A[0] = 1;\n' + ' A[1] = 2;\n' + ' A[2] = x;\n' + ' (*B) = 2*x;\n' + '}\n' + ) + + result = codegen(name_expr, "c", "test", header=False, empty=False, + argument_sequence=(x, C, z, y, A, B)) + source = result[0][1] + assert source == expected + + +def test_ccode_matrixsymbol_slice(): + A = MatrixSymbol('A', 5, 3) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 1, 3) + D = MatrixSymbol('D', 5, 1) + name_expr = ("test", [Equality(B, A[0, :]), + Equality(C, A[1, :]), + Equality(D, A[:, 2])]) + result = codegen(name_expr, "c99", "test", header=False, empty=False) + source = result[0][1] + expected = ( + '#include "test.h"\n' + '#include \n' + 'void test(double *A, double *B, double *C, double *D) {\n' + ' B[0] = A[0];\n' + ' B[1] = A[1];\n' + ' B[2] = A[2];\n' + ' C[0] = A[3];\n' + ' C[1] = A[4];\n' + ' C[2] = A[5];\n' + ' D[0] = A[2];\n' + ' D[1] = A[5];\n' + ' D[2] = A[8];\n' + ' D[3] = A[11];\n' + ' D[4] = A[14];\n' + '}\n' + ) + assert source == expected + +def test_ccode_cse(): + a, b, c, d = symbols('a b c d') + e = MatrixSymbol('e', 3, 1) + name_expr = ("test", [Equality(e, Matrix([[a*b], [a*b + c*d], [a*b*c*d]]))]) + generator = CCodeGen(cse=True) + result = codegen(name_expr, code_gen=generator, header=False, empty=False) + source = result[0][1] + expected = ( + '#include "test.h"\n' + '#include \n' + 'void test(double a, double b, double c, double d, double *e) {\n' + ' const double x0 = a*b;\n' + ' const double x1 = c*d;\n' + ' e[0] = x0;\n' + ' e[1] = x0 + x1;\n' + ' e[2] = x0*x1;\n' + '}\n' + ) + assert source == expected + +def test_ccode_unused_array_arg(): + x = MatrixSymbol('x', 2, 1) + # x does not appear in output + name_expr = ("test", 1.0) + generator = CCodeGen() + result = codegen(name_expr, code_gen=generator, header=False, empty=False, argument_sequence=(x,)) + source = result[0][1] + # note: x should appear as (double *) + expected = ( + '#include "test.h"\n' + '#include \n' + 'double test(double *x) {\n' + ' double test_result;\n' + ' test_result = 1.0;\n' + ' return test_result;\n' + '}\n' + ) + assert source == expected + +def test_empty_f_code(): + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, []) + assert source == "" + + +def test_empty_f_code_with_header(): + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [], header=True) + assert source[:82] == ( + "!******************************************************************************\n!*" + ) + # " Code generated with SymPy 0.7.2-git " + assert source[158:] == ( "*\n" + "!* *\n" + "!* See http://www.sympy.org/ for more information. *\n" + "!* *\n" + "!* This file is part of 'project' *\n" + "!******************************************************************************\n" + ) + + +def test_empty_f_header(): + code_gen = FCodeGen() + source = get_string(code_gen.dump_h, []) + assert source == "" + + +def test_simple_f_code(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "test = z*(x + y)\n" + "end function\n" + ) + assert source == expected + + +def test_numbersymbol_f_code(): + routine = make_routine("test", pi**Catalan) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test()\n" + "implicit none\n" + "REAL*8, parameter :: Catalan = %sd0\n" + "REAL*8, parameter :: pi = %sd0\n" + "test = pi**Catalan\n" + "end function\n" + ) % (Catalan.evalf(17), pi.evalf(17)) + assert source == expected + +def test_erf_f_code(): + x = symbols('x') + routine = make_routine("test", erf(x) - erf(-2 * x)) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test(x)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "test = erf(x) + erf(2.0d0*x)\n" + "end function\n" + ) + assert source == expected, source + +def test_f_code_argument_order(): + x, y, z = symbols('x,y,z') + expr = x + y + routine = make_routine("test", expr, argument_sequence=[z, x, y]) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test(z, x, y)\n" + "implicit none\n" + "REAL*8, intent(in) :: z\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "test = x + y\n" + "end function\n" + ) + assert source == expected + + +def test_simple_f_header(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = FCodeGen() + source = get_string(code_gen.dump_h, [routine]) + expected = ( + "interface\n" + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "end function\n" + "end interface\n" + ) + assert source == expected + + +def test_simple_f_codegen(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + result = codegen( + ("test", expr), "F95", "file", header=False, empty=False) + expected = [ + ("file.f90", + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "test = z*(x + y)\n" + "end function\n"), + ("file.h", + "interface\n" + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "end function\n" + "end interface\n") + ] + assert result == expected + + +def test_multiple_results_f(): + x, y, z = symbols('x,y,z') + expr1 = (x + y)*z + expr2 = (x - y)*z + routine = make_routine( + "test", + [expr1, expr2] + ) + code_gen = FCodeGen() + raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) + + +def test_no_results_f(): + raises(ValueError, lambda: make_routine("test", [])) + + +def test_intrinsic_math_codegen(): + # not included: log10 + from sympy.functions.elementary.complexes import Abs + from sympy.functions.elementary.exponential import log + from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) + x = symbols('x') + name_expr = [ + ("test_abs", Abs(x)), + ("test_acos", acos(x)), + ("test_asin", asin(x)), + ("test_atan", atan(x)), + ("test_cos", cos(x)), + ("test_cosh", cosh(x)), + ("test_log", log(x)), + ("test_ln", log(x)), + ("test_sin", sin(x)), + ("test_sinh", sinh(x)), + ("test_sqrt", sqrt(x)), + ("test_tan", tan(x)), + ("test_tanh", tanh(x)), + ] + result = codegen(name_expr, "F95", "file", header=False, empty=False) + assert result[0][0] == "file.f90" + expected = ( + 'REAL*8 function test_abs(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_abs = abs(x)\n' + 'end function\n' + 'REAL*8 function test_acos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_acos = acos(x)\n' + 'end function\n' + 'REAL*8 function test_asin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_asin = asin(x)\n' + 'end function\n' + 'REAL*8 function test_atan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_atan = atan(x)\n' + 'end function\n' + 'REAL*8 function test_cos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_cos = cos(x)\n' + 'end function\n' + 'REAL*8 function test_cosh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_cosh = cosh(x)\n' + 'end function\n' + 'REAL*8 function test_log(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_log = log(x)\n' + 'end function\n' + 'REAL*8 function test_ln(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_ln = log(x)\n' + 'end function\n' + 'REAL*8 function test_sin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_sin = sin(x)\n' + 'end function\n' + 'REAL*8 function test_sinh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_sinh = sinh(x)\n' + 'end function\n' + 'REAL*8 function test_sqrt(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_sqrt = sqrt(x)\n' + 'end function\n' + 'REAL*8 function test_tan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_tan = tan(x)\n' + 'end function\n' + 'REAL*8 function test_tanh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_tanh = tanh(x)\n' + 'end function\n' + ) + assert result[0][1] == expected + + assert result[1][0] == "file.h" + expected = ( + 'interface\n' + 'REAL*8 function test_abs(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_acos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_asin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_atan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_cos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_cosh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_log(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_ln(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_sin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_sinh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_sqrt(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_tan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_tanh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + ) + assert result[1][1] == expected + + +def test_intrinsic_math2_codegen(): + # not included: frexp, ldexp, modf, fmod + from sympy.functions.elementary.trigonometric import atan2 + x, y = symbols('x,y') + name_expr = [ + ("test_atan2", atan2(x, y)), + ("test_pow", x**y), + ] + result = codegen(name_expr, "F95", "file", header=False, empty=False) + assert result[0][0] == "file.f90" + expected = ( + 'REAL*8 function test_atan2(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'test_atan2 = atan2(x, y)\n' + 'end function\n' + 'REAL*8 function test_pow(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'test_pow = x**y\n' + 'end function\n' + ) + assert result[0][1] == expected + + assert result[1][0] == "file.h" + expected = ( + 'interface\n' + 'REAL*8 function test_atan2(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_pow(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'end function\n' + 'end interface\n' + ) + assert result[1][1] == expected + + +def test_complicated_codegen_f95(): + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + x, y, z = symbols('x,y,z') + name_expr = [ + ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), + ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), + ] + result = codegen(name_expr, "F95", "file", header=False, empty=False) + assert result[0][0] == "file.f90" + expected = ( + 'REAL*8 function test1(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'test1 = sin(x)**7 + 7*sin(x)**6*cos(y) + 7*sin(x)**6*tan(z) + 21*sin(x) &\n' + ' **5*cos(y)**2 + 42*sin(x)**5*cos(y)*tan(z) + 21*sin(x)**5*tan(z) &\n' + ' **2 + 35*sin(x)**4*cos(y)**3 + 105*sin(x)**4*cos(y)**2*tan(z) + &\n' + ' 105*sin(x)**4*cos(y)*tan(z)**2 + 35*sin(x)**4*tan(z)**3 + 35*sin( &\n' + ' x)**3*cos(y)**4 + 140*sin(x)**3*cos(y)**3*tan(z) + 210*sin(x)**3* &\n' + ' cos(y)**2*tan(z)**2 + 140*sin(x)**3*cos(y)*tan(z)**3 + 35*sin(x) &\n' + ' **3*tan(z)**4 + 21*sin(x)**2*cos(y)**5 + 105*sin(x)**2*cos(y)**4* &\n' + ' tan(z) + 210*sin(x)**2*cos(y)**3*tan(z)**2 + 210*sin(x)**2*cos(y) &\n' + ' **2*tan(z)**3 + 105*sin(x)**2*cos(y)*tan(z)**4 + 21*sin(x)**2*tan &\n' + ' (z)**5 + 7*sin(x)*cos(y)**6 + 42*sin(x)*cos(y)**5*tan(z) + 105* &\n' + ' sin(x)*cos(y)**4*tan(z)**2 + 140*sin(x)*cos(y)**3*tan(z)**3 + 105 &\n' + ' *sin(x)*cos(y)**2*tan(z)**4 + 42*sin(x)*cos(y)*tan(z)**5 + 7*sin( &\n' + ' x)*tan(z)**6 + cos(y)**7 + 7*cos(y)**6*tan(z) + 21*cos(y)**5*tan( &\n' + ' z)**2 + 35*cos(y)**4*tan(z)**3 + 35*cos(y)**3*tan(z)**4 + 21*cos( &\n' + ' y)**2*tan(z)**5 + 7*cos(y)*tan(z)**6 + tan(z)**7\n' + 'end function\n' + 'REAL*8 function test2(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'test2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n' + 'end function\n' + ) + assert result[0][1] == expected + assert result[1][0] == "file.h" + expected = ( + 'interface\n' + 'REAL*8 function test1(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test2(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'end function\n' + 'end interface\n' + ) + assert result[1][1] == expected + + +def test_loops(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + + n, m = symbols('n,m', integer=True) + A, x, y = map(IndexedBase, 'Axy') + i = Idx('i', m) + j = Idx('j', n) + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) + + assert f1 == 'file.f90' + expected = ( + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(out), dimension(1:m) :: y\n' + 'INTEGER*4 :: i\n' + 'INTEGER*4 :: j\n' + 'do i = 1, m\n' + ' y(i) = 0\n' + 'end do\n' + 'do i = 1, m\n' + ' do j = 1, n\n' + ' y(i) = %(rhs)s + y(i)\n' + ' end do\n' + 'end do\n' + 'end subroutine\n' + ) + + assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ + code == expected % {'rhs': 'x(j)*A(i, j)'} + assert f2 == 'file.h' + assert interface == ( + 'interface\n' + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(out), dimension(1:m) :: y\n' + 'end subroutine\n' + 'end interface\n' + ) + + +def test_dummy_loops_f95(): + from sympy.tensor import IndexedBase, Idx + i, m = symbols('i m', integer=True, cls=Dummy) + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx(i, m) + expected = ( + 'subroutine test_dummies(m_%(mcount)i, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m_%(mcount)i\n' + 'REAL*8, intent(in), dimension(1:m_%(mcount)i) :: x\n' + 'REAL*8, intent(out), dimension(1:m_%(mcount)i) :: y\n' + 'INTEGER*4 :: i_%(icount)i\n' + 'do i_%(icount)i = 1, m_%(mcount)i\n' + ' y(i_%(icount)i) = x(i_%(icount)i)\n' + 'end do\n' + 'end subroutine\n' + ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} + r = make_routine('test_dummies', Eq(y[i], x[i])) + c = FCodeGen() + code = get_string(c.dump_f95, [r]) + assert code == expected + + +def test_loops_InOut(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + + i, j, n, m = symbols('i,j,n,m', integer=True) + A, x, y = symbols('A,x,y') + A = IndexedBase(A)[Idx(i, m), Idx(j, n)] + x = IndexedBase(x)[Idx(j, n)] + y = IndexedBase(y)[Idx(i, m)] + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y, y + A*x)), "F95", "file", header=False, empty=False) + + assert f1 == 'file.f90' + expected = ( + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(inout), dimension(1:m) :: y\n' + 'INTEGER*4 :: i\n' + 'INTEGER*4 :: j\n' + 'do i = 1, m\n' + ' do j = 1, n\n' + ' y(i) = %(rhs)s + y(i)\n' + ' end do\n' + 'end do\n' + 'end subroutine\n' + ) + + assert (code == expected % {'rhs': 'A(i, j)*x(j)'} or + code == expected % {'rhs': 'x(j)*A(i, j)'}) + assert f2 == 'file.h' + assert interface == ( + 'interface\n' + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(inout), dimension(1:m) :: y\n' + 'end subroutine\n' + 'end interface\n' + ) + + +def test_partial_loops_f(): + # check that loop boundaries are determined by Idx, and array strides + # determined by shape of IndexedBase object. + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m, o, p = symbols('n m o p', integer=True) + A = IndexedBase('A', shape=(m, p)) + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', (o, m - 5)) # Note: bounds are inclusive + j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1) + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) + + expected = ( + 'subroutine matrix_vector(A, m, n, o, p, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'INTEGER*4, intent(in) :: o\n' + 'INTEGER*4, intent(in) :: p\n' + 'REAL*8, intent(in), dimension(1:m, 1:p) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(out), dimension(1:%(iup-ilow)s) :: y\n' + 'INTEGER*4 :: i\n' + 'INTEGER*4 :: j\n' + 'do i = %(ilow)s, %(iup)s\n' + ' y(i) = 0\n' + 'end do\n' + 'do i = %(ilow)s, %(iup)s\n' + ' do j = 1, n\n' + ' y(i) = %(rhs)s + y(i)\n' + ' end do\n' + 'end do\n' + 'end subroutine\n' + ) % { + 'rhs': '%(rhs)s', + 'iup': str(m - 4), + 'ilow': str(1 + o), + 'iup-ilow': str(m - 4 - o) + } + + assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ + code == expected % {'rhs': 'x(j)*A(i, j)'} + + +def test_output_arg_f(): + from sympy.core.relational import Equality + from sympy.functions.elementary.trigonometric import (cos, sin) + x, y, z = symbols("x,y,z") + r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) + c = FCodeGen() + result = c.write([r], "test", header=False, empty=False) + assert result[0][0] == "test.f90" + assert result[0][1] == ( + 'REAL*8 function foo(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(out) :: y\n' + 'y = sin(x)\n' + 'foo = cos(x)\n' + 'end function\n' + ) + + +def test_inline_function(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m = symbols('n m', integer=True) + A, x, y = map(IndexedBase, 'Axy') + i = Idx('i', m) + p = FCodeGen() + func = implemented_function('func', Lambda(n, n*(n + 1))) + routine = make_routine('test_inline', Eq(y[i], func(x[i]))) + code = get_string(p.dump_f95, [routine]) + expected = ( + 'subroutine test_inline(m, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'REAL*8, intent(in), dimension(1:m) :: x\n' + 'REAL*8, intent(out), dimension(1:m) :: y\n' + 'INTEGER*4 :: i\n' + 'do i = 1, m\n' + ' y(i) = %s*%s\n' + 'end do\n' + 'end subroutine\n' + ) + args = ('x(i)', '(x(i) + 1)') + assert code == expected % args or\ + code == expected % args[::-1] + + +def test_f_code_call_signature_wrap(): + # Issue #7934 + x = symbols('x:20') + expr = 0 + for sym in x: + expr += sym + routine = make_routine("test", expr) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = """\ +REAL*8 function test(x0, x1, x10, x11, x12, x13, x14, x15, x16, x17, x18, & + x19, x2, x3, x4, x5, x6, x7, x8, x9) +implicit none +REAL*8, intent(in) :: x0 +REAL*8, intent(in) :: x1 +REAL*8, intent(in) :: x10 +REAL*8, intent(in) :: x11 +REAL*8, intent(in) :: x12 +REAL*8, intent(in) :: x13 +REAL*8, intent(in) :: x14 +REAL*8, intent(in) :: x15 +REAL*8, intent(in) :: x16 +REAL*8, intent(in) :: x17 +REAL*8, intent(in) :: x18 +REAL*8, intent(in) :: x19 +REAL*8, intent(in) :: x2 +REAL*8, intent(in) :: x3 +REAL*8, intent(in) :: x4 +REAL*8, intent(in) :: x5 +REAL*8, intent(in) :: x6 +REAL*8, intent(in) :: x7 +REAL*8, intent(in) :: x8 +REAL*8, intent(in) :: x9 +test = x0 + x1 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + & + x19 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 +end function +""" + assert source == expected + + +def test_check_case(): + x, X = symbols('x,X') + raises(CodeGenError, lambda: codegen(('test', x*X), 'f95', 'prefix')) + + +def test_check_case_false_positive(): + # The upper case/lower case exception should not be triggered by SymPy + # objects that differ only because of assumptions. (It may be useful to + # have a check for that as well, but here we only want to test against + # false positives with respect to case checking.) + x1 = symbols('x') + x2 = symbols('x', my_assumption=True) + try: + codegen(('test', x1*x2), 'f95', 'prefix') + except CodeGenError as e: + if e.args[0].startswith("Fortran ignores case."): + raise AssertionError("This exception should not be raised!") + + +def test_c_fortran_omit_routine_name(): + x, y = symbols("x,y") + name_expr = [("foo", 2*x)] + result = codegen(name_expr, "F95", header=False, empty=False) + expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) + assert result[0][1] == expresult[0][1] + + name_expr = ("foo", x*y) + result = codegen(name_expr, "F95", header=False, empty=False) + expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) + assert result[0][1] == expresult[0][1] + + name_expr = ("foo", Matrix([[x, y], [x+y, x-y]])) + result = codegen(name_expr, "C89", header=False, empty=False) + expresult = codegen(name_expr, "C89", "foo", header=False, empty=False) + assert result[0][1] == expresult[0][1] + + +def test_fcode_matrix_output(): + x, y, z = symbols('x,y,z') + e1 = x + y + e2 = Matrix([[x, y], [z, 16]]) + name_expr = ("test", (e1, e2)) + result = codegen(name_expr, "f95", "test", header=False, empty=False) + source = result[0][1] + expected = ( + "REAL*8 function test(x, y, z, out_%(hash)s)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "REAL*8, intent(out), dimension(1:2, 1:2) :: out_%(hash)s\n" + "out_%(hash)s(1, 1) = x\n" + "out_%(hash)s(2, 1) = z\n" + "out_%(hash)s(1, 2) = y\n" + "out_%(hash)s(2, 2) = 16\n" + "test = x + y\n" + "end function\n" + ) + # look for the magic number + a = source.splitlines()[5] + b = a.split('_') + out = b[1] + expected = expected % {'hash': out} + assert source == expected + + +def test_fcode_results_named_ordered(): + x, y, z = symbols('x,y,z') + B, C = symbols('B,C') + A = MatrixSymbol('A', 1, 3) + expr1 = Equality(A, Matrix([[1, 2, x]])) + expr2 = Equality(C, (x + y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result = codegen(name_expr, "f95", "test", header=False, empty=False, + argument_sequence=(x, z, y, C, A, B)) + source = result[0][1] + expected = ( + "subroutine test(x, z, y, C, A, B)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: z\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(out) :: C\n" + "REAL*8, intent(out) :: B\n" + "REAL*8, intent(out), dimension(1:1, 1:3) :: A\n" + "C = z*(x + y)\n" + "A(1, 1) = 1\n" + "A(1, 2) = 2\n" + "A(1, 3) = x\n" + "B = 2*x\n" + "end subroutine\n" + ) + assert source == expected + + +def test_fcode_matrixsymbol_slice(): + A = MatrixSymbol('A', 2, 3) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 1, 3) + D = MatrixSymbol('D', 2, 1) + name_expr = ("test", [Equality(B, A[0, :]), + Equality(C, A[1, :]), + Equality(D, A[:, 2])]) + result = codegen(name_expr, "f95", "test", header=False, empty=False) + source = result[0][1] + expected = ( + "subroutine test(A, B, C, D)\n" + "implicit none\n" + "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" + "REAL*8, intent(out), dimension(1:1, 1:3) :: B\n" + "REAL*8, intent(out), dimension(1:1, 1:3) :: C\n" + "REAL*8, intent(out), dimension(1:2, 1:1) :: D\n" + "B(1, 1) = A(1, 1)\n" + "B(1, 2) = A(1, 2)\n" + "B(1, 3) = A(1, 3)\n" + "C(1, 1) = A(2, 1)\n" + "C(1, 2) = A(2, 2)\n" + "C(1, 3) = A(2, 3)\n" + "D(1, 1) = A(1, 3)\n" + "D(2, 1) = A(2, 3)\n" + "end subroutine\n" + ) + assert source == expected + + +def test_fcode_matrixsymbol_slice_autoname(): + # see issue #8093 + A = MatrixSymbol('A', 2, 3) + name_expr = ("test", A[:, 1]) + result = codegen(name_expr, "f95", "test", header=False, empty=False) + source = result[0][1] + expected = ( + "subroutine test(A, out_%(hash)s)\n" + "implicit none\n" + "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" + "REAL*8, intent(out), dimension(1:2, 1:1) :: out_%(hash)s\n" + "out_%(hash)s(1, 1) = A(1, 2)\n" + "out_%(hash)s(2, 1) = A(2, 2)\n" + "end subroutine\n" + ) + # look for the magic number + a = source.splitlines()[3] + b = a.split('_') + out = b[1] + expected = expected % {'hash': out} + assert source == expected + + +def test_global_vars(): + x, y, z, t = symbols("x y z t") + result = codegen(('f', x*y), "F95", header=False, empty=False, + global_vars=(y,)) + source = result[0][1] + expected = ( + "REAL*8 function f(x)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "f = x*y\n" + "end function\n" + ) + assert source == expected + + expected = ( + '#include "f.h"\n' + '#include \n' + 'double f(double x, double y) {\n' + ' double f_result;\n' + ' f_result = x*y + z;\n' + ' return f_result;\n' + '}\n' + ) + result = codegen(('f', x*y+z), "C", header=False, empty=False, + global_vars=(z, t)) + source = result[0][1] + assert source == expected + +def test_custom_codegen(): + from sympy.printing.c import C99CodePrinter + from sympy.functions.elementary.exponential import exp + + printer = C99CodePrinter(settings={'user_functions': {'exp': 'fastexp'}}) + + x, y = symbols('x y') + expr = exp(x + y) + + # replace math.h with a different header + gen = C99CodeGen(printer=printer, + preprocessor_statements=['#include "fastexp.h"']) + + expected = ( + '#include "expr.h"\n' + '#include "fastexp.h"\n' + 'double expr(double x, double y) {\n' + ' double expr_result;\n' + ' expr_result = fastexp(x + y);\n' + ' return expr_result;\n' + '}\n' + ) + + result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) + source = result[0][1] + assert source == expected + + # use both math.h and an external header + gen = C99CodeGen(printer=printer) + gen.preprocessor_statements.append('#include "fastexp.h"') + + expected = ( + '#include "expr.h"\n' + '#include \n' + '#include "fastexp.h"\n' + 'double expr(double x, double y) {\n' + ' double expr_result;\n' + ' expr_result = fastexp(x + y);\n' + ' return expr_result;\n' + '}\n' + ) + + result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) + source = result[0][1] + assert source == expected + +def test_c_with_printer(): + #issue 13586 + from sympy.printing.c import C99CodePrinter + class CustomPrinter(C99CodePrinter): + def _print_Pow(self, expr): + return "fastpow({}, {})".format(self._print(expr.base), + self._print(expr.exp)) + + x = symbols('x') + expr = x**3 + expected =[ + ("file.c", + "#include \"file.h\"\n" + "#include \n" + "double test(double x) {\n" + " double test_result;\n" + " test_result = fastpow(x, 3);\n" + " return test_result;\n" + "}\n"), + ("file.h", + "#ifndef PROJECT__FILE__H\n" + "#define PROJECT__FILE__H\n" + "double test(double x);\n" + "#endif\n") + ] + result = codegen(("test", expr), "C","file", header=False, empty=False, printer = CustomPrinter()) + assert result == expected + + +def test_fcode_complex(): + import sympy.utilities.codegen + sympy.utilities.codegen.COMPLEX_ALLOWED = True + x = Symbol('x', real=True) + y = Symbol('y',real=True) + result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) + source = (result[0][1]) + expected = ( + "REAL*8 function test(x, y)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "test = x + y\n" + "end function\n") + assert source == expected + x = Symbol('x') + y = Symbol('y',real=True) + result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) + source = (result[0][1]) + expected = ( + "COMPLEX*16 function test(x, y)\n" + "implicit none\n" + "COMPLEX*16, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "test = x + y\n" + "end function\n" + ) + assert source==expected + sympy.utilities.codegen.COMPLEX_ALLOWED = False diff --git a/shared/package-files/3c/3cc3881603ca45bdad5e2dd4037835d8b1be5403d985ea2592eeab81e1994b02/putty-screen b/shared/package-files/3c/3cc3881603ca45bdad5e2dd4037835d8b1be5403d985ea2592eeab81e1994b02/putty-screen new file mode 100644 index 0000000000000000000000000000000000000000..d6510ae614b11a38ee97f3adfe3f4ea34da37743 Binary files /dev/null and b/shared/package-files/3c/3cc3881603ca45bdad5e2dd4037835d8b1be5403d985ea2592eeab81e1994b02/putty-screen differ diff --git a/shared/package-files/3c/3cc5c46bba39c6ac27b01848d871a1dea20d0f5a930e2fa6af485fab41a8be4c/scrutineer.py b/shared/package-files/3c/3cc5c46bba39c6ac27b01848d871a1dea20d0f5a930e2fa6af485fab41a8be4c/scrutineer.py new file mode 100644 index 0000000000000000000000000000000000000000..39352844b4d91f67c2d846aa54660ddf7889003f --- /dev/null +++ b/shared/package-files/3c/3cc5c46bba39c6ac27b01848d871a1dea20d0f5a930e2fa6af485fab41a8be4c/scrutineer.py @@ -0,0 +1,241 @@ +# 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 functools +import os +import subprocess +import sys +import types +from collections import defaultdict +from functools import lru_cache, reduce +from os import sep +from pathlib import Path +from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple + +from hypothesis._settings import Phase, Verbosity +from hypothesis.internal.escalation import is_hypothesis_file + +if TYPE_CHECKING: + from typing import TypeAlias +else: + TypeAlias = object + +Location: TypeAlias = Tuple[str, int] +Branch: TypeAlias = Tuple[Optional[Location], Location] +Trace: TypeAlias = Set[Branch] + + +@lru_cache(maxsize=None) +def should_trace_file(fname): + # fname.startswith("<") indicates runtime code-generation via compile, + # e.g. compile("def ...", "", "exec") in e.g. attrs methods. + return not (is_hypothesis_file(fname) or fname.startswith("<")) + + +# where possible, we'll use 3.12's new sys.monitoring module for low-overhead +# coverage instrumentation; on older python versions we'll use sys.settrace. +# tool_id = 1 is designated for coverage, but we intentionally choose a +# non-reserved tool id so we can co-exist with coverage tools. +MONITORING_TOOL_ID = 3 +if sys.version_info[:2] >= (3, 12): + MONITORING_EVENTS = {sys.monitoring.events.LINE: "trace_line"} + + +class Tracer: + """A super-simple branch coverage tracer.""" + + __slots__ = ("branches", "_previous_location") + + def __init__(self): + self.branches: Trace = set() + self._previous_location = None + + def trace(self, frame, event, arg): + if event == "call": + return self.trace + elif event == "line": + # manual inlining of self.trace_line for performance. + fname = frame.f_code.co_filename + if should_trace_file(fname): + current_location = (fname, frame.f_lineno) + self.branches.add((self._previous_location, current_location)) + self._previous_location = current_location + + def trace_line(self, code: types.CodeType, line_number: int) -> None: + fname = code.co_filename + if should_trace_file(fname): + current_location = (fname, line_number) + self.branches.add((self._previous_location, current_location)) + self._previous_location = current_location + + def __enter__(self): + if sys.version_info[:2] < (3, 12): + assert sys.gettrace() is None # caller checks in core.py + sys.settrace(self.trace) + return self + + sys.monitoring.use_tool_id(MONITORING_TOOL_ID, "scrutineer") + for event, callback_name in MONITORING_EVENTS.items(): + sys.monitoring.set_events(MONITORING_TOOL_ID, event) + callback = getattr(self, callback_name) + sys.monitoring.register_callback(MONITORING_TOOL_ID, event, callback) + + return self + + def __exit__(self, *args, **kwargs): + if sys.version_info[:2] < (3, 12): + sys.settrace(None) + return + + sys.monitoring.free_tool_id(MONITORING_TOOL_ID) + for event in MONITORING_EVENTS: + sys.monitoring.register_callback(MONITORING_TOOL_ID, event, None) + + +UNHELPFUL_LOCATIONS = ( + # There's a branch which is only taken when an exception is active while exiting + # a contextmanager; this is probably after the fault has been triggered. + # Similar reasoning applies to a few other standard-library modules: even + # if the fault was later, these still aren't useful locations to report! + f"{sep}contextlib.py", + f"{sep}inspect.py", + f"{sep}re.py", + f"{sep}re{sep}__init__.py", # refactored in Python 3.11 + f"{sep}warnings.py", + # Quite rarely, the first AFNP line is in Pytest's internals. + f"{sep}_pytest{sep}assertion{sep}__init__.py", + f"{sep}_pytest{sep}assertion{sep}rewrite.py", + f"{sep}_pytest{sep}_io{sep}saferepr.py", + f"{sep}pluggy{sep}_result.py", +) + + +def get_explaining_locations(traces): + # Traces is a dict[interesting_origin | None, set[frozenset[tuple[str, int]]]] + # Each trace in the set might later become a Counter instead of frozenset. + if not traces: + return {} + + unions = {origin: set().union(*values) for origin, values in traces.items()} + seen_passing = {None}.union(*unions.pop(None, set())) + + always_failing_never_passing = { + origin: reduce(set.intersection, [set().union(*v) for v in values]) + - seen_passing + for origin, values in traces.items() + if origin is not None + } + + # Build the observed parts of the control-flow graph for each origin + cf_graphs = {origin: defaultdict(set) for origin in unions} + for origin, seen_arcs in unions.items(): + for src, dst in seen_arcs: + cf_graphs[origin][src].add(dst) + assert cf_graphs[origin][None], "Expected start node with >=1 successor" + + # For each origin, our explanation is the always_failing_never_passing lines + # which are reachable from the start node (None) without passing through another + # AFNP line. So here's a whatever-first search with early stopping: + explanations = defaultdict(set) + for origin in unions: + queue = {None} + seen = set() + while queue: + assert queue.isdisjoint(seen), f"Intersection: {queue & seen}" + src = queue.pop() + seen.add(src) + if src in always_failing_never_passing[origin]: + explanations[origin].add(src) + else: + queue.update(cf_graphs[origin][src] - seen) + + # The last step is to filter out explanations that we know would be uninformative. + # When this is the first AFNP location, we conclude that Scrutineer missed the + # real divergence (earlier in the trace) and drop that unhelpful explanation. + return { + origin: {loc for loc in afnp_locs if not loc[0].endswith(UNHELPFUL_LOCATIONS)} + for origin, afnp_locs in explanations.items() + } + + +LIB_DIR = str(Path(sys.executable).parent / "lib") +EXPLANATION_STUB = ( + "Explanation:", + " These lines were always and only run by failing examples:", +) + + +def make_report(explanations, cap_lines_at=5): + report = defaultdict(list) + for origin, locations in explanations.items(): + report_lines = [f" {fname}:{lineno}" for fname, lineno in locations] + report_lines.sort(key=lambda line: (line.startswith(LIB_DIR), line)) + if len(report_lines) > cap_lines_at + 1: + msg = " (and {} more with settings.verbosity >= verbose)" + report_lines[cap_lines_at:] = [msg.format(len(report_lines[cap_lines_at:]))] + if report_lines: # We might have filtered out every location as uninformative. + report[origin] = list(EXPLANATION_STUB) + report_lines + return report + + +def explanatory_lines(traces, settings): + if Phase.explain in settings.phases and sys.gettrace() and not traces: + return defaultdict(list) + # Return human-readable report lines summarising the traces + explanations = get_explaining_locations(traces) + max_lines = 5 if settings.verbosity <= Verbosity.normal else float("inf") + return make_report(explanations, cap_lines_at=max_lines) + + +# beware the code below; we're using some heuristics to make a nicer report... + + +@functools.lru_cache +def _get_git_repo_root() -> Path: + try: + where = subprocess.run( + ["git", "rev-parse", "--show-toplevel"], + check=True, + timeout=10, + capture_output=True, + text=True, + encoding="utf-8", + ).stdout.strip() + except Exception: # pragma: no cover + return Path().absolute().parents[-1] + else: + return Path(where) + + +if sys.version_info[:2] <= (3, 8): + + def is_relative_to(self, other): + return other == self or other in self.parents + +else: + is_relative_to = Path.is_relative_to + + +def tractable_coverage_report(trace: Trace) -> Dict[str, List[int]]: + """Report a simple coverage map which is (probably most) of the user's code.""" + coverage: dict = {} + t = dict(trace) + for file, line in set(t.keys()).union(t.values()) - {None}: # type: ignore + # On Python <= 3.11, we can use coverage.py xor Hypothesis' tracer, + # so the trace will be empty and this line never run under coverage. + coverage.setdefault(file, set()).add(line) # pragma: no cover + stdlib_fragment = f"{os.sep}lib{os.sep}python3.{sys.version_info.minor}{os.sep}" + return { + k: sorted(v) + for k, v in coverage.items() + if stdlib_fragment not in k + and is_relative_to(p := Path(k), _get_git_repo_root()) + and "site-packages" not in p.parts + } diff --git a/shared/package-files/3c/3cceee07a67cba524952cf90f47925ec98bf916ad065bfcf26bfbc6034a2799c/is_complex_compositeimplicitautograd_dispatch.h b/shared/package-files/3c/3cceee07a67cba524952cf90f47925ec98bf916ad065bfcf26bfbc6034a2799c/is_complex_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..97d19a2aed49393d57d11d14f60d5be91f139293 --- /dev/null +++ b/shared/package-files/3c/3cceee07a67cba524952cf90f47925ec98bf916ad065bfcf26bfbc6034a2799c/is_complex_compositeimplicitautograd_dispatch.h @@ -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_complex(const at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/3c/3cd46afa9da7c604fe7f30b9e0ad9d7a98bc75d85dc7a43ce86f2aa548877946/calculus.py b/shared/package-files/3c/3cd46afa9da7c604fe7f30b9e0ad9d7a98bc75d85dc7a43ce86f2aa548877946/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..7fae2a7a9a29898241ed41810331b480ff70798f --- /dev/null +++ b/shared/package-files/3c/3cd46afa9da7c604fe7f30b9e0ad9d7a98bc75d85dc7a43ce86f2aa548877946/calculus.py @@ -0,0 +1,531 @@ +from ..libmp.backend import xrange + +# TODO: should use diagonalization-based algorithms + +class MatrixCalculusMethods(object): + + def _exp_pade(ctx, a): + """ + Exponential of a matrix using Pade approximants. + + See G. H. Golub, C. F. van Loan 'Matrix Computations', + third Ed., page 572 + + TODO: + - find a good estimate for q + - reduce the number of matrix multiplications to improve + performance + """ + def eps_pade(p): + return ctx.mpf(2)**(3-2*p) * \ + ctx.factorial(p)**2/(ctx.factorial(2*p)**2 * (2*p + 1)) + q = 4 + extraq = 8 + while 1: + if eps_pade(q) < ctx.eps: + break + q += 1 + q += extraq + j = int(max(1, ctx.mag(ctx.mnorm(a,'inf')))) + extra = q + prec = ctx.prec + ctx.dps += extra + 3 + try: + a = a/2**j + na = a.rows + den = ctx.eye(na) + num = ctx.eye(na) + x = ctx.eye(na) + c = ctx.mpf(1) + for k in range(1, q+1): + c *= ctx.mpf(q - k + 1)/((2*q - k + 1) * k) + x = a*x + cx = c*x + num += cx + den += (-1)**k * cx + f = ctx.lu_solve_mat(den, num) + for k in range(j): + f = f*f + finally: + ctx.prec = prec + return f*1 + + def expm(ctx, A, method='taylor'): + r""" + Computes the matrix exponential of a square matrix `A`, which is defined + by the power series + + .. math :: + + \exp(A) = I + A + \frac{A^2}{2!} + \frac{A^3}{3!} + \ldots + + With method='taylor', the matrix exponential is computed + using the Taylor series. With method='pade', Pade approximants + are used instead. + + **Examples** + + Basic examples:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> expm(zeros(3)) + [1.0 0.0 0.0] + [0.0 1.0 0.0] + [0.0 0.0 1.0] + >>> expm(eye(3)) + [2.71828182845905 0.0 0.0] + [ 0.0 2.71828182845905 0.0] + [ 0.0 0.0 2.71828182845905] + >>> expm([[1,1,0],[1,0,1],[0,1,0]]) + [ 3.86814500615414 2.26812870852145 0.841130841230196] + [ 2.26812870852145 2.44114713886289 1.42699786729125] + [0.841130841230196 1.42699786729125 1.6000162976327] + >>> expm([[1,1,0],[1,0,1],[0,1,0]], method='pade') + [ 3.86814500615414 2.26812870852145 0.841130841230196] + [ 2.26812870852145 2.44114713886289 1.42699786729125] + [0.841130841230196 1.42699786729125 1.6000162976327] + >>> expm([[1+j, 0], [1+j,1]]) + [(1.46869393991589 + 2.28735528717884j) 0.0] + [ (1.03776739863568 + 3.536943175722j) (2.71828182845905 + 0.0j)] + + Matrices with large entries are allowed:: + + >>> expm(matrix([[1,2],[2,3]])**25) + [5.65024064048415e+2050488462815550 9.14228140091932e+2050488462815550] + [9.14228140091932e+2050488462815550 1.47925220414035e+2050488462815551] + + The identity `\exp(A+B) = \exp(A) \exp(B)` does not hold for + noncommuting matrices:: + + >>> A = hilbert(3) + >>> B = A + eye(3) + >>> chop(mnorm(A*B - B*A)) + 0.0 + >>> chop(mnorm(expm(A+B) - expm(A)*expm(B))) + 0.0 + >>> B = A + ones(3) + >>> mnorm(A*B - B*A) + 1.8 + >>> mnorm(expm(A+B) - expm(A)*expm(B)) + 42.0927851137247 + + """ + if method == 'pade': + prec = ctx.prec + try: + A = ctx.matrix(A) + ctx.prec += 2*A.rows + res = ctx._exp_pade(A) + finally: + ctx.prec = prec + return res + A = ctx.matrix(A) + prec = ctx.prec + j = int(max(1, ctx.mag(ctx.mnorm(A,'inf')))) + j += int(0.5*prec**0.5) + try: + ctx.prec += 10 + 2*j + tol = +ctx.eps + A = A/2**j + T = A + Y = A**0 + A + k = 2 + while 1: + T *= A * (1/ctx.mpf(k)) + if ctx.mnorm(T, 'inf') < tol: + break + Y += T + k += 1 + for k in xrange(j): + Y = Y*Y + finally: + ctx.prec = prec + Y *= 1 + return Y + + def cosm(ctx, A): + r""" + Gives the cosine of a square matrix `A`, defined in analogy + with the matrix exponential. + + Examples:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> X = eye(3) + >>> cosm(X) + [0.54030230586814 0.0 0.0] + [ 0.0 0.54030230586814 0.0] + [ 0.0 0.0 0.54030230586814] + >>> X = hilbert(3) + >>> cosm(X) + [ 0.424403834569555 -0.316643413047167 -0.221474945949293] + [-0.316643413047167 0.820646708837824 -0.127183694770039] + [-0.221474945949293 -0.127183694770039 0.909236687217541] + >>> X = matrix([[1+j,-2],[0,-j]]) + >>> cosm(X) + [(0.833730025131149 - 0.988897705762865j) (1.07485840848393 - 0.17192140544213j)] + [ 0.0 (1.54308063481524 + 0.0j)] + """ + B = 0.5 * (ctx.expm(A*ctx.j) + ctx.expm(A*(-ctx.j))) + if not sum(A.apply(ctx.im).apply(abs)): + B = B.apply(ctx.re) + return B + + def sinm(ctx, A): + r""" + Gives the sine of a square matrix `A`, defined in analogy + with the matrix exponential. + + Examples:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> X = eye(3) + >>> sinm(X) + [0.841470984807897 0.0 0.0] + [ 0.0 0.841470984807897 0.0] + [ 0.0 0.0 0.841470984807897] + >>> X = hilbert(3) + >>> sinm(X) + [0.711608512150994 0.339783913247439 0.220742837314741] + [0.339783913247439 0.244113865695532 0.187231271174372] + [0.220742837314741 0.187231271174372 0.155816730769635] + >>> X = matrix([[1+j,-2],[0,-j]]) + >>> sinm(X) + [(1.29845758141598 + 0.634963914784736j) (-1.96751511930922 + 0.314700021761367j)] + [ 0.0 (0.0 - 1.1752011936438j)] + """ + B = (-0.5j) * (ctx.expm(A*ctx.j) - ctx.expm(A*(-ctx.j))) + if not sum(A.apply(ctx.im).apply(abs)): + B = B.apply(ctx.re) + return B + + def _sqrtm_rot(ctx, A, _may_rotate): + # If the iteration fails to converge, cheat by performing + # a rotation by a complex number + u = ctx.j**0.3 + return ctx.sqrtm(u*A, _may_rotate) / ctx.sqrt(u) + + def sqrtm(ctx, A, _may_rotate=2): + r""" + Computes a square root of the square matrix `A`, i.e. returns + a matrix `B = A^{1/2}` such that `B^2 = A`. The square root + of a matrix, if it exists, is not unique. + + **Examples** + + Square roots of some simple matrices:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> sqrtm([[1,0], [0,1]]) + [1.0 0.0] + [0.0 1.0] + >>> sqrtm([[0,0], [0,0]]) + [0.0 0.0] + [0.0 0.0] + >>> sqrtm([[2,0],[0,1]]) + [1.4142135623731 0.0] + [ 0.0 1.0] + >>> sqrtm([[1,1],[1,0]]) + [ (0.920442065259926 - 0.21728689675164j) (0.568864481005783 + 0.351577584254143j)] + [(0.568864481005783 + 0.351577584254143j) (0.351577584254143 - 0.568864481005783j)] + >>> sqrtm([[1,0],[0,1]]) + [1.0 0.0] + [0.0 1.0] + >>> sqrtm([[-1,0],[0,1]]) + [(0.0 - 1.0j) 0.0] + [ 0.0 (1.0 + 0.0j)] + >>> sqrtm([[j,0],[0,j]]) + [(0.707106781186547 + 0.707106781186547j) 0.0] + [ 0.0 (0.707106781186547 + 0.707106781186547j)] + + A square root of a rotation matrix, giving the corresponding + half-angle rotation matrix:: + + >>> t1 = 0.75 + >>> t2 = t1 * 0.5 + >>> A1 = matrix([[cos(t1), -sin(t1)], [sin(t1), cos(t1)]]) + >>> A2 = matrix([[cos(t2), -sin(t2)], [sin(t2), cos(t2)]]) + >>> sqrtm(A1) + [0.930507621912314 -0.366272529086048] + [0.366272529086048 0.930507621912314] + >>> A2 + [0.930507621912314 -0.366272529086048] + [0.366272529086048 0.930507621912314] + + The identity `(A^2)^{1/2} = A` does not necessarily hold:: + + >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]]) + >>> sqrtm(A**2) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> sqrtm(A)**2 + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> A = matrix([[-4,1,4],[7,-8,9],[10,2,11]]) + >>> sqrtm(A**2) + [ 7.43715112194995 -0.324127569985474 1.8481718827526] + [-0.251549715716942 9.32699765900402 2.48221180985147] + [ 4.11609388833616 0.775751877098258 13.017955697342] + >>> chop(sqrtm(A)**2) + [-4.0 1.0 4.0] + [ 7.0 -8.0 9.0] + [10.0 2.0 11.0] + + For some matrices, a square root does not exist:: + + >>> sqrtm([[0,1], [0,0]]) + Traceback (most recent call last): + ... + ZeroDivisionError: matrix is numerically singular + + Two examples from the documentation for Matlab's ``sqrtm``:: + + >>> mp.dps = 15; mp.pretty = True + >>> sqrtm([[7,10],[15,22]]) + [1.56669890360128 1.74077655955698] + [2.61116483933547 4.17786374293675] + >>> + >>> X = matrix(\ + ... [[5,-4,1,0,0], + ... [-4,6,-4,1,0], + ... [1,-4,6,-4,1], + ... [0,1,-4,6,-4], + ... [0,0,1,-4,5]]) + >>> Y = matrix(\ + ... [[2,-1,-0,-0,-0], + ... [-1,2,-1,0,-0], + ... [0,-1,2,-1,0], + ... [-0,0,-1,2,-1], + ... [-0,-0,-0,-1,2]]) + >>> mnorm(sqrtm(X) - Y) + 4.53155328326114e-19 + + """ + A = ctx.matrix(A) + # Trivial + if A*0 == A: + return A + prec = ctx.prec + if _may_rotate: + d = ctx.det(A) + if abs(ctx.im(d)) < 16*ctx.eps and ctx.re(d) < 0: + return ctx._sqrtm_rot(A, _may_rotate-1) + try: + ctx.prec += 10 + tol = ctx.eps * 128 + Y = A + Z = I = A**0 + k = 0 + # Denman-Beavers iteration + while 1: + Yprev = Y + try: + Y, Z = 0.5*(Y+ctx.inverse(Z)), 0.5*(Z+ctx.inverse(Y)) + except ZeroDivisionError: + if _may_rotate: + Y = ctx._sqrtm_rot(A, _may_rotate-1) + break + else: + raise + mag1 = ctx.mnorm(Y-Yprev, 'inf') + mag2 = ctx.mnorm(Y, 'inf') + if mag1 <= mag2*tol: + break + if _may_rotate and k > 6 and not mag1 < mag2 * 0.001: + return ctx._sqrtm_rot(A, _may_rotate-1) + k += 1 + if k > ctx.prec: + raise ctx.NoConvergence + finally: + ctx.prec = prec + Y *= 1 + return Y + + def logm(ctx, A): + r""" + Computes a logarithm of the square matrix `A`, i.e. returns + a matrix `B = \log(A)` such that `\exp(B) = A`. The logarithm + of a matrix, if it exists, is not unique. + + **Examples** + + Logarithms of some simple matrices:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> X = eye(3) + >>> logm(X) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + >>> logm(2*X) + [0.693147180559945 0.0 0.0] + [ 0.0 0.693147180559945 0.0] + [ 0.0 0.0 0.693147180559945] + >>> logm(expm(X)) + [1.0 0.0 0.0] + [0.0 1.0 0.0] + [0.0 0.0 1.0] + + A logarithm of a complex matrix:: + + >>> X = matrix([[2+j, 1, 3], [1-j, 1-2*j, 1], [-4, -5, j]]) + >>> B = logm(X) + >>> nprint(B) + [ (0.808757 + 0.107759j) (2.20752 + 0.202762j) (1.07376 - 0.773874j)] + [ (0.905709 - 0.107795j) (0.0287395 - 0.824993j) (0.111619 + 0.514272j)] + [(-0.930151 + 0.399512j) (-2.06266 - 0.674397j) (0.791552 + 0.519839j)] + >>> chop(expm(B)) + [(2.0 + 1.0j) 1.0 3.0] + [(1.0 - 1.0j) (1.0 - 2.0j) 1.0] + [ -4.0 -5.0 (0.0 + 1.0j)] + + A matrix `X` close to the identity matrix, for which + `\log(\exp(X)) = \exp(\log(X)) = X` holds:: + + >>> X = eye(3) + hilbert(3)/4 + >>> X + [ 1.25 0.125 0.0833333333333333] + [ 0.125 1.08333333333333 0.0625] + [0.0833333333333333 0.0625 1.05] + >>> logm(expm(X)) + [ 1.25 0.125 0.0833333333333333] + [ 0.125 1.08333333333333 0.0625] + [0.0833333333333333 0.0625 1.05] + >>> expm(logm(X)) + [ 1.25 0.125 0.0833333333333333] + [ 0.125 1.08333333333333 0.0625] + [0.0833333333333333 0.0625 1.05] + + A logarithm of a rotation matrix, giving back the angle of + the rotation:: + + >>> t = 3.7 + >>> A = matrix([[cos(t),sin(t)],[-sin(t),cos(t)]]) + >>> chop(logm(A)) + [ 0.0 -2.58318530717959] + [2.58318530717959 0.0] + >>> (2*pi-t) + 2.58318530717959 + + For some matrices, a logarithm does not exist:: + + >>> logm([[1,0], [0,0]]) + Traceback (most recent call last): + ... + ZeroDivisionError: matrix is numerically singular + + Logarithm of a matrix with large entries:: + + >>> logm(hilbert(3) * 10**20).apply(re) + [ 45.5597513593433 1.27721006042799 0.317662687717978] + [ 1.27721006042799 42.5222778973542 2.24003708791604] + [0.317662687717978 2.24003708791604 42.395212822267] + + """ + A = ctx.matrix(A) + prec = ctx.prec + try: + ctx.prec += 10 + tol = ctx.eps * 128 + I = A**0 + B = A + n = 0 + while 1: + B = ctx.sqrtm(B) + n += 1 + if ctx.mnorm(B-I, 'inf') < 0.125: + break + T = X = B-I + L = X*0 + k = 1 + while 1: + if k & 1: + L += T / k + else: + L -= T / k + T *= X + if ctx.mnorm(T, 'inf') < tol: + break + k += 1 + if k > ctx.prec: + raise ctx.NoConvergence + finally: + ctx.prec = prec + L *= 2**n + return L + + def powm(ctx, A, r): + r""" + Computes `A^r = \exp(A \log r)` for a matrix `A` and complex + number `r`. + + **Examples** + + Powers and inverse powers of a matrix:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]]) + >>> powm(A, 2) + [ 63.0 20.0 69.0] + [174.0 89.0 199.0] + [164.0 48.0 179.0] + >>> chop(powm(powm(A, 4), 1/4.)) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> powm(extraprec(20)(powm)(A, -4), -1/4.) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> chop(powm(powm(A, 1+0.5j), 1/(1+0.5j))) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> powm(extraprec(5)(powm)(A, -1.5), -1/(1.5)) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + + A Fibonacci-generating matrix:: + + >>> powm([[1,1],[1,0]], 10) + [89.0 55.0] + [55.0 34.0] + >>> fib(10) + 55.0 + >>> powm([[1,1],[1,0]], 6.5) + [(16.5166626964253 - 0.0121089837381789j) (10.2078589271083 + 0.0195927472575932j)] + [(10.2078589271083 + 0.0195927472575932j) (6.30880376931698 - 0.0317017309957721j)] + >>> (phi**6.5 - (1-phi)**6.5)/sqrt(5) + (10.2078589271083 - 0.0195927472575932j) + >>> powm([[1,1],[1,0]], 6.2) + [ (14.3076953002666 - 0.008222855781077j) (8.81733464837593 + 0.0133048601383712j)] + [(8.81733464837593 + 0.0133048601383712j) (5.49036065189071 - 0.0215277159194482j)] + >>> (phi**6.2 - (1-phi)**6.2)/sqrt(5) + (8.81733464837593 - 0.0133048601383712j) + + """ + A = ctx.matrix(A) + r = ctx.convert(r) + prec = ctx.prec + try: + ctx.prec += 10 + if ctx.isint(r): + v = A ** int(r) + elif ctx.isint(r*2): + y = int(r*2) + v = ctx.sqrtm(A) ** y + else: + v = ctx.expm(r*ctx.logm(A)) + finally: + ctx.prec = prec + v *= 1 + return v diff --git a/shared/package-files/3c/3cd690946c157422fc2baba34629e600b9fd3b6f2d3596f181e94670afba312a/test_compression.py b/shared/package-files/3c/3cd690946c157422fc2baba34629e600b9fd3b6f2d3596f181e94670afba312a/test_compression.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7d34c85c01599707e648c4d9964773d16a13fc --- /dev/null +++ b/shared/package-files/3c/3cd690946c157422fc2baba34629e600b9fd3b6f2d3596f181e94670afba312a/test_compression.py @@ -0,0 +1,130 @@ +from io import ( + BytesIO, + StringIO, +) + +import pytest + +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +def test_compression_roundtrip(compression): + df = pd.DataFrame( + [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + + with tm.ensure_clean() as path: + df.to_json(path, compression=compression) + tm.assert_frame_equal(df, pd.read_json(path, compression=compression)) + + # explicitly ensure file was compressed. + with tm.decompress_file(path, compression) as fh: + result = fh.read().decode("utf8") + data = StringIO(result) + tm.assert_frame_equal(df, pd.read_json(data)) + + +def test_read_zipped_json(datapath): + uncompressed_path = datapath("io", "json", "data", "tsframe_v012.json") + uncompressed_df = pd.read_json(uncompressed_path) + + compressed_path = datapath("io", "json", "data", "tsframe_v012.json.zip") + compressed_df = pd.read_json(compressed_path, compression="zip") + + tm.assert_frame_equal(uncompressed_df, compressed_df) + + +@td.skip_if_not_us_locale +@pytest.mark.single_cpu +def test_with_s3_url(compression, s3_public_bucket, s3so): + # Bucket created in tests/io/conftest.py + df = pd.read_json(StringIO('{"a": [1, 2, 3], "b": [4, 5, 6]}')) + + with tm.ensure_clean() as path: + df.to_json(path, compression=compression) + with open(path, "rb") as f: + s3_public_bucket.put_object(Key="test-1", Body=f) + + roundtripped_df = pd.read_json( + f"s3://{s3_public_bucket.name}/test-1", + compression=compression, + storage_options=s3so, + ) + tm.assert_frame_equal(df, roundtripped_df) + + +def test_lines_with_compression(compression): + with tm.ensure_clean() as path: + df = pd.read_json(StringIO('{"a": [1, 2, 3], "b": [4, 5, 6]}')) + df.to_json(path, orient="records", lines=True, compression=compression) + roundtripped_df = pd.read_json(path, lines=True, compression=compression) + tm.assert_frame_equal(df, roundtripped_df) + + +def test_chunksize_with_compression(compression): + with tm.ensure_clean() as path: + df = pd.read_json(StringIO('{"a": ["foo", "bar", "baz"], "b": [4, 5, 6]}')) + df.to_json(path, orient="records", lines=True, compression=compression) + + with pd.read_json( + path, lines=True, chunksize=1, compression=compression + ) as res: + roundtripped_df = pd.concat(res) + tm.assert_frame_equal(df, roundtripped_df) + + +def test_write_unsupported_compression_type(): + df = pd.read_json(StringIO('{"a": [1, 2, 3], "b": [4, 5, 6]}')) + with tm.ensure_clean() as path: + msg = "Unrecognized compression type: unsupported" + with pytest.raises(ValueError, match=msg): + df.to_json(path, compression="unsupported") + + +def test_read_unsupported_compression_type(): + with tm.ensure_clean() as path: + msg = "Unrecognized compression type: unsupported" + with pytest.raises(ValueError, match=msg): + pd.read_json(path, compression="unsupported") + + +@pytest.mark.parametrize( + "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))] +) +@pytest.mark.parametrize("to_infer", [True, False]) +@pytest.mark.parametrize("read_infer", [True, False]) +def test_to_json_compression( + compression_only, read_infer, to_infer, compression_to_extension, infer_string +): + with pd.option_context("future.infer_string", infer_string): + # see gh-15008 + compression = compression_only + + # We'll complete file extension subsequently. + filename = "test." + filename += compression_to_extension[compression] + + df = pd.DataFrame({"A": [1]}) + + to_compression = "infer" if to_infer else compression + read_compression = "infer" if read_infer else compression + + with tm.ensure_clean(filename) as path: + df.to_json(path, compression=to_compression) + result = pd.read_json(path, compression=read_compression) + tm.assert_frame_equal(result, df) + + +def test_to_json_compression_mode(compression): + # GH 39985 (read_json does not support user-provided binary files) + expected = pd.DataFrame({"A": [1]}) + + with BytesIO() as buffer: + expected.to_json(buffer, compression=compression) + # df = pd.read_json(buffer, compression=compression) + # tm.assert_frame_equal(expected, df) diff --git a/shared/package-files/3c/3cd9d82f57bb2c9c58afbd7023ddefd24bb07eb6bc60638766f0fafb5c08a1d0/detail.pyi b/shared/package-files/3c/3cd9d82f57bb2c9c58afbd7023ddefd24bb07eb6bc60638766f0fafb5c08a1d0/detail.pyi new file mode 100644 index 0000000000000000000000000000000000000000..70229eacedb21fcea0e4408ed8791fcf242419ea --- /dev/null +++ b/shared/package-files/3c/3cd9d82f57bb2c9c58afbd7023ddefd24bb07eb6bc60638766f0fafb5c08a1d0/detail.pyi @@ -0,0 +1,28 @@ +from typing import Any, Optional, Type + +from django.views.generic.base import ContextMixin, TemplateResponseMixin, View + +from django.db import models +from django.http import HttpRequest, HttpResponse + +class SingleObjectMixin(ContextMixin): + model: Type[models.Model] = ... + queryset: models.query.QuerySet = ... + slug_field: str = ... + context_object_name: str = ... + slug_url_kwarg: str = ... + pk_url_kwarg: str = ... + query_pk_and_slug: bool = ... + def get_object(self, queryset: Optional[models.query.QuerySet] = ...) -> models.Model: ... + def get_queryset(self) -> models.query.QuerySet: ... + def get_slug_field(self) -> str: ... + def get_context_object_name(self, obj: Any) -> Optional[str]: ... + +class BaseDetailView(SingleObjectMixin, View): + def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ... + +class SingleObjectTemplateResponseMixin(TemplateResponseMixin): + template_name_field: Optional[str] = ... + template_name_suffix: str = ... + +class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView): ... diff --git a/shared/package-files/3c/3cde5d2114dc303f936a3ac89eed5e4446718ddc04124139a427d7252e3b478b/stride_compositeimplicitautograd_dispatch.h b/shared/package-files/3c/3cde5d2114dc303f936a3ac89eed5e4446718ddc04124139a427d7252e3b478b/stride_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9914ee31e9de530d9a6dcf8e993d76055a925089 --- /dev/null +++ b/shared/package-files/3c/3cde5d2114dc303f936a3ac89eed5e4446718ddc04124139a427d7252e3b478b/stride_compositeimplicitautograd_dispatch.h @@ -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 int64_t stride(const at::Tensor & self, int64_t dim); +TORCH_API int64_t stride(const at::Tensor & self, at::Dimname dim); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/3c/3cdf1b2e8920a7bcee61b8e46655d8ece6ba335eddd96cd398e521300fc1ddc3/adamax.pyi b/shared/package-files/3c/3cdf1b2e8920a7bcee61b8e46655d8ece6ba335eddd96cd398e521300fc1ddc3/adamax.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d38cfaefe388cd703f4a816459f572216226bf4f --- /dev/null +++ b/shared/package-files/3c/3cdf1b2e8920a7bcee61b8e46655d8ece6ba335eddd96cd398e521300fc1ddc3/adamax.pyi @@ -0,0 +1,13 @@ +from typing import Tuple + +from .optimizer import Optimizer, ParamsT + +class Adamax(Optimizer): + def __init__( + self, + params: ParamsT, + lr: float = ..., + betas: Tuple[float, float] = ..., + eps: float = ..., + weight_decay: float = ..., + ) -> None: ... diff --git a/shared/package-files/3c/3cdf40bbd8b7d43acc2c94c8d3410655ee6ffce210b834b425832c9b72e11d7d/special_scaled_modified_bessel_k0_ops.h b/shared/package-files/3c/3cdf40bbd8b7d43acc2c94c8d3410655ee6ffce210b834b425832c9b72e11d7d/special_scaled_modified_bessel_k0_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cbc198c7a3b6ddc4972871569fedc01eee9ae1be --- /dev/null +++ b/shared/package-files/3c/3cdf40bbd8b7d43acc2c94c8d3410655ee6ffce210b834b425832c9b72e11d7d/special_scaled_modified_bessel_k0_ops.h @@ -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 special_scaled_modified_bessel_k0 { + 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::special_scaled_modified_bessel_k0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_scaled_modified_bessel_k0(Tensor x) -> Tensor") + static at::Tensor call(const at::Tensor & x); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x); +}; + +struct TORCH_API special_scaled_modified_bessel_k0_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::special_scaled_modified_bessel_k0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_scaled_modified_bessel_k0.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & x, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3c/3ce1763ce0738470a44361fb2b836f0842d9b1f7258f3a2347b7bb1417a1f967/test_oinspect.py b/shared/package-files/3c/3ce1763ce0738470a44361fb2b836f0842d9b1f7258f3a2347b7bb1417a1f967/test_oinspect.py new file mode 100644 index 0000000000000000000000000000000000000000..8d65941bf5217d40d7be1470679c728cc159dda0 --- /dev/null +++ b/shared/package-files/3c/3ce1763ce0738470a44361fb2b836f0842d9b1f7258f3a2347b7bb1417a1f967/test_oinspect.py @@ -0,0 +1,579 @@ +"""Tests for the object inspection functionality. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + +from contextlib import contextmanager +from inspect import signature, Signature, Parameter +import inspect +import os +import pytest +import re +import sys + +from .. import oinspect + +from decorator import decorator + +from IPython.testing.tools import AssertPrints, AssertNotPrints +from IPython.utils.path import compress_user + + +#----------------------------------------------------------------------------- +# Globals and constants +#----------------------------------------------------------------------------- + +inspector = None + +def setup_module(): + global inspector + inspector = oinspect.Inspector() + + +class SourceModuleMainTest: + __module__ = "__main__" + + +#----------------------------------------------------------------------------- +# Local utilities +#----------------------------------------------------------------------------- + +# WARNING: since this test checks the line number where a function is +# defined, if any code is inserted above, the following line will need to be +# updated. Do NOT insert any whitespace between the next line and the function +# definition below. +THIS_LINE_NUMBER = 47 # Put here the actual number of this line + + +def test_find_source_lines(): + assert oinspect.find_source_lines(test_find_source_lines) == THIS_LINE_NUMBER + 3 + assert oinspect.find_source_lines(type) is None + assert oinspect.find_source_lines(SourceModuleMainTest) is None + assert oinspect.find_source_lines(SourceModuleMainTest()) is None + + +def test_getsource(): + assert oinspect.getsource(type) is None + assert oinspect.getsource(SourceModuleMainTest) is None + assert oinspect.getsource(SourceModuleMainTest()) is None + + +def test_inspect_getfile_raises_exception(): + """Check oinspect.find_file/getsource/find_source_lines expectations""" + with pytest.raises(TypeError): + inspect.getfile(type) + with pytest.raises(OSError): + inspect.getfile(SourceModuleMainTest) + + +# A couple of utilities to ensure these tests work the same from a source or a +# binary install +def pyfile(fname): + return os.path.normcase(re.sub('.py[co]$', '.py', fname)) + + +def match_pyfiles(f1, f2): + assert pyfile(f1) == pyfile(f2) + + +def test_find_file(): + match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__)) + assert oinspect.find_file(type) is None + assert oinspect.find_file(SourceModuleMainTest) is None + assert oinspect.find_file(SourceModuleMainTest()) is None + + +def test_find_file_decorated1(): + + @decorator + def noop1(f): + def wrapper(*a, **kw): + return f(*a, **kw) + return wrapper + + @noop1 + def f(x): + "My docstring" + + match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__)) + assert f.__doc__ == "My docstring" + + +def test_find_file_decorated2(): + + @decorator + def noop2(f, *a, **kw): + return f(*a, **kw) + + @noop2 + @noop2 + @noop2 + def f(x): + "My docstring 2" + + match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__)) + assert f.__doc__ == "My docstring 2" + + +def test_find_file_magic(): + run = ip.find_line_magic('run') + assert oinspect.find_file(run) is not None + + +# A few generic objects we can then inspect in the tests below + +class Call(object): + """This is the class docstring.""" + + def __init__(self, x, y=1): + """This is the constructor docstring.""" + + def __call__(self, *a, **kw): + """This is the call docstring.""" + + def method(self, x, z=2): + """Some method's docstring""" + +class HasSignature(object): + """This is the class docstring.""" + __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)]) + + def __init__(self, *args): + """This is the init docstring""" + + +class SimpleClass(object): + def method(self, x, z=2): + """Some method's docstring""" + + +class Awkward(object): + def __getattr__(self, name): + raise Exception(name) + +class NoBoolCall: + """ + callable with `__bool__` raising should still be inspect-able. + """ + + def __call__(self): + """does nothing""" + pass + + def __bool__(self): + """just raise NotImplemented""" + raise NotImplementedError('Must be implemented') + + +class SerialLiar(object): + """Attribute accesses always get another copy of the same class. + + unittest.mock.call does something similar, but it's not ideal for testing + as the failure mode is to eat all your RAM. This gives up after 10k levels. + """ + def __init__(self, max_fibbing_twig, lies_told=0): + if lies_told > 10000: + raise RuntimeError('Nose too long, honesty is the best policy') + self.max_fibbing_twig = max_fibbing_twig + self.lies_told = lies_told + max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told) + + def __getattr__(self, item): + return SerialLiar(self.max_fibbing_twig, self.lies_told + 1) + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + +def test_info(): + "Check that Inspector.info fills out various fields as expected." + i = inspector.info(Call, oname="Call") + assert i["type_name"] == "type" + expected_class = str(type(type)) # (Python 3) or + assert i["base_class"] == expected_class + assert re.search( + "", + i["string_form"], + ) + fname = __file__ + if fname.endswith(".pyc"): + fname = fname[:-1] + # case-insensitive comparison needed on some filesystems + # e.g. Windows: + assert i["file"].lower() == compress_user(fname).lower() + assert i["definition"] == None + assert i["docstring"] == Call.__doc__ + assert i["source"] == None + assert i["isclass"] is True + assert i["init_definition"] == "Call(x, y=1)" + assert i["init_docstring"] == Call.__init__.__doc__ + + i = inspector.info(Call, detail_level=1) + assert i["source"] is not None + assert i["docstring"] == None + + c = Call(1) + c.__doc__ = "Modified instance docstring" + i = inspector.info(c) + assert i["type_name"] == "Call" + assert i["docstring"] == "Modified instance docstring" + assert i["class_docstring"] == Call.__doc__ + assert i["init_docstring"] == Call.__init__.__doc__ + assert i["call_docstring"] == Call.__call__.__doc__ + + +def test_class_signature(): + info = inspector.info(HasSignature, "HasSignature") + assert info["init_definition"] == "HasSignature(test)" + assert info["init_docstring"] == HasSignature.__init__.__doc__ + + +def test_info_awkward(): + # Just test that this doesn't throw an error. + inspector.info(Awkward()) + +def test_bool_raise(): + inspector.info(NoBoolCall()) + +def test_info_serialliar(): + fib_tracker = [0] + inspector.info(SerialLiar(fib_tracker)) + + # Nested attribute access should be cut off at 100 levels deep to avoid + # infinite loops: https://github.com/ipython/ipython/issues/9122 + assert fib_tracker[0] < 9000 + +def support_function_one(x, y=2, *a, **kw): + """A simple function.""" + +def test_calldef_none(): + # We should ignore __call__ for all of these. + for obj in [support_function_one, SimpleClass().method, any, str.upper]: + i = inspector.info(obj) + assert i["call_def"] is None + + +def f_kwarg(pos, *, kwonly): + pass + +def test_definition_kwonlyargs(): + i = inspector.info(f_kwarg, oname="f_kwarg") # analysis:ignore + assert i["definition"] == "f_kwarg(pos, *, kwonly)" + + +def test_getdoc(): + class A(object): + """standard docstring""" + pass + + class B(object): + """standard docstring""" + def getdoc(self): + return "custom docstring" + + class C(object): + """standard docstring""" + def getdoc(self): + return None + + a = A() + b = B() + c = C() + + assert oinspect.getdoc(a) == "standard docstring" + assert oinspect.getdoc(b) == "custom docstring" + assert oinspect.getdoc(c) == "standard docstring" + + +def test_empty_property_has_no_source(): + i = inspector.info(property(), detail_level=1) + assert i["source"] is None + + +def test_property_sources(): + # A simple adder whose source and signature stays + # the same across Python distributions + def simple_add(a, b): + "Adds two numbers" + return a + b + + class A(object): + @property + def foo(self): + return 'bar' + + foo = foo.setter(lambda self, v: setattr(self, 'bar', v)) + + dname = property(oinspect.getdoc) + adder = property(simple_add) + + i = inspector.info(A.foo, detail_level=1) + assert "def foo(self):" in i["source"] + assert "lambda self, v:" in i["source"] + + i = inspector.info(A.dname, detail_level=1) + assert "def getdoc(obj)" in i["source"] + + i = inspector.info(A.adder, detail_level=1) + assert "def simple_add(a, b)" in i["source"] + + +def test_property_docstring_is_in_info_for_detail_level_0(): + class A(object): + @property + def foobar(self): + """This is `foobar` property.""" + pass + + ip.user_ns["a_obj"] = A() + assert ( + "This is `foobar` property." + == ip.object_inspect("a_obj.foobar", detail_level=0)["docstring"] + ) + + ip.user_ns["a_cls"] = A + assert ( + "This is `foobar` property." + == ip.object_inspect("a_cls.foobar", detail_level=0)["docstring"] + ) + + +def test_pdef(): + # See gh-1914 + def foo(): pass + inspector.pdef(foo, 'foo') + + +@contextmanager +def cleanup_user_ns(**kwargs): + """ + On exit delete all the keys that were not in user_ns before entering. + + It does not restore old values ! + + Parameters + ---------- + + **kwargs + used to update ip.user_ns + + """ + try: + known = set(ip.user_ns.keys()) + ip.user_ns.update(kwargs) + yield + finally: + added = set(ip.user_ns.keys()) - known + for k in added: + del ip.user_ns[k] + + +def test_pinfo_bool_raise(): + """ + Test that bool method is not called on parent. + """ + + class RaiseBool: + attr = None + + def __bool__(self): + raise ValueError("pinfo should not access this method") + + raise_bool = RaiseBool() + + with cleanup_user_ns(raise_bool=raise_bool): + ip._inspect("pinfo", "raise_bool.attr", detail_level=0) + + +def test_pinfo_getindex(): + def dummy(): + """ + MARKER + """ + + container = [dummy] + with cleanup_user_ns(container=container): + with AssertPrints("MARKER"): + ip._inspect("pinfo", "container[0]", detail_level=0) + assert "container" not in ip.user_ns.keys() + + +def test_qmark_getindex(): + def dummy(): + """ + MARKER 2 + """ + + container = [dummy] + with cleanup_user_ns(container=container): + with AssertPrints("MARKER 2"): + ip.run_cell("container[0]?") + assert "container" not in ip.user_ns.keys() + + +def test_qmark_getindex_negatif(): + def dummy(): + """ + MARKER 3 + """ + + container = [dummy] + with cleanup_user_ns(container=container): + with AssertPrints("MARKER 3"): + ip.run_cell("container[-1]?") + assert "container" not in ip.user_ns.keys() + + + +def test_pinfo_nonascii(): + # See gh-1177 + from . import nonascii2 + ip.user_ns['nonascii2'] = nonascii2 + ip._inspect('pinfo', 'nonascii2', detail_level=1) + +def test_pinfo_type(): + """ + type can fail in various edge case, for example `type.__subclass__()` + """ + ip._inspect('pinfo', 'type') + + +def test_pinfo_docstring_no_source(): + """Docstring should be included with detail_level=1 if there is no source""" + with AssertPrints('Docstring:'): + ip._inspect('pinfo', 'str.format', detail_level=0) + with AssertPrints('Docstring:'): + ip._inspect('pinfo', 'str.format', detail_level=1) + + +def test_pinfo_no_docstring_if_source(): + """Docstring should not be included with detail_level=1 if source is found""" + def foo(): + """foo has a docstring""" + + ip.user_ns['foo'] = foo + + with AssertPrints('Docstring:'): + ip._inspect('pinfo', 'foo', detail_level=0) + with AssertPrints('Source:'): + ip._inspect('pinfo', 'foo', detail_level=1) + with AssertNotPrints('Docstring:'): + ip._inspect('pinfo', 'foo', detail_level=1) + + +def test_pinfo_docstring_if_detail_and_no_source(): + """ Docstring should be displayed if source info not available """ + obj_def = '''class Foo(object): + """ This is a docstring for Foo """ + def bar(self): + """ This is a docstring for Foo.bar """ + pass + ''' + + ip.run_cell(obj_def) + ip.run_cell('foo = Foo()') + + with AssertNotPrints("Source:"): + with AssertPrints('Docstring:'): + ip._inspect('pinfo', 'foo', detail_level=0) + with AssertPrints('Docstring:'): + ip._inspect('pinfo', 'foo', detail_level=1) + with AssertPrints('Docstring:'): + ip._inspect('pinfo', 'foo.bar', detail_level=0) + + with AssertNotPrints('Docstring:'): + with AssertPrints('Source:'): + ip._inspect('pinfo', 'foo.bar', detail_level=1) + + +def test_pinfo_docstring_dynamic(): + obj_def = """class Bar: + __custom_documentations__ = { + "prop" : "cdoc for prop", + "non_exist" : "cdoc for non_exist", + } + @property + def prop(self): + ''' + Docstring for prop + ''' + return self._prop + + @prop.setter + def prop(self, v): + self._prop = v + """ + ip.run_cell(obj_def) + + ip.run_cell("b = Bar()") + + with AssertPrints("Docstring: cdoc for prop"): + ip.run_line_magic("pinfo", "b.prop") + + with AssertPrints("Docstring: cdoc for non_exist"): + ip.run_line_magic("pinfo", "b.non_exist") + + with AssertPrints("Docstring: cdoc for prop"): + ip.run_cell("b.prop?") + + with AssertPrints("Docstring: cdoc for non_exist"): + ip.run_cell("b.non_exist?") + + with AssertPrints("Docstring: "): + ip.run_cell("b.undefined?") + + +def test_pinfo_magic(): + with AssertPrints("Docstring:"): + ip._inspect("pinfo", "lsmagic", detail_level=0) + + with AssertPrints("Source:"): + ip._inspect("pinfo", "lsmagic", detail_level=1) + + +def test_init_colors(): + # ensure colors are not present in signature info + info = inspector.info(HasSignature) + init_def = info["init_definition"] + assert "[0m" not in init_def + + +def test_builtin_init(): + info = inspector.info(list) + init_def = info['init_definition'] + assert init_def is not None + + +def test_render_signature_short(): + def short_fun(a=1): pass + sig = oinspect._render_signature( + signature(short_fun), + short_fun.__name__, + ) + assert sig == "short_fun(a=1)" + + +def test_render_signature_long(): + from typing import Optional + + def long_function( + a_really_long_parameter: int, + and_another_long_one: bool = False, + let_us_make_sure_this_is_looong: Optional[str] = None, + ) -> bool: pass + + sig = oinspect._render_signature( + signature(long_function), + long_function.__name__, + ) + expected = """\ +long_function( + a_really_long_parameter: int, + and_another_long_one: bool = False, + let_us_make_sure_this_is_looong: Optional[str] = None, +) -> bool\ +""" + + assert sig == expected diff --git a/shared/package-files/3c/3ce39d5877c1d64191cf27e3bc01a2747bcc66b111a92a14b68441d01126e23a/WHEEL b/shared/package-files/3c/3ce39d5877c1d64191cf27e3bc01a2747bcc66b111a92a14b68441d01126e23a/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..eacebf978faf327e15b0599269223db6460746b8 --- /dev/null +++ b/shared/package-files/3c/3ce39d5877c1d64191cf27e3bc01a2747bcc66b111a92a14b68441d01126e23a/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: maturin (1.3.1) +Root-Is-Purelib: false +Tag: cp310-cp310-linux_x86_64 diff --git a/shared/package-files/3c/3ce4c369538e84641cd035f8a8350100f3f6385e285fc2b15037aa46c84c6fd7/test_dfm_blocks_111.mat b/shared/package-files/3c/3ce4c369538e84641cd035f8a8350100f3f6385e285fc2b15037aa46c84c6fd7/test_dfm_blocks_111.mat new file mode 100644 index 0000000000000000000000000000000000000000..5517dbfa11bdf9c378ade8e6566e4dff29ca3486 Binary files /dev/null and b/shared/package-files/3c/3ce4c369538e84641cd035f8a8350100f3f6385e285fc2b15037aa46c84c6fd7/test_dfm_blocks_111.mat differ diff --git a/shared/package-files/3c/3ced724aa06cb6d07d9459d0d69b160ecb3f24431baa21f27b4736401451554f/test_complex.py b/shared/package-files/3c/3ced724aa06cb6d07d9459d0d69b160ecb3f24431baa21f27b4736401451554f/test_complex.py new file mode 100644 index 0000000000000000000000000000000000000000..9583931629ccd421c3a1a8d5aa39232766510e26 --- /dev/null +++ b/shared/package-files/3c/3ced724aa06cb6d07d9459d0d69b160ecb3f24431baa21f27b4736401451554f/test_complex.py @@ -0,0 +1,296 @@ +import math +import itertools + +import numpy as np + +from numba.cuda.testing import unittest, CUDATestCase +from numba.core import types +from numba import cuda +from numba.tests.complex_usecases import (real_usecase, imag_usecase, + conjugate_usecase, phase_usecase, + polar_as_complex_usecase, + rect_usecase, isnan_usecase, + isinf_usecase, isfinite_usecase, + exp_usecase, log_usecase, + log_base_usecase, log10_usecase, + sqrt_usecase, asin_usecase, + acos_usecase, atan_usecase, + cos_usecase, sin_usecase, + tan_usecase, acosh_usecase, + asinh_usecase, atanh_usecase, + cosh_usecase, sinh_usecase, + tanh_usecase) +from numba.np import numpy_support + + +def compile_scalar_func(pyfunc, argtypes, restype): + # First compile a scalar device function + assert not any(isinstance(tp, types.Array) for tp in argtypes) + assert not isinstance(restype, types.Array) + device_func = cuda.jit(restype(*argtypes), device=True)(pyfunc) + + kernel_types = [types.Array(tp, 1, "C") + for tp in [restype] + list(argtypes)] + + if len(argtypes) == 1: + def kernel_func(out, a): + i = cuda.grid(1) + if i < out.shape[0]: + out[i] = device_func(a[i]) + elif len(argtypes) == 2: + def kernel_func(out, a, b): + i = cuda.grid(1) + if i < out.shape[0]: + out[i] = device_func(a[i], b[i]) + else: + assert 0 + + kernel = cuda.jit(tuple(kernel_types))(kernel_func) + + def kernel_wrapper(values): + n = len(values) + inputs = [np.empty(n, dtype=numpy_support.as_dtype(tp)) + for tp in argtypes] + output = np.empty(n, dtype=numpy_support.as_dtype(restype)) + for i, vs in enumerate(values): + for v, inp in zip(vs, inputs): + inp[i] = v + args = [output] + inputs + kernel[int(math.ceil(n / 256)), 256](*args) + return list(output) + return kernel_wrapper + + +class BaseComplexTest(CUDATestCase): + + def basic_values(self): + reals = [-0.0, +0.0, 1, -1, +1.5, -3.5, + float('-inf'), float('+inf'), float('nan')] + return [complex(x, y) for x, y in itertools.product(reals, reals)] + + def more_values(self): + reals = [0.0, +0.0, 1, -1, -math.pi, +math.pi, + float('-inf'), float('+inf'), float('nan')] + return [complex(x, y) for x, y in itertools.product(reals, reals)] + + def non_nan_values(self): + reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi, + float('inf'), float('-inf')] + return [complex(x, y) for x, y in itertools.product(reals, reals)] + + def run_func(self, pyfunc, sigs, values, ulps=1, ignore_sign_on_zero=False): + for sig in sigs: + if isinstance(sig, types.Type): + sig = sig, + if isinstance(sig, tuple): + # Assume return type is the type of first argument + sig = sig[0](*sig) + prec = ('single' + if sig.args[0] in (types.float32, types.complex64) + else 'double') + cudafunc = compile_scalar_func(pyfunc, sig.args, sig.return_type) + ok_values = [] + expected_list = [] + for args in values: + if not isinstance(args, (list, tuple)): + args = args, + try: + expected_list.append(pyfunc(*args)) + ok_values.append(args) + except ValueError as e: + self.assertIn("math domain error", str(e)) + continue + got_list = cudafunc(ok_values) + for got, expected, args in zip(got_list, expected_list, ok_values): + msg = 'for input %r with prec %r' % (args, prec) + self.assertPreciseEqual(got, expected, prec=prec, + ulps=ulps, + ignore_sign_on_zero=ignore_sign_on_zero, + msg=msg) + + run_unary = run_func + run_binary = run_func + + +class TestComplex(BaseComplexTest): + + def check_real_image(self, pyfunc): + values = self.basic_values() + self.run_unary(pyfunc, + [tp.underlying_float(tp) + for tp in (types.complex64, types.complex128)], + values) + + def test_real(self): + self.check_real_image(real_usecase) + + def test_imag(self): + self.check_real_image(imag_usecase) + + def test_conjugate(self): + pyfunc = conjugate_usecase + values = self.basic_values() + self.run_unary(pyfunc, + [types.complex64, types.complex128], + values) + + +class TestCMath(BaseComplexTest): + """ + Tests for cmath module support. + """ + + def check_predicate_func(self, pyfunc): + self.run_unary(pyfunc, + [types.boolean(tp) + for tp in (types.complex128, types.complex64)], + self.basic_values()) + + def check_unary_func(self, pyfunc, ulps=1, values=None, + returns_float=False, ignore_sign_on_zero=False): + if returns_float: + def sig(tp): + return tp.underlying_float(tp) + else: + def sig(tp): + return tp(tp) + self.run_unary(pyfunc, [sig(types.complex128)], + values or self.more_values(), ulps=ulps, + ignore_sign_on_zero=ignore_sign_on_zero) + # Avoid discontinuities around pi when in single precision. + self.run_unary(pyfunc, [sig(types.complex64)], + values or self.basic_values(), ulps=ulps, + ignore_sign_on_zero=ignore_sign_on_zero) + + # Conversions + + def test_phase(self): + self.check_unary_func(phase_usecase, returns_float=True) + + def test_polar(self): + self.check_unary_func(polar_as_complex_usecase) + + def test_rect(self): + def do_test(tp, seed_values): + values = [(z.real, z.imag) for z in seed_values + if not math.isinf(z.imag) or z.real == 0] + float_type = tp.underlying_float + self.run_binary(rect_usecase, [tp(float_type, float_type)], + values) + do_test(types.complex128, self.more_values()) + # Avoid discontinuities around pi when in single precision. + do_test(types.complex64, self.basic_values()) + + # Classification + + def test_isnan(self): + self.check_predicate_func(isnan_usecase) + + def test_isinf(self): + self.check_predicate_func(isinf_usecase) + + def test_isfinite(self): + self.check_predicate_func(isfinite_usecase) + + # Power and logarithms + + def test_exp(self): + self.check_unary_func(exp_usecase, ulps=2) + + def test_log(self): + self.check_unary_func(log_usecase) + + def test_log_base(self): + values = list(itertools.product(self.more_values(), self.more_values())) + value_types = [(types.complex128, types.complex128), + (types.complex64, types.complex64)] + self.run_binary(log_base_usecase, value_types, values, + ulps=3) + + def test_log10(self): + self.check_unary_func(log10_usecase) + + def test_sqrt(self): + self.check_unary_func(sqrt_usecase) + + # Trigonometric functions + + def test_acos(self): + self.check_unary_func(acos_usecase, ulps=2) + + def test_asin(self): + self.check_unary_func(asin_usecase, ulps=2) + + def test_atan(self): + self.check_unary_func(atan_usecase, ulps=2, + values=self.non_nan_values()) + + def test_cos(self): + self.check_unary_func(cos_usecase, ulps=2) + + def test_sin(self): + # See test_sinh. + self.check_unary_func(sin_usecase, ulps=2) + + def test_tan(self): + self.check_unary_func(tan_usecase, ulps=2, + ignore_sign_on_zero=True) + + # Hyperbolic functions + + def test_acosh(self): + self.check_unary_func(acosh_usecase) + + def test_asinh(self): + self.check_unary_func(asinh_usecase, ulps=2) + + def test_atanh(self): + self.check_unary_func(atanh_usecase, ulps=2, + ignore_sign_on_zero=True) + + def test_cosh(self): + self.check_unary_func(cosh_usecase, ulps=2) + + def test_sinh(self): + self.check_unary_func(sinh_usecase, ulps=2) + + def test_tanh(self): + self.check_unary_func(tanh_usecase, ulps=2, + ignore_sign_on_zero=True) + + +class TestAtomicOnComplexComponents(CUDATestCase): + # Based on the reproducer from Issue #8309. array.real and array.imag could + # not be used because they required returning an array from a generated + # function, and even if this was permitted, they could not be resolved from + # the atomic lowering when they were overloads. + # + # See https://github.com/numba/numba/issues/8309 + + def test_atomic_on_real(self): + @cuda.jit + def atomic_add_one(values): + i = cuda.grid(1) + cuda.atomic.add(values.real, i, 1) + + N = 32 + arr1 = np.arange(N) + np.arange(N) * 1j + arr2 = arr1.copy() + atomic_add_one[1, N](arr2) + np.testing.assert_equal(arr1 + 1, arr2) + + def test_atomic_on_imag(self): + @cuda.jit + def atomic_add_one_j(values): + i = cuda.grid(1) + cuda.atomic.add(values.imag, i, 1) + + N = 32 + arr1 = np.arange(N) + np.arange(N) * 1j + arr2 = arr1.copy() + atomic_add_one_j[1, N](arr2) + np.testing.assert_equal(arr1 + 1j, arr2) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/3c/3cf7aefc97df33da1df8b9af60b71a6590bd793c841cec850911c21db877aff6/_efficientzerotensor_cuda_dispatch.h b/shared/package-files/3c/3cf7aefc97df33da1df8b9af60b71a6590bd793c841cec850911c21db877aff6/_efficientzerotensor_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1b731bddee2eb09216135749e84162a523618a45 --- /dev/null +++ b/shared/package-files/3c/3cf7aefc97df33da1df8b9af60b71a6590bd793c841cec850911c21db877aff6/_efficientzerotensor_cuda_dispatch.h @@ -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 _efficientzerotensor(at::IntArrayRef size, at::TensorOptions options={}); +TORCH_API at::Tensor _efficientzerotensor(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor _efficientzerotensor_symint(c10::SymIntArrayRef size, at::TensorOptions options={}); +TORCH_API at::Tensor _efficientzerotensor_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/4f/4f04b662048b949c0e5e334db0706e5f2c6129e28aa69b551cb055ed061909ab/kaldi_io.py b/shared/package-files/4f/4f04b662048b949c0e5e334db0706e5f2c6129e28aa69b551cb055ed061909ab/kaldi_io.py new file mode 100644 index 0000000000000000000000000000000000000000..4d372429dcfd23fdcbe8cd0f38abef1086d8a5eb --- /dev/null +++ b/shared/package-files/4f/4f04b662048b949c0e5e334db0706e5f2c6129e28aa69b551cb055ed061909ab/kaldi_io.py @@ -0,0 +1,144 @@ +# To use this file, the dependency (https://github.com/vesis84/kaldi-io-for-python) +# needs to be installed. This is a light wrapper around kaldi_io that returns +# torch.Tensors. +from typing import Any, Callable, Iterable, Tuple + +import torch +from torch import Tensor +from torchaudio._internal import module_utils as _mod_utils + +if _mod_utils.is_module_available("numpy"): + import numpy as np + + +__all__ = [ + "read_vec_int_ark", + "read_vec_flt_scp", + "read_vec_flt_ark", + "read_mat_scp", + "read_mat_ark", +] + + +def _convert_method_output_to_tensor( + file_or_fd: Any, fn: Callable, convert_contiguous: bool = False +) -> Iterable[Tuple[str, Tensor]]: + r"""Takes a method invokes it. The output is converted to a tensor. + + Args: + file_or_fd (str/FileDescriptor): File name or file descriptor + fn (Callable): Function that has the signature (file name/descriptor) and converts it to + Iterable[Tuple[str, Tensor]]. + convert_contiguous (bool, optional): Determines whether the array should be converted into a + contiguous layout. (Default: ``False``) + + Returns: + Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is vec/mat + """ + for key, np_arr in fn(file_or_fd): + if convert_contiguous: + np_arr = np.ascontiguousarray(np_arr) + yield key, torch.from_numpy(np_arr) + + +@_mod_utils.requires_module("kaldi_io", "numpy") +def read_vec_int_ark(file_or_fd: Any) -> Iterable[Tuple[str, Tensor]]: + r"""Create generator of (key,vector) tuples, which reads from the ark file/stream. + + Args: + file_or_fd (str/FileDescriptor): ark, gzipped ark, pipe or opened file descriptor + + Returns: + Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is the vector read from file + + Example + >>> # read ark to a 'dictionary' + >>> d = { u:d for u,d in torchaudio.kaldi_io.read_vec_int_ark(file) } + """ + + import kaldi_io + + # Requires convert_contiguous to be True because elements from int32 vector are + # sorted in tuples: (sizeof(int32), value) so strides are (5,) instead of (4,) which will throw an error + # in from_numpy as it expects strides to be a multiple of 4 (int32). + return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_vec_int_ark, convert_contiguous=True) + + +@_mod_utils.requires_module("kaldi_io", "numpy") +def read_vec_flt_scp(file_or_fd: Any) -> Iterable[Tuple[str, Tensor]]: + r"""Create generator of (key,vector) tuples, read according to Kaldi scp. + + Args: + file_or_fd (str/FileDescriptor): scp, gzipped scp, pipe or opened file descriptor + + Returns: + Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is the vector read from file + + Example + >>> # read scp to a 'dictionary' + >>> # d = { u:d for u,d in torchaudio.kaldi_io.read_vec_flt_scp(file) } + """ + + import kaldi_io + + return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_vec_flt_scp) + + +@_mod_utils.requires_module("kaldi_io", "numpy") +def read_vec_flt_ark(file_or_fd: Any) -> Iterable[Tuple[str, Tensor]]: + r"""Create generator of (key,vector) tuples, which reads from the ark file/stream. + + Args: + file_or_fd (str/FileDescriptor): ark, gzipped ark, pipe or opened file descriptor + + Returns: + Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is the vector read from file + + Example + >>> # read ark to a 'dictionary' + >>> d = { u:d for u,d in torchaudio.kaldi_io.read_vec_flt_ark(file) } + """ + + import kaldi_io + + return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_vec_flt_ark) + + +@_mod_utils.requires_module("kaldi_io", "numpy") +def read_mat_scp(file_or_fd: Any) -> Iterable[Tuple[str, Tensor]]: + r"""Create generator of (key,matrix) tuples, read according to Kaldi scp. + + Args: + file_or_fd (str/FileDescriptor): scp, gzipped scp, pipe or opened file descriptor + + Returns: + Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is the matrix read from file + + Example + >>> # read scp to a 'dictionary' + >>> d = { u:d for u,d in torchaudio.kaldi_io.read_mat_scp(file) } + """ + + import kaldi_io + + return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_mat_scp) + + +@_mod_utils.requires_module("kaldi_io", "numpy") +def read_mat_ark(file_or_fd: Any) -> Iterable[Tuple[str, Tensor]]: + r"""Create generator of (key,matrix) tuples, which reads from the ark file/stream. + + Args: + file_or_fd (str/FileDescriptor): ark, gzipped ark, pipe or opened file descriptor + + Returns: + Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is the matrix read from file + + Example + >>> # read ark to a 'dictionary' + >>> d = { u:d for u,d in torchaudio.kaldi_io.read_mat_ark(file) } + """ + + import kaldi_io + + return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_mat_ark) diff --git a/shared/package-files/4f/4f0bbf47541b2d4b0f960acce6f5fe46eaf9ef39b273048b6badf6eed6c0af36/linux-m b/shared/package-files/4f/4f0bbf47541b2d4b0f960acce6f5fe46eaf9ef39b273048b6badf6eed6c0af36/linux-m new file mode 100644 index 0000000000000000000000000000000000000000..02b202e4e3f2afeccd783d4b5aefd0d78014f036 Binary files /dev/null and b/shared/package-files/4f/4f0bbf47541b2d4b0f960acce6f5fe46eaf9ef39b273048b6badf6eed6c0af36/linux-m differ diff --git a/shared/package-files/4f/4f0cb5664826781fade374d5004d0ee4086332c32a473fdc60c4be6e77a1fa32/example_ssm_wpi1.m b/shared/package-files/4f/4f0cb5664826781fade374d5004d0ee4086332c32a473fdc60c4be6e77a1fa32/example_ssm_wpi1.m new file mode 100644 index 0000000000000000000000000000000000000000..7e14fcb19291ad25d44beeff2f06aecf254c2f56 --- /dev/null +++ b/shared/package-files/4f/4f0cb5664826781fade374d5004d0ee4086332c32a473fdc60c4be6e77a1fa32/example_ssm_wpi1.m @@ -0,0 +1,53 @@ +% Load the dataset +data = csvread('results_wpi1_ar3_stata.csv', 1, 0); + +% First differences +dwpi1 = diff(data(:,1)); + +% Parameters +ar = [.5270715, .0952613, .2580355]; +sigma2 = .5307459; + +% Create the state space representation +[nobs, k_endog] = size(dwpi1); +k_states = 3; +k_posdef = 1; + +obs = dwpi1'; +obs_intercept = [0]; +design = [1, 0, 0]; +obs_cov = [0]; + +state_intercept = [0; 0]; +transition = [ar; 1, 0, 0; 0, 1, 0]; +selection = [1; 0; 0]; +state_cov = [sigma2]; +selected_state_cov = selection * state_cov * selection'; + +initial_state = [0; 0]; +initial_state_cov = dlyap(conj(transition), selected_state_cov); + +mod = ssmodel('test', ssmat(obs_cov), ssmat(design), ssmat(transition),ssmat(selection),ssmat(state_cov)); +mod.P1 = initial_state_cov; + +% Optionally add missing values +% obs(10:20) = nan; + +% Estimate +[a, P] = kalman(dwpi1', mod); +[alphahat, V] = statesmo(dwpi1', mod); +[eps, eta, epsvar, etavar] = disturbsmo(dwpi1', mod); +% Note: simsmo seems to always crashes MATLAB +%[alphatilde, epstilde, etatilde] = simsmo(dwpi1', mod); + +% Calculate determinants of variance matrices (so that we can compare +% in unit tests) +detP = zeros(1,nobs); +detV = zeros(1,nobs); +for i = 1:nobs+1; + detP(i) = det(P(:,:,i)); + detV(i) = det(V(:,:,i)); +end; + +% Write output +csvwrite('results_wpi1_ar3_matlab_ssm.csv', [a(:,1:end-1) detP(:,1:end-1) alphahat detV eps epsvar eta etavar]); diff --git a/shared/package-files/4f/4f10049280b9cac03926e2bc20cdb1a2aeb4c9d7555aa397b26c585c8afee3f1/_ni_docstrings.py b/shared/package-files/4f/4f10049280b9cac03926e2bc20cdb1a2aeb4c9d7555aa397b26c585c8afee3f1/_ni_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0d977500574b73f168296645fb36d10c1320de --- /dev/null +++ b/shared/package-files/4f/4f10049280b9cac03926e2bc20cdb1a2aeb4c9d7555aa397b26c585c8afee3f1/_ni_docstrings.py @@ -0,0 +1,210 @@ +"""Docstring components common to several ndimage functions.""" +from typing import Final + +from scipy._lib import doccer + +__all__ = ['docfiller'] + + +_input_doc = ( +"""input : array_like + The input array.""") +_axis_doc = ( +"""axis : int, optional + The axis of `input` along which to calculate. Default is -1.""") +_output_doc = ( +"""output : array or dtype, optional + The array in which to place the output, or the dtype of the + returned array. By default an array of the same dtype as input + will be created.""") +_size_foot_doc = ( +"""size : scalar or tuple, optional + See footprint, below. Ignored if footprint is given. +footprint : array, optional + Either `size` or `footprint` must be defined. `size` gives + the shape that is taken from the input array, at every element + position, to define the input to the filter function. + `footprint` is a boolean array that specifies (implicitly) a + shape, but also which of the elements within this shape will get + passed to the filter function. Thus ``size=(n,m)`` is equivalent + to ``footprint=np.ones((n,m))``. We adjust `size` to the number + of dimensions of the input array, so that, if the input array is + shape (10,10,10), and `size` is 2, then the actual size used is + (2,2,2). When `footprint` is given, `size` is ignored.""") +_mode_reflect_doc = ( +"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'reflect'. Behavior for each valid + value is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") + +_mode_interp_constant_doc = ( +"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \ +'mirror', 'grid-wrap', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'constant'. Behavior for each valid + value is as follows (see additional plots and details on + :ref:`boundary modes `): + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. No + interpolation is performed beyond the edges of the input. + + 'grid-constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. Interpolation + occurs for samples outside the input's extent as well. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'grid-wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + 'wrap' (`d b c d | a b c d | b c a b`) + The input is extended by wrapping around to the opposite edge, but in a + way such that the last point and initial point exactly overlap. In this + case it is not well defined which sample will be chosen at the point of + overlap.""") +_mode_interp_mirror_doc = ( + _mode_interp_constant_doc.replace("Default is 'constant'", + "Default is 'mirror'") +) +assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \ + 'Default not replaced' + +_mode_multiple_doc = ( +"""mode : str or sequence, optional + The `mode` parameter determines how the input array is extended + when the filter overlaps a border. By passing a sequence of modes + with length equal to the number of dimensions of the input array, + different modes can be specified along each axis. Default value is + 'reflect'. The valid values and their behavior is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") +_cval_doc = ( +"""cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0.""") +_origin_doc = ( +"""origin : int, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right.""") +_origin_multiple_doc = ( +"""origin : int or sequence, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right. By passing a sequence of origins with length equal to + the number of dimensions of the input array, different shifts can + be specified along each axis.""") +_extra_arguments_doc = ( +"""extra_arguments : sequence, optional + Sequence of extra positional arguments to pass to passed function.""") +_extra_keywords_doc = ( +"""extra_keywords : dict, optional + dict of extra keyword arguments to pass to passed function.""") +_prefilter_doc = ( +"""prefilter : bool, optional + Determines if the input array is prefiltered with `spline_filter` + before interpolation. The default is True, which will create a + temporary `float64` array of filtered values if ``order > 1``. If + setting this to False, the output will be slightly blurred if + ``order > 1``, unless the input is prefiltered, i.e. it is the result + of calling `spline_filter` on the original input.""") + +docdict = { + 'input': _input_doc, + 'axis': _axis_doc, + 'output': _output_doc, + 'size_foot': _size_foot_doc, + 'mode_interp_constant': _mode_interp_constant_doc, + 'mode_interp_mirror': _mode_interp_mirror_doc, + 'mode_reflect': _mode_reflect_doc, + 'mode_multiple': _mode_multiple_doc, + 'cval': _cval_doc, + 'origin': _origin_doc, + 'origin_multiple': _origin_multiple_doc, + 'extra_arguments': _extra_arguments_doc, + 'extra_keywords': _extra_keywords_doc, + 'prefilter': _prefilter_doc + } + +docfiller: Final = doccer.filldoc(docdict) diff --git a/shared/package-files/4f/4f10fb501b5ecc5e1109d6c202e4ec481e6570539066b1a72ceb8231ad17598d/test_degree_centrality.py b/shared/package-files/4f/4f10fb501b5ecc5e1109d6c202e4ec481e6570539066b1a72ceb8231ad17598d/test_degree_centrality.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f6c39d3bd58d243627c9f33a088e4f4e37d3bb --- /dev/null +++ b/shared/package-files/4f/4f10fb501b5ecc5e1109d6c202e4ec481e6570539066b1a72ceb8231ad17598d/test_degree_centrality.py @@ -0,0 +1,144 @@ +""" + Unit tests for degree centrality. +""" + +import pytest + +import networkx as nx + + +class TestDegreeCentrality: + def setup_method(self): + self.K = nx.krackhardt_kite_graph() + self.P3 = nx.path_graph(3) + self.K5 = nx.complete_graph(5) + + F = nx.Graph() # Florentine families + F.add_edge("Acciaiuoli", "Medici") + F.add_edge("Castellani", "Peruzzi") + F.add_edge("Castellani", "Strozzi") + F.add_edge("Castellani", "Barbadori") + F.add_edge("Medici", "Barbadori") + F.add_edge("Medici", "Ridolfi") + F.add_edge("Medici", "Tornabuoni") + F.add_edge("Medici", "Albizzi") + F.add_edge("Medici", "Salviati") + F.add_edge("Salviati", "Pazzi") + F.add_edge("Peruzzi", "Strozzi") + F.add_edge("Peruzzi", "Bischeri") + F.add_edge("Strozzi", "Ridolfi") + F.add_edge("Strozzi", "Bischeri") + F.add_edge("Ridolfi", "Tornabuoni") + F.add_edge("Tornabuoni", "Guadagni") + F.add_edge("Albizzi", "Ginori") + F.add_edge("Albizzi", "Guadagni") + F.add_edge("Bischeri", "Guadagni") + F.add_edge("Guadagni", "Lamberteschi") + self.F = F + + G = nx.DiGraph() + G.add_edge(0, 5) + G.add_edge(1, 5) + G.add_edge(2, 5) + G.add_edge(3, 5) + G.add_edge(4, 5) + G.add_edge(5, 6) + G.add_edge(5, 7) + G.add_edge(5, 8) + self.G = G + + def test_degree_centrality_1(self): + d = nx.degree_centrality(self.K5) + exact = dict(zip(range(5), [1] * 5)) + for n, dc in d.items(): + assert exact[n] == pytest.approx(dc, abs=1e-7) + + def test_degree_centrality_2(self): + d = nx.degree_centrality(self.P3) + exact = {0: 0.5, 1: 1, 2: 0.5} + for n, dc in d.items(): + assert exact[n] == pytest.approx(dc, abs=1e-7) + + def test_degree_centrality_3(self): + d = nx.degree_centrality(self.K) + exact = { + 0: 0.444, + 1: 0.444, + 2: 0.333, + 3: 0.667, + 4: 0.333, + 5: 0.556, + 6: 0.556, + 7: 0.333, + 8: 0.222, + 9: 0.111, + } + for n, dc in d.items(): + assert exact[n] == pytest.approx(float(f"{dc:.3f}"), abs=1e-7) + + def test_degree_centrality_4(self): + d = nx.degree_centrality(self.F) + names = sorted(self.F.nodes()) + dcs = [ + 0.071, + 0.214, + 0.143, + 0.214, + 0.214, + 0.071, + 0.286, + 0.071, + 0.429, + 0.071, + 0.214, + 0.214, + 0.143, + 0.286, + 0.214, + ] + exact = dict(zip(names, dcs)) + for n, dc in d.items(): + assert exact[n] == pytest.approx(float(f"{dc:.3f}"), abs=1e-7) + + def test_indegree_centrality(self): + d = nx.in_degree_centrality(self.G) + exact = { + 0: 0.0, + 1: 0.0, + 2: 0.0, + 3: 0.0, + 4: 0.0, + 5: 0.625, + 6: 0.125, + 7: 0.125, + 8: 0.125, + } + for n, dc in d.items(): + assert exact[n] == pytest.approx(dc, abs=1e-7) + + def test_outdegree_centrality(self): + d = nx.out_degree_centrality(self.G) + exact = { + 0: 0.125, + 1: 0.125, + 2: 0.125, + 3: 0.125, + 4: 0.125, + 5: 0.375, + 6: 0.0, + 7: 0.0, + 8: 0.0, + } + for n, dc in d.items(): + assert exact[n] == pytest.approx(dc, abs=1e-7) + + def test_small_graph_centrality(self): + G = nx.empty_graph(create_using=nx.DiGraph) + assert {} == nx.degree_centrality(G) + assert {} == nx.out_degree_centrality(G) + assert {} == nx.in_degree_centrality(G) + + G = nx.empty_graph(1, create_using=nx.DiGraph) + assert {0: 1} == nx.degree_centrality(G) + assert {0: 1} == nx.out_degree_centrality(G) + assert {0: 1} == nx.in_degree_centrality(G) diff --git a/shared/package-files/4f/4f11e0c54a7cd6cd374c626a1ffd1d2d0e76d999d7de00a3d23e422bc157a011/view_ops.h b/shared/package-files/4f/4f11e0c54a7cd6cd374c626a1ffd1d2d0e76d999d7de00a3d23e422bc157a011/view_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a13519b0c39bf434905b95994d56797103bdc45c --- /dev/null +++ b/shared/package-files/4f/4f11e0c54a7cd6cd374c626a1ffd1d2d0e76d999d7de00a3d23e422bc157a011/view_ops.h @@ -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 view { + using schema = 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::view") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "view(Tensor(a) self, SymInt[] size) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size); +}; + +struct TORCH_API view_dtype { + using schema = at::Tensor (const at::Tensor &, at::ScalarType); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::view") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dtype") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self, at::ScalarType dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::ScalarType dtype); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/4f/4f173c39c0a3c89891f349e940a830d3af89817fe916712ff011ec177728eb83/PalmImagePlugin.py b/shared/package-files/4f/4f173c39c0a3c89891f349e940a830d3af89817fe916712ff011ec177728eb83/PalmImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..65be7fef7b1bc8a7779a35ac9b31be506f1f906a --- /dev/null +++ b/shared/package-files/4f/4f173c39c0a3c89891f349e940a830d3af89817fe916712ff011ec177728eb83/PalmImagePlugin.py @@ -0,0 +1,226 @@ +# +# The Python Imaging Library. +# $Id$ +# + +## +# Image plugin for Palm pixmap images (output only). +## +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import o8 +from ._binary import o16be as o16b + +# fmt: off +_Palm8BitColormapValues = ( + (255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255), + (255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204), + (255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204), + (255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153), + (255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255), + (204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255), + (204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204), + (204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153), + (204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153), + (153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255), + (153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204), + (153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204), + (153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153), + (153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255), + (102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255), + (102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204), + (102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153), + (102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153), + (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255), + (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204), + (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204), + (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153), + (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255), + (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255), + (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204), + (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153), + (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153), + (255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102), + (255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51), + (255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51), + (255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0), + (255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102), + (204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102), + (204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51), + (204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0), + (204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0), + (153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102), + (153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51), + (153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51), + (153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0), + (153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102), + (102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102), + (102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51), + (102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0), + (102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0), + (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102), + (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51), + (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51), + (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0), + (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102), + (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102), + (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51), + (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0), + (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17), + (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119), + (136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221), + (238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128), + (0, 128, 0), (0, 128, 128), (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), (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)) +# fmt: on + + +# so build a prototype image to be used for palette resampling +def build_prototype_image(): + image = Image.new("L", (1, len(_Palm8BitColormapValues))) + image.putdata(list(range(len(_Palm8BitColormapValues)))) + palettedata = () + for colormapValue in _Palm8BitColormapValues: + palettedata += colormapValue + palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues)) + image.putpalette(palettedata) + return image + + +Palm8BitColormapImage = build_prototype_image() + +# OK, we now have in Palm8BitColormapImage, +# a "P"-mode image with the right palette +# +# -------------------------------------------------------------------- + +_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000} + +_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00} + + +# +# -------------------------------------------------------------------- + +## +# (Internal) Image save plugin for the Palm format. + + +def _save(im, fp, filename): + if im.mode == "P": + # we assume this is a color Palm image with the standard colormap, + # unless the "info" dict has a "custom-colormap" field + + rawmode = "P" + bpp = 8 + version = 1 + + elif im.mode == "L": + if im.encoderinfo.get("bpp") in (1, 2, 4): + # this is 8-bit grayscale, so we shift it to get the high-order bits, + # and invert it because + # Palm does grayscale from white (0) to black (1) + bpp = im.encoderinfo["bpp"] + im = im.point( + lambda x, shift=8 - bpp, maxval=(1 << bpp) - 1: maxval - (x >> shift) + ) + elif im.info.get("bpp") in (1, 2, 4): + # here we assume that even though the inherent mode is 8-bit grayscale, + # only the lower bpp bits are significant. + # We invert them to match the Palm. + bpp = im.info["bpp"] + im = im.point(lambda x, maxval=(1 << bpp) - 1: maxval - (x & maxval)) + else: + msg = f"cannot write mode {im.mode} as Palm" + raise OSError(msg) + + # we ignore the palette here + im.mode = "P" + rawmode = "P;" + str(bpp) + version = 1 + + elif im.mode == "1": + # monochrome -- write it inverted, as is the Palm standard + rawmode = "1;I" + bpp = 1 + version = 0 + + else: + msg = f"cannot write mode {im.mode} as Palm" + raise OSError(msg) + + # + # make sure image data is available + im.load() + + # write header + + cols = im.size[0] + rows = im.size[1] + + rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2 + transparent_index = 0 + compression_type = _COMPRESSION_TYPES["none"] + + flags = 0 + if im.mode == "P" and "custom-colormap" in im.info: + flags = flags & _FLAGS["custom-colormap"] + colormapsize = 4 * 256 + 2 + colormapmode = im.palette.mode + colormap = im.getdata().getpalette() + else: + colormapsize = 0 + + if "offset" in im.info: + offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4 + else: + offset = 0 + + fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags)) + fp.write(o8(bpp)) + fp.write(o8(version)) + fp.write(o16b(offset)) + fp.write(o8(transparent_index)) + fp.write(o8(compression_type)) + fp.write(o16b(0)) # reserved by Palm + + # now write colormap if necessary + + if colormapsize > 0: + fp.write(o16b(256)) + for i in range(256): + fp.write(o8(i)) + if colormapmode == "RGB": + fp.write( + o8(colormap[3 * i]) + + o8(colormap[3 * i + 1]) + + o8(colormap[3 * i + 2]) + ) + elif colormapmode == "RGBA": + fp.write( + o8(colormap[4 * i]) + + o8(colormap[4 * i + 1]) + + o8(colormap[4 * i + 2]) + ) + + # now convert data to raw form + ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))]) + + if hasattr(fp, "flush"): + fp.flush() + + +# +# -------------------------------------------------------------------- + +Image.register_save("Palm", _save) + +Image.register_extension("Palm", ".palm") + +Image.register_mime("Palm", "image/palm") diff --git a/shared/package-files/4f/4f18d4342a2cc82479c35889ea8efbc8a0785812f28ab56139a00b19876437d9/test_misc.py b/shared/package-files/4f/4f18d4342a2cc82479c35889ea8efbc8a0785812f28ab56139a00b19876437d9/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f61ee6c84def5388ba9cd206851f36950aa2c5 --- /dev/null +++ b/shared/package-files/4f/4f18d4342a2cc82479c35889ea8efbc8a0785812f28ab56139a00b19876437d9/test_misc.py @@ -0,0 +1,151 @@ +from textwrap import dedent +import sys +from subprocess import Popen, PIPE +import os + +from sympy.core.singleton import S +from sympy.testing.pytest import (raises, warns_deprecated_sympy, + skip_under_pyodide) +from sympy.utilities.misc import (translate, replace, ordinal, rawlines, + strlines, as_int, find_executable) +from sympy.external import import_module + +pyodide_js = import_module('pyodide_js') + + +def test_translate(): + abc = 'abc' + assert translate(abc, None, 'a') == 'bc' + assert translate(abc, None, '') == 'abc' + assert translate(abc, {'a': 'x'}, 'c') == 'xb' + assert translate(abc, {'a': 'bc'}, 'c') == 'bcb' + assert translate(abc, {'ab': 'x'}, 'c') == 'x' + assert translate(abc, {'ab': ''}, 'c') == '' + assert translate(abc, {'bc': 'x'}, 'c') == 'ab' + assert translate(abc, {'abc': 'x', 'a': 'y'}) == 'x' + u = chr(4096) + assert translate(abc, 'a', 'x', u) == 'xbc' + assert (u in translate(abc, 'a', u, u)) is True + + +def test_replace(): + assert replace('abc', ('a', 'b')) == 'bbc' + assert replace('abc', {'a': 'Aa'}) == 'Aabc' + assert replace('abc', ('a', 'b'), ('c', 'C')) == 'bbC' + + +def test_ordinal(): + assert ordinal(-1) == '-1st' + assert ordinal(0) == '0th' + assert ordinal(1) == '1st' + assert ordinal(2) == '2nd' + assert ordinal(3) == '3rd' + assert all(ordinal(i).endswith('th') for i in range(4, 21)) + assert ordinal(100) == '100th' + assert ordinal(101) == '101st' + assert ordinal(102) == '102nd' + assert ordinal(103) == '103rd' + assert ordinal(104) == '104th' + assert ordinal(200) == '200th' + assert all(ordinal(i) == str(i) + 'th' for i in range(-220, -203)) + + +def test_rawlines(): + assert rawlines('a a\na') == "dedent('''\\\n a a\n a''')" + assert rawlines('a a') == "'a a'" + assert rawlines(strlines('\\le"ft')) == ( + '(\n' + " '(\\n'\n" + ' \'r\\\'\\\\le"ft\\\'\\n\'\n' + " ')'\n" + ')') + + +def test_strlines(): + q = 'this quote (") is in the middle' + # the following assert rhs was prepared with + # print(rawlines(strlines(q, 10))) + assert strlines(q, 10) == dedent('''\ + ( + 'this quo' + 'te (") i' + 's in the' + ' middle' + )''') + assert q == ( + 'this quo' + 'te (") i' + 's in the' + ' middle' + ) + q = "this quote (') is in the middle" + assert strlines(q, 20) == dedent('''\ + ( + "this quote (') is " + "in the middle" + )''') + assert strlines('\\left') == ( + '(\n' + "r'\\left'\n" + ')') + assert strlines('\\left', short=True) == r"r'\left'" + assert strlines('\\le"ft') == ( + '(\n' + 'r\'\\le"ft\'\n' + ')') + q = 'this\nother line' + assert strlines(q) == rawlines(q) + + +def test_translate_args(): + try: + translate(None, None, None, 'not_none') + except ValueError: + pass # Exception raised successfully + else: + assert False + + assert translate('s', None, None, None) == 's' + + try: + translate('s', 'a', 'bc') + except ValueError: + pass # Exception raised successfully + else: + assert False + + +@skip_under_pyodide("Cannot create subprocess under pyodide.") +def test_debug_output(): + env = os.environ.copy() + env['SYMPY_DEBUG'] = 'True' + cmd = 'from sympy import *; x = Symbol("x"); print(integrate((1-cos(x))/x, x))' + cmdline = [sys.executable, '-c', cmd] + proc = Popen(cmdline, env=env, stdout=PIPE, stderr=PIPE) + out, err = proc.communicate() + out = out.decode('ascii') # utf-8? + err = err.decode('ascii') + expected = 'substituted: -x*(1 - cos(x)), u: 1/x, u_var: _u' + assert expected in err, err + + +def test_as_int(): + raises(ValueError, lambda : as_int(True)) + raises(ValueError, lambda : as_int(1.1)) + raises(ValueError, lambda : as_int([])) + raises(ValueError, lambda : as_int(S.NaN)) + raises(ValueError, lambda : as_int(S.Infinity)) + raises(ValueError, lambda : as_int(S.NegativeInfinity)) + raises(ValueError, lambda : as_int(S.ComplexInfinity)) + # for the following, limited precision makes int(arg) == arg + # but the int value is not necessarily what a user might have + # expected; Q.prime is more nuanced in its response for + # expressions which might be complex representations of an + # integer. This is not -- by design -- as_ints role. + raises(ValueError, lambda : as_int(1e23)) + raises(ValueError, lambda : as_int(S('1.'+'0'*20+'1'))) + assert as_int(True, strict=False) == 1 + +def test_deprecated_find_executable(): + with warns_deprecated_sympy(): + find_executable('python') diff --git a/shared/package-files/4f/4f1bccb3061725d8229bd7eb0699906c2e6afc2bbc48cdfbbd6d9916b7ef1f6d/exceptions.pyi b/shared/package-files/4f/4f1bccb3061725d8229bd7eb0699906c2e6afc2bbc48cdfbbd6d9916b7ef1f6d/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ddb4e83ba77ec06dd74e92aa93bb1e93b4a7713a --- /dev/null +++ b/shared/package-files/4f/4f1bccb3061725d8229bd7eb0699906c2e6afc2bbc48cdfbbd6d9916b7ef1f6d/exceptions.pyi @@ -0,0 +1,50 @@ +from typing import Any + +class HTTPError(Exception): ... +class HTTPWarning(Warning): ... + +class PoolError(HTTPError): + pool: Any + def __init__(self, pool, message) -> None: ... + def __reduce__(self): ... + +class RequestError(PoolError): + url: Any + def __init__(self, pool, url, message) -> None: ... + def __reduce__(self): ... + +class SSLError(HTTPError): ... +class ProxyError(HTTPError): ... +class DecodeError(HTTPError): ... +class ProtocolError(HTTPError): ... + +ConnectionError: Any + +class MaxRetryError(RequestError): + reason: Any + def __init__(self, pool, url, reason=...) -> None: ... + +class HostChangedError(RequestError): + retries: Any + def __init__(self, pool, url, retries=...) -> None: ... + +class TimeoutStateError(HTTPError): ... +class TimeoutError(HTTPError): ... +class ReadTimeoutError(TimeoutError, RequestError): ... +class ConnectTimeoutError(TimeoutError): ... +class EmptyPoolError(PoolError): ... +class ClosedPoolError(PoolError): ... +class LocationValueError(ValueError, HTTPError): ... + +class LocationParseError(LocationValueError): + location: Any + def __init__(self, location) -> None: ... + +class ResponseError(HTTPError): + GENERIC_ERROR: Any + SPECIFIC_ERROR: Any + +class SecurityWarning(HTTPWarning): ... +class InsecureRequestWarning(SecurityWarning): ... +class SystemTimeWarning(SecurityWarning): ... +class InsecurePlatformWarning(SecurityWarning): ... diff --git a/shared/package-files/4f/4f2dc8ffdbfc7837b60edc32ac2f593a220f4abf0ea00cc477382ad8ecf8eb3d/README.txt b/shared/package-files/4f/4f2dc8ffdbfc7837b60edc32ac2f593a220f4abf0ea00cc477382ad8ecf8eb3d/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..76aec58912f00e543d0a623719bc42589478b97a --- /dev/null +++ b/shared/package-files/4f/4f2dc8ffdbfc7837b60edc32ac2f593a220f4abf0ea00cc477382ad8ecf8eb3d/README.txt @@ -0,0 +1,290 @@ +README.txt: an index to idlelib files and the IDLE menu. + +IDLE is Python's Integrated Development and Learning +Environment. The user documentation is part of the Library Reference and +is available in IDLE by selecting Help => IDLE Help. This README documents +idlelib for IDLE developers and curious users. + +IDLELIB FILES lists files alphabetically by category, +with a short description of each. + +IDLE MENU show the menu tree, annotated with the module +or module object that implements the corresponding function. + +This file is descriptive, not prescriptive, and may have errors +and omissions and lag behind changes in idlelib. + + +IDLELIB FILES +============= + +Implementation files not in IDLE MENU are marked (nim). + +Startup +------- +__init__.py # import, does nothing +__main__.py # -m, starts IDLE +idle.bat +idle.py +idle.pyw + +Implementation +-------------- +autocomplete.py # Complete attribute names or filenames. +autocomplete_w.py # Display completions. +autoexpand.py # Expand word with previous word in file. +browser.py # Create module browser window. +calltip.py # Create calltip text. +calltip_w.py # Display calltip. +codecontext.py # Show compound statement headers otherwise not visible. +colorizer.py # Colorize text (nim). +config.py # Load, fetch, and save configuration (nim). +configdialog.py # Display user configuration dialogs. +config_key.py # Change keybindings. +debugger.py # Debug code run from shell or editor; show window. +debugger_r.py # Debug code run in remote process. +debugobj.py # Define class used in stackviewer. +debugobj_r.py # Communicate objects between processes with rpc (nim). +delegator.py # Define base class for delegators (nim). +dynoption.py # Define mutable OptionMenu widget (nim) +editor.py # Define most of editor and utility functions. +filelist.py # Open files and manage list of open windows (nim). +format.py # Define format menu options. +grep.py # Find all occurrences of pattern in multiple files. +help.py # Display IDLE's html doc. +help_about.py # Display About IDLE dialog. +history.py # Get previous or next user input in shell (nim) +hyperparser.py # Parse code around a given index. +iomenu.py # Open, read, and write files +macosx.py # Help IDLE run on Macs (nim). +mainmenu.py # Define most of IDLE menu. +multicall.py # Wrap tk widget to allow multiple calls per event (nim). +outwin.py # Create window for grep output. +parenmatch.py # Match fenceposts: (), [], and {}. +pathbrowser.py # Create path browser window. +percolator.py # Manage delegator stack (nim). +pyparse.py # Give information on code indentation +pyshell.py # Start IDLE, manage shell, complete editor window +query.py # Query user for information +redirector.py # Intercept widget subcommands (for percolator) (nim). +replace.py # Search and replace pattern in text. +rpc.py # Communicate between idle and user processes (nim). +run.py # Manage user code execution subprocess. +runscript.py # Check and run user code. +scrolledlist.py # Define scrolledlist widget for IDLE (nim). +search.py # Search for pattern in text. +searchbase.py # Define base for search, replace, and grep dialogs. +searchengine.py # Define engine for all 3 search dialogs. +sidebar.py # Define line number and shell prompt sidebars. +squeezer.py # Squeeze long shell output (nim). +stackviewer.py # View stack after exception. +statusbar.py # Define status bar for windows (nim). +tabbedpages.py # Define tabbed pages widget (nim). +textview.py # Define read-only text widget (nim). +tooltip.py # Define popups for calltips, squeezer (nim). +tree.py # Define tree widget, used in browsers (nim). +undo.py # Manage undo stack. +util.py # Define common objects imported elsewhere (nim). +windows.py # Manage window list and define listed top level. +zoomheight.py # Zoom window to full height of screen. +zzdummy.py # Example extension. + +Configuration +------------- +config-extensions.def # Defaults for extensions +config-highlight.def # Defaults for colorizing +config-keys.def # Defaults for key bindings +config-main.def # Defaults for font and general tabs + +Text +---- +CREDITS.txt # not maintained, displayed by About IDLE +HISTORY.txt # NEWS up to July 2001 +NEWS.txt # commits, displayed by About IDLE +NEWS2.txt # commits to Python2 +README.txt # this file, displayed by About IDLE +TODO.txt # needs review +extend.txt # about writing extensions +help.html # copy of idle.html in docs, displayed by IDLE Help + +Subdirectories +-------------- +Icons # small image files +idle_test # files for human test and automated unit tests + + +IDLE MENUS +========== + +Top level items and most submenu items are defined in mainmenu. +Extensions add submenu items when active. The names given are +found, quoted, in one of these modules, paired with a '<>'. +Each pseudoevent is bound to an event handler. Some event handlers +call another function that does the actual work. The annotations below +are intended to at least give the module where the actual work is done. +'eEW' = editor.EditorWindow + +File + New File # eEW.new_callback + Open... # iomenu.open + Open Module # eEw.open_module + Recent Files + Class Browser # eEW.open_class_browser, browser.ClassBrowser + Path Browser # eEW.open_path_browser, pathbrowser + --- + Save # iomenu.save + Save As... # iomenu.save_as + Save Copy As... # iomenu.save_a_copy + --- + Print Window # iomenu.print_window + --- + Close # eEW.close_event + Exit # flist.close_all_callback (bound in eEW) + +Edit + Undo # undodelegator + Redo # undodelegator + --- # eEW.right_menu_event + Cut # eEW.cut + Copy # eEW.copy + Paste # eEW.past + Select All # eEW.select_all (+ see eEW.remove_selection) + --- # Next 5 items use searchengine; dialogs use searchbase + Find # eEW.find_event, search.SearchDialog.find + Find Again # eEW.find_again_event, sSD.find_again + Find Selection # eEW.find_selection_event, sSD.find_selection + Find in Files... # eEW.find_in_files_event, grep + Replace... # eEW.replace_event, replace.ReplaceDialog.replace + Go to Line # eEW.goto_line_event + Show Completions # autocomplete extension and autocompleteWidow (&HP) + Expand Word # autoexpand extension + Show call tip # Calltips extension and CalltipWindow (& Hyperparser) + Show surrounding parens # parenmatch (& Hyperparser) + +Format (Editor only) [fFR = format.FormatRegion] + Format Paragraph # format.FormatParagraph.format_paragraph_event + Indent Region # fFR.indent_region_event + Dedent Region # fFR.dedent_region_event + Comment Out Reg. # fFR.comment_region_event + Uncomment Region # fFR.uncomment_region_event + Tabify Region # fFR.tabify_region_event + Untabify Region # fFR.untabify_region_event + Toggle Tabs # format.Indents.toggle_tabs_event + New Indent Width # format.Indents.change_indentwidth_event + Strip tailing whitespace # format.rstrip + Zin # zzdummy + Zout # zzdummy + +Run (Editor only) + Run Module # runscript.ScriptBinding.run_module_event + Run... Customized # runscript.ScriptBinding.run_custom_event + Check Module # runscript.ScriptBinding.check_module_event + Python Shell # pyshell.Pyshell, pyshell.ModifiedInterpreter + +Shell # pyshell + View Last Restart # pyshell.PyShell.view_restart_mark + Restart Shell # pyshell.PyShell.restart_shell + Previous History # history.History.history_prev + Next History # history.History.history_next + Interrupt Execution # pyshell.PyShell.cancel_callback + +Debug (Shell only) + Go to File/Line # outwin.OutputWindow.goto_file_line + debugger # debugger, debugger_r, PyShell.toggle_debugger + Stack Viewer # stackviewer, PyShell.open_stack_viewer + Auto-open Stack Viewer # stackviewer + +Options + Configure IDLE # eEW.config_dialog, config, configdialog (cd) + (Parts of the dialog) + Buttons # cd.ConfigDialog + Font tab # cd.FontPage, config-main.def + Highlight tab # cd.HighPage, query, config-highlight.def + Keys tab # cd.KeysPage, query, config_key, config_keys.def + Windows tab # cd.WinPage, config_main.def + Shell/Ed tab # cd.ShedPage, config-main.def + Extensions tab # config-extensions.def, corresponding .py files + --- + ... Code Context # codecontext + ... Line Numbers # sidebar + Zoomheight # zoomheight + +Window + # windows + +Help + About IDLE # eEW.about_dialog, help_about.AboutDialog + --- + IDLE Help # eEW.help_dialog, help.show_idlehelp + Python Docs # eEW.python_docs + Turtle Demo # eEW.open_turtle_demo + --- + + + (right click) + Defined in editor, PyShell.pyshell + Cut + Copy + Paste + --- + Go to file/line (shell and output only) + Set Breakpoint (editor only) + Clear Breakpoint (editor only) + Defined in debugger + Go to source line + Show stack frame + + +Center Insert # eEW.center_insert_event + + +OTHER TOPICS +============ + +Generally use PEP 8. + +import statements +----------------- +Put imports at the top, unless there is a good reason otherwise. +PEP 8 says to group stdlib, 3rd-party dependencies, and package imports. +For idlelib, the groups are general stdlib, tkinter, and idlelib. +Sort modules within each group, except that tkinter.ttk follows tkinter. +Sort 'from idlelib import mod1' and 'from idlelib.mod2 import object' +together by module, ignoring within module objects. +Put 'import __main__' after other idlelib imports. + +Imports only needed for testing are put not at the top but in an +htest function def or "if __name__ == '__main__'" clause. + +Within module imports like "from idlelib.mod import class" may cause +circular imports to deadlock. Even without this, circular imports may +require at least one of the imports to be delayed until a function call. + +What's New entries +------------------ + +Repository directory Doc/whatsnew/ has a file 3.n.rst for each 3.n +Python version. For the first entry in each file, add subsection +'IDLE and idlelib', in alphabetical position, to the 'Improved Modules' +section. For the rest of cpython, entries to 3.(n+1).rst begin with +the release of 3.n.0b1. For IDLE, entries for features backported from +'main' to '3.n' during its beta period do not got in 3.(n+1).rst. The +latter usually gets its first entry during the 3.n.0 candidate period +or after the 3.n.0 release. + +When, as per PEP 434, feature changes are backported, entries are placed +in the 3.n.rst file *in the main branch* for each Python version n that +gets the backport. (Note: the format of entries have varied between +versions.) Add a line "New in 3.n maintenance releases." before the +first back-ported feature after 3.n.0 is released. Since each older +version file gets a different number of backports, it is easiest to +make a separate PR for each file and label it with the backports +needed. + +Github repository and issues +---------------------------- + +The CPython repository is https://github.com/python/cpython. The +IDLE Issues listing is https://github.com/orgs/python/projects/31. +The main classification is by Topic, based on the IDLE menu. View the +topics list by clicking the [<]] button in the upper right. diff --git a/shared/package-files/4f/4f2f044fb9cb238249793a833323f4a441fd4158fdc6cec1a49919ae7ae968f6/type_fwd.h b/shared/package-files/4f/4f2f044fb9cb238249793a833323f4a441fd4158fdc6cec1a49919ae7ae968f6/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..b0d3afa922f789f4f9a8a0b2b435b3ebe0456d42 --- /dev/null +++ b/shared/package-files/4f/4f2f044fb9cb238249793a833323f4a441fd4158fdc6cec1a49919ae7ae968f6/type_fwd.h @@ -0,0 +1,68 @@ +// 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 + +namespace arrow { +namespace ipc { + +enum class MetadataVersion : char { + /// 0.1.0 + V1, + + /// 0.2.0 + V2, + + /// 0.3.0 to 0.7.1 + V3, + + /// 0.8.0 to 0.17.0 + V4, + + /// >= 1.0.0 + V5 +}; + +class Message; +enum class MessageType { + NONE, + SCHEMA, + DICTIONARY_BATCH, + RECORD_BATCH, + TENSOR, + SPARSE_TENSOR +}; + +struct IpcReadOptions; +struct IpcWriteOptions; + +class MessageReader; + +class RecordBatchStreamReader; +class RecordBatchFileReader; +class RecordBatchWriter; + +class DictionaryFieldMapper; +class DictionaryMemo; + +namespace feather { + +class Reader; + +} // namespace feather +} // namespace ipc +} // namespace arrow diff --git a/shared/package-files/4f/4f30bd5229f471cca4ee81b9cfb1d03e144fe88d3febe1c2dbc0ce5e9cd46731/_backward_state.py b/shared/package-files/4f/4f30bd5229f471cca4ee81b9cfb1d03e144fe88d3febe1c2dbc0ce5e9cd46731/_backward_state.py new file mode 100644 index 0000000000000000000000000000000000000000..9c742431857c33af22dbc1ad73b5bdfcf6124b9c --- /dev/null +++ b/shared/package-files/4f/4f30bd5229f471cca4ee81b9cfb1d03e144fe88d3febe1c2dbc0ce5e9cd46731/_backward_state.py @@ -0,0 +1,27 @@ +import torch.fx + + +class BackwardState: + """ + BackwardState is used to pass Python hooks from the forwards pass + into the backwards pass in Dynamo+Compiled Autograd. + + It is created by TorchDynamo and has special handling there. + Dynamo will pass an empty BackwardState to the forwards, then populate + members on it (via setattr) only after the forwards graph is finished. + Later on, in CompileAutograd we will inline and add the needed guards + on the BackwardState. + + BackwardState is identified and has special handling in AOTAutograd. + During AOTAutograd: + 1) BackwardState is an input to the forwards graph + 2) It must only be used in the backwards + 3) It will be empty in the forwards + 4) In the forwards we add a wrapper to save it + 5) In the backwards it becomes an input + 6) There can only be one per graph + + BackwardState requires CompiledAutograd. + """ + + proxy: torch.fx.Proxy diff --git a/shared/package-files/4f/4f3102899a0228d32a83053be9c3c278a58506a696bc074b31ebf9fdb0a4858f/enums.py b/shared/package-files/4f/4f3102899a0228d32a83053be9c3c278a58506a696bc074b31ebf9fdb0a4858f/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..5e3e198233698f2b007489dd299cecb87d971067 --- /dev/null +++ b/shared/package-files/4f/4f3102899a0228d32a83053be9c3c278a58506a696bc074b31ebf9fdb0a4858f/enums.py @@ -0,0 +1,85 @@ +""" +All of the Enums that are used throughout the chardet package. + +:author: Dan Blanchard (dan.blanchard@gmail.com) +""" + +from enum import Enum, Flag + + +class InputState: + """ + This enum represents the different states a universal detector can be in. + """ + + PURE_ASCII = 0 + ESC_ASCII = 1 + HIGH_BYTE = 2 + + +class LanguageFilter(Flag): + """ + This enum represents the different language filters we can apply to a + ``UniversalDetector``. + """ + + NONE = 0x00 + CHINESE_SIMPLIFIED = 0x01 + CHINESE_TRADITIONAL = 0x02 + JAPANESE = 0x04 + KOREAN = 0x08 + NON_CJK = 0x10 + ALL = 0x1F + CHINESE = CHINESE_SIMPLIFIED | CHINESE_TRADITIONAL + CJK = CHINESE | JAPANESE | KOREAN + + +class ProbingState(Enum): + """ + This enum represents the different states a prober can be in. + """ + + DETECTING = 0 + FOUND_IT = 1 + NOT_ME = 2 + + +class MachineState: + """ + This enum represents the different states a state machine can be in. + """ + + START = 0 + ERROR = 1 + ITS_ME = 2 + + +class SequenceLikelihood: + """ + This enum represents the likelihood of a character following the previous one. + """ + + NEGATIVE = 0 + UNLIKELY = 1 + LIKELY = 2 + POSITIVE = 3 + + @classmethod + def get_num_categories(cls) -> int: + """:returns: The number of likelihood categories in the enum.""" + return 4 + + +class CharacterCategory: + """ + This enum represents the different categories language models for + ``SingleByteCharsetProber`` put characters into. + + Anything less than CONTROL is considered a letter. + """ + + UNDEFINED = 255 + LINE_BREAK = 254 + SYMBOL = 253 + DIGIT = 252 + CONTROL = 251 diff --git a/shared/package-files/4f/4f31fe19fd0981b3ff3a078a61b57c65b257bd6b7555eb5d52be82ff38949738/struct_arrays.sav b/shared/package-files/4f/4f31fe19fd0981b3ff3a078a61b57c65b257bd6b7555eb5d52be82ff38949738/struct_arrays.sav new file mode 100644 index 0000000000000000000000000000000000000000..40c9cd330e0c731968d71dbbfeae9bd8c4a745a2 Binary files /dev/null and b/shared/package-files/4f/4f31fe19fd0981b3ff3a078a61b57c65b257bd6b7555eb5d52be82ff38949738/struct_arrays.sav differ diff --git a/shared/package-files/4f/4f32e1518be3270f4db80136fac0031c385dd3ce133faa534f141cf459c6113a/sv.msg b/shared/package-files/4f/4f32e1518be3270f4db80136fac0031c385dd3ce133faa534f141cf459c6113a/sv.msg new file mode 100644 index 0000000000000000000000000000000000000000..f7a67c6eabd1e1d5968114fb928a3bfc3f981cd0 --- /dev/null +++ b/shared/package-files/4f/4f32e1518be3270f4db80136fac0031c385dd3ce133faa534f141cf459c6113a/sv.msg @@ -0,0 +1,52 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset sv DAYS_OF_WEEK_ABBREV [list \ + "s\u00f6"\ + "m\u00e5"\ + "ti"\ + "on"\ + "to"\ + "fr"\ + "l\u00f6"] + ::msgcat::mcset sv DAYS_OF_WEEK_FULL [list \ + "s\u00f6ndag"\ + "m\u00e5ndag"\ + "tisdag"\ + "onsdag"\ + "torsdag"\ + "fredag"\ + "l\u00f6rdag"] + ::msgcat::mcset sv MONTHS_ABBREV [list \ + "jan"\ + "feb"\ + "mar"\ + "apr"\ + "maj"\ + "jun"\ + "jul"\ + "aug"\ + "sep"\ + "okt"\ + "nov"\ + "dec"\ + ""] + ::msgcat::mcset sv MONTHS_FULL [list \ + "januari"\ + "februari"\ + "mars"\ + "april"\ + "maj"\ + "juni"\ + "juli"\ + "augusti"\ + "september"\ + "oktober"\ + "november"\ + "december"\ + ""] + ::msgcat::mcset sv BCE "f.Kr." + ::msgcat::mcset sv CE "e.Kr." + ::msgcat::mcset sv DATE_FORMAT "%Y-%m-%d" + ::msgcat::mcset sv TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset sv DATE_TIME_FORMAT "%Y-%m-%d %H:%M:%S %z" +} diff --git a/shared/package-files/4f/4f33480f6fdd306e828564b038c22a945f4059c735523b630872cd993d2f9411/test_isna.py b/shared/package-files/4f/4f33480f6fdd306e828564b038c22a945f4059c735523b630872cd993d2f9411/test_isna.py new file mode 100644 index 0000000000000000000000000000000000000000..7e324aa86a052246a074950082e272fee7e505e3 --- /dev/null +++ b/shared/package-files/4f/4f33480f6fdd306e828564b038c22a945f4059c735523b630872cd993d2f9411/test_isna.py @@ -0,0 +1,35 @@ +""" +We also test Series.notna in this file. +""" +import numpy as np + +from pandas import ( + Period, + Series, +) +import pandas._testing as tm + + +class TestIsna: + def test_isna_period_dtype(self): + # GH#13737 + ser = Series([Period("2011-01", freq="M"), Period("NaT", freq="M")]) + + expected = Series([False, True]) + + result = ser.isna() + tm.assert_series_equal(result, expected) + + result = ser.notna() + tm.assert_series_equal(result, ~expected) + + def test_isna(self): + ser = Series([0, 5.4, 3, np.nan, -0.001]) + expected = Series([False, False, False, True, False]) + tm.assert_series_equal(ser.isna(), expected) + tm.assert_series_equal(ser.notna(), ~expected) + + ser = Series(["hi", "", np.nan]) + expected = Series([False, False, True]) + tm.assert_series_equal(ser.isna(), expected) + tm.assert_series_equal(ser.notna(), ~expected) diff --git a/shared/package-files/4f/4f362e5abe38fba76f37fa91b38233f65acd60b2c6de2e34836bf82351a614a4/slice_inverse.h b/shared/package-files/4f/4f362e5abe38fba76f37fa91b38233f65acd60b2c6de2e34836bf82351a614a4/slice_inverse.h new file mode 100644 index 0000000000000000000000000000000000000000..d83e223301d6456243d64e62a044a46a305949f9 --- /dev/null +++ b/shared/package-files/4f/4f362e5abe38fba76f37fa91b38233f65acd60b2c6de2e34836bf82351a614a4/slice_inverse.h @@ -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::slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) +inline at::Tensor slice_inverse(const at::Tensor & self, const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, int64_t step=1) { + return at::_ops::slice_inverse::call(self, 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); +} +namespace symint { + template ::value>> + at::Tensor slice_inverse(const at::Tensor & self, const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, int64_t step=1) { + return at::_ops::slice_inverse::call(self, 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 slice_inverse_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, c10::SymInt step=1) { + return at::_ops::slice_inverse::call(self, src, dim, start, end, step); +} +namespace symint { + template ::value>> + at::Tensor slice_inverse(const at::Tensor & self, const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, c10::SymInt step=1) { + return at::_ops::slice_inverse::call(self, src, dim, start, end, step); + } +} + +} diff --git a/shared/package-files/4f/4f379d98d6a40eed00909edaefbf957cfc1d714aa8db1114746bc42e684da65c/replication_pad3d_backward_cuda_dispatch.h b/shared/package-files/4f/4f379d98d6a40eed00909edaefbf957cfc1d714aa8db1114746bc42e684da65c/replication_pad3d_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..608763284f8db350b9677e6e5ebb6e401fd1cca2 --- /dev/null +++ b/shared/package-files/4f/4f379d98d6a40eed00909edaefbf957cfc1d714aa8db1114746bc42e684da65c/replication_pad3d_backward_cuda_dispatch.h @@ -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 cuda { + +TORCH_API at::Tensor replication_pad3d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding); +TORCH_API at::Tensor replication_pad3d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); +TORCH_API at::Tensor & replication_pad3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding); +TORCH_API at::Tensor & replication_pad3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input); +TORCH_API at::Tensor & replication_pad3d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); +TORCH_API at::Tensor & replication_pad3d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/4f/4f39f415c55c2a66e3628b1e5249318eae2608e846d9c3df0f2a3d7d009854f2/test_onenormest.py b/shared/package-files/4f/4f39f415c55c2a66e3628b1e5249318eae2608e846d9c3df0f2a3d7d009854f2/test_onenormest.py new file mode 100644 index 0000000000000000000000000000000000000000..d306e8177568d8db31189a5c67b5862e37e8a0fc --- /dev/null +++ b/shared/package-files/4f/4f39f415c55c2a66e3628b1e5249318eae2608e846d9c3df0f2a3d7d009854f2/test_onenormest.py @@ -0,0 +1,252 @@ +"""Test functions for the sparse.linalg._onenormest module +""" + +import numpy as np +from numpy.testing import assert_allclose, assert_equal, assert_ +import pytest +import scipy.linalg +import scipy.sparse.linalg +from scipy.sparse.linalg._onenormest import _onenormest_core, _algorithm_2_2 + + +class MatrixProductOperator(scipy.sparse.linalg.LinearOperator): + """ + This is purely for onenormest testing. + """ + + def __init__(self, A, B): + if A.ndim != 2 or B.ndim != 2: + raise ValueError('expected ndarrays representing matrices') + if A.shape[1] != B.shape[0]: + raise ValueError('incompatible shapes') + self.A = A + self.B = B + self.ndim = 2 + self.shape = (A.shape[0], B.shape[1]) + + def _matvec(self, x): + return np.dot(self.A, np.dot(self.B, x)) + + def _rmatvec(self, x): + return np.dot(np.dot(x, self.A), self.B) + + def _matmat(self, X): + return np.dot(self.A, np.dot(self.B, X)) + + @property + def T(self): + return MatrixProductOperator(self.B.T, self.A.T) + + +class TestOnenormest: + + @pytest.mark.xslow + def test_onenormest_table_3_t_2(self): + # This will take multiple seconds if your computer is slow like mine. + # It is stochastic, so the tolerance could be too strict. + np.random.seed(1234) + t = 2 + n = 100 + itmax = 5 + nsamples = 5000 + observed = [] + expected = [] + nmult_list = [] + nresample_list = [] + for i in range(nsamples): + A = scipy.linalg.inv(np.random.randn(n, n)) + est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax) + observed.append(est) + expected.append(scipy.linalg.norm(A, 1)) + nmult_list.append(nmults) + nresample_list.append(nresamples) + observed = np.array(observed, dtype=float) + expected = np.array(expected, dtype=float) + relative_errors = np.abs(observed - expected) / expected + + # check the mean underestimation ratio + underestimation_ratio = observed / expected + assert_(0.99 < np.mean(underestimation_ratio) < 1.0) + + # check the max and mean required column resamples + assert_equal(np.max(nresample_list), 2) + assert_(0.05 < np.mean(nresample_list) < 0.2) + + # check the proportion of norms computed exactly correctly + nexact = np.count_nonzero(relative_errors < 1e-14) + proportion_exact = nexact / float(nsamples) + assert_(0.9 < proportion_exact < 0.95) + + # check the average number of matrix*vector multiplications + assert_(3.5 < np.mean(nmult_list) < 4.5) + + @pytest.mark.xslow + def test_onenormest_table_4_t_7(self): + # This will take multiple seconds if your computer is slow like mine. + # It is stochastic, so the tolerance could be too strict. + np.random.seed(1234) + t = 7 + n = 100 + itmax = 5 + nsamples = 5000 + observed = [] + expected = [] + nmult_list = [] + nresample_list = [] + for i in range(nsamples): + A = np.random.randint(-1, 2, size=(n, n)) + est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax) + observed.append(est) + expected.append(scipy.linalg.norm(A, 1)) + nmult_list.append(nmults) + nresample_list.append(nresamples) + observed = np.array(observed, dtype=float) + expected = np.array(expected, dtype=float) + relative_errors = np.abs(observed - expected) / expected + + # check the mean underestimation ratio + underestimation_ratio = observed / expected + assert_(0.90 < np.mean(underestimation_ratio) < 0.99) + + # check the required column resamples + assert_equal(np.max(nresample_list), 0) + + # check the proportion of norms computed exactly correctly + nexact = np.count_nonzero(relative_errors < 1e-14) + proportion_exact = nexact / float(nsamples) + assert_(0.15 < proportion_exact < 0.25) + + # check the average number of matrix*vector multiplications + assert_(3.5 < np.mean(nmult_list) < 4.5) + + def test_onenormest_table_5_t_1(self): + # "note that there is no randomness and hence only one estimate for t=1" + t = 1 + n = 100 + itmax = 5 + alpha = 1 - 1e-6 + A = -scipy.linalg.inv(np.identity(n) + alpha*np.eye(n, k=1)) + first_col = np.array([1] + [0]*(n-1)) + first_row = np.array([(-alpha)**i for i in range(n)]) + B = -scipy.linalg.toeplitz(first_col, first_row) + assert_allclose(A, B) + est, v, w, nmults, nresamples = _onenormest_core(B, B.T, t, itmax) + exact_value = scipy.linalg.norm(B, 1) + underest_ratio = est / exact_value + assert_allclose(underest_ratio, 0.05, rtol=1e-4) + assert_equal(nmults, 11) + assert_equal(nresamples, 0) + # check the non-underscored version of onenormest + est_plain = scipy.sparse.linalg.onenormest(B, t=t, itmax=itmax) + assert_allclose(est, est_plain) + + @pytest.mark.xslow + def test_onenormest_table_6_t_2(self): + #TODO this test seems to give estimates that match the table, + #TODO even though no attempt has been made to deal with + #TODO complex numbers in the one-norm estimation. + # This will take multiple seconds if your computer is slow like mine. + # It is stochastic, so the tolerance could be too strict. + np.random.seed(1234) + t = 2 + n = 100 + itmax = 5 + nsamples = 5000 + observed = [] + expected = [] + nmult_list = [] + nresample_list = [] + for i in range(nsamples): + A_inv = np.random.rand(n, n) + 1j * np.random.rand(n, n) + A = scipy.linalg.inv(A_inv) + est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax) + observed.append(est) + expected.append(scipy.linalg.norm(A, 1)) + nmult_list.append(nmults) + nresample_list.append(nresamples) + observed = np.array(observed, dtype=float) + expected = np.array(expected, dtype=float) + relative_errors = np.abs(observed - expected) / expected + + # check the mean underestimation ratio + underestimation_ratio = observed / expected + underestimation_ratio_mean = np.mean(underestimation_ratio) + assert_(0.90 < underestimation_ratio_mean < 0.99) + + # check the required column resamples + max_nresamples = np.max(nresample_list) + assert_equal(max_nresamples, 0) + + # check the proportion of norms computed exactly correctly + nexact = np.count_nonzero(relative_errors < 1e-14) + proportion_exact = nexact / float(nsamples) + assert_(0.7 < proportion_exact < 0.8) + + # check the average number of matrix*vector multiplications + mean_nmult = np.mean(nmult_list) + assert_(4 < mean_nmult < 5) + + def _help_product_norm_slow(self, A, B): + # for profiling + C = np.dot(A, B) + return scipy.linalg.norm(C, 1) + + def _help_product_norm_fast(self, A, B): + # for profiling + t = 2 + itmax = 5 + D = MatrixProductOperator(A, B) + est, v, w, nmults, nresamples = _onenormest_core(D, D.T, t, itmax) + return est + + @pytest.mark.slow + def test_onenormest_linear_operator(self): + # Define a matrix through its product A B. + # Depending on the shapes of A and B, + # it could be easy to multiply this product by a small matrix, + # but it could be annoying to look at all of + # the entries of the product explicitly. + np.random.seed(1234) + n = 6000 + k = 3 + A = np.random.randn(n, k) + B = np.random.randn(k, n) + fast_estimate = self._help_product_norm_fast(A, B) + exact_value = self._help_product_norm_slow(A, B) + assert_(fast_estimate <= exact_value <= 3*fast_estimate, + f'fast: {fast_estimate:g}\nexact:{exact_value:g}') + + def test_returns(self): + np.random.seed(1234) + A = scipy.sparse.rand(50, 50, 0.1) + + s0 = scipy.linalg.norm(A.toarray(), 1) + s1, v = scipy.sparse.linalg.onenormest(A, compute_v=True) + s2, w = scipy.sparse.linalg.onenormest(A, compute_w=True) + s3, v2, w2 = scipy.sparse.linalg.onenormest(A, compute_w=True, compute_v=True) + + assert_allclose(s1, s0, rtol=1e-9) + assert_allclose(np.linalg.norm(A.dot(v), 1), s0*np.linalg.norm(v, 1), rtol=1e-9) + assert_allclose(A.dot(v), w, rtol=1e-9) + + +class TestAlgorithm_2_2: + + @pytest.mark.thread_unsafe + def test_randn_inv(self): + rng = np.random.RandomState(1234) + n = 20 + nsamples = 100 + for i in range(nsamples): + + # Choose integer t uniformly between 1 and 3 inclusive. + t = rng.randint(1, 4) + + # Choose n uniformly between 10 and 40 inclusive. + n = rng.randint(10, 41) + + # Sample the inverse of a matrix with random normal entries. + A = scipy.linalg.inv(rng.randn(n, n)) + + # Compute the 1-norm bounds. + g, ind = _algorithm_2_2(A, A.T, t) diff --git a/shared/package-files/4f/4f43344512167c88123ae09f5115682a9e3cfb529b560dbde8cbfde431a0525b/dg211 b/shared/package-files/4f/4f43344512167c88123ae09f5115682a9e3cfb529b560dbde8cbfde431a0525b/dg211 new file mode 100644 index 0000000000000000000000000000000000000000..394e4a73b2c43eb564a05abfbec66e031395a494 Binary files /dev/null and b/shared/package-files/4f/4f43344512167c88123ae09f5115682a9e3cfb529b560dbde8cbfde431a0525b/dg211 differ diff --git a/shared/package-files/4f/4f457335f1b992d0a0313f0f63e2529954e85545d8c58f53ef689a610f719a69/langgreekmodel.pyi b/shared/package-files/4f/4f457335f1b992d0a0313f0f63e2529954e85545d8c58f53ef689a610f719a69/langgreekmodel.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f0fa3e8c21d342ce32c18279af1efa0d29389959 --- /dev/null +++ b/shared/package-files/4f/4f457335f1b992d0a0313f0f63e2529954e85545d8c58f53ef689a610f719a69/langgreekmodel.pyi @@ -0,0 +1,9 @@ +from typing import Tuple + +from . import _LangModelType + +Latin7_char_to_order_map: Tuple[int, ...] +win1253_char_to_order_map: Tuple[int, ...] +GreekLangModel: Tuple[int, ...] +Latin7GreekModel: _LangModelType +Win1253GreekModel: _LangModelType diff --git a/shared/package-files/4f/4f47e644834bb5941d24bb94ab577b8317030992c19e532a16023e37ef46b614/reflection_pad2d_backward_cuda_dispatch.h b/shared/package-files/4f/4f47e644834bb5941d24bb94ab577b8317030992c19e532a16023e37ef46b614/reflection_pad2d_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..fefdb41e28e893b394bcc3bd5145148e29dd3e76 --- /dev/null +++ b/shared/package-files/4f/4f47e644834bb5941d24bb94ab577b8317030992c19e532a16023e37ef46b614/reflection_pad2d_backward_cuda_dispatch.h @@ -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 cuda { + +TORCH_API at::Tensor reflection_pad2d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding); +TORCH_API at::Tensor reflection_pad2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); +TORCH_API at::Tensor & reflection_pad2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding); +TORCH_API at::Tensor & reflection_pad2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input); +TORCH_API at::Tensor & reflection_pad2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); +TORCH_API at::Tensor & reflection_pad2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/4f/4f49ba5ebcf1944b51bad1ae51c60108ed60e0218a0fbce5ff7fc85b0d8ac17d/teraterm2.3 b/shared/package-files/4f/4f49ba5ebcf1944b51bad1ae51c60108ed60e0218a0fbce5ff7fc85b0d8ac17d/teraterm2.3 new file mode 100644 index 0000000000000000000000000000000000000000..6f0d9d7a586af98210eb772e664fbc03e9df225d Binary files /dev/null and b/shared/package-files/4f/4f49ba5ebcf1944b51bad1ae51c60108ed60e0218a0fbce5ff7fc85b0d8ac17d/teraterm2.3 differ diff --git a/shared/package-files/4f/4f5277c8a449ce11ad5e115e35473dddd46f9252b0e0d71b7b44edac9276e196/configTools.py b/shared/package-files/4f/4f5277c8a449ce11ad5e115e35473dddd46f9252b0e0d71b7b44edac9276e196/configTools.py new file mode 100644 index 0000000000000000000000000000000000000000..d1899bab9006d4b822dd617f39427d8aea441e94 --- /dev/null +++ b/shared/package-files/4f/4f5277c8a449ce11ad5e115e35473dddd46f9252b0e0d71b7b44edac9276e196/configTools.py @@ -0,0 +1,350 @@ +""" +Code of the config system; not related to fontTools or fonts in particular. + +The options that are specific to fontTools are in :mod:`fontTools.config`. + +To create your own config system, you need to create an instance of +:class:`Options`, and a subclass of :class:`AbstractConfig` with its +``options`` class variable set to your instance of Options. + +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass +from typing import ( + Any, + Callable, + ClassVar, + Dict, + Iterable, + Mapping, + MutableMapping, + Optional, + Set, + Union, +) + +log = logging.getLogger(__name__) + +__all__ = [ + "AbstractConfig", + "ConfigAlreadyRegisteredError", + "ConfigError", + "ConfigUnknownOptionError", + "ConfigValueParsingError", + "ConfigValueValidationError", + "Option", + "Options", +] + + +class ConfigError(Exception): + """Base exception for the config module.""" + + +class ConfigAlreadyRegisteredError(ConfigError): + """Raised when a module tries to register a configuration option that + already exists. + + Should not be raised too much really, only when developing new fontTools + modules. + """ + + def __init__(self, name): + super().__init__(f"Config option {name} is already registered.") + + +class ConfigValueParsingError(ConfigError): + """Raised when a configuration value cannot be parsed.""" + + def __init__(self, name, value): + super().__init__( + f"Config option {name}: value cannot be parsed (given {repr(value)})" + ) + + +class ConfigValueValidationError(ConfigError): + """Raised when a configuration value cannot be validated.""" + + def __init__(self, name, value): + super().__init__( + f"Config option {name}: value is invalid (given {repr(value)})" + ) + + +class ConfigUnknownOptionError(ConfigError): + """Raised when a configuration option is unknown.""" + + def __init__(self, option_or_name): + name = ( + f"'{option_or_name.name}' (id={id(option_or_name)})>" + if isinstance(option_or_name, Option) + else f"'{option_or_name}'" + ) + super().__init__(f"Config option {name} is unknown") + + +# eq=False because Options are unique, not fungible objects +@dataclass(frozen=True, eq=False) +class Option: + name: str + """Unique name identifying the option (e.g. package.module:MY_OPTION).""" + help: str + """Help text for this option.""" + default: Any + """Default value for this option.""" + parse: Callable[[str], Any] + """Turn input (e.g. string) into proper type. Only when reading from file.""" + validate: Optional[Callable[[Any], bool]] = None + """Return true if the given value is an acceptable value.""" + + @staticmethod + def parse_optional_bool(v: str) -> Optional[bool]: + s = str(v).lower() + if s in {"0", "no", "false"}: + return False + if s in {"1", "yes", "true"}: + return True + if s in {"auto", "none"}: + return None + raise ValueError("invalid optional bool: {v!r}") + + @staticmethod + def validate_optional_bool(v: Any) -> bool: + return v is None or isinstance(v, bool) + + +class Options(Mapping): + """Registry of available options for a given config system. + + Define new options using the :meth:`register()` method. + + Access existing options using the Mapping interface. + """ + + __options: Dict[str, Option] + + def __init__(self, other: "Options" = None) -> None: + self.__options = {} + if other is not None: + for option in other.values(): + self.register_option(option) + + def register( + self, + name: str, + help: str, + default: Any, + parse: Callable[[str], Any], + validate: Optional[Callable[[Any], bool]] = None, + ) -> Option: + """Create and register a new option.""" + return self.register_option(Option(name, help, default, parse, validate)) + + def register_option(self, option: Option) -> Option: + """Register a new option.""" + name = option.name + if name in self.__options: + raise ConfigAlreadyRegisteredError(name) + self.__options[name] = option + return option + + def is_registered(self, option: Option) -> bool: + """Return True if the same option object is already registered.""" + return self.__options.get(option.name) is option + + def __getitem__(self, key: str) -> Option: + return self.__options.__getitem__(key) + + def __iter__(self) -> Iterator[str]: + return self.__options.__iter__() + + def __len__(self) -> int: + return self.__options.__len__() + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}({{\n" + + "".join( + f" {k!r}: Option(default={v.default!r}, ...),\n" + for k, v in self.__options.items() + ) + + "})" + ) + + +_USE_GLOBAL_DEFAULT = object() + + +class AbstractConfig(MutableMapping): + """ + Create a set of config values, optionally pre-filled with values from + the given dictionary or pre-existing config object. + + The class implements the MutableMapping protocol keyed by option name (`str`). + For convenience its methods accept either Option or str as the key parameter. + + .. seealso:: :meth:`set()` + + This config class is abstract because it needs its ``options`` class + var to be set to an instance of :class:`Options` before it can be + instanciated and used. + + .. code:: python + + class MyConfig(AbstractConfig): + options = Options() + + MyConfig.register_option( "test:option_name", "This is an option", 0, int, lambda v: isinstance(v, int)) + + cfg = MyConfig({"test:option_name": 10}) + + """ + + options: ClassVar[Options] + + @classmethod + def register_option( + cls, + name: str, + help: str, + default: Any, + parse: Callable[[str], Any], + validate: Optional[Callable[[Any], bool]] = None, + ) -> Option: + """Register an available option in this config system.""" + return cls.options.register( + name, help=help, default=default, parse=parse, validate=validate + ) + + _values: Dict[str, Any] + + def __init__( + self, + values: Union[ + AbstractConfig, Dict[Union[Option, str], Any], Mapping[str, Any] + ] = {}, + parse_values: bool = False, + skip_unknown: bool = False, + ): + self._values = {} + values_dict = values._values if isinstance(values, AbstractConfig) else values + for name, value in values_dict.items(): + self.set(name, value, parse_values, skip_unknown) + + def _resolve_option(self, option_or_name: Union[Option, str]) -> Option: + if isinstance(option_or_name, Option): + option = option_or_name + if not self.options.is_registered(option): + raise ConfigUnknownOptionError(option) + return option + elif isinstance(option_or_name, str): + name = option_or_name + try: + return self.options[name] + except KeyError: + raise ConfigUnknownOptionError(name) + else: + raise TypeError( + "expected Option or str, found " + f"{type(option_or_name).__name__}: {option_or_name!r}" + ) + + def set( + self, + option_or_name: Union[Option, str], + value: Any, + parse_values: bool = False, + skip_unknown: bool = False, + ): + """Set the value of an option. + + Args: + * `option_or_name`: an `Option` object or its name (`str`). + * `value`: the value to be assigned to given option. + * `parse_values`: parse the configuration value from a string into + its proper type, as per its `Option` object. The default + behavior is to raise `ConfigValueValidationError` when the value + is not of the right type. Useful when reading options from a + file type that doesn't support as many types as Python. + * `skip_unknown`: skip unknown configuration options. The default + behaviour is to raise `ConfigUnknownOptionError`. Useful when + reading options from a configuration file that has extra entries + (e.g. for a later version of fontTools) + """ + try: + option = self._resolve_option(option_or_name) + except ConfigUnknownOptionError as e: + if skip_unknown: + log.debug(str(e)) + return + raise + + # Can be useful if the values come from a source that doesn't have + # strict typing (.ini file? Terminal input?) + if parse_values: + try: + value = option.parse(value) + except Exception as e: + raise ConfigValueParsingError(option.name, value) from e + + if option.validate is not None and not option.validate(value): + raise ConfigValueValidationError(option.name, value) + + self._values[option.name] = value + + def get( + self, option_or_name: Union[Option, str], default: Any = _USE_GLOBAL_DEFAULT + ) -> Any: + """ + Get the value of an option. The value which is returned is the first + provided among: + + 1. a user-provided value in the options's ``self._values`` dict + 2. a caller-provided default value to this method call + 3. the global default for the option provided in ``fontTools.config`` + + This is to provide the ability to migrate progressively from config + options passed as arguments to fontTools APIs to config options read + from the current TTFont, e.g. + + .. code:: python + + def fontToolsAPI(font, some_option): + value = font.cfg.get("someLib.module:SOME_OPTION", some_option) + # use value + + That way, the function will work the same for users of the API that + still pass the option to the function call, but will favour the new + config mechanism if the given font specifies a value for that option. + """ + option = self._resolve_option(option_or_name) + if option.name in self._values: + return self._values[option.name] + if default is not _USE_GLOBAL_DEFAULT: + return default + return option.default + + def copy(self): + return self.__class__(self._values) + + def __getitem__(self, option_or_name: Union[Option, str]) -> Any: + return self.get(option_or_name) + + def __setitem__(self, option_or_name: Union[Option, str], value: Any) -> None: + return self.set(option_or_name, value) + + def __delitem__(self, option_or_name: Union[Option, str]) -> None: + option = self._resolve_option(option_or_name) + del self._values[option.name] + + def __iter__(self) -> Iterable[str]: + return self._values.__iter__() + + def __len__(self) -> int: + return len(self._values) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({repr(self._values)})" diff --git a/shared/package-files/4f/4f54081cb1435bc9e0b3dcb09bc7c5a75247cd913f1b394165f1dcf890e398aa/embedding_renorm_cpu_dispatch.h b/shared/package-files/4f/4f54081cb1435bc9e0b3dcb09bc7c5a75247cd913f1b394165f1dcf890e398aa/embedding_renorm_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..804c77bb81c066d11ae990e858b45fb8ae7f714b --- /dev/null +++ b/shared/package-files/4f/4f54081cb1435bc9e0b3dcb09bc7c5a75247cd913f1b394165f1dcf890e398aa/embedding_renorm_cpu_dispatch.h @@ -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 at::Tensor & embedding_renorm_(at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/4f/4f595865e5bed0dc03c43386e9924bafe38809fc58db06b47d51d5d95e845d29/test_eigen.py b/shared/package-files/4f/4f595865e5bed0dc03c43386e9924bafe38809fc58db06b47d51d5d95e845d29/test_eigen.py new file mode 100644 index 0000000000000000000000000000000000000000..70482eab686d5b4e1c45d552f5eccb5bdaa9e1ed --- /dev/null +++ b/shared/package-files/4f/4f595865e5bed0dc03c43386e9924bafe38809fc58db06b47d51d5d95e845d29/test_eigen.py @@ -0,0 +1,90 @@ +""" +Tests for the sympy.polys.matrices.eigen module +""" + +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.matrices.dense import Matrix + +from sympy.polys.agca.extensions import FiniteExtension +from sympy.polys.domains import QQ +from sympy.polys.polytools import Poly +from sympy.polys.rootoftools import CRootOf +from sympy.polys.matrices.domainmatrix import DomainMatrix + +from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy + + +def test_dom_eigenvects_rational(): + # Rational eigenvalues + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) + rational_eigenvects = [ + (QQ, QQ(3), 1, DomainMatrix([[QQ(1), QQ(1)]], (1, 2), QQ)), + (QQ, QQ(0), 1, DomainMatrix([[QQ(-2), QQ(1)]], (1, 2), QQ)), + ] + assert dom_eigenvects(A) == (rational_eigenvects, []) + + # Test converting to Expr: + sympy_eigenvects = [ + (S(3), 1, [Matrix([1, 1])]), + (S(0), 1, [Matrix([-2, 1])]), + ] + assert dom_eigenvects_to_sympy(rational_eigenvects, [], Matrix) == sympy_eigenvects + + +def test_dom_eigenvects_algebraic(): + # Algebraic eigenvalues + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Avects = dom_eigenvects(A) + + # Extract the dummy to build the expected result: + lamda = Avects[1][0][1].gens[0] + irreducible = Poly(lamda**2 - 5*lamda - 2, lamda, domain=QQ) + K = FiniteExtension(irreducible) + KK = K.from_sympy + algebraic_eigenvects = [ + (K, irreducible, 1, DomainMatrix([[KK((lamda-4)/3), KK(1)]], (1, 2), K)), + ] + assert Avects == ([], algebraic_eigenvects) + + # Test converting to Expr: + sympy_eigenvects = [ + (S(5)/2 - sqrt(33)/2, 1, [Matrix([[-sqrt(33)/6 - S(1)/2], [1]])]), + (S(5)/2 + sqrt(33)/2, 1, [Matrix([[-S(1)/2 + sqrt(33)/6], [1]])]), + ] + assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects + + +def test_dom_eigenvects_rootof(): + # Algebraic eigenvalues + A = DomainMatrix([ + [0, 0, 0, 0, -1], + [1, 0, 0, 0, 1], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0]], (5, 5), QQ) + Avects = dom_eigenvects(A) + + # Extract the dummy to build the expected result: + lamda = Avects[1][0][1].gens[0] + irreducible = Poly(lamda**5 - lamda + 1, lamda, domain=QQ) + K = FiniteExtension(irreducible) + KK = K.from_sympy + algebraic_eigenvects = [ + (K, irreducible, 1, + DomainMatrix([ + [KK(lamda**4-1), KK(lamda**3), KK(lamda**2), KK(lamda), KK(1)] + ], (1, 5), K)), + ] + assert Avects == ([], algebraic_eigenvects) + + # Test converting to Expr (slow): + l0, l1, l2, l3, l4 = [CRootOf(lamda**5 - lamda + 1, i) for i in range(5)] + sympy_eigenvects = [ + (l0, 1, [Matrix([-1 + l0**4, l0**3, l0**2, l0, 1])]), + (l1, 1, [Matrix([-1 + l1**4, l1**3, l1**2, l1, 1])]), + (l2, 1, [Matrix([-1 + l2**4, l2**3, l2**2, l2, 1])]), + (l3, 1, [Matrix([-1 + l3**4, l3**3, l3**2, l3, 1])]), + (l4, 1, [Matrix([-1 + l4**4, l4**3, l4**2, l4, 1])]), + ] + assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects diff --git a/shared/package-files/4f/4f5b877fa75cbcb142c1aa4e08d854919d19412dbae2f27f7cf9c4f90d6267f9/CUDASparse.h b/shared/package-files/4f/4f5b877fa75cbcb142c1aa4e08d854919d19412dbae2f27f7cf9c4f90d6267f9/CUDASparse.h new file mode 100644 index 0000000000000000000000000000000000000000..1052469ea7d8ad1047466b3092e184c127a49661 --- /dev/null +++ b/shared/package-files/4f/4f5b877fa75cbcb142c1aa4e08d854919d19412dbae2f27f7cf9c4f90d6267f9/CUDASparse.h @@ -0,0 +1,76 @@ +#pragma once + +#include +#if defined(USE_ROCM) +#include +#define HIPSPARSE_VERSION ((hipsparseVersionMajor*100000) + (hipsparseVersionMinor*100) + hipsparseVersionPatch) +#endif + +// cuSparse Generic API added in CUDA 10.1 +// Windows support added in CUDA 11.0 +#if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && ((CUSPARSE_VERSION >= 10300) || (CUSPARSE_VERSION >= 11000 && defined(_WIN32))) +#define AT_USE_CUSPARSE_GENERIC_API() 1 +#else +#define AT_USE_CUSPARSE_GENERIC_API() 0 +#endif + +// cuSparse Generic API descriptor pointers were changed to const in CUDA 12.0 +#if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && \ + (CUSPARSE_VERSION < 12000) +#define AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS() 1 +#else +#define AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS() 0 +#endif + +#if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && \ + (CUSPARSE_VERSION >= 12000) +#define AT_USE_CUSPARSE_CONST_DESCRIPTORS() 1 +#else +#define AT_USE_CUSPARSE_CONST_DESCRIPTORS() 0 +#endif + +#if defined(USE_ROCM) +// hipSparse const API added in v2.4.0 +#if HIPSPARSE_VERSION >= 200400 +#define AT_USE_HIPSPARSE_CONST_DESCRIPTORS() 1 +#define AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS() 0 +#define AT_USE_HIPSPARSE_GENERIC_API() 1 +#else +#define AT_USE_HIPSPARSE_CONST_DESCRIPTORS() 0 +#define AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS() 1 +#define AT_USE_HIPSPARSE_GENERIC_API() 1 +#endif +#else // USE_ROCM +#define AT_USE_HIPSPARSE_CONST_DESCRIPTORS() 0 +#define AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS() 0 +#define AT_USE_HIPSPARSE_GENERIC_API() 0 +#endif // USE_ROCM + +// cuSparse Generic API spsv function was added in CUDA 11.3.0 +#if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11500) +#define AT_USE_CUSPARSE_GENERIC_SPSV() 1 +#else +#define AT_USE_CUSPARSE_GENERIC_SPSV() 0 +#endif + +// cuSparse Generic API spsm function was added in CUDA 11.3.1 +#if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11600) +#define AT_USE_CUSPARSE_GENERIC_SPSM() 1 +#else +#define AT_USE_CUSPARSE_GENERIC_SPSM() 0 +#endif + +// cuSparse Generic API sddmm function was added in CUDA 11.2.1 (cuSparse version 11400) +#if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11400) +#define AT_USE_CUSPARSE_GENERIC_SDDMM() 1 +#else +#define AT_USE_CUSPARSE_GENERIC_SDDMM() 0 +#endif + +// BSR triangular solve functions were added in hipSPARSE 1.11.2 (ROCm 4.5.0) +#if defined(CUDART_VERSION) || \ + (defined(USE_ROCM) && ROCM_VERSION >= 40500 ) +#define AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() 1 +#else +#define AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() 0 +#endif diff --git a/shared/package-files/4f/4f631ff3988f2c7540b37f907a7dd84397fafab48b40f11af5fbf19f9c16ba3b/Functions.cpp b/shared/package-files/4f/4f631ff3988f2c7540b37f907a7dd84397fafab48b40f11af5fbf19f9c16ba3b/Functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5bc089f67df74b300bc8de6568b702d48e0cb6c2 --- /dev/null +++ b/shared/package-files/4f/4f631ff3988f2c7540b37f907a7dd84397fafab48b40f11af5fbf19f9c16ba3b/Functions.cpp @@ -0,0 +1,20 @@ +#include "torch/csrc/autograd/FunctionsManual.h" +#include "torch/csrc/dynamo/compiled_autograd.h" + +// ${generated_comment} + +// The manual function definitions that used to be here are now in torch/csrc/autograd/FunctionsManual.cpp +// This speeds up re-compilation and allow to share these implementations so that they can be +// used for forward mode AD formulas as well. + +using namespace torch::autograd::generated::details; +using at::Tensor; +using at::Scalar; +using at::IntArrayRef; +using at::TensorList; + +namespace torch::autograd::generated { + +${autograd_function_definitions} + +} // namespace torch::autograd::generated diff --git a/shared/package-files/4f/4f6b941637aca2e767cbe1e79ecf00ed6241a8c419c1444976575bca4bbe6b0b/MPSEvent.h b/shared/package-files/4f/4f6b941637aca2e767cbe1e79ecf00ed6241a8c419c1444976575bca4bbe6b0b/MPSEvent.h new file mode 100644 index 0000000000000000000000000000000000000000..880ff1c75d12e17ecf719f3de875c2217f852e51 --- /dev/null +++ b/shared/package-files/4f/4f6b941637aca2e767cbe1e79ecf00ed6241a8c419c1444976575bca4bbe6b0b/MPSEvent.h @@ -0,0 +1,100 @@ +// Copyright © 2023 Apple Inc. + +#pragma once + +#include +#include +#include + +namespace at::mps { + +// NOTE: don't create instances of this class directly. +// Use MPSEventPool to acquire instances of MPSEvent. +class MPSEvent { +public: + explicit MPSEvent(id_t ID, MPSStream* stream, bool enable_timing); + ~MPSEvent(); + + // records an event on the stream + void record(bool needsLock, bool syncEvent = false); + // makes all future work submitted to the stream wait for this event. + bool wait(bool needsLock, bool syncEvent = false); + // schedules a notifyListener callback for the event. + bool notify(bool needsLock, MTLSharedEventNotificationBlock block); + // checks if events are already signaled. + bool query() const; + // blocks the CPU thread until all the GPU work that were scheduled + // prior to recording this event are completed. + bool synchronize(); + // resets this event with new parameters in case it gets reused from the event pool + void reset(MPSStream* stream, bool enable_timing); + // returns the unique ID of the event instance + id_t getID() const { return m_id; } + // returns the completion timestamp of the event + uint64_t getCompletionTime() const { return m_completion_time; } + // if already recorded, waits for cpu_sync_cv to be signaled + void waitForCpuSync(); + +private: + id_t m_id; + // enables measuring the completion time of the notifyListener of this event + bool m_enable_timing; + uint64_t m_signalCounter = 0; + MPSStream* m_stream = nullptr; + MTLSharedEvent_t m_event = nullptr; + MTLSharedEventListener* m_listener = nullptr; + // used to sync the events created on this Stream with CPU + std::mutex m_cpu_sync_mutex{}; + std::condition_variable m_cpu_sync_cv{}; + // CondVar predicate to sync the events created on this Stream with CPU + bool m_cpu_sync_completed = false; + // used to compute elapsed time + uint64_t m_completion_time = 0; + + void recordLocked(bool syncEvent); + bool waitLocked(bool syncEvent); + bool notifyLocked(MTLSharedEventNotificationBlock block); + void notifyCpuSync(); + static uint64_t getTime() { + return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW); + } +}; + +typedef std::unique_ptr> MPSEventPtr; + +class MPSEventPool { +public: + explicit MPSEventPool(MPSStream* default_stream); + ~MPSEventPool(); + + MPSEventPtr acquireEvent(bool enable_timing, MPSStream* stream); + void emptyCache(); + + // these are mainly used for MPSHooks and torch.mps.Event() bindings + id_t acquireEvent(bool enable_timing); + void releaseEvent(id_t event_id); + void recordEvent(id_t event_id, bool syncEvent); + void waitForEvent(id_t event_id, bool syncEvent); + void synchronizeEvent(id_t event_id); + bool queryEvent(id_t event_id); + // returns elapsed time between two recorded events in milliseconds + double elapsedTime(id_t start_event_id, id_t end_event_id); + +private: + MPSStream* m_default_stream = nullptr; + std::recursive_mutex m_mutex; + std::stack> m_pool{}; + // dictionary to associate event IDs with event objects + // used to retain in-use events out of the pool + // for torch.mps.Event() bindings. + std::unordered_map m_in_use_events{}; + uint64_t m_event_counter = 0; + std::function m_default_deleter; + + MPSEvent* getInUseEvent(id_t event_id, bool locked = true); +}; + +// shared_ptr is used to get MPSEventPool destroyed after dependent instances +std::shared_ptr getMPSEventPool(); + +} // namespace at::mps diff --git a/shared/package-files/4f/4f765fba681973f6d57ea2d283559fa8dea96499b62dab24725dc463c8f1de30/Functions.h b/shared/package-files/4f/4f765fba681973f6d57ea2d283559fa8dea96499b62dab24725dc463c8f1de30/Functions.h new file mode 100644 index 0000000000000000000000000000000000000000..437a5e8e898895b2c1f113d19bdf34c6e34b1ea8 --- /dev/null +++ b/shared/package-files/4f/4f765fba681973f6d57ea2d283559fa8dea96499b62dab24725dc463c8f1de30/Functions.h @@ -0,0 +1,51 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include + +#include "torch/csrc/autograd/function.h" +#include "torch/csrc/autograd/variable.h" +#include "torch/csrc/autograd/saved_variable.h" +#include + +#include + +namespace torch { namespace autograd { namespace generated { + +using at::Scalar; +using at::Tensor; +using at::IntArrayRef; +using at::ArrayRef; +using at::Type; +using at::TensorGeometry; +using at::ScalarType; +using c10::optional; +using c10::fmap; + +inline std::vector unpack_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) { + // NB: we must explicitly do the conversion in the lambda, otherwise template + // deduction will give a Tensor of Variable which is not convertible + return fmap(xs, [&saved_for](const SavedVariable& x) { + // TODO(crcrpar): Use `std::move(saved_for)` to avoid incrementing refcount, which would need refactoring. + return static_cast(x.unpack(saved_for)); + }); +} + +inline c10::List> unpack_opt_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) { + torch::List> result; + result.reserve(xs.size()); + for (const SavedVariable& v : xs) { + auto var = v.unpack(saved_for); + result.push_back(var.defined() ? c10::optional(var) : c10::nullopt); + } + return result; +} + +using torch::autograd::TypeAndSize; + +${autograd_function_declarations} + +}}} // namespace torch::autograd::generated diff --git a/shared/package-files/4f/4f7785e5c2723f419fbfef3ef140d943aec6600ce7545bf8fd2e4c3abe90128c/operator_options.h b/shared/package-files/4f/4f7785e5c2723f419fbfef3ef140d943aec6600ce7545bf8fd2e4c3abe90128c/operator_options.h new file mode 100644 index 0000000000000000000000000000000000000000..50c41fc3ad39d44262b4da8e54fd4b75b00d8f2d --- /dev/null +++ b/shared/package-files/4f/4f7785e5c2723f419fbfef3ef140d943aec6600ce7545bf8fd2e4c3abe90128c/operator_options.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +using AliasAnalysisKind = c10::AliasAnalysisKind; + +} // namespace torch::jit diff --git a/shared/package-files/4f/4f7b232d3823300aba57261189c58f68c215049d984aec19c55e95739c99b502/etree.py b/shared/package-files/4f/4f7b232d3823300aba57261189c58f68c215049d984aec19c55e95739c99b502/etree.py new file mode 100644 index 0000000000000000000000000000000000000000..07b924ac8523c0680b175f0269c42fa1959abc47 --- /dev/null +++ b/shared/package-files/4f/4f7b232d3823300aba57261189c58f68c215049d984aec19c55e95739c99b502/etree.py @@ -0,0 +1,6 @@ +"""DEPRECATED - This module is kept here only as a backward compatibility shim +for the old ufoLib.etree module, which was moved to :mod:`fontTools.misc.etree`. +Please use the latter instead. +""" + +from fontTools.misc.etree import * diff --git a/shared/package-files/4f/4f7c038c10af3bf6ae5ccd23fe617f656ce497f2f251f90eadcc4658bb738607/metadata.py b/shared/package-files/4f/4f7c038c10af3bf6ae5ccd23fe617f656ce497f2f251f90eadcc4658bb738607/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..b7bae9e6664a6ef4bbbf9f0c52623a1f68c9649e --- /dev/null +++ b/shared/package-files/4f/4f7c038c10af3bf6ae5ccd23fe617f656ce497f2f251f90eadcc4658bb738607/metadata.py @@ -0,0 +1,61 @@ +from dataclasses import dataclass +from typing import List, Union, Optional +from functools import reduce + +from torch.distributed.remote_device import _remote_device + +@dataclass +class ShardMetadata: + """ + Represents a shard of the overall Tensor including its + offsets, lengths and device placement. + + Args: + shard_offsets(List[int]): Offsets in the original tensor indicating + the start offsets for this shard. Should have the same rank as + the original tensor. + shard_sizes(List[int]): Integers indicating the size of each + dimension for this shard. Should have the same rank as the + original tensor. + placement(:class:`torch.distributed._remote_device`): + Specifies the placement of this shard. + """ + + __slots__ = ['shard_offsets', 'shard_sizes', 'placement'] + + shard_offsets: List[int] + shard_sizes: List[int] + placement: Optional[_remote_device] + + def __init__( + self, + shard_offsets: List[int], + shard_sizes: List[int], + placement: Optional[Union[str, _remote_device]] = None + ): + self.shard_offsets = shard_offsets + self.shard_sizes = shard_sizes + if isinstance(placement, str): + self.placement = _remote_device(placement) + else: + self.placement = placement + if len(self.shard_offsets) != len(self.shard_sizes): + raise ValueError( + f'shard_offsets and shard_sizes should have ' + f'the same number of elements, found {len(self.shard_offsets)} ' + f'and {self.shard_sizes} respectively') + + for i in range(len(self.shard_offsets)): + if self.shard_offsets[i] < 0: + raise ValueError('shard_offsets should be >=0') + if self.shard_sizes[i] < 0: + raise ValueError('shard_sizes should be >= 0') + + def __hash__(self): + def _hash_reduce(a, b): + return (a << 8) + hash(b) + + res = reduce(_hash_reduce, self.shard_offsets, 37) + res = reduce(_hash_reduce, self.shard_sizes, res) + res = _hash_reduce(res, self.placement) + return res diff --git a/shared/package-files/4f/4f7f4ec33f0480be28aa6562053d2081e9fd0d73ad347591c61fa7e88ee92f2c/_pseudo_diffs.py b/shared/package-files/4f/4f7f4ec33f0480be28aa6562053d2081e9fd0d73ad347591c61fa7e88ee92f2c/_pseudo_diffs.py new file mode 100644 index 0000000000000000000000000000000000000000..6dbcc8d3979b35c1497266fea34cf565cd3d11d7 --- /dev/null +++ b/shared/package-files/4f/4f7f4ec33f0480be28aa6562053d2081e9fd0d73ad347591c61fa7e88ee92f2c/_pseudo_diffs.py @@ -0,0 +1,554 @@ +""" +Differential and pseudo-differential operators. +""" +# Created by Pearu Peterson, September 2002 + +__all__ = ['diff', + 'tilbert','itilbert','hilbert','ihilbert', + 'cs_diff','cc_diff','sc_diff','ss_diff', + 'shift'] + +import threading + +from numpy import pi, asarray, sin, cos, sinh, cosh, tanh, iscomplexobj +from . import convolve + +from scipy.fft._pocketfft.helper import _datacopied + + +_cache = threading.local() + + +def diff(x,order=1,period=None, _cache=_cache): + """ + Return kth derivative (or integral) of a periodic sequence x. + + If x_j and y_j are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = pow(sqrt(-1)*j*2*pi/period, order) * x_j + y_0 = 0 if order is not 0. + + Parameters + ---------- + x : array_like + Input array. + order : int, optional + The order of differentiation. Default order is 1. If order is + negative, then integration is carried out under the assumption + that ``x_0 == 0``. + period : float, optional + The assumed period of the sequence. Default is ``2*pi``. + + Notes + ----- + If ``sum(x, axis=0) = 0`` then ``diff(diff(x, k), -k) == x`` (within + numerical accuracy). + + For odd order and even ``len(x)``, the Nyquist mode is taken zero. + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'diff_cache'): + _cache.diff_cache = {} + _cache = _cache.diff_cache + + tmp = asarray(x) + if order == 0: + return tmp + if iscomplexobj(tmp): + return diff(tmp.real, order, period, _cache)+1j*diff( + tmp.imag, order, period, _cache) + if period is not None: + c = 2*pi/period + else: + c = 1.0 + n = len(x) + omega = _cache.get((n,order,c)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k,order=order,c=c): + if k: + return pow(c*k,order) + return 0 + omega = convolve.init_convolution_kernel(n,kernel,d=order, + zero_nyquist=1) + _cache[(n,order,c)] = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,swap_real_imag=order % 2, + overwrite_x=overwrite_x) + + +def tilbert(x, h, period=None, _cache=_cache): + """ + Return h-Tilbert transform of a periodic sequence x. + + If x_j and y_j are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = sqrt(-1)*coth(j*h*2*pi/period) * x_j + y_0 = 0 + + Parameters + ---------- + x : array_like + The input array to transform. + h : float + Defines the parameter of the Tilbert transform. + period : float, optional + The assumed period of the sequence. Default period is ``2*pi``. + + Returns + ------- + tilbert : ndarray + The result of the transform. + + Notes + ----- + If ``sum(x, axis=0) == 0`` and ``n = len(x)`` is odd, then + ``tilbert(itilbert(x)) == x``. + + If ``2 * pi * h / period`` is approximately 10 or larger, then + numerically ``tilbert == hilbert`` + (theoretically oo-Tilbert == Hilbert). + + For even ``len(x)``, the Nyquist mode of ``x`` is taken zero. + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'tilbert_cache'): + _cache.tilbert_cache = {} + _cache = _cache.tilbert_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return tilbert(tmp.real, h, period, _cache) + \ + 1j * tilbert(tmp.imag, h, period, _cache) + + if period is not None: + h = h * 2 * pi / period + + n = len(x) + omega = _cache.get((n, h)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k, h=h): + if k: + return 1.0/tanh(h*k) + + return 0 + + omega = convolve.init_convolution_kernel(n, kernel, d=1) + _cache[(n,h)] = omega + + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x) + + +def itilbert(x,h,period=None, _cache=_cache): + """ + Return inverse h-Tilbert transform of a periodic sequence x. + + If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = -sqrt(-1)*tanh(j*h*2*pi/period) * x_j + y_0 = 0 + + For more details, see `tilbert`. + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'itilbert_cache'): + _cache.itilbert_cache = {} + _cache = _cache.itilbert_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return itilbert(tmp.real, h, period, _cache) + \ + 1j*itilbert(tmp.imag, h, period, _cache) + if period is not None: + h = h*2*pi/period + n = len(x) + omega = _cache.get((n,h)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k,h=h): + if k: + return -tanh(h*k) + return 0 + omega = convolve.init_convolution_kernel(n,kernel,d=1) + _cache[(n,h)] = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x) + + +def hilbert(x, _cache=_cache): + """ + Return Hilbert transform of a periodic sequence x. + + If x_j and y_j are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = sqrt(-1)*sign(j) * x_j + y_0 = 0 + + Parameters + ---------- + x : array_like + The input array, should be periodic. + _cache : dict, optional + Dictionary that contains the kernel used to do a convolution with. + + Returns + ------- + y : ndarray + The transformed input. + + See Also + -------- + scipy.signal.hilbert : Compute the analytic signal, using the Hilbert + transform. + + Notes + ----- + If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``. + + For even len(x), the Nyquist mode of x is taken zero. + + The sign of the returned transform does not have a factor -1 that is more + often than not found in the definition of the Hilbert transform. Note also + that `scipy.signal.hilbert` does have an extra -1 factor compared to this + function. + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'hilbert_cache'): + _cache.hilbert_cache = {} + _cache = _cache.hilbert_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return hilbert(tmp.real, _cache) + 1j * hilbert(tmp.imag, _cache) + n = len(x) + omega = _cache.get(n) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k): + if k > 0: + return 1.0 + elif k < 0: + return -1.0 + return 0.0 + omega = convolve.init_convolution_kernel(n,kernel,d=1) + _cache[n] = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x) + + +def ihilbert(x, _cache=_cache): + """ + Return inverse Hilbert transform of a periodic sequence x. + + If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = -sqrt(-1)*sign(j) * x_j + y_0 = 0 + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'ihilbert_cache'): + _cache.ihilbert_cache = {} + _cache = _cache.ihilbert_cache + return -hilbert(x, _cache) + + +def cs_diff(x, a, b, period=None, _cache=_cache): + """ + Return (a,b)-cosh/sinh pseudo-derivative of a periodic sequence. + + If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = -sqrt(-1)*cosh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j + y_0 = 0 + + Parameters + ---------- + x : array_like + The array to take the pseudo-derivative from. + a, b : float + Defines the parameters of the cosh/sinh pseudo-differential + operator. + period : float, optional + The period of the sequence. Default period is ``2*pi``. + + Returns + ------- + cs_diff : ndarray + Pseudo-derivative of periodic sequence `x`. + + Notes + ----- + For even len(`x`), the Nyquist mode of `x` is taken as zero. + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'cs_diff_cache'): + _cache.cs_diff_cache = {} + _cache = _cache.cs_diff_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return cs_diff(tmp.real, a, b, period, _cache) + \ + 1j*cs_diff(tmp.imag, a, b, period, _cache) + if period is not None: + a = a*2*pi/period + b = b*2*pi/period + n = len(x) + omega = _cache.get((n,a,b)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k,a=a,b=b): + if k: + return -cosh(a*k)/sinh(b*k) + return 0 + omega = convolve.init_convolution_kernel(n,kernel,d=1) + _cache[(n,a,b)] = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x) + + +def sc_diff(x, a, b, period=None, _cache=_cache): + """ + Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x. + + If x_j and y_j are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j + y_0 = 0 + + Parameters + ---------- + x : array_like + Input array. + a,b : float + Defines the parameters of the sinh/cosh pseudo-differential + operator. + period : float, optional + The period of the sequence x. Default is 2*pi. + + Notes + ----- + ``sc_diff(cs_diff(x,a,b),b,a) == x`` + For even ``len(x)``, the Nyquist mode of x is taken as zero. + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'sc_diff_cache'): + _cache.sc_diff_cache = {} + _cache = _cache.sc_diff_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return sc_diff(tmp.real, a, b, period, _cache) + \ + 1j * sc_diff(tmp.imag, a, b, period, _cache) + if period is not None: + a = a*2*pi/period + b = b*2*pi/period + n = len(x) + omega = _cache.get((n,a,b)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k,a=a,b=b): + if k: + return sinh(a*k)/cosh(b*k) + return 0 + omega = convolve.init_convolution_kernel(n,kernel,d=1) + _cache[(n,a,b)] = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x) + + +def ss_diff(x, a, b, period=None, _cache=_cache): + """ + Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x. + + If x_j and y_j are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j + y_0 = a/b * x_0 + + Parameters + ---------- + x : array_like + The array to take the pseudo-derivative from. + a,b + Defines the parameters of the sinh/sinh pseudo-differential + operator. + period : float, optional + The period of the sequence x. Default is ``2*pi``. + + Notes + ----- + ``ss_diff(ss_diff(x,a,b),b,a) == x`` + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'ss_diff_cache'): + _cache.ss_diff_cache = {} + _cache = _cache.ss_diff_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return ss_diff(tmp.real, a, b, period, _cache) + \ + 1j*ss_diff(tmp.imag, a, b, period, _cache) + if period is not None: + a = a*2*pi/period + b = b*2*pi/period + n = len(x) + omega = _cache.get((n,a,b)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k,a=a,b=b): + if k: + return sinh(a*k)/sinh(b*k) + return float(a)/b + omega = convolve.init_convolution_kernel(n,kernel) + _cache[(n,a,b)] = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,overwrite_x=overwrite_x) + + +def cc_diff(x, a, b, period=None, _cache=_cache): + """ + Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence. + + If x_j and y_j are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j + + Parameters + ---------- + x : array_like + The array to take the pseudo-derivative from. + a,b : float + Defines the parameters of the sinh/sinh pseudo-differential + operator. + period : float, optional + The period of the sequence x. Default is ``2*pi``. + + Returns + ------- + cc_diff : ndarray + Pseudo-derivative of periodic sequence `x`. + + Notes + ----- + ``cc_diff(cc_diff(x,a,b),b,a) == x`` + + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'cc_diff_cache'): + _cache.cc_diff_cache = {} + _cache = _cache.cc_diff_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return cc_diff(tmp.real, a, b, period, _cache) + \ + 1j * cc_diff(tmp.imag, a, b, period, _cache) + if period is not None: + a = a*2*pi/period + b = b*2*pi/period + n = len(x) + omega = _cache.get((n,a,b)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel(k,a=a,b=b): + return cosh(a*k)/cosh(b*k) + omega = convolve.init_convolution_kernel(n,kernel) + _cache[(n,a,b)] = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve(tmp,omega,overwrite_x=overwrite_x) + + +def shift(x, a, period=None, _cache=_cache): + """ + Shift periodic sequence x by a: y(u) = x(u+a). + + If x_j and y_j are Fourier coefficients of periodic functions x + and y, respectively, then:: + + y_j = exp(j*a*2*pi/period*sqrt(-1)) * x_f + + Parameters + ---------- + x : array_like + The array to take the pseudo-derivative from. + a : float + Defines the parameters of the sinh/sinh pseudo-differential + period : float, optional + The period of the sequences x and y. Default period is ``2*pi``. + """ + if isinstance(_cache, threading.local): + if not hasattr(_cache, 'shift_cache'): + _cache.shift_cache = {} + _cache = _cache.shift_cache + + tmp = asarray(x) + if iscomplexobj(tmp): + return shift(tmp.real, a, period, _cache) + 1j * shift( + tmp.imag, a, period, _cache) + if period is not None: + a = a*2*pi/period + n = len(x) + omega = _cache.get((n,a)) + if omega is None: + if len(_cache) > 20: + while _cache: + _cache.popitem() + + def kernel_real(k,a=a): + return cos(a*k) + + def kernel_imag(k,a=a): + return sin(a*k) + omega_real = convolve.init_convolution_kernel(n,kernel_real,d=0, + zero_nyquist=0) + omega_imag = convolve.init_convolution_kernel(n,kernel_imag,d=1, + zero_nyquist=0) + _cache[(n,a)] = omega_real,omega_imag + else: + omega_real,omega_imag = omega + overwrite_x = _datacopied(tmp, x) + return convolve.convolve_z(tmp,omega_real,omega_imag, + overwrite_x=overwrite_x) + diff --git a/shared/package-files/4f/4f8201d3ada7b6d0f450b417e55747adaee5f894412c4875169b0736a5ff0faa/dialog.py b/shared/package-files/4f/4f8201d3ada7b6d0f450b417e55747adaee5f894412c4875169b0736a5ff0faa/dialog.py new file mode 100644 index 0000000000000000000000000000000000000000..36ae6c277cb66ac86a48f42d07ce4c08dce10738 --- /dev/null +++ b/shared/package-files/4f/4f8201d3ada7b6d0f450b417e55747adaee5f894412c4875169b0736a5ff0faa/dialog.py @@ -0,0 +1,49 @@ +# dialog.py -- Tkinter interface to the tk_dialog script. + +from tkinter import _cnfmerge, Widget, TclError, Button, Pack + +__all__ = ["Dialog"] + +DIALOG_ICON = 'questhead' + + +class Dialog(Widget): + def __init__(self, master=None, cnf={}, **kw): + cnf = _cnfmerge((cnf, kw)) + self.widgetName = '__dialog__' + self._setup(master, cnf) + self.num = self.tk.getint( + self.tk.call( + 'tk_dialog', self._w, + cnf['title'], cnf['text'], + cnf['bitmap'], cnf['default'], + *cnf['strings'])) + try: Widget.destroy(self) + except TclError: pass + + def destroy(self): pass + + +def _test(): + d = Dialog(None, {'title': 'File Modified', + 'text': + 'File "Python.h" has been modified' + ' since the last time it was saved.' + ' Do you want to save it before' + ' exiting the application.', + 'bitmap': DIALOG_ICON, + 'default': 0, + 'strings': ('Save File', + 'Discard Changes', + 'Return to Editor')}) + print(d.num) + + +if __name__ == '__main__': + t = Button(None, {'text': 'Test', + 'command': _test, + Pack: {}}) + q = Button(None, {'text': 'Quit', + 'command': t.quit, + Pack: {}}) + t.mainloop() diff --git a/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/abm85h-old b/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/abm85h-old new file mode 100644 index 0000000000000000000000000000000000000000..74a82556ba8c3a3589fa3d3c18e37f73c75b23cd Binary files /dev/null and b/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/abm85h-old differ diff --git a/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/o85h b/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/o85h new file mode 100644 index 0000000000000000000000000000000000000000..74a82556ba8c3a3589fa3d3c18e37f73c75b23cd Binary files /dev/null and b/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/o85h differ diff --git a/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/oabm85h b/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/oabm85h new file mode 100644 index 0000000000000000000000000000000000000000..74a82556ba8c3a3589fa3d3c18e37f73c75b23cd Binary files /dev/null and b/shared/package-files/4f/4f82582112a994af1736d178654c60a5cf7f6ae3587ffa188d9ecbf719de37dc/oabm85h differ diff --git a/shared/package-files/4f/4f83f7d6422e25ae9a864c75b83423803d78c0625777b09a6ac00e3d2ea5fa65/__init__.py b/shared/package-files/4f/4f83f7d6422e25ae9a864c75b83423803d78c0625777b09a6ac00e3d2ea5fa65/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..261ee764485b653a9ecd50c8e8fe3943f0c23449 --- /dev/null +++ b/shared/package-files/4f/4f83f7d6422e25ae9a864c75b83423803d78c0625777b09a6ac00e3d2ea5fa65/__init__.py @@ -0,0 +1,56 @@ +import torch + + +def is_available(): + r"""Return whether PyTorch is built with MKL support.""" + return torch._C.has_mkl + + +VERBOSE_OFF = 0 +VERBOSE_ON = 1 + + +class verbose: + """ + On-demand oneMKL verbosing functionality. + + To make it easier to debug performance issues, oneMKL can dump verbose + messages containing execution information like duration while executing + the kernel. The verbosing functionality can be invoked via an environment + variable named `MKL_VERBOSE`. However, this methodology dumps messages in + all steps. Those are a large amount of verbose messages. Moreover, for + investigating the performance issues, generally taking verbose messages + for one single iteration is enough. This on-demand verbosing functionality + makes it possible to control scope for verbose message dumping. In the + following example, verbose messages will be dumped out for the second + inference only. + + .. highlight:: python + .. code-block:: python + + import torch + model(data) + with torch.backends.mkl.verbose(torch.backends.mkl.VERBOSE_ON): + model(data) + + Args: + level: Verbose level + - ``VERBOSE_OFF``: Disable verbosing + - ``VERBOSE_ON``: Enable verbosing + """ + + def __init__(self, enable): + self.enable = enable + + def __enter__(self): + if self.enable == VERBOSE_OFF: + return + st = torch._C._verbose.mkl_set_verbose(self.enable) + assert ( + st + ), "Failed to set MKL into verbose mode. Please consider to disable this verbose scope." + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + torch._C._verbose.mkl_set_verbose(VERBOSE_OFF) + return False diff --git a/shared/package-files/4f/4f8a378efa8a0ff2265c3929eba5c5395ff1ac1545528949537e090c59355e49/seaborn-v0_8-muted.mplstyle b/shared/package-files/4f/4f8a378efa8a0ff2265c3929eba5c5395ff1ac1545528949537e090c59355e49/seaborn-v0_8-muted.mplstyle new file mode 100644 index 0000000000000000000000000000000000000000..4a71646ce9036116fedfb2094d9f21d52ac3e40a --- /dev/null +++ b/shared/package-files/4f/4f8a378efa8a0ff2265c3929eba5c5395ff1ac1545528949537e090c59355e49/seaborn-v0_8-muted.mplstyle @@ -0,0 +1,3 @@ +# Seaborn muted palette +axes.prop_cycle: cycler('color', ['4878CF', '6ACC65', 'D65F5F', 'B47CC7', 'C4AD66', '77BEDB']) +patch.facecolor: 4878CF diff --git a/shared/package-files/4f/4f92a015a13c4d1a040bef018aa13430b4f1bc73b41b16bb846c346766de7439/COPYING b/shared/package-files/4f/4f92a015a13c4d1a040bef018aa13430b4f1bc73b41b16bb846c346766de7439/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..af9cfbdb134f42e5205ecbad597421d778826481 --- /dev/null +++ b/shared/package-files/4f/4f92a015a13c4d1a040bef018aa13430b4f1bc73b41b16bb846c346766de7439/COPYING @@ -0,0 +1,19 @@ +Copyright (c) 2013 Julian Berman + +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/4f/4f930580b48dd82ac12fe79cf1c5500bc9f42f4a95ebfea520bf091d56cbc36c/max_pool2d_with_indices_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/4f/4f930580b48dd82ac12fe79cf1c5500bc9f42f4a95ebfea520bf091d56cbc36c/max_pool2d_with_indices_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..90cb462e80eb3c6fb0f53cd3da058af12e413546 --- /dev/null +++ b/shared/package-files/4f/4f930580b48dd82ac12fe79cf1c5500bc9f42f4a95ebfea520bf091d56cbc36c/max_pool2d_with_indices_compositeexplicitautogradnonfunctional_dispatch.h @@ -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 ::std::tuple max_pool2d_with_indices(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/4f/4f96cd69b1754c3029dbc4bb57fbedfd52039fa97905ed3339508785c4dc15ff/benchmark_util.h b/shared/package-files/4f/4f96cd69b1754c3029dbc4bb57fbedfd52039fa97905ed3339508785c4dc15ff/benchmark_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0ba8553887c03f876b6e08f031f5641170c2e09f --- /dev/null +++ b/shared/package-files/4f/4f96cd69b1754c3029dbc4bb57fbedfd52039fa97905ed3339508785c4dc15ff/benchmark_util.h @@ -0,0 +1,48 @@ +// 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 "benchmark/benchmark.h" + +#include "arrow/acero/exec_plan.h" +#include "arrow/acero/test_util_internal.h" +#include "arrow/compute/exec.h" + +namespace arrow { + +namespace acero { + +Status BenchmarkNodeOverhead(benchmark::State& state, int32_t num_batches, + int32_t batch_size, arrow::acero::BatchesWithSchema data, + std::vector& node_declarations, + arrow::MemoryPool* pool = default_memory_pool()); + +Status BenchmarkIsolatedNodeOverhead(benchmark::State& state, + arrow::compute::Expression expr, int32_t num_batches, + int32_t batch_size, + arrow::acero::BatchesWithSchema data, + std::string factory_name, + arrow::acero::ExecNodeOptions& options, + arrow::MemoryPool* pool = default_memory_pool()); + +} // namespace acero +} // namespace arrow diff --git a/shared/package-files/4f/4f99cf801c5839bf0390d1e510ce7641fef435fed06fa945b650edbaf9849387/_funcs.py b/shared/package-files/4f/4f99cf801c5839bf0390d1e510ce7641fef435fed06fa945b650edbaf9849387/_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..ce800189b46d25316c3123a22ce4ff2e7e1e81ce --- /dev/null +++ b/shared/package-files/4f/4f99cf801c5839bf0390d1e510ce7641fef435fed06fa945b650edbaf9849387/_funcs.py @@ -0,0 +1,484 @@ +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._typing import Array, ModuleType + +__all__ = ["atleast_nd", "cov", "create_diagonal", "expand_dims", "kron", "sinc"] + + +def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array: + """ + Recursively expand the dimension of an array to at least `ndim`. + + Parameters + ---------- + x : array + ndim : int + The minimum number of dimensions for the result. + xp : array_namespace + The standard-compatible namespace for `x`. + + Returns + ------- + res : array + An array with ``res.ndim`` >= `ndim`. + If ``x.ndim`` >= `ndim`, `x` is returned. + If ``x.ndim`` < `ndim`, `x` is expanded by prepending new axes + until ``res.ndim`` equals `ndim`. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.asarray([1]) + >>> xpx.atleast_nd(x, ndim=3, xp=xp) + Array([[[1]]], dtype=array_api_strict.int64) + + >>> x = xp.asarray([[[1, 2], + ... [3, 4]]]) + >>> xpx.atleast_nd(x, ndim=1, xp=xp) is x + True + + """ + if x.ndim < ndim: + x = xp.expand_dims(x, axis=0) + x = atleast_nd(x, ndim=ndim, xp=xp) + return x + + +def cov(m: Array, /, *, xp: ModuleType) -> Array: + """ + Estimate a covariance matrix. + + Covariance indicates the level to which two variables vary together. + If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, + then the covariance matrix element :math:`C_{ij}` is the covariance of + :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance + of :math:`x_i`. + + This provides a subset of the functionality of ``numpy.cov``. + + Parameters + ---------- + m : array + A 1-D or 2-D array containing multiple variables and observations. + Each row of `m` represents a variable, and each column a single + observation of all those variables. + xp : array_namespace + The standard-compatible namespace for `m`. + + Returns + ------- + res : array + The covariance matrix of the variables. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + + Consider two variables, :math:`x_0` and :math:`x_1`, which + correlate perfectly, but in opposite directions: + + >>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T + >>> x + Array([[0, 1, 2], + [2, 1, 0]], dtype=array_api_strict.int64) + + Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance + matrix shows this clearly: + + >>> xpx.cov(x, xp=xp) + Array([[ 1., -1.], + [-1., 1.]], dtype=array_api_strict.float64) + + + Note that element :math:`C_{0,1}`, which shows the correlation between + :math:`x_0` and :math:`x_1`, is negative. + + Further, note how `x` and `y` are combined: + + >>> x = xp.asarray([-2.1, -1, 4.3]) + >>> y = xp.asarray([3, 1.1, 0.12]) + >>> X = xp.stack((x, y), axis=0) + >>> xpx.cov(X, xp=xp) + Array([[11.71 , -4.286 ], + [-4.286 , 2.14413333]], dtype=array_api_strict.float64) + + >>> xpx.cov(x, xp=xp) + Array(11.71, dtype=array_api_strict.float64) + + >>> xpx.cov(y, xp=xp) + Array(2.14413333, dtype=array_api_strict.float64) + + """ + m = xp.asarray(m, copy=True) + dtype = ( + xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64) + ) + + m = atleast_nd(m, ndim=2, xp=xp) + m = xp.astype(m, dtype) + + avg = _mean(m, axis=1, xp=xp) + fact = m.shape[1] - 1 + + if fact <= 0: + warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2) + fact = 0.0 + + m -= avg[:, None] + m_transpose = m.T + if xp.isdtype(m_transpose.dtype, "complex floating"): + m_transpose = xp.conj(m_transpose) + c = m @ m_transpose + c /= fact + axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1) + return xp.squeeze(c, axis=axes) + + +def create_diagonal(x: Array, /, *, offset: int = 0, xp: ModuleType) -> Array: + """ + Construct a diagonal array. + + Parameters + ---------- + x : array + A 1-D array + offset : int, optional + Offset from the leading diagonal (default is ``0``). + Use positive ints for diagonals above the leading diagonal, + and negative ints for diagonals below the leading diagonal. + xp : array_namespace + The standard-compatible namespace for `x`. + + Returns + ------- + res : array + A 2-D array with `x` on the diagonal (offset by `offset`). + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.asarray([2, 4, 8]) + + >>> xpx.create_diagonal(x, xp=xp) + Array([[2, 0, 0], + [0, 4, 0], + [0, 0, 8]], dtype=array_api_strict.int64) + + >>> xpx.create_diagonal(x, offset=-2, xp=xp) + Array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [2, 0, 0, 0, 0], + [0, 4, 0, 0, 0], + [0, 0, 8, 0, 0]], dtype=array_api_strict.int64) + + """ + if x.ndim != 1: + err_msg = "`x` must be 1-dimensional." + raise ValueError(err_msg) + n = x.shape[0] + abs(offset) + diag = xp.zeros(n**2, dtype=x.dtype) + i = offset if offset >= 0 else abs(offset) * n + diag[i : min(n * (n - offset), diag.shape[0]) : n + 1] = x + return xp.reshape(diag, (n, n)) + + +def _mean( + x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, + xp: ModuleType, +) -> Array: + """ + Complex mean, https://github.com/data-apis/array-api/issues/846. + """ + if xp.isdtype(x.dtype, "complex floating"): + x_real = xp.real(x) + x_imag = xp.imag(x) + mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims) + mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims) + return mean_real + (mean_imag * xp.asarray(1j)) + return xp.mean(x, axis=axis, keepdims=keepdims) + + +def expand_dims( + a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType +) -> Array: + """ + Expand the shape of an array. + + Insert (a) new axis/axes that will appear at the position(s) specified by + `axis` in the expanded array shape. + + This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*. + Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays. + + Parameters + ---------- + a : array + axis : int or tuple of ints, optional + Position(s) in the expanded axes where the new axis (or axes) is/are placed. + If multiple positions are provided, they should be unique (note that a position + given by a positive index could also be referred to by a negative index - + that will also result in an error). + Default: ``(0,)``. + xp : array_namespace + The standard-compatible namespace for `a`. + + Returns + ------- + res : array + `a` with an expanded shape. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.asarray([1, 2]) + >>> x.shape + (2,) + + The following is equivalent to ``x[xp.newaxis, :]`` or ``x[xp.newaxis]``: + + >>> y = xpx.expand_dims(x, axis=0, xp=xp) + >>> y + Array([[1, 2]], dtype=array_api_strict.int64) + >>> y.shape + (1, 2) + + The following is equivalent to ``x[:, xp.newaxis]``: + + >>> y = xpx.expand_dims(x, axis=1, xp=xp) + >>> y + Array([[1], + [2]], dtype=array_api_strict.int64) + >>> y.shape + (2, 1) + + ``axis`` may also be a tuple: + + >>> y = xpx.expand_dims(x, axis=(0, 1), xp=xp) + >>> y + Array([[[1, 2]]], dtype=array_api_strict.int64) + + >>> y = xpx.expand_dims(x, axis=(2, 0), xp=xp) + >>> y + Array([[[1], + [2]]], dtype=array_api_strict.int64) + + """ + if not isinstance(axis, tuple): + axis = (axis,) + ndim = a.ndim + len(axis) + if axis != () and (min(axis) < -ndim or max(axis) >= ndim): + err_msg = ( + f"a provided axis position is out of bounds for array of dimension {a.ndim}" + ) + raise IndexError(err_msg) + axis = tuple(dim % ndim for dim in axis) + if len(set(axis)) != len(axis): + err_msg = "Duplicate dimensions specified in `axis`." + raise ValueError(err_msg) + for i in sorted(axis): + a = xp.expand_dims(a, axis=i) + return a + + +def kron(a: Array, b: Array, /, *, xp: ModuleType) -> Array: + """ + Kronecker product of two arrays. + + Computes the Kronecker product, a composite array made of blocks of the + second array scaled by the first. + + Equivalent to ``numpy.kron`` for NumPy arrays. + + Parameters + ---------- + a, b : array + xp : array_namespace + The standard-compatible namespace for `a` and `b`. + + Returns + ------- + res : array + The Kronecker product of `a` and `b`. + + Notes + ----- + The function assumes that the number of dimensions of `a` and `b` + are the same, if necessary prepending the smallest with ones. + If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``, + the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``. + The elements are products of elements from `a` and `b`, organized + explicitly by:: + + kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN] + + where:: + + kt = it * st + jt, t = 0,...,N + + In the common 2-D case (N=1), the block structure can be visualized:: + + [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ], + [ ... ... ], + [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]] + + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> xpx.kron(xp.asarray([1, 10, 100]), xp.asarray([5, 6, 7]), xp=xp) + Array([ 5, 6, 7, 50, 60, 70, 500, + 600, 700], dtype=array_api_strict.int64) + + >>> xpx.kron(xp.asarray([5, 6, 7]), xp.asarray([1, 10, 100]), xp=xp) + Array([ 5, 50, 500, 6, 60, 600, 7, + 70, 700], dtype=array_api_strict.int64) + + >>> xpx.kron(xp.eye(2), xp.ones((2, 2)), xp=xp) + Array([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]], dtype=array_api_strict.float64) + + + >>> a = xp.reshape(xp.arange(100), (2, 5, 2, 5)) + >>> b = xp.reshape(xp.arange(24), (2, 3, 4)) + >>> c = xpx.kron(a, b, xp=xp) + >>> c.shape + (2, 10, 6, 20) + >>> I = (1, 3, 0, 2) + >>> J = (0, 2, 1) + >>> J1 = (0,) + J # extend to ndim=4 + >>> S1 = (1,) + b.shape + >>> K = tuple(xp.asarray(I) * xp.asarray(S1) + xp.asarray(J1)) + >>> c[K] == a[I]*b[J] + Array(True, dtype=array_api_strict.bool) + + """ + + b = xp.asarray(b) + singletons = (1,) * (b.ndim - a.ndim) + a = xp.broadcast_to(xp.asarray(a), singletons + a.shape) + + nd_b, nd_a = b.ndim, a.ndim + nd_max = max(nd_b, nd_a) + if nd_a == 0 or nd_b == 0: + return xp.multiply(a, b) + + a_shape = a.shape + b_shape = b.shape + + # Equalise the shapes by prepending smaller one with 1s + a_shape = (1,) * max(0, nd_b - nd_a) + a_shape + b_shape = (1,) * max(0, nd_a - nd_b) + b_shape + + # Insert empty dimensions + a_arr = expand_dims(a, axis=tuple(range(nd_b - nd_a)), xp=xp) + b_arr = expand_dims(b, axis=tuple(range(nd_a - nd_b)), xp=xp) + + # Compute the product + a_arr = expand_dims(a_arr, axis=tuple(range(1, nd_max * 2, 2)), xp=xp) + b_arr = expand_dims(b_arr, axis=tuple(range(0, nd_max * 2, 2)), xp=xp) + result = xp.multiply(a_arr, b_arr) + + # Reshape back and return + a_shape = xp.asarray(a_shape) + b_shape = xp.asarray(b_shape) + return xp.reshape(result, tuple(xp.multiply(a_shape, b_shape))) + + +def sinc(x: Array, /, *, xp: ModuleType) -> Array: + r""" + Return the normalized sinc function. + + The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument + :math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not + only everywhere continuous but also infinitely differentiable. + + .. note:: + + Note the normalization factor of ``pi`` used in the definition. + This is the most commonly used definition in signal processing. + Use ``sinc(x / xp.pi)`` to obtain the unnormalized sinc function + :math:`\sin(x)/x` that is more common in mathematics. + + Parameters + ---------- + x : array + Array (possibly multi-dimensional) of values for which to calculate + ``sinc(x)``. Must have a real floating point dtype. + xp : array_namespace + The standard-compatible namespace for `x`. + + Returns + ------- + res : array + ``sinc(x)`` calculated elementwise, which has the same shape as the input. + + Notes + ----- + The name sinc is short for "sine cardinal" or "sinus cardinalis". + + The sinc function is used in various signal processing applications, + including in anti-aliasing, in the construction of a Lanczos resampling + filter, and in interpolation. + + For bandlimited interpolation of discrete-time signals, the ideal + interpolation kernel is proportional to the sinc function. + + References + ---------- + .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web + Resource. https://mathworld.wolfram.com/SincFunction.html + .. [2] Wikipedia, "Sinc function", + https://en.wikipedia.org/wiki/Sinc_function + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.linspace(-4, 4, 41) + >>> xpx.sinc(x, xp=xp) + Array([-3.89817183e-17, -4.92362781e-02, + -8.40918587e-02, -8.90384387e-02, + -5.84680802e-02, 3.89817183e-17, + 6.68206631e-02, 1.16434881e-01, + 1.26137788e-01, 8.50444803e-02, + -3.89817183e-17, -1.03943254e-01, + -1.89206682e-01, -2.16236208e-01, + -1.55914881e-01, 3.89817183e-17, + 2.33872321e-01, 5.04551152e-01, + 7.56826729e-01, 9.35489284e-01, + 1.00000000e+00, 9.35489284e-01, + 7.56826729e-01, 5.04551152e-01, + 2.33872321e-01, 3.89817183e-17, + -1.55914881e-01, -2.16236208e-01, + -1.89206682e-01, -1.03943254e-01, + -3.89817183e-17, 8.50444803e-02, + 1.26137788e-01, 1.16434881e-01, + 6.68206631e-02, 3.89817183e-17, + -5.84680802e-02, -8.90384387e-02, + -8.40918587e-02, -4.92362781e-02, + -3.89817183e-17], dtype=array_api_strict.float64) + + """ + if not xp.isdtype(x.dtype, "real floating"): + err_msg = "`x` must have a real floating data type." + raise ValueError(err_msg) + # no scalars in `where` - array-api#807 + y = xp.pi * xp.where( + x, x, xp.asarray(xp.finfo(x.dtype).smallest_normal, dtype=x.dtype) + ) + return xp.sin(y) / y diff --git a/shared/package-files/4f/4f9af15550a26814df6d387f9530c36f74b0597caeeb313cd39b4a2329deb940/log1p_cpu_dispatch.h b/shared/package-files/4f/4f9af15550a26814df6d387f9530c36f74b0597caeeb313cd39b4a2329deb940/log1p_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f5fb20b93cbb5b4ddc23a35e7d7a0dae3374865b --- /dev/null +++ b/shared/package-files/4f/4f9af15550a26814df6d387f9530c36f74b0597caeeb313cd39b4a2329deb940/log1p_cpu_dispatch.h @@ -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 log1p(const at::Tensor & self); +TORCH_API at::Tensor & log1p_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & log1p_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & log1p_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/4f/4f9af2ece9bbe9c2cb88c95a4bc7abd2f0ef1359733f37a332eea6528e83b1f7/multi_threaded_pg.py b/shared/package-files/4f/4f9af2ece9bbe9c2cb88c95a4bc7abd2f0ef1359733f37a332eea6528e83b1f7/multi_threaded_pg.py new file mode 100644 index 0000000000000000000000000000000000000000..d6741582328d94a77108f3e6b5553012234a37f6 --- /dev/null +++ b/shared/package-files/4f/4f9af2ece9bbe9c2cb88c95a4bc7abd2f0ef1359733f37a332eea6528e83b1f7/multi_threaded_pg.py @@ -0,0 +1,494 @@ +# mypy: ignore-errors + +import sys +import threading +from dataclasses import dataclass +from typing import Dict, List, Optional, Tuple, Union +from functools import partial, reduce + +import torch +import torch.distributed as dist +import weakref +from torch._C._distributed_c10d import ( + _create_work_from_future, + AllgatherOptions, + AllreduceOptions, + AllToAllOptions, + BarrierOptions, + BroadcastOptions, + ReduceScatterOptions, + ScatterOptions, + Store, + ReduceOp, +) +from torch.distributed.distributed_c10d import _CollOp, _store_based_barrier, P2POp +from torch.futures import Future +from torch.utils import _pytree as pytree + +""" +TODO: +Lots of missing collectives. +Collectives validation. +Make timeout robust by making collectives respect the test deadline. +Make tests robust by making collectives interruptible. +We need some synchronization around cleanup to ensure that timedout ranks don't cause spurious failures. + +""" + + +def flatten_list(lst): + return pytree.tree_leaves(lst) + + +def ret_work(ret): + fut = Future() + fut.set_result(ret) + return _create_work_from_future(fut) + +def binop_reduce(tensors, op): + res = op(torch.stack(tensors), dim=0) + if isinstance(res, torch.Tensor): + return res + # min/max return a namedtuple + return res.values + +def bitwise_reduce(tensors, op): + return reduce(op, tensors) + +_reduce_ops = { + ReduceOp.SUM: partial(binop_reduce, op=torch.sum), + ReduceOp.AVG: partial(binop_reduce, op=torch.mean), + ReduceOp.PRODUCT: partial(binop_reduce, op=torch.prod), + ReduceOp.MIN: partial(binop_reduce, op=torch.min), + ReduceOp.MAX: partial(binop_reduce, op=torch.max), + ReduceOp.BAND: partial(bitwise_reduce, op=torch.bitwise_and), + ReduceOp.BOR: partial(bitwise_reduce, op=torch.bitwise_or), + ReduceOp.BXOR: partial(bitwise_reduce, op=torch.bitwise_xor), +} + +class AllToAll: + @torch.no_grad() + def work(self, data): + world_size = len(data) + for dest_rank in range(world_size): + output_tensor_list, _ = data[dest_rank] + for src_rank in range(world_size): + _, input_tensor_list = data[src_rank] + output_tensor_list[src_rank].copy_(input_tensor_list[dest_rank]) + +class AllReduce: + def __init__(self, op): + if op.op not in _reduce_ops: + raise NotImplementedError( + f"AllReduce op {op.op} not supported on multithreaded pg for now." + ) + self.op = op.op + + @torch.no_grad() + def work(self, data): + for i in range(len(data[0])): + tensors = [] + # use rank0 as the device for sum + rank_0_device = data[0][i].device + # collect all data to the list and make them + # all on rank 0 device + for src_rank in range(0, len(data)): + tensors.append(data[src_rank][i].to(rank_0_device)) + + # now mimic reduce across all ranks + res = _reduce_ops[self.op](tensors) + + # copy all the reduced value to each rank + for src_rank in range(len(data)): + data[src_rank][i].copy_(res.to(data[src_rank][i].device)) + + +class AllGather: + @torch.no_grad() + def work(self, data): + for src_rank in range(len(data)): + in_tensor_list = data[src_rank][1] + # Can't handle all_gather with multiple tensors + assert len(in_tensor_list) == 1 + src_tensor = in_tensor_list[0] + + for dest in data: + dest_tensor = dest[0][0][src_rank] + dest_tensor.copy_(src_tensor) + + +class Scatter: + def __init__(self, src): + self.src = src + + @torch.no_grad() + def work(self, data): + src_in_tensor_list = data[self.src][1] + # Can't handle scatter with multiple input tensor list + assert len(src_in_tensor_list) == 1 + src_in_tensors = src_in_tensor_list[0] + + for rank, each_rank_data in enumerate(data): + out_tensor_list = each_rank_data[0] + # Can't handle scatter with multiple output tensor + assert len(out_tensor_list) == 1 + dest_tensor = out_tensor_list[0] + dest_tensor.copy_(src_in_tensors[rank]) + + +class Gather: + def __init__(self, dst): + self.dst = dst + + @torch.no_grad() + def work(self, data): + # Can't handle gather with multiple tensor lists + assert len(data[self.dst][0]) == 1 + out_tensor_list = data[self.dst][0][0] + for rank, each_rank_data in enumerate(data): + src_in_tensor_list = each_rank_data[1] + # Can't handle gather with multiple tensor lists + assert len(src_in_tensor_list) == 1 + dest_tensor = out_tensor_list[rank] + dest_tensor.copy_(src_in_tensor_list[0]) + +class ReduceScatter: + def __init__(self, op): + if op != dist.ReduceOp.SUM and op != dist.ReduceOp.AVG: + raise NotImplementedError(f"ReduceScatter does not support {op}") + self.op = op + + @torch.no_grad() + def work(self, data): + start_reduction = [False for _ in range(len(data))] + for each_rank_data in data: + # Can't handle reduce_scatter with multiple scatter list + assert len(each_rank_data[1]) == 1 + to_scatter = each_rank_data[1][0] + for i in range(len(to_scatter)): + dest_tensor_on_rank_i = data[i][0] + # Can't handle reduce_scatter with multiple output tensor + assert len(dest_tensor_on_rank_i) == 1 + dst_tensor_device = dest_tensor_on_rank_i[0].device + if not start_reduction[i]: + dest_tensor_on_rank_i[0].copy_(to_scatter[i].to(dst_tensor_device)) + start_reduction[i] = True + else: + dest_tensor_on_rank_i[0].add_(to_scatter[i].to(dst_tensor_device)) + if self.op == dist.ReduceOp.AVG: + num_ranks = len(data) + for each_rank_data in data: + each_rank_data[0][0] /= num_ranks + + +class Broadcast: + def __init__(self, src): + self.src = src + + @torch.no_grad() + def work(self, data): + in_tensor_list = flatten_list(data[self.src]) + for i in range(len(data)): + out_tensor_list = flatten_list(data[i]) + for j in range(len(in_tensor_list)): + out_tensor_list[j].copy_(in_tensor_list[j]) + + +class Collective: + def __init__(self, world_size, collective, pg): + self._world_size = world_size + self._collective = collective + + self._start_cond = threading.Condition() + self._done_cond = threading.Condition() + + self._data = [None] * world_size + self._count = 0 + self._done = False + + self._pg = pg + + def join(self, rank, data): + with self._start_cond: + self._data[rank] = data + self._count += 1 + + # notify rank 0 + if self._count == self._world_size: + if rank > 0: + self._start_cond.notify() + + if rank == 0: + self._start_cond.wait_for( + lambda: self._count == self._world_size or self._pg._terminate.is_set() + ) + # SystemExit is not a subclass of Exception but BaseException + # and can be distinguished from normal exception raised from program errors + # so that we can hide it from the exception queue + if self._pg._terminate.is_set(): + sys.exit("Test termination event occurs.") + + with self._done_cond: + # wait for rank 0 to finish + if rank > 0: + self._done_cond.wait_for(lambda: self._done or self._pg._terminate.is_set()) + if self._pg._terminate.is_set(): + sys.exit("Test termination event occurs.") + else: + # copy data around + self._collective.work(self._data) + self._done = True + self._done_cond.notify_all() + return ret_work(data) + + +class ProcessLocalGroup(dist.ProcessGroup): + _coll_lock = threading.Lock() + _cur_coll_on_pgs = {} + + _terminate = threading.Event() + + @classmethod + def _start_coll(cls, collective, pg): + with cls._coll_lock: + # pg_name is unique, we use that to record the mapping between pg and collective + if pg.pg_name not in cls._cur_coll_on_pgs: + cls._cur_coll_on_pgs[pg.pg_name] = Collective(pg.size(), collective, cls) + return cls._cur_coll_on_pgs[pg.pg_name] + + @classmethod + def _end_coll(cls, collective, pg): + # This is racily called by all ranks, so only one will work + with cls._coll_lock: + if pg.pg_name in cls._cur_coll_on_pgs and cls._cur_coll_on_pgs[pg.pg_name] == collective: + cls._cur_coll_on_pgs.pop(pg.pg_name) + + @classmethod + def exception_handle(cls, exc): + cls._terminate.set() + for coll in cls._cur_coll_on_pgs.values(): + with coll._start_cond: + coll._start_cond.notify() + with coll._done_cond: + coll._done_cond.notify_all() + + @classmethod + def reset(cls): + with cls._coll_lock: + cls._cur_coll_on_pgs = {} + cls._terminate.clear() + + def alltoall(self, output_tensor_list, input_tensor_list, opts=AllToAllOptions()): + coll = ProcessLocalGroup._start_coll(AllToAll(), self) + res = coll.join(self._rank, (output_tensor_list, input_tensor_list)) + ProcessLocalGroup._end_coll(coll, self) + return res + + def allreduce(self, tensor_list, opts=AllreduceOptions()): + coll = ProcessLocalGroup._start_coll(AllReduce(opts.reduceOp), self) + res = coll.join(self._rank, tensor_list) + ProcessLocalGroup._end_coll(coll, self) + return res + + def allreduce_coalesced(self, tensor_list, opts=AllreduceOptions()): + coll = ProcessLocalGroup._start_coll(AllReduce(opts.reduceOp), self) + res = coll.join(self._rank, tensor_list) + ProcessLocalGroup._end_coll(coll, self) + return res + + def barrier(self, opts=BarrierOptions()): + return self.allreduce(tensor_list=[torch.ones(1)]) + + def allgather(self, output_tensors, input_tensor, opts=AllgatherOptions()): + coll = ProcessLocalGroup._start_coll(AllGather(), self) + res = coll.join(self._rank, (output_tensors, input_tensor)) + ProcessLocalGroup._end_coll(coll, self) + return res + + def _allgather_base(self, output_tensor, input_tensor, opts=AllgatherOptions()): + tensor_list = list(torch.chunk(output_tensor, self._world_size)) + return self.allgather([tensor_list], [input_tensor], opts) + + def broadcast(self, tensor_list, opts=BroadcastOptions()): + coll = ProcessLocalGroup._start_coll(Broadcast(opts.rootRank), self) + res = coll.join(self._rank, tensor_list) + ProcessLocalGroup._end_coll(coll, self) + return res + + def scatter(self, output_tensors, input_tensors, opts=ScatterOptions()): + coll = ProcessLocalGroup._start_coll(Scatter(opts.rootRank), self) + res = coll.join(self._rank, (output_tensors, input_tensors)) + ProcessLocalGroup._end_coll(coll, self) + return res + + def gather(self, output_tensors, input_tensors, opts=ScatterOptions()): + coll = ProcessLocalGroup._start_coll(Gather(opts.rootRank), self) + res = coll.join(self._rank, (output_tensors, input_tensors)) + ProcessLocalGroup._end_coll(coll, self) + return res + + def reduce_scatter(self, output_tensor, scatter_list, opts=ReduceScatterOptions()): + coll = ProcessLocalGroup._start_coll(ReduceScatter(opts.reduceOp), self) + res = coll.join(self._rank, (output_tensor, scatter_list)) + ProcessLocalGroup._end_coll(coll, self) + return res + + def _reduce_scatter_base(self, output_tensor, input_tensor, opts=ReduceScatterOptions()): + tensor_list = list(torch.chunk(input_tensor, self._world_size)) + return self.reduce_scatter([output_tensor], [tensor_list], opts) + + def reduce_scatter_tensor_coalesced(self, output_tensors, input_tensors, opts=ReduceScatterOptions()): + works = [ + self._reduce_scatter_base(output_tensor, input_tensor, opts) + for output_tensor, input_tensor + in zip(output_tensors, input_tensors) + ] + for work in works[:-1]: + work.wait() + return works[-1] + + def allgather_into_tensor_coalesced(self, output_tensor_list, input_tensor_list, opts=AllgatherOptions()): + res = None + for o_t, i_t in zip(output_tensor_list, input_tensor_list): + res = self._allgather_base(o_t, i_t) + return res + + def __init__(self, rank, world_size): + super().__init__(rank, world_size) + self._rank = rank + self._world_size = world_size + world = dist.distributed_c10d._world + if isinstance(world, ThreadLocalWorld): + world = world._get_world() + self._world = weakref.ref(world) + self._ctx = torch.autograd.set_multithreading_enabled(False) + + def size(self): + return self._world_size + + @property + def pg_name(self): + """ + return the global registered name of the current pg in the world + """ + return self._world().pg_names[self] + + @property + def group_name(self): + return self.pg_name + + def getBackendName(self): + return "threaded" + + def __repr__(self): + return f"ThreadedPG world_size:{self._world_size} rank:{self._rank}" + + +def _create_threaded_pg(prefix_store, rank, world_size, timeout): + pg = ProcessLocalGroup(rank, world_size) + # https://github.com/pytorch/pytorch/pull/103033 changed store based barrier to optional + # When device mesh involves sub groups while store based barrier is not enabled in c10d, + # even though threaded pg actual collectives are assumed to be single threaded, + # different threads may be initializing different groups, + # leading to race conditions. + # For example, if we have a mesh of [[0, 1], [2, 3]], the sub groups + # (dim 0 and 1) would be initialized in different threads independently. + # In this case we can no longer rely on class or global variables + # but have to rely on store based barrier to make sure each group + # is ready separately before we can invoke collectives in any of the groups. + + # the prefix store is already per group so we pass an empty name here + _store_based_barrier(rank, prefix_store, "", world_size, timeout) + return pg + + +dist.Backend.register_backend("threaded", _create_threaded_pg, devices=["cpu", "cuda"]) + + +@dataclass +class WorldData: + default_pg: dist.ProcessGroup + pg_map: Dict[dist.ProcessGroup, Tuple[str, Optional[Store]]] + pg_names: Dict[dist.ProcessGroup, str] + pg_group_ranks: Dict[dist.ProcessGroup, Dict[int, int]] + pg_backend_config: Dict[dist.ProcessGroup, str] + group_count: int + tags_to_pg: Dict[str, List[dist.ProcessGroup]] + pg_to_tag: Dict[dist.ProcessGroup, str] + pg_coalesce_state: Dict[dist.ProcessGroup, List[Union[_CollOp, P2POp]]] + pg_default_device: Dict[dist.ProcessGroup, torch.device] + + +class ThreadLocalWorld: + _world = threading.local() + + def _get_world(self) -> WorldData: + if not hasattr(ThreadLocalWorld._world, "world"): + ThreadLocalWorld._world.world = WorldData(None, {}, {}, {}, {}, 0, {}, {}, {}, {}) + return ThreadLocalWorld._world.world + + @property + def default_pg(self): + return self._get_world().default_pg + + @default_pg.setter + def default_pg(self, value): + self._get_world().default_pg = value + + @property + def pg_map(self): + return self._get_world().pg_map + + @property + def pg_names(self): + return self._get_world().pg_names + + @property + def pg_group_ranks(self): + return self._get_world().pg_group_ranks + + @property + def pg_backend_config(self): + return self._get_world().pg_backend_config + + @property + def group_count(self) -> int: + return self._get_world().group_count + + @group_count.setter + def group_count(self, value): + self._get_world().group_count = value + + @property + def tags_to_pg(self): + return self._get_world().tags_to_pg + + @property + def pg_to_tag(self): + return self._get_world().pg_to_tag + + @property + def pg_coalesce_state(self) -> Dict[dist.ProcessGroup, List[Union[_CollOp, P2POp]]]: + return self._get_world().pg_coalesce_state + + @property + def pg_default_device(self) -> Dict[dist.ProcessGroup, torch.device]: + return self._get_world().pg_default_device + + +_old_pg_world = None +_ctx_manager = None + + +def _install_threaded_pg(): + global _old_pg_world + global _ctx_manager + _old_pg_world = dist.distributed_c10d._world + dist.distributed_c10d._world = ThreadLocalWorld() + _ctx_manager = torch.autograd.set_multithreading_enabled(False) + + return dist.distributed_c10d._world + + +def _uninstall_threaded_pg(): + dist.distributed_c10d._world = _old_pg_world diff --git a/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/ntconsole-25-w b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/ntconsole-25-w new file mode 100644 index 0000000000000000000000000000000000000000..740ed010d56371462913602ba71269bb5ca57a86 Binary files /dev/null and b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/ntconsole-25-w differ diff --git a/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/ntconsole-w b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/ntconsole-w new file mode 100644 index 0000000000000000000000000000000000000000..740ed010d56371462913602ba71269bb5ca57a86 Binary files /dev/null and b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/ntconsole-w differ diff --git a/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/opennt-25-w b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/opennt-25-w new file mode 100644 index 0000000000000000000000000000000000000000..740ed010d56371462913602ba71269bb5ca57a86 Binary files /dev/null and b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/opennt-25-w differ diff --git a/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/opennt-w b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/opennt-w new file mode 100644 index 0000000000000000000000000000000000000000..740ed010d56371462913602ba71269bb5ca57a86 Binary files /dev/null and b/shared/package-files/4f/4f9f50b1fdb89f95e293c99f37b54bbaba0d6e333db1aa0ba8a9add61bce3439/opennt-w differ diff --git a/shared/package-files/4f/4fa0163b03675b7f75523569cc9f2d7db68eb4cfe149a35adb0c89574d9fe704/deletemarker.pyi b/shared/package-files/4f/4fa0163b03675b7f75523569cc9f2d7db68eb4cfe149a35adb0c89574d9fe704/deletemarker.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b2955c01398c0e1f387b206d5423bbf15ee41799 --- /dev/null +++ b/shared/package-files/4f/4fa0163b03675b7f75523569cc9f2d7db68eb4cfe149a35adb0c89574d9fe704/deletemarker.pyi @@ -0,0 +1,12 @@ +from typing import Any, Optional + +class DeleteMarker: + bucket: Any + name: Any + version_id: Any + is_latest: bool + last_modified: Any + owner: Any + def __init__(self, bucket: Optional[Any] = ..., name: Optional[Any] = ...) -> None: ... + def startElement(self, name, attrs, connection): ... + def endElement(self, name, value, connection): ... diff --git a/shared/package-files/4f/4fa041898d20f791f2287b2aad395db5d84423df6d52ddb2e9987087a2a6efea/concatenate_compositeimplicitautograd_dispatch.h b/shared/package-files/4f/4fa041898d20f791f2287b2aad395db5d84423df6d52ddb2e9987087a2a6efea/concatenate_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..396d7ce2b976abcc67f9ed78c4c9beb5ea16ab59 --- /dev/null +++ b/shared/package-files/4f/4fa041898d20f791f2287b2aad395db5d84423df6d52ddb2e9987087a2a6efea/concatenate_compositeimplicitautograd_dispatch.h @@ -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 compositeimplicitautograd { + +TORCH_API at::Tensor concatenate(at::TensorList tensors, int64_t dim=0); +TORCH_API at::Tensor & concatenate_out(at::Tensor & out, at::TensorList tensors, int64_t dim=0); +TORCH_API at::Tensor & concatenate_outf(at::TensorList tensors, int64_t dim, at::Tensor & out); +TORCH_API at::Tensor concatenate(at::TensorList tensors, at::Dimname dim); +TORCH_API at::Tensor & concatenate_out(at::Tensor & out, at::TensorList tensors, at::Dimname dim); +TORCH_API at::Tensor & concatenate_outf(at::TensorList tensors, at::Dimname dim, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/4f/4fa129e7386c94129b61a10215407a8142a1de24d93f23285b59238689f1ad4a/GMT+2 b/shared/package-files/4f/4fa129e7386c94129b61a10215407a8142a1de24d93f23285b59238689f1ad4a/GMT+2 new file mode 100644 index 0000000000000000000000000000000000000000..fbd2a941fda996f4abc1f0e09cdf99c271f5a1e2 Binary files /dev/null and b/shared/package-files/4f/4fa129e7386c94129b61a10215407a8142a1de24d93f23285b59238689f1ad4a/GMT+2 differ diff --git a/shared/package-files/4f/4fa8727a5c1f4a9dfb32d88ddcd892217206141fa29a1ffe3f0f0b92577541ed/tek4106brl b/shared/package-files/4f/4fa8727a5c1f4a9dfb32d88ddcd892217206141fa29a1ffe3f0f0b92577541ed/tek4106brl new file mode 100644 index 0000000000000000000000000000000000000000..495593e6623aba95bebb9791166e08f0722c573d Binary files /dev/null and b/shared/package-files/4f/4fa8727a5c1f4a9dfb32d88ddcd892217206141fa29a1ffe3f0f0b92577541ed/tek4106brl differ diff --git a/shared/package-files/4f/4fa8727a5c1f4a9dfb32d88ddcd892217206141fa29a1ffe3f0f0b92577541ed/tek4109brl b/shared/package-files/4f/4fa8727a5c1f4a9dfb32d88ddcd892217206141fa29a1ffe3f0f0b92577541ed/tek4109brl new file mode 100644 index 0000000000000000000000000000000000000000..495593e6623aba95bebb9791166e08f0722c573d Binary files /dev/null and b/shared/package-files/4f/4fa8727a5c1f4a9dfb32d88ddcd892217206141fa29a1ffe3f0f0b92577541ed/tek4109brl differ diff --git a/shared/package-files/4f/4fa9014ca79860690cf3749b6e0571f4bdfc79a660a8463e02481f08bafd19b5/sre_constants.pyi b/shared/package-files/4f/4fa9014ca79860690cf3749b6e0571f4bdfc79a660a8463e02481f08bafd19b5/sre_constants.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bc15754d6fa1b3da9e2a2645fe984b3e998870a9 --- /dev/null +++ b/shared/package-files/4f/4fa9014ca79860690cf3749b6e0571f4bdfc79a660a8463e02481f08bafd19b5/sre_constants.pyi @@ -0,0 +1,93 @@ +from typing import Dict, List, TypeVar + +MAGIC: int +MAXREPEAT: int + +class error(Exception): ... + +FAILURE: str +SUCCESS: str +ANY: str +ANY_ALL: str +ASSERT: str +ASSERT_NOT: str +AT: str +BIGCHARSET: str +BRANCH: str +CALL: str +CATEGORY: str +CHARSET: str +GROUPREF: str +GROUPREF_IGNORE: str +GROUPREF_EXISTS: str +IN: str +IN_IGNORE: str +INFO: str +JUMP: str +LITERAL: str +LITERAL_IGNORE: str +MARK: str +MAX_REPEAT: str +MAX_UNTIL: str +MIN_REPEAT: str +MIN_UNTIL: str +NEGATE: str +NOT_LITERAL: str +NOT_LITERAL_IGNORE: str +RANGE: str +REPEAT: str +REPEAT_ONE: str +SUBPATTERN: str +MIN_REPEAT_ONE: str +AT_BEGINNING: str +AT_BEGINNING_LINE: str +AT_BEGINNING_STRING: str +AT_BOUNDARY: str +AT_NON_BOUNDARY: str +AT_END: str +AT_END_LINE: str +AT_END_STRING: str +AT_LOC_BOUNDARY: str +AT_LOC_NON_BOUNDARY: str +AT_UNI_BOUNDARY: str +AT_UNI_NON_BOUNDARY: str +CATEGORY_DIGIT: str +CATEGORY_NOT_DIGIT: str +CATEGORY_SPACE: str +CATEGORY_NOT_SPACE: str +CATEGORY_WORD: str +CATEGORY_NOT_WORD: str +CATEGORY_LINEBREAK: str +CATEGORY_NOT_LINEBREAK: str +CATEGORY_LOC_WORD: str +CATEGORY_LOC_NOT_WORD: str +CATEGORY_UNI_DIGIT: str +CATEGORY_UNI_NOT_DIGIT: str +CATEGORY_UNI_SPACE: str +CATEGORY_UNI_NOT_SPACE: str +CATEGORY_UNI_WORD: str +CATEGORY_UNI_NOT_WORD: str +CATEGORY_UNI_LINEBREAK: str +CATEGORY_UNI_NOT_LINEBREAK: str + +_T = TypeVar("_T") + +def makedict(list: List[_T]) -> Dict[_T, int]: ... + +OP_IGNORE: Dict[str, str] +AT_MULTILINE: Dict[str, str] +AT_LOCALE: Dict[str, str] +AT_UNICODE: Dict[str, str] +CH_LOCALE: Dict[str, str] +CH_UNICODE: Dict[str, str] +SRE_FLAG_TEMPLATE: int +SRE_FLAG_IGNORECASE: int +SRE_FLAG_LOCALE: int +SRE_FLAG_MULTILINE: int +SRE_FLAG_DOTALL: int +SRE_FLAG_UNICODE: int +SRE_FLAG_VERBOSE: int +SRE_FLAG_DEBUG: int +SRE_INFO_PREFIX: int +SRE_INFO_LITERAL: int +SRE_INFO_CHARSET: int diff --git a/shared/package-files/4f/4faa8f364535109e83e419efc8949726fe33789e4c513e512eca2f3249174bd1/__init__.py b/shared/package-files/4f/4faa8f364535109e83e419efc8949726fe33789e4c513e512eca2f3249174bd1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6839b4494afd0ee0c0ecd9ddee65d1afbdc6b53 --- /dev/null +++ b/shared/package-files/4f/4faa8f364535109e83e419efc8949726fe33789e4c513e512eca2f3249174bd1/__init__.py @@ -0,0 +1,57 @@ +"""Implementation of mathematical domains. """ + +__all__ = [ + 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField', + 'ComplexField', 'AlgebraicField', 'PolynomialRing', 'FractionField', + 'ExpressionDomain', 'PythonRational', + + 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', +] + +from .domain import Domain +from .finitefield import FiniteField, FF, GF +from .integerring import IntegerRing, ZZ +from .rationalfield import RationalField, QQ +from .algebraicfield import AlgebraicField +from .gaussiandomains import ZZ_I, QQ_I +from .realfield import RealField, RR +from .complexfield import ComplexField, CC +from .polynomialring import PolynomialRing +from .fractionfield import FractionField +from .expressiondomain import ExpressionDomain, EX +from .expressionrawdomain import EXRAW +from .pythonrational import PythonRational + + +# This is imported purely for backwards compatibility because some parts of +# the codebase used to import this from here and it's possible that downstream +# does as well: +from sympy.external.gmpy import GROUND_TYPES # noqa: F401 + +# +# The rest of these are obsolete and provided only for backwards +# compatibility: +# + +from .pythonfinitefield import PythonFiniteField +from .gmpyfinitefield import GMPYFiniteField +from .pythonintegerring import PythonIntegerRing +from .gmpyintegerring import GMPYIntegerRing +from .pythonrationalfield import PythonRationalField +from .gmpyrationalfield import GMPYRationalField + +FF_python = PythonFiniteField +FF_gmpy = GMPYFiniteField + +ZZ_python = PythonIntegerRing +ZZ_gmpy = GMPYIntegerRing + +QQ_python = PythonRationalField +QQ_gmpy = GMPYRationalField + +__all__.extend(( + 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', + 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', + + 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', +)) diff --git a/shared/package-files/4f/4faa90039964cd6945a9c05e46a058aaaafc5b6b069a9f1453c9d8435fbc99df/pixel_shuffle_compositeexplicitautograd_dispatch.h b/shared/package-files/4f/4faa90039964cd6945a9c05e46a058aaaafc5b6b069a9f1453c9d8435fbc99df/pixel_shuffle_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9a81b814bde4a3c77f00dde1923e620230f02865 --- /dev/null +++ b/shared/package-files/4f/4faa90039964cd6945a9c05e46a058aaaafc5b6b069a9f1453c9d8435fbc99df/pixel_shuffle_compositeexplicitautograd_dispatch.h @@ -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 & pixel_shuffle_out(at::Tensor & out, const at::Tensor & self, int64_t upscale_factor); +TORCH_API at::Tensor & pixel_shuffle_outf(const at::Tensor & self, int64_t upscale_factor, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/4f/4faabdfd51d217d09aef26361494fa16a6e9d1ee5f9735c53d4e20e949a3ada5/backend_tools.pyi b/shared/package-files/4f/4faabdfd51d217d09aef26361494fa16a6e9d1ee5f9735c53d4e20e949a3ada5/backend_tools.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fa89e3d66871a65dc718f049f5a1f72b529299b7 --- /dev/null +++ b/shared/package-files/4f/4faabdfd51d217d09aef26361494fa16a6e9d1ee5f9735c53d4e20e949a3ada5/backend_tools.pyi @@ -0,0 +1,121 @@ +import enum +from matplotlib import cbook +from matplotlib.axes import Axes +from matplotlib.backend_bases import ToolContainerBase, FigureCanvasBase +from matplotlib.backend_managers import ToolManager, ToolEvent +from matplotlib.figure import Figure +from matplotlib.scale import ScaleBase + +from typing import Any, cast + +class Cursors(enum.IntEnum): + POINTER = cast(int, ...) + HAND = cast(int, ...) + SELECT_REGION = cast(int, ...) + MOVE = cast(int, ...) + WAIT = cast(int, ...) + RESIZE_HORIZONTAL = cast(int, ...) + RESIZE_VERTICAL = cast(int, ...) + +cursors = Cursors + +class ToolBase: + @property + def default_keymap(self) -> list[str] | None: ... + description: str | None + image: str | None + def __init__(self, toolmanager: ToolManager, name: str) -> None: ... + @property + def name(self) -> str: ... + @property + def toolmanager(self) -> ToolManager: ... + @property + def canvas(self) -> FigureCanvasBase | None: ... + @property + def figure(self) -> Figure | None: ... + @figure.setter + def figure(self, figure: Figure | None) -> None: ... + def set_figure(self, figure: Figure | None) -> None: ... + def trigger(self, sender: Any, event: ToolEvent, data: Any = ...) -> None: ... + +class ToolToggleBase(ToolBase): + radio_group: str | None + cursor: Cursors | None + default_toggled: bool + def __init__(self, *args, **kwargs) -> None: ... + def enable(self, event: ToolEvent | None = ...) -> None: ... + def disable(self, event: ToolEvent | None = ...) -> None: ... + @property + def toggled(self) -> bool: ... + def set_figure(self, figure: Figure | None) -> None: ... + +class ToolSetCursor(ToolBase): ... + +class ToolCursorPosition(ToolBase): + def send_message(self, event: ToolEvent) -> None: ... + +class RubberbandBase(ToolBase): + def draw_rubberband(self, *data) -> None: ... + def remove_rubberband(self) -> None: ... + +class ToolQuit(ToolBase): ... +class ToolQuitAll(ToolBase): ... +class ToolGrid(ToolBase): ... +class ToolMinorGrid(ToolBase): ... +class ToolFullScreen(ToolBase): ... + +class AxisScaleBase(ToolToggleBase): + def enable(self, event: ToolEvent | None = ...) -> None: ... + def disable(self, event: ToolEvent | None = ...) -> None: ... + +class ToolYScale(AxisScaleBase): + def set_scale(self, ax: Axes, scale: str | ScaleBase) -> None: ... + +class ToolXScale(AxisScaleBase): + def set_scale(self, ax, scale: str | ScaleBase) -> None: ... + +class ToolViewsPositions(ToolBase): + views: dict[Figure | Axes, cbook._Stack] + positions: dict[Figure | Axes, cbook._Stack] + home_views: dict[Figure, dict[Axes, tuple[float, float, float, float]]] + def add_figure(self, figure: Figure) -> None: ... + def clear(self, figure: Figure) -> None: ... + def update_view(self) -> None: ... + def push_current(self, figure: Figure | None = ...) -> None: ... + def update_home_views(self, figure: Figure | None = ...) -> None: ... + def home(self) -> None: ... + def back(self) -> None: ... + def forward(self) -> None: ... + +class ViewsPositionsBase(ToolBase): ... +class ToolHome(ViewsPositionsBase): ... +class ToolBack(ViewsPositionsBase): ... +class ToolForward(ViewsPositionsBase): ... +class ConfigureSubplotsBase(ToolBase): ... +class SaveFigureBase(ToolBase): ... + +class ZoomPanBase(ToolToggleBase): + base_scale: float + scrollthresh: float + lastscroll: float + def __init__(self, *args) -> None: ... + def enable(self, event: ToolEvent | None = ...) -> None: ... + def disable(self, event: ToolEvent | None = ...) -> None: ... + def scroll_zoom(self, event: ToolEvent) -> None: ... + +class ToolZoom(ZoomPanBase): ... +class ToolPan(ZoomPanBase): ... + +class ToolHelpBase(ToolBase): + @staticmethod + def format_shortcut(key_sequence: str) -> str: ... + +class ToolCopyToClipboardBase(ToolBase): ... + +default_tools: dict[str, type[ToolBase]] +default_toolbar_tools: list[list[str | list[str]]] + +def add_tools_to_manager( + toolmanager: ToolManager, tools: dict[str, type[ToolBase]] | None = ... +) -> None: ... +def add_tools_to_container(container: ToolContainerBase, tools: list[Any] | None = ...) -> None: ... diff --git a/shared/package-files/4f/4fab9acc086763c73b0bc037a99f0782971954dc63ca3e23d8289f4981aca6f9/f1720 b/shared/package-files/4f/4fab9acc086763c73b0bc037a99f0782971954dc63ca3e23d8289f4981aca6f9/f1720 new file mode 100644 index 0000000000000000000000000000000000000000..13837dc3b8736d9726b637bd1f2678b113c96e80 Binary files /dev/null and b/shared/package-files/4f/4fab9acc086763c73b0bc037a99f0782971954dc63ca3e23d8289f4981aca6f9/f1720 differ diff --git a/shared/package-files/4f/4fae3a20f1bdf3e84e31faa6a4dd68098d1cdda5d808536f2aa42943f74d959c/wy75 b/shared/package-files/4f/4fae3a20f1bdf3e84e31faa6a4dd68098d1cdda5d808536f2aa42943f74d959c/wy75 new file mode 100644 index 0000000000000000000000000000000000000000..e499b1fc85e21054bd573a955c2ad5cfce6eeb8f Binary files /dev/null and b/shared/package-files/4f/4fae3a20f1bdf3e84e31faa6a4dd68098d1cdda5d808536f2aa42943f74d959c/wy75 differ diff --git a/shared/package-files/4f/4fb3001bfe695fa625c1f9f728e46d9b67aa6706eba7cdf19008d3ff7b6ced3a/convolution_backward_native.h b/shared/package-files/4f/4fb3001bfe695fa625c1f9f728e46d9b67aa6706eba7cdf19008d3ff7b6ced3a/convolution_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..74b714200721096db1d00d48d13c463e7e08d9d7 --- /dev/null +++ b/shared/package-files/4f/4fb3001bfe695fa625c1f9f728e46d9b67aa6706eba7cdf19008d3ff7b6ced3a/convolution_backward_native.h @@ -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 convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask); +TORCH_API ::std::tuple convolution_backward_out_symint(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalSymIntArrayRef bias_sizes, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +} // namespace native +} // namespace at diff --git a/shared/package-files/4f/4fb9cc5d746406aa302c19eeb02dae40285f7a0bb3a4c1f384f95cc4ede1048e/symbolic_helper.py b/shared/package-files/4f/4fb9cc5d746406aa302c19eeb02dae40285f7a0bb3a4c1f384f95cc4ede1048e/symbolic_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..fbba99c4ec69383f7b4c0547af988bb444afce85 --- /dev/null +++ b/shared/package-files/4f/4fb9cc5d746406aa302c19eeb02dae40285f7a0bb3a4c1f384f95cc4ede1048e/symbolic_helper.py @@ -0,0 +1,1823 @@ +from __future__ import annotations + +import functools +import inspect +import sys +import typing +import warnings +from typing import ( + Any, + Callable, + List, + Literal, + NoReturn, + Optional, + Sequence, + Set, + Tuple, + Union, +) + +import torch +import torch._C._onnx as _C_onnx +from torch import _C + +# Monkey-patch graph manipulation methods on Graph, used for the ONNX symbolics +from torch.onnx import _constants, _type_utils, errors +from torch.onnx._globals import GLOBALS +from torch.onnx._internal import _beartype, jit_utils +from torch.types import Number + +__all__ = [ + "args_have_same_dtype", + "cast_pytorch_to_onnx", + "check_training_mode", + "dequantize_helper", + "is_caffe2_aten_fallback", + "is_complex_value", + "parse_args", + "pytorch_name_to_type", + "quantize_helper", + "quantized_args", + "requantize_bias_helper", + "scalar_name_to_pytorch", + "scalar_type_to_onnx", + "scalar_type_to_pytorch_type", +] + +# --------------------------------------------------------------------------------- +# Helper functions +# --------------------------------------------------------------------------------- + +_ValueDescriptor = Literal[ + "v", + "i", + "is", + "f", + "fs", + "b", + "s", + "t", + "none", +] + + +@_beartype.beartype +def _parse_arg( + value, + desc: _ValueDescriptor, + arg_name: Optional[str] = None, + node_name: Optional[str] = None, +): + if desc == "none": + return value + if desc == "v" or not _is_value(value): + return value + + node = value.node() + if node.mustBeNone(): + return None + if node.kind() == "onnx::Constant": + node_val = _node_get(node, "value") + if desc == "i": + return int(node_val) + elif desc == "f": + return float(node_val) + elif desc == "b": + return bool(node_val) + elif desc == "s": + return str(node_val) + elif desc == "t": + return node_val + elif desc == "is": + return [int(v) for v in node_val] + elif desc == "fs": + return [float(v) for v in node_val] + else: + raise errors.SymbolicValueError( + f"ONNX symbolic does not understand the Constant node '{node}' " + f"specified with descriptor '{desc}'.", + value, + ) + elif node.kind() == "prim::ListConstruct": + if desc == "is": + for v in node.inputs(): + element_node = v.node() + if element_node.kind() != "onnx::Constant": + raise errors.SymbolicValueError( + f"Failed to export a node '{element_node}' " + f"(in list node {node}) " + f"because it is not constant. " + f"Please try to make things (e.g. kernel sizes) static if possible.", + value, + ) + return [int(_node_get(v.node(), "value")) for v in value.node().inputs()] + else: + raise errors.SymbolicValueError( + f"ONNX symbolic does not know how to unpack the ListConstruct node that " + f"is not a list of integers: '{node}'", + value, + ) + + if arg_name is None or node_name is None: + raise errors.SymbolicValueError( + f"Expected node type 'onnx::Constant', got '{node.kind()}'.", + value, + ) + + raise errors.SymbolicValueError( + "Expected node type 'onnx::Constant' " + f"for argument '{arg_name}' of node '{node_name}', got '{node.kind()}'.", + value, + ) + + +@_beartype.beartype +def _node_get(node: _C.Node, key: str): + """Gets attributes of a node which is polymorphic over return type.""" + assert isinstance(node, _C.Node) + sel = node.kindOf(key) + return getattr(node, sel)(key) + + +@_beartype.beartype +def _is_onnx_constant(value: _C.Value): + """Whether a Value is an ONNX constant.""" + return value.node().kind() == "onnx::Constant" + + +@_beartype.beartype +def _maybe_get_const( + value: Optional[Union[_C.Value, torch.Tensor, Number, Sequence]], + descriptor: _ValueDescriptor, +): + # NOTE: prim::Constant at this stage usually means something not compatible in ONNX, + # otherwise it'd be converted to onnx::Constant + # TODO(justinchuby): Replace insinstance with _is_value once we figure out mypy + if isinstance(value, _C.Value) and _is_onnx_constant(value): + return _parse_arg(value, descriptor) + return value + + +@_beartype.beartype +def _maybe_get_scalar(value): + value_t = _maybe_get_const(value, "t") + if isinstance(value_t, torch.Tensor) and value_t.shape == (): + return value_t + return value + + +@_beartype.beartype +def _get_const(value, desc, arg_name): + if not _is_constant(value): + raise errors.SymbolicValueError( + f"ONNX symbolic expected a constant value of the '{arg_name}' argument, " + f"got '{value}'", + value, + ) + return _parse_arg(value, desc) + + +@_beartype.beartype +def _unpack_list(list_value: _C.Value) -> List[_C.Value]: + list_node = list_value.node() + if list_node.kind() != "prim::ListConstruct": + raise errors.SymbolicValueError( + f"ONNX symbolic expected node type prim::ListConstruct, " + f"got '{list_node}'.", + list_value, + ) + return list(list_node.inputs()) + + +@_beartype.beartype +def _unpack_tuple(tuple_value: _C.Value) -> Tuple[_C.Value, ...]: + tuple_node = tuple_value.node() + if not _is_tuple_construct(tuple_value): + raise errors.SymbolicValueError( + f"ONNX symbolic expected node type 'prim::TupleConstruct', " + f"got '{tuple_node.kind()}'.", + tuple_value, + ) + return tuple(tuple_node.inputs()) + + +@_beartype.beartype +def _unpack_quantized_tensor(tuple_value: _C.Value) -> Tuple[_C.Value, ...]: + """Unpacks a quantized tensor into a tuple of tensor and scale/zero_point. + Args: + tuple_value: A tuple of tensor, scale, zero_point, and optionally axis. + Returns: + A tuple of tensor, scale, zero_point, and optionally axis. + """ + tuple_node = tuple_value.node() + # A quantized tensor is represented as tuple of the form (tensor, scale, zero_point, ) + if not _is_tuple_construct(tuple_value): + raise errors.SymbolicValueError( + f"ONNX symbolic expected the output of `{tuple_node}` to be a quantized " + f"tensor. Is this likely due to missing support for quantized " + f"`{tuple_node.kind()}`. Please create an issue on {_constants.PYTORCH_GITHUB_ISSUES_URL}", + tuple_value, + ) + unpacked = tuple(tuple_node.inputs()) + assert len(unpacked) == 3 or len(unpacked) == 4 + return unpacked + + +# Check if list_value is output from prim::ListConstruct +# This is usually called before _unpack_list to ensure the list can be unpacked. +@_beartype.beartype +def _is_packed_list(list_value: Any) -> bool: + return _is_value(list_value) and list_value.node().kind() == "prim::ListConstruct" + + +@_beartype.beartype +def parse_args(*arg_descriptors: _ValueDescriptor): + """A decorator which converts args from torch._C.Value to built-in types. + + For example: + + ``` + @parse_args('v', 'i', 'fs') + foo(g, a, b, c): + assert isinstance(a, torch._C.Value) + assert isinstance(b, int) + assert isinstance(c, list) + assert isinstance(c[0], float) + ``` + + Args: + arg_descriptors: list of str, where each element is + a string that specifies the type to convert to. Valid descriptors: + "v": no conversion, keep torch._C.Value. + "i": int + "is": list of int + "f": float + "fs": list of float + "b": bool + "s": str + "t": torch.Tensor + "none": the variable is unused + """ + + def decorator(fn): + fn._arg_descriptors = arg_descriptors + + @functools.wraps(fn) + def wrapper(g, *args, **kwargs): + # some args may be optional, so the length may be smaller + FILE_BUG_MSG = ( + "If you believe this is not due to custom symbolic implementation within your code or " + "an external library, please file an issue at " + "https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml to report this bug." + ) + assert len(arg_descriptors) >= len(args), ( + f"A mismatch between the number of arguments ({len(args)}) and " + f"their descriptors ({len(arg_descriptors)}) was found at symbolic function '{fn.__name__}'. " + f"{FILE_BUG_MSG}" + ) + + try: + sig = inspect.signature(fn) + arg_names = list(sig.parameters.keys())[1:] + fn_name = fn.__name__ + except Exception: + # FIXME(justinchuby): Avoid catching Exception. + # Catch a more specific exception instead. + arg_names = [None] * len(args) # type: ignore[list-item] + fn_name = None + args = [ + _parse_arg(arg, arg_desc, arg_name, fn_name) # type: ignore[method-assign] + for arg, arg_desc, arg_name in zip(args, arg_descriptors, arg_names) + ] + # only support _outputs in kwargs + assert len(kwargs) <= 1, ( + f"Symbolic function {fn.__name__}'s '**kwargs' can contain a single " + f"key/value entry. " + f"{FILE_BUG_MSG}" + ) + + if len(kwargs) == 1: + assert "_outputs" in kwargs, ( + f"Symbolic function {fn.__name__}'s '**kwargs' can only contain " + f"'_outputs' key at '**kwargs'. " + f"{FILE_BUG_MSG}" + ) + return fn(g, *args, **kwargs) + + return wrapper + + return decorator + + +@_beartype.beartype +def quantized_args( + *arg_q_descriptors: bool, + scale: Optional[float] = None, + zero_point: Optional[int] = None, + quantize_output: bool = True, +): + """A decorator which extends support for quantized version of the base operator. + + Quantization is detected by examining the arguments that are annotated by + `arg_q_descriptors`. + + If quantization is detected, the base operator symbolic function will be wrapped with + argument de-quantization and output quantization. + + Otherwise, only the base symbolic function will be invoked. + + For example: + + ``` + @quantized_args(True, False) + def foo(g, x, y): + return x + y + ``` + + is equivalent to + + ``` + def q_foo(g, x, y): + if is_quantized_tensor(x): + x = dequantize(x) + out = foo(g, x, y) + return quantize(out) + else: + return foo(g, x, y) + ``` + + Args: + arg_q_descriptors: A sequence of bool, where each element represents if the + argument is QTensor for quantized version of this operator. It defaults + to False for unspecified (variable length) arguments. + scale: Quantized output scale. If None, derive from + the first quantized input scale. + zero_point: Quantized output zero point. If None, + derive from the first quantized input zero point. + quantize_output: If True, quantize the output of the base operator. Default is True + """ + + def decorator(fn): + @functools.wraps(fn) + def wrapper(g, *args, **kwargs): + nonlocal scale + nonlocal zero_point + if scale is not None: + _scale = g.op("Constant", value_t=torch.tensor(scale)) + else: + _scale = None + if zero_point is not None: + _zero_point = g.op("Constant", value_t=torch.tensor(zero_point)) + else: + _zero_point = None + + # Support variable length arguments by marking unspecified ones as non-quantized + arg_q_descriptors_extended = arg_q_descriptors + (False,) * ( + len(args) - len(arg_q_descriptors) + ) + descriptor_args = tuple(zip(arg_q_descriptors_extended, args)) + + def _is_arg_quantized(descriptor, arg): + return descriptor and _is_value(arg) and _is_tuple_construct(arg) + + # Run regular symbolic function if none of the argument is QTensor. + is_quantized = list() + for descriptor, arg in descriptor_args: + # ListConstruct + if _is_packed_list(arg): + for arg_input in arg.node().inputs(): + is_quantized.append(_is_arg_quantized(descriptor, arg_input)) + else: + is_quantized.append(_is_arg_quantized(descriptor, arg)) + + if not any(is_quantized): + return fn(g, *args, **kwargs) + + # Dequantize arguments that are quantized + non_quantized_args = [] + for descriptor, arg in descriptor_args: + if _is_arg_quantized(descriptor, arg): + # Quantized arg is a tuple of (value, scale, zero_point) + dequantized_arg, arg_scale, arg_zero_point, _ = dequantize_helper( + g, arg + ) + non_quantized_args.append(dequantized_arg) + # Set scale and zero_point to the first quantized input if not already set + if _scale is None: + _scale = arg_scale + if _zero_point is None: + _zero_point = arg_zero_point + # ListConstruct + elif _is_packed_list(arg): + for arg_input in arg.node().inputs(): + if _is_arg_quantized(descriptor, arg_input): + # Quantized arg is a tuple of (value, scale, zero_point) + ( + dequantized_arg, + arg_scale, + arg_zero_point, + _, + ) = dequantize_helper(g, arg_input) + # Set scale and zero_point to the first quantized input if not already set + if _scale is None: + _scale = arg_scale + if _zero_point is None: + _zero_point = arg_zero_point + arg_input.replaceAllUsesWith(dequantized_arg) + non_quantized_args.append(arg) + else: + # Non-quantized arg + non_quantized_args.append(arg) + # TODO(justinchuby): Only single output is supported for now. We may want to + # support multiple outputs in the future. + output = fn(g, *non_quantized_args, **kwargs) + + assert _scale is not None, "Bug: Scale must be set for quantized operator" + assert ( + _zero_point is not None + ), "Bug: Zero point must be set for quantized operator" + + if quantize_output: + return quantize_helper(g, output, _scale, _zero_point) + return output + + return wrapper + + return decorator + + +@_beartype.beartype +def _scalar(x: Any) -> Optional[Number]: + """Convert a scalar tensor into a Python value.""" + if isinstance(x, torch.Tensor) and x.shape == (): + return x.item() + return None + + +@_beartype.beartype +def _if_scalar_type_as(self, tensor): + """ + Convert self into the same type of tensor, as necessary. + We only support implicit casting for scalars, so we never + actually need to insert an ONNX cast operator here; just + fix up the scalar. + """ + if isinstance(self, _C.Value): + return self + + scalar_type = _type_utils.JitScalarType.from_value( + tensor, _type_utils.JitScalarType.UNDEFINED + ) + if scalar_type != _type_utils.JitScalarType.UNDEFINED: + ty = scalar_type.scalar_name().lower() + return getattr(self, ty)() + return self + + +@_beartype.beartype +def _is_none(x: Any) -> bool: + return x is None or (x.node().mustBeNone() if isinstance(x, _C.Value) else False) + + +@_beartype.beartype +def _is_value(x: Any) -> bool: + return isinstance(x, _C.Value) + + +@_beartype.beartype +def _is_constant(value: Any) -> bool: + return not _is_value(value) or value.node().kind() in { + "onnx::Constant", + "prim::Constant", + } + + +@_beartype.beartype +def _is_tensor(x: _C.Value) -> bool: + return x.type().isSubtypeOf(_C.TensorType.get()) + + +# Note: _C.JitType is not exposed to Python and cannot be checked in runtime. +def _as_list_type(jit_type: _C.JitType) -> Optional[_C.ListType]: + if isinstance(jit_type, _C.ListType): + return jit_type + return None + + +@_beartype.beartype +def _is_list(x: _C.Value) -> bool: + return _as_list_type(x.type()) is not None + + +@_beartype.beartype +def _is_tensor_list(x: _C.Value) -> bool: + x_type = _as_list_type(x.type()) + if x_type is None: + return False + return isinstance(x_type.getElementType(), _C.TensorType) + + +@_beartype.beartype +def _is_scalar_list(x: _C.Value) -> bool: + """Checks if x is a scalar list, for example: List[float], List[int]. + + Besides checking the type is ListType, we also check if the data type is + a valid ONNX data type. + """ + x_type = _as_list_type(x.type()) + if x_type is None: + return False + scalar_type = _type_utils.JitScalarType.from_value(x) + return scalar_type.onnx_compatible() + + +@_beartype.beartype +def _is_tuple_construct(x: _C.Value) -> bool: + return x.node().kind() == "prim::TupleConstruct" + + +@_beartype.beartype +def is_complex_value(x: _C.Value) -> bool: + assert _is_value(x) + return _type_utils.JitScalarType.from_value( + x, _type_utils.JitScalarType.UNDEFINED + ) in { + _type_utils.JitScalarType.COMPLEX32, + _type_utils.JitScalarType.COMPLEX64, + _type_utils.JitScalarType.COMPLEX128, + } + + +@_beartype.beartype +def is_caffe2_aten_fallback() -> bool: + return ( + GLOBALS.operator_export_type == _C_onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK + and _C_onnx._CAFFE2_ATEN_FALLBACK + ) + + +@_beartype.beartype +def _get_tensor_rank(x: _C.Value) -> Optional[int]: + if not _is_tensor(x) or x.type() is None: + return None + x_type = x.type() + x_type = typing.cast(_C.TensorType, x_type) + return x_type.dim() + + +@_beartype.beartype +def _get_tensor_sizes(x: _C.Value, allow_nonstatic: bool = True): + if not _is_tensor(x) or x.type() is None: + return None + x_type = x.type() + x_type = typing.cast(_C.TensorType, x_type) + if allow_nonstatic: + # Each individual symbol is returned as None. + # e.g. [1, "a", "b"] -> [1, None, None] + return x_type.varyingSizes() + # returns None, if exists any symbol in sizes. + # e.g. [1, "a", "b"] -> None + return x_type.sizes() + + +@_beartype.beartype +def _get_tensor_dim_size(x: _C.Value, dim: int) -> Optional[int]: + sizes = _get_tensor_sizes(x) + return sizes[dim] if sizes else None + + +@_beartype.beartype +def _get_dim_for_cross(x: _C.Value, dim: Optional[int]): + if dim == -1: + tensor_rank = _get_tensor_rank(x) + assert tensor_rank is not None + return dim + tensor_rank + # If dim is not given, it defaults to the first dimension found with the size 3 + if dim is None: + sizes = _get_tensor_sizes(x) + assert sizes is not None + for index, size in enumerate(sizes): + if size is not None and size == 3: + return index + return dim + + +@_beartype.beartype +def _unimplemented(op: str, msg: str, value: Optional[_C.Value] = None) -> None: + # For BC reasons, the behavior for Caffe2 does not raise exception for unimplemented operators + if _C_onnx._CAFFE2_ATEN_FALLBACK: + warnings.warn(f"ONNX export failed on {op} because {msg} not supported") + elif GLOBALS.operator_export_type == _C_onnx.OperatorExportTypes.ONNX: + _onnx_unsupported(f"{op}, {msg}", value) + + +@_beartype.beartype +def _onnx_unsupported(op_name: str, value: Optional[_C.Value] = None) -> NoReturn: + message = ( + f"Unsupported: ONNX export of operator {op_name}. " + f"Please feel free to request support or submit a pull request " + f"on PyTorch GitHub: {_constants.PYTORCH_GITHUB_ISSUES_URL}" + ) + if isinstance(value, _C.Value): + raise errors.SymbolicValueError( + message, + value, + ) + raise errors.OnnxExporterError(message) + + +@_beartype.beartype +def _onnx_opset_unsupported( + op_name: str, + current_opset: int, + supported_opset: int, + value: Optional[_C.Value] = None, +) -> NoReturn: + message = ( + f"Unsupported: ONNX export of {op_name} in opset {current_opset}. " + f"Please try opset version {supported_opset}." + ) + if isinstance(value, _C.Value): + raise errors.SymbolicValueError( + message, + value, + ) + raise errors.OnnxExporterError(message) + + +@_beartype.beartype +def _onnx_opset_unsupported_detailed( + op_name: str, + current_opset: int, + supported_opset: int, + reason: str, + value: Optional[_C.Value] = None, +) -> NoReturn: + message = ( + f"Unsupported: ONNX export of {op_name} in " + f"opset {current_opset}. {reason}. Please try opset version {supported_opset}." + ) + if isinstance(value, _C.Value): + raise errors.SymbolicValueError( + message, + value, + ) + raise errors.OnnxExporterError(message) + + +@_beartype.beartype +def _block_list_in_opset(name: str): + def symbolic_fn(*args, **kwargs): + raise errors.OnnxExporterError( + f"ONNX export failed on {name}, which is not implemented for opset " + f"{GLOBALS.export_onnx_opset_version}. " + "Try exporting with other opset versions." + ) + + return symbolic_fn + + +@_beartype.beartype +def _try_get_scalar_type(*args) -> Optional[_type_utils.JitScalarType]: + for arg in args: + scalar_type = _type_utils.JitScalarType.from_value( + arg, _type_utils.JitScalarType.UNDEFINED + ) + if scalar_type != _type_utils.JitScalarType.UNDEFINED: + return scalar_type + return None + + +@_beartype.beartype +def _select_helper(g: jit_utils.GraphContext, self, dim, index, apply_reshape=True): + index_const = _maybe_get_scalar(index) + index_dim = _get_tensor_rank(index) + if not _is_value(index_const): + # Index is a constant scalar. Make it a size 1 constant tensor. + index = g.op("Constant", value_t=torch.LongTensor([index_const])) + elif index_dim is not None and apply_reshape: + if index_dim == 0: + # Index is a scalar. Reshape it to a size 1 tensor. + index = _reshape_helper( + g, index, g.op("Constant", value_t=torch.LongTensor([1])) + ) + + index_scalar_type = _type_utils.JitScalarType.from_value( + index, _type_utils.JitScalarType.UNDEFINED + ) + if index_scalar_type not in { + _type_utils.JitScalarType.INT64, + _type_utils.JitScalarType.INT, + }: + index = g.op("Cast", index, to_i=_C_onnx.TensorProtoDataType.INT64) + return g.op("Gather", self, index, axis_i=dim) + + +@_beartype.beartype +def _slice_helper( + g: jit_utils.GraphContext, + input, + axes, + starts, + ends, + steps=None, +): + if g.opset <= 9: + from torch.onnx.symbolic_opset9 import _slice as _slice9 + + return _slice9(g, input, axes, starts, ends) + else: + from torch.onnx.symbolic_opset10 import _slice as _slice10 + + return _slice10(g, input, axes, starts, ends, steps) + + +@_beartype.beartype +def _is_fp(value) -> bool: + return _type_utils.JitScalarType.from_value( + value, _type_utils.JitScalarType.UNDEFINED + ) in { + _type_utils.JitScalarType.FLOAT, + _type_utils.JitScalarType.DOUBLE, + _type_utils.JitScalarType.HALF, + _type_utils.JitScalarType.BFLOAT16, + } + + +@_beartype.beartype +def _is_bool(value) -> bool: + return _type_utils.JitScalarType.from_value( + value, _type_utils.JitScalarType.UNDEFINED + ) in {_type_utils.JitScalarType.BOOL} + + +@_beartype.beartype +def _generate_wrapped_number(g: jit_utils.GraphContext, scalar): + """Creates a wrapped number based on https://github.com/pytorch/pytorch/issues/9515. + + A Tensor is a considered a "wrapped number" if it is + auto-wrapped from a C++ or Python number type. Integer types are + wrapped as 0-dim int64 tensors and floating-point types are + wrapped as 0-dim double tensors. + + The input to this function is constant value. If the data type + is a floating point type, it is converted to a 0-dim double + tensor, else it is converted to a 0-dim tensor of its original type + """ + assert not isinstance(scalar, torch.Tensor) + if isinstance(scalar, float): + return g.op("Constant", value_t=torch.tensor(scalar, dtype=torch.double)) + return g.op("Constant", value_t=torch.tensor(scalar)) + + +@_beartype.beartype +def _sort_helper(g: jit_utils.GraphContext, input, dim, decending=True, out=None): + if out is not None: + _unimplemented("Sort", "Out parameter is not supported") + shape_ = g.op("Shape", input) + dim_size_ = g.op( + "Gather", + shape_, + g.op("Constant", value_t=torch.tensor([dim], dtype=torch.int64)), + ) + if g.opset <= 10: + if not decending: + _unimplemented("Sort", "Ascending is not supported") + return g.op("TopK", input, dim_size_, axis_i=dim, outputs=2) + else: + return g.op( + "TopK", input, dim_size_, axis_i=dim, largest_i=decending, outputs=2 + ) + + +@_beartype.beartype +def _topk_helper( + g: jit_utils.GraphContext, input, k, dim, largest=True, sorted=False, out=None +): + if out is not None: + _unimplemented("TopK", "Out parameter is not supported") + if not _is_value(k): + k = g.op("Constant", value_t=torch.tensor([k], dtype=torch.int64)) + else: + k = _reshape_helper(g, k, g.op("Constant", value_t=torch.tensor([1]))) + if _try_get_scalar_type(k) != _type_utils.JitScalarType.INT64: + k = g.op("Cast", k, to_i=_C_onnx.TensorProtoDataType.INT64) + if g.opset <= 10: + if not largest: + _unimplemented("TopK", "Ascending is not supported") + return g.op("TopK", input, k, axis_i=dim, outputs=2) + else: + return g.op( + "TopK", input, k, axis_i=dim, largest_i=largest, sorted_i=sorted, outputs=2 + ) + + +@_beartype.beartype +def _lt_helper(g: jit_utils.GraphContext, input, other): + if g.opset <= 8: + from torch.onnx.symbolic_opset8 import lt as _lt8 + + return _lt8(g, input, other) + else: + from torch.onnx.symbolic_opset9 import lt as _lt9 + + return _lt9(g, input, other) + + +@_beartype.beartype +def _interpolate_warning(interpolate_mode): + onnx_op = ( + "onnx:Resize" if GLOBALS.export_onnx_opset_version >= 10 else "onnx:Upsample" + ) + warnings.warn( + "You are trying to export the model with " + + onnx_op + + " for ONNX opset version " + "" + str(GLOBALS.export_onnx_opset_version) + ". " + "This operator might cause results to not match the expected results by PyTorch.\n" + "ONNX's Upsample/Resize operator did not match Pytorch's Interpolation until opset 11. " + "Attributes to determine how to transform the input were added in onnx:Resize in opset 11 " + "to support Pytorch's behavior (like coordinate_transformation_mode and nearest_mode).\n" + "We recommend using opset 11 and above for models using this operator." + ) + + +@_beartype.beartype +def _unsqueeze_helper(g: jit_utils.GraphContext, input, axes_i): + if _is_constant(axes_i[0]): + if g.opset >= 13: + axes = g.op("Constant", value_t=torch.tensor(axes_i, dtype=torch.long)) + return g.op("Unsqueeze", input, axes) + return g.op("Unsqueeze", input, axes_i=axes_i) + # Tensor type + if g.opset < 13: + raise errors.SymbolicValueError( + "Opset version must be >= 13 for Unsqueeze with dynamic axes.", input + ) + return g.op("Unsqueeze", input, axes_i[0]) + + +@_beartype.beartype +def _squeeze_helper(g: jit_utils.GraphContext, input, axes_i): + if _is_constant(axes_i[0]): + if g.opset >= 13: + axes = g.op("Constant", value_t=torch.tensor(axes_i, dtype=torch.long)) + return g.op("Squeeze", input, axes) + return g.op("Squeeze", input, axes_i=axes_i) + # Tensor type + if g.opset < 13: + raise errors.SymbolicValueError( + "Opset version must be >= 13 for Squeeze with dynamic axes.", input + ) + axes_t = axes_i[0] + axes_rank = _get_tensor_rank(axes_t) + assert axes_rank is not None + if axes_rank > 1: + raise errors.SymbolicValueError( + "For Squeeze axses as input, the axes rank must be one in ONNX spec.", input + ) + elif axes_rank == 0: + # The axes is a scalar. Unsqueeze it to a rank 1 tensor. + axes_t = _unsqueeze_helper(g, axes_t, [0]) + return g.op("Squeeze", input, axes_t) + return g.op("Squeeze", input, axes_t) + + +@_beartype.beartype +def _reducesum_helper( + g: jit_utils.GraphContext, + input, + axes_i=None, + keepdims_i=1, + noop_with_empty_axes_i=0, +): + keepdims_i = _maybe_get_const(keepdims_i, "i") + if g.opset >= 13: + if axes_i: + if not _is_value(axes_i): + axes_i = g.op( + "Constant", value_t=torch.tensor(axes_i, dtype=torch.long) + ) + return g.op( + "ReduceSum", + input, + axes_i, + keepdims_i=keepdims_i, + noop_with_empty_axes_i=noop_with_empty_axes_i, + ) + return g.op( + "ReduceSum", + input, + keepdims_i=keepdims_i, + noop_with_empty_axes_i=noop_with_empty_axes_i, + ) + else: + return g.op("ReduceSum", input, axes_i=axes_i, keepdims_i=keepdims_i) + + +@_beartype.beartype +def _interpolate_size_to_scales(g: jit_utils.GraphContext, input, output_size, dim): + output_size = _maybe_get_const(output_size, "is") + if _is_value(output_size): + offset = 2 + offsets = g.op("Constant", value_t=torch.ones(offset, dtype=torch.float32)) + dividend = g.op("Cast", output_size, to_i=_C_onnx.TensorProtoDataType.FLOAT) + divisor = _slice_helper( + g, g.op("Shape", input), axes=[0], ends=[sys.maxsize], starts=[offset] + ) + divisor = g.op("Cast", divisor, to_i=_C_onnx.TensorProtoDataType.FLOAT) + scale_dims = g.op("Div", dividend, divisor) + scales = g.op("Concat", offsets, scale_dims, axis_i=0) + else: + scales_constant = [ + 1.0 + if i < 2 + else float(output_size[-(dim - i)]) + / float(input.type().sizes()[-(dim - i)]) + for i in range(0, dim) + ] + scales = g.op( + "Constant", value_t=torch.tensor(scales_constant, dtype=torch.float32) + ) + return scales + + +@_beartype.beartype +def _interpolate_get_scales_if_available(g: jit_utils.GraphContext, scales): + available_scales = _maybe_get_const(scales[0], "fs") != -1 and not _is_none( + scales[0] + ) + + if not available_scales: + return None + + offsets = g.op("Constant", value_t=torch.ones(2, dtype=torch.float32)) + scales_list = g.op( + "Constant", value_t=torch.tensor(_maybe_get_const(scales[0], "fs")) + ) + scales = g.op("Concat", offsets, scales_list, axis_i=0) + return scales + + +@_beartype.beartype +def _get_interpolate_attributes(g: jit_utils.GraphContext, mode, args): + if mode == "nearest": + align_corners = None + scales = args[0:] + else: + align_corners = args[0] + scales = args[1:] + scales = _interpolate_get_scales_if_available(g, scales) + return scales, align_corners + + +@_beartype.beartype +def _interpolate_get_scales(g: jit_utils.GraphContext, scale_factor, dim): + offsets = g.op("Constant", value_t=torch.ones(2, dtype=torch.float32)) + scale_factor_rank = _get_tensor_rank(scale_factor) + if isinstance(scale_factor.type(), _C.ListType) or ( + scale_factor_rank is not None and scale_factor_rank > 0 + ): + return g.op("Concat", offsets, scale_factor, axis_i=0) + else: + scale_factor = _unsqueeze_helper(g, scale_factor, [0]) + scale_factor = g.op( + "Cast", scale_factor, to_i=_C_onnx.TensorProtoDataType.FLOAT + ) + scales = [scale_factor for i in range(dim - 2)] + scale_factor = g.op("Concat", offsets, *scales, axis_i=0) + return scale_factor + + +@_beartype.beartype +def _interpolate_get_scales_and_mode( + g: jit_utils.GraphContext, input, size, scale_factor, mode, align_corners +): + mode = _maybe_get_const(mode, "s") + if "linear" in mode: + mode = "linear" + if "cubic" in mode: + mode = "cubic" + _interpolate_warning(mode) + + align_corners = _maybe_get_const(align_corners, "b") + if isinstance(align_corners, bool) and align_corners: + return _unimplemented("interpolate", "align_corners == True") + + if not input.type().dim(): + return _unimplemented("interpolate", "missing input shape") + dim = input.type().dim() + + if not _is_none(scale_factor): + scale_factor = _interpolate_get_scales(g, scale_factor, dim) + elif not _is_none(size): + if not _is_packed_list(size): + is_scalar = _maybe_get_const(size, "t").dim() == 0 + if is_scalar: + size = _unsqueeze_helper(g, size, [0]) + size = [size for i in range(dim - 2)] + size = g.op("Concat", *size, axis_i=0) + scale_factor = _interpolate_size_to_scales(g, input, size, dim) + else: + return _unimplemented( + "interpolate", "Both size and scales are None in __interpolate" + ) + return scale_factor, mode + + +@_beartype.beartype +def _argmin_argmax_helper( + g: jit_utils.GraphContext, + input: torch._C.Value, + dim: torch._C.Value, + keepdim: bool, + op_name: str, +): + def op_wrapper(input, axis_i, keepdims_i): + if g.opset >= 12: + return g.op( + op_name, + input, + axis_i=axis_i, + keepdims_i=keepdims_i, + select_last_index_i=False, + ) + return g.op(op_name, input, axis_i=axis_i, keepdims_i=keepdims_i) + + if _is_none(dim): + flattened = _reshape_helper( + g, input, g.op("Constant", value_t=torch.tensor([-1])) + ) + output = op_wrapper(flattened, axis_i=0, keepdims_i=False) + if keepdim: + input_shape = g.op("Shape", input) + input_shape_shape = g.op("Shape", input_shape) + new_shape = g.op( + "ConstantOfShape", + input_shape_shape, + value_t=torch.tensor([1], dtype=torch.int64), + ) + output = g.op("Reshape", output, new_shape) + return output + + dim = _parse_arg(dim, "i") + return op_wrapper(input, axis_i=dim, keepdims_i=keepdim) + + +@_beartype.beartype +def _interpolate_helper(name, dim, interpolate_mode): + @quantized_args(True, False, False) + def symbolic_fn(g, input, output_size, *args): + scales, align_corners = _get_interpolate_attributes(g, interpolate_mode, args) + align_corners = _maybe_get_scalar(align_corners) + coordinate_transformation_mode = ( + "asymmetric" + if interpolate_mode == "nearest" + else "align_corners" + if align_corners + else "half_pixel" + ) + + if scales is None: + input_size = g.op("Shape", input) + input_size_beg = _slice_helper( + g, input_size, axes=[0], ends=[2], starts=[0] + ) + output_size = g.op( + "Cast", output_size, to_i=_C_onnx.TensorProtoDataType.INT64 + ) + output_size = g.op("Concat", input_size_beg, output_size, axis_i=0) + + if g.opset >= 13: + empty_roi = _optional_input_placeholder_tensor(g) + empty_scales = _optional_input_placeholder_tensor(g) + else: + empty_roi = g.op( + "Constant", value_t=torch.tensor([], dtype=torch.float32) + ) + empty_scales = g.op( + "Constant", value_t=torch.tensor([], dtype=torch.float32) + ) + + return g.op( + "Resize", + input, + empty_roi, + empty_scales, + output_size, + coordinate_transformation_mode_s=coordinate_transformation_mode, + cubic_coeff_a_f=-0.75, # only valid when mode="cubic" + mode_s=interpolate_mode, # nearest, linear, or cubic + nearest_mode_s="floor", + ) # only valid when mode="nearest" + else: + if g.opset >= 13: + empty_roi = _optional_input_placeholder_tensor(g) + else: + empty_roi = g.op( + "Constant", value_t=torch.tensor([], dtype=torch.float32) + ) + + return g.op( + "Resize", + input, + empty_roi, + scales, + coordinate_transformation_mode_s=coordinate_transformation_mode, + cubic_coeff_a_f=-0.75, # only valid when mode="cubic" + mode_s=interpolate_mode, # nearest, linear, or cubic + nearest_mode_s="floor", + ) # only valid when mode="nearest" + + return symbolic_fn + + +@_beartype.beartype +def __interpolate_helper( + g: jit_utils.GraphContext, + input, + size, + scale_factor, + mode, + align_corners, + recompute_scale_factor, +): + mode = _maybe_get_const(mode, "s") + if "linear" in mode: + mode = "linear" + if "cubic" in mode: + mode = "cubic" + align_corners = _maybe_get_const(align_corners, "b") + align_corners = False if not isinstance(align_corners, bool) else align_corners + coordinate_transformation_mode = ( + "asymmetric" + if mode == "nearest" + else "align_corners" + if align_corners + else "half_pixel" + ) + + if not _is_none(size): + input_size = g.op("Shape", input) + input_size = _slice_helper(g, input_size, axes=[0], ends=[2], starts=[0]) + # in some cases size is not a packed list but size is a scalar + # We need to also verify that (_maybe_get_const(size, "t").dim() == 0) + # but this information is not always available. Try to get the dim, + # and if not assume that it is not a scalar. + try: + is_scalar = not _is_packed_list(size) and ( + _maybe_get_const(size, "t").dim() == 0 + ) + except AttributeError: + is_scalar = not _is_packed_list(size) + if not is_scalar: + warnings.warn( + "Cannot verify if the output_size is a scalar " + "while exporting interpolate. Assuming that it is not a scalar." + ) + + if is_scalar: + rank = _get_tensor_rank(input) + if rank is None: + return _unimplemented( + "interpolate (with a scalar output_size)", + "missing input shape (try giving an array of output_size values)", + ) + size = _unsqueeze_helper(g, size, [0]) + size = [size for i in range(rank - 2)] + size = g.op("Concat", *size, axis_i=0) + size = g.op("Cast", size, to_i=_C_onnx.TensorProtoDataType.INT64) + size = g.op("Concat", input_size, size, axis_i=0) + + if g.opset >= 13: + empty_roi = _optional_input_placeholder_tensor(g) + empty_scales = _optional_input_placeholder_tensor(g) + else: + empty_roi = g.op("Constant", value_t=torch.tensor([], dtype=torch.float32)) + empty_scales = g.op( + "Constant", value_t=torch.tensor([], dtype=torch.float32) + ) + + return g.op( + "Resize", + input, + empty_roi, + empty_scales, + size, + coordinate_transformation_mode_s=coordinate_transformation_mode, + cubic_coeff_a_f=-0.75, # only valid when mode="cubic" + mode_s=mode, # nearest, linear, or cubic + nearest_mode_s="floor", + ) + else: # if not _is_none(scales) + rank = _get_tensor_rank(input) + if rank is None: + return _unimplemented("interpolate (with scales)", "missing input shape") + + if g.opset >= 13: + empty_roi = _optional_input_placeholder_tensor(g) + else: + empty_roi = g.op("Constant", value_t=torch.tensor([], dtype=torch.float32)) + + scales = _interpolate_get_scales(g, scale_factor, rank) + return g.op( + "Resize", + input, + empty_roi, + scales, + coordinate_transformation_mode_s=coordinate_transformation_mode, + cubic_coeff_a_f=-0.75, # only valid when mode="cubic" + mode_s=mode, # nearest, linear, or cubic + nearest_mode_s="floor", + ) # only valid when mode="nearest" + + +@_beartype.beartype +def _unbind_helper(g: jit_utils.GraphContext, self, dim, _outputs): + if g.opset < 11: + from torch.onnx.symbolic_opset9 import unbind + elif g.opset <= 12: + from torch.onnx.symbolic_opset11 import unbind # type: ignore[no-redef] + else: + from torch.onnx.symbolic_opset13 import unbind # type: ignore[no-redef] + return unbind(g, self, dim, _outputs) + + +@_beartype.beartype +def _scatter_helper(g: jit_utils.GraphContext, self, dim, index, src): + if g.opset <= 10: + from torch.onnx.symbolic_opset9 import scatter + else: + # for mypy, scatter was imported two lines above + from torch.onnx.symbolic_opset11 import scatter # type: ignore[no-redef] + return scatter(g, self, dim, index, src) + + +@_beartype.beartype +def _repeat_interleave_split_helper(g: jit_utils.GraphContext, self, reps, dim): + if g.opset <= 12: + split_out = g.op("Split", self, split_i=[1] * reps, axis_i=dim, outputs=reps) + else: + from torch.onnx.symbolic_opset13 import split + + repeats = g.op("Constant", value_t=torch.tensor([1] * reps)) + split_out = split(g, self, repeats, dim, _outputs=reps) + return split_out if reps > 1 else [split_out] + + +@_beartype.beartype +def _repeat_interleave_single_value_repeat_helper( + g: jit_utils.GraphContext, self, repeats, dim +): + from torch.onnx.symbolic_opset9 import flatten, unsqueeze + + if not _is_tensor(repeats): + repeats = g.op("Constant", value_t=torch.LongTensor(repeats)) + + const_repeats: bool = _is_constant(repeats) + reps = _maybe_get_const(repeats, "t") + + # Convert 'repeats' to 1-d if it is 0-d. + if _get_tensor_rank(repeats) == 0: + repeats = g.op("Reshape", repeats, g.op("Constant", value_t=torch.tensor([1]))) + + # Create a new dim of size 1, then expand it to be 'repeats' long, and finally collapse it. + unsqueezed = unsqueeze(g, self, dim + 1) + + # repeats_per_dim is 1 for all dims except for the new unsqueezed dim, where it has value 'repeats'. + if const_repeats: + # 'Repeats' is a constant, 'repeats_per_dim' can be a constant. + onehot = torch.ones(_get_tensor_rank(unsqueezed), dtype=torch.int64) + onehot[dim + 1] = reps + repeats_per_dim = g.op("Constant", value_t=onehot) + else: + # 'Repeats' is a variable, 'repeats_per_dim' cannot be a constant. + onehot = g.op( + "OneHot", + unsqueeze(g, dim + 1, 0), # indices, must be >= 1-dimensional + g.op( + "Constant", value_t=torch.tensor(_get_tensor_rank(unsqueezed)) + ), # depth + g.op( + "Concat", g.op("Constant", value_t=torch.tensor([1])), repeats, axis_i=0 + ), # on/off values + ) + repeats_per_dim = flatten(g, onehot, 0, 1) + + tiled = g.op("Tile", unsqueezed, repeats_per_dim) + return flatten(g, tiled, dim, dim + 1) + + +@_beartype.beartype +def _arange_cast_helper( + g: jit_utils.GraphContext, end, start=None, step=None, dtype=None +) -> Tuple[ + _type_utils.JitScalarType, + Optional[_C.Value], + Optional[_C.Value], + Optional[_C.Value], +]: + def _is_all_integral(scalars): + for scalar in scalars: + scalar_type = _type_utils.JitScalarType.from_value( + scalar, _type_utils.JitScalarType.UNDEFINED + ) + if ( + scalar_type != _type_utils.JitScalarType.INT64 + and scalar_type != _type_utils.JitScalarType.UNDEFINED + ): + return False + return True + + # This logic is based on torch.arange docs. If "dtype" is provided, + # infer input types from dtype. If not, then check if any of start, stop, + # or step are floating point, and infer the type from get_default. + # Otherwise, the dtype is inferred to be torch.int64. + if dtype is None or (_is_value(dtype) and _is_none(dtype)): + if _is_all_integral([start, end, step]): + scalar_type = _type_utils.JitScalarType.INT64 + else: + scalar_type = _type_utils.JitScalarType.from_dtype( + torch.get_default_dtype() + ) + else: + assert isinstance(dtype, int) + # TODO(justinchuby): Check if dtype is indeed a int. + scalar_type = _type_utils.JitScalarType(dtype) + + start = g.op("Cast", start, to_i=scalar_type.onnx_type()) if start else None + end = g.op("Cast", end, to_i=scalar_type.onnx_type()) if end else None + step = g.op("Cast", step, to_i=scalar_type.onnx_type()) if step else None + return scalar_type, end, start, step + + +@_beartype.beartype +def _arange_helper(g: jit_utils.GraphContext, *args): + if g.opset <= 10: + from torch.onnx.symbolic_opset9 import arange + else: + from torch.onnx.symbolic_opset11 import arange # type: ignore[no-redef] + return arange(g, *args) + + +@_beartype.beartype +def _size_helper(g: jit_utils.GraphContext, self, dim): + full_shape = g.op("Shape", self) + from torch.onnx.symbolic_opset9 import select + + return select(g, full_shape, g.op("Constant", value_t=torch.tensor([0])), dim) + + +@_beartype.beartype +def _index_fill_reshape_helper(g: jit_utils.GraphContext, self, dim, index): + # 1. reshape index => [1, ..., 1, dim, 1, ..., 1] + # 2. expand index => [..., dim, ...], same shape as self except for dim. + # 3. expand value as well. + # 4. apply onnx::scatter. + + from torch.onnx.symbolic_opset9 import expand + + if g.opset <= 10: + from torch.onnx.symbolic_opset9 import scatter + else: + # for mypy, scatter was imported two lines above + from torch.onnx.symbolic_opset11 import scatter # type: ignore[no-redef] + + if self.type().dim() is None: + return _unimplemented("index_fill", "input rank not accessible") + self_dim = self.type().dim() + dim_value = _parse_arg(dim, "i") + if dim_value < 0: + dim_value += self_dim + unsqueezed_index = _unsqueeze_helper( + g, index, [i for i in range(self_dim) if i != dim_value] + ) + expanded_index_shape = scatter( + g, g.op("Shape", self), 0, _unsqueeze_helper(g, dim, [0]), g.op("Shape", index) + ) + expanded_index = expand(g, unsqueezed_index, expanded_index_shape, None) + return expanded_index_shape, expanded_index + + +# By default, when any value in the 'shape' input is equal to zero +# the corresponding dimension value is copied from the input tensor dynamically. +# allowzero=1 indicates that if any value in the 'shape' input is set to zero, +# the zero value is honored, similar to NumPy. +# allowzero=1 is only supported for opset version >= 14. +@_beartype.beartype +def _reshape_helper(g: jit_utils.GraphContext, input, shape, allowzero=0): + shape = _maybe_get_const(shape, "is") + if not _is_value(shape): + shape = g.op("Constant", value_t=torch.LongTensor(shape)) + if g.opset <= 13: + if allowzero == 1: + _onnx_opset_unsupported( + "Reshape with allowzero=1", GLOBALS.export_onnx_opset_version, 14, input + ) + return g.op("Reshape", input, shape) + else: + return g.op("Reshape", input, shape, allowzero_i=allowzero) + + +@_beartype.beartype +def _batchnorm_helper( + g: jit_utils.GraphContext, input, weight, bias, running_mean, running_var +): + from torch.onnx.symbolic_opset9 import _var_mean + + batch_size = _get_tensor_dim_size(input, 0) + channel_size = _get_tensor_dim_size(input, 1) + + if weight is None or _is_none(weight): + if channel_size is None: + raise errors.SymbolicValueError( + "Unsupported: ONNX export of batch_norm for unknown channel size.", + input, + ) + weight_value = torch.tensor( + [1.0] * channel_size, + dtype=_type_utils.JitScalarType.from_value(input).dtype(), + ) + weight = g.op("Constant", value_t=weight_value) + if bias is None or _is_none(bias): + if channel_size is None: + raise errors.SymbolicValueError( + "Unsupported: ONNX export of batch_norm for unknown channel size.", + input, + ) + bias_value = torch.tensor( + [0.0] * channel_size, + dtype=_type_utils.JitScalarType.from_value(input).dtype(), + ) + bias = g.op("Constant", value_t=bias_value) + # If track_running_stats is set to False batch statistics are instead used during evaluation time + if ( + running_mean is None + or _is_none(running_mean) + or running_var is None + or _is_none(running_var) + ): + assert batch_size is not None and channel_size is not None + reshape_in = _reshape_helper( + g, + input, + g.op( + "Constant", + value_t=torch.tensor([batch_size, channel_size, -1], dtype=torch.int64), + ), + ) + trans_in = g.op("Transpose", reshape_in, perm_i=[0, 2, 1]) + running_var, running_mean = _var_mean( + g, + trans_in, + g.op("Constant", value_t=torch.tensor([0, 1], dtype=torch.int64)), + False, + False, + ) + return weight, bias, running_mean, running_var + + +@_beartype.beartype +def _avgpool_helper( + tuple_fn: Callable[[Any], Sequence[int]], + padding: Union[int, Sequence[int]], + kernel_size, + stride, + divisor_override, + name, +) -> Tuple[int, ...]: + if divisor_override and divisor_override.node().kind() != "prim::Constant": + _unimplemented(name, "divisor_override") + return tuple(tuple_fn(padding)) + + +@_beartype.beartype +def check_training_mode(op_train_mode: int, op_name: str) -> None: + """Warns the user if the model's training mode and the export mode do not agree.""" + if GLOBALS.training_mode == _C_onnx.TrainingMode.PRESERVE: + return + + if op_train_mode: + op_mode_enum = _C_onnx.TrainingMode.TRAINING + else: + op_mode_enum = _C_onnx.TrainingMode.EVAL + if op_mode_enum == GLOBALS.training_mode: + # The modes agree. Do nothing + return + + op_mode_text = f"train={bool(op_train_mode)}" + # Setting the model mode could result in op_mode != GLOBALS.training_mode + # if the model is a FuncModule. In this case we warn the user of + # the state and export depending on op_mode + # This is to support use-cases of fixing certain layer weights + # in training. + warnings.warn( + f"ONNX export mode is set to {GLOBALS.training_mode}, but operator '{op_name}' " + f"is set to {op_mode_text}. Exporting with {op_mode_text}." + ) + + +@_beartype.beartype +def _flatten_helper(g: jit_utils.GraphContext, input, start_dim, end_dim, dim): + input_size = g.op("Shape", input) + slice1 = _slice_helper(g, input_size, axes=[0], starts=[0], ends=[start_dim]) + slices = [slice1, g.op("Constant", value_t=torch.tensor([-1], dtype=torch.long))] + if end_dim < dim - 1: + slice3 = _slice_helper( + g, input_size, axes=[0], starts=[end_dim + 1], ends=[dim] + ) + slices = [ + slice1, + g.op("Constant", value_t=torch.tensor([-1], dtype=torch.long)), + slice3, + ] + + final_shape = g.op("Concat", *slices, axis_i=0) + from torch.onnx.symbolic_opset9 import _reshape_from_tensor + + return _reshape_from_tensor(g, input, final_shape) + + +@_beartype.beartype +def _is_split_static(split_size_or_sizes, _outputs): + if _outputs is None: + return False + if ( + _is_value(split_size_or_sizes) + and split_size_or_sizes.node().kind() != "onnx::Constant" + ): + return False + return True + + +@_beartype.beartype +def _optional_input_placeholder_tensor(g): + n = g.op("prim::Constant") + n.setType(_C.OptionalType.ofTensor()) + return n + + +@_beartype.beartype +def _handle_reduce_dim_none(g: jit_utils.GraphContext, self, op_name): + rank = _get_tensor_rank(self) + if rank is not None and any( + _get_tensor_dim_size(self, i) == 0 for i in range(rank) + ): + # If input tensor is empty, according to ONNX ReduceSum definition, + # set keepdims=1 so that the resulted tensor has the same rank as the input. + return g.op(op_name, self, keepdims_i=1) + return g.op(op_name, self, keepdims_i=0) + + +@_beartype.beartype +def dequantize_helper( + g: jit_utils.GraphContext, + qtensor: _C.Value, + qdtype: Optional[_C_onnx.TensorProtoDataType] = None, +) -> Tuple[_C.Value, _C.Value, _C.Value, Optional[_C.Value]]: + """Appends to graph `g` ONNX nodes that dequantizes `qtensor` into `tensor`. + + Args: + g: Graph, the ONNX IR graph that is under construction. + qtensor: torch._C.Value, either a tuple of (quantized_tensor, scale, zero_point) + for per tensor quantization, or + (quantized_tensor, scale, zero_point, axis) for per channel quantization, + representing the quantized tensor. + qdtype: torch.onnx.TensorProtoDataType default None, if not None, represents the + data type of quantized tensor. It must be either + torch.onnx.TensorProtoDataType.UINT8 or torch.onnx.TensorProtoDataType.INT8. + """ + unpacked_qtensors = _unpack_quantized_tensor(qtensor) + tensor, scale, zero_point = unpacked_qtensors[:3] + axis = unpacked_qtensors[3] if len(unpacked_qtensors) >= 4 else None + axis_i = _get_const(axis, "i", "axis") + input_qdtype = _type_utils.JitScalarType.from_value(tensor) + if qdtype is None: + if input_qdtype is not None: + qdtype = input_qdtype.onnx_type() + else: + qdtype = _C_onnx.TensorProtoDataType.UINT8 + value = g.op("Cast", tensor, to_i=qdtype) + scale = g.op("Cast", scale, to_i=_C_onnx.TensorProtoDataType.FLOAT) + zero_point = g.op("Cast", zero_point, to_i=qdtype) + + if axis_i is not None and GLOBALS.export_onnx_opset_version < 13: + _onnx_opset_unsupported_detailed( + "DequantizeLinear", + GLOBALS.export_onnx_opset_version, + 13, + "Attribute axis is not supported.", + qtensor, + ) + + return ( + g.op("DequantizeLinear", value, scale, zero_point, axis_i=axis_i), + scale, + zero_point, + axis, + ) + + +@_beartype.beartype +def quantize_helper( + g: jit_utils.GraphContext, + tensor: _C.Value, + scale: _C.Value, + zero_point: _C.Value, + axis: Optional[_C.Value] = None, +) -> _C.Value: + """Appends to graph `g` ONNX nodes that quantizes `tensor` based on `scale`, `zero_point` and `axis`. + + Args: + g: Graph, the ONNX IR graph that is under construction. + tensor: torch._C.Value, representing the tensor to be quantized. + scale: torch._C.Value, quantized scale. + zero_point: torch._C.Value, quantized zero point. + axis: Optional[torch._C.Value] default None, if None, represents per tensor quantization. + Otherwise, represents per channel quantization, along given axis. + + Returns: + A TupleConstruct storing information of the quantized tensor. + """ + if ( + axis is not None + and not _is_none(axis) + and GLOBALS.export_onnx_opset_version < 13 + ): + _onnx_opset_unsupported_detailed( + "QuantizeLinear", + GLOBALS.export_onnx_opset_version, + 13, + "Attribute axis is not supported.", + tensor, + ) + + assert scale is not None + if ( + _type_utils.JitScalarType.from_value(scale, _type_utils.JitScalarType.UNDEFINED) + != _type_utils.JitScalarType.FLOAT + ): + scale = g.op("Cast", scale, to_i=_C_onnx.TensorProtoDataType.FLOAT) + + assert zero_point is not None + if _type_utils.JitScalarType.from_value( + zero_point, _type_utils.JitScalarType.UNDEFINED + ) not in { + _type_utils.JitScalarType.UINT8, + _type_utils.JitScalarType.INT8, + }: + zero_point = g.op("Cast", zero_point, to_i=_C_onnx.TensorProtoDataType.UINT8) + output = g.op( + "QuantizeLinear", + tensor, + scale, + zero_point, + axis_i=_get_const(axis, "i", "axis"), + ) + args = [output, scale, zero_point] + if axis is not None and not _is_none(axis): + args.append(axis) + return g.op("prim::TupleConstruct", *args) + + +@_beartype.beartype +def requantize_bias_helper( + g: jit_utils.GraphContext, bias, input_scale, weight_scale, axis=None +): + """In PyTorch, bias is float and is quantized to int32 implicitly inside the quantized ATen op kernel. + In ONNX we need to make the quantization explicit because operators expect all of their inputs to be quantized. + Since int32 is not a supported output type by ONNX operator `QuantizeLinear`, quantization is exported using + regular operators. + """ + bias_scale = g.op("Mul", weight_scale, input_scale) + bias_scale_shape = g.op("Shape", bias_scale) + bias_zero_point = g.op( + "ConstantOfShape", bias_scale_shape, value_t=torch.tensor([0], dtype=torch.int) + ) + q_bias = g.op( + "Cast", g.op("Div", bias, bias_scale), to_i=_C_onnx.TensorProtoDataType.INT32 + ) + axis_args = [] + if axis is not None and not _is_none(axis): + axis_args.append(axis) + return g.op("prim::TupleConstruct", q_bias, bias_scale, bias_zero_point, *axis_args) + + +@_beartype.beartype +def args_have_same_dtype(args): + assert args + base_dtype = _type_utils.JitScalarType.from_value(args[0]) + has_same_dtype = all( + _type_utils.JitScalarType.from_value(elem) == base_dtype for elem in args + ) + return has_same_dtype + + +# Deprecated. Internally use _type_utils.ScalarType +# TODO: remove these once we support Type's in the JIT IR and we can once again +# use the unified toType operator +cast_pytorch_to_onnx = { + "Byte": _C_onnx.TensorProtoDataType.UINT8, + "Char": _C_onnx.TensorProtoDataType.INT8, + "Double": _C_onnx.TensorProtoDataType.DOUBLE, + "Float": _C_onnx.TensorProtoDataType.FLOAT, + "Half": _C_onnx.TensorProtoDataType.FLOAT16, + "Int": _C_onnx.TensorProtoDataType.INT32, + "Long": _C_onnx.TensorProtoDataType.INT64, + "Short": _C_onnx.TensorProtoDataType.INT16, + "Bool": _C_onnx.TensorProtoDataType.BOOL, + "ComplexFloat": _C_onnx.TensorProtoDataType.COMPLEX64, + "ComplexDouble": _C_onnx.TensorProtoDataType.COMPLEX128, + "BFloat16": _C_onnx.TensorProtoDataType.BFLOAT16, + "Undefined": _C_onnx.TensorProtoDataType.UNDEFINED, +} + +# Deprecated. Internally use _type_utils.ScalarType +scalar_name_to_pytorch = { + "uint8_t": "Byte", + "int8_t": "Char", + "double": "Double", + "float": "Float", + "half": "Half", + "int": "Int", + "int64_t": "Long", + "int16_t": "Short", + "bool": "Bool", + "complex64": "ComplexFloat", + "complex128": "ComplexDouble", + "qint8": "QInt8", + "quint8": "QUInt8", + "qint32": "QInt32", + "bfloat16": "BFloat16", +} + + +# Deprecated. Internally use _type_utils.ScalarType +# This indicates each scalar type's corresponding +# torch type. Related source: +# https://github.com/pytorch/pytorch/blob/344defc9733a45fee8d0c4d3f5530f631e823196/c10/core/ScalarType.h +scalar_type_to_pytorch_type = [ + torch.uint8, # 0 + torch.int8, # 1 + torch.short, # 2 + torch.int, # 3 + torch.int64, # 4 + torch.half, # 5 + torch.float, # 6 + torch.double, # 7 + torch.complex32, # 8 + torch.complex64, # 9 + torch.complex128, # 10 + torch.bool, # 11 + torch.qint8, # 12 + torch.quint8, # 13 + torch.qint32, # 14 + torch.bfloat16, # 15 +] + +# Deprecated. Internally use _type_utils.ScalarType +# source of truth is +# https://github.com/pytorch/pytorch/blob/master/torch/csrc/utils/tensor_dtypes.cpp +pytorch_name_to_type = { + "Byte": torch.uint8, + "Char": torch.int8, + "Double": torch.double, + "Float": torch.float, + "Half": torch.half, + "Int": torch.int, + "Long": torch.int64, + "Short": torch.short, + "Bool": torch.bool, + "ComplexFloat": torch.complex64, + "ComplexDouble": torch.complex128, + "QInt8": torch.qint8, + "QUInt8": torch.quint8, + "QInt32": torch.qint32, + "BFloat16": torch.bfloat16, +} + + +# Deprecated. Internally use _type_utils.ScalarType +scalar_type_to_onnx = [ + cast_pytorch_to_onnx["Byte"], # 0 + cast_pytorch_to_onnx["Char"], # 1 + cast_pytorch_to_onnx["Short"], # 2 + cast_pytorch_to_onnx["Int"], # 3 + cast_pytorch_to_onnx["Long"], # 4 + cast_pytorch_to_onnx["Half"], # 5 + cast_pytorch_to_onnx["Float"], # 6 + cast_pytorch_to_onnx["Double"], # 7 + cast_pytorch_to_onnx["Undefined"], # 8 + cast_pytorch_to_onnx["ComplexFloat"], # 9 + cast_pytorch_to_onnx["ComplexDouble"], # 10 + cast_pytorch_to_onnx["Bool"], # 11 + cast_pytorch_to_onnx["Char"], # 12 + cast_pytorch_to_onnx["Byte"], # 13 + cast_pytorch_to_onnx["Int"], # 14 + cast_pytorch_to_onnx["BFloat16"], # 15 +] + +# Global set to store the list of quantized operators in the network. +# This is currently only used in the conversion of quantized ops from PT -> C2 via ONNX. +_quantized_ops: Set[int] = set() diff --git a/shared/package-files/4f/4fbba98ef2905beb04479d85e70ba3ef964b1c8c9d26652f29ea0c48dc9bb8dc/quantize_per_channel.h b/shared/package-files/4f/4fbba98ef2905beb04479d85e70ba3ef964b1c8c9d26652f29ea0c48dc9bb8dc/quantize_per_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..f8adf17a2b800de24d770c028e9a5b4b9744b96d --- /dev/null +++ b/shared/package-files/4f/4fbba98ef2905beb04479d85e70ba3ef964b1c8c9d26652f29ea0c48dc9bb8dc/quantize_per_channel.h @@ -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::quantize_per_channel(Tensor self, Tensor scales, Tensor zero_points, int axis, ScalarType dtype) -> Tensor +inline at::Tensor quantize_per_channel(const at::Tensor & self, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::ScalarType dtype) { + return at::_ops::quantize_per_channel::call(self, scales, zero_points, axis, dtype); +} + +// aten::quantize_per_channel.out(Tensor self, Tensor scales, Tensor zero_points, int axis, ScalarType dtype, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & quantize_per_channel_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::ScalarType dtype) { + return at::_ops::quantize_per_channel_out::call(self, scales, zero_points, axis, dtype, out); +} +// aten::quantize_per_channel.out(Tensor self, Tensor scales, Tensor zero_points, int axis, ScalarType dtype, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & quantize_per_channel_outf(const at::Tensor & self, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::ScalarType dtype, at::Tensor & out) { + return at::_ops::quantize_per_channel_out::call(self, scales, zero_points, axis, dtype, out); +} + +} diff --git a/shared/package-files/4f/4fbd9356e5e73eb9f349f4fd373bd4b07b0c3aa584154879d8e643517a2a2b10/adadelta.py b/shared/package-files/4f/4fbd9356e5e73eb9f349f4fd373bd4b07b0c3aa584154879d8e643517a2a2b10/adadelta.py new file mode 100644 index 0000000000000000000000000000000000000000..ac16c13101b408ff6fbe01e9b7de666911b9dd2d --- /dev/null +++ b/shared/package-files/4f/4fbd9356e5e73eb9f349f4fd373bd4b07b0c3aa584154879d8e643517a2a2b10/adadelta.py @@ -0,0 +1,316 @@ +import torch +from torch import Tensor + +from .optimizer import (Optimizer, _use_grad_for_differentiable, _default_to_fused_or_foreach, + _differentiable_doc, _foreach_doc, _maximize_doc, _view_as_real) +from typing import List, Optional + +__all__ = ["Adadelta", "adadelta"] + + +class Adadelta(Optimizer): + def __init__( + self, + params, + lr=1.0, + rho=0.9, + eps=1e-6, + weight_decay=0, + foreach: Optional[bool] = None, + *, + maximize: bool = False, + differentiable: bool = False, + ): + if not 0.0 <= lr: + raise ValueError(f"Invalid learning rate: {lr}") + if not 0.0 <= rho <= 1.0: + raise ValueError(f"Invalid rho value: {rho}") + if not 0.0 <= eps: + raise ValueError(f"Invalid epsilon value: {eps}") + if not 0.0 <= weight_decay: + raise ValueError(f"Invalid weight_decay value: {weight_decay}") + + defaults = dict( + lr=lr, + rho=rho, + eps=eps, + weight_decay=weight_decay, + maximize=maximize, + foreach=foreach, + differentiable=differentiable, + ) + super().__init__(params, defaults) + + def __setstate__(self, state): + super().__setstate__(state) + for group in self.param_groups: + group.setdefault("foreach", None) + group.setdefault("maximize", False) + group.setdefault("differentiable", False) + + def _init_group(self, group, params_with_grad, grads, square_avgs, acc_deltas): + has_complex = False + for p in group["params"]: + if p.grad is None: + continue + has_complex |= torch.is_complex(p) + params_with_grad.append(p) + if p.grad.is_sparse: + raise RuntimeError("Adadelta does not support sparse gradients") + grads.append(p.grad) + + state = self.state[p] + + # Lazy state initialization + if len(state) == 0: + state["step"] = 0 + state["square_avg"] = torch.zeros_like( + p, memory_format=torch.preserve_format + ) + state["acc_delta"] = torch.zeros_like( + p, memory_format=torch.preserve_format + ) + + square_avgs.append(state["square_avg"]) + acc_deltas.append(state["acc_delta"]) + + state["step"] += 1 + return has_complex + + @_use_grad_for_differentiable + def step(self, closure=None): + """Perform a single optimization step. + + Args: + closure (Callable, optional): A closure that reevaluates the model + and returns the loss. + """ + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + params_with_grad = [] + grads = [] + square_avgs = [] + acc_deltas = [] + lr, rho, eps, weight_decay, foreach, maximize, differentiable = ( + group["lr"], + group["rho"], + group["eps"], + group["weight_decay"], + group["foreach"], + group["maximize"], + group["differentiable"], + ) + + has_complex = self._init_group(group, params_with_grad, grads, square_avgs, acc_deltas) + + adadelta( + params_with_grad, + grads, + square_avgs, + acc_deltas, + lr=lr, + rho=rho, + eps=eps, + weight_decay=weight_decay, + foreach=foreach, + maximize=maximize, + differentiable=differentiable, + has_complex=has_complex, + ) + + return loss + + +Adadelta.__doc__ = r"""Implements Adadelta algorithm. + + .. math:: + \begin{aligned} + &\rule{110mm}{0.4pt} \\ + &\textbf{input} : \gamma \text{ (lr)}, \: \theta_0 \text{ (params)}, + \: f(\theta) \text{ (objective)}, \: \rho \text{ (decay)}, + \: \lambda \text{ (weight decay)} \\ + &\textbf{initialize} : v_0 \leftarrow 0 \: \text{ (square avg)}, + \: u_0 \leftarrow 0 \: \text{ (accumulate variables)} \\[-1.ex] + &\rule{110mm}{0.4pt} \\ + &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\ + &\hspace{5mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\ + &\hspace{5mm}if \: \lambda \neq 0 \\ + &\hspace{10mm} g_t \leftarrow g_t + \lambda \theta_{t-1} \\ + &\hspace{5mm} v_t \leftarrow v_{t-1} \rho + g^2_t (1 - \rho) \\ + &\hspace{5mm}\Delta x_t \leftarrow \frac{\sqrt{u_{t-1} + + \epsilon }}{ \sqrt{v_t + \epsilon} }g_t \hspace{21mm} \\ + &\hspace{5mm} u_t \leftarrow u_{t-1} \rho + + \Delta x^2_t (1 - \rho) \\ + &\hspace{5mm}\theta_t \leftarrow \theta_{t-1} - \gamma \Delta x_t \\ + &\rule{110mm}{0.4pt} \\[-1.ex] + &\bf{return} \: \theta_t \\[-1.ex] + &\rule{110mm}{0.4pt} \\[-1.ex] + \end{aligned} + + For further details regarding the algorithm we refer to `ADADELTA: An Adaptive Learning Rate Method`_. + """ + fr""" + Args: + params (iterable): iterable of parameters to optimize or dicts defining + parameter groups + rho (float, optional): coefficient used for computing a running average + of squared gradients (default: 0.9). A higher value of `rho` will + result in a slower average, which can be helpful for preventing + oscillations in the learning process. + eps (float, optional): term added to the denominator to improve + numerical stability (default: 1e-6). + lr (float, optional): coefficient that scale delta before it is applied + to the parameters (default: 1.0) + weight_decay (float, optional): weight decay (L2 penalty) (default: 0) + {_foreach_doc} + {_maximize_doc} + {_differentiable_doc} + + .. _ADADELTA\: An Adaptive Learning Rate Method: + https://arxiv.org/abs/1212.5701 + + """ + + +def adadelta( + params: List[Tensor], + grads: List[Tensor], + square_avgs: List[Tensor], + acc_deltas: List[Tensor], + # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627 + # setting this as kwarg for now as functional API is compiled by torch/distributed/optim + foreach: Optional[bool] = None, + differentiable: bool = False, + has_complex: bool = False, + *, + lr: float, + rho: float, + eps: float, + weight_decay: float, + maximize: bool, +): + r"""Functional API that performs Adadelta algorithm computation. + + See :class:`~torch.optim.Adadelta` for details. + """ + # We still respect when the user inputs False for foreach. + if foreach is None: + _, foreach = _default_to_fused_or_foreach(params, differentiable, use_fused=False) + + if foreach and torch.jit.is_scripting(): + raise RuntimeError("torch.jit.script not supported with foreach optimizers") + + if foreach and not torch.jit.is_scripting(): + func = _multi_tensor_adadelta + else: + func = _single_tensor_adadelta + + func( + params, + grads, + square_avgs, + acc_deltas, + lr=lr, + rho=rho, + eps=eps, + weight_decay=weight_decay, + maximize=maximize, + differentiable=differentiable, + has_complex=has_complex, + ) + + +def _single_tensor_adadelta( + params: List[Tensor], + grads: List[Tensor], + square_avgs: List[Tensor], + acc_deltas: List[Tensor], + *, + lr: float, + rho: float, + eps: float, + weight_decay: float, + maximize: bool, + differentiable: bool, + has_complex: bool, +): + + for (param, grad, square_avg, acc_delta) in zip( + params, grads, square_avgs, acc_deltas + ): + grad = grad if not maximize else -grad + + if weight_decay != 0: + grad = grad.add(param, alpha=weight_decay) + + if torch.is_complex(param): + square_avg = torch.view_as_real(square_avg) + acc_delta = torch.view_as_real(acc_delta) + grad = torch.view_as_real(grad) + + square_avg.mul_(rho).addcmul_(grad, grad, value=1 - rho) + std = square_avg.add(eps).sqrt_() + delta = acc_delta.add(eps).sqrt_() + if differentiable: + delta = delta.clone() + delta.div_(std).mul_(grad) + acc_delta.mul_(rho).addcmul_(delta, delta, value=1 - rho) + + if torch.is_complex(param): + delta = torch.view_as_complex(delta) + param.add_(delta, alpha=-lr) + + +def _multi_tensor_adadelta( + params: List[Tensor], + grads: List[Tensor], + square_avgs: List[Tensor], + acc_deltas: List[Tensor], + *, + lr: float, + weight_decay: float, + rho: float, + eps: float, + maximize: bool, + differentiable: bool, + has_complex: bool, +): + + assert not differentiable, "_foreach ops don't support autograd" + + if len(params) == 0: + return + + grouped_tensors = Optimizer._group_tensors_by_device_and_dtype([params, grads, square_avgs, acc_deltas]) + for ((device_params, device_grads, device_square_avgs, device_acc_deltas), _) in grouped_tensors.values(): + if has_complex: + _view_as_real(device_params, device_grads, device_square_avgs, device_acc_deltas) + + if maximize: + device_grads = torch._foreach_neg(device_grads) + + if weight_decay != 0: + # Re-use the intermediate memory (device_grads) already allocated for maximize + if maximize: + torch._foreach_add_(device_grads, device_params, alpha=weight_decay) + else: + device_grads = torch._foreach_add(device_grads, device_params, alpha=weight_decay) + + torch._foreach_mul_(device_square_avgs, rho) + torch._foreach_addcmul_(device_square_avgs, device_grads, device_grads, value=1 - rho) + + std = torch._foreach_add(device_square_avgs, eps) + torch._foreach_sqrt_(std) + + deltas = torch._foreach_add(device_acc_deltas, eps) + torch._foreach_sqrt_(deltas) + torch._foreach_div_(deltas, std) + torch._foreach_mul_(deltas, device_grads) + + torch._foreach_add_(device_params, deltas, alpha=-lr) + + torch._foreach_mul_(device_acc_deltas, rho) + torch._foreach_addcmul_(device_acc_deltas, deltas, deltas, value=1 - rho) diff --git a/shared/package-files/4f/4fbfd409e3ebad8b3565e31ab6f094614bd0717beb0e34386f4f3fba05881c0a/__init__.py b/shared/package-files/4f/4fbfd409e3ebad8b3565e31ab6f094614bd0717beb0e34386f4f3fba05881c0a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..474f8d195895a459a75f090e7020c0b36f254776 --- /dev/null +++ b/shared/package-files/4f/4fbfd409e3ebad8b3565e31ab6f094614bd0717beb0e34386f4f3fba05881c0a/__init__.py @@ -0,0 +1 @@ +# ! Any change to this module will trigger the pyspark and pyspark-connect tests in CI diff --git a/shared/package-files/4f/4fc28c3230191c9f2498cde824626bca00f5f5ef460de5cdd6b371e4ac2d814a/subclass_utils.py b/shared/package-files/4f/4fc28c3230191c9f2498cde824626bca00f5f5ef460de5cdd6b371e4ac2d814a/subclass_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cee3cf6e4edab5a263a136427da0830a0dab3c4d --- /dev/null +++ b/shared/package-files/4f/4fc28c3230191c9f2498cde824626bca00f5f5ef460de5cdd6b371e4ac2d814a/subclass_utils.py @@ -0,0 +1,295 @@ +""" +This file contains utilities for tracing through __torch_dispatch__ based tensor subclasses and modes. +AOTAutograd's responsibility is to trace through all pytorch capabilities that live in the pytorch dispatcher, +and this includes tensor subclasses that implement __torch_dispatch__. +""" + +from typing import Any, List, Optional, Tuple, Union + +import torch.utils._pytree as pytree + +from torch import Tensor +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .schemas import MutationType, SubclassCreationMeta, ViewAndMutationMeta +from .utils import strict_zip + +zip = strict_zip + + +def requires_subclass_dispatch(args, fw_metadata: ViewAndMutationMeta) -> bool: + args_flattened = pytree.arg_tree_leaves(*args) + any_subclass_args = any( + is_traceable_wrapper_subclass(x) + for x in args_flattened + if isinstance(x, Tensor) + ) + from torch._functorch._aot_autograd.schemas import SubclassCreationMeta + + any_subclass_outputs = any( + type(x) is SubclassCreationMeta for x in fw_metadata.subclass_fw_graph_out_meta + ) + # This tells us whether or not we need to perform any unwrapping/wrapping of tensor subclasses at runtime. + return any_subclass_args or any_subclass_outputs + + +# Given a flat list of arguments, some of which may be tensor subclasses, +# computes metadata about "how to reconstruct the current list of subclasses, +# if we were given their flattened dense tensors instead" +def create_subclass_meta( + curr_args: Union[List[Any], Tuple[Any, ...]], +) -> List[Union[int, SubclassCreationMeta]]: + idx = 0 + infos: List[Union[int, SubclassCreationMeta]] = [] + for a in curr_args: + if isinstance(a, Tensor) and is_traceable_wrapper_subclass(a): + attrs, meta = a.__tensor_flatten__() # type: ignore[attr-defined] + start_idx = idx + cnt = len(attrs) + curr_cnt = cnt + infos.append( + SubclassCreationMeta( + flat_tensor_start_idx=start_idx, + arg_count=curr_cnt, + original_subclass=a, + meta=meta, + inner_keys=attrs, + outer_size=a.shape, + outer_stride=a.stride(), + ) + ) + else: + infos.append(idx) + cnt = 1 + idx += cnt + return infos + + +# Output structure: +# - List[Tensor] if tracing an inference graph +# - Tuple[List[Tensor], List[Tensor]] if tracing a joint graph. +# This function effectively concats each inner list of subclass tensors +# into a (potentially longer) list of inner tensors. +# +# This function takes in a pytree of arguments and unwraps any tensor subclasses. +# Annoyingly, we can't use pytrees to perform the unwrapping, because unwrapping returns +# a list of tensors that we would then need to concat together. +# Instead, we specialize the logic for the inference vs. joint graph case. +# NOTE: this function is hot, since we unwrap tensor subclass inputs at runtime +def unwrap_tensor_subclasses(wrapped_args, *, is_joint_structure: bool): + def concat_inner_tensors_from_subclasses(xs): + xs_inner = [] + for x in xs: + if isinstance(x, Tensor) and is_traceable_wrapper_subclass(x): + attrs, _ = x.__tensor_flatten__() # type: ignore[attr-defined] + xs_inner += [getattr(x, attr) for attr in attrs] + else: + xs_inner += [x] + return xs_inner + + if is_joint_structure: + assert isinstance(wrapped_args, tuple) and len(wrapped_args) == 2 + assert isinstance(wrapped_args[0], (tuple, list)) and isinstance( + wrapped_args[1], (tuple, list) + ) + unwrapped_args_fw = concat_inner_tensors_from_subclasses(wrapped_args[0]) + unwrapped_args_tangents = concat_inner_tensors_from_subclasses(wrapped_args[1]) + unwrapped_args = (unwrapped_args_fw, unwrapped_args_tangents) + else: + assert isinstance(wrapped_args, (list, tuple)) + unwrapped_args_fw = concat_inner_tensors_from_subclasses(wrapped_args) + unwrapped_args = unwrapped_args_fw + return unwrapped_args + + +# Turns a flattened list of tensor arguments into (maybe) subclass tensors. +# This function is used both at trace time and runtime, so we have an is_runtime flag telling us which context we're in. +def wrap_tensor_subclasses( + unwrapped_args: Union[Tuple[Any, ...], List[Any]], + *, + subclass_metas: List[Union[int, SubclassCreationMeta]], + num_fw_outs_saved_for_bw: Optional[int] = None, + is_runtime: bool = False, +) -> Tuple[Any, ...]: + wrapped_args = [] + num_args_tallied = 0 + for subclass_meta in subclass_metas: + if isinstance(subclass_meta, int): + wrapped_args.append(unwrapped_args[subclass_meta]) + num_args_tallied += 1 + else: + assert isinstance(subclass_meta, SubclassCreationMeta) + wrapped_args.append( + subclass_meta.creation_fn(unwrapped_args, is_runtime=is_runtime) + ) + num_args_tallied += subclass_meta.arg_count + + # Note: [Partitioner handling for Subclasses, Part 2] + # At the beginning of AOTAutograd, we collect metadata on the inputs and outputs of the user fw, + # to figure out which inputs/outputs are subclasses, and how to reconstruct the subclasses after flattening them. + # + # When this function is called at runtime in the forward, + # we have been passed a list of (flattened) dense-tensor fw-outs, and need to reconstruct any subclass fw outs. + # + # One reasonable question that you should ask: when should the dense_tensor -> subclass_tensor wrapping happen? + # Answer: we do it **inside of our compiled autograd.Function**. + # This seems like morally the right place: autograd happens above subclass desugaring, + # so autograd should see actual tensor subclasses at runtime, and not flattened dense tensors. + # + # This causes a tricky interaction though: when we run the min-cut partitioner to divvy up the joint graph + # into a forward and backward graph, we end up with some activations that show up as extra outputs + # in the compiled forward graph, that are **not** user outputs. + # These activations are not visible to the user, and so there's no need for us to wrap them back into subclasses. + # + # On top of that, when we first computed subclass metadata (in `run_functionalized_fw_and_collect_metadata`), + # we computed subclass metadata on every forward output, but this did **not** include activations + # created by the partitioner. + # as a result, `unwrapped_args` here will correspond to (*unwrapped_user_fw_outs, *activations), + # but `subclass_metas` will only correspond to subclass metatadata on `user_fw_outs`. + # We then need to make sure that we return (*wrapped_user_fw_outs, *activations). + if num_fw_outs_saved_for_bw is not None: + assert len(unwrapped_args) == num_args_tallied + num_fw_outs_saved_for_bw, ( + f"Expected the number actual unwrapped-subclass outputs {len(unwrapped_args)} to equal " + f"the number of args calculated from subclasses ({num_args_tallied}) plus the number of " + f"additional activations saved for the backward pass ({num_fw_outs_saved_for_bw})" + ) + activations = unwrapped_args[num_args_tallied:] + if isinstance(wrapped_args, tuple) and isinstance(activations, tuple): + return wrapped_args + activations + return tuple(list(wrapped_args) + list(activations)) + else: + assert len(unwrapped_args) == num_args_tallied + return tuple(wrapped_args) + + +# Given a bunch of "dense" tensor arguments, this function (potentially) wraps them into tensor subclasses. +# This function carefully handles the inference vs. joint cases: +# - when is_joint_structure is True, args is (primals, tangents) +# - when is_joint_structure is False, args is [*primals] +def wrap_tensor_subclasses_maybe_joint( + unwrapped_args, *, is_joint_structure: bool, meta: ViewAndMutationMeta +) -> Union[Tuple[Any, ...], List[Any]]: + # Since this function is re-used for both inference and joint graphs, + if is_joint_structure: + assert isinstance(unwrapped_args, tuple) and len(unwrapped_args) == 2 + assert isinstance(unwrapped_args[0], (tuple, list)) and isinstance( + unwrapped_args[1], (tuple, list) + ) + primals, tangents = unwrapped_args[0], unwrapped_args[1] + wrapped_primals = wrap_tensor_subclasses( + primals, subclass_metas=meta.subclass_inp_meta + ) + wrapped_tangents = wrap_tensor_subclasses( + tangents, subclass_metas=meta.subclass_tangent_meta + ) + return (wrapped_primals, wrapped_tangents) + else: + wrapped_args = wrap_tensor_subclasses( + unwrapped_args, subclass_metas=meta.subclass_inp_meta + ) + return wrapped_args + + +# TODO: UNUSED. delete? +def create_metadata_for_subclass(meta: ViewAndMutationMeta) -> ViewAndMutationMeta: + # input infos + input_info = [] + for inp, subclass_meta in zip(meta.input_info, meta.subclass_inp_meta): + num_inps = 1 if isinstance(subclass_meta, int) else subclass_meta.arg_count + for _ in range(num_inps): + input_info.append(inp) + + # output infos + output_info = [] + subclass_out_meta_user_outs_only = meta.subclass_fw_graph_out_meta[ + meta.num_mutated_inp_runtime_indices : + ] + if meta.num_intermediate_bases > 0: + subclass_out_meta_user_outs_only = subclass_out_meta_user_outs_only[ + : -meta.num_intermediate_bases + ] + # sanity assert + assert len(meta.output_info) == len(subclass_out_meta_user_outs_only) + # Assume that the information on the output is shared by all of its inner tensors. + for out, subclass_meta in zip(meta.output_info, subclass_out_meta_user_outs_only): + num_outs = 1 if isinstance(subclass_meta, int) else subclass_meta.arg_count + for _ in range(num_outs): + output_info.append(out) + + # A bit hacky, but we don't actually care about all of the metadata here. + # This metadata is used **underneath** both autograd and subclass de-sugaring, + # So all we really care about is stuff like: + # - num inputs/outputs (needed by the partitioner) + # - input mutations (**not** used today, since we don't handle input mutations inside the subclass, + # although we should handle this eventually) + # TODO: add a test case to assert we error when this happens, instead of getting silent correctness + num_intermediate_bases = None + keep_input_mutations = meta.keep_input_mutations + traced_tangents = None + subclass_inp_meta = None + subclass_fw_graph_out_meta = None + subclass_tangent_meta = None + + metadata = ViewAndMutationMeta( + input_info=input_info, # type: ignore[arg-type] + output_info=output_info, # type: ignore[arg-type] + num_intermediate_bases=num_intermediate_bases, # type: ignore[arg-type] + keep_input_mutations=keep_input_mutations, # type: ignore[arg-type] + traced_tangents=traced_tangents, # type: ignore[arg-type] + subclass_inp_meta=subclass_inp_meta, # type: ignore[arg-type] + subclass_fw_graph_out_meta=subclass_fw_graph_out_meta, # type: ignore[arg-type] + subclass_tangent_meta=subclass_tangent_meta, # type: ignore[arg-type] + ) + return metadata + + +def compute_inner_mutated_inp_indices_from_subclass_meta( + fw_metadata: ViewAndMutationMeta, + inner_metadata: ViewAndMutationMeta, +) -> List[int]: + # Note: [Recomputing subclass mutation handling] + # + # Generally, if a subclass requires grad, its components will not require grad. + # But for the purposes of tracking returned tensors, we should treat those component + # tensors as if they require grad. + # + # For example, if the subclass tensor requires grad and will be mutated in a way that + # requires us to handle the mutation outside of the graph, we need to return it + # from the forward graph. The inner_meta data won't consider the component tensors + # as if they need to be returned, because they don't require grad; but really, we + # should handle those tensors the same way we handle the subclass tensor itself; i.e. + # if we'd include the subclass tensor as part of the outputs, then we should also + # include the component tensors. + # + # To do this, we patch num_mutated_inp_runtime_indices below by expanding the inputs + # from the outer subclass tensors and propagating + + updated_input_info = [] + inner_idx = 0 + if not fw_metadata.subclass_inp_meta: + # Sometimes we don't have subclass info, e.g. synthetic_base codepaths + return inner_metadata.mutated_inp_runtime_indices + assert len(fw_metadata.subclass_inp_meta) == len(fw_metadata.input_info) + for outer_idx, inp_meta in enumerate(fw_metadata.subclass_inp_meta): + if isinstance(inp_meta, int): + assert outer_idx < len(fw_metadata.input_info) + if inner_metadata is not None: + assert inner_idx < len(inner_metadata.input_info) + assert ( + inner_metadata.input_info[inner_idx] + == fw_metadata.input_info[outer_idx] + ) + updated_input_info.append(fw_metadata.input_info[outer_idx]) + inner_idx += 1 + else: + for _ in range(inp_meta.arg_count): + updated_input_info.append(fw_metadata.input_info[outer_idx]) + inner_idx += 1 + if inner_metadata is not None: + assert len(inner_metadata.input_info) == len(updated_input_info) + + return [ + i + for i, inp in enumerate(updated_input_info) + if inp.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] diff --git a/shared/package-files/4f/4fc30889d5672d0fe1f9ebad40dea03eed139052eec0f28017e13b3ffc915e36/xterm+sm+1002 b/shared/package-files/4f/4fc30889d5672d0fe1f9ebad40dea03eed139052eec0f28017e13b3ffc915e36/xterm+sm+1002 new file mode 100644 index 0000000000000000000000000000000000000000..11c7ae7cd406ad577cca38964b23f3dca982129d Binary files /dev/null and b/shared/package-files/4f/4fc30889d5672d0fe1f9ebad40dea03eed139052eec0f28017e13b3ffc915e36/xterm+sm+1002 differ diff --git a/shared/package-files/4f/4fc3be2bade4e57cc4083fbab410ecaa4cc29d56fe711fd7d1dfc72993c33aeb/test_time_grouper.py b/shared/package-files/4f/4fc3be2bade4e57cc4083fbab410ecaa4cc29d56fe711fd7d1dfc72993c33aeb/test_time_grouper.py new file mode 100644 index 0000000000000000000000000000000000000000..3d9098917a12d556a7c4a919dbd996fd0a6fe966 --- /dev/null +++ b/shared/package-files/4f/4fc3be2bade4e57cc4083fbab410ecaa4cc29d56fe711fd7d1dfc72993c33aeb/test_time_grouper.py @@ -0,0 +1,390 @@ +from datetime import datetime +from operator import methodcaller + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Index, + Series, + Timestamp, +) +import pandas._testing as tm +from pandas.core.groupby.grouper import Grouper +from pandas.core.indexes.datetimes import date_range + + +@pytest.fixture +def test_series(): + return Series( + np.random.default_rng(2).standard_normal(1000), + index=date_range("1/1/2000", periods=1000), + ) + + +def test_apply(test_series): + grouper = Grouper(freq="YE", label="right", closed="right") + + grouped = test_series.groupby(grouper) + + def f(x): + return x.sort_values()[-3:] + + applied = grouped.apply(f) + expected = test_series.groupby(lambda x: x.year).apply(f) + + applied.index = applied.index.droplevel(0) + expected.index = expected.index.droplevel(0) + tm.assert_series_equal(applied, expected) + + +def test_count(test_series): + test_series[::3] = np.nan + + expected = test_series.groupby(lambda x: x.year).count() + + grouper = Grouper(freq="YE", label="right", closed="right") + result = test_series.groupby(grouper).count() + expected.index = result.index + tm.assert_series_equal(result, expected) + + result = test_series.resample("YE").count() + expected.index = result.index + tm.assert_series_equal(result, expected) + + +def test_numpy_reduction(test_series): + result = test_series.resample("YE", closed="right").prod() + + msg = "using SeriesGroupBy.prod" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = test_series.groupby(lambda x: x.year).agg(np.prod) + expected.index = result.index + + tm.assert_series_equal(result, expected) + + +def test_apply_iteration(): + # #2300 + N = 1000 + ind = date_range(start="2000-01-01", freq="D", periods=N) + df = DataFrame({"open": 1, "close": 2}, index=ind) + tg = Grouper(freq="ME") + + grouper, _ = tg._get_grouper(df) + + # Errors + grouped = df.groupby(grouper, group_keys=False) + + def f(df): + return df["close"] / df["open"] + + # it works! + result = grouped.apply(f) + tm.assert_index_equal(result.index, df.index) + + +@pytest.mark.parametrize( + "index", + [ + Index([1, 2]), + Index(["a", "b"]), + Index([1.1, 2.2]), + pd.MultiIndex.from_arrays([[1, 2], ["a", "b"]]), + ], +) +def test_fails_on_no_datetime_index(index): + name = type(index).__name__ + df = DataFrame({"a": range(len(index))}, index=index) + + msg = ( + "Only valid with DatetimeIndex, TimedeltaIndex " + f"or PeriodIndex, but got an instance of '{name}'" + ) + with pytest.raises(TypeError, match=msg): + df.groupby(Grouper(freq="D")) + + +def test_aaa_group_order(): + # GH 12840 + # check TimeGrouper perform stable sorts + n = 20 + data = np.random.default_rng(2).standard_normal((n, 4)) + df = DataFrame(data, columns=["A", "B", "C", "D"]) + df["key"] = [ + datetime(2013, 1, 1), + datetime(2013, 1, 2), + datetime(2013, 1, 3), + datetime(2013, 1, 4), + datetime(2013, 1, 5), + ] * 4 + grouped = df.groupby(Grouper(key="key", freq="D")) + + tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 1)), df[::5]) + tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 2)), df[1::5]) + tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 3)), df[2::5]) + tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 4)), df[3::5]) + tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 5)), df[4::5]) + + +def test_aggregate_normal(resample_method): + """Check TimeGrouper's aggregation is identical as normal groupby.""" + + data = np.random.default_rng(2).standard_normal((20, 4)) + normal_df = DataFrame(data, columns=["A", "B", "C", "D"]) + normal_df["key"] = [1, 2, 3, 4, 5] * 4 + + dt_df = DataFrame(data, columns=["A", "B", "C", "D"]) + dt_df["key"] = Index( + [ + datetime(2013, 1, 1), + datetime(2013, 1, 2), + datetime(2013, 1, 3), + datetime(2013, 1, 4), + datetime(2013, 1, 5), + ] + * 4, + dtype="M8[ns]", + ) + + normal_grouped = normal_df.groupby("key") + dt_grouped = dt_df.groupby(Grouper(key="key", freq="D")) + + expected = getattr(normal_grouped, resample_method)() + dt_result = getattr(dt_grouped, resample_method)() + expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key") + tm.assert_equal(expected, dt_result) + + +@pytest.mark.xfail(reason="if TimeGrouper is used included, 'nth' doesn't work yet") +def test_aggregate_nth(): + """Check TimeGrouper's aggregation is identical as normal groupby.""" + + data = np.random.default_rng(2).standard_normal((20, 4)) + normal_df = DataFrame(data, columns=["A", "B", "C", "D"]) + normal_df["key"] = [1, 2, 3, 4, 5] * 4 + + dt_df = DataFrame(data, columns=["A", "B", "C", "D"]) + dt_df["key"] = [ + datetime(2013, 1, 1), + datetime(2013, 1, 2), + datetime(2013, 1, 3), + datetime(2013, 1, 4), + datetime(2013, 1, 5), + ] * 4 + + normal_grouped = normal_df.groupby("key") + dt_grouped = dt_df.groupby(Grouper(key="key", freq="D")) + + expected = normal_grouped.nth(3) + expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key") + dt_result = dt_grouped.nth(3) + tm.assert_frame_equal(expected, dt_result) + + +@pytest.mark.parametrize( + "method, method_args, unit", + [ + ("sum", {}, 0), + ("sum", {"min_count": 0}, 0), + ("sum", {"min_count": 1}, np.nan), + ("prod", {}, 1), + ("prod", {"min_count": 0}, 1), + ("prod", {"min_count": 1}, np.nan), + ], +) +def test_resample_entirely_nat_window(method, method_args, unit): + ser = Series([0] * 2 + [np.nan] * 2, index=date_range("2017", periods=4)) + result = methodcaller(method, **method_args)(ser.resample("2d")) + + exp_dti = pd.DatetimeIndex(["2017-01-01", "2017-01-03"], dtype="M8[ns]", freq="2D") + expected = Series([0.0, unit], index=exp_dti) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func, fill_value", + [("min", np.nan), ("max", np.nan), ("sum", 0), ("prod", 1), ("count", 0)], +) +def test_aggregate_with_nat(func, fill_value): + # check TimeGrouper's aggregation is identical as normal groupby + # if NaT is included, 'var', 'std', 'mean', 'first','last' + # and 'nth' doesn't work yet + + n = 20 + data = np.random.default_rng(2).standard_normal((n, 4)).astype("int64") + normal_df = DataFrame(data, columns=["A", "B", "C", "D"]) + normal_df["key"] = [1, 2, np.nan, 4, 5] * 4 + + dt_df = DataFrame(data, columns=["A", "B", "C", "D"]) + dt_df["key"] = Index( + [ + datetime(2013, 1, 1), + datetime(2013, 1, 2), + pd.NaT, + datetime(2013, 1, 4), + datetime(2013, 1, 5), + ] + * 4, + dtype="M8[ns]", + ) + + normal_grouped = normal_df.groupby("key") + dt_grouped = dt_df.groupby(Grouper(key="key", freq="D")) + + normal_result = getattr(normal_grouped, func)() + dt_result = getattr(dt_grouped, func)() + + pad = DataFrame([[fill_value] * 4], index=[3], columns=["A", "B", "C", "D"]) + expected = pd.concat([normal_result, pad]) + expected = expected.sort_index() + dti = date_range( + start="2013-01-01", + freq="D", + periods=5, + name="key", + unit=dt_df["key"]._values.unit, + ) + expected.index = dti._with_freq(None) # TODO: is this desired? + tm.assert_frame_equal(expected, dt_result) + assert dt_result.index.name == "key" + + +def test_aggregate_with_nat_size(): + # GH 9925 + n = 20 + data = np.random.default_rng(2).standard_normal((n, 4)).astype("int64") + normal_df = DataFrame(data, columns=["A", "B", "C", "D"]) + normal_df["key"] = [1, 2, np.nan, 4, 5] * 4 + + dt_df = DataFrame(data, columns=["A", "B", "C", "D"]) + dt_df["key"] = Index( + [ + datetime(2013, 1, 1), + datetime(2013, 1, 2), + pd.NaT, + datetime(2013, 1, 4), + datetime(2013, 1, 5), + ] + * 4, + dtype="M8[ns]", + ) + + normal_grouped = normal_df.groupby("key") + dt_grouped = dt_df.groupby(Grouper(key="key", freq="D")) + + normal_result = normal_grouped.size() + dt_result = dt_grouped.size() + + pad = Series([0], index=[3]) + expected = pd.concat([normal_result, pad]) + expected = expected.sort_index() + expected.index = date_range( + start="2013-01-01", + freq="D", + periods=5, + name="key", + unit=dt_df["key"]._values.unit, + )._with_freq(None) + tm.assert_series_equal(expected, dt_result) + assert dt_result.index.name == "key" + + +def test_repr(): + # GH18203 + result = repr(Grouper(key="A", freq="h")) + expected = ( + "TimeGrouper(key='A', freq=, axis=0, sort=True, dropna=True, " + "closed='left', label='left', how='mean', " + "convention='e', origin='start_day')" + ) + assert result == expected + + result = repr(Grouper(key="A", freq="h", origin="2000-01-01")) + expected = ( + "TimeGrouper(key='A', freq=, axis=0, sort=True, dropna=True, " + "closed='left', label='left', how='mean', " + "convention='e', origin=Timestamp('2000-01-01 00:00:00'))" + ) + assert result == expected + + +@pytest.mark.parametrize( + "method, method_args, expected_values", + [ + ("sum", {}, [1, 0, 1]), + ("sum", {"min_count": 0}, [1, 0, 1]), + ("sum", {"min_count": 1}, [1, np.nan, 1]), + ("sum", {"min_count": 2}, [np.nan, np.nan, np.nan]), + ("prod", {}, [1, 1, 1]), + ("prod", {"min_count": 0}, [1, 1, 1]), + ("prod", {"min_count": 1}, [1, np.nan, 1]), + ("prod", {"min_count": 2}, [np.nan, np.nan, np.nan]), + ], +) +def test_upsample_sum(method, method_args, expected_values): + ser = Series(1, index=date_range("2017", periods=2, freq="h")) + resampled = ser.resample("30min") + index = pd.DatetimeIndex( + ["2017-01-01T00:00:00", "2017-01-01T00:30:00", "2017-01-01T01:00:00"], + dtype="M8[ns]", + freq="30min", + ) + result = methodcaller(method, **method_args)(resampled) + expected = Series(expected_values, index=index) + tm.assert_series_equal(result, expected) + + +def test_groupby_resample_interpolate(): + # GH 35325 + d = {"price": [10, 11, 9], "volume": [50, 60, 50]} + + df = DataFrame(d) + + df["week_starting"] = date_range("01/01/2018", periods=3, freq="W") + + msg = "DataFrameGroupBy.resample operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ( + df.set_index("week_starting") + .groupby("volume") + .resample("1D") + .interpolate(method="linear") + ) + + volume = [50] * 15 + [60] + week_starting = list(date_range("2018-01-07", "2018-01-21")) + [ + Timestamp("2018-01-14") + ] + expected_ind = pd.MultiIndex.from_arrays( + [volume, week_starting], + names=["volume", "week_starting"], + ) + + expected = DataFrame( + data={ + "price": [ + 10.0, + 9.928571428571429, + 9.857142857142858, + 9.785714285714286, + 9.714285714285714, + 9.642857142857142, + 9.571428571428571, + 9.5, + 9.428571428571429, + 9.357142857142858, + 9.285714285714286, + 9.214285714285714, + 9.142857142857142, + 9.071428571428571, + 9.0, + 11.0, + ], + "volume": [50.0] * 15 + [60], + }, + index=expected_ind, + ) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/4f/4fc5a79f53d60fd0576f94dfe8aa7677357d9ad95315ea220ba523f53c89229b/idna.py b/shared/package-files/4f/4fc5a79f53d60fd0576f94dfe8aa7677357d9ad95315ea220ba523f53c89229b/idna.py new file mode 100644 index 0000000000000000000000000000000000000000..bf98f513366b314d69d3af30d2f7b2a7ea7b07f7 --- /dev/null +++ b/shared/package-files/4f/4fc5a79f53d60fd0576f94dfe8aa7677357d9ad95315ea220ba523f53c89229b/idna.py @@ -0,0 +1,307 @@ +# This module implements the RFCs 3490 (IDNA) and 3491 (Nameprep) + +import stringprep, re, codecs +from unicodedata import ucd_3_2_0 as unicodedata + +# IDNA section 3.1 +dots = re.compile("[\u002E\u3002\uFF0E\uFF61]") + +# IDNA section 5 +ace_prefix = b"xn--" +sace_prefix = "xn--" + +# This assumes query strings, so AllowUnassigned is true +def nameprep(label): + # Map + newlabel = [] + for c in label: + if stringprep.in_table_b1(c): + # Map to nothing + continue + newlabel.append(stringprep.map_table_b2(c)) + label = "".join(newlabel) + + # Normalize + label = unicodedata.normalize("NFKC", label) + + # Prohibit + for c in label: + if stringprep.in_table_c12(c) or \ + stringprep.in_table_c22(c) or \ + stringprep.in_table_c3(c) or \ + stringprep.in_table_c4(c) or \ + stringprep.in_table_c5(c) or \ + stringprep.in_table_c6(c) or \ + stringprep.in_table_c7(c) or \ + stringprep.in_table_c8(c) or \ + stringprep.in_table_c9(c): + raise UnicodeError("Invalid character %r" % c) + + # Check bidi + RandAL = [stringprep.in_table_d1(x) for x in label] + if any(RandAL): + # There is a RandAL char in the string. Must perform further + # tests: + # 1) The characters in section 5.8 MUST be prohibited. + # This is table C.8, which was already checked + # 2) If a string contains any RandALCat character, the string + # MUST NOT contain any LCat character. + if any(stringprep.in_table_d2(x) for x in label): + raise UnicodeError("Violation of BIDI requirement 2") + # 3) If a string contains any RandALCat character, a + # RandALCat character MUST be the first character of the + # string, and a RandALCat character MUST be the last + # character of the string. + if not RandAL[0] or not RandAL[-1]: + raise UnicodeError("Violation of BIDI requirement 3") + + return label + +def ToASCII(label): + try: + # Step 1: try ASCII + label = label.encode("ascii") + except UnicodeError: + pass + else: + # Skip to step 3: UseSTD3ASCIIRules is false, so + # Skip to step 8. + if 0 < len(label) < 64: + return label + raise UnicodeError("label empty or too long") + + # Step 2: nameprep + label = nameprep(label) + + # Step 3: UseSTD3ASCIIRules is false + # Step 4: try ASCII + try: + label = label.encode("ascii") + except UnicodeError: + pass + else: + # Skip to step 8. + if 0 < len(label) < 64: + return label + raise UnicodeError("label empty or too long") + + # Step 5: Check ACE prefix + if label.startswith(sace_prefix): + raise UnicodeError("Label starts with ACE prefix") + + # Step 6: Encode with PUNYCODE + label = label.encode("punycode") + + # Step 7: Prepend ACE prefix + label = ace_prefix + label + + # Step 8: Check size + if 0 < len(label) < 64: + return label + raise UnicodeError("label empty or too long") + +def ToUnicode(label): + # Step 1: Check for ASCII + if isinstance(label, bytes): + pure_ascii = True + else: + try: + label = label.encode("ascii") + pure_ascii = True + except UnicodeError: + pure_ascii = False + if not pure_ascii: + # Step 2: Perform nameprep + label = nameprep(label) + # It doesn't say this, but apparently, it should be ASCII now + try: + label = label.encode("ascii") + except UnicodeError: + raise UnicodeError("Invalid character in IDN label") + # Step 3: Check for ACE prefix + if not label.startswith(ace_prefix): + return str(label, "ascii") + + # Step 4: Remove ACE prefix + label1 = label[len(ace_prefix):] + + # Step 5: Decode using PUNYCODE + result = label1.decode("punycode") + + # Step 6: Apply ToASCII + label2 = ToASCII(result) + + # Step 7: Compare the result of step 6 with the one of step 3 + # label2 will already be in lower case. + if str(label, "ascii").lower() != str(label2, "ascii"): + raise UnicodeError("IDNA does not round-trip", label, label2) + + # Step 8: return the result of step 5 + return result + +### Codec APIs + +class Codec(codecs.Codec): + def encode(self, input, errors='strict'): + + if errors != 'strict': + # IDNA is quite clear that implementations must be strict + raise UnicodeError("unsupported error handling "+errors) + + if not input: + return b'', 0 + + try: + result = input.encode('ascii') + except UnicodeEncodeError: + pass + else: + # ASCII name: fast path + labels = result.split(b'.') + for label in labels[:-1]: + if not (0 < len(label) < 64): + raise UnicodeError("label empty or too long") + if len(labels[-1]) >= 64: + raise UnicodeError("label too long") + return result, len(input) + + result = bytearray() + labels = dots.split(input) + if labels and not labels[-1]: + trailing_dot = b'.' + del labels[-1] + else: + trailing_dot = b'' + for label in labels: + if result: + # Join with U+002E + result.extend(b'.') + result.extend(ToASCII(label)) + return bytes(result+trailing_dot), len(input) + + def decode(self, input, errors='strict'): + + if errors != 'strict': + raise UnicodeError("Unsupported error handling "+errors) + + if not input: + return "", 0 + + # IDNA allows decoding to operate on Unicode strings, too. + if not isinstance(input, bytes): + # XXX obviously wrong, see #3232 + input = bytes(input) + + if ace_prefix not in input: + # Fast path + try: + return input.decode('ascii'), len(input) + except UnicodeDecodeError: + pass + + labels = input.split(b".") + + if labels and len(labels[-1]) == 0: + trailing_dot = '.' + del labels[-1] + else: + trailing_dot = '' + + result = [] + for label in labels: + result.append(ToUnicode(label)) + + return ".".join(result)+trailing_dot, len(input) + +class IncrementalEncoder(codecs.BufferedIncrementalEncoder): + def _buffer_encode(self, input, errors, final): + if errors != 'strict': + # IDNA is quite clear that implementations must be strict + raise UnicodeError("unsupported error handling "+errors) + + if not input: + return (b'', 0) + + labels = dots.split(input) + trailing_dot = b'' + if labels: + if not labels[-1]: + trailing_dot = b'.' + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = b'.' + + result = bytearray() + size = 0 + for label in labels: + if size: + # Join with U+002E + result.extend(b'.') + size += 1 + result.extend(ToASCII(label)) + size += len(label) + + result += trailing_dot + size += len(trailing_dot) + return (bytes(result), size) + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input, errors, final): + if errors != 'strict': + raise UnicodeError("Unsupported error handling "+errors) + + if not input: + return ("", 0) + + # IDNA allows decoding to operate on Unicode strings, too. + if isinstance(input, str): + labels = dots.split(input) + else: + # Must be ASCII string + input = str(input, "ascii") + labels = input.split(".") + + trailing_dot = '' + if labels: + if not labels[-1]: + trailing_dot = '.' + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = '.' + + result = [] + size = 0 + for label in labels: + result.append(ToUnicode(label)) + if size: + size += 1 + size += len(label) + + result = ".".join(result) + trailing_dot + size += len(trailing_dot) + return (result, size) + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='idna', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamwriter=StreamWriter, + streamreader=StreamReader, + ) diff --git a/shared/package-files/4f/4fc6372c4f1eb2aad8dde73c3273ad167b36303247984af35acefb4ea33775bb/_test_warn_in_autograd.h b/shared/package-files/4f/4fc6372c4f1eb2aad8dde73c3273ad167b36303247984af35acefb4ea33775bb/_test_warn_in_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..c0066582f803cd5d609c6481f16056cf2a4ca9b1 --- /dev/null +++ b/shared/package-files/4f/4fc6372c4f1eb2aad8dde73c3273ad167b36303247984af35acefb4ea33775bb/_test_warn_in_autograd.h @@ -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::_test_warn_in_autograd(Tensor self) -> Tensor +inline at::Tensor _test_warn_in_autograd(const at::Tensor & self) { + return at::_ops::_test_warn_in_autograd::call(self); +} + +// aten::_test_warn_in_autograd.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_warn_in_autograd_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::_test_warn_in_autograd_out::call(self, out); +} +// aten::_test_warn_in_autograd.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_warn_in_autograd_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::_test_warn_in_autograd_out::call(self, out); +} + +} diff --git a/shared/package-files/4f/4fca893321b60c35638d834da54bc181f03db42a36dc84b4c3d6f2441eadc304/format.py b/shared/package-files/4f/4fca893321b60c35638d834da54bc181f03db42a36dc84b4c3d6f2441eadc304/format.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b3fbac23ab6e680510cbc3d47387cdee2c6048 --- /dev/null +++ b/shared/package-files/4f/4fca893321b60c35638d834da54bc181f03db42a36dc84b4c3d6f2441eadc304/format.py @@ -0,0 +1,976 @@ +""" +Binary serialization + +NPY format +========== + +A simple format for saving numpy arrays to disk with the full +information about them. + +The ``.npy`` format is the standard binary file format in NumPy for +persisting a *single* arbitrary NumPy array on disk. The format stores all +of the shape and dtype information necessary to reconstruct the array +correctly even on another machine with a different architecture. +The format is designed to be as simple as possible while achieving +its limited goals. + +The ``.npz`` format is the standard format for persisting *multiple* NumPy +arrays on disk. A ``.npz`` file is a zip file containing multiple ``.npy`` +files, one for each array. + +Capabilities +------------ + +- Can represent all NumPy arrays including nested record arrays and + object arrays. + +- Represents the data in its native binary form. + +- Supports Fortran-contiguous arrays directly. + +- Stores all of the necessary information to reconstruct the array + including shape and dtype on a machine of a different + architecture. Both little-endian and big-endian arrays are + supported, and a file with little-endian numbers will yield + a little-endian array on any machine reading the file. The + types are described in terms of their actual sizes. For example, + if a machine with a 64-bit C "long int" writes out an array with + "long ints", a reading machine with 32-bit C "long ints" will yield + an array with 64-bit integers. + +- Is straightforward to reverse engineer. Datasets often live longer than + the programs that created them. A competent developer should be + able to create a solution in their preferred programming language to + read most ``.npy`` files that they have been given without much + documentation. + +- Allows memory-mapping of the data. See `open_memmap`. + +- Can be read from a filelike stream object instead of an actual file. + +- Stores object arrays, i.e. arrays containing elements that are arbitrary + Python objects. Files with object arrays are not to be mmapable, but + can be read and written to disk. + +Limitations +----------- + +- Arbitrary subclasses of numpy.ndarray are not completely preserved. + Subclasses will be accepted for writing, but only the array data will + be written out. A regular numpy.ndarray object will be created + upon reading the file. + +.. warning:: + + Due to limitations in the interpretation of structured dtypes, dtypes + with fields with empty names will have the names replaced by 'f0', 'f1', + etc. Such arrays will not round-trip through the format entirely + accurately. The data is intact; only the field names will differ. We are + working on a fix for this. This fix will not require a change in the + file format. The arrays with such structures can still be saved and + restored, and the correct dtype may be restored by using the + ``loadedarray.view(correct_dtype)`` method. + +File extensions +--------------- + +We recommend using the ``.npy`` and ``.npz`` extensions for files saved +in this format. This is by no means a requirement; applications may wish +to use these file formats but use an extension specific to the +application. In the absence of an obvious alternative, however, +we suggest using ``.npy`` and ``.npz``. + +Version numbering +----------------- + +The version numbering of these formats is independent of NumPy version +numbering. If the format is upgraded, the code in `numpy.io` will still +be able to read and write Version 1.0 files. + +Format Version 1.0 +------------------ + +The first 6 bytes are a magic string: exactly ``\\x93NUMPY``. + +The next 1 byte is an unsigned byte: the major version number of the file +format, e.g. ``\\x01``. + +The next 1 byte is an unsigned byte: the minor version number of the file +format, e.g. ``\\x00``. Note: the version of the file format is not tied +to the version of the numpy package. + +The next 2 bytes form a little-endian unsigned short int: the length of +the header data HEADER_LEN. + +The next HEADER_LEN bytes form the header data describing the array's +format. It is an ASCII string which contains a Python literal expression +of a dictionary. It is terminated by a newline (``\\n``) and padded with +spaces (``\\x20``) to make the total of +``len(magic string) + 2 + len(length) + HEADER_LEN`` be evenly divisible +by 64 for alignment purposes. + +The dictionary contains three keys: + + "descr" : dtype.descr + An object that can be passed as an argument to the `numpy.dtype` + constructor to create the array's dtype. + "fortran_order" : bool + Whether the array data is Fortran-contiguous or not. Since + Fortran-contiguous arrays are a common form of non-C-contiguity, + we allow them to be written directly to disk for efficiency. + "shape" : tuple of int + The shape of the array. + +For repeatability and readability, the dictionary keys are sorted in +alphabetic order. This is for convenience only. A writer SHOULD implement +this if possible. A reader MUST NOT depend on this. + +Following the header comes the array data. If the dtype contains Python +objects (i.e. ``dtype.hasobject is True``), then the data is a Python +pickle of the array. Otherwise the data is the contiguous (either C- +or Fortran-, depending on ``fortran_order``) bytes of the array. +Consumers can figure out the number of bytes by multiplying the number +of elements given by the shape (noting that ``shape=()`` means there is +1 element) by ``dtype.itemsize``. + +Format Version 2.0 +------------------ + +The version 1.0 format only allowed the array header to have a total size of +65535 bytes. This can be exceeded by structured arrays with a large number of +columns. The version 2.0 format extends the header size to 4 GiB. +`numpy.save` will automatically save in 2.0 format if the data requires it, +else it will always use the more compatible 1.0 format. + +The description of the fourth element of the header therefore has become: +"The next 4 bytes form a little-endian unsigned int: the length of the header +data HEADER_LEN." + +Format Version 3.0 +------------------ + +This version replaces the ASCII string (which in practice was latin1) with +a utf8-encoded string, so supports structured types with any unicode field +names. + +Notes +----- +The ``.npy`` format, including motivation for creating it and a comparison of +alternatives, is described in the +:doc:`"npy-format" NEP `, however details have +evolved with time and this document is more current. + +""" +import numpy +import warnings +from numpy.lib.utils import safe_eval, drop_metadata +from numpy.compat import ( + isfileobj, os_fspath, pickle + ) + + +__all__ = [] + + +EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} +MAGIC_PREFIX = b'\x93NUMPY' +MAGIC_LEN = len(MAGIC_PREFIX) + 2 +ARRAY_ALIGN = 64 # plausible values are powers of 2 between 16 and 4096 +BUFFER_SIZE = 2**18 # size of buffer for reading npz files in bytes +# allow growth within the address space of a 64 bit machine along one axis +GROWTH_AXIS_MAX_DIGITS = 21 # = len(str(8*2**64-1)) hypothetical int1 dtype + +# difference between version 1.0 and 2.0 is a 4 byte (I) header length +# instead of 2 bytes (H) allowing storage of large structured arrays +_header_size_info = { + (1, 0): (' 255: + raise ValueError("major version must be 0 <= major < 256") + if minor < 0 or minor > 255: + raise ValueError("minor version must be 0 <= minor < 256") + return MAGIC_PREFIX + bytes([major, minor]) + +def read_magic(fp): + """ Read the magic string to get the version of the file format. + + Parameters + ---------- + fp : filelike object + + Returns + ------- + major : int + minor : int + """ + magic_str = _read_bytes(fp, MAGIC_LEN, "magic string") + if magic_str[:-2] != MAGIC_PREFIX: + msg = "the magic string is not correct; expected %r, got %r" + raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) + major, minor = magic_str[-2:] + return major, minor + + +def dtype_to_descr(dtype): + """ + Get a serializable descriptor from the dtype. + + The .descr attribute of a dtype object cannot be round-tripped through + the dtype() constructor. Simple types, like dtype('float32'), have + a descr which looks like a record array with one field with '' as + a name. The dtype() constructor interprets this as a request to give + a default name. Instead, we construct descriptor that can be passed to + dtype(). + + Parameters + ---------- + dtype : dtype + The dtype of the array that will be written to disk. + + Returns + ------- + descr : object + An object that can be passed to `numpy.dtype()` in order to + replicate the input dtype. + + """ + # NOTE: that drop_metadata may not return the right dtype e.g. for user + # dtypes. In that case our code below would fail the same, though. + new_dtype = drop_metadata(dtype) + if new_dtype is not dtype: + warnings.warn("metadata on a dtype is not saved to an npy/npz. " + "Use another format (such as pickle) to store it.", + UserWarning, stacklevel=2) + if dtype.names is not None: + # This is a record array. The .descr is fine. XXX: parts of the + # record array with an empty name, like padding bytes, still get + # fiddled with. This needs to be fixed in the C implementation of + # dtype(). + return dtype.descr + else: + return dtype.str + +def descr_to_dtype(descr): + """ + Returns a dtype based off the given description. + + This is essentially the reverse of `dtype_to_descr()`. It will remove + the valueless padding fields created by, i.e. simple fields like + dtype('float32'), and then convert the description to its corresponding + dtype. + + Parameters + ---------- + descr : object + The object retrieved by dtype.descr. Can be passed to + `numpy.dtype()` in order to replicate the input dtype. + + Returns + ------- + dtype : dtype + The dtype constructed by the description. + + """ + if isinstance(descr, str): + # No padding removal needed + return numpy.dtype(descr) + elif isinstance(descr, tuple): + # subtype, will always have a shape descr[1] + dt = descr_to_dtype(descr[0]) + return numpy.dtype((dt, descr[1])) + + titles = [] + names = [] + formats = [] + offsets = [] + offset = 0 + for field in descr: + if len(field) == 2: + name, descr_str = field + dt = descr_to_dtype(descr_str) + else: + name, descr_str, shape = field + dt = numpy.dtype((descr_to_dtype(descr_str), shape)) + + # Ignore padding bytes, which will be void bytes with '' as name + # Once support for blank names is removed, only "if name == ''" needed) + is_pad = (name == '' and dt.type is numpy.void and dt.names is None) + if not is_pad: + title, name = name if isinstance(name, tuple) else (None, name) + titles.append(title) + names.append(name) + formats.append(dt) + offsets.append(offset) + offset += dt.itemsize + + return numpy.dtype({'names': names, 'formats': formats, 'titles': titles, + 'offsets': offsets, 'itemsize': offset}) + +def header_data_from_array_1_0(array): + """ Get the dictionary of header metadata from a numpy.ndarray. + + Parameters + ---------- + array : numpy.ndarray + + Returns + ------- + d : dict + This has the appropriate entries for writing its string representation + to the header of the file. + """ + d = {'shape': array.shape} + if array.flags.c_contiguous: + d['fortran_order'] = False + elif array.flags.f_contiguous: + d['fortran_order'] = True + else: + # Totally non-contiguous data. We will have to make it C-contiguous + # before writing. Note that we need to test for C_CONTIGUOUS first + # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS. + d['fortran_order'] = False + + d['descr'] = dtype_to_descr(array.dtype) + return d + + +def _wrap_header(header, version): + """ + Takes a stringified header, and attaches the prefix and padding to it + """ + import struct + assert version is not None + fmt, encoding = _header_size_info[version] + header = header.encode(encoding) + hlen = len(header) + 1 + padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) + try: + header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen) + except struct.error: + msg = "Header length {} too big for version={}".format(hlen, version) + raise ValueError(msg) from None + + # Pad the header with spaces and a final newline such that the magic + # string, the header-length short and the header are aligned on a + # ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes + # aligned up to ARRAY_ALIGN on systems like Linux where mmap() + # offset must be page-aligned (i.e. the beginning of the file). + return header_prefix + header + b' '*padlen + b'\n' + + +def _wrap_header_guess_version(header): + """ + Like `_wrap_header`, but chooses an appropriate version given the contents + """ + try: + return _wrap_header(header, (1, 0)) + except ValueError: + pass + + try: + ret = _wrap_header(header, (2, 0)) + except UnicodeEncodeError: + pass + else: + warnings.warn("Stored array in format 2.0. It can only be" + "read by NumPy >= 1.9", UserWarning, stacklevel=2) + return ret + + header = _wrap_header(header, (3, 0)) + warnings.warn("Stored array in format 3.0. It can only be " + "read by NumPy >= 1.17", UserWarning, stacklevel=2) + return header + + +def _write_array_header(fp, d, version=None): + """ Write the header for an array and returns the version used + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string representation + to the header of the file. + version : tuple or None + None means use oldest that works. Providing an explicit version will + raise a ValueError if the format does not allow saving this data. + Default: None + """ + header = ["{"] + for key, value in sorted(d.items()): + # Need to use repr here, since we eval these when reading + header.append("'%s': %s, " % (key, repr(value))) + header.append("}") + header = "".join(header) + + # Add some spare space so that the array header can be modified in-place + # when changing the array size, e.g. when growing it by appending data at + # the end. + shape = d['shape'] + header += " " * ((GROWTH_AXIS_MAX_DIGITS - len(repr( + shape[-1 if d['fortran_order'] else 0] + ))) if len(shape) > 0 else 0) + + if version is None: + header = _wrap_header_guess_version(header) + else: + header = _wrap_header(header, version) + fp.write(header) + +def write_array_header_1_0(fp, d): + """ Write the header for an array using the 1.0 format. + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string + representation to the header of the file. + """ + _write_array_header(fp, d, (1, 0)) + + +def write_array_header_2_0(fp, d): + """ Write the header for an array using the 2.0 format. + The 2.0 format allows storing very large structured arrays. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string + representation to the header of the file. + """ + _write_array_header(fp, d, (2, 0)) + +def read_array_header_1_0(fp, max_header_size=_MAX_HEADER_SIZE): + """ + Read an array header from a filelike object using the 1.0 file format + version. + + This will leave the file object located just after the header. + + Parameters + ---------- + fp : filelike object + A file object or something with a `.read()` method like a file. + + Returns + ------- + shape : tuple of int + The shape of the array. + fortran_order : bool + The array data will be written out directly if it is either + C-contiguous or Fortran-contiguous. Otherwise, it will be made + contiguous before writing it out. + dtype : dtype + The dtype of the file's data. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + + Raises + ------ + ValueError + If the data is invalid. + + """ + return _read_array_header( + fp, version=(1, 0), max_header_size=max_header_size) + +def read_array_header_2_0(fp, max_header_size=_MAX_HEADER_SIZE): + """ + Read an array header from a filelike object using the 2.0 file format + version. + + This will leave the file object located just after the header. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + fp : filelike object + A file object or something with a `.read()` method like a file. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + + Returns + ------- + shape : tuple of int + The shape of the array. + fortran_order : bool + The array data will be written out directly if it is either + C-contiguous or Fortran-contiguous. Otherwise, it will be made + contiguous before writing it out. + dtype : dtype + The dtype of the file's data. + + Raises + ------ + ValueError + If the data is invalid. + + """ + return _read_array_header( + fp, version=(2, 0), max_header_size=max_header_size) + + +def _filter_header(s): + """Clean up 'L' in npz header ints. + + Cleans up the 'L' in strings representing integers. Needed to allow npz + headers produced in Python2 to be read in Python3. + + Parameters + ---------- + s : string + Npy file header. + + Returns + ------- + header : str + Cleaned up header. + + """ + import tokenize + from io import StringIO + + tokens = [] + last_token_was_number = False + for token in tokenize.generate_tokens(StringIO(s).readline): + token_type = token[0] + token_string = token[1] + if (last_token_was_number and + token_type == tokenize.NAME and + token_string == "L"): + continue + else: + tokens.append(token) + last_token_was_number = (token_type == tokenize.NUMBER) + return tokenize.untokenize(tokens) + + +def _read_array_header(fp, version, max_header_size=_MAX_HEADER_SIZE): + """ + see read_array_header_1_0 + """ + # Read an unsigned, little-endian short int which has the length of the + # header. + import struct + hinfo = _header_size_info.get(version) + if hinfo is None: + raise ValueError("Invalid version {!r}".format(version)) + hlength_type, encoding = hinfo + + hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), "array header length") + header_length = struct.unpack(hlength_type, hlength_str)[0] + header = _read_bytes(fp, header_length, "array header") + header = header.decode(encoding) + if len(header) > max_header_size: + raise ValueError( + f"Header info length ({len(header)}) is large and may not be safe " + "to load securely.\n" + "To allow loading, adjust `max_header_size` or fully trust " + "the `.npy` file using `allow_pickle=True`.\n" + "For safety against large resource use or crashes, sandboxing " + "may be necessary.") + + # The header is a pretty-printed string representation of a literal + # Python dictionary with trailing newlines padded to a ARRAY_ALIGN byte + # boundary. The keys are strings. + # "shape" : tuple of int + # "fortran_order" : bool + # "descr" : dtype.descr + # Versions (2, 0) and (1, 0) could have been created by a Python 2 + # implementation before header filtering was implemented. + # + # For performance reasons, we try without _filter_header first though + try: + d = safe_eval(header) + except SyntaxError as e: + if version <= (2, 0): + header = _filter_header(header) + try: + d = safe_eval(header) + except SyntaxError as e2: + msg = "Cannot parse header: {!r}" + raise ValueError(msg.format(header)) from e2 + else: + warnings.warn( + "Reading `.npy` or `.npz` file required additional " + "header parsing as it was created on Python 2. Save the " + "file again to speed up loading and avoid this warning.", + UserWarning, stacklevel=4) + else: + msg = "Cannot parse header: {!r}" + raise ValueError(msg.format(header)) from e + if not isinstance(d, dict): + msg = "Header is not a dictionary: {!r}" + raise ValueError(msg.format(d)) + + if EXPECTED_KEYS != d.keys(): + keys = sorted(d.keys()) + msg = "Header does not contain the correct keys: {!r}" + raise ValueError(msg.format(keys)) + + # Sanity-check the values. + if (not isinstance(d['shape'], tuple) or + not all(isinstance(x, int) for x in d['shape'])): + msg = "shape is not valid: {!r}" + raise ValueError(msg.format(d['shape'])) + if not isinstance(d['fortran_order'], bool): + msg = "fortran_order is not a valid bool: {!r}" + raise ValueError(msg.format(d['fortran_order'])) + try: + dtype = descr_to_dtype(d['descr']) + except TypeError as e: + msg = "descr is not a valid dtype descriptor: {!r}" + raise ValueError(msg.format(d['descr'])) from e + + return d['shape'], d['fortran_order'], dtype + +def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): + """ + Write an array to an NPY file, including a header. + + If the array is neither C-contiguous nor Fortran-contiguous AND the + file_like object is not a real file object, this function will have to + copy data in memory. + + Parameters + ---------- + fp : file_like object + An open, writable file object, or similar object with a + ``.write()`` method. + array : ndarray + The array to write to disk. + version : (int, int) or None, optional + The version number of the format. None means use the oldest + supported version that is able to store the data. Default: None + allow_pickle : bool, optional + Whether to allow writing pickled data. Default: True + pickle_kwargs : dict, optional + Additional keyword arguments to pass to pickle.dump, excluding + 'protocol'. These are only useful when pickling objects in object + arrays on Python 3 to Python 2 compatible format. + + Raises + ------ + ValueError + If the array cannot be persisted. This includes the case of + allow_pickle=False and array being an object array. + Various other errors + If the array contains Python objects as part of its dtype, the + process of pickling them may raise various errors if the objects + are not picklable. + + """ + _check_version(version) + _write_array_header(fp, header_data_from_array_1_0(array), version) + + if array.itemsize == 0: + buffersize = 0 + else: + # Set buffer size to 16 MiB to hide the Python loop overhead. + buffersize = max(16 * 1024 ** 2 // array.itemsize, 1) + + if array.dtype.hasobject: + # We contain Python objects so we cannot write out the data + # directly. Instead, we will pickle it out + if not allow_pickle: + raise ValueError("Object arrays cannot be saved when " + "allow_pickle=False") + if pickle_kwargs is None: + pickle_kwargs = {} + pickle.dump(array, fp, protocol=3, **pickle_kwargs) + elif array.flags.f_contiguous and not array.flags.c_contiguous: + if isfileobj(fp): + array.T.tofile(fp) + else: + for chunk in numpy.nditer( + array, flags=['external_loop', 'buffered', 'zerosize_ok'], + buffersize=buffersize, order='F'): + fp.write(chunk.tobytes('C')) + else: + if isfileobj(fp): + array.tofile(fp) + else: + for chunk in numpy.nditer( + array, flags=['external_loop', 'buffered', 'zerosize_ok'], + buffersize=buffersize, order='C'): + fp.write(chunk.tobytes('C')) + + +def read_array(fp, allow_pickle=False, pickle_kwargs=None, *, + max_header_size=_MAX_HEADER_SIZE): + """ + Read an array from an NPY file. + + Parameters + ---------- + fp : file_like object + If this is not a real file object, then this may take extra memory + and time. + allow_pickle : bool, optional + Whether to allow writing pickled data. Default: False + + .. versionchanged:: 1.16.3 + Made default False in response to CVE-2019-6446. + + pickle_kwargs : dict + Additional keyword arguments to pass to pickle.load. These are only + useful when loading object arrays saved on Python 2 when using + Python 3. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + This option is ignored when `allow_pickle` is passed. In that case + the file is by definition trusted and the limit is unnecessary. + + Returns + ------- + array : ndarray + The array from the data on disk. + + Raises + ------ + ValueError + If the data is invalid, or allow_pickle=False and the file contains + an object array. + + """ + if allow_pickle: + # Effectively ignore max_header_size, since `allow_pickle` indicates + # that the input is fully trusted. + max_header_size = 2**64 + + version = read_magic(fp) + _check_version(version) + shape, fortran_order, dtype = _read_array_header( + fp, version, max_header_size=max_header_size) + if len(shape) == 0: + count = 1 + else: + count = numpy.multiply.reduce(shape, dtype=numpy.int64) + + # Now read the actual data. + if dtype.hasobject: + # The array contained Python objects. We need to unpickle the data. + if not allow_pickle: + raise ValueError("Object arrays cannot be loaded when " + "allow_pickle=False") + if pickle_kwargs is None: + pickle_kwargs = {} + try: + array = pickle.load(fp, **pickle_kwargs) + except UnicodeError as err: + # Friendlier error message + raise UnicodeError("Unpickling a python object failed: %r\n" + "You may need to pass the encoding= option " + "to numpy.load" % (err,)) from err + else: + if isfileobj(fp): + # We can use the fast fromfile() function. + array = numpy.fromfile(fp, dtype=dtype, count=count) + else: + # This is not a real file. We have to read it the + # memory-intensive way. + # crc32 module fails on reads greater than 2 ** 32 bytes, + # breaking large reads from gzip streams. Chunk reads to + # BUFFER_SIZE bytes to avoid issue and reduce memory overhead + # of the read. In non-chunked case count < max_read_count, so + # only one read is performed. + + # Use np.ndarray instead of np.empty since the latter does + # not correctly instantiate zero-width string dtypes; see + # https://github.com/numpy/numpy/pull/6430 + array = numpy.ndarray(count, dtype=dtype) + + if dtype.itemsize > 0: + # If dtype.itemsize == 0 then there's nothing more to read + max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) + + for i in range(0, count, max_read_count): + read_count = min(max_read_count, count - i) + read_size = int(read_count * dtype.itemsize) + data = _read_bytes(fp, read_size, "array data") + array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, + count=read_count) + + if fortran_order: + array.shape = shape[::-1] + array = array.transpose() + else: + array.shape = shape + + return array + + +def open_memmap(filename, mode='r+', dtype=None, shape=None, + fortran_order=False, version=None, *, + max_header_size=_MAX_HEADER_SIZE): + """ + Open a .npy file as a memory-mapped array. + + This may be used to read an existing file or create a new one. + + Parameters + ---------- + filename : str or path-like + The name of the file on disk. This may *not* be a file-like + object. + mode : str, optional + The mode in which to open the file; the default is 'r+'. In + addition to the standard file modes, 'c' is also accepted to mean + "copy on write." See `memmap` for the available mode strings. + dtype : data-type, optional + The data type of the array if we are creating a new file in "write" + mode, if not, `dtype` is ignored. The default value is None, which + results in a data-type of `float64`. + shape : tuple of int + The shape of the array if we are creating a new file in "write" + mode, in which case this parameter is required. Otherwise, this + parameter is ignored and is thus optional. + fortran_order : bool, optional + Whether the array should be Fortran-contiguous (True) or + C-contiguous (False, the default) if we are creating a new file in + "write" mode. + version : tuple of int (major, minor) or None + If the mode is a "write" mode, then this is the version of the file + format used to create the file. None means use the oldest + supported version that is able to store the data. Default: None + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + + Returns + ------- + marray : memmap + The memory-mapped array. + + Raises + ------ + ValueError + If the data or the mode is invalid. + OSError + If the file is not found or cannot be opened correctly. + + See Also + -------- + numpy.memmap + + """ + if isfileobj(filename): + raise ValueError("Filename must be a string or a path-like object." + " Memmap cannot use existing file handles.") + + if 'w' in mode: + # We are creating the file, not reading it. + # Check if we ought to create the file. + _check_version(version) + # Ensure that the given dtype is an authentic dtype object rather + # than just something that can be interpreted as a dtype object. + dtype = numpy.dtype(dtype) + if dtype.hasobject: + msg = "Array can't be memory-mapped: Python objects in dtype." + raise ValueError(msg) + d = dict( + descr=dtype_to_descr(dtype), + fortran_order=fortran_order, + shape=shape, + ) + # If we got here, then it should be safe to create the file. + with open(os_fspath(filename), mode+'b') as fp: + _write_array_header(fp, d, version) + offset = fp.tell() + else: + # Read the header of the file first. + with open(os_fspath(filename), 'rb') as fp: + version = read_magic(fp) + _check_version(version) + + shape, fortran_order, dtype = _read_array_header( + fp, version, max_header_size=max_header_size) + if dtype.hasobject: + msg = "Array can't be memory-mapped: Python objects in dtype." + raise ValueError(msg) + offset = fp.tell() + + if fortran_order: + order = 'F' + else: + order = 'C' + + # We need to change a write-only mode to a read-write mode since we've + # already written data to the file. + if mode == 'w+': + mode = 'r+' + + marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order, + mode=mode, offset=offset) + + return marray + + +def _read_bytes(fp, size, error_template="ran out of data"): + """ + Read from file-like object until size bytes are read. + Raises ValueError if not EOF is encountered before size bytes are read. + Non-blocking objects only supported if they derive from io objects. + + Required as e.g. ZipExtFile in python 2.6 can return less data than + requested. + """ + data = bytes() + while True: + # io files (default in python3) return None or raise on + # would-block, python2 file will truncate, probably nothing can be + # done about that. note that regular files can't be non-blocking + try: + r = fp.read(size - len(data)) + data += r + if len(r) == 0 or len(data) == size: + break + except BlockingIOError: + pass + if len(data) != size: + msg = "EOF: reading %s, expected %d bytes got %d" + raise ValueError(msg % (error_template, size, len(data))) + else: + return data diff --git a/shared/package-files/4f/4fcb50ab8d40a3f3ca8d068a4d85ca409d3777dc0c02dafd344154b20a49a52f/lgamma_cpu_dispatch.h b/shared/package-files/4f/4fcb50ab8d40a3f3ca8d068a4d85ca409d3777dc0c02dafd344154b20a49a52f/lgamma_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9a0f37286cf8a364a7ce77c54dfd2e9dc4352b8e --- /dev/null +++ b/shared/package-files/4f/4fcb50ab8d40a3f3ca8d068a4d85ca409d3777dc0c02dafd344154b20a49a52f/lgamma_cpu_dispatch.h @@ -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 lgamma(const at::Tensor & self); +TORCH_API at::Tensor & lgamma_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & lgamma_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & lgamma_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/4f/4fcbdd032dd830e5961d93c8e01b072b2cba36d6e2d954fd6abd6c2dfa5f93b7/origin.py b/shared/package-files/4f/4fcbdd032dd830e5961d93c8e01b072b2cba36d6e2d954fd6abd6c2dfa5f93b7/origin.py new file mode 100644 index 0000000000000000000000000000000000000000..fcabf21f43fdb2d8d89fbe25d464546b0b4fb44e --- /dev/null +++ b/shared/package-files/4f/4fcbdd032dd830e5961d93c8e01b072b2cba36d6e2d954fd6abd6c2dfa5f93b7/origin.py @@ -0,0 +1,151 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# The core 'origin' tracking system. This point of this is to have machinery +# so if some object is ultimately derived from some portion of a string (e.g., +# a formula), then we can keep track of that, and use it to give proper error +# messages. + +# These are made available in the patsy.* namespace +__all__ = ["Origin"] + + +class Origin(object): + """This represents the origin of some object in some string. + + For example, if we have an object ``x1_obj`` that was produced by parsing + the ``x1`` in the formula ``"y ~ x1:x2"``, then we conventionally keep + track of that relationship by doing:: + + x1_obj.origin = Origin("y ~ x1:x2", 4, 6) + + Then later if we run into a problem, we can do:: + + raise PatsyError("invalid factor", x1_obj) + + and we'll produce a nice error message like:: + + PatsyError: invalid factor + y ~ x1:x2 + ^^ + + Origins are compared by value, and hashable. + """ + + def __init__(self, code, start, end): + self.code = code + self.start = start + self.end = end + + @classmethod + def combine(cls, origin_objs): + """Class method for combining a set of Origins into one large Origin + that spans them. + + Example usage: if we wanted to represent the origin of the "x1:x2" + term, we could do ``Origin.combine([x1_obj, x2_obj])``. + + Single argument is an iterable, and each element in the iterable + should be either: + + * An Origin object + * ``None`` + * An object that has a ``.origin`` attribute which fulfills the above + criteria. + + Returns either an Origin object, or None. + """ + origins = [] + for obj in origin_objs: + if obj is not None and not isinstance(obj, Origin): + obj = obj.origin + if obj is None: + continue + origins.append(obj) + if not origins: + return None + codes = set([o.code for o in origins]) + assert len(codes) == 1 + start = min([o.start for o in origins]) + end = max([o.end for o in origins]) + return cls(codes.pop(), start, end) + + def relevant_code(self): + """Extracts and returns the span of the original code represented by + this Origin. Example: ``x1``.""" + return self.code[self.start : self.end] + + def __eq__(self, other): + return ( + isinstance(other, Origin) + and self.code == other.code + and self.start == other.start + and self.end == other.end + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((Origin, self.code, self.start, self.end)) + + def caretize(self, indent=0): + """Produces a user-readable two line string indicating the origin of + some code. Example:: + + y ~ x1:x2 + ^^ + + If optional argument 'indent' is given, then both lines will be + indented by this much. The returned string does not have a trailing + newline. + """ + return "%s%s\n%s%s%s" % ( + " " * indent, + self.code, + " " * indent, + " " * self.start, + "^" * (self.end - self.start), + ) + + def __repr__(self): + return "%s<-%s (%s-%s)>" % ( + self.code[: self.start], + self.code[self.start : self.end], + self.code[self.end :], + self.start, + self.end, + ) + + # We reimplement patsy.util.no_pickling, to avoid circular import issues + def __getstate__(self): + raise NotImplementedError + + +def test_Origin(): + o1 = Origin("012345", 2, 4) + o2 = Origin("012345", 4, 5) + assert o1.caretize() == "012345\n ^^" + assert o2.caretize() == "012345\n ^" + o3 = Origin.combine([o1, o2]) + assert o3.code == "012345" + assert o3.start == 2 + assert o3.end == 5 + assert o3.caretize(indent=2) == " 012345\n ^^^" + assert o3 == Origin("012345", 2, 5) + + class ObjWithOrigin(object): + def __init__(self, origin=None): + self.origin = origin + + o4 = Origin.combine([ObjWithOrigin(o1), ObjWithOrigin(), None]) + assert o4 == o1 + o5 = Origin.combine([ObjWithOrigin(o1), o2]) + assert o5 == o3 + + assert Origin.combine([ObjWithOrigin(), ObjWithOrigin()]) is None + + from patsy.util import assert_no_pickling + + assert_no_pickling(Origin("", 0, 0)) diff --git a/shared/package-files/4f/4fd7f3837d429a42367e5270bf5213a3ef9ed7bea3871f4a24e09a061bc37b9b/_native_multi_head_attention_cuda_dispatch.h b/shared/package-files/4f/4fd7f3837d429a42367e5270bf5213a3ef9ed7bea3871f4a24e09a061bc37b9b/_native_multi_head_attention_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e4c28c720a8c0e349382fadc907d77d9018eab25 --- /dev/null +++ b/shared/package-files/4f/4fd7f3837d429a42367e5270bf5213a3ef9ed7bea3871f4a24e09a061bc37b9b/_native_multi_head_attention_cuda_dispatch.h @@ -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 _native_multi_head_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional & mask={}, bool need_weights=true, bool average_attn_weights=true, c10::optional mask_type=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/4f/4fd98f267d2438c05de38f64b36e9180855ca09755d0fabe848f7a2668abde94/_tkinter_finder.py b/shared/package-files/4f/4fd98f267d2438c05de38f64b36e9180855ca09755d0fabe848f7a2668abde94/_tkinter_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..03a6eba44ffe9104130c8263bfabc3bc30f736e2 --- /dev/null +++ b/shared/package-files/4f/4fd98f267d2438c05de38f64b36e9180855ca09755d0fabe848f7a2668abde94/_tkinter_finder.py @@ -0,0 +1,19 @@ +""" Find compiled module linking to Tcl / Tk libraries +""" +from __future__ import annotations + +import sys +import tkinter +from tkinter import _tkinter as tk + +try: + if hasattr(sys, "pypy_find_executable"): + TKINTER_LIB = tk.tklib_cffi.__file__ + else: + TKINTER_LIB = tk.__file__ +except AttributeError: + # _tkinter may be compiled directly into Python, in which case __file__ is + # not available. load_tkinter_funcs will check the binary first in any case. + TKINTER_LIB = None + +tk_version = str(tkinter.TkVersion) diff --git a/shared/package-files/4f/4fda90bafdcfa0602d5243a8a6a6585f7f7c2fdfe2f74c2b1e7ea86deec498de/test_pycolorize.py b/shared/package-files/4f/4fda90bafdcfa0602d5243a8a6a6585f7f7c2fdfe2f74c2b1e7ea86deec498de/test_pycolorize.py new file mode 100644 index 0000000000000000000000000000000000000000..df2acd035b0e387949d38a31c7295cd939844662 --- /dev/null +++ b/shared/package-files/4f/4fda90bafdcfa0602d5243a8a6a6585f7f7c2fdfe2f74c2b1e7ea86deec498de/test_pycolorize.py @@ -0,0 +1,70 @@ +# coding: utf-8 +"""Test suite for our color utilities. + +Authors +------- + +* Min RK +""" +#----------------------------------------------------------------------------- +# Copyright (C) 2011 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING.txt, distributed as part of this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# our own +import sys +from IPython.utils.PyColorize import Parser +import io +import pytest + + +@pytest.fixture(scope="module", params=("Linux", "NoColor", "LightBG", "Neutral")) +def style(request): + yield request.param + +#----------------------------------------------------------------------------- +# Test functions +#----------------------------------------------------------------------------- + +sample = """ +def function(arg, *args, kwarg=True, **kwargs): + ''' + this is docs + ''' + pass is True + False == None + + with io.open(ru'unicode', encoding='utf-8'): + raise ValueError("escape \r sequence") + + print("wěird ünicoðe") + +class Bar(Super): + + def __init__(self): + super(Bar, self).__init__(1**2, 3^4, 5 or 6) +""" + + +def test_parse_sample(style): + """and test writing to a buffer""" + buf = io.StringIO() + p = Parser(style=style) + p.format(sample, buf) + buf.seek(0) + f1 = buf.read() + + assert "ERROR" not in f1 + + +def test_parse_error(style): + p = Parser(style=style) + f1 = p.format(r"\ " if sys.version_info >= (3, 12) else ")", "str") + if style != "NoColor": + assert "ERROR" in f1 diff --git a/shared/package-files/4f/4fe0c7eff5b3f65dd12530f0cd14da3df414097f6dae175edc0fd8bb787dcac2/_factor_analysis.py b/shared/package-files/4f/4fe0c7eff5b3f65dd12530f0cd14da3df414097f6dae175edc0fd8bb787dcac2/_factor_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d5e72a5b7d3a3b032a1465de639f60ebc58d7f --- /dev/null +++ b/shared/package-files/4f/4fe0c7eff5b3f65dd12530f0cd14da3df414097f6dae175edc0fd8bb787dcac2/_factor_analysis.py @@ -0,0 +1,457 @@ +"""Factor Analysis. + +A latent linear variable model. + +FactorAnalysis is similar to probabilistic PCA implemented by PCA.score +While PCA assumes Gaussian noise with the same variance for each +feature, the FactorAnalysis model assumes different variances for +each of them. + +This implementation is based on David Barber's Book, +Bayesian Reasoning and Machine Learning, +http://www.cs.ucl.ac.uk/staff/d.barber/brml, +Algorithm 21.1 +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from math import log, sqrt +from numbers import Integral, Real + +import numpy as np +from scipy import linalg + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, +) +from ..exceptions import ConvergenceWarning +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions +from ..utils.extmath import _randomized_svd, fast_logdet, squared_norm +from ..utils.validation import check_is_fitted, validate_data + + +class FactorAnalysis(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + """Factor Analysis (FA). + + A simple linear generative model with Gaussian latent variables. + + The observations are assumed to be caused by a linear transformation of + lower dimensional latent factors and added Gaussian noise. + Without loss of generality the factors are distributed according to a + Gaussian with zero mean and unit covariance. The noise is also zero mean + and has an arbitrary diagonal covariance matrix. + + If we would restrict the model further, by assuming that the Gaussian + noise is even isotropic (all diagonal entries are the same) we would obtain + :class:`PCA`. + + FactorAnalysis performs a maximum likelihood estimate of the so-called + `loading` matrix, the transformation of the latent variables to the + observed ones, using SVD based approach. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.13 + + Parameters + ---------- + n_components : int, default=None + Dimensionality of latent space, the number of components + of ``X`` that are obtained after ``transform``. + If None, n_components is set to the number of features. + + tol : float, default=1e-2 + Stopping tolerance for log-likelihood increase. + + copy : bool, default=True + Whether to make a copy of X. If ``False``, the input X gets overwritten + during fitting. + + max_iter : int, default=1000 + Maximum number of iterations. + + noise_variance_init : array-like of shape (n_features,), default=None + The initial guess of the noise variance for each feature. + If None, it defaults to np.ones(n_features). + + svd_method : {'lapack', 'randomized'}, default='randomized' + Which SVD method to use. If 'lapack' use standard SVD from + scipy.linalg, if 'randomized' use fast ``randomized_svd`` function. + Defaults to 'randomized'. For most applications 'randomized' will + be sufficiently precise while providing significant speed gains. + Accuracy can also be improved by setting higher values for + `iterated_power`. If this is not sufficient, for maximum precision + you should choose 'lapack'. + + iterated_power : int, default=3 + Number of iterations for the power method. 3 by default. Only used + if ``svd_method`` equals 'randomized'. + + rotation : {'varimax', 'quartimax'}, default=None + If not None, apply the indicated rotation. Currently, varimax and + quartimax are implemented. See + `"The varimax criterion for analytic rotation in factor analysis" + `_ + H. F. Kaiser, 1958. + + .. versionadded:: 0.24 + + random_state : int or RandomState instance, default=0 + Only used when ``svd_method`` equals 'randomized'. Pass an int for + reproducible results across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + components_ : ndarray of shape (n_components, n_features) + Components with maximum variance. + + loglike_ : list of shape (n_iterations,) + The log likelihood at each iteration. + + noise_variance_ : ndarray of shape (n_features,) + The estimated noise variance for each feature. + + n_iter_ : int + Number of iterations run. + + mean_ : ndarray of shape (n_features,) + Per-feature empirical mean, estimated from the training set. + + 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 + -------- + PCA: Principal component analysis is also a latent linear variable model + which however assumes equal noise variance for each feature. + This extra assumption makes probabilistic PCA faster as it can be + computed in closed form. + FastICA: Independent component analysis, a latent variable model with + non-Gaussian latent variables. + + References + ---------- + - David Barber, Bayesian Reasoning and Machine Learning, + Algorithm 21.1. + + - Christopher M. Bishop: Pattern Recognition and Machine Learning, + Chapter 12.2.4. + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.decomposition import FactorAnalysis + >>> X, _ = load_digits(return_X_y=True) + >>> transformer = FactorAnalysis(n_components=7, random_state=0) + >>> X_transformed = transformer.fit_transform(X) + >>> X_transformed.shape + (1797, 7) + """ + + _parameter_constraints: dict = { + "n_components": [Interval(Integral, 0, None, closed="left"), None], + "tol": [Interval(Real, 0.0, None, closed="left")], + "copy": ["boolean"], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "noise_variance_init": ["array-like", None], + "svd_method": [StrOptions({"randomized", "lapack"})], + "iterated_power": [Interval(Integral, 0, None, closed="left")], + "rotation": [StrOptions({"varimax", "quartimax"}), None], + "random_state": ["random_state"], + } + + def __init__( + self, + n_components=None, + *, + tol=1e-2, + copy=True, + max_iter=1000, + noise_variance_init=None, + svd_method="randomized", + iterated_power=3, + rotation=None, + random_state=0, + ): + self.n_components = n_components + self.copy = copy + self.tol = tol + self.max_iter = max_iter + self.svd_method = svd_method + + self.noise_variance_init = noise_variance_init + self.iterated_power = iterated_power + self.random_state = random_state + self.rotation = rotation + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the FactorAnalysis model to X using SVD based approach. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : Ignored + Ignored parameter. + + Returns + ------- + self : object + FactorAnalysis class instance. + """ + X = validate_data( + self, X, copy=self.copy, dtype=np.float64, force_writeable=True + ) + + n_samples, n_features = X.shape + n_components = self.n_components + if n_components is None: + n_components = n_features + + self.mean_ = np.mean(X, axis=0) + X -= self.mean_ + + # some constant terms + nsqrt = sqrt(n_samples) + llconst = n_features * log(2.0 * np.pi) + n_components + var = np.var(X, axis=0) + + if self.noise_variance_init is None: + psi = np.ones(n_features, dtype=X.dtype) + else: + if len(self.noise_variance_init) != n_features: + raise ValueError( + "noise_variance_init dimension does not " + "with number of features : %d != %d" + % (len(self.noise_variance_init), n_features) + ) + psi = np.array(self.noise_variance_init) + + loglike = [] + old_ll = -np.inf + SMALL = 1e-12 + + # we'll modify svd outputs to return unexplained variance + # to allow for unified computation of loglikelihood + if self.svd_method == "lapack": + + def my_svd(X): + _, s, Vt = linalg.svd(X, full_matrices=False, check_finite=False) + return ( + s[:n_components], + Vt[:n_components], + squared_norm(s[n_components:]), + ) + + else: # svd_method == "randomized" + random_state = check_random_state(self.random_state) + + def my_svd(X): + _, s, Vt = _randomized_svd( + X, + n_components, + random_state=random_state, + n_iter=self.iterated_power, + ) + return s, Vt, squared_norm(X) - squared_norm(s) + + for i in range(self.max_iter): + # SMALL helps numerics + sqrt_psi = np.sqrt(psi) + SMALL + s, Vt, unexp_var = my_svd(X / (sqrt_psi * nsqrt)) + s **= 2 + # Use 'maximum' here to avoid sqrt problems. + W = np.sqrt(np.maximum(s - 1.0, 0.0))[:, np.newaxis] * Vt + del Vt + W *= sqrt_psi + + # loglikelihood + ll = llconst + np.sum(np.log(s)) + ll += unexp_var + np.sum(np.log(psi)) + ll *= -n_samples / 2.0 + loglike.append(ll) + if (ll - old_ll) < self.tol: + break + old_ll = ll + + psi = np.maximum(var - np.sum(W**2, axis=0), SMALL) + else: + warnings.warn( + "FactorAnalysis did not converge." + " You might want" + " to increase the number of iterations.", + ConvergenceWarning, + ) + + self.components_ = W + if self.rotation is not None: + self.components_ = self._rotate(W) + self.noise_variance_ = psi + self.loglike_ = loglike + self.n_iter_ = i + 1 + return self + + def transform(self, X): + """Apply dimensionality reduction to X using the model. + + Compute the expected mean of the latent variables. + See Barber, 21.2.33 (or Bishop, 12.66). + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_components) + The latent variables of X. + """ + check_is_fitted(self) + + X = validate_data(self, X, reset=False) + Ih = np.eye(len(self.components_)) + + X_transformed = X - self.mean_ + + Wpsi = self.components_ / self.noise_variance_ + cov_z = linalg.inv(Ih + np.dot(Wpsi, self.components_.T)) + tmp = np.dot(X_transformed, Wpsi.T) + X_transformed = np.dot(tmp, cov_z) + + return X_transformed + + def get_covariance(self): + """Compute data covariance with the FactorAnalysis model. + + ``cov = components_.T * components_ + diag(noise_variance)`` + + Returns + ------- + cov : ndarray of shape (n_features, n_features) + Estimated covariance of data. + """ + check_is_fitted(self) + + cov = np.dot(self.components_.T, self.components_) + cov.flat[:: len(cov) + 1] += self.noise_variance_ # modify diag inplace + return cov + + def get_precision(self): + """Compute data precision matrix with the FactorAnalysis model. + + Returns + ------- + precision : ndarray of shape (n_features, n_features) + Estimated precision of data. + """ + check_is_fitted(self) + + n_features = self.components_.shape[1] + + # handle corner cases first + if self.n_components == 0: + return np.diag(1.0 / self.noise_variance_) + if self.n_components == n_features: + return linalg.inv(self.get_covariance()) + + # Get precision using matrix inversion lemma + components_ = self.components_ + precision = np.dot(components_ / self.noise_variance_, components_.T) + precision.flat[:: len(precision) + 1] += 1.0 + precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_)) + precision /= self.noise_variance_[:, np.newaxis] + precision /= -self.noise_variance_[np.newaxis, :] + precision.flat[:: len(precision) + 1] += 1.0 / self.noise_variance_ + return precision + + def score_samples(self, X): + """Compute the log-likelihood of each sample. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The data. + + Returns + ------- + ll : ndarray of shape (n_samples,) + Log-likelihood of each sample under the current model. + """ + check_is_fitted(self) + X = validate_data(self, X, reset=False) + Xr = X - self.mean_ + precision = self.get_precision() + n_features = X.shape[1] + log_like = -0.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1) + log_like -= 0.5 * (n_features * log(2.0 * np.pi) - fast_logdet(precision)) + return log_like + + def score(self, X, y=None): + """Compute the average log-likelihood of the samples. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The data. + + y : Ignored + Ignored parameter. + + Returns + ------- + ll : float + Average log-likelihood of the samples under the current model. + """ + return np.mean(self.score_samples(X)) + + def _rotate(self, components, n_components=None, tol=1e-6): + "Rotate the factor analysis solution." + # note that tol is not exposed + return _ortho_rotation(components.T, method=self.rotation, tol=tol)[ + : self.n_components + ] + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] + + +def _ortho_rotation(components, method="varimax", tol=1e-6, max_iter=100): + """Return rotated components.""" + nrow, ncol = components.shape + rotation_matrix = np.eye(ncol) + var = 0 + + for _ in range(max_iter): + comp_rot = np.dot(components, rotation_matrix) + if method == "varimax": + tmp = comp_rot * np.transpose((comp_rot**2).sum(axis=0) / nrow) + elif method == "quartimax": + tmp = 0 + u, s, v = np.linalg.svd(np.dot(components.T, comp_rot**3 - tmp)) + rotation_matrix = np.dot(u, v) + var_new = np.sum(s) + if var != 0 and var_new < var * (1 + tol): + break + var = var_new + + return np.dot(components, rotation_matrix).T diff --git a/shared/package-files/4f/4fe29187dab3c0e2f7bac97fe82972dc5565bdabb31a11a779d7c01b5841432f/test_math.py b/shared/package-files/4f/4fe29187dab3c0e2f7bac97fe82972dc5565bdabb31a11a779d7c01b5841432f/test_math.py new file mode 100644 index 0000000000000000000000000000000000000000..028a402ff05ea36698c6eea654655e3e8f727b51 --- /dev/null +++ b/shared/package-files/4f/4fe29187dab3c0e2f7bac97fe82972dc5565bdabb31a11a779d7c01b5841432f/test_math.py @@ -0,0 +1,786 @@ +import numpy as np +from numba.cuda.testing import (skip_unless_cc_53, + unittest, + CUDATestCase, + skip_on_cudasim) +from numba.np import numpy_support +from numba import cuda, float32, float64, int32, vectorize, void, int64 +import math + + +def math_acos(A, B): + i = cuda.grid(1) + B[i] = math.acos(A[i]) + + +def math_asin(A, B): + i = cuda.grid(1) + B[i] = math.asin(A[i]) + + +def math_atan(A, B): + i = cuda.grid(1) + B[i] = math.atan(A[i]) + + +def math_acosh(A, B): + i = cuda.grid(1) + B[i] = math.acosh(A[i]) + + +def math_asinh(A, B): + i = cuda.grid(1) + B[i] = math.asinh(A[i]) + + +def math_atanh(A, B): + i = cuda.grid(1) + B[i] = math.atanh(A[i]) + + +def math_cos(A, B): + i = cuda.grid(1) + B[i] = math.cos(A[i]) + + +def math_sin(A, B): + i = cuda.grid(1) + B[i] = math.sin(A[i]) + + +def math_tan(A, B): + i = cuda.grid(1) + B[i] = math.tan(A[i]) + + +def math_cosh(A, B): + i = cuda.grid(1) + B[i] = math.cosh(A[i]) + + +def math_sinh(A, B): + i = cuda.grid(1) + B[i] = math.sinh(A[i]) + + +def math_tanh(A, B): + i = cuda.grid(1) + B[i] = math.tanh(A[i]) + + +def math_atan2(A, B, C): + i = cuda.grid(1) + C[i] = math.atan2(A[i], B[i]) + + +def math_exp(A, B): + i = cuda.grid(1) + B[i] = math.exp(A[i]) + + +def math_erf(A, B): + i = cuda.grid(1) + B[i] = math.erf(A[i]) + + +def math_erfc(A, B): + i = cuda.grid(1) + B[i] = math.erfc(A[i]) + + +def math_expm1(A, B): + i = cuda.grid(1) + B[i] = math.expm1(A[i]) + + +def math_fabs(A, B): + i = cuda.grid(1) + B[i] = math.fabs(A[i]) + + +def math_gamma(A, B): + i = cuda.grid(1) + B[i] = math.gamma(A[i]) + + +def math_lgamma(A, B): + i = cuda.grid(1) + B[i] = math.lgamma(A[i]) + + +def math_log(A, B): + i = cuda.grid(1) + B[i] = math.log(A[i]) + + +def math_log2(A, B): + i = cuda.grid(1) + B[i] = math.log2(A[i]) + + +def math_log10(A, B): + i = cuda.grid(1) + B[i] = math.log10(A[i]) + + +def math_log1p(A, B): + i = cuda.grid(1) + B[i] = math.log1p(A[i]) + + +def math_remainder(A, B, C): + i = cuda.grid(1) + C[i] = math.remainder(A[i], B[i]) + + +def math_sqrt(A, B): + i = cuda.grid(1) + B[i] = math.sqrt(A[i]) + + +def math_hypot(A, B, C): + i = cuda.grid(1) + C[i] = math.hypot(A[i], B[i]) + + +def math_pow(A, B, C): + i = cuda.grid(1) + C[i] = math.pow(A[i], B[i]) + + +def math_ceil(A, B): + i = cuda.grid(1) + B[i] = math.ceil(A[i]) + + +def math_floor(A, B): + i = cuda.grid(1) + B[i] = math.floor(A[i]) + + +def math_copysign(A, B, C): + i = cuda.grid(1) + C[i] = math.copysign(A[i], B[i]) + + +def math_fmod(A, B, C): + i = cuda.grid(1) + C[i] = math.fmod(A[i], B[i]) + + +def math_modf(A, B, C): + i = cuda.grid(1) + B[i], C[i] = math.modf(A[i]) + + +def math_isnan(A, B): + i = cuda.grid(1) + B[i] = math.isnan(A[i]) + + +def math_isinf(A, B): + i = cuda.grid(1) + B[i] = math.isinf(A[i]) + + +def math_isfinite(A, B): + i = cuda.grid(1) + B[i] = math.isfinite(A[i]) + + +def math_degrees(A, B): + i = cuda.grid(1) + B[i] = math.degrees(A[i]) + + +def math_radians(A, B): + i = cuda.grid(1) + B[i] = math.radians(A[i]) + + +def math_trunc(A, B): + i = cuda.grid(1) + B[i] = math.trunc(A[i]) + + +def math_pow_binop(A, B, C): + i = cuda.grid(1) + C[i] = A[i] ** B[i] + + +def math_mod_binop(A, B, C): + i = cuda.grid(1) + C[i] = A[i] % B[i] + + +class TestCudaMath(CUDATestCase): + def unary_template_float16(self, func, npfunc, start=0, stop=1): + self.unary_template(func, npfunc, np.float16, np.float16, start, stop) + + def unary_template_float32(self, func, npfunc, start=0, stop=1): + self.unary_template(func, npfunc, np.float32, np.float32, start, stop) + + def unary_template_float64(self, func, npfunc, start=0, stop=1): + self.unary_template(func, npfunc, np.float64, np.float64, start, stop) + + def unary_template_int64(self, func, npfunc, start=0, stop=50): + self.unary_template(func, npfunc, np.int64, np.float64, start, stop) + + def unary_template_uint64(self, func, npfunc, start=0, stop=50): + self.unary_template(func, npfunc, np.uint64, np.float64, start, stop) + + def unary_template(self, func, npfunc, npdtype, nprestype, start, stop): + nelem = 50 + A = np.linspace(start, stop, nelem).astype(npdtype) + B = np.empty_like(A).astype(nprestype) + arytype = numpy_support.from_dtype(npdtype)[::1] + restype = numpy_support.from_dtype(nprestype)[::1] + cfunc = cuda.jit((arytype, restype))(func) + cfunc[1, nelem](A, B) + + # When this test was originally written it used + # assertTrue(np.allclose(...), which has different default tolerance + # values to assert_allclose. The tolerance values here are chosen as + # the tightest under which the tests will pass. + if npdtype == np.float64: + rtol = 1e-13 + elif npdtype == np.float32: + rtol = 1e-6 + else: + rtol = 1e-3 + np.testing.assert_allclose(npfunc(A), B, rtol=rtol) + + def unary_bool_special_values(self, func, npfunc, npdtype, npmtype): + fi = np.finfo(npdtype) + denorm = fi.tiny / 4 + A = np.array([0., denorm, fi.tiny, 0.5, 1., fi.max, np.inf, np.nan], + dtype=npdtype) + B = np.empty_like(A, dtype=np.int32) + cfunc = cuda.jit((npmtype[::1], int32[::1]))(func) + + cfunc[1, A.size](A, B) + np.testing.assert_array_equal(B, npfunc(A)) + + cfunc[1, A.size](-A, B) + np.testing.assert_array_equal(B, npfunc(-A)) + + def unary_bool_special_values_float32(self, func, npfunc): + self.unary_bool_special_values(func, npfunc, np.float32, float32) + + def unary_bool_special_values_float64(self, func, npfunc): + self.unary_bool_special_values(func, npfunc, np.float64, float64) + + def unary_bool_template_float32(self, func, npfunc, start=0, stop=1): + self.unary_template(func, npfunc, np.float32, np.float32, start, stop) + + def unary_bool_template_float64(self, func, npfunc, start=0, stop=1): + self.unary_template(func, npfunc, np.float64, np.float64, start, stop) + + def unary_bool_template_int32(self, func, npfunc, start=0, stop=49): + self.unary_template(func, npfunc, np.int32, np.int32, start, stop) + + def unary_bool_template_int64(self, func, npfunc, start=0, stop=49): + self.unary_template(func, npfunc, np.int64, np.int64, start, stop) + + def unary_bool_template(self, func, npfunc, npdtype, npmtype, start, stop): + nelem = 50 + A = np.linspace(start, stop, nelem).astype(npdtype) + B = np.empty(A.shape, dtype=np.int32) + iarytype = npmtype[::1] + oarytype = int32[::1] + cfunc = cuda.jit((iarytype, oarytype))(func) + cfunc[1, nelem](A, B) + np.testing.assert_allclose(npfunc(A), B) + + def binary_template_float32(self, func, npfunc, start=0, stop=1): + self.binary_template(func, npfunc, np.float32, np.float32, start, stop) + + def binary_template_float64(self, func, npfunc, start=0, stop=1): + self.binary_template(func, npfunc, np.float64, np.float64, start, stop) + + def binary_template_int64(self, func, npfunc, start=0, stop=50): + self.binary_template(func, npfunc, np.int64, np.float64, start, stop) + + def binary_template_uint64(self, func, npfunc, start=0, stop=50): + self.binary_template(func, npfunc, np.uint64, np.float64, start, stop) + + def binary_template(self, func, npfunc, npdtype, nprestype, start, stop): + nelem = 50 + A = np.linspace(start, stop, nelem).astype(npdtype) + B = np.empty_like(A).astype(nprestype) + arytype = numpy_support.from_dtype(npdtype)[::1] + restype = numpy_support.from_dtype(nprestype)[::1] + cfunc = cuda.jit((arytype, arytype, restype))(func) + cfunc[1, nelem](A, A, B) + np.testing.assert_allclose(npfunc(A, A), B) + + #--------------------------------------------------------------------------- + # test_math_acos + + def test_math_acos(self): + self.unary_template_float32(math_acos, np.arccos) + self.unary_template_float64(math_acos, np.arccos) + # For integers we can only test with zero, since <=-1 and >=1 result in + # invalid values. + self.unary_template_int64(math_acos, np.arccos, start=0, stop=0) + self.unary_template_uint64(math_acos, np.arccos, start=0, stop=0) + + #--------------------------------------------------------------------------- + # test_math_asin + + def test_math_asin(self): + self.unary_template_float32(math_asin, np.arcsin) + self.unary_template_float64(math_asin, np.arcsin) + # For integers we can only test with zero, since <=-1 and >=1 result in + # invalid values. + self.unary_template_int64(math_asin, np.arcsin, start=0, stop=0) + self.unary_template_uint64(math_asin, np.arcsin, start=0, stop=0) + + #--------------------------------------------------------------------------- + # test_math_atan + + def test_math_atan(self): + self.unary_template_float32(math_atan, np.arctan) + self.unary_template_float64(math_atan, np.arctan) + self.unary_template_int64(math_atan, np.arctan) + self.unary_template_uint64(math_atan, np.arctan) + + #--------------------------------------------------------------------------- + # test_math_acosh + + def test_math_acosh(self): + self.unary_template_float32(math_acosh, np.arccosh, start=1, stop=2) + self.unary_template_float64(math_acosh, np.arccosh, start=1, stop=2) + self.unary_template_int64(math_acosh, np.arccosh, start=1, stop=2) + self.unary_template_uint64(math_acosh, np.arccosh, start=1, stop=2) + + #--------------------------------------------------------------------------- + # test_math_asinh + + def test_math_asinh(self): + self.unary_template_float32(math_asinh, np.arcsinh) + self.unary_template_float64(math_asinh, np.arcsinh) + self.unary_template_int64(math_asinh, np.arcsinh) + self.unary_template_uint64(math_asinh, np.arcsinh) + + #--------------------------------------------------------------------------- + # test_math_atanh + + def test_math_atanh(self): + self.unary_template_float32(math_atanh, np.arctanh, start=0, stop=.9) + self.unary_template_float64(math_atanh, np.arctanh, start=0, stop=.9) + self.unary_template_int64(math_atanh, np.arctanh, start=0, stop=.9) + self.unary_template_uint64(math_atanh, np.arctanh, start=0, stop=.9) + + #--------------------------------------------------------------------------- + # test_math_cos + + def test_math_cos(self): + self.unary_template_float32(math_cos, np.cos) + self.unary_template_float64(math_cos, np.cos) + self.unary_template_int64(math_cos, np.cos) + self.unary_template_uint64(math_cos, np.cos) + + @skip_unless_cc_53 + def test_math_fp16(self): + self.unary_template_float16(math_sin, np.sin) + self.unary_template_float16(math_cos, np.cos) + self.unary_template_float16(math_exp, np.exp) + self.unary_template_float16(math_log, np.log, start=1) + self.unary_template_float16(math_log2, np.log2, start=1) + self.unary_template_float16(math_log10, np.log10, start=1) + self.unary_template_float16(math_fabs, np.fabs, start=-1) + self.unary_template_float16(math_sqrt, np.sqrt) + self.unary_template_float16(math_ceil, np.ceil) + self.unary_template_float16(math_floor, np.floor) + + @skip_on_cudasim("numpy does not support trunc for float16") + @skip_unless_cc_53 + def test_math_fp16_trunc(self): + self.unary_template_float16(math_trunc, np.trunc) + + #--------------------------------------------------------------------------- + # test_math_sin + + def test_math_sin(self): + self.unary_template_float32(math_sin, np.sin) + self.unary_template_float64(math_sin, np.sin) + self.unary_template_int64(math_sin, np.sin) + self.unary_template_uint64(math_sin, np.sin) + + #--------------------------------------------------------------------------- + # test_math_tan + + def test_math_tan(self): + self.unary_template_float32(math_tan, np.tan) + self.unary_template_float64(math_tan, np.tan) + self.unary_template_int64(math_tan, np.tan) + self.unary_template_uint64(math_tan, np.tan) + + #--------------------------------------------------------------------------- + # test_math_cosh + + def test_math_cosh(self): + self.unary_template_float32(math_cosh, np.cosh) + self.unary_template_float64(math_cosh, np.cosh) + self.unary_template_int64(math_cosh, np.cosh) + self.unary_template_uint64(math_cosh, np.cosh) + + #--------------------------------------------------------------------------- + # test_math_sinh + + def test_math_sinh(self): + self.unary_template_float32(math_sinh, np.sinh) + self.unary_template_float64(math_sinh, np.sinh) + self.unary_template_int64(math_sinh, np.sinh) + self.unary_template_uint64(math_sinh, np.sinh) + + #--------------------------------------------------------------------------- + # test_math_tanh + + def test_math_tanh(self): + self.unary_template_float32(math_tanh, np.tanh) + self.unary_template_float64(math_tanh, np.tanh) + self.unary_template_int64(math_tanh, np.tanh) + self.unary_template_uint64(math_tanh, np.tanh) + + #--------------------------------------------------------------------------- + # test_math_atan2 + + def test_math_atan2(self): + self.binary_template_float32(math_atan2, np.arctan2) + self.binary_template_float64(math_atan2, np.arctan2) + self.binary_template_int64(math_atan2, np.arctan2) + self.binary_template_uint64(math_atan2, np.arctan2) + + #--------------------------------------------------------------------------- + # test_math_erf + + def test_math_erf(self): + @vectorize + def ufunc(x): + return math.erf(x) + self.unary_template_float32(math_erf, ufunc) + self.unary_template_float64(math_erf, ufunc) + self.unary_template_int64(math_erf, ufunc) + self.unary_template_uint64(math_erf, ufunc) + + #--------------------------------------------------------------------------- + # test_math_erfc + + def test_math_erfc(self): + @vectorize + def ufunc(x): + return math.erfc(x) + self.unary_template_float32(math_erfc, ufunc) + self.unary_template_float64(math_erfc, ufunc) + self.unary_template_int64(math_erfc, ufunc) + self.unary_template_uint64(math_erfc, ufunc) + + #--------------------------------------------------------------------------- + # test_math_exp + + def test_math_exp(self): + self.unary_template_float32(math_exp, np.exp) + self.unary_template_float64(math_exp, np.exp) + self.unary_template_int64(math_exp, np.exp) + self.unary_template_uint64(math_exp, np.exp) + + #--------------------------------------------------------------------------- + # test_math_expm1 + + def test_math_expm1(self): + self.unary_template_float32(math_expm1, np.expm1) + self.unary_template_float64(math_expm1, np.expm1) + self.unary_template_int64(math_expm1, np.expm1) + self.unary_template_uint64(math_expm1, np.expm1) + + #--------------------------------------------------------------------------- + # test_math_fabs + + def test_math_fabs(self): + self.unary_template_float32(math_fabs, np.fabs, start=-1) + self.unary_template_float64(math_fabs, np.fabs, start=-1) + self.unary_template_int64(math_fabs, np.fabs, start=-1) + self.unary_template_uint64(math_fabs, np.fabs, start=-1) + + #--------------------------------------------------------------------------- + # test_math_gamma + + def test_math_gamma(self): + @vectorize + def ufunc(x): + return math.gamma(x) + self.unary_template_float32(math_gamma, ufunc, start=0.1) + self.unary_template_float64(math_gamma, ufunc, start=0.1) + self.unary_template_int64(math_gamma, ufunc, start=1) + self.unary_template_uint64(math_gamma, ufunc, start=1) + + #--------------------------------------------------------------------------- + # test_math_lgamma + + def test_math_lgamma(self): + @vectorize + def ufunc(x): + return math.lgamma(x) + self.unary_template_float32(math_lgamma, ufunc, start=0.1) + self.unary_template_float64(math_lgamma, ufunc, start=0.1) + self.unary_template_int64(math_lgamma, ufunc, start=1) + self.unary_template_uint64(math_lgamma, ufunc, start=1) + + #--------------------------------------------------------------------------- + # test_math_log + + def test_math_log(self): + self.unary_template_float32(math_log, np.log, start=1) + self.unary_template_float64(math_log, np.log, start=1) + self.unary_template_int64(math_log, np.log, start=1) + self.unary_template_uint64(math_log, np.log, start=1) + + #--------------------------------------------------------------------------- + # test_math_log2 + + def test_math_log2(self): + self.unary_template_float32(math_log2, np.log2, start=1) + self.unary_template_float64(math_log2, np.log2, start=1) + self.unary_template_int64(math_log2, np.log2, start=1) + self.unary_template_uint64(math_log2, np.log2, start=1) + + #--------------------------------------------------------------------------- + # test_math_log10 + + def test_math_log10(self): + self.unary_template_float32(math_log10, np.log10, start=1) + self.unary_template_float64(math_log10, np.log10, start=1) + self.unary_template_int64(math_log10, np.log10, start=1) + self.unary_template_uint64(math_log10, np.log10, start=1) + + #--------------------------------------------------------------------------- + # test_math_log1p + + def test_math_log1p(self): + self.unary_template_float32(math_log1p, np.log1p) + self.unary_template_float64(math_log1p, np.log1p) + self.unary_template_int64(math_log1p, np.log1p) + self.unary_template_uint64(math_log1p, np.log1p) + + #--------------------------------------------------------------------------- + # test_math_remainder + + def test_math_remainder(self): + self.binary_template_float32(math_remainder, np.remainder, start=1e-11) + self.binary_template_float64(math_remainder, np.remainder, start=1e-11) + self.binary_template_int64(math_remainder, np.remainder, start=1) + self.binary_template_uint64(math_remainder, np.remainder, start=1) + + @skip_on_cudasim('math.remainder(0, 0) raises a ValueError on CUDASim') + def test_math_remainder_0_0(self): + @cuda.jit(void(float64[::1], int64, int64)) + def test_0_0(r, x, y): + r[0] = math.remainder(x, y) + r = np.zeros(1, np.float64) + test_0_0[1, 1](r, 0, 0) + self.assertTrue(np.isnan(r[0])) + + #--------------------------------------------------------------------------- + # test_math_sqrt + + def test_math_sqrt(self): + self.unary_template_float32(math_sqrt, np.sqrt) + self.unary_template_float64(math_sqrt, np.sqrt) + self.unary_template_int64(math_sqrt, np.sqrt) + self.unary_template_uint64(math_sqrt, np.sqrt) + + #--------------------------------------------------------------------------- + # test_math_hypot + + def test_math_hypot(self): + self.binary_template_float32(math_hypot, np.hypot) + self.binary_template_float64(math_hypot, np.hypot) + self.binary_template_int64(math_hypot, np.hypot) + self.binary_template_uint64(math_hypot, np.hypot) + + #--------------------------------------------------------------------------- + # test_math_pow + + def pow_template_int32(self, npdtype): + nelem = 50 + A = np.linspace(0, 25, nelem).astype(npdtype) + B = np.arange(nelem, dtype=np.int32) + C = np.empty_like(A) + arytype = numpy_support.from_dtype(npdtype)[::1] + cfunc = cuda.jit((arytype, int32[::1], arytype))(math_pow) + cfunc[1, nelem](A, B, C) + + # NumPy casting rules result in a float64 output always, which doesn't + # match the overflow to inf of math.pow and libdevice.powi for large + # values of float32, so we compute the reference result with math.pow. + Cref = np.empty_like(A) + for i in range(len(A)): + Cref[i] = math.pow(A[i], B[i]) + np.testing.assert_allclose(np.power(A, B).astype(npdtype), C, rtol=1e-6) + + def test_math_pow(self): + self.binary_template_float32(math_pow, np.power) + self.binary_template_float64(math_pow, np.power) + self.pow_template_int32(np.float32) + self.pow_template_int32(np.float64) + + #--------------------------------------------------------------------------- + # test_math_pow_binop + + def test_math_pow_binop(self): + self.binary_template_float32(math_pow_binop, np.power) + self.binary_template_float64(math_pow_binop, np.power) + + #--------------------------------------------------------------------------- + # test_math_ceil + + def test_math_ceil(self): + self.unary_template_float32(math_ceil, np.ceil) + self.unary_template_float64(math_ceil, np.ceil) + self.unary_template_int64(math_ceil, np.ceil) + self.unary_template_uint64(math_ceil, np.ceil) + + #--------------------------------------------------------------------------- + # test_math_floor + + def test_math_floor(self): + self.unary_template_float32(math_floor, np.floor) + self.unary_template_float64(math_floor, np.floor) + self.unary_template_int64(math_floor, np.floor) + self.unary_template_uint64(math_floor, np.floor) + + #--------------------------------------------------------------------------- + # test_math_trunc + # + # Note that math.trunc() is only supported on NumPy float64s, and not + # other float types or int types. See NumPy Issue #13375: + # + # - https://github.com/numpy/numpy/issues/13375 - "Add methods from the + # builtin float types to the numpy floating point types" + + def test_math_trunc(self): + self.unary_template_float64(math_trunc, np.trunc) + + @skip_on_cudasim('trunc only supported on NumPy float64') + def test_math_trunc_non_float64(self): + self.unary_template_float32(math_trunc, np.trunc) + self.unary_template_int64(math_trunc, np.trunc) + self.unary_template_uint64(math_trunc, np.trunc) + + #--------------------------------------------------------------------------- + # test_math_copysign + + def test_math_copysign(self): + self.binary_template_float32(math_copysign, np.copysign, start=-1) + self.binary_template_float64(math_copysign, np.copysign, start=-1) + + #--------------------------------------------------------------------------- + # test_math_modf + + def test_math_modf(self): + def modf_template_nan(dtype, arytype): + A = np.array([np.nan], dtype=dtype) + B = np.zeros_like(A) + C = np.zeros_like(A) + cfunc = cuda.jit((arytype, arytype, arytype))(math_modf) + cfunc[1, len(A)](A, B, C) + self.assertTrue(np.isnan(B)) + self.assertTrue(np.isnan(C)) + + def modf_template_compare(A, dtype, arytype): + A = A.astype(dtype) + B = np.zeros_like(A) + C = np.zeros_like(A) + cfunc = cuda.jit((arytype, arytype, arytype))(math_modf) + cfunc[1, len(A)](A, B, C) + D, E = np.modf(A) + self.assertTrue(np.array_equal(B,D)) + self.assertTrue(np.array_equal(C,E)) + + nelem = 50 + #32 bit float + with self.subTest("float32 modf on simple float"): + modf_template_compare(np.linspace(0, 10, nelem), dtype=np.float32, + arytype=float32[:]) + with self.subTest("float32 modf on +- infinity"): + modf_template_compare(np.array([np.inf, -np.inf]), dtype=np.float32, + arytype=float32[:]) + with self.subTest("float32 modf on nan"): + modf_template_nan(dtype=np.float32, arytype=float32[:]) + + #64 bit float + with self.subTest("float64 modf on simple float"): + modf_template_compare(np.linspace(0, 10, nelem), dtype=np.float64, + arytype=float64[:]) + with self.subTest("float64 modf on +- infinity"): + modf_template_compare(np.array([np.inf, -np.inf]), dtype=np.float64, + arytype=float64[:]) + with self.subTest("float64 modf on nan"): + modf_template_nan(dtype=np.float64, arytype=float64[:]) + + #--------------------------------------------------------------------------- + # test_math_fmod + + def test_math_fmod(self): + self.binary_template_float32(math_fmod, np.fmod, start=1) + self.binary_template_float64(math_fmod, np.fmod, start=1) + + #--------------------------------------------------------------------------- + # test_math_mod_binop + + def test_math_mod_binop(self): + self.binary_template_float32(math_mod_binop, np.fmod, start=1) + self.binary_template_float64(math_mod_binop, np.fmod, start=1) + + #--------------------------------------------------------------------------- + # test_math_isnan + + def test_math_isnan(self): + self.unary_bool_template_float32(math_isnan, np.isnan) + self.unary_bool_template_float64(math_isnan, np.isnan) + self.unary_bool_template_int32(math_isnan, np.isnan) + self.unary_bool_template_int64(math_isnan, np.isnan) + self.unary_bool_special_values_float32(math_isnan, np.isnan) + self.unary_bool_special_values_float64(math_isnan, np.isnan) + + #--------------------------------------------------------------------------- + # test_math_isinf + + def test_math_isinf(self): + self.unary_bool_template_float32(math_isinf, np.isinf) + self.unary_bool_template_float64(math_isinf, np.isinf) + self.unary_bool_template_int32(math_isinf, np.isinf) + self.unary_bool_template_int64(math_isinf, np.isinf) + self.unary_bool_special_values_float32(math_isinf, np.isinf) + self.unary_bool_special_values_float64(math_isinf, np.isinf) + + #--------------------------------------------------------------------------- + # test_math_isfinite + + def test_math_isfinite(self): + self.unary_bool_template_float32(math_isfinite, np.isfinite) + self.unary_bool_template_float64(math_isfinite, np.isfinite) + self.unary_bool_template_int32(math_isfinite, np.isfinite) + self.unary_bool_template_int64(math_isfinite, np.isfinite) + self.unary_bool_special_values_float32(math_isfinite, np.isfinite) + self.unary_bool_special_values_float64(math_isfinite, np.isfinite) + + #--------------------------------------------------------------------------- + # test_math_degrees + + def test_math_degrees(self): + self.unary_bool_template_float32(math_degrees, np.degrees) + self.unary_bool_template_float64(math_degrees, np.degrees) + + #--------------------------------------------------------------------------- + # test_math_radians + + def test_math_radians(self): + self.unary_bool_template_float32(math_radians, np.radians) + self.unary_bool_template_float64(math_radians, np.radians) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/a80 b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/a80 new file mode 100644 index 0000000000000000000000000000000000000000..1265d5eddbf8c0390c3e954a7e2d7f4d57d86da8 Binary files /dev/null and b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/a80 differ diff --git a/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/ampex80 b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/ampex80 new file mode 100644 index 0000000000000000000000000000000000000000..1265d5eddbf8c0390c3e954a7e2d7f4d57d86da8 Binary files /dev/null and b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/ampex80 differ diff --git a/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/d80 b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/d80 new file mode 100644 index 0000000000000000000000000000000000000000..1265d5eddbf8c0390c3e954a7e2d7f4d57d86da8 Binary files /dev/null and b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/d80 differ diff --git a/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/dialogue b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/dialogue new file mode 100644 index 0000000000000000000000000000000000000000..1265d5eddbf8c0390c3e954a7e2d7f4d57d86da8 Binary files /dev/null and b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/dialogue differ diff --git a/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/dialogue80 b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/dialogue80 new file mode 100644 index 0000000000000000000000000000000000000000..1265d5eddbf8c0390c3e954a7e2d7f4d57d86da8 Binary files /dev/null and b/shared/package-files/4f/4fe771d2d82d8e563928a7a79313a97b50f64c8dfc37c1b38db11ca63dedd2fb/dialogue80 differ diff --git a/shared/package-files/4f/4fee3a03afdb3231dcde2ce8f73ae68c8759ec44127b001b1004350052b501f3/test_profiler.py b/shared/package-files/4f/4fee3a03afdb3231dcde2ce8f73ae68c8759ec44127b001b1004350052b501f3/test_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..727abb2775c76415e7e8df04b50b0e0c83511d60 --- /dev/null +++ b/shared/package-files/4f/4fee3a03afdb3231dcde2ce8f73ae68c8759ec44127b001b1004350052b501f3/test_profiler.py @@ -0,0 +1,142 @@ +import cProfile as profiler +import os +import pstats +import subprocess +import sys + +import numpy as np + +from numba import jit, types +from numba.tests.support import needs_blas +import unittest + + +def generate_standard_dot_case(): + + @jit((types.float32[::1], types.float32[::1],)) + def dot(a, b): + sum = 0 + for i in range(len(a)): + sum += a[i]*b[i] + return sum + + dot._enable_sysmon = True + return dot, dot + + +def generate_raising_dot_case(): + + @jit((types.float32[::1], types.float32[::1],)) + def raising_dot(a, b): + # this is like dot above, it does all the work, but the raises + sum = 0 + for i in range(len(a)): + sum += a[i]*b[i] + raise ValueError("problem with dot") + + raising_dot._enable_sysmon = True + + def call_raising_dot(a, b): + try: + raising_dot(a, b) + except ValueError: + pass + + return raising_dot, call_raising_dot + + +def np_dot(a, b): + return np.dot(a, b) + + +class TestProfiler(unittest.TestCase): + + def check_profiler_dot(self, caller, cfunc): + """ + Make sure the jit-compiled function shows up in the profile stats + as a regular Python function. + """ + a = np.arange(16, dtype=np.float32) + b = np.arange(16, dtype=np.float32) + n_calls = 123 + p = profiler.Profile() + p.enable() + try: + for _ in range(n_calls): + caller(a, b) + finally: + p.disable() + stats = pstats.Stats(p).strip_dirs() + + def check_stats_for_key(stats, code, n_calls): + expected_key = (os.path.basename(code.co_filename), + code.co_firstlineno, + code.co_name, + ) + # check the key is in the stats + self.assertIn(expected_key, stats.stats) + # check that call for the key has been made `n_calls` times. + func_stats = stats.stats[expected_key] + self.assertEqual(func_stats[:2], (n_calls, n_calls)) + + # check the JIT compiled function + check_stats_for_key(stats, cfunc.py_func.__code__, n_calls) + + # check the caller if it's not the same as the cfunc + if caller is not cfunc: + check_stats_for_key(stats, caller.__code__, n_calls) + + def test_profiler(self): + dot, _ = generate_standard_dot_case() + self.check_profiler_dot(dot, dot) + + def test_profiler_for_raising_function(self): + raising_dot, call_raising_dot = generate_raising_dot_case() + self.check_profiler_dot(call_raising_dot, raising_dot) + + @needs_blas + def test_profiler_np_dot(self): + # Issue #1786: initializing BLAS would crash when profiling + code = """if 1: + import cProfile as profiler + + import numpy as np + + from numba import jit + from numba.tests.test_profiler import np_dot + + cfunc = jit(nopython=True)(np_dot) + + a = np.arange(16, dtype=np.float32) + b = np.arange(16, dtype=np.float32) + + p = profiler.Profile() + p.enable() + cfunc(a, b) + cfunc(a, b) + p.disable() + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_issue_3229(self): + # Issue #3229: Seemingly random segfaults when profiling due to + # frame injection. + # numba.tests.npyufunc.test_dufunc.TestDUFunc.test_npm_call is the + # first test case crashing when profiling. Fingers crossed fixing + # this is sufficient proof for the general case. + + code = """if 1: + import cProfile as profiler + p = profiler.Profile() + p.enable() + + from numba.tests.npyufunc.test_dufunc import TestDUFunc + t = TestDUFunc('test_npm_call') + t.test_npm_call() + + p.disable() + """ + subprocess.check_call([sys.executable, "-c", code]) + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/4f/4ff3d30528c355d965d93ccc123d31284905c0922befa08ad36387d2a8bbe84e/nntplib.py b/shared/package-files/4f/4ff3d30528c355d965d93ccc123d31284905c0922befa08ad36387d2a8bbe84e/nntplib.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e746e7c95c5bfdcaebff155a140de34d71fed1 --- /dev/null +++ b/shared/package-files/4f/4ff3d30528c355d965d93ccc123d31284905c0922befa08ad36387d2a8bbe84e/nntplib.py @@ -0,0 +1,1090 @@ +"""An NNTP client class based on: +- RFC 977: Network News Transfer Protocol +- RFC 2980: Common NNTP Extensions +- RFC 3977: Network News Transfer Protocol (version 2) + +Example: + +>>> from nntplib import NNTP +>>> s = NNTP('news') +>>> resp, count, first, last, name = s.group('comp.lang.python') +>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) +Group comp.lang.python has 51 articles, range 5770 to 5821 +>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last)) +>>> resp = s.quit() +>>> + +Here 'resp' is the server response line. +Error responses are turned into exceptions. + +To post an article from a file: +>>> f = open(filename, 'rb') # file containing article, including header +>>> resp = s.post(f) +>>> + +For descriptions of all methods, read the comments in the code below. +Note that all arguments and return values representing article numbers +are strings, not numbers, since they are rarely used for calculations. +""" + +# RFC 977 by Brian Kantor and Phil Lapsley. +# xover, xgtitle, xpath, date methods by Kevan Heydon + +# Incompatible changes from the 2.x nntplib: +# - all commands are encoded as UTF-8 data (using the "surrogateescape" +# error handler), except for raw message data (POST, IHAVE) +# - all responses are decoded as UTF-8 data (using the "surrogateescape" +# error handler), except for raw message data (ARTICLE, HEAD, BODY) +# - the `file` argument to various methods is keyword-only +# +# - NNTP.date() returns a datetime object +# - NNTP.newgroups() and NNTP.newnews() take a datetime (or date) object, +# rather than a pair of (date, time) strings. +# - NNTP.newgroups() and NNTP.list() return a list of GroupInfo named tuples +# - NNTP.descriptions() returns a dict mapping group names to descriptions +# - NNTP.xover() returns a list of dicts mapping field names (header or metadata) +# to field values; each dict representing a message overview. +# - NNTP.article(), NNTP.head() and NNTP.body() return a (response, ArticleInfo) +# tuple. +# - the "internal" methods have been marked private (they now start with +# an underscore) + +# Other changes from the 2.x/3.1 nntplib: +# - automatic querying of capabilities at connect +# - New method NNTP.getcapabilities() +# - New method NNTP.over() +# - New helper function decode_header() +# - NNTP.post() and NNTP.ihave() accept file objects, bytes-like objects and +# arbitrary iterables yielding lines. +# - An extensive test suite :-) + +# TODO: +# - return structured data (GroupInfo etc.) everywhere +# - support HDR + +# Imports +import re +import socket +import collections +import datetime +import sys + +try: + import ssl +except ImportError: + _have_ssl = False +else: + _have_ssl = True + +from email.header import decode_header as _email_decode_header +from socket import _GLOBAL_DEFAULT_TIMEOUT + +__all__ = ["NNTP", + "NNTPError", "NNTPReplyError", "NNTPTemporaryError", + "NNTPPermanentError", "NNTPProtocolError", "NNTPDataError", + "decode_header", + ] + +# maximal line length when calling readline(). This is to prevent +# reading arbitrary length lines. RFC 3977 limits NNTP line length to +# 512 characters, including CRLF. We have selected 2048 just to be on +# the safe side. +_MAXLINE = 2048 + + +# Exceptions raised when an error or invalid response is received +class NNTPError(Exception): + """Base class for all nntplib exceptions""" + def __init__(self, *args): + Exception.__init__(self, *args) + try: + self.response = args[0] + except IndexError: + self.response = 'No response given' + +class NNTPReplyError(NNTPError): + """Unexpected [123]xx reply""" + pass + +class NNTPTemporaryError(NNTPError): + """4xx errors""" + pass + +class NNTPPermanentError(NNTPError): + """5xx errors""" + pass + +class NNTPProtocolError(NNTPError): + """Response does not begin with [1-5]""" + pass + +class NNTPDataError(NNTPError): + """Error in response data""" + pass + + +# Standard port used by NNTP servers +NNTP_PORT = 119 +NNTP_SSL_PORT = 563 + +# Response numbers that are followed by additional text (e.g. article) +_LONGRESP = { + '100', # HELP + '101', # CAPABILITIES + '211', # LISTGROUP (also not multi-line with GROUP) + '215', # LIST + '220', # ARTICLE + '221', # HEAD, XHDR + '222', # BODY + '224', # OVER, XOVER + '225', # HDR + '230', # NEWNEWS + '231', # NEWGROUPS + '282', # XGTITLE +} + +# Default decoded value for LIST OVERVIEW.FMT if not supported +_DEFAULT_OVERVIEW_FMT = [ + "subject", "from", "date", "message-id", "references", ":bytes", ":lines"] + +# Alternative names allowed in LIST OVERVIEW.FMT response +_OVERVIEW_FMT_ALTERNATIVES = { + 'bytes': ':bytes', + 'lines': ':lines', +} + +# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) +_CRLF = b'\r\n' + +GroupInfo = collections.namedtuple('GroupInfo', + ['group', 'last', 'first', 'flag']) + +ArticleInfo = collections.namedtuple('ArticleInfo', + ['number', 'message_id', 'lines']) + + +# Helper function(s) +def decode_header(header_str): + """Takes a unicode string representing a munged header value + and decodes it as a (possibly non-ASCII) readable value.""" + parts = [] + for v, enc in _email_decode_header(header_str): + if isinstance(v, bytes): + parts.append(v.decode(enc or 'ascii')) + else: + parts.append(v) + return ''.join(parts) + +def _parse_overview_fmt(lines): + """Parse a list of string representing the response to LIST OVERVIEW.FMT + and return a list of header/metadata names. + Raises NNTPDataError if the response is not compliant + (cf. RFC 3977, section 8.4).""" + fmt = [] + for line in lines: + if line[0] == ':': + # Metadata name (e.g. ":bytes") + name, _, suffix = line[1:].partition(':') + name = ':' + name + else: + # Header name (e.g. "Subject:" or "Xref:full") + name, _, suffix = line.partition(':') + name = name.lower() + name = _OVERVIEW_FMT_ALTERNATIVES.get(name, name) + # Should we do something with the suffix? + fmt.append(name) + defaults = _DEFAULT_OVERVIEW_FMT + if len(fmt) < len(defaults): + raise NNTPDataError("LIST OVERVIEW.FMT response too short") + if fmt[:len(defaults)] != defaults: + raise NNTPDataError("LIST OVERVIEW.FMT redefines default fields") + return fmt + +def _parse_overview(lines, fmt, data_process_func=None): + """Parse the response to an OVER or XOVER command according to the + overview format `fmt`.""" + n_defaults = len(_DEFAULT_OVERVIEW_FMT) + overview = [] + for line in lines: + fields = {} + article_number, *tokens = line.split('\t') + article_number = int(article_number) + for i, token in enumerate(tokens): + if i >= len(fmt): + # XXX should we raise an error? Some servers might not + # support LIST OVERVIEW.FMT and still return additional + # headers. + continue + field_name = fmt[i] + is_metadata = field_name.startswith(':') + if i >= n_defaults and not is_metadata: + # Non-default header names are included in full in the response + # (unless the field is totally empty) + h = field_name + ": " + if token and token[:len(h)].lower() != h: + raise NNTPDataError("OVER/XOVER response doesn't include " + "names of additional headers") + token = token[len(h):] if token else None + fields[fmt[i]] = token + overview.append((article_number, fields)) + return overview + +def _parse_datetime(date_str, time_str=None): + """Parse a pair of (date, time) strings, and return a datetime object. + If only the date is given, it is assumed to be date and time + concatenated together (e.g. response to the DATE command). + """ + if time_str is None: + time_str = date_str[-6:] + date_str = date_str[:-6] + hours = int(time_str[:2]) + minutes = int(time_str[2:4]) + seconds = int(time_str[4:]) + year = int(date_str[:-4]) + month = int(date_str[-4:-2]) + day = int(date_str[-2:]) + # RFC 3977 doesn't say how to interpret 2-char years. Assume that + # there are no dates before 1970 on Usenet. + if year < 70: + year += 2000 + elif year < 100: + year += 1900 + return datetime.datetime(year, month, day, hours, minutes, seconds) + +def _unparse_datetime(dt, legacy=False): + """Format a date or datetime object as a pair of (date, time) strings + in the format required by the NEWNEWS and NEWGROUPS commands. If a + date object is passed, the time is assumed to be midnight (00h00). + + The returned representation depends on the legacy flag: + * if legacy is False (the default): + date has the YYYYMMDD format and time the HHMMSS format + * if legacy is True: + date has the YYMMDD format and time the HHMMSS format. + RFC 3977 compliant servers should understand both formats; therefore, + legacy is only needed when talking to old servers. + """ + if not isinstance(dt, datetime.datetime): + time_str = "000000" + else: + time_str = "{0.hour:02d}{0.minute:02d}{0.second:02d}".format(dt) + y = dt.year + if legacy: + y = y % 100 + date_str = "{0:02d}{1.month:02d}{1.day:02d}".format(y, dt) + else: + date_str = "{0:04d}{1.month:02d}{1.day:02d}".format(y, dt) + return date_str, time_str + + +if _have_ssl: + + def _encrypt_on(sock, context, hostname): + """Wrap a socket in SSL/TLS. Arguments: + - sock: Socket to wrap + - context: SSL context to use for the encrypted connection + Returns: + - sock: New, encrypted socket. + """ + # Generate a default SSL context if none was passed. + if context is None: + context = ssl._create_stdlib_context() + return context.wrap_socket(sock, server_hostname=hostname) + + +# The classes themselves +class NNTP: + # UTF-8 is the character set for all NNTP commands and responses: they + # are automatically encoded (when sending) and decoded (and receiving) + # by this class. + # However, some multi-line data blocks can contain arbitrary bytes (for + # example, latin-1 or utf-16 data in the body of a message). Commands + # taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message + # data will therefore only accept and produce bytes objects. + # Furthermore, since there could be non-compliant servers out there, + # we use 'surrogateescape' as the error handler for fault tolerance + # and easy round-tripping. This could be useful for some applications + # (e.g. NNTP gateways). + + encoding = 'utf-8' + errors = 'surrogateescape' + + def __init__(self, host, port=NNTP_PORT, user=None, password=None, + readermode=None, usenetrc=False, + timeout=_GLOBAL_DEFAULT_TIMEOUT): + """Initialize an instance. Arguments: + - host: hostname to connect to + - port: port to connect to (default the standard NNTP port) + - user: username to authenticate with + - password: password to use with username + - readermode: if true, send 'mode reader' command after + connecting. + - usenetrc: allow loading username and password from ~/.netrc file + if not specified explicitly + - timeout: timeout (in seconds) used for socket connections + + readermode is sometimes necessary if you are connecting to an + NNTP server on the local machine and intend to call + reader-specific commands, such as `group'. If you get + unexpected NNTPPermanentErrors, you might need to set + readermode. + """ + self.host = host + self.port = port + self.sock = self._create_socket(timeout) + self.file = None + try: + self.file = self.sock.makefile("rwb") + self._base_init(readermode) + if user or usenetrc: + self.login(user, password, usenetrc) + except: + if self.file: + self.file.close() + self.sock.close() + raise + + def _base_init(self, readermode): + """Partial initialization for the NNTP protocol. + This instance method is extracted for supporting the test code. + """ + self.debugging = 0 + self.welcome = self._getresp() + + # Inquire about capabilities (RFC 3977). + self._caps = None + self.getcapabilities() + + # 'MODE READER' is sometimes necessary to enable 'reader' mode. + # However, the order in which 'MODE READER' and 'AUTHINFO' need to + # arrive differs between some NNTP servers. If _setreadermode() fails + # with an authorization failed error, it will set this to True; + # the login() routine will interpret that as a request to try again + # after performing its normal function. + # Enable only if we're not already in READER mode anyway. + self.readermode_afterauth = False + if readermode and 'READER' not in self._caps: + self._setreadermode() + if not self.readermode_afterauth: + # Capabilities might have changed after MODE READER + self._caps = None + self.getcapabilities() + + # RFC 4642 2.2.2: Both the client and the server MUST know if there is + # a TLS session active. A client MUST NOT attempt to start a TLS + # session if a TLS session is already active. + self.tls_on = False + + # Log in and encryption setup order is left to subclasses. + self.authenticated = False + + def __enter__(self): + return self + + def __exit__(self, *args): + is_connected = lambda: hasattr(self, "file") + if is_connected(): + try: + self.quit() + except (OSError, EOFError): + pass + finally: + if is_connected(): + self._close() + + def _create_socket(self, timeout): + if timeout is not None and not timeout: + raise ValueError('Non-blocking socket (timeout=0) is not supported') + sys.audit("nntplib.connect", self, self.host, self.port) + return socket.create_connection((self.host, self.port), timeout) + + def getwelcome(self): + """Get the welcome message from the server + (this is read and squirreled away by __init__()). + If the response code is 200, posting is allowed; + if it 201, posting is not allowed.""" + + if self.debugging: print('*welcome*', repr(self.welcome)) + return self.welcome + + def getcapabilities(self): + """Get the server capabilities, as read by __init__(). + If the CAPABILITIES command is not supported, an empty dict is + returned.""" + if self._caps is None: + self.nntp_version = 1 + self.nntp_implementation = None + try: + resp, caps = self.capabilities() + except (NNTPPermanentError, NNTPTemporaryError): + # Server doesn't support capabilities + self._caps = {} + else: + self._caps = caps + if 'VERSION' in caps: + # The server can advertise several supported versions, + # choose the highest. + self.nntp_version = max(map(int, caps['VERSION'])) + if 'IMPLEMENTATION' in caps: + self.nntp_implementation = ' '.join(caps['IMPLEMENTATION']) + return self._caps + + def set_debuglevel(self, level): + """Set the debugging level. Argument 'level' means: + 0: no debugging output (default) + 1: print commands and responses but not body text etc. + 2: also print raw lines read and sent before stripping CR/LF""" + + self.debugging = level + debug = set_debuglevel + + def _putline(self, line): + """Internal: send one line to the server, appending CRLF. + The `line` must be a bytes-like object.""" + sys.audit("nntplib.putline", self, line) + line = line + _CRLF + if self.debugging > 1: print('*put*', repr(line)) + self.file.write(line) + self.file.flush() + + def _putcmd(self, line): + """Internal: send one command to the server (through _putline()). + The `line` must be a unicode string.""" + if self.debugging: print('*cmd*', repr(line)) + line = line.encode(self.encoding, self.errors) + self._putline(line) + + def _getline(self, strip_crlf=True): + """Internal: return one line from the server, stripping _CRLF. + Raise EOFError if the connection is closed. + Returns a bytes object.""" + line = self.file.readline(_MAXLINE +1) + if len(line) > _MAXLINE: + raise NNTPDataError('line too long') + if self.debugging > 1: + print('*get*', repr(line)) + if not line: raise EOFError + if strip_crlf: + if line[-2:] == _CRLF: + line = line[:-2] + elif line[-1:] in _CRLF: + line = line[:-1] + return line + + def _getresp(self): + """Internal: get a response from the server. + Raise various errors if the response indicates an error. + Returns a unicode string.""" + resp = self._getline() + if self.debugging: print('*resp*', repr(resp)) + resp = resp.decode(self.encoding, self.errors) + c = resp[:1] + if c == '4': + raise NNTPTemporaryError(resp) + if c == '5': + raise NNTPPermanentError(resp) + if c not in '123': + raise NNTPProtocolError(resp) + return resp + + def _getlongresp(self, file=None): + """Internal: get a response plus following text from the server. + Raise various errors if the response indicates an error. + + Returns a (response, lines) tuple where `response` is a unicode + string and `lines` is a list of bytes objects. + If `file` is a file-like object, it must be open in binary mode. + """ + + openedFile = None + try: + # If a string was passed then open a file with that name + if isinstance(file, (str, bytes)): + openedFile = file = open(file, "wb") + + resp = self._getresp() + if resp[:3] not in _LONGRESP: + raise NNTPReplyError(resp) + + lines = [] + if file is not None: + # XXX lines = None instead? + terminators = (b'.' + _CRLF, b'.\n') + while 1: + line = self._getline(False) + if line in terminators: + break + if line.startswith(b'..'): + line = line[1:] + file.write(line) + else: + terminator = b'.' + while 1: + line = self._getline() + if line == terminator: + break + if line.startswith(b'..'): + line = line[1:] + lines.append(line) + finally: + # If this method created the file, then it must close it + if openedFile: + openedFile.close() + + return resp, lines + + def _shortcmd(self, line): + """Internal: send a command and get the response. + Same return value as _getresp().""" + self._putcmd(line) + return self._getresp() + + def _longcmd(self, line, file=None): + """Internal: send a command and get the response plus following text. + Same return value as _getlongresp().""" + self._putcmd(line) + return self._getlongresp(file) + + def _longcmdstring(self, line, file=None): + """Internal: send a command and get the response plus following text. + Same as _longcmd() and _getlongresp(), except that the returned `lines` + are unicode strings rather than bytes objects. + """ + self._putcmd(line) + resp, list = self._getlongresp(file) + return resp, [line.decode(self.encoding, self.errors) + for line in list] + + def _getoverviewfmt(self): + """Internal: get the overview format. Queries the server if not + already done, else returns the cached value.""" + try: + return self._cachedoverviewfmt + except AttributeError: + pass + try: + resp, lines = self._longcmdstring("LIST OVERVIEW.FMT") + except NNTPPermanentError: + # Not supported by server? + fmt = _DEFAULT_OVERVIEW_FMT[:] + else: + fmt = _parse_overview_fmt(lines) + self._cachedoverviewfmt = fmt + return fmt + + def _grouplist(self, lines): + # Parse lines into "group last first flag" + return [GroupInfo(*line.split()) for line in lines] + + def capabilities(self): + """Process a CAPABILITIES command. Not supported by all servers. + Return: + - resp: server response if successful + - caps: a dictionary mapping capability names to lists of tokens + (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) + """ + caps = {} + resp, lines = self._longcmdstring("CAPABILITIES") + for line in lines: + name, *tokens = line.split() + caps[name] = tokens + return resp, caps + + def newgroups(self, date, *, file=None): + """Process a NEWGROUPS command. Arguments: + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of newsgroup names + """ + if not isinstance(date, (datetime.date, datetime.date)): + raise TypeError( + "the date parameter must be a date or datetime object, " + "not '{:40}'".format(date.__class__.__name__)) + date_str, time_str = _unparse_datetime(date, self.nntp_version < 2) + cmd = 'NEWGROUPS {0} {1}'.format(date_str, time_str) + resp, lines = self._longcmdstring(cmd, file) + return resp, self._grouplist(lines) + + def newnews(self, group, date, *, file=None): + """Process a NEWNEWS command. Arguments: + - group: group name or '*' + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of message ids + """ + if not isinstance(date, (datetime.date, datetime.date)): + raise TypeError( + "the date parameter must be a date or datetime object, " + "not '{:40}'".format(date.__class__.__name__)) + date_str, time_str = _unparse_datetime(date, self.nntp_version < 2) + cmd = 'NEWNEWS {0} {1} {2}'.format(group, date_str, time_str) + return self._longcmdstring(cmd, file) + + def list(self, group_pattern=None, *, file=None): + """Process a LIST or LIST ACTIVE command. Arguments: + - group_pattern: a pattern indicating which groups to query + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (group, last, first, flag) (strings) + """ + if group_pattern is not None: + command = 'LIST ACTIVE ' + group_pattern + else: + command = 'LIST' + resp, lines = self._longcmdstring(command, file) + return resp, self._grouplist(lines) + + def _getdescriptions(self, group_pattern, return_all): + line_pat = re.compile('^(?P[^ \t]+)[ \t]+(.*)$') + # Try the more std (acc. to RFC2980) LIST NEWSGROUPS first + resp, lines = self._longcmdstring('LIST NEWSGROUPS ' + group_pattern) + if not resp.startswith('215'): + # Now the deprecated XGTITLE. This either raises an error + # or succeeds with the same output structure as LIST + # NEWSGROUPS. + resp, lines = self._longcmdstring('XGTITLE ' + group_pattern) + groups = {} + for raw_line in lines: + match = line_pat.search(raw_line.strip()) + if match: + name, desc = match.group(1, 2) + if not return_all: + return desc + groups[name] = desc + if return_all: + return resp, groups + else: + # Nothing found + return '' + + def description(self, group): + """Get a description for a single group. If more than one + group matches ('group' is a pattern), return the first. If no + group matches, return an empty string. + + This elides the response code from the server, since it can + only be '215' or '285' (for xgtitle) anyway. If the response + code is needed, use the 'descriptions' method. + + NOTE: This neither checks for a wildcard in 'group' nor does + it check whether the group actually exists.""" + return self._getdescriptions(group, False) + + def descriptions(self, group_pattern): + """Get descriptions for a range of groups.""" + return self._getdescriptions(group_pattern, True) + + def group(self, name): + """Process a GROUP command. Argument: + - group: the group name + Returns: + - resp: server response if successful + - count: number of articles + - first: first article number + - last: last article number + - name: the group name + """ + resp = self._shortcmd('GROUP ' + name) + if not resp.startswith('211'): + raise NNTPReplyError(resp) + words = resp.split() + count = first = last = 0 + n = len(words) + if n > 1: + count = words[1] + if n > 2: + first = words[2] + if n > 3: + last = words[3] + if n > 4: + name = words[4].lower() + return resp, int(count), int(first), int(last), name + + def help(self, *, file=None): + """Process a HELP command. Argument: + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of strings returned by the server in response to the + HELP command + """ + return self._longcmdstring('HELP', file) + + def _statparse(self, resp): + """Internal: parse the response line of a STAT, NEXT, LAST, + ARTICLE, HEAD or BODY command.""" + if not resp.startswith('22'): + raise NNTPReplyError(resp) + words = resp.split() + art_num = int(words[1]) + message_id = words[2] + return resp, art_num, message_id + + def _statcmd(self, line): + """Internal: process a STAT, NEXT or LAST command.""" + resp = self._shortcmd(line) + return self._statparse(resp) + + def stat(self, message_spec=None): + """Process a STAT command. Argument: + - message_spec: article number or message id (if not specified, + the current article is selected) + Returns: + - resp: server response if successful + - art_num: the article number + - message_id: the message id + """ + if message_spec: + return self._statcmd('STAT {0}'.format(message_spec)) + else: + return self._statcmd('STAT') + + def next(self): + """Process a NEXT command. No arguments. Return as for STAT.""" + return self._statcmd('NEXT') + + def last(self): + """Process a LAST command. No arguments. Return as for STAT.""" + return self._statcmd('LAST') + + def _artcmd(self, line, file=None): + """Internal: process a HEAD, BODY or ARTICLE command.""" + resp, lines = self._longcmd(line, file) + resp, art_num, message_id = self._statparse(resp) + return resp, ArticleInfo(art_num, message_id, lines) + + def head(self, message_spec=None, *, file=None): + """Process a HEAD command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the headers in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of header lines) + """ + if message_spec is not None: + cmd = 'HEAD {0}'.format(message_spec) + else: + cmd = 'HEAD' + return self._artcmd(cmd, file) + + def body(self, message_spec=None, *, file=None): + """Process a BODY command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the body in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of body lines) + """ + if message_spec is not None: + cmd = 'BODY {0}'.format(message_spec) + else: + cmd = 'BODY' + return self._artcmd(cmd, file) + + def article(self, message_spec=None, *, file=None): + """Process an ARTICLE command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the article in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of article lines) + """ + if message_spec is not None: + cmd = 'ARTICLE {0}'.format(message_spec) + else: + cmd = 'ARTICLE' + return self._artcmd(cmd, file) + + def slave(self): + """Process a SLAVE command. Returns: + - resp: server response if successful + """ + return self._shortcmd('SLAVE') + + def xhdr(self, hdr, str, *, file=None): + """Process an XHDR command (optional server extension). Arguments: + - hdr: the header type (e.g. 'subject') + - str: an article nr, a message id, or a range nr1-nr2 + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (nr, value) strings + """ + pat = re.compile('^([0-9]+) ?(.*)\n?') + resp, lines = self._longcmdstring('XHDR {0} {1}'.format(hdr, str), file) + def remove_number(line): + m = pat.match(line) + return m.group(1, 2) if m else line + return resp, [remove_number(line) for line in lines] + + def xover(self, start, end, *, file=None): + """Process an XOVER command (optional server extension) Arguments: + - start: start of range + - end: end of range + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + """ + resp, lines = self._longcmdstring('XOVER {0}-{1}'.format(start, end), + file) + fmt = self._getoverviewfmt() + return resp, _parse_overview(lines, fmt) + + def over(self, message_spec, *, file=None): + """Process an OVER command. If the command isn't supported, fall + back to XOVER. Arguments: + - message_spec: + - either a message id, indicating the article to fetch + information about + - or a (start, end) tuple, indicating a range of article numbers; + if end is None, information up to the newest message will be + retrieved + - or None, indicating the current article number must be used + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + + NOTE: the "message id" form isn't supported by XOVER + """ + cmd = 'OVER' if 'OVER' in self._caps else 'XOVER' + if isinstance(message_spec, (tuple, list)): + start, end = message_spec + cmd += ' {0}-{1}'.format(start, end or '') + elif message_spec is not None: + cmd = cmd + ' ' + message_spec + resp, lines = self._longcmdstring(cmd, file) + fmt = self._getoverviewfmt() + return resp, _parse_overview(lines, fmt) + + def date(self): + """Process the DATE command. + Returns: + - resp: server response if successful + - date: datetime object + """ + resp = self._shortcmd("DATE") + if not resp.startswith('111'): + raise NNTPReplyError(resp) + elem = resp.split() + if len(elem) != 2: + raise NNTPDataError(resp) + date = elem[1] + if len(date) != 14: + raise NNTPDataError(resp) + return resp, _parse_datetime(date, None) + + def _post(self, command, f): + resp = self._shortcmd(command) + # Raises a specific exception if posting is not allowed + if not resp.startswith('3'): + raise NNTPReplyError(resp) + if isinstance(f, (bytes, bytearray)): + f = f.splitlines() + # We don't use _putline() because: + # - we don't want additional CRLF if the file or iterable is already + # in the right format + # - we don't want a spurious flush() after each line is written + for line in f: + if not line.endswith(_CRLF): + line = line.rstrip(b"\r\n") + _CRLF + if line.startswith(b'.'): + line = b'.' + line + self.file.write(line) + self.file.write(b".\r\n") + self.file.flush() + return self._getresp() + + def post(self, data): + """Process a POST command. Arguments: + - data: bytes object, iterable or file containing the article + Returns: + - resp: server response if successful""" + return self._post('POST', data) + + def ihave(self, message_id, data): + """Process an IHAVE command. Arguments: + - message_id: message-id of the article + - data: file containing the article + Returns: + - resp: server response if successful + Note that if the server refuses the article an exception is raised.""" + return self._post('IHAVE {0}'.format(message_id), data) + + def _close(self): + try: + if self.file: + self.file.close() + del self.file + finally: + self.sock.close() + + def quit(self): + """Process a QUIT command and close the socket. Returns: + - resp: server response if successful""" + try: + resp = self._shortcmd('QUIT') + finally: + self._close() + return resp + + def login(self, user=None, password=None, usenetrc=True): + if self.authenticated: + raise ValueError("Already logged in.") + if not user and not usenetrc: + raise ValueError( + "At least one of `user` and `usenetrc` must be specified") + # If no login/password was specified but netrc was requested, + # try to get them from ~/.netrc + # Presume that if .netrc has an entry, NNRP authentication is required. + try: + if usenetrc and not user: + import netrc + credentials = netrc.netrc() + auth = credentials.authenticators(self.host) + if auth: + user = auth[0] + password = auth[2] + except OSError: + pass + # Perform NNTP authentication if needed. + if not user: + return + resp = self._shortcmd('authinfo user ' + user) + if resp.startswith('381'): + if not password: + raise NNTPReplyError(resp) + else: + resp = self._shortcmd('authinfo pass ' + password) + if not resp.startswith('281'): + raise NNTPPermanentError(resp) + # Capabilities might have changed after login + self._caps = None + self.getcapabilities() + # Attempt to send mode reader if it was requested after login. + # Only do so if we're not in reader mode already. + if self.readermode_afterauth and 'READER' not in self._caps: + self._setreadermode() + # Capabilities might have changed after MODE READER + self._caps = None + self.getcapabilities() + + def _setreadermode(self): + try: + self.welcome = self._shortcmd('mode reader') + except NNTPPermanentError: + # Error 5xx, probably 'not implemented' + pass + except NNTPTemporaryError as e: + if e.response.startswith('480'): + # Need authorization before 'mode reader' + self.readermode_afterauth = True + else: + raise + + if _have_ssl: + def starttls(self, context=None): + """Process a STARTTLS command. Arguments: + - context: SSL context to use for the encrypted connection + """ + # Per RFC 4642, STARTTLS MUST NOT be sent after authentication or if + # a TLS session already exists. + if self.tls_on: + raise ValueError("TLS is already enabled.") + if self.authenticated: + raise ValueError("TLS cannot be started after authentication.") + resp = self._shortcmd('STARTTLS') + if resp.startswith('382'): + self.file.close() + self.sock = _encrypt_on(self.sock, context, self.host) + self.file = self.sock.makefile("rwb") + self.tls_on = True + # Capabilities may change after TLS starts up, so ask for them + # again. + self._caps = None + self.getcapabilities() + else: + raise NNTPError("TLS failed to start.") + + +if _have_ssl: + class NNTP_SSL(NNTP): + + def __init__(self, host, port=NNTP_SSL_PORT, + user=None, password=None, ssl_context=None, + readermode=None, usenetrc=False, + timeout=_GLOBAL_DEFAULT_TIMEOUT): + """This works identically to NNTP.__init__, except for the change + in default port and the `ssl_context` argument for SSL connections. + """ + self.ssl_context = ssl_context + super().__init__(host, port, user, password, readermode, + usenetrc, timeout) + + def _create_socket(self, timeout): + sock = super()._create_socket(timeout) + try: + sock = _encrypt_on(sock, self.ssl_context, self.host) + except: + sock.close() + raise + else: + return sock + + __all__.append("NNTP_SSL") + + +# Test retrieval when run as a script. +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser(description="""\ + nntplib built-in demo - display the latest articles in a newsgroup""") + parser.add_argument('-g', '--group', default='gmane.comp.python.general', + help='group to fetch messages from (default: %(default)s)') + parser.add_argument('-s', '--server', default='news.gmane.io', + help='NNTP server hostname (default: %(default)s)') + parser.add_argument('-p', '--port', default=-1, type=int, + help='NNTP port number (default: %s / %s)' % (NNTP_PORT, NNTP_SSL_PORT)) + parser.add_argument('-n', '--nb-articles', default=10, type=int, + help='number of articles to fetch (default: %(default)s)') + parser.add_argument('-S', '--ssl', action='store_true', default=False, + help='use NNTP over SSL') + args = parser.parse_args() + + port = args.port + if not args.ssl: + if port == -1: + port = NNTP_PORT + s = NNTP(host=args.server, port=port) + else: + if port == -1: + port = NNTP_SSL_PORT + s = NNTP_SSL(host=args.server, port=port) + + caps = s.getcapabilities() + if 'STARTTLS' in caps: + s.starttls() + resp, count, first, last, name = s.group(args.group) + print('Group', name, 'has', count, 'articles, range', first, 'to', last) + + def cut(s, lim): + if len(s) > lim: + s = s[:lim - 4] + "..." + return s + + first = str(int(last) - args.nb_articles + 1) + resp, overviews = s.xover(first, last) + for artnum, over in overviews: + author = decode_header(over['from']).split('<', 1)[0] + subject = decode_header(over['subject']) + lines = int(over[':lines']) + print("{:7} {:20} {:42} ({})".format( + artnum, cut(author, 20), cut(subject, 42), lines) + ) + + s.quit() diff --git a/shared/package-files/4f/4ff588b28c7a55ee82c661709f1e9b5f72a42f2d71cc109b00505c1aa1d5602f/country211.py b/shared/package-files/4f/4ff588b28c7a55ee82c661709f1e9b5f72a42f2d71cc109b00505c1aa1d5602f/country211.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f82ee1226670ae274cc09dc0697dd4c51fb1c2 --- /dev/null +++ b/shared/package-files/4f/4ff588b28c7a55ee82c661709f1e9b5f72a42f2d71cc109b00505c1aa1d5602f/country211.py @@ -0,0 +1,58 @@ +from pathlib import Path +from typing import Callable, Optional, Union + +from .folder import ImageFolder +from .utils import download_and_extract_archive, verify_str_arg + + +class Country211(ImageFolder): + """`The Country211 Data Set `_ from OpenAI. + + This dataset was built by filtering the images from the YFCC100m dataset + that have GPS coordinate corresponding to a ISO-3166 country code. The + dataset is balanced by sampling 150 train images, 50 validation images, and + 100 test images for each country. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"valid"`` and ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and puts it into + ``root/country211/``. If dataset is already downloaded, it is not downloaded again. + """ + + _URL = "https://openaipublic.azureedge.net/clip/data/country211.tgz" + _MD5 = "84988d7644798601126c29e9877aab6a" + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "valid", "test")) + + root = Path(root).expanduser() + self.root = str(root) + self._base_folder = root / "country211" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + super().__init__(str(self._base_folder / self._split), transform=transform, target_transform=target_transform) + self.root = str(root) + + def _check_exists(self) -> bool: + return self._base_folder.exists() and self._base_folder.is_dir() + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5) diff --git a/shared/package-files/4f/4ff898738bbf1337c887bcdb1bfc56d39d9fc893175171293df0ce68043ab006/common.py b/shared/package-files/4f/4ff898738bbf1337c887bcdb1bfc56d39d9fc893175171293df0ce68043ab006/common.py new file mode 100644 index 0000000000000000000000000000000000000000..3f736bf4017c952c850dcbb3cc5fe1fe14f2715f --- /dev/null +++ b/shared/package-files/4f/4ff898738bbf1337c887bcdb1bfc56d39d9fc893175171293df0ce68043ab006/common.py @@ -0,0 +1,13 @@ +def __getattr__(name: str): + if name == "AudioMetaData": + import warnings + + warnings.warn( + "`torchaudio.backend.common.AudioMetaData` has been moved to " + "`torchaudio.AudioMetaData`. Please update the import path.", + stacklevel=2, + ) + from torchaudio import AudioMetaData + + return AudioMetaData + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/shared/package-files/4f/4ffce38cca111cef848adfd59d9f83b16e9e2d9f86bdc38a6a44e3325a565375/_nested_view_from_jagged_ops.h b/shared/package-files/4f/4ffce38cca111cef848adfd59d9f83b16e9e2d9f86bdc38a6a44e3325a565375/_nested_view_from_jagged_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..149af92a478895163506cf740c55ac446a6e261c --- /dev/null +++ b/shared/package-files/4f/4ffce38cca111cef848adfd59d9f83b16e9e2d9f86bdc38a6a44e3325a565375/_nested_view_from_jagged_ops.h @@ -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_view_from_jagged { + 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") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_view_from_jagged(Tensor(a) self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1) -> 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); + 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); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/4f/4ffd978e3fa18d058d98c66771cfea7ed634aaf7023cf9612b8b55eee9a8f0fe/LICENSE b/shared/package-files/4f/4ffd978e3fa18d058d98c66771cfea7ed634aaf7023cf9612b8b55eee9a8f0fe/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ca9f2fee821caf1a99a27ea17e3467cccd8c73b8 --- /dev/null +++ b/shared/package-files/4f/4ffd978e3fa18d058d98c66771cfea7ed634aaf7023cf9612b8b55eee9a8f0fe/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Consortium for Python Data API Standards + +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/56/5601bc37370598892115b299a5b8e3cd5e16e4939a2471a3f54b7cba058cd943/test_secondquant.py b/shared/package-files/56/5601bc37370598892115b299a5b8e3cd5e16e4939a2471a3f54b7cba058cd943/test_secondquant.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9f4a499a7bee96d5fb5c76e83d84a72db5db8a --- /dev/null +++ b/shared/package-files/56/5601bc37370598892115b299a5b8e3cd5e16e4939a2471a3f54b7cba058cd943/test_secondquant.py @@ -0,0 +1,1280 @@ +from sympy.physics.secondquant import ( + Dagger, Bd, VarBosonicBasis, BBra, B, BKet, FixedBosonicBasis, + matrix_rep, apply_operators, InnerProduct, Commutator, KroneckerDelta, + AnnihilateBoson, CreateBoson, BosonicOperator, + F, Fd, FKet, BosonState, CreateFermion, AnnihilateFermion, + evaluate_deltas, AntiSymmetricTensor, contraction, NO, wicks, + PermutationOperator, simplify_index_permutations, + _sort_anticommuting_fermions, _get_ordered_dummies, + substitute_dummies, FockStateBosonKet, + ContractionAppliesOnlyToFermions +) + +from sympy.concrete.summations import Sum +from sympy.core.function import (Function, expand) +from sympy.core.numbers import (I, Rational) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.printing.repr import srepr +from sympy.simplify.simplify import simplify + +from sympy.testing.pytest import slow, raises +from sympy.printing.latex import latex + + +def test_PermutationOperator(): + p, q, r, s = symbols('p,q,r,s') + f, g, h, i = map(Function, 'fghi') + P = PermutationOperator + assert P(p, q).get_permuted(f(p)*g(q)) == -f(q)*g(p) + assert P(p, q).get_permuted(f(p, q)) == -f(q, p) + assert P(p, q).get_permuted(f(p)) == f(p) + expr = (f(p)*g(q)*h(r)*i(s) + - f(q)*g(p)*h(r)*i(s) + - f(p)*g(q)*h(s)*i(r) + + f(q)*g(p)*h(s)*i(r)) + perms = [P(p, q), P(r, s)] + assert (simplify_index_permutations(expr, perms) == + P(p, q)*P(r, s)*f(p)*g(q)*h(r)*i(s)) + assert latex(P(p, q)) == 'P(pq)' + + +def test_index_permutations_with_dummies(): + a, b, c, d = symbols('a b c d') + p, q, r, s = symbols('p q r s', cls=Dummy) + f, g = map(Function, 'fg') + P = PermutationOperator + + # No dummy substitution necessary + expr = f(a, b, p, q) - f(b, a, p, q) + assert simplify_index_permutations( + expr, [P(a, b)]) == P(a, b)*f(a, b, p, q) + + # Cases where dummy substitution is needed + expected = P(a, b)*substitute_dummies(f(a, b, p, q)) + + expr = f(a, b, p, q) - f(b, a, q, p) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expected == substitute_dummies(result) + + expr = f(a, b, q, p) - f(b, a, p, q) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expected == substitute_dummies(result) + + # A case where nothing can be done + expr = f(a, b, q, p) - g(b, a, p, q) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expr == result + + +def test_dagger(): + i, j, n, m = symbols('i,j,n,m') + assert Dagger(1) == 1 + assert Dagger(1.0) == 1.0 + assert Dagger(2*I) == -2*I + assert Dagger(S.Half*I/3.0) == I*Rational(-1, 2)/3.0 + assert Dagger(BKet([n])) == BBra([n]) + assert Dagger(B(0)) == Bd(0) + assert Dagger(Bd(0)) == B(0) + assert Dagger(B(n)) == Bd(n) + assert Dagger(Bd(n)) == B(n) + assert Dagger(B(0) + B(1)) == Bd(0) + Bd(1) + assert Dagger(n*m) == Dagger(n)*Dagger(m) # n, m commute + assert Dagger(B(n)*B(m)) == Bd(m)*Bd(n) + assert Dagger(B(n)**10) == Dagger(B(n))**10 + assert Dagger('a') == Dagger(Symbol('a')) + assert Dagger(Dagger('a')) == Symbol('a') + + +def test_operator(): + i, j = symbols('i,j') + o = BosonicOperator(i) + assert o.state == i + assert o.is_symbolic + o = BosonicOperator(1) + assert o.state == 1 + assert not o.is_symbolic + + +def test_create(): + i, j, n, m = symbols('i,j,n,m') + o = Bd(i) + assert latex(o) == "{b^\\dagger_{i}}" + assert isinstance(o, CreateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Bd(0) + assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1]) + o = Bd(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_annihilate(): + i, j, n, m = symbols('i,j,n,m') + o = B(i) + assert latex(o) == "b_{i}" + assert isinstance(o, AnnihilateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = B(0) + assert o.apply_operator(BKet([n])) == sqrt(n)*BKet([n - 1]) + o = B(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_basic_state(): + i, j, n, m = symbols('i,j,n,m') + s = BosonState([0, 1, 2, 3, 4]) + assert len(s) == 5 + assert s.args[0] == tuple(range(5)) + assert s.up(0) == BosonState([1, 1, 2, 3, 4]) + assert s.down(4) == BosonState([0, 1, 2, 3, 3]) + for i in range(5): + assert s.up(i).down(i) == s + assert s.down(0) == 0 + for i in range(5): + assert s[i] == i + s = BosonState([n, m]) + assert s.down(0) == BosonState([n - 1, m]) + assert s.up(0) == BosonState([n + 1, m]) + + +def test_basic_apply(): + n = symbols("n") + e = B(0)*BKet([n]) + assert apply_operators(e) == sqrt(n)*BKet([n - 1]) + e = Bd(0)*BKet([n]) + assert apply_operators(e) == sqrt(n + 1)*BKet([n + 1]) + + +def test_complex_apply(): + n, m = symbols("n,m") + o = Bd(0)*B(0)*Bd(1)*B(0) + e = apply_operators(o*BKet([n, m])) + answer = sqrt(n)*sqrt(m + 1)*(-1 + n)*BKet([-1 + n, 1 + m]) + assert expand(e) == expand(answer) + + +def test_number_operator(): + n = symbols("n") + o = Bd(0)*B(0) + e = apply_operators(o*BKet([n])) + assert e == n*BKet([n]) + + +def test_inner_product(): + i, j, k, l = symbols('i,j,k,l') + s1 = BBra([0]) + s2 = BKet([1]) + assert InnerProduct(s1, Dagger(s1)) == 1 + assert InnerProduct(s1, s2) == 0 + s1 = BBra([i, j]) + s2 = BKet([k, l]) + r = InnerProduct(s1, s2) + assert r == KroneckerDelta(i, k)*KroneckerDelta(j, l) + + +def test_symbolic_matrix_elements(): + n, m = symbols('n,m') + s1 = BBra([n]) + s2 = BKet([m]) + o = B(0) + e = apply_operators(s1*o*s2) + assert e == sqrt(m)*KroneckerDelta(n, m - 1) + + +def test_matrix_elements(): + b = VarBosonicBasis(5) + o = B(0) + m = matrix_rep(o, b) + for i in range(4): + assert m[i, i + 1] == sqrt(i + 1) + o = Bd(0) + m = matrix_rep(o, b) + for i in range(4): + assert m[i + 1, i] == sqrt(i + 1) + + +def test_fixed_bosonic_basis(): + b = FixedBosonicBasis(2, 2) + # assert b == [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))] + state = b.state(1) + assert state == FockStateBosonKet((1, 1)) + assert b.index(state) == 1 + assert b.state(1) == b[1] + assert len(b) == 3 + assert str(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + assert repr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + assert srepr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + + +@slow +def test_sho(): + n, m = symbols('n,m') + h_n = Bd(n)*B(n)*(n + S.Half) + H = Sum(h_n, (n, 0, 5)) + o = H.doit(deep=False) + b = FixedBosonicBasis(2, 6) + m = matrix_rep(o, b) + # We need to double check these energy values to make sure that they + # are correct and have the proper degeneracies! + diag = [1, 2, 3, 3, 4, 5, 4, 5, 6, 7, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 11] + for i in range(len(diag)): + assert diag[i] == m[i, i] + + +def test_commutation(): + n, m = symbols("n,m", above_fermi=True) + c = Commutator(B(0), Bd(0)) + assert c == 1 + c = Commutator(Bd(0), B(0)) + assert c == -1 + c = Commutator(B(n), Bd(0)) + assert c == KroneckerDelta(n, 0) + c = Commutator(B(0), B(0)) + assert c == 0 + c = Commutator(B(0), Bd(0)) + e = simplify(apply_operators(c*BKet([n]))) + assert e == BKet([n]) + c = Commutator(B(0), B(1)) + e = simplify(apply_operators(c*BKet([n, m]))) + assert e == 0 + + c = Commutator(F(m), Fd(m)) + assert c == +1 - 2*NO(Fd(m)*F(m)) + c = Commutator(Fd(m), F(m)) + assert c.expand() == -1 + 2*NO(Fd(m)*F(m)) + + C = Commutator + X, Y, Z = symbols('X,Y,Z', commutative=False) + assert C(C(X, Y), Z) != 0 + assert C(C(X, Z), Y) != 0 + assert C(Y, C(X, Z)) != 0 + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + D = KroneckerDelta + + assert C(Fd(a), F(i)) == -2*NO(F(i)*Fd(a)) + assert C(Fd(j), NO(Fd(a)*F(i))).doit(wicks=True) == -D(j, i)*Fd(a) + assert C(Fd(a)*F(i), Fd(b)*F(j)).doit(wicks=True) == 0 + + c1 = Commutator(F(a), Fd(a)) + assert Commutator.eval(c1, c1) == 0 + c = Commutator(Fd(a)*F(i),Fd(b)*F(j)) + assert latex(c) == r'\left[{a^\dagger_{a}} a_{i},{a^\dagger_{b}} a_{j}\right]' + assert repr(c) == 'Commutator(CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j))' + assert str(c) == '[CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j)]' + + +def test_create_f(): + i, j, n, m = symbols('i,j,n,m') + o = Fd(i) + assert isinstance(o, CreateFermion) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Fd(1) + assert o.apply_operator(FKet([n])) == FKet([1, n]) + assert o.apply_operator(FKet([n])) == -FKet([n, 1]) + o = Fd(n) + assert o.apply_operator(FKet([])) == FKet([n]) + + vacuum = FKet([], fermi_level=4) + assert vacuum == FKet([], fermi_level=4) + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + + assert Fd(i).apply_operator(FKet([i, j, k], 4)) == FKet([j, k], 4) + assert Fd(a).apply_operator(FKet([i, b, k], 4)) == FKet([a, i, b, k], 4) + + assert Dagger(B(p)).apply_operator(q) == q*CreateBoson(p) + assert repr(Fd(p)) == 'CreateFermion(p)' + assert srepr(Fd(p)) == "CreateFermion(Symbol('p'))" + assert latex(Fd(p)) == r'{a^\dagger_{p}}' + + +def test_annihilate_f(): + i, j, n, m = symbols('i,j,n,m') + o = F(i) + assert isinstance(o, AnnihilateFermion) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = F(1) + assert o.apply_operator(FKet([1, n])) == FKet([n]) + assert o.apply_operator(FKet([n, 1])) == -FKet([n]) + o = F(n) + assert o.apply_operator(FKet([n])) == FKet([]) + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + assert F(i).apply_operator(FKet([i, j, k], 4)) == 0 + assert F(a).apply_operator(FKet([i, b, k], 4)) == 0 + assert F(l).apply_operator(FKet([i, j, k], 3)) == 0 + assert F(l).apply_operator(FKet([i, j, k], 4)) == FKet([l, i, j, k], 4) + assert str(F(p)) == 'f(p)' + assert repr(F(p)) == 'AnnihilateFermion(p)' + assert srepr(F(p)) == "AnnihilateFermion(Symbol('p'))" + assert latex(F(p)) == 'a_{p}' + + +def test_create_b(): + i, j, n, m = symbols('i,j,n,m') + o = Bd(i) + assert isinstance(o, CreateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Bd(0) + assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1]) + o = Bd(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_annihilate_b(): + i, j, n, m = symbols('i,j,n,m') + o = B(i) + assert isinstance(o, AnnihilateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = B(0) + + +def test_wicks(): + p, q, r, s = symbols('p,q,r,s', above_fermi=True) + + # Testing for particles only + + str = F(p)*Fd(q) + assert wicks(str) == NO(F(p)*Fd(q)) + KroneckerDelta(p, q) + str = Fd(p)*F(q) + assert wicks(str) == NO(Fd(p)*F(q)) + + str = F(p)*Fd(q)*F(r)*Fd(s) + nstr = wicks(str) + fasit = NO( + KroneckerDelta(p, q)*KroneckerDelta(r, s) + + KroneckerDelta(p, q)*AnnihilateFermion(r)*CreateFermion(s) + + KroneckerDelta(r, s)*AnnihilateFermion(p)*CreateFermion(q) + - KroneckerDelta(p, s)*AnnihilateFermion(r)*CreateFermion(q) + - AnnihilateFermion(p)*AnnihilateFermion(r)*CreateFermion(q)*CreateFermion(s)) + assert nstr == fasit + + assert (p*q*nstr).expand() == wicks(p*q*str) + assert (nstr*p*q*2).expand() == wicks(str*p*q*2) + + # Testing CC equations particles and holes + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + p, q, r, s = symbols('p q r s', cls=Dummy) + + assert (wicks(F(a)*NO(F(i)*F(j))*Fd(b)) == + NO(F(a)*F(i)*F(j)*Fd(b)) + + KroneckerDelta(a, b)*NO(F(i)*F(j))) + assert (wicks(F(a)*NO(F(i)*F(j)*F(k))*Fd(b)) == + NO(F(a)*F(i)*F(j)*F(k)*Fd(b)) - + KroneckerDelta(a, b)*NO(F(i)*F(j)*F(k))) + + expr = wicks(Fd(i)*NO(Fd(j)*F(k))*F(l)) + assert (expr == + -KroneckerDelta(i, k)*NO(Fd(j)*F(l)) - + KroneckerDelta(j, l)*NO(Fd(i)*F(k)) - + KroneckerDelta(i, k)*KroneckerDelta(j, l) + + KroneckerDelta(i, l)*NO(Fd(j)*F(k)) + + NO(Fd(i)*Fd(j)*F(k)*F(l))) + expr = wicks(F(a)*NO(F(b)*Fd(c))*Fd(d)) + assert (expr == + -KroneckerDelta(a, c)*NO(F(b)*Fd(d)) - + KroneckerDelta(b, d)*NO(F(a)*Fd(c)) - + KroneckerDelta(a, c)*KroneckerDelta(b, d) + + KroneckerDelta(a, d)*NO(F(b)*Fd(c)) + + NO(F(a)*F(b)*Fd(c)*Fd(d))) + + +def test_NO(): + i, j, k, l = symbols('i j k l', below_fermi=True) + a, b, c, d = symbols('a b c d', above_fermi=True) + p, q, r, s = symbols('p q r s', cls=Dummy) + + assert (NO(Fd(p)*F(q) + Fd(a)*F(b)) == + NO(Fd(p)*F(q)) + NO(Fd(a)*F(b))) + assert (NO(Fd(i)*NO(F(j)*Fd(a))) == + NO(Fd(i)*F(j)*Fd(a))) + assert NO(1) == 1 + assert NO(i) == i + assert (NO(Fd(a)*Fd(b)*(F(c) + F(d))) == + NO(Fd(a)*Fd(b)*F(c)) + + NO(Fd(a)*Fd(b)*F(d))) + + assert NO(Fd(a)*F(b))._remove_brackets() == Fd(a)*F(b) + assert NO(F(j)*Fd(i))._remove_brackets() == F(j)*Fd(i) + + assert (NO(Fd(p)*F(q)).subs(Fd(p), Fd(a) + Fd(i)) == + NO(Fd(a)*F(q)) + NO(Fd(i)*F(q))) + assert (NO(Fd(p)*F(q)).subs(F(q), F(a) + F(i)) == + NO(Fd(p)*F(a)) + NO(Fd(p)*F(i))) + + expr = NO(Fd(p)*F(q))._remove_brackets() + assert wicks(expr) == NO(expr) + + assert NO(Fd(a)*F(b)) == - NO(F(b)*Fd(a)) + + no = NO(Fd(a)*F(i)*F(b)*Fd(j)) + l1 = list(no.iter_q_creators()) + assert l1 == [0, 1] + l2 = list(no.iter_q_annihilators()) + assert l2 == [3, 2] + no = NO(Fd(a)*Fd(i)) + assert no.has_q_creators == 1 + assert no.has_q_annihilators == -1 + assert str(no) == ':CreateFermion(a)*CreateFermion(i):' + assert repr(no) == 'NO(CreateFermion(a)*CreateFermion(i))' + assert latex(no) == r'\left\{{a^\dagger_{a}} {a^\dagger_{i}}\right\}' + raises(NotImplementedError, lambda: NO(Bd(p)*F(q))) + + +def test_sorting(): + i, j = symbols('i,j', below_fermi=True) + a, b = symbols('a,b', above_fermi=True) + p, q = symbols('p,q') + + # p, q + assert _sort_anticommuting_fermions([Fd(p), F(q)]) == ([Fd(p), F(q)], 0) + assert _sort_anticommuting_fermions([F(p), Fd(q)]) == ([Fd(q), F(p)], 1) + + # i, p + assert _sort_anticommuting_fermions([F(p), Fd(i)]) == ([F(p), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), F(p)]) == ([F(p), Fd(i)], 1) + assert _sort_anticommuting_fermions([Fd(p), Fd(i)]) == ([Fd(p), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), Fd(p)]) == ([Fd(p), Fd(i)], 1) + assert _sort_anticommuting_fermions([F(p), F(i)]) == ([F(i), F(p)], 1) + assert _sort_anticommuting_fermions([F(i), F(p)]) == ([F(i), F(p)], 0) + assert _sort_anticommuting_fermions([Fd(p), F(i)]) == ([F(i), Fd(p)], 1) + assert _sort_anticommuting_fermions([F(i), Fd(p)]) == ([F(i), Fd(p)], 0) + + # a, p + assert _sort_anticommuting_fermions([F(p), Fd(a)]) == ([Fd(a), F(p)], 1) + assert _sort_anticommuting_fermions([Fd(a), F(p)]) == ([Fd(a), F(p)], 0) + assert _sort_anticommuting_fermions([Fd(p), Fd(a)]) == ([Fd(a), Fd(p)], 1) + assert _sort_anticommuting_fermions([Fd(a), Fd(p)]) == ([Fd(a), Fd(p)], 0) + assert _sort_anticommuting_fermions([F(p), F(a)]) == ([F(p), F(a)], 0) + assert _sort_anticommuting_fermions([F(a), F(p)]) == ([F(p), F(a)], 1) + assert _sort_anticommuting_fermions([Fd(p), F(a)]) == ([Fd(p), F(a)], 0) + assert _sort_anticommuting_fermions([F(a), Fd(p)]) == ([Fd(p), F(a)], 1) + + # i, a + assert _sort_anticommuting_fermions([F(i), Fd(j)]) == ([F(i), Fd(j)], 0) + assert _sort_anticommuting_fermions([Fd(j), F(i)]) == ([F(i), Fd(j)], 1) + assert _sort_anticommuting_fermions([Fd(a), Fd(i)]) == ([Fd(a), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), Fd(a)]) == ([Fd(a), Fd(i)], 1) + assert _sort_anticommuting_fermions([F(a), F(i)]) == ([F(i), F(a)], 1) + assert _sort_anticommuting_fermions([F(i), F(a)]) == ([F(i), F(a)], 0) + + +def test_contraction(): + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + assert contraction(Fd(i), F(j)) == KroneckerDelta(i, j) + assert contraction(F(a), Fd(b)) == KroneckerDelta(a, b) + assert contraction(F(a), Fd(i)) == 0 + assert contraction(Fd(a), F(i)) == 0 + assert contraction(F(i), Fd(a)) == 0 + assert contraction(Fd(i), F(a)) == 0 + assert contraction(Fd(i), F(p)) == KroneckerDelta(i, p) + restr = evaluate_deltas(contraction(Fd(p), F(q))) + assert restr.is_only_below_fermi + restr = evaluate_deltas(contraction(F(p), Fd(q))) + assert restr.is_only_above_fermi + raises(ContractionAppliesOnlyToFermions, lambda: contraction(B(a), Fd(b))) + + +def test_evaluate_deltas(): + i, j, k = symbols('i,j,k') + + r = KroneckerDelta(i, j) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(i, k) + + r = KroneckerDelta(i, 0) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(i, 0) * KroneckerDelta(j, k) + + r = KroneckerDelta(1, j) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(1, k) + + r = KroneckerDelta(j, 2) * KroneckerDelta(k, j) + assert evaluate_deltas(r) == KroneckerDelta(2, k) + + r = KroneckerDelta(i, 0) * KroneckerDelta(i, j) * KroneckerDelta(j, 1) + assert evaluate_deltas(r) == 0 + + r = (KroneckerDelta(0, i) * KroneckerDelta(0, j) + * KroneckerDelta(1, j) * KroneckerDelta(1, j)) + assert evaluate_deltas(r) == 0 + + +def test_Tensors(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + p, q, r, s = symbols('p q r s') + + AT = AntiSymmetricTensor + assert AT('t', (a, b), (i, j)) == -AT('t', (b, a), (i, j)) + assert AT('t', (a, b), (i, j)) == AT('t', (b, a), (j, i)) + assert AT('t', (a, b), (i, j)) == -AT('t', (a, b), (j, i)) + assert AT('t', (a, a), (i, j)) == 0 + assert AT('t', (a, b), (i, i)) == 0 + assert AT('t', (a, b, c), (i, j)) == -AT('t', (b, a, c), (i, j)) + assert AT('t', (a, b, c), (i, j, k)) == AT('t', (b, a, c), (i, k, j)) + + tabij = AT('t', (a, b), (i, j)) + assert tabij.has(a) + assert tabij.has(b) + assert tabij.has(i) + assert tabij.has(j) + assert tabij.subs(b, c) == AT('t', (a, c), (i, j)) + assert (2*tabij).subs(i, c) == 2*AT('t', (a, b), (c, j)) + assert tabij.symbol == Symbol('t') + assert latex(tabij) == '{t^{ab}_{ij}}' + assert str(tabij) == 't((_a, _b),(_i, _j))' + + assert AT('t', (a, a), (i, j)).subs(a, b) == AT('t', (b, b), (i, j)) + assert AT('t', (a, i), (a, j)).subs(a, b) == AT('t', (b, i), (b, j)) + + +def test_fully_contracted(): + i, j, k, l = symbols('i j k l', below_fermi=True) + a, b, c, d = symbols('a b c d', above_fermi=True) + p, q, r, s = symbols('p q r s', cls=Dummy) + + Fock = (AntiSymmetricTensor('f', (p,), (q,))* + NO(Fd(p)*F(q))) + V = (AntiSymmetricTensor('v', (p, q), (r, s))* + NO(Fd(p)*Fd(q)*F(s)*F(r)))/4 + + Fai = wicks(NO(Fd(i)*F(a))*Fock, + keep_only_fully_contracted=True, + simplify_kronecker_deltas=True) + assert Fai == AntiSymmetricTensor('f', (a,), (i,)) + Vabij = wicks(NO(Fd(i)*Fd(j)*F(b)*F(a))*V, + keep_only_fully_contracted=True, + simplify_kronecker_deltas=True) + assert Vabij == AntiSymmetricTensor('v', (a, b), (i, j)) + + +def test_substitute_dummies_without_dummies(): + i, j = symbols('i,j') + assert substitute_dummies(att(i, j) + 2) == att(i, j) + 2 + assert substitute_dummies(att(i, j) + 1) == att(i, j) + 1 + + +def test_substitute_dummies_NO_operator(): + i, j = symbols('i j', cls=Dummy) + assert substitute_dummies(att(i, j)*NO(Fd(i)*F(j)) + - att(j, i)*NO(Fd(j)*F(i))) == 0 + + +def test_substitute_dummies_SQ_operator(): + i, j = symbols('i j', cls=Dummy) + assert substitute_dummies(att(i, j)*Fd(i)*F(j) + - att(j, i)*Fd(j)*F(i)) == 0 + + +def test_substitute_dummies_new_indices(): + i, j = symbols('i j', below_fermi=True, cls=Dummy) + a, b = symbols('a b', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + f = Function('f') + assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0 + + +def test_substitute_dummies_substitution_order(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + f = Function('f') + from sympy.utilities.iterables import variations + for permut in variations([i, j, k, l], 4): + assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0 + + +def test_dummy_order_inner_outer_lines_VT1T1T1(): + ii = symbols('i', below_fermi=True) + aa = symbols('a', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # Coupled-Cluster T1 terms with V*T1*T1*T1 + # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc} + exprs = [ + # permut v and t <=> swapping internal lines, equivalent + # irrespective of symmetries in v + v(k, l, c, d)*t(c, ii)*t(d, l)*t(aa, k), + v(l, k, c, d)*t(c, ii)*t(d, k)*t(aa, l), + v(k, l, d, c)*t(d, ii)*t(c, l)*t(aa, k), + v(l, k, d, c)*t(d, ii)*t(c, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_inner_outer_lines_VT1T1T1T1(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # Coupled-Cluster T2 terms with V*T1*T1*T1*T1 + exprs = [ + # permut t <=> swapping external lines, not equivalent + # except if v has certain symmetries. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, c, d)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l), + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l), + v(k, l, c, d)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + exprs = [ + # permut v <=> swapping external lines, not equivalent + # except if v has certain symmetries. + # + # Note that in contrast to above, these permutations have identical + # dummy order. That is because the proximity to external indices + # has higher influence on the canonical dummy ordering than the + # position of a dummy on the factors. In fact, the terms here are + # similar in structure as the result of the dummy substitutions above. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(l, k, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(l, k, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + exprs = [ + # permut t and v <=> swapping internal lines, equivalent. + # Canonical dummy order is different, and a consistent + # substitution reveals the equivalence. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, d, c)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l), + v(l, k, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l), + v(l, k, d, c)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_get_subNO(): + p, q, r = symbols('p,q,r') + assert NO(F(p)*F(q)*F(r)).get_subNO(1) == NO(F(p)*F(r)) + assert NO(F(p)*F(q)*F(r)).get_subNO(0) == NO(F(q)*F(r)) + assert NO(F(p)*F(q)*F(r)).get_subNO(2) == NO(F(p)*F(q)) + + +def test_equivalent_internal_lines_VT1T1(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ # permute v. Different dummy order. Not equivalent. + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, a, b)*t(a, i)*t(b, j), + v(i, j, b, a)*t(a, i)*t(b, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v. Different dummy order. Equivalent + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, b, a)*t(a, i)*t(b, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + exprs = [ # permute t. Same dummy order, not equivalent. + v(i, j, a, b)*t(a, i)*t(b, j), + v(i, j, a, b)*t(b, i)*t(a, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Different dummy order, equivalent + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, a, b)*t(a, j)*t(b, i), + v(i, j, b, a)*t(b, i)*t(a, j), + v(j, i, b, a)*t(b, j)*t(a, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT2conjT2(): + # this diagram requires special handling in TCE + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # v(abcd)t(abij)t(ijcd) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + # v(abcd)t(abij)t(jicd) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2conjT2_ambiguous_order(): + # These diagrams invokes _determine_ambiguous() because the + # dummies can not be ordered unambiguously by the key alone + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # v(abcd)t(abij)t(cdij) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + exprs = [ + # permute v. Same dummy order, not equivalent. + # + # This test show that the dummy order may not be sensitive to all + # index permutations. The following expressions have identical + # structure as the resulting terms from of the dummy substitutions + # in the test above. Here, all expressions have the same dummy + # order, so they cannot be simplified by means of dummy + # substitution. In order to simplify further, it is necessary to + # exploit symmetries in the objects, for instance if t or v is + # antisymmetric. + v(i, j, a, b)*t(a, b, i, j), + v(j, i, a, b)*t(a, b, i, j), + v(i, j, b, a)*t(a, b, i, j), + v(j, i, b, a)*t(a, b, i, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ + # permute t. + v(i, j, a, b)*t(a, b, i, j), + v(i, j, a, b)*t(b, a, i, j), + v(i, j, a, b)*t(a, b, j, i), + v(i, j, a, b)*t(b, a, j, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Relabelling of dummies should be equivalent. + v(i, j, a, b)*t(a, b, i, j), + v(j, i, a, b)*t(a, b, j, i), + v(i, j, b, a)*t(b, a, i, j), + v(j, i, b, a)*t(b, a, j, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_VT2T2(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(d, bb, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(d, bb, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(c, bb, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(c, bb, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + v(k, l, c, d)*t(c, aa, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(c, aa, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(d, aa, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(d, aa, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_pqrs(): + ii, jj = symbols('i j') + aa, bb = symbols('a b') + k, l = symbols('k l', cls=Dummy) + c, d = symbols('c d', cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_well_defined(): + aa, bb = symbols('a b', above_fermi=True) + k, l, m = symbols('k l m', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + + A = Function('A') + B = Function('B') + C = Function('C') + dums = _get_ordered_dummies + + # We go through all key components in the order of increasing priority, + # and consider only fully orderable expressions. Non-orderable expressions + # are tested elsewhere. + + # pos in first factor determines sort order + assert dums(A(k, l)*B(l, k)) == [k, l] + assert dums(A(l, k)*B(l, k)) == [l, k] + assert dums(A(k, l)*B(k, l)) == [k, l] + assert dums(A(l, k)*B(k, l)) == [l, k] + + # factors involving the index + assert dums(A(k, l)*B(l, m)*C(k, m)) == [l, k, m] + assert dums(A(k, l)*B(l, m)*C(m, k)) == [l, k, m] + assert dums(A(l, k)*B(l, m)*C(k, m)) == [l, k, m] + assert dums(A(l, k)*B(l, m)*C(m, k)) == [l, k, m] + assert dums(A(k, l)*B(m, l)*C(k, m)) == [l, k, m] + assert dums(A(k, l)*B(m, l)*C(m, k)) == [l, k, m] + assert dums(A(l, k)*B(m, l)*C(k, m)) == [l, k, m] + assert dums(A(l, k)*B(m, l)*C(m, k)) == [l, k, m] + + # same, but with factor order determined by non-dummies + assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, k, m)) == [l, k, m] + assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, m, k)) == [l, k, m] + assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, k, m)) == [l, k, m] + assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, m, k)) == [l, k, m] + assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, k, m)) == [l, k, m] + assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, m, k)) == [l, k, m] + assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, k, m)) == [l, k, m] + assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, m, k)) == [l, k, m] + + # index range + assert dums(A(p, c, k)*B(p, c, k)) == [k, c, p] + assert dums(A(p, k, c)*B(p, c, k)) == [k, c, p] + assert dums(A(c, k, p)*B(p, c, k)) == [k, c, p] + assert dums(A(c, p, k)*B(p, c, k)) == [k, c, p] + assert dums(A(k, c, p)*B(p, c, k)) == [k, c, p] + assert dums(A(k, p, c)*B(p, c, k)) == [k, c, p] + assert dums(B(p, c, k)*A(p, c, k)) == [k, c, p] + assert dums(B(p, k, c)*A(p, c, k)) == [k, c, p] + assert dums(B(c, k, p)*A(p, c, k)) == [k, c, p] + assert dums(B(c, p, k)*A(p, c, k)) == [k, c, p] + assert dums(B(k, c, p)*A(p, c, k)) == [k, c, p] + assert dums(B(k, p, c)*A(p, c, k)) == [k, c, p] + + +def test_dummy_order_ambiguous(): + aa, bb = symbols('a b', above_fermi=True) + i, j, k, l, m = symbols('i j k l m', below_fermi=True, cls=Dummy) + a, b, c, d, e = symbols('a b c d e', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + p5, p6, p7, p8 = symbols('p5 p6 p7 p8', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + h5, h6, h7, h8 = symbols('h5 h6 h7 h8', below_fermi=True, cls=Dummy) + + A = Function('A') + B = Function('B') + + from sympy.utilities.iterables import variations + + # A*A*A*A*B -- ordering of p5 and p4 is used to figure out the rest + template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*B(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # A*A*A*A*A -- an arbitrary index is assigned and the rest are figured out + template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*A(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # A*A*A -- ordering of p5 and p4 is used to figure out the rest + template = A(p1, p2, p4, p1)*A(p2, p3, p3, p5)*A(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def atv(*args): + return AntiSymmetricTensor('v', args[:2], args[2:] ) + + +def att(*args): + if len(args) == 4: + return AntiSymmetricTensor('t', args[:2], args[2:] ) + elif len(args) == 2: + return AntiSymmetricTensor('t', (args[0],), (args[1],)) + + +def test_dummy_order_inner_outer_lines_VT1T1T1_AT(): + ii = symbols('i', below_fermi=True) + aa = symbols('a', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + # Coupled-Cluster T1 terms with V*T1*T1*T1 + # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc} + exprs = [ + # permut v and t <=> swapping internal lines, equivalent + # irrespective of symmetries in v + atv(k, l, c, d)*att(c, ii)*att(d, l)*att(aa, k), + atv(l, k, c, d)*att(c, ii)*att(d, k)*att(aa, l), + atv(k, l, d, c)*att(d, ii)*att(c, l)*att(aa, k), + atv(l, k, d, c)*att(d, ii)*att(c, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_inner_outer_lines_VT1T1T1T1_AT(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + # Coupled-Cluster T2 terms with V*T1*T1*T1*T1 + # non-equivalent substitutions (change of sign) + exprs = [ + # permut t <=> swapping external lines + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l), + atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(aa, k)*att(bb, l), + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(bb, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == -substitute_dummies(permut) + + # equivalent substitutions + exprs = [ + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l), + # permut t <=> swapping external lines + atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(bb, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT1T1_AT(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + exprs = [ # permute v. Different dummy order. Not equivalent. + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, a, b)*att(a, i)*att(b, j), + atv(i, j, b, a)*att(a, i)*att(b, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v. Different dummy order. Equivalent + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, b, a)*att(a, i)*att(b, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + exprs = [ # permute t. Same dummy order, not equivalent. + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(i, j, a, b)*att(b, i)*att(a, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Different dummy order, equivalent + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, a, b)*att(a, j)*att(b, i), + atv(i, j, b, a)*att(b, i)*att(a, j), + atv(j, i, b, a)*att(b, j)*att(a, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT2conjT2_AT(): + # this diagram requires special handling in TCE + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + # atv(abcd)att(abij)att(ijcd) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # atv(abcd)att(abij)att(jicd) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2conjT2_ambiguous_order_AT(): + # These diagrams invokes _determine_ambiguous() because the + # dummies can not be ordered unambiguously by the key alone + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + # atv(abcd)att(abij)att(cdij) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2_AT(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + exprs = [ + # permute v. Same dummy order, not equivalent. + atv(i, j, a, b)*att(a, b, i, j), + atv(j, i, a, b)*att(a, b, i, j), + atv(i, j, b, a)*att(a, b, i, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ + # permute t. + atv(i, j, a, b)*att(a, b, i, j), + atv(i, j, a, b)*att(b, a, i, j), + atv(i, j, a, b)*att(a, b, j, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Relabelling of dummies should be equivalent. + atv(i, j, a, b)*att(a, b, i, j), + atv(j, i, a, b)*att(a, b, j, i), + atv(i, j, b, a)*att(b, a, i, j), + atv(j, i, b, a)*att(b, a, j, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_VT2T2_AT(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(d, bb, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(d, bb, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(c, bb, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(c, bb, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + atv(k, l, c, d)*att(c, aa, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(c, aa, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(d, aa, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(d, aa, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_pqrs_AT(): + ii, jj = symbols('i j') + aa, bb = symbols('a b') + k, l = symbols('k l', cls=Dummy) + c, d = symbols('c d', cls=Dummy) + + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_issue_19661(): + a = Symbol('0') + assert latex(Commutator(Bd(a)**2, B(a)) + ) == '- \\left[b_{0},{b^\\dagger_{0}}^{2}\\right]' + + +def test_canonical_ordering_AntiSymmetricTensor(): + v = symbols("v") + + c, d = symbols(('c','d'), above_fermi=True, + cls=Dummy) + k, l = symbols(('k','l'), below_fermi=True, + cls=Dummy) + + # formerly, the left gave either the left or the right + assert AntiSymmetricTensor(v, (k, l), (d, c) + ) == -AntiSymmetricTensor(v, (l, k), (d, c)) diff --git a/shared/package-files/56/5601d9ccc30211737ae7d85341024ff5016b274d6e1b91a8cf3d8ddf9e1ad79c/adaptive_max_pool3d.h b/shared/package-files/56/5601d9ccc30211737ae7d85341024ff5016b274d6e1b91a8cf3d8ddf9e1ad79c/adaptive_max_pool3d.h new file mode 100644 index 0000000000000000000000000000000000000000..54c0c4cef7440dc921e000afcf46596ad104bb28 --- /dev/null +++ b/shared/package-files/56/5601d9ccc30211737ae7d85341024ff5016b274d6e1b91a8cf3d8ddf9e1ad79c/adaptive_max_pool3d.h @@ -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_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple adaptive_max_pool3d_out(at::Tensor & out, at::Tensor & indices, const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::adaptive_max_pool3d_out::call(self, output_size, out, indices); +} +// aten::adaptive_max_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple adaptive_max_pool3d_outf(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out, at::Tensor & indices) { + return at::_ops::adaptive_max_pool3d_out::call(self, output_size, out, indices); +} + +// aten::adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor) +inline ::std::tuple adaptive_max_pool3d(const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::adaptive_max_pool3d::call(self, output_size); +} + +} diff --git a/shared/package-files/56/560514cf4d11e7a9d7f5d1e9ea6177ae9cc5cb3ac3765eb9dc4f7dd48c7836d8/amax_meta.h b/shared/package-files/56/560514cf4d11e7a9d7f5d1e9ea6177ae9cc5cb3ac3765eb9dc4f7dd48c7836d8/amax_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..d078523d9ed6ad27e77139b9c1a4db21f5773154 --- /dev/null +++ b/shared/package-files/56/560514cf4d11e7a9d7f5d1e9ea6177ae9cc5cb3ac3765eb9dc4f7dd48c7836d8/amax_meta.h @@ -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_amax : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, at::IntArrayRef dim, bool keepdim); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/56/5606f94c3c521c578b8cf4ad39b83078f7feb721db3dd890c5c6bda3c9bf76e8/kron.h b/shared/package-files/56/5606f94c3c521c578b8cf4ad39b83078f7feb721db3dd890c5c6bda3c9bf76e8/kron.h new file mode 100644 index 0000000000000000000000000000000000000000..02d7b1f58712de24c10718aab804f482b9d0925c --- /dev/null +++ b/shared/package-files/56/5606f94c3c521c578b8cf4ad39b83078f7feb721db3dd890c5c6bda3c9bf76e8/kron.h @@ -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::kron(Tensor self, Tensor other) -> Tensor +inline at::Tensor kron(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::kron::call(self, other); +} + +// aten::kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & kron_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::kron_out::call(self, other, out); +} +// aten::kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & kron_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::kron_out::call(self, other, out); +} + +} diff --git a/shared/package-files/56/560a5bc45f5cacf1c6a9c4e4b1a4d64362ceebb8bd9ec1eeb10454f4782592f2/neg_meta_dispatch.h b/shared/package-files/56/560a5bc45f5cacf1c6a9c4e4b1a4d64362ceebb8bd9ec1eeb10454f4782592f2/neg_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..690d24220b768a96ea9c14035037407b5bcbb617 --- /dev/null +++ b/shared/package-files/56/560a5bc45f5cacf1c6a9c4e4b1a4d64362ceebb8bd9ec1eeb10454f4782592f2/neg_meta_dispatch.h @@ -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 neg(const at::Tensor & self); +TORCH_API at::Tensor & neg_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & neg_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & neg_(at::Tensor & self); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/56/561401d9bf37a416f9e9df75be5f432708e7a7241797f088a23cc491ab3eae93/special_psi.h b/shared/package-files/56/561401d9bf37a416f9e9df75be5f432708e7a7241797f088a23cc491ab3eae93/special_psi.h new file mode 100644 index 0000000000000000000000000000000000000000..35ecd7f1dc24882da09d9e2dff9577a7d93d91d3 --- /dev/null +++ b/shared/package-files/56/561401d9bf37a416f9e9df75be5f432708e7a7241797f088a23cc491ab3eae93/special_psi.h @@ -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::special_psi(Tensor self) -> Tensor +inline at::Tensor special_psi(const at::Tensor & self) { + return at::_ops::special_psi::call(self); +} + +// aten::special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_psi_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_psi_out::call(self, out); +} +// aten::special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_psi_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_psi_out::call(self, out); +} + +} diff --git a/shared/package-files/56/561621dde9f6a27872264cd37a5cf7dbe53855cdd769dca34f039572db2a9442/parsing.py b/shared/package-files/56/561621dde9f6a27872264cd37a5cf7dbe53855cdd769dca34f039572db2a9442/parsing.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfa0f2baffd5ed45db19242c2afd00b6e5e23dc --- /dev/null +++ b/shared/package-files/56/561621dde9f6a27872264cd37a5cf7dbe53855cdd769dca34f039572db2a9442/parsing.py @@ -0,0 +1,198 @@ +""" +:func:`~pandas.eval` source string parsing functions +""" +from __future__ import annotations + +from io import StringIO +from keyword import iskeyword +import token +import tokenize +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import ( + Hashable, + Iterator, + ) + +# A token value Python's tokenizer probably will never use. +BACKTICK_QUOTED_STRING = 100 + + +def create_valid_python_identifier(name: str) -> str: + """ + Create valid Python identifiers from any string. + + Check if name contains any special characters. If it contains any + special characters, the special characters will be replaced by + a special string and a prefix is added. + + Raises + ------ + SyntaxError + If the returned name is not a Python valid identifier, raise an exception. + This can happen if there is a hashtag in the name, as the tokenizer will + than terminate and not find the backtick. + But also for characters that fall out of the range of (U+0001..U+007F). + """ + if name.isidentifier() and not iskeyword(name): + return name + + # Create a dict with the special characters and their replacement string. + # EXACT_TOKEN_TYPES contains these special characters + # token.tok_name contains a readable description of the replacement string. + special_characters_replacements = { + char: f"_{token.tok_name[tokval]}_" + for char, tokval in (tokenize.EXACT_TOKEN_TYPES.items()) + } + special_characters_replacements.update( + { + " ": "_", + "?": "_QUESTIONMARK_", + "!": "_EXCLAMATIONMARK_", + "$": "_DOLLARSIGN_", + "€": "_EUROSIGN_", + "°": "_DEGREESIGN_", + # Including quotes works, but there are exceptions. + "'": "_SINGLEQUOTE_", + '"': "_DOUBLEQUOTE_", + # Currently not possible. Terminates parser and won't find backtick. + # "#": "_HASH_", + } + ) + + name = "".join([special_characters_replacements.get(char, char) for char in name]) + name = f"BACKTICK_QUOTED_STRING_{name}" + + if not name.isidentifier(): + raise SyntaxError(f"Could not convert '{name}' to a valid Python identifier.") + + return name + + +def clean_backtick_quoted_toks(tok: tuple[int, str]) -> tuple[int, str]: + """ + Clean up a column name if surrounded by backticks. + + Backtick quoted string are indicated by a certain tokval value. If a string + is a backtick quoted token it will processed by + :func:`_create_valid_python_identifier` so that the parser can find this + string when the query is executed. + In this case the tok will get the NAME tokval. + + Parameters + ---------- + tok : tuple of int, str + ints correspond to the all caps constants in the tokenize module + + Returns + ------- + tok : Tuple[int, str] + Either the input or token or the replacement values + """ + toknum, tokval = tok + if toknum == BACKTICK_QUOTED_STRING: + return tokenize.NAME, create_valid_python_identifier(tokval) + return toknum, tokval + + +def clean_column_name(name: Hashable) -> Hashable: + """ + Function to emulate the cleaning of a backtick quoted name. + + The purpose for this function is to see what happens to the name of + identifier if it goes to the process of being parsed a Python code + inside a backtick quoted string and than being cleaned + (removed of any special characters). + + Parameters + ---------- + name : hashable + Name to be cleaned. + + Returns + ------- + name : hashable + Returns the name after tokenizing and cleaning. + + Notes + ----- + For some cases, a name cannot be converted to a valid Python identifier. + In that case :func:`tokenize_string` raises a SyntaxError. + In that case, we just return the name unmodified. + + If this name was used in the query string (this makes the query call impossible) + an error will be raised by :func:`tokenize_backtick_quoted_string` instead, + which is not caught and propagates to the user level. + """ + try: + tokenized = tokenize_string(f"`{name}`") + tokval = next(tokenized)[1] + return create_valid_python_identifier(tokval) + except SyntaxError: + return name + + +def tokenize_backtick_quoted_string( + token_generator: Iterator[tokenize.TokenInfo], source: str, string_start: int +) -> tuple[int, str]: + """ + Creates a token from a backtick quoted string. + + Moves the token_generator forwards till right after the next backtick. + + Parameters + ---------- + token_generator : Iterator[tokenize.TokenInfo] + The generator that yields the tokens of the source string (Tuple[int, str]). + The generator is at the first token after the backtick (`) + + source : str + The Python source code string. + + string_start : int + This is the start of backtick quoted string inside the source string. + + Returns + ------- + tok: Tuple[int, str] + The token that represents the backtick quoted string. + The integer is equal to BACKTICK_QUOTED_STRING (100). + """ + for _, tokval, start, _, _ in token_generator: + if tokval == "`": + string_end = start[1] + break + + return BACKTICK_QUOTED_STRING, source[string_start:string_end] + + +def tokenize_string(source: str) -> Iterator[tuple[int, str]]: + """ + Tokenize a Python source code string. + + Parameters + ---------- + source : str + The Python source code string. + + Returns + ------- + tok_generator : Iterator[Tuple[int, str]] + An iterator yielding all tokens with only toknum and tokval (Tuple[ing, str]). + """ + line_reader = StringIO(source).readline + token_generator = tokenize.generate_tokens(line_reader) + + # Loop over all tokens till a backtick (`) is found. + # Then, take all tokens till the next backtick to form a backtick quoted string + for toknum, tokval, start, _, _ in token_generator: + if tokval == "`": + try: + yield tokenize_backtick_quoted_string( + token_generator, source, string_start=start[1] + 1 + ) + except Exception as err: + raise SyntaxError(f"Failed to parse backticks in '{source}'.") from err + else: + yield toknum, tokval diff --git a/shared/package-files/56/561626b036664705579c43c117f0b62e9896fab6a73e7e84217588b8c6ba5da5/utils.py b/shared/package-files/56/561626b036664705579c43c117f0b62e9896fab6a73e7e84217588b8c6ba5da5/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..313836137c939febd86fdf710935850f4e03de4c --- /dev/null +++ b/shared/package-files/56/561626b036664705579c43c117f0b62e9896fab6a73e7e84217588b8c6ba5da5/utils.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import asyncio +import contextvars +import sys +import time +from asyncio import get_running_loop +from types import TracebackType +from typing import Any, Awaitable, Callable, TypeVar, cast + +__all__ = [ + "run_in_executor_with_context", + "call_soon_threadsafe", + "get_traceback_from_context", +] + +_T = TypeVar("_T") + + +def run_in_executor_with_context( + func: Callable[..., _T], + *args: Any, + loop: asyncio.AbstractEventLoop | None = None, +) -> Awaitable[_T]: + """ + Run a function in an executor, but make sure it uses the same contextvars. + This is required so that the function will see the right application. + + See also: https://bugs.python.org/issue34014 + """ + loop = loop or get_running_loop() + ctx: contextvars.Context = contextvars.copy_context() + + return loop.run_in_executor(None, ctx.run, func, *args) + + +def call_soon_threadsafe( + func: Callable[[], None], + max_postpone_time: float | None = None, + loop: asyncio.AbstractEventLoop | None = None, +) -> None: + """ + Wrapper around asyncio's `call_soon_threadsafe`. + + This takes a `max_postpone_time` which can be used to tune the urgency of + the method. + + Asyncio runs tasks in first-in-first-out. However, this is not what we + want for the render function of the prompt_toolkit UI. Rendering is + expensive, but since the UI is invalidated very often, in some situations + we render the UI too often, so much that the rendering CPU usage slows down + the rest of the processing of the application. (Pymux is an example where + we have to balance the CPU time spend on rendering the UI, and parsing + process output.) + However, we want to set a deadline value, for when the rendering should + happen. (The UI should stay responsive). + """ + loop2 = loop or get_running_loop() + + # If no `max_postpone_time` has been given, schedule right now. + if max_postpone_time is None: + loop2.call_soon_threadsafe(func) + return + + max_postpone_until = time.time() + max_postpone_time + + def schedule() -> None: + # When there are no other tasks scheduled in the event loop. Run it + # now. + # Notice: uvloop doesn't have this _ready attribute. In that case, + # always call immediately. + if not getattr(loop2, "_ready", []): + func() + return + + # If the timeout expired, run this now. + if time.time() > max_postpone_until: + func() + return + + # Schedule again for later. + loop2.call_soon_threadsafe(schedule) + + loop2.call_soon_threadsafe(schedule) + + +def get_traceback_from_context(context: dict[str, Any]) -> TracebackType | None: + """ + Get the traceback object from the context. + """ + exception = context.get("exception") + if exception: + if hasattr(exception, "__traceback__"): + return cast(TracebackType, exception.__traceback__) + else: + # call_exception_handler() is usually called indirectly + # from an except block. If it's not the case, the traceback + # is undefined... + return sys.exc_info()[2] + + return None diff --git a/shared/package-files/56/5617a58acd695eb243eff3df41bebed132dad542416661db58557344b8f73f45/_foreach_lgamma.h b/shared/package-files/56/5617a58acd695eb243eff3df41bebed132dad542416661db58557344b8f73f45/_foreach_lgamma.h new file mode 100644 index 0000000000000000000000000000000000000000..fc7042d4d3de6de2706fead6afcb6fdbb3a8c8b9 --- /dev/null +++ b/shared/package-files/56/5617a58acd695eb243eff3df41bebed132dad542416661db58557344b8f73f45/_foreach_lgamma.h @@ -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_lgamma(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_lgamma(at::TensorList self) { + return at::_ops::_foreach_lgamma::call(self); +} + +// aten::_foreach_lgamma_(Tensor(a!)[] self) -> () +inline void _foreach_lgamma_(at::TensorList self) { + return at::_ops::_foreach_lgamma_::call(self); +} + +// aten::_foreach_lgamma.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_lgamma_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_lgamma_out::call(self, out); +} +// aten::_foreach_lgamma.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_lgamma_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_lgamma_out::call(self, out); +} + +} diff --git a/shared/package-files/56/5617f82d17ea2e9edd13cb302362e600a17795fe993a30ba2f5d24d485c9f7a2/svm.h b/shared/package-files/56/5617f82d17ea2e9edd13cb302362e600a17795fe993a30ba2f5d24d485c9f7a2/svm.h new file mode 100644 index 0000000000000000000000000000000000000000..518872c67bc5ca70db197af18dae3a284746b25e --- /dev/null +++ b/shared/package-files/56/5617f82d17ea2e9edd13cb302362e600a17795fe993a30ba2f5d24d485c9f7a2/svm.h @@ -0,0 +1,176 @@ +#ifndef _LIBSVM_H +#define _LIBSVM_H + +#define LIBSVM_VERSION 310 + +#ifdef __cplusplus +extern "C" { +#endif +#include "_svm_cython_blas_helpers.h" + +struct svm_node +{ + int dim; + int ind; /* index. A bit redundant, but needed if using a + precomputed kernel */ + double *values; +}; + +struct svm_problem +{ + int l; + double *y; + struct svm_node *x; + double *W; /* instance weights */ +}; + + +struct svm_csr_node +{ + int index; + double value; +}; + +struct svm_csr_problem +{ + int l; + double *y; + struct svm_csr_node **x; + double *W; /* instance weights */ +}; + + +enum { C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR }; /* svm_type */ +enum { LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED }; /* kernel_type */ + +struct svm_parameter +{ + int svm_type; + int kernel_type; + int degree; /* for poly */ + double gamma; /* for poly/rbf/sigmoid */ + double coef0; /* for poly/sigmoid */ + + /* these are for training only */ + double cache_size; /* in MB */ + double eps; /* stopping criteria */ + double C; /* for C_SVC, EPSILON_SVR and NU_SVR */ + int nr_weight; /* for C_SVC */ + int *weight_label; /* for C_SVC */ + double* weight; /* for C_SVC */ + double nu; /* for NU_SVC, ONE_CLASS, and NU_SVR */ + double p; /* for EPSILON_SVR */ + int shrinking; /* use the shrinking heuristics */ + int probability; /* do probability estimates */ + int max_iter; /* ceiling on Solver runtime */ + int random_seed; /* seed for random number generator */ +}; + +// +// svm_model +// +struct svm_model +{ + struct svm_parameter param; /* parameter */ + int nr_class; /* number of classes, = 2 in regression/one class svm */ + int l; /* total #SV */ + struct svm_node *SV; /* SVs (SV[l]) */ + double **sv_coef; /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */ + int *n_iter; /* number of iterations run by the optimization routine to fit the model */ + + int *sv_ind; /* index of support vectors */ + + double *rho; /* constants in decision functions (rho[k*(k-1)/2]) */ + double *probA; /* pairwise probability information */ + double *probB; + + /* for classification only */ + + int *label; /* label of each class (label[k]) */ + int *nSV; /* number of SVs for each class (nSV[k]) */ + /* nSV[0] + nSV[1] + ... + nSV[k-1] = l */ + /* XXX */ + int free_sv; /* 1 if svm_model is created by svm_load_model*/ + /* 0 if svm_model is created by svm_train */ +}; + + +struct svm_csr_model +{ + struct svm_parameter param; /* parameter */ + int nr_class; /* number of classes, = 2 in regression/one class svm */ + int l; /* total #SV */ + struct svm_csr_node **SV; /* SVs (SV[l]) */ + double **sv_coef; /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */ + int *n_iter; /* number of iterations run by the optimization routine to fit the model */ + + int *sv_ind; /* index of support vectors */ + + double *rho; /* constants in decision functions (rho[k*(k-1)/2]) */ + double *probA; /* pairwise probability information */ + double *probB; + + /* for classification only */ + + int *label; /* label of each class (label[k]) */ + int *nSV; /* number of SVs for each class (nSV[k]) */ + /* nSV[0] + nSV[1] + ... + nSV[k-1] = l */ + /* XXX */ + int free_sv; /* 1 if svm_model is created by svm_load_model*/ + /* 0 if svm_model is created by svm_train */ +}; + +/* svm_ functions are defined by libsvm_template.cpp from generic versions in svm.cpp */ +struct svm_model *svm_train(const struct svm_problem *prob, const struct svm_parameter *param, int *status, BlasFunctions *blas_functions); +void svm_cross_validation(const struct svm_problem *prob, const struct svm_parameter *param, int nr_fold, double *target, BlasFunctions *blas_functions); + +int svm_save_model(const char *model_file_name, const struct svm_model *model); +struct svm_model *svm_load_model(const char *model_file_name); + +int svm_get_svm_type(const struct svm_model *model); +int svm_get_nr_class(const struct svm_model *model); +void svm_get_labels(const struct svm_model *model, int *label); +double svm_get_svr_probability(const struct svm_model *model); + +double svm_predict_values(const struct svm_model *model, const struct svm_node *x, double* dec_values, BlasFunctions *blas_functions); +double svm_predict(const struct svm_model *model, const struct svm_node *x, BlasFunctions *blas_functions); +double svm_predict_probability(const struct svm_model *model, const struct svm_node *x, double* prob_estimates, BlasFunctions *blas_functions); + +void svm_free_model_content(struct svm_model *model_ptr); +void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr); +void svm_destroy_param(struct svm_parameter *param); + +const char *svm_check_parameter(const struct svm_problem *prob, const struct svm_parameter *param); + +void svm_set_print_string_function(void (*print_func)(const char *)); + + +/* sparse version */ + +/* svm_csr_ functions are defined by libsvm_template.cpp from generic versions in svm.cpp */ +struct svm_csr_model *svm_csr_train(const struct svm_csr_problem *prob, const struct svm_parameter *param, int *status, BlasFunctions *blas_functions); +void svm_csr_cross_validation(const struct svm_csr_problem *prob, const struct svm_parameter *param, int nr_fold, double *target, BlasFunctions *blas_functions); + +int svm_csr_get_svm_type(const struct svm_csr_model *model); +int svm_csr_get_nr_class(const struct svm_csr_model *model); +void svm_csr_get_labels(const struct svm_csr_model *model, int *label); +double svm_csr_get_svr_probability(const struct svm_csr_model *model); + +double svm_csr_predict_values(const struct svm_csr_model *model, const struct svm_csr_node *x, double* dec_values, BlasFunctions *blas_functions); +double svm_csr_predict(const struct svm_csr_model *model, const struct svm_csr_node *x, BlasFunctions *blas_functions); +double svm_csr_predict_probability(const struct svm_csr_model *model, const struct svm_csr_node *x, double* prob_estimates, BlasFunctions *blas_functions); + +void svm_csr_free_model_content(struct svm_csr_model *model_ptr); +void svm_csr_free_and_destroy_model(struct svm_csr_model **model_ptr_ptr); +void svm_csr_destroy_param(struct svm_parameter *param); + +const char *svm_csr_check_parameter(const struct svm_csr_problem *prob, const struct svm_parameter *param); + +/* end sparse version */ + + +#ifdef __cplusplus +} +#endif + +#endif /* _LIBSVM_H */ diff --git a/shared/package-files/56/5618af3cbcd4d55b9d24b4d526f28e09fc91ddef58d1d2c1c1a79f25a1835a95/anomaly_mode.h b/shared/package-files/56/5618af3cbcd4d55b9d24b4d526f28e09fc91ddef58d1d2c1c1a79f25a1835a95/anomaly_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..e29d1bbf054cb55890d9186bf6bc5374f9ed8f1a --- /dev/null +++ b/shared/package-files/56/5618af3cbcd4d55b9d24b4d526f28e09fc91ddef58d1d2c1c1a79f25a1835a95/anomaly_mode.h @@ -0,0 +1,71 @@ +#pragma once + +#include +#include +#include + +namespace torch::autograd { + +// forward declaration of Node from function.h +struct Node; + +struct TORCH_API AnomalyMode { + static bool is_enabled() { + return _enabled; + } + static bool should_check_nan() { + return _check_nan; + } + static void set_enabled(bool enabled, bool check_nan = true) { + _enabled = enabled; + _check_nan = check_nan; + } + + private: + static bool _enabled; + static bool _check_nan; +}; + +/// A RAII guard that enables Anomaly Detection Mode. +/// +/// Anomaly detection mode is useful for debugging problems happening +/// in the backward, such as unexpectedly modified tensors or NaNs +/// occuring in the backward. +/// +/// The enabling of anomaly mode is global - as soon as there is one +/// such guard, it is enabled for all computation and threads. It also +/// comes with a significant performance penalty. +/// +/// Example: +/// @code +/// auto x = torch::tensor({1.}, torch::requires_grad()); +/// { +/// torch::autograd::DetectAnomalyGuard detect_anomaly; +/// auto x = torch::tensor({5.0}, torch::requires_grad()); +/// auto y = x * x; +/// auto z = y * y; +/// y += 1; +/// z.backward(); +/// } +/// @endcode +class TORCH_API DetectAnomalyGuard { + public: + DetectAnomalyGuard(bool check_nan = true); + ~DetectAnomalyGuard(); + + private: + bool prev_check_nan_; +}; + +struct TORCH_API AnomalyMetadata { + virtual ~AnomalyMetadata(); + virtual void store_stack(); + virtual void print_stack(const std::string& current_node_name); + virtual void assign_parent(const std::shared_ptr& parent_node); + + private: + std::string traceback_; + std::shared_ptr parent_; +}; + +} // namespace torch::autograd diff --git a/shared/package-files/56/561937fe8cd87fc3ec72d7bf56497fbbd000945c89c553697bc8c0aaf887945e/iterative.py b/shared/package-files/56/561937fe8cd87fc3ec72d7bf56497fbbd000945c89c553697bc8c0aaf887945e/iterative.py new file mode 100644 index 0000000000000000000000000000000000000000..4b91ef8fe4b37191e76710670eccd9557a397964 --- /dev/null +++ b/shared/package-files/56/561937fe8cd87fc3ec72d7bf56497fbbd000945c89c553697bc8c0aaf887945e/iterative.py @@ -0,0 +1,1045 @@ +import warnings +import numpy as np +from scipy.sparse.linalg._interface import LinearOperator +from .utils import make_system +from scipy.linalg import get_lapack_funcs + +__all__ = ['bicg', 'bicgstab', 'cg', 'cgs', 'gmres', 'qmr'] + + +def _get_atol_rtol(name, b_norm, atol=0., rtol=1e-5): + """ + A helper function to handle tolerance normalization + """ + if atol == 'legacy' or atol is None or atol < 0: + msg = (f"'scipy.sparse.linalg.{name}' called with invalid `atol`={atol}; " + "if set, `atol` must be a real, non-negative number.") + raise ValueError(msg) + + atol = max(float(atol), float(rtol) * float(b_norm)) + + return atol, rtol + + +def bicg(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None): + """Use BIConjugate Gradient iteration to solve ``Ax = b``. + + 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`` and ``A^T x`` using, e.g., + ``scipy.sparse.linalg.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 ``atol=0.`` and ``rtol=1e-5``. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M : {sparse array, ndarray, LinearOperator} + Preconditioner for `A`. It should approximate the + inverse of `A` (see Notes). Effective preconditioning dramatically improves the + rate of convergence, which implies that fewer iterations are needed + to reach a given error tolerance. + callback : function + User-supplied function to call after each iteration. It is called + as ``callback(xk)``, where ``xk`` is the current solution vector. + + Returns + ------- + x : ndarray + The converged solution. + info : integer + Provides convergence information: + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : parameter breakdown + + Notes + ----- + The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller + condition number than `A`, see [1]_ . + + References + ---------- + .. [1] "Preconditioner", Wikipedia, + https://en.wikipedia.org/wiki/Preconditioner + .. [2] "Biconjugate gradient method", Wikipedia, + https://en.wikipedia.org/wiki/Biconjugate_gradient_method + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import bicg + >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1.]]) + >>> b = np.array([2., 4., -1.]) + >>> x, exitCode = bicg(A, b, atol=1e-5) + >>> print(exitCode) # 0 indicates successful convergence + 0 + >>> np.allclose(A.dot(x), b) + True + """ + A, M, x, b, postprocess = make_system(A, M, x0, b) + bnrm2 = np.linalg.norm(b) + + atol, _ = _get_atol_rtol('bicg', bnrm2, atol, rtol) + + if bnrm2 == 0: + return postprocess(b), 0 + + n = len(b) + dotprod = np.vdot if np.iscomplexobj(x) else np.dot + + if maxiter is None: + maxiter = n*10 + + matvec, rmatvec = A.matvec, A.rmatvec + psolve, rpsolve = M.matvec, M.rmatvec + + rhotol = np.finfo(x.dtype.char).eps**2 + + # Dummy values to initialize vars, silence linter warnings + rho_prev, p, ptilde = None, None, None + + r = b - matvec(x) if x.any() else b.copy() + rtilde = r.copy() + + for iteration in range(maxiter): + if np.linalg.norm(r) < atol: # Are we done? + return postprocess(x), 0 + + z = psolve(r) + ztilde = rpsolve(rtilde) + # order matters in this dot product + rho_cur = dotprod(rtilde, z) + + if np.abs(rho_cur) < rhotol: # Breakdown case + return postprocess, -10 + + if iteration > 0: + beta = rho_cur / rho_prev + p *= beta + p += z + ptilde *= beta.conj() + ptilde += ztilde + else: # First spin + p = z.copy() + ptilde = ztilde.copy() + + q = matvec(p) + qtilde = rmatvec(ptilde) + rv = dotprod(ptilde, q) + + if rv == 0: + return postprocess(x), -11 + + alpha = rho_cur / rv + x += alpha*p + r -= alpha*q + rtilde -= alpha.conj()*qtilde + rho_prev = rho_cur + + if callback: + callback(x) + + else: # for loop exhausted + # Return incomplete progress + return postprocess(x), maxiter + + +def bicgstab(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, + callback=None): + """Use BIConjugate Gradient STABilized iteration to solve ``Ax = b``. + + 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`` and ``A^T x`` using, e.g., + ``scipy.sparse.linalg.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 ``atol=0.`` and ``rtol=1e-5``. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M : {sparse array, ndarray, LinearOperator} + Preconditioner for `A`. It should approximate the + inverse of `A` (see Notes). Effective preconditioning dramatically improves the + rate of convergence, which implies that fewer iterations are needed + to reach a given error tolerance. + callback : function + User-supplied function to call after each iteration. It is called + as ``callback(xk)``, where ``xk`` is the current solution vector. + + Returns + ------- + x : ndarray + The converged solution. + info : integer + Provides convergence information: + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : parameter breakdown + + Notes + ----- + The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller + condition number than `A`, see [1]_ . + + References + ---------- + .. [1] "Preconditioner", Wikipedia, + https://en.wikipedia.org/wiki/Preconditioner + .. [2] "Biconjugate gradient stabilized method", + Wikipedia, https://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import bicgstab + >>> R = np.array([[4, 2, 0, 1], + ... [3, 0, 0, 2], + ... [0, 1, 1, 1], + ... [0, 2, 1, 0]]) + >>> A = csc_array(R) + >>> b = np.array([-1, -0.5, -1, 2]) + >>> x, exit_code = bicgstab(A, b, atol=1e-5) + >>> print(exit_code) # 0 indicates successful convergence + 0 + >>> np.allclose(A.dot(x), b) + True + """ + A, M, x, b, postprocess = make_system(A, M, x0, b) + bnrm2 = np.linalg.norm(b) + + atol, _ = _get_atol_rtol('bicgstab', bnrm2, atol, rtol) + + if bnrm2 == 0: + return postprocess(b), 0 + + n = len(b) + + dotprod = np.vdot if np.iscomplexobj(x) else np.dot + + if maxiter is None: + maxiter = n*10 + + matvec = A.matvec + psolve = M.matvec + + # These values make no sense but coming from original Fortran code + # sqrt might have been meant instead. + rhotol = np.finfo(x.dtype.char).eps**2 + omegatol = rhotol + + # Dummy values to initialize vars, silence linter warnings + rho_prev, omega, alpha, p, v = None, None, None, None, None + + r = b - matvec(x) if x.any() else b.copy() + rtilde = r.copy() + + for iteration in range(maxiter): + if np.linalg.norm(r) < atol: # Are we done? + return postprocess(x), 0 + + rho = dotprod(rtilde, r) + if np.abs(rho) < rhotol: # rho breakdown + return postprocess(x), -10 + + if iteration > 0: + if np.abs(omega) < omegatol: # omega breakdown + return postprocess(x), -11 + + beta = (rho / rho_prev) * (alpha / omega) + p -= omega*v + p *= beta + p += r + else: # First spin + s = np.empty_like(r) + p = r.copy() + + phat = psolve(p) + v = matvec(phat) + rv = dotprod(rtilde, v) + if rv == 0: + return postprocess(x), -11 + alpha = rho / rv + r -= alpha*v + s[:] = r[:] + + if np.linalg.norm(s) < atol: + x += alpha*phat + return postprocess(x), 0 + + shat = psolve(s) + t = matvec(shat) + omega = dotprod(t, s) / dotprod(t, t) + x += alpha*phat + x += omega*shat + r -= omega*t + rho_prev = rho + + if callback: + callback(x) + + else: # for loop exhausted + # Return incomplete progress + return postprocess(x), maxiter + + +def cg(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None): + """Use Conjugate Gradient iteration to solve ``Ax = b``. + + Parameters + ---------- + A : {sparse array, ndarray, LinearOperator} + The real or complex N-by-N matrix of the linear system. + `A` must represent a hermitian, positive definite matrix. + Alternatively, `A` can be a linear operator which can + produce ``Ax`` using, e.g., + ``scipy.sparse.linalg.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 ``atol=0.`` and ``rtol=1e-5``. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M : {sparse array, ndarray, LinearOperator} + Preconditioner for `A`. `M` must represent a hermitian, positive definite + matrix. It should approximate the inverse of `A` (see Notes). + Effective preconditioning dramatically improves the + rate of convergence, which implies that fewer iterations are needed + to reach a given error tolerance. + callback : function + User-supplied function to call after each iteration. It is called + as ``callback(xk)``, where ``xk`` is the current solution vector. + + Returns + ------- + x : ndarray + The converged solution. + info : integer + Provides convergence information: + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + + Notes + ----- + The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller + condition number than `A`, see [2]_. + + References + ---------- + .. [1] "Conjugate Gradient Method, Wikipedia, + https://en.wikipedia.org/wiki/Conjugate_gradient_method + .. [2] "Preconditioner", + Wikipedia, https://en.wikipedia.org/wiki/Preconditioner + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import cg + >>> P = np.array([[4, 0, 1, 0], + ... [0, 5, 0, 0], + ... [1, 0, 3, 2], + ... [0, 0, 2, 4]]) + >>> A = csc_array(P) + >>> b = np.array([-1, -0.5, -1, 2]) + >>> x, exit_code = cg(A, b, atol=1e-5) + >>> print(exit_code) # 0 indicates successful convergence + 0 + >>> np.allclose(A.dot(x), b) + True + """ + A, M, x, b, postprocess = make_system(A, M, x0, b) + bnrm2 = np.linalg.norm(b) + + atol, _ = _get_atol_rtol('cg', bnrm2, atol, rtol) + + if bnrm2 == 0: + return postprocess(b), 0 + + n = len(b) + + if maxiter is None: + maxiter = n*10 + + dotprod = np.vdot if np.iscomplexobj(x) else np.dot + + matvec = A.matvec + psolve = M.matvec + r = b - matvec(x) if x.any() else b.copy() + + # Dummy value to initialize var, silences warnings + rho_prev, p = None, None + + for iteration in range(maxiter): + if np.linalg.norm(r) < atol: # Are we done? + return postprocess(x), 0 + + z = psolve(r) + rho_cur = dotprod(r, z) + if iteration > 0: + beta = rho_cur / rho_prev + p *= beta + p += z + else: # First spin + p = np.empty_like(r) + p[:] = z[:] + + q = matvec(p) + alpha = rho_cur / dotprod(p, q) + x += alpha*p + r -= alpha*q + rho_prev = rho_cur + + if callback: + callback(x) + + else: # for loop exhausted + # Return incomplete progress + return postprocess(x), maxiter + + +def cgs(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None): + """Use Conjugate Gradient Squared iteration to solve ``Ax = b``. + + Parameters + ---------- + A : {sparse array, ndarray, LinearOperator} + The real-valued N-by-N matrix of the linear system. + Alternatively, `A` can be a linear operator which can + produce ``Ax`` using, e.g., + ``scipy.sparse.linalg.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 ``atol=0.`` and ``rtol=1e-5``. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M : {sparse array, ndarray, LinearOperator} + Preconditioner for ``A``. It should approximate the + inverse of `A` (see Notes). Effective preconditioning dramatically improves the + rate of convergence, which implies that fewer iterations are needed + to reach a given error tolerance. + callback : function + User-supplied function to call after each iteration. It is called + as ``callback(xk)``, where ``xk`` is the current solution vector. + + Returns + ------- + x : ndarray + The converged solution. + info : integer + Provides convergence information: + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : parameter breakdown + + Notes + ----- + The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller + condition number than `A`, see [1]_. + + References + ---------- + .. [1] "Preconditioner", Wikipedia, + https://en.wikipedia.org/wiki/Preconditioner + .. [2] "Conjugate gradient squared", Wikipedia, + https://en.wikipedia.org/wiki/Conjugate_gradient_squared_method + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import cgs + >>> R = np.array([[4, 2, 0, 1], + ... [3, 0, 0, 2], + ... [0, 1, 1, 1], + ... [0, 2, 1, 0]]) + >>> A = csc_array(R) + >>> b = np.array([-1, -0.5, -1, 2]) + >>> x, exit_code = cgs(A, b) + >>> print(exit_code) # 0 indicates successful convergence + 0 + >>> np.allclose(A.dot(x), b) + True + """ + A, M, x, b, postprocess = make_system(A, M, x0, b) + bnrm2 = np.linalg.norm(b) + + atol, _ = _get_atol_rtol('cgs', bnrm2, atol, rtol) + + if bnrm2 == 0: + return postprocess(b), 0 + + n = len(b) + + dotprod = np.vdot if np.iscomplexobj(x) else np.dot + + if maxiter is None: + maxiter = n*10 + + matvec = A.matvec + psolve = M.matvec + + rhotol = np.finfo(x.dtype.char).eps**2 + + r = b - matvec(x) if x.any() else b.copy() + + rtilde = r.copy() + bnorm = np.linalg.norm(b) + if bnorm == 0: + bnorm = 1 + + # Dummy values to initialize vars, silence linter warnings + rho_prev, p, u, q = None, None, None, None + + for iteration in range(maxiter): + rnorm = np.linalg.norm(r) + if rnorm < atol: # Are we done? + return postprocess(x), 0 + + rho_cur = dotprod(rtilde, r) + if np.abs(rho_cur) < rhotol: # Breakdown case + return postprocess, -10 + + if iteration > 0: + beta = rho_cur / rho_prev + + # u = r + beta * q + # p = u + beta * (q + beta * p); + u[:] = r[:] + u += beta*q + + p *= beta + p += q + p *= beta + p += u + + else: # First spin + p = r.copy() + u = r.copy() + q = np.empty_like(r) + + phat = psolve(p) + vhat = matvec(phat) + rv = dotprod(rtilde, vhat) + + if rv == 0: # Dot product breakdown + return postprocess(x), -11 + + alpha = rho_cur / rv + q[:] = u[:] + q -= alpha*vhat + uhat = psolve(u + q) + x += alpha*uhat + + # Due to numerical error build-up the actual residual is computed + # instead of the following two lines that were in the original + # FORTRAN templates, still using a single matvec. + + # qhat = matvec(uhat) + # r -= alpha*qhat + r = b - matvec(x) + + rho_prev = rho_cur + + if callback: + callback(x) + + else: # for loop exhausted + # Return incomplete progress + return postprocess(x), maxiter + + +def gmres(A, b, x0=None, *, rtol=1e-5, atol=0., restart=None, maxiter=None, M=None, + callback=None, callback_type=None): + """ + Use Generalized Minimal RESidual iteration to solve ``Ax = b``. + + 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., + ``scipy.sparse.linalg.LinearOperator``. + b : ndarray + Right hand side of the linear system. Has shape (N,) or (N,1). + x0 : ndarray + Starting guess for the solution (a vector of zeros by default). + atol, rtol : float + Parameters for the convergence test. For convergence, + ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied. + The default is ``atol=0.`` and ``rtol=1e-5``. + restart : int, optional + Number of iterations between restarts. Larger values increase + iteration cost, but may be necessary for convergence. + If omitted, ``min(20, n)`` is used. + maxiter : int, optional + Maximum number of iterations (restart cycles). Iteration will stop + after maxiter steps even if the specified tolerance has not been + achieved. See `callback_type`. + M : {sparse array, ndarray, LinearOperator} + Inverse of the preconditioner of `A`. `M` should approximate the + inverse of `A` and be easy to solve for (see Notes). Effective + preconditioning dramatically improves the rate of convergence, + which implies that fewer iterations are needed to reach a given + error tolerance. By default, no preconditioner is used. + In this implementation, left preconditioning is used, + and the preconditioned residual is minimized. However, the final + convergence is tested with respect to the ``b - A @ x`` residual. + callback : function + User-supplied function to call after each iteration. It is called + as ``callback(args)``, where ``args`` are selected by `callback_type`. + callback_type : {'x', 'pr_norm', 'legacy'}, optional + Callback function argument requested: + - ``x``: current iterate (ndarray), called on every restart + - ``pr_norm``: relative (preconditioned) residual norm (float), + called on every inner iteration + - ``legacy`` (default): same as ``pr_norm``, but also changes the + meaning of `maxiter` to count inner iterations instead of restart + cycles. + + This keyword has no effect if `callback` is not set. + + Returns + ------- + x : ndarray + The converged solution. + info : int + Provides convergence information: + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + + See Also + -------- + LinearOperator + + Notes + ----- + A preconditioner, P, is chosen such that P is close to A but easy to solve + for. The preconditioner parameter required by this routine is + ``M = P^-1``. The inverse should preferably not be calculated + explicitly. Rather, use the following template to produce M:: + + # Construct a linear operator that computes P^-1 @ x. + import scipy.sparse.linalg as spla + M_x = lambda x: spla.spsolve(P, x) + M = spla.LinearOperator((n, n), M_x) + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import gmres + >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float) + >>> b = np.array([2, 4, -1], dtype=float) + >>> x, exitCode = gmres(A, b, atol=1e-5) + >>> print(exitCode) # 0 indicates successful convergence + 0 + >>> np.allclose(A.dot(x), b) + True + """ + if callback is not None and callback_type is None: + # Warn about 'callback_type' semantic changes. + # Probably should be removed only in far future, Scipy 2.0 or so. + msg = ("scipy.sparse.linalg.gmres called without specifying " + "`callback_type`. The default value will be changed in" + " a future release. For compatibility, specify a value " + "for `callback_type` explicitly, e.g., " + "``gmres(..., callback_type='pr_norm')``, or to retain the " + "old behavior ``gmres(..., callback_type='legacy')``" + ) + warnings.warn(msg, category=DeprecationWarning, stacklevel=3) + + if callback_type is None: + callback_type = 'legacy' + + if callback_type not in ('x', 'pr_norm', 'legacy'): + raise ValueError(f"Unknown callback_type: {callback_type!r}") + + if callback is None: + callback_type = None + + A, M, x, b, postprocess = make_system(A, M, x0, b) + matvec = A.matvec + psolve = M.matvec + n = len(b) + bnrm2 = np.linalg.norm(b) + + atol, _ = _get_atol_rtol('gmres', bnrm2, atol, rtol) + + if bnrm2 == 0: + return postprocess(b), 0 + + eps = np.finfo(x.dtype.char).eps + + dotprod = np.vdot if np.iscomplexobj(x) else np.dot + + if maxiter is None: + maxiter = n*10 + + if restart is None: + restart = 20 + restart = min(restart, n) + + Mb_nrm2 = np.linalg.norm(psolve(b)) + + # ==================================================== + # =========== Tolerance control from gh-8400 ========= + # ==================================================== + # Tolerance passed to GMRESREVCOM applies to the inner + # iteration and deals with the left-preconditioned + # residual. + ptol_max_factor = 1. + ptol = Mb_nrm2 * min(ptol_max_factor, atol / bnrm2) + presid = 0. + # ==================================================== + lartg = get_lapack_funcs('lartg', dtype=x.dtype) + + # allocate internal variables + v = np.empty([restart+1, n], dtype=x.dtype) + h = np.zeros([restart, restart+1], dtype=x.dtype) + givens = np.zeros([restart, 2], dtype=x.dtype) + + # legacy iteration count + inner_iter = 0 + + for iteration in range(maxiter): + if iteration == 0: + r = b - matvec(x) if x.any() else b.copy() + if np.linalg.norm(r) < atol: # Are we done? + return postprocess(x), 0 + + v[0, :] = psolve(r) + tmp = np.linalg.norm(v[0, :]) + v[0, :] *= (1 / tmp) + # RHS of the Hessenberg problem + S = np.zeros(restart+1, dtype=x.dtype) + S[0] = tmp + + breakdown = False + for col in range(restart): + av = matvec(v[col, :]) + w = psolve(av) + + # Modified Gram-Schmidt + h0 = np.linalg.norm(w) + for k in range(col+1): + tmp = dotprod(v[k, :], w) + h[col, k] = tmp + w -= tmp*v[k, :] + + h1 = np.linalg.norm(w) + h[col, col + 1] = h1 + v[col + 1, :] = w[:] + + # Exact solution indicator + if h1 <= eps*h0: + h[col, col + 1] = 0 + breakdown = True + else: + v[col + 1, :] *= (1 / h1) + + # apply past Givens rotations to current h column + for k in range(col): + c, s = givens[k, 0], givens[k, 1] + n0, n1 = h[col, [k, k+1]] + h[col, [k, k + 1]] = [c*n0 + s*n1, -s.conj()*n0 + c*n1] + + # get and apply current rotation to h and S + c, s, mag = lartg(h[col, col], h[col, col+1]) + givens[col, :] = [c, s] + h[col, [col, col+1]] = mag, 0 + + # S[col+1] component is always 0 + tmp = -np.conjugate(s)*S[col] + S[[col, col + 1]] = [c*S[col], tmp] + presid = np.abs(tmp) + inner_iter += 1 + + if callback_type in ('legacy', 'pr_norm'): + callback(presid / bnrm2) + # Legacy behavior + if callback_type == 'legacy' and inner_iter == maxiter: + break + if presid <= ptol or breakdown: + break + + # Solve h(col, col) upper triangular system and allow pseudo-solve + # singular cases as in (but without the f2py copies): + # y = trsv(h[:col+1, :col+1].T, S[:col+1]) + + if h[col, col] == 0: + S[col] = 0 + + y = np.zeros([col+1], dtype=x.dtype) + y[:] = S[:col+1] + for k in range(col, 0, -1): + if y[k] != 0: + y[k] /= h[k, k] + tmp = y[k] + y[:k] -= tmp*h[k, :k] + if y[0] != 0: + y[0] /= h[0, 0] + + x += y @ v[:col+1, :] + + r = b - matvec(x) + rnorm = np.linalg.norm(r) + + # Legacy exit + if callback_type == 'legacy' and inner_iter == maxiter: + return postprocess(x), 0 if rnorm <= atol else maxiter + + if callback_type == 'x': + callback(x) + + if rnorm <= atol: + break + elif breakdown: + # Reached breakdown (= exact solution), but the external + # tolerance check failed. Bail out with failure. + break + elif presid <= ptol: + # Inner loop passed but outer didn't + ptol_max_factor = max(eps, 0.25 * ptol_max_factor) + else: + ptol_max_factor = min(1.0, 1.5 * ptol_max_factor) + + ptol = presid * min(ptol_max_factor, atol / rnorm) + + info = 0 if (rnorm <= atol) else maxiter + return postprocess(x), info + + +def qmr(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M1=None, M2=None, + callback=None): + """Use Quasi-Minimal Residual iteration to solve ``Ax = b``. + + Parameters + ---------- + A : {sparse array, ndarray, LinearOperator} + The real-valued N-by-N matrix of the linear system. + Alternatively, ``A`` can be a linear operator which can + produce ``Ax`` and ``A^T x`` using, e.g., + ``scipy.sparse.linalg.LinearOperator``. + b : ndarray + Right hand side of the linear system. Has shape (N,) or (N,1). + x0 : ndarray + Starting guess for the solution. + atol, rtol : float, optional + Parameters for the convergence test. For convergence, + ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied. + The default is ``atol=0.`` and ``rtol=1e-5``. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M1 : {sparse array, ndarray, LinearOperator} + Left preconditioner for A. + M2 : {sparse array, ndarray, LinearOperator} + Right preconditioner for A. Used together with the left + preconditioner M1. The matrix M1@A@M2 should have better + conditioned than A alone. + callback : function + User-supplied function to call after each iteration. It is called + as callback(xk), where xk is the current solution vector. + + Returns + ------- + x : ndarray + The converged solution. + info : integer + Provides convergence information: + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : parameter breakdown + + See Also + -------- + LinearOperator + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import qmr + >>> A = csc_array([[3., 2., 0.], [1., -1., 0.], [0., 5., 1.]]) + >>> b = np.array([2., 4., -1.]) + >>> x, exitCode = qmr(A, b, atol=1e-5) + >>> print(exitCode) # 0 indicates successful convergence + 0 + >>> np.allclose(A.dot(x), b) + True + """ + A_ = A + A, M, x, b, postprocess = make_system(A, None, x0, b) + bnrm2 = np.linalg.norm(b) + + atol, _ = _get_atol_rtol('qmr', bnrm2, atol, rtol) + + if bnrm2 == 0: + return postprocess(b), 0 + + if M1 is None and M2 is None: + if hasattr(A_, 'psolve'): + def left_psolve(b): + return A_.psolve(b, 'left') + + def right_psolve(b): + return A_.psolve(b, 'right') + + def left_rpsolve(b): + return A_.rpsolve(b, 'left') + + def right_rpsolve(b): + return A_.rpsolve(b, 'right') + M1 = LinearOperator(A.shape, + matvec=left_psolve, + rmatvec=left_rpsolve) + M2 = LinearOperator(A.shape, + matvec=right_psolve, + rmatvec=right_rpsolve) + else: + def id(b): + return b + M1 = LinearOperator(A.shape, matvec=id, rmatvec=id) + M2 = LinearOperator(A.shape, matvec=id, rmatvec=id) + + n = len(b) + if maxiter is None: + maxiter = n*10 + + dotprod = np.vdot if np.iscomplexobj(x) else np.dot + + rhotol = np.finfo(x.dtype.char).eps + betatol = rhotol + gammatol = rhotol + deltatol = rhotol + epsilontol = rhotol + xitol = rhotol + + r = b - A.matvec(x) if x.any() else b.copy() + + vtilde = r.copy() + y = M1.matvec(vtilde) + rho = np.linalg.norm(y) + wtilde = r.copy() + z = M2.rmatvec(wtilde) + xi = np.linalg.norm(z) + gamma, eta, theta = 1, -1, 0 + v = np.empty_like(vtilde) + w = np.empty_like(wtilde) + + # Dummy values to initialize vars, silence linter warnings + epsilon, q, d, p, s = None, None, None, None, None + + for iteration in range(maxiter): + if np.linalg.norm(r) < atol: # Are we done? + return postprocess(x), 0 + if np.abs(rho) < rhotol: # rho breakdown + return postprocess(x), -10 + if np.abs(xi) < xitol: # xi breakdown + return postprocess(x), -15 + + v[:] = vtilde[:] + v *= (1 / rho) + y *= (1 / rho) + w[:] = wtilde[:] + w *= (1 / xi) + z *= (1 / xi) + delta = dotprod(z, y) + + if np.abs(delta) < deltatol: # delta breakdown + return postprocess(x), -13 + + ytilde = M2.matvec(y) + ztilde = M1.rmatvec(z) + + if iteration > 0: + ytilde -= (xi * delta / epsilon) * p + p[:] = ytilde[:] + ztilde -= (rho * (delta / epsilon).conj()) * q + q[:] = ztilde[:] + else: # First spin + p = ytilde.copy() + q = ztilde.copy() + + ptilde = A.matvec(p) + epsilon = dotprod(q, ptilde) + if np.abs(epsilon) < epsilontol: # epsilon breakdown + return postprocess(x), -14 + + beta = epsilon / delta + if np.abs(beta) < betatol: # beta breakdown + return postprocess(x), -11 + + vtilde[:] = ptilde[:] + vtilde -= beta*v + y = M1.matvec(vtilde) + + rho_prev = rho + rho = np.linalg.norm(y) + wtilde[:] = w[:] + wtilde *= - beta.conj() + wtilde += A.rmatvec(q) + z = M2.rmatvec(wtilde) + xi = np.linalg.norm(z) + gamma_prev = gamma + theta_prev = theta + theta = rho / (gamma_prev * np.abs(beta)) + gamma = 1 / np.sqrt(1 + theta**2) + + if np.abs(gamma) < gammatol: # gamma breakdown + return postprocess(x), -12 + + eta *= -(rho_prev / beta) * (gamma / gamma_prev)**2 + + if iteration > 0: + d *= (theta_prev * gamma) ** 2 + d += eta*p + s *= (theta_prev * gamma) ** 2 + s += eta*ptilde + else: + d = p.copy() + d *= eta + s = ptilde.copy() + s *= eta + + x += d + r -= s + + if callback: + callback(x) + + else: # for loop exhausted + # Return incomplete progress + return postprocess(x), maxiter diff --git a/shared/package-files/56/561ec7f24a961f85fc6b7557d976765737bdb2bc096af90d1c0671749533fdb9/backend_qt5agg.py b/shared/package-files/56/561ec7f24a961f85fc6b7557d976765737bdb2bc096af90d1c0671749533fdb9/backend_qt5agg.py new file mode 100644 index 0000000000000000000000000000000000000000..8a92fd5135d5a3f4b05b3a71d1089e15d031fd59 --- /dev/null +++ b/shared/package-files/56/561ec7f24a961f85fc6b7557d976765737bdb2bc096af90d1c0671749533fdb9/backend_qt5agg.py @@ -0,0 +1,14 @@ +""" +Render to qt from agg +""" +from .. import backends + +backends._QT_FORCE_QT5_BINDING = True +from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611 + _BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT, + FigureCanvasAgg, FigureCanvasQT) + + +@_BackendQTAgg.export +class _BackendQT5Agg(_BackendQTAgg): + pass diff --git a/shared/package-files/56/562173cf3e5a16d3dc69ef89fd17b99d9aefbd1789fc63443d84f01b855ef8cc/_reshape_copy.h b/shared/package-files/56/562173cf3e5a16d3dc69ef89fd17b99d9aefbd1789fc63443d84f01b855ef8cc/_reshape_copy.h new file mode 100644 index 0000000000000000000000000000000000000000..58df5f06892d8e4e784d4d59a197dda98b40c1dc --- /dev/null +++ b/shared/package-files/56/562173cf3e5a16d3dc69ef89fd17b99d9aefbd1789fc63443d84f01b855ef8cc/_reshape_copy.h @@ -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::_reshape_copy(Tensor self, SymInt[] size) -> Tensor +inline at::Tensor _reshape_copy(const at::Tensor & self, at::IntArrayRef size) { + return at::_ops::_reshape_copy::call(self, c10::fromIntArrayRefSlow(size)); +} +namespace symint { + template ::value>> + at::Tensor _reshape_copy(const at::Tensor & self, at::IntArrayRef size) { + return at::_ops::_reshape_copy::call(self, c10::fromIntArrayRefSlow(size)); + } +} + +// aten::_reshape_copy(Tensor self, SymInt[] size) -> Tensor +inline at::Tensor _reshape_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size) { + return at::_ops::_reshape_copy::call(self, size); +} +namespace symint { + template ::value>> + at::Tensor _reshape_copy(const at::Tensor & self, c10::SymIntArrayRef size) { + return at::_ops::_reshape_copy::call(self, size); + } +} + +} diff --git a/shared/package-files/56/5621b7f0f809b08853df1680aee82fc344cf3fa556a0fd95263ec51085b2a648/_unix.py b/shared/package-files/56/5621b7f0f809b08853df1680aee82fc344cf3fa556a0fd95263ec51085b2a648/_unix.py new file mode 100644 index 0000000000000000000000000000000000000000..93ce3be58fbea2a736072cddb0dc5d6454395cc2 --- /dev/null +++ b/shared/package-files/56/5621b7f0f809b08853df1680aee82fc344cf3fa556a0fd95263ec51085b2a648/_unix.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import os +import sys +from contextlib import suppress +from errno import ENOSYS +from typing import cast + +from ._api import BaseFileLock +from ._util import ensure_directory_exists + +#: a flag to indicate if the fcntl API is available +has_fcntl = False +if sys.platform == "win32": # pragma: win32 cover + + class UnixFileLock(BaseFileLock): + """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.""" + + def _acquire(self) -> None: + raise NotImplementedError + + def _release(self) -> None: + raise NotImplementedError + +else: # pragma: win32 no cover + try: + import fcntl + except ImportError: + pass + else: + has_fcntl = True + + class UnixFileLock(BaseFileLock): + """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.""" + + def _acquire(self) -> None: + ensure_directory_exists(self.lock_file) + open_flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC + fd = os.open(self.lock_file, open_flags, self._context.mode) + with suppress(PermissionError): # This locked is not owned by this UID + os.fchmod(fd, self._context.mode) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as exception: + os.close(fd) + if exception.errno == ENOSYS: # NotImplemented error + msg = "FileSystem does not appear to support flock; user SoftFileLock instead" + raise NotImplementedError(msg) from exception + else: + self._context.lock_file_fd = fd + + def _release(self) -> None: + # Do not remove the lockfile: + # https://github.com/tox-dev/py-filelock/issues/31 + # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition + fd = cast(int, self._context.lock_file_fd) + self._context.lock_file_fd = None + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + + +__all__ = [ + "has_fcntl", + "UnixFileLock", +] diff --git a/shared/package-files/56/56243a12c4fe44781e453d01d2388a4dfbcfe0107b49a7010b64656cd569a966/kernel_regression.py b/shared/package-files/56/56243a12c4fe44781e453d01d2388a4dfbcfe0107b49a7010b64656cd569a966/kernel_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..091f323d49c2d394fd29a23cb71e1040a0bda182 --- /dev/null +++ b/shared/package-files/56/56243a12c4fe44781e453d01d2388a4dfbcfe0107b49a7010b64656cd569a966/kernel_regression.py @@ -0,0 +1,1205 @@ +""" +Multivariate Conditional and Unconditional Kernel Regression +with Mixed Data Types + +References +---------- +[1] Racine, J., Li, Q. Nonparametric econometrics: theory and practice. + Princeton University Press. (2007) +[2] Racine, Jeff. "Nonparametric Econometrics: A Primer," Foundation + and Trends in Econometrics: Vol 3: No 1, pp1-88. (2008) + http://dx.doi.org/10.1561/0800000009 +[3] Racine, J., Li, Q. "Nonparametric Estimation of Distributions + with Categorical and Continuous Data." Working Paper. (2000) +[4] Racine, J. Li, Q. "Kernel Estimation of Multivariate Conditional + Distributions Annals of Economics and Finance 5, 211-235 (2004) +[5] Liu, R., Yang, L. "Kernel estimation of multivariate + cumulative distribution function." + Journal of Nonparametric Statistics (2008) +[6] Li, R., Ju, G. "Nonparametric Estimation of Multivariate CDF + with Categorical and Continuous Data." Working Paper +[7] Li, Q., Racine, J. "Cross-validated local linear nonparametric + regression" Statistica Sinica 14(2004), pp. 485-512 +[8] Racine, J.: "Consistent Significance Testing for Nonparametric + Regression" Journal of Business & Economics Statistics +[9] Racine, J., Hart, J., Li, Q., "Testing the Significance of + Categorical Predictor Variables in Nonparametric Regression + Models", 2006, Econometric Reviews 25, 523-544 + +""" + +from statsmodels.compat.pandas import deprecate_kwarg + +# TODO: make default behavior efficient=True above a certain n_obs +import copy +import warnings + +import numpy as np +from scipy import optimize +from scipy.stats.mstats import mquantiles + +from ._kernel_base import ( + EstimatorSettings, + GenericKDE, + LeaveOneOut, + _adjust_shape, + _compute_min_std_IQR, + _get_type_pos, + gpke, + initialize_generator, + kernel_func, +) + +__all__ = ["KernelCensoredReg", "KernelReg"] + + +class KernelReg(GenericKDE): + """ + Nonparametric kernel regression class + + Calculates the conditional mean ``E[y|X]`` where ``y = g(X) + e``. + Note that the "local constant" type of regression provided here is also + known as Nadaraya-Watson kernel regression; "local linear" is an extension + of that which suffers less from bias issues at the edge of the support. Note + that specifying a custom kernel works only with "local linear" kernel + regression. For example, a custom ``tricube`` kernel yields LOESS regression. + + Parameters + ---------- + endog : array_like + This is the dependent variable. + exog : array_like + The training data for the independent variable(s) + Each element in the list is a separate variable + var_type : str + The type of the variables, one character per variable: + + - c: continuous + - u: unordered (discrete) + - o: ordered (discrete) + + reg_type : {'lc', 'll'}, optional + Type of regression estimator. 'lc' means local constant and + 'll' local Linear estimator. Default is 'll' + bw : str or array_like, optional + Either a user-specified bandwidth or the method for bandwidth + selection. If a string, valid values are 'cv_ls' (least-squares + cross-validation) and 'aic' (AIC Hurvich bandwidth estimation). + Default is 'cv_ls'. User specified bandwidth must have as many + entries as the number of variables. + ckertype : str, optional + The kernel used for the continuous variables. + okertype : str, optional + The kernel used for the ordered discrete variables. + ukertype : str, optional + The kernel used for the unordered discrete variables. + defaults : EstimatorSettings instance, optional + The default values for the efficient bandwidth estimation. + rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional + If `rng` is None, the legacy global (singleton) ``RandomState`` + provided by ``numpy.random`` is used; this behavior is + deprecated and will change to creating a new ``Generator`` + using fresh entropy from the operating system in a future + release. If `rng` is an int or array of ints, a new + ``Generator`` is created, seeded with `rng`. If `rng` is + already a ``Generator`` or ``RandomState`` instance, that + instance is used. + + .. deprecated:: 0.15.0 + + In release 0.17.0 or after January 2028, whichever comes sooner, + using None will initialize a new numpy.random.default_rng using + system entropy. + + Attributes + ---------- + bw : ndarray + The bandwidth parameters. + """ + + @deprecate_kwarg("seed", "rng") + def __init__( + self, + endog, + exog, + var_type, + reg_type="ll", + bw="cv_ls", + ckertype="gaussian", + okertype="wangryzin", + ukertype="aitchisonaitken", + defaults=None, + *, + rng=None, + ): + self.var_type = var_type + self.data_type = var_type + self.reg_type = reg_type + self.ckertype = ckertype + self.okertype = okertype + self.ukertype = ukertype + if not ( + self.ckertype in kernel_func + and self.ukertype in kernel_func + and self.okertype in kernel_func + ): + raise ValueError( + "user specified kernel must be a supported " + "kernel from statsmodels.nonparametric.kernels." + ) + + self.k_vars = len(self.var_type) + self.endog = _adjust_shape(endog, 1) + self.exog = _adjust_shape(exog, self.k_vars) + self.data = np.column_stack((self.endog, self.exog)) + self.nobs = np.shape(self.exog)[0] + self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear) + defaults = EstimatorSettings() if defaults is None else defaults + self._set_defaults(defaults) + self.seed = rng + self.rng = rng + self._generator = initialize_generator(rng) + if not isinstance(bw, str): + bw = np.asarray(bw) + if len(bw) != self.k_vars: + raise ValueError( + "bw must have the same dimension as the number of variables." + ) + if not self.efficient: + self.bw = self._compute_reg_bw(bw) + else: + self.bw = self._compute_efficient(bw) + + def _compute_reg_bw(self, bw): + if not isinstance(bw, str): + self._bw_method = "user-specified" + return np.asarray(bw) + else: + # The user specified a bandwidth selection method e.g., 'cv_ls' + self._bw_method = bw + # Workaround to avoid instance methods in __dict__ + if bw == "cv_ls": + res = self.cv_loo + else: # bw == 'aic' + res = self.aic_hurvich + X = np.std(self.exog, axis=0) + h0 = 1.06 * X * self.nobs ** (-1.0 / (4 + np.size(self.exog, axis=1))) + + func = self.est[self.reg_type] + bw_estimated = optimize.fmin( + res, x0=h0, args=(func,), maxiter=1e3, maxfun=1e3, disp=0 + ) + return bw_estimated + + def _est_loc_linear(self, bw, endog, exog, data_predict): + """ + Local linear estimator of g(x) in the regression ``y = g(x) + e`` + + Parameters + ---------- + bw : array_like + Vector of bandwidth value(s). + endog : 1D array_like + The dependent variable. + exog : 1D or 2D array_like + The independent variable(s). + data_predict : 1D array_like of length K, where K is the number of variables. + The point at which the conditional mean is estimated. + + Returns + ------- + mean : ndarray + The value of the conditional mean at `data_predict`. + mfx : ndarray + The marginal effects. + + Notes + ----- + See p. 81 in [1] and p.38 in [2] for the formulas. + Unlike other methods, this one requires that `data_predict` be 1D. + """ + nobs, k_vars = exog.shape + ker = gpke( + bw, + data=exog, + data_predict=data_predict, + var_type=self.var_type, + ckertype=self.ckertype, + ukertype=self.ukertype, + okertype=self.okertype, + tosum=False, + ) / float(nobs) + # Create the matrix on p.492 in [7], after the multiplication w/ K_h,ij + # See also p. 38 in [2] + # ix_cont = np.arange(self.k_vars) # Use all vars instead of continuous only + # Note: because ix_cont was defined here such that it selected all + # columns, I removed the indexing with it from exog/data_predict. + + # Convert ker to a 2-D array to make matrix operations below work + ker = ker[:, np.newaxis] + + M12 = exog - data_predict + M22 = np.dot(M12.T, M12 * ker) + M12 = (M12 * ker).sum(axis=0) + M = np.empty((k_vars + 1, k_vars + 1)) + M[0, 0] = ker.sum() + M[0, 1:] = M12 + M[1:, 0] = M12 + M[1:, 1:] = M22 + + ker_endog = ker * endog + V = np.empty((k_vars + 1, 1)) + V[0, 0] = ker_endog.sum() + V[1:, 0] = ((exog - data_predict) * ker_endog).sum(axis=0) + + mean_mfx = np.dot(np.linalg.pinv(M), V) + mean = mean_mfx[0] + mfx = mean_mfx[1:, :] + return mean, mfx + + def _est_loc_constant(self, bw, endog, exog, data_predict): + """ + Local constant estimator of g(x) in the regression + y = g(x) + e + + Parameters + ---------- + bw : array_like + Array of bandwidth value(s). + endog : 1D array_like + The dependent variable. + exog : 1D or 2D array_like + The independent variable(s). + data_predict : 1D or 2D array_like + The point(s) at which the conditional mean is estimated. + + Returns + ------- + G : ndarray + The value of the conditional mean at `data_predict`. + B_x : ndarray + The marginal effects. + """ + ker_x = gpke( + bw, + data=exog, + data_predict=data_predict, + var_type=self.var_type, + ckertype=self.ckertype, + ukertype=self.ukertype, + okertype=self.okertype, + tosum=False, + ) + ker_x = np.reshape(ker_x, np.shape(endog)) + G_numer = (ker_x * endog).sum(axis=0) + G_denom = ker_x.sum(axis=0) + G = G_numer / G_denom + nobs = exog.shape[0] + f_x = G_denom / float(nobs) + ker_xc = gpke( + bw, + data=exog, + data_predict=data_predict, + var_type=self.var_type, + ckertype="d_gaussian", + # okertype='wangryzin_reg', + tosum=False, + ) + + ker_xc = ker_xc[:, np.newaxis] + d_mx = -(endog * ker_xc).sum(axis=0) / float(nobs) # * np.prod(bw[:, ix_cont])) + d_fx = -ker_xc.sum(axis=0) / float(nobs) # * np.prod(bw[:, ix_cont])) + B_x = d_mx / f_x - G * d_fx / f_x + B_x = (G_numer * d_fx - G_denom * d_mx) / (G_denom**2) + # B_x = (f_x * d_mx - m_x * d_fx) / (f_x ** 2) + return G, B_x + + def aic_hurvich(self, bw, func=None): + """ + Computes the AIC Hurvich criteria for the estimation of the bandwidth + + Parameters + ---------- + bw : array_like + Vector of bandwidth value(s) at which to evaluate the criterion. + func : callable, optional + Unused here, needed in signature because it's used in `cv_loo`. + + Returns + ------- + aic : ndarray + The value of the AIC Hurvich criterion. + + References + ---------- + See ch.2 in [1] and p.35 in [2]. + """ + H = np.empty((self.nobs, self.nobs)) + for j in range(self.nobs): + H[:, j] = gpke( + bw, + data=self.exog, + data_predict=self.exog[j, :], + ckertype=self.ckertype, + ukertype=self.ukertype, + okertype=self.okertype, + var_type=self.var_type, + tosum=False, + ) + + denom = H.sum(axis=1) + H = H / denom + gx = KernelReg( + endog=self.endog, + exog=self.exog, + var_type=self.var_type, + reg_type=self.reg_type, + bw=bw, + defaults=EstimatorSettings(efficient=False), + ).fit()[0] + gx = np.reshape(gx, (self.nobs, 1)) + sigma = ((self.endog - gx) ** 2).sum(axis=0) / float(self.nobs) + + frac = (1 + np.trace(H) / float(self.nobs)) / ( + 1 - (np.trace(H) + 2) / float(self.nobs) + ) + # siga = np.dot(self.endog.T, (I - H).T) + # sigb = np.dot((I - H), self.endog) + # sigma = np.dot(siga, sigb) / float(self.nobs) + aic = np.log(sigma) + frac + return aic + + def cv_loo(self, bw, func): + r""" + The cross-validation function with leave-one-out estimator + + Parameters + ---------- + bw : array_like + Vector of bandwidth values. + func : callable + Returns the estimator of g(x). Can be either ``_est_loc_constant`` + (local constant) or ``_est_loc_linear`` (local_linear). + + Returns + ------- + L : float + The value of the CV function. + + Notes + ----- + Calculates the cross-validation least-squares function. This function + is minimized by compute_bw to calculate the optimal value of `bw`. + + For details see p.35 in [2] + + .. math:: CV(h)=n^{-1}\sum_{i=1}^{n}(Y_{i}-g_{-i}(X_{i}))^{2} + + where :math:`g_{-i}(X_{i})` is the leave-one-out estimator of g(X) + and :math:`h` is the vector of bandwidths + """ + LOO_X = LeaveOneOut(self.exog) + LOO_Y = LeaveOneOut(self.endog).__iter__() + L = 0 + for ii, X_not_i in enumerate(LOO_X): + Y = next(LOO_Y) + G = func(bw, endog=Y, exog=-X_not_i, data_predict=-self.exog[ii, :])[0] + L += (self.endog[ii] - G) ** 2 + + # Note: There might be a way to vectorize this. See p.72 in [1] + return L / self.nobs + + def r_squared(self): + r""" + Returns the R-Squared for the nonparametric regression + + Returns + ------- + r2 : float + The R-Squared statistic computed from the fitted mean. + + Notes + ----- + For more details see p.45 in [2] + The R-Squared is calculated by: + + .. math:: R^{2}=\frac{\left[\sum_{i=1}^{n} + (Y_{i}-\bar{y})(\hat{Y_{i}}-\bar{y}\right]^{2}}{\sum_{i=1}^{n} + (Y_{i}-\bar{y})^{2}\sum_{i=1}^{n}(\hat{Y_{i}}-\bar{y})^{2}}, + + where :math:`\hat{Y_{i}}` is the mean calculated in `fit` at the exog + points. + """ + Y = np.squeeze(self.endog) + Yhat = self.fit()[0] + Y_bar = np.mean(Yhat) + R2_numer = (((Y - Y_bar) * (Yhat - Y_bar)).sum()) ** 2 + R2_denom = ((Y - Y_bar) ** 2).sum(axis=0) * ((Yhat - Y_bar) ** 2).sum(axis=0) + return R2_numer / R2_denom + + def fit(self, data_predict=None): + """ + Returns the mean and marginal effects at the `data_predict` points + + Parameters + ---------- + data_predict : array_like, optional + Points at which to return the mean and marginal effects. If not + given, ``data_predict == exog``. + + Returns + ------- + mean : ndarray + The regression result for the mean (i.e., the actual curve). + mfx : ndarray + The marginal effects, i.e., the partial derivatives of the mean. + """ + func = self.est[self.reg_type] + if data_predict is None: + data_predict = self.exog + else: + data_predict = _adjust_shape(data_predict, self.k_vars) + + N_data_predict = np.shape(data_predict)[0] + mean = np.empty((N_data_predict,)) + mfx = np.empty((N_data_predict, self.k_vars)) + for i in range(N_data_predict): + mean_mfx = func( + self.bw, self.endog, self.exog, data_predict=data_predict[i, :] + ) + mean[i] = np.squeeze(mean_mfx[0]) + mfx_c = np.squeeze(mean_mfx[1]) + mfx[i, :] = mfx_c + + return mean, mfx + + def sig_test(self, var_pos, nboot=50, nested_res=25, pivot=False): + """ + Significance test for the variables in the regression + + Parameters + ---------- + var_pos : array_like of int + The position of the variable in exog to be tested. + nboot : int, optional + Number of bootstrap samples used to determine the distribution + of the test statistic in a finite sample. Default is 50. + nested_res : int, optional + Number of nested resamples used to calculate lambda when + `pivot` is True. Default is 25. + pivot : bool, optional + Pivot the test statistic by dividing by its standard error. + Significantly increases computational time, but pivot + statistics have more desirable properties. Default is False. + + Returns + ------- + sig : str + The level of significance: + + - `*` : at 90% confidence level + - `**` : at 95% confidence level + - `***` : at 99% confidence level + - "Not Significant" : if not significant + """ + var_pos = np.asarray(var_pos) + ix_cont, ix_ord, ix_unord = _get_type_pos(self.var_type) + if np.any(ix_cont[var_pos]): + if np.any(ix_ord[var_pos]) or np.any(ix_unord[var_pos]): + raise ValueError("Discrete variable in hypothesis. Must be continuous") + + Sig = TestRegCoefC(self, var_pos, nboot, nested_res, pivot, rng=self.rng) + else: + Sig = TestRegCoefD(self, var_pos, nboot, rng=self.rng) + + return Sig.sig + + def __repr__(self): + """Provide something sane to print""" + rpr = "KernelReg instance\n" + rpr += "Number of variables: k_vars = " + str(self.k_vars) + "\n" + rpr += "Number of samples: N = " + str(self.nobs) + "\n" + rpr += "Variable types: " + self.var_type + "\n" + rpr += "BW selection method: " + self._bw_method + "\n" + rpr += "Estimator type: " + self.reg_type + "\n" + return rpr + + def _get_class_vars_type(self): + """Helper method to be able to pass needed vars to _compute_subset""" + class_type = "KernelReg" + class_vars = (self.var_type, self.k_vars, self.reg_type) + return class_type, class_vars + + def _compute_dispersion(self, data): + """ + Computes the measure of dispersion + + The minimum of the standard deviation and interquartile range / 1.349 + + Parameters + ---------- + data : ndarray + The data array, with the dependent variable in the first column + and the independent variables in the remaining columns. + + Returns + ------- + ndarray + The minimum of the standard deviation and IQR / 1.349 for each + independent variable. + + References + ---------- + See the user guide for the np package in R. + In the notes on bwscaling option in npreg, npudens, npcdens there is + a discussion on the measure of dispersion + """ + data = data[:, 1:] + return _compute_min_std_IQR(data) + + +class KernelCensoredReg(KernelReg): + """ + Nonparametric censored regression + + Calculates the conditional mean ``E[y|X]`` where ``y = g(X) + e``, + where y is left-censored. Left censored variable Y is defined as + ``Y = min {Y', L}`` where ``L`` is the value at which ``Y`` is censored + and ``Y'`` is the true value of the variable. + + Parameters + ---------- + endog : array_like + This is the dependent variable. + exog : array_like + The training data for the independent variable(s) + Each element in the list is a separate variable + var_type : str + The type of the variables, one character per variable: + + - c: Continuous + - u: Unordered (Discrete) + - o: Ordered (Discrete) + + reg_type : str + Type of regression estimator + + - lc: Local Constant Estimator + - ll: Local Linear Estimator + + bw : str or array_like, optional + Either a user-specified bandwidth or + the method for bandwidth selection. + + - cv_ls: cross-validation least squares + - aic: AIC Hurvich Estimator + + ckertype : str, optional + The kernel used for the continuous variables. + okertype : str, optional + The kernel used for the ordered discrete variables. + ukertype : str, optional + The kernel used for the unordered discrete variables. + censor_val : float, optional + Value at which the dependent variable is censored. Default is 0. + defaults : EstimatorSettings instance, optional + The default values for the efficient bandwidth estimation + rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional + If `rng` is None, the legacy global (singleton) ``RandomState`` + provided by ``numpy.random`` is used; this behavior is + deprecated and will change to creating a new ``Generator`` + using fresh entropy from the operating system in a future + release. If `rng` is an int or array of ints, a new + ``Generator`` is created, seeded with `rng`. If `rng` is + already a ``Generator`` or ``RandomState`` instance, that + instance is used. + + .. deprecated:: 0.15.0 + + In release 0.17.0 or after January 2028, whichever comes sooner, + using None will initialize a new numpy.random.default_rng using + system entropy. + + Attributes + ---------- + bw : ndarray + The bandwidth parameters + """ + + @deprecate_kwarg("seed", "rng") + def __init__( + self, + endog, + exog, + var_type, + reg_type, + bw="cv_ls", + ckertype="gaussian", + ukertype="aitchison_aitken_reg", + okertype="wangryzin_reg", + censor_val=0, + defaults=None, + *, + rng=None, + ): + self.var_type = var_type + self.data_type = var_type + self.reg_type = reg_type + self.ckertype = ckertype + self.okertype = okertype + self.ukertype = ukertype + if not ( + self.ckertype in kernel_func + and self.ukertype in kernel_func + and self.okertype in kernel_func + ): + raise ValueError( + "user specified kernel must be a supported " + "kernel from statsmodels.nonparametric.kernels." + ) + + self.k_vars = len(self.var_type) + self.endog = _adjust_shape(endog, 1) + self.exog = _adjust_shape(exog, self.k_vars) + self.data = np.column_stack((self.endog, self.exog)) + self.nobs = np.shape(self.exog)[0] + self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear) + self._generator = initialize_generator(rng) + defaults = EstimatorSettings() if defaults is None else defaults + self._set_defaults(defaults) + self.censor_val = censor_val + if self.censor_val is not None: + self.censored(censor_val) + else: + self.W_in = np.ones((self.nobs, 1)) + + if not self.efficient: + self.bw = self._compute_reg_bw(bw) + else: + self.bw = self._compute_efficient(bw) + + def censored(self, censor_val): + # see pp. 341-344 in [1] + self.d = (self.endog != censor_val) * 1.0 + ix = np.argsort(np.squeeze(self.endog)) + self.sortix = ix + self.sortix_rev = np.zeros(ix.shape, int) + self.sortix_rev[ix] = np.arange(len(ix)) + self.endog = np.squeeze(self.endog[ix]) + self.endog = _adjust_shape(self.endog, 1) + self.exog = np.squeeze(self.exog[ix]) + self.d = np.squeeze(self.d[ix]) + self.W_in = np.empty((self.nobs, 1)) + for i in range(1, self.nobs + 1): + P = 1 + for j in range(1, i): + P *= ((self.nobs - j) / (float(self.nobs) - j + 1)) ** self.d[j - 1] + self.W_in[i - 1, 0] = P * self.d[i - 1] / (float(self.nobs) - i + 1) + + def __repr__(self): + """Provide something sane to print""" + rpr = "KernelCensoredReg instance\n" + rpr += "Number of variables: k_vars = " + str(self.k_vars) + "\n" + rpr += "Number of samples: nobs = " + str(self.nobs) + "\n" + rpr += "Variable types: " + self.var_type + "\n" + rpr += "BW selection method: " + self._bw_method + "\n" + rpr += "Estimator type: " + self.reg_type + "\n" + return rpr + + def _est_loc_linear(self, bw, endog, exog, data_predict, W): + """ + Local linear estimator of g(x) in the regression ``y = g(x) + e`` + + Parameters + ---------- + bw : array_like + Vector of bandwidth value(s) + endog : 1D array_like + The dependent variable + exog : 1D or 2D array_like + The independent variable(s) + data_predict : 1D array_like of length K, where K is + the number of variables. The point at which + the conditional mean is estimated + W : array_like + The weights used to account for the censoring, as computed by + `censored`. + + Returns + ------- + mean : ndarray + The value of the conditional mean at data_predict + mfx : ndarray + The marginal effects. + + Notes + ----- + See p. 81 in [1] and p.38 in [2] for the formulas + Unlike other methods, this one requires that data_predict be 1D + """ + nobs, k_vars = exog.shape + ker = gpke( + bw, + data=exog, + data_predict=data_predict, + var_type=self.var_type, + ckertype=self.ckertype, + ukertype=self.ukertype, + okertype=self.okertype, + tosum=False, + ) + # Create the matrix on p.492 in [7], after the multiplication w/ K_h,ij + # See also p. 38 in [2] + + # Convert ker to a 2-D array to make matrix operations below work + ker = W * ker[:, np.newaxis] + + M12 = exog - data_predict + M22 = np.dot(M12.T, M12 * ker) + M12 = (M12 * ker).sum(axis=0) + M = np.empty((k_vars + 1, k_vars + 1)) + M[0, 0] = ker.sum() + M[0, 1:] = M12 + M[1:, 0] = M12 + M[1:, 1:] = M22 + + ker_endog = ker * endog + V = np.empty((k_vars + 1, 1)) + V[0, 0] = ker_endog.sum() + V[1:, 0] = ((exog - data_predict) * ker_endog).sum(axis=0) + + mean_mfx = np.dot(np.linalg.pinv(M), V) + mean = mean_mfx[0] + mfx = mean_mfx[1:, :] + return mean, mfx + + def cv_loo(self, bw, func): + r""" + The cross-validation function with leave-one-out + estimator + + Parameters + ---------- + bw : array_like + Vector of bandwidth values + func : callable + Returns the estimator of g(x). + Can be either ``_est_loc_constant`` (local constant) or + ``_est_loc_linear`` (local_linear). + + Returns + ------- + L : float + The value of the CV function + + Notes + ----- + Calculates the cross-validation least-squares + function. This function is minimized by compute_bw + to calculate the optimal value of bw + + For details see p.35 in [2] + + .. math:: CV(h)=n^{-1}\sum_{i=1}^{n}(Y_{i}-g_{-i}(X_{i}))^{2} + + where :math:`g_{-i}(X_{i})` is the leave-one-out estimator of g(X) + and :math:`h` is the vector of bandwidths + """ + LOO_X = LeaveOneOut(self.exog) + LOO_Y = LeaveOneOut(self.endog).__iter__() + LOO_W = LeaveOneOut(self.W_in).__iter__() + L = 0 + for ii, X_not_i in enumerate(LOO_X): + Y = next(LOO_Y) + w = next(LOO_W) + G = func(bw, endog=Y, exog=-X_not_i, data_predict=-self.exog[ii, :], W=w)[0] + L += (self.endog[ii] - G) ** 2 + + # Note: There might be a way to vectorize this. See p.72 in [1] + return L / self.nobs + + def fit(self, data_predict=None): + """ + Returns the mean and marginal effects at the `data_predict` points + + Parameters + ---------- + data_predict : array_like, optional + Points at which to return the mean and marginal effects. If not + given, ``data_predict == exog``. + + Returns + ------- + mean : ndarray + The regression result for the mean (i.e., the actual curve). + mfx : ndarray + The marginal effects, i.e., the partial derivatives of the mean. + """ + func = self.est[self.reg_type] + if data_predict is None: + data_predict = self.exog + else: + data_predict = _adjust_shape(data_predict, self.k_vars) + + N_data_predict = np.shape(data_predict)[0] + mean = np.empty((N_data_predict,)) + mfx = np.empty((N_data_predict, self.k_vars)) + for i in range(N_data_predict): + mean_mfx = func( + self.bw, + self.endog, + self.exog, + data_predict=data_predict[i, :], + W=self.W_in, + ) + mean[i] = np.squeeze(mean_mfx[0]) + mfx_c = np.squeeze(mean_mfx[1]) + mfx[i, :] = mfx_c + + return mean, mfx + + +class TestRegCoefC: + """ + Significance test for continuous variables in a nonparametric regression + + The null hypothesis is ``dE(Y|X)/dX_not_i = 0``, the alternative hypothesis + is ``dE(Y|X)/dX_not_i != 0``. + + Parameters + ---------- + model : KernelReg instance + This is the nonparametric regression model whose elements + are tested for significance. + test_vars : sequence of int + index of position of the continuous variables to be tested + for significance. e.g., (1,3,5) jointly tests variables at + position 1,3 and 5 for significance. + nboot : int, optional + Number of bootstrap samples used to determine the distribution + of the test statistic in a finite sample. Default is 400 + nested_res : int, optional + Number of nested resamples used to calculate lambda. Default is 400. + Must enable the pivot option + pivot : bool, optional + Pivot the test statistic by dividing by its standard error + Significantly increases computational time. But pivot statistics + have more desirable properties + (See references). Default is False. + rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional + If `rng` is None, the legacy global (singleton) ``RandomState`` + provided by ``numpy.random`` is used; this behavior is + deprecated and will change to creating a new ``Generator`` + using fresh entropy from the operating system in a future + release. If `rng` is an int or array of ints, a new + ``Generator`` is created, seeded with `rng`. If `rng` is + already a ``Generator`` or ``RandomState`` instance, that + instance is used. + + .. deprecated:: 0.15.0 + + In release 0.17.0 or after January 2028, whichever comes sooner, + using None will initialize a new numpy.random.default_rng using + system entropy. + + Attributes + ---------- + sig : str + The significance level of the variable(s) tested + "Not Significant": Not significant at the 90% confidence level + Fails to reject the null + "*": Significant at the 90% confidence level + "**": Significant at the 95% confidence level + "***": Significant at the 99% confidence level + + Notes + ----- + This class allows testing of joint hypothesis as long as all variables + are continuous. + + References + ---------- + Racine, J.: "Consistent Significance Testing for Nonparametric Regression" + Journal of Business & Economics Statistics. + + Chapter 12 in [1]. + """ + + # Significance of continuous vars in nonparametric regression + # Racine: Consistent Significance Testing for Nonparametric Regression + # Journal of Business & Economics Statistics + @deprecate_kwarg("seed", "rng") + def __init__( + self, model, test_vars, nboot=400, nested_res=400, pivot=False, rng=None + ): + self.nboot = nboot + self.nres = nested_res + self.test_vars = test_vars + self.model = model + self.bw = model.bw + self.var_type = model.var_type + self.k_vars = len(self.var_type) + self.endog = model.endog + self.exog = model.exog + self.gx = model.est[model.reg_type] + self.test_vars = test_vars + self.pivot = pivot + self._generator = initialize_generator(rng) + self.run() + + def run(self): + self.test_stat = self._compute_test_stat(self.endog, self.exog) + self.sig = self._compute_sig() + + def _compute_test_stat(self, Y, X): + """ + Computes the test statistic + + See p.371 in [8]. + """ + lam = self._compute_lambda(Y, X) + t = lam + if self.pivot: + se_lam = self._compute_se_lambda(Y, X) + t = lam / float(se_lam) + + return t + + def _compute_lambda(self, Y, X): + """Computes only lambda -- the main part of the test statistic""" + n = np.shape(X)[0] + Y = _adjust_shape(Y, 1) + X = _adjust_shape(X, self.k_vars) + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + category=FutureWarning, + ) + b = KernelReg( + Y, + X, + self.var_type, + self.model.reg_type, + self.bw, + defaults=EstimatorSettings(efficient=False), + ).fit()[1] + + b = b[:, self.test_vars] + b = np.reshape(b, (n, len(self.test_vars))) + # fct = np.std(b) # Pivot the statistic by dividing by SE + fct = 1.0 # Do not Pivot -- Bootstrapping works better if Pivot + lam = ((b / fct) ** 2).sum() / float(n) + return lam + + def _compute_se_lambda(self, Y, X): + """ + Calculates the SE of lambda by nested resampling + Used to pivot the statistic. + Bootstrapping works better with estimating pivotal statistics + but slows down computation significantly. + """ + n = np.shape(Y)[0] + lam = np.empty(shape=(self.nres,)) + for i in range(self.nres): + ind = self._integers(0, n, size=(n, 1)) + Y1 = Y[ind, 0] + X1 = X[ind, :] + lam[i] = self._compute_lambda(Y1, X1) + + se_lambda = np.std(lam) + return se_lambda + + def _compute_sig(self): + """ + Computes the significance value for the variable(s) tested + + The empirical distribution of the test statistic is obtained through + bootstrapping the sample. The null hypothesis is rejected if the test + statistic is larger than the 90, 95, 99 percentiles. + """ + t_dist = np.empty(shape=(self.nboot,)) + Y = self.endog + X = copy.deepcopy(self.exog) + n = np.shape(Y)[0] + + X[:, self.test_vars] = np.mean(X[:, self.test_vars], axis=0) + # Calculate the restricted mean. See p. 372 in [8] + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + category=FutureWarning, + ) + M = KernelReg( + Y, + X, + self.var_type, + self.model.reg_type, + self.bw, + defaults=EstimatorSettings(efficient=False), + ).fit()[0] + M = np.reshape(M, (n, 1)) + e = Y - M + e = e - np.mean(e) # recenter residuals + for i in range(self.nboot): + ind = self._integers(0, n, size=(n, 1)) + e_boot = e[ind, 0] + Y_boot = M + e_boot + t_dist[i] = self._compute_test_stat(Y_boot, self.exog) + + self.t_dist = t_dist + sig = "Not Significant" + if self.test_stat > mquantiles(t_dist, 0.9): + sig = "*" + if self.test_stat > mquantiles(t_dist, 0.95): + sig = "**" + if self.test_stat > mquantiles(t_dist, 0.99): + sig = "***" + + return sig + + def _integers(self, low: int, upper: int, size: tuple[int, int]): + if self._generator is None: + return np.random.randint(low, upper, size=size) + elif isinstance(self._generator, np.random.RandomState): + return self._generator.randint(low, upper, size=size) + else: + return self._generator.integers(low, upper, size=size) + + def _uniform(self, low: float, upper: float, size: tuple[int, int]): + if self._generator is None: + return np.random.uniform(low, upper, size=size) + return self._generator.uniform(low, upper, size=size) + + +class TestRegCoefD(TestRegCoefC): + """ + Significance test for the categorical variables in a nonparametric + regression + + Parameters + ---------- + model : Instance of KernelReg class + This is the nonparametric regression model whose elements + are tested for significance. + test_vars : sequence of int + index of position of the discrete variable to be tested + for significance. e.g., (3) tests variable at + position 3 for significance. + nboot : int, optional + Number of bootstrap samples used to determine the distribution + of the test statistic in a finite sample. Default is 400 + rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional + If `rng` is None, the legacy global (singleton) ``RandomState`` + provided by ``numpy.random`` is used; this behavior is + deprecated and will change to creating a new ``Generator`` + using fresh entropy from the operating system in a future + release. If `rng` is an int or array of ints, a new + ``Generator`` is created, seeded with `rng`. If `rng` is + already a ``Generator`` or ``RandomState`` instance, that + instance is used. + + .. deprecated:: 0.15.0 + + In release 0.17.0 or after January 2028, whichever comes sooner, + using None will initialize a new numpy.random.default_rng using + system entropy. + + Attributes + ---------- + sig : str + The significance level of the variable(s) tested + "Not Significant": Not significant at the 90% confidence level + Fails to reject the null + "*": Significant at the 90% confidence level + "**": Significant at the 95% confidence level + "***": Significant at the 99% confidence level + + Notes + ----- + This class currently does not allow joint hypothesis. + Only one variable can be tested at a time + + References + ---------- + See [9] and chapter 12 in [1]. + """ + + def _compute_test_stat(self, Y, X): + """Computes the test statistic""" + + dom_x = np.sort(np.unique(self.exog[:, self.test_vars])) + + n = np.shape(X)[0] + model = KernelReg( + Y, + X, + self.var_type, + self.model.reg_type, + self.bw, + defaults=EstimatorSettings(efficient=False), + rng=self._generator, + ) + X1 = copy.deepcopy(X) + X1[:, self.test_vars] = 0 + + m0 = model.fit(data_predict=X1)[0] + m0 = np.reshape(m0, (n, 1)) + zvec = np.zeros((n, 1)) + for i in dom_x[1:]: + X1[:, self.test_vars] = i + m1 = model.fit(data_predict=X1)[0] + m1 = np.reshape(m1, (n, 1)) + zvec += (m1 - m0) ** 2 + + avg = zvec.sum(axis=0) / float(n) + return avg + + def _compute_sig(self): + """Calculates the significance level of the variable tested""" + + m = self._est_cond_mean() + Y = self.endog + X = self.exog + n = np.shape(X)[0] + u = Y - m + u = u - np.mean(u) # center + fct1 = (1 - 5**0.5) / 2.0 + fct2 = (1 + 5**0.5) / 2.0 + u1 = fct1 * u + u2 = fct2 * u + r = fct2 / (5**0.5) + I_dist = np.empty((self.nboot, 1)) + for j in range(self.nboot): + u_boot = copy.deepcopy(u2) + + prob = self._uniform(0, 1, size=(n, 1)) + ind = prob < r + u_boot[ind] = u1[ind] + Y_boot = m + u_boot + I_dist[j] = self._compute_test_stat(Y_boot, X) + + sig = "Not Significant" + if self.test_stat > mquantiles(I_dist, 0.9): + sig = "*" + if self.test_stat > mquantiles(I_dist, 0.95): + sig = "**" + if self.test_stat > mquantiles(I_dist, 0.99): + sig = "***" + + return sig + + def _est_cond_mean(self): + """ + Calculates the expected conditional mean + m(X, Z=l) for all possible l + """ + self.dom_x = np.sort(np.unique(self.exog[:, self.test_vars])) + X = copy.deepcopy(self.exog) + m = 0 + for i in self.dom_x: + X[:, self.test_vars] = i + m += self.model.fit(data_predict=X)[0] + + m = m / float(len(self.dom_x)) + m = np.reshape(m, (np.shape(self.exog)[0], 1)) + return m diff --git a/shared/package-files/56/5625ccbe57902084adaae1cdd350a94d43d8c6ede3802e7b19a08e92e5d1b285/util.py b/shared/package-files/56/5625ccbe57902084adaae1cdd350a94d43d8c6ede3802e7b19a08e92e5d1b285/util.py new file mode 100644 index 0000000000000000000000000000000000000000..e140396d8cd73bdcc769dc79366ad70c3e302715 --- /dev/null +++ b/shared/package-files/56/5625ccbe57902084adaae1cdd350a94d43d8c6ede3802e7b19a08e92e5d1b285/util.py @@ -0,0 +1,841 @@ +from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401 +from .singularities import singularities +from sympy.core import Pow, S +from sympy.core.function import diff, expand_mul +from sympy.core.kind import NumberKind +from sympy.core.mod import Mod +from sympy.core.numbers import equal_valued +from sympy.core.relational import Relational +from sympy.core.symbol import Symbol, Dummy +from sympy.core.sympify import _sympify +from sympy.functions.elementary.complexes import Abs, im, re +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import ( + TrigonometricFunction, sin, cos, csc, sec) +from sympy.polys.polytools import degree, lcm_list +from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union, + Complement) +from sympy.sets.fancysets import ImageSet +from sympy.utilities import filldedent +from sympy.utilities.iterables import iterable + + +def continuous_domain(f, symbol, domain): + """ + Returns the intervals in the given domain for which the function + is continuous. + This method is limited by the ability to determine the various + singularities and discontinuities of the given function. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the intervals are to be determined. + domain : :py:class:`~.Interval` + The domain over which the continuity of the symbol has to be checked. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt + >>> from sympy.calculus.util import continuous_domain + >>> x = Symbol('x') + >>> continuous_domain(1/x, x, S.Reals) + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + >>> continuous_domain(tan(x), x, Interval(0, pi)) + Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi)) + >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5)) + Interval(2, 5) + >>> continuous_domain(log(2*x - 1), x, S.Reals) + Interval.open(1/2, oo) + + Returns + ======= + + :py:class:`~.Interval` + Union of all intervals where the function is continuous. + + Raises + ====== + + NotImplementedError + If the method to determine continuity of such a function + has not yet been developed. + + """ + from sympy.solvers.inequalities import solve_univariate_inequality + + if domain.is_subset(S.Reals): + constrained_interval = domain + for atom in f.atoms(Pow): + den = atom.exp.as_numer_denom()[1] + if den.is_even and den.is_nonzero: + constraint = solve_univariate_inequality(atom.base >= 0, + symbol).as_set() + constrained_interval = Intersection(constraint, + constrained_interval) + + for atom in f.atoms(log): + constraint = solve_univariate_inequality(atom.args[0] > 0, + symbol).as_set() + constrained_interval = Intersection(constraint, + constrained_interval) + + + return constrained_interval - singularities(f, symbol, domain) + + +def function_range(f, symbol, domain): + """ + Finds the range of a function in a given domain. + This method is limited by the ability to determine the singularities and + determine limits. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the range of function is to be determined. + domain : :py:class:`~.Interval` + The domain under which the range of the function has to be found. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan + >>> from sympy.calculus.util import function_range + >>> x = Symbol('x') + >>> function_range(sin(x), x, Interval(0, 2*pi)) + Interval(-1, 1) + >>> function_range(tan(x), x, Interval(-pi/2, pi/2)) + Interval(-oo, oo) + >>> function_range(1/x, x, S.Reals) + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + >>> function_range(exp(x), x, S.Reals) + Interval.open(0, oo) + >>> function_range(log(x), x, S.Reals) + Interval(-oo, oo) + >>> function_range(sqrt(x), x, Interval(-5, 9)) + Interval(0, 3) + + Returns + ======= + + :py:class:`~.Interval` + Union of all ranges for all intervals under domain where function is + continuous. + + Raises + ====== + + NotImplementedError + If any of the intervals, in the given domain, for which function + is continuous are not finite or real, + OR if the critical points of the function on the domain cannot be found. + """ + + if domain is S.EmptySet: + return S.EmptySet + + period = periodicity(f, symbol) + if period == S.Zero: + # the expression is constant wrt symbol + return FiniteSet(f.expand()) + + from sympy.series.limits import limit + from sympy.solvers.solveset import solveset + + if period is not None: + if isinstance(domain, Interval): + if (domain.inf - domain.sup).is_infinite: + domain = Interval(0, period) + elif isinstance(domain, Union): + for sub_dom in domain.args: + if isinstance(sub_dom, Interval) and \ + ((sub_dom.inf - sub_dom.sup).is_infinite): + domain = Interval(0, period) + + intervals = continuous_domain(f, symbol, domain) + range_int = S.EmptySet + if isinstance(intervals,(Interval, FiniteSet)): + interval_iter = (intervals,) + + elif isinstance(intervals, Union): + interval_iter = intervals.args + + else: + raise NotImplementedError(filldedent(''' + Unable to find range for the given domain. + ''')) + + for interval in interval_iter: + if isinstance(interval, FiniteSet): + for singleton in interval: + if singleton in domain: + range_int += FiniteSet(f.subs(symbol, singleton)) + elif isinstance(interval, Interval): + vals = S.EmptySet + critical_points = S.EmptySet + critical_values = S.EmptySet + bounds = ((interval.left_open, interval.inf, '+'), + (interval.right_open, interval.sup, '-')) + + for is_open, limit_point, direction in bounds: + if is_open: + critical_values += FiniteSet(limit(f, symbol, limit_point, direction)) + vals += critical_values + + else: + vals += FiniteSet(f.subs(symbol, limit_point)) + + solution = solveset(f.diff(symbol), symbol, interval) + + if not iterable(solution): + raise NotImplementedError( + 'Unable to find critical points for {}'.format(f)) + if isinstance(solution, ImageSet): + raise NotImplementedError( + 'Infinite number of critical points for {}'.format(f)) + + critical_points += solution + + for critical_point in critical_points: + vals += FiniteSet(f.subs(symbol, critical_point)) + + left_open, right_open = False, False + + if critical_values is not S.EmptySet: + if critical_values.inf == vals.inf: + left_open = True + + if critical_values.sup == vals.sup: + right_open = True + + range_int += Interval(vals.inf, vals.sup, left_open, right_open) + else: + raise NotImplementedError(filldedent(''' + Unable to find range for the given domain. + ''')) + + return range_int + + +def not_empty_in(finset_intersection, *syms): + """ + Finds the domain of the functions in ``finset_intersection`` in which the + ``finite_set`` is not-empty. + + Parameters + ========== + + finset_intersection : Intersection of FiniteSet + The unevaluated intersection of FiniteSet containing + real-valued functions with Union of Sets + syms : Tuple of symbols + Symbol for which domain is to be found + + Raises + ====== + + NotImplementedError + The algorithms to find the non-emptiness of the given FiniteSet are + not yet implemented. + ValueError + The input is not valid. + RuntimeError + It is a bug, please report it to the github issue tracker + (https://github.com/sympy/sympy/issues). + + Examples + ======== + + >>> from sympy import FiniteSet, Interval, not_empty_in, oo + >>> from sympy.abc import x + >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x) + Interval(0, 2) + >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) + Union(Interval(1, 2), Interval(-sqrt(2), -1)) + >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) + Union(Interval.Lopen(-2, -1), Interval(2, oo)) + """ + + # TODO: handle piecewise defined functions + # TODO: handle transcendental functions + # TODO: handle multivariate functions + if len(syms) == 0: + raise ValueError("One or more symbols must be given in syms.") + + if finset_intersection is S.EmptySet: + return S.EmptySet + + if isinstance(finset_intersection, Union): + elm_in_sets = finset_intersection.args[0] + return Union(not_empty_in(finset_intersection.args[1], *syms), + elm_in_sets) + + if isinstance(finset_intersection, FiniteSet): + finite_set = finset_intersection + _sets = S.Reals + else: + finite_set = finset_intersection.args[1] + _sets = finset_intersection.args[0] + + if not isinstance(finite_set, FiniteSet): + raise ValueError('A FiniteSet must be given, not %s: %s' % + (type(finite_set), finite_set)) + + if len(syms) == 1: + symb = syms[0] + else: + raise NotImplementedError('more than one variables %s not handled' % + (syms,)) + + def elm_domain(expr, intrvl): + """ Finds the domain of an expression in any given interval """ + from sympy.solvers.solveset import solveset + + _start = intrvl.start + _end = intrvl.end + _singularities = solveset(expr.as_numer_denom()[1], symb, + domain=S.Reals) + + if intrvl.right_open: + if _end is S.Infinity: + _domain1 = S.Reals + else: + _domain1 = solveset(expr < _end, symb, domain=S.Reals) + else: + _domain1 = solveset(expr <= _end, symb, domain=S.Reals) + + if intrvl.left_open: + if _start is S.NegativeInfinity: + _domain2 = S.Reals + else: + _domain2 = solveset(expr > _start, symb, domain=S.Reals) + else: + _domain2 = solveset(expr >= _start, symb, domain=S.Reals) + + # domain in the interval + expr_with_sing = Intersection(_domain1, _domain2) + expr_domain = Complement(expr_with_sing, _singularities) + return expr_domain + + if isinstance(_sets, Interval): + return Union(*[elm_domain(element, _sets) for element in finite_set]) + + if isinstance(_sets, Union): + _domain = S.EmptySet + for intrvl in _sets.args: + _domain_element = Union(*[elm_domain(element, intrvl) + for element in finite_set]) + _domain = Union(_domain, _domain_element) + return _domain + + +def periodicity(f, symbol, check=False): + """ + Tests the given function for periodicity in the given symbol. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the period is to be determined. + check : bool, optional + The flag to verify whether the value being returned is a period or not. + + Returns + ======= + + period + The period of the function is returned. + ``None`` is returned when the function is aperiodic or has a complex period. + The value of $0$ is returned as the period of a constant function. + + Raises + ====== + + NotImplementedError + The value of the period computed cannot be verified. + + + Notes + ===== + + Currently, we do not support functions with a complex period. + The period of functions having complex periodic values such + as ``exp``, ``sinh`` is evaluated to ``None``. + + The value returned might not be the "fundamental" period of the given + function i.e. it may not be the smallest periodic value of the function. + + The verification of the period through the ``check`` flag is not reliable + due to internal simplification of the given expression. Hence, it is set + to ``False`` by default. + + Examples + ======== + >>> from sympy import periodicity, Symbol, sin, cos, tan, exp + >>> x = Symbol('x') + >>> f = sin(x) + sin(2*x) + sin(3*x) + >>> periodicity(f, x) + 2*pi + >>> periodicity(sin(x)*cos(x), x) + pi + >>> periodicity(exp(tan(2*x) - 1), x) + pi/2 + >>> periodicity(sin(4*x)**cos(2*x), x) + pi + >>> periodicity(exp(x), x) + """ + if symbol.kind is not NumberKind: + raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind) + temp = Dummy('x', real=True) + f = f.subs(symbol, temp) + symbol = temp + + def _check(orig_f, period): + '''Return the checked period or raise an error.''' + new_f = orig_f.subs(symbol, symbol + period) + if new_f.equals(orig_f): + return period + else: + raise NotImplementedError(filldedent(''' + The period of the given function cannot be verified. + When `%s` was replaced with `%s + %s` in `%s`, the result + was `%s` which was not recognized as being the same as + the original function. + So either the period was wrong or the two forms were + not recognized as being equal. + Set check=False to obtain the value.''' % + (symbol, symbol, period, orig_f, new_f))) + + orig_f = f + period = None + + if isinstance(f, Relational): + f = f.lhs - f.rhs + + f = f.simplify() + + if symbol not in f.free_symbols: + return S.Zero + + if isinstance(f, TrigonometricFunction): + try: + period = f.period(symbol) + except NotImplementedError: + pass + + if isinstance(f, Abs): + arg = f.args[0] + if isinstance(arg, (sec, csc, cos)): + # all but tan and cot might have a + # a period that is half as large + # so recast as sin + arg = sin(arg.args[0]) + period = periodicity(arg, symbol) + if period is not None and isinstance(arg, sin): + # the argument of Abs was a trigonometric other than + # cot or tan; test to see if the half-period + # is valid. Abs(arg) has behaviour equivalent to + # orig_f, so use that for test: + orig_f = Abs(arg) + try: + return _check(orig_f, period/2) + except NotImplementedError as err: + if check: + raise NotImplementedError(err) + # else let new orig_f and period be + # checked below + + if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): + f = Pow(S.Exp1, expand_mul(f.exp)) + if im(f) != 0: + period_real = periodicity(re(f), symbol) + period_imag = periodicity(im(f), symbol) + if period_real is not None and period_imag is not None: + period = lcim([period_real, period_imag]) + + if f.is_Pow and f.base != S.Exp1: + base, expo = f.args + base_has_sym = base.has(symbol) + expo_has_sym = expo.has(symbol) + + if base_has_sym and not expo_has_sym: + period = periodicity(base, symbol) + + elif expo_has_sym and not base_has_sym: + period = periodicity(expo, symbol) + + else: + period = _periodicity(f.args, symbol) + + elif f.is_Mul: + coeff, g = f.as_independent(symbol, as_Add=False) + if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1): + period = periodicity(g, symbol) + else: + period = _periodicity(g.args, symbol) + + elif f.is_Add: + k, g = f.as_independent(symbol) + if k is not S.Zero: + return periodicity(g, symbol) + + period = _periodicity(g.args, symbol) + + elif isinstance(f, Mod): + a, n = f.args + + if a == symbol: + period = n + elif isinstance(a, TrigonometricFunction): + period = periodicity(a, symbol) + #check if 'f' is linear in 'symbol' + elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and + symbol not in n.free_symbols): + period = Abs(n / a.diff(symbol)) + + elif isinstance(f, Piecewise): + pass # not handling Piecewise yet as the return type is not favorable + + elif period is None: + from sympy.solvers.decompogen import compogen, decompogen + g_s = decompogen(f, symbol) + num_of_gs = len(g_s) + if num_of_gs > 1: + for index, g in enumerate(reversed(g_s)): + start_index = num_of_gs - 1 - index + g = compogen(g_s[start_index:], symbol) + if g not in (orig_f, f): # Fix for issue 12620 + period = periodicity(g, symbol) + if period is not None: + break + + if period is not None: + if check: + return _check(orig_f, period) + return period + + return None + + +def _periodicity(args, symbol): + """ + Helper for `periodicity` to find the period of a list of simpler + functions. + It uses the `lcim` method to find the least common period of + all the functions. + + Parameters + ========== + + args : Tuple of :py:class:`~.Symbol` + All the symbols present in a function. + + symbol : :py:class:`~.Symbol` + The symbol over which the function is to be evaluated. + + Returns + ======= + + period + The least common period of the function for all the symbols + of the function. + ``None`` if for at least one of the symbols the function is aperiodic. + + """ + periods = [] + for f in args: + period = periodicity(f, symbol) + if period is None: + return None + + if period is not S.Zero: + periods.append(period) + + if len(periods) > 1: + return lcim(periods) + + if periods: + return periods[0] + + +def lcim(numbers): + """Returns the least common integral multiple of a list of numbers. + + The numbers can be rational or irrational or a mixture of both. + `None` is returned for incommensurable numbers. + + Parameters + ========== + + numbers : list + Numbers (rational and/or irrational) for which lcim is to be found. + + Returns + ======= + + number + lcim if it exists, otherwise ``None`` for incommensurable numbers. + + Examples + ======== + + >>> from sympy.calculus.util import lcim + >>> from sympy import S, pi + >>> lcim([S(1)/2, S(3)/4, S(5)/6]) + 15/2 + >>> lcim([2*pi, 3*pi, pi, pi/2]) + 6*pi + >>> lcim([S(1), 2*pi]) + """ + result = None + if all(num.is_irrational for num in numbers): + factorized_nums = [num.factor() for num in numbers] + factors_num = [num.as_coeff_Mul() for num in factorized_nums] + term = factors_num[0][1] + if all(factor == term for coeff, factor in factors_num): + common_term = term + coeffs = [coeff for coeff, factor in factors_num] + result = lcm_list(coeffs) * common_term + + elif all(num.is_rational for num in numbers): + result = lcm_list(numbers) + + else: + pass + + return result + +def is_convex(f, *syms, domain=S.Reals): + r"""Determines the convexity of the function passed in the argument. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + syms : Tuple of :py:class:`~.Symbol` + The variables with respect to which the convexity is to be determined. + domain : :py:class:`~.Interval`, optional + The domain over which the convexity of the function has to be checked. + If unspecified, S.Reals will be the default domain. + + Returns + ======= + + bool + The method returns ``True`` if the function is convex otherwise it + returns ``False``. + + Raises + ====== + + NotImplementedError + The check for the convexity of multivariate functions is not implemented yet. + + Notes + ===== + + To determine concavity of a function pass `-f` as the concerned function. + To determine logarithmic convexity of a function pass `\log(f)` as + concerned function. + To determine logarithmic concavity of a function pass `-\log(f)` as + concerned function. + + Currently, convexity check of multivariate functions is not handled. + + Examples + ======== + + >>> from sympy import is_convex, symbols, exp, oo, Interval + >>> x = symbols('x') + >>> is_convex(exp(x), x) + True + >>> is_convex(x**3, x, domain = Interval(-1, oo)) + False + >>> is_convex(1/x**2, x, domain=Interval.open(0, oo)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Convex_function + .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf + .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function + .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function + .. [5] https://en.wikipedia.org/wiki/Concave_function + + """ + + if len(syms) > 1: + raise NotImplementedError( + "The check for the convexity of multivariate functions is not implemented yet.") + + from sympy.solvers.inequalities import solve_univariate_inequality + + f = _sympify(f) + var = syms[0] + if any(s in domain for s in singularities(f, var)): + return False + + condition = f.diff(var, 2) < 0 + if solve_univariate_inequality(condition, var, False, domain): + return False + return True + + +def stationary_points(f, symbol, domain=S.Reals): + """ + Returns the stationary points of a function (where derivative of the + function is 0) in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the stationary points are to be determined. + domain : :py:class:`~.Interval` + The domain over which the stationary points have to be checked. + If unspecified, ``S.Reals`` will be the default domain. + + Returns + ======= + + Set + A set of stationary points for the function. If there are no + stationary point, an :py:class:`~.EmptySet` is returned. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points + >>> x = Symbol('x') + + >>> stationary_points(1/x, x, S.Reals) + EmptySet + + >>> pprint(stationary_points(sin(x), x), use_unicode=False) + pi 3*pi + {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers} + 2 2 + + >>> stationary_points(sin(x),x, Interval(0, 4*pi)) + {pi/2, 3*pi/2, 5*pi/2, 7*pi/2} + + """ + from sympy.solvers.solveset import solveset + + if domain is S.EmptySet: + return S.EmptySet + + domain = continuous_domain(f, symbol, domain) + set = solveset(diff(f, symbol), symbol, domain) + + return set + + +def maximum(f, symbol, domain=S.Reals): + """ + Returns the maximum value of a function in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for maximum value needs to be determined. + domain : :py:class:`~.Interval` + The domain over which the maximum have to be checked. + If unspecified, then the global maximum is returned. + + Returns + ======= + + number + Maximum value of the function in given domain. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum + >>> x = Symbol('x') + + >>> f = -x**2 + 2*x + 5 + >>> maximum(f, x, S.Reals) + 6 + + >>> maximum(sin(x), x, Interval(-pi, pi/4)) + sqrt(2)/2 + + >>> maximum(sin(x)*cos(x), x) + 1/2 + + """ + if isinstance(symbol, Symbol): + if domain is S.EmptySet: + raise ValueError("Maximum value not defined for empty domain.") + + return function_range(f, symbol, domain).sup + else: + raise ValueError("%s is not a valid symbol." % symbol) + + +def minimum(f, symbol, domain=S.Reals): + """ + Returns the minimum value of a function in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for minimum value needs to be determined. + domain : :py:class:`~.Interval` + The domain over which the minimum have to be checked. + If unspecified, then the global minimum is returned. + + Returns + ======= + + number + Minimum value of the function in the given domain. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, cos, minimum + >>> x = Symbol('x') + + >>> f = x**2 + 2*x + 5 + >>> minimum(f, x, S.Reals) + 4 + + >>> minimum(sin(x), x, Interval(2, 3)) + sin(3) + + >>> minimum(sin(x)*cos(x), x) + -1/2 + + """ + if isinstance(symbol, Symbol): + if domain is S.EmptySet: + raise ValueError("Minimum value not defined for empty domain.") + + return function_range(f, symbol, domain).inf + else: + raise ValueError("%s is not a valid symbol." % symbol) diff --git a/shared/package-files/56/5625dde86e5d3428f96dd588a61155f28936505d3c537a4a448d967e716af150/CUDAGuardImpl.h b/shared/package-files/56/5625dde86e5d3428f96dd588a61155f28936505d3c537a4a448d967e716af150/CUDAGuardImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..f3dee77c683c26632c5191b287236e843cab3986 --- /dev/null +++ b/shared/package-files/56/5625dde86e5d3428f96dd588a61155f28936505d3c537a4a448d967e716af150/CUDAGuardImpl.h @@ -0,0 +1,212 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace c10::cuda::impl { + +struct CUDAGuardImpl final : public c10::impl::DeviceGuardImplInterface { + static constexpr DeviceType static_type = DeviceType::CUDA; + + CUDAGuardImpl() = default; + explicit CUDAGuardImpl(DeviceType t) { + TORCH_INTERNAL_ASSERT(t == DeviceType::CUDA); + } + DeviceType type() const override { + return DeviceType::CUDA; + } + Device exchangeDevice(Device d) const override { + TORCH_INTERNAL_ASSERT(d.is_cuda()); + auto old_device_index = c10::cuda::ExchangeDevice(d.index()); + return Device(DeviceType::CUDA, old_device_index); + } + Device getDevice() const override { + DeviceIndex device = 0; + C10_CUDA_CHECK(c10::cuda::GetDevice(&device)); + return Device(DeviceType::CUDA, device); + } + c10::optional uncheckedGetDevice() const noexcept { + DeviceIndex device{-1}; + const auto err = C10_CUDA_ERROR_HANDLED(c10::cuda::GetDevice(&device)); + C10_CUDA_CHECK_WARN(err); + if (err != cudaSuccess) { + return c10::nullopt; + } + return Device(DeviceType::CUDA, device); + } + void setDevice(Device d) const override { + TORCH_INTERNAL_ASSERT(d.is_cuda()); + C10_CUDA_CHECK(c10::cuda::SetDevice(d.index())); + } + void uncheckedSetDevice(Device d) const noexcept override { + C10_CUDA_CHECK_WARN(c10::cuda::MaybeSetDevice(d.index())); + } + Stream getStream(Device d) const noexcept override { + return getCurrentCUDAStream(d.index()).unwrap(); + } + Stream getDefaultStream(Device d) const override { + return getDefaultCUDAStream(d.index()); + } + Stream getStreamFromGlobalPool(Device d, bool isHighPriority = false) + const override { + return getStreamFromPool(isHighPriority, d.index()); + } + // NB: These do NOT set the current device + Stream exchangeStream(Stream s) const noexcept override { + CUDAStream cs(s); + auto old_stream = getCurrentCUDAStream(s.device().index()); + setCurrentCUDAStream(cs); + return old_stream.unwrap(); + } + DeviceIndex deviceCount() const noexcept override { + return device_count(); + } + + // Event-related functions + void createEvent(cudaEvent_t* cuda_event, const EventFlag flag) const { + // Maps PyTorch's Event::Flag to CUDA flag + auto cuda_flag = cudaEventDefault; + switch (flag) { + case EventFlag::PYTORCH_DEFAULT: + case EventFlag::CUDA_EVENT_DISABLE_TIMING: + cuda_flag = cudaEventDisableTiming; + break; + case EventFlag::BACKEND_DEFAULT: + case EventFlag::CUDA_EVENT_DEFAULT: + cuda_flag = cudaEventDefault; + break; + default: + TORCH_CHECK(false, "CUDA event received unknown flag"); + } + + C10_CUDA_CHECK(cudaEventCreateWithFlags(cuda_event, cuda_flag)); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_creation( + reinterpret_cast(cuda_event)); + } + } + + void destroyEvent(void* event, const DeviceIndex device_index) + const noexcept override { + if (!event) + return; + auto cuda_event = static_cast(event); + DeviceIndex orig_device{-1}; + C10_CUDA_CHECK_WARN(c10::cuda::GetDevice(&orig_device)); + C10_CUDA_CHECK_WARN(c10::cuda::SetDevice(device_index)); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_deletion( + reinterpret_cast(cuda_event)); + } + C10_CUDA_CHECK_WARN(cudaEventDestroy(cuda_event)); + C10_CUDA_CHECK_WARN(c10::cuda::SetDevice(orig_device)); + } + + void record( + void** event, + const Stream& stream, + const DeviceIndex device_index, + const EventFlag flag) const override { + TORCH_CHECK( + device_index == -1 || device_index == stream.device_index(), + "Event device index ", + device_index, + " does not match recording stream's device index ", + stream.device_index(), + "."); + + cudaEvent_t cuda_event = static_cast(*event); + CUDAStream cuda_stream{stream}; + + // Moves to stream's device to record + const auto orig_device = getDevice(); + setDevice(stream.device()); + + // Creates the event (lazily) + if (!cuda_event) + createEvent(&cuda_event, flag); + C10_CUDA_CHECK(cudaEventRecord(cuda_event, cuda_stream)); + // Makes the void* point to the (possibly just allocated) CUDA event + *event = cuda_event; + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_record( + reinterpret_cast(cuda_event), + reinterpret_cast(cuda_stream.stream())); + } + + // Resets device + setDevice(orig_device); + } + + void block(void* event, const Stream& stream) const override { + if (!event) + return; + cudaEvent_t cuda_event = static_cast(event); + CUDAStream cuda_stream{stream}; + const auto orig_device = getDevice(); + setDevice(stream.device()); + C10_CUDA_CHECK(cudaStreamWaitEvent( + cuda_stream, + cuda_event, + /*flags (must be zero)=*/0)); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_wait( + reinterpret_cast(cuda_event), + reinterpret_cast(cuda_stream.stream())); + } + setDevice(orig_device); + } + + // May be called from any device + bool queryEvent(void* event) const override { + if (!event) + return true; + cudaEvent_t cuda_event = static_cast(event); + const cudaError_t err = C10_CUDA_ERROR_HANDLED(cudaEventQuery(cuda_event)); + if (err != cudaErrorNotReady) { + C10_CUDA_CHECK(err); + } else { + // ignore and clear the error if not ready + (void)cudaGetLastError(); + } + return (err == cudaSuccess); + } + + // Stream-related functions + bool queryStream(const Stream& stream) const override { + CUDAStream cuda_stream{stream}; + return cuda_stream.query(); + } + + void synchronizeStream(const Stream& stream) const override { + CUDAStream cuda_stream{stream}; + cuda_stream.synchronize(); + } + + void recordDataPtrOnStream(const c10::DataPtr& data_ptr, const Stream& stream) + const override { + CUDAStream cuda_stream{stream}; + CUDACachingAllocator::recordStream(data_ptr, cuda_stream); + } +}; + +} // namespace c10::cuda::impl diff --git a/shared/package-files/56/5627831bc850c2f3bb9ecaafe77e4a9afaa5c219ac19f0acdebde802a9078900/special_modified_bessel_k0_ops.h b/shared/package-files/56/5627831bc850c2f3bb9ecaafe77e4a9afaa5c219ac19f0acdebde802a9078900/special_modified_bessel_k0_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6d03401eea9cc72a757bbbdc8a6ac0bda97f4556 --- /dev/null +++ b/shared/package-files/56/5627831bc850c2f3bb9ecaafe77e4a9afaa5c219ac19f0acdebde802a9078900/special_modified_bessel_k0_ops.h @@ -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 special_modified_bessel_k0 { + 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::special_modified_bessel_k0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_modified_bessel_k0(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 special_modified_bessel_k0_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::special_modified_bessel_k0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_modified_bessel_k0.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/56/562825f936033f38d1b61561663a9b6f3352aeed36351d6259f65f9a1ed621f2/softplus_backward.h b/shared/package-files/56/562825f936033f38d1b61561663a9b6f3352aeed36351d6259f65f9a1ed621f2/softplus_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..fc5fdfa8ff84b659ac6c895274c7439a0e2da020 --- /dev/null +++ b/shared/package-files/56/562825f936033f38d1b61561663a9b6f3352aeed36351d6259f65f9a1ed621f2/softplus_backward.h @@ -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::softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & softplus_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold) { + return at::_ops::softplus_backward_grad_input::call(grad_output, self, beta, threshold, grad_input); +} +// aten::softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & softplus_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold, at::Tensor & grad_input) { + return at::_ops::softplus_backward_grad_input::call(grad_output, self, beta, threshold, grad_input); +} + +// aten::softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor +inline at::Tensor softplus_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold) { + return at::_ops::softplus_backward::call(grad_output, self, beta, threshold); +} + +} diff --git a/shared/package-files/56/562d4b893ac95f9058d000cbc68264c02ec7dbb1f7d2d4cf33cf71674e00e465/Backtrace.h b/shared/package-files/56/562d4b893ac95f9058d000cbc68264c02ec7dbb1f7d2d4cf33cf71674e00e465/Backtrace.h new file mode 100644 index 0000000000000000000000000000000000000000..ac728968750297227c1be4aa3e444557c1899b03 --- /dev/null +++ b/shared/package-files/56/562d4b893ac95f9058d000cbc68264c02ec7dbb1f7d2d4cf33cf71674e00e465/Backtrace.h @@ -0,0 +1,2 @@ +#include +#include diff --git a/shared/package-files/56/562d4d8bd25e6725fb9145fb60482f6a3d52ea4cba472532f2a2ff08e375520c/__init__.py b/shared/package-files/56/562d4d8bd25e6725fb9145fb60482f6a3d52ea4cba472532f2a2ff08e375520c/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e2eeddc88f079f90cdc1df9ac8e6ba3b62578639 --- /dev/null +++ b/shared/package-files/56/562d4d8bd25e6725fb9145fb60482f6a3d52ea4cba472532f2a2ff08e375520c/__init__.py @@ -0,0 +1,20 @@ +# coding: utf-8 +from __future__ import absolute_import +from six.moves import cStringIO +from .unparser import Unparser +from .printer import Printer + + +__version__ = '1.6.3' + + +def unparse(tree): + v = cStringIO() + Unparser(tree, file=v) + return v.getvalue() + + +def dump(tree): + v = cStringIO() + Printer(file=v).visit(tree) + return v.getvalue() diff --git a/shared/package-files/56/562d986ed52133d57160f6373c1bf17eed31658afa7c1cac9798103c9128f3c9/__init__.py b/shared/package-files/56/562d986ed52133d57160f6373c1bf17eed31658afa7c1cac9798103c9128f3c9/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33c1f014b867cc069d532839b405c3f7696c5a22 --- /dev/null +++ b/shared/package-files/56/562d986ed52133d57160f6373c1bf17eed31658afa7c1cac9798103c9128f3c9/__init__.py @@ -0,0 +1,285 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +from contourpy._contourpy import ( + ContourGenerator, + FillType, + LineType, + Mpl2005ContourGenerator, + Mpl2014ContourGenerator, + SerialContourGenerator, + ThreadedContourGenerator, + ZInterp, + max_threads, +) +from contourpy._version import __version__ +from contourpy.chunk import calc_chunk_sizes +from contourpy.convert import ( + convert_filled, + convert_lines, + convert_multi_filled, + convert_multi_lines, +) +from contourpy.dechunk import ( + dechunk_filled, + dechunk_lines, + dechunk_multi_filled, + dechunk_multi_lines, +) +from contourpy.enum_util import as_fill_type, as_line_type, as_z_interp + +if TYPE_CHECKING: + from typing import Any + + from numpy.typing import ArrayLike + + from ._contourpy import CoordinateArray, MaskArray + +__all__ = [ + "__version__", + "contour_generator", + "convert_filled", + "convert_lines", + "convert_multi_filled", + "convert_multi_lines", + "dechunk_filled", + "dechunk_lines", + "dechunk_multi_filled", + "dechunk_multi_lines", + "max_threads", + "FillType", + "LineType", + "ContourGenerator", + "Mpl2005ContourGenerator", + "Mpl2014ContourGenerator", + "SerialContourGenerator", + "ThreadedContourGenerator", + "ZInterp", +] + + +# Simple mapping of algorithm name to class name. +_class_lookup: dict[str, type[ContourGenerator]] = { + "mpl2005": Mpl2005ContourGenerator, + "mpl2014": Mpl2014ContourGenerator, + "serial": SerialContourGenerator, + "threaded": ThreadedContourGenerator, +} + + +def _remove_z_mask( + z: ArrayLike | np.ma.MaskedArray[Any, Any] | None, +) -> tuple[CoordinateArray, MaskArray | None]: + # Preserve mask if present. + z_array = np.ma.asarray(z, dtype=np.float64) # type: ignore[no-untyped-call] + z_masked = np.ma.masked_invalid(z_array, copy=False) # type: ignore[no-untyped-call] + + if np.ma.is_masked(z_masked): # type: ignore[no-untyped-call] + mask = np.ma.getmask(z_masked) # type: ignore[no-untyped-call] + else: + mask = None + + return np.ma.getdata(z_masked), mask # type: ignore[no-untyped-call] + + +def contour_generator( + x: ArrayLike | None = None, + y: ArrayLike | None = None, + z: ArrayLike | np.ma.MaskedArray[Any, Any] | None = None, + *, + name: str = "serial", + corner_mask: bool | None = None, + line_type: LineType | str | None = None, + fill_type: FillType | str | None = None, + chunk_size: int | tuple[int, int] | None = None, + chunk_count: int | tuple[int, int] | None = None, + total_chunk_count: int | None = None, + quad_as_tri: bool = False, + z_interp: ZInterp | str | None = ZInterp.Linear, + thread_count: int = 0, +) -> ContourGenerator: + """Create and return a :class:`~.ContourGenerator` object. + + The class and properties of the returned :class:`~.ContourGenerator` are determined by the + function arguments, with sensible defaults. + + Args: + x (array-like of shape (ny, nx) or (nx,), optional): The x-coordinates of the ``z`` values. + May be 2D with the same shape as ``z.shape``, or 1D with length ``nx = z.shape[1]``. + If not specified are assumed to be ``np.arange(nx)``. Must be ordered monotonically. + y (array-like of shape (ny, nx) or (ny,), optional): The y-coordinates of the ``z`` values. + May be 2D with the same shape as ``z.shape``, or 1D with length ``ny = z.shape[0]``. + If not specified are assumed to be ``np.arange(ny)``. Must be ordered monotonically. + z (array-like of shape (ny, nx), may be a masked array): The 2D gridded values to calculate + the contours of. May be a masked array, and any invalid values (``np.inf`` or + ``np.nan``) will also be masked out. + name (str): Algorithm name, one of ``"serial"``, ``"threaded"``, ``"mpl2005"`` or + ``"mpl2014"``, default ``"serial"``. + corner_mask (bool, optional): Enable/disable corner masking, which only has an effect if + ``z`` is a masked array. If ``False``, any quad touching a masked point is masked out. + If ``True``, only the triangular corners of quads nearest these points are always masked + out, other triangular corners comprising three unmasked points are contoured as usual. + If not specified, uses the default provided by the algorithm ``name``. + line_type (LineType or str, optional): The format of contour line data returned from calls + to :meth:`~.ContourGenerator.lines`, specified either as a :class:`~.LineType` or its + string equivalent such as ``"SeparateCode"``. + If not specified, uses the default provided by the algorithm ``name``. + The relationship between the :class:`~.LineType` enum and the data format returned from + :meth:`~.ContourGenerator.lines` is explained at :ref:`line_type`. + fill_type (FillType or str, optional): The format of filled contour data returned from calls + to :meth:`~.ContourGenerator.filled`, specified either as a :class:`~.FillType` or its + string equivalent such as ``"OuterOffset"``. + If not specified, uses the default provided by the algorithm ``name``. + The relationship between the :class:`~.FillType` enum and the data format returned from + :meth:`~.ContourGenerator.filled` is explained at :ref:`fill_type`. + chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same + size in both directions if only one value is specified. + chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the + same count in both directions if only one value is specified. + total_chunk_count (int, optional): Total number of chunks. + quad_as_tri (bool): Enable/disable treating quads as 4 triangles, default ``False``. + If ``False``, a contour line within a quad is a straight line between points on two of + its edges. If ``True``, each full quad is divided into 4 triangles using a virtual point + at the centre (mean x, y of the corner points) and a contour line is piecewise linear + within those triangles. Corner-masked triangles are not affected by this setting, only + full unmasked quads. + z_interp (ZInterp or str, optional): How to interpolate ``z`` values when determining where + contour lines intersect the edges of quads and the ``z`` values of the central points of + quads, specified either as a :class:`~contourpy.ZInterp` or its string equivalent such + as ``"Log"``. Default is ``ZInterp.Linear``. + thread_count (int): Number of threads to use for contour calculation, default 0. Threads can + only be used with an algorithm ``name`` that supports threads (currently only + ``name="threaded"``) and there must be at least the same number of chunks as threads. + If ``thread_count=0`` and ``name="threaded"`` then it uses the maximum number of threads + as determined by the C++11 call ``std::thread::hardware_concurrency()``. If ``name`` is + something other than ``"threaded"`` then the ``thread_count`` will be set to ``1``. + + Return: + :class:`~.ContourGenerator`. + + Note: + A maximum of one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` may be + specified. + + Warning: + The ``name="mpl2005"`` algorithm does not implement chunking for contour lines. + """ + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + z, mask = _remove_z_mask(z) + + # Check arguments: z. + if z.ndim != 2: + raise TypeError(f"Input z must be 2D, not {z.ndim}D") + + if z.shape[0] < 2 or z.shape[1] < 2: + raise TypeError(f"Input z must be at least a (2, 2) shaped array, but has shape {z.shape}") + + ny, nx = z.shape + + # Check arguments: x and y. + if x.ndim != y.ndim: + raise TypeError(f"Number of dimensions of x ({x.ndim}) and y ({y.ndim}) do not match") + + if x.ndim == 0: + x = np.arange(nx, dtype=np.float64) + y = np.arange(ny, dtype=np.float64) + x, y = np.meshgrid(x, y) + elif x.ndim == 1: + if len(x) != nx: + raise TypeError(f"Length of x ({len(x)}) must match number of columns in z ({nx})") + if len(y) != ny: + raise TypeError(f"Length of y ({len(y)}) must match number of rows in z ({ny})") + x, y = np.meshgrid(x, y) + elif x.ndim == 2: + if x.shape != z.shape: + raise TypeError(f"Shapes of x {x.shape} and z {z.shape} do not match") + if y.shape != z.shape: + raise TypeError(f"Shapes of y {y.shape} and z {z.shape} do not match") + else: + raise TypeError(f"Inputs x and y must be None, 1D or 2D, not {x.ndim}D") + + # Check mask shape just in case. + if mask is not None and mask.shape != z.shape: + raise ValueError("If mask is set it must be a 2D array with the same shape as z") + + # Check arguments: name. + if name not in _class_lookup: + raise ValueError(f"Unrecognised contour generator name: {name}") + + # Check arguments: chunk_size, chunk_count and total_chunk_count. + y_chunk_size, x_chunk_size = calc_chunk_sizes( + chunk_size, chunk_count, total_chunk_count, ny, nx) + + cls = _class_lookup[name] + + # Check arguments: corner_mask. + if corner_mask is None: + # Set it to default, which is True if the algorithm supports it. + corner_mask = cls.supports_corner_mask() + elif corner_mask and not cls.supports_corner_mask(): + raise ValueError(f"{name} contour generator does not support corner_mask=True") + + # Check arguments: line_type. + if line_type is None: + line_type = cls.default_line_type + else: + line_type = as_line_type(line_type) + + if not cls.supports_line_type(line_type): + raise ValueError(f"{name} contour generator does not support line_type {line_type}") + + # Check arguments: fill_type. + if fill_type is None: + fill_type = cls.default_fill_type + else: + fill_type = as_fill_type(fill_type) + + if not cls.supports_fill_type(fill_type): + raise ValueError(f"{name} contour generator does not support fill_type {fill_type}") + + # Check arguments: quad_as_tri. + if quad_as_tri and not cls.supports_quad_as_tri(): + raise ValueError(f"{name} contour generator does not support quad_as_tri=True") + + # Check arguments: z_interp. + if z_interp is None: + z_interp = ZInterp.Linear + else: + z_interp = as_z_interp(z_interp) + + if z_interp != ZInterp.Linear and not cls.supports_z_interp(): + raise ValueError(f"{name} contour generator does not support z_interp {z_interp}") + + # Check arguments: thread_count. + if thread_count not in (0, 1) and not cls.supports_threads(): + raise ValueError(f"{name} contour generator does not support thread_count {thread_count}") + + # Prepare args and kwargs for contour generator constructor. + args = [x, y, z, mask] + kwargs: dict[str, int | bool | LineType | FillType | ZInterp] = { + "x_chunk_size": x_chunk_size, + "y_chunk_size": y_chunk_size, + } + + if name not in ("mpl2005", "mpl2014"): + kwargs["line_type"] = line_type + kwargs["fill_type"] = fill_type + + if cls.supports_corner_mask(): + kwargs["corner_mask"] = corner_mask + + if cls.supports_quad_as_tri(): + kwargs["quad_as_tri"] = quad_as_tri + + if cls.supports_z_interp(): + kwargs["z_interp"] = z_interp + + if cls.supports_threads(): + kwargs["thread_count"] = thread_count + + # Create contour generator. + return cls(*args, **kwargs) diff --git a/shared/package-files/56/56325687bbec94c348a1074f14d525019234131b8b155e8476bcb061a223a905/dotnet.py b/shared/package-files/56/56325687bbec94c348a1074f14d525019234131b8b155e8476bcb061a223a905/dotnet.py new file mode 100644 index 0000000000000000000000000000000000000000..5c488dd9743d9676c0079196c3af85ecac832739 --- /dev/null +++ b/shared/package-files/56/56325687bbec94c348a1074f14d525019234131b8b155e8476bcb061a223a905/dotnet.py @@ -0,0 +1,841 @@ +""" + pygments.lexers.dotnet + ~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for .net languages. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" +import re + +from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \ + using, this, default, words +from pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ + Name, String, Number, Literal, Other, Whitespace +from pygments.util import get_choice_opt +from pygments import unistring as uni + +from pygments.lexers.html import XmlLexer + +__all__ = ['CSharpLexer', 'NemerleLexer', 'BooLexer', 'VbNetLexer', + 'CSharpAspxLexer', 'VbNetAspxLexer', 'FSharpLexer', 'XppLexer'] + + +class CSharpLexer(RegexLexer): + """ + For C# source code. + + Additional options accepted: + + `unicodelevel` + Determines which Unicode characters this lexer allows for identifiers. + The possible values are: + + * ``none`` -- only the ASCII letters and numbers are allowed. This + is the fastest selection. + * ``basic`` -- all Unicode characters from the specification except + category ``Lo`` are allowed. + * ``full`` -- all Unicode characters as specified in the C# specs + are allowed. Note that this means a considerable slowdown since the + ``Lo`` category has more than 40,000 characters in it! + + The default value is ``basic``. + + .. versionadded:: 0.8 + """ + + name = 'C#' + url = 'https://docs.microsoft.com/en-us/dotnet/csharp/' + aliases = ['csharp', 'c#', 'cs'] + filenames = ['*.cs'] + mimetypes = ['text/x-csharp'] # inferred + + flags = re.MULTILINE | re.DOTALL + + # for the range of allowed unicode characters in identifiers, see + # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf + + levels = { + 'none': r'@?[_a-zA-Z]\w*', + 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', + 'Cf', 'Mn', 'Mc') + ']*'), + 'full': ('@?(?:_|[^' + + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', + 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), + } + + tokens = {} + token_variants = True + + for levelname, cs_ident in levels.items(): + tokens[levelname] = { + 'root': [ + # method names + (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type + r'(' + cs_ident + ')' # method name + r'(\s*)(\()', # signature start + bygroups(Whitespace, using(this), Name.Function, Whitespace, + Punctuation)), + (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), + (r'[^\S\n]+', Whitespace), + (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation + (r'//.*?\n', Comment.Single), + (r'/[*].*?[*]/', Comment.Multiline), + (r'\n', Whitespace), + (words(( + '>>>=', '>>=', '<<=', '<=', '>=', '+=', '-=', '*=', '/=', + '%=', '&=', '|=', '^=', '??=', '=>', '??', '?.', '!=', '==', + '&&', '||', '>>>', '>>', '<<', '++', '--', '+', '-', '*', + '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', + )), Operator), + (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), + (r'[()\[\];:,.]', Punctuation), + (r'[{}]', Punctuation), + (r'@"(""|[^"])*"', String), + (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), + (r"'\\.'|'[^\\]'", String.Char), + (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" + r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), + (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' + r'line|error|warning|region|endregion|pragma)\b(.*?)(\n)', + bygroups(Comment.Preproc, Whitespace, Comment.Preproc, + Comment.Preproc, Whitespace)), + (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, + Keyword)), + (r'(abstract|as|async|await|base|break|by|case|catch|' + r'checked|const|continue|default|delegate|' + r'do|else|enum|event|explicit|extern|false|finally|' + r'fixed|for|foreach|goto|if|implicit|in|interface|' + r'internal|is|let|lock|new|null|on|operator|' + r'out|override|params|private|protected|public|readonly|' + r'ref|return|sealed|sizeof|stackalloc|static|' + r'switch|this|throw|true|try|typeof|' + r'unchecked|unsafe|virtual|void|while|' + r'get|set|new|partial|yield|add|remove|value|alias|ascending|' + r'descending|from|group|into|orderby|select|thenby|where|' + r'join|equals)\b', Keyword), + (r'(global)(::)', bygroups(Keyword, Punctuation)), + (r'(bool|byte|char|decimal|double|dynamic|float|int|long|object|' + r'sbyte|short|string|uint|ulong|ushort|var)\b\??', Keyword.Type), + (r'(class|struct)(\s+)', bygroups(Keyword, Whitespace), 'class'), + (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), + (cs_ident, Name), + ], + 'class': [ + (cs_ident, Name.Class, '#pop'), + default('#pop'), + ], + 'namespace': [ + (r'(?=\()', Text, '#pop'), # using (resource) + ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop'), + ] + } + + def __init__(self, **options): + level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic') + if level not in self._all_tokens: + # compile the regexes now + self._tokens = self.__class__.process_tokendef(level) + else: + self._tokens = self._all_tokens[level] + + RegexLexer.__init__(self, **options) + + +class NemerleLexer(RegexLexer): + """ + For Nemerle source code. + + Additional options accepted: + + `unicodelevel` + Determines which Unicode characters this lexer allows for identifiers. + The possible values are: + + * ``none`` -- only the ASCII letters and numbers are allowed. This + is the fastest selection. + * ``basic`` -- all Unicode characters from the specification except + category ``Lo`` are allowed. + * ``full`` -- all Unicode characters as specified in the C# specs + are allowed. Note that this means a considerable slowdown since the + ``Lo`` category has more than 40,000 characters in it! + + The default value is ``basic``. + + .. versionadded:: 1.5 + """ + + name = 'Nemerle' + url = 'http://nemerle.org' + aliases = ['nemerle'] + filenames = ['*.n'] + mimetypes = ['text/x-nemerle'] # inferred + + flags = re.MULTILINE | re.DOTALL + + # for the range of allowed unicode characters in identifiers, see + # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf + + levels = { + 'none': r'@?[_a-zA-Z]\w*', + 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', + 'Cf', 'Mn', 'Mc') + ']*'), + 'full': ('@?(?:_|[^' + + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', + 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), + } + + tokens = {} + token_variants = True + + for levelname, cs_ident in levels.items(): + tokens[levelname] = { + 'root': [ + # method names + (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type + r'(' + cs_ident + ')' # method name + r'(\s*)(\()', # signature start + bygroups(Whitespace, using(this), Name.Function, Whitespace, \ + Punctuation)), + (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), + (r'[^\S\n]+', Whitespace), + (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation + (r'//.*?\n', Comment.Single), + (r'/[*].*?[*]/', Comment.Multiline), + (r'\n', Whitespace), + (r'(\$)(\s*)(")', bygroups(String, Whitespace, String), + 'splice-string'), + (r'(\$)(\s*)(<#)', bygroups(String, Whitespace, String), + 'splice-string2'), + (r'<#', String, 'recursive-string'), + + (r'(<\[)(\s*)(' + cs_ident + ':)?', + bygroups(Keyword, Whitespace, Keyword)), + (r'\]\>', Keyword), + + # quasiquotation only + (r'\$' + cs_ident, Name), + (r'(\$)(\()', bygroups(Name, Punctuation), + 'splice-string-content'), + + (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation), + (r'[{}]', Punctuation), + (r'@"(""|[^"])*"', String), + (r'"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), + (r"'\\.'|'[^\\]'", String.Char), + (r"0[xX][0-9a-fA-F]+[Ll]?", Number), + (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number), + (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' + r'line|error|warning|region|endregion|pragma)\b', + bygroups(Comment.Preproc, Whitespace, Comment.Preproc), 'preproc'), + (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)), + (r'(abstract|and|as|base|catch|def|delegate|' + r'enum|event|extern|false|finally|' + r'fun|implements|interface|internal|' + r'is|macro|match|matches|module|mutable|new|' + r'null|out|override|params|partial|private|' + r'protected|public|ref|sealed|static|' + r'syntax|this|throw|true|try|type|typeof|' + r'virtual|volatile|when|where|with|' + r'assert|assert2|async|break|checked|continue|do|else|' + r'ensures|for|foreach|if|late|lock|new|nolate|' + r'otherwise|regexp|repeat|requires|return|surroundwith|' + r'unchecked|unless|using|while|yield)\b', Keyword), + (r'(global)(::)', bygroups(Keyword, Punctuation)), + (r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|' + r'short|string|uint|ulong|ushort|void|array|list)\b\??', + Keyword.Type), + (r'(:>?)(\s*)(' + cs_ident + r'\??)', + bygroups(Punctuation, Whitespace, Keyword.Type)), + (r'(class|struct|variant|module)(\s+)', + bygroups(Keyword, Whitespace), 'class'), + (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), + 'namespace'), + (cs_ident, Name), + ], + 'class': [ + (cs_ident, Name.Class, '#pop') + ], + 'preproc': [ + (r'\w+', Comment.Preproc), + (r'[ \t]+', Whitespace), + (r'\n', Whitespace, '#pop') + ], + 'namespace': [ + (r'(?=\()', Text, '#pop'), # using (resource) + ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop') + ], + 'splice-string': [ + (r'[^"$]', String), + (r'\$' + cs_ident, Name), + (r'(\$)(\()', bygroups(Name, Punctuation), + 'splice-string-content'), + (r'\\"', String), + (r'"', String, '#pop') + ], + 'splice-string2': [ + (r'[^#<>$]', String), + (r'\$' + cs_ident, Name), + (r'(\$)(\()', bygroups(Name, Punctuation), + 'splice-string-content'), + (r'<#', String, '#push'), + (r'#>', String, '#pop') + ], + 'recursive-string': [ + (r'[^#<>]', String), + (r'<#', String, '#push'), + (r'#>', String, '#pop') + ], + 'splice-string-content': [ + (r'if|match', Keyword), + (r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation), + (cs_ident, Name), + (r'\d+', Number), + (r'\(', Punctuation, '#push'), + (r'\)', Punctuation, '#pop') + ] + } + + def __init__(self, **options): + level = get_choice_opt(options, 'unicodelevel', list(self.tokens), + 'basic') + if level not in self._all_tokens: + # compile the regexes now + self._tokens = self.__class__.process_tokendef(level) + else: + self._tokens = self._all_tokens[level] + + RegexLexer.__init__(self, **options) + + def analyse_text(text): + """Nemerle is quite similar to Python, but @if is relatively uncommon + elsewhere.""" + result = 0 + + if '@if' in text: + result += 0.1 + + return result + + +class BooLexer(RegexLexer): + """ + For Boo source code. + """ + + name = 'Boo' + url = 'https://github.com/boo-lang/boo' + aliases = ['boo'] + filenames = ['*.boo'] + mimetypes = ['text/x-boo'] + + tokens = { + 'root': [ + (r'\s+', Whitespace), + (r'(#|//).*$', Comment.Single), + (r'/[*]', Comment.Multiline, 'comment'), + (r'[]{}:(),.;[]', Punctuation), + (r'(\\)(\n)', bygroups(Text, Whitespace)), + (r'\\', Text), + (r'(in|is|and|or|not)\b', Operator.Word), + (r'/(\\\\|\\[^\\]|[^/\\\s])/', String.Regex), + (r'@/(\\\\|\\[^\\]|[^/\\])*/', String.Regex), + (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), + (r'(as|abstract|callable|constructor|destructor|do|import|' + r'enum|event|final|get|interface|internal|of|override|' + r'partial|private|protected|public|return|set|static|' + r'struct|transient|virtual|yield|super|and|break|cast|' + r'continue|elif|else|ensure|except|for|given|goto|if|in|' + r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|' + r'while|from|as)\b', Keyword), + (r'def(?=\s+\(.*?\))', Keyword), + (r'(def)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), + (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'), + (r'(namespace)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), + (r'(?', Name.Attribute), + (r'\s+', Whitespace), + (r'\n', Whitespace), + (r'(rem\b.*?)(\n)', bygroups(Comment, Whitespace)), + (r"('.*?)(\n)", bygroups(Comment, Whitespace)), + (r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#Else|#End\s+If|#Const|' + r'#ExternalSource.*?\n|#End\s+ExternalSource|' + r'#Region.*?\n|#End\s+Region|#ExternalChecksum', + Comment.Preproc), + (r'[(){}!#,.:]', Punctuation), + (r'(Option)(\s+)(Strict|Explicit|Compare)(\s+)' + r'(On|Off|Binary|Text)', + bygroups(Keyword.Declaration, Whitespace, Keyword.Declaration, + Whitespace, Keyword.Declaration)), + (words(( + 'AddHandler', 'Alias', 'ByRef', 'ByVal', 'Call', 'Case', + 'Catch', 'CBool', 'CByte', 'CChar', 'CDate', 'CDec', 'CDbl', + 'CInt', 'CLng', 'CObj', 'Continue', 'CSByte', 'CShort', 'CSng', + 'CStr', 'CType', 'CUInt', 'CULng', 'CUShort', 'Declare', + 'Default', 'Delegate', 'DirectCast', 'Do', 'Each', 'Else', + 'ElseIf', 'EndIf', 'Erase', 'Error', 'Event', 'Exit', 'False', + 'Finally', 'For', 'Friend', 'Get', 'Global', 'GoSub', 'GoTo', + 'Handles', 'If', 'Implements', 'Inherits', 'Interface', 'Let', + 'Lib', 'Loop', 'Me', 'MustInherit', 'MustOverride', 'MyBase', + 'MyClass', 'Narrowing', 'New', 'Next', 'Not', 'Nothing', + 'NotInheritable', 'NotOverridable', 'Of', 'On', 'Operator', + 'Option', 'Optional', 'Overloads', 'Overridable', 'Overrides', + 'ParamArray', 'Partial', 'Private', 'Protected', 'Public', + 'RaiseEvent', 'ReadOnly', 'ReDim', 'RemoveHandler', 'Resume', + 'Return', 'Select', 'Set', 'Shadows', 'Shared', 'Single', + 'Static', 'Step', 'Stop', 'SyncLock', 'Then', 'Throw', 'To', + 'True', 'Try', 'TryCast', 'Wend', 'Using', 'When', 'While', + 'Widening', 'With', 'WithEvents', 'WriteOnly'), + prefix=r'(?>=|<<|>>|:=|' + r'<=|>=|<>|[-&*/\\^+=<>\[\]]', + Operator), + ('"', String, 'string'), + (r'(_)(\n)', bygroups(Text, Whitespace)), # Line continuation (must be before Name) + (uni_name + '[%&@!#$]?', Name), + ('#.*?#', Literal.Date), + (r'(\d+\.\d*|\d*\.\d+)(F[+-]?[0-9]+)?', Number.Float), + (r'\d+([SILDFR]|US|UI|UL)?', Number.Integer), + (r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer), + (r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer), + ], + 'string': [ + (r'""', String), + (r'"C?', String, '#pop'), + (r'[^"]+', String), + ], + 'dim': [ + (uni_name, Name.Variable, '#pop'), + default('#pop'), # any other syntax + ], + 'funcname': [ + (uni_name, Name.Function, '#pop'), + ], + 'classname': [ + (uni_name, Name.Class, '#pop'), + ], + 'namespace': [ + (uni_name, Name.Namespace), + (r'\.', Name.Namespace), + default('#pop'), + ], + 'end': [ + (r'\s+', Whitespace), + (r'(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b', + Keyword, '#pop'), + default('#pop'), + ] + } + + def analyse_text(text): + if re.search(r'^\s*(#If|Module|Namespace)', text, re.MULTILINE): + return 0.5 + + +class GenericAspxLexer(RegexLexer): + """ + Lexer for ASP.NET pages. + """ + + name = 'aspx-gen' + filenames = [] + mimetypes = [] + + flags = re.DOTALL + + tokens = { + 'root': [ + (r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)), + (r'()(.*?)()', bygroups(using(XmlLexer), + Other, + using(XmlLexer))), + (r'(.+?)(?=<)', using(XmlLexer)), + (r'.+', using(XmlLexer)), + ], + } + + +# TODO support multiple languages within the same source file +class CSharpAspxLexer(DelegatingLexer): + """ + Lexer for highlighting C# within ASP.NET pages. + """ + + name = 'aspx-cs' + aliases = ['aspx-cs'] + filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] + mimetypes = [] + + def __init__(self, **options): + super().__init__(CSharpLexer, GenericAspxLexer, **options) + + def analyse_text(text): + if re.search(r'Page\s*Language="C#"', text, re.I) is not None: + return 0.2 + elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None: + return 0.15 + + +class VbNetAspxLexer(DelegatingLexer): + """ + Lexer for highlighting Visual Basic.net within ASP.NET pages. + """ + + name = 'aspx-vb' + aliases = ['aspx-vb'] + filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] + mimetypes = [] + + def __init__(self, **options): + super().__init__(VbNetLexer, GenericAspxLexer, **options) + + def analyse_text(text): + if re.search(r'Page\s*Language="Vb"', text, re.I) is not None: + return 0.2 + elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None: + return 0.15 + + +# Very close to functional.OcamlLexer +class FSharpLexer(RegexLexer): + """ + For the F# language (version 3.0). + + .. versionadded:: 1.5 + """ + + name = 'F#' + url = 'https://fsharp.org/' + aliases = ['fsharp', 'f#'] + filenames = ['*.fs', '*.fsi', '*.fsx'] + mimetypes = ['text/x-fsharp'] + + keywords = [ + 'abstract', 'as', 'assert', 'base', 'begin', 'class', 'default', + 'delegate', 'do!', 'do', 'done', 'downcast', 'downto', 'elif', 'else', + 'end', 'exception', 'extern', 'false', 'finally', 'for', 'function', + 'fun', 'global', 'if', 'inherit', 'inline', 'interface', 'internal', + 'in', 'lazy', 'let!', 'let', 'match', 'member', 'module', 'mutable', + 'namespace', 'new', 'null', 'of', 'open', 'override', 'private', 'public', + 'rec', 'return!', 'return', 'select', 'static', 'struct', 'then', 'to', + 'true', 'try', 'type', 'upcast', 'use!', 'use', 'val', 'void', 'when', + 'while', 'with', 'yield!', 'yield', + ] + # Reserved words; cannot hurt to color them as keywords too. + keywords += [ + 'atomic', 'break', 'checked', 'component', 'const', 'constraint', + 'constructor', 'continue', 'eager', 'event', 'external', 'fixed', + 'functor', 'include', 'method', 'mixin', 'object', 'parallel', + 'process', 'protected', 'pure', 'sealed', 'tailcall', 'trait', + 'virtual', 'volatile', + ] + keyopts = [ + '!=', '#', '&&', '&', r'\(', r'\)', r'\*', r'\+', ',', r'-\.', + '->', '-', r'\.\.', r'\.', '::', ':=', ':>', ':', ';;', ';', '<-', + r'<\]', '<', r'>\]', '>', r'\?\?', r'\?', r'\[<', r'\[\|', r'\[', r'\]', + '_', '`', r'\{', r'\|\]', r'\|', r'\}', '~', '<@@', '<@', '=', '@>', '@@>', + ] + + operators = r'[!$%&*+\./:<=>?@^|~-]' + word_operators = ['and', 'or', 'not'] + prefix_syms = r'[!?~]' + infix_syms = r'[=<>@^|&+\*/$%-]' + primitives = [ + 'sbyte', 'byte', 'char', 'nativeint', 'unativeint', 'float32', 'single', + 'float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', + 'uint32', 'int64', 'uint64', 'decimal', 'unit', 'bool', 'string', + 'list', 'exn', 'obj', 'enum', + ] + + # See http://msdn.microsoft.com/en-us/library/dd233181.aspx and/or + # http://fsharp.org/about/files/spec.pdf for reference. Good luck. + + tokens = { + 'escape-sequence': [ + (r'\\[\\"\'ntbrafv]', String.Escape), + (r'\\[0-9]{3}', String.Escape), + (r'\\u[0-9a-fA-F]{4}', String.Escape), + (r'\\U[0-9a-fA-F]{8}', String.Escape), + ], + 'root': [ + (r'\s+', Whitespace), + (r'\(\)|\[\]', Name.Builtin.Pseudo), + (r'\b(? and <| are weak + indicators.""" + result = 0 + if '|>' in text: + result += 0.05 + if '<|' in text: + result += 0.05 + + return result + + +class XppLexer(RegexLexer): + + """ + For X++ source code. This is based loosely on the CSharpLexer + + .. versionadded:: 2.15 + """ + + name = 'X++' + url = 'https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/dev-ref/xpp-language-reference' + aliases = ['xpp', 'x++'] + filenames = ['*.xpp'] + + flags = re.MULTILINE + + XPP_CHARS = ('@?(?:_|[^' + + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', + 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'); + # Temporary, see + # https://github.com/thatch/regexlint/pull/49 + XPP_CHARS = XPP_CHARS.replace('\x00', '\x01') + + OPERATORS = ( + '<=', '>=', '+=', '-=', '*=', '/=', '!=', '==', + '&&', '||', '>>', '<<', '++', '--', '+', '-', '*', + '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', + ) + KEYWORDS = ('abstract','anytype','as','async','asc','at','avg','break','breakpoint','by','byref','case','catch', + 'changecompany','client','container','continue','count','crosscompany','default','delegate', + 'delete_from','desc','display','div','do','edit','else','element','eventhandler','exists','false','final', + 'firstfast','firstonly','firstonly10','firstonly100','firstonly1000','flush','for','forceliterals', + 'forcenestedloop','forceplaceholders','forceselectorder','forupdate','from','group','if','insert_recordset', + 'interface','is','join','like','maxof','minof','mod','new','next','nofetch','notexists','null','optimisticlock','order', + 'outer','pause','pessimisticlock','print','private','protected','public','repeatableread','retry','return', + 'reverse','select','server','setting','static','sum','super','switch','tablelock','this','throw','true','try','ttsabort','ttsbegin', + 'ttscommit','update_recordset','validtimestate','void','where','while','window') + RUNTIME_FUNCTIONS = ('_duration','abs','acos','any2Date','any2Enum','any2Guid','any2Int','any2Int64','any2Real','any2Str','anytodate', + 'anytoenum','anytoguid','anytoint','anytoint64','anytoreal','anytostr','asin','atan','beep','cTerm','char2Num','classIdGet', + 'corrFlagGet','corrFlagSet','cos','cosh','curExt','curUserId','date2Num','date2Str','datetime2Str','dayName','dayOfMth', + 'dayOfWk','dayOfYr','ddb','decRound','dg','dimOf','endMth','enum2str','exp','exp10','fV','fieldId2Name','fieldId2PName', + 'fieldName2Id','frac','funcName','getCurrentPartition','getCurrentPartitionRecId','getPrefix','guid2Str','idg','indexId2Name', + 'indexName2Id','int2Str','int642Str','intvMax','intvName','intvNo','intvNorm','log10','logN','match','max','min','mkDate','mthName', + 'mthOfYr','newGuid','nextMth','nextQtr','nextYr','num2Char','num2Date','num2Str','pmt','power','prevMth','prevQtr','prevYr', + 'prmIsDefault','pt','pv','rate','refPrintAll','round','runAs','sessionId','setPrefix','sin','sinh','sleep','sln','str2Date', + 'str2Datetime','str2Enum','str2Guid','str2Int','str2Int64','str2Num','str2Time','strAlpha','strCmp','strColSeq','strDel', + 'strFind','strFmt','strIns','strKeep','strLTrim','strLen','strLine','strLwr','strNFind','strPoke','strPrompt','strRTrim', + 'strRem','strRep','strScan','strUpr','subStr','syd','systemDateGet','systemDateSet','tableId2Name', + 'tableId2PName','tableName2Id','tan','tanh','term','time2Str','timeNow','today','trunc','typeOf','uint2Str','wkOfYr','year') + COMPILE_FUNCTIONS = ('attributeStr','classNum','classStr','configurationKeyNum','configurationKeyStr','dataEntityDataSourceStr','delegateStr', + 'dimensionHierarchyLevelStr','dimensionHierarchyStr','dimensionReferenceStr','dutyStr','enumCnt','enumLiteralStr','enumNum','enumStr', + 'extendedTypeNum','extendedTypeStr','fieldNum','fieldPName','fieldStr','formControlStr','formDataFieldStr','formDataSourceStr', + 'formMethodStr','formStr','identifierStr','indexNum','indexStr','licenseCodeNum','licenseCodeStr','literalStr','maxDate','maxInt', + 'measureStr','measurementStr','menuItemActionStr','menuItemDisplayStr','menuItemOutputStr','menuStr','methodStr','minInt','privilegeStr', + 'queryDatasourceStr','queryMethodStr','queryStr','reportStr','resourceStr','roleStr','ssrsReportStr','staticDelegateStr','staticMethodStr', + 'tableCollectionStr','tableFieldGroupStr','tableMethodStr','tableNum','tablePName','tableStaticMethodStr','tableStr','tileStr','varStr', + 'webActionItemStr','webDisplayContentItemStr','webFormStr','webMenuStr','webOutputContentItemStr','webReportStr','webSiteTempStr', + 'webStaticFileStr','webUrlItemStr','webWebPartStr','webletItemStr','webpageDefStr','websiteDefStr','workflowApprovalStr', + 'workflowCategoryStr','workflowTaskStr','workflowTypeStr') + + tokens = {} + + tokens = { + 'root': [ + # method names + (r'(\s*)\b(else|if)\b([^\n])', bygroups(Whitespace, Keyword, using(this))), # ensure that if is not treated like a function + (r'^([ \t]*)((?:' + XPP_CHARS + r'(?:\[\])?\s+)+?)' # return type + r'(' + XPP_CHARS + ')' # method name + r'(\s*)(\()', # signature start + bygroups(Whitespace, using(this), Name.Function, Whitespace, + Punctuation)), + (r'^(\s*)(\[)([^\n]*?)(\])', bygroups(Whitespace, Name.Attribute, Name.Variable.Class, Name.Attribute)), + (r'[^\S\n]+', Whitespace), + (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation + (r'//[^\n]*?\n', Comment.Single), + (r'/[*][^\n]*?[*]/', Comment.Multiline), + (r'\n', Whitespace), + (words(OPERATORS), Operator), + (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), + (r'[()\[\];:,.#@]', Punctuation), + (r'[{}]', Punctuation), + (r'@"(""|[^"])*"', String), + (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), + (r"'\\.'|'[^\\]'", String.Char), + (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" + r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), + (words(KEYWORDS, suffix=r'\b'), Keyword), + (r'(boolean|int|int64|str|real|guid|date)\b\??', Keyword.Type), + (r'(class|struct|extends|implements)(\s+)', bygroups(Keyword, Whitespace), 'class'), + (r'('+XPP_CHARS+')(::)', bygroups(Name.Variable.Class, Punctuation)), + (r'(\s*)(\w+)(\s+\w+(,|=)?[^\n]*;)', bygroups(Whitespace, Name.Variable.Class, using(this))), # declaration + # x++ specific function to get field should highlight the classname + (r'(fieldNum\()('+XPP_CHARS+r')(\s*,\s*)('+XPP_CHARS+r')(\s*\))', + bygroups(using(this), Name.Variable.Class, using(this), Name.Property, using(this))), + # x++ specific function to get table should highlight the classname + (r'(tableNum\()('+XPP_CHARS+r')(\s*\))', + bygroups(using(this), Name.Variable.Class, using(this))), + (words(RUNTIME_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), + (words(COMPILE_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), + (XPP_CHARS, Name), + ], + 'class': [ + (XPP_CHARS, Name.Class, '#pop'), + default('#pop'), + ], + 'namespace': [ + (r'(?=\()', Text, '#pop'), # using (resource) + ('(' + XPP_CHARS + r'|\.)+', Name.Namespace, '#pop'), + ] + } diff --git a/shared/package-files/56/5637254ab13a7f25d7584d074a6c0fa33cde89d8b7a9f397d94291ce47025fd0/_cast_Half.h b/shared/package-files/56/5637254ab13a7f25d7584d074a6c0fa33cde89d8b7a9f397d94291ce47025fd0/_cast_Half.h new file mode 100644 index 0000000000000000000000000000000000000000..08d54433f81df2aef0b82ffb1db85ce1de61489b --- /dev/null +++ b/shared/package-files/56/5637254ab13a7f25d7584d074a6c0fa33cde89d8b7a9f397d94291ce47025fd0/_cast_Half.h @@ -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::_cast_Half(Tensor self, bool non_blocking=False) -> Tensor +inline at::Tensor _cast_Half(const at::Tensor & self, bool non_blocking=false) { + return at::_ops::_cast_Half::call(self, non_blocking); +} + +} diff --git a/shared/package-files/56/563906875503fa2d734c3035757a35b9e712b3a3f11dd190e6f94293f982098b/__main__.py b/shared/package-files/56/563906875503fa2d734c3035757a35b9e712b3a3f11dd190e6f94293f982098b/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c74ad3c86e54cb7e9939ed2bf96aa59cc6dcd06 --- /dev/null +++ b/shared/package-files/56/563906875503fa2d734c3035757a35b9e712b3a3f11dd190e6f94293f982098b/__main__.py @@ -0,0 +1,35 @@ +import sys + + +def main(args=None): + if args is None: + args = sys.argv[1:] + + # TODO Handle library-wide options. Eg.: + # --unicodedata + # --verbose / other logging stuff + + # TODO Allow a way to run arbitrary modules? Useful for setting + # library-wide options and calling another library. Eg.: + # + # $ fonttools --unicodedata=... fontmake ... + # + # This allows for a git-like command where thirdparty commands + # can be added. Should we just try importing the fonttools + # module first and try without if it fails? + + if len(sys.argv) < 2: + sys.argv.append("help") + if sys.argv[1] == "-h" or sys.argv[1] == "--help": + sys.argv[1] = "help" + mod = "fontTools." + sys.argv[1] + sys.argv[1] = sys.argv[0] + " " + sys.argv[1] + del sys.argv[0] + + import runpy + + runpy.run_module(mod, run_name="__main__") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/shared/package-files/56/56396fd018eb070fa3025504ec0605f95dfe1aa31824ef3068d3a92c144ab373/streams.pyi b/shared/package-files/56/56396fd018eb070fa3025504ec0605f95dfe1aa31824ef3068d3a92c144ab373/streams.pyi new file mode 100644 index 0000000000000000000000000000000000000000..36aafedd7aa36fc7f88928f9021e92dcc9fe95eb --- /dev/null +++ b/shared/package-files/56/56396fd018eb070fa3025504ec0605f95dfe1aa31824ef3068d3a92c144ab373/streams.pyi @@ -0,0 +1,104 @@ +import sys +from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional, Tuple, Union + +from . import events, protocols, transports + +_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] + +if sys.version_info < (3, 8): + 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: ... + +async def open_connection( + host: Optional[str] = ..., + port: Optional[Union[int, str]] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + ssl_handshake_timeout: Optional[float] = ..., + **kwds: Any, +) -> Tuple[StreamReader, StreamWriter]: ... +async def start_server( + client_connected_cb: _ClientConnectedCallback, + host: Optional[str] = ..., + port: Optional[Union[int, str]] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + ssl_handshake_timeout: Optional[float] = ..., + **kwds: Any, +) -> events.AbstractServer: ... + +if sys.platform != "win32": + if sys.version_info >= (3, 7): + from os import PathLike + + _PathType = Union[str, PathLike[str]] + else: + _PathType = str + async def open_unix_connection( + path: Optional[_PathType] = ..., *, loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., **kwds: Any + ) -> Tuple[StreamReader, StreamWriter]: ... + async def start_unix_server( + client_connected_cb: _ClientConnectedCallback, + path: Optional[_PathType] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any, + ) -> events.AbstractServer: ... + +class FlowControlMixin(protocols.Protocol): ... + +class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): + def __init__( + self, + stream_reader: StreamReader, + client_connected_cb: Optional[_ClientConnectedCallback] = ..., + loop: Optional[events.AbstractEventLoop] = ..., + ) -> None: ... + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Optional[Exception]) -> None: ... + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> bool: ... + +class StreamWriter: + def __init__( + self, + transport: transports.BaseTransport, + protocol: protocols.BaseProtocol, + reader: Optional[StreamReader], + loop: events.AbstractEventLoop, + ) -> None: ... + @property + def transport(self) -> transports.BaseTransport: ... + def write(self, data: bytes) -> None: ... + def writelines(self, data: Iterable[bytes]) -> None: ... + def write_eof(self) -> None: ... + def can_write_eof(self) -> bool: ... + def close(self) -> None: ... + if sys.version_info >= (3, 7): + def is_closing(self) -> bool: ... + async def wait_closed(self) -> None: ... + def get_extra_info(self, name: str, default: Any = ...) -> Any: ... + async def drain(self) -> None: ... + +class StreamReader: + def __init__(self, limit: int = ..., loop: Optional[events.AbstractEventLoop] = ...) -> None: ... + def exception(self) -> Exception: ... + def set_exception(self, exc: Exception) -> None: ... + def set_transport(self, transport: transports.BaseTransport) -> None: ... + def feed_eof(self) -> None: ... + def at_eof(self) -> bool: ... + def feed_data(self, data: bytes) -> None: ... + async def readline(self) -> bytes: ... + async def readuntil(self, separator: bytes = ...) -> bytes: ... + async def read(self, n: int = ...) -> bytes: ... + async def readexactly(self, n: int) -> bytes: ... + def __aiter__(self) -> AsyncIterator[bytes]: ... + async def __anext__(self) -> bytes: ... diff --git a/shared/package-files/56/5639df194837f65be5083c4ea0649e626f142f5db0642e724399fcf96f76783d/registry.py b/shared/package-files/56/5639df194837f65be5083c4ea0649e626f142f5db0642e724399fcf96f76783d/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..8a36e0948332e324a41487efc757bc1b0acc50c6 --- /dev/null +++ b/shared/package-files/56/5639df194837f65be5083c4ea0649e626f142f5db0642e724399fcf96f76783d/registry.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +import importlib +import types +import warnings + +__all__ = ["registry", "get_filesystem_class", "default"] + +# internal, mutable +_registry: dict[str, type] = {} + +# external, immutable +registry = types.MappingProxyType(_registry) +default = "file" + + +def register_implementation(name, cls, clobber=False, errtxt=None): + """Add implementation class to the registry + + Parameters + ---------- + name: str + Protocol name to associate with the class + cls: class or str + if a class: fsspec-compliant implementation class (normally inherits from + ``fsspec.AbstractFileSystem``, gets added straight to the registry. If a + str, the full path to an implementation class like package.module.class, + which gets added to known_implementations, + so the import is deferred until the filesystem is actually used. + clobber: bool (optional) + Whether to overwrite a protocol with the same name; if False, will raise + instead. + errtxt: str (optional) + If given, then a failure to import the given class will result in this + text being given. + """ + if isinstance(cls, str): + if name in known_implementations and clobber is False: + if cls != known_implementations[name]["class"]: + raise ValueError( + f"Name ({name}) already in the known_implementations and clobber " + f"is False" + ) + else: + known_implementations[name] = { + "class": cls, + "err": errtxt or f"{cls} import failed for protocol {name}", + } + + else: + if name in registry and clobber is False: + if _registry[name] is not cls: + raise ValueError( + f"Name ({name}) already in the registry and clobber is False" + ) + else: + _registry[name] = cls + + +# protocols mapped to the class which implements them. This dict can be +# updated with register_implementation +known_implementations = { + "abfs": { + "class": "adlfs.AzureBlobFileSystem", + "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage", + }, + "adl": { + "class": "adlfs.AzureDatalakeFileSystem", + "err": "Install adlfs to access Azure Datalake Gen1", + }, + "arrow_hdfs": { + "class": "fsspec.implementations.arrow.HadoopFileSystem", + "err": "pyarrow and local java libraries required for HDFS", + }, + "asynclocal": { + "class": "morefs.asyn_local.AsyncLocalFileSystem", + "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem", + }, + "az": { + "class": "adlfs.AzureBlobFileSystem", + "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage", + }, + "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"}, + "box": { + "class": "boxfs.BoxFileSystem", + "err": "Please install boxfs to access BoxFileSystem", + }, + "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"}, + "dask": { + "class": "fsspec.implementations.dask.DaskWorkerFileSystem", + "err": "Install dask distributed to access worker file system", + }, + "data": {"class": "fsspec.implementations.data.DataFileSystem"}, + "dbfs": { + "class": "fsspec.implementations.dbfs.DatabricksFileSystem", + "err": "Install the requests package to use the DatabricksFileSystem", + }, + "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"}, + "dropbox": { + "class": "dropboxdrivefs.DropboxDriveFileSystem", + "err": ( + 'DropboxFileSystem requires "dropboxdrivefs","requests" and "' + '"dropbox" to be installed' + ), + }, + "dvc": { + "class": "dvc.api.DVCFileSystem", + "err": "Install dvc to access DVCFileSystem", + }, + "file": {"class": "fsspec.implementations.local.LocalFileSystem"}, + "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"}, + "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"}, + "gcs": { + "class": "gcsfs.GCSFileSystem", + "err": "Please install gcsfs to access Google Storage", + }, + "gdrive": { + "class": "gdrivefs.GoogleDriveFileSystem", + "err": "Please install gdrivefs for access to Google Drive", + }, + "generic": {"class": "fsspec.generic.GenericFileSystem"}, + "git": { + "class": "fsspec.implementations.git.GitFileSystem", + "err": "Install pygit2 to browse local git repos", + }, + "github": { + "class": "fsspec.implementations.github.GithubFileSystem", + "err": "Install the requests package to use the github FS", + }, + "gs": { + "class": "gcsfs.GCSFileSystem", + "err": "Please install gcsfs to access Google Storage", + }, + "hdfs": { + "class": "fsspec.implementations.arrow.HadoopFileSystem", + "err": "pyarrow and local java libraries required for HDFS", + }, + "hf": { + "class": "huggingface_hub.HfFileSystem", + "err": "Install huggingface_hub to access HfFileSystem", + }, + "http": { + "class": "fsspec.implementations.http.HTTPFileSystem", + "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed', + }, + "https": { + "class": "fsspec.implementations.http.HTTPFileSystem", + "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed', + }, + "jlab": { + "class": "fsspec.implementations.jupyter.JupyterFileSystem", + "err": "Jupyter FS requires requests to be installed", + }, + "jupyter": { + "class": "fsspec.implementations.jupyter.JupyterFileSystem", + "err": "Jupyter FS requires requests to be installed", + }, + "lakefs": { + "class": "lakefs_spec.LakeFSFileSystem", + "err": "Please install lakefs-spec to access LakeFSFileSystem", + }, + "libarchive": { + "class": "fsspec.implementations.libarchive.LibArchiveFileSystem", + "err": "LibArchive requires to be installed", + }, + "local": {"class": "fsspec.implementations.local.LocalFileSystem"}, + "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"}, + "oci": { + "class": "ocifs.OCIFileSystem", + "err": "Install ocifs to access OCI Object Storage", + }, + "ocilake": { + "class": "ocifs.OCIFileSystem", + "err": "Install ocifs to access OCI Data Lake", + }, + "oss": { + "class": "ossfs.OSSFileSystem", + "err": "Install ossfs to access Alibaba Object Storage System", + }, + "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"}, + "root": { + "class": "fsspec_xrootd.XRootDFileSystem", + "err": ( + "Install fsspec-xrootd to access xrootd storage system. " + "Note: 'root' is the protocol name for xrootd storage systems, " + "not referring to root directories" + ), + }, + "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"}, + "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"}, + "sftp": { + "class": "fsspec.implementations.sftp.SFTPFileSystem", + "err": 'SFTPFileSystem requires "paramiko" to be installed', + }, + "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"}, + "smb": { + "class": "fsspec.implementations.smb.SMBFileSystem", + "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed', + }, + "ssh": { + "class": "fsspec.implementations.sftp.SFTPFileSystem", + "err": 'SFTPFileSystem requires "paramiko" to be installed', + }, + "tar": {"class": "fsspec.implementations.tar.TarFileSystem"}, + "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"}, + "webdav": { + "class": "webdav4.fsspec.WebdavFileSystem", + "err": "Install webdav4 to access WebDAV", + }, + "webhdfs": { + "class": "fsspec.implementations.webhdfs.WebHDFS", + "err": 'webHDFS access requires "requests" to be installed', + }, + "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"}, +} + + +def get_filesystem_class(protocol): + """Fetch named protocol implementation from the registry + + The dict ``known_implementations`` maps protocol names to the locations + of classes implementing the corresponding file-system. When used for the + first time, appropriate imports will happen and the class will be placed in + the registry. All subsequent calls will fetch directly from the registry. + + Some protocol implementations require additional dependencies, and so the + import may fail. In this case, the string in the "err" field of the + ``known_implementations`` will be given as the error message. + """ + if not protocol: + protocol = default + + if protocol not in registry: + if protocol not in known_implementations: + raise ValueError(f"Protocol not known: {protocol}") + bit = known_implementations[protocol] + try: + register_implementation(protocol, _import_class(bit["class"])) + except ImportError as e: + raise ImportError(bit["err"]) from e + cls = registry[protocol] + if getattr(cls, "protocol", None) in ("abstract", None): + cls.protocol = protocol + + return cls + + +s3_msg = """Your installed version of s3fs is very old and known to cause +severe performance issues, see also https://github.com/dask/dask/issues/10276 + +To fix, you should specify a lower version bound on s3fs, or +update the current installation. +""" + + +def _import_class(cls, minv=None): + """Take a string FQP and return the imported class or identifier + + cls is of the form "package.module.klass" or "package.module:subobject.klass" + """ + if ":" in cls: + mod, name = cls.rsplit(":", 1) + s3 = mod == "s3fs" + mod = importlib.import_module(mod) + if s3 and mod.__version__.split(".") < ["0", "5"]: + warnings.warn(s3_msg) + for part in name.split("."): + mod = getattr(mod, part) + return mod + else: + mod, name = cls.rsplit(".", 1) + s3 = mod == "s3fs" + mod = importlib.import_module(mod) + if s3 and mod.__version__.split(".") < ["0", "5"]: + warnings.warn(s3_msg) + return getattr(mod, name) + + +def filesystem(protocol, **storage_options): + """Instantiate filesystems for given protocol and arguments + + ``storage_options`` are specific to the protocol being chosen, and are + passed directly to the class. + """ + if protocol == "arrow_hdfs": + warnings.warn( + "The 'arrow_hdfs' protocol has been deprecated and will be " + "removed in the future. Specify it as 'hdfs'.", + DeprecationWarning, + ) + + cls = get_filesystem_class(protocol) + return cls(**storage_options) + + +def available_protocols(): + """Return a list of the implemented protocols. + + Note that any given protocol may require extra packages to be importable. + """ + return list(known_implementations) diff --git a/shared/package-files/56/563a1e1c187330875efa2ccd66fae72633c03e07e5497df26d155b2eb6f2a38b/nonzero_numpy_ops.h b/shared/package-files/56/563a1e1c187330875efa2ccd66fae72633c03e07e5497df26d155b2eb6f2a38b/nonzero_numpy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..583ae4923ceccbde2d5df17767e2903806abd9f4 --- /dev/null +++ b/shared/package-files/56/563a1e1c187330875efa2ccd66fae72633c03e07e5497df26d155b2eb6f2a38b/nonzero_numpy_ops.h @@ -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 nonzero_numpy { + using schema = ::std::vector (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::nonzero_numpy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nonzero_numpy(Tensor self) -> Tensor[]") + static ::std::vector call(const at::Tensor & self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Acre b/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Acre new file mode 100644 index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325 Binary files /dev/null and b/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Acre differ diff --git a/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Porto_Acre b/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Porto_Acre new file mode 100644 index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325 Binary files /dev/null and b/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Porto_Acre differ diff --git a/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Rio_Branco b/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Rio_Branco new file mode 100644 index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325 Binary files /dev/null and b/shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/Rio_Branco differ diff --git a/shared/package-files/56/563b9821194c63e2bbf616ab92d863cdc8052fbae59242cea00c0d7c4088959c/_pca.py b/shared/package-files/56/563b9821194c63e2bbf616ab92d863cdc8052fbae59242cea00c0d7c4088959c/_pca.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0d21d5d38be9288a7e3c3405bd4ca449cfd808 --- /dev/null +++ b/shared/package-files/56/563b9821194c63e2bbf616ab92d863cdc8052fbae59242cea00c0d7c4088959c/_pca.py @@ -0,0 +1,857 @@ +"""Principal Component Analysis.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from math import lgamma, log, sqrt +from numbers import Integral, Real + +import numpy as np +from scipy import linalg +from scipy.sparse import issparse +from scipy.sparse.linalg import svds + +from ..base import _fit_context +from ..utils import check_random_state +from ..utils._arpack import _init_arpack_v0 +from ..utils._array_api import _convert_to_numpy, get_namespace +from ..utils._param_validation import Interval, RealNotInt, StrOptions +from ..utils.extmath import _randomized_svd, fast_logdet, stable_cumsum, svd_flip +from ..utils.sparsefuncs import _implicit_column_offset, mean_variance_axis +from ..utils.validation import check_is_fitted, validate_data +from ._base import _BasePCA + + +def _assess_dimension(spectrum, rank, n_samples): + """Compute the log-likelihood of a rank ``rank`` dataset. + + The dataset is assumed to be embedded in gaussian noise of shape(n, + dimf) having spectrum ``spectrum``. This implements the method of + T. P. Minka. + + Parameters + ---------- + spectrum : ndarray of shape (n_features,) + Data spectrum. + rank : int + Tested rank value. It should be strictly lower than n_features, + otherwise the method isn't specified (division by zero in equation + (31) from the paper). + n_samples : int + Number of samples. + + Returns + ------- + ll : float + The log-likelihood. + + References + ---------- + This implements the method of `Thomas P. Minka: + Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604 + `_ + """ + xp, _ = get_namespace(spectrum) + + n_features = spectrum.shape[0] + if not 1 <= rank < n_features: + raise ValueError("the tested rank should be in [1, n_features - 1]") + + eps = 1e-15 + + if spectrum[rank - 1] < eps: + # When the tested rank is associated with a small eigenvalue, there's + # no point in computing the log-likelihood: it's going to be very + # small and won't be the max anyway. Also, it can lead to numerical + # issues below when computing pa, in particular in log((spectrum[i] - + # spectrum[j]) because this will take the log of something very small. + return -xp.inf + + pu = -rank * log(2.0) + for i in range(1, rank + 1): + pu += ( + lgamma((n_features - i + 1) / 2.0) - log(xp.pi) * (n_features - i + 1) / 2.0 + ) + + pl = xp.sum(xp.log(spectrum[:rank])) + pl = -pl * n_samples / 2.0 + + v = max(eps, xp.sum(spectrum[rank:]) / (n_features - rank)) + pv = -log(v) * n_samples * (n_features - rank) / 2.0 + + m = n_features * rank - rank * (rank + 1.0) / 2.0 + pp = log(2.0 * xp.pi) * (m + rank) / 2.0 + + pa = 0.0 + spectrum_ = xp.asarray(spectrum, copy=True) + spectrum_[rank:n_features] = v + for i in range(rank): + for j in range(i + 1, spectrum.shape[0]): + pa += log( + (spectrum[i] - spectrum[j]) * (1.0 / spectrum_[j] - 1.0 / spectrum_[i]) + ) + log(n_samples) + + ll = pu + pl + pv + pp - pa / 2.0 - rank * log(n_samples) / 2.0 + + return ll + + +def _infer_dimension(spectrum, n_samples): + """Infers the dimension of a dataset with a given spectrum. + + The returned value will be in [1, n_features - 1]. + """ + xp, _ = get_namespace(spectrum) + + ll = xp.empty_like(spectrum) + ll[0] = -xp.inf # we don't want to return n_components = 0 + for rank in range(1, spectrum.shape[0]): + ll[rank] = _assess_dimension(spectrum, rank, n_samples) + return xp.argmax(ll) + + +class PCA(_BasePCA): + """Principal component analysis (PCA). + + Linear dimensionality reduction using Singular Value Decomposition of the + data to project it to a lower dimensional space. The input data is centered + but not scaled for each feature before applying the SVD. + + It uses the LAPACK implementation of the full SVD or a randomized truncated + SVD by the method of Halko et al. 2009, depending on the shape of the input + data and the number of components to extract. + + With sparse inputs, the ARPACK implementation of the truncated SVD can be + used (i.e. through :func:`scipy.sparse.linalg.svds`). Alternatively, one + may consider :class:`TruncatedSVD` where the data are not centered. + + Notice that this class only supports sparse inputs for some solvers such as + "arpack" and "covariance_eigh". See :class:`TruncatedSVD` for an + alternative with sparse data. + + For a usage example, see + :ref:`sphx_glr_auto_examples_decomposition_plot_pca_iris.py` + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, float or 'mle', default=None + Number of components to keep. + if n_components is not set all components are kept:: + + n_components == min(n_samples, n_features) + + If ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's + MLE is used to guess the dimension. Use of ``n_components == 'mle'`` + will interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``. + + If ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the + number of components such that the amount of variance that needs to be + explained is greater than the percentage specified by n_components. + + If ``svd_solver == 'arpack'``, the number of components must be + strictly less than the minimum of n_features and n_samples. + + Hence, the None case results in:: + + n_components == min(n_samples, n_features) - 1 + + copy : bool, default=True + If False, data passed to fit are overwritten and running + fit(X).transform(X) will not yield the expected results, + use fit_transform(X) instead. + + whiten : bool, default=False + When True (False by default) the `components_` vectors are multiplied + by the square root of n_samples and then divided by the singular values + to ensure uncorrelated outputs with unit component-wise variances. + + Whitening will remove some information from the transformed signal + (the relative variance scales of the components) but can sometime + improve the predictive accuracy of the downstream estimators by + making their data respect some hard-wired assumptions. + + svd_solver : {'auto', 'full', 'covariance_eigh', 'arpack', 'randomized'},\ + default='auto' + "auto" : + The solver is selected by a default 'auto' policy is based on `X.shape` and + `n_components`: if the input data has fewer than 1000 features and + more than 10 times as many samples, then the "covariance_eigh" + solver is used. Otherwise, if the input data is larger than 500x500 + and the number of components to extract is lower than 80% of the + smallest dimension of the data, then the more efficient + "randomized" method is selected. Otherwise the exact "full" SVD is + computed and optionally truncated afterwards. + "full" : + Run exact full SVD calling the standard LAPACK solver via + `scipy.linalg.svd` and select the components by postprocessing + "covariance_eigh" : + Precompute the covariance matrix (on centered data), run a + classical eigenvalue decomposition on the covariance matrix + typically using LAPACK and select the components by postprocessing. + This solver is very efficient for n_samples >> n_features and small + n_features. It is, however, not tractable otherwise for large + n_features (large memory footprint required to materialize the + covariance matrix). Also note that compared to the "full" solver, + this solver effectively doubles the condition number and is + therefore less numerical stable (e.g. on input data with a large + range of singular values). + "arpack" : + Run SVD truncated to `n_components` calling ARPACK solver via + `scipy.sparse.linalg.svds`. It requires strictly + `0 < n_components < min(X.shape)` + "randomized" : + Run randomized SVD by the method of Halko et al. + + .. versionadded:: 0.18.0 + + .. versionchanged:: 1.5 + Added the 'covariance_eigh' solver. + + tol : float, default=0.0 + Tolerance for singular values computed by svd_solver == 'arpack'. + Must be of range [0.0, infinity). + + .. versionadded:: 0.18.0 + + iterated_power : int or 'auto', default='auto' + Number of iterations for the power method computed by + svd_solver == 'randomized'. + Must be of range [0, infinity). + + .. versionadded:: 0.18.0 + + n_oversamples : int, default=10 + This parameter is only relevant when `svd_solver="randomized"`. + It corresponds to the additional number of random vectors to sample the + range of `X` so as to ensure proper conditioning. See + :func:`~sklearn.utils.extmath.randomized_svd` for more details. + + .. versionadded:: 1.1 + + power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' + Power iteration normalizer for randomized SVD solver. + Not used by ARPACK. See :func:`~sklearn.utils.extmath.randomized_svd` + for more details. + + .. versionadded:: 1.1 + + random_state : int, RandomState instance or None, default=None + Used when the 'arpack' or 'randomized' solvers are used. Pass an int + for reproducible results across multiple function calls. + See :term:`Glossary `. + + .. versionadded:: 0.18.0 + + Attributes + ---------- + components_ : ndarray of shape (n_components, n_features) + Principal axes in feature space, representing the directions of + maximum variance in the data. Equivalently, the right singular + vectors of the centered input data, parallel to its eigenvectors. + The components are sorted by decreasing ``explained_variance_``. + + explained_variance_ : ndarray of shape (n_components,) + The amount of variance explained by each of the selected components. + The variance estimation uses `n_samples - 1` degrees of freedom. + + Equal to n_components largest eigenvalues + of the covariance matrix of X. + + .. versionadded:: 0.18 + + explained_variance_ratio_ : ndarray of shape (n_components,) + Percentage of variance explained by each of the selected components. + + If ``n_components`` is not set then all components are stored and the + sum of the ratios is equal to 1.0. + + singular_values_ : ndarray of shape (n_components,) + The singular values corresponding to each of the selected components. + The singular values are equal to the 2-norms of the ``n_components`` + variables in the lower-dimensional space. + + .. versionadded:: 0.19 + + mean_ : ndarray of shape (n_features,) + Per-feature empirical mean, estimated from the training set. + + Equal to `X.mean(axis=0)`. + + n_components_ : int + The estimated number of components. When n_components is set + to 'mle' or a number between 0 and 1 (with svd_solver == 'full') this + number is estimated from input data. Otherwise it equals the parameter + n_components, or the lesser value of n_features and n_samples + if n_components is None. + + n_samples_ : int + Number of samples in the training data. + + noise_variance_ : float + The estimated noise covariance following the Probabilistic PCA model + from Tipping and Bishop 1999. See "Pattern Recognition and + Machine Learning" by C. Bishop, 12.2.1 p. 574 or + http://www.miketipping.com/papers/met-mppca.pdf. It is required to + compute the estimated data covariance and score samples. + + Equal to the average of (min(n_features, n_samples) - n_components) + smallest eigenvalues of the covariance matrix of X. + + 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 + -------- + KernelPCA : Kernel Principal Component Analysis. + SparsePCA : Sparse Principal Component Analysis. + TruncatedSVD : Dimensionality reduction using truncated SVD. + IncrementalPCA : Incremental Principal Component Analysis. + + References + ---------- + For n_components == 'mle', this class uses the method from: + `Minka, T. P.. "Automatic choice of dimensionality for PCA". + In NIPS, pp. 598-604 `_ + + Implements the probabilistic PCA model from: + `Tipping, M. E., and Bishop, C. M. (1999). "Probabilistic principal + component analysis". Journal of the Royal Statistical Society: + Series B (Statistical Methodology), 61(3), 611-622. + `_ + via the score and score_samples methods. + + For svd_solver == 'arpack', refer to `scipy.sparse.linalg.svds`. + + For svd_solver == 'randomized', see: + :doi:`Halko, N., Martinsson, P. G., and Tropp, J. A. (2011). + "Finding structure with randomness: Probabilistic algorithms for + constructing approximate matrix decompositions". + SIAM review, 53(2), 217-288. + <10.1137/090771806>` + and also + :doi:`Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011). + "A randomized algorithm for the decomposition of matrices". + Applied and Computational Harmonic Analysis, 30(1), 47-68. + <10.1016/j.acha.2010.02.003>` + + Examples + -------- + >>> import numpy as np + >>> from sklearn.decomposition import PCA + >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) + >>> pca = PCA(n_components=2) + >>> pca.fit(X) + PCA(n_components=2) + >>> print(pca.explained_variance_ratio_) + [0.9924 0.0075] + >>> print(pca.singular_values_) + [6.30061 0.54980] + + >>> pca = PCA(n_components=2, svd_solver='full') + >>> pca.fit(X) + PCA(n_components=2, svd_solver='full') + >>> print(pca.explained_variance_ratio_) + [0.9924 0.00755] + >>> print(pca.singular_values_) + [6.30061 0.54980] + + >>> pca = PCA(n_components=1, svd_solver='arpack') + >>> pca.fit(X) + PCA(n_components=1, svd_solver='arpack') + >>> print(pca.explained_variance_ratio_) + [0.99244] + >>> print(pca.singular_values_) + [6.30061] + """ + + _parameter_constraints: dict = { + "n_components": [ + Interval(Integral, 0, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="neither"), + StrOptions({"mle"}), + None, + ], + "copy": ["boolean"], + "whiten": ["boolean"], + "svd_solver": [ + StrOptions({"auto", "full", "covariance_eigh", "arpack", "randomized"}) + ], + "tol": [Interval(Real, 0, None, closed="left")], + "iterated_power": [ + StrOptions({"auto"}), + Interval(Integral, 0, None, closed="left"), + ], + "n_oversamples": [Interval(Integral, 1, None, closed="left")], + "power_iteration_normalizer": [StrOptions({"auto", "QR", "LU", "none"})], + "random_state": ["random_state"], + } + + def __init__( + self, + n_components=None, + *, + copy=True, + whiten=False, + svd_solver="auto", + tol=0.0, + iterated_power="auto", + n_oversamples=10, + power_iteration_normalizer="auto", + random_state=None, + ): + self.n_components = n_components + self.copy = copy + self.whiten = whiten + self.svd_solver = svd_solver + self.tol = tol + self.iterated_power = iterated_power + self.n_oversamples = n_oversamples + self.power_iteration_normalizer = power_iteration_normalizer + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the model with X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : Ignored + Ignored. + + Returns + ------- + self : object + Returns the instance itself. + """ + self._fit(X) + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit_transform(self, X, y=None): + """Fit the model with X and apply the dimensionality reduction on X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : Ignored + Ignored. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_components) + Transformed values. + + Notes + ----- + This method returns a Fortran-ordered array. To convert it to a + C-ordered array, use 'np.ascontiguousarray'. + """ + U, S, _, X, x_is_centered, xp = self._fit(X) + if U is not None: + U = U[:, : self.n_components_] + + if self.whiten: + # X_new = X * V / S * sqrt(n_samples) = U * sqrt(n_samples) + U *= sqrt(X.shape[0] - 1) + else: + # X_new = X * V = U * S * Vt * V = U * S + U *= S[: self.n_components_] + + return U + else: # solver="covariance_eigh" does not compute U at fit time. + return self._transform(X, xp, x_is_centered=x_is_centered) + + def _fit(self, X): + """Dispatch to the right submethod depending on the chosen solver.""" + xp, is_array_api_compliant = get_namespace(X) + + # Raise an error for sparse input and unsupported svd_solver + if issparse(X) and self.svd_solver not in ["auto", "arpack", "covariance_eigh"]: + raise TypeError( + 'PCA only support sparse inputs with the "arpack" and' + f' "covariance_eigh" solvers, while "{self.svd_solver}" was passed. See' + " TruncatedSVD for a possible alternative." + ) + if self.svd_solver == "arpack" and is_array_api_compliant: + raise ValueError( + "PCA with svd_solver='arpack' is not supported for Array API inputs." + ) + + # Validate the data, without ever forcing a copy as any solver that + # supports sparse input data and the `covariance_eigh` solver are + # written in a way to avoid the need for any inplace modification of + # the input data contrary to the other solvers. + # The copy will happen + # later, only if needed, once the solver negotiation below is done. + X = validate_data( + self, + X, + dtype=[xp.float64, xp.float32], + force_writeable=True, + accept_sparse=("csr", "csc"), + ensure_2d=True, + copy=False, + ) + self._fit_svd_solver = self.svd_solver + if self._fit_svd_solver == "auto" and issparse(X): + self._fit_svd_solver = "arpack" + + if self.n_components is None: + if self._fit_svd_solver != "arpack": + n_components = min(X.shape) + else: + n_components = min(X.shape) - 1 + else: + n_components = self.n_components + + if self._fit_svd_solver == "auto": + # Tall and skinny problems are best handled by precomputing the + # covariance matrix. + if X.shape[1] <= 1_000 and X.shape[0] >= 10 * X.shape[1]: + self._fit_svd_solver = "covariance_eigh" + # Small problem or n_components == 'mle', just call full PCA + elif max(X.shape) <= 500 or n_components == "mle": + self._fit_svd_solver = "full" + elif 1 <= n_components < 0.8 * min(X.shape): + self._fit_svd_solver = "randomized" + # This is also the case of n_components in (0, 1) + else: + self._fit_svd_solver = "full" + + # Call different fits for either full or truncated SVD + if self._fit_svd_solver in ("full", "covariance_eigh"): + return self._fit_full(X, n_components, xp, is_array_api_compliant) + elif self._fit_svd_solver in ["arpack", "randomized"]: + return self._fit_truncated(X, n_components, xp) + + def _fit_full(self, X, n_components, xp, is_array_api_compliant): + """Fit the model by computing full SVD on X.""" + n_samples, n_features = X.shape + + if n_components == "mle": + if n_samples < n_features: + raise ValueError( + "n_components='mle' is only supported if n_samples >= n_features" + ) + elif not 0 <= n_components <= min(n_samples, n_features): + raise ValueError( + f"n_components={n_components} must be between 0 and " + f"min(n_samples, n_features)={min(n_samples, n_features)} with " + f"svd_solver={self._fit_svd_solver!r}" + ) + + self.mean_ = xp.mean(X, axis=0) + # When X is a scipy sparse matrix, self.mean_ is a numpy matrix, so we need + # to transform it to a 1D array. Note that this is not the case when X + # is a scipy sparse array. + # TODO: remove the following two lines when scikit-learn only depends + # on scipy versions that no longer support scipy.sparse matrices. + self.mean_ = xp.reshape(xp.asarray(self.mean_), (-1,)) + + if self._fit_svd_solver == "full": + X_centered = xp.asarray(X, copy=True) if self.copy else X + X_centered -= self.mean_ + x_is_centered = not self.copy + + if not is_array_api_compliant: + # Use scipy.linalg with NumPy/SciPy inputs for the sake of not + # introducing unanticipated behavior changes. In the long run we + # could instead decide to always use xp.linalg.svd for all inputs, + # but that would make this code rely on numpy's SVD instead of + # scipy's. It's not 100% clear whether they use the same LAPACK + # solver by default though (assuming both are built against the + # same BLAS). + U, S, Vt = linalg.svd(X_centered, full_matrices=False) + else: + U, S, Vt = xp.linalg.svd(X_centered, full_matrices=False) + explained_variance_ = (S**2) / (n_samples - 1) + + else: + assert self._fit_svd_solver == "covariance_eigh" + # In the following, we center the covariance matrix C afterwards + # (without centering the data X first) to avoid an unnecessary copy + # of X. Note that the mean_ attribute is still needed to center + # test data in the transform method. + # + # Note: at the time of writing, `xp.cov` does not exist in the + # Array API standard: + # https://github.com/data-apis/array-api/issues/43 + # + # Besides, using `numpy.cov`, as of numpy 1.26.0, would not be + # memory efficient for our use case when `n_samples >> n_features`: + # `numpy.cov` centers a copy of the data before computing the + # matrix product instead of subtracting a small `(n_features, + # n_features)` square matrix from the gram matrix X.T @ X, as we do + # below. + x_is_centered = False + C = X.T @ X + C -= ( + n_samples + * xp.reshape(self.mean_, (-1, 1)) + * xp.reshape(self.mean_, (1, -1)) + ) + C /= n_samples - 1 + eigenvals, eigenvecs = xp.linalg.eigh(C) + + # When X is a scipy sparse matrix, the following two datastructures + # are returned as instances of the soft-deprecated numpy.matrix + # class. Note that this problem does not occur when X is a scipy + # sparse array (or another other kind of supported array). + # TODO: remove the following two lines when scikit-learn only + # depends on scipy versions that no longer support scipy.sparse + # matrices. + eigenvals = xp.reshape(xp.asarray(eigenvals), (-1,)) + eigenvecs = xp.asarray(eigenvecs) + + eigenvals = xp.flip(eigenvals, axis=0) + eigenvecs = xp.flip(eigenvecs, axis=1) + + # The covariance matrix C is positive semi-definite by + # construction. However, the eigenvalues returned by xp.linalg.eigh + # can be slightly negative due to numerical errors. This would be + # an issue for the subsequent sqrt, hence the manual clipping. + eigenvals[eigenvals < 0.0] = 0.0 + explained_variance_ = eigenvals + + # Re-construct SVD of centered X indirectly and make it consistent + # with the other solvers. + S = xp.sqrt(eigenvals * (n_samples - 1)) + Vt = eigenvecs.T + U = None + + # flip eigenvectors' sign to enforce deterministic output + U, Vt = svd_flip(U, Vt, u_based_decision=False) + + components_ = Vt + + # Get variance explained by singular values + total_var = xp.sum(explained_variance_) + explained_variance_ratio_ = explained_variance_ / total_var + singular_values_ = xp.asarray(S, copy=True) # Store the singular values. + + # Postprocess the number of components required + if n_components == "mle": + n_components = _infer_dimension(explained_variance_, n_samples) + elif 0 < n_components < 1.0: + # number of components for which the cumulated explained + # variance percentage is superior to the desired threshold + # side='right' ensures that number of features selected + # their variance is always greater than n_components float + # passed. More discussion in issue: #15669 + if is_array_api_compliant: + # Convert to numpy as xp.cumsum and xp.searchsorted are not + # part of the Array API standard yet: + # + # https://github.com/data-apis/array-api/issues/597 + # https://github.com/data-apis/array-api/issues/688 + # + # Furthermore, it's not always safe to call them for namespaces + # that already implement them: for instance as + # cupy.searchsorted does not accept a float as second argument. + explained_variance_ratio_np = _convert_to_numpy( + explained_variance_ratio_, xp=xp + ) + else: + explained_variance_ratio_np = explained_variance_ratio_ + ratio_cumsum = stable_cumsum(explained_variance_ratio_np) + n_components = np.searchsorted(ratio_cumsum, n_components, side="right") + 1 + + # Compute noise covariance using Probabilistic PCA model + # The sigma2 maximum likelihood (cf. eq. 12.46) + if n_components < min(n_features, n_samples): + self.noise_variance_ = xp.mean(explained_variance_[n_components:]) + else: + self.noise_variance_ = 0.0 + + self.n_samples_ = n_samples + self.n_components_ = n_components + # Assign a copy of the result of the truncation of the components in + # order to: + # - release the memory used by the discarded components, + # - ensure that the kept components are allocated contiguously in + # memory to make the transform method faster by leveraging cache + # locality. + self.components_ = xp.asarray(components_[:n_components, :], copy=True) + + # We do the same for the other arrays for the sake of consistency. + self.explained_variance_ = xp.asarray( + explained_variance_[:n_components], copy=True + ) + self.explained_variance_ratio_ = xp.asarray( + explained_variance_ratio_[:n_components], copy=True + ) + self.singular_values_ = xp.asarray(singular_values_[:n_components], copy=True) + + return U, S, Vt, X, x_is_centered, xp + + def _fit_truncated(self, X, n_components, xp): + """Fit the model by computing truncated SVD (by ARPACK or randomized) + on X. + """ + n_samples, n_features = X.shape + + svd_solver = self._fit_svd_solver + if isinstance(n_components, str): + raise ValueError( + "n_components=%r cannot be a string with svd_solver='%s'" + % (n_components, svd_solver) + ) + elif not 1 <= n_components <= min(n_samples, n_features): + raise ValueError( + "n_components=%r must be between 1 and " + "min(n_samples, n_features)=%r with " + "svd_solver='%s'" + % (n_components, min(n_samples, n_features), svd_solver) + ) + elif svd_solver == "arpack" and n_components == min(n_samples, n_features): + raise ValueError( + "n_components=%r must be strictly less than " + "min(n_samples, n_features)=%r with " + "svd_solver='%s'" + % (n_components, min(n_samples, n_features), svd_solver) + ) + + random_state = check_random_state(self.random_state) + + # Center data + total_var = None + if issparse(X): + self.mean_, var = mean_variance_axis(X, axis=0) + total_var = var.sum() * n_samples / (n_samples - 1) # ddof=1 + X_centered = _implicit_column_offset(X, self.mean_) + x_is_centered = False + else: + self.mean_ = xp.mean(X, axis=0) + X_centered = xp.asarray(X, copy=True) if self.copy else X + X_centered -= self.mean_ + x_is_centered = not self.copy + + if svd_solver == "arpack": + v0 = _init_arpack_v0(min(X.shape), random_state) + U, S, Vt = svds(X_centered, k=n_components, tol=self.tol, v0=v0) + # svds doesn't abide by scipy.linalg.svd/randomized_svd + # conventions, so reverse its outputs. + S = S[::-1] + # flip eigenvectors' sign to enforce deterministic output + U, Vt = svd_flip(U[:, ::-1], Vt[::-1], u_based_decision=False) + + elif svd_solver == "randomized": + # sign flipping is done inside + U, S, Vt = _randomized_svd( + X_centered, + n_components=n_components, + n_oversamples=self.n_oversamples, + n_iter=self.iterated_power, + power_iteration_normalizer=self.power_iteration_normalizer, + flip_sign=False, + random_state=random_state, + ) + U, Vt = svd_flip(U, Vt, u_based_decision=False) + + self.n_samples_ = n_samples + self.components_ = Vt + self.n_components_ = n_components + + # Get variance explained by singular values + self.explained_variance_ = (S**2) / (n_samples - 1) + + # Workaround in-place variance calculation since at the time numpy + # did not have a way to calculate variance in-place. + # + # TODO: update this code to either: + # * Use the array-api variance calculation, unless memory usage suffers + # * Update sklearn.utils.extmath._incremental_mean_and_var to support array-api + # See: https://github.com/scikit-learn/scikit-learn/pull/18689#discussion_r1335540991 + if total_var is None: + N = X.shape[0] - 1 + X_centered **= 2 + total_var = xp.sum(X_centered) / N + + self.explained_variance_ratio_ = self.explained_variance_ / total_var + self.singular_values_ = xp.asarray(S, copy=True) # Store the singular values. + + if self.n_components_ < min(n_features, n_samples): + self.noise_variance_ = total_var - xp.sum(self.explained_variance_) + self.noise_variance_ /= min(n_features, n_samples) - n_components + else: + self.noise_variance_ = 0.0 + + return U, S, Vt, X, x_is_centered, xp + + def score_samples(self, X): + """Return the log-likelihood of each sample. + + See. "Pattern Recognition and Machine Learning" + by C. Bishop, 12.2.1 p. 574 + or http://www.miketipping.com/papers/met-mppca.pdf + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + Returns + ------- + ll : ndarray of shape (n_samples,) + Log-likelihood of each sample under the current model. + """ + check_is_fitted(self) + xp, _ = get_namespace(X) + X = validate_data(self, X, dtype=[xp.float64, xp.float32], reset=False) + Xr = X - self.mean_ + n_features = X.shape[1] + precision = self.get_precision() + log_like = -0.5 * xp.sum(Xr * (Xr @ precision), axis=1) + log_like -= 0.5 * (n_features * log(2.0 * np.pi) - fast_logdet(precision)) + return log_like + + def score(self, X, y=None): + """Return the average log-likelihood of all samples. + + See. "Pattern Recognition and Machine Learning" + by C. Bishop, 12.2.1 p. 574 + or http://www.miketipping.com/papers/met-mppca.pdf + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + y : Ignored + Ignored. + + Returns + ------- + ll : float + Average log-likelihood of the samples under the current model. + """ + xp, _ = get_namespace(X) + return float(xp.mean(self.score_samples(X))) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + tags.array_api_support = True + tags.input_tags.sparse = self.svd_solver in ( + "auto", + "arpack", + "covariance_eigh", + ) + return tags diff --git a/shared/package-files/56/563cf6e58e87fe2874884136006d246b13bd53c3f07174aba1fcea9cde170702/test_index_tricks.py b/shared/package-files/56/563cf6e58e87fe2874884136006d246b13bd53c3f07174aba1fcea9cde170702/test_index_tricks.py new file mode 100644 index 0000000000000000000000000000000000000000..b599cb345b8af2b98c972bd0f43d6eb014fa77fb --- /dev/null +++ b/shared/package-files/56/563cf6e58e87fe2874884136006d246b13bd53c3f07174aba1fcea9cde170702/test_index_tricks.py @@ -0,0 +1,551 @@ +import pytest + +import numpy as np +from numpy.testing import ( + assert_, assert_equal, assert_array_equal, assert_almost_equal, + assert_array_almost_equal, assert_raises, assert_raises_regex, + ) +from numpy.lib.index_tricks import ( + mgrid, ogrid, ndenumerate, fill_diagonal, diag_indices, diag_indices_from, + index_exp, ndindex, r_, s_, ix_ + ) + + +class TestRavelUnravelIndex: + def test_basic(self): + assert_equal(np.unravel_index(2, (2, 2)), (1, 0)) + + # test that new shape argument works properly + assert_equal(np.unravel_index(indices=2, + shape=(2, 2)), + (1, 0)) + + # test that an invalid second keyword argument + # is properly handled, including the old name `dims`. + with assert_raises(TypeError): + np.unravel_index(indices=2, hape=(2, 2)) + + with assert_raises(TypeError): + np.unravel_index(2, hape=(2, 2)) + + with assert_raises(TypeError): + np.unravel_index(254, ims=(17, 94)) + + with assert_raises(TypeError): + np.unravel_index(254, dims=(17, 94)) + + assert_equal(np.ravel_multi_index((1, 0), (2, 2)), 2) + assert_equal(np.unravel_index(254, (17, 94)), (2, 66)) + assert_equal(np.ravel_multi_index((2, 66), (17, 94)), 254) + assert_raises(ValueError, np.unravel_index, -1, (2, 2)) + assert_raises(TypeError, np.unravel_index, 0.5, (2, 2)) + assert_raises(ValueError, np.unravel_index, 4, (2, 2)) + assert_raises(ValueError, np.ravel_multi_index, (-3, 1), (2, 2)) + assert_raises(ValueError, np.ravel_multi_index, (2, 1), (2, 2)) + assert_raises(ValueError, np.ravel_multi_index, (0, -3), (2, 2)) + assert_raises(ValueError, np.ravel_multi_index, (0, 2), (2, 2)) + assert_raises(TypeError, np.ravel_multi_index, (0.1, 0.), (2, 2)) + + assert_equal(np.unravel_index((2*3 + 1)*6 + 4, (4, 3, 6)), [2, 1, 4]) + assert_equal( + np.ravel_multi_index([2, 1, 4], (4, 3, 6)), (2*3 + 1)*6 + 4) + + arr = np.array([[3, 6, 6], [4, 5, 1]]) + assert_equal(np.ravel_multi_index(arr, (7, 6)), [22, 41, 37]) + assert_equal( + np.ravel_multi_index(arr, (7, 6), order='F'), [31, 41, 13]) + assert_equal( + np.ravel_multi_index(arr, (4, 6), mode='clip'), [22, 23, 19]) + assert_equal(np.ravel_multi_index(arr, (4, 4), mode=('clip', 'wrap')), + [12, 13, 13]) + assert_equal(np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9)), 1621) + + assert_equal(np.unravel_index(np.array([22, 41, 37]), (7, 6)), + [[3, 6, 6], [4, 5, 1]]) + assert_equal( + np.unravel_index(np.array([31, 41, 13]), (7, 6), order='F'), + [[3, 6, 6], [4, 5, 1]]) + assert_equal(np.unravel_index(1621, (6, 7, 8, 9)), [3, 1, 4, 1]) + + def test_empty_indices(self): + msg1 = 'indices must be integral: the provided empty sequence was' + msg2 = 'only int indices permitted' + assert_raises_regex(TypeError, msg1, np.unravel_index, [], (10, 3, 5)) + assert_raises_regex(TypeError, msg1, np.unravel_index, (), (10, 3, 5)) + assert_raises_regex(TypeError, msg2, np.unravel_index, np.array([]), + (10, 3, 5)) + assert_equal(np.unravel_index(np.array([],dtype=int), (10, 3, 5)), + [[], [], []]) + assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], []), + (10, 3)) + assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], ['abc']), + (10, 3)) + assert_raises_regex(TypeError, msg2, np.ravel_multi_index, + (np.array([]), np.array([])), (5, 3)) + assert_equal(np.ravel_multi_index( + (np.array([], dtype=int), np.array([], dtype=int)), (5, 3)), []) + assert_equal(np.ravel_multi_index(np.array([[], []], dtype=int), + (5, 3)), []) + + def test_big_indices(self): + # ravel_multi_index for big indices (issue #7546) + if np.intp == np.int64: + arr = ([1, 29], [3, 5], [3, 117], [19, 2], + [2379, 1284], [2, 2], [0, 1]) + assert_equal( + np.ravel_multi_index(arr, (41, 7, 120, 36, 2706, 8, 6)), + [5627771580, 117259570957]) + + # test unravel_index for big indices (issue #9538) + assert_raises(ValueError, np.unravel_index, 1, (2**32-1, 2**31+1)) + + # test overflow checking for too big array (issue #7546) + dummy_arr = ([0],[0]) + half_max = np.iinfo(np.intp).max // 2 + assert_equal( + np.ravel_multi_index(dummy_arr, (half_max, 2)), [0]) + assert_raises(ValueError, + np.ravel_multi_index, dummy_arr, (half_max+1, 2)) + assert_equal( + np.ravel_multi_index(dummy_arr, (half_max, 2), order='F'), [0]) + assert_raises(ValueError, + np.ravel_multi_index, dummy_arr, (half_max+1, 2), order='F') + + def test_dtypes(self): + # Test with different data types + for dtype in [np.int16, np.uint16, np.int32, + np.uint32, np.int64, np.uint64]: + coords = np.array( + [[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0]], dtype=dtype) + shape = (5, 8) + uncoords = 8*coords[0]+coords[1] + assert_equal(np.ravel_multi_index(coords, shape), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape)) + uncoords = coords[0]+5*coords[1] + assert_equal( + np.ravel_multi_index(coords, shape, order='F'), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape, order='F')) + + coords = np.array( + [[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0], [1, 3, 1, 0, 9, 5]], + dtype=dtype) + shape = (5, 8, 10) + uncoords = 10*(8*coords[0]+coords[1])+coords[2] + assert_equal(np.ravel_multi_index(coords, shape), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape)) + uncoords = coords[0]+5*(coords[1]+8*coords[2]) + assert_equal( + np.ravel_multi_index(coords, shape, order='F'), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape, order='F')) + + def test_clipmodes(self): + # Test clipmodes + assert_equal( + np.ravel_multi_index([5, 1, -1, 2], (4, 3, 7, 12), mode='wrap'), + np.ravel_multi_index([1, 1, 6, 2], (4, 3, 7, 12))) + assert_equal(np.ravel_multi_index([5, 1, -1, 2], (4, 3, 7, 12), + mode=( + 'wrap', 'raise', 'clip', 'raise')), + np.ravel_multi_index([1, 1, 0, 2], (4, 3, 7, 12))) + assert_raises( + ValueError, np.ravel_multi_index, [5, 1, -1, 2], (4, 3, 7, 12)) + + def test_writeability(self): + # See gh-7269 + x, y = np.unravel_index([1, 2, 3], (4, 5)) + assert_(x.flags.writeable) + assert_(y.flags.writeable) + + def test_0d(self): + # gh-580 + x = np.unravel_index(0, ()) + assert_equal(x, ()) + + assert_raises_regex(ValueError, "0d array", np.unravel_index, [0], ()) + assert_raises_regex( + ValueError, "out of bounds", np.unravel_index, [1], ()) + + @pytest.mark.parametrize("mode", ["clip", "wrap", "raise"]) + def test_empty_array_ravel(self, mode): + res = np.ravel_multi_index( + np.zeros((3, 0), dtype=np.intp), (2, 1, 0), mode=mode) + assert(res.shape == (0,)) + + with assert_raises(ValueError): + np.ravel_multi_index( + np.zeros((3, 1), dtype=np.intp), (2, 1, 0), mode=mode) + + def test_empty_array_unravel(self): + res = np.unravel_index(np.zeros(0, dtype=np.intp), (2, 1, 0)) + # res is a tuple of three empty arrays + assert(len(res) == 3) + assert(all(a.shape == (0,) for a in res)) + + with assert_raises(ValueError): + np.unravel_index([1], (2, 1, 0)) + +class TestGrid: + def test_basic(self): + a = mgrid[-1:1:10j] + b = mgrid[-1:1:0.1] + assert_(a.shape == (10,)) + assert_(b.shape == (20,)) + assert_(a[0] == -1) + assert_almost_equal(a[-1], 1) + assert_(b[0] == -1) + assert_almost_equal(b[1]-b[0], 0.1, 11) + assert_almost_equal(b[-1], b[0]+19*0.1, 11) + assert_almost_equal(a[1]-a[0], 2.0/9.0, 11) + + def test_linspace_equivalence(self): + y, st = np.linspace(2, 10, retstep=True) + assert_almost_equal(st, 8/49.0) + assert_array_almost_equal(y, mgrid[2:10:50j], 13) + + def test_nd(self): + c = mgrid[-1:1:10j, -2:2:10j] + d = mgrid[-1:1:0.1, -2:2:0.2] + assert_(c.shape == (2, 10, 10)) + assert_(d.shape == (2, 20, 20)) + assert_array_equal(c[0][0, :], -np.ones(10, 'd')) + assert_array_equal(c[1][:, 0], -2*np.ones(10, 'd')) + assert_array_almost_equal(c[0][-1, :], np.ones(10, 'd'), 11) + assert_array_almost_equal(c[1][:, -1], 2*np.ones(10, 'd'), 11) + assert_array_almost_equal(d[0, 1, :] - d[0, 0, :], + 0.1*np.ones(20, 'd'), 11) + assert_array_almost_equal(d[1, :, 1] - d[1, :, 0], + 0.2*np.ones(20, 'd'), 11) + + def test_sparse(self): + grid_full = mgrid[-1:1:10j, -2:2:10j] + grid_sparse = ogrid[-1:1:10j, -2:2:10j] + + # sparse grids can be made dense by broadcasting + grid_broadcast = np.broadcast_arrays(*grid_sparse) + for f, b in zip(grid_full, grid_broadcast): + assert_equal(f, b) + + @pytest.mark.parametrize("start, stop, step, expected", [ + (None, 10, 10j, (200, 10)), + (-10, 20, None, (1800, 30)), + ]) + def test_mgrid_size_none_handling(self, start, stop, step, expected): + # regression test None value handling for + # start and step values used by mgrid; + # internally, this aims to cover previously + # unexplored code paths in nd_grid() + grid = mgrid[start:stop:step, start:stop:step] + # need a smaller grid to explore one of the + # untested code paths + grid_small = mgrid[start:stop:step] + assert_equal(grid.size, expected[0]) + assert_equal(grid_small.size, expected[1]) + + def test_accepts_npfloating(self): + # regression test for #16466 + grid64 = mgrid[0.1:0.33:0.1, ] + grid32 = mgrid[np.float32(0.1):np.float32(0.33):np.float32(0.1), ] + assert_(grid32.dtype == np.float64) + assert_array_almost_equal(grid64, grid32) + + # different code path for single slice + grid64 = mgrid[0.1:0.33:0.1] + grid32 = mgrid[np.float32(0.1):np.float32(0.33):np.float32(0.1)] + assert_(grid32.dtype == np.float64) + assert_array_almost_equal(grid64, grid32) + + def test_accepts_longdouble(self): + # regression tests for #16945 + grid64 = mgrid[0.1:0.33:0.1, ] + grid128 = mgrid[ + np.longdouble(0.1):np.longdouble(0.33):np.longdouble(0.1), + ] + assert_(grid128.dtype == np.longdouble) + assert_array_almost_equal(grid64, grid128) + + grid128c_a = mgrid[0:np.longdouble(1):3.4j] + grid128c_b = mgrid[0:np.longdouble(1):3.4j, ] + assert_(grid128c_a.dtype == grid128c_b.dtype == np.longdouble) + assert_array_equal(grid128c_a, grid128c_b[0]) + + # different code path for single slice + grid64 = mgrid[0.1:0.33:0.1] + grid128 = mgrid[ + np.longdouble(0.1):np.longdouble(0.33):np.longdouble(0.1) + ] + assert_(grid128.dtype == np.longdouble) + assert_array_almost_equal(grid64, grid128) + + def test_accepts_npcomplexfloating(self): + # Related to #16466 + assert_array_almost_equal( + mgrid[0.1:0.3:3j, ], mgrid[0.1:0.3:np.complex64(3j), ] + ) + + # different code path for single slice + assert_array_almost_equal( + mgrid[0.1:0.3:3j], mgrid[0.1:0.3:np.complex64(3j)] + ) + + # Related to #16945 + grid64_a = mgrid[0.1:0.3:3.3j] + grid64_b = mgrid[0.1:0.3:3.3j, ][0] + assert_(grid64_a.dtype == grid64_b.dtype == np.float64) + assert_array_equal(grid64_a, grid64_b) + + grid128_a = mgrid[0.1:0.3:np.clongdouble(3.3j)] + grid128_b = mgrid[0.1:0.3:np.clongdouble(3.3j), ][0] + assert_(grid128_a.dtype == grid128_b.dtype == np.longdouble) + assert_array_equal(grid64_a, grid64_b) + + +class TestConcatenator: + def test_1d(self): + assert_array_equal(r_[1, 2, 3, 4, 5, 6], np.array([1, 2, 3, 4, 5, 6])) + b = np.ones(5) + c = r_[b, 0, 0, b] + assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1]) + + def test_mixed_type(self): + g = r_[10.1, 1:10] + assert_(g.dtype == 'f8') + + def test_more_mixed_type(self): + g = r_[-10.1, np.array([1]), np.array([2, 3, 4]), 10.0] + assert_(g.dtype == 'f8') + + def test_complex_step(self): + # Regression test for #12262 + g = r_[0:36:100j] + assert_(g.shape == (100,)) + + # Related to #16466 + g = r_[0:36:np.complex64(100j)] + assert_(g.shape == (100,)) + + def test_2d(self): + b = np.random.rand(5, 5) + c = np.random.rand(5, 5) + d = r_['1', b, c] # append columns + assert_(d.shape == (5, 10)) + assert_array_equal(d[:, :5], b) + assert_array_equal(d[:, 5:], c) + d = r_[b, c] + assert_(d.shape == (10, 5)) + assert_array_equal(d[:5, :], b) + assert_array_equal(d[5:, :], c) + + def test_0d(self): + assert_equal(r_[0, np.array(1), 2], [0, 1, 2]) + assert_equal(r_[[0, 1, 2], np.array(3)], [0, 1, 2, 3]) + assert_equal(r_[np.array(0), [1, 2, 3]], [0, 1, 2, 3]) + + +class TestNdenumerate: + def test_basic(self): + a = np.array([[1, 2], [3, 4]]) + assert_equal(list(ndenumerate(a)), + [((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)]) + + +class TestIndexExpression: + def test_regression_1(self): + # ticket #1196 + a = np.arange(2) + assert_equal(a[:-1], a[s_[:-1]]) + assert_equal(a[:-1], a[index_exp[:-1]]) + + def test_simple_1(self): + a = np.random.rand(4, 5, 6) + + assert_equal(a[:, :3, [1, 2]], a[index_exp[:, :3, [1, 2]]]) + assert_equal(a[:, :3, [1, 2]], a[s_[:, :3, [1, 2]]]) + + +class TestIx_: + def test_regression_1(self): + # Test empty untyped inputs create outputs of indexing type, gh-5804 + a, = np.ix_(range(0)) + assert_equal(a.dtype, np.intp) + + a, = np.ix_([]) + assert_equal(a.dtype, np.intp) + + # but if the type is specified, don't change it + a, = np.ix_(np.array([], dtype=np.float32)) + assert_equal(a.dtype, np.float32) + + def test_shape_and_dtype(self): + sizes = (4, 5, 3, 2) + # Test both lists and arrays + for func in (range, np.arange): + arrays = np.ix_(*[func(sz) for sz in sizes]) + for k, (a, sz) in enumerate(zip(arrays, sizes)): + assert_equal(a.shape[k], sz) + assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k)) + assert_(np.issubdtype(a.dtype, np.integer)) + + def test_bool(self): + bool_a = [True, False, True, True] + int_a, = np.nonzero(bool_a) + assert_equal(np.ix_(bool_a)[0], int_a) + + def test_1d_only(self): + idx2d = [[1, 2, 3], [4, 5, 6]] + assert_raises(ValueError, np.ix_, idx2d) + + def test_repeated_input(self): + length_of_vector = 5 + x = np.arange(length_of_vector) + out = ix_(x, x) + assert_equal(out[0].shape, (length_of_vector, 1)) + assert_equal(out[1].shape, (1, length_of_vector)) + # check that input shape is not modified + assert_equal(x.shape, (length_of_vector,)) + + +def test_c_(): + a = np.c_[np.array([[1, 2, 3]]), 0, 0, np.array([[4, 5, 6]])] + assert_equal(a, [[1, 2, 3, 0, 0, 4, 5, 6]]) + + +class TestFillDiagonal: + def test_basic(self): + a = np.zeros((3, 3), int) + fill_diagonal(a, 5) + assert_array_equal( + a, np.array([[5, 0, 0], + [0, 5, 0], + [0, 0, 5]]) + ) + + def test_tall_matrix(self): + a = np.zeros((10, 3), int) + fill_diagonal(a, 5) + assert_array_equal( + a, np.array([[5, 0, 0], + [0, 5, 0], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]) + ) + + def test_tall_matrix_wrap(self): + a = np.zeros((10, 3), int) + fill_diagonal(a, 5, True) + assert_array_equal( + a, np.array([[5, 0, 0], + [0, 5, 0], + [0, 0, 5], + [0, 0, 0], + [5, 0, 0], + [0, 5, 0], + [0, 0, 5], + [0, 0, 0], + [5, 0, 0], + [0, 5, 0]]) + ) + + def test_wide_matrix(self): + a = np.zeros((3, 10), int) + fill_diagonal(a, 5) + assert_array_equal( + a, np.array([[5, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 5, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 5, 0, 0, 0, 0, 0, 0, 0]]) + ) + + def test_operate_4d_array(self): + a = np.zeros((3, 3, 3, 3), int) + fill_diagonal(a, 4) + i = np.array([0, 1, 2]) + assert_equal(np.where(a != 0), (i, i, i, i)) + + def test_low_dim_handling(self): + # raise error with low dimensionality + a = np.zeros(3, int) + with assert_raises_regex(ValueError, "at least 2-d"): + fill_diagonal(a, 5) + + def test_hetero_shape_handling(self): + # raise error with high dimensionality and + # shape mismatch + a = np.zeros((3,3,7,3), int) + with assert_raises_regex(ValueError, "equal length"): + fill_diagonal(a, 2) + + +def test_diag_indices(): + di = diag_indices(4) + a = np.array([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]]) + a[di] = 100 + assert_array_equal( + a, np.array([[100, 2, 3, 4], + [5, 100, 7, 8], + [9, 10, 100, 12], + [13, 14, 15, 100]]) + ) + + # Now, we create indices to manipulate a 3-d array: + d3 = diag_indices(2, 3) + + # And use it to set the diagonal of a zeros array to 1: + a = np.zeros((2, 2, 2), int) + a[d3] = 1 + assert_array_equal( + a, np.array([[[1, 0], + [0, 0]], + [[0, 0], + [0, 1]]]) + ) + + +class TestDiagIndicesFrom: + + def test_diag_indices_from(self): + x = np.random.random((4, 4)) + r, c = diag_indices_from(x) + assert_array_equal(r, np.arange(4)) + assert_array_equal(c, np.arange(4)) + + def test_error_small_input(self): + x = np.ones(7) + with assert_raises_regex(ValueError, "at least 2-d"): + diag_indices_from(x) + + def test_error_shape_mismatch(self): + x = np.zeros((3, 3, 2, 3), int) + with assert_raises_regex(ValueError, "equal length"): + diag_indices_from(x) + + +def test_ndindex(): + x = list(ndindex(1, 2, 3)) + expected = [ix for ix, e in ndenumerate(np.zeros((1, 2, 3)))] + assert_array_equal(x, expected) + + x = list(ndindex((1, 2, 3))) + assert_array_equal(x, expected) + + # Test use of scalars and tuples + x = list(ndindex((3,))) + assert_array_equal(x, list(ndindex(3))) + + # Make sure size argument is optional + x = list(ndindex()) + assert_equal(x, [()]) + + x = list(ndindex(())) + assert_equal(x, [()]) + + # Make sure 0-sized ndindex works correctly + x = list(ndindex(*[0])) + assert_equal(x, []) diff --git a/shared/package-files/56/563dcf55580ef635d85c2c376da6f3269d00624d3d914e0cde871258b0929f8b/arima111nc_css_results.py b/shared/package-files/56/563dcf55580ef635d85c2c376da6f3269d00624d3d914e0cde871258b0929f8b/arima111nc_css_results.py new file mode 100644 index 0000000000000000000000000000000000000000..664d00b340054e2d944b0713a9ae40acf54cefd2 --- /dev/null +++ b/shared/package-files/56/563dcf55580ef635d85c2c376da6f3269d00624d3d914e0cde871258b0929f8b/arima111nc_css_results.py @@ -0,0 +1,1297 @@ +import numpy as np + +from statsmodels.tools.tools import Bunch + +llf = np.array([-242.89663276735]) + +nobs = np.array([202]) + +k = np.array([3]) + +k_exog = np.array([1]) + +sigma = np.array([.8053519404535]) + +chi2 = np.array([15723.381396967]) + +df_model = np.array([2]) + +k_ar = np.array([1]) + +k_ma = np.array([1]) + +params = np.array([ + .99479180506163, + -.84461527652809, + .64859174799221]) + +cov_params = np.array([ + .00008904968254, + -.00023560410507, + .00012795903324, + -.00023560410507, + .00131628534915, + -.00022462340695, + .00012795903324, + -.00022462340695, + .0005651128627]).reshape(3, 3) + +xb = np.array([ + 0, + 0, + .02869686298072, + .05651443824172, + .0503994859755, + .06887971609831, + .05940540507436, + .08067328482866, + .08167565613985, + .06429278105497, + .07087650150061, + .06886467337608, + .06716959923506, + .08230647444725, + .07099691033363, + .08401278406382, + .07996553182602, + .07354256510735, + .09366323798895, + .08811800926924, + .10296355187893, + .08846370875835, + .0852297320962, + .08700425922871, + .09751411527395, + .09737934917212, + .11228405684233, + .1053489819169, + .12352022528648, + .16439816355705, + .1643835157156, + .19891132414341, + .17551273107529, + .17827558517456, + .19562774896622, + .21028305590153, + .23767858743668, + .24580039083958, + .28269505500793, + .29883882403374, + .31247469782829, + .35402658581734, + .37410452961922, + .39106267690659, + .42040377855301, + .44518512487411, + .43608102202415, + .44340893626213, + .44959822297096, + .40977239608765, + .42118826508522, + .40079545974731, + .38357082009315, + .36902260780334, + .35673499107361, + .36137464642525, + .38031083345413, + .47139286994934, + .47323387861252, + .60994738340378, + .69538277387619, + .7825602889061, + .84117436408997, + .9657689332962, + 1.0109325647354, + .95897275209427, + .96013957262039, + .9461076259613, + .9342554807663, + .83413934707642, + .83968591690063, + .84437066316605, + .83330947160721, + .8990553021431, + .87949693202972, + .86297762393951, + .89407861232758, + .93536442518234, + 1.0303052663803, + 1.1104937791824, + 1.1481873989105, + 1.2851470708847, + 1.4458787441254, + 1.5515991449356, + 1.7309991121292, + 1.8975404500961, + 1.8579913377762, + 1.8846583366394, + 1.9672524929047, + 1.9469071626663, + 2.0048115253448, + 1.9786299467087, + 1.8213576078415, + 1.6284521818161, + 1.7508568763733, + 1.5689061880112, + 1.2950873374939, + 1.2290096282959, + 1.1882168054581, + 1.1537625789642, + 1.1697143316269, + 1.1681711673737, + 1.106795668602, + 1.0849931240082, + 1.006507396698, + 1.0453414916992, + .98803448677063, + .95465070009232, + 1.0165599584579, + .67838954925537, + .69311982393265, + .69054269790649, + .76345545053482, + .84005492925644, + .87471830844879, + .91901183128357, + .92638796567917, + .96265280246735, + 1.0083012580872, + 1.0618740320206, + 1.0921038389206, + 1.2077431678772, + 1.2303256988525, + 1.174311041832, + 1.3072115182877, + 1.314337015152, + 1.3503924608231, + 1.5760731697083, + 1.5264053344727, + 1.34929728508, + 1.304829955101, + 1.2522557973862, + 1.222869515419, + 1.198047041893, + 1.1770839691162, + 1.1743944883347, + 1.1571066379547, + 1.1274864673615, + 1.0574153661728, + 1.058304309845, + .99898308515549, + .9789143204689, + 1.0070173740387, + 1.000718832016, + 1.0104174613953, + 1.0486439466476, + 1.0058424472809, + .98470783233643, + 1.0119106769562, + 1.0649236440659, + 1.0346088409424, + 1.0540577173233, + 1.0704846382141, + .97923594713211, + .90216588973999, + .9271782040596, + .85819715261459, + .75488126277924, + .78776079416275, + .77047789096832, + .77089905738831, + .8313245177269, + .82229107618332, + .90476810932159, + .94439232349396, + 1.0379292964935, + 1.1469690799713, + 1.1489590406418, + 1.2257302999496, + 1.1554099321365, + 1.1260533332825, + .9811190366745, + .8436843752861, + .95287209749222, + .90993344783783, + .94875508546829, + 1.0115815401077, + .94450175762177, + .87282890081406, + .91741597652435, + .98511207103729, + .9972335100174, + 1.0975805521011, + 1.1823329925537, + 1.1487929821014, + 1.270641207695, + 1.2083609104156, + 1.696394443512, + 1.4628355503082, + 1.4307631254196, + 1.5087975263596, + 1.1542117595673, + 1.2262620925903, + 1.3880327939987, + 1.3853038549423, + 1.4396153688431, + 1.7208145856857, + 1.678991317749, + 2.110867023468, + 1.524417757988, + .57946246862411, + .56406193971634, + .74643105268478]) + +y = np.array([ + np.nan, + 28.979999542236, + 29.178695678711, + 29.40651512146, + 29.420400619507, + 29.608880996704, + 29.609405517578, + 29.830673217773, + 29.921676635742, + 29.874292373657, + 29.990877151489, + 30.048864364624, + 30.10717010498, + 30.292304992676, + 30.290996551514, + 30.464012145996, + 30.519966125488, + 30.553541183472, + 30.783664703369, + 30.838117599487, + 31.042964935303, + 31.038463592529, + 31.105230331421, + 31.207004547119, + 31.377513885498, + 31.477378845215, + 31.692283630371, + 31.755348205566, + 32.003520965576, + 32.444396972656, + 32.61438369751, + 33.048908233643, + 33.07551574707, + 33.278274536133, + 33.595630645752, + 33.91028213501, + 34.337677001953, + 34.645801544189, + 35.182697296143, + 35.598838806152, + 36.012474060059, + 36.654026031494, + 37.174102783203, + 37.691062927246, + 38.320404052734, + 38.94518661499, + 39.336082458496, + 39.843410491943, + 40.349597930908, + 40.509769439697, + 41.021186828613, + 41.300796508789, + 41.583572387695, + 41.869022369385, + 42.156734466553, + 42.561374664307, + 43.080310821533, + 44.171394348145, + 44.673233032227, + 46.209945678711, + 47.495380401611, + 48.882556915283, + 50.141174316406, + 51.965770721436, + 53.310932159424, + 53.958972930908, + 54.960140228271, + 55.84610748291, + 56.734252929688, + 56.934139251709, + 57.839687347412, + 58.744373321533, + 59.533309936523, + 60.899055480957, + 61.679496765137, + 62.46297454834, + 63.594078063965, + 64.83536529541, + 66.530303955078, + 68.210494995117, + 69.64818572998, + 71.885147094727, + 74.445877075195, + 76.751594543457, + 79.731002807617, + 82.797538757324, + 84.457992553711, + 86.584655761719, + 89.167251586914, + 91.046905517578, + 93.504814147949, + 95.378631591797, + 96.22135925293, + 96.628448486328, + 99.250854492188, + 99.668907165527, + 99.195091247559, + 100.0290145874, + 100.98822021484, + 101.95376586914, + 103.26971435547, + 104.46817779541, + 105.20679473877, + 106.1849899292, + 106.70650482178, + 108.0453414917, + 108.68803405762, + 109.45465087891, + 110.91656494141, + 109.37838745117, + 110.19312286377, + 110.89054107666, + 112.16345977783, + 113.54005432129, + 114.67472076416, + 115.91901397705, + 116.92639160156, + 118.16265106201, + 119.50830078125, + 120.96187591553, + 122.29209899902, + 124.30773925781, + 125.7303237915, + 126.57431030273, + 128.8072052002, + 130.21432495117, + 131.85038757324, + 134.97607421875, + 136.22640991211, + 136.44931030273, + 137.50482177734, + 138.45225524902, + 139.5228729248, + 140.59803771973, + 141.67707824707, + 142.87438964844, + 143.95710754395, + 144.92749023438, + 145.55741882324, + 146.65830993652, + 147.29898071289, + 148.17890930176, + 149.40701293945, + 150.40071105957, + 151.51042175293, + 152.84864807129, + 153.60585021973, + 154.48471069336, + 155.7119140625, + 157.16493225098, + 158.03460693359, + 159.25405883789, + 160.47047424316, + 160.87922668457, + 161.30215454102, + 162.42718505859, + 162.85820007324, + 162.95487976074, + 163.98776245117, + 164.67047119141, + 165.47090148926, + 166.73132324219, + 167.52229309082, + 169.00477600098, + 170.24440002441, + 171.93792724609, + 173.84696960449, + 175.04895019531, + 176.82572937012, + 177.55540466309, + 178.52604675293, + 178.58113098145, + 178.54368591309, + 180.25286865234, + 180.90992736816, + 182.14875793457, + 183.61158752441, + 184.14450073242, + 184.5728302002, + 185.81741333008, + 187.28511047363, + 188.39723205566, + 190.19758605957, + 191.98233032227, + 192.94879150391, + 195.07064819336, + 195.90835571289, + 200.89639282227, + 200.86282348633, + 202.13075256348, + 204.20880126953, + 203.05419921875, + 204.80026245117, + 207.3080291748, + 208.72329711914, + 210.57261657715, + 214.21580505371, + 215.67597961426, + 220.72087097168, + 218.41342163086, + 212.75346374512, + 213.23506164551, + 215.21542358398]) + +resid = np.array([ + np.nan, + .17000007629395, + .17130389809608, + -.03651398047805, + .11960058659315, + -.05888139456511, + .14059536159039, + .00932686589658, + -.11167634278536, + .04570783302188, + -.0108770346269, + -.00886330008507, + .10282856971025, + -.07230624556541, + .08900293707848, + -.0240114107728, + -.03996651992202, + .13645842671394, + -.03366377204657, + .10188252478838, + -.09296332299709, + -.01846401393414, + .01477065030485, + .0729955881834, + .00248436117545, + .10262141376734, + -.04228436201811, + .12465056031942, + .27647939324379, + .00560382334515, + .23561419546604, + -.1489082723856, + .02448422275484, + .12172746658325, + .10437148809433, + .18971465528011, + .06232447177172, + .25419962406158, + .11730266362429, + .10116269439459, + .2875237762928, + .14597341418266, + .12589547038078, + .20893961191177, + .17959471046925, + -.04518361017108, + .06391899287701, + .05659105628729, + -.24960128962994, + .09022761881351, + -.12118522822857, + -.10079623758793, + -.08357158303261, + -.06902338564396, + .04326653853059, + .13862533867359, + .61968916654587, + .02860714122653, + .92676383256912, + .59005337953568, + .60461646318436, + .41744044423103, + .85882639884949, + .33423033356667, + -.31093180179596, + .04102724045515, + -.06013804674149, + -.04610994458199, + -.63425624370575, + .06586220860481, + .06031560897827, + -.04437142238021, + .46668976545334, + -.09905604273081, + -.07949769496918, + .23702463507652, + .30592212080956, + .66463404893875, + .56969320774078, + .28950771689415, + .95181107521057, + 1.1148544549942, + .75411820411682, + 1.2484039068222, + 1.1690024137497, + -.1975435167551, + .24200716614723, + .6153416633606, + -.06725100427866, + .45309436321259, + -.10480991750956, + -.97863000631332, + -1.2213591337204, + .8715478181839, + -1.1508584022522, + -1.7689031362534, + -.39508575201035, + -.22900961339474, + -.18821682035923, + .14623281359673, + .03029025532305, + -.36817568540573, + -.10679569840431, + -.48499462008476, + .29349562525749, + -.34534454345703, + -.18803144991398, + .44535079598427, + -2.2165644168854, + .12161350995302, + .00687709869817, + .50946187973022, + .53653997182846, + .25995117425919, + .32527860999107, + .08098815381527, + .27360898256302, + .33735024929047, + .39170032739639, + .23812144994736, + .80789774656296, + .19225835800171, + -.33032417297363, + .92568749189377, + .09278241544962, + .28566908836365, + 1.5496014356613, + -.27607008814812, + -1.1263961791992, + -.24930645525455, + -.30482992529869, + -.15224970877171, + -.12287864089012, + -.09804095327854, + .02291300706565, + -.07438835501671, + -.15710659325123, + -.42748948931694, + .04259072244167, + -.35830733180046, + -.09898918122053, + .22108262777328, + -.00701736938208, + .0992873236537, + .28958559036255, + -.24864092469215, + -.10584850609303, + .21528913080692, + .38809850811958, + -.16492980718613, + .16538816690445, + .1459391862154, + -.57048463821411, + -.47923597693443, + .19784018397331, + -.4271782040596, + -.65820020437241, + .24511873722076, + -.0877638310194, + .02952514961362, + .42909786105156, + -.03132146969438, + .57771807909012, + .29522883892059, + .6555985212326, + .76207375526428, + .05302781611681, + .55105316638947, + -.42574247717857, + -.15540990233421, + -.92604118585587, + -.88112819194794, + .75632172822952, + -.25287514925003, + .29006350040436, + .45125409960747, + -.41159069538116, + -.44450175762177, + .32716807723045, + .48259317874908, + .11487878113985, + .70277869701385, + .60241633653641, + -.18233296275139, + .85120695829391, + -.37064728140831, + 3.2916390895844, + -1.4963974952698, + -.16283248364925, + .56923681497574, + -2.3088004589081, + .51979947090149, + 1.1197309494019, + .02996650896966, + .40969428420067, + 1.9223841428757, + -.21881568431854, + 2.9340152740479, + -3.8318600654602, + -6.239429473877, + -.08245316892862, + 1.2339268922806, + 1.1695692539215]) + +yr = np.array([ + np.nan, + .17000007629395, + .17130389809608, + -.03651398047805, + .11960058659315, + -.05888139456511, + .14059536159039, + .00932686589658, + -.11167634278536, + .04570783302188, + -.0108770346269, + -.00886330008507, + .10282856971025, + -.07230624556541, + .08900293707848, + -.0240114107728, + -.03996651992202, + .13645842671394, + -.03366377204657, + .10188252478838, + -.09296332299709, + -.01846401393414, + .01477065030485, + .0729955881834, + .00248436117545, + .10262141376734, + -.04228436201811, + .12465056031942, + .27647939324379, + .00560382334515, + .23561419546604, + -.1489082723856, + .02448422275484, + .12172746658325, + .10437148809433, + .18971465528011, + .06232447177172, + .25419962406158, + .11730266362429, + .10116269439459, + .2875237762928, + .14597341418266, + .12589547038078, + .20893961191177, + .17959471046925, + -.04518361017108, + .06391899287701, + .05659105628729, + -.24960128962994, + .09022761881351, + -.12118522822857, + -.10079623758793, + -.08357158303261, + -.06902338564396, + .04326653853059, + .13862533867359, + .61968916654587, + .02860714122653, + .92676383256912, + .59005337953568, + .60461646318436, + .41744044423103, + .85882639884949, + .33423033356667, + -.31093180179596, + .04102724045515, + -.06013804674149, + -.04610994458199, + -.63425624370575, + .06586220860481, + .06031560897827, + -.04437142238021, + .46668976545334, + -.09905604273081, + -.07949769496918, + .23702463507652, + .30592212080956, + .66463404893875, + .56969320774078, + .28950771689415, + .95181107521057, + 1.1148544549942, + .75411820411682, + 1.2484039068222, + 1.1690024137497, + -.1975435167551, + .24200716614723, + .6153416633606, + -.06725100427866, + .45309436321259, + -.10480991750956, + -.97863000631332, + -1.2213591337204, + .8715478181839, + -1.1508584022522, + -1.7689031362534, + -.39508575201035, + -.22900961339474, + -.18821682035923, + .14623281359673, + .03029025532305, + -.36817568540573, + -.10679569840431, + -.48499462008476, + .29349562525749, + -.34534454345703, + -.18803144991398, + .44535079598427, + -2.2165644168854, + .12161350995302, + .00687709869817, + .50946187973022, + .53653997182846, + .25995117425919, + .32527860999107, + .08098815381527, + .27360898256302, + .33735024929047, + .39170032739639, + .23812144994736, + .80789774656296, + .19225835800171, + -.33032417297363, + .92568749189377, + .09278241544962, + .28566908836365, + 1.5496014356613, + -.27607008814812, + -1.1263961791992, + -.24930645525455, + -.30482992529869, + -.15224970877171, + -.12287864089012, + -.09804095327854, + .02291300706565, + -.07438835501671, + -.15710659325123, + -.42748948931694, + .04259072244167, + -.35830733180046, + -.09898918122053, + .22108262777328, + -.00701736938208, + .0992873236537, + .28958559036255, + -.24864092469215, + -.10584850609303, + .21528913080692, + .38809850811958, + -.16492980718613, + .16538816690445, + .1459391862154, + -.57048463821411, + -.47923597693443, + .19784018397331, + -.4271782040596, + -.65820020437241, + .24511873722076, + -.0877638310194, + .02952514961362, + .42909786105156, + -.03132146969438, + .57771807909012, + .29522883892059, + .6555985212326, + .76207375526428, + .05302781611681, + .55105316638947, + -.42574247717857, + -.15540990233421, + -.92604118585587, + -.88112819194794, + .75632172822952, + -.25287514925003, + .29006350040436, + .45125409960747, + -.41159069538116, + -.44450175762177, + .32716807723045, + .48259317874908, + .11487878113985, + .70277869701385, + .60241633653641, + -.18233296275139, + .85120695829391, + -.37064728140831, + 3.2916390895844, + -1.4963974952698, + -.16283248364925, + .56923681497574, + -2.3088004589081, + .51979947090149, + 1.1197309494019, + .02996650896966, + .40969428420067, + 1.9223841428757, + -.21881568431854, + 2.9340152740479, + -3.8318600654602, + -6.239429473877, + -.08245316892862, + 1.2339268922806, + 1.1695692539215]) + +mse = np.array([ + 1.1112809181213, + .6632194519043, + .65879660844803, + .65575885772705, + .65364873409271, + .65217137336731, + .65113133192062, + .6503963470459, + .64987552165985, + .64950579404831, + .64924287796021, + .64905577898026, + .64892256259918, + .64882761240005, + .64875996112823, + .64871168136597, + .64867728948593, + .64865279197693, + .64863526821136, + .64862281084061, + .64861387014389, + .64860755205154, + .64860302209854, + .64859980344772, + .64859747886658, + .64859586954117, + .64859467744827, + .64859384298325, + .6485932469368, + .64859282970428, + .64859253168106, + .64859229326248, + .64859211444855, + .64859199523926, + .64859193563461, + .64859187602997, + .64859187602997, + .64859181642532, + .64859181642532, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068, + .64859175682068]) + +stdp = np.array([ + 0, + 0, + .02869686298072, + .05651443824172, + .0503994859755, + .06887971609831, + .05940540507436, + .08067328482866, + .08167565613985, + .06429278105497, + .07087650150061, + .06886467337608, + .06716959923506, + .08230647444725, + .07099691033363, + .08401278406382, + .07996553182602, + .07354256510735, + .09366323798895, + .08811800926924, + .10296355187893, + .08846370875835, + .0852297320962, + .08700425922871, + .09751411527395, + .09737934917212, + .11228405684233, + .1053489819169, + .12352022528648, + .16439816355705, + .1643835157156, + .19891132414341, + .17551273107529, + .17827558517456, + .19562774896622, + .21028305590153, + .23767858743668, + .24580039083958, + .28269505500793, + .29883882403374, + .31247469782829, + .35402658581734, + .37410452961922, + .39106267690659, + .42040377855301, + .44518512487411, + .43608102202415, + .44340893626213, + .44959822297096, + .40977239608765, + .42118826508522, + .40079545974731, + .38357082009315, + .36902260780334, + .35673499107361, + .36137464642525, + .38031083345413, + .47139286994934, + .47323387861252, + .60994738340378, + .69538277387619, + .7825602889061, + .84117436408997, + .9657689332962, + 1.0109325647354, + .95897275209427, + .96013957262039, + .9461076259613, + .9342554807663, + .83413934707642, + .83968591690063, + .84437066316605, + .83330947160721, + .8990553021431, + .87949693202972, + .86297762393951, + .89407861232758, + .93536442518234, + 1.0303052663803, + 1.1104937791824, + 1.1481873989105, + 1.2851470708847, + 1.4458787441254, + 1.5515991449356, + 1.7309991121292, + 1.8975404500961, + 1.8579913377762, + 1.8846583366394, + 1.9672524929047, + 1.9469071626663, + 2.0048115253448, + 1.9786299467087, + 1.8213576078415, + 1.6284521818161, + 1.7508568763733, + 1.5689061880112, + 1.2950873374939, + 1.2290096282959, + 1.1882168054581, + 1.1537625789642, + 1.1697143316269, + 1.1681711673737, + 1.106795668602, + 1.0849931240082, + 1.006507396698, + 1.0453414916992, + .98803448677063, + .95465070009232, + 1.0165599584579, + .67838954925537, + .69311982393265, + .69054269790649, + .76345545053482, + .84005492925644, + .87471830844879, + .91901183128357, + .92638796567917, + .96265280246735, + 1.0083012580872, + 1.0618740320206, + 1.0921038389206, + 1.2077431678772, + 1.2303256988525, + 1.174311041832, + 1.3072115182877, + 1.314337015152, + 1.3503924608231, + 1.5760731697083, + 1.5264053344727, + 1.34929728508, + 1.304829955101, + 1.2522557973862, + 1.222869515419, + 1.198047041893, + 1.1770839691162, + 1.1743944883347, + 1.1571066379547, + 1.1274864673615, + 1.0574153661728, + 1.058304309845, + .99898308515549, + .9789143204689, + 1.0070173740387, + 1.000718832016, + 1.0104174613953, + 1.0486439466476, + 1.0058424472809, + .98470783233643, + 1.0119106769562, + 1.0649236440659, + 1.0346088409424, + 1.0540577173233, + 1.0704846382141, + .97923594713211, + .90216588973999, + .9271782040596, + .85819715261459, + .75488126277924, + .78776079416275, + .77047789096832, + .77089905738831, + .8313245177269, + .82229107618332, + .90476810932159, + .94439232349396, + 1.0379292964935, + 1.1469690799713, + 1.1489590406418, + 1.2257302999496, + 1.1554099321365, + 1.1260533332825, + .9811190366745, + .8436843752861, + .95287209749222, + .90993344783783, + .94875508546829, + 1.0115815401077, + .94450175762177, + .87282890081406, + .91741597652435, + .98511207103729, + .9972335100174, + 1.0975805521011, + 1.1823329925537, + 1.1487929821014, + 1.270641207695, + 1.2083609104156, + 1.696394443512, + 1.4628355503082, + 1.4307631254196, + 1.5087975263596, + 1.1542117595673, + 1.2262620925903, + 1.3880327939987, + 1.3853038549423, + 1.4396153688431, + 1.7208145856857, + 1.678991317749, + 2.110867023468, + 1.524417757988, + .57946246862411, + .56406193971634, + .74643105268478]) + +icstats = np.array([ + 202, + np.nan, + -242.89663276735, + 3, + 491.79326553469, + 501.7180686269]) + + +results = Bunch( + llf=llf, + nobs=nobs, + k=k, + k_exog=k_exog, + sigma=sigma, + chi2=chi2, + df_model=df_model, + k_ar=k_ar, + k_ma=k_ma, + params=params, + cov_params=cov_params, + xb=xb, + y=y, + resid=resid, + yr=yr, + mse=mse, + stdp=stdp, + icstats=icstats +) diff --git a/shared/package-files/56/563e1558fcad6e16795bbefe59ab34fffabc06bf514d4d6f467045ac7f0cdf3c/byte_order.h b/shared/package-files/56/563e1558fcad6e16795bbefe59ab34fffabc06bf514d4d6f467045ac7f0cdf3c/byte_order.h new file mode 100644 index 0000000000000000000000000000000000000000..d960b287e20fbc363dbe53bc7676bd6bf28c6759 --- /dev/null +++ b/shared/package-files/56/563e1558fcad6e16795bbefe59ab34fffabc06bf514d4d6f467045ac7f0cdf3c/byte_order.h @@ -0,0 +1,227 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __FreeBSD__ +#include +#include +#define thp_bswap16(x) bswap16(x) +#define thp_bswap32(x) bswap32(x) +#define thp_bswap64(x) bswap64(x) +#elif defined(__APPLE__) +#include +#define thp_bswap16(x) OSSwapInt16(x) +#define thp_bswap32(x) OSSwapInt32(x) +#define thp_bswap64(x) OSSwapInt64(x) +#elif defined(__GNUC__) && !defined(__MINGW32__) +#include +#define thp_bswap16(x) bswap_16(x) +#define thp_bswap32(x) bswap_32(x) +#define thp_bswap64(x) bswap_64(x) +#elif defined _WIN32 || defined _WIN64 +#define thp_bswap16(x) _byteswap_ushort(x) +#define thp_bswap32(x) _byteswap_ulong(x) +#define thp_bswap64(x) _byteswap_uint64(x) +#endif + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define to_be16(x) thp_bswap16(x) +#define from_be16(x) thp_bswap16(x) +#define to_be32(x) thp_bswap32(x) +#define from_be32(x) thp_bswap32(x) +#define to_be64(x) thp_bswap64(x) +#define from_be64(x) thp_bswap64(x) +#define to_le16(x) (x) +#define from_le16(x) (x) +#define to_le32(x) (x) +#define from_le32(x) (x) +#define to_le64(x) (x) +#define from_le64(x) (x) +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define to_be16(x) (x) +#define from_be16(x) (x) +#define to_be32(x) (x) +#define from_be32(x) (x) +#define to_be64(x) (x) +#define from_be64(x) (x) +#define to_le16(x) thp_bswap16(x) +#define from_le16(x) thp_bswap16(x) +#define to_le32(x) thp_bswap32(x) +#define from_le32(x) thp_bswap32(x) +#define to_le64(x) thp_bswap64(x) +#define from_le64(x) thp_bswap64(x) +#else +#error Unexpected or undefined __BYTE_ORDER__ +#endif + +namespace torch { +namespace utils { + +enum THPByteOrder { THP_LITTLE_ENDIAN = 0, THP_BIG_ENDIAN = 1 }; + +TORCH_API THPByteOrder THP_nativeByteOrder(); + +TORCH_API void THP_decodeInt16Buffer( + int16_t* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeInt32Buffer( + int32_t* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeInt64Buffer( + int64_t* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeHalfBuffer( + c10::Half* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeFloatBuffer( + float* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeDoubleBuffer( + double* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeBoolBuffer( + bool* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeBFloat16Buffer( + at::BFloat16* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeComplexFloatBuffer( + c10::complex* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeComplexDoubleBuffer( + c10::complex* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); + +TORCH_API void THP_decodeInt16Buffer( + int16_t* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeInt32Buffer( + int32_t* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeInt64Buffer( + int64_t* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeHalfBuffer( + c10::Half* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeFloatBuffer( + float* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeDoubleBuffer( + double* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeBoolBuffer( + bool* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeBFloat16Buffer( + at::BFloat16* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeFloat8_e5m2Buffer( + at::Float8_e5m2* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeFloat8_e4m3fnBuffer( + at::Float8_e4m3fn* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeFloat8_e5m2fnuzBuffer( + at::Float8_e5m2fnuz* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeFloat8_e4m3fnuzBuffer( + at::Float8_e4m3fnuz* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeComplexFloatBuffer( + c10::complex* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeComplexDoubleBuffer( + c10::complex* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); + +TORCH_API void THP_encodeInt16Buffer( + uint8_t* dst, + const int16_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeInt32Buffer( + uint8_t* dst, + const int32_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeInt64Buffer( + uint8_t* dst, + const int64_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeFloatBuffer( + uint8_t* dst, + const float* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeDoubleBuffer( + uint8_t* dst, + const double* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeComplexFloatBuffer( + uint8_t* dst, + const c10::complex* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeComplexDoubleBuffer( + uint8_t* dst, + const c10::complex* src, + THPByteOrder order, + size_t len); + +} // namespace utils +} // namespace torch diff --git a/shared/package-files/56/563e435ddf0f296b765370c217a43555179ae3317e4104ce4494b5b4c3b59e4b/det_ops.h b/shared/package-files/56/563e435ddf0f296b765370c217a43555179ae3317e4104ce4494b5b4c3b59e4b/det_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..77ceba91198bb20f151d7cf0ccb52a84794b5de8 --- /dev/null +++ b/shared/package-files/56/563e435ddf0f296b765370c217a43555179ae3317e4104ce4494b5b4c3b59e4b/det_ops.h @@ -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 det { + 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::det") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "det(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/56/563fa8988b3ade8702d35f49f4e1940ba66e3adae9fe83cd64743e2e400353a9/scroll.py b/shared/package-files/56/563fa8988b3ade8702d35f49f4e1940ba66e3adae9fe83cd64743e2e400353a9/scroll.py new file mode 100644 index 0000000000000000000000000000000000000000..83a4be1f8fc5d1856a36836ed0e48e20d2fab4e2 --- /dev/null +++ b/shared/package-files/56/563fa8988b3ade8702d35f49f4e1940ba66e3adae9fe83cd64743e2e400353a9/scroll.py @@ -0,0 +1,189 @@ +""" +Key bindings, for scrolling up and down through pages. + +This are separate bindings, because GNU readline doesn't have them, but +they are very useful for navigating through long multiline buffers, like in +Vi, Emacs, etc... +""" +from __future__ import annotations + +from prompt_toolkit.key_binding.key_processor import KeyPressEvent + +__all__ = [ + "scroll_forward", + "scroll_backward", + "scroll_half_page_up", + "scroll_half_page_down", + "scroll_one_line_up", + "scroll_one_line_down", +] + +E = KeyPressEvent + + +def scroll_forward(event: E, half: bool = False) -> None: + """ + Scroll window down. + """ + w = event.app.layout.current_window + b = event.app.current_buffer + + if w and w.render_info: + info = w.render_info + ui_content = info.ui_content + + # Height to scroll. + scroll_height = info.window_height + if half: + scroll_height //= 2 + + # Calculate how many lines is equivalent to that vertical space. + y = b.document.cursor_position_row + 1 + height = 0 + while y < ui_content.line_count: + line_height = info.get_height_for_line(y) + + if height + line_height < scroll_height: + height += line_height + y += 1 + else: + break + + b.cursor_position = b.document.translate_row_col_to_index(y, 0) + + +def scroll_backward(event: E, half: bool = False) -> None: + """ + Scroll window up. + """ + w = event.app.layout.current_window + b = event.app.current_buffer + + if w and w.render_info: + info = w.render_info + + # Height to scroll. + scroll_height = info.window_height + if half: + scroll_height //= 2 + + # Calculate how many lines is equivalent to that vertical space. + y = max(0, b.document.cursor_position_row - 1) + height = 0 + while y > 0: + line_height = info.get_height_for_line(y) + + if height + line_height < scroll_height: + height += line_height + y -= 1 + else: + break + + b.cursor_position = b.document.translate_row_col_to_index(y, 0) + + +def scroll_half_page_down(event: E) -> None: + """ + Same as ControlF, but only scroll half a page. + """ + scroll_forward(event, half=True) + + +def scroll_half_page_up(event: E) -> None: + """ + Same as ControlB, but only scroll half a page. + """ + scroll_backward(event, half=True) + + +def scroll_one_line_down(event: E) -> None: + """ + scroll_offset += 1 + """ + w = event.app.layout.current_window + b = event.app.current_buffer + + if w: + # When the cursor is at the top, move to the next line. (Otherwise, only scroll.) + if w.render_info: + info = w.render_info + + if w.vertical_scroll < info.content_height - info.window_height: + if info.cursor_position.y <= info.configured_scroll_offsets.top: + b.cursor_position += b.document.get_cursor_down_position() + + w.vertical_scroll += 1 + + +def scroll_one_line_up(event: E) -> None: + """ + scroll_offset -= 1 + """ + w = event.app.layout.current_window + b = event.app.current_buffer + + if w: + # When the cursor is at the bottom, move to the previous line. (Otherwise, only scroll.) + if w.render_info: + info = w.render_info + + if w.vertical_scroll > 0: + first_line_height = info.get_height_for_line(info.first_visible_line()) + + cursor_up = info.cursor_position.y - ( + info.window_height + - 1 + - first_line_height + - info.configured_scroll_offsets.bottom + ) + + # Move cursor up, as many steps as the height of the first line. + # TODO: not entirely correct yet, in case of line wrapping and many long lines. + for _ in range(max(0, cursor_up)): + b.cursor_position += b.document.get_cursor_up_position() + + # Scroll window + w.vertical_scroll -= 1 + + +def scroll_page_down(event: E) -> None: + """ + Scroll page down. (Prefer the cursor at the top of the page, after scrolling.) + """ + w = event.app.layout.current_window + b = event.app.current_buffer + + if w and w.render_info: + # Scroll down one page. + line_index = max(w.render_info.last_visible_line(), w.vertical_scroll + 1) + w.vertical_scroll = line_index + + b.cursor_position = b.document.translate_row_col_to_index(line_index, 0) + b.cursor_position += b.document.get_start_of_line_position( + after_whitespace=True + ) + + +def scroll_page_up(event: E) -> None: + """ + Scroll page up. (Prefer the cursor at the bottom of the page, after scrolling.) + """ + w = event.app.layout.current_window + b = event.app.current_buffer + + if w and w.render_info: + # Put cursor at the first visible line. (But make sure that the cursor + # moves at least one line up.) + line_index = max( + 0, + min(w.render_info.first_visible_line(), b.document.cursor_position_row - 1), + ) + + b.cursor_position = b.document.translate_row_col_to_index(line_index, 0) + b.cursor_position += b.document.get_start_of_line_position( + after_whitespace=True + ) + + # Set the scroll offset. We can safely set it to zero; the Window will + # make sure that it scrolls at least until the cursor becomes visible. + w.vertical_scroll = 0 diff --git a/shared/package-files/56/5641a9e909f66d0b990a6d4fb2093bc4490352081f4974b9844e06dbfdfb5822/FunctionOfAMatrixUtils.h b/shared/package-files/56/5641a9e909f66d0b990a6d4fb2093bc4490352081f4974b9844e06dbfdfb5822/FunctionOfAMatrixUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..68b26ed1381133db9de0ba7cb2187578fb7d680d --- /dev/null +++ b/shared/package-files/56/5641a9e909f66d0b990a6d4fb2093bc4490352081f4974b9844e06dbfdfb5822/FunctionOfAMatrixUtils.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +namespace at { +struct TensorIterator; + +namespace native { + +using _compute_linear_combination_fn = void(*)( + TensorIterator& iter, + int64_t in_stride, + int64_t coeff_stride, + int64_t num_summations +); + +DECLARE_DISPATCH(_compute_linear_combination_fn, _compute_linear_combination_stub); + +}} // namespace at::native diff --git a/shared/package-files/56/5642d1b0a514557a37ceb8405e7f6233ea4ac926c62157f35a8a290e199c78c0/Palau b/shared/package-files/56/5642d1b0a514557a37ceb8405e7f6233ea4ac926c62157f35a8a290e199c78c0/Palau new file mode 100644 index 0000000000000000000000000000000000000000..bc8eb7a55b8a20a8c800507b620d0afef1d477a4 Binary files /dev/null and b/shared/package-files/56/5642d1b0a514557a37ceb8405e7f6233ea4ac926c62157f35a8a290e199c78c0/Palau differ diff --git a/shared/package-files/56/5643ad9376af2ed3a5d23bdae0172e6ec19fbb325d68d62661e90050f4cf118f/bmm_cuda_dispatch.h b/shared/package-files/56/5643ad9376af2ed3a5d23bdae0172e6ec19fbb325d68d62661e90050f4cf118f/bmm_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..24f873e339c639ea39f9091d4431e8871ec1ca47 --- /dev/null +++ b/shared/package-files/56/5643ad9376af2ed3a5d23bdae0172e6ec19fbb325d68d62661e90050f4cf118f/bmm_cuda_dispatch.h @@ -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 bmm(const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & bmm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & bmm_outf(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/b-128 b/shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/b-128 new file mode 100644 index 0000000000000000000000000000000000000000..775ba0954feda1dab5d4e3dd8232e135db3d08d6 Binary files /dev/null and b/shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/b-128 differ diff --git a/shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/commodore b/shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/commodore new file mode 100644 index 0000000000000000000000000000000000000000..775ba0954feda1dab5d4e3dd8232e135db3d08d6 Binary files /dev/null and b/shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/commodore differ diff --git a/shared/package-files/56/5646119d7e7043b4628400fa918aa2748fe16fd36028948013419a62e94da476/nameserver.py b/shared/package-files/56/5646119d7e7043b4628400fa918aa2748fe16fd36028948013419a62e94da476/nameserver.py new file mode 100644 index 0000000000000000000000000000000000000000..5dbb4e8baf00a4086f54ee6b796de6a89e462fb2 --- /dev/null +++ b/shared/package-files/56/5646119d7e7043b4628400fa918aa2748fe16fd36028948013419a62e94da476/nameserver.py @@ -0,0 +1,359 @@ +from typing import Optional, Union +from urllib.parse import urlparse + +import dns.asyncbackend +import dns.asyncquery +import dns.inet +import dns.message +import dns.query + + +class Nameserver: + def __init__(self): + pass + + def __str__(self): + raise NotImplementedError + + def kind(self) -> str: + raise NotImplementedError + + def is_always_max_size(self) -> bool: + raise NotImplementedError + + def answer_nameserver(self) -> str: + raise NotImplementedError + + def answer_port(self) -> int: + raise NotImplementedError + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + raise NotImplementedError + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + raise NotImplementedError + + +class AddressAndPortNameserver(Nameserver): + def __init__(self, address: str, port: int): + super().__init__() + self.address = address + self.port = port + + def kind(self) -> str: + raise NotImplementedError + + def is_always_max_size(self) -> bool: + return False + + def __str__(self): + ns_kind = self.kind() + return f"{ns_kind}:{self.address}@{self.port}" + + def answer_nameserver(self) -> str: + return self.address + + def answer_port(self) -> int: + return self.port + + +class Do53Nameserver(AddressAndPortNameserver): + def __init__(self, address: str, port: int = 53): + super().__init__(address, port) + + def kind(self): + return "Do53" + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + if max_size: + response = dns.query.tcp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + else: + response = dns.query.udp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + raise_on_truncation=True, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ignore_errors=True, + ignore_unexpected=True, + ) + return response + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + if max_size: + response = await dns.asyncquery.tcp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + backend=backend, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + else: + response = await dns.asyncquery.udp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + raise_on_truncation=True, + backend=backend, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ignore_errors=True, + ignore_unexpected=True, + ) + return response + + +class DoHNameserver(Nameserver): + def __init__( + self, + url: str, + bootstrap_address: Optional[str] = None, + verify: Union[bool, str] = True, + want_get: bool = False, + ): + super().__init__() + self.url = url + self.bootstrap_address = bootstrap_address + self.verify = verify + self.want_get = want_get + + def kind(self): + return "DoH" + + def is_always_max_size(self) -> bool: + return True + + def __str__(self): + return self.url + + def answer_nameserver(self) -> str: + return self.url + + def answer_port(self) -> int: + port = urlparse(self.url).port + if port is None: + port = 443 + return port + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return dns.query.https( + request, + self.url, + timeout=timeout, + source=source, + source_port=source_port, + bootstrap_address=self.bootstrap_address, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + post=(not self.want_get), + ) + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return await dns.asyncquery.https( + request, + self.url, + timeout=timeout, + source=source, + source_port=source_port, + bootstrap_address=self.bootstrap_address, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + post=(not self.want_get), + ) + + +class DoTNameserver(AddressAndPortNameserver): + def __init__( + self, + address: str, + port: int = 853, + hostname: Optional[str] = None, + verify: Union[bool, str] = True, + ): + super().__init__(address, port) + self.hostname = hostname + self.verify = verify + + def kind(self): + return "DoT" + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return dns.query.tls( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + server_hostname=self.hostname, + verify=self.verify, + ) + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return await dns.asyncquery.tls( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + server_hostname=self.hostname, + verify=self.verify, + ) + + +class DoQNameserver(AddressAndPortNameserver): + def __init__( + self, + address: str, + port: int = 853, + verify: Union[bool, str] = True, + server_hostname: Optional[str] = None, + ): + super().__init__(address, port) + self.verify = verify + self.server_hostname = server_hostname + + def kind(self): + return "DoQ" + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return dns.query.quic( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + server_hostname=self.server_hostname, + ) + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: Optional[str], + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return await dns.asyncquery.quic( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + server_hostname=self.server_hostname, + ) diff --git a/shared/package-files/56/56496724da7238138ed04b02aa5dfd17e03f3830063abcc620bc2f92b5436833/sphinxdoc.py b/shared/package-files/56/56496724da7238138ed04b02aa5dfd17e03f3830063abcc620bc2f92b5436833/sphinxdoc.py new file mode 100644 index 0000000000000000000000000000000000000000..92c2d64d67c4726b0d33b3f55c1c9716dc60198b --- /dev/null +++ b/shared/package-files/56/56496724da7238138ed04b02aa5dfd17e03f3830063abcc620bc2f92b5436833/sphinxdoc.py @@ -0,0 +1,161 @@ +"""Machinery for documenting traitlets config options with Sphinx. + +This includes: + +- A Sphinx extension defining directives and roles for config options. +- A function to generate an rst file given an Application instance. + +To make this documentation, first set this module as an extension in Sphinx's +conf.py:: + + extensions = [ + # ... + 'traitlets.config.sphinxdoc', + ] + +Autogenerate the config documentation by running code like this before +Sphinx builds:: + + from traitlets.config.sphinxdoc import write_doc + from myapp import MyApplication + + writedoc('config/options.rst', # File to write + 'MyApp config options', # Title + MyApplication() + ) + +The generated rST syntax looks like this:: + + .. configtrait:: Application.log_datefmt + + Description goes here. + + Cross reference like this: :configtrait:`Application.log_datefmt`. +""" +from collections import defaultdict +from textwrap import dedent + +from traitlets import Undefined +from traitlets.utils.text import indent + + +def setup(app): + """Registers the Sphinx extension. + + You shouldn't need to call this directly; configure Sphinx to use this + module instead. + """ + app.add_object_type("configtrait", "configtrait", objname="Config option") + metadata = {"parallel_read_safe": True, "parallel_write_safe": True} + return metadata + + +def interesting_default_value(dv): + if (dv is None) or (dv is Undefined): + return False + if isinstance(dv, (str, list, tuple, dict, set)): + return bool(dv) + return True + + +def format_aliases(aliases): + fmted = [] + for a in aliases: + dashes = "-" if len(a) == 1 else "--" + fmted.append(f"``{dashes}{a}``") + return ", ".join(fmted) + + +def class_config_rst_doc(cls, trait_aliases): + """Generate rST documentation for this class' config options. + + Excludes traits defined on parent classes. + """ + lines = [] + classname = cls.__name__ + for _, trait in sorted(cls.class_traits(config=True).items()): + ttype = trait.__class__.__name__ + + fullname = classname + "." + trait.name + lines += [".. configtrait:: " + fullname, ""] + + help = trait.help.rstrip() or "No description" + lines.append(indent(dedent(help)) + "\n") + + # Choices or type + if "Enum" in ttype: + # include Enum choices + lines.append(indent(":options: " + ", ".join("``%r``" % x for x in trait.values))) + else: + lines.append(indent(":trait type: " + ttype)) + + # Default value + # Ignore boring default values like None, [] or '' + if interesting_default_value(trait.default_value): + try: + dvr = trait.default_value_repr() + except Exception: + dvr = None # ignore defaults we can't construct + if dvr is not None: + if len(dvr) > 64: + dvr = dvr[:61] + "..." + # Double up backslashes, so they get to the rendered docs + dvr = dvr.replace("\\n", "\\\\n") + lines.append(indent(":default: ``%s``" % dvr)) + + # Command line aliases + if trait_aliases[fullname]: + fmt_aliases = format_aliases(trait_aliases[fullname]) + lines.append(indent(":CLI option: " + fmt_aliases)) + + # Blank line + lines.append("") + + return "\n".join(lines) + + +def reverse_aliases(app): + """Produce a mapping of trait names to lists of command line aliases.""" + res = defaultdict(list) + for alias, trait in app.aliases.items(): + res[trait].append(alias) + + # Flags also often act as aliases for a boolean trait. + # Treat flags which set one trait to True as aliases. + for flag, (cfg, _) in app.flags.items(): + if len(cfg) == 1: + classname = list(cfg)[0] + cls_cfg = cfg[classname] + if len(cls_cfg) == 1: + traitname = list(cls_cfg)[0] + if cls_cfg[traitname] is True: + res[classname + "." + traitname].append(flag) + + return res + + +def write_doc(path, title, app, preamble=None): + """Write a rst file documenting config options for a traitlets application. + + Parameters + ---------- + path : str + The file to be written + title : str + The human-readable title of the document + app : traitlets.config.Application + An instance of the application class to be documented + preamble : str + Extra text to add just after the title (optional) + """ + trait_aliases = reverse_aliases(app) + with open(path, "w") as f: + f.write(title + "\n") + f.write(("=" * len(title)) + "\n") + f.write("\n") + if preamble is not None: + f.write(preamble + "\n\n") + + for c in app._classes_inc_parents(): + f.write(class_config_rst_doc(c, trait_aliases)) + f.write("\n") diff --git a/shared/package-files/56/564c14cab191be17a8429c304e53fe65b464a83d6175f5d304e3232bab785e97/guards.py b/shared/package-files/56/564c14cab191be17a8429c304e53fe65b464a83d6175f5d304e3232bab785e97/guards.py new file mode 100644 index 0000000000000000000000000000000000000000..682610aeb908a47d756da38a18543493e753b970 --- /dev/null +++ b/shared/package-files/56/564c14cab191be17a8429c304e53fe65b464a83d6175f5d304e3232bab785e97/guards.py @@ -0,0 +1,1505 @@ +from __future__ import annotations + +import ast +import builtins +import collections +import dataclasses +import enum +import functools +import importlib +import inspect +import itertools +import logging +import math +import os +import re +import sys +import textwrap +import types +import weakref +from inspect import currentframe, getframeinfo +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union +from weakref import ReferenceType + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +import torch +import torch.utils._device +from torch._dynamo.source import ( + is_from_local_source, + TensorProperty, + TensorPropertySource, +) + +from torch._guards import ( + DuplicateInputs, + Guard, + GuardBuilderBase, + GuardEnvExpr, + GuardSource, + Source, +) + +from torch._logging import structured +from torch.fx.experimental.symbolic_shapes import ( + EqualityConstraint, + is_symbolic, + SYMPY_INTERP, +) +from torch.utils._traceback import format_frame, report_compile_source_on_error +from torch.utils.weak import TensorWeakRef + +from . import config, convert_frame, exc, mutation_guard +from .eval_frame import set_guard_error_hook +from .source import AttrSource, DefaultsSource, LocalSource, TypeSource +from .types import CacheEntry, ExtraState, GuardedCode, GuardFail, GuardFn # noqa: F401 +from .utils import ( + common_constant_types, + dict_keys_repr, + guard_failures, + istype, + key_is_id, + key_to_id, + orig_code_map, + tensor_always_has_static_shape, + tuple_iterator_getitem, + tuple_iterator_len, +) + +log = logging.getLogger(__name__) +guards_log = torch._logging.getArtifactLogger(__name__, "guards") +recompiles_log = torch._logging.getArtifactLogger(__name__, "recompiles") +recompiles_verbose_log = torch._logging.getArtifactLogger( + __name__, "recompiles_verbose" +) +verbose_guards_log = torch._logging.getArtifactLogger(__name__, "verbose_guards") + +TensorGuards = torch._C._dynamo.guards.TensorGuards +check_obj_id = torch._C._dynamo.guards.check_obj_id +check_type_id = torch._C._dynamo.guards.check_type_id +dict_version = torch._C._dynamo.guards.dict_version + + +# For user stack printing +@functools.lru_cache(None) +def uninteresting_files(): + import torch._dynamo.external_utils + + mods = [ + torch._dynamo.external_utils, + ] + return {inspect.getfile(m) for m in mods} + + +CLOSURE_VARS = { + "___check_type_id": check_type_id, + "___check_obj_id": check_obj_id, + "___odict_getitem": collections.OrderedDict.__getitem__, + "___key_to_id": key_to_id, + "___dict_version": dict_version, + "___dict_contains": lambda a, b: a in b, + "___tuple_iterator_len": tuple_iterator_len, + "___tuple_iterator_getitem": tuple_iterator_getitem, + "__math_isnan": math.isnan, + "__numpy_isnan": None if np is None else np.isnan, + "inf": float("inf"), + "__load_module": importlib.import_module, + "utils_device": torch.utils._device, + "device": torch.device, + "___from_numpy": + # If not numpy array, piggy back on e.g. tensor guards to check type + (lambda a: torch.as_tensor(a) if isinstance(a, (np.generic, np.ndarray)) else a), + "torch": torch, + "inspect": inspect, +} + +if sys.version_info[:2] <= (3, 8): + # [Note: Python Version <= 3.8] + # This branch should be dropped when we drop support for Python 3.8. + # Reason: 'ast.unparse' function was introduced in Python 3.9. + + try: + import astunparse # type: ignore[import] + + def _ast_unparse(node: ast.AST) -> str: + return astunparse.unparse(node).replace("\n", "") + + HAS_UNPARSE_FUNCTIONS = True + except ImportError: + HAS_UNPARSE_FUNCTIONS = False + pass +else: + HAS_UNPARSE_FUNCTIONS = True + + def _ast_unparse(node: ast.AST) -> str: + return ast.unparse(node).replace("\n", "") + + +def strip_function_call(name): + """ + "___odict_getitem(a, 1)" => "a" + "a.layers[slice(2)][0]._xyz" ==> "a" + "getattr(a.layers[slice(2)][0]._abc, '0')" ==> "a" + "getattr(getattr(a.x[3], '0'), '3')" ==> "a" + "a.layers[slice(None, -1, None)][0]._xyz" ==> "a" + """ + # recursively find valid object name in function + valid_name = re.compile("[A-Za-z_].*") + curr = "" + for char in name: + if char in " (": + curr = "" + elif char in "),[]": + if curr and curr != "None" and valid_name.match(curr): + return strip_function_call(curr) + else: + curr += char + + return strip_getattr_getitem(name) + + +def strip_getattr_getitem(name): + """ + "a[1]" => "a" + "a.foo" => "a" + """ + return re.split(r"[.\[]", name)[0] + + +def get_verbose_code_part(code_part, guard): + extra = "" + if guard.user_stack: + for fs in reversed(guard.user_stack): + if fs.filename not in uninteresting_files(): + extra = f" # {format_frame(fs, line=True)}" + break + elif guard.stack: + extra = f" # {format_frame(guard.stack.summary()[-1])}" + + return f"{code_part:<60}{extra}" + + +def convert_to_concrete_values(size_or_stride): + converted: List[Optional[int]] = [] + for dim in size_or_stride: + if not is_symbolic(dim): + converted.append(dim) + else: + assert isinstance(dim, torch.SymInt) + converted.append(dim.node.maybe_as_int()) + return converted + + +def get_tensor_guard_code_part(value, name, sizes, strides): + pytype = type(value) + dispatch_key = ( + torch._C._dispatch_keys(value) | torch._C._dispatch_tls_local_include_set() + ) - torch._C._dispatch_tls_local_exclude_set() + dtype = value.dtype + device_index = value.device.index + requires_grad = value.requires_grad + guard_str = ( + f"check_tensor({name}, {pytype.__qualname__}, {dispatch_key}, {dtype}, " + f"device={device_index}, requires_grad={requires_grad}, size={sizes}, stride={strides})" + ) + return guard_str + + +# The ready to eval generated code (possibly multiple parts) for a guard, plus +# the original guard object that created it for provenance +@dataclasses.dataclass +class GuardCodeList: + code_list: List[str] + guard: Guard + + +class GuardBuilder(GuardBuilderBase): + def __init__( + self, + id_ref: Callable[[Any], str], + source_ref: Callable[[Source], str], + lookup_weakrefs: Callable[[object], ReferenceType[object]], + local_scope: Dict[str, object], + global_scope: Dict[str, object], + check_fn_manager: CheckFunctionManager, + ): + self.id_ref = id_ref + self.source_ref = source_ref + self.lookup_weakrefs = lookup_weakrefs + self.scope: Dict[str, Dict[str, object]] = {"L": local_scope, "G": global_scope} + self.scope["__builtins__"] = builtins.__dict__.copy() + for ( + name, + package_module, + ) in torch.package.package_importer._package_imported_modules.items(): + name = name.replace(">", "_").replace("<", "_").replace(".", "_dot_") + # Write the package module into the scope so that we can import it + self.scope["__builtins__"][name] = package_module + # Write the demangled name to the scope so that we can use it + self.scope[name] = package_module + + self.argnames: List[str] = [] + # Code is python expression strings generated for each guard + self.code: List[GuardCodeList] = [] + # shape_env_code is only used by builder and is used for + # shape env code. This exists only because we need to make sure + # shape env guards get run after tensor match guards (since the + # tensor match guards make sure we actually have tensors) + self.shape_env_code: List[GuardCodeList] = [] + + # [Note - On Eager Tensor Guards] + # Most of the time, we generate Python code in a guard to directly + # check various properties. However, tensors are a bit special; + # it is too slow to check their properties one-by-one in Python. + # Instead, there is a C++ function TensorGuards.check which takes + # all of the tensor arguments and checks them all against compile-time + # examples entirely in C++. Thus, every time we process a + # TENSOR_MATCH guard, we just add another entry to + # tensor_check_names/tensor_check_examples, saying "for this local, + # check it against this example", and it all ends up getting + # swept up into a single call to ___check_tensors. Invariant: + # len(tensor_check_names) == len(tensor_check_examples). + # TODO: something here + self.tensor_check_names: List[str] = [] + self.tensor_check_examples: List[torch.Tensor] = [] + self.tensor_check_guards: List[Guard] = [] + + self.check_fn_manager: CheckFunctionManager = check_fn_manager + # Keep track of weak references of objects with ID_MATCH guard. This + # info is stored alongside optimized_code and check_fn and is used to + # limit the number of cache entries with same ID_MATCH'd object. + self.id_matched_objs: Dict[str, ReferenceType[object]] = {} + + # Warning: use this with care! This lets you access what the current + # value of the value you are guarding on is. You probably don't want + # to actually durably save this value though (because it's specific + # to this frame!) Instead, you should be reading out some property + # (like its type) which is what you permanently install into the + # guard code. + def get(self, name: str) -> Any: + return eval(name, self.scope, CLOSURE_VARS) + + # Registers the usage of the source name referenced by the + # string (or stored in the Guard) as being guarded upon. It's important + # to call this before generating some code that makes use of 'guard', + # because without this call, we won't actually bind the variable + # you reference in the actual guard closure (oops!) + def arg_ref(self, guard: Union[str, Guard]) -> str: + name: str + if isinstance(guard, str): + name = guard + else: + name = guard.name + base = strip_getattr_getitem(strip_function_call(name)) + if base not in self.argnames: + if re.match(r"[a-zA-Z0-9_]+", base): + if re.match(r"^\d+$", base): + log.warning("invalid var name: %s", guard) + self.argnames.append(base) + + return name + + def _guard_on_attribute(self, guard: Guard, attr_name: str, guard_fn): + attr_source = AttrSource(guard.originating_source, attr_name) + # Copy the stack info + new_guard = Guard( + attr_source, guard_fn, stack=guard.stack, user_stack=guard.user_stack + ) + new_guard.create(self) + + def TYPE_MATCH(self, guard: Guard) -> None: + # ___check_type_id is same as `id(type(x)) == y` + t = type(self.get(guard.name)) + obj_id = self.id_ref(t) + code = f"___check_type_id({self.arg_ref(guard)}, {obj_id})" + self._produce_guard_code(guard, [code]) + + def DICT_VERSION(self, guard: Guard): + # ___check_dict_version is same as `dict_version(x) == y` + ref = self.arg_ref(guard) + version = dict_version(self.get(guard.name)) + code = f"___dict_version({ref}) == {version}" + self._produce_guard_code(guard, [code]) + + def DICT_CONTAINS(self, guard: Guard, key: str, invert: bool): + dict_ref = self.arg_ref(guard) + + maybe_not = "not " if invert else "" + code = f"{maybe_not}___dict_contains({key!r}, {dict_ref})" + return self._produce_guard_code(guard, [code]) + + def BOOL_FALSE(self, guard: Guard): + # Guard on the runtime value being 'False', + # can be faster than seemingly equivalent checks like DICT_KEYS for empty dict + # + # WARNING: this guard is not safe to use generally. It only works if the runtime + # value is of a type that supports bool(), and some types e.g. Tensor do not. + # Only use this guard in cases you can guarantee the runtime type will be friendly. + # (e.g. Specialized NNModule with mutation protection via setattr) + # + # Why not simply check the runtime type inside this guard? It's slow enough to defeat + # the purpose of using this guard, which itself is supposed to be a faster alternative + # to DICT_KEYS. + ref = self.arg_ref(guard) + code = f"not {ref}" + self._produce_guard_code(guard, [code]) + + def ID_MATCH(self, guard: Guard): + # ___check_obj_id is same as `id(x) == y` + if isinstance(guard.originating_source, TypeSource): + # optional optimization to produce cleaner/faster guard code + return self.TYPE_MATCH( + Guard(guard.originating_source.base, GuardBuilder.TYPE_MATCH) # type: ignore[arg-type] + ) + + ref = self.arg_ref(guard) + val = self.get(guard.name) + code = f"___check_obj_id({ref}, {self.id_ref(val)})" + self._produce_guard_code(guard, [code]) + + # Keep track of ID_MATCH'd objects. This will be used to modify the + # cache size logic + if isinstance(guard.originating_source, LocalSource): + # TODO(janimesh) - This is currently restricted to nn.Module objects + # because many other ID_MATCH'd objects fail - like DeviceMesh. + # Increase the scope of ID_MATCH'd objects. + if isinstance(val, torch.nn.Module): + local_name = guard.originating_source.local_name + weak_id = self.lookup_weakrefs(val) + if weak_id is not None: + self.id_matched_objs[local_name] = weak_id + + def NAME_MATCH(self, guard: Guard): + obj = self.get(guard.name) + self._guard_on_attribute(guard, "__name__", GuardBuilder.EQUALS_MATCH) + + def DATA_PTR_MATCH(self, guard: Guard): + obj = self.get(guard.name) + code = f"{self.arg_ref(guard)}.data_ptr() == {obj.data_ptr()}" + self._produce_guard_code(guard, [code]) + + def HASATTR(self, guard: Guard): + assert isinstance( + guard.originating_source, AttrSource + ), f"invalid source {guard.name}" + base_source = guard.originating_source.base + base = base_source.name() + attr = guard.originating_source.member + + ref = self.arg_ref(base) + val = hasattr(self.get(base), attr) + code = None + if val: + code = f"hasattr({ref}, {attr!r})" + else: + code = f"not hasattr({ref}, {attr!r})" + + self._produce_guard_code(guard, [code], provided_guarded_object=self.get(base)) + + def FUNCTORCH_STACK_MATCH(self, guard: Guard): + # Invalidate functorch code if current level is different than + # the one when FX graph was generated + # if torch._C._functorch.peek_interpreter_stack() is not None: + cis = torch._functorch.pyfunctorch.retrieve_all_functorch_interpreters() + states = [ci.get_state() for ci in cis] + code = [f"torch._functorch.pyfunctorch.compare_functorch_state({states})"] + self._produce_guard_code(guard, code) + + def EQUALS_MATCH(self, guard: Guard): + ref = self.arg_ref(guard) + val = self.get(guard.name) + t = type(val) + if np: + np_types: Tuple[Type[Any], ...] = ( + np.int8, + np.int16, + np.int32, + np.int64, + np.uint8, + np.uint16, + np.uint32, + np.uint64, + np.float16, + np.float32, + np.float64, + ) + else: + np_types = () + ok_types = tuple( + common_constant_types + | { + type, + list, + tuple, + set, + frozenset, + slice, + range, + torch.Size, + *np_types, + } + ) + if istype(val, dict): + assert all( + istype(x, ok_types) for x in itertools.chain(val.keys(), val.values()) + ) + else: + assert istype( + val, + ok_types, + ), f"Unexpected type {type(val)}, not in {ok_types}" + + # Special case for nan because float("nan") == float("nan") evaluates to False + if istype(val, float) and math.isnan(val): + self.TYPE_MATCH(guard) + code = list() + code.append(f"__math_isnan({ref})") + self._produce_guard_code(guard, code) + return + # Python math library doesn't support complex nan, so we need to use numpy + elif istype(val, complex) and np.isnan(val): + self.TYPE_MATCH(guard) + code = list() + code.append(f"__numpy_isnan({ref})") + self._produce_guard_code(guard, code) + return + + code = list() + + # If matching equality against list/tuple, we must also check that + # the internal types match. (TODO: what about nested lists?) + if istype(val, (list, tuple)): + # NB: SEQUENCE_LENGTH takes care of the outer __check_type_id test + self.SEQUENCE_LENGTH(guard) + + for idx, elem in enumerate(val): + code.append( + f"___check_type_id({ref}[{idx}], {self.id_ref(type(elem))})" + ) + else: + # Add type check to prevent equality check between tensor and non-tensor. + self.TYPE_MATCH(guard) + + if istype(val, torch.Size): + val = tuple(val) + + # Code object can not be compared against their string representation + # I.e `eval(f"{compile('2+2','','exec')!r}")` raises SyntaxError + assert not istype(val, types.CodeType) + + # TODO: It feels like it would be better to just implement our own + # equality test in C that handles all of the necessary type checking + # and NaN tests + code.append(f"{ref} == {val!r}") + self._produce_guard_code(guard, code) + + def CONSTANT_MATCH(self, guard: Guard): + val = self.get(guard.name) + if istype(val, (bool, type(None), types.CodeType)): + self.ID_MATCH(guard) + else: + self.EQUALS_MATCH(guard) + + def NN_MODULE(self, guard: Guard): + self.ID_MATCH(guard) + ref = self.arg_ref(guard) + val = self.get(guard.name) + + def setup_guard(): + assert istype(val.training, bool) + self._guard_on_attribute(guard, "training", GuardBuilder.CONSTANT_MATCH) + + if hasattr(val, "training"): + # There are cases where a monkeypatched object has a guard made between __new__ and __init__ + setup_guard() + else: + exc.unimplemented(f"Guard setup for uninitialized class {type(val)}") + + def FUNCTION_MATCH(self, guard: Guard): + """things like torch.add and user defined functions""" + if guard.is_local(): + return self.ID_MATCH(guard) + + def CLOSURE_MATCH(self, guard: Guard): + """matches a closure by __code__ id.""" + if guard.is_local(): + val = self.get(guard.name) + # Strictly only want user-defined functions + if type(val) == types.FunctionType and hasattr(val, "__code__"): + self._guard_on_attribute(guard, "__code__", GuardBuilder.HASATTR) + self._guard_on_attribute(guard, "__code__", GuardBuilder.FUNCTION_MATCH) + else: + self.FUNCTION_MATCH(guard) + + def BUILTIN_MATCH(self, guard: Guard): + return self.FUNCTION_MATCH(guard) + + def PYMODULE_MATCH(self, guard: Guard): + return self.FUNCTION_MATCH(guard) + + def SEQUENCE_LENGTH(self, guard): + # This guard is used to check lenght of PySequence objects like list, + # tuple, collections.deque etc + ref = self.arg_ref(guard) + value = self.get(guard.name) + t = type(value) + + self.TYPE_MATCH(guard) + code = list() + if len(value) == 0: + code.append(f"not {ref}") + else: + code.append(f"len({ref}) == {len(value)}") + + self._produce_guard_code(guard, code) + + def DICT_LENGTH(self, guard): + self.SEQUENCE_LENGTH(guard) + + def TUPLE_ITERATOR_LEN(self, guard): + ref = self.arg_ref(guard) + value = self.get(guard.name) + t = type(value) + + self.TYPE_MATCH(guard) + code = list() + code.append(f"___tuple_iterator_len({ref}) == {tuple_iterator_len(value)}") + + self._produce_guard_code(guard, code) + + # TODO(voz): Deduplicate w/ AOTAutograd dupe input guards + def DUPLICATE_INPUT(self, guard, source_b): + ref_a = self.arg_ref(guard) + ref_b = self.arg_ref(source_b.name()) + + code = [f"{ref_b} is {ref_a}"] + self._produce_guard_code(guard, code) + + def DICT_KEYS(self, guard): + # Guard on the keys and their order + ref = self.arg_ref(guard) + value = self.get(guard.name) + t = type(value) + + self.TYPE_MATCH(guard) + code = list() + any_key_is_id = any(key_is_id(k) for k in value.keys()) + const_keys_repr = dict_keys_repr( + key_to_id(value), + local=is_from_local_source(guard.originating_source), + ) + if any_key_is_id: + code.append(f"___key_to_id({ref}) == {const_keys_repr}") + else: + code.append(f"list({ref}.keys()) == {const_keys_repr}") + + self._produce_guard_code(guard, code) + + def WEAKREF_ALIVE(self, guard): + self._produce_guard_code(guard, [f"{self.arg_ref(guard)} is not None"]) + + def NN_MODULE_PARAM_NAMES(self, guard): + ref = self.arg_ref(guard) + value = self.get(guard.name) + t = type(value) + keys = {k for k, v in value.named_parameters()} + + self.TYPE_MATCH(guard) + code = list() + code.append(f"{{k for k, v in {ref}.named_parameters()}} == {keys!r}") + + self._produce_guard_code(guard, code) + + def DICT_CONST_KEYS(self, guard): + """Constant keys match""" + ref = self.arg_ref(guard) + value = self.get(guard.name) + t = type(value) + + self.TYPE_MATCH(guard) + code = list() + code.append(f"list({ref}.keys()) == {list(value.keys())!r}") + + self._produce_guard_code(guard, code) + + def OBJECT_MUTATION(self, guard: Guard): + mutation_guard.watch(self.get(guard.name), self.check_fn_manager) + + def GRAD_MODE(self, guard: Guard): + pass # we always guard on this via GlobalStateGuard() + + def DETERMINISTIC_ALGORITHMS(self, guard: Guard): + pass # we always guard on this via GlobalStateGuard() + + def TORCH_FUNCTION_STATE(self, guard: Guard): + pass # we always guard on this via GlobalStateGuard() + + def DEFAULT_DEVICE(self, guard: Guard): + """Guard on CURRENT_DEVICE per torch.utils._device""" + assert guard.source is GuardSource.GLOBAL + import torch.utils._device as m + + self._produce_guard_code( + guard, [f"utils_device.CURRENT_DEVICE == {m.CURRENT_DEVICE!r}"] + ) + + def BACKEND_MATCH(self, guard: Guard): + """Guard on backend matching based on id of current_backend""" + assert guard.source is GuardSource.GLOBAL + backend_id = ( + f"{id(torch._dynamo.eval_frame.guarded_backend_cache.current_backend)}" + ) + code = [f"___check_current_backend({backend_id})"] + self._produce_guard_code(guard, code) + + def SHAPE_ENV(self, guard: Guard): + # Let's handle ShapeEnv guards. To do this, we will resolve + # shape variables to sources from tracked_fakes. This must happen after + # tensor checks. + assert guard.name == "" + output_graph = self.check_fn_manager.output_graph + # NB: self.output_graph can be None in the debug_nops tests + fs = output_graph.tracked_fakes + input_contexts = [a.symbolic_context for a in fs] + + def get_sources(t_id, dim): + # Looks up base sources mapped to a tensor id and uses them to create + # sources for the corresponding tensor dimension. + return [ + TensorPropertySource(source, TensorProperty.SIZE, dim) + for source in output_graph.tracked_fakes_id_to_source[t_id] + ] + + if output_graph.export_constraints: + from sympy import Symbol + + source_pairs: List[Tuple[Source, Source]] = [] + derived_equalities: List[ # type: ignore[type-arg] + Tuple[Source, Union[Source, Symbol], Callable] + ] = [] + phantom_symbols: Dict[str, Symbol] = {} + for constraint in output_graph.export_constraints: + if constraint.t_id in output_graph.tracked_fakes_id_to_source: + torch.export.dynamic_shapes._process_equalities( + constraint, + get_sources, + output_graph.shape_env, + source_pairs, + derived_equalities, + phantom_symbols, + ) + else: + log.warning("Untracked tensor used in export constraints") + equalities_inputs = EqualityConstraint( + source_pairs=source_pairs, + derived_equalities=derived_equalities, + phantom_symbols=list(phantom_symbols.values()), + warn_only=False, + ) + else: + equalities_inputs = None + guards = output_graph.shape_env.produce_guards( + [a.fake for a in fs], + [a.source for a in fs], + input_contexts=input_contexts, + equalities_inputs=equalities_inputs, + source_ref=self.source_ref, + # Export keeps static. + ignore_static=(not self.check_fn_manager.output_graph.export), + ) + # When exporting, we may work with the shape constraints some more in + # postprocessing, so don't freeze yet + if not self.check_fn_manager.output_graph.export: + output_graph.shape_env.freeze() + for shape_guard in guards: + self._produce_guard_code(guard, [shape_guard], shape_env=True) + + def TENSOR_MATCH(self, guard: Guard, value=None): + if guard.is_nn_module() or guard.originating_source.is_dict_key(): + self.ID_MATCH(guard) + else: + if isinstance(value, TensorWeakRef): + value = value() + + value = value if value is not None else self.get(guard.name) + assert isinstance(value, torch.Tensor) + + tensor_name = self.arg_ref(guard) + # [Note - On Export Tensor Guards] + # + # In eager mode, tensor guards are evaluated through C++, in guards.cpp + # see [Note - On Eager Tensor Guards] for more info. + # + # In export mode, we instead maintain parallel logic between C++ and python + # here, with an exception of checking the dispatch key - with the idea that a dispatch key + # is an entirely runtime notion that would make no sense to keep in an exported graph. + # + # Now, this idea is okay, but to paraphrase @ezyang, this mental model is sufficient for now, although + # not entirely true. + # For example, suppose one of the input tensors had the negative dispatch key. + # You should end up with a graph that is specialized for tensors that have a negative dispatch key. + # If you allow a Tensor that does NOT have this bit set, you will accidentally run it "as if" it were negated. + # Now, negative key only shows up for complex numbers, and most likely, the exported to target doesn't + # support this feature at all, but the point stands that :some: tensor state only shows up on dispatch key. + # TODO(voz): Either populate a dispatch_key check into the guards, or error on users passing in an unsupported + # subset of keys during export. + # + # The list of tensor fields and calls we care about can be found in `terms` below. + # TODO(voz): We are missing storage offset in all our tensor guards? + code: List[str] = list() + if self.check_fn_manager.output_graph.export: + self.TYPE_MATCH(guard) + terms = [ + "dtype", + "device", + "requires_grad", + "ndimension()", + ] + + for term in terms: + real_value = self.get(tensor_name + "." + term) + if istype(real_value, (torch.device, torch.dtype)): + # copy pasted from EQUALS_MATCH + code.append(f"str({tensor_name}.{term}) == {str(real_value)!r}") + else: + code.append(f"{tensor_name}.{term} == {real_value}") + else: + self.tensor_check_names.append(tensor_name) + self.tensor_check_examples.append(value) + self.tensor_check_guards.append(guard) + + # A frame is valid for reuse with dynamic dimensions if the new + # (user-requested) dynamic dimensions are a subset of the old + # (already compiled) dynamic dimensions. + # + # It's a little non-obvious why you'd want this: in particular, + # if an already compiled frame matches all of the guards, why + # not just use it, why force a recompile? + # + # We force it for two reasons: + # + # - The user *required* us to compile with a new dynamic dimension, + # we should not ignore that and serve up the old, specialized + # frame. Listen to the user! + # + # - In fact, we are obligated to *raise an error* if we fail to + # make the requested dimension dynamic. If we don't + # recompile, we can't tell if that dimension can actually be + # made dynamic. + # + # If the new dynamic dims are a subset of the old, we already know + # we can make them dynamic (since we made them dynamic in old). + # This is slightly unsound, because maybe your input size is + # [s0, s0, s1] and so you can do it dynamic if you say dynamic + # dims {0, 1, 2} but you can't if you only do {0, 2} (because now + # the second s0 is specialized). But we're not entirely sure if + # this is a good idea anyway lol... (if you want to try removing + # this logic, be my guest! -- ezyang 2024) + # + assert guard.source is not None + static, reason = tensor_always_has_static_shape( + value, is_tensor=True, guard_source=guard.source + ) + if not static: + if hasattr(value, "_dynamo_dynamic_indices"): + code.append( + f"(({tensor_name}._dynamo_dynamic_indices.issubset({value._dynamo_dynamic_indices})) if hasattr({tensor_name}, '_dynamo_dynamic_indices') else True)" # noqa: B950 + ) + # In the case of us not having any dynamic dimension indices, we compiled the frame with no chance of + # raising for this specific tensor - and any inputs with more dynamic user directives specified must be recompiled. + else: + code.append( + f"hasattr({tensor_name}, '_dynamo_dynamic_indices') == False" + ) + if len(code) > 0: + self._produce_guard_code(guard, code) + + # A util that appends guarded code, or, in the case of export, adds data onto guards + def _produce_guard_code( + self, guard, code_list, provided_guarded_object=None, shape_env=False + ): + # WARNING: It is important that cur_frame/caller do NOT stay in + # the current frame, because they will keep things live longer + # than they should. See TestMisc.test_release_module_memory + cur_frame = currentframe() + assert cur_frame is not None + caller = cur_frame.f_back + del cur_frame + assert caller is not None + func_name = getframeinfo(caller)[2] + del caller + # We use func_name for export, so might as well get a nice defensive check out of it + assert func_name in dir( + self.__class__ + ), f"_produce_guard_code must be called from inside GuardedCode. Called from {func_name}" + + if shape_env: + self.shape_env_code.append(GuardCodeList(code_list, guard)) + else: + self.code.append(GuardCodeList(code_list, guard)) + + # Not all guards have names, some can be installed globally (see asserts on HAS_GRAD) + if provided_guarded_object is None: + name_valid = guard.name is not None and guard.name != "" + + guarded_object = self.get(guard.name) if name_valid else None + else: + guarded_object = provided_guarded_object + + guarded_object_type = ( + weakref.ref(type(guarded_object)) if guarded_object is not None else None + ) + obj_ref = None + # Not necessary to have weakref for Enum type, but there is a bug that + # makes hasattr(guarded_object.__class__, "__weakref__") return True. + if hasattr(guarded_object.__class__, "__weakref__") and not isinstance( + guarded_object, enum.Enum + ): + obj_ref = weakref.ref(guarded_object) + + guard.set_export_info( + func_name, + guarded_object_type, + code_list, + obj_ref, + ) + + +# Common Sub-Expression Elimination for Python expressions. +# +# There are 2 steps to this pass: +# 1. Count the frequency of each sub-expression (i.e. inner +# node in the AST tree) +# +# 2. Replace those that occur more than once by a fresh variable 'v'. +# 'v' will be defined in the 'preface' list (output argument to +# 'NodeTransformer') +# +# NB: the use of 'ast.unparse' while visiting the nodes makes this pass +# quadratic on the depth of the tree. +# +# NB: this pass creates a new variable for each AST node that is repeated +# more than 'USE_THRESHOLD'. e.g. if 'a.b.c.d' is used 10 times, 'a.b.c' +# and 'a.b' are also used 10 times. So, there will be a new variable for +# each of them. +class PyExprCSEPass: + # Maximum number of times a given expression can be used without being + # replaced by a fresh variable. + USE_THRESHOLD = 1 + + # Ad-Hoc: AST nodes this pass focuses on. + ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript) + + @dataclasses.dataclass + class Config: + expr_count: Dict[str, int] + expr_to_name: Dict[str, str] + + class ExprCounter(ast.NodeVisitor): + def __init__(self, config: PyExprCSEPass.Config) -> None: + self._config = config + + def visit(self, node: ast.AST) -> Any: + if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES): + self._config.expr_count[_ast_unparse(node)] += 1 + super().visit(node) + + class Replacer(ast.NodeTransformer): + def __init__( + self, + config: PyExprCSEPass.Config, + gen_name: Callable[[], str], + ) -> None: + super().__init__() + self._config = config + self._gen_name = gen_name + self.preface: List[str] = [] + + def visit(self, node: ast.AST) -> Any: + if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES): + expr = _ast_unparse(node) + + # Replacement only occurs if a given expression is used more + # than once. + if self._config.expr_count[expr] > PyExprCSEPass.USE_THRESHOLD: + if expr not in self._config.expr_to_name: + # Parent 'visit' is called so that we CSE the inner expressions first. + # + # The resulting expression is used as right-hand-side of the variable + # assignment. i.e. we are CSE-ing the children before the parents. + # + # Indexing still uses the old 'node', since that's what was counted + # by the 'NodeVisitor'. + node_ = super().visit(node) + expr_ = _ast_unparse(node_) + var_name = self._gen_name() + self.preface.append(f"{var_name} = {expr_}") + self._config.expr_to_name[expr] = var_name + else: + var_name = self._config.expr_to_name[expr] + return ast.Name(var_name, ast.Load()) + + return super().visit(node) + + def __init__(self) -> None: + self._counter = 0 + self._config = self.Config( + expr_count=collections.defaultdict(lambda: 0), expr_to_name={} + ) + + def _new_var(self, prefix: str = "_var") -> str: + name = f"{prefix}{self._counter}" + self._counter += 1 + return name + + def count(self, exprs: List[str]) -> None: + counter = self.ExprCounter(self._config) + for e in exprs: + try: + counter.visit(ast.parse(e)) + except SyntaxError as ex: + log.exception("Failed to visit expr at line %s.\n%s", ex.lineno, e) + raise + + def replace(self, expr: str) -> Tuple[List[str], str]: + replacer = self.Replacer(self._config, self._new_var) + new_node = replacer.visit(ast.parse(expr)) + return replacer.preface, _ast_unparse(new_node) + + +def must_add_nn_module_guards(guard): + # For config.guard_nn_modules=False, we can skip all the guards that + # originate from inside of nn module except for a few categories. + return ( + # Guard for defaults + isinstance(guard.originating_source, DefaultsSource) + # Guard using dict tags if the config flag is set + or ( + config.guard_nn_modules_using_dict_tags + and guard.create_fn is GuardBuilder.NN_MODULE + ) + ) + + +class DeletedGuardFn: + pass + + +# NB: Naively, you'd expect this to only be a function that produces +# the callable that constitutes the guard. However, there is some +# delicate handling for invalidating this check function when the +# locals/globals get invalidated, so there's some extra state +# we have to hold in this manager class. +class CheckFunctionManager: + def __init__( + self, + output_graph=None, + guard_fail_fn: Optional[Callable[[GuardFail], None]] = None, + ): + guards = output_graph.guards if output_graph else None + self._weakrefs: Dict[int, ReferenceType[object]] = {} + self.output_graph = output_graph + w_builder = None + + def source_ref(source): + guard_source = source.guard_source() + if guard_source is GuardSource.CONSTANT: + # No need to track constants + return source.name() + assert w_builder + r_builder = w_builder() + assert r_builder is not None + return r_builder.arg_ref(source.name()) + + builder = GuardBuilder( + self.id_ref, + source_ref, + self.lookup_weakrefs, + output_graph.local_scope, + output_graph.global_scope, + self, + ) + + # Break retain cycle. See test_release_scope_memory + def cleanup_builder(weak_b): + b = weak_b() + if b: + b.scope = None + + # Break retain cycle. See test_release_input_memory + w_builder = weakref.ref(builder, cleanup_builder) + + for guard in sorted(guards or [], key=Guard.sort_key): + if ( + not config.guard_nn_modules + and guard.is_nn_module() + # Default func args must be guarded on. + # TODO: we could make use of 'DefaultsSource' and offer a .guard.is_defaults() API + and "__defaults__" not in guard.name + and "__kwdefaults__" not in guard.name + and (config.skip_nnmodule_hook_guards or "hooks" not in guard.name) + ): + continue + + guard.create(builder) + self.check_fn = self.compile_check_fn(builder, guards, guard_fail_fn) + # Keep track of weak references of objects with ID_MATCH guard. This + # info is stored alongside optimized_code and check_fn and is used to + # limit the number of cache entries with same ID_MATCH'd object. + # TODO(janimesh) - Currently this information is stored as an attr on + # the check_fn itself to avoid changing CacehEntry datastructure in + # eval_frame.c. In future, we should probably replace check_fn with a + # queryable data structure such that this information is already present + # in some form. + self.check_fn.id_matched_objs = builder.id_matched_objs + + # NB - We have to very careful of cleaning up here. Because of the + # invalidate function, we can create a weakref finalizer that keeps + # `self` alive for very long. Sometimes by mistake, we can run + # invalidate for a type/object (check id_ref method) that Python can + # leak by design, preventing us from calling the finalizer. In that + # case, the `self` will be alive even though the cache entry will be + # deleted (check invalidate method), which can cause a memory leak, + # e.g., not setting output_graph = None can keep hold of nn_modules. + self._weakrefs.clear() + self.output_graph = None + + def compile_check_fn(self, builder, guards_out, guard_fail_fn): + # see parallel handling of ".0" / "___implicit0" in _eval_frame.c + largs = builder.argnames + largs += ["**___kwargs_ignored"] + + guards_log.debug("GUARDS:") + + # Don't report this guard, it's always the same, useless! + code_parts = ["___check_global_state()"] + verbose_code_parts = code_parts[:] + structured_guard_fns = [] + + def add_code_part(code_part, guard, log_only=False): + verbose_code_part = get_verbose_code_part(code_part, guard) + guards_log.debug("%s", verbose_code_part) + + structured_guard_fns.append( + lambda: { + "code": code_part, + "stack": structured.from_traceback(guard.stack.summary()) + if guard.stack + else None, + "user_stack": structured.from_traceback(guard.user_stack) + if guard.user_stack + else None, + } + ) + + if verbose_guards_log.isEnabledFor(logging.DEBUG): + maybe_stack = "" + maybe_user_stack = "" + if guard is not None: + if guard.stack: + maybe_stack = f"\nStack:\n{''.join(guard.stack.format())}" + if guard.user_stack: + maybe_user_stack = ( + f"\nUser stack:\n{''.join(guard.user_stack.format())}" + ) + verbose_guards_log.debug( + "Guard: %s%s%s", + code_part, + maybe_stack, + maybe_user_stack, + ) + + if not log_only: + code_parts.append(code_part) + verbose_code_parts.append(verbose_code_part) + + seen = set() + for gcl in builder.code: + for code in gcl.code_list: + if code not in seen: + add_code_part(code, gcl.guard) + seen.add(code) + + tensor_check_names = builder.tensor_check_names + check_tensors_fn = None + check_tensors_verbose_fn = None + if tensor_check_names: + assert ( + not self.output_graph.export + ), "Illegal to set tensor_check_names in export." + tensor_check_examples = builder.tensor_check_examples + + dynamic_dims_sizes = [ + convert_to_concrete_values( + self.output_graph.tensor_weakref_to_sizes_strides[t]["size"] + ) + for t in tensor_check_examples + ] + + dynamic_dims_strides = [ + convert_to_concrete_values( + self.output_graph.tensor_weakref_to_sizes_strides[t]["stride"] + ) + for t in tensor_check_examples + ] + + tensor_guards = TensorGuards( + *tensor_check_examples, + dynamic_dims_sizes=dynamic_dims_sizes, + dynamic_dims_strides=dynamic_dims_strides, + ) + check_tensors_fn = tensor_guards.check + check_tensors_verbose_fn = tensor_guards.check_verbose + tensor_check_args = ", ".join( + tensor_check_names + ["tensor_check_names=tensor_check_names"] + ) + # Do this manually, to un-stagger the guards in log message + code_parts.append(f"___check_tensors({tensor_check_args})") + verbose_code_parts.append(f"___check_tensors({tensor_check_args})") + tensor_check_guards = builder.tensor_check_guards + + for i, name in enumerate(tensor_check_names): + # This is a copy of what guards.cpp checks against + # Keep this in sync with TensorCheck constructor + t = tensor_check_examples[i] + sizes = dynamic_dims_sizes[i] + strides = dynamic_dims_strides[i] + code_part = get_tensor_guard_code_part(t, name, sizes, strides) + add_code_part(code_part, tensor_check_guards[i], log_only=True) + + aotautograd_guards: List[GuardEnvExpr] = ( + self.output_graph.tracing_context.guards_context.aotautograd_guards + if self.output_graph + else [] + ) + for guard in aotautograd_guards: + if isinstance(guard, DuplicateInputs): + source_a = guard.input_source_a + source_b = guard.input_source_b + add_code_part(f"{source_a.name()} is {source_b.name()}", None) + else: + raise RuntimeError(f"Unknown GuardEnvExpr: {guard}") + + # TODO: the "guard" here is actually just the top level SHAPE_ENV + # which is useless. Get ShapeEnv to pass in more provenance. + for gcl in builder.shape_env_code: + for code in gcl.code_list: + add_code_part(code, gcl.guard) + + # OK, all done generating guards + torch._logging.trace_structured( + "dynamo_guards", payload_fn=lambda: [f() for f in structured_guard_fns] + ) + + global_state = convert_frame.initial_global_state + if global_state is None: + # we should only hit this case in NopTests() + global_state = convert_frame.GlobalStateGuard() + closure_vars = { + "___check_tensors": check_tensors_fn, + "___check_tensors_verbose": check_tensors_verbose_fn, + "___check_global_state": global_state.check, + "___check_current_backend": torch._dynamo.eval_frame.check_current_backend, + "tensor_check_names": tensor_check_names, + **SYMPY_INTERP, + **CLOSURE_VARS, + } + + unique_code_parts = list(unique(code_parts)) + make_guard_fn_args = ", ".join(closure_vars.keys()) + guard_body, pycode = build_guard_function(unique_code_parts, make_guard_fn_args) + + if os.environ.get("TORCHDYNAMO_PRINT_GUARDS", None) == "1": + print("GUARDS\n", guard_body) + + out: Dict[str, Any] = dict() + + # We don't put builder.scope as the globals in exec call because + # guard_fn.__globals__ becomes equal to builder.scope. This causes + # guard_fn to hold a referece to f_locals sitting in builder.scope["L"] + globals_for_guard_fn = {"G": builder.scope["G"]} + try: + exec(pycode, globals_for_guard_fn, out) + except SyntaxError as ex: + log.exception("Failed to exec guard at line %s.\n%s", ex.lineno, pycode) + raise + guard_fn = out["___make_guard_fn"](*closure_vars.values()) + guard_fn.closure_vars = closure_vars + # TODO(whc) maybe '.code_parts' was only kept around for the guard callback? so we don't need both + guard_fn.args = largs + guard_fn.code_parts = code_parts + guard_fn.verbose_code_parts = verbose_code_parts + # Grab only G, but preserve "G" because guards access it as "G" + guard_fn.global_scope = globals_for_guard_fn + guard_fn.guard_fail_fn = guard_fail_fn + # will be populated by a non-owning reference to CacheEntry/ExtraState + # when the CacheEntry is constructed + guard_fn.cache_entry = None + guard_fn.extra_state = None + return guard_fn + + def invalidate(self): + # Some tests reveal that CheckFunctionManager has no attribute + # check_fn, but this case should not be of any concern. + # This case doesn't seem easy to repro. + if ( + hasattr(self, "check_fn") + and self.check_fn is not DeletedGuardFn + and (cache_entry := self.check_fn.cache_entry) is not None + and (extra_state := self.check_fn.extra_state) is not None + ): + assert isinstance(cache_entry, CacheEntry) + assert isinstance(extra_state, ExtraState) + extra_state.invalidate(cache_entry) + self.check_fn.cache_entry = None + self.check_fn.extra_state = None + self.check_fn = DeletedGuardFn + + def id_ref(self, obj): + """add a weakref, return the id""" + try: + if id(obj) not in self._weakrefs: + # We will clear the _weakrefs dict at the end of __init__ + # function, which will delete the callbacks as well. Therefore, + # we are using a finalizer which is kept alive. + self._weakrefs[id(obj)] = weakref.ref(obj) + weakref.finalize(obj, self.invalidate) + except TypeError: + pass # cannot weakref bool object + return id(obj) + + def lookup_weakrefs(self, obj): + """Lookup the _weakrefs created in id_ref function for ID_MATCH'd objects""" + if id(obj) in self._weakrefs: + return self._weakrefs[id(obj)] + return None + + +def build_guard_function(code_parts, closure_args) -> Tuple[str, str]: + from torch._inductor.utils import IndentedBuffer + + if HAS_UNPARSE_FUNCTIONS: + csepass = PyExprCSEPass() + csepass.count(code_parts) + + def replace(expr: str) -> Tuple[List[str], str]: + return csepass.replace(expr) + + else: + + def replace(expr: str) -> Tuple[List[str], str]: + return [], expr + + # Generate the inner body of the guard function. + # i.e. if-chain of the guard expressions. + guard_body = IndentedBuffer() + for expr in code_parts: + preface, expr = replace(expr) + guard_body.writelines(preface) + guard_body.writeline(f"if not ({expr}):") + with guard_body.indent(): + guard_body.writeline("return False") + + # Wrap the inner body into the actual guard function. + guard = IndentedBuffer() + guard.writeline("def guard(L):") + with guard.indent(): + guard.splice(guard_body) + guard.writeline("return True") + + # Wrap the whole guard function into another function + # with the closure variables. + make_guard_fn = IndentedBuffer() + make_guard_fn.writeline(f"def ___make_guard_fn({closure_args}):") + with make_guard_fn.indent(): + make_guard_fn.splice(guard) + make_guard_fn.writeline("return guard") + + return guard_body.getvalue(), make_guard_fn.getvalue() + + +def is_recompiles_enabled(): + return torch._logging._internal.log_state.is_artifact_enabled("recompiles") + + +def is_recompiles_verbose_enabled(): + return torch._logging._internal.log_state.is_artifact_enabled("recompiles_verbose") + + +def get_guard_fail_reason( + guard_fn: GuardFn, + code: types.CodeType, + f_locals: Dict[str, object], +) -> str: + """ + Return the reason why `guard_fn` failed. + Updates `guard_failures` with the generated reason. + Only the first failed check of guard_fn is reported. + """ + scope = {"L": f_locals, "G": guard_fn.global_scope["G"]} + scope.update(guard_fn.closure_vars) + scope["___check_tensors"] = scope["___check_tensors_verbose"] + reasons: List[str] = [] + for part in guard_fn.verbose_code_parts: + global_scope = dict(guard_fn.global_scope) + global_scope["__compile_source__"] = part + with report_compile_source_on_error(): + try: + fail_reason = eval(part, global_scope, scope) + except Exception as e: + if is_recompiles_verbose_enabled(): + continue + else: + raise + # Only ___check_tensors knows how to return a fancy fail reason; + # for everything else we just report the code that failed + + if isinstance(fail_reason, bool) and not fail_reason: + fail_reason = part + if isinstance(fail_reason, str): + reasons.append(fail_reason) + if not is_recompiles_verbose_enabled(): + break + + reason_str = "\n".join(reasons) + guard_failures[orig_code_map[code]].append(reason_str) + + try: + if guard_fn.guard_fail_fn is not None: + guard_fn.guard_fail_fn( + GuardFail(reason_str or "unknown reason", orig_code_map[code]) + ) + except Exception as e: + log.exception( + "Failure in guard_fail_fn callback - raising here will cause a NULL Error on guard eval", + ) + + return reason_str + + +def get_and_maybe_log_recompilation_reason( + cache_entry, frame: types.FrameType +) -> List[str]: + """ + Return the list of guard failure reasons using cache_entry. + Logs the recompilation reason if `recompiles` logging is enabled. + Raises a RecompileError if `config.error_on_recompile` is enabled. + """ + reasons = [] + while cache_entry is not None: + reason = get_guard_fail_reason( + cache_entry.check_fn, cache_entry.code, frame.f_locals + ) + if reason: + reasons.append(reason) + cache_entry = cache_entry.next + + code = frame.f_code + + # at least one of "recompiles" or "recompiles_verbose" is enabled + do_recompiles_log = is_recompiles_enabled() or is_recompiles_verbose_enabled() + + if do_recompiles_log or config.error_on_recompile: + if is_recompiles_verbose_enabled(): + failures = "\n\n".join( + f"guard {i} failures:\n" + textwrap.indent(reason, "- ") + for i, reason in enumerate(reasons) + ) + else: + failures = textwrap.indent("\n".join(reasons), "- ") + guard_failure_details = ( + f"triggered by the following guard failure(s):\n{failures}" + ) + message = ( + f"Recompiling function {code.co_name} in {code.co_filename}:{code.co_firstlineno}\n" + f"{textwrap.indent(guard_failure_details, ' ')}" + ) + if do_recompiles_log: + if is_recompiles_verbose_enabled(): + recompiles_verbose_log.debug(message) + else: + recompiles_log.debug(message) + if config.error_on_recompile: + raise exc.RecompileError(message) + + return reasons + + +def guard_error_hook( + guard_fn: GuardFn, + code: types.CodeType, + f_locals: Dict[str, object], + index: int, + last: bool, +): + print( + f"ERROR RUNNING GUARDS {code.co_name} {code.co_filename}:{code.co_firstlineno}" + ) + print("lambda " + ", ".join(guard_fn.args) + ":") + print(" ", " and\n ".join(guard_fn.code_parts)) + local_scope = {"L": f_locals, **guard_fn.closure_vars} + for guard in guard_fn.code_parts: + try: + eval(guard, guard_fn.global_scope, local_scope) + except: # noqa: B001,E722 + print(f"Malformed guard:\n{guard}") + + +set_guard_error_hook(guard_error_hook) + + +def unique(seq): + seen = set() + for x in seq: + if x not in seen: + yield x + seen.add(x) + + +def make_dupe_guard(obj_source, dupe_source): + # Note - we may end up in a situation where we invoke something like + # def fn(x, y) + # with fn(x, x) + # Prior to the addition of tracking to all relevant objects, we would handle this just fine by + # eagerly re-entering VB and rewrapping inputs, correctly creating graphargs and placeholders. However, + # with tracking on inputs, duplicate inputs or aliased relationships may end up getting erased here - + # In the fn(x, x) example call above look like a graph with a single input. + # In order to ensure that we do not reuse fn(x, x) for fn(x, y), we create a duplicate input guard. + + # Note - we may not have a source, that is fine, it just means we had an object that is safe to have + # leave unsourced - like a local list created and discharged entirely within a local scope. + if dupe_source and dupe_source != obj_source: + ser_source_is_local = is_from_local_source(dupe_source) + source_is_local = is_from_local_source(obj_source) + # Note - both must be local, or global, or we will run afoul of a lack of merging in how we currently + # reconcile guards builder scopes in compile_check_fn. This technically means we miss a guard here, + # so maybe we should do this refactor before we land this... + # TODO(voz): Combine local and global guard builders. + if ser_source_is_local == source_is_local: + # Note - this is a little aggressive - these being duplicate input does not always matter. + # However, this should always be a sound guard to add here. + return functools.partial(GuardBuilder.DUPLICATE_INPUT, source_b=dupe_source) + return None + + +def install_guard(*guards, skip=0): + """ + Add dynamo guards to the current tracing context. + + Args: + guards: guard(s) to add + skip: number of stack frames to ignore for debug stack trace + """ + from torch._guards import TracingContext + + collect_debug_stack = guards_log.isEnabledFor( + logging.DEBUG + ) or verbose_guards_log.isEnabledFor(logging.DEBUG) + add = TracingContext.get().guards_context.dynamo_guards.add + for guard in guards: + assert isinstance(guard, Guard) + add(guard, collect_debug_stack=collect_debug_stack, skip=skip + 1) diff --git a/shared/package-files/56/564d6cca251b3adad0ba10b91ca657e113d82ad7406f2a53b17f9f668c7c1ad7/api_pb2.pyi b/shared/package-files/56/564d6cca251b3adad0ba10b91ca657e113d82ad7406f2a53b17f9f668c7c1ad7/api_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5bc4de797a4407701148a316c5c054b5b666428c --- /dev/null +++ b/shared/package-files/56/564d6cca251b3adad0ba10b91ca657e113d82ad7406f2a53b17f9f668c7c1ad7/api_pb2.pyi @@ -0,0 +1,114 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" +from google.protobuf.descriptor import ( + Descriptor as google___protobuf___descriptor___Descriptor, + FileDescriptor as google___protobuf___descriptor___FileDescriptor, +) + +from google.protobuf.internal.containers import ( + RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer, +) + +from google.protobuf.message import ( + Message as google___protobuf___message___Message, +) + +from google.protobuf.source_context_pb2 import ( + SourceContext as google___protobuf___source_context_pb2___SourceContext, +) + +from google.protobuf.type_pb2 import ( + Option as google___protobuf___type_pb2___Option, + SyntaxValue as google___protobuf___type_pb2___SyntaxValue, +) + +from typing import ( + Iterable as typing___Iterable, + Optional as typing___Optional, + Text as typing___Text, +) + +from typing_extensions import ( + Literal as typing_extensions___Literal, +) + + +builtin___bool = bool +builtin___bytes = bytes +builtin___float = float +builtin___int = int + + +DESCRIPTOR: google___protobuf___descriptor___FileDescriptor = ... + +class Api(google___protobuf___message___Message): + DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... + name: typing___Text = ... + version: typing___Text = ... + syntax: google___protobuf___type_pb2___SyntaxValue = ... + + @property + def methods(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___Method]: ... + + @property + def options(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[google___protobuf___type_pb2___Option]: ... + + @property + def source_context(self) -> google___protobuf___source_context_pb2___SourceContext: ... + + @property + def mixins(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___Mixin]: ... + + def __init__(self, + *, + name : typing___Optional[typing___Text] = None, + methods : typing___Optional[typing___Iterable[type___Method]] = None, + options : typing___Optional[typing___Iterable[google___protobuf___type_pb2___Option]] = None, + version : typing___Optional[typing___Text] = None, + source_context : typing___Optional[google___protobuf___source_context_pb2___SourceContext] = None, + mixins : typing___Optional[typing___Iterable[type___Mixin]] = None, + syntax : typing___Optional[google___protobuf___type_pb2___SyntaxValue] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"source_context",b"source_context"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"methods",b"methods",u"mixins",b"mixins",u"name",b"name",u"options",b"options",u"source_context",b"source_context",u"syntax",b"syntax",u"version",b"version"]) -> None: ... +type___Api = Api + +class Method(google___protobuf___message___Message): + DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... + name: typing___Text = ... + request_type_url: typing___Text = ... + request_streaming: builtin___bool = ... + response_type_url: typing___Text = ... + response_streaming: builtin___bool = ... + syntax: google___protobuf___type_pb2___SyntaxValue = ... + + @property + def options(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[google___protobuf___type_pb2___Option]: ... + + def __init__(self, + *, + name : typing___Optional[typing___Text] = None, + request_type_url : typing___Optional[typing___Text] = None, + request_streaming : typing___Optional[builtin___bool] = None, + response_type_url : typing___Optional[typing___Text] = None, + response_streaming : typing___Optional[builtin___bool] = None, + options : typing___Optional[typing___Iterable[google___protobuf___type_pb2___Option]] = None, + syntax : typing___Optional[google___protobuf___type_pb2___SyntaxValue] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"name",b"name",u"options",b"options",u"request_streaming",b"request_streaming",u"request_type_url",b"request_type_url",u"response_streaming",b"response_streaming",u"response_type_url",b"response_type_url",u"syntax",b"syntax"]) -> None: ... +type___Method = Method + +class Mixin(google___protobuf___message___Message): + DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... + name: typing___Text = ... + root: typing___Text = ... + + def __init__(self, + *, + name : typing___Optional[typing___Text] = None, + root : typing___Optional[typing___Text] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"name",b"name",u"root",b"root"]) -> None: ... +type___Mixin = Mixin diff --git a/shared/package-files/56/564f153bbe095146991ef7a3be45890519e693ece9987c2392c3026680435837/svhn.py b/shared/package-files/56/564f153bbe095146991ef7a3be45890519e693ece9987c2392c3026680435837/svhn.py new file mode 100644 index 0000000000000000000000000000000000000000..5d20d7db7e3ccc1d77c5949830cf7b610d88355f --- /dev/null +++ b/shared/package-files/56/564f153bbe095146991ef7a3be45890519e693ece9987c2392c3026680435837/svhn.py @@ -0,0 +1,130 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Tuple, Union + +import numpy as np +from PIL import Image + +from .utils import check_integrity, download_url, verify_str_arg +from .vision import VisionDataset + + +class SVHN(VisionDataset): + """`SVHN `_ Dataset. + Note: The SVHN dataset assigns the label `10` to the digit `0`. However, in this Dataset, + we assign the label `0` to the digit `0` to be compatible with PyTorch loss functions which + expect the class labels to be in the range `[0, C-1]` + + .. warning:: + + This class needs `scipy `_ to load data from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset where the data is stored. + split (string): One of {'train', 'test', 'extra'}. + Accordingly dataset is selected. 'extra' is Extra training set. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + split_list = { + "train": [ + "http://ufldl.stanford.edu/housenumbers/train_32x32.mat", + "train_32x32.mat", + "e26dedcc434d2e4c54c9b2d4a06d8373", + ], + "test": [ + "http://ufldl.stanford.edu/housenumbers/test_32x32.mat", + "test_32x32.mat", + "eb5a983be6a315427106f1b164d9cef3", + ], + "extra": [ + "http://ufldl.stanford.edu/housenumbers/extra_32x32.mat", + "extra_32x32.mat", + "a93ce644f1a588dc4d68dda5feec44a7", + ], + } + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.split = verify_str_arg(split, "split", tuple(self.split_list.keys())) + self.url = self.split_list[split][0] + self.filename = self.split_list[split][1] + self.file_md5 = self.split_list[split][2] + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + # import here rather than at top of file because this is + # an optional dependency for torchvision + import scipy.io as sio + + # reading(loading) mat file as array + loaded_mat = sio.loadmat(os.path.join(self.root, self.filename)) + + self.data = loaded_mat["X"] + # loading from the .mat file gives an np.ndarray of type np.uint8 + # converting to np.int64, so that we have a LongTensor after + # the conversion from the numpy array + # the squeeze is needed to obtain a 1D tensor + self.labels = loaded_mat["y"].astype(np.int64).squeeze() + + # the svhn dataset assigns the class label "10" to the digit 0 + # this makes it inconsistent with several loss functions + # which expect the class labels to be in the range [0, C-1] + np.place(self.labels, self.labels == 10, 0) + self.data = np.transpose(self.data, (3, 2, 0, 1)) + + def __getitem__(self, index: int) -> Tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.labels[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = Image.fromarray(np.transpose(img, (1, 2, 0))) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + def _check_integrity(self) -> bool: + root = self.root + md5 = self.split_list[self.split][2] + fpath = os.path.join(root, self.filename) + return check_integrity(fpath, md5) + + def download(self) -> None: + md5 = self.split_list[self.split][2] + download_url(self.url, self.root, self.filename, md5) + + def extra_repr(self) -> str: + return "Split: {split}".format(**self.__dict__) diff --git a/shared/package-files/56/5652bcc2d84bb33915968e96a2b1f17c53beb242a11ed79abd839a80779d0821/test_array_arg.py b/shared/package-files/56/5652bcc2d84bb33915968e96a2b1f17c53beb242a11ed79abd839a80779d0821/test_array_arg.py new file mode 100644 index 0000000000000000000000000000000000000000..cb48dae2c536a7b1e2568244bf2058ce934238f0 --- /dev/null +++ b/shared/package-files/56/5652bcc2d84bb33915968e96a2b1f17c53beb242a11ed79abd839a80779d0821/test_array_arg.py @@ -0,0 +1,51 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit, types +import numpy as np +from numba.tests.gdb_support import GdbMIDriver +from numba.tests.support import TestCase, needs_subprocess +import unittest + + +@needs_subprocess +class Test(TestCase): + + def test(self): + @njit(debug=True) + def foo(x): + z = np.ones_like(x) # break here + return x, z + + tmp = np.ones(5) + foo(tmp) + + driver = GdbMIDriver(__file__) + driver.set_breakpoint(line=15) + driver.run() + driver.check_hit_breakpoint(1) + driver.stack_list_arguments(2) + llvm_intp = f"i{types.intp.bitwidth}" + expect = ( + '[frame={level="0",args=[{name="x",type="array(float64, 1d, C) ' + f'({{i8*, i8*, {llvm_intp}, {llvm_intp}, double*, ' + f'[1 x {llvm_intp}], [1 x {llvm_intp}]}})"}}]}}]' + ) + driver.assert_output(expect) + driver.stack_list_variables(1) + # 'z' should be zero-init + expect = ('{name="z",value="{meminfo = 0x0, parent = 0x0, nitems = 0, ' + 'itemsize = 0, data = 0x0, shape = {0}, strides = {0}}"}') + driver.assert_output(expect) + driver.set_breakpoint(line=16) + driver.cont() + driver.check_hit_breakpoint(2) + driver.stack_list_variables(1) + # 'z' should be populated + expect = (r'^.*\{name="z",value="\{meminfo = 0x[0-9a-f]+ .*, ' + r'parent = 0x0, nitems = 5, itemsize = 8, ' + r'data = 0x[0-9a-f]+, shape = \{5\}, strides = \{8\}\}.*$') + driver.assert_regex_output(expect) + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/56/565454d155b79ca728b997f7ca4b7c23e8ad2bd520ed89561831c99d8b95b438/scatter_reduce_meta.h b/shared/package-files/56/565454d155b79ca728b997f7ca4b7c23e8ad2bd520ed89561831c99d8b95b438/scatter_reduce_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..1176edc2208a7ef30b2265f30f8e60a194fdc232 --- /dev/null +++ b/shared/package-files/56/565454d155b79ca728b997f7ca4b7c23e8ad2bd520ed89561831c99d8b95b438/scatter_reduce_meta.h @@ -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_scatter_reduce_two : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/56/56549f6a15910c6ee83b2922aefd8b06bbe24d0c739afb966802d06cf10023b5/qansi b/shared/package-files/56/56549f6a15910c6ee83b2922aefd8b06bbe24d0c739afb966802d06cf10023b5/qansi new file mode 100644 index 0000000000000000000000000000000000000000..633429959ef4371a2ff58d482b244e9c4f832e9f Binary files /dev/null and b/shared/package-files/56/56549f6a15910c6ee83b2922aefd8b06bbe24d0c739afb966802d06cf10023b5/qansi differ diff --git a/shared/package-files/56/5659af72d45a42d8ee62f42ea1edaddae7e26fbe13b9affbaac895aecde3fa9d/test_utils.py b/shared/package-files/56/5659af72d45a42d8ee62f42ea1edaddae7e26fbe13b9affbaac895aecde3fa9d/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb62e2223d515288bd5aa6c5a70028279c4f6d30 --- /dev/null +++ b/shared/package-files/56/5659af72d45a42d8ee62f42ea1edaddae7e26fbe13b9affbaac895aecde3fa9d/test_utils.py @@ -0,0 +1,9 @@ +import numpy as np +from pytest import raises as assert_raises + +import scipy.sparse.linalg._isolve.utils as utils + + +def test_make_system_bad_shape(): + assert_raises(ValueError, + utils.make_system, np.zeros((5,3)), None, np.zeros(4), np.zeros(4)) diff --git a/shared/package-files/56/565b18e09c1951c905e6ec43ad596b2510559ef4e6bae6a3774877ec13246cea/test_parquet_file.py b/shared/package-files/56/565b18e09c1951c905e6ec43ad596b2510559ef4e6bae6a3774877ec13246cea/test_parquet_file.py new file mode 100644 index 0000000000000000000000000000000000000000..a62b5c3298c9ceb95e9fd62a462828f8a7155843 --- /dev/null +++ b/shared/package-files/56/565b18e09c1951c905e6ec43ad596b2510559ef4e6bae6a3774877ec13246cea/test_parquet_file.py @@ -0,0 +1,447 @@ +# 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 +import os +import re +import sys +import types + +import pytest +from unittest import mock + +import pyarrow as pa + +try: + import pyarrow.parquet as pq + from pyarrow.tests.parquet.common import _write_table +except ImportError: + pq = None + +try: + import pandas as pd + import pandas.testing as tm + + from pyarrow.tests.parquet.common import alltypes_sample +except ImportError: + pd = tm = None + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet' +pytestmark = pytest.mark.parquet + + +@pytest.mark.pandas +def test_pass_separate_metadata(): + # ARROW-471 + df = alltypes_sample(size=10000) + + a_table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(a_table, buf, compression='snappy', version='2.6') + + buf.seek(0) + metadata = pq.read_metadata(buf) + + buf.seek(0) + + fileh = pq.ParquetFile(buf, metadata=metadata) + + tm.assert_frame_equal(df, fileh.read().to_pandas()) + + +@pytest.mark.pandas +def test_read_single_row_group(): + # ARROW-471 + N, K = 10000, 4 + df = alltypes_sample(size=N) + + a_table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(a_table, buf, row_group_size=N / K, + compression='snappy', version='2.6') + + buf.seek(0) + + pf = pq.ParquetFile(buf) + + assert pf.num_row_groups == K + + row_groups = [pf.read_row_group(i) for i in range(K)] + result = pa.concat_tables(row_groups) + tm.assert_frame_equal(df, result.to_pandas()) + + +@pytest.mark.pandas +def test_read_single_row_group_with_column_subset(): + N, K = 10000, 4 + df = alltypes_sample(size=N) + a_table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(a_table, buf, row_group_size=N / K, + compression='snappy', version='2.6') + + buf.seek(0) + pf = pq.ParquetFile(buf) + + cols = list(df.columns[:2]) + row_groups = [pf.read_row_group(i, columns=cols) for i in range(K)] + result = pa.concat_tables(row_groups) + tm.assert_frame_equal(df[cols], result.to_pandas()) + + # ARROW-4267: Selection of duplicate columns still leads to these columns + # being read uniquely. + row_groups = [pf.read_row_group(i, columns=cols + cols) for i in range(K)] + result = pa.concat_tables(row_groups) + tm.assert_frame_equal(df[cols], result.to_pandas()) + + +@pytest.mark.pandas +def test_read_multiple_row_groups(): + N, K = 10000, 4 + df = alltypes_sample(size=N) + + a_table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(a_table, buf, row_group_size=N / K, + compression='snappy', version='2.6') + + buf.seek(0) + + pf = pq.ParquetFile(buf) + + assert pf.num_row_groups == K + + result = pf.read_row_groups(range(K)) + tm.assert_frame_equal(df, result.to_pandas()) + + +@pytest.mark.pandas +def test_read_multiple_row_groups_with_column_subset(): + N, K = 10000, 4 + df = alltypes_sample(size=N) + a_table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(a_table, buf, row_group_size=N / K, + compression='snappy', version='2.6') + + buf.seek(0) + pf = pq.ParquetFile(buf) + + cols = list(df.columns[:2]) + result = pf.read_row_groups(range(K), columns=cols) + tm.assert_frame_equal(df[cols], result.to_pandas()) + + # ARROW-4267: Selection of duplicate columns still leads to these columns + # being read uniquely. + result = pf.read_row_groups(range(K), columns=cols + cols) + tm.assert_frame_equal(df[cols], result.to_pandas()) + + +@pytest.mark.pandas +def test_scan_contents(): + N, K = 10000, 4 + df = alltypes_sample(size=N) + a_table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(a_table, buf, row_group_size=N / K, + compression='snappy', version='2.6') + + buf.seek(0) + pf = pq.ParquetFile(buf) + + assert pf.scan_contents() == 10000 + assert pf.scan_contents(df.columns[:4]) == 10000 + + +def test_parquet_file_pass_directory_instead_of_file(tempdir): + # ARROW-7208 + path = tempdir / 'directory' + os.mkdir(str(path)) + + msg = f"Cannot open for reading: path '{str(path)}' is a directory" + with pytest.raises(IOError) as exc: + pq.ParquetFile(path) + if exc.errisinstance(PermissionError) and sys.platform == 'win32': + return # Windows CI can get a PermissionError here. + exc.match(msg) + + +def test_read_column_invalid_index(): + table = pa.table([pa.array([4, 5]), pa.array(["foo", "bar"])], + names=['ints', 'strs']) + bio = pa.BufferOutputStream() + pq.write_table(table, bio) + f = pq.ParquetFile(bio.getvalue()) + assert f.reader.read_column(0).to_pylist() == [4, 5] + assert f.reader.read_column(1).to_pylist() == ["foo", "bar"] + for index in (-1, 2): + with pytest.raises((ValueError, IndexError)): + f.reader.read_column(index) + + +@pytest.mark.pandas +@pytest.mark.parametrize('batch_size', [300, 1000, 1300]) +def test_iter_batches_columns_reader(tempdir, batch_size): + total_size = 3000 + chunk_size = 1000 + # TODO: Add categorical support + df = alltypes_sample(size=total_size) + + filename = tempdir / 'pandas_roundtrip.parquet' + arrow_table = pa.Table.from_pandas(df) + _write_table(arrow_table, filename, version='2.6', + chunk_size=chunk_size) + + file_ = pq.ParquetFile(filename) + for columns in [df.columns[:10], df.columns[10:]]: + batches = file_.iter_batches(batch_size=batch_size, columns=columns) + batch_starts = range(0, total_size+batch_size, batch_size) + for batch, start in zip(batches, batch_starts): + end = min(total_size, start + batch_size) + tm.assert_frame_equal( + batch.to_pandas(), + df.iloc[start:end, :].loc[:, columns].reset_index(drop=True) + ) + + +@pytest.mark.pandas +@pytest.mark.parametrize('chunk_size', [1000]) +def test_iter_batches_reader(tempdir, chunk_size): + df = alltypes_sample(size=10000, categorical=True) + + filename = tempdir / 'pandas_roundtrip.parquet' + arrow_table = pa.Table.from_pandas(df) + assert arrow_table.schema.pandas_metadata is not None + + _write_table(arrow_table, filename, version='2.6', + chunk_size=chunk_size) + + file_ = pq.ParquetFile(filename) + + def get_all_batches(f): + for row_group in range(f.num_row_groups): + batches = f.iter_batches( + batch_size=900, + row_groups=[row_group], + ) + + for batch in batches: + yield batch + + batches = list(get_all_batches(file_)) + batch_no = 0 + + for i in range(file_.num_row_groups): + tm.assert_frame_equal( + batches[batch_no].to_pandas(), + file_.read_row_groups([i]).to_pandas().head(900) + ) + + batch_no += 1 + + tm.assert_frame_equal( + batches[batch_no].to_pandas().reset_index(drop=True), + file_.read_row_groups([i]).to_pandas().iloc[900:].reset_index( + drop=True + ) + ) + + batch_no += 1 + + +@pytest.mark.pandas +@pytest.mark.parametrize('pre_buffer', [False, True]) +def test_pre_buffer(pre_buffer): + N, K = 10000, 4 + df = alltypes_sample(size=N) + a_table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(a_table, buf, row_group_size=N / K, + compression='snappy', version='2.6') + + buf.seek(0) + pf = pq.ParquetFile(buf, pre_buffer=pre_buffer) + assert pf.read().num_rows == N + + +def test_parquet_file_explicitly_closed(tempdir): + """ + Unopened files should be closed explicitly after use, + and previously opened files should be left open. + Applies to read_table, ParquetDataset, and ParquetFile + """ + # create test parquet file + fn = tempdir.joinpath('file.parquet') + table = pa.table({'col1': [0, 1], 'col2': [0, 1]}) + pq.write_table(table, fn) + + # ParquetFile with opened file (will leave open) + with open(fn, 'rb') as f: + with pq.ParquetFile(f) as p: + p.read() + assert not f.closed + assert not p.closed + assert not f.closed # opened input file was not closed + assert not p.closed # parquet file obj reports as not closed + assert f.closed + assert p.closed # parquet file being closed reflects underlying file + + # ParquetFile with unopened file (will close) + with pq.ParquetFile(fn) as p: + p.read() + assert not p.closed + assert p.closed # parquet file obj reports as closed + + +@pytest.mark.s3 +@pytest.mark.parametrize("use_uri", (True, False)) +def test_parquet_file_with_filesystem(s3_example_fs, use_uri): + s3_fs, s3_uri, s3_path = s3_example_fs + + args = (s3_uri if use_uri else s3_path,) + kwargs = {} if use_uri else dict(filesystem=s3_fs) + + table = pa.table({"a": range(10)}) + pq.write_table(table, s3_path, filesystem=s3_fs) + + parquet_file = pq.ParquetFile(*args, **kwargs) + assert parquet_file.read() == table + assert not parquet_file.closed + parquet_file.close() + assert parquet_file.closed + + with pq.ParquetFile(*args, **kwargs) as f: + assert f.read() == table + assert not f.closed + assert f.closed + + +def test_read_statistics(): + table = pa.table({"value": pa.array([-1, None, 3])}) + buf = io.BytesIO() + _write_table(table, buf) + buf.seek(0) + + statistics = pq.ParquetFile(buf).read().columns[0].chunks[0].statistics + assert statistics.is_null_count_exact is True + assert statistics.null_count == 1 + assert statistics.distinct_count is None + # TODO: add tests for is_distinct_count_exact == None and True + # once Python API allows + assert statistics.is_distinct_count_exact is False + assert statistics.min == -1 + assert statistics.is_min_exact + assert statistics.max == 3 + assert statistics.is_max_exact + assert repr(statistics) == ("arrow.ArrayStatistics<" + "null_count=1, distinct_count=None, " + "min=-1, is_min_exact=True, " + "max=3, is_max_exact=True>") + + +def test_read_undefined_logical_type(parquet_test_datadir): + test_file = f"{parquet_test_datadir}/unknown-logical-type.parquet" + + table = pq.ParquetFile(test_file).read() + assert table.column_names == ["column with known type", "column with unknown type"] + assert table["column with unknown type"].to_pylist() == [ + b"unknown string 1", + b"unknown string 2", + b"unknown string 3" + ] + + +def test_parquet_file_fsspec_support(): + pytest.importorskip("fsspec") + + table = pa.table({"a": range(10)}) + pq.write_table(table, "fsspec+memory://example.parquet") + table2 = pq.read_table("fsspec+memory://example.parquet") + assert table.equals(table2) + + msg = "Unrecognized filesystem type in URI" + with pytest.raises(pa.ArrowInvalid, match=msg): + pq.read_table("non-existing://example.parquet") + + +def test_parquet_file_fsspec_support_through_filesystem_argument(): + try: + from fsspec.implementations.memory import MemoryFileSystem + except ImportError: + pytest.skip("fsspec is not installed, skipping test") + + table = pa.table({"b": range(10)}) + + fs = MemoryFileSystem() + fs.mkdir("/path/to/prefix", create_parents=True) + assert fs.exists("/path/to/prefix") + + fs_str = "fsspec+memory://path/to/prefix" + pq.write_table(table, "b.parquet", filesystem=fs_str) + table2 = pq.read_table("fsspec+memory://path/to/prefix/b.parquet") + assert table.equals(table2) + + +def test_parquet_file_hugginface_support(): + try: + from fsspec.implementations.memory import MemoryFileSystem + except ImportError: + pytest.skip("fsspec is not installed, skipping Hugging Face test") + + fake_hf_module = types.ModuleType("huggingface_hub") + fake_hf_module.HfFileSystem = MemoryFileSystem + with mock.patch.dict("sys.modules", {"huggingface_hub": fake_hf_module}): + uri = "hf://datasets/apache/arrow/test.parquet" + table = pa.table({"a": range(10)}) + pq.write_table(table, uri) + table2 = pq.read_table(uri) + assert table.equals(table2) + + +def test_fsspec_uri_raises_if_fsspec_is_not_available(): + # sadly cannot patch sys.modules because cython will still be able to import fsspec + try: + import fsspec # noqa: F401 + except ImportError: + pass + else: + pytest.skip("fsspec is available, skipping test") + + msg = re.escape( + "`fsspec` is required to handle `fsspec+://` and `hf://` URIs.") + with pytest.raises(ImportError, match=msg): + pq.read_table("fsspec+memory://example.parquet") + + +def test_iter_batches_raises_batch_size_zero(tempdir): + # See https://github.com/apache/arrow/issues/46811 + schema = pa.schema([]) + empty_table = pa.Table.from_batches([], schema=schema) + parquet_file_path = tempdir / "empty_file.parquet" + pq.write_table(empty_table, parquet_file_path) + parquet_file = pq.ParquetFile(parquet_file_path) + with pytest.raises(ValueError): + parquet_file.iter_batches(batch_size=0) diff --git a/shared/package-files/56/565ef8fb81829dc98a4be79bd3ac584d2e4a66d9a63a5ff80e55dc78583f95b6/composer.pyi b/shared/package-files/56/565ef8fb81829dc98a4be79bd3ac584d2e4a66d9a63a5ff80e55dc78583f95b6/composer.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c367f50b59e639a50bc03f3b45b6b81bce71ab53 --- /dev/null +++ b/shared/package-files/56/565ef8fb81829dc98a4be79bd3ac584d2e4a66d9a63a5ff80e55dc78583f95b6/composer.pyi @@ -0,0 +1,17 @@ +from typing import Any + +from yaml.error import MarkedYAMLError + +class ComposerError(MarkedYAMLError): ... + +class Composer: + anchors: Any + def __init__(self) -> None: ... + def check_node(self): ... + def get_node(self): ... + def get_single_node(self): ... + def compose_document(self): ... + def compose_node(self, parent, index): ... + def compose_scalar_node(self, anchor): ... + def compose_sequence_node(self, anchor): ... + def compose_mapping_node(self, anchor): ... diff --git a/shared/package-files/56/566141a62fbfb4d6bccb3366bbf7ee7dec263d39c253ac9c34219c377e1405c7/__init__.py b/shared/package-files/56/566141a62fbfb4d6bccb3366bbf7ee7dec263d39c253ac9c34219c377e1405c7/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01a1ad3c6f4cb5c0c9b99d1ce35fea92e7618ff5 --- /dev/null +++ b/shared/package-files/56/566141a62fbfb4d6bccb3366bbf7ee7dec263d39c253ac9c34219c377e1405c7/__init__.py @@ -0,0 +1,14 @@ +from .geometry import cauchy_geometry, spider_geometry +from .optim import ( + tangential_byrd_omojokun, + constrained_tangential_byrd_omojokun, + normal_byrd_omojokun, +) + +__all__ = [ + "cauchy_geometry", + "spider_geometry", + "tangential_byrd_omojokun", + "constrained_tangential_byrd_omojokun", + "normal_byrd_omojokun", +] diff --git a/shared/package-files/56/566520ef07b56189e8e87e331e08c2a0f63ba533b7cf314792714c0bca18c047/agent.pyi b/shared/package-files/56/566520ef07b56189e8e87e331e08c2a0f63ba533b7cf314792714c0bca18c047/agent.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3d5aa4bc61b19036f868c36bf3fe189c1a9608fb --- /dev/null +++ b/shared/package-files/56/566520ef07b56189e8e87e331e08c2a0f63ba533b7cf314792714c0bca18c047/agent.pyi @@ -0,0 +1,67 @@ +from socket import _RetAddress, socket +from threading import Thread +from typing import Dict, Protocol, Tuple + +from paramiko.channel import Channel +from paramiko.message import Message +from paramiko.pkey import PKey +from paramiko.transport import Transport + +class _AgentProxy(Protocol): + def connect(self) -> None: ... + def close(self) -> None: ... + +cSSH2_AGENTC_REQUEST_IDENTITIES: bytes +SSH2_AGENT_IDENTITIES_ANSWER: int +cSSH2_AGENTC_SIGN_REQUEST: bytes +SSH2_AGENT_SIGN_RESPONSE: int + +class AgentSSH: + def __init__(self) -> None: ... + def get_keys(self) -> Tuple[AgentKey, ...]: ... + +class AgentProxyThread(Thread): + def __init__(self, agent: _AgentProxy) -> None: ... + def run(self) -> None: ... + +class AgentLocalProxy(AgentProxyThread): + def __init__(self, agent: AgentServerProxy) -> None: ... + def get_connection(self) -> Tuple[socket, _RetAddress]: ... + +class AgentRemoteProxy(AgentProxyThread): + def __init__(self, agent: AgentClientProxy, chan: Channel) -> None: ... + def get_connection(self) -> Tuple[socket, _RetAddress]: ... + +class AgentClientProxy: + thread: Thread + def __init__(self, chanRemote: Channel) -> None: ... + def __del__(self) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + +class AgentServerProxy(AgentSSH): + thread: Thread + def __init__(self, t: Transport) -> None: ... + def __del__(self) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + def get_env(self) -> Dict[str, str]: ... + +class AgentRequestHandler: + def __init__(self, chanClient: Channel) -> None: ... + def __del__(self) -> None: ... + def close(self) -> None: ... + +class Agent(AgentSSH): + def __init__(self) -> None: ... + def close(self) -> None: ... + +class AgentKey(PKey): + agent: AgentSSH + blob: bytes + public_blob: None + name: str + def __init__(self, agent: AgentSSH, blob: bytes) -> None: ... + def asbytes(self) -> bytes: ... + def get_name(self) -> str: ... + def sign_ssh_data(self, data: bytes) -> Message: ... diff --git a/shared/package-files/56/56664ff52e693ee705c72a80395f74f049965d066f8028162e6949253525d0b1/Santarem b/shared/package-files/56/56664ff52e693ee705c72a80395f74f049965d066f8028162e6949253525d0b1/Santarem new file mode 100644 index 0000000000000000000000000000000000000000..001638c2f2a964eb2cc75660f66a1bcc447d7a57 Binary files /dev/null and b/shared/package-files/56/56664ff52e693ee705c72a80395f74f049965d066f8028162e6949253525d0b1/Santarem differ diff --git a/shared/package-files/56/5666818020fce78b306322e8b8330725fe0b2fa8943606a310e41fd295231e38/array_float32_5d.sav b/shared/package-files/56/5666818020fce78b306322e8b8330725fe0b2fa8943606a310e41fd295231e38/array_float32_5d.sav new file mode 100644 index 0000000000000000000000000000000000000000..2854dbc8b1e53f298ac3b135eac1f06e73940152 Binary files /dev/null and b/shared/package-files/56/5666818020fce78b306322e8b8330725fe0b2fa8943606a310e41fd295231e38/array_float32_5d.sav differ diff --git a/shared/package-files/56/5666bb7eda54f19534e85cecf9cca49fce014790c8cd7bb2eaf3b1646851eba8/lark.py b/shared/package-files/56/5666bb7eda54f19534e85cecf9cca49fce014790c8cd7bb2eaf3b1646851eba8/lark.py new file mode 100644 index 0000000000000000000000000000000000000000..ec70beeaf4891efb41581a92b643f2cb358bafde --- /dev/null +++ b/shared/package-files/56/5666bb7eda54f19534e85cecf9cca49fce014790c8cd7bb2eaf3b1646851eba8/lark.py @@ -0,0 +1,661 @@ +from abc import ABC, abstractmethod +import getpass +import sys, os, pickle +import tempfile +import types +import re +from typing import ( + TypeVar, Type, List, Dict, Iterator, Callable, Union, Optional, Sequence, + Tuple, Iterable, IO, Any, TYPE_CHECKING, Collection +) +if TYPE_CHECKING: + from .parsers.lalr_interactive_parser import InteractiveParser + from .tree import ParseTree + from .visitors import Transformer + if sys.version_info >= (3, 8): + from typing import Literal + else: + from typing_extensions import Literal + from .parser_frontends import ParsingFrontend + +from .exceptions import ConfigurationError, assert_config, UnexpectedInput +from .utils import Serialize, SerializeMemoizer, FS, isascii, logger +from .load_grammar import load_grammar, FromPackageLoader, Grammar, verify_used_files, PackageResource, sha256_digest +from .tree import Tree +from .common import LexerConf, ParserConf, _ParserArgType, _LexerArgType + +from .lexer import Lexer, BasicLexer, TerminalDef, LexerThread, Token +from .parse_tree_builder import ParseTreeBuilder +from .parser_frontends import _validate_frontend_args, _get_lexer_callbacks, _deserialize_parsing_frontend, _construct_parsing_frontend +from .grammar import Rule + + +try: + import regex + _has_regex = True +except ImportError: + _has_regex = False + + +###{standalone + + +class PostLex(ABC): + @abstractmethod + def process(self, stream: Iterator[Token]) -> Iterator[Token]: + return stream + + always_accept: Iterable[str] = () + +class LarkOptions(Serialize): + """Specifies the options for Lark + + """ + + start: List[str] + debug: bool + strict: bool + transformer: 'Optional[Transformer]' + propagate_positions: Union[bool, str] + maybe_placeholders: bool + cache: Union[bool, str] + regex: bool + g_regex_flags: int + keep_all_tokens: bool + tree_class: Optional[Callable[[str, List], Any]] + parser: _ParserArgType + lexer: _LexerArgType + ambiguity: 'Literal["auto", "resolve", "explicit", "forest"]' + postlex: Optional[PostLex] + priority: 'Optional[Literal["auto", "normal", "invert"]]' + lexer_callbacks: Dict[str, Callable[[Token], Token]] + use_bytes: bool + ordered_sets: bool + edit_terminals: Optional[Callable[[TerminalDef], TerminalDef]] + import_paths: 'List[Union[str, Callable[[Union[None, str, PackageResource], str], Tuple[str, str]]]]' + source_path: Optional[str] + + OPTIONS_DOC = r""" + **=== General Options ===** + + start + The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start") + debug + Display debug information and extra warnings. Use only when debugging (Default: ``False``) + When used with Earley, it generates a forest graph as "sppf.png", if 'dot' is installed. + strict + Throw an exception on any potential ambiguity, including shift/reduce conflicts, and regex collisions. + transformer + Applies the transformer to every parse tree (equivalent to applying it after the parse, but faster) + propagate_positions + Propagates positional attributes into the 'meta' attribute of all tree branches. + Sets attributes: (line, column, end_line, end_column, start_pos, end_pos, + container_line, container_column, container_end_line, container_end_column) + Accepts ``False``, ``True``, or a callable, which will filter which nodes to ignore when propagating. + maybe_placeholders + When ``True``, the ``[]`` operator returns ``None`` when not matched. + When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all. + (default= ``True``) + cache + Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now. + + - When ``False``, does nothing (default) + - When ``True``, caches to a temporary file in the local directory + - When given a string, caches to the path pointed by the string + regex + When True, uses the ``regex`` module instead of the stdlib ``re``. + g_regex_flags + Flags that are applied to all terminals (both regex and strings) + keep_all_tokens + Prevent the tree builder from automagically removing "punctuation" tokens (Default: ``False``) + tree_class + Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``. + + **=== Algorithm Options ===** + + parser + Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley"). + (there is also a "cyk" option for legacy) + lexer + Decides whether or not to use a lexer stage + + - "auto" (default): Choose for me based on the parser + - "basic": Use a basic lexer + - "contextual": Stronger lexer (only works with parser="lalr") + - "dynamic": Flexible and powerful (only with parser="earley") + - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible. + ambiguity + Decides how to handle ambiguity in the parse. Only relevant if parser="earley" + + - "resolve": The parser will automatically choose the simplest derivation + (it chooses consistently: greedy for tokens, non-greedy for rules) + - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest). + - "forest": The parser will return the root of the shared packed parse forest. + + **=== Misc. / Domain Specific Options ===** + + postlex + Lexer post-processing (Default: ``None``) Only works with the basic and contextual lexers. + priority + How priorities should be evaluated - "auto", ``None``, "normal", "invert" (Default: "auto") + lexer_callbacks + Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution. + use_bytes + Accept an input of type ``bytes`` instead of ``str``. + ordered_sets + Should Earley use ordered-sets to achieve stable output (~10% slower than regular sets. Default: True) + edit_terminals + A callback for editing the terminals before parse. + import_paths + A List of either paths or loader functions to specify from where grammars are imported + source_path + Override the source of from where the grammar was loaded. Useful for relative imports and unconventional grammar loading + **=== End of Options ===** + """ + if __doc__: + __doc__ += OPTIONS_DOC + + + # Adding a new option needs to be done in multiple places: + # - In the dictionary below. This is the primary truth of which options `Lark.__init__` accepts + # - In the docstring above. It is used both for the docstring of `LarkOptions` and `Lark`, and in readthedocs + # - As an attribute of `LarkOptions` above + # - Potentially in `_LOAD_ALLOWED_OPTIONS` below this class, when the option doesn't change how the grammar is loaded + # - Potentially in `lark.tools.__init__`, if it makes sense, and it can easily be passed as a cmd argument + _defaults: Dict[str, Any] = { + 'debug': False, + 'strict': False, + 'keep_all_tokens': False, + 'tree_class': None, + 'cache': False, + 'postlex': None, + 'parser': 'earley', + 'lexer': 'auto', + 'transformer': None, + 'start': 'start', + 'priority': 'auto', + 'ambiguity': 'auto', + 'regex': False, + 'propagate_positions': False, + 'lexer_callbacks': {}, + 'maybe_placeholders': True, + 'edit_terminals': None, + 'g_regex_flags': 0, + 'use_bytes': False, + 'ordered_sets': True, + 'import_paths': [], + 'source_path': None, + '_plugins': {}, + } + + def __init__(self, options_dict: Dict[str, Any]) -> None: + o = dict(options_dict) + + options = {} + for name, default in self._defaults.items(): + if name in o: + value = o.pop(name) + if isinstance(default, bool) and name not in ('cache', 'use_bytes', 'propagate_positions'): + value = bool(value) + else: + value = default + + options[name] = value + + if isinstance(options['start'], str): + options['start'] = [options['start']] + + self.__dict__['options'] = options + + + assert_config(self.parser, ('earley', 'lalr', 'cyk', None)) + + if self.parser == 'earley' and self.transformer: + raise ConfigurationError('Cannot specify an embedded transformer when using the Earley algorithm. ' + 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)') + + if o: + raise ConfigurationError("Unknown options: %s" % o.keys()) + + def __getattr__(self, name: str) -> Any: + try: + return self.__dict__['options'][name] + except KeyError as e: + raise AttributeError(e) + + def __setattr__(self, name: str, value: str) -> None: + assert_config(name, self.options.keys(), "%r isn't a valid option. Expected one of: %s") + self.options[name] = value + + def serialize(self, memo = None) -> Dict[str, Any]: + return self.options + + @classmethod + def deserialize(cls, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]]) -> "LarkOptions": + return cls(data) + + +# Options that can be passed to the Lark parser, even when it was loaded from cache/standalone. +# These options are only used outside of `load_grammar`. +_LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'lexer_callbacks', 'use_bytes', 'debug', 'g_regex_flags', 'regex', 'propagate_positions', 'tree_class', '_plugins'} + +_VALID_PRIORITY_OPTIONS = ('auto', 'normal', 'invert', None) +_VALID_AMBIGUITY_OPTIONS = ('auto', 'resolve', 'explicit', 'forest') + + +_T = TypeVar('_T', bound="Lark") + +class Lark(Serialize): + """Main interface for the library. + + It's mostly a thin wrapper for the many different parsers, and for the tree constructor. + + Parameters: + grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax) + options: a dictionary controlling various aspects of Lark. + + Example: + >>> Lark(r'''start: "foo" ''') + Lark(...) + """ + + source_path: str + source_grammar: str + grammar: 'Grammar' + options: LarkOptions + lexer: Lexer + parser: 'ParsingFrontend' + terminals: Collection[TerminalDef] + + def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None: + self.options = LarkOptions(options) + re_module: types.ModuleType + + # Set regex or re module + use_regex = self.options.regex + if use_regex: + if _has_regex: + re_module = regex + else: + raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.') + else: + re_module = re + + # Some, but not all file-like objects have a 'name' attribute + if self.options.source_path is None: + try: + self.source_path = grammar.name # type: ignore[union-attr] + except AttributeError: + self.source_path = '' + else: + self.source_path = self.options.source_path + + # Drain file-like objects to get their contents + try: + read = grammar.read # type: ignore[union-attr] + except AttributeError: + pass + else: + grammar = read() + + cache_fn = None + cache_sha256 = None + if isinstance(grammar, str): + self.source_grammar = grammar + if self.options.use_bytes: + if not isascii(grammar): + raise ConfigurationError("Grammar must be ascii only, when use_bytes=True") + + if self.options.cache: + if self.options.parser != 'lalr': + raise ConfigurationError("cache only works with parser='lalr' for now") + + unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins') + options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable) + from . import __version__ + s = grammar + options_str + __version__ + str(sys.version_info[:2]) + cache_sha256 = sha256_digest(s) + + if isinstance(self.options.cache, str): + cache_fn = self.options.cache + else: + if self.options.cache is not True: + raise ConfigurationError("cache argument must be bool or str") + + try: + username = getpass.getuser() + except Exception: + # The exception raised may be ImportError or OSError in + # the future. For the cache, we don't care about the + # specific reason - we just want a username. + username = "unknown" + + cache_fn = tempfile.gettempdir() + "/.lark_cache_%s_%s_%s_%s.tmp" % (username, cache_sha256, *sys.version_info[:2]) + + old_options = self.options + try: + with FS.open(cache_fn, 'rb') as f: + logger.debug('Loading grammar from cache: %s', cache_fn) + # Remove options that aren't relevant for loading from cache + for name in (set(options) - _LOAD_ALLOWED_OPTIONS): + del options[name] + file_sha256 = f.readline().rstrip(b'\n') + cached_used_files = pickle.load(f) + if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files): + cached_parser_data = pickle.load(f) + self._load(cached_parser_data, **options) + return + except FileNotFoundError: + # The cache file doesn't exist; parse and compose the grammar as normal + pass + except Exception: # We should probably narrow done which errors we catch here. + logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn) + + # In theory, the Lark instance might have been messed up by the call to `_load`. + # In practice the only relevant thing that might have been overwritten should be `options` + self.options = old_options + + + # Parse the grammar file and compose the grammars + self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens) + else: + assert isinstance(grammar, Grammar) + self.grammar = grammar + + + if self.options.lexer == 'auto': + if self.options.parser == 'lalr': + self.options.lexer = 'contextual' + elif self.options.parser == 'earley': + if self.options.postlex is not None: + logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. " + "Consider using lalr with contextual instead of earley") + self.options.lexer = 'basic' + else: + self.options.lexer = 'dynamic' + elif self.options.parser == 'cyk': + self.options.lexer = 'basic' + else: + assert False, self.options.parser + lexer = self.options.lexer + if isinstance(lexer, type): + assert issubclass(lexer, Lexer) # XXX Is this really important? Maybe just ensure interface compliance + else: + assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete')) + if self.options.postlex is not None and 'dynamic' in lexer: + raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead") + + if self.options.ambiguity == 'auto': + if self.options.parser == 'earley': + self.options.ambiguity = 'resolve' + else: + assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s") + + if self.options.priority == 'auto': + self.options.priority = 'normal' + + if self.options.priority not in _VALID_PRIORITY_OPTIONS: + raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS)) + if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS: + raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS)) + + if self.options.parser is None: + terminals_to_keep = '*' + elif self.options.postlex is not None: + terminals_to_keep = set(self.options.postlex.always_accept) + else: + terminals_to_keep = set() + + # Compile the EBNF grammar into BNF + self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep) + + if self.options.edit_terminals: + for t in self.terminals: + self.options.edit_terminals(t) + + self._terminals_dict = {t.name: t for t in self.terminals} + + # If the user asked to invert the priorities, negate them all here. + if self.options.priority == 'invert': + for rule in self.rules: + if rule.options.priority is not None: + rule.options.priority = -rule.options.priority + for term in self.terminals: + term.priority = -term.priority + # Else, if the user asked to disable priorities, strip them from the + # rules and terminals. This allows the Earley parsers to skip an extra forest walk + # for improved performance, if you don't need them (or didn't specify any). + elif self.options.priority is None: + for rule in self.rules: + if rule.options.priority is not None: + rule.options.priority = None + for term in self.terminals: + term.priority = 0 + + # TODO Deprecate lexer_callbacks? + self.lexer_conf = LexerConf( + self.terminals, re_module, self.ignore_tokens, self.options.postlex, + self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict + ) + + if self.options.parser: + self.parser = self._build_parser() + elif lexer: + self.lexer = self._build_lexer() + + if cache_fn: + logger.debug('Saving grammar to cache: %s', cache_fn) + try: + with FS.open(cache_fn, 'wb') as f: + assert cache_sha256 is not None + f.write(cache_sha256.encode('utf8') + b'\n') + pickle.dump(used_files, f) + self.save(f, _LOAD_ALLOWED_OPTIONS) + except IOError as e: + logger.exception("Failed to save Lark to cache: %r.", cache_fn, e) + + if __doc__: + __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC + + __serialize_fields__ = 'parser', 'rules', 'options' + + def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer: + lexer_conf = self.lexer_conf + if dont_ignore: + from copy import copy + lexer_conf = copy(lexer_conf) + lexer_conf.ignore = () + return BasicLexer(lexer_conf) + + def _prepare_callbacks(self) -> None: + self._callbacks = {} + # we don't need these callbacks if we aren't building a tree + if self.options.ambiguity != 'forest': + self._parse_tree_builder = ParseTreeBuilder( + self.rules, + self.options.tree_class or Tree, + self.options.propagate_positions, + self.options.parser != 'lalr' and self.options.ambiguity == 'explicit', + self.options.maybe_placeholders + ) + self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer) + self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals)) + + def _build_parser(self) -> "ParsingFrontend": + self._prepare_callbacks() + _validate_frontend_args(self.options.parser, self.options.lexer) + parser_conf = ParserConf(self.rules, self._callbacks, self.options.start) + return _construct_parsing_frontend( + self.options.parser, + self.options.lexer, + self.lexer_conf, + parser_conf, + options=self.options + ) + + def save(self, f, exclude_options: Collection[str] = ()) -> None: + """Saves the instance into the given file object + + Useful for caching and multiprocessing. + """ + if self.options.parser != 'lalr': + raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.") + data, m = self.memo_serialize([TerminalDef, Rule]) + if exclude_options: + data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options} + pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL) + + @classmethod + def load(cls: Type[_T], f) -> _T: + """Loads an instance from the given file object + + Useful for caching and multiprocessing. + """ + inst = cls.__new__(cls) + return inst._load(f) + + def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf: + lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo) + lexer_conf.callbacks = options.lexer_callbacks or {} + lexer_conf.re_module = regex if options.regex else re + lexer_conf.use_bytes = options.use_bytes + lexer_conf.g_regex_flags = options.g_regex_flags + lexer_conf.skip_validation = True + lexer_conf.postlex = options.postlex + return lexer_conf + + def _load(self: _T, f: Any, **kwargs) -> _T: + if isinstance(f, dict): + d = f + else: + d = pickle.load(f) + memo_json = d['memo'] + data = d['data'] + + assert memo_json + memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {}) + options = dict(data['options']) + if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults): + raise ConfigurationError("Some options are not allowed when loading a Parser: {}" + .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS)) + options.update(kwargs) + self.options = LarkOptions.deserialize(options, memo) + self.rules = [Rule.deserialize(r, memo) for r in data['rules']] + self.source_path = '' + _validate_frontend_args(self.options.parser, self.options.lexer) + self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options) + self.terminals = self.lexer_conf.terminals + self._prepare_callbacks() + self._terminals_dict = {t.name: t for t in self.terminals} + self.parser = _deserialize_parsing_frontend( + data['parser'], + memo, + self.lexer_conf, + self._callbacks, + self.options, # Not all, but multiple attributes are used + ) + return self + + @classmethod + def _load_from_dict(cls, data, memo, **kwargs): + inst = cls.__new__(cls) + return inst._load({'data': data, 'memo': memo}, **kwargs) + + @classmethod + def open(cls: Type[_T], grammar_filename: str, rel_to: Optional[str]=None, **options) -> _T: + """Create an instance of Lark with the grammar given by its filename + + If ``rel_to`` is provided, the function will find the grammar filename in relation to it. + + Example: + + >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr") + Lark(...) + + """ + if rel_to: + basepath = os.path.dirname(rel_to) + grammar_filename = os.path.join(basepath, grammar_filename) + with open(grammar_filename, encoding='utf8') as f: + return cls(f, **options) + + @classmethod + def open_from_package(cls: Type[_T], package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> _T: + """Create an instance of Lark with the grammar loaded from within the package `package`. + This allows grammar loading from zipapps. + + Imports in the grammar will use the `package` and `search_paths` provided, through `FromPackageLoader` + + Example: + + Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...) + """ + package_loader = FromPackageLoader(package, search_paths) + full_path, text = package_loader(None, grammar_path) + options.setdefault('source_path', full_path) + options.setdefault('import_paths', []) + options['import_paths'].append(package_loader) + return cls(text, **options) + + def __repr__(self): + return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer) + + + def lex(self, text: str, dont_ignore: bool=False) -> Iterator[Token]: + """Only lex (and postlex) the text, without parsing it. Only relevant when lexer='basic' + + When dont_ignore=True, the lexer will return all tokens, even those marked for %ignore. + + :raises UnexpectedCharacters: In case the lexer cannot find a suitable match. + """ + lexer: Lexer + if not hasattr(self, 'lexer') or dont_ignore: + lexer = self._build_lexer(dont_ignore) + else: + lexer = self.lexer + lexer_thread = LexerThread.from_text(lexer, text) + stream = lexer_thread.lex(None) + if self.options.postlex: + return self.options.postlex.process(stream) + return stream + + def get_terminal(self, name: str) -> TerminalDef: + """Get information about a terminal""" + return self._terminals_dict[name] + + def parse_interactive(self, text: Optional[str]=None, start: Optional[str]=None) -> 'InteractiveParser': + """Start an interactive parsing session. + + Parameters: + text (str, optional): Text to be parsed. Required for ``resume_parse()``. + start (str, optional): Start symbol + + Returns: + A new InteractiveParser instance. + + See Also: ``Lark.parse()`` + """ + return self.parser.parse_interactive(text, start=start) + + def parse(self, text: str, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> 'ParseTree': + """Parse the given text, according to the options provided. + + Parameters: + text (str): Text to be parsed. + start (str, optional): Required if Lark was given multiple possible start symbols (using the start option). + on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing. + LALR only. See examples/advanced/error_handling.py for an example of how to use on_error. + + Returns: + If a transformer is supplied to ``__init__``, returns whatever is the + result of the transformation. Otherwise, returns a Tree instance. + + :raises UnexpectedInput: On a parse error, one of these sub-exceptions will rise: + ``UnexpectedCharacters``, ``UnexpectedToken``, or ``UnexpectedEOF``. + For convenience, these sub-exceptions also inherit from ``ParserError`` and ``LexerError``. + + """ + return self.parser.parse(text, start=start, on_error=on_error) + + +###} diff --git a/shared/package-files/56/56678668d6a1892cc1253e114d7301f010ea40bbce65c8d67bfc518a620f3f62/conj_physical_compositeimplicitautograd_dispatch.h b/shared/package-files/56/56678668d6a1892cc1253e114d7301f010ea40bbce65c8d67bfc518a620f3f62/conj_physical_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..617bc805032a1dc9e83f784aaf0cc7117b967bd7 --- /dev/null +++ b/shared/package-files/56/56678668d6a1892cc1253e114d7301f010ea40bbce65c8d67bfc518a620f3f62/conj_physical_compositeimplicitautograd_dispatch.h @@ -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 conj_physical(const at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/56/5667c31dcece0b6d20cad709faa0d16a2a57ee42563742cfa16ea8c0cca4dc48/period.py b/shared/package-files/56/5667c31dcece0b6d20cad709faa0d16a2a57ee42563742cfa16ea8c0cca4dc48/period.py new file mode 100644 index 0000000000000000000000000000000000000000..2947ba7b8c72ac09497f796aaaec8edfb133a948 --- /dev/null +++ b/shared/package-files/56/5667c31dcece0b6d20cad709faa0d16a2a57ee42563742cfa16ea8c0cca4dc48/period.py @@ -0,0 +1,1331 @@ +from __future__ import annotations + +from datetime import timedelta +import operator +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Literal, + TypeVar, + cast, + overload, +) +import warnings + +import numpy as np + +from pandas._libs import ( + algos as libalgos, + lib, +) +from pandas._libs.arrays import NDArrayBacked +from pandas._libs.tslibs import ( + BaseOffset, + NaT, + NaTType, + Timedelta, + add_overflowsafe, + astype_overflowsafe, + dt64arr_to_periodarr as c_dt64arr_to_periodarr, + get_unit_from_dtype, + iNaT, + parsing, + period as libperiod, + to_offset, +) +from pandas._libs.tslibs.dtypes import ( + FreqGroup, + PeriodDtypeBase, + freq_to_period_freqstr, +) +from pandas._libs.tslibs.fields import isleapyear_arr +from pandas._libs.tslibs.offsets import ( + Tick, + delta_to_tick, +) +from pandas._libs.tslibs.period import ( + DIFFERENT_FREQ, + IncompatibleFrequency, + Period, + get_period_field_arr, + period_asfreq_arr, +) +from pandas.util._decorators import ( + cache_readonly, + doc, +) +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.common import ( + ensure_object, + pandas_dtype, +) +from pandas.core.dtypes.dtypes import ( + DatetimeTZDtype, + PeriodDtype, +) +from pandas.core.dtypes.generic import ( + ABCIndex, + ABCPeriodIndex, + ABCSeries, + ABCTimedeltaArray, +) +from pandas.core.dtypes.missing import isna + +from pandas.core.arrays import datetimelike as dtl +import pandas.core.common as com + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pandas._typing import ( + AnyArrayLike, + Dtype, + FillnaOptions, + NpDtype, + NumpySorter, + NumpyValueArrayLike, + Self, + npt, + ) + + from pandas.core.arrays import ( + DatetimeArray, + TimedeltaArray, + ) + from pandas.core.arrays.base import ExtensionArray + + +BaseOffsetT = TypeVar("BaseOffsetT", bound=BaseOffset) + + +_shared_doc_kwargs = { + "klass": "PeriodArray", +} + + +def _field_accessor(name: str, docstring: str | None = None): + def f(self): + base = self.dtype._dtype_code + result = get_period_field_arr(name, self.asi8, base) + return result + + f.__name__ = name + f.__doc__ = docstring + return property(f) + + +# error: Definition of "_concat_same_type" in base class "NDArrayBacked" is +# incompatible with definition in base class "ExtensionArray" +class PeriodArray(dtl.DatelikeOps, libperiod.PeriodMixin): # type: ignore[misc] + """ + Pandas ExtensionArray for storing Period data. + + Users should use :func:`~pandas.array` to create new instances. + + Parameters + ---------- + values : Union[PeriodArray, Series[period], ndarray[int], PeriodIndex] + The data to store. These should be arrays that can be directly + converted to ordinals without inference or copy (PeriodArray, + ndarray[int64]), or a box around such an array (Series[period], + PeriodIndex). + dtype : PeriodDtype, optional + A PeriodDtype instance from which to extract a `freq`. If both + `freq` and `dtype` are specified, then the frequencies must match. + freq : str or DateOffset + The `freq` to use for the array. Mostly applicable when `values` + is an ndarray of integers, when `freq` is required. When `values` + is a PeriodArray (or box around), it's checked that ``values.freq`` + matches `freq`. + copy : bool, default False + Whether to copy the ordinals before storing. + + Attributes + ---------- + None + + Methods + ------- + None + + See Also + -------- + Period: Represents a period of time. + PeriodIndex : Immutable Index for period data. + period_range: Create a fixed-frequency PeriodArray. + array: Construct a pandas array. + + Notes + ----- + There are two components to a PeriodArray + + - ordinals : integer ndarray + - freq : pd.tseries.offsets.Offset + + The values are physically stored as a 1-D ndarray of integers. These are + called "ordinals" and represent some kind of offset from a base. + + The `freq` indicates the span covered by each element of the array. + All elements in the PeriodArray have the same `freq`. + + Examples + -------- + >>> pd.arrays.PeriodArray(pd.PeriodIndex(['2023-01-01', + ... '2023-01-02'], freq='D')) + + ['2023-01-01', '2023-01-02'] + Length: 2, dtype: period[D] + """ + + # array priority higher than numpy scalars + __array_priority__ = 1000 + _typ = "periodarray" # ABCPeriodArray + _internal_fill_value = np.int64(iNaT) + _recognized_scalars = (Period,) + _is_recognized_dtype = lambda x: isinstance( + x, PeriodDtype + ) # check_compatible_with checks freq match + _infer_matches = ("period",) + + @property + def _scalar_type(self) -> type[Period]: + return Period + + # Names others delegate to us + _other_ops: list[str] = [] + _bool_ops: list[str] = ["is_leap_year"] + _object_ops: list[str] = ["start_time", "end_time", "freq"] + _field_ops: list[str] = [ + "year", + "month", + "day", + "hour", + "minute", + "second", + "weekofyear", + "weekday", + "week", + "dayofweek", + "day_of_week", + "dayofyear", + "day_of_year", + "quarter", + "qyear", + "days_in_month", + "daysinmonth", + ] + _datetimelike_ops: list[str] = _field_ops + _object_ops + _bool_ops + _datetimelike_methods: list[str] = ["strftime", "to_timestamp", "asfreq"] + + _dtype: PeriodDtype + + # -------------------------------------------------------------------- + # Constructors + + def __init__( + self, values, dtype: Dtype | None = None, freq=None, copy: bool = False + ) -> None: + if freq is not None: + # GH#52462 + warnings.warn( + "The 'freq' keyword in the PeriodArray constructor is deprecated " + "and will be removed in a future version. Pass 'dtype' instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + freq = validate_dtype_freq(dtype, freq) + dtype = PeriodDtype(freq) + + if dtype is not None: + dtype = pandas_dtype(dtype) + if not isinstance(dtype, PeriodDtype): + raise ValueError(f"Invalid dtype {dtype} for PeriodArray") + + if isinstance(values, ABCSeries): + values = values._values + if not isinstance(values, type(self)): + raise TypeError("Incorrect dtype") + + elif isinstance(values, ABCPeriodIndex): + values = values._values + + if isinstance(values, type(self)): + if dtype is not None and dtype != values.dtype: + raise raise_on_incompatible(values, dtype.freq) + values, dtype = values._ndarray, values.dtype + + if not copy: + values = np.asarray(values, dtype="int64") + else: + values = np.array(values, dtype="int64", copy=copy) + if dtype is None: + raise ValueError("dtype is not specified and cannot be inferred") + dtype = cast(PeriodDtype, dtype) + NDArrayBacked.__init__(self, values, dtype) + + # error: Signature of "_simple_new" incompatible with supertype "NDArrayBacked" + @classmethod + def _simple_new( # type: ignore[override] + cls, + values: npt.NDArray[np.int64], + dtype: PeriodDtype, + ) -> Self: + # alias for PeriodArray.__init__ + assertion_msg = "Should be numpy array of type i8" + assert isinstance(values, np.ndarray) and values.dtype == "i8", assertion_msg + return cls(values, dtype=dtype) + + @classmethod + def _from_sequence( + cls, + scalars, + *, + dtype: Dtype | None = None, + copy: bool = False, + ) -> Self: + if dtype is not None: + dtype = pandas_dtype(dtype) + if dtype and isinstance(dtype, PeriodDtype): + freq = dtype.freq + else: + freq = None + + if isinstance(scalars, cls): + validate_dtype_freq(scalars.dtype, freq) + if copy: + scalars = scalars.copy() + return scalars + + periods = np.asarray(scalars, dtype=object) + + freq = freq or libperiod.extract_freq(periods) + ordinals = libperiod.extract_ordinals(periods, freq) + dtype = PeriodDtype(freq) + return cls(ordinals, dtype=dtype) + + @classmethod + def _from_sequence_of_strings( + cls, strings, *, dtype: Dtype | None = None, copy: bool = False + ) -> Self: + return cls._from_sequence(strings, dtype=dtype, copy=copy) + + @classmethod + def _from_datetime64(cls, data, freq, tz=None) -> Self: + """ + Construct a PeriodArray from a datetime64 array + + Parameters + ---------- + data : ndarray[datetime64[ns], datetime64[ns, tz]] + freq : str or Tick + tz : tzinfo, optional + + Returns + ------- + PeriodArray[freq] + """ + if isinstance(freq, BaseOffset): + freq = freq_to_period_freqstr(freq.n, freq.name) + data, freq = dt64arr_to_periodarr(data, freq, tz) + dtype = PeriodDtype(freq) + return cls(data, dtype=dtype) + + @classmethod + def _generate_range(cls, start, end, periods, freq): + periods = dtl.validate_periods(periods) + + if freq is not None: + freq = Period._maybe_convert_freq(freq) + + if start is not None or end is not None: + subarr, freq = _get_ordinal_range(start, end, periods, freq) + else: + raise ValueError("Not enough parameters to construct Period range") + + return subarr, freq + + @classmethod + def _from_fields(cls, *, fields: dict, freq) -> Self: + subarr, freq = _range_from_fields(freq=freq, **fields) + dtype = PeriodDtype(freq) + return cls._simple_new(subarr, dtype=dtype) + + # ----------------------------------------------------------------- + # DatetimeLike Interface + + # error: Argument 1 of "_unbox_scalar" is incompatible with supertype + # "DatetimeLikeArrayMixin"; supertype defines the argument type as + # "Union[Union[Period, Any, Timedelta], NaTType]" + def _unbox_scalar( # type: ignore[override] + self, + value: Period | NaTType, + ) -> np.int64: + if value is NaT: + # error: Item "Period" of "Union[Period, NaTType]" has no attribute "value" + return np.int64(value._value) # type: ignore[union-attr] + elif isinstance(value, self._scalar_type): + self._check_compatible_with(value) + return np.int64(value.ordinal) + else: + raise ValueError(f"'value' should be a Period. Got '{value}' instead.") + + def _scalar_from_string(self, value: str) -> Period: + return Period(value, freq=self.freq) + + # error: Argument 1 of "_check_compatible_with" is incompatible with + # supertype "DatetimeLikeArrayMixin"; supertype defines the argument type + # as "Period | Timestamp | Timedelta | NaTType" + def _check_compatible_with(self, other: Period | NaTType | PeriodArray) -> None: # type: ignore[override] + if other is NaT: + return + # error: Item "NaTType" of "Period | NaTType | PeriodArray" has no + # attribute "freq" + self._require_matching_freq(other.freq) # type: ignore[union-attr] + + # -------------------------------------------------------------------- + # Data / Attributes + + @cache_readonly + def dtype(self) -> PeriodDtype: + return self._dtype + + # error: Cannot override writeable attribute with read-only property + @property # type: ignore[override] + def freq(self) -> BaseOffset: + """ + Return the frequency object for this PeriodArray. + """ + return self.dtype.freq + + @property + def freqstr(self) -> str: + return freq_to_period_freqstr(self.freq.n, self.freq.name) + + def __array__( + self, dtype: NpDtype | None = None, copy: bool | None = None + ) -> np.ndarray: + if dtype == "i8": + # For NumPy 1.x compatibility we cannot use copy=None. And + # `copy=False` has the meaning of `copy=None` here: + if not copy: + return np.asarray(self.asi8, dtype=dtype) + else: + return np.array(self.asi8, dtype=dtype) + + if copy is False: + warnings.warn( + "Starting with NumPy 2.0, the behavior of the 'copy' keyword has " + "changed and passing 'copy=False' raises an error when returning " + "a zero-copy NumPy array is not possible. pandas will follow " + "this behavior starting with pandas 3.0.\nThis conversion to " + "NumPy requires a copy, but 'copy=False' was passed. Consider " + "using 'np.asarray(..)' instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + if dtype == bool: + return ~self._isnan + + # This will raise TypeError for non-object dtypes + return np.array(list(self), dtype=object) + + def __arrow_array__(self, type=None): + """ + Convert myself into a pyarrow Array. + """ + import pyarrow + + from pandas.core.arrays.arrow.extension_types import ArrowPeriodType + + if type is not None: + if pyarrow.types.is_integer(type): + return pyarrow.array(self._ndarray, mask=self.isna(), type=type) + elif isinstance(type, ArrowPeriodType): + # ensure we have the same freq + if self.freqstr != type.freq: + raise TypeError( + "Not supported to convert PeriodArray to array with different " + f"'freq' ({self.freqstr} vs {type.freq})" + ) + else: + raise TypeError( + f"Not supported to convert PeriodArray to '{type}' type" + ) + + period_type = ArrowPeriodType(self.freqstr) + storage_array = pyarrow.array(self._ndarray, mask=self.isna(), type="int64") + return pyarrow.ExtensionArray.from_storage(period_type, storage_array) + + # -------------------------------------------------------------------- + # Vectorized analogues of Period properties + + year = _field_accessor( + "year", + """ + The year of the period. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y") + >>> idx.year + Index([2023, 2024, 2025], dtype='int64') + """, + ) + month = _field_accessor( + "month", + """ + The month as January=1, December=12. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M") + >>> idx.month + Index([1, 2, 3], dtype='int64') + """, + ) + day = _field_accessor( + "day", + """ + The days of the period. + + Examples + -------- + >>> idx = pd.PeriodIndex(['2020-01-31', '2020-02-28'], freq='D') + >>> idx.day + Index([31, 28], dtype='int64') + """, + ) + hour = _field_accessor( + "hour", + """ + The hour of the period. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01-01 10:00", "2023-01-01 11:00"], freq='h') + >>> idx.hour + Index([10, 11], dtype='int64') + """, + ) + minute = _field_accessor( + "minute", + """ + The minute of the period. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01-01 10:30:00", + ... "2023-01-01 11:50:00"], freq='min') + >>> idx.minute + Index([30, 50], dtype='int64') + """, + ) + second = _field_accessor( + "second", + """ + The second of the period. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01-01 10:00:30", + ... "2023-01-01 10:00:31"], freq='s') + >>> idx.second + Index([30, 31], dtype='int64') + """, + ) + weekofyear = _field_accessor( + "week", + """ + The week ordinal of the year. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M") + >>> idx.week # It can be written `weekofyear` + Index([5, 9, 13], dtype='int64') + """, + ) + week = weekofyear + day_of_week = _field_accessor( + "day_of_week", + """ + The day of the week with Monday=0, Sunday=6. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01-01", "2023-01-02", "2023-01-03"], freq="D") + >>> idx.weekday + Index([6, 0, 1], dtype='int64') + """, + ) + dayofweek = day_of_week + weekday = dayofweek + dayofyear = day_of_year = _field_accessor( + "day_of_year", + """ + The ordinal day of the year. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01-10", "2023-02-01", "2023-03-01"], freq="D") + >>> idx.dayofyear + Index([10, 32, 60], dtype='int64') + + >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y") + >>> idx + PeriodIndex(['2023', '2024', '2025'], dtype='period[Y-DEC]') + >>> idx.dayofyear + Index([365, 366, 365], dtype='int64') + """, + ) + quarter = _field_accessor( + "quarter", + """ + The quarter of the date. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M") + >>> idx.quarter + Index([1, 1, 1], dtype='int64') + """, + ) + qyear = _field_accessor("qyear") + days_in_month = _field_accessor( + "days_in_month", + """ + The number of days in the month. + + Examples + -------- + For Series: + + >>> period = pd.period_range('2020-1-1 00:00', '2020-3-1 00:00', freq='M') + >>> s = pd.Series(period) + >>> s + 0 2020-01 + 1 2020-02 + 2 2020-03 + dtype: period[M] + >>> s.dt.days_in_month + 0 31 + 1 29 + 2 31 + dtype: int64 + + For PeriodIndex: + + >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M") + >>> idx.days_in_month # It can be also entered as `daysinmonth` + Index([31, 28, 31], dtype='int64') + """, + ) + daysinmonth = days_in_month + + @property + def is_leap_year(self) -> npt.NDArray[np.bool_]: + """ + Logical indicating if the date belongs to a leap year. + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y") + >>> idx.is_leap_year + array([False, True, False]) + """ + return isleapyear_arr(np.asarray(self.year)) + + def to_timestamp(self, freq=None, how: str = "start") -> DatetimeArray: + """ + Cast to DatetimeArray/Index. + + Parameters + ---------- + freq : str or DateOffset, optional + Target frequency. The default is 'D' for week or longer, + 's' otherwise. + how : {'s', 'e', 'start', 'end'} + Whether to use the start or end of the time period being converted. + + Returns + ------- + DatetimeArray/Index + + Examples + -------- + >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M") + >>> idx.to_timestamp() + DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'], + dtype='datetime64[ns]', freq='MS') + """ + from pandas.core.arrays import DatetimeArray + + how = libperiod.validate_end_alias(how) + + end = how == "E" + if end: + if freq == "B" or self.freq == "B": + # roll forward to ensure we land on B date + adjust = Timedelta(1, "D") - Timedelta(1, "ns") + return self.to_timestamp(how="start") + adjust + else: + adjust = Timedelta(1, "ns") + return (self + self.freq).to_timestamp(how="start") - adjust + + if freq is None: + freq_code = self._dtype._get_to_timestamp_base() + dtype = PeriodDtypeBase(freq_code, 1) + freq = dtype._freqstr + base = freq_code + else: + freq = Period._maybe_convert_freq(freq) + base = freq._period_dtype_code + + new_parr = self.asfreq(freq, how=how) + + new_data = libperiod.periodarr_to_dt64arr(new_parr.asi8, base) + dta = DatetimeArray._from_sequence(new_data) + + if self.freq.name == "B": + # See if we can retain BDay instead of Day in cases where + # len(self) is too small for infer_freq to distinguish between them + diffs = libalgos.unique_deltas(self.asi8) + if len(diffs) == 1: + diff = diffs[0] + if diff == self.dtype._n: + dta._freq = self.freq + elif diff == 1: + dta._freq = self.freq.base + # TODO: other cases? + return dta + else: + return dta._with_freq("infer") + + # -------------------------------------------------------------------- + + def _box_func(self, x) -> Period | NaTType: + return Period._from_ordinal(ordinal=x, freq=self.freq) + + @doc(**_shared_doc_kwargs, other="PeriodIndex", other_name="PeriodIndex") + def asfreq(self, freq=None, how: str = "E") -> Self: + """ + Convert the {klass} to the specified frequency `freq`. + + Equivalent to applying :meth:`pandas.Period.asfreq` with the given arguments + to each :class:`~pandas.Period` in this {klass}. + + Parameters + ---------- + freq : str + A frequency. + how : str {{'E', 'S'}}, default 'E' + Whether the elements should be aligned to the end + or start within pa period. + + * 'E', 'END', or 'FINISH' for end, + * 'S', 'START', or 'BEGIN' for start. + + January 31st ('END') vs. January 1st ('START') for example. + + Returns + ------- + {klass} + The transformed {klass} with the new frequency. + + See Also + -------- + {other}.asfreq: Convert each Period in a {other_name} to the given frequency. + Period.asfreq : Convert a :class:`~pandas.Period` object to the given frequency. + + Examples + -------- + >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='Y') + >>> pidx + PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'], + dtype='period[Y-DEC]') + + >>> pidx.asfreq('M') + PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12', + '2015-12'], dtype='period[M]') + + >>> pidx.asfreq('M', how='S') + PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01', + '2015-01'], dtype='period[M]') + """ + how = libperiod.validate_end_alias(how) + if isinstance(freq, BaseOffset) and hasattr(freq, "_period_dtype_code"): + freq = PeriodDtype(freq)._freqstr + freq = Period._maybe_convert_freq(freq) + + base1 = self._dtype._dtype_code + base2 = freq._period_dtype_code + + asi8 = self.asi8 + # self.freq.n can't be negative or 0 + end = how == "E" + if end: + ordinal = asi8 + self.dtype._n - 1 + else: + ordinal = asi8 + + new_data = period_asfreq_arr(ordinal, base1, base2, end) + + if self._hasna: + new_data[self._isnan] = iNaT + + dtype = PeriodDtype(freq) + return type(self)(new_data, dtype=dtype) + + # ------------------------------------------------------------------ + # Rendering Methods + + def _formatter(self, boxed: bool = False): + if boxed: + return str + return "'{}'".format + + def _format_native_types( + self, *, na_rep: str | float = "NaT", date_format=None, **kwargs + ) -> npt.NDArray[np.object_]: + """ + actually format my specific types + """ + return libperiod.period_array_strftime( + self.asi8, self.dtype._dtype_code, na_rep, date_format + ) + + # ------------------------------------------------------------------ + + def astype(self, dtype, copy: bool = True): + # We handle Period[T] -> Period[U] + # Our parent handles everything else. + dtype = pandas_dtype(dtype) + if dtype == self._dtype: + if not copy: + return self + else: + return self.copy() + if isinstance(dtype, PeriodDtype): + return self.asfreq(dtype.freq) + + if lib.is_np_dtype(dtype, "M") or isinstance(dtype, DatetimeTZDtype): + # GH#45038 match PeriodIndex behavior. + tz = getattr(dtype, "tz", None) + unit = dtl.dtype_to_unit(dtype) + return self.to_timestamp().tz_localize(tz).as_unit(unit) + + return super().astype(dtype, copy=copy) + + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter | None = None, + ) -> npt.NDArray[np.intp] | np.intp: + npvalue = self._validate_setitem_value(value).view("M8[ns]") + + # Cast to M8 to get datetime-like NaT placement, + # similar to dtl._period_dispatch + m8arr = self._ndarray.view("M8[ns]") + return m8arr.searchsorted(npvalue, side=side, sorter=sorter) + + def _pad_or_backfill( + self, + *, + method: FillnaOptions, + limit: int | None = None, + limit_area: Literal["inside", "outside"] | None = None, + copy: bool = True, + ) -> Self: + # view as dt64 so we get treated as timelike in core.missing, + # similar to dtl._period_dispatch + dta = self.view("M8[ns]") + result = dta._pad_or_backfill( + method=method, limit=limit, limit_area=limit_area, copy=copy + ) + if copy: + return cast("Self", result.view(self.dtype)) + else: + return self + + def fillna( + self, value=None, method=None, limit: int | None = None, copy: bool = True + ) -> Self: + if method is not None: + # view as dt64 so we get treated as timelike in core.missing, + # similar to dtl._period_dispatch + dta = self.view("M8[ns]") + result = dta.fillna(value=value, method=method, limit=limit, copy=copy) + # error: Incompatible return value type (got "Union[ExtensionArray, + # ndarray[Any, Any]]", expected "PeriodArray") + return result.view(self.dtype) # type: ignore[return-value] + return super().fillna(value=value, method=method, limit=limit, copy=copy) + + # ------------------------------------------------------------------ + # Arithmetic Methods + + def _addsub_int_array_or_scalar( + self, other: np.ndarray | int, op: Callable[[Any, Any], Any] + ) -> Self: + """ + Add or subtract array of integers. + + Parameters + ---------- + other : np.ndarray[int64] or int + op : {operator.add, operator.sub} + + Returns + ------- + result : PeriodArray + """ + assert op in [operator.add, operator.sub] + if op is operator.sub: + other = -other + res_values = add_overflowsafe(self.asi8, np.asarray(other, dtype="i8")) + return type(self)(res_values, dtype=self.dtype) + + def _add_offset(self, other: BaseOffset): + assert not isinstance(other, Tick) + + self._require_matching_freq(other, base=True) + return self._addsub_int_array_or_scalar(other.n, operator.add) + + # TODO: can we de-duplicate with Period._add_timedeltalike_scalar? + def _add_timedeltalike_scalar(self, other): + """ + Parameters + ---------- + other : timedelta, Tick, np.timedelta64 + + Returns + ------- + PeriodArray + """ + if not isinstance(self.freq, Tick): + # We cannot add timedelta-like to non-tick PeriodArray + raise raise_on_incompatible(self, other) + + if isna(other): + # i.e. np.timedelta64("NaT") + return super()._add_timedeltalike_scalar(other) + + td = np.asarray(Timedelta(other).asm8) + return self._add_timedelta_arraylike(td) + + def _add_timedelta_arraylike( + self, other: TimedeltaArray | npt.NDArray[np.timedelta64] + ) -> Self: + """ + Parameters + ---------- + other : TimedeltaArray or ndarray[timedelta64] + + Returns + ------- + PeriodArray + """ + if not self.dtype._is_tick_like(): + # We cannot add timedelta-like to non-tick PeriodArray + raise TypeError( + f"Cannot add or subtract timedelta64[ns] dtype from {self.dtype}" + ) + + dtype = np.dtype(f"m8[{self.dtype._td64_unit}]") + + # Similar to _check_timedeltalike_freq_compat, but we raise with a + # more specific exception message if necessary. + try: + delta = astype_overflowsafe( + np.asarray(other), dtype=dtype, copy=False, round_ok=False + ) + except ValueError as err: + # e.g. if we have minutes freq and try to add 30s + # "Cannot losslessly convert units" + raise IncompatibleFrequency( + "Cannot add/subtract timedelta-like from PeriodArray that is " + "not an integer multiple of the PeriodArray's freq." + ) from err + + res_values = add_overflowsafe(self.asi8, np.asarray(delta.view("i8"))) + return type(self)(res_values, dtype=self.dtype) + + def _check_timedeltalike_freq_compat(self, other): + """ + Arithmetic operations with timedelta-like scalars or array `other` + are only valid if `other` is an integer multiple of `self.freq`. + If the operation is valid, find that integer multiple. Otherwise, + raise because the operation is invalid. + + Parameters + ---------- + other : timedelta, np.timedelta64, Tick, + ndarray[timedelta64], TimedeltaArray, TimedeltaIndex + + Returns + ------- + multiple : int or ndarray[int64] + + Raises + ------ + IncompatibleFrequency + """ + assert self.dtype._is_tick_like() # checked by calling function + + dtype = np.dtype(f"m8[{self.dtype._td64_unit}]") + + if isinstance(other, (timedelta, np.timedelta64, Tick)): + td = np.asarray(Timedelta(other).asm8) + else: + td = np.asarray(other) + + try: + delta = astype_overflowsafe(td, dtype=dtype, copy=False, round_ok=False) + except ValueError as err: + raise raise_on_incompatible(self, other) from err + + delta = delta.view("i8") + return lib.item_from_zerodim(delta) + + +def raise_on_incompatible(left, right) -> IncompatibleFrequency: + """ + Helper function to render a consistent error message when raising + IncompatibleFrequency. + + Parameters + ---------- + left : PeriodArray + right : None, DateOffset, Period, ndarray, or timedelta-like + + Returns + ------- + IncompatibleFrequency + Exception to be raised by the caller. + """ + # GH#24283 error message format depends on whether right is scalar + if isinstance(right, (np.ndarray, ABCTimedeltaArray)) or right is None: + other_freq = None + elif isinstance(right, BaseOffset): + other_freq = freq_to_period_freqstr(right.n, right.name) + elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period)): + other_freq = right.freqstr + else: + other_freq = delta_to_tick(Timedelta(right)).freqstr + + own_freq = freq_to_period_freqstr(left.freq.n, left.freq.name) + msg = DIFFERENT_FREQ.format( + cls=type(left).__name__, own_freq=own_freq, other_freq=other_freq + ) + return IncompatibleFrequency(msg) + + +# ------------------------------------------------------------------- +# Constructor Helpers + + +def period_array( + data: Sequence[Period | str | None] | AnyArrayLike, + freq: str | Tick | BaseOffset | None = None, + copy: bool = False, +) -> PeriodArray: + """ + Construct a new PeriodArray from a sequence of Period scalars. + + Parameters + ---------- + data : Sequence of Period objects + A sequence of Period objects. These are required to all have + the same ``freq.`` Missing values can be indicated by ``None`` + or ``pandas.NaT``. + freq : str, Tick, or Offset + The frequency of every element of the array. This can be specified + to avoid inferring the `freq` from `data`. + copy : bool, default False + Whether to ensure a copy of the data is made. + + Returns + ------- + PeriodArray + + See Also + -------- + PeriodArray + pandas.PeriodIndex + + Examples + -------- + >>> period_array([pd.Period('2017', freq='Y'), + ... pd.Period('2018', freq='Y')]) + + ['2017', '2018'] + Length: 2, dtype: period[Y-DEC] + + >>> period_array([pd.Period('2017', freq='Y'), + ... pd.Period('2018', freq='Y'), + ... pd.NaT]) + + ['2017', '2018', 'NaT'] + Length: 3, dtype: period[Y-DEC] + + Integers that look like years are handled + + >>> period_array([2000, 2001, 2002], freq='D') + + ['2000-01-01', '2001-01-01', '2002-01-01'] + Length: 3, dtype: period[D] + + Datetime-like strings may also be passed + + >>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q') + + ['2000Q1', '2000Q2', '2000Q3', '2000Q4'] + Length: 4, dtype: period[Q-DEC] + """ + data_dtype = getattr(data, "dtype", None) + + if lib.is_np_dtype(data_dtype, "M"): + return PeriodArray._from_datetime64(data, freq) + if isinstance(data_dtype, PeriodDtype): + out = PeriodArray(data) + if freq is not None: + if freq == data_dtype.freq: + return out + return out.asfreq(freq) + return out + + # other iterable of some kind + if not isinstance(data, (np.ndarray, list, tuple, ABCSeries)): + data = list(data) + + arrdata = np.asarray(data) + + dtype: PeriodDtype | None + if freq: + dtype = PeriodDtype(freq) + else: + dtype = None + + if arrdata.dtype.kind == "f" and len(arrdata) > 0: + raise TypeError("PeriodIndex does not allow floating point in construction") + + if arrdata.dtype.kind in "iu": + arr = arrdata.astype(np.int64, copy=False) + # error: Argument 2 to "from_ordinals" has incompatible type "Union[str, + # Tick, None]"; expected "Union[timedelta, BaseOffset, str]" + ordinals = libperiod.from_ordinals(arr, freq) # type: ignore[arg-type] + return PeriodArray(ordinals, dtype=dtype) + + data = ensure_object(arrdata) + if freq is None: + freq = libperiod.extract_freq(data) + dtype = PeriodDtype(freq) + return PeriodArray._from_sequence(data, dtype=dtype) + + +@overload +def validate_dtype_freq(dtype, freq: BaseOffsetT) -> BaseOffsetT: + ... + + +@overload +def validate_dtype_freq(dtype, freq: timedelta | str | None) -> BaseOffset: + ... + + +def validate_dtype_freq( + dtype, freq: BaseOffsetT | BaseOffset | timedelta | str | None +) -> BaseOffsetT: + """ + If both a dtype and a freq are available, ensure they match. If only + dtype is available, extract the implied freq. + + Parameters + ---------- + dtype : dtype + freq : DateOffset or None + + Returns + ------- + freq : DateOffset + + Raises + ------ + ValueError : non-period dtype + IncompatibleFrequency : mismatch between dtype and freq + """ + if freq is not None: + freq = to_offset(freq, is_period=True) + + if dtype is not None: + dtype = pandas_dtype(dtype) + if not isinstance(dtype, PeriodDtype): + raise ValueError("dtype must be PeriodDtype") + if freq is None: + freq = dtype.freq + elif freq != dtype.freq: + raise IncompatibleFrequency("specified freq and dtype are different") + # error: Incompatible return value type (got "Union[BaseOffset, Any, None]", + # expected "BaseOffset") + return freq # type: ignore[return-value] + + +def dt64arr_to_periodarr( + data, freq, tz=None +) -> tuple[npt.NDArray[np.int64], BaseOffset]: + """ + Convert an datetime-like array to values Period ordinals. + + Parameters + ---------- + data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]] + freq : Optional[Union[str, Tick]] + Must match the `freq` on the `data` if `data` is a DatetimeIndex + or Series. + tz : Optional[tzinfo] + + Returns + ------- + ordinals : ndarray[int64] + freq : Tick + The frequency extracted from the Series or DatetimeIndex if that's + used. + + """ + if not isinstance(data.dtype, np.dtype) or data.dtype.kind != "M": + raise ValueError(f"Wrong dtype: {data.dtype}") + + if freq is None: + if isinstance(data, ABCIndex): + data, freq = data._values, data.freq + elif isinstance(data, ABCSeries): + data, freq = data._values, data.dt.freq + + elif isinstance(data, (ABCIndex, ABCSeries)): + data = data._values + + reso = get_unit_from_dtype(data.dtype) + freq = Period._maybe_convert_freq(freq) + base = freq._period_dtype_code + return c_dt64arr_to_periodarr(data.view("i8"), base, tz, reso=reso), freq + + +def _get_ordinal_range(start, end, periods, freq, mult: int = 1): + if com.count_not_none(start, end, periods) != 2: + raise ValueError( + "Of the three parameters: start, end, and periods, " + "exactly two must be specified" + ) + + if freq is not None: + freq = to_offset(freq, is_period=True) + mult = freq.n + + if start is not None: + start = Period(start, freq) + if end is not None: + end = Period(end, freq) + + is_start_per = isinstance(start, Period) + is_end_per = isinstance(end, Period) + + if is_start_per and is_end_per and start.freq != end.freq: + raise ValueError("start and end must have same freq") + if start is NaT or end is NaT: + raise ValueError("start and end must not be NaT") + + if freq is None: + if is_start_per: + freq = start.freq + elif is_end_per: + freq = end.freq + else: # pragma: no cover + raise ValueError("Could not infer freq from start/end") + mult = freq.n + + if periods is not None: + periods = periods * mult + if start is None: + data = np.arange( + end.ordinal - periods + mult, end.ordinal + 1, mult, dtype=np.int64 + ) + else: + data = np.arange( + start.ordinal, start.ordinal + periods, mult, dtype=np.int64 + ) + else: + data = np.arange(start.ordinal, end.ordinal + 1, mult, dtype=np.int64) + + return data, freq + + +def _range_from_fields( + year=None, + month=None, + quarter=None, + day=None, + hour=None, + minute=None, + second=None, + freq=None, +) -> tuple[np.ndarray, BaseOffset]: + if hour is None: + hour = 0 + if minute is None: + minute = 0 + if second is None: + second = 0 + if day is None: + day = 1 + + ordinals = [] + + if quarter is not None: + if freq is None: + freq = to_offset("Q", is_period=True) + base = FreqGroup.FR_QTR.value + else: + freq = to_offset(freq, is_period=True) + base = libperiod.freq_to_dtype_code(freq) + if base != FreqGroup.FR_QTR.value: + raise AssertionError("base must equal FR_QTR") + + freqstr = freq.freqstr + year, quarter = _make_field_arrays(year, quarter) + for y, q in zip(year, quarter): + calendar_year, calendar_month = parsing.quarter_to_myear(y, q, freqstr) + val = libperiod.period_ordinal( + calendar_year, calendar_month, 1, 1, 1, 1, 0, 0, base + ) + ordinals.append(val) + else: + freq = to_offset(freq, is_period=True) + base = libperiod.freq_to_dtype_code(freq) + arrays = _make_field_arrays(year, month, day, hour, minute, second) + for y, mth, d, h, mn, s in zip(*arrays): + ordinals.append(libperiod.period_ordinal(y, mth, d, h, mn, s, 0, 0, base)) + + return np.array(ordinals, dtype=np.int64), freq + + +def _make_field_arrays(*fields) -> list[np.ndarray]: + length = None + for x in fields: + if isinstance(x, (list, np.ndarray, ABCSeries)): + if length is not None and len(x) != length: + raise ValueError("Mismatched Period array lengths") + if length is None: + length = len(x) + + # error: Argument 2 to "repeat" has incompatible type "Optional[int]"; expected + # "Union[Union[int, integer[Any]], Union[bool, bool_], ndarray, Sequence[Union[int, + # integer[Any]]], Sequence[Union[bool, bool_]], Sequence[Sequence[Any]]]" + return [ + np.asarray(x) + if isinstance(x, (np.ndarray, list, ABCSeries)) + else np.repeat(x, length) # type: ignore[arg-type] + for x in fields + ] diff --git a/shared/package-files/56/5668580ce550f79698302dbd6a39bd6bef6e852c6e0b0d60666fb6d70b533c39/remainder_native.h b/shared/package-files/56/5668580ce550f79698302dbd6a39bd6bef6e852c6e0b0d60666fb6d70b533c39/remainder_native.h new file mode 100644 index 0000000000000000000000000000000000000000..a86cfee57b39a8f330e2ad0effbdc36e4cad57bf --- /dev/null +++ b/shared/package-files/56/5668580ce550f79698302dbd6a39bd6bef6e852c6e0b0d60666fb6d70b533c39/remainder_native.h @@ -0,0 +1,28 @@ +#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 at::Tensor remainder(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & remainder_out(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & remainder_(at::Tensor & self, const at::Scalar & other); +struct TORCH_API structured_remainder_out : public at::meta::structured_remainder_Tensor { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out); +}; +TORCH_API at::Tensor & remainder_Scalar_Tensor_out(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor remainder(const at::Scalar & self, const at::Tensor & other); +} // namespace native +} // namespace at diff --git a/shared/package-files/56/566b5dbaa8c09b9da0833a776ff9f8a23e6c1920c787c9a45b1e94e42667c9a1/vt220-base b/shared/package-files/56/566b5dbaa8c09b9da0833a776ff9f8a23e6c1920c787c9a45b1e94e42667c9a1/vt220-base new file mode 100644 index 0000000000000000000000000000000000000000..d094ba5bd51cba847a648ed86d1d329f4abbb1dd Binary files /dev/null and b/shared/package-files/56/566b5dbaa8c09b9da0833a776ff9f8a23e6c1920c787c9a45b1e94e42667c9a1/vt220-base differ diff --git a/shared/package-files/56/566ba90b67b3511de9e6d819c74aea5c41c0b73b229015b6620688c6e1b03b90/test_pdtr.py b/shared/package-files/56/566ba90b67b3511de9e6d819c74aea5c41c0b73b229015b6620688c6e1b03b90/test_pdtr.py new file mode 100644 index 0000000000000000000000000000000000000000..122e6009bd71e77ae39f55da5cf056500ff526a9 --- /dev/null +++ b/shared/package-files/56/566ba90b67b3511de9e6d819c74aea5c41c0b73b229015b6620688c6e1b03b90/test_pdtr.py @@ -0,0 +1,48 @@ +import numpy as np +import scipy.special as sc +from numpy.testing import assert_almost_equal, assert_array_equal + + +class TestPdtr: + def test(self): + val = sc.pdtr(0, 1) + assert_almost_equal(val, np.exp(-1)) + + def test_m_zero(self): + val = sc.pdtr([0, 1, 2], 0) + assert_array_equal(val, [1, 1, 1]) + + def test_rounding(self): + double_val = sc.pdtr([0.1, 1.1, 2.1], 1.0) + int_val = sc.pdtr([0, 1, 2], 1.0) + assert_array_equal(double_val, int_val) + + def test_inf(self): + val = sc.pdtr(np.inf, 1.0) + assert_almost_equal(val, 1.0) + + def test_domain(self): + val = sc.pdtr(-1.1, 1.0) + assert np.isnan(val) + +class TestPdtrc: + def test_value(self): + val = sc.pdtrc(0, 1) + assert_almost_equal(val, 1 - np.exp(-1)) + + def test_m_zero(self): + val = sc.pdtrc([0, 1, 2], 0.0) + assert_array_equal(val, [0, 0, 0]) + + def test_rounding(self): + double_val = sc.pdtrc([0.1, 1.1, 2.1], 1.0) + int_val = sc.pdtrc([0, 1, 2], 1.0) + assert_array_equal(double_val, int_val) + + def test_inf(self): + val = sc.pdtrc(np.inf, 1.0) + assert_almost_equal(val, 0.0) + + def test_domain(self): + val = sc.pdtrc(-1.1, 1.0) + assert np.isnan(val) diff --git a/shared/package-files/56/5671ef63dc847a761de43990d44f0adf2a1c63bb645ca2ccc91572047585290f/hardsigmoid_backward.h b/shared/package-files/56/5671ef63dc847a761de43990d44f0adf2a1c63bb645ca2ccc91572047585290f/hardsigmoid_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..4ca467b9ad64eddbc8f625230c5562da65a151d0 --- /dev/null +++ b/shared/package-files/56/5671ef63dc847a761de43990d44f0adf2a1c63bb645ca2ccc91572047585290f/hardsigmoid_backward.h @@ -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::hardsigmoid_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & hardsigmoid_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self) { + return at::_ops::hardsigmoid_backward_grad_input::call(grad_output, self, grad_input); +} +// aten::hardsigmoid_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & hardsigmoid_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::Tensor & grad_input) { + return at::_ops::hardsigmoid_backward_grad_input::call(grad_output, self, grad_input); +} + +// aten::hardsigmoid_backward(Tensor grad_output, Tensor self) -> Tensor +inline at::Tensor hardsigmoid_backward(const at::Tensor & grad_output, const at::Tensor & self) { + return at::_ops::hardsigmoid_backward::call(grad_output, self); +} + +} diff --git a/shared/package-files/56/56776b6c7cc73dd2e4e9440d69b498eb8cfc1ea9060f46d201317014d5e1578f/structured.py b/shared/package-files/56/56776b6c7cc73dd2e4e9440d69b498eb8cfc1ea9060f46d201317014d5e1578f/structured.py new file mode 100644 index 0000000000000000000000000000000000000000..c8ac982cf1df2b85cb0fd201078a7211e58aeeb0 --- /dev/null +++ b/shared/package-files/56/56776b6c7cc73dd2e4e9440d69b498eb8cfc1ea9060f46d201317014d5e1578f/structured.py @@ -0,0 +1,37 @@ +""" +Utilities for converting data types into structured JSON for dumping. +""" + +import traceback +from typing import Dict, Sequence + +import torch._logging._internal + + +INTERN_TABLE: Dict[str, int] = {} + + +def intern_string(s: str) -> int: + r = INTERN_TABLE.get(s, None) + if r is None: + r = len(INTERN_TABLE) + INTERN_TABLE[s] = r + torch._logging._internal.trace_structured( + "str", lambda: (s, r), suppress_context=True + ) + return r + + +def from_traceback(tb: Sequence[traceback.FrameSummary]) -> object: + r = [] + for frame in tb: + # dict naming convention here coincides with + # python/combined_traceback.cpp + r.append( + { + "line": frame.lineno, + "name": frame.name, + "filename": intern_string(frame.filename), + } + ) + return r diff --git a/shared/package-files/56/567860b355d9addfdc00ab699b9aaecd043bd9596368d37ab70148b6b21a73c7/upsample_nearest2d_native.h b/shared/package-files/56/567860b355d9addfdc00ab699b9aaecd043bd9596368d37ab70148b6b21a73c7/upsample_nearest2d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..3b35319b6b3a9eed962f1b5adc3e1a6845a18f17 --- /dev/null +++ b/shared/package-files/56/567860b355d9addfdc00ab699b9aaecd043bd9596368d37ab70148b6b21a73c7/upsample_nearest2d_native.h @@ -0,0 +1,28 @@ +#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 at::Tensor upsample_nearest2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, c10::optional> scale_factors); +struct TORCH_API structured_upsample_nearest2d_out_cpu : public at::meta::structured_upsample_nearest2d { +void impl(const at::Tensor & self, at::ArrayRef output_size, c10::optional scales_h, c10::optional scales_w, const at::Tensor & out); +}; +struct TORCH_API structured_upsample_nearest2d_out_cuda : public at::meta::structured_upsample_nearest2d { +void impl(const at::Tensor & self, at::ArrayRef output_size, c10::optional scales_h, c10::optional scales_w, const at::Tensor & out); +}; +TORCH_API at::Tensor upsample_nearest2d_quantized_cpu(const at::Tensor & self, at::IntArrayRef output_size, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/56/5678e80e6cb4a4a428b9b5d740943f3258e80d88b515c2dd35907628dfd3408b/plain_text.py b/shared/package-files/56/5678e80e6cb4a4a428b9b5d740943f3258e80d88b515c2dd35907628dfd3408b/plain_text.py new file mode 100644 index 0000000000000000000000000000000000000000..4b24ad960e4f2359e0363a216ad91a00d2910d24 --- /dev/null +++ b/shared/package-files/56/5678e80e6cb4a4a428b9b5d740943f3258e80d88b515c2dd35907628dfd3408b/plain_text.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +from typing import TextIO + +from prompt_toolkit.cursor_shapes import CursorShape +from prompt_toolkit.data_structures import Size +from prompt_toolkit.styles import Attrs + +from .base import Output +from .color_depth import ColorDepth +from .flush_stdout import flush_stdout + +__all__ = ["PlainTextOutput"] + + +class PlainTextOutput(Output): + """ + Output that won't include any ANSI escape sequences. + + Useful when stdout is not a terminal. Maybe stdout is redirected to a file. + In this case, if `print_formatted_text` is used, for instance, we don't + want to include formatting. + + (The code is mostly identical to `Vt100_Output`, but without the + formatting.) + """ + + def __init__(self, stdout: TextIO) -> None: + assert all(hasattr(stdout, a) for a in ("write", "flush")) + + self.stdout: TextIO = stdout + self._buffer: list[str] = [] + + def fileno(self) -> int: + "There is no sensible default for fileno()." + return self.stdout.fileno() + + def encoding(self) -> str: + return "utf-8" + + def write(self, data: str) -> None: + self._buffer.append(data) + + def write_raw(self, data: str) -> None: + self._buffer.append(data) + + def set_title(self, title: str) -> None: + pass + + def clear_title(self) -> None: + pass + + def flush(self) -> None: + if not self._buffer: + return + + data = "".join(self._buffer) + self._buffer = [] + flush_stdout(self.stdout, data) + + def erase_screen(self) -> None: + pass + + def enter_alternate_screen(self) -> None: + pass + + def quit_alternate_screen(self) -> None: + pass + + def enable_mouse_support(self) -> None: + pass + + def disable_mouse_support(self) -> None: + pass + + def erase_end_of_line(self) -> None: + pass + + def erase_down(self) -> None: + pass + + def reset_attributes(self) -> None: + pass + + def set_attributes(self, attrs: Attrs, color_depth: ColorDepth) -> None: + pass + + def disable_autowrap(self) -> None: + pass + + def enable_autowrap(self) -> None: + pass + + def cursor_goto(self, row: int = 0, column: int = 0) -> None: + pass + + def cursor_up(self, amount: int) -> None: + pass + + def cursor_down(self, amount: int) -> None: + self._buffer.append("\n") + + def cursor_forward(self, amount: int) -> None: + self._buffer.append(" " * amount) + + def cursor_backward(self, amount: int) -> None: + pass + + def hide_cursor(self) -> None: + pass + + def show_cursor(self) -> None: + pass + + def set_cursor_shape(self, cursor_shape: CursorShape) -> None: + pass + + def reset_cursor_shape(self) -> None: + pass + + def ask_for_cpr(self) -> None: + pass + + def bell(self) -> None: + pass + + def enable_bracketed_paste(self) -> None: + pass + + def disable_bracketed_paste(self) -> None: + pass + + def scroll_buffer_to_prompt(self) -> None: + pass + + def get_size(self) -> Size: + return Size(rows=40, columns=80) + + def get_rows_below_cursor_position(self) -> int: + return 8 + + def get_default_color_depth(self) -> ColorDepth: + return ColorDepth.DEPTH_1_BIT diff --git a/shared/package-files/56/567c18af9293fc52ca7dcd3057b76d373edb36d682f55210b7ea33e7a1dbe441/ufuncs.pyi b/shared/package-files/56/567c18af9293fc52ca7dcd3057b76d373edb36d682f55210b7ea33e7a1dbe441/ufuncs.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5f7d99efd12d3052e5442238bf826d13b5acf6b3 --- /dev/null +++ b/shared/package-files/56/567c18af9293fc52ca7dcd3057b76d373edb36d682f55210b7ea33e7a1dbe441/ufuncs.pyi @@ -0,0 +1,76 @@ +import sys +from typing import Literal, 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 + +f8: np.float64 +AR_f8: npt.NDArray[np.float64] +AR_i8: npt.NDArray[np.int64] + +assert_type(np.absolute.__doc__, str) +assert_type(np.absolute.types, list[str]) + +assert_type(np.absolute.__name__, Literal["absolute"]) +assert_type(np.absolute.ntypes, Literal[20]) +assert_type(np.absolute.identity, None) +assert_type(np.absolute.nin, Literal[1]) +assert_type(np.absolute.nin, Literal[1]) +assert_type(np.absolute.nout, Literal[1]) +assert_type(np.absolute.nargs, Literal[2]) +assert_type(np.absolute.signature, None) +assert_type(np.absolute(f8), Any) +assert_type(np.absolute(AR_f8), npt.NDArray[Any]) +assert_type(np.absolute.at(AR_f8, AR_i8), None) + +assert_type(np.add.__name__, Literal["add"]) +assert_type(np.add.ntypes, Literal[22]) +assert_type(np.add.identity, Literal[0]) +assert_type(np.add.nin, Literal[2]) +assert_type(np.add.nout, Literal[1]) +assert_type(np.add.nargs, Literal[3]) +assert_type(np.add.signature, None) +assert_type(np.add(f8, f8), Any) +assert_type(np.add(AR_f8, f8), npt.NDArray[Any]) +assert_type(np.add.at(AR_f8, AR_i8, f8), None) +assert_type(np.add.reduce(AR_f8, axis=0), Any) +assert_type(np.add.accumulate(AR_f8), npt.NDArray[Any]) +assert_type(np.add.reduceat(AR_f8, AR_i8), npt.NDArray[Any]) +assert_type(np.add.outer(f8, f8), Any) +assert_type(np.add.outer(AR_f8, f8), npt.NDArray[Any]) + +assert_type(np.frexp.__name__, Literal["frexp"]) +assert_type(np.frexp.ntypes, Literal[4]) +assert_type(np.frexp.identity, None) +assert_type(np.frexp.nin, Literal[1]) +assert_type(np.frexp.nout, Literal[2]) +assert_type(np.frexp.nargs, Literal[3]) +assert_type(np.frexp.signature, None) +assert_type(np.frexp(f8), tuple[Any, Any]) +assert_type(np.frexp(AR_f8), tuple[npt.NDArray[Any], npt.NDArray[Any]]) + +assert_type(np.divmod.__name__, Literal["divmod"]) +assert_type(np.divmod.ntypes, Literal[15]) +assert_type(np.divmod.identity, None) +assert_type(np.divmod.nin, Literal[2]) +assert_type(np.divmod.nout, Literal[2]) +assert_type(np.divmod.nargs, Literal[4]) +assert_type(np.divmod.signature, None) +assert_type(np.divmod(f8, f8), tuple[Any, Any]) +assert_type(np.divmod(AR_f8, f8), tuple[npt.NDArray[Any], npt.NDArray[Any]]) + +assert_type(np.matmul.__name__, Literal["matmul"]) +assert_type(np.matmul.ntypes, Literal[19]) +assert_type(np.matmul.identity, None) +assert_type(np.matmul.nin, Literal[2]) +assert_type(np.matmul.nout, Literal[1]) +assert_type(np.matmul.nargs, Literal[3]) +assert_type(np.matmul.signature, Literal["(n?,k),(k,m?)->(n?,m?)"]) +assert_type(np.matmul.identity, None) +assert_type(np.matmul(AR_f8, AR_f8), Any) +assert_type(np.matmul(AR_f8, AR_f8, axes=[(0, 1), (0, 1), (0, 1)]), Any) diff --git a/shared/package-files/56/567fc4fab7b1b7393e5c62e307301256d390d2032be9c259138681d2f7ae7461/libhistory.a b/shared/package-files/56/567fc4fab7b1b7393e5c62e307301256d390d2032be9c259138681d2f7ae7461/libhistory.a new file mode 100644 index 0000000000000000000000000000000000000000..d2b9723e36fb0fcc3592dacf19ad10481b79a3d2 Binary files /dev/null and b/shared/package-files/56/567fc4fab7b1b7393e5c62e307301256d390d2032be9c259138681d2f7ae7461/libhistory.a differ diff --git a/shared/package-files/56/5684b25c17c6d8db80a8777f58045eed41f57aaabd8da3b9be28d130d9370054/ec.pyi b/shared/package-files/56/5684b25c17c6d8db80a8777f58045eed41f57aaabd8da3b9be28d130d9370054/ec.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cfdd031fa27b5299780f7227b5d4b27f0deacc35 --- /dev/null +++ b/shared/package-files/56/5684b25c17c6d8db80a8777f58045eed41f57aaabd8da3b9be28d130d9370054/ec.pyi @@ -0,0 +1,196 @@ +from abc import ABCMeta, abstractmethod +from typing import ClassVar, Optional, Union + +from cryptography.hazmat.backends.interfaces import EllipticCurveBackend +from cryptography.hazmat.primitives.asymmetric import AsymmetricVerificationContext +from cryptography.hazmat.primitives.asymmetric.utils import Prehashed +from cryptography.hazmat.primitives.hashes import HashAlgorithm +from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat +from cryptography.x509 import ObjectIdentifier + +class EllipticCurve(metaclass=ABCMeta): + @property + @abstractmethod + def key_size(self) -> int: ... + @property + @abstractmethod + def name(self) -> str: ... + +class BrainpoolP256R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class BrainpoolP384R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class BrainpoolP512R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECP192R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECP224R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECP256K1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECP256R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECP384R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECP521R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT163K1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT163R2(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT233K1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT233R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT283K1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT283R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT409K1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT409R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT571K1(EllipticCurve): + key_size: int = ... + name: str = ... + +class SECT571R1(EllipticCurve): + key_size: int = ... + name: str = ... + +class EllipticCurveOID(object): + SECP192R1: ClassVar[ObjectIdentifier] + SECP224R1: ClassVar[ObjectIdentifier] + SECP256K1: ClassVar[ObjectIdentifier] + SECP256R1: ClassVar[ObjectIdentifier] + SECP384R1: ClassVar[ObjectIdentifier] + SECP521R1: ClassVar[ObjectIdentifier] + BRAINPOOLP256R1: ClassVar[ObjectIdentifier] + BRAINPOOLP384R1: ClassVar[ObjectIdentifier] + BRAINPOOLP512R1: ClassVar[ObjectIdentifier] + SECT163K1: ClassVar[ObjectIdentifier] + SECT163R2: ClassVar[ObjectIdentifier] + SECT233K1: ClassVar[ObjectIdentifier] + SECT233R1: ClassVar[ObjectIdentifier] + SECT283K1: ClassVar[ObjectIdentifier] + SECT283R1: ClassVar[ObjectIdentifier] + SECT409K1: ClassVar[ObjectIdentifier] + SECT409R1: ClassVar[ObjectIdentifier] + SECT571K1: ClassVar[ObjectIdentifier] + SECT571R1: ClassVar[ObjectIdentifier] + +class EllipticCurvePrivateKey(metaclass=ABCMeta): + @property + @abstractmethod + def curve(self) -> EllipticCurve: ... + @property + @abstractmethod + def key_size(self) -> int: ... + @abstractmethod + def exchange(self, algorithm: ECDH, peer_public_key: EllipticCurvePublicKey) -> bytes: ... + @abstractmethod + def public_key(self) -> EllipticCurvePublicKey: ... + @abstractmethod + def sign(self, data: bytes, signature_algorithm: EllipticCurveSignatureAlgorithm) -> bytes: ... + +class EllipticCurvePrivateKeyWithSerialization(EllipticCurvePrivateKey): + @abstractmethod + def private_bytes( + self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption + ) -> bytes: ... + @abstractmethod + def private_numbers(self) -> EllipticCurvePrivateNumbers: ... + +class EllipticCurvePrivateNumbers(object): + @property + def private_value(self) -> int: ... + @property + def public_numbers(self) -> EllipticCurvePublicNumbers: ... + def __init__(self, private_value: int, public_numbers: EllipticCurvePublicNumbers) -> None: ... + def private_key(self, backend: Optional[EllipticCurveBackend] = ...) -> EllipticCurvePrivateKey: ... + +class EllipticCurvePublicKey(metaclass=ABCMeta): + @property + @abstractmethod + def curve(self) -> EllipticCurve: ... + @property + @abstractmethod + def key_size(self) -> int: ... + @classmethod + def from_encoded_point(cls, curve: EllipticCurve, data: bytes) -> EllipticCurvePublicKey: ... + @abstractmethod + def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... + @abstractmethod + def public_numbers(self) -> EllipticCurvePublicNumbers: ... + @abstractmethod + def verifier( + self, signature: bytes, signature_algorithm: EllipticCurveSignatureAlgorithm + ) -> AsymmetricVerificationContext: ... + @abstractmethod + def verify(self, signature: bytes, data: bytes, signature_algorithm: EllipticCurveSignatureAlgorithm) -> None: ... + +EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey + +class EllipticCurvePublicNumbers(object): + @property + def curve(self) -> EllipticCurve: ... + @property + def x(self) -> int: ... + @property + def y(self) -> int: ... + def __init__(self, x: int, y: int, curve: EllipticCurve) -> None: ... + @classmethod + def from_encoded_point(cls, curve: EllipticCurve, data: bytes) -> EllipticCurvePublicNumbers: ... + def public_key(self, backend: Optional[EllipticCurveBackend] = ...) -> EllipticCurvePublicKey: ... + +class EllipticCurveSignatureAlgorithm(metaclass=ABCMeta): + @property + @abstractmethod + def algorithm(self) -> Union[HashAlgorithm, Prehashed]: ... + +class ECDH(object): ... + +class ECDSA(EllipticCurveSignatureAlgorithm): + def __init__(self, algorithm: Union[HashAlgorithm, Prehashed]): ... + @property + def algorithm(self) -> Union[HashAlgorithm, Prehashed]: ... + +def derive_private_key( + private_value: int, curve: EllipticCurve, backend: Optional[EllipticCurveBackend] = ... +) -> EllipticCurvePrivateKey: ... +def generate_private_key(curve: EllipticCurve, backend: Optional[EllipticCurveBackend] = ...) -> EllipticCurvePrivateKey: ... +def get_curve_for_oid(oid: ObjectIdentifier) -> EllipticCurve: ... diff --git a/shared/package-files/56/5684c82cd0eb516bd9c742caf7ff7b9412d014ab521a60ede102ce1fccd8be5a/__init__.py b/shared/package-files/56/5684c82cd0eb516bd9c742caf7ff7b9412d014ab521a60ede102ce1fccd8be5a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cf02fe868b04d3fd1ff145e57332475d7466b57 --- /dev/null +++ b/shared/package-files/56/5684c82cd0eb516bd9c742caf7ff7b9412d014ab521a60ede102ce1fccd8be5a/__init__.py @@ -0,0 +1,175 @@ +""" +============================ +Typing (:mod:`numpy.typing`) +============================ + +.. versionadded:: 1.20 + +Large parts of the NumPy API have :pep:`484`-style type annotations. In +addition a number of type aliases are available to users, most prominently +the two below: + +- `ArrayLike`: objects that can be converted to arrays +- `DTypeLike`: objects that can be converted to dtypes + +.. _typing-extensions: https://pypi.org/project/typing-extensions/ + +Mypy plugin +----------- + +.. versionadded:: 1.21 + +.. automodule:: numpy.typing.mypy_plugin + +.. currentmodule:: numpy.typing + +Differences from the runtime NumPy API +-------------------------------------- + +NumPy is very flexible. Trying to describe the full range of +possibilities statically would result in types that are not very +helpful. For that reason, the typed NumPy API is often stricter than +the runtime NumPy API. This section describes some notable +differences. + +ArrayLike +~~~~~~~~~ + +The `ArrayLike` type tries to avoid creating object arrays. For +example, + +.. code-block:: python + + >>> np.array(x**2 for x in range(10)) + array( at ...>, dtype=object) + +is valid NumPy code which will create a 0-dimensional object +array. Type checkers will complain about the above example when using +the NumPy types however. If you really intended to do the above, then +you can either use a ``# type: ignore`` comment: + +.. code-block:: python + + >>> np.array(x**2 for x in range(10)) # type: ignore + +or explicitly type the array like object as `~typing.Any`: + +.. code-block:: python + + >>> from typing import Any + >>> array_like: Any = (x**2 for x in range(10)) + >>> np.array(array_like) + array( at ...>, dtype=object) + +ndarray +~~~~~~~ + +It's possible to mutate the dtype of an array at runtime. For example, +the following code is valid: + +.. code-block:: python + + >>> x = np.array([1, 2]) + >>> x.dtype = np.bool_ + +This sort of mutation is not allowed by the types. Users who want to +write statically typed code should instead use the `numpy.ndarray.view` +method to create a view of the array with a different dtype. + +DTypeLike +~~~~~~~~~ + +The `DTypeLike` type tries to avoid creation of dtype objects using +dictionary of fields like below: + +.. code-block:: python + + >>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)}) + +Although this is valid NumPy code, the type checker will complain about it, +since its usage is discouraged. +Please see : :ref:`Data type objects ` + +Number precision +~~~~~~~~~~~~~~~~ + +The precision of `numpy.number` subclasses is treated as a covariant generic +parameter (see :class:`~NBitBase`), simplifying the annotating of processes +involving precision-based casting. + +.. code-block:: python + + >>> from typing import TypeVar + >>> import numpy as np + >>> import numpy.typing as npt + + >>> T = TypeVar("T", bound=npt.NBitBase) + >>> def func(a: "np.floating[T]", b: "np.floating[T]") -> "np.floating[T]": + ... ... + +Consequently, the likes of `~numpy.float16`, `~numpy.float32` and +`~numpy.float64` are still sub-types of `~numpy.floating`, but, contrary to +runtime, they're not necessarily considered as sub-classes. + +Timedelta64 +~~~~~~~~~~~ + +The `~numpy.timedelta64` class is not considered a subclass of +`~numpy.signedinteger`, the former only inheriting from `~numpy.generic` +while static type checking. + +0D arrays +~~~~~~~~~ + +During runtime numpy aggressively casts any passed 0D arrays into their +corresponding `~numpy.generic` instance. Until the introduction of shape +typing (see :pep:`646`) it is unfortunately not possible to make the +necessary distinction between 0D and >0D arrays. While thus not strictly +correct, all operations are that can potentially perform a 0D-array -> scalar +cast are currently annotated as exclusively returning an `ndarray`. + +If it is known in advance that an operation _will_ perform a +0D-array -> scalar cast, then one can consider manually remedying the +situation with either `typing.cast` or a ``# type: ignore`` comment. + +Record array dtypes +~~~~~~~~~~~~~~~~~~~ + +The dtype of `numpy.recarray`, and the `numpy.rec` functions in general, +can be specified in one of two ways: + +* Directly via the ``dtype`` argument. +* With up to five helper arguments that operate via `numpy.format_parser`: + ``formats``, ``names``, ``titles``, ``aligned`` and ``byteorder``. + +These two approaches are currently typed as being mutually exclusive, +*i.e.* if ``dtype`` is specified than one may not specify ``formats``. +While this mutual exclusivity is not (strictly) enforced during runtime, +combining both dtype specifiers can lead to unexpected or even downright +buggy behavior. + +API +--- + +""" +# NOTE: The API section will be appended with additional entries +# further down in this file + +from numpy._typing import ( + ArrayLike, + DTypeLike, + NBitBase, + NDArray, +) + +__all__ = ["ArrayLike", "DTypeLike", "NBitBase", "NDArray"] + +if __doc__ is not None: + from numpy._typing._add_docstring import _docstrings + __doc__ += _docstrings + __doc__ += '\n.. autoclass:: numpy.typing.NBitBase\n' + del _docstrings + +from numpy._pytesttester import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/shared/package-files/56/56851e6586b568ee6b53af5d0e9bf839be45398cabde79be789de6d24bad8b45/objective.py b/shared/package-files/56/56851e6586b568ee6b53af5d0e9bf839be45398cabde79be789de6d24bad8b45/objective.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4332adfa216bb42f3726d1c6be0a238844b5ae --- /dev/null +++ b/shared/package-files/56/56851e6586b568ee6b53af5d0e9bf839be45398cabde79be789de6d24bad8b45/objective.py @@ -0,0 +1,505 @@ +""" + pygments.lexers.objective + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for Objective-C family languages. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.lexer import RegexLexer, include, bygroups, using, this, words, \ + inherit, default +from pygments.token import Text, Keyword, Name, String, Operator, \ + Number, Punctuation, Literal, Comment + +from pygments.lexers.c_cpp import CLexer, CppLexer + +__all__ = ['ObjectiveCLexer', 'ObjectiveCppLexer', 'LogosLexer', 'SwiftLexer'] + + +def objective(baselexer): + """ + Generate a subclass of baselexer that accepts the Objective-C syntax + extensions. + """ + + # Have to be careful not to accidentally match JavaDoc/Doxygen syntax here, + # since that's quite common in ordinary C/C++ files. It's OK to match + # JavaDoc/Doxygen keywords that only apply to Objective-C, mind. + # + # The upshot of this is that we CANNOT match @class or @interface + _oc_keywords = re.compile(r'@(?:end|implementation|protocol)') + + # Matches [ ? identifier ( identifier ? ] | identifier? : ) + # (note the identifier is *optional* when there is a ':'!) + _oc_message = re.compile(r'\[\s*[a-zA-Z_]\w*\s+' + r'(?:[a-zA-Z_]\w*\s*\]|' + r'(?:[a-zA-Z_]\w*)?:)') + + class GeneratedObjectiveCVariant(baselexer): + """ + Implements Objective-C syntax on top of an existing C family lexer. + """ + + tokens = { + 'statements': [ + (r'@"', String, 'string'), + (r'@(YES|NO)', Number), + (r"@'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), + (r'@(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float), + (r'@(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), + (r'@0x[0-9a-fA-F]+[Ll]?', Number.Hex), + (r'@0[0-7]+[Ll]?', Number.Oct), + (r'@\d+[Ll]?', Number.Integer), + (r'@\(', Literal, 'literal_number'), + (r'@\[', Literal, 'literal_array'), + (r'@\{', Literal, 'literal_dictionary'), + (words(( + '@selector', '@private', '@protected', '@public', '@encode', + '@synchronized', '@try', '@throw', '@catch', '@finally', + '@end', '@property', '@synthesize', '__bridge', '__bridge_transfer', + '__autoreleasing', '__block', '__weak', '__strong', 'weak', 'strong', + 'copy', 'retain', 'assign', 'unsafe_unretained', 'atomic', 'nonatomic', + 'readonly', 'readwrite', 'setter', 'getter', 'typeof', 'in', + 'out', 'inout', 'release', 'class', '@dynamic', '@optional', + '@required', '@autoreleasepool', '@import'), suffix=r'\b'), + Keyword), + (words(('id', 'instancetype', 'Class', 'IMP', 'SEL', 'BOOL', + 'IBOutlet', 'IBAction', 'unichar'), suffix=r'\b'), + Keyword.Type), + (r'@(true|false|YES|NO)\n', Name.Builtin), + (r'(YES|NO|nil|self|super)\b', Name.Builtin), + # Carbon types + (r'(Boolean|UInt8|SInt8|UInt16|SInt16|UInt32|SInt32)\b', Keyword.Type), + # Carbon built-ins + (r'(TRUE|FALSE)\b', Name.Builtin), + (r'(@interface|@implementation)(\s+)', bygroups(Keyword, Text), + ('#pop', 'oc_classname')), + (r'(@class|@protocol)(\s+)', bygroups(Keyword, Text), + ('#pop', 'oc_forward_classname')), + # @ can also prefix other expressions like @{...} or @(...) + (r'@', Punctuation), + inherit, + ], + 'oc_classname': [ + # interface definition that inherits + (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?(\s*)(\{)', + bygroups(Name.Class, Text, Name.Class, Text, Punctuation), + ('#pop', 'oc_ivars')), + (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?', + bygroups(Name.Class, Text, Name.Class), '#pop'), + # interface definition for a category + (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))(\s*)(\{)', + bygroups(Name.Class, Text, Name.Label, Text, Punctuation), + ('#pop', 'oc_ivars')), + (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))', + bygroups(Name.Class, Text, Name.Label), '#pop'), + # simple interface / implementation + (r'([a-zA-Z$_][\w$]*)(\s*)(\{)', + bygroups(Name.Class, Text, Punctuation), ('#pop', 'oc_ivars')), + (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop') + ], + 'oc_forward_classname': [ + (r'([a-zA-Z$_][\w$]*)(\s*,\s*)', + bygroups(Name.Class, Text), 'oc_forward_classname'), + (r'([a-zA-Z$_][\w$]*)(\s*;?)', + bygroups(Name.Class, Text), '#pop') + ], + 'oc_ivars': [ + include('whitespace'), + include('statements'), + (';', Punctuation), + (r'\{', Punctuation, '#push'), + (r'\}', Punctuation, '#pop'), + ], + 'root': [ + # methods + (r'^([-+])(\s*)' # method marker + r'(\(.*?\))?(\s*)' # return type + r'([a-zA-Z$_][\w$]*:?)', # begin of method name + bygroups(Punctuation, Text, using(this), + Text, Name.Function), + 'method'), + inherit, + ], + 'method': [ + include('whitespace'), + # TODO unsure if ellipses are allowed elsewhere, see + # discussion in Issue 789 + (r',', Punctuation), + (r'\.\.\.', Punctuation), + (r'(\(.*?\))(\s*)([a-zA-Z$_][\w$]*)', + bygroups(using(this), Text, Name.Variable)), + (r'[a-zA-Z$_][\w$]*:', Name.Function), + (';', Punctuation, '#pop'), + (r'\{', Punctuation, 'function'), + default('#pop'), + ], + 'literal_number': [ + (r'\(', Punctuation, 'literal_number_inner'), + (r'\)', Literal, '#pop'), + include('statement'), + ], + 'literal_number_inner': [ + (r'\(', Punctuation, '#push'), + (r'\)', Punctuation, '#pop'), + include('statement'), + ], + 'literal_array': [ + (r'\[', Punctuation, 'literal_array_inner'), + (r'\]', Literal, '#pop'), + include('statement'), + ], + 'literal_array_inner': [ + (r'\[', Punctuation, '#push'), + (r'\]', Punctuation, '#pop'), + include('statement'), + ], + 'literal_dictionary': [ + (r'\}', Literal, '#pop'), + include('statement'), + ], + } + + def analyse_text(text): + if _oc_keywords.search(text): + return 1.0 + elif '@"' in text: # strings + return 0.8 + elif re.search('@[0-9]+', text): + return 0.7 + elif _oc_message.search(text): + return 0.8 + return 0 + + def get_tokens_unprocessed(self, text, stack=('root',)): + from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \ + COCOA_PROTOCOLS, COCOA_PRIMITIVES + + for index, token, value in \ + baselexer.get_tokens_unprocessed(self, text, stack): + if token is Name or token is Name.Class: + if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \ + or value in COCOA_PRIMITIVES: + token = Name.Builtin.Pseudo + + yield index, token, value + + return GeneratedObjectiveCVariant + + +class ObjectiveCLexer(objective(CLexer)): + """ + For Objective-C source code with preprocessor directives. + """ + + name = 'Objective-C' + url = 'https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html' + aliases = ['objective-c', 'objectivec', 'obj-c', 'objc'] + filenames = ['*.m', '*.h'] + mimetypes = ['text/x-objective-c'] + priority = 0.05 # Lower than C + + +class ObjectiveCppLexer(objective(CppLexer)): + """ + For Objective-C++ source code with preprocessor directives. + """ + + name = 'Objective-C++' + aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++'] + filenames = ['*.mm', '*.hh'] + mimetypes = ['text/x-objective-c++'] + priority = 0.05 # Lower than C++ + + +class LogosLexer(ObjectiveCppLexer): + """ + For Logos + Objective-C source code with preprocessor directives. + + .. versionadded:: 1.6 + """ + + name = 'Logos' + aliases = ['logos'] + filenames = ['*.x', '*.xi', '*.xm', '*.xmi'] + mimetypes = ['text/x-logos'] + priority = 0.25 + + tokens = { + 'statements': [ + (r'(%orig|%log)\b', Keyword), + (r'(%c)\b(\()(\s*)([a-zA-Z$_][\w$]*)(\s*)(\))', + bygroups(Keyword, Punctuation, Text, Name.Class, Text, Punctuation)), + (r'(%init)\b(\()', + bygroups(Keyword, Punctuation), 'logos_init_directive'), + (r'(%init)(?=\s*;)', bygroups(Keyword)), + (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)', + bygroups(Keyword, Text, Name.Class), '#pop'), + (r'(%subclass)(\s+)', bygroups(Keyword, Text), + ('#pop', 'logos_classname')), + inherit, + ], + 'logos_init_directive': [ + (r'\s+', Text), + (',', Punctuation, ('logos_init_directive', '#pop')), + (r'([a-zA-Z$_][\w$]*)(\s*)(=)(\s*)([^);]*)', + bygroups(Name.Class, Text, Punctuation, Text, Text)), + (r'([a-zA-Z$_][\w$]*)', Name.Class), + (r'\)', Punctuation, '#pop'), + ], + 'logos_classname': [ + (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?', + bygroups(Name.Class, Text, Name.Class), '#pop'), + (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop') + ], + 'root': [ + (r'(%subclass)(\s+)', bygroups(Keyword, Text), + 'logos_classname'), + (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)', + bygroups(Keyword, Text, Name.Class)), + (r'(%config)(\s*\(\s*)(\w+)(\s*=)(.*?)(\)\s*)', + bygroups(Keyword, Text, Name.Variable, Text, String, Text)), + (r'(%ctor)(\s*)(\{)', bygroups(Keyword, Text, Punctuation), + 'function'), + (r'(%new)(\s*)(\()(.*?)(\))', + bygroups(Keyword, Text, Keyword, String, Keyword)), + (r'(\s*)(%end)(\s*)', bygroups(Text, Keyword, Text)), + inherit, + ], + } + + _logos_keywords = re.compile(r'%(?:hook|ctor|init|c\()') + + def analyse_text(text): + if LogosLexer._logos_keywords.search(text): + return 1.0 + return 0 + + +class SwiftLexer(RegexLexer): + """ + For Swift source. + + .. versionadded:: 2.0 + """ + name = 'Swift' + url = 'https://www.swift.org/' + filenames = ['*.swift'] + aliases = ['swift'] + mimetypes = ['text/x-swift'] + + tokens = { + 'root': [ + # Whitespace and Comments + (r'\n', Text), + (r'\s+', Text), + (r'//', Comment.Single, 'comment-single'), + (r'/\*', Comment.Multiline, 'comment-multi'), + (r'#(if|elseif|else|endif|available)\b', Comment.Preproc, 'preproc'), + + # Keywords + include('keywords'), + + # Global Types + (words(( + 'Array', 'AutoreleasingUnsafeMutablePointer', 'BidirectionalReverseView', + 'Bit', 'Bool', 'CFunctionPointer', 'COpaquePointer', 'CVaListPointer', + 'Character', 'ClosedInterval', 'CollectionOfOne', 'ContiguousArray', + 'Dictionary', 'DictionaryGenerator', 'DictionaryIndex', 'Double', + 'EmptyCollection', 'EmptyGenerator', 'EnumerateGenerator', + 'EnumerateSequence', 'FilterCollectionView', + 'FilterCollectionViewIndex', 'FilterGenerator', 'FilterSequenceView', + 'Float', 'Float80', 'FloatingPointClassification', 'GeneratorOf', + 'GeneratorOfOne', 'GeneratorSequence', 'HalfOpenInterval', 'HeapBuffer', + 'HeapBufferStorage', 'ImplicitlyUnwrappedOptional', 'IndexingGenerator', + 'Int', 'Int16', 'Int32', 'Int64', 'Int8', 'LazyBidirectionalCollection', + 'LazyForwardCollection', 'LazyRandomAccessCollection', + 'LazySequence', 'MapCollectionView', 'MapSequenceGenerator', + 'MapSequenceView', 'MirrorDisposition', 'ObjectIdentifier', 'OnHeap', + 'Optional', 'PermutationGenerator', 'QuickLookObject', + 'RandomAccessReverseView', 'Range', 'RangeGenerator', 'RawByte', 'Repeat', + 'ReverseBidirectionalIndex', 'ReverseRandomAccessIndex', 'SequenceOf', + 'SinkOf', 'Slice', 'StaticString', 'StrideThrough', 'StrideThroughGenerator', + 'StrideTo', 'StrideToGenerator', 'String', 'UInt', 'UInt16', 'UInt32', + 'UInt64', 'UInt8', 'UTF16', 'UTF32', 'UTF8', 'UnicodeDecodingResult', + 'UnicodeScalar', 'Unmanaged', 'UnsafeBufferPointer', + 'UnsafeBufferPointerGenerator', 'UnsafeMutableBufferPointer', + 'UnsafeMutablePointer', 'UnsafePointer', 'Zip2', 'ZipGenerator2', + # Protocols + 'AbsoluteValuable', 'AnyObject', 'ArrayLiteralConvertible', + 'BidirectionalIndexType', 'BitwiseOperationsType', + 'BooleanLiteralConvertible', 'BooleanType', 'CVarArgType', + 'CollectionType', 'Comparable', 'DebugPrintable', + 'DictionaryLiteralConvertible', 'Equatable', + 'ExtendedGraphemeClusterLiteralConvertible', + 'ExtensibleCollectionType', 'FloatLiteralConvertible', + 'FloatingPointType', 'ForwardIndexType', 'GeneratorType', 'Hashable', + 'IntegerArithmeticType', 'IntegerLiteralConvertible', 'IntegerType', + 'IntervalType', 'MirrorType', 'MutableCollectionType', 'MutableSliceable', + 'NilLiteralConvertible', 'OutputStreamType', 'Printable', + 'RandomAccessIndexType', 'RangeReplaceableCollectionType', + 'RawOptionSetType', 'RawRepresentable', 'Reflectable', 'SequenceType', + 'SignedIntegerType', 'SignedNumberType', 'SinkType', 'Sliceable', + 'Streamable', 'Strideable', 'StringInterpolationConvertible', + 'StringLiteralConvertible', 'UnicodeCodecType', + 'UnicodeScalarLiteralConvertible', 'UnsignedIntegerType', + '_ArrayBufferType', '_BidirectionalIndexType', '_CocoaStringType', + '_CollectionType', '_Comparable', '_ExtensibleCollectionType', + '_ForwardIndexType', '_Incrementable', '_IntegerArithmeticType', + '_IntegerType', '_ObjectiveCBridgeable', '_RandomAccessIndexType', + '_RawOptionSetType', '_SequenceType', '_Sequence_Type', + '_SignedIntegerType', '_SignedNumberType', '_Sliceable', '_Strideable', + '_SwiftNSArrayRequiredOverridesType', '_SwiftNSArrayType', + '_SwiftNSCopyingType', '_SwiftNSDictionaryRequiredOverridesType', + '_SwiftNSDictionaryType', '_SwiftNSEnumeratorType', + '_SwiftNSFastEnumerationType', '_SwiftNSStringRequiredOverridesType', + '_SwiftNSStringType', '_UnsignedIntegerType', + # Variables + 'C_ARGC', 'C_ARGV', 'Process', + # Typealiases + 'Any', 'AnyClass', 'BooleanLiteralType', 'CBool', 'CChar', 'CChar16', + 'CChar32', 'CDouble', 'CFloat', 'CInt', 'CLong', 'CLongLong', 'CShort', + 'CSignedChar', 'CUnsignedInt', 'CUnsignedLong', 'CUnsignedShort', + 'CWideChar', 'ExtendedGraphemeClusterType', 'Float32', 'Float64', + 'FloatLiteralType', 'IntMax', 'IntegerLiteralType', 'StringLiteralType', + 'UIntMax', 'UWord', 'UnicodeScalarType', 'Void', 'Word', + # Foundation/Cocoa + 'NSErrorPointer', 'NSObjectProtocol', 'Selector'), suffix=r'\b'), + Name.Builtin), + # Functions + (words(( + 'abs', 'advance', 'alignof', 'alignofValue', 'assert', 'assertionFailure', + 'contains', 'count', 'countElements', 'debugPrint', 'debugPrintln', + 'distance', 'dropFirst', 'dropLast', 'dump', 'enumerate', 'equal', + 'extend', 'fatalError', 'filter', 'find', 'first', 'getVaList', 'indices', + 'insert', 'isEmpty', 'join', 'last', 'lazy', 'lexicographicalCompare', + 'map', 'max', 'maxElement', 'min', 'minElement', 'numericCast', 'overlaps', + 'partition', 'precondition', 'preconditionFailure', 'prefix', 'print', + 'println', 'reduce', 'reflect', 'removeAll', 'removeAtIndex', 'removeLast', + 'removeRange', 'reverse', 'sizeof', 'sizeofValue', 'sort', 'sorted', + 'splice', 'split', 'startsWith', 'stride', 'strideof', 'strideofValue', + 'suffix', 'swap', 'toDebugString', 'toString', 'transcode', + 'underestimateCount', 'unsafeAddressOf', 'unsafeBitCast', 'unsafeDowncast', + 'withExtendedLifetime', 'withUnsafeMutablePointer', + 'withUnsafeMutablePointers', 'withUnsafePointer', 'withUnsafePointers', + 'withVaList'), suffix=r'\b'), + Name.Builtin.Pseudo), + + # Implicit Block Variables + (r'\$\d+', Name.Variable), + + # Binary Literal + (r'0b[01_]+', Number.Bin), + # Octal Literal + (r'0o[0-7_]+', Number.Oct), + # Hexadecimal Literal + (r'0x[0-9a-fA-F_]+', Number.Hex), + # Decimal Literal + (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|' + r'\.[0-9_]*|[eE][+\-]?[0-9_]+)', Number.Float), + (r'[0-9][0-9_]*', Number.Integer), + # String Literal + (r'"', String, 'string'), + + # Operators and Punctuation + (r'[(){}\[\].,:;=@#`?]|->|[<&?](?=\w)|(?<=\w)[>!?]', Punctuation), + (r'[/=\-+!*%<>&|^?~]+', Operator), + + # Identifier + (r'[a-zA-Z_]\w*', Name) + ], + 'keywords': [ + (words(( + 'as', 'async', 'await', 'break', 'case', 'catch', 'continue', 'default', 'defer', + 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'is', + 'repeat', 'return', '#selector', 'switch', 'throw', 'try', + 'where', 'while'), suffix=r'\b'), + Keyword), + (r'@availability\([^)]+\)', Keyword.Reserved), + (words(( + 'associativity', 'convenience', 'dynamic', 'didSet', 'final', + 'get', 'indirect', 'infix', 'inout', 'lazy', 'left', 'mutating', + 'none', 'nonmutating', 'optional', 'override', 'postfix', + 'precedence', 'prefix', 'Protocol', 'required', 'rethrows', + 'right', 'set', 'throws', 'Type', 'unowned', 'weak', 'willSet', + '@availability', '@autoclosure', '@noreturn', + '@NSApplicationMain', '@NSCopying', '@NSManaged', '@objc', + '@UIApplicationMain', '@IBAction', '@IBDesignable', + '@IBInspectable', '@IBOutlet'), suffix=r'\b'), + Keyword.Reserved), + (r'(as|dynamicType|false|is|nil|self|Self|super|true|__COLUMN__' + r'|__FILE__|__FUNCTION__|__LINE__|_' + r'|#(?:file|line|column|function))\b', Keyword.Constant), + (r'import\b', Keyword.Declaration, 'module'), + (r'(class|enum|extension|struct|protocol)(\s+)([a-zA-Z_]\w*)', + bygroups(Keyword.Declaration, Text, Name.Class)), + (r'(func)(\s+)([a-zA-Z_]\w*)', + bygroups(Keyword.Declaration, Text, Name.Function)), + (r'(var|let)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration, + Text, Name.Variable)), + (words(( + 'actor', 'associatedtype', 'class', 'deinit', 'enum', 'extension', 'func', 'import', + 'init', 'internal', 'let', 'operator', 'private', 'protocol', 'public', + 'static', 'struct', 'subscript', 'typealias', 'var'), suffix=r'\b'), + Keyword.Declaration) + ], + 'comment': [ + (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):', + Comment.Special) + ], + + # Nested + 'comment-single': [ + (r'\n', Text, '#pop'), + include('comment'), + (r'[^\n]', Comment.Single) + ], + 'comment-multi': [ + include('comment'), + (r'[^*/]', Comment.Multiline), + (r'/\*', Comment.Multiline, '#push'), + (r'\*/', Comment.Multiline, '#pop'), + (r'[*/]', Comment.Multiline) + ], + 'module': [ + (r'\n', Text, '#pop'), + (r'[a-zA-Z_]\w*', Name.Class), + include('root') + ], + 'preproc': [ + (r'\n', Text, '#pop'), + include('keywords'), + (r'[A-Za-z]\w*', Comment.Preproc), + include('root') + ], + 'string': [ + (r'\\\(', String.Interpol, 'string-intp'), + (r'"', String, '#pop'), + (r"""\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}""" + r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}""", String.Escape), + (r'[^\\"]+', String), + (r'\\', String) + ], + 'string-intp': [ + (r'\(', String.Interpol, '#push'), + (r'\)', String.Interpol, '#pop'), + include('root') + ] + } + + def get_tokens_unprocessed(self, text): + from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \ + COCOA_PROTOCOLS, COCOA_PRIMITIVES + + for index, token, value in \ + RegexLexer.get_tokens_unprocessed(self, text): + if token is Name or token is Name.Class: + if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \ + or value in COCOA_PRIMITIVES: + token = Name.Builtin.Pseudo + + yield index, token, value diff --git a/shared/package-files/56/5687b07e11ecf0c194a47ffec082d05889f5fc1baa4c5cdc7bf75e67a329ebfe/exp2.h b/shared/package-files/56/5687b07e11ecf0c194a47ffec082d05889f5fc1baa4c5cdc7bf75e67a329ebfe/exp2.h new file mode 100644 index 0000000000000000000000000000000000000000..bd74aa318198233e38437970067b24eaeafa2b34 --- /dev/null +++ b/shared/package-files/56/5687b07e11ecf0c194a47ffec082d05889f5fc1baa4c5cdc7bf75e67a329ebfe/exp2.h @@ -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::exp2(Tensor self) -> Tensor +inline at::Tensor exp2(const at::Tensor & self) { + return at::_ops::exp2::call(self); +} + +// aten::exp2_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & exp2_(at::Tensor & self) { + return at::_ops::exp2_::call(self); +} + +// aten::exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & exp2_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::exp2_out::call(self, out); +} +// aten::exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & exp2_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::exp2_out::call(self, out); +} + +} diff --git a/shared/package-files/56/568c40fb25e8c3f0918a4275b659e2d4fb0000e4f50f65fc3ed4d9c893864175/test_isetitem.py b/shared/package-files/56/568c40fb25e8c3f0918a4275b659e2d4fb0000e4f50f65fc3ed4d9c893864175/test_isetitem.py new file mode 100644 index 0000000000000000000000000000000000000000..69f394afb65191fe4cc52519fbc52959d2e1dd76 --- /dev/null +++ b/shared/package-files/56/568c40fb25e8c3f0918a4275b659e2d4fb0000e4f50f65fc3ed4d9c893864175/test_isetitem.py @@ -0,0 +1,50 @@ +import pytest + +from pandas import ( + DataFrame, + Series, +) +import pandas._testing as tm + + +class TestDataFrameSetItem: + def test_isetitem_ea_df(self): + # GH#49922 + df = DataFrame([[1, 2, 3], [4, 5, 6]]) + rhs = DataFrame([[11, 12], [13, 14]], dtype="Int64") + + df.isetitem([0, 1], rhs) + expected = DataFrame( + { + 0: Series([11, 13], dtype="Int64"), + 1: Series([12, 14], dtype="Int64"), + 2: [3, 6], + } + ) + tm.assert_frame_equal(df, expected) + + def test_isetitem_ea_df_scalar_indexer(self): + # GH#49922 + df = DataFrame([[1, 2, 3], [4, 5, 6]]) + rhs = DataFrame([[11], [13]], dtype="Int64") + + df.isetitem(2, rhs) + expected = DataFrame( + { + 0: [1, 4], + 1: [2, 5], + 2: Series([11, 13], dtype="Int64"), + } + ) + tm.assert_frame_equal(df, expected) + + def test_isetitem_dimension_mismatch(self): + # GH#51701 + df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}) + value = df.copy() + with pytest.raises(ValueError, match="Got 2 positions but value has 3 columns"): + df.isetitem([1, 2], value) + + value = df.copy() + with pytest.raises(ValueError, match="Got 2 positions but value has 1 columns"): + df.isetitem([1, 2], value[["a"]]) diff --git a/shared/package-files/56/568ea0601a40247033b65abc9b7807fbd1aa29493148e1e0d9f93a700a478051/array.py b/shared/package-files/56/568ea0601a40247033b65abc9b7807fbd1aa29493148e1e0d9f93a700a478051/array.py new file mode 100644 index 0000000000000000000000000000000000000000..2789d51ec2ce3096c64b41af90b5a416ceef9f5b --- /dev/null +++ b/shared/package-files/56/568ea0601a40247033b65abc9b7807fbd1aa29493148e1e0d9f93a700a478051/array.py @@ -0,0 +1,89 @@ +""" +Test extension array that has custom attribute information (not stored on the dtype). + +""" +from __future__ import annotations + +import numbers +from typing import TYPE_CHECKING + +import numpy as np + +from pandas.core.dtypes.base import ExtensionDtype + +import pandas as pd +from pandas.core.arrays import ExtensionArray + +if TYPE_CHECKING: + from pandas._typing import type_t + + +class FloatAttrDtype(ExtensionDtype): + type = float + name = "float_attr" + na_value = np.nan + + @classmethod + def construct_array_type(cls) -> type_t[FloatAttrArray]: + """ + Return the array type associated with this dtype. + + Returns + ------- + type + """ + return FloatAttrArray + + +class FloatAttrArray(ExtensionArray): + dtype = FloatAttrDtype() + __array_priority__ = 1000 + + def __init__(self, values, attr=None) -> None: + if not isinstance(values, np.ndarray): + raise TypeError("Need to pass a numpy array of float64 dtype as values") + if not values.dtype == "float64": + raise TypeError("Need to pass a numpy array of float64 dtype as values") + self.data = values + self.attr = attr + + @classmethod + def _from_sequence(cls, scalars, *, dtype=None, copy=False): + if not copy: + data = np.asarray(scalars, dtype="float64") + else: + data = np.array(scalars, dtype="float64", copy=copy) + return cls(data) + + def __getitem__(self, item): + if isinstance(item, numbers.Integral): + return self.data[item] + else: + # slice, list-like, mask + item = pd.api.indexers.check_array_indexer(self, item) + return type(self)(self.data[item], self.attr) + + def __len__(self) -> int: + return len(self.data) + + def isna(self): + return np.isnan(self.data) + + def take(self, indexer, allow_fill=False, fill_value=None): + from pandas.api.extensions import take + + data = self.data + if allow_fill and fill_value is None: + fill_value = self.dtype.na_value + + result = take(data, indexer, fill_value=fill_value, allow_fill=allow_fill) + return type(self)(result, self.attr) + + def copy(self): + return type(self)(self.data.copy(), self.attr) + + @classmethod + def _concat_same_type(cls, to_concat): + data = np.concatenate([x.data for x in to_concat]) + attr = to_concat[0].attr if len(to_concat) else None + return cls(data, attr) diff --git a/shared/package-files/56/568eb9c241a993e5474e047261d55be46eb53026d79850cdb6fd97059d5fb090/data.py b/shared/package-files/56/568eb9c241a993e5474e047261d55be46eb53026d79850cdb6fd97059d5fb090/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2dae661c9692f12b1cc4759e7dd9b1c681ff763b --- /dev/null +++ b/shared/package-files/56/568eb9c241a993e5474e047261d55be46eb53026d79850cdb6fd97059d5fb090/data.py @@ -0,0 +1,73 @@ +"""El Nino dataset, 1950 - 2010""" +from statsmodels.datasets import utils as du + +__docformat__ = "restructuredtext" + +COPYRIGHT = """This data is in the public domain.""" + +TITLE = """El Nino - Sea Surface Temperatures""" + +SOURCE = """ +National Oceanic and Atmospheric Administration's National Weather Service + +ERSST.V3B dataset, Nino 1+2 +http://www.cpc.ncep.noaa.gov/data/indices/ +""" + +DESCRSHORT = """Averaged monthly sea surface temperature - Pacific Ocean.""" + +DESCRLONG = """This data contains the averaged monthly sea surface +temperature in degrees Celsius of the Pacific Ocean, between 0-10 degrees South +and 90-80 degrees West, from 1950 to 2010. This dataset was obtained from +NOAA. +""" + +NOTE = """:: + + Number of Observations - 61 x 12 + + Number of Variables - 1 + + Variable name definitions:: + + TEMPERATURE - average sea surface temperature in degrees Celsius + (12 columns, one per month). +""" + + +def load_pandas(): + """ + Load the El Nino data and return a Dataset class. + + Returns + ------- + Dataset + A `Dataset` instance with ``data`` and ``names`` attributes. + + Notes + ----- + The elnino Dataset instance does not contain endog and exog attributes. + """ + data = _get_data() + dataset = du.Dataset(data=data, names=list(data.columns)) + return dataset + + +def load(): + """ + Load the El Nino data and return a Dataset class. + + Returns + ------- + Dataset + A `Dataset` instance with ``data`` and ``names`` attributes. + + Notes + ----- + The elnino Dataset instance does not contain endog and exog attributes. + """ + return load_pandas() + + +def _get_data(): + return du.load_csv(__file__, "elnino.csv", convert_float=True) diff --git a/shared/package-files/56/568f09a6d16bf8a8367f6704a0383c2ed10b4a354dc9c71d258ef858ffe4aad7/miutf8_array_name.mat b/shared/package-files/56/568f09a6d16bf8a8367f6704a0383c2ed10b4a354dc9c71d258ef858ffe4aad7/miutf8_array_name.mat new file mode 100644 index 0000000000000000000000000000000000000000..ccfdaa8adb7879ba852eab9ce55b602e11dad06d Binary files /dev/null and b/shared/package-files/56/568f09a6d16bf8a8367f6704a0383c2ed10b4a354dc9c71d258ef858ffe4aad7/miutf8_array_name.mat differ diff --git a/shared/package-files/56/568f46e6065a1934d0c253616c8f19240eed5dee8949878d0a42938221bc73f9/tab132-w b/shared/package-files/56/568f46e6065a1934d0c253616c8f19240eed5dee8949878d0a42938221bc73f9/tab132-w new file mode 100644 index 0000000000000000000000000000000000000000..28d713fbb4464f75f4bf98f23d581f373069a70b Binary files /dev/null and b/shared/package-files/56/568f46e6065a1934d0c253616c8f19240eed5dee8949878d0a42938221bc73f9/tab132-w differ diff --git a/shared/package-files/56/5690ec210c05373f68d3870fb53676a4fa7b2db4c881b43fae6c60572e0a41d3/special_chebyshev_polynomial_t_compositeexplicitautograd_dispatch.h b/shared/package-files/56/5690ec210c05373f68d3870fb53676a4fa7b2db4c881b43fae6c60572e0a41d3/special_chebyshev_polynomial_t_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..446a4de530b1c65fabcc5f03c88dcbbbfbcfb387 --- /dev/null +++ b/shared/package-files/56/5690ec210c05373f68d3870fb53676a4fa7b2db4c881b43fae6c60572e0a41d3/special_chebyshev_polynomial_t_compositeexplicitautograd_dispatch.h @@ -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_chebyshev_polynomial_t(const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_t_out(at::Tensor & out, const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_t_outf(const at::Scalar & x, const at::Tensor & n, at::Tensor & out); +TORCH_API at::Tensor special_chebyshev_polynomial_t(const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_t_out(at::Tensor & out, const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_t_outf(const at::Tensor & x, const at::Scalar & n, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/56/56914a1d79fcbab672f1fd6194f663dc4bde2a5b0a9ea51b070a09d16dc09122/tek4105 b/shared/package-files/56/56914a1d79fcbab672f1fd6194f663dc4bde2a5b0a9ea51b070a09d16dc09122/tek4105 new file mode 100644 index 0000000000000000000000000000000000000000..795a1faf2c36dac0d952e4e58d24e91f32fee6b0 Binary files /dev/null and b/shared/package-files/56/56914a1d79fcbab672f1fd6194f663dc4bde2a5b0a9ea51b070a09d16dc09122/tek4105 differ diff --git a/shared/package-files/56/5691b2820b0c6ea77608bd934525f5228ce9d46e153083cd4bb14c304fa13c0c/iterables.py b/shared/package-files/56/5691b2820b0c6ea77608bd934525f5228ce9d46e153083cd4bb14c304fa13c0c/iterables.py new file mode 100644 index 0000000000000000000000000000000000000000..e84a694df754f33419212ad23c94aaf84bfc1e5a --- /dev/null +++ b/shared/package-files/56/5691b2820b0c6ea77608bd934525f5228ce9d46e153083cd4bb14c304fa13c0c/iterables.py @@ -0,0 +1,3172 @@ +from collections import Counter, defaultdict, OrderedDict +from itertools import ( + chain, combinations, combinations_with_replacement, cycle, islice, + permutations, product, groupby +) +# For backwards compatibility +from itertools import product as cartes # noqa: F401 +from operator import gt + + + +# this is the logical location of these functions +from sympy.utilities.enumerative import ( + multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser) + +from sympy.utilities.misc import as_int +from sympy.utilities.decorator import deprecated + + +def is_palindromic(s, i=0, j=None): + """ + Return True if the sequence is the same from left to right as it + is from right to left in the whole sequence (default) or in the + Python slice ``s[i: j]``; else False. + + Examples + ======== + + >>> from sympy.utilities.iterables import is_palindromic + >>> is_palindromic([1, 0, 1]) + True + >>> is_palindromic('abcbb') + False + >>> is_palindromic('abcbb', 1) + False + + Normal Python slicing is performed in place so there is no need to + create a slice of the sequence for testing: + + >>> is_palindromic('abcbb', 1, -1) + True + >>> is_palindromic('abcbb', -4, -1) + True + + See Also + ======== + + sympy.ntheory.digits.is_palindromic: tests integers + + """ + i, j, _ = slice(i, j).indices(len(s)) + m = (j - i)//2 + # if length is odd, middle element will be ignored + return all(s[i + k] == s[j - 1 - k] for k in range(m)) + + +def flatten(iterable, levels=None, cls=None): # noqa: F811 + """ + Recursively denest iterable containers. + + >>> from sympy import flatten + + >>> flatten([1, 2, 3]) + [1, 2, 3] + >>> flatten([1, 2, [3]]) + [1, 2, 3] + >>> flatten([1, [2, 3], [4, 5]]) + [1, 2, 3, 4, 5] + >>> flatten([1.0, 2, (1, None)]) + [1.0, 2, 1, None] + + If you want to denest only a specified number of levels of + nested containers, then set ``levels`` flag to the desired + number of levels:: + + >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]] + + >>> flatten(ls, levels=1) + [(-2, -1), (1, 2), (0, 0)] + + If cls argument is specified, it will only flatten instances of that + class, for example: + + >>> from sympy import Basic, S + >>> class MyOp(Basic): + ... pass + ... + >>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp) + [1, 2, 3] + + adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks + """ + from sympy.tensor.array import NDimArray + if levels is not None: + if not levels: + return iterable + elif levels > 0: + levels -= 1 + else: + raise ValueError( + "expected non-negative number of levels, got %s" % levels) + + if cls is None: + def reducible(x): + return is_sequence(x, set) + else: + def reducible(x): + return isinstance(x, cls) + + result = [] + + for el in iterable: + if reducible(el): + if hasattr(el, 'args') and not isinstance(el, NDimArray): + el = el.args + result.extend(flatten(el, levels=levels, cls=cls)) + else: + result.append(el) + + return result + + +def unflatten(iter, n=2): + """Group ``iter`` into tuples of length ``n``. Raise an error if + the length of ``iter`` is not a multiple of ``n``. + """ + if n < 1 or len(iter) % n: + raise ValueError('iter length is not a multiple of %i' % n) + return list(zip(*(iter[i::n] for i in range(n)))) + + +def reshape(seq, how): + """Reshape the sequence according to the template in ``how``. + + Examples + ======== + + >>> from sympy.utilities import reshape + >>> seq = list(range(1, 9)) + + >>> reshape(seq, [4]) # lists of 4 + [[1, 2, 3, 4], [5, 6, 7, 8]] + + >>> reshape(seq, (4,)) # tuples of 4 + [(1, 2, 3, 4), (5, 6, 7, 8)] + + >>> reshape(seq, (2, 2)) # tuples of 4 + [(1, 2, 3, 4), (5, 6, 7, 8)] + + >>> reshape(seq, (2, [2])) # (i, i, [i, i]) + [(1, 2, [3, 4]), (5, 6, [7, 8])] + + >>> reshape(seq, ((2,), [2])) # etc.... + [((1, 2), [3, 4]), ((5, 6), [7, 8])] + + >>> reshape(seq, (1, [2], 1)) + [(1, [2, 3], 4), (5, [6, 7], 8)] + + >>> reshape(tuple(seq), ([[1], 1, (2,)],)) + (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) + + >>> reshape(tuple(seq), ([1], 1, (2,))) + (([1], 2, (3, 4)), ([5], 6, (7, 8))) + + >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) + [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] + + """ + m = sum(flatten(how)) + n, rem = divmod(len(seq), m) + if m < 0 or rem: + raise ValueError('template must sum to positive number ' + 'that divides the length of the sequence') + i = 0 + container = type(how) + rv = [None]*n + for k in range(len(rv)): + _rv = [] + for hi in how: + if isinstance(hi, int): + _rv.extend(seq[i: i + hi]) + i += hi + else: + n = sum(flatten(hi)) + hi_type = type(hi) + _rv.append(hi_type(reshape(seq[i: i + n], hi)[0])) + i += n + rv[k] = container(_rv) + return type(seq)(rv) + + +def group(seq, multiple=True): + """ + Splits a sequence into a list of lists of equal, adjacent elements. + + Examples + ======== + + >>> from sympy import group + + >>> group([1, 1, 1, 2, 2, 3]) + [[1, 1, 1], [2, 2], [3]] + >>> group([1, 1, 1, 2, 2, 3], multiple=False) + [(1, 3), (2, 2), (3, 1)] + >>> group([1, 1, 3, 2, 2, 1], multiple=False) + [(1, 2), (3, 1), (2, 2), (1, 1)] + + See Also + ======== + + multiset + + """ + if multiple: + return [(list(g)) for _, g in groupby(seq)] + return [(k, len(list(g))) for k, g in groupby(seq)] + + +def _iproduct2(iterable1, iterable2): + '''Cartesian product of two possibly infinite iterables''' + + it1 = iter(iterable1) + it2 = iter(iterable2) + + elems1 = [] + elems2 = [] + + sentinel = object() + def append(it, elems): + e = next(it, sentinel) + if e is not sentinel: + elems.append(e) + + n = 0 + append(it1, elems1) + append(it2, elems2) + + while n <= len(elems1) + len(elems2): + for m in range(n-len(elems1)+1, len(elems2)): + yield (elems1[n-m], elems2[m]) + n += 1 + append(it1, elems1) + append(it2, elems2) + + +def iproduct(*iterables): + ''' + Cartesian product of iterables. + + Generator of the Cartesian product of iterables. This is analogous to + itertools.product except that it works with infinite iterables and will + yield any item from the infinite product eventually. + + Examples + ======== + + >>> from sympy.utilities.iterables import iproduct + >>> sorted(iproduct([1,2], [3,4])) + [(1, 3), (1, 4), (2, 3), (2, 4)] + + With an infinite iterator: + + >>> from sympy import S + >>> (3,) in iproduct(S.Integers) + True + >>> (3, 4) in iproduct(S.Integers, S.Integers) + True + + .. seealso:: + + `itertools.product + `_ + ''' + if len(iterables) == 0: + yield () + return + elif len(iterables) == 1: + for e in iterables[0]: + yield (e,) + elif len(iterables) == 2: + yield from _iproduct2(*iterables) + else: + first, others = iterables[0], iterables[1:] + for ef, eo in _iproduct2(first, iproduct(*others)): + yield (ef,) + eo + + +def multiset(seq): + """Return the hashable sequence in multiset form with values being the + multiplicity of the item in the sequence. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset + >>> multiset('mississippi') + {'i': 4, 'm': 1, 'p': 2, 's': 4} + + See Also + ======== + + group + + """ + return dict(Counter(seq).items()) + + + + +def ibin(n, bits=None, str=False): + """Return a list of length ``bits`` corresponding to the binary value + of ``n`` with small bits to the right (last). If bits is omitted, the + length will be the number required to represent ``n``. If the bits are + desired in reversed order, use the ``[::-1]`` slice of the returned list. + + If a sequence of all bits-length lists starting from ``[0, 0,..., 0]`` + through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g. + ``'all'``. + + If the bit *string* is desired pass ``str=True``. + + Examples + ======== + + >>> from sympy.utilities.iterables import ibin + >>> ibin(2) + [1, 0] + >>> ibin(2, 4) + [0, 0, 1, 0] + + If all lists corresponding to 0 to 2**n - 1, pass a non-integer + for bits: + + >>> bits = 2 + >>> for i in ibin(2, 'all'): + ... print(i) + (0, 0) + (0, 1) + (1, 0) + (1, 1) + + If a bit string is desired of a given length, use str=True: + + >>> n = 123 + >>> bits = 10 + >>> ibin(n, bits, str=True) + '0001111011' + >>> ibin(n, bits, str=True)[::-1] # small bits left + '1101111000' + >>> list(ibin(3, 'all', str=True)) + ['000', '001', '010', '011', '100', '101', '110', '111'] + + """ + if n < 0: + raise ValueError("negative numbers are not allowed") + n = as_int(n) + + if bits is None: + bits = 0 + else: + try: + bits = as_int(bits) + except ValueError: + bits = -1 + else: + if n.bit_length() > bits: + raise ValueError( + "`bits` must be >= {}".format(n.bit_length())) + + if not str: + if bits >= 0: + return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")] + else: + return variations(range(2), n, repetition=True) + else: + if bits >= 0: + return bin(n)[2:].rjust(bits, "0") + else: + return (bin(i)[2:].rjust(n, "0") for i in range(2**n)) + + +def variations(seq, n, repetition=False): + r"""Returns an iterator over the n-sized variations of ``seq`` (size N). + ``repetition`` controls whether items in ``seq`` can appear more than once; + + Examples + ======== + + ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without + repetition of ``seq``'s elements: + + >>> from sympy import variations + >>> list(variations([1, 2], 2)) + [(1, 2), (2, 1)] + + ``variations(seq, n, True)`` will return the `N^n` permutations obtained + by allowing repetition of elements: + + >>> list(variations([1, 2], 2, repetition=True)) + [(1, 1), (1, 2), (2, 1), (2, 2)] + + If you ask for more items than are in the set you get the empty set unless + you allow repetitions: + + >>> list(variations([0, 1], 3, repetition=False)) + [] + >>> list(variations([0, 1], 3, repetition=True))[:4] + [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)] + + .. seealso:: + + `itertools.permutations + `_, + `itertools.product + `_ + """ + if not repetition: + seq = tuple(seq) + if len(seq) < n: + return iter(()) # 0 length iterator + return permutations(seq, n) + else: + if n == 0: + return iter(((),)) # yields 1 empty tuple + else: + return product(seq, repeat=n) + + +def subsets(seq, k=None, repetition=False): + r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``. + + A `k`-subset of an `n`-element set is any subset of length exactly `k`. The + number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``, + whereas there are `2^n` subsets all together. If `k` is ``None`` then all + `2^n` subsets will be returned from shortest to longest. + + Examples + ======== + + >>> from sympy import subsets + + ``subsets(seq, k)`` will return the + `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations) + without repetition, i.e. once an item has been removed, it can no + longer be "taken": + + >>> list(subsets([1, 2], 2)) + [(1, 2)] + >>> list(subsets([1, 2])) + [(), (1,), (2,), (1, 2)] + >>> list(subsets([1, 2, 3], 2)) + [(1, 2), (1, 3), (2, 3)] + + + ``subsets(seq, k, repetition=True)`` will return the + `\frac{(n - 1 + k)!}{k!(n - 1)!}` + combinations *with* repetition: + + >>> list(subsets([1, 2], 2, repetition=True)) + [(1, 1), (1, 2), (2, 2)] + + If you ask for more items than are in the set you get the empty set unless + you allow repetitions: + + >>> list(subsets([0, 1], 3, repetition=False)) + [] + >>> list(subsets([0, 1], 3, repetition=True)) + [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] + + """ + if k is None: + if not repetition: + return chain.from_iterable((combinations(seq, k) + for k in range(len(seq) + 1))) + else: + return chain.from_iterable((combinations_with_replacement(seq, k) + for k in range(len(seq) + 1))) + else: + if not repetition: + return combinations(seq, k) + else: + return combinations_with_replacement(seq, k) + + +def filter_symbols(iterator, exclude): + """ + Only yield elements from `iterator` that do not occur in `exclude`. + + Parameters + ========== + + iterator : iterable + iterator to take elements from + + exclude : iterable + elements to exclude + + Returns + ======= + + iterator : iterator + filtered iterator + """ + exclude = set(exclude) + for s in iterator: + if s not in exclude: + yield s + +def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions): + """ + Generate an infinite stream of Symbols consisting of a prefix and + increasing subscripts provided that they do not occur in ``exclude``. + + Parameters + ========== + + prefix : str, optional + The prefix to use. By default, this function will generate symbols of + the form "x0", "x1", etc. + + cls : class, optional + The class to use. By default, it uses ``Symbol``, but you can also use ``Wild`` + or ``Dummy``. + + start : int, optional + The start number. By default, it is 0. + + Returns + ======= + + sym : Symbol + The subscripted symbols. + """ + exclude = set(exclude or []) + if cls is None: + # We can't just make the default cls=Symbol because it isn't + # imported yet. + from sympy.core import Symbol + cls = Symbol + + while True: + name = '%s%s' % (prefix, start) + s = cls(name, *args, **assumptions) + if s not in exclude: + yield s + start += 1 + + +def capture(func): + """Return the printed output of func(). + + ``func`` should be a function without arguments that produces output with + print statements. + + >>> from sympy.utilities.iterables import capture + >>> from sympy import pprint + >>> from sympy.abc import x + >>> def foo(): + ... print('hello world!') + ... + >>> 'hello' in capture(foo) # foo, not foo() + True + >>> capture(lambda: pprint(2/x)) + '2\\n-\\nx\\n' + + """ + from io import StringIO + import sys + + stdout = sys.stdout + sys.stdout = file = StringIO() + try: + func() + finally: + sys.stdout = stdout + return file.getvalue() + + +def sift(seq, keyfunc, binary=False): + """ + Sift the sequence, ``seq`` according to ``keyfunc``. + + Returns + ======= + + When ``binary`` is ``False`` (default), the output is a dictionary + where elements of ``seq`` are stored in a list keyed to the value + of keyfunc for that element. If ``binary`` is True then a tuple + with lists ``T`` and ``F`` are returned where ``T`` is a list + containing elements of seq for which ``keyfunc`` was ``True`` and + ``F`` containing those elements for which ``keyfunc`` was ``False``; + a ValueError is raised if the ``keyfunc`` is not binary. + + Examples + ======== + + >>> from sympy.utilities import sift + >>> from sympy.abc import x, y + >>> from sympy import sqrt, exp, pi, Tuple + + >>> sift(range(5), lambda x: x % 2) + {0: [0, 2, 4], 1: [1, 3]} + + sift() returns a defaultdict() object, so any key that has no matches will + give []. + + >>> sift([x], lambda x: x.is_commutative) + {True: [x]} + >>> _[False] + [] + + Sometimes you will not know how many keys you will get: + + >>> sift([sqrt(x), exp(x), (y**x)**2], + ... lambda x: x.as_base_exp()[0]) + {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]} + + Sometimes you expect the results to be binary; the + results can be unpacked by setting ``binary`` to True: + + >>> sift(range(4), lambda x: x % 2, binary=True) + ([1, 3], [0, 2]) + >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True) + ([1], [pi]) + + A ValueError is raised if the predicate was not actually binary + (which is a good test for the logic where sifting is used and + binary results were expected): + + >>> unknown = exp(1) - pi # the rationality of this is unknown + >>> args = Tuple(1, pi, unknown) + >>> sift(args, lambda x: x.is_rational, binary=True) + Traceback (most recent call last): + ... + ValueError: keyfunc gave non-binary output + + The non-binary sifting shows that there were 3 keys generated: + + >>> set(sift(args, lambda x: x.is_rational).keys()) + {None, False, True} + + If you need to sort the sifted items it might be better to use + ``ordered`` which can economically apply multiple sort keys + to a sequence while sorting. + + See Also + ======== + + ordered + + """ + if not binary: + m = defaultdict(list) + for i in seq: + m[keyfunc(i)].append(i) + return m + sift = F, T = [], [] + for i in seq: + try: + sift[keyfunc(i)].append(i) + except (IndexError, TypeError): + raise ValueError('keyfunc gave non-binary output') + return T, F + + +def take(iter, n): + """Return ``n`` items from ``iter`` iterator. """ + return [ value for _, value in zip(range(n), iter) ] + + +def dict_merge(*dicts): + """Merge dictionaries into a single dictionary. """ + merged = {} + + for dict in dicts: + merged.update(dict) + + return merged + + +def common_prefix(*seqs): + """Return the subsequence that is a common start of sequences in ``seqs``. + + >>> from sympy.utilities.iterables import common_prefix + >>> common_prefix(list(range(3))) + [0, 1, 2] + >>> common_prefix(list(range(3)), list(range(4))) + [0, 1, 2] + >>> common_prefix([1, 2, 3], [1, 2, 5]) + [1, 2] + >>> common_prefix([1, 2, 3], [1, 3, 5]) + [1] + """ + if not all(seqs): + return [] + elif len(seqs) == 1: + return seqs[0] + i = 0 + for i in range(min(len(s) for s in seqs)): + if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): + break + else: + i += 1 + return seqs[0][:i] + + +def common_suffix(*seqs): + """Return the subsequence that is a common ending of sequences in ``seqs``. + + >>> from sympy.utilities.iterables import common_suffix + >>> common_suffix(list(range(3))) + [0, 1, 2] + >>> common_suffix(list(range(3)), list(range(4))) + [] + >>> common_suffix([1, 2, 3], [9, 2, 3]) + [2, 3] + >>> common_suffix([1, 2, 3], [9, 7, 3]) + [3] + """ + + if not all(seqs): + return [] + elif len(seqs) == 1: + return seqs[0] + i = 0 + for i in range(-1, -min(len(s) for s in seqs) - 1, -1): + if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): + break + else: + i -= 1 + if i == -1: + return [] + else: + return seqs[0][i + 1:] + + +def prefixes(seq): + """ + Generate all prefixes of a sequence. + + Examples + ======== + + >>> from sympy.utilities.iterables import prefixes + + >>> list(prefixes([1,2,3,4])) + [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] + + """ + n = len(seq) + + for i in range(n): + yield seq[:i + 1] + + +def postfixes(seq): + """ + Generate all postfixes of a sequence. + + Examples + ======== + + >>> from sympy.utilities.iterables import postfixes + + >>> list(postfixes([1,2,3,4])) + [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]] + + """ + n = len(seq) + + for i in range(n): + yield seq[n - i - 1:] + + +def topological_sort(graph, key=None): + r""" + Topological sort of graph's vertices. + + Parameters + ========== + + graph : tuple[list, list[tuple[T, T]] + A tuple consisting of a list of vertices and a list of edges of + a graph to be sorted topologically. + + key : callable[T] (optional) + Ordering key for vertices on the same level. By default the natural + (e.g. lexicographic) ordering is used (in this case the base type + must implement ordering relations). + + Examples + ======== + + Consider a graph:: + + +---+ +---+ +---+ + | 7 |\ | 5 | | 3 | + +---+ \ +---+ +---+ + | _\___/ ____ _/ | + | / \___/ \ / | + V V V V | + +----+ +---+ | + | 11 | | 8 | | + +----+ +---+ | + | | \____ ___/ _ | + | \ \ / / \ | + V \ V V / V V + +---+ \ +---+ | +----+ + | 2 | | | 9 | | | 10 | + +---+ | +---+ | +----+ + \________/ + + where vertices are integers. This graph can be encoded using + elementary Python's data structures as follows:: + + >>> V = [2, 3, 5, 7, 8, 9, 10, 11] + >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), + ... (11, 2), (11, 9), (11, 10), (8, 9)] + + To compute a topological sort for graph ``(V, E)`` issue:: + + >>> from sympy.utilities.iterables import topological_sort + + >>> topological_sort((V, E)) + [3, 5, 7, 8, 11, 2, 9, 10] + + If specific tie breaking approach is needed, use ``key`` parameter:: + + >>> topological_sort((V, E), key=lambda v: -v) + [7, 5, 11, 3, 10, 8, 9, 2] + + Only acyclic graphs can be sorted. If the input graph has a cycle, + then ``ValueError`` will be raised:: + + >>> topological_sort((V, E + [(10, 7)])) + Traceback (most recent call last): + ... + ValueError: cycle detected + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Topological_sorting + + """ + V, E = graph + + L = [] + S = set(V) + E = list(E) + + for v, u in E: + S.discard(u) + + if key is None: + def key(value): + return value + + S = sorted(S, key=key, reverse=True) + + while S: + node = S.pop() + L.append(node) + + for u, v in list(E): + if u == node: + E.remove((u, v)) + + for _u, _v in E: + if v == _v: + break + else: + kv = key(v) + + for i, s in enumerate(S): + ks = key(s) + + if kv > ks: + S.insert(i, v) + break + else: + S.append(v) + + if E: + raise ValueError("cycle detected") + else: + return L + + +def strongly_connected_components(G): + r""" + Strongly connected components of a directed graph in reverse topological + order. + + + Parameters + ========== + + graph : tuple[list, list[tuple[T, T]] + A tuple consisting of a list of vertices and a list of edges of + a graph whose strongly connected components are to be found. + + + Examples + ======== + + Consider a directed graph (in dot notation):: + + digraph { + A -> B + A -> C + B -> C + C -> B + B -> D + } + + .. graphviz:: + + digraph { + A -> B + A -> C + B -> C + C -> B + B -> D + } + + where vertices are the letters A, B, C and D. This graph can be encoded + using Python's elementary data structures as follows:: + + >>> V = ['A', 'B', 'C', 'D'] + >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')] + + The strongly connected components of this graph can be computed as + + >>> from sympy.utilities.iterables import strongly_connected_components + + >>> strongly_connected_components((V, E)) + [['D'], ['B', 'C'], ['A']] + + This also gives the components in reverse topological order. + + Since the subgraph containing B and C has a cycle they must be together in + a strongly connected component. A and D are connected to the rest of the + graph but not in a cyclic manner so they appear as their own strongly + connected components. + + + Notes + ===== + + The vertices of the graph must be hashable for the data structures used. + If the vertices are unhashable replace them with integer indices. + + This function uses Tarjan's algorithm to compute the strongly connected + components in `O(|V|+|E|)` (linear) time. + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component + .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm + + + See Also + ======== + + sympy.utilities.iterables.connected_components + + """ + # Map from a vertex to its neighbours + V, E = G + Gmap = {vi: [] for vi in V} + for v1, v2 in E: + Gmap[v1].append(v2) + return _strongly_connected_components(V, Gmap) + + +def _strongly_connected_components(V, Gmap): + """More efficient internal routine for strongly_connected_components""" + # + # Here V is an iterable of vertices and Gmap is a dict mapping each vertex + # to a list of neighbours e.g.: + # + # V = [0, 1, 2, 3] + # Gmap = {0: [2, 3], 1: [0]} + # + # For a large graph these data structures can often be created more + # efficiently then those expected by strongly_connected_components() which + # in this case would be + # + # V = [0, 1, 2, 3] + # Gmap = [(0, 2), (0, 3), (1, 0)] + # + # XXX: Maybe this should be the recommended function to use instead... + # + + # Non-recursive Tarjan's algorithm: + lowlink = {} + indices = {} + stack = OrderedDict() + callstack = [] + components = [] + nomore = object() + + def start(v): + index = len(stack) + indices[v] = lowlink[v] = index + stack[v] = None + callstack.append((v, iter(Gmap[v]))) + + def finish(v1): + # Finished a component? + if lowlink[v1] == indices[v1]: + component = [stack.popitem()[0]] + while component[-1] is not v1: + component.append(stack.popitem()[0]) + components.append(component[::-1]) + v2, _ = callstack.pop() + if callstack: + v1, _ = callstack[-1] + lowlink[v1] = min(lowlink[v1], lowlink[v2]) + + for v in V: + if v in indices: + continue + start(v) + while callstack: + v1, it1 = callstack[-1] + v2 = next(it1, nomore) + # Finished children of v1? + if v2 is nomore: + finish(v1) + # Recurse on v2 + elif v2 not in indices: + start(v2) + elif v2 in stack: + lowlink[v1] = min(lowlink[v1], indices[v2]) + + # Reverse topological sort order: + return components + + +def connected_components(G): + r""" + Connected components of an undirected graph or weakly connected components + of a directed graph. + + + Parameters + ========== + + graph : tuple[list, list[tuple[T, T]] + A tuple consisting of a list of vertices and a list of edges of + a graph whose connected components are to be found. + + + Examples + ======== + + + Given an undirected graph:: + + graph { + A -- B + C -- D + } + + .. graphviz:: + + graph { + A -- B + C -- D + } + + We can find the connected components using this function if we include + each edge in both directions:: + + >>> from sympy.utilities.iterables import connected_components + + >>> V = ['A', 'B', 'C', 'D'] + >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')] + >>> connected_components((V, E)) + [['A', 'B'], ['C', 'D']] + + The weakly connected components of a directed graph can found the same + way. + + + Notes + ===== + + The vertices of the graph must be hashable for the data structures used. + If the vertices are unhashable replace them with integer indices. + + This function uses Tarjan's algorithm to compute the connected components + in `O(|V|+|E|)` (linear) time. + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Component_%28graph_theory%29 + .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm + + + See Also + ======== + + sympy.utilities.iterables.strongly_connected_components + + """ + # Duplicate edges both ways so that the graph is effectively undirected + # and return the strongly connected components: + V, E = G + E_undirected = [] + for v1, v2 in E: + E_undirected.extend([(v1, v2), (v2, v1)]) + return strongly_connected_components((V, E_undirected)) + + +def rotate_left(x, y): + """ + Left rotates a list x by the number of steps specified + in y. + + Examples + ======== + + >>> from sympy.utilities.iterables import rotate_left + >>> a = [0, 1, 2] + >>> rotate_left(a, 1) + [1, 2, 0] + """ + if len(x) == 0: + return [] + y = y % len(x) + return x[y:] + x[:y] + + +def rotate_right(x, y): + """ + Right rotates a list x by the number of steps specified + in y. + + Examples + ======== + + >>> from sympy.utilities.iterables import rotate_right + >>> a = [0, 1, 2] + >>> rotate_right(a, 1) + [2, 0, 1] + """ + if len(x) == 0: + return [] + y = len(x) - y % len(x) + return x[y:] + x[:y] + + +def least_rotation(x, key=None): + ''' + Returns the number of steps of left rotation required to + obtain lexicographically minimal string/list/tuple, etc. + + Examples + ======== + + >>> from sympy.utilities.iterables import least_rotation, rotate_left + >>> a = [3, 1, 5, 1, 2] + >>> least_rotation(a) + 3 + >>> rotate_left(a, _) + [1, 2, 3, 1, 5] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation + + ''' + from sympy.functions.elementary.miscellaneous import Id + if key is None: key = Id + S = x + x # Concatenate string to it self to avoid modular arithmetic + f = [-1] * len(S) # Failure function + k = 0 # Least rotation of string found so far + for j in range(1,len(S)): + sj = S[j] + i = f[j-k-1] + while i != -1 and sj != S[k+i+1]: + if key(sj) < key(S[k+i+1]): + k = j-i-1 + i = f[i] + if sj != S[k+i+1]: + if key(sj) < key(S[k]): + k = j + f[j-k] = -1 + else: + f[j-k] = i+1 + return k + + +def multiset_combinations(m, n, g=None): + """ + Return the unique combinations of size ``n`` from multiset ``m``. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_combinations + >>> from itertools import combinations + >>> [''.join(i) for i in multiset_combinations('baby', 3)] + ['abb', 'aby', 'bby'] + + >>> def count(f, s): return len(list(f(s, 3))) + + The number of combinations depends on the number of letters; the + number of unique combinations depends on how the letters are + repeated. + + >>> s1 = 'abracadabra' + >>> s2 = 'banana tree' + >>> count(combinations, s1), count(multiset_combinations, s1) + (165, 23) + >>> count(combinations, s2), count(multiset_combinations, s2) + (165, 54) + + """ + from sympy.core.sorting import ordered + if g is None: + if isinstance(m, dict): + if any(as_int(v) < 0 for v in m.values()): + raise ValueError('counts cannot be negative') + N = sum(m.values()) + if n > N: + return + g = [[k, m[k]] for k in ordered(m)] + else: + m = list(m) + N = len(m) + if n > N: + return + try: + m = multiset(m) + g = [(k, m[k]) for k in ordered(m)] + except TypeError: + m = list(ordered(m)) + g = [list(i) for i in group(m, multiple=False)] + del m + else: + # not checking counts since g is intended for internal use + N = sum(v for k, v in g) + if n > N or not n: + yield [] + else: + for i, (k, v) in enumerate(g): + if v >= n: + yield [k]*n + v = n - 1 + for v in range(min(n, v), 0, -1): + for j in multiset_combinations(None, n - v, g[i + 1:]): + rv = [k]*v + j + if len(rv) == n: + yield rv + +def multiset_permutations(m, size=None, g=None): + """ + Return the unique permutations of multiset ``m``. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_permutations + >>> from sympy import factorial + >>> [''.join(i) for i in multiset_permutations('aab')] + ['aab', 'aba', 'baa'] + >>> factorial(len('banana')) + 720 + >>> len(list(multiset_permutations('banana'))) + 60 + """ + from sympy.core.sorting import ordered + if g is None: + if isinstance(m, dict): + if any(as_int(v) < 0 for v in m.values()): + raise ValueError('counts cannot be negative') + g = [[k, m[k]] for k in ordered(m)] + else: + m = list(ordered(m)) + g = [list(i) for i in group(m, multiple=False)] + del m + do = [gi for gi in g if gi[1] > 0] + SUM = sum([gi[1] for gi in do]) + if not do or size is not None and (size > SUM or size < 1): + if not do and size is None or size == 0: + yield [] + return + elif size == 1: + for k, v in do: + yield [k] + elif len(do) == 1: + k, v = do[0] + v = v if size is None else (size if size <= v else 0) + yield [k for i in range(v)] + elif all(v == 1 for k, v in do): + for p in permutations([k for k, v in do], size): + yield list(p) + else: + size = size if size is not None else SUM + for i, (k, v) in enumerate(do): + do[i][1] -= 1 + for j in multiset_permutations(None, size - 1, do): + if j: + yield [k] + j + do[i][1] += 1 + + +def _partition(seq, vector, m=None): + """ + Return the partition of seq as specified by the partition vector. + + Examples + ======== + + >>> from sympy.utilities.iterables import _partition + >>> _partition('abcde', [1, 0, 1, 2, 0]) + [['b', 'e'], ['a', 'c'], ['d']] + + Specifying the number of bins in the partition is optional: + + >>> _partition('abcde', [1, 0, 1, 2, 0], 3) + [['b', 'e'], ['a', 'c'], ['d']] + + The output of _set_partitions can be passed as follows: + + >>> output = (3, [1, 0, 1, 2, 0]) + >>> _partition('abcde', *output) + [['b', 'e'], ['a', 'c'], ['d']] + + See Also + ======== + + combinatorics.partitions.Partition.from_rgs + + """ + if m is None: + m = max(vector) + 1 + elif isinstance(vector, int): # entered as m, vector + vector, m = m, vector + p = [[] for i in range(m)] + for i, v in enumerate(vector): + p[v].append(seq[i]) + return p + + +def _set_partitions(n): + """Cycle through all partitions of n elements, yielding the + current number of partitions, ``m``, and a mutable list, ``q`` + such that ``element[i]`` is in part ``q[i]`` of the partition. + + NOTE: ``q`` is modified in place and generally should not be changed + between function calls. + + Examples + ======== + + >>> from sympy.utilities.iterables import _set_partitions, _partition + >>> for m, q in _set_partitions(3): + ... print('%s %s %s' % (m, q, _partition('abc', q, m))) + 1 [0, 0, 0] [['a', 'b', 'c']] + 2 [0, 0, 1] [['a', 'b'], ['c']] + 2 [0, 1, 0] [['a', 'c'], ['b']] + 2 [0, 1, 1] [['a'], ['b', 'c']] + 3 [0, 1, 2] [['a'], ['b'], ['c']] + + Notes + ===== + + This algorithm is similar to, and solves the same problem as, + Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer + Programming. Knuth uses the term "restricted growth string" where + this code refers to a "partition vector". In each case, the meaning is + the same: the value in the ith element of the vector specifies to + which part the ith set element is to be assigned. + + At the lowest level, this code implements an n-digit big-endian + counter (stored in the array q) which is incremented (with carries) to + get the next partition in the sequence. A special twist is that a + digit is constrained to be at most one greater than the maximum of all + the digits to the left of it. The array p maintains this maximum, so + that the code can efficiently decide when a digit can be incremented + in place or whether it needs to be reset to 0 and trigger a carry to + the next digit. The enumeration starts with all the digits 0 (which + corresponds to all the set elements being assigned to the same 0th + part), and ends with 0123...n, which corresponds to each set element + being assigned to a different, singleton, part. + + This routine was rewritten to use 0-based lists while trying to + preserve the beauty and efficiency of the original algorithm. + + References + ========== + + .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms, + 2nd Ed, p 91, algorithm "nexequ". Available online from + https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed + November 17, 2012). + + """ + p = [0]*n + q = [0]*n + nc = 1 + yield nc, q + while nc != n: + m = n + while 1: + m -= 1 + i = q[m] + if p[i] != 1: + break + q[m] = 0 + i += 1 + q[m] = i + m += 1 + nc += m - n + p[0] += n - m + if i == nc: + p[nc] = 0 + nc += 1 + p[i - 1] -= 1 + p[i] += 1 + yield nc, q + + +def multiset_partitions(multiset, m=None): + """ + Return unique partitions of the given multiset (in list form). + If ``m`` is None, all multisets will be returned, otherwise only + partitions with ``m`` parts will be returned. + + If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1] + will be supplied. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_partitions + >>> list(multiset_partitions([1, 2, 3, 4], 2)) + [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], + [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], + [[1], [2, 3, 4]]] + >>> list(multiset_partitions([1, 2, 3, 4], 1)) + [[[1, 2, 3, 4]]] + + Only unique partitions are returned and these will be returned in a + canonical order regardless of the order of the input: + + >>> a = [1, 2, 2, 1] + >>> ans = list(multiset_partitions(a, 2)) + >>> a.sort() + >>> list(multiset_partitions(a, 2)) == ans + True + >>> a = range(3, 1, -1) + >>> (list(multiset_partitions(a)) == + ... list(multiset_partitions(sorted(a)))) + True + + If m is omitted then all partitions will be returned: + + >>> list(multiset_partitions([1, 1, 2])) + [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]] + >>> list(multiset_partitions([1]*3)) + [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] + + Counting + ======== + + The number of partitions of a set is given by the bell number: + + >>> from sympy import bell + >>> len(list(multiset_partitions(5))) == bell(5) == 52 + True + + The number of partitions of length k from a set of size n is given by the + Stirling Number of the 2nd kind: + + >>> from sympy.functions.combinatorial.numbers import stirling + >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15 + True + + These comments on counting apply to *sets*, not multisets. + + Notes + ===== + + When all the elements are the same in the multiset, the order + of the returned partitions is determined by the ``partitions`` + routine. If one is counting partitions then it is better to use + the ``nT`` function. + + See Also + ======== + + partitions + sympy.combinatorics.partitions.Partition + sympy.combinatorics.partitions.IntegerPartition + sympy.functions.combinatorial.numbers.nT + + """ + # This function looks at the supplied input and dispatches to + # several special-case routines as they apply. + if isinstance(multiset, int): + n = multiset + if m and m > n: + return + multiset = list(range(n)) + if m == 1: + yield [multiset[:]] + return + + # If m is not None, it can sometimes be faster to use + # MultisetPartitionTraverser.enum_range() even for inputs + # which are sets. Since the _set_partitions code is quite + # fast, this is only advantageous when the overall set + # partitions outnumber those with the desired number of parts + # by a large factor. (At least 60.) Such a switch is not + # currently implemented. + for nc, q in _set_partitions(n): + if m is None or nc == m: + rv = [[] for i in range(nc)] + for i in range(n): + rv[q[i]].append(multiset[i]) + yield rv + return + + if len(multiset) == 1 and isinstance(multiset, str): + multiset = [multiset] + + if not has_variety(multiset): + # Only one component, repeated n times. The resulting + # partitions correspond to partitions of integer n. + n = len(multiset) + if m and m > n: + return + if m == 1: + yield [multiset[:]] + return + x = multiset[:1] + for size, p in partitions(n, m, size=True): + if m is None or size == m: + rv = [] + for k in sorted(p): + rv.extend([x*k]*p[k]) + yield rv + else: + from sympy.core.sorting import ordered + multiset = list(ordered(multiset)) + n = len(multiset) + if m and m > n: + return + if m == 1: + yield [multiset[:]] + return + + # Split the information of the multiset into two lists - + # one of the elements themselves, and one (of the same length) + # giving the number of repeats for the corresponding element. + elements, multiplicities = zip(*group(multiset, False)) + + if len(elements) < len(multiset): + # General case - multiset with more than one distinct element + # and at least one element repeated more than once. + if m: + mpt = MultisetPartitionTraverser() + for state in mpt.enum_range(multiplicities, m-1, m): + yield list_visitor(state, elements) + else: + for state in multiset_partitions_taocp(multiplicities): + yield list_visitor(state, elements) + else: + # Set partitions case - no repeated elements. Pretty much + # same as int argument case above, with same possible, but + # currently unimplemented optimization for some cases when + # m is not None + for nc, q in _set_partitions(n): + if m is None or nc == m: + rv = [[] for i in range(nc)] + for i in range(n): + rv[q[i]].append(i) + yield [[multiset[j] for j in i] for i in rv] + + +def partitions(n, m=None, k=None, size=False): + """Generate all partitions of positive integer, n. + + Parameters + ========== + + m : integer (default gives partitions of all sizes) + limits number of parts in partition (mnemonic: m, maximum parts) + k : integer (default gives partitions number from 1 through n) + limits the numbers that are kept in the partition (mnemonic: k, keys) + size : bool (default False, only partition is returned) + when ``True`` then (M, P) is returned where M is the sum of the + multiplicities and P is the generated partition. + + Each partition is represented as a dictionary, mapping an integer + to the number of copies of that integer in the partition. For example, + the first partition of 4 returned is {4: 1}, "4: one of them". + + Examples + ======== + + >>> from sympy.utilities.iterables import partitions + + The numbers appearing in the partition (the key of the returned dict) + are limited with k: + + >>> for p in partitions(6, k=2): # doctest: +SKIP + ... print(p) + {2: 3} + {1: 2, 2: 2} + {1: 4, 2: 1} + {1: 6} + + The maximum number of parts in the partition (the sum of the values in + the returned dict) are limited with m (default value, None, gives + partitions from 1 through n): + + >>> for p in partitions(6, m=2): # doctest: +SKIP + ... print(p) + ... + {6: 1} + {1: 1, 5: 1} + {2: 1, 4: 1} + {3: 2} + + References + ========== + + .. [1] modified from Tim Peter's version to allow for k and m values: + https://code.activestate.com/recipes/218332-generator-for-integer-partitions/ + + See Also + ======== + + sympy.combinatorics.partitions.Partition + sympy.combinatorics.partitions.IntegerPartition + + """ + if (n <= 0 or + m is not None and m < 1 or + k is not None and k < 1 or + m and k and m*k < n): + # the empty set is the only way to handle these inputs + # and returning {} to represent it is consistent with + # the counting convention, e.g. nT(0) == 1. + if size: + yield 0, {} + else: + yield {} + return + + if m is None: + m = n + else: + m = min(m, n) + k = min(k or n, n) + + n, m, k = as_int(n), as_int(m), as_int(k) + q, r = divmod(n, k) + ms = {k: q} + keys = [k] # ms.keys(), from largest to smallest + if r: + ms[r] = 1 + keys.append(r) + room = m - q - bool(r) + if size: + yield sum(ms.values()), ms.copy() + else: + yield ms.copy() + + while keys != [1]: + # Reuse any 1's. + if keys[-1] == 1: + del keys[-1] + reuse = ms.pop(1) + room += reuse + else: + reuse = 0 + + while 1: + # Let i be the smallest key larger than 1. Reuse one + # instance of i. + i = keys[-1] + newcount = ms[i] = ms[i] - 1 + reuse += i + if newcount == 0: + del keys[-1], ms[i] + room += 1 + + # Break the remainder into pieces of size i-1. + i -= 1 + q, r = divmod(reuse, i) + need = q + bool(r) + if need > room: + if not keys: + return + continue + + ms[i] = q + keys.append(i) + if r: + ms[r] = 1 + keys.append(r) + break + room -= need + if size: + yield sum(ms.values()), ms.copy() + else: + yield ms.copy() + + +def ordered_partitions(n, m=None, sort=True): + """Generates ordered partitions of integer ``n``. + + Parameters + ========== + + m : integer (default None) + The default value gives partitions of all sizes else only + those with size m. In addition, if ``m`` is not None then + partitions are generated *in place* (see examples). + sort : bool (default True) + Controls whether partitions are + returned in sorted order when ``m`` is not None; when False, + the partitions are returned as fast as possible with elements + sorted, but when m|n the partitions will not be in + ascending lexicographical order. + + Examples + ======== + + >>> from sympy.utilities.iterables import ordered_partitions + + All partitions of 5 in ascending lexicographical: + + >>> for p in ordered_partitions(5): + ... print(p) + [1, 1, 1, 1, 1] + [1, 1, 1, 2] + [1, 1, 3] + [1, 2, 2] + [1, 4] + [2, 3] + [5] + + Only partitions of 5 with two parts: + + >>> for p in ordered_partitions(5, 2): + ... print(p) + [1, 4] + [2, 3] + + When ``m`` is given, a given list objects will be used more than + once for speed reasons so you will not see the correct partitions + unless you make a copy of each as it is generated: + + >>> [p for p in ordered_partitions(7, 3)] + [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]] + >>> [list(p) for p in ordered_partitions(7, 3)] + [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]] + + When ``n`` is a multiple of ``m``, the elements are still sorted + but the partitions themselves will be *unordered* if sort is False; + the default is to return them in ascending lexicographical order. + + >>> for p in ordered_partitions(6, 2): + ... print(p) + [1, 5] + [2, 4] + [3, 3] + + But if speed is more important than ordering, sort can be set to + False: + + >>> for p in ordered_partitions(6, 2, sort=False): + ... print(p) + [1, 5] + [3, 3] + [2, 4] + + References + ========== + + .. [1] Generating Integer Partitions, [online], + Available: https://jeromekelleher.net/generating-integer-partitions.html + .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All + Partitions: A Comparison Of Two Encodings", [online], + Available: https://arxiv.org/pdf/0909.2331v2.pdf + """ + if n < 1 or m is not None and m < 1: + # the empty set is the only way to handle these inputs + # and returning {} to represent it is consistent with + # the counting convention, e.g. nT(0) == 1. + yield [] + return + + if m is None: + # The list `a`'s leading elements contain the partition in which + # y is the biggest element and x is either the same as y or the + # 2nd largest element; v and w are adjacent element indices + # to which x and y are being assigned, respectively. + a = [1]*n + y = -1 + v = n + while v > 0: + v -= 1 + x = a[v] + 1 + while y >= 2 * x: + a[v] = x + y -= x + v += 1 + w = v + 1 + while x <= y: + a[v] = x + a[w] = y + yield a[:w + 1] + x += 1 + y -= 1 + a[v] = x + y + y = a[v] - 1 + yield a[:w] + elif m == 1: + yield [n] + elif n == m: + yield [1]*n + else: + # recursively generate partitions of size m + for b in range(1, n//m + 1): + a = [b]*m + x = n - b*m + if not x: + if sort: + yield a + elif not sort and x <= m: + for ax in ordered_partitions(x, sort=False): + mi = len(ax) + a[-mi:] = [i + b for i in ax] + yield a + a[-mi:] = [b]*mi + else: + for mi in range(1, m): + for ax in ordered_partitions(x, mi, sort=True): + a[-mi:] = [i + b for i in ax] + yield a + a[-mi:] = [b]*mi + + +def binary_partitions(n): + """ + Generates the binary partition of n. + + A binary partition consists only of numbers that are + powers of two. Each step reduces a `2^{k+1}` to `2^k` and + `2^k`. Thus 16 is converted to 8 and 8. + + Examples + ======== + + >>> from sympy.utilities.iterables import binary_partitions + >>> for i in binary_partitions(5): + ... print(i) + ... + [4, 1] + [2, 2, 1] + [2, 1, 1, 1] + [1, 1, 1, 1, 1] + + References + ========== + + .. [1] TAOCP 4, section 7.2.1.5, problem 64 + + """ + from math import ceil, log + power = int(2**(ceil(log(n, 2)))) + acc = 0 + partition = [] + while power: + if acc + power <= n: + partition.append(power) + acc += power + power >>= 1 + + last_num = len(partition) - 1 - (n & 1) + while last_num >= 0: + yield partition + if partition[last_num] == 2: + partition[last_num] = 1 + partition.append(1) + last_num -= 1 + continue + partition.append(1) + partition[last_num] >>= 1 + x = partition[last_num + 1] = partition[last_num] + last_num += 1 + while x > 1: + if x <= len(partition) - last_num - 1: + del partition[-x + 1:] + last_num += 1 + partition[last_num] = x + else: + x >>= 1 + yield [1]*n + + +def has_dups(seq): + """Return True if there are any duplicate elements in ``seq``. + + Examples + ======== + + >>> from sympy import has_dups, Dict, Set + >>> has_dups((1, 2, 1)) + True + >>> has_dups(range(3)) + False + >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict())) + True + """ + from sympy.core.containers import Dict + from sympy.sets.sets import Set + if isinstance(seq, (dict, set, Dict, Set)): + return False + unique = set() + try: + return any(True for s in seq if s in unique or unique.add(s)) + except TypeError: + return len(seq) != len(list(uniq(seq))) + + +def has_variety(seq): + """Return True if there are any different elements in ``seq``. + + Examples + ======== + + >>> from sympy import has_variety + + >>> has_variety((1, 2, 1)) + True + >>> has_variety((1, 1, 1)) + False + """ + for i, s in enumerate(seq): + if i == 0: + sentinel = s + else: + if s != sentinel: + return True + return False + + +def uniq(seq, result=None): + """ + Yield unique elements from ``seq`` as an iterator. The second + parameter ``result`` is used internally; it is not necessary + to pass anything for this. + + Note: changing the sequence during iteration will raise a + RuntimeError if the size of the sequence is known; if you pass + an iterator and advance the iterator you will change the + output of this routine but there will be no warning. + + Examples + ======== + + >>> from sympy.utilities.iterables import uniq + >>> dat = [1, 4, 1, 5, 4, 2, 1, 2] + >>> type(uniq(dat)) in (list, tuple) + False + + >>> list(uniq(dat)) + [1, 4, 5, 2] + >>> list(uniq(x for x in dat)) + [1, 4, 5, 2] + >>> list(uniq([[1], [2, 1], [1]])) + [[1], [2, 1]] + """ + try: + n = len(seq) + except TypeError: + n = None + def check(): + # check that size of seq did not change during iteration; + # if n == None the object won't support size changing, e.g. + # an iterator can't be changed + if n is not None and len(seq) != n: + raise RuntimeError('sequence changed size during iteration') + try: + seen = set() + result = result or [] + for i, s in enumerate(seq): + if not (s in seen or seen.add(s)): + yield s + check() + except TypeError: + if s not in result: + yield s + check() + result.append(s) + if hasattr(seq, '__getitem__'): + yield from uniq(seq[i + 1:], result) + else: + yield from uniq(seq, result) + + +def generate_bell(n): + """Return permutations of [0, 1, ..., n - 1] such that each permutation + differs from the last by the exchange of a single pair of neighbors. + The ``n!`` permutations are returned as an iterator. In order to obtain + the next permutation from a random starting permutation, use the + ``next_trotterjohnson`` method of the Permutation class (which generates + the same sequence in a different manner). + + Examples + ======== + + >>> from itertools import permutations + >>> from sympy.utilities.iterables import generate_bell + >>> from sympy import zeros, Matrix + + This is the sort of permutation used in the ringing of physical bells, + and does not produce permutations in lexicographical order. Rather, the + permutations differ from each other by exactly one inversion, and the + position at which the swapping occurs varies periodically in a simple + fashion. Consider the first few permutations of 4 elements generated + by ``permutations`` and ``generate_bell``: + + >>> list(permutations(range(4)))[:5] + [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)] + >>> list(generate_bell(4))[:5] + [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)] + + Notice how the 2nd and 3rd lexicographical permutations have 3 elements + out of place whereas each "bell" permutation always has only two + elements out of place relative to the previous permutation (and so the + signature (+/-1) of a permutation is opposite of the signature of the + previous permutation). + + How the position of inversion varies across the elements can be seen + by tracing out where the largest number appears in the permutations: + + >>> m = zeros(4, 24) + >>> for i, p in enumerate(generate_bell(4)): + ... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero + >>> m.print_nonzero('X') + [XXX XXXXXX XXXXXX XXX] + [XX XX XXXX XX XXXX XX XX] + [X XXXX XX XXXX XX XXXX X] + [ XXXXXX XXXXXX XXXXXX ] + + See Also + ======== + + sympy.combinatorics.permutations.Permutation.next_trotterjohnson + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Method_ringing + + .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018 + + .. [3] https://web.archive.org/web/20160313023044/http://programminggeeks.com/bell-algorithm-for-permutation/ + + .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm + + .. [5] Generating involutions, derangements, and relatives by ECO + Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010 + + """ + n = as_int(n) + if n < 1: + raise ValueError('n must be a positive integer') + if n == 1: + yield (0,) + elif n == 2: + yield (0, 1) + yield (1, 0) + elif n == 3: + yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] + else: + m = n - 1 + op = [0] + [-1]*m + l = list(range(n)) + while True: + yield tuple(l) + # find biggest element with op + big = None, -1 # idx, value + for i in range(n): + if op[i] and l[i] > big[1]: + big = i, l[i] + i, _ = big + if i is None: + break # there are no ops left + # swap it with neighbor in the indicated direction + j = i + op[i] + l[i], l[j] = l[j], l[i] + op[i], op[j] = op[j], op[i] + # if it landed at the end or if the neighbor in the same + # direction is bigger then turn off op + if j == 0 or j == m or l[j + op[j]] > l[j]: + op[j] = 0 + # any element bigger to the left gets +1 op + for i in range(j): + if l[i] > l[j]: + op[i] = 1 + # any element bigger to the right gets -1 op + for i in range(j + 1, n): + if l[i] > l[j]: + op[i] = -1 + + +def generate_involutions(n): + """ + Generates involutions. + + An involution is a permutation that when multiplied + by itself equals the identity permutation. In this + implementation the involutions are generated using + Fixed Points. + + Alternatively, an involution can be considered as + a permutation that does not contain any cycles with + a length that is greater than two. + + Examples + ======== + + >>> from sympy.utilities.iterables import generate_involutions + >>> list(generate_involutions(3)) + [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)] + >>> len(list(generate_involutions(4))) + 10 + + References + ========== + + .. [1] https://mathworld.wolfram.com/PermutationInvolution.html + + """ + idx = list(range(n)) + for p in permutations(idx): + for i in idx: + if p[p[i]] != i: + break + else: + yield p + + +def multiset_derangements(s): + """Generate derangements of the elements of s *in place*. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_derangements, uniq + + Because the derangements of multisets (not sets) are generated + in place, copies of the return value must be made if a collection + of derangements is desired or else all values will be the same: + + >>> list(uniq([i for i in multiset_derangements('1233')])) + [[None, None, None, None]] + >>> [i.copy() for i in multiset_derangements('1233')] + [['3', '3', '1', '2'], ['3', '3', '2', '1']] + >>> [''.join(i) for i in multiset_derangements('1233')] + ['3312', '3321'] + """ + from sympy.core.sorting import ordered + # create multiset dictionary of hashable elements or else + # remap elements to integers + try: + ms = multiset(s) + except TypeError: + # give each element a canonical integer value + key = dict(enumerate(ordered(uniq(s)))) + h = [] + for si in s: + for k in key: + if key[k] == si: + h.append(k) + break + for i in multiset_derangements(h): + yield [key[j] for j in i] + return + + mx = max(ms.values()) # max repetition of any element + n = len(s) # the number of elements + + ## special cases + + # 1) one element has more than half the total cardinality of s: no + # derangements are possible. + if mx*2 > n: + return + + # 2) all elements appear once: singletons + if len(ms) == n: + yield from _set_derangements(s) + return + + # find the first element that is repeated the most to place + # in the following two special cases where the selection + # is unambiguous: either there are two elements with multiplicity + # of mx or else there is only one with multiplicity mx + for M in ms: + if ms[M] == mx: + break + + inonM = [i for i in range(n) if s[i] != M] # location of non-M + iM = [i for i in range(n) if s[i] == M] # locations of M + rv = [None]*n + + # 3) half are the same + if 2*mx == n: + # M goes into non-M locations + for i in inonM: + rv[i] = M + # permutations of non-M go to M locations + for p in multiset_permutations([s[i] for i in inonM]): + for i, pi in zip(iM, p): + rv[i] = pi + yield rv + # clean-up (and encourages proper use of routine) + rv[:] = [None]*n + return + + # 4) single repeat covers all but 1 of the non-repeats: + # if there is one repeat then the multiset of the values + # of ms would be {mx: 1, 1: n - mx}, i.e. there would + # be n - mx + 1 values with the condition that n - 2*mx = 1 + if n - 2*mx == 1 and len(ms.values()) == n - mx + 1: + for i, i1 in enumerate(inonM): + ifill = inonM[:i] + inonM[i+1:] + for j in ifill: + rv[j] = M + for p in permutations([s[j] for j in ifill]): + rv[i1] = s[i1] + for j, pi in zip(iM, p): + rv[j] = pi + k = i1 + for j in iM: + rv[j], rv[k] = rv[k], rv[j] + yield rv + k = j + # clean-up (and encourages proper use of routine) + rv[:] = [None]*n + return + + ## general case is handled with 3 helpers: + # 1) `finish_derangements` will place the last two elements + # which have arbitrary multiplicities, e.g. for multiset + # {c: 3, a: 2, b: 2}, the last two elements are a and b + # 2) `iopen` will tell where a given element can be placed + # 3) `do` will recursively place elements into subsets of + # valid locations + + def finish_derangements(): + """Place the last two elements into the partially completed + derangement, and yield the results. + """ + + a = take[1][0] # penultimate element + a_ct = take[1][1] + b = take[0][0] # last element to be placed + b_ct = take[0][1] + + # split the indexes of the not-already-assigned elements of rv into + # three categories + forced_a = [] # positions which must have an a + forced_b = [] # positions which must have a b + open_free = [] # positions which could take either + for i in range(len(s)): + if rv[i] is None: + if s[i] == a: + forced_b.append(i) + elif s[i] == b: + forced_a.append(i) + else: + open_free.append(i) + + if len(forced_a) > a_ct or len(forced_b) > b_ct: + # No derangement possible + return + + for i in forced_a: + rv[i] = a + for i in forced_b: + rv[i] = b + for a_place in combinations(open_free, a_ct - len(forced_a)): + for a_pos in a_place: + rv[a_pos] = a + for i in open_free: + if rv[i] is None: # anything not in the subset is set to b + rv[i] = b + yield rv + # Clean up/undo the final placements + for i in open_free: + rv[i] = None + + # additional cleanup - clear forced_a, forced_b + for i in forced_a: + rv[i] = None + for i in forced_b: + rv[i] = None + + def iopen(v): + # return indices at which element v can be placed in rv: + # locations which are not already occupied if that location + # does not already contain v in the same location of s + return [i for i in range(n) if rv[i] is None and s[i] != v] + + def do(j): + if j == 1: + # handle the last two elements (regardless of multiplicity) + # with a special method + yield from finish_derangements() + else: + # place the mx elements of M into a subset of places + # into which it can be replaced + M, mx = take[j] + for i in combinations(iopen(M), mx): + # place M + for ii in i: + rv[ii] = M + # recursively place the next element + yield from do(j - 1) + # mark positions where M was placed as once again + # open for placement of other elements + for ii in i: + rv[ii] = None + + # process elements in order of canonically decreasing multiplicity + take = sorted(ms.items(), key=lambda x:(x[1], x[0])) + yield from do(len(take) - 1) + rv[:] = [None]*n + + +def random_derangement(t, choice=None, strict=True): + """Return a list of elements in which none are in the same positions + as they were originally. If an element fills more than half of the positions + then an error will be raised since no derangement is possible. To obtain + a derangement of as many items as possible--with some of the most numerous + remaining in their original positions--pass `strict=False`. To produce a + pseudorandom derangment, pass a pseudorandom selector like `choice` (see + below). + + Examples + ======== + + >>> from sympy.utilities.iterables import random_derangement + >>> t = 'SymPy: a CAS in pure Python' + >>> d = random_derangement(t) + >>> all(i != j for i, j in zip(d, t)) + True + + A predictable result can be obtained by using a pseudorandom + generator for the choice: + + >>> from sympy.core.random import seed, choice as c + >>> seed(1) + >>> d = [''.join(random_derangement(t, c)) for i in range(5)] + >>> assert len(set(d)) != 1 # we got different values + + By reseeding, the same sequence can be obtained: + + >>> seed(1) + >>> d2 = [''.join(random_derangement(t, c)) for i in range(5)] + >>> assert d == d2 + """ + if choice is None: + import secrets + choice = secrets.choice + def shuffle(rv): + '''Knuth shuffle''' + for i in range(len(rv) - 1, 0, -1): + x = choice(rv[:i + 1]) + j = rv.index(x) + rv[i], rv[j] = rv[j], rv[i] + def pick(rv, n): + '''shuffle rv and return the first n values + ''' + shuffle(rv) + return rv[:n] + ms = multiset(t) + tot = len(t) + ms = sorted(ms.items(), key=lambda x: x[1]) + # if there are not enough spaces for the most + # plentiful element to move to then some of them + # will have to stay in place + M, mx = ms[-1] + n = len(t) + xs = 2*mx - tot + if xs > 0: + if strict: + raise ValueError('no derangement possible') + opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]] + pick(opts, xs) + stay = sorted(opts[:xs]) + rv = list(t) + for i in reversed(stay): + rv.pop(i) + rv = random_derangement(rv, choice) + for i in stay: + rv.insert(i, ms[-1][0]) + return ''.join(rv) if type(t) is str else rv + # the normal derangement calculated from here + if n == len(ms): + # approx 1/3 will succeed + rv = list(t) + while True: + shuffle(rv) + if all(i != j for i,j in zip(rv, t)): + break + else: + # general case + rv = [None]*n + while True: + j = 0 + while j > -len(ms): # do most numerous first + j -= 1 + e, c = ms[j] + opts = [i for i in range(n) if rv[i] is None and t[i] != e] + if len(opts) < c: + for i in range(n): + rv[i] = None + break # try again + pick(opts, c) + for i in range(c): + rv[opts[i]] = e + else: + return rv + return rv + + +def _set_derangements(s): + """ + yield derangements of items in ``s`` which are assumed to contain + no repeated elements + """ + if len(s) < 2: + return + if len(s) == 2: + yield [s[1], s[0]] + return + if len(s) == 3: + yield [s[1], s[2], s[0]] + yield [s[2], s[0], s[1]] + return + for p in permutations(s): + if not any(i == j for i, j in zip(p, s)): + yield list(p) + + +def generate_derangements(s): + """ + Return unique derangements of the elements of iterable ``s``. + + Examples + ======== + + >>> from sympy.utilities.iterables import generate_derangements + >>> list(generate_derangements([0, 1, 2])) + [[1, 2, 0], [2, 0, 1]] + >>> list(generate_derangements([0, 1, 2, 2])) + [[2, 2, 0, 1], [2, 2, 1, 0]] + >>> list(generate_derangements([0, 1, 1])) + [] + + See Also + ======== + + sympy.functions.combinatorial.factorials.subfactorial + + """ + if not has_dups(s): + yield from _set_derangements(s) + else: + for p in multiset_derangements(s): + yield list(p) + + +def necklaces(n, k, free=False): + """ + A routine to generate necklaces that may (free=True) or may not + (free=False) be turned over to be viewed. The "necklaces" returned + are comprised of ``n`` integers (beads) with ``k`` different + values (colors). Only unique necklaces are returned. + + Examples + ======== + + >>> from sympy.utilities.iterables import necklaces, bracelets + >>> def show(s, i): + ... return ''.join(s[j] for j in i) + + The "unrestricted necklace" is sometimes also referred to as a + "bracelet" (an object that can be turned over, a sequence that can + be reversed) and the term "necklace" is used to imply a sequence + that cannot be reversed. So ACB == ABC for a bracelet (rotate and + reverse) while the two are different for a necklace since rotation + alone cannot make the two sequences the same. + + (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.) + + >>> B = [show('ABC', i) for i in bracelets(3, 3)] + >>> N = [show('ABC', i) for i in necklaces(3, 3)] + >>> set(N) - set(B) + {'ACB'} + + >>> list(necklaces(4, 2)) + [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), + (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)] + + >>> [show('.o', i) for i in bracelets(4, 2)] + ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo'] + + References + ========== + + .. [1] https://mathworld.wolfram.com/Necklace.html + + .. [2] Frank Ruskey, Carla Savage, and Terry Min Yih Wang, + Generating necklaces, Journal of Algorithms 13 (1992), 414-430; + https://doi.org/10.1016/0196-6774(92)90047-G + + """ + # The FKM algorithm + if k == 0 and n > 0: + return + a = [0]*n + yield tuple(a) + if n == 0: + return + while True: + i = n - 1 + while a[i] == k - 1: + i -= 1 + if i == -1: + return + a[i] += 1 + for j in range(n - i - 1): + a[j + i + 1] = a[j] + if n % (i + 1) == 0 and (not free or all(a <= a[j::-1] + a[-1:j:-1] for j in range(n - 1))): + # No need to test j = n - 1. + yield tuple(a) + + +def bracelets(n, k): + """Wrapper to necklaces to return a free (unrestricted) necklace.""" + return necklaces(n, k, free=True) + + +def generate_oriented_forest(n): + """ + This algorithm generates oriented forests. + + An oriented graph is a directed graph having no symmetric pair of directed + edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can + also be described as a disjoint union of trees, which are graphs in which + any two vertices are connected by exactly one simple path. + + Examples + ======== + + >>> from sympy.utilities.iterables import generate_oriented_forest + >>> list(generate_oriented_forest(4)) + [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \ + [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]] + + References + ========== + + .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of + rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980 + + .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python + + """ + P = list(range(-1, n)) + while True: + yield P[1:] + if P[n] > 0: + P[n] = P[P[n]] + else: + for p in range(n - 1, 0, -1): + if P[p] != 0: + target = P[p] - 1 + for q in range(p - 1, 0, -1): + if P[q] == target: + break + offset = p - q + for i in range(p, n + 1): + P[i] = P[i - offset] + break + else: + break + + +def minlex(seq, directed=True, key=None): + r""" + Return the rotation of the sequence in which the lexically smallest + elements appear first, e.g. `cba \rightarrow acb`. + + The sequence returned is a tuple, unless the input sequence is a string + in which case a string is returned. + + If ``directed`` is False then the smaller of the sequence and the + reversed sequence is returned, e.g. `cba \rightarrow abc`. + + If ``key`` is not None then it is used to extract a comparison key from each element in iterable. + + Examples + ======== + + >>> from sympy.combinatorics.polyhedron import minlex + >>> minlex((1, 2, 0)) + (0, 1, 2) + >>> minlex((1, 0, 2)) + (0, 2, 1) + >>> minlex((1, 0, 2), directed=False) + (0, 1, 2) + + >>> minlex('11010011000', directed=True) + '00011010011' + >>> minlex('11010011000', directed=False) + '00011001011' + + >>> minlex(('bb', 'aaa', 'c', 'a')) + ('a', 'bb', 'aaa', 'c') + >>> minlex(('bb', 'aaa', 'c', 'a'), key=len) + ('c', 'a', 'bb', 'aaa') + + """ + from sympy.functions.elementary.miscellaneous import Id + if key is None: key = Id + best = rotate_left(seq, least_rotation(seq, key=key)) + if not directed: + rseq = seq[::-1] + rbest = rotate_left(rseq, least_rotation(rseq, key=key)) + best = min(best, rbest, key=key) + + # Convert to tuple, unless we started with a string. + return tuple(best) if not isinstance(seq, str) else best + + +def runs(seq, op=gt): + """Group the sequence into lists in which successive elements + all compare the same with the comparison operator, ``op``: + op(seq[i + 1], seq[i]) is True from all elements in a run. + + Examples + ======== + + >>> from sympy.utilities.iterables import runs + >>> from operator import ge + >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2]) + [[0, 1, 2], [2], [1, 4], [3], [2], [2]] + >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge) + [[0, 1, 2, 2], [1, 4], [3], [2, 2]] + """ + cycles = [] + seq = iter(seq) + try: + run = [next(seq)] + except StopIteration: + return [] + while True: + try: + ei = next(seq) + except StopIteration: + break + if op(ei, run[-1]): + run.append(ei) + continue + else: + cycles.append(run) + run = [ei] + if run: + cycles.append(run) + return cycles + + +def sequence_partitions(l, n, /): + r"""Returns the partition of sequence $l$ into $n$ bins + + Explanation + =========== + + Given the sequence $l_1 \cdots l_m \in V^+$ where + $V^+$ is the Kleene plus of $V$ + + The set of $n$ partitions of $l$ is defined as: + + .. math:: + \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+, + s_1 \cdots s_n = l_1 \cdots l_m\} + + Parameters + ========== + + l : Sequence[T] + A nonempty sequence of any Python objects + + n : int + A positive integer + + Yields + ====== + + out : list[Sequence[T]] + A list of sequences with concatenation equals $l$. + This should conform with the type of $l$. + + Examples + ======== + + >>> from sympy.utilities.iterables import sequence_partitions + >>> for out in sequence_partitions([1, 2, 3, 4], 2): + ... print(out) + [[1], [2, 3, 4]] + [[1, 2], [3, 4]] + [[1, 2, 3], [4]] + + Notes + ===== + + This is modified version of EnricoGiampieri's partition generator + from https://stackoverflow.com/questions/13131491/partition-n-items-into-k-bins-in-python-lazily + + See Also + ======== + + sequence_partitions_empty + """ + # Asserting l is nonempty is done only for sanity check + if n == 1 and l: + yield [l] + return + for i in range(1, len(l)): + for part in sequence_partitions(l[i:], n - 1): + yield [l[:i]] + part + + +def sequence_partitions_empty(l, n, /): + r"""Returns the partition of sequence $l$ into $n$ bins with + empty sequence + + Explanation + =========== + + Given the sequence $l_1 \cdots l_m \in V^*$ where + $V^*$ is the Kleene star of $V$ + + The set of $n$ partitions of $l$ is defined as: + + .. math:: + \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*, + s_1 \cdots s_n = l_1 \cdots l_m\} + + There are more combinations than :func:`sequence_partitions` because + empty sequence can fill everywhere, so we try to provide different + utility for this. + + Parameters + ========== + + l : Sequence[T] + A sequence of any Python objects (can be possibly empty) + + n : int + A positive integer + + Yields + ====== + + out : list[Sequence[T]] + A list of sequences with concatenation equals $l$. + This should conform with the type of $l$. + + Examples + ======== + + >>> from sympy.utilities.iterables import sequence_partitions_empty + >>> for out in sequence_partitions_empty([1, 2, 3, 4], 2): + ... print(out) + [[], [1, 2, 3, 4]] + [[1], [2, 3, 4]] + [[1, 2], [3, 4]] + [[1, 2, 3], [4]] + [[1, 2, 3, 4], []] + + See Also + ======== + + sequence_partitions + """ + if n < 1: + return + if n == 1: + yield [l] + return + for i in range(0, len(l) + 1): + for part in sequence_partitions_empty(l[i:], n - 1): + yield [l[:i]] + part + + +def kbins(l, k, ordered=None): + """ + Return sequence ``l`` partitioned into ``k`` bins. + + Examples + ======== + + The default is to give the items in the same order, but grouped + into k partitions without any reordering: + + >>> from sympy.utilities.iterables import kbins + >>> for p in kbins(list(range(5)), 2): + ... print(p) + ... + [[0], [1, 2, 3, 4]] + [[0, 1], [2, 3, 4]] + [[0, 1, 2], [3, 4]] + [[0, 1, 2, 3], [4]] + + The ``ordered`` flag is either None (to give the simple partition + of the elements) or is a 2 digit integer indicating whether the order of + the bins and the order of the items in the bins matters. Given:: + + A = [[0], [1, 2]] + B = [[1, 2], [0]] + C = [[2, 1], [0]] + D = [[0], [2, 1]] + + the following values for ``ordered`` have the shown meanings:: + + 00 means A == B == C == D + 01 means A == B + 10 means A == D + 11 means A == A + + >>> for ordered_flag in [None, 0, 1, 10, 11]: + ... print('ordered = %s' % ordered_flag) + ... for p in kbins(list(range(3)), 2, ordered=ordered_flag): + ... print(' %s' % p) + ... + ordered = None + [[0], [1, 2]] + [[0, 1], [2]] + ordered = 0 + [[0, 1], [2]] + [[0, 2], [1]] + [[0], [1, 2]] + ordered = 1 + [[0], [1, 2]] + [[0], [2, 1]] + [[1], [0, 2]] + [[1], [2, 0]] + [[2], [0, 1]] + [[2], [1, 0]] + ordered = 10 + [[0, 1], [2]] + [[2], [0, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[0], [1, 2]] + [[1, 2], [0]] + ordered = 11 + [[0], [1, 2]] + [[0, 1], [2]] + [[0], [2, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[1, 0], [2]] + [[1], [2, 0]] + [[1, 2], [0]] + [[2], [0, 1]] + [[2, 0], [1]] + [[2], [1, 0]] + [[2, 1], [0]] + + See Also + ======== + + partitions, multiset_partitions + + """ + if ordered is None: + yield from sequence_partitions(l, k) + elif ordered == 11: + for pl in multiset_permutations(l): + pl = list(pl) + yield from sequence_partitions(pl, k) + elif ordered == 00: + yield from multiset_partitions(l, k) + elif ordered == 10: + for p in multiset_partitions(l, k): + for perm in permutations(p): + yield list(perm) + elif ordered == 1: + for kgot, p in partitions(len(l), k, size=True): + if kgot != k: + continue + for li in multiset_permutations(l): + rv = [] + i = j = 0 + li = list(li) + for size, multiplicity in sorted(p.items()): + for m in range(multiplicity): + j = i + size + rv.append(li[i: j]) + i = j + yield rv + else: + raise ValueError( + 'ordered must be one of 00, 01, 10 or 11, not %s' % ordered) + + +def permute_signs(t): + """Return iterator in which the signs of non-zero elements + of t are permuted. + + Examples + ======== + + >>> from sympy.utilities.iterables import permute_signs + >>> list(permute_signs((0, 1, 2))) + [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)] + """ + for signs in product(*[(1, -1)]*(len(t) - t.count(0))): + signs = list(signs) + yield type(t)([i*signs.pop() if i else i for i in t]) + + +def signed_permutations(t): + """Return iterator in which the signs of non-zero elements + of t and the order of the elements are permuted. + + Examples + ======== + + >>> from sympy.utilities.iterables import signed_permutations + >>> list(signed_permutations((0, 1, 2))) + [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1), + (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2), + (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0), + (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1), + (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)] + """ + return (type(t)(i) for j in permutations(t) + for i in permute_signs(j)) + + +def rotations(s, dir=1): + """Return a generator giving the items in s as list where + each subsequent list has the items rotated to the left (default) + or right (``dir=-1``) relative to the previous list. + + Examples + ======== + + >>> from sympy import rotations + >>> list(rotations([1,2,3])) + [[1, 2, 3], [2, 3, 1], [3, 1, 2]] + >>> list(rotations([1,2,3], -1)) + [[1, 2, 3], [3, 1, 2], [2, 3, 1]] + """ + seq = list(s) + for i in range(len(seq)): + yield seq + seq = rotate_left(seq, dir) + + +def roundrobin(*iterables): + """roundrobin recipe taken from itertools documentation: + https://docs.python.org/3/library/itertools.html#itertools-recipes + + roundrobin('ABC', 'D', 'EF') --> A D E B F C + + Recipe credited to George Sakkis + """ + nexts = cycle(iter(it).__next__ for it in iterables) + + pending = len(iterables) + while pending: + try: + for nxt in nexts: + yield nxt() + except StopIteration: + pending -= 1 + nexts = cycle(islice(nexts, pending)) + + + +class NotIterable: + """ + Use this as mixin when creating a class which is not supposed to + return true when iterable() is called on its instances because + calling list() on the instance, for example, would result in + an infinite loop. + """ + pass + + +def iterable(i, exclude=(str, dict, NotIterable)): + """ + Return a boolean indicating whether ``i`` is SymPy iterable. + True also indicates that the iterator is finite, e.g. you can + call list(...) on the instance. + + When SymPy is working with iterables, it is almost always assuming + that the iterable is not a string or a mapping, so those are excluded + by default. If you want a pure Python definition, make exclude=None. To + exclude multiple items, pass them as a tuple. + + You can also set the _iterable attribute to True or False on your class, + which will override the checks here, including the exclude test. + + As a rule of thumb, some SymPy functions use this to check if they should + recursively map over an object. If an object is technically iterable in + the Python sense but does not desire this behavior (e.g., because its + iteration is not finite, or because iteration might induce an unwanted + computation), it should disable it by setting the _iterable attribute to False. + + See also: is_sequence + + Examples + ======== + + >>> from sympy.utilities.iterables import iterable + >>> from sympy import Tuple + >>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1] + >>> for i in things: + ... print('%s %s' % (iterable(i), type(i))) + True <... 'list'> + True <... 'tuple'> + True <... 'set'> + True + True <... 'generator'> + False <... 'dict'> + False <... 'str'> + False <... 'int'> + + >>> iterable({}, exclude=None) + True + >>> iterable({}, exclude=str) + True + >>> iterable("no", exclude=str) + False + + """ + if hasattr(i, '_iterable'): + return i._iterable + try: + iter(i) + except TypeError: + return False + if exclude: + return not isinstance(i, exclude) + return True + + +def is_sequence(i, include=None): + """ + Return a boolean indicating whether ``i`` is a sequence in the SymPy + sense. If anything that fails the test below should be included as + being a sequence for your application, set 'include' to that object's + type; multiple types should be passed as a tuple of types. + + Note: although generators can generate a sequence, they often need special + handling to make sure their elements are captured before the generator is + exhausted, so these are not included by default in the definition of a + sequence. + + See also: iterable + + Examples + ======== + + >>> from sympy.utilities.iterables import is_sequence + >>> from types import GeneratorType + >>> is_sequence([]) + True + >>> is_sequence(set()) + False + >>> is_sequence('abc') + False + >>> is_sequence('abc', include=str) + True + >>> generator = (c for c in 'abc') + >>> is_sequence(generator) + False + >>> is_sequence(generator, include=(str, GeneratorType)) + True + + """ + return (hasattr(i, '__getitem__') and + iterable(i) or + bool(include) and + isinstance(i, include)) + + +@deprecated( + """ + Using postorder_traversal from the sympy.utilities.iterables submodule is + deprecated. + + Instead, use postorder_traversal from the top-level sympy namespace, like + + sympy.postorder_traversal + """, + deprecated_since_version="1.10", + active_deprecations_target="deprecated-traversal-functions-moved") +def postorder_traversal(node, keys=None): + from sympy.core.traversal import postorder_traversal as _postorder_traversal + return _postorder_traversal(node, keys=keys) + + +@deprecated( + """ + Using interactive_traversal from the sympy.utilities.iterables submodule + is deprecated. + + Instead, use interactive_traversal from the top-level sympy namespace, + like + + sympy.interactive_traversal + """, + deprecated_since_version="1.10", + active_deprecations_target="deprecated-traversal-functions-moved") +def interactive_traversal(expr): + from sympy.interactive.traversal import interactive_traversal as _interactive_traversal + return _interactive_traversal(expr) + + +@deprecated( + """ + Importing default_sort_key from sympy.utilities.iterables is deprecated. + Use from sympy import default_sort_key instead. + """, + deprecated_since_version="1.10", +active_deprecations_target="deprecated-sympy-core-compatibility", +) +def default_sort_key(*args, **kwargs): + from sympy import default_sort_key as _default_sort_key + return _default_sort_key(*args, **kwargs) + + +@deprecated( + """ + Importing default_sort_key from sympy.utilities.iterables is deprecated. + Use from sympy import default_sort_key instead. + """, + deprecated_since_version="1.10", +active_deprecations_target="deprecated-sympy-core-compatibility", +) +def ordered(*args, **kwargs): + from sympy import ordered as _ordered + return _ordered(*args, **kwargs) diff --git a/shared/package-files/56/56944549c98227170ca64fe6a5c15391e4ea6df01206e1ed7d7b75aee14ced6c/PyColorize.py b/shared/package-files/56/56944549c98227170ca64fe6a5c15391e4ea6df01206e1ed7d7b75aee14ced6c/PyColorize.py new file mode 100644 index 0000000000000000000000000000000000000000..86bb9af4c160ff9a9355f2c0982e531d1548928b --- /dev/null +++ b/shared/package-files/56/56944549c98227170ca64fe6a5c15391e4ea6df01206e1ed7d7b75aee14ced6c/PyColorize.py @@ -0,0 +1,331 @@ +# -*- coding: utf-8 -*- +""" +Class and program to colorize python source code for ANSI terminals. + +Based on an HTML code highlighter by Jurgen Hermann found at: +http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 + +Modifications by Fernando Perez (fperez@colorado.edu). + +Information on the original HTML highlighter follows: + +MoinMoin - Python Source Parser + +Title: Colorize Python source using the built-in tokenizer + +Submitter: Jurgen Hermann +Last Updated:2001/04/06 + +Version no:1.2 + +Description: + +This code is part of MoinMoin (http://moin.sourceforge.net/) and converts +Python source code to HTML markup, rendering comments, keywords, +operators, numeric and string literals in different colors. + +It shows how to use the built-in keyword, token and tokenize modules to +scan Python source code and re-emit it with no changes to its original +formatting (which is the hard part). +""" + +__all__ = ['ANSICodeColors', 'Parser'] + +_scheme_default = 'Linux' + + +# Imports +import keyword +import os +import sys +import token +import tokenize + +generate_tokens = tokenize.generate_tokens + +from IPython.utils.coloransi import TermColors, InputTermColors,ColorScheme, ColorSchemeTable +from .colorable import Colorable +from io import StringIO + +############################################################################# +### Python Source Parser (does Highlighting) +############################################################################# + +_KEYWORD = token.NT_OFFSET + 1 +_TEXT = token.NT_OFFSET + 2 + +#**************************************************************************** +# Builtin color schemes + +Colors = TermColors # just a shorthand + +# Build a few color schemes +NoColor = ColorScheme( + 'NoColor',{ + 'header' : Colors.NoColor, + token.NUMBER : Colors.NoColor, + token.OP : Colors.NoColor, + token.STRING : Colors.NoColor, + tokenize.COMMENT : Colors.NoColor, + token.NAME : Colors.NoColor, + token.ERRORTOKEN : Colors.NoColor, + + _KEYWORD : Colors.NoColor, + _TEXT : Colors.NoColor, + + 'in_prompt' : InputTermColors.NoColor, # Input prompt + 'in_number' : InputTermColors.NoColor, # Input prompt number + 'in_prompt2' : InputTermColors.NoColor, # Continuation prompt + 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal) + + 'out_prompt' : Colors.NoColor, # Output prompt + 'out_number' : Colors.NoColor, # Output prompt number + + 'normal' : Colors.NoColor # color off (usu. Colors.Normal) + } ) + +LinuxColors = ColorScheme( + 'Linux',{ + 'header' : Colors.LightRed, + token.NUMBER : Colors.LightCyan, + token.OP : Colors.Yellow, + token.STRING : Colors.LightBlue, + tokenize.COMMENT : Colors.LightRed, + token.NAME : Colors.Normal, + token.ERRORTOKEN : Colors.Red, + + _KEYWORD : Colors.LightGreen, + _TEXT : Colors.Yellow, + + 'in_prompt' : InputTermColors.Green, + 'in_number' : InputTermColors.LightGreen, + 'in_prompt2' : InputTermColors.Green, + 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal) + + 'out_prompt' : Colors.Red, + 'out_number' : Colors.LightRed, + + 'normal' : Colors.Normal # color off (usu. Colors.Normal) + } ) + +NeutralColors = ColorScheme( + 'Neutral',{ + 'header' : Colors.Red, + token.NUMBER : Colors.Cyan, + token.OP : Colors.Blue, + token.STRING : Colors.Blue, + tokenize.COMMENT : Colors.Red, + token.NAME : Colors.Normal, + token.ERRORTOKEN : Colors.Red, + + _KEYWORD : Colors.Green, + _TEXT : Colors.Blue, + + 'in_prompt' : InputTermColors.Blue, + 'in_number' : InputTermColors.LightBlue, + 'in_prompt2' : InputTermColors.Blue, + 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal) + + 'out_prompt' : Colors.Red, + 'out_number' : Colors.LightRed, + + 'normal' : Colors.Normal # color off (usu. Colors.Normal) + } ) + +# Hack: the 'neutral' colours are not very visible on a dark background on +# Windows. Since Windows command prompts have a dark background by default, and +# relatively few users are likely to alter that, we will use the 'Linux' colours, +# designed for a dark background, as the default on Windows. Changing it here +# avoids affecting the prompt colours rendered by prompt_toolkit, where the +# neutral defaults do work OK. + +if os.name == 'nt': + NeutralColors = LinuxColors.copy(name='Neutral') + +LightBGColors = ColorScheme( + 'LightBG',{ + 'header' : Colors.Red, + token.NUMBER : Colors.Cyan, + token.OP : Colors.Blue, + token.STRING : Colors.Blue, + tokenize.COMMENT : Colors.Red, + token.NAME : Colors.Normal, + token.ERRORTOKEN : Colors.Red, + + + _KEYWORD : Colors.Green, + _TEXT : Colors.Blue, + + 'in_prompt' : InputTermColors.Blue, + 'in_number' : InputTermColors.LightBlue, + 'in_prompt2' : InputTermColors.Blue, + 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal) + + 'out_prompt' : Colors.Red, + 'out_number' : Colors.LightRed, + + 'normal' : Colors.Normal # color off (usu. Colors.Normal) + } ) + +# Build table of color schemes (needed by the parser) +ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors], + _scheme_default) + +Undefined = object() + +class Parser(Colorable): + """ Format colored Python source. + """ + + def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None): + """ Create a parser with a specified color table and output channel. + + Call format() to process code. + """ + + super(Parser, self).__init__(parent=parent) + + self.color_table = color_table if color_table else ANSICodeColors + self.out = out + self.pos = None + self.lines = None + self.raw = None + if not style: + self.style = self.default_style + else: + self.style = style + + + def format(self, raw, out=None, scheme=Undefined): + import warnings + if scheme is not Undefined: + warnings.warn('The `scheme` argument of IPython.utils.PyColorize:Parser.format is deprecated since IPython 6.0.' + 'It will have no effect. Set the parser `style` directly.', + stacklevel=2) + return self.format2(raw, out)[0] + + def format2(self, raw, out = None): + """ Parse and send the colored source. + + If out and scheme are not specified, the defaults (given to + constructor) are used. + + out should be a file-type object. Optionally, out can be given as the + string 'str' and the parser will automatically return the output in a + string.""" + + string_output = 0 + if out == 'str' or self.out == 'str' or \ + isinstance(self.out, StringIO): + # XXX - I don't really like this state handling logic, but at this + # point I don't want to make major changes, so adding the + # isinstance() check is the simplest I can do to ensure correct + # behavior. + out_old = self.out + self.out = StringIO() + string_output = 1 + elif out is not None: + self.out = out + else: + raise ValueError('`out` or `self.out` should be file-like or the value `"str"`') + + # Fast return of the unmodified input for NoColor scheme + if self.style == 'NoColor': + error = False + self.out.write(raw) + if string_output: + return raw, error + return None, error + + # local shorthands + colors = self.color_table[self.style].colors + self.colors = colors # put in object so __call__ sees it + + # Remove trailing whitespace and normalize tabs + self.raw = raw.expandtabs().rstrip() + + # store line offsets in self.lines + self.lines = [0, 0] + pos = 0 + raw_find = self.raw.find + lines_append = self.lines.append + while True: + pos = raw_find('\n', pos) + 1 + if not pos: + break + lines_append(pos) + lines_append(len(self.raw)) + + # parse the source and write it + self.pos = 0 + text = StringIO(self.raw) + + error = False + try: + for atoken in generate_tokens(text.readline): + self(*atoken) + except tokenize.TokenError as ex: + msg = ex.args[0] + line = ex.args[1][0] + self.out.write("%s\n\n*** ERROR: %s%s%s\n" % + (colors[token.ERRORTOKEN], + msg, self.raw[self.lines[line]:], + colors.normal) + ) + error = True + self.out.write(colors.normal+'\n') + if string_output: + output = self.out.getvalue() + self.out = out_old + return (output, error) + return (None, error) + + + def _inner_call_(self, toktype, toktext, start_pos): + """like call but write to a temporary buffer""" + buff = StringIO() + srow, scol = start_pos + colors = self.colors + owrite = buff.write + + # line separator, so this works across platforms + linesep = os.linesep + + # calculate new positions + oldpos = self.pos + newpos = self.lines[srow] + scol + self.pos = newpos + len(toktext) + + # send the original whitespace, if needed + if newpos > oldpos: + owrite(self.raw[oldpos:newpos]) + + # skip indenting tokens + if toktype in [token.INDENT, token.DEDENT]: + self.pos = newpos + buff.seek(0) + return buff.read() + + # map token type to a color group + if token.LPAR <= toktype <= token.OP: + toktype = token.OP + elif toktype == token.NAME and keyword.iskeyword(toktext): + toktype = _KEYWORD + color = colors.get(toktype, colors[_TEXT]) + + # Triple quoted strings must be handled carefully so that backtracking + # in pagers works correctly. We need color terminators on _each_ line. + if linesep in toktext: + toktext = toktext.replace(linesep, '%s%s%s' % + (colors.normal,linesep,color)) + + # send text + owrite('%s%s%s' % (color,toktext,colors.normal)) + buff.seek(0) + return buff.read() + + + def __call__(self, toktype, toktext, start_pos, end_pos, line): + """ Token handler, with syntax highlighting.""" + self.out.write( + self._inner_call_(toktype, toktext, start_pos)) diff --git a/shared/package-files/56/5695c819ce3892ec785fe6c12ca2c3b079296dcd3fd3b627a183e67e9a84e1be/fractional_max_pool2d_native.h b/shared/package-files/56/5695c819ce3892ec785fe6c12ca2c3b079296dcd3fd3b627a183e67e9a84e1be/fractional_max_pool2d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..16957f3219887a1ff1efd63af3637313fa7f4fd2 --- /dev/null +++ b/shared/package-files/56/5695c819ce3892ec785fe6c12ca2c3b079296dcd3fd3b627a183e67e9a84e1be/fractional_max_pool2d_native.h @@ -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_fractional_max_pool2d_out_cpu : public at::meta::structured_fractional_max_pool2d { +void impl(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples, const at::Tensor & output, const at::Tensor & indices); +}; +struct TORCH_API structured_fractional_max_pool2d_out_cuda : public at::meta::structured_fractional_max_pool2d { +void impl(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples, const at::Tensor & output, const at::Tensor & indices); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/56/56976c9e2a8a13deb90901908fad52e22d58f0aa245059b73970aea3b54bc7f0/Caffe2Targets-release.cmake b/shared/package-files/56/56976c9e2a8a13deb90901908fad52e22d58f0aa245059b73970aea3b54bc7f0/Caffe2Targets-release.cmake new file mode 100644 index 0000000000000000000000000000000000000000..946f1b44746743e286f5a8d06816572df52b8c47 --- /dev/null +++ b/shared/package-files/56/56976c9e2a8a13deb90901908fad52e22d58f0aa245059b73970aea3b54bc7f0/Caffe2Targets-release.cmake @@ -0,0 +1,59 @@ +#---------------------------------------------------------------- +# Generated CMake target import file for configuration "Release". +#---------------------------------------------------------------- + +# Commands may need to know the format version. +set(CMAKE_IMPORT_FILE_VERSION 1) + +# Import target "c10_cuda" for configuration "Release" +set_property(TARGET c10_cuda APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) +set_target_properties(c10_cuda PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libc10_cuda.so" + IMPORTED_SONAME_RELEASE "libc10_cuda.so" + ) + +list(APPEND _cmake_import_check_targets c10_cuda ) +list(APPEND _cmake_import_check_files_for_c10_cuda "${_IMPORT_PREFIX}/lib/libc10_cuda.so" ) + +# Import target "c10" for configuration "Release" +set_property(TARGET c10 APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) +set_target_properties(c10 PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libc10.so" + IMPORTED_SONAME_RELEASE "libc10.so" + ) + +list(APPEND _cmake_import_check_targets c10 ) +list(APPEND _cmake_import_check_files_for_c10 "${_IMPORT_PREFIX}/lib/libc10.so" ) + +# Import target "torch_cpu" for configuration "Release" +set_property(TARGET torch_cpu APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) +set_target_properties(torch_cpu PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libtorch_cpu.so" + IMPORTED_SONAME_RELEASE "libtorch_cpu.so" + ) + +list(APPEND _cmake_import_check_targets torch_cpu ) +list(APPEND _cmake_import_check_files_for_torch_cpu "${_IMPORT_PREFIX}/lib/libtorch_cpu.so" ) + +# Import target "torch_cuda" for configuration "Release" +set_property(TARGET torch_cuda APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) +set_target_properties(torch_cuda PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libtorch_cuda.so" + IMPORTED_SONAME_RELEASE "libtorch_cuda.so" + ) + +list(APPEND _cmake_import_check_targets torch_cuda ) +list(APPEND _cmake_import_check_files_for_torch_cuda "${_IMPORT_PREFIX}/lib/libtorch_cuda.so" ) + +# Import target "torch" for configuration "Release" +set_property(TARGET torch APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) +set_target_properties(torch PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libtorch.so" + IMPORTED_SONAME_RELEASE "libtorch.so" + ) + +list(APPEND _cmake_import_check_targets torch ) +list(APPEND _cmake_import_check_files_for_torch "${_IMPORT_PREFIX}/lib/libtorch.so" ) + +# Commands beyond this point should not need to know the version. +set(CMAKE_IMPORT_FILE_VERSION) diff --git a/shared/package-files/56/5698c36139a83034d9718ec2b06ce29c187447f3880aec0eca45826e60914195/test_arraymethod.py b/shared/package-files/56/5698c36139a83034d9718ec2b06ce29c187447f3880aec0eca45826e60914195/test_arraymethod.py new file mode 100644 index 0000000000000000000000000000000000000000..4fd4d555845aa9dddb42d86c4f4968f86d30014d --- /dev/null +++ b/shared/package-files/56/5698c36139a83034d9718ec2b06ce29c187447f3880aec0eca45826e60914195/test_arraymethod.py @@ -0,0 +1,85 @@ +""" +This file tests the generic aspects of ArrayMethod. At the time of writing +this is private API, but when added, public API may be added here. +""" + +from __future__ import annotations + +import sys +import types +from typing import Any + +import pytest + +import numpy as np +from numpy.core._multiarray_umath import _get_castingimpl as get_castingimpl + + +class TestResolveDescriptors: + # Test mainly error paths of the resolve_descriptors function, + # note that the `casting_unittests` tests exercise this non-error paths. + + # Casting implementations are the main/only current user: + method = get_castingimpl(type(np.dtype("d")), type(np.dtype("f"))) + + @pytest.mark.parametrize("args", [ + (True,), # Not a tuple. + ((None,)), # Too few elements + ((None, None, None),), # Too many + ((None, None),), # Input dtype is None, which is invalid. + ((np.dtype("d"), True),), # Output dtype is not a dtype + ((np.dtype("f"), None),), # Input dtype does not match method + ]) + def test_invalid_arguments(self, args): + with pytest.raises(TypeError): + self.method._resolve_descriptors(*args) + + +class TestSimpleStridedCall: + # Test mainly error paths of the resolve_descriptors function, + # note that the `casting_unittests` tests exercise this non-error paths. + + # Casting implementations are the main/only current user: + method = get_castingimpl(type(np.dtype("d")), type(np.dtype("f"))) + + @pytest.mark.parametrize(["args", "error"], [ + ((True,), TypeError), # Not a tuple + (((None,),), TypeError), # Too few elements + ((None, None), TypeError), # Inputs are not arrays. + (((None, None, None),), TypeError), # Too many + (((np.arange(3), np.arange(3)),), TypeError), # Incorrect dtypes + (((np.ones(3, dtype=">d"), np.ones(3, dtype=" None: + """Test `ndarray.__class_getitem__`.""" + alias = cls[Any, Any] + assert isinstance(alias, types.GenericAlias) + assert alias.__origin__ is cls + + @pytest.mark.parametrize("arg_len", range(4)) + def test_subscript_tup(self, cls: type[np.ndarray], arg_len: int) -> None: + arg_tup = (Any,) * arg_len + if arg_len in (1, 2): + assert cls[arg_tup] + else: + match = f"Too {'few' if arg_len == 0 else 'many'} arguments" + with pytest.raises(TypeError, match=match): + cls[arg_tup] diff --git a/shared/package-files/56/56995a7e4cbe4c6b501cdff0114bd22af926fa44e3388f2cec9d3b40b4076834/frobenius_norm_compositeimplicitautograd_dispatch.h b/shared/package-files/56/56995a7e4cbe4c6b501cdff0114bd22af926fa44e3388f2cec9d3b40b4076834/frobenius_norm_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..5ad00b4311a2fadc2c4f5fcfd5223ea427d41fa1 --- /dev/null +++ b/shared/package-files/56/56995a7e4cbe4c6b501cdff0114bd22af926fa44e3388f2cec9d3b40b4076834/frobenius_norm_compositeimplicitautograd_dispatch.h @@ -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 frobenius_norm(const at::Tensor & self, at::IntArrayRef dim, bool keepdim=false); +TORCH_API at::Tensor & frobenius_norm_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef dim, bool keepdim=false); +TORCH_API at::Tensor & frobenius_norm_outf(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/56/569a886ba64263e6b7d788e429d6191f6d49aeb4b9f99dbf0f6d3faed6ffcdc6/gru_ops.h b/shared/package-files/56/569a886ba64263e6b7d788e429d6191f6d49aeb4b9f99dbf0f6d3faed6ffcdc6/gru_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..edc4efd811868010515bc98366f777d52554cc3c --- /dev/null +++ b/shared/package-files/56/569a886ba64263e6b7d788e429d6191f6d49aeb4b9f99dbf0f6d3faed6ffcdc6/gru_ops.h @@ -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 gru_input { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, at::TensorList, bool, int64_t, double, bool, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::gru") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "input") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first); +}; + +struct TORCH_API gru_data { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::TensorList, bool, int64_t, double, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::gru") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "data") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/56/569cbfc563e01cd749c3e2b534a6df3836f369c8123c4d2fcd02689aa24aeaa9/libtiffxx.a b/shared/package-files/56/569cbfc563e01cd749c3e2b534a6df3836f369c8123c4d2fcd02689aa24aeaa9/libtiffxx.a new file mode 100644 index 0000000000000000000000000000000000000000..fa03033a8f89191224d7ab36db142e6ed3716aa5 Binary files /dev/null and b/shared/package-files/56/569cbfc563e01cd749c3e2b534a6df3836f369c8123c4d2fcd02689aa24aeaa9/libtiffxx.a differ diff --git a/shared/package-files/56/569d4d57305f33c8f3d15246868a7750e9ca5dad6698948d237bb48afffe37bd/algorithms.pyi b/shared/package-files/56/569d4d57305f33c8f3d15246868a7750e9ca5dad6698948d237bb48afffe37bd/algorithms.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fe83e56b6be6d8605c473d05cfabbd3468697a32 --- /dev/null +++ b/shared/package-files/56/569d4d57305f33c8f3d15246868a7750e9ca5dad6698948d237bb48afffe37bd/algorithms.pyi @@ -0,0 +1,101 @@ +import sys +from hashlib import _Hash +from typing import Any, ClassVar, Dict, Generic, Optional, Set, TypeVar, Union + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.ec import ( + EllipticCurvePrivateKey, + EllipticCurvePrivateKeyWithSerialization, + EllipticCurvePrivateNumbers, + EllipticCurvePublicKey, + EllipticCurvePublicKeyWithSerialization, + EllipticCurvePublicNumbers, +) +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.hazmat.primitives.asymmetric.rsa import ( + RSAPrivateKey, + RSAPrivateKeyWithSerialization, + RSAPrivateNumbers, + RSAPublicKey, + RSAPublicKeyWithSerialization, + RSAPublicNumbers, +) +from cryptography.hazmat.primitives.asymmetric.utils import Prehashed +from cryptography.hazmat.primitives.hashes import HashAlgorithm + +requires_cryptography = Set[str] + +def get_default_algorithms() -> Dict[str, Algorithm[Any]]: ... + +_K = TypeVar("_K") + +class Algorithm(Generic[_K]): + def prepare_key(self, key: _K) -> _K: ... + def sign(self, msg: bytes, key: _K) -> bytes: ... + def verify(self, msg: bytes, key: _K, sig: bytes) -> bool: ... + @staticmethod + def to_jwk(key_obj: _K) -> str: ... + @staticmethod + def from_jwk(jwk: str) -> _K: ... + +class NoneAlgorithm(Algorithm[None]): + def prepare_key(self, key: Optional[str]) -> None: ... + +class _HashAlg: + def __call__(self, arg: Union[bytes, bytearray, memoryview] = ...) -> _Hash: ... + +class HMACAlgorithm(Algorithm[bytes]): + SHA256: ClassVar[_HashAlg] + SHA384: ClassVar[_HashAlg] + SHA512: ClassVar[_HashAlg] + hash_alg: _HashAlg + def __init__(self, hash_alg: _HashAlg) -> None: ... + def prepare_key(self, key: Union[str, bytes]) -> bytes: ... + @staticmethod + def to_jwk(key_obj: Union[str, bytes]) -> str: ... + @staticmethod + def from_jwk(jwk: Union[str, bytes]) -> bytes: ... + +# Only defined if cryptography is installed. +class RSAAlgorithm(Algorithm[Any]): + SHA256: ClassVar[hashes.SHA256] + SHA384: ClassVar[hashes.SHA384] + SHA512: ClassVar[hashes.SHA512] + hash_alg: Union[HashAlgorithm, Prehashed] + def __init__(self, hash_alg: Union[HashAlgorithm, Prehashed]) -> None: ... + def prepare_key(self, key: Union[bytes, str, RSAPrivateKey, RSAPublicKey]) -> Union[RSAPrivateKey, RSAPublicKey]: ... + @staticmethod + def from_jwk(jwk: Union[str, bytes, Dict[str, Any]]) -> Union[RSAPrivateKey, RSAPublicKey]: ... + def sign(self, msg: bytes, key: RSAPrivateKey) -> bytes: ... + def verify(self, msg: bytes, key: RSAPublicKey, sig: bytes) -> bool: ... + +# Only defined if cryptography is installed. +class ECAlgorithm(Algorithm[Any]): + SHA256: ClassVar[hashes.SHA256] + SHA384: ClassVar[hashes.SHA384] + SHA512: ClassVar[hashes.SHA512] + hash_alg: Union[HashAlgorithm, Prehashed] + def __init__(self, hash_alg: Union[HashAlgorithm, Prehashed]) -> None: ... + def prepare_key( + self, key: Union[bytes, str, EllipticCurvePrivateKey, EllipticCurvePublicKey] + ) -> Union[EllipticCurvePrivateKey, EllipticCurvePublicKey]: ... + @staticmethod + def to_jwk(key_obj: Union[EllipticCurvePrivateKeyWithSerialization, EllipticCurvePublicKeyWithSerialization]) -> str: ... + @staticmethod + def from_jwk(jwk: Union[str, bytes]) -> Union[EllipticCurvePrivateKey, EllipticCurvePublicKey]: ... + def sign(self, msg: bytes, key: EllipticCurvePrivateKey) -> bytes: ... + def verify(self, msg: bytes, key: EllipticCurvePublicKey, sig: bytes) -> bool: ... + +# Only defined if cryptography is installed. Types should be tightened when +# cryptography gets type hints. +# See https://github.com/python/typeshed/issues/2542 +class RSAPSSAlgorithm(RSAAlgorithm): + def sign(self, msg: bytes, key: Any) -> bytes: ... + def verify(self, msg: bytes, key: Any, sig: bytes) -> bool: ... + +# Only defined if cryptography is installed. +class Ed25519Algorithm(Algorithm[Any]): + def __init__(self, **kwargs: Any) -> None: ... + def prepare_key(self, key: Union[str, bytes, Ed25519PrivateKey, Ed25519PublicKey]) -> Any: ... + def sign(self, msg: Union[str, bytes], key: Ed25519PrivateKey) -> bytes: ... + def verify(self, msg: Union[str, bytes], key: Ed25519PublicKey, sig: Union[str, bytes]) -> bool: ... diff --git a/shared/package-files/56/569da10acd97d93411a337e50cdc0984d298279159a89619718e4e62f207853d/__init__.py b/shared/package-files/56/569da10acd97d93411a337e50cdc0984d298279159a89619718e4e62f207853d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..82886d3c774b78de0526b2bce2bfc06db6f23a92 --- /dev/null +++ b/shared/package-files/56/569da10acd97d93411a337e50cdc0984d298279159a89619718e4e62f207853d/__init__.py @@ -0,0 +1,34 @@ +""" +:mod:`torch.distributed.optim` exposes DistributedOptimizer, which takes a list +of remote parameters (:class:`~torch.distributed.rpc.RRef`) and runs the +optimizer locally on the workers where the parameters live. The distributed +optimizer can use any of the local optimizer :ref:`optimizer-algorithms` to +apply the gradients on each worker. +""" +import torch +from torch import optim + +from .apply_optimizer_in_backward import ( + _apply_optimizer_in_backward, + _get_in_backward_optimizers, +) +from .functional_adadelta import _FunctionalAdadelta + +from .functional_adagrad import _FunctionalAdagrad +from .functional_adam import _FunctionalAdam +from .functional_adamax import _FunctionalAdamax +from .functional_adamw import _FunctionalAdamW +from .functional_rmsprop import _FunctionalRMSprop +from .functional_rprop import _FunctionalRprop +from .functional_sgd import _FunctionalSGD +from .named_optimizer import _NamedOptimizer +from .utils import as_functional_optim + + +# DistributedOptimizer imports torch.distributed.rpc names, so gate availability +# based on RPC being available. +if hasattr(torch._C, "_rpc_init"): + from .optimizer import DistributedOptimizer + +from .post_localSGD_optimizer import PostLocalSGDOptimizer +from .zero_redundancy_optimizer import ZeroRedundancyOptimizer diff --git a/shared/package-files/56/56a0bc0ea9b79c604b309812e79ae5ecf3a879ad59ba0adcb74ec3f7aebbab98/tracer.h b/shared/package-files/56/56a0bc0ea9b79c604b309812e79ae5ecf3a879ad59ba0adcb74ec3f7aebbab98/tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..f265d57b649dda335d6c4124d401d229154c8bc4 --- /dev/null +++ b/shared/package-files/56/56a0bc0ea9b79c604b309812e79ae5ecf3a879ad59ba0adcb74ec3f7aebbab98/tracer.h @@ -0,0 +1,412 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit { +struct Node; +struct Value; +struct Graph; +struct Module; + +namespace tracer { + +using ::c10::ivalue::Shared; + +using ::c10::IValue; +using ::c10::ivalue::Future; + +using ::c10::ArrayRef; +using ::c10::TupleType; +using ::c10::TupleTypePtr; +using ::c10::ivalue::ConstantString; + +using torch::autograd::Variable; +using variable_list = std::vector; + +TORCH_API std::atomic& getTracerStateWarnMode(); + +struct TORCH_API TracingState + : public std::enable_shared_from_this { + TracingState(); + ~TracingState(); + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr graph; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool warn = getTracerStateWarnMode(); + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool strict = true; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool force_outplace = false; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::function lookup_var_name_fn = + [](const Variable& var) { return ""; }; + + void enterFrame() { + env_stack.emplace_back(); + } + + void leaveFrame() { + env_stack.pop_back(); + } + + void setValue(const IValue& v, Value* value); + void delValue(const IValue& var); + Value* getValue(const IValue& var); + Value* getOutput(const IValue& var, size_t i); + bool hasValue(const IValue& var) const; + + Node* createNode(c10::Symbol op_name, size_t num_outputs); + void insertNode(Node* node); + + private: + using WeakIValue = at::WeakIValue; + + struct WeakIValueHasher { + size_t operator()(const WeakIValue& t) const { + return t.hash(); + } + }; + + struct WeakIValueEq { + bool operator()(const WeakIValue& t1, const WeakIValue& t2) const { + return t1.isSameIdentity(t2); + } + }; + + using Frame = + std::unordered_map; + std::vector env_stack; +}; + +// This is meant to be used as a thread local place, where we can store extra +// info that gets lost when we call into ATen from Python bindings. One example +// for when this happens is when we get an IntArrayRef argument with e.g. sizes +// for view. When tracing, those might be tensors, which let us encode extra +// data dependencies, but once they get to the ATen call where we actually have +// the tracing logic, they get converted into a raw IntArrayRef, and we loose +// all information. To prevent this, we temporarily stash it in here. +// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) +struct ArgumentStash { + struct IntArrayRefTrace : std::vector { + IntArrayRefTrace(int size) : std::vector(size, nullptr) {} + }; + + static bool empty() { + return stash.intlists.empty(); + } + + TORCH_API static void stashIntArrayRefElem( + const std::string& arg_name, + size_t size, + size_t idx, + const Variable& var); + + static bool hasIntArrayRef(const std::string& arg_name) { + return stash.intlists.count(arg_name) > 0; + } + + static IntArrayRefTrace popIntArrayRef(const std::string& arg_name) { + auto info = std::move(stash.intlists.at(arg_name)); + stash.intlists.erase(arg_name); + return info; + } + + // Value stashing: Use these methods to stash arguments which correspond + // to regular Value*'s in the graph. i.e. they don't require special + // handling like in the case of IntArrayRefs + TORCH_API static void stashValue( + const std::string& arg_name, + size_t idx, + const Variable& var, + const c10::TypePtr& type = nullptr); + + static bool hasValue(const std::string& arg_name) { + return stash.values.count(arg_name) > 0; + } + + static Value* popValue(const std::string& arg_name) { + auto info = stash.values.at(arg_name); + stash.values.erase(arg_name); + return info; + } + + private: + static thread_local ArgumentStash stash; + std::unordered_map intlists; + std::unordered_map values; +}; + +// Retrieve or set the current tracing state. Returns a nullptr if tracing is +// disabled. +TORCH_API const std::shared_ptr& getTracingState(); +TORCH_API void setTracingState(std::shared_ptr state); + +inline bool isTracing() { + return static_cast(getTracingState()); +} + +using warn_fn_type = void (*)(const std::string& msg); +TORCH_API extern const char* WARN_PYTHON_DATAFLOW; +TORCH_API extern const char* WARN_CONSTRUCTOR; +TORCH_API extern const char* WARN_RESIZE; +TORCH_API extern const char* STRICT_TRACER_MSG; +TORCH_API void _do_warn(const char* _reason, const char* _kind); +inline void warn(const char* _reason, const char* _kind = nullptr) { + if (const auto& state = getTracingState()) { + if (!state->warn) + return; + _do_warn(_reason, _kind); + } +} +TORCH_API void setWarn(warn_fn_type fn); + +struct TORCH_API NoWarn { + NoWarn() : state(getTracingState()) { + if (state) { + prev = state->warn; + state->warn = false; + } + } + ~NoWarn() { + if (state) { + state->warn = prev; + } + } + std::shared_ptr state; + bool prev{false}; +}; + +struct WithNestedTracingFrame { + WithNestedTracingFrame() { + getTracingState()->enterFrame(); + } + + ~WithNestedTracingFrame() { + getTracingState()->leaveFrame(); + } +}; +TORCH_API void recordSourceLocation(Node* n); +TORCH_API void setRecordSourceLocation(void (*v)(Node*)); + +TORCH_API std::vector pythonCallstack(); +TORCH_API void setPythonCallstack(std::vector (*v)()); + +// Having finished adding a new 'node' to the graph IR 'setValueTrace' +// associates this node with an output variable, so that further operations +// involving this variable know which node in the IR to reference. +TORCH_API void setValueTrace(const IValue& v, Value* value); + +TORCH_API void delValueTrace(const IValue& var); + +TORCH_API std::function pauseTracing(); + +TORCH_API Value* getValueTrace(const IValue& var); + +TORCH_API std::pair, Stack> trace( + Stack inputs, + const std::function& traced_fn, + std::function var_name_lookup_fn, + bool strict = true, + bool force_outplace = false, + Module* self = nullptr, + const std::vector& argument_names = {}); + +TORCH_API void abandon(); + +// NB: those serve both as an intermediate steps in addInputs below, +// as well as the overloads that terminate template recursion +TORCH_API void addInputs(Node* n, const char* name, int64_t value); +TORCH_API void addInputs(Node* n, const char* name, c10::SymInt value); +TORCH_API void addInputs( + Node* n, + const char* name, + c10::optional value); +TORCH_API void addInputs(Node* n, const char* name, bool value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs(Node* n, const char* name, double value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs(Node* n, const char* name, const at::Scalar& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs(Node* n, const char* name, const at::Tensor& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs(Node* n, const char* name, ArrayRef value); +TORCH_API void addInputs(Node* n, const char* name, c10::SymIntArrayRef value); +TORCH_API void addInputs( + Node* n, + const char* name, + c10::optional value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const at::OptionalIntArrayRef& opt_value); +TORCH_API void addInputs( + Node* n, + const char* name, + const at::OptionalSymIntArrayRef& opt_value); +TORCH_API void addInputs( + Node* n, + const char* name, + ArrayRef value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + std::vector value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + at::ITensorListRef value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + const List>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + ArrayRef> value, + const c10::ClassTypePtr& class_type); +TORCH_API void addInputs(Node* n, const char* name, ArrayRef value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::string_view value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs(Node* n, const char* name, at::Device value); +TORCH_API void addInputs(Node* n, const char* name, c10::Stream stream); +TORCH_API void addInputs(Node* n, const char* name, at::Layout value); +TORCH_API void addInputs(Node* n, const char* name, at::ScalarType value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs(Node* n, const char* name, at::MemoryFormat value); +TORCH_API void addInputs( + Node* n, + const char* name, + c10::optional value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::optional& value); + +inline void addInputs( + Node* n, + const char* name, + const std::vector& value) { + AT_ERROR("Tracing a list of bool type is currently not supported!"); +} + +template +void addInputs(Node* n, const char* name, ArrayRef value) { + AT_ERROR("Tracing a list of arbitrary type is currently not supported!"); +} +template +void addInputs( + Node* n, + const char* name, + const std::unordered_map& value) { + AT_ERROR("Tracing a dict of arbitrary types is currently not supported!"); +} + +template +void addInputs(Node* n, const char* name, std::array value) { + throw std::runtime_error( + "Found an unsupported argument type in the JIT tracer. File a bug report."); +} + +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::intrusive_ptr& obj); + +TORCH_API void ensureUniqueIfOutOfPlaced( + const char* name, + const at::Tensor& tensor); +TORCH_API void ensureUniqueIfOutOfPlaced( + const char* name, + const c10::optional& tensor); + +template < + typename T, + typename = torch::enable_if_t< + (!std::is_convertible_v, at::TensorList> && + !std::is_convertible_v, c10::List> && + !std::is_convertible_v, at::Tensor> && + !std::is_convertible_v< + torch::decay_t, + c10::intrusive_ptr>)>> +void addOutput(Node* node, T&&) { + AT_ERROR( + "Found an unsupported argument type ", + c10::demangle_type(), + " in the JIT tracer. File a bug report."); +} +TORCH_API void addOutput(Node* node, const at::Tensor& tensor); +TORCH_API void setOutput(Value* value, const at::Tensor& output); +TORCH_API void addOutput(Node* node, const std::vector& list); +TORCH_API void addOutput(Node* node, const c10::List& list); +TORCH_API void addOutput( + Node* node, + const c10::intrusive_ptr& output); + +TORCH_API autograd::Variable getSizeOf( + const autograd::Variable& var, + int64_t dim); + +TORCH_API autograd::Variable getNumelOf(const autograd::Variable& var); + +} // namespace tracer +} // namespace torch::jit diff --git a/shared/package-files/56/56a147374ff499d23e8374ad0b3d474af95dfdc3da65777f3bdc206add359074/oxford_iiit_pet.py b/shared/package-files/56/56a147374ff499d23e8374ad0b3d474af95dfdc3da65777f3bdc206add359074/oxford_iiit_pet.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe78901626378f642429b2c781bf86322a45d3f --- /dev/null +++ b/shared/package-files/56/56a147374ff499d23e8374ad0b3d474af95dfdc3da65777f3bdc206add359074/oxford_iiit_pet.py @@ -0,0 +1,125 @@ +import os +import os.path +import pathlib +from typing import Any, Callable, Optional, Sequence, Tuple, Union + +from PIL import Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class OxfordIIITPet(VisionDataset): + """`Oxford-IIIT Pet Dataset `_. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"trainval"`` (default) or ``"test"``. + target_types (string, sequence of strings, optional): Types of target to use. Can be ``category`` (default) or + ``segmentation``. Can also be a list to output a tuple with all specified target types. The types represent: + + - ``category`` (int): Label for one of the 37 pet categories. + - ``segmentation`` (PIL image): Segmentation trimap of the image. + + If empty, ``None`` will be returned as target. + + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and puts it into + ``root/oxford-iiit-pet``. If dataset is already downloaded, it is not downloaded again. + """ + + _RESOURCES = ( + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz", "5c4f3ee8e5d25df40f4fd59a7f44e54c"), + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz", "95a8c909bbe2e81eed6a22bccdf3f68f"), + ) + _VALID_TARGET_TYPES = ("category", "segmentation") + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "trainval", + target_types: Union[Sequence[str], str] = "category", + transforms: Optional[Callable] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ): + self._split = verify_str_arg(split, "split", ("trainval", "test")) + if isinstance(target_types, str): + target_types = [target_types] + self._target_types = [ + verify_str_arg(target_type, "target_types", self._VALID_TARGET_TYPES) for target_type in target_types + ] + + super().__init__(root, transforms=transforms, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / "oxford-iiit-pet" + self._images_folder = self._base_folder / "images" + self._anns_folder = self._base_folder / "annotations" + self._segs_folder = self._anns_folder / "trimaps" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + image_ids = [] + self._labels = [] + with open(self._anns_folder / f"{self._split}.txt") as file: + for line in file: + image_id, label, *_ = line.strip().split() + image_ids.append(image_id) + self._labels.append(int(label) - 1) + + self.classes = [ + " ".join(part.title() for part in raw_cls.split("_")) + for raw_cls, _ in sorted( + {(image_id.rsplit("_", 1)[0], label) for image_id, label in zip(image_ids, self._labels)}, + key=lambda image_id_and_label: image_id_and_label[1], + ) + ] + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + + self._images = [self._images_folder / f"{image_id}.jpg" for image_id in image_ids] + self._segs = [self._segs_folder / f"{image_id}.png" for image_id in image_ids] + + def __len__(self) -> int: + return len(self._images) + + def __getitem__(self, idx: int) -> Tuple[Any, Any]: + image = Image.open(self._images[idx]).convert("RGB") + + target: Any = [] + for target_type in self._target_types: + if target_type == "category": + target.append(self._labels[idx]) + else: # target_type == "segmentation" + target.append(Image.open(self._segs[idx])) + + if not target: + target = None + elif len(target) == 1: + target = target[0] + else: + target = tuple(target) + + if self.transforms: + image, target = self.transforms(image, target) + + return image, target + + def _check_exists(self) -> bool: + for folder in (self._images_folder, self._anns_folder): + if not (os.path.exists(folder) and os.path.isdir(folder)): + return False + else: + return True + + def _download(self) -> None: + if self._check_exists(): + return + + for url, md5 in self._RESOURCES: + download_and_extract_archive(url, download_root=str(self._base_folder), md5=md5) diff --git a/shared/package-files/56/56a1d075b9361f149caf456fec04975387816fdbed302f170596d39c8b7a5360/xterm-sco b/shared/package-files/56/56a1d075b9361f149caf456fec04975387816fdbed302f170596d39c8b7a5360/xterm-sco new file mode 100644 index 0000000000000000000000000000000000000000..05d4b0d5e867b57afe6b09d8508d208fa5c35f64 Binary files /dev/null and b/shared/package-files/56/56a1d075b9361f149caf456fec04975387816fdbed302f170596d39c8b7a5360/xterm-sco differ diff --git a/shared/package-files/56/56a3ddde4887c362cce726f4603b63fd1c7e91294e5289f65b7712bb5778f4a6/tracemalloc.pyi b/shared/package-files/56/56a3ddde4887c362cce726f4603b63fd1c7e91294e5289f65b7712bb5778f4a6/tracemalloc.pyi new file mode 100644 index 0000000000000000000000000000000000000000..593c4edaec65885cef39e3fed9af9069543dd556 --- /dev/null +++ b/shared/package-files/56/56a3ddde4887c362cce726f4603b63fd1c7e91294e5289f65b7712bb5778f4a6/tracemalloc.pyi @@ -0,0 +1,86 @@ +import sys +from typing import List, Optional, Sequence, Tuple, Union, overload + +from _tracemalloc import * + +def get_object_traceback(obj: object) -> Optional[Traceback]: ... +def take_snapshot() -> Snapshot: ... + +class DomainFilter: + inclusive: bool + domain: int + def __init__(self, inclusive: bool, domain: int) -> None: ... + +class Filter: + domain: Optional[int] + inclusive: bool + lineno: Optional[int] + filename_pattern: str + all_frames: bool + def __init__( + self, + inclusive: bool, + filename_pattern: str, + lineno: Optional[int] = ..., + all_frames: bool = ..., + domain: Optional[int] = ..., + ) -> None: ... + +class Statistic: + count: int + size: int + traceback: Traceback + def __init__(self, traceback: Traceback, size: int, count: int) -> None: ... + +class StatisticDiff: + count: int + count_diff: int + size: int + size_diff: int + traceback: Traceback + def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ... + +_FrameTupleT = Tuple[str, int] + +class Frame: + filename: str + lineno: int + def __init__(self, frame: _FrameTupleT) -> None: ... + +if sys.version_info >= (3, 9): + _TraceTupleT = Union[Tuple[int, int, Sequence[_FrameTupleT], Optional[int]], Tuple[int, int, Sequence[_FrameTupleT]]] +else: + _TraceTupleT = Tuple[int, int, Sequence[_FrameTupleT]] + +class Trace: + domain: int + size: int + traceback: Traceback + def __init__(self, trace: _TraceTupleT) -> None: ... + +class Traceback(Sequence[Frame]): + if sys.version_info >= (3, 9): + total_nframe: Optional[int] + def __init__(self, frames: Sequence[_FrameTupleT], total_nframe: Optional[int] = ...) -> None: ... + else: + def __init__(self, frames: Sequence[_FrameTupleT]) -> None: ... + if sys.version_info >= (3, 7): + def format(self, limit: Optional[int] = ..., most_recent_first: bool = ...) -> List[str]: ... + else: + def format(self, limit: Optional[int] = ...) -> List[str]: ... + @overload + def __getitem__(self, i: int) -> Frame: ... + @overload + def __getitem__(self, s: slice) -> Sequence[Frame]: ... + def __len__(self) -> int: ... + +class Snapshot: + def __init__(self, traces: Sequence[_TraceTupleT], traceback_limit: int) -> None: ... + def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = ...) -> List[StatisticDiff]: ... + def dump(self, filename: str) -> None: ... + def filter_traces(self, filters: Sequence[Union[DomainFilter, Filter]]) -> Snapshot: ... + @staticmethod + def load(filename: str) -> Snapshot: ... + def statistics(self, key_type: str, cumulative: bool = ...) -> List[Statistic]: ... + traceback_limit: int + traces: Sequence[Trace] diff --git a/shared/package-files/56/56a52a776276f9d2ad96d66db183fc78f2a85f58ec343a53caa95c9a97c2fa5a/pylab.py b/shared/package-files/56/56a52a776276f9d2ad96d66db183fc78f2a85f58ec343a53caa95c9a97c2fa5a/pylab.py new file mode 100644 index 0000000000000000000000000000000000000000..a50779cf6d264408f1f99a086a25cb5c9d525588 --- /dev/null +++ b/shared/package-files/56/56a52a776276f9d2ad96d66db183fc78f2a85f58ec343a53caa95c9a97c2fa5a/pylab.py @@ -0,0 +1,67 @@ +""" +`pylab` is a historic interface and its use is strongly discouraged. The equivalent +replacement is `matplotlib.pyplot`. See :ref:`api_interfaces` for a full overview +of Matplotlib interfaces. + +`pylab` was designed to support a MATLAB-like way of working with all plotting related +functions directly available in the global namespace. This was achieved through a +wildcard import (``from pylab import *``). + +.. warning:: + The use of `pylab` is discouraged for the following reasons: + + ``from pylab import *`` imports all the functions from `matplotlib.pyplot`, `numpy`, + `numpy.fft`, `numpy.linalg`, and `numpy.random`, and some additional functions into + the global namespace. + + Such a pattern is considered bad practice in modern python, as it clutters the global + namespace. Even more severely, in the case of `pylab`, this will overwrite some + builtin functions (e.g. the builtin `sum` will be replaced by `numpy.sum`), which + can lead to unexpected behavior. + +""" + +from matplotlib.cbook import flatten, silent_list + +import matplotlib as mpl + +from matplotlib.dates import ( + date2num, num2date, datestr2num, drange, DateFormatter, DateLocator, + RRuleLocator, YearLocator, MonthLocator, WeekdayLocator, DayLocator, + HourLocator, MinuteLocator, SecondLocator, rrule, MO, TU, WE, TH, FR, + SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, + relativedelta) + +# bring all the symbols in so folks can import them from +# pylab in one fell swoop + +## We are still importing too many things from mlab; more cleanup is needed. + +from matplotlib.mlab import ( + detrend, detrend_linear, detrend_mean, detrend_none, window_hanning, + window_none) + +from matplotlib import cbook, mlab, pyplot as plt +from matplotlib.pyplot import * + +from numpy import * +from numpy.fft import * +from numpy.random import * +from numpy.linalg import * + +import numpy as np +import numpy.ma as ma + +# don't let numpy's datetime hide stdlib +import datetime + +# This is needed, or bytes will be numpy.random.bytes from +# "from numpy.random import *" above +bytes = __import__("builtins").bytes +# We also don't want the numpy version of these functions +abs = __import__("builtins").abs +bool = __import__("builtins").bool +max = __import__("builtins").max +min = __import__("builtins").min +pow = __import__("builtins").pow +round = __import__("builtins").round diff --git a/shared/package-files/56/56aac2a7abf671e0aa8572d582c9662988dc085efa5bbe09a76c74dfc31afaa8/as_strided_meta_dispatch.h b/shared/package-files/56/56aac2a7abf671e0aa8572d582c9662988dc085efa5bbe09a76c74dfc31afaa8/as_strided_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..75316d26bdacd8c7d882685f43056f616142d24c --- /dev/null +++ b/shared/package-files/56/56aac2a7abf671e0aa8572d582c9662988dc085efa5bbe09a76c74dfc31afaa8/as_strided_meta_dispatch.h @@ -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 meta { + +TORCH_API at::Tensor as_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt); +TORCH_API at::Tensor as_strided_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/56/56ae000d5391f3ba8171b2fd04c397ec339bb3a4c9406108893dcb8af1f89a48/config.py b/shared/package-files/56/56ae000d5391f3ba8171b2fd04c397ec339bb3a4c9406108893dcb8af1f89a48/config.py new file mode 100644 index 0000000000000000000000000000000000000000..da5120d6edf180f7fbbe88ac342b4d0e4b383e50 --- /dev/null +++ b/shared/package-files/56/56ae000d5391f3ba8171b2fd04c397ec339bb3a4c9406108893dcb8af1f89a48/config.py @@ -0,0 +1,6 @@ +# Whether to disable showing progress on compilation passes +# Need to add a new config otherwise wil get a circular import if dynamo config is imported here +disable_progress = True + +# If True this also shows the node names in each pass, for small models this is great but larger models it's quite noisy +verbose_progress = False diff --git a/shared/package-files/56/56b1707aca5ac95c91c0c3d55b154ce30ec38d9f1750e811e5881e867abd93d3/plugin.py b/shared/package-files/56/56b1707aca5ac95c91c0c3d55b154ce30ec38d9f1750e811e5881e867abd93d3/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..4c87162bfcbad518cc9d1dc8404acc48316e5a37 --- /dev/null +++ b/shared/package-files/56/56b1707aca5ac95c91c0c3d55b154ce30ec38d9f1750e811e5881e867abd93d3/plugin.py @@ -0,0 +1,14 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import conda.plugins + +from .cli import cli + + +@conda.plugins.hookimpl +def conda_subcommands(): + yield conda.plugins.CondaSubcommand( + name="content-trust", + summary="Signing and verification tools for Conda", + action=cli, + ) diff --git a/shared/package-files/56/56b32974d0816450421972b81d81b9e08b2a1b6f9e111d786b3da7dc28c45c02/fft_rfft2.h b/shared/package-files/56/56b32974d0816450421972b81d81b9e08b2a1b6f9e111d786b3da7dc28c45c02/fft_rfft2.h new file mode 100644 index 0000000000000000000000000000000000000000..fd8be03e251b18c255f5df3de1f6173c2a246e8e --- /dev/null +++ b/shared/package-files/56/56b32974d0816450421972b81d81b9e08b2a1b6f9e111d786b3da7dc28c45c02/fft_rfft2.h @@ -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::fft_rfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor +inline at::Tensor fft_rfft2(const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2::call(self, s.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*s)) : c10::nullopt, dim, norm); +} +namespace symint { + template ::value>> + at::Tensor fft_rfft2(const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2::call(self, s.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*s)) : c10::nullopt, dim, norm); + } +} + +// aten::fft_rfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor +inline at::Tensor fft_rfft2_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2::call(self, s, dim, norm); +} +namespace symint { + template ::value>> + at::Tensor fft_rfft2(const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2::call(self, s, dim, norm); + } +} + +// aten::fft_rfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2_out::call(self, s.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*s)) : c10::nullopt, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_rfft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2_out::call(self, s.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*s)) : c10::nullopt, dim, norm, out); + } +} + +// aten::fft_rfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, c10::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft2_out::call(self, s.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*s)) : c10::nullopt, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_rfft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, c10::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft2_out::call(self, s.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*s)) : c10::nullopt, dim, norm, out); + } +} + +// aten::fft_rfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft2_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2_out::call(self, s, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_rfft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_rfft2_out::call(self, s, dim, norm, out); + } +} + +// aten::fft_rfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft2_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, c10::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft2_out::call(self, s, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_rfft2_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, c10::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft2_out::call(self, s, dim, norm, out); + } +} + +} diff --git a/shared/package-files/56/56b3bb75cf45bdf58c01c1aee4015648403890c4409885d95020bd8bf064f024/resolve_conj.h b/shared/package-files/56/56b3bb75cf45bdf58c01c1aee4015648403890c4409885d95020bd8bf064f024/resolve_conj.h new file mode 100644 index 0000000000000000000000000000000000000000..16baec799a0056dcdf077dec9de5e55ee65c915b --- /dev/null +++ b/shared/package-files/56/56b3bb75cf45bdf58c01c1aee4015648403890c4409885d95020bd8bf064f024/resolve_conj.h @@ -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::resolve_conj(Tensor(a) self) -> Tensor(a) +inline at::Tensor resolve_conj(const at::Tensor & self) { + return at::_ops::resolve_conj::call(self); +} + +} diff --git a/shared/package-files/56/56b54bb7f01a0ecf31d750dd59916901e39678e52f48413929cc77b2d5014485/test_base.py b/shared/package-files/56/56b54bb7f01a0ecf31d750dd59916901e39678e52f48413929cc77b2d5014485/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0842cf0c82b485b16717ac19c78b4d51098769eb --- /dev/null +++ b/shared/package-files/56/56b54bb7f01a0ecf31d750dd59916901e39678e52f48413929cc77b2d5014485/test_base.py @@ -0,0 +1,1081 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import pickle +import re +import warnings + +import numpy as np +import pytest +import scipy.sparse as sp +from numpy.testing import assert_allclose + +import sklearn +from sklearn import config_context, datasets +from sklearn.base import ( + BaseEstimator, + OutlierMixin, + TransformerMixin, + clone, + is_classifier, + is_clusterer, + is_outlier_detector, + is_regressor, +) +from sklearn.cluster import KMeans +from sklearn.decomposition import PCA +from sklearn.ensemble import IsolationForest +from sklearn.exceptions import InconsistentVersionWarning +from sklearn.metrics import get_scorer +from sklearn.model_selection import GridSearchCV, KFold +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC, SVR +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.utils._mocking import MockDataFrame +from sklearn.utils._set_output import _get_output_config +from sklearn.utils._testing import ( + _convert_container, + assert_array_equal, +) +from sklearn.utils.validation import _check_n_features, validate_data + + +############################################################################# +# A few test classes +class MyEstimator(BaseEstimator): + def __init__(self, l1=0, empty=None): + self.l1 = l1 + self.empty = empty + + +class K(BaseEstimator): + def __init__(self, c=None, d=None): + self.c = c + self.d = d + + +class T(BaseEstimator): + def __init__(self, a=None, b=None): + self.a = a + self.b = b + + +class NaNTag(BaseEstimator): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = True + return tags + + +class NoNaNTag(BaseEstimator): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = False + return tags + + +class OverrideTag(NaNTag): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = False + return tags + + +class DiamondOverwriteTag(NaNTag, NoNaNTag): + pass + + +class InheritDiamondOverwriteTag(DiamondOverwriteTag): + pass + + +class ModifyInitParams(BaseEstimator): + """Deprecated behavior. + Equal parameters but with a type cast. + Doesn't fulfill a is a + """ + + def __init__(self, a=np.array([0])): + self.a = a.copy() + + +class Buggy(BaseEstimator): + "A buggy estimator that does not set its parameters right." + + def __init__(self, a=None): + self.a = 1 + + +class NoEstimator: + def __init__(self): + pass + + def fit(self, X=None, y=None): + return self + + def predict(self, X=None): + return None + + +class VargEstimator(BaseEstimator): + """scikit-learn estimators shouldn't have vargs.""" + + def __init__(self, *vargs): + pass + + +############################################################################# +# The tests + + +def test_clone(): + # Tests that clone creates a correct deep copy. + # We create an estimator, make a copy of its original state + # (which, in this case, is the current state of the estimator), + # and check that the obtained copy is a correct deep copy. + + from sklearn.feature_selection import SelectFpr, f_classif + + selector = SelectFpr(f_classif, alpha=0.1) + new_selector = clone(selector) + assert selector is not new_selector + assert selector.get_params() == new_selector.get_params() + + selector = SelectFpr(f_classif, alpha=np.zeros((10, 2))) + new_selector = clone(selector) + assert selector is not new_selector + + +def test_clone_2(): + # Tests that clone doesn't copy everything. + # We first create an estimator, give it an own attribute, and + # make a copy of its original state. Then we check that the copy doesn't + # have the specific attribute we manually added to the initial estimator. + + from sklearn.feature_selection import SelectFpr, f_classif + + selector = SelectFpr(f_classif, alpha=0.1) + selector.own_attribute = "test" + new_selector = clone(selector) + assert not hasattr(new_selector, "own_attribute") + + +def test_clone_buggy(): + # Check that clone raises an error on buggy estimators. + buggy = Buggy() + buggy.a = 2 + with pytest.raises(RuntimeError): + clone(buggy) + + no_estimator = NoEstimator() + with pytest.raises(TypeError): + clone(no_estimator) + + varg_est = VargEstimator() + with pytest.raises(RuntimeError): + clone(varg_est) + + est = ModifyInitParams() + with pytest.raises(RuntimeError): + clone(est) + + +def test_clone_empty_array(): + # Regression test for cloning estimators with empty arrays + clf = MyEstimator(empty=np.array([])) + clf2 = clone(clf) + assert_array_equal(clf.empty, clf2.empty) + + clf = MyEstimator(empty=sp.csr_matrix(np.array([[0]]))) + clf2 = clone(clf) + assert_array_equal(clf.empty.data, clf2.empty.data) + + +def test_clone_nan(): + # Regression test for cloning estimators with default parameter as np.nan + clf = MyEstimator(empty=np.nan) + clf2 = clone(clf) + + assert clf.empty is clf2.empty + + +def test_clone_dict(): + # test that clone creates a clone of a dict + orig = {"a": MyEstimator()} + cloned = clone(orig) + assert orig["a"] is not cloned["a"] + + +def test_clone_sparse_matrices(): + sparse_matrix_classes = [ + cls + for name in dir(sp) + if name.endswith("_matrix") and type(cls := getattr(sp, name)) is type + ] + + for cls in sparse_matrix_classes: + sparse_matrix = cls(np.eye(5)) + clf = MyEstimator(empty=sparse_matrix) + clf_cloned = clone(clf) + assert clf.empty.__class__ is clf_cloned.empty.__class__ + assert_array_equal(clf.empty.toarray(), clf_cloned.empty.toarray()) + + +def test_clone_estimator_types(): + # Check that clone works for parameters that are types rather than + # instances + clf = MyEstimator(empty=MyEstimator) + clf2 = clone(clf) + + assert clf.empty is clf2.empty + + +def test_clone_class_rather_than_instance(): + # Check that clone raises expected error message when + # cloning class rather than instance + msg = "You should provide an instance of scikit-learn estimator" + with pytest.raises(TypeError, match=msg): + clone(MyEstimator) + + +def test_repr(): + # Smoke test the repr of the base estimator. + my_estimator = MyEstimator() + repr(my_estimator) + test = T(K(), K()) + assert repr(test) == "T(a=K(), b=K())" + + some_est = T(a=["long_params"] * 1000) + assert len(repr(some_est)) == 485 + + +def test_str(): + # Smoke test the str of the base estimator + my_estimator = MyEstimator() + str(my_estimator) + + +def test_get_params(): + test = T(K(), K) + + assert "a__d" in test.get_params(deep=True) + assert "a__d" not in test.get_params(deep=False) + + test.set_params(a__d=2) + assert test.a.d == 2 + + with pytest.raises(ValueError): + test.set_params(a__a=2) + + +# TODO(1.8): Remove this test when the deprecation is removed +def test_is_estimator_type_class(): + with pytest.warns(FutureWarning, match="passing a class to.*is deprecated"): + assert is_classifier(SVC) + + with pytest.warns(FutureWarning, match="passing a class to.*is deprecated"): + assert is_regressor(SVR) + + with pytest.warns(FutureWarning, match="passing a class to.*is deprecated"): + assert is_clusterer(KMeans) + + with pytest.warns(FutureWarning, match="passing a class to.*is deprecated"): + assert is_outlier_detector(IsolationForest) + + +@pytest.mark.parametrize( + "estimator, expected_result", + [ + (SVC(), True), + (GridSearchCV(SVC(), {"C": [0.1, 1]}), True), + (Pipeline([("svc", SVC())]), True), + (Pipeline([("svc_cv", GridSearchCV(SVC(), {"C": [0.1, 1]}))]), True), + (SVR(), False), + (GridSearchCV(SVR(), {"C": [0.1, 1]}), False), + (Pipeline([("svr", SVR())]), False), + (Pipeline([("svr_cv", GridSearchCV(SVR(), {"C": [0.1, 1]}))]), False), + ], +) +def test_is_classifier(estimator, expected_result): + assert is_classifier(estimator) == expected_result + + +@pytest.mark.parametrize( + "estimator, expected_result", + [ + (SVR(), True), + (GridSearchCV(SVR(), {"C": [0.1, 1]}), True), + (Pipeline([("svr", SVR())]), True), + (Pipeline([("svr_cv", GridSearchCV(SVR(), {"C": [0.1, 1]}))]), True), + (SVC(), False), + (GridSearchCV(SVC(), {"C": [0.1, 1]}), False), + (Pipeline([("svc", SVC())]), False), + (Pipeline([("svc_cv", GridSearchCV(SVC(), {"C": [0.1, 1]}))]), False), + ], +) +def test_is_regressor(estimator, expected_result): + assert is_regressor(estimator) == expected_result + + +@pytest.mark.parametrize( + "estimator, expected_result", + [ + (KMeans(), True), + (GridSearchCV(KMeans(), {"n_clusters": [3, 8]}), True), + (Pipeline([("km", KMeans())]), True), + (Pipeline([("km_cv", GridSearchCV(KMeans(), {"n_clusters": [3, 8]}))]), True), + (SVC(), False), + (GridSearchCV(SVC(), {"C": [0.1, 1]}), False), + (Pipeline([("svc", SVC())]), False), + (Pipeline([("svc_cv", GridSearchCV(SVC(), {"C": [0.1, 1]}))]), False), + ], +) +def test_is_clusterer(estimator, expected_result): + assert is_clusterer(estimator) == expected_result + + +def test_set_params(): + # test nested estimator parameter setting + clf = Pipeline([("svc", SVC())]) + + # non-existing parameter in svc + with pytest.raises(ValueError): + clf.set_params(svc__stupid_param=True) + + # non-existing parameter of pipeline + with pytest.raises(ValueError): + clf.set_params(svm__stupid_param=True) + + # we don't currently catch if the things in pipeline are estimators + # bad_pipeline = Pipeline([("bad", NoEstimator())]) + # with pytest.raises(AttributeError): + # bad_pipeline.set_params(bad__stupid_param=True) + + +def test_set_params_passes_all_parameters(): + # Make sure all parameters are passed together to set_params + # of nested estimator. Regression test for #9944 + + class TestDecisionTree(DecisionTreeClassifier): + def set_params(self, **kwargs): + super().set_params(**kwargs) + # expected_kwargs is in test scope + assert kwargs == expected_kwargs + return self + + expected_kwargs = {"max_depth": 5, "min_samples_leaf": 2} + for est in [ + Pipeline([("estimator", TestDecisionTree())]), + GridSearchCV(TestDecisionTree(), {}), + ]: + est.set_params(estimator__max_depth=5, estimator__min_samples_leaf=2) + + +def test_set_params_updates_valid_params(): + # Check that set_params tries to set SVC().C, not + # DecisionTreeClassifier().C + gscv = GridSearchCV(DecisionTreeClassifier(), {}) + gscv.set_params(estimator=SVC(), estimator__C=42.0) + assert gscv.estimator.C == 42.0 + + +@pytest.mark.parametrize( + "tree,dataset", + [ + ( + DecisionTreeClassifier(max_depth=2, random_state=0), + datasets.make_classification(random_state=0), + ), + ( + DecisionTreeRegressor(max_depth=2, random_state=0), + datasets.make_regression(random_state=0), + ), + ], +) +def test_score_sample_weight(tree, dataset): + rng = np.random.RandomState(0) + # check that the score with and without sample weights are different + X, y = dataset + + tree.fit(X, y) + # generate random sample weights + sample_weight = rng.randint(1, 10, size=len(y)) + score_unweighted = tree.score(X, y) + score_weighted = tree.score(X, y, sample_weight=sample_weight) + msg = "Unweighted and weighted scores are unexpectedly equal" + assert score_unweighted != score_weighted, msg + + +def test_clone_pandas_dataframe(): + class DummyEstimator(TransformerMixin, BaseEstimator): + """This is a dummy class for generating numerical features + + This feature extractor extracts numerical features from pandas data + frame. + + Parameters + ---------- + + df: pandas data frame + The pandas data frame parameter. + + Notes + ----- + """ + + def __init__(self, df=None, scalar_param=1): + self.df = df + self.scalar_param = scalar_param + + def fit(self, X, y=None): + pass + + def transform(self, X): + pass + + # build and clone estimator + d = np.arange(10) + df = MockDataFrame(d) + e = DummyEstimator(df, scalar_param=1) + cloned_e = clone(e) + + # the test + assert (e.df == cloned_e.df).values.all() + assert e.scalar_param == cloned_e.scalar_param + + +def test_clone_protocol(): + """Checks that clone works with `__sklearn_clone__` protocol.""" + + class FrozenEstimator(BaseEstimator): + def __init__(self, fitted_estimator): + self.fitted_estimator = fitted_estimator + + def __getattr__(self, name): + return getattr(self.fitted_estimator, name) + + def __sklearn_clone__(self): + return self + + def fit(self, *args, **kwargs): + return self + + def fit_transform(self, *args, **kwargs): + return self.fitted_estimator.transform(*args, **kwargs) + + X = np.array([[-1, -1], [-2, -1], [-3, -2]]) + pca = PCA().fit(X) + components = pca.components_ + + frozen_pca = FrozenEstimator(pca) + assert_allclose(frozen_pca.components_, components) + + # Calling PCA methods such as `get_feature_names_out` still works + assert_array_equal(frozen_pca.get_feature_names_out(), pca.get_feature_names_out()) + + # Fitting on a new data does not alter `components_` + X_new = np.asarray([[-1, 2], [3, 4], [1, 2]]) + frozen_pca.fit(X_new) + assert_allclose(frozen_pca.components_, components) + + # `fit_transform` does not alter state + frozen_pca.fit_transform(X_new) + assert_allclose(frozen_pca.components_, components) + + # Cloning estimator is a no-op + clone_frozen_pca = clone(frozen_pca) + assert clone_frozen_pca is frozen_pca + assert_allclose(clone_frozen_pca.components_, components) + + +def test_pickle_version_warning_is_not_raised_with_matching_version(): + iris = datasets.load_iris() + tree = DecisionTreeClassifier().fit(iris.data, iris.target) + tree_pickle = pickle.dumps(tree) + assert b"_sklearn_version" in tree_pickle + + with warnings.catch_warnings(): + warnings.simplefilter("error") + tree_restored = pickle.loads(tree_pickle) + + # test that we can predict with the restored decision tree classifier + score_of_original = tree.score(iris.data, iris.target) + score_of_restored = tree_restored.score(iris.data, iris.target) + assert score_of_original == score_of_restored + + +class TreeBadVersion(DecisionTreeClassifier): + def __getstate__(self): + return dict(self.__dict__.items(), _sklearn_version="something") + + +pickle_error_message = ( + "Trying to unpickle estimator {estimator} from " + "version {old_version} when using version " + "{current_version}. This might " + "lead to breaking code or invalid results. " + "Use at your own risk." +) + + +def test_pickle_version_warning_is_issued_upon_different_version(): + iris = datasets.load_iris() + tree = TreeBadVersion().fit(iris.data, iris.target) + tree_pickle_other = pickle.dumps(tree) + message = pickle_error_message.format( + estimator="TreeBadVersion", + old_version="something", + current_version=sklearn.__version__, + ) + with pytest.warns(UserWarning, match=message) as warning_record: + pickle.loads(tree_pickle_other) + + message = warning_record.list[0].message + assert isinstance(message, InconsistentVersionWarning) + assert message.estimator_name == "TreeBadVersion" + assert message.original_sklearn_version == "something" + assert message.current_sklearn_version == sklearn.__version__ + + +class TreeNoVersion(DecisionTreeClassifier): + def __getstate__(self): + return self.__dict__ + + +def test_pickle_version_warning_is_issued_when_no_version_info_in_pickle(): + iris = datasets.load_iris() + # TreeNoVersion has no getstate, like pre-0.18 + tree = TreeNoVersion().fit(iris.data, iris.target) + + tree_pickle_noversion = pickle.dumps(tree) + assert b"_sklearn_version" not in tree_pickle_noversion + message = pickle_error_message.format( + estimator="TreeNoVersion", + old_version="pre-0.18", + current_version=sklearn.__version__, + ) + # check we got the warning about using pre-0.18 pickle + with pytest.warns(UserWarning, match=message): + pickle.loads(tree_pickle_noversion) + + +def test_pickle_version_no_warning_is_issued_with_non_sklearn_estimator(): + iris = datasets.load_iris() + tree = TreeNoVersion().fit(iris.data, iris.target) + tree_pickle_noversion = pickle.dumps(tree) + try: + module_backup = TreeNoVersion.__module__ + TreeNoVersion.__module__ = "notsklearn" + + with warnings.catch_warnings(): + warnings.simplefilter("error") + + pickle.loads(tree_pickle_noversion) + finally: + TreeNoVersion.__module__ = module_backup + + +class DontPickleAttributeMixin: + def __getstate__(self): + data = self.__dict__.copy() + data["_attribute_not_pickled"] = None + return data + + def __setstate__(self, state): + state["_restored"] = True + self.__dict__.update(state) + + +class MultiInheritanceEstimator(DontPickleAttributeMixin, BaseEstimator): + def __init__(self, attribute_pickled=5): + self.attribute_pickled = attribute_pickled + self._attribute_not_pickled = None + + +def test_pickling_when_getstate_is_overwritten_by_mixin(): + estimator = MultiInheritanceEstimator() + estimator._attribute_not_pickled = "this attribute should not be pickled" + + serialized = pickle.dumps(estimator) + estimator_restored = pickle.loads(serialized) + assert estimator_restored.attribute_pickled == 5 + assert estimator_restored._attribute_not_pickled is None + assert estimator_restored._restored + + +def test_pickling_when_getstate_is_overwritten_by_mixin_outside_of_sklearn(): + try: + estimator = MultiInheritanceEstimator() + text = "this attribute should not be pickled" + estimator._attribute_not_pickled = text + old_mod = type(estimator).__module__ + type(estimator).__module__ = "notsklearn" + + serialized = estimator.__getstate__() + assert serialized == {"_attribute_not_pickled": None, "attribute_pickled": 5} + + serialized["attribute_pickled"] = 4 + estimator.__setstate__(serialized) + assert estimator.attribute_pickled == 4 + assert estimator._restored + finally: + type(estimator).__module__ = old_mod + + +class SingleInheritanceEstimator(BaseEstimator): + def __init__(self, attribute_pickled=5): + self.attribute_pickled = attribute_pickled + self._attribute_not_pickled = None + + def __getstate__(self): + state = super().__getstate__() + state["_attribute_not_pickled"] = None + return state + + +def test_pickling_works_when_getstate_is_overwritten_in_the_child_class(): + estimator = SingleInheritanceEstimator() + estimator._attribute_not_pickled = "this attribute should not be pickled" + + serialized = pickle.dumps(estimator) + estimator_restored = pickle.loads(serialized) + assert estimator_restored.attribute_pickled == 5 + assert estimator_restored._attribute_not_pickled is None + + +def test_tag_inheritance(): + # test that changing tags by inheritance is not allowed + + nan_tag_est = NaNTag() + no_nan_tag_est = NoNaNTag() + assert nan_tag_est.__sklearn_tags__().input_tags.allow_nan + assert not no_nan_tag_est.__sklearn_tags__().input_tags.allow_nan + + redefine_tags_est = OverrideTag() + assert not redefine_tags_est.__sklearn_tags__().input_tags.allow_nan + + diamond_tag_est = DiamondOverwriteTag() + assert diamond_tag_est.__sklearn_tags__().input_tags.allow_nan + + inherit_diamond_tag_est = InheritDiamondOverwriteTag() + assert inherit_diamond_tag_est.__sklearn_tags__().input_tags.allow_nan + + +def test_raises_on_get_params_non_attribute(): + class MyEstimator(BaseEstimator): + def __init__(self, param=5): + pass + + def fit(self, X, y=None): + return self + + est = MyEstimator() + msg = "'MyEstimator' object has no attribute 'param'" + + with pytest.raises(AttributeError, match=msg): + est.get_params() + + +def test_repr_mimebundle_(): + # Checks the display configuration flag controls the json output + tree = DecisionTreeClassifier() + output = tree._repr_mimebundle_() + assert "text/plain" in output + assert "text/html" in output + + with config_context(display="text"): + output = tree._repr_mimebundle_() + assert "text/plain" in output + assert "text/html" not in output + + +def test_repr_html_wraps(): + # Checks the display configuration flag controls the html output + tree = DecisionTreeClassifier() + + output = tree._repr_html_() + assert "