diff --git a/shared/package-files/02/02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece/test_numbers.py b/shared/package-files/02/02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece/test_numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..f9dccaaddda569b5ede6f97f5e175ea505d0e305 --- /dev/null +++ b/shared/package-files/02/02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece/test_numbers.py @@ -0,0 +1,2266 @@ +import numbers as nums +import decimal +from sympy.concrete.summations import Sum +from sympy.core import (EulerGamma, Catalan, TribonacciConstant, + GoldenRatio) +from sympy.core.containers import Tuple +from sympy.core.expr import unchanged +from sympy.core.logic import fuzzy_not +from sympy.core.mul import Mul +from sympy.core.numbers import (mpf_norm, mod_inverse, igcd, seterr, + igcd_lehmer, Integer, I, pi, comp, ilcm, Rational, E, nan, igcd2, + oo, AlgebraicNumber, igcdex, Number, Float, zoo, equal_valued) +from sympy.core.power import Pow +from sympy.core.relational import Ge, Gt, Le, Lt +from sympy.core.singleton import S +from sympy.core.symbol import Dummy, Symbol +from sympy.core.sympify import sympify +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.integers import floor +from sympy.functions.combinatorial.numbers import fibonacci +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.miscellaneous import sqrt, cbrt +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.polys.domains.realfield import RealField +from sympy.printing.latex import latex +from sympy.printing.repr import srepr +from sympy.simplify import simplify +from sympy.core.power import integer_nthroot, isqrt, integer_log +from sympy.polys.domains.groundtypes import PythonRational +from sympy.utilities.decorator import conserve_mpmath_dps +from sympy.utilities.iterables import permutations +from sympy.testing.pytest import XFAIL, raises, _both_exp_pow + +from mpmath import mpf +from mpmath.rational import mpq +import mpmath +from sympy.core import numbers +t = Symbol('t', real=False) + +_ninf = float(-oo) +_inf = float(oo) + + +def same_and_same_prec(a, b): + # stricter matching for Floats + return a == b and a._prec == b._prec + + +def test_seterr(): + seterr(divide=True) + raises(ValueError, lambda: S.Zero/S.Zero) + seterr(divide=False) + assert S.Zero / S.Zero is S.NaN + + +def test_mod(): + x = S.Half + y = Rational(3, 4) + z = Rational(5, 18043) + + assert x % x == 0 + assert x % y == S.Half + assert x % z == Rational(3, 36086) + assert y % x == Rational(1, 4) + assert y % y == 0 + assert y % z == Rational(9, 72172) + assert z % x == Rational(5, 18043) + assert z % y == Rational(5, 18043) + assert z % z == 0 + + a = Float(2.6) + + assert (a % .2) == 0.0 + assert (a % 2).round(15) == 0.6 + assert (a % 0.5).round(15) == 0.1 + + p = Symbol('p', infinite=True) + + assert oo % oo is nan + assert zoo % oo is nan + assert 5 % oo is nan + assert p % 5 is nan + + # In these two tests, if the precision of m does + # not match the precision of the ans, then it is + # likely that the change made now gives an answer + # with degraded accuracy. + r = Rational(500, 41) + f = Float('.36', 3) + m = r % f + ans = Float(r % Rational(f), 3) + assert m == ans and m._prec == ans._prec + f = Float('8.36', 3) + m = f % r + ans = Float(Rational(f) % r, 3) + assert m == ans and m._prec == ans._prec + + s = S.Zero + + assert s % float(1) == 0.0 + + # No rounding required since these numbers can be represented + # exactly. + assert Rational(3, 4) % Float(1.1) == 0.75 + assert Float(1.5) % Rational(5, 4) == 0.25 + assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25 + assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25') + assert 2.75 % Float('1.5') == Float('1.25') + + a = Integer(7) + b = Integer(4) + + assert type(a % b) == Integer + assert a % b == Integer(3) + assert Integer(1) % Rational(2, 3) == Rational(1, 3) + assert Rational(7, 5) % Integer(1) == Rational(2, 5) + assert Integer(2) % 1.5 == 0.5 + + assert Integer(3).__rmod__(Integer(10)) == Integer(1) + assert Integer(10) % 4 == Integer(2) + assert 15 % Integer(4) == Integer(3) + + +def test_divmod(): + x = Symbol("x") + assert divmod(S(12), S(8)) == Tuple(1, 4) + assert divmod(-S(12), S(8)) == Tuple(-2, 4) + assert divmod(S.Zero, S.One) == Tuple(0, 0) + raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero)) + raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero)) + assert divmod(S(12), 8) == Tuple(1, 4) + assert divmod(12, S(8)) == Tuple(1, 4) + assert S(1024)//x == 1024//x == floor(1024/x) + + assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2")) + assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2")) + assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2")) + assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5")) + assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0")) + assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3")) + assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0")) + assert divmod(S("2"), S(".1"))[0] == 19 + assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1")) + assert divmod(S("2"), 2) == Tuple(S("1"), S("0")) + assert divmod(2, S("2")) == Tuple(S("1"), S("0")) + assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5")) + assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5")) + assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3")) + assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2")) + assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5")) + assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6")) + assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3")) + assert divmod(S("3/2"), S("0.1"))[0] == 14 + assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1")) + assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2")) + assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2")) + assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0")) + assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0")) + assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0")) + assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3")) + assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3")) + assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0")) + assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1")) + assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5")) + assert divmod(2, S("3.5")) == Tuple(S("0"), S("2")) + assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5")) + assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5")) + assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3")) + assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1")) + assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3")) + assert divmod(2, S("1/3")) == Tuple(S("6"), S("0")) + assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3")) + assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3")) + assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1")) + assert divmod(2, S("0.1"))[0] == 19 + assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1")) + assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0")) + assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1")) + + assert str(divmod(S("2"), 0.3)) == '(6, 0.2)' + assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)' + assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)' + assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)' + assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)' + assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)' + assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)' + + assert divmod(-3, S(2)) == (-2, 1) + assert divmod(S(-3), S(2)) == (-2, 1) + assert divmod(S(-3), 2) == (-2, 1) + + assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2) + assert divmod(S(4), S(-2.1)) == divmod(4, -2.1) + assert divmod(S(-8), S(-2.5) ) == Tuple(3, -0.5) + + assert divmod(oo, 1) == (S.NaN, S.NaN) + assert divmod(S.NaN, 1) == (S.NaN, S.NaN) + assert divmod(1, S.NaN) == (S.NaN, S.NaN) + ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)] + OO = float('inf') + ANS = [tuple(map(float, i)) for i in ans] + assert [divmod(i, oo) for i in range(-2, 3)] == ans + ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)] + ANS = [tuple(map(float, i)) for i in ans] + assert [divmod(i, -oo) for i in range(-2, 3)] == ans + assert [divmod(i, -OO) for i in range(-2, 3)] == ANS + assert divmod(S(3.5), S(-2)) == divmod(3.5, -2) + assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2) + assert divmod(S(0.0), S(9)) == divmod(0.0, 9) + assert divmod(S(0), S(9.0)) == divmod(0, 9.0) + + +def test_igcd(): + assert igcd(0, 0) == 0 + assert igcd(0, 1) == 1 + assert igcd(1, 0) == 1 + assert igcd(0, 7) == 7 + assert igcd(7, 0) == 7 + assert igcd(7, 1) == 1 + assert igcd(1, 7) == 1 + assert igcd(-1, 0) == 1 + assert igcd(0, -1) == 1 + assert igcd(-1, -1) == 1 + assert igcd(-1, 7) == 1 + assert igcd(7, -1) == 1 + assert igcd(8, 2) == 2 + assert igcd(4, 8) == 4 + assert igcd(8, 16) == 8 + assert igcd(7, -3) == 1 + assert igcd(-7, 3) == 1 + assert igcd(-7, -3) == 1 + assert igcd(*[10, 20, 30]) == 10 + raises(TypeError, lambda: igcd()) + raises(TypeError, lambda: igcd(2)) + raises(ValueError, lambda: igcd(0, None)) + raises(ValueError, lambda: igcd(1, 2.2)) + for args in permutations((45.1, 1, 30)): + raises(ValueError, lambda: igcd(*args)) + for args in permutations((1, 2, None)): + raises(ValueError, lambda: igcd(*args)) + + +def test_igcd_lehmer(): + a, b = fibonacci(10001), fibonacci(10000) + # len(str(a)) == 2090 + # small divisors, long Euclidean sequence + assert igcd_lehmer(a, b) == 1 + c = fibonacci(100) + assert igcd_lehmer(a*c, b*c) == c + # big divisor + assert igcd_lehmer(a, 10**1000) == 1 + # swapping argument + assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1) + + +def test_igcd2(): + # short loop + assert igcd2(2**100 - 1, 2**99 - 1) == 1 + # Lehmer's algorithm + a, b = int(fibonacci(10001)), int(fibonacci(10000)) + assert igcd2(a, b) == 1 + + +def test_ilcm(): + assert ilcm(0, 0) == 0 + assert ilcm(1, 0) == 0 + assert ilcm(0, 1) == 0 + assert ilcm(1, 1) == 1 + assert ilcm(2, 1) == 2 + assert ilcm(8, 2) == 8 + assert ilcm(8, 6) == 24 + assert ilcm(8, 7) == 56 + assert ilcm(*[10, 20, 30]) == 60 + raises(ValueError, lambda: ilcm(8.1, 7)) + raises(ValueError, lambda: ilcm(8, 7.1)) + raises(TypeError, lambda: ilcm(8)) + + +def test_igcdex(): + assert igcdex(2, 3) == (-1, 1, 1) + assert igcdex(10, 12) == (-1, 1, 2) + assert igcdex(100, 2004) == (-20, 1, 4) + assert igcdex(0, 0) == (0, 1, 0) + assert igcdex(1, 0) == (1, 0, 1) + + +def _strictly_equal(a, b): + return (a.p, a.q, type(a.p), type(a.q)) == \ + (b.p, b.q, type(b.p), type(b.q)) + + +def _test_rational_new(cls): + """ + Tests that are common between Integer and Rational. + """ + assert cls(0) is S.Zero + assert cls(1) is S.One + assert cls(-1) is S.NegativeOne + # These look odd, but are similar to int(): + assert cls('1') is S.One + assert cls('-1') is S.NegativeOne + + i = Integer(10) + assert _strictly_equal(i, cls('10')) + assert _strictly_equal(i, cls('10')) + assert _strictly_equal(i, cls(int(10))) + assert _strictly_equal(i, cls(i)) + + raises(TypeError, lambda: cls(Symbol('x'))) + + +def test_Integer_new(): + """ + Test for Integer constructor + """ + _test_rational_new(Integer) + + assert _strictly_equal(Integer(0.9), S.Zero) + assert _strictly_equal(Integer(10.5), Integer(10)) + raises(ValueError, lambda: Integer("10.5")) + assert Integer(Rational('1.' + '9'*20)) == 1 + + +def test_Rational_new(): + """" + Test for Rational constructor + """ + _test_rational_new(Rational) + + n1 = S.Half + assert n1 == Rational(Integer(1), 2) + assert n1 == Rational(Integer(1), Integer(2)) + assert n1 == Rational(1, Integer(2)) + assert n1 == Rational(S.Half) + assert 1 == Rational(n1, n1) + assert Rational(3, 2) == Rational(S.Half, Rational(1, 3)) + assert Rational(3, 1) == Rational(1, Rational(1, 3)) + n3_4 = Rational(3, 4) + assert Rational('3/4') == n3_4 + assert -Rational('-3/4') == n3_4 + assert Rational('.76').limit_denominator(4) == n3_4 + assert Rational(19, 25).limit_denominator(4) == n3_4 + assert Rational('19/25').limit_denominator(4) == n3_4 + assert Rational(1.0, 3) == Rational(1, 3) + assert Rational(1, 3.0) == Rational(1, 3) + assert Rational(Float(0.5)) == S.Half + assert Rational('1e2/1e-2') == Rational(10000) + assert Rational('1 234') == Rational(1234) + assert Rational('1/1 234') == Rational(1, 1234) + assert Rational(-1, 0) is S.ComplexInfinity + assert Rational(1, 0) is S.ComplexInfinity + # Make sure Rational doesn't lose precision on Floats + assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100) + raises(TypeError, lambda: Rational('3**3')) + raises(TypeError, lambda: Rational('1/2 + 2/3')) + + # handle fractions.Fraction instances + try: + import fractions + assert Rational(fractions.Fraction(1, 2)) == S.Half + except ImportError: + pass + + assert Rational(mpq(2, 6)) == Rational(1, 3) + assert Rational(PythonRational(2, 6)) == Rational(1, 3) + + assert Rational(2, 4, gcd=1).q == 4 + n = Rational(2, -4, gcd=1) + assert n.q == 4 + assert n.p == -2 + +def test_issue_24543(): + for p in ('1.5', 1.5, 2): + for q in ('1.5', 1.5, 2): + assert Rational(p, q).as_numer_denom() == Rational('%s/%s'%(p,q)).as_numer_denom() + + assert Rational('0.5', '100') == Rational(1, 200) + + +def test_Number_new(): + """" + Test for Number constructor + """ + # Expected behavior on numbers and strings + assert Number(1) is S.One + assert Number(2).__class__ is Integer + assert Number(-622).__class__ is Integer + assert Number(5, 3).__class__ is Rational + assert Number(5.3).__class__ is Float + assert Number('1') is S.One + assert Number('2').__class__ is Integer + assert Number('-622').__class__ is Integer + assert Number('5/3').__class__ is Rational + assert Number('5.3').__class__ is Float + raises(ValueError, lambda: Number('cos')) + raises(TypeError, lambda: Number(cos)) + a = Rational(3, 5) + assert Number(a) is a # Check idempotence on Numbers + u = ['inf', '-inf', 'nan', 'iNF', '+inf'] + v = [oo, -oo, nan, oo, oo] + for i, a in zip(u, v): + assert Number(i) is a, (i, Number(i), a) + + +def test_Number_cmp(): + n1 = Number(1) + n2 = Number(2) + n3 = Number(-3) + + assert n1 < n2 + assert n1 <= n2 + assert n3 < n1 + assert n2 > n3 + assert n2 >= n3 + + raises(TypeError, lambda: n1 < S.NaN) + raises(TypeError, lambda: n1 <= S.NaN) + raises(TypeError, lambda: n1 > S.NaN) + raises(TypeError, lambda: n1 >= S.NaN) + + +def test_Rational_cmp(): + n1 = Rational(1, 4) + n2 = Rational(1, 3) + n3 = Rational(2, 4) + n4 = Rational(2, -4) + n5 = Rational(0) + n6 = Rational(1) + n7 = Rational(3) + n8 = Rational(-3) + + assert n8 < n5 + assert n5 < n6 + assert n6 < n7 + assert n8 < n7 + assert n7 > n8 + assert (n1 + 1)**n2 < 2 + assert ((n1 + n6)/n7) < 1 + + assert n4 < n3 + assert n2 < n3 + assert n1 < n2 + assert n3 > n1 + assert not n3 < n1 + assert not (Rational(-1) > 0) + assert Rational(-1) < 0 + + raises(TypeError, lambda: n1 < S.NaN) + raises(TypeError, lambda: n1 <= S.NaN) + raises(TypeError, lambda: n1 > S.NaN) + raises(TypeError, lambda: n1 >= S.NaN) + + +def test_Float(): + def eq(a, b): + t = Float("1.0E-15") + return (-t < a - b < t) + + zeros = (0, S.Zero, 0., Float(0)) + for i, j in permutations(zeros, 2): + assert i == j + for z in zeros: + assert z in zeros + assert S.Zero.is_zero + + a = Float(2) ** Float(3) + assert eq(a.evalf(), Float(8)) + assert eq((pi ** -1).evalf(), Float("0.31830988618379067")) + a = Float(2) ** Float(4) + assert eq(a.evalf(), Float(16)) + assert (S(.3) == S(.5)) is False + + mpf = (0, 5404319552844595, -52, 53) + x_str = Float((0, '13333333333333', -52, 53)) + x_0xstr = Float((0, '0x13333333333333', -52, 53)) + x2_str = Float((0, '26666666666666', -53, 54)) + x_hex = Float((0, int(0x13333333333333), -52, 53)) + x_dec = Float(mpf) + assert x_str == x_0xstr == x_hex == x_dec == Float(1.2) + # x2_str was entered slightly malformed in that the mantissa + # was even -- it should be odd and the even part should be + # included with the exponent, but this is resolved by normalization + # ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must + # be exact: double the mantissa ==> increase bc by 1 + assert Float(1.2)._mpf_ == mpf + assert x2_str._mpf_ == mpf + + assert Float((0, int(0), -123, -1)) is S.NaN + assert Float((0, int(0), -456, -2)) is S.Infinity + assert Float((1, int(0), -789, -3)) is S.NegativeInfinity + # if you don't give the full signature, it's not special + assert Float((0, int(0), -123)) == Float(0) + assert Float((0, int(0), -456)) == Float(0) + assert Float((1, int(0), -789)) == Float(0) + + raises(ValueError, lambda: Float((0, 7, 1, 3), '')) + + assert Float('0.0').is_finite is True + assert Float('0.0').is_negative is False + assert Float('0.0').is_positive is False + assert Float('0.0').is_infinite is False + assert Float('0.0').is_zero is True + + # rationality properties + # if the integer test fails then the use of intlike + # should be removed from gamma_functions.py + assert Float(1).is_integer is False + assert Float(1).is_rational is None + assert Float(1).is_irrational is None + assert sqrt(2).n(15).is_rational is None + assert sqrt(2).n(15).is_irrational is None + + # do not automatically evalf + def teq(a): + assert (a.evalf() == a) is False + assert (a.evalf() != a) is True + assert (a == a.evalf()) is False + assert (a != a.evalf()) is True + + teq(pi) + teq(2*pi) + teq(cos(0.1, evaluate=False)) + + # long integer + i = 12345678901234567890 + assert same_and_same_prec(Float(12, ''), Float('12', '')) + assert same_and_same_prec(Float(Integer(i), ''), Float(i, '')) + assert same_and_same_prec(Float(i, ''), Float(str(i), 20)) + assert same_and_same_prec(Float(str(i)), Float(i, '')) + assert same_and_same_prec(Float(i), Float(i, '')) + + # inexact floats (repeating binary = denom not multiple of 2) + # cannot have precision greater than 15 + assert Float(.125, 22) == .125 + assert Float(2.0, 22) == 2 + assert float(Float('.12500000000000001', '')) == .125 + raises(ValueError, lambda: Float(.12500000000000001, '')) + + # allow spaces + assert Float('123 456.123 456') == Float('123456.123456') + assert Integer('123 456') == Integer('123456') + assert Rational('123 456.123 456') == Rational('123456.123456') + assert Float(' .3e2') == Float('0.3e2') + + # allow underscore + assert Float('1_23.4_56') == Float('123.456') + assert Float('1_') == Float('1.0') + assert Float('1_.') == Float('1.0') + assert Float('1._') == Float('1.0') + assert Float('1__2') == Float('12.0') + # assert Float('1_23.4_5_6', 12) == Float('123.456', 12) + # ...but not in all cases (per Py 3.6) + raises(ValueError, lambda: Float('_1')) + raises(ValueError, lambda: Float('_inf')) + + # allow auto precision detection + assert Float('.1', '') == Float(.1, 1) + assert Float('.125', '') == Float(.125, 3) + assert Float('.100', '') == Float(.1, 3) + assert Float('2.0', '') == Float('2', 2) + + raises(ValueError, lambda: Float("12.3d-4", "")) + raises(ValueError, lambda: Float(12.3, "")) + raises(ValueError, lambda: Float('.')) + raises(ValueError, lambda: Float('-.')) + + zero = Float('0.0') + assert Float('-0') == zero + assert Float('.0') == zero + assert Float('-.0') == zero + assert Float('-0.0') == zero + assert Float(0.0) == zero + assert Float(0) == zero + assert Float(0, '') == Float('0', '') + assert Float(1) == Float(1.0) + assert Float(S.Zero) == zero + assert Float(S.One) == Float(1.0) + + assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3) + assert Float(decimal.Decimal('nan')) is S.NaN + assert Float(decimal.Decimal('Infinity')) is S.Infinity + assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity + + assert '{:.3f}'.format(Float(4.236622)) == '4.237' + assert '{:.35f}'.format(Float(pi.n(40), 40)) == \ + '3.14159265358979323846264338327950288' + + # unicode + assert Float('0.73908513321516064100000000') == \ + Float('0.73908513321516064100000000') + assert Float('0.73908513321516064100000000', 28) == \ + Float('0.73908513321516064100000000', 28) + + # binary precision + # Decimal value 0.1 cannot be expressed precisely as a base 2 fraction + a = Float(S.One/10, dps=15) + b = Float(S.One/10, dps=16) + p = Float(S.One/10, precision=53) + q = Float(S.One/10, precision=54) + assert a._mpf_ == p._mpf_ + assert not a._mpf_ == q._mpf_ + assert not b._mpf_ == q._mpf_ + + # Precision specifying errors + raises(ValueError, lambda: Float("1.23", dps=3, precision=10)) + raises(ValueError, lambda: Float("1.23", dps="", precision=10)) + raises(ValueError, lambda: Float("1.23", dps=3, precision="")) + raises(ValueError, lambda: Float("1.23", dps="", precision="")) + + # from NumberSymbol + assert same_and_same_prec(Float(pi, 32), pi.evalf(32)) + assert same_and_same_prec(Float(Catalan), Catalan.evalf()) + + # oo and nan + u = ['inf', '-inf', 'nan', 'iNF', '+inf'] + v = [oo, -oo, nan, oo, oo] + for i, a in zip(u, v): + assert Float(i) is a + + +def test_zero_not_false(): + # https://github.com/sympy/sympy/issues/20796 + assert (S(0.0) == S.false) is False + assert (S.false == S(0.0)) is False + assert (S(0) == S.false) is False + assert (S.false == S(0)) is False + + +@conserve_mpmath_dps +def test_float_mpf(): + import mpmath + mpmath.mp.dps = 100 + mp_pi = mpmath.pi() + + assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) + + mpmath.mp.dps = 15 + + assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) + + +def test_Float_RealElement(): + repi = RealField(dps=100)(pi.evalf(100)) + # We still have to pass the precision because Float doesn't know what + # RealElement is, but make sure it keeps full precision from the result. + assert Float(repi, 100) == pi.evalf(100) + + +def test_Float_default_to_highprec_from_str(): + s = str(pi.evalf(128)) + assert same_and_same_prec(Float(s), Float(s, '')) + + +def test_Float_eval(): + a = Float(3.2) + assert (a**2).is_Float + + +def test_Float_issue_2107(): + a = Float(0.1, 10) + b = Float("0.1", 10) + + assert a - a == 0 + assert a + (-a) == 0 + assert S.Zero + a - a == 0 + assert S.Zero + a + (-a) == 0 + + assert b - b == 0 + assert b + (-b) == 0 + assert S.Zero + b - b == 0 + assert S.Zero + b + (-b) == 0 + + +def test_issue_14289(): + from sympy.polys.numberfields import to_number_field + + a = 1 - sqrt(2) + b = to_number_field(a) + assert b.as_expr() == a + assert b.minpoly(a).expand() == 0 + + +def test_Float_from_tuple(): + a = Float((0, '1L', 0, 1)) + b = Float((0, '1', 0, 1)) + assert a == b + + +def test_Infinity(): + assert oo != 1 + assert 1*oo is oo + assert 1 != oo + assert oo != -oo + assert oo != Symbol("x")**3 + assert oo + 1 is oo + assert 2 + oo is oo + assert 3*oo + 2 is oo + assert S.Half**oo == 0 + assert S.Half**(-oo) is oo + assert -oo*3 is -oo + assert oo + oo is oo + assert -oo + oo*(-5) is -oo + assert 1/oo == 0 + assert 1/(-oo) == 0 + assert 8/oo == 0 + assert oo % 2 is nan + assert 2 % oo is nan + assert oo/oo is nan + assert oo/-oo is nan + assert -oo/oo is nan + assert -oo/-oo is nan + assert oo - oo is nan + assert oo - -oo is oo + assert -oo - oo is -oo + assert -oo - -oo is nan + assert oo + -oo is nan + assert -oo + oo is nan + assert oo + oo is oo + assert -oo + oo is nan + assert oo + -oo is nan + assert -oo + -oo is -oo + assert oo*oo is oo + assert -oo*oo is -oo + assert oo*-oo is -oo + assert -oo*-oo is oo + assert oo/0 is oo + assert -oo/0 is -oo + assert 0/oo == 0 + assert 0/-oo == 0 + assert oo*0 is nan + assert -oo*0 is nan + assert 0*oo is nan + assert 0*-oo is nan + assert oo + 0 is oo + assert -oo + 0 is -oo + assert 0 + oo is oo + assert 0 + -oo is -oo + assert oo - 0 is oo + assert -oo - 0 is -oo + assert 0 - oo is -oo + assert 0 - -oo is oo + assert oo/2 is oo + assert -oo/2 is -oo + assert oo/-2 is -oo + assert -oo/-2 is oo + assert oo*2 is oo + assert -oo*2 is -oo + assert oo*-2 is -oo + assert 2/oo == 0 + assert 2/-oo == 0 + assert -2/oo == 0 + assert -2/-oo == 0 + assert 2*oo is oo + assert 2*-oo is -oo + assert -2*oo is -oo + assert -2*-oo is oo + assert 2 + oo is oo + assert 2 - oo is -oo + assert -2 + oo is oo + assert -2 - oo is -oo + assert 2 + -oo is -oo + assert 2 - -oo is oo + assert -2 + -oo is -oo + assert -2 - -oo is oo + assert S(2) + oo is oo + assert S(2) - oo is -oo + assert oo/I == -oo*I + assert -oo/I == oo*I + assert oo*float(1) == _inf and (oo*float(1)) is oo + assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo + assert oo/float(1) == _inf and (oo/float(1)) is oo + assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo + assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo + assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo + assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo + assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo + assert oo + float(1) == _inf and (oo + float(1)) is oo + assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo + assert oo - float(1) == _inf and (oo - float(1)) is oo + assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo + assert float(1)*oo == _inf and (float(1)*oo) is oo + assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo + assert float(1)/oo == 0 + assert float(1)/-oo == 0 + assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo + assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo + assert float(-1)/oo == 0 + assert float(-1)/-oo == 0 + assert float(1) + oo is oo + assert float(1) + -oo is -oo + assert float(1) - oo is -oo + assert float(1) - -oo is oo + assert oo == float(oo) + assert (oo != float(oo)) is False + assert type(float(oo)) is float + assert -oo == float(-oo) + assert (-oo != float(-oo)) is False + assert type(float(-oo)) is float + + assert Float('nan') is nan + assert nan*1.0 is nan + assert -1.0*nan is nan + assert nan*oo is nan + assert nan*-oo is nan + assert nan/oo is nan + assert nan/-oo is nan + assert nan + oo is nan + assert nan + -oo is nan + assert nan - oo is nan + assert nan - -oo is nan + assert -oo * S.Zero is nan + + assert oo*nan is nan + assert -oo*nan is nan + assert oo/nan is nan + assert -oo/nan is nan + assert oo + nan is nan + assert -oo + nan is nan + assert oo - nan is nan + assert -oo - nan is nan + assert S.Zero * oo is nan + assert oo.is_Rational is False + assert isinstance(oo, Rational) is False + + assert S.One/oo == 0 + assert -S.One/oo == 0 + assert S.One/-oo == 0 + assert -S.One/-oo == 0 + assert S.One*oo is oo + assert -S.One*oo is -oo + assert S.One*-oo is -oo + assert -S.One*-oo is oo + assert S.One/nan is nan + assert S.One - -oo is oo + assert S.One + nan is nan + assert S.One - nan is nan + assert nan - S.One is nan + assert nan/S.One is nan + assert -oo - S.One is -oo + + +def test_Infinity_2(): + x = Symbol('x') + assert oo*x != oo + assert oo*(pi - 1) is oo + assert oo*(1 - pi) is -oo + + assert (-oo)*x != -oo + assert (-oo)*(pi - 1) is -oo + assert (-oo)*(1 - pi) is oo + + assert (-1)**S.NaN is S.NaN + assert oo - _inf is S.NaN + assert oo + _ninf is S.NaN + assert oo*0 is S.NaN + assert oo/_inf is S.NaN + assert oo/_ninf is S.NaN + assert oo**S.NaN is S.NaN + assert -oo + _inf is S.NaN + assert -oo - _ninf is S.NaN + assert -oo*S.NaN is S.NaN + assert -oo*0 is S.NaN + assert -oo/_inf is S.NaN + assert -oo/_ninf is S.NaN + assert -oo/S.NaN is S.NaN + assert abs(-oo) is oo + assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN)) + assert (-oo)**3 is -oo + assert (-oo)**2 is oo + assert abs(S.ComplexInfinity) is oo + + +def test_Mul_Infinity_Zero(): + assert Float(0)*_inf is nan + assert Float(0)*_ninf is nan + assert Float(0)*_inf is nan + assert Float(0)*_ninf is nan + assert _inf*Float(0) is nan + assert _ninf*Float(0) is nan + assert _inf*Float(0) is nan + assert _ninf*Float(0) is nan + + +def test_Div_By_Zero(): + assert 1/S.Zero is zoo + assert 1/Float(0) is zoo + assert 0/S.Zero is nan + assert 0/Float(0) is nan + assert S.Zero/0 is nan + assert Float(0)/0 is nan + assert -1/S.Zero is zoo + assert -1/Float(0) is zoo + + +@_both_exp_pow +def test_Infinity_inequations(): + assert oo > pi + assert not (oo < pi) + assert exp(-3) < oo + + assert _inf > pi + assert not (_inf < pi) + assert exp(-3) < _inf + + raises(TypeError, lambda: oo < I) + raises(TypeError, lambda: oo <= I) + raises(TypeError, lambda: oo > I) + raises(TypeError, lambda: oo >= I) + raises(TypeError, lambda: -oo < I) + raises(TypeError, lambda: -oo <= I) + raises(TypeError, lambda: -oo > I) + raises(TypeError, lambda: -oo >= I) + + raises(TypeError, lambda: I < oo) + raises(TypeError, lambda: I <= oo) + raises(TypeError, lambda: I > oo) + raises(TypeError, lambda: I >= oo) + raises(TypeError, lambda: I < -oo) + raises(TypeError, lambda: I <= -oo) + raises(TypeError, lambda: I > -oo) + raises(TypeError, lambda: I >= -oo) + + assert oo > -oo and oo >= -oo + assert (oo < -oo) == False and (oo <= -oo) == False + assert -oo < oo and -oo <= oo + assert (-oo > oo) == False and (-oo >= oo) == False + + assert (oo < oo) == False # issue 7775 + assert (oo > oo) == False + assert (-oo > -oo) == False and (-oo < -oo) == False + assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo + assert (-oo < -_inf) == False + assert (oo > _inf) == False + assert -oo >= -_inf + assert oo <= _inf + + x = Symbol('x') + b = Symbol('b', finite=True, real=True) + assert (x < oo) == Lt(x, oo) # issue 7775 + assert b < oo and b > -oo and b <= oo and b >= -oo + assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False + assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b + assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x) + assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x) + assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x) + assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x) + + +def test_NaN(): + assert nan is nan + assert nan != 1 + assert 1*nan is nan + assert 1 != nan + assert -nan is nan + assert oo != Symbol("x")**3 + assert 2 + nan is nan + assert 3*nan + 2 is nan + assert -nan*3 is nan + assert nan + nan is nan + assert -nan + nan*(-5) is nan + assert 8/nan is nan + raises(TypeError, lambda: nan > 0) + raises(TypeError, lambda: nan < 0) + raises(TypeError, lambda: nan >= 0) + raises(TypeError, lambda: nan <= 0) + raises(TypeError, lambda: 0 < nan) + raises(TypeError, lambda: 0 > nan) + raises(TypeError, lambda: 0 <= nan) + raises(TypeError, lambda: 0 >= nan) + assert nan**0 == 1 # as per IEEE 754 + assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work + # test Pow._eval_power's handling of NaN + assert Pow(nan, 0, evaluate=False)**2 == 1 + for n in (1, 1., S.One, S.NegativeOne, Float(1)): + assert n + nan is nan + assert n - nan is nan + assert nan + n is nan + assert nan - n is nan + assert n/nan is nan + assert nan/n is nan + + +def test_special_numbers(): + assert isinstance(S.NaN, Number) is True + assert isinstance(S.Infinity, Number) is True + assert isinstance(S.NegativeInfinity, Number) is True + + assert S.NaN.is_number is True + assert S.Infinity.is_number is True + assert S.NegativeInfinity.is_number is True + assert S.ComplexInfinity.is_number is True + + assert isinstance(S.NaN, Rational) is False + assert isinstance(S.Infinity, Rational) is False + assert isinstance(S.NegativeInfinity, Rational) is False + + assert S.NaN.is_rational is not True + assert S.Infinity.is_rational is not True + assert S.NegativeInfinity.is_rational is not True + + +def test_powers(): + assert integer_nthroot(1, 2) == (1, True) + assert integer_nthroot(1, 5) == (1, True) + assert integer_nthroot(2, 1) == (2, True) + assert integer_nthroot(2, 2) == (1, False) + assert integer_nthroot(2, 5) == (1, False) + assert integer_nthroot(4, 2) == (2, True) + assert integer_nthroot(123**25, 25) == (123, True) + assert integer_nthroot(123**25 + 1, 25) == (123, False) + assert integer_nthroot(123**25 - 1, 25) == (122, False) + assert integer_nthroot(1, 1) == (1, True) + assert integer_nthroot(0, 1) == (0, True) + assert integer_nthroot(0, 3) == (0, True) + assert integer_nthroot(10000, 1) == (10000, True) + assert integer_nthroot(4, 2) == (2, True) + assert integer_nthroot(16, 2) == (4, True) + assert integer_nthroot(26, 2) == (5, False) + assert integer_nthroot(1234567**7, 7) == (1234567, True) + assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False) + assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False) + b = 25**1000 + assert integer_nthroot(b, 1000) == (25, True) + assert integer_nthroot(b + 1, 1000) == (25, False) + assert integer_nthroot(b - 1, 1000) == (24, False) + c = 10**400 + c2 = c**2 + assert integer_nthroot(c2, 2) == (c, True) + assert integer_nthroot(c2 + 1, 2) == (c, False) + assert integer_nthroot(c2 - 1, 2) == (c - 1, False) + assert integer_nthroot(2, 10**10) == (1, False) + + p, r = integer_nthroot(int(factorial(10000)), 100) + assert p % (10**10) == 5322420655 + assert not r + + # Test that this is fast + assert integer_nthroot(2, 10**10) == (1, False) + + # output should be int if possible + assert type(integer_nthroot(2**61, 2)[0]) is int + + +def test_integer_nthroot_overflow(): + assert integer_nthroot(10**(50*50), 50) == (10**50, True) + assert integer_nthroot(10**100000, 10000) == (10**10, True) + + +def test_integer_log(): + raises(ValueError, lambda: integer_log(2, 1)) + raises(ValueError, lambda: integer_log(0, 2)) + raises(ValueError, lambda: integer_log(1.1, 2)) + raises(ValueError, lambda: integer_log(1, 2.2)) + + assert integer_log(1, 2) == (0, True) + assert integer_log(1, 3) == (0, True) + assert integer_log(2, 3) == (0, False) + assert integer_log(3, 3) == (1, True) + assert integer_log(3*2, 3) == (1, False) + assert integer_log(3**2, 3) == (2, True) + assert integer_log(3*4, 3) == (2, False) + assert integer_log(3**3, 3) == (3, True) + assert integer_log(27, 5) == (2, False) + assert integer_log(2, 3) == (0, False) + assert integer_log(-4, -2) == (2, False) + assert integer_log(27, -3) == (3, False) + assert integer_log(-49, 7) == (0, False) + assert integer_log(-49, -7) == (2, False) + + +def test_isqrt(): + from math import sqrt as _sqrt + limit = 4503599761588223 + assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0] + assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0] + assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0] + assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0] + assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0] + assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0] + + # Regression tests for https://github.com/sympy/sympy/issues/17034 + assert isqrt(4503599761588224) == 67108864 + assert isqrt(9999999999999999) == 99999999 + + # Other corner cases, especially involving non-integers. + raises(ValueError, lambda: isqrt(-1)) + raises(ValueError, lambda: isqrt(-10**1000)) + raises(ValueError, lambda: isqrt(Rational(-1, 2))) + + tiny = Rational(1, 10**1000) + raises(ValueError, lambda: isqrt(-tiny)) + assert isqrt(1-tiny) == 0 + assert isqrt(4503599761588224-tiny) == 67108864 + assert isqrt(10**100 - tiny) == 10**50 - 1 + + # Check that using an inaccurate math.sqrt doesn't affect the results. + from sympy.core import power + old_sqrt = power._sqrt + power._sqrt = lambda x: 2.999999999 + try: + assert isqrt(9) == 3 + assert isqrt(10000) == 100 + finally: + power._sqrt = old_sqrt + + +def test_powers_Integer(): + """Test Integer._eval_power""" + # check infinity + assert S.One ** S.Infinity is S.NaN + assert S.NegativeOne** S.Infinity is S.NaN + assert S(2) ** S.Infinity is S.Infinity + assert S(-2)** S.Infinity == zoo + assert S(0) ** S.Infinity is S.Zero + + # check Nan + assert S.One ** S.NaN is S.NaN + assert S.NegativeOne ** S.NaN is S.NaN + + # check for exact roots + assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5) + assert sqrt(S(4)) == 2 + assert sqrt(S(-4)) == I * 2 + assert S(16) ** Rational(1, 4) == 2 + assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4) + assert S(9) ** Rational(3, 2) == 27 + assert S(-9) ** Rational(3, 2) == -27*I + assert S(27) ** Rational(2, 3) == 9 + assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3)) + assert (-2) ** Rational(-2, 1) == Rational(1, 4) + + # not exact roots + assert sqrt(-3) == I*sqrt(3) + assert (3) ** (Rational(3, 2)) == 3 * sqrt(3) + assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3) + assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3) + assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3) + assert (2) ** (Rational(3, 2)) == 2 * sqrt(2) + assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4 + assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3))) + assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3))) + assert (-3) ** Rational(-7, 3) == \ + -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 + assert (-3) ** Rational(-2, 3) == \ + -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 + + # join roots + assert sqrt(6) + sqrt(24) == 3*sqrt(6) + assert sqrt(2) * sqrt(3) == sqrt(6) + + # separate symbols & constansts + x = Symbol("x") + assert sqrt(49 * x) == 7 * sqrt(x) + assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi) + + # check that it is fast for big numbers + assert (2**64 + 1) ** Rational(4, 3) + assert (2**64 + 1) ** Rational(17, 25) + + # negative rational power and negative base + assert (-3) ** Rational(-7, 3) == \ + -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 + assert (-3) ** Rational(-2, 3) == \ + -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 + assert (-2) ** Rational(-10, 3) == \ + (-1)**Rational(2, 3)*2**Rational(2, 3)/16 + assert abs(Pow(-2, Rational(-10, 3)).n() - + Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16 + + # negative base and rational power with some simplification + assert (-8) ** Rational(2, 5) == \ + 2*(-1)**Rational(2, 5)*2**Rational(1, 5) + assert (-4) ** Rational(9, 5) == \ + -8*(-1)**Rational(4, 5)*2**Rational(3, 5) + + assert S(1234).factors() == {617: 1, 2: 1} + assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1} + + # test that eval_power factors numbers bigger than + # the current limit in factor_trial_division (2**15) + from sympy.ntheory.generate import nextprime + n = nextprime(2**15) + assert sqrt(n**2) == n + assert sqrt(n**3) == n*sqrt(n) + assert sqrt(4*n) == 2*sqrt(n) + + # check that factors of base with powers sharing gcd with power are removed + assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6) + assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6) + + # check that bases sharing a gcd are exptracted + assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \ + 2**Rational(8, 15)*3**Rational(9, 20) + assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \ + 4*2**Rational(7, 10)*3**Rational(8, 15) + assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \ + 4*(-3)**Rational(8, 15)*2**Rational(7, 10) + assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9) + assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3) + assert 2**Rational(2, 3)*6**Rational(8, 9) == \ + 2*2**Rational(5, 9)*3**Rational(8, 9) + assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3) + assert 3*Pow(3, 2, evaluate=False) == 3**3 + assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3) + assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \ + -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \ + 5**Rational(5, 6) + + assert Integer(-2)**Symbol('', even=True) == \ + Integer(2)**Symbol('', even=True) + assert (-1)**Float(.5) == 1.0*I + + +def test_powers_Rational(): + """Test Rational._eval_power""" + # check infinity + assert S.Half ** S.Infinity == 0 + assert Rational(3, 2) ** S.Infinity is S.Infinity + assert Rational(-1, 2) ** S.Infinity == 0 + assert Rational(-3, 2) ** S.Infinity == zoo + + # check Nan + assert Rational(3, 4) ** S.NaN is S.NaN + assert Rational(-2, 3) ** S.NaN is S.NaN + + # exact roots on numerator + assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3 + assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9 + assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3 + assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9 + assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2 + assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4) + + # exact root on denominator + assert sqrt(Rational(1, 4)) == S.Half + assert sqrt(Rational(1, -4)) == I * S.Half + assert sqrt(Rational(3, 4)) == sqrt(3) / 2 + assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2 + assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3 + + # not exact roots + assert sqrt(S.Half) == sqrt(2) / 2 + assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7)) + assert Rational(-3, 2)**Rational(-7, 3) == \ + -4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27 + assert Rational(-3, 2)**Rational(-2, 3) == \ + -(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3 + assert Rational(-3, 2)**Rational(-10, 3) == \ + 8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81 + assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() - + Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16 + + # negative integer power and negative rational base + assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4) + + a = Rational(1, 10) + assert a**Float(a, 2) == Float(a, 2)**Float(a, 2) + assert Rational(-2, 3)**Symbol('', even=True) == \ + Rational(2, 3)**Symbol('', even=True) + + +def test_powers_Float(): + assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3)) + + +def test_lshift_Integer(): + assert Integer(0) << Integer(2) == Integer(0) + assert Integer(0) << 2 == Integer(0) + assert 0 << Integer(2) == Integer(0) + + assert Integer(0b11) << Integer(0) == Integer(0b11) + assert Integer(0b11) << 0 == Integer(0b11) + assert 0b11 << Integer(0) == Integer(0b11) + + assert Integer(0b11) << Integer(2) == Integer(0b11 << 2) + assert Integer(0b11) << 2 == Integer(0b11 << 2) + assert 0b11 << Integer(2) == Integer(0b11 << 2) + + assert Integer(-0b11) << Integer(2) == Integer(-0b11 << 2) + assert Integer(-0b11) << 2 == Integer(-0b11 << 2) + assert -0b11 << Integer(2) == Integer(-0b11 << 2) + + raises(TypeError, lambda: Integer(2) << 0.0) + raises(TypeError, lambda: 0.0 << Integer(2)) + raises(ValueError, lambda: Integer(1) << Integer(-1)) + + +def test_rshift_Integer(): + assert Integer(0) >> Integer(2) == Integer(0) + assert Integer(0) >> 2 == Integer(0) + assert 0 >> Integer(2) == Integer(0) + + assert Integer(0b11) >> Integer(0) == Integer(0b11) + assert Integer(0b11) >> 0 == Integer(0b11) + assert 0b11 >> Integer(0) == Integer(0b11) + + assert Integer(0b11) >> Integer(2) == Integer(0) + assert Integer(0b11) >> 2 == Integer(0) + assert 0b11 >> Integer(2) == Integer(0) + + assert Integer(-0b11) >> Integer(2) == Integer(-1) + assert Integer(-0b11) >> 2 == Integer(-1) + assert -0b11 >> Integer(2) == Integer(-1) + + assert Integer(0b1100) >> Integer(2) == Integer(0b1100 >> 2) + assert Integer(0b1100) >> 2 == Integer(0b1100 >> 2) + assert 0b1100 >> Integer(2) == Integer(0b1100 >> 2) + + assert Integer(-0b1100) >> Integer(2) == Integer(-0b1100 >> 2) + assert Integer(-0b1100) >> 2 == Integer(-0b1100 >> 2) + assert -0b1100 >> Integer(2) == Integer(-0b1100 >> 2) + + raises(TypeError, lambda: Integer(0b10) >> 0.0) + raises(TypeError, lambda: 0.0 >> Integer(2)) + raises(ValueError, lambda: Integer(1) >> Integer(-1)) + + +def test_and_Integer(): + assert Integer(0b01010101) & Integer(0b10101010) == Integer(0) + assert Integer(0b01010101) & 0b10101010 == Integer(0) + assert 0b01010101 & Integer(0b10101010) == Integer(0) + + assert Integer(0b01010101) & Integer(0b11011011) == Integer(0b01010001) + assert Integer(0b01010101) & 0b11011011 == Integer(0b01010001) + assert 0b01010101 & Integer(0b11011011) == Integer(0b01010001) + + assert -Integer(0b01010101) & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011) + assert Integer(-0b01010101) & 0b11011011 == Integer(-0b01010101 & 0b11011011) + assert -0b01010101 & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011) + + assert Integer(0b01010101) & -Integer(0b11011011) == Integer(0b01010101 & -0b11011011) + assert Integer(0b01010101) & -0b11011011 == Integer(0b01010101 & -0b11011011) + assert 0b01010101 & Integer(-0b11011011) == Integer(0b01010101 & -0b11011011) + + raises(TypeError, lambda: Integer(2) & 0.0) + raises(TypeError, lambda: 0.0 & Integer(2)) + + +def test_xor_Integer(): + assert Integer(0b01010101) ^ Integer(0b11111111) == Integer(0b10101010) + assert Integer(0b01010101) ^ 0b11111111 == Integer(0b10101010) + assert 0b01010101 ^ Integer(0b11111111) == Integer(0b10101010) + + assert Integer(0b01010101) ^ Integer(0b11011011) == Integer(0b10001110) + assert Integer(0b01010101) ^ 0b11011011 == Integer(0b10001110) + assert 0b01010101 ^ Integer(0b11011011) == Integer(0b10001110) + + assert -Integer(0b01010101) ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011) + assert Integer(-0b01010101) ^ 0b11011011 == Integer(-0b01010101 ^ 0b11011011) + assert -0b01010101 ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011) + + assert Integer(0b01010101) ^ -Integer(0b11011011) == Integer(0b01010101 ^ -0b11011011) + assert Integer(0b01010101) ^ -0b11011011 == Integer(0b01010101 ^ -0b11011011) + assert 0b01010101 ^ Integer(-0b11011011) == Integer(0b01010101 ^ -0b11011011) + + raises(TypeError, lambda: Integer(2) ^ 0.0) + raises(TypeError, lambda: 0.0 ^ Integer(2)) + + +def test_or_Integer(): + assert Integer(0b01010101) | Integer(0b10101010) == Integer(0b11111111) + assert Integer(0b01010101) | 0b10101010 == Integer(0b11111111) + assert 0b01010101 | Integer(0b10101010) == Integer(0b11111111) + + assert Integer(0b01010101) | Integer(0b11011011) == Integer(0b11011111) + assert Integer(0b01010101) | 0b11011011 == Integer(0b11011111) + assert 0b01010101 | Integer(0b11011011) == Integer(0b11011111) + + assert -Integer(0b01010101) | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011) + assert Integer(-0b01010101) | 0b11011011 == Integer(-0b01010101 | 0b11011011) + assert -0b01010101 | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011) + + assert Integer(0b01010101) | -Integer(0b11011011) == Integer(0b01010101 | -0b11011011) + assert Integer(0b01010101) | -0b11011011 == Integer(0b01010101 | -0b11011011) + assert 0b01010101 | Integer(-0b11011011) == Integer(0b01010101 | -0b11011011) + + raises(TypeError, lambda: Integer(2) | 0.0) + raises(TypeError, lambda: 0.0 | Integer(2)) + + +def test_invert_Integer(): + assert ~Integer(0b01010101) == Integer(-0b01010110) + assert ~Integer(0b01010101) == Integer(~0b01010101) + assert ~(~Integer(0b01010101)) == Integer(0b01010101) + + +def test_abs1(): + assert Rational(1, 6) != Rational(-1, 6) + assert abs(Rational(1, 6)) == abs(Rational(-1, 6)) + + +def test_accept_int(): + assert Float(4) == 4 + + +def test_dont_accept_str(): + assert Float("0.2") != "0.2" + assert not (Float("0.2") == "0.2") + + +def test_int(): + a = Rational(5) + assert int(a) == 5 + a = Rational(9, 10) + assert int(a) == int(-a) == 0 + assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3) + # issue 10368 + a = Rational(32442016954, 78058255275) + assert type(int(a)) is type(int(-a)) is int + + +def test_int_NumberSymbols(): + assert int(Catalan) == 0 + assert int(EulerGamma) == 0 + assert int(pi) == 3 + assert int(E) == 2 + assert int(GoldenRatio) == 1 + assert int(TribonacciConstant) == 1 + for i in [Catalan, E, EulerGamma, GoldenRatio, TribonacciConstant, pi]: + a, b = i.approximation_interval(Integer) + ia = int(i) + assert ia == a + assert isinstance(ia, int) + assert b == a + 1 + assert a.is_Integer and b.is_Integer + + +def test_real_bug(): + x = Symbol("x") + assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"] + assert str(2.1*x*x) != "(2.0*x)*x" + + +def test_bug_sqrt(): + assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1 + + +def test_pi_Pi(): + "Test that pi (instance) is imported, but Pi (class) is not" + from sympy import pi # noqa + with raises(ImportError): + from sympy import Pi # noqa + + +def test_no_len(): + # there should be no len for numbers + raises(TypeError, lambda: len(Rational(2))) + raises(TypeError, lambda: len(Rational(2, 3))) + raises(TypeError, lambda: len(Integer(2))) + + +def test_issue_3321(): + assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half + assert 5 * sqrt(Rational(1, 5)) == sqrt(5) + + +def test_issue_3692(): + assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2 + assert ((-5)**Rational(1, 6)).expand(complex=True) == \ + 5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2 + assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3) + + +def test_issue_3423(): + x = Symbol("x") + assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half) + assert sqrt(x - 1) != I*sqrt(1 - x) + + +def test_issue_3449(): + x = Symbol("x") + assert sqrt(x - 1).subs(x, 5) == 2 + + +def test_issue_13890(): + x = Symbol("x") + e = (-x/4 - S.One/12)**x - 1 + f = simplify(e) + a = Rational(9, 5) + assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15 + + +def test_Integer_factors(): + def F(i): + return Integer(i).factors() + + assert F(1) == {} + assert F(2) == {2: 1} + assert F(3) == {3: 1} + assert F(4) == {2: 2} + assert F(5) == {5: 1} + assert F(6) == {2: 1, 3: 1} + assert F(7) == {7: 1} + assert F(8) == {2: 3} + assert F(9) == {3: 2} + assert F(10) == {2: 1, 5: 1} + assert F(11) == {11: 1} + assert F(12) == {2: 2, 3: 1} + assert F(13) == {13: 1} + assert F(14) == {2: 1, 7: 1} + assert F(15) == {3: 1, 5: 1} + assert F(16) == {2: 4} + assert F(17) == {17: 1} + assert F(18) == {2: 1, 3: 2} + assert F(19) == {19: 1} + assert F(20) == {2: 2, 5: 1} + assert F(21) == {3: 1, 7: 1} + assert F(22) == {2: 1, 11: 1} + assert F(23) == {23: 1} + assert F(24) == {2: 3, 3: 1} + assert F(25) == {5: 2} + assert F(26) == {2: 1, 13: 1} + assert F(27) == {3: 3} + assert F(28) == {2: 2, 7: 1} + assert F(29) == {29: 1} + assert F(30) == {2: 1, 3: 1, 5: 1} + assert F(31) == {31: 1} + assert F(32) == {2: 5} + assert F(33) == {3: 1, 11: 1} + assert F(34) == {2: 1, 17: 1} + assert F(35) == {5: 1, 7: 1} + assert F(36) == {2: 2, 3: 2} + assert F(37) == {37: 1} + assert F(38) == {2: 1, 19: 1} + assert F(39) == {3: 1, 13: 1} + assert F(40) == {2: 3, 5: 1} + assert F(41) == {41: 1} + assert F(42) == {2: 1, 3: 1, 7: 1} + assert F(43) == {43: 1} + assert F(44) == {2: 2, 11: 1} + assert F(45) == {3: 2, 5: 1} + assert F(46) == {2: 1, 23: 1} + assert F(47) == {47: 1} + assert F(48) == {2: 4, 3: 1} + assert F(49) == {7: 2} + assert F(50) == {2: 1, 5: 2} + assert F(51) == {3: 1, 17: 1} + + +def test_Rational_factors(): + def F(p, q, visual=None): + return Rational(p, q).factors(visual=visual) + + assert F(2, 3) == {2: 1, 3: -1} + assert F(2, 9) == {2: 1, 3: -2} + assert F(2, 15) == {2: 1, 3: -1, 5: -1} + assert F(6, 10) == {3: 1, 5: -1} + + +def test_issue_4107(): + assert pi*(E + 10) + pi*(-E - 10) != 0 + assert pi*(E + 10**10) + pi*(-E - 10**10) != 0 + assert pi*(E + 10**20) + pi*(-E - 10**20) != 0 + assert pi*(E + 10**80) + pi*(-E - 10**80) != 0 + + assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0 + assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0 + assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0 + assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0 + + +def test_IntegerInteger(): + a = Integer(4) + b = Integer(a) + + assert a == b + + +def test_Rational_gcd_lcm_cofactors(): + assert Integer(4).gcd(2) == Integer(2) + assert Integer(4).lcm(2) == Integer(4) + assert Integer(4).gcd(Integer(2)) == Integer(2) + assert Integer(4).lcm(Integer(2)) == Integer(4) + a, b = 720**99911, 480**12342 + assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b) + + assert Integer(4).gcd(3) == Integer(1) + assert Integer(4).lcm(3) == Integer(12) + assert Integer(4).gcd(Integer(3)) == Integer(1) + assert Integer(4).lcm(Integer(3)) == Integer(12) + + assert Rational(4, 3).gcd(2) == Rational(2, 3) + assert Rational(4, 3).lcm(2) == Integer(4) + assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3) + assert Rational(4, 3).lcm(Integer(2)) == Integer(4) + + assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9) + assert Integer(4).lcm(Rational(2, 9)) == Integer(4) + + assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9) + assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3) + assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45) + assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4) + assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7)) + + assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1)) + assert Integer(4).cofactors(Integer(2)) == \ + (Integer(2), Integer(2), Integer(1)) + + assert Integer(4).gcd(Float(2.0)) == Float(1.0) + assert Integer(4).lcm(Float(2.0)) == Float(8.0) + assert Integer(4).cofactors(Float(2.0)) == (Float(1.0), Float(4.0), Float(2.0)) + + assert S.Half.gcd(Float(2.0)) == Float(1.0) + assert S.Half.lcm(Float(2.0)) == Float(1.0) + assert S.Half.cofactors(Float(2.0)) == \ + (Float(1.0), Float(0.5), Float(2.0)) + + +def test_Float_gcd_lcm_cofactors(): + assert Float(2.0).gcd(Integer(4)) == Float(1.0) + assert Float(2.0).lcm(Integer(4)) == Float(8.0) + assert Float(2.0).cofactors(Integer(4)) == (Float(1.0), Float(2.0), Float(4.0)) + + assert Float(2.0).gcd(S.Half) == Float(1.0) + assert Float(2.0).lcm(S.Half) == Float(1.0) + assert Float(2.0).cofactors(S.Half) == \ + (Float(1.0), Float(2.0), Float(0.5)) + + +def test_issue_4611(): + assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10 + assert abs(E._evalf(50) - 2.71828182845905) < 1e-10 + assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10 + assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10 + assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10 + assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10 + + x = Symbol("x") + assert (pi + x).evalf() == pi.evalf() + x + assert (E + x).evalf() == E.evalf() + x + assert (Catalan + x).evalf() == Catalan.evalf() + x + assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x + assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x + assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x + + +@conserve_mpmath_dps +def test_conversion_to_mpmath(): + assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1) + assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5) + assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23') + + assert mpmath.mpmathify(I) == mpmath.mpc(1j) + + assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j) + + assert mpmath.mpmathify(2*I) == mpmath.mpc(2j) + assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j) + assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j) + + mpmath.mp.dps = 100 + assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j + assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j + + +def test_relational(): + # real + x = S(.1) + assert (x != cos) is True + assert (x == cos) is False + + # rational + x = Rational(1, 3) + assert (x != cos) is True + assert (x == cos) is False + + # integer defers to rational so these tests are omitted + + # number symbol + x = pi + assert (x != cos) is True + assert (x == cos) is False + + +def test_Integer_as_index(): + assert 'hello'[Integer(2):] == 'llo' + + +def test_Rational_int(): + assert int( Rational(7, 5)) == 1 + assert int( S.Half) == 0 + assert int(Rational(-1, 2)) == 0 + assert int(-Rational(7, 5)) == -1 + + +def test_zoo(): + b = Symbol('b', finite=True) + nz = Symbol('nz', nonzero=True) + p = Symbol('p', positive=True) + n = Symbol('n', negative=True) + im = Symbol('i', imaginary=True) + c = Symbol('c', complex=True) + pb = Symbol('pb', positive=True) + nb = Symbol('nb', negative=True) + imb = Symbol('ib', imaginary=True, finite=True) + for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3), + b, nz, p, n, im, pb, nb, imb, c]: + if i.is_finite and (i.is_real or i.is_imaginary): + assert i + zoo is zoo + assert i - zoo is zoo + assert zoo + i is zoo + assert zoo - i is zoo + elif i.is_finite is not False: + assert (i + zoo).is_Add + assert (i - zoo).is_Add + assert (zoo + i).is_Add + assert (zoo - i).is_Add + else: + assert (i + zoo) is S.NaN + assert (i - zoo) is S.NaN + assert (zoo + i) is S.NaN + assert (zoo - i) is S.NaN + + if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary): + assert i*zoo is zoo + assert zoo*i is zoo + elif i.is_zero: + assert i*zoo is S.NaN + assert zoo*i is S.NaN + else: + assert (i*zoo).is_Mul + assert (zoo*i).is_Mul + + if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary): + assert zoo/i is zoo + elif (1/i).is_zero: + assert zoo/i is S.NaN + elif i.is_zero: + assert zoo/i is zoo + else: + assert (zoo/i).is_Mul + + assert (I*oo).is_Mul # allow directed infinity + assert zoo + zoo is S.NaN + assert zoo * zoo is zoo + assert zoo - zoo is S.NaN + assert zoo/zoo is S.NaN + assert zoo**zoo is S.NaN + assert zoo**0 is S.One + assert zoo**2 is zoo + assert 1/zoo is S.Zero + + assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None) + + +def test_issue_4122(): + x = Symbol('x', nonpositive=True) + assert oo + x is oo + x = Symbol('x', extended_nonpositive=True) + assert (oo + x).is_Add + x = Symbol('x', finite=True) + assert (oo + x).is_Add # x could be imaginary + x = Symbol('x', nonnegative=True) + assert oo + x is oo + x = Symbol('x', extended_nonnegative=True) + assert oo + x is oo + x = Symbol('x', finite=True, real=True) + assert oo + x is oo + + # similarly for negative infinity + x = Symbol('x', nonnegative=True) + assert -oo + x is -oo + x = Symbol('x', extended_nonnegative=True) + assert (-oo + x).is_Add + x = Symbol('x', finite=True) + assert (-oo + x).is_Add + x = Symbol('x', nonpositive=True) + assert -oo + x is -oo + x = Symbol('x', extended_nonpositive=True) + assert -oo + x is -oo + x = Symbol('x', finite=True, real=True) + assert -oo + x is -oo + + +def test_GoldenRatio_expand(): + assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2 + + +def test_TribonacciConstant_expand(): + assert TribonacciConstant.expand(func=True) == \ + (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 + + +def test_as_content_primitive(): + assert S.Zero.as_content_primitive() == (1, 0) + assert S.Half.as_content_primitive() == (S.Half, 1) + assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1) + assert S(3).as_content_primitive() == (3, 1) + assert S(3.1).as_content_primitive() == (1, 3.1) + + +def test_hashing_sympy_integers(): + # Test for issue 5072 + assert {Integer(3)} == {int(3)} + assert hash(Integer(4)) == hash(int(4)) + + +def test_rounding_issue_4172(): + assert int((E**100).round()) == \ + 26881171418161354484126255515800135873611119 + assert int((pi**100).round()) == \ + 51878483143196131920862615246303013562686760680406 + assert int((Rational(1)/EulerGamma**100).round()) == \ + 734833795660954410469466 + + +@XFAIL +def test_mpmath_issues(): + from mpmath.libmp.libmpf import _normalize + import mpmath.libmp as mlib + rnd = mlib.round_nearest + mpf = (0, int(0), -123, -1, 53, rnd) # nan + assert _normalize(mpf, 53) != (0, int(0), 0, 0) + mpf = (0, int(0), -456, -2, 53, rnd) # +inf + assert _normalize(mpf, 53) != (0, int(0), 0, 0) + mpf = (1, int(0), -789, -3, 53, rnd) # -inf + assert _normalize(mpf, 53) != (0, int(0), 0, 0) + + from mpmath.libmp.libmpf import fnan + assert mlib.mpf_eq(fnan, fnan) + + +def test_Catalan_EulerGamma_prec(): + n = GoldenRatio + f = Float(n.n(), 5) + assert f._mpf_ == (0, int(212079), -17, 18) + assert f._prec == 20 + assert n._as_mpf_val(20) == f._mpf_ + + n = EulerGamma + f = Float(n.n(), 5) + assert f._mpf_ == (0, int(302627), -19, 19) + assert f._prec == 20 + assert n._as_mpf_val(20) == f._mpf_ + + +def test_Catalan_rewrite(): + k = Dummy('k', integer=True, nonnegative=True) + assert Catalan.rewrite(Sum).dummy_eq( + Sum((-1)**k/(2*k + 1)**2, (k, 0, oo))) + assert Catalan.rewrite() == Catalan + + +def test_bool_eq(): + assert 0 == False + assert S(0) == False + assert S(0) != S.false + assert 1 == True + assert S.One == True + assert S.One != S.true + + +def test_Float_eq(): + # all .5 values are the same + assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1) + # but floats that aren't exact in base-2 still + # don't compare the same because they have different + # underlying mpf values + assert Float(.12, 3) != Float(.12, 4) + assert Float(.12, 3) != .12 + assert 0.12 != Float(.12, 3) + assert Float('.12', 22) != .12 + # issue 11707 + # but Float/Rational -- except for 0 -- + # are exact so Rational(x) = Float(y) only if + # Rational(x) == Rational(Float(y)) + assert Float('1.1') != Rational(11, 10) + assert Rational(11, 10) != Float('1.1') + # coverage + assert not Float(3) == 2 + assert not Float(2**2) == S.Half + assert Float(2**2) == 4 + assert not Float(2**-2) == 1 + assert Float(2**-1) == S.Half + assert not Float(2*3) == 3 + assert not Float(2*3) == S.Half + assert Float(2*3) == 6 + assert not Float(2*3) == 8 + assert Float(.75) == Rational(3, 4) + assert Float(5/18) == 5/18 + # 4473 + assert Float(2.) != 3 + assert Float((0,1,-3)) == S.One/8 + assert Float((0,1,-3)) != S.One/9 + # 16196 + assert 2 == Float(2) # as per Python + # but in a computation... + assert t**2 != t**2.0 + + +def test_issue_6640(): + from mpmath.libmp.libmpf import finf, fninf + # fnan is not included because Float no longer returns fnan, + # but otherwise, the same sort of test could apply + assert Float(finf).is_zero is False + assert Float(fninf).is_zero is False + assert bool(Float(0)) is False + + +def test_issue_6349(): + assert Float('23.e3', '')._prec == 10 + assert Float('23e3', '')._prec == 20 + assert Float('23000', '')._prec == 20 + assert Float('-23000', '')._prec == 20 + + +def test_mpf_norm(): + assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_ + assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_ + + +def test_latex(): + assert latex(pi) == r"\pi" + assert latex(E) == r"e" + assert latex(GoldenRatio) == r"\phi" + assert latex(TribonacciConstant) == r"\text{TribonacciConstant}" + assert latex(EulerGamma) == r"\gamma" + assert latex(oo) == r"\infty" + assert latex(-oo) == r"-\infty" + assert latex(zoo) == r"\tilde{\infty}" + assert latex(nan) == r"\text{NaN}" + assert latex(I) == r"i" + + +def test_issue_7742(): + assert -oo % 1 is nan + + +def test_simplify_AlgebraicNumber(): + A = AlgebraicNumber + e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3) + assert simplify(A(e)) == A(12) # wester test_C20 + + e = (41 + 29*sqrt(2))**(S.One/5) + assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21 + + e = (3 + 4*I)**Rational(3, 2) + assert simplify(A(e)) == A(2 + 11*I) # issue 4401 + + +def test_Float_idempotence(): + x = Float('1.23', '') + y = Float(x) + z = Float(x, 15) + assert same_and_same_prec(y, x) + assert not same_and_same_prec(z, x) + x = Float(10**20) + y = Float(x) + z = Float(x, 15) + assert same_and_same_prec(y, x) + assert not same_and_same_prec(z, x) + + +def test_comp1(): + # sqrt(2) = 1.414213 5623730950... + a = sqrt(2).n(7) + assert comp(a, 1.4142129) is False + assert comp(a, 1.4142130) + # ... + assert comp(a, 1.4142141) + assert comp(a, 1.4142142) is False + assert comp(sqrt(2).n(2), '1.4') + assert comp(sqrt(2).n(2), Float(1.4, 2), '') + assert comp(sqrt(2).n(2), 1.4, '') + assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False + assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1) + assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1) + assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1) + assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1) + assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1) + assert [(i, j) + for i in range(130, 150) + for j in range(170, 180) + if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [ + (141, 173), (142, 173)] + raises(ValueError, lambda: comp(t, '1')) + raises(ValueError, lambda: comp(t, 1)) + assert comp(0, 0.0) + assert comp(.5, S.Half) + assert comp(2 + sqrt(2), 2.0 + sqrt(2)) + assert not comp(0, 1) + assert not comp(2, sqrt(2)) + assert not comp(2 + I, 2.0 + sqrt(2)) + assert not comp(2.0 + sqrt(2), 2 + I) + assert not comp(2.0 + sqrt(2), sqrt(3)) + assert comp(1/pi.n(4), 0.3183, 1e-5) + assert not comp(1/pi.n(4), 0.3183, 8e-6) + + +def test_issue_9491(): + assert oo**zoo is nan + + +def test_issue_10063(): + assert 2**Float(3) == Float(8) + + +def test_issue_10020(): + assert oo**I is S.NaN + assert oo**(1 + I) is S.ComplexInfinity + assert oo**(-1 + I) is S.Zero + assert (-oo)**I is S.NaN + assert (-oo)**(-1 + I) is S.Zero + assert oo**t == Pow(oo, t, evaluate=False) + assert (-oo)**t == Pow(-oo, t, evaluate=False) + + +def test_invert_numbers(): + assert S(2).invert(5) == 3 + assert S(2).invert(Rational(5, 2)) == S.Half + assert S(2).invert(5.) == S.Half + assert S(2).invert(S(5)) == 3 + assert S(2.).invert(5) == 0.5 + assert S(sqrt(2)).invert(5) == 1/sqrt(2) + assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2) + + +def test_mod_inverse(): + assert mod_inverse(3, 11) == 4 + assert mod_inverse(5, 11) == 9 + assert mod_inverse(21124921, 521512) == 7713 + assert mod_inverse(124215421, 5125) == 2981 + assert mod_inverse(214, 12515) == 1579 + assert mod_inverse(5823991, 3299) == 1442 + assert mod_inverse(123, 44) == 39 + assert mod_inverse(2, 5) == 3 + assert mod_inverse(-2, 5) == 2 + assert mod_inverse(2, -5) == -2 + assert mod_inverse(-2, -5) == -3 + assert mod_inverse(-3, -7) == -5 + x = Symbol('x') + assert S(2).invert(x) == S.Half + raises(TypeError, lambda: mod_inverse(2, x)) + raises(ValueError, lambda: mod_inverse(2, S.Half)) + raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2)) + + +def test_golden_ratio_rewrite_as_sqrt(): + assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half + + +def test_tribonacci_constant_rewrite_as_sqrt(): + assert TribonacciConstant.rewrite(sqrt) == \ + (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 + + +def test_comparisons_with_unknown_type(): + class Foo: + """ + Class that is unaware of Basic, and relies on both classes returning + the NotImplemented singleton for equivalence to evaluate to False. + + """ + + ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3) + foo = Foo() + + for n in ni, nf, nr, oo, -oo, zoo, nan: + assert n != foo + assert foo != n + assert not n == foo + assert not foo == n + raises(TypeError, lambda: n < foo) + raises(TypeError, lambda: foo > n) + raises(TypeError, lambda: n > foo) + raises(TypeError, lambda: foo < n) + raises(TypeError, lambda: n <= foo) + raises(TypeError, lambda: foo >= n) + raises(TypeError, lambda: n >= foo) + raises(TypeError, lambda: foo <= n) + + class Bar: + """ + Class that considers itself equal to any instance of Number except + infinities and nans, and relies on SymPy types returning the + NotImplemented singleton for symmetric equality relations. + + """ + def __eq__(self, other): + if other in (oo, -oo, zoo, nan): + return False + if isinstance(other, Number): + return True + return NotImplemented + + def __ne__(self, other): + return not self == other + + bar = Bar() + + for n in ni, nf, nr: + assert n == bar + assert bar == n + assert not n != bar + assert not bar != n + + for n in oo, -oo, zoo, nan: + assert n != bar + assert bar != n + assert not n == bar + assert not bar == n + + for n in ni, nf, nr, oo, -oo, zoo, nan: + raises(TypeError, lambda: n < bar) + raises(TypeError, lambda: bar > n) + raises(TypeError, lambda: n > bar) + raises(TypeError, lambda: bar < n) + raises(TypeError, lambda: n <= bar) + raises(TypeError, lambda: bar >= n) + raises(TypeError, lambda: n >= bar) + raises(TypeError, lambda: bar <= n) + + +def test_NumberSymbol_comparison(): + from sympy.core.tests.test_relational import rel_check + rpi = Rational('905502432259640373/288230376151711744') + fpi = Float(float(pi)) + assert rel_check(rpi, fpi) + + +def test_Integer_precision(): + # Make sure Integer inputs for keyword args work + assert Float('1.0', dps=Integer(15))._prec == 53 + assert Float('1.0', precision=Integer(15))._prec == 15 + assert type(Float('1.0', precision=Integer(15))._prec) == int + assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15) + + +def test_numpy_to_float(): + from sympy.testing.pytest import skip + from sympy.external import import_module + np = import_module('numpy') + if not np: + skip('numpy not installed. Abort numpy tests.') + + def check_prec_and_relerr(npval, ratval): + prec = np.finfo(npval).nmant + 1 + x = Float(npval) + assert x._prec == prec + y = Float(ratval, precision=prec) + assert abs((x - y)/y) < 2**(-(prec + 1)) + + check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3)) + check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3)) + check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3)) + # extended precision, on some arch/compilers: + x = np.longdouble(2)/3 + check_prec_and_relerr(x, Rational(2, 3)) + y = Float(x, precision=10) + assert same_and_same_prec(y, Float(Rational(2, 3), precision=10)) + + raises(TypeError, lambda: Float(np.complex64(1+2j))) + raises(TypeError, lambda: Float(np.complex128(1+2j))) + + +def test_Integer_ceiling_floor(): + a = Integer(4) + + assert a.floor() == a + assert a.ceiling() == a + + +def test_ComplexInfinity(): + assert zoo.floor() is zoo + assert zoo.ceiling() is zoo + assert zoo**zoo is S.NaN + + +def test_Infinity_floor_ceiling_power(): + assert oo.floor() is oo + assert oo.ceiling() is oo + assert oo**S.NaN is S.NaN + assert oo**zoo is S.NaN + + +def test_One_power(): + assert S.One**12 is S.One + assert S.NegativeOne**S.NaN is S.NaN + + +def test_NegativeInfinity(): + assert (-oo).floor() is -oo + assert (-oo).ceiling() is -oo + assert (-oo)**11 is -oo + assert (-oo)**12 is oo + + +def test_issue_6133(): + raises(TypeError, lambda: (-oo < None)) + raises(TypeError, lambda: (S(-2) < None)) + raises(TypeError, lambda: (oo < None)) + raises(TypeError, lambda: (oo > None)) + raises(TypeError, lambda: (S(2) < None)) + + +def test_abc(): + x = numbers.Float(5) + assert(isinstance(x, nums.Number)) + assert(isinstance(x, numbers.Number)) + assert(isinstance(x, nums.Real)) + y = numbers.Rational(1, 3) + assert(isinstance(y, nums.Number)) + assert(y.numerator == 1) + assert(y.denominator == 3) + assert(isinstance(y, nums.Rational)) + z = numbers.Integer(3) + assert(isinstance(z, nums.Number)) + assert(isinstance(z, numbers.Number)) + assert(isinstance(z, nums.Rational)) + assert(isinstance(z, numbers.Rational)) + assert(isinstance(z, nums.Integral)) + + +def test_floordiv(): + assert S(2)//S.Half == 4 + + +def test_negation(): + assert -S.Zero is S.Zero + assert -Float(0) is not S.Zero and -Float(0) == 0.0 + + +def test_exponentiation_of_0(): + x = Symbol('x') + assert 0**-x == zoo**x + assert unchanged(Pow, 0, x) + x = Symbol('x', zero=True) + assert 0**-x == S.One + assert 0**x == S.One + + +def test_equal_valued(): + x = Symbol('x') + + equal_values = [ + [1, 1.0, S(1), S(1.0), S(1).n(5)], + [2, 2.0, S(2), S(2.0), S(2).n(5)], + [-1, -1.0, -S(1), -S(1.0), -S(1).n(5)], + [0.5, S(0.5), S(1)/2], + [-0.5, -S(0.5), -S(1)/2], + [0, 0.0, S(0), S(0.0), S(0).n()], + [pi], [pi.n()], # <-- not equal + [S(1)/10], [0.1, S(0.1)], # <-- not equal + [S(0.1).n(5)], + [oo], + [cos(x/2)], [cos(0.5*x)], # <-- no recursion + ] + + for m, values_m in enumerate(equal_values): + for value_i in values_m: + + # All values in same list equal + for value_j in values_m: + assert equal_valued(value_i, value_j) is True + + # Not equal to anything in any other list: + for n, values_n in enumerate(equal_values): + if n == m: + continue + for value_j in values_n: + assert equal_valued(value_i, value_j) is False diff --git a/shared/package-files/02/0201abc9e320bf0a23453582581971b0bf4f826a91e4cd1e0b1283ddfe214bf7/is_complex.h b/shared/package-files/02/0201abc9e320bf0a23453582581971b0bf4f826a91e4cd1e0b1283ddfe214bf7/is_complex.h new file mode 100644 index 0000000000000000000000000000000000000000..e23576d017fcd1f660020d8ac5327ff0b9f3cd38 --- /dev/null +++ b/shared/package-files/02/0201abc9e320bf0a23453582581971b0bf4f826a91e4cd1e0b1283ddfe214bf7/is_complex.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::is_complex(Tensor self) -> bool +inline bool __dispatch_is_complex(const at::Tensor & self) { + return at::_ops::is_complex::call(self); +} + +} diff --git a/shared/package-files/02/0203398ea9789f2c6b4c3e73970d030b5a5138b46d94bdadb5439223407486ac/kernel_approximation.py b/shared/package-files/02/0203398ea9789f2c6b4c3e73970d030b5a5138b46d94bdadb5439223407486ac/kernel_approximation.py new file mode 100644 index 0000000000000000000000000000000000000000..02c8af755baeaa53ffe13c33371167dcc2aeeb6e --- /dev/null +++ b/shared/package-files/02/0203398ea9789f2c6b4c3e73970d030b5a5138b46d94bdadb5439223407486ac/kernel_approximation.py @@ -0,0 +1,1106 @@ +"""Approximate kernel feature maps based on Fourier transforms and count sketches.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +import scipy.sparse as sp +from scipy.fft import fft, ifft +from scipy.linalg import svd + +from .base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, +) +from .metrics.pairwise import KERNEL_PARAMS, PAIRWISE_KERNEL_FUNCTIONS, pairwise_kernels +from .utils import check_random_state +from .utils._param_validation import Interval, StrOptions +from .utils.extmath import safe_sparse_dot +from .utils.validation import ( + _check_feature_names_in, + check_is_fitted, + validate_data, +) + + +class PolynomialCountSketch( + ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator +): + """Polynomial kernel approximation via Tensor Sketch. + + Implements Tensor Sketch, which approximates the feature map + of the polynomial kernel:: + + K(X, Y) = (gamma * + coef0)^degree + + by efficiently computing a Count Sketch of the outer product of a + vector with itself using Fast Fourier Transforms (FFT). Read more in the + :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + gamma : float, default=1.0 + Parameter of the polynomial kernel whose feature map + will be approximated. + + degree : int, default=2 + Degree of the polynomial kernel whose feature map + will be approximated. + + coef0 : int, default=0 + Constant term of the polynomial kernel whose feature map + will be approximated. + + n_components : int, default=100 + Dimensionality of the output feature space. Usually, `n_components` + should be greater than the number of features in input samples in + order to achieve good performance. The optimal score / run time + balance is typically achieved around `n_components` = 10 * `n_features`, + but this depends on the specific dataset being used. + + random_state : int, RandomState instance, default=None + Determines random number generation for indexHash and bitHash + initialization. Pass an int for reproducible results across multiple + function calls. See :term:`Glossary `. + + Attributes + ---------- + indexHash_ : ndarray of shape (degree, n_features), dtype=int64 + Array of indexes in range [0, n_components) used to represent + the 2-wise independent hash functions for Count Sketch computation. + + bitHash_ : ndarray of shape (degree, n_features), dtype=float32 + Array with random entries in {+1, -1}, used to represent + the 2-wise independent hash functions for Count Sketch computation. + + 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 + -------- + AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel. + Nystroem : Approximate a kernel map using a subset of the training data. + RBFSampler : Approximate a RBF kernel feature map using random Fourier + features. + SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel. + sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels. + + Examples + -------- + >>> from sklearn.kernel_approximation import PolynomialCountSketch + >>> from sklearn.linear_model import SGDClassifier + >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]] + >>> y = [0, 0, 1, 1] + >>> ps = PolynomialCountSketch(degree=3, random_state=1) + >>> X_features = ps.fit_transform(X) + >>> clf = SGDClassifier(max_iter=10, tol=1e-3) + >>> clf.fit(X_features, y) + SGDClassifier(max_iter=10) + >>> clf.score(X_features, y) + 1.0 + + For a more detailed example of usage, see + :ref:`sphx_glr_auto_examples_kernel_approximation_plot_scalable_poly_kernels.py` + """ + + _parameter_constraints: dict = { + "gamma": [Interval(Real, 0, None, closed="left")], + "degree": [Interval(Integral, 1, None, closed="left")], + "coef0": [Interval(Real, None, None, closed="neither")], + "n_components": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + } + + def __init__( + self, *, gamma=1.0, degree=2, coef0=0, n_components=100, random_state=None + ): + self.gamma = gamma + self.degree = degree + self.coef0 = coef0 + self.n_components = n_components + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the model with X. + + Initializes the internal variables. The method needs no information + about the distribution of data, so we only care about n_features in 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 : array-like of shape (n_samples,) or (n_samples, n_outputs), \ + default=None + Target values (None for unsupervised transformations). + + Returns + ------- + self : object + Returns the instance itself. + """ + X = validate_data(self, X, accept_sparse="csc") + random_state = check_random_state(self.random_state) + + n_features = X.shape[1] + if self.coef0 != 0: + n_features += 1 + + self.indexHash_ = random_state.randint( + 0, high=self.n_components, size=(self.degree, n_features) + ) + + self.bitHash_ = random_state.choice(a=[-1, 1], size=(self.degree, n_features)) + self._n_features_out = self.n_components + return self + + def transform(self, X): + """Generate the feature map approximation for X. + + Parameters + ---------- + X : {array-like}, shape (n_samples, n_features) + New data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + Returns the instance itself. + """ + + check_is_fitted(self) + X = validate_data(self, X, accept_sparse="csc", reset=False) + + X_gamma = np.sqrt(self.gamma) * X + + if sp.issparse(X_gamma) and self.coef0 != 0: + X_gamma = sp.hstack( + [X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))], + format="csc", + ) + + elif not sp.issparse(X_gamma) and self.coef0 != 0: + X_gamma = np.hstack( + [X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))] + ) + + if X_gamma.shape[1] != self.indexHash_.shape[1]: + raise ValueError( + "Number of features of test samples does not" + " match that of training samples." + ) + + count_sketches = np.zeros((X_gamma.shape[0], self.degree, self.n_components)) + + if sp.issparse(X_gamma): + for j in range(X_gamma.shape[1]): + for d in range(self.degree): + iHashIndex = self.indexHash_[d, j] + iHashBit = self.bitHash_[d, j] + count_sketches[:, d, iHashIndex] += ( + (iHashBit * X_gamma[:, [j]]).toarray().ravel() + ) + + else: + for j in range(X_gamma.shape[1]): + for d in range(self.degree): + iHashIndex = self.indexHash_[d, j] + iHashBit = self.bitHash_[d, j] + count_sketches[:, d, iHashIndex] += iHashBit * X_gamma[:, j] + + # For each same, compute a count sketch of phi(x) using the polynomial + # multiplication (via FFT) of p count sketches of x. + count_sketches_fft = fft(count_sketches, axis=2, overwrite_x=True) + count_sketches_fft_prod = np.prod(count_sketches_fft, axis=1) + data_sketch = np.real(ifft(count_sketches_fft_prod, overwrite_x=True)) + + return data_sketch + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class RBFSampler(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + """Approximate a RBF kernel feature map using random Fourier features. + + It implements a variant of Random Kitchen Sinks.[1] + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + gamma : 'scale' or float, default=1.0 + Parameter of RBF kernel: exp(-gamma * x^2). + If ``gamma='scale'`` is passed then it uses + 1 / (n_features * X.var()) as value of gamma. + + .. versionadded:: 1.2 + The option `"scale"` was added in 1.2. + + n_components : int, default=100 + Number of Monte Carlo samples per original feature. + Equals the dimensionality of the computed feature space. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the generation of the random + weights and random offset when fitting the training data. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + random_offset_ : ndarray of shape (n_components,), dtype={np.float64, np.float32} + Random offset used to compute the projection in the `n_components` + dimensions of the feature space. + + random_weights_ : ndarray of shape (n_features, n_components),\ + dtype={np.float64, np.float32} + Random projection directions drawn from the Fourier transform + of the RBF kernel. + + 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 + -------- + AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel. + Nystroem : Approximate a kernel map using a subset of the training data. + PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch. + SkewedChi2Sampler : Approximate feature map for + "skewed chi-squared" kernel. + sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels. + + Notes + ----- + See "Random Features for Large-Scale Kernel Machines" by A. Rahimi and + Benjamin Recht. + + [1] "Weighted Sums of Random Kitchen Sinks: Replacing + minimization with randomization in learning" by A. Rahimi and + Benjamin Recht. + (https://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf) + + Examples + -------- + >>> from sklearn.kernel_approximation import RBFSampler + >>> from sklearn.linear_model import SGDClassifier + >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]] + >>> y = [0, 0, 1, 1] + >>> rbf_feature = RBFSampler(gamma=1, random_state=1) + >>> X_features = rbf_feature.fit_transform(X) + >>> clf = SGDClassifier(max_iter=5, tol=1e-3) + >>> clf.fit(X_features, y) + SGDClassifier(max_iter=5) + >>> clf.score(X_features, y) + 1.0 + """ + + _parameter_constraints: dict = { + "gamma": [ + StrOptions({"scale"}), + Interval(Real, 0.0, None, closed="left"), + ], + "n_components": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + } + + def __init__(self, *, gamma=1.0, n_components=100, random_state=None): + self.gamma = gamma + self.n_components = n_components + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the model with X. + + Samples random projection according to n_features. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like, shape (n_samples,) or (n_samples, n_outputs), \ + default=None + Target values (None for unsupervised transformations). + + Returns + ------- + self : object + Returns the instance itself. + """ + X = validate_data(self, X, accept_sparse="csr") + random_state = check_random_state(self.random_state) + n_features = X.shape[1] + sparse = sp.issparse(X) + if self.gamma == "scale": + # var = E[X^2] - E[X]^2 if sparse + X_var = (X.multiply(X)).mean() - (X.mean()) ** 2 if sparse else X.var() + self._gamma = 1.0 / (n_features * X_var) if X_var != 0 else 1.0 + else: + self._gamma = self.gamma + self.random_weights_ = (2.0 * self._gamma) ** 0.5 * random_state.normal( + size=(n_features, self.n_components) + ) + + self.random_offset_ = random_state.uniform(0, 2 * np.pi, size=self.n_components) + + if X.dtype == np.float32: + # Setting the data type of the fitted attribute will ensure the + # output data type during `transform`. + self.random_weights_ = self.random_weights_.astype(X.dtype, copy=False) + self.random_offset_ = self.random_offset_.astype(X.dtype, copy=False) + + self._n_features_out = self.n_components + return self + + def transform(self, X): + """Apply the approximate feature map to X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + New data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + Returns the instance itself. + """ + check_is_fitted(self) + + X = validate_data(self, X, accept_sparse="csr", reset=False) + projection = safe_sparse_dot(X, self.random_weights_) + projection += self.random_offset_ + np.cos(projection, projection) + projection *= (2.0 / self.n_components) ** 0.5 + return projection + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + return tags + + +class SkewedChi2Sampler( + ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator +): + """Approximate feature map for "skewed chi-squared" kernel. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + skewedness : float, default=1.0 + "skewedness" parameter of the kernel. Needs to be cross-validated. + + n_components : int, default=100 + Number of Monte Carlo samples per original feature. + Equals the dimensionality of the computed feature space. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the generation of the random + weights and random offset when fitting the training data. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + random_weights_ : ndarray of shape (n_features, n_components) + Weight array, sampled from a secant hyperbolic distribution, which will + be used to linearly transform the log of the data. + + random_offset_ : ndarray of shape (n_features, n_components) + Bias term, which will be added to the data. It is uniformly distributed + between 0 and 2*pi. + + 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 + -------- + AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel. + Nystroem : Approximate a kernel map using a subset of the training data. + RBFSampler : Approximate a RBF kernel feature map using random Fourier + features. + SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel. + sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel. + sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels. + + References + ---------- + See "Random Fourier Approximations for Skewed Multiplicative Histogram + Kernels" by Fuxin Li, Catalin Ionescu and Cristian Sminchisescu. + + Examples + -------- + >>> from sklearn.kernel_approximation import SkewedChi2Sampler + >>> from sklearn.linear_model import SGDClassifier + >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]] + >>> y = [0, 0, 1, 1] + >>> chi2_feature = SkewedChi2Sampler(skewedness=.01, + ... n_components=10, + ... random_state=0) + >>> X_features = chi2_feature.fit_transform(X, y) + >>> clf = SGDClassifier(max_iter=10, tol=1e-3) + >>> clf.fit(X_features, y) + SGDClassifier(max_iter=10) + >>> clf.score(X_features, y) + 1.0 + """ + + _parameter_constraints: dict = { + "skewedness": [Interval(Real, None, None, closed="neither")], + "n_components": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + } + + def __init__(self, *, skewedness=1.0, n_components=100, random_state=None): + self.skewedness = skewedness + self.n_components = n_components + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the model with X. + + Samples random projection according to n_features. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like, shape (n_samples,) or (n_samples, n_outputs), \ + default=None + Target values (None for unsupervised transformations). + + Returns + ------- + self : object + Returns the instance itself. + """ + X = validate_data(self, X) + random_state = check_random_state(self.random_state) + n_features = X.shape[1] + uniform = random_state.uniform(size=(n_features, self.n_components)) + # transform by inverse CDF of sech + self.random_weights_ = 1.0 / np.pi * np.log(np.tan(np.pi / 2.0 * uniform)) + self.random_offset_ = random_state.uniform(0, 2 * np.pi, size=self.n_components) + + if X.dtype == np.float32: + # Setting the data type of the fitted attribute will ensure the + # output data type during `transform`. + self.random_weights_ = self.random_weights_.astype(X.dtype, copy=False) + self.random_offset_ = self.random_offset_.astype(X.dtype, copy=False) + + self._n_features_out = self.n_components + return self + + def transform(self, X): + """Apply the approximate feature map to X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + New data, where `n_samples` is the number of samples + and `n_features` is the number of features. All values of X must be + strictly greater than "-skewedness". + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + Returns the instance itself. + """ + check_is_fitted(self) + X = validate_data( + self, X, copy=True, dtype=[np.float64, np.float32], reset=False + ) + if (X <= -self.skewedness).any(): + raise ValueError("X may not contain entries smaller than -skewedness.") + + X += self.skewedness + np.log(X, X) + projection = safe_sparse_dot(X, self.random_weights_) + projection += self.random_offset_ + np.cos(projection, projection) + projection *= np.sqrt(2.0) / np.sqrt(self.n_components) + return projection + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + return tags + + +class AdditiveChi2Sampler(TransformerMixin, BaseEstimator): + """Approximate feature map for additive chi2 kernel. + + Uses sampling the fourier transform of the kernel characteristic + at regular intervals. + + Since the kernel that is to be approximated is additive, the components of + the input vectors can be treated separately. Each entry in the original + space is transformed into 2*sample_steps-1 features, where sample_steps is + a parameter of the method. Typical values of sample_steps include 1, 2 and + 3. + + Optimal choices for the sampling interval for certain data ranges can be + computed (see the reference). The default values should be reasonable. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + sample_steps : int, default=2 + Gives the number of (complex) sampling points. + + sample_interval : float, default=None + Sampling interval. Must be specified when sample_steps not in {1,2,3}. + + Attributes + ---------- + 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 + -------- + SkewedChi2Sampler : A Fourier-approximation to a non-additive variant of + the chi squared kernel. + + sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel. + + sklearn.metrics.pairwise.additive_chi2_kernel : The exact additive chi + squared kernel. + + Notes + ----- + This estimator approximates a slightly different version of the additive + chi squared kernel then ``metric.additive_chi2`` computes. + + This estimator is stateless and does not need to be fitted. However, we + recommend to call :meth:`fit_transform` instead of :meth:`transform`, as + parameter validation is only performed in :meth:`fit`. + + References + ---------- + See `"Efficient additive kernels via explicit feature maps" + `_ + A. Vedaldi and A. Zisserman, Pattern Analysis and Machine Intelligence, + 2011 + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.linear_model import SGDClassifier + >>> from sklearn.kernel_approximation import AdditiveChi2Sampler + >>> X, y = load_digits(return_X_y=True) + >>> chi2sampler = AdditiveChi2Sampler(sample_steps=2) + >>> X_transformed = chi2sampler.fit_transform(X, y) + >>> clf = SGDClassifier(max_iter=5, random_state=0, tol=1e-3) + >>> clf.fit(X_transformed, y) + SGDClassifier(max_iter=5, random_state=0) + >>> clf.score(X_transformed, y) + 0.9499... + """ + + _parameter_constraints: dict = { + "sample_steps": [Interval(Integral, 1, None, closed="left")], + "sample_interval": [Interval(Real, 0, None, closed="left"), None], + } + + def __init__(self, *, sample_steps=2, sample_interval=None): + self.sample_steps = sample_steps + self.sample_interval = sample_interval + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Only validates estimator's parameters. + + This method allows to: (i) validate the estimator's parameters and + (ii) be consistent with the scikit-learn transformer API. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like, shape (n_samples,) or (n_samples, n_outputs), \ + default=None + Target values (None for unsupervised transformations). + + Returns + ------- + self : object + Returns the transformer. + """ + X = validate_data(self, X, accept_sparse="csr", ensure_non_negative=True) + + if self.sample_interval is None and self.sample_steps not in (1, 2, 3): + raise ValueError( + "If sample_steps is not in [1, 2, 3]," + " you need to provide sample_interval" + ) + + return self + + def transform(self, X): + """Apply approximate feature map to X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Returns + ------- + X_new : {ndarray, sparse matrix}, \ + shape = (n_samples, n_features * (2*sample_steps - 1)) + Whether the return value is an array or sparse matrix depends on + the type of the input X. + """ + X = validate_data( + self, X, accept_sparse="csr", reset=False, ensure_non_negative=True + ) + sparse = sp.issparse(X) + + if self.sample_interval is None: + # See figure 2 c) of "Efficient additive kernels via explicit feature maps" + # + # A. Vedaldi and A. Zisserman, Pattern Analysis and Machine Intelligence, + # 2011 + if self.sample_steps == 1: + sample_interval = 0.8 + elif self.sample_steps == 2: + sample_interval = 0.5 + elif self.sample_steps == 3: + sample_interval = 0.4 + else: + raise ValueError( + "If sample_steps is not in [1, 2, 3]," + " you need to provide sample_interval" + ) + else: + sample_interval = self.sample_interval + + # zeroth component + # 1/cosh = sech + # cosh(0) = 1.0 + transf = self._transform_sparse if sparse else self._transform_dense + return transf(X, self.sample_steps, sample_interval) + + 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 + Only used to validate feature names with the names seen in :meth:`fit`. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + # Note that passing attributes="n_features_in_" forces check_is_fitted + # to check if the attribute is present. Otherwise it will pass on this + # stateless estimator (requires_fit=False) + check_is_fitted(self, attributes="n_features_in_") + input_features = _check_feature_names_in( + self, input_features, generate_names=True + ) + est_name = self.__class__.__name__.lower() + + names_list = [f"{est_name}_{name}_sqrt" for name in input_features] + + for j in range(1, self.sample_steps): + cos_names = [f"{est_name}_{name}_cos{j}" for name in input_features] + sin_names = [f"{est_name}_{name}_sin{j}" for name in input_features] + names_list.extend(cos_names + sin_names) + + return np.asarray(names_list, dtype=object) + + @staticmethod + def _transform_dense(X, sample_steps, sample_interval): + non_zero = X != 0.0 + X_nz = X[non_zero] + + X_step = np.zeros_like(X) + X_step[non_zero] = np.sqrt(X_nz * sample_interval) + + X_new = [X_step] + + log_step_nz = sample_interval * np.log(X_nz) + step_nz = 2 * X_nz * sample_interval + + for j in range(1, sample_steps): + factor_nz = np.sqrt(step_nz / np.cosh(np.pi * j * sample_interval)) + + X_step = np.zeros_like(X) + X_step[non_zero] = factor_nz * np.cos(j * log_step_nz) + X_new.append(X_step) + + X_step = np.zeros_like(X) + X_step[non_zero] = factor_nz * np.sin(j * log_step_nz) + X_new.append(X_step) + + return np.hstack(X_new) + + @staticmethod + def _transform_sparse(X, sample_steps, sample_interval): + indices = X.indices.copy() + indptr = X.indptr.copy() + + data_step = np.sqrt(X.data * sample_interval) + X_step = sp.csr_matrix( + (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False + ) + X_new = [X_step] + + log_step_nz = sample_interval * np.log(X.data) + step_nz = 2 * X.data * sample_interval + + for j in range(1, sample_steps): + factor_nz = np.sqrt(step_nz / np.cosh(np.pi * j * sample_interval)) + + data_step = factor_nz * np.cos(j * log_step_nz) + X_step = sp.csr_matrix( + (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False + ) + X_new.append(X_step) + + data_step = factor_nz * np.sin(j * log_step_nz) + X_step = sp.csr_matrix( + (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False + ) + X_new.append(X_step) + + return sp.hstack(X_new) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.requires_fit = False + tags.input_tags.positive_only = True + tags.input_tags.sparse = True + return tags + + +class Nystroem(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + """Approximate a kernel map using a subset of the training data. + + Constructs an approximate feature map for an arbitrary kernel + using a subset of the data as basis. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.13 + + Parameters + ---------- + kernel : str or callable, default='rbf' + Kernel map to be approximated. A callable should accept two arguments + and the keyword arguments passed to this object as `kernel_params`, and + should return a floating point number. + + gamma : float, default=None + Gamma parameter for the RBF, laplacian, polynomial, exponential chi2 + and sigmoid kernels. Interpretation of the default value is left to + the kernel; see the documentation for sklearn.metrics.pairwise. + Ignored by other kernels. + + coef0 : float, default=None + Zero coefficient for polynomial and sigmoid kernels. + Ignored by other kernels. + + degree : float, default=None + Degree of the polynomial kernel. Ignored by other kernels. + + kernel_params : dict, default=None + Additional parameters (keyword arguments) for kernel function passed + as callable object. + + n_components : int, default=100 + Number of features to construct. + How many data points will be used to construct the mapping. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the uniform sampling without + replacement of `n_components` of the training data to construct the + basis kernel. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + n_jobs : int, default=None + The number of jobs to use for the computation. This works by breaking + down the kernel matrix into `n_jobs` even slices and computing them in + parallel. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 0.24 + + Attributes + ---------- + components_ : ndarray of shape (n_components, n_features) + Subset of training points used to construct the feature map. + + component_indices_ : ndarray of shape (n_components) + Indices of ``components_`` in the training set. + + normalization_ : ndarray of shape (n_components, n_components) + Normalization matrix needed for embedding. + Square root of the kernel matrix on ``components_``. + + 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 + -------- + AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel. + PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch. + RBFSampler : Approximate a RBF kernel feature map using random Fourier + features. + SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel. + sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels. + + References + ---------- + * Williams, C.K.I. and Seeger, M. + "Using the Nystroem method to speed up kernel machines", + Advances in neural information processing systems 2001 + + * T. Yang, Y. Li, M. Mahdavi, R. Jin and Z. Zhou + "Nystroem Method vs Random Fourier Features: A Theoretical and Empirical + Comparison", + Advances in Neural Information Processing Systems 2012 + + Examples + -------- + >>> from sklearn import datasets, svm + >>> from sklearn.kernel_approximation import Nystroem + >>> X, y = datasets.load_digits(n_class=9, return_X_y=True) + >>> data = X / 16. + >>> clf = svm.LinearSVC() + >>> feature_map_nystroem = Nystroem(gamma=.2, + ... random_state=1, + ... n_components=300) + >>> data_transformed = feature_map_nystroem.fit_transform(data) + >>> clf.fit(data_transformed, y) + LinearSVC() + >>> clf.score(data_transformed, y) + 0.9987... + """ + + _parameter_constraints: dict = { + "kernel": [ + StrOptions(set(PAIRWISE_KERNEL_FUNCTIONS.keys()) | {"precomputed"}), + callable, + ], + "gamma": [Interval(Real, 0, None, closed="left"), None], + "coef0": [Interval(Real, None, None, closed="neither"), None], + "degree": [Interval(Real, 1, None, closed="left"), None], + "kernel_params": [dict, None], + "n_components": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + "n_jobs": [Integral, None], + } + + def __init__( + self, + kernel="rbf", + *, + gamma=None, + coef0=None, + degree=None, + kernel_params=None, + n_components=100, + random_state=None, + n_jobs=None, + ): + self.kernel = kernel + self.gamma = gamma + self.coef0 = coef0 + self.degree = degree + self.kernel_params = kernel_params + self.n_components = n_components + self.random_state = random_state + self.n_jobs = n_jobs + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit estimator to data. + + Samples a subset of training points, computes kernel + on these and computes normalization matrix. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like, shape (n_samples,) or (n_samples, n_outputs), \ + default=None + Target values (None for unsupervised transformations). + + Returns + ------- + self : object + Returns the instance itself. + """ + X = validate_data(self, X, accept_sparse="csr") + rnd = check_random_state(self.random_state) + n_samples = X.shape[0] + + # get basis vectors + if self.n_components > n_samples: + # XXX should we just bail? + n_components = n_samples + warnings.warn( + "n_components > n_samples. This is not possible.\n" + "n_components was set to n_samples, which results" + " in inefficient evaluation of the full kernel." + ) + + else: + n_components = self.n_components + n_components = min(n_samples, n_components) + inds = rnd.permutation(n_samples) + basis_inds = inds[:n_components] + basis = X[basis_inds] + + basis_kernel = pairwise_kernels( + basis, + metric=self.kernel, + filter_params=True, + n_jobs=self.n_jobs, + **self._get_kernel_params(), + ) + + # sqrt of kernel matrix on basis vectors + U, S, V = svd(basis_kernel) + S = np.maximum(S, 1e-12) + self.normalization_ = np.dot(U / np.sqrt(S), V) + self.components_ = basis + self.component_indices_ = basis_inds + self._n_features_out = n_components + return self + + def transform(self, X): + """Apply feature map to X. + + Computes an approximate feature map using the kernel + between some training points and X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Data to transform. + + Returns + ------- + X_transformed : ndarray of shape (n_samples, n_components) + Transformed data. + """ + check_is_fitted(self) + X = validate_data(self, X, accept_sparse="csr", reset=False) + + kernel_params = self._get_kernel_params() + embedded = pairwise_kernels( + X, + self.components_, + metric=self.kernel, + filter_params=True, + n_jobs=self.n_jobs, + **kernel_params, + ) + return np.dot(embedded, self.normalization_.T) + + def _get_kernel_params(self): + params = self.kernel_params + if params is None: + params = {} + if not callable(self.kernel) and self.kernel != "precomputed": + for param in KERNEL_PARAMS[self.kernel]: + if getattr(self, param) is not None: + params[param] = getattr(self, param) + else: + if ( + self.gamma is not None + or self.coef0 is not None + or self.degree is not None + ): + raise ValueError( + "Don't pass gamma, coef0 or degree to " + "Nystroem if using a callable " + "or precomputed kernel" + ) + + return params + + 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/02/020417a134f7c95351600141013eb61c1a2efcaf411dfbad1ffd6554b906be69/frexp_cpu_dispatch.h b/shared/package-files/02/020417a134f7c95351600141013eb61c1a2efcaf411dfbad1ffd6554b906be69/frexp_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7e0e57c4b9968c165ef584bb37592a601954d882 --- /dev/null +++ b/shared/package-files/02/020417a134f7c95351600141013eb61c1a2efcaf411dfbad1ffd6554b906be69/frexp_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 ::std::tuple frexp_out(at::Tensor & mantissa, at::Tensor & exponent, const at::Tensor & self); +TORCH_API ::std::tuple frexp_outf(const at::Tensor & self, at::Tensor & mantissa, at::Tensor & exponent); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/02/020861c07567ff026c101068f931e6308293f73afe80126590b4dcb49ad3fde6/factortools.py b/shared/package-files/02/020861c07567ff026c101068f931e6308293f73afe80126590b4dcb49ad3fde6/factortools.py new file mode 100644 index 0000000000000000000000000000000000000000..de1821a89fa435a52c79787524ad7b5b8622c706 --- /dev/null +++ b/shared/package-files/02/020861c07567ff026c101068f931e6308293f73afe80126590b4dcb49ad3fde6/factortools.py @@ -0,0 +1,1502 @@ +"""Polynomial factorization routines in characteristic zero. """ + +from sympy.core.random import _randint + +from sympy.polys.galoistools import ( + gf_from_int_poly, gf_to_int_poly, + gf_lshift, gf_add_mul, gf_mul, + gf_div, gf_rem, + gf_gcdex, + gf_sqf_p, + gf_factor_sqf, gf_factor) + +from sympy.polys.densebasic import ( + dup_LC, dmp_LC, dmp_ground_LC, + dup_TC, + dup_convert, dmp_convert, + dup_degree, dmp_degree, + dmp_degree_in, dmp_degree_list, + dmp_from_dict, + dmp_zero_p, + dmp_one, + dmp_nest, dmp_raise, + dup_strip, + dmp_ground, + dup_inflate, + dmp_exclude, dmp_include, + dmp_inject, dmp_eject, + dup_terms_gcd, dmp_terms_gcd) + +from sympy.polys.densearith import ( + dup_neg, dmp_neg, + dup_add, dmp_add, + dup_sub, dmp_sub, + dup_mul, dmp_mul, + dup_sqr, + dmp_pow, + dup_div, dmp_div, + dup_quo, dmp_quo, + dmp_expand, + dmp_add_mul, + dup_sub_mul, dmp_sub_mul, + dup_lshift, + dup_max_norm, dmp_max_norm, + dup_l1_norm, + dup_mul_ground, dmp_mul_ground, + dup_quo_ground, dmp_quo_ground) + +from sympy.polys.densetools import ( + dup_clear_denoms, dmp_clear_denoms, + dup_trunc, dmp_ground_trunc, + dup_content, + dup_monic, dmp_ground_monic, + dup_primitive, dmp_ground_primitive, + dmp_eval_tail, + dmp_eval_in, dmp_diff_eval_in, + dmp_compose, + dup_shift, dup_mirror) + +from sympy.polys.euclidtools import ( + dmp_primitive, + dup_inner_gcd, dmp_inner_gcd) + +from sympy.polys.sqfreetools import ( + dup_sqf_p, + dup_sqf_norm, dmp_sqf_norm, + dup_sqf_part, dmp_sqf_part) + +from sympy.polys.polyutils import _sort_factors +from sympy.polys.polyconfig import query + +from sympy.polys.polyerrors import ( + ExtraneousFactors, DomainError, CoercionFailed, EvaluationFailed) + +from sympy.utilities import subsets + +from math import ceil as _ceil, log as _log + + +def dup_trial_division(f, factors, K): + """ + Determine multiplicities of factors for a univariate polynomial + using trial division. + """ + result = [] + + for factor in factors: + k = 0 + + while True: + q, r = dup_div(f, factor, K) + + if not r: + f, k = q, k + 1 + else: + break + + result.append((factor, k)) + + return _sort_factors(result) + + +def dmp_trial_division(f, factors, u, K): + """ + Determine multiplicities of factors for a multivariate polynomial + using trial division. + """ + result = [] + + for factor in factors: + k = 0 + + while True: + q, r = dmp_div(f, factor, u, K) + + if dmp_zero_p(r, u): + f, k = q, k + 1 + else: + break + + result.append((factor, k)) + + return _sort_factors(result) + + +def dup_zz_mignotte_bound(f, K): + """ + The Knuth-Cohen variant of Mignotte bound for + univariate polynomials in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> f = x**3 + 14*x**2 + 56*x + 64 + >>> R.dup_zz_mignotte_bound(f) + 152 + + By checking `factor(f)` we can see that max coeff is 8 + + Also consider a case that `f` is irreducible for example `f = 2*x**2 + 3*x + 4` + To avoid a bug for these cases, we return the bound plus the max coefficient of `f` + + >>> f = 2*x**2 + 3*x + 4 + >>> R.dup_zz_mignotte_bound(f) + 6 + + Lastly,To see the difference between the new and the old Mignotte bound + consider the irreducible polynomial:: + + >>> f = 87*x**7 + 4*x**6 + 80*x**5 + 17*x**4 + 9*x**3 + 12*x**2 + 49*x + 26 + >>> R.dup_zz_mignotte_bound(f) + 744 + + The new Mignotte bound is 744 whereas the old one (SymPy 1.5.1) is 1937664. + + + References + ========== + + ..[1] [Abbott2013]_ + + """ + from sympy.functions.combinatorial.factorials import binomial + d = dup_degree(f) + delta = _ceil(d / 2) + delta2 = _ceil(delta / 2) + + # euclidean-norm + eucl_norm = K.sqrt( sum( [cf**2 for cf in f] ) ) + + # biggest values of binomial coefficients (p. 538 of reference) + t1 = binomial(delta - 1, delta2) + t2 = binomial(delta - 1, delta2 - 1) + + lc = K.abs(dup_LC(f, K)) # leading coefficient + bound = t1 * eucl_norm + t2 * lc # (p. 538 of reference) + bound += dup_max_norm(f, K) # add max coeff for irreducible polys + bound = _ceil(bound / 2) * 2 # round up to even integer + + return bound + +def dmp_zz_mignotte_bound(f, u, K): + """Mignotte bound for multivariate polynomials in `K[X]`. """ + a = dmp_max_norm(f, u, K) + b = abs(dmp_ground_LC(f, u, K)) + n = sum(dmp_degree_list(f, u)) + + return K.sqrt(K(n + 1))*2**n*a*b + + +def dup_zz_hensel_step(m, f, g, h, s, t, K): + """ + One step in Hensel lifting in `Z[x]`. + + Given positive integer `m` and `Z[x]` polynomials `f`, `g`, `h`, `s` + and `t` such that:: + + f = g*h (mod m) + s*g + t*h = 1 (mod m) + + lc(f) is not a zero divisor (mod m) + lc(h) = 1 + + deg(f) = deg(g) + deg(h) + deg(s) < deg(h) + deg(t) < deg(g) + + returns polynomials `G`, `H`, `S` and `T`, such that:: + + f = G*H (mod m**2) + S*G + T*H = 1 (mod m**2) + + References + ========== + + .. [1] [Gathen99]_ + + """ + M = m**2 + + e = dup_sub_mul(f, g, h, K) + e = dup_trunc(e, M, K) + + q, r = dup_div(dup_mul(s, e, K), h, K) + + q = dup_trunc(q, M, K) + r = dup_trunc(r, M, K) + + u = dup_add(dup_mul(t, e, K), dup_mul(q, g, K), K) + G = dup_trunc(dup_add(g, u, K), M, K) + H = dup_trunc(dup_add(h, r, K), M, K) + + u = dup_add(dup_mul(s, G, K), dup_mul(t, H, K), K) + b = dup_trunc(dup_sub(u, [K.one], K), M, K) + + c, d = dup_div(dup_mul(s, b, K), H, K) + + c = dup_trunc(c, M, K) + d = dup_trunc(d, M, K) + + u = dup_add(dup_mul(t, b, K), dup_mul(c, G, K), K) + S = dup_trunc(dup_sub(s, d, K), M, K) + T = dup_trunc(dup_sub(t, u, K), M, K) + + return G, H, S, T + + +def dup_zz_hensel_lift(p, f, f_list, l, K): + r""" + Multifactor Hensel lifting in `Z[x]`. + + Given a prime `p`, polynomial `f` over `Z[x]` such that `lc(f)` + is a unit modulo `p`, monic pair-wise coprime polynomials `f_i` + over `Z[x]` satisfying:: + + f = lc(f) f_1 ... f_r (mod p) + + and a positive integer `l`, returns a list of monic polynomials + `F_1,\ F_2,\ \dots,\ F_r` satisfying:: + + f = lc(f) F_1 ... F_r (mod p**l) + + F_i = f_i (mod p), i = 1..r + + References + ========== + + .. [1] [Gathen99]_ + + """ + r = len(f_list) + lc = dup_LC(f, K) + + if r == 1: + F = dup_mul_ground(f, K.gcdex(lc, p**l)[0], K) + return [ dup_trunc(F, p**l, K) ] + + m = p + k = r // 2 + d = int(_ceil(_log(l, 2))) + + g = gf_from_int_poly([lc], p) + + for f_i in f_list[:k]: + g = gf_mul(g, gf_from_int_poly(f_i, p), p, K) + + h = gf_from_int_poly(f_list[k], p) + + for f_i in f_list[k + 1:]: + h = gf_mul(h, gf_from_int_poly(f_i, p), p, K) + + s, t, _ = gf_gcdex(g, h, p, K) + + g = gf_to_int_poly(g, p) + h = gf_to_int_poly(h, p) + s = gf_to_int_poly(s, p) + t = gf_to_int_poly(t, p) + + for _ in range(1, d + 1): + (g, h, s, t), m = dup_zz_hensel_step(m, f, g, h, s, t, K), m**2 + + return dup_zz_hensel_lift(p, g, f_list[:k], l, K) \ + + dup_zz_hensel_lift(p, h, f_list[k:], l, K) + +def _test_pl(fc, q, pl): + if q > pl // 2: + q = q - pl + if not q: + return True + return fc % q == 0 + +def dup_zz_zassenhaus(f, K): + """Factor primitive square-free polynomials in `Z[x]`. """ + n = dup_degree(f) + + if n == 1: + return [f] + + from sympy.ntheory import isprime + + fc = f[-1] + A = dup_max_norm(f, K) + b = dup_LC(f, K) + B = int(abs(K.sqrt(K(n + 1))*2**n*A*b)) + C = int((n + 1)**(2*n)*A**(2*n - 1)) + gamma = int(_ceil(2*_log(C, 2))) + bound = int(2*gamma*_log(gamma)) + a = [] + # choose a prime number `p` such that `f` be square free in Z_p + # if there are many factors in Z_p, choose among a few different `p` + # the one with fewer factors + for px in range(3, bound + 1): + if not isprime(px) or b % px == 0: + continue + + px = K.convert(px) + + F = gf_from_int_poly(f, px) + + if not gf_sqf_p(F, px, K): + continue + fsqfx = gf_factor_sqf(F, px, K)[1] + a.append((px, fsqfx)) + if len(fsqfx) < 15 or len(a) > 4: + break + p, fsqf = min(a, key=lambda x: len(x[1])) + + l = int(_ceil(_log(2*B + 1, p))) + + modular = [gf_to_int_poly(ff, p) for ff in fsqf] + + g = dup_zz_hensel_lift(p, f, modular, l, K) + + sorted_T = range(len(g)) + T = set(sorted_T) + factors, s = [], 1 + pl = p**l + + while 2*s <= len(T): + for S in subsets(sorted_T, s): + # lift the constant coefficient of the product `G` of the factors + # in the subset `S`; if it is does not divide `fc`, `G` does + # not divide the input polynomial + + if b == 1: + q = 1 + for i in S: + q = q*g[i][-1] + q = q % pl + if not _test_pl(fc, q, pl): + continue + else: + G = [b] + for i in S: + G = dup_mul(G, g[i], K) + G = dup_trunc(G, pl, K) + G = dup_primitive(G, K)[1] + q = G[-1] + if q and fc % q != 0: + continue + + H = [b] + S = set(S) + T_S = T - S + + if b == 1: + G = [b] + for i in S: + G = dup_mul(G, g[i], K) + G = dup_trunc(G, pl, K) + + for i in T_S: + H = dup_mul(H, g[i], K) + + H = dup_trunc(H, pl, K) + + G_norm = dup_l1_norm(G, K) + H_norm = dup_l1_norm(H, K) + + if G_norm*H_norm <= B: + T = T_S + sorted_T = [i for i in sorted_T if i not in S] + + G = dup_primitive(G, K)[1] + f = dup_primitive(H, K)[1] + + factors.append(G) + b = dup_LC(f, K) + + break + else: + s += 1 + + return factors + [f] + + +def dup_zz_irreducible_p(f, K): + """Test irreducibility using Eisenstein's criterion. """ + lc = dup_LC(f, K) + tc = dup_TC(f, K) + + e_fc = dup_content(f[1:], K) + + if e_fc: + from sympy.ntheory import factorint + e_ff = factorint(int(e_fc)) + + for p in e_ff.keys(): + if (lc % p) and (tc % p**2): + return True + + +def dup_cyclotomic_p(f, K, irreducible=False): + """ + Efficiently test if ``f`` is a cyclotomic polynomial. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 + >>> R.dup_cyclotomic_p(f) + False + + >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 + >>> R.dup_cyclotomic_p(g) + True + + References + ========== + + Bradford, Russell J., and James H. Davenport. "Effective tests for + cyclotomic polynomials." In International Symposium on Symbolic and + Algebraic Computation, pp. 244-251. Springer, Berlin, Heidelberg, 1988. + + """ + if K.is_QQ: + try: + K0, K = K, K.get_ring() + f = dup_convert(f, K0, K) + except CoercionFailed: + return False + elif not K.is_ZZ: + return False + + lc = dup_LC(f, K) + tc = dup_TC(f, K) + + if lc != 1 or (tc != -1 and tc != 1): + return False + + if not irreducible: + coeff, factors = dup_factor_list(f, K) + + if coeff != K.one or factors != [(f, 1)]: + return False + + n = dup_degree(f) + g, h = [], [] + + for i in range(n, -1, -2): + g.insert(0, f[i]) + + for i in range(n - 1, -1, -2): + h.insert(0, f[i]) + + g = dup_sqr(dup_strip(g), K) + h = dup_sqr(dup_strip(h), K) + + F = dup_sub(g, dup_lshift(h, 1, K), K) + + if K.is_negative(dup_LC(F, K)): + F = dup_neg(F, K) + + if F == f: + return True + + g = dup_mirror(f, K) + + if K.is_negative(dup_LC(g, K)): + g = dup_neg(g, K) + + if F == g and dup_cyclotomic_p(g, K): + return True + + G = dup_sqf_part(F, K) + + if dup_sqr(G, K) == F and dup_cyclotomic_p(G, K): + return True + + return False + + +def dup_zz_cyclotomic_poly(n, K): + """Efficiently generate n-th cyclotomic polynomial. """ + from sympy.ntheory import factorint + h = [K.one, -K.one] + + for p, k in factorint(n).items(): + h = dup_quo(dup_inflate(h, p, K), h, K) + h = dup_inflate(h, p**(k - 1), K) + + return h + + +def _dup_cyclotomic_decompose(n, K): + from sympy.ntheory import factorint + + H = [[K.one, -K.one]] + + for p, k in factorint(n).items(): + Q = [ dup_quo(dup_inflate(h, p, K), h, K) for h in H ] + H.extend(Q) + + for i in range(1, k): + Q = [ dup_inflate(q, p, K) for q in Q ] + H.extend(Q) + + return H + + +def dup_zz_cyclotomic_factor(f, K): + """ + Efficiently factor polynomials `x**n - 1` and `x**n + 1` in `Z[x]`. + + Given a univariate polynomial `f` in `Z[x]` returns a list of factors + of `f`, provided that `f` is in the form `x**n - 1` or `x**n + 1` for + `n >= 1`. Otherwise returns None. + + Factorization is performed using cyclotomic decomposition of `f`, + which makes this method much faster that any other direct factorization + approach (e.g. Zassenhaus's). + + References + ========== + + .. [1] [Weisstein09]_ + + """ + lc_f, tc_f = dup_LC(f, K), dup_TC(f, K) + + if dup_degree(f) <= 0: + return None + + if lc_f != 1 or tc_f not in [-1, 1]: + return None + + if any(bool(cf) for cf in f[1:-1]): + return None + + n = dup_degree(f) + F = _dup_cyclotomic_decompose(n, K) + + if not K.is_one(tc_f): + return F + else: + H = [] + + for h in _dup_cyclotomic_decompose(2*n, K): + if h not in F: + H.append(h) + + return H + + +def dup_zz_factor_sqf(f, K): + """Factor square-free (non-primitive) polynomials in `Z[x]`. """ + cont, g = dup_primitive(f, K) + + n = dup_degree(g) + + if dup_LC(g, K) < 0: + cont, g = -cont, dup_neg(g, K) + + if n <= 0: + return cont, [] + elif n == 1: + return cont, [g] + + if query('USE_IRREDUCIBLE_IN_FACTOR'): + if dup_zz_irreducible_p(g, K): + return cont, [g] + + factors = None + + if query('USE_CYCLOTOMIC_FACTOR'): + factors = dup_zz_cyclotomic_factor(g, K) + + if factors is None: + factors = dup_zz_zassenhaus(g, K) + + return cont, _sort_factors(factors, multiple=False) + + +def dup_zz_factor(f, K): + """ + Factor (non square-free) polynomials in `Z[x]`. + + Given a univariate polynomial `f` in `Z[x]` computes its complete + factorization `f_1, ..., f_n` into irreducibles over integers:: + + f = content(f) f_1**k_1 ... f_n**k_n + + The factorization is computed by reducing the input polynomial + into a primitive square-free polynomial and factoring it using + Zassenhaus algorithm. Trial division is used to recover the + multiplicities of factors. + + The result is returned as a tuple consisting of:: + + (content(f), [(f_1, k_1), ..., (f_n, k_n)) + + Examples + ======== + + Consider the polynomial `f = 2*x**4 - 2`:: + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_zz_factor(2*x**4 - 2) + (2, [(x - 1, 1), (x + 1, 1), (x**2 + 1, 1)]) + + In result we got the following factorization:: + + f = 2 (x - 1) (x + 1) (x**2 + 1) + + Note that this is a complete factorization over integers, + however over Gaussian integers we can factor the last term. + + By default, polynomials `x**n - 1` and `x**n + 1` are factored + using cyclotomic decomposition to speedup computations. To + disable this behaviour set cyclotomic=False. + + References + ========== + + .. [1] [Gathen99]_ + + """ + cont, g = dup_primitive(f, K) + + n = dup_degree(g) + + if dup_LC(g, K) < 0: + cont, g = -cont, dup_neg(g, K) + + if n <= 0: + return cont, [] + elif n == 1: + return cont, [(g, 1)] + + if query('USE_IRREDUCIBLE_IN_FACTOR'): + if dup_zz_irreducible_p(g, K): + return cont, [(g, 1)] + + g = dup_sqf_part(g, K) + H = None + + if query('USE_CYCLOTOMIC_FACTOR'): + H = dup_zz_cyclotomic_factor(g, K) + + if H is None: + H = dup_zz_zassenhaus(g, K) + + factors = dup_trial_division(f, H, K) + return cont, factors + + +def dmp_zz_wang_non_divisors(E, cs, ct, K): + """Wang/EEZ: Compute a set of valid divisors. """ + result = [ cs*ct ] + + for q in E: + q = abs(q) + + for r in reversed(result): + while r != 1: + r = K.gcd(r, q) + q = q // r + + if K.is_one(q): + return None + + result.append(q) + + return result[1:] + + +def dmp_zz_wang_test_points(f, T, ct, A, u, K): + """Wang/EEZ: Test evaluation points for suitability. """ + if not dmp_eval_tail(dmp_LC(f, K), A, u - 1, K): + raise EvaluationFailed('no luck') + + g = dmp_eval_tail(f, A, u, K) + + if not dup_sqf_p(g, K): + raise EvaluationFailed('no luck') + + c, h = dup_primitive(g, K) + + if K.is_negative(dup_LC(h, K)): + c, h = -c, dup_neg(h, K) + + v = u - 1 + + E = [ dmp_eval_tail(t, A, v, K) for t, _ in T ] + D = dmp_zz_wang_non_divisors(E, c, ct, K) + + if D is not None: + return c, h, E + else: + raise EvaluationFailed('no luck') + + +def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K): + """Wang/EEZ: Compute correct leading coefficients. """ + C, J, v = [], [0]*len(E), u - 1 + + for h in H: + c = dmp_one(v, K) + d = dup_LC(h, K)*cs + + for i in reversed(range(len(E))): + k, e, (t, _) = 0, E[i], T[i] + + while not (d % e): + d, k = d//e, k + 1 + + if k != 0: + c, J[i] = dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1 + + C.append(c) + + if not all(J): + raise ExtraneousFactors # pragma: no cover + + CC, HH = [], [] + + for c, h in zip(C, H): + d = dmp_eval_tail(c, A, v, K) + lc = dup_LC(h, K) + + if K.is_one(cs): + cc = lc//d + else: + g = K.gcd(lc, d) + d, cc = d//g, lc//g + h, cs = dup_mul_ground(h, d, K), cs//d + + c = dmp_mul_ground(c, cc, v, K) + + CC.append(c) + HH.append(h) + + if K.is_one(cs): + return f, HH, CC + + CCC, HHH = [], [] + + for c, h in zip(CC, HH): + CCC.append(dmp_mul_ground(c, cs, v, K)) + HHH.append(dmp_mul_ground(h, cs, 0, K)) + + f = dmp_mul_ground(f, cs**(len(H) - 1), u, K) + + return f, HHH, CCC + + +def dup_zz_diophantine(F, m, p, K): + """Wang/EEZ: Solve univariate Diophantine equations. """ + if len(F) == 2: + a, b = F + + f = gf_from_int_poly(a, p) + g = gf_from_int_poly(b, p) + + s, t, G = gf_gcdex(g, f, p, K) + + s = gf_lshift(s, m, K) + t = gf_lshift(t, m, K) + + q, s = gf_div(s, f, p, K) + + t = gf_add_mul(t, q, g, p, K) + + s = gf_to_int_poly(s, p) + t = gf_to_int_poly(t, p) + + result = [s, t] + else: + G = [F[-1]] + + for f in reversed(F[1:-1]): + G.insert(0, dup_mul(f, G[0], K)) + + S, T = [], [[1]] + + for f, g in zip(F, G): + t, s = dmp_zz_diophantine([g, f], T[-1], [], 0, p, 1, K) + T.append(t) + S.append(s) + + result, S = [], S + [T[-1]] + + for s, f in zip(S, F): + s = gf_from_int_poly(s, p) + f = gf_from_int_poly(f, p) + + r = gf_rem(gf_lshift(s, m, K), f, p, K) + s = gf_to_int_poly(r, p) + + result.append(s) + + return result + + +def dmp_zz_diophantine(F, c, A, d, p, u, K): + """Wang/EEZ: Solve multivariate Diophantine equations. """ + if not A: + S = [ [] for _ in F ] + n = dup_degree(c) + + for i, coeff in enumerate(c): + if not coeff: + continue + + T = dup_zz_diophantine(F, n - i, p, K) + + for j, (s, t) in enumerate(zip(S, T)): + t = dup_mul_ground(t, coeff, K) + S[j] = dup_trunc(dup_add(s, t, K), p, K) + else: + n = len(A) + e = dmp_expand(F, u, K) + + a, A = A[-1], A[:-1] + B, G = [], [] + + for f in F: + B.append(dmp_quo(e, f, u, K)) + G.append(dmp_eval_in(f, a, n, u, K)) + + C = dmp_eval_in(c, a, n, u, K) + + v = u - 1 + + S = dmp_zz_diophantine(G, C, A, d, p, v, K) + S = [ dmp_raise(s, 1, v, K) for s in S ] + + for s, b in zip(S, B): + c = dmp_sub_mul(c, s, b, u, K) + + c = dmp_ground_trunc(c, p, u, K) + + m = dmp_nest([K.one, -a], n, K) + M = dmp_one(n, K) + + for k in K.map(range(0, d)): + if dmp_zero_p(c, u): + break + + M = dmp_mul(M, m, u, K) + C = dmp_diff_eval_in(c, k + 1, a, n, u, K) + + if not dmp_zero_p(C, v): + C = dmp_quo_ground(C, K.factorial(k + 1), v, K) + T = dmp_zz_diophantine(G, C, A, d, p, v, K) + + for i, t in enumerate(T): + T[i] = dmp_mul(dmp_raise(t, 1, v, K), M, u, K) + + for i, (s, t) in enumerate(zip(S, T)): + S[i] = dmp_add(s, t, u, K) + + for t, b in zip(T, B): + c = dmp_sub_mul(c, t, b, u, K) + + c = dmp_ground_trunc(c, p, u, K) + + S = [ dmp_ground_trunc(s, p, u, K) for s in S ] + + return S + + +def dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K): + """Wang/EEZ: Parallel Hensel lifting algorithm. """ + S, n, v = [f], len(A), u - 1 + + H = list(H) + + for i, a in enumerate(reversed(A[1:])): + s = dmp_eval_in(S[0], a, n - i, u - i, K) + S.insert(0, dmp_ground_trunc(s, p, v - i, K)) + + d = max(dmp_degree_list(f, u)[1:]) + + for j, s, a in zip(range(2, n + 2), S, A): + G, w = list(H), j - 1 + + I, J = A[:j - 2], A[j - 1:] + + for i, (h, lc) in enumerate(zip(H, LC)): + lc = dmp_ground_trunc(dmp_eval_tail(lc, J, v, K), p, w - 1, K) + H[i] = [lc] + dmp_raise(h[1:], 1, w - 1, K) + + m = dmp_nest([K.one, -a], w, K) + M = dmp_one(w, K) + + c = dmp_sub(s, dmp_expand(H, w, K), w, K) + + dj = dmp_degree_in(s, w, w) + + for k in K.map(range(0, dj)): + if dmp_zero_p(c, w): + break + + M = dmp_mul(M, m, w, K) + C = dmp_diff_eval_in(c, k + 1, a, w, w, K) + + if not dmp_zero_p(C, w - 1): + C = dmp_quo_ground(C, K.factorial(k + 1), w - 1, K) + T = dmp_zz_diophantine(G, C, I, d, p, w - 1, K) + + for i, (h, t) in enumerate(zip(H, T)): + h = dmp_add_mul(h, dmp_raise(t, 1, w - 1, K), M, w, K) + H[i] = dmp_ground_trunc(h, p, w, K) + + h = dmp_sub(s, dmp_expand(H, w, K), w, K) + c = dmp_ground_trunc(h, p, w, K) + + if dmp_expand(H, u, K) != f: + raise ExtraneousFactors # pragma: no cover + else: + return H + + +def dmp_zz_wang(f, u, K, mod=None, seed=None): + r""" + Factor primitive square-free polynomials in `Z[X]`. + + Given a multivariate polynomial `f` in `Z[x_1,...,x_n]`, which is + primitive and square-free in `x_1`, computes factorization of `f` into + irreducibles over integers. + + The procedure is based on Wang's Enhanced Extended Zassenhaus + algorithm. The algorithm works by viewing `f` as a univariate polynomial + in `Z[x_2,...,x_n][x_1]`, for which an evaluation mapping is computed:: + + x_2 -> a_2, ..., x_n -> a_n + + where `a_i`, for `i = 2, \dots, n`, are carefully chosen integers. The + mapping is used to transform `f` into a univariate polynomial in `Z[x_1]`, + which can be factored efficiently using Zassenhaus algorithm. The last + step is to lift univariate factors to obtain true multivariate + factors. For this purpose a parallel Hensel lifting procedure is used. + + The parameter ``seed`` is passed to _randint and can be used to seed randint + (when an integer) or (for testing purposes) can be a sequence of numbers. + + References + ========== + + .. [1] [Wang78]_ + .. [2] [Geddes92]_ + + """ + from sympy.ntheory import nextprime + + randint = _randint(seed) + + ct, T = dmp_zz_factor(dmp_LC(f, K), u - 1, K) + + b = dmp_zz_mignotte_bound(f, u, K) + p = K(nextprime(b)) + + if mod is None: + if u == 1: + mod = 2 + else: + mod = 1 + + history, configs, A, r = set(), [], [K.zero]*u, None + + try: + cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K) + + _, H = dup_zz_factor_sqf(s, K) + + r = len(H) + + if r == 1: + return [f] + + configs = [(s, cs, E, H, A)] + except EvaluationFailed: + pass + + eez_num_configs = query('EEZ_NUMBER_OF_CONFIGS') + eez_num_tries = query('EEZ_NUMBER_OF_TRIES') + eez_mod_step = query('EEZ_MODULUS_STEP') + + while len(configs) < eez_num_configs: + for _ in range(eez_num_tries): + A = [ K(randint(-mod, mod)) for _ in range(u) ] + + if tuple(A) not in history: + history.add(tuple(A)) + else: + continue + + try: + cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K) + except EvaluationFailed: + continue + + _, H = dup_zz_factor_sqf(s, K) + + rr = len(H) + + if r is not None: + if rr != r: # pragma: no cover + if rr < r: + configs, r = [], rr + else: + continue + else: + r = rr + + if r == 1: + return [f] + + configs.append((s, cs, E, H, A)) + + if len(configs) == eez_num_configs: + break + else: + mod += eez_mod_step + + s_norm, s_arg, i = None, 0, 0 + + for s, _, _, _, _ in configs: + _s_norm = dup_max_norm(s, K) + + if s_norm is not None: + if _s_norm < s_norm: + s_norm = _s_norm + s_arg = i + else: + s_norm = _s_norm + + i += 1 + + _, cs, E, H, A = configs[s_arg] + orig_f = f + + try: + f, H, LC = dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K) + factors = dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K) + except ExtraneousFactors: # pragma: no cover + if query('EEZ_RESTART_IF_NEEDED'): + return dmp_zz_wang(orig_f, u, K, mod + 1) + else: + raise ExtraneousFactors( + "we need to restart algorithm with better parameters") + + result = [] + + for f in factors: + _, f = dmp_ground_primitive(f, u, K) + + if K.is_negative(dmp_ground_LC(f, u, K)): + f = dmp_neg(f, u, K) + + result.append(f) + + return result + + +def dmp_zz_factor(f, u, K): + r""" + Factor (non square-free) polynomials in `Z[X]`. + + Given a multivariate polynomial `f` in `Z[x]` computes its complete + factorization `f_1, \dots, f_n` into irreducibles over integers:: + + f = content(f) f_1**k_1 ... f_n**k_n + + The factorization is computed by reducing the input polynomial + into a primitive square-free polynomial and factoring it using + Enhanced Extended Zassenhaus (EEZ) algorithm. Trial division + is used to recover the multiplicities of factors. + + The result is returned as a tuple consisting of:: + + (content(f), [(f_1, k_1), ..., (f_n, k_n)) + + Consider polynomial `f = 2*(x**2 - y**2)`:: + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_zz_factor(2*x**2 - 2*y**2) + (2, [(x - y, 1), (x + y, 1)]) + + In result we got the following factorization:: + + f = 2 (x - y) (x + y) + + References + ========== + + .. [1] [Gathen99]_ + + """ + if not u: + return dup_zz_factor(f, K) + + if dmp_zero_p(f, u): + return K.zero, [] + + cont, g = dmp_ground_primitive(f, u, K) + + if dmp_ground_LC(g, u, K) < 0: + cont, g = -cont, dmp_neg(g, u, K) + + if all(d <= 0 for d in dmp_degree_list(g, u)): + return cont, [] + + G, g = dmp_primitive(g, u, K) + + factors = [] + + if dmp_degree(g, u) > 0: + g = dmp_sqf_part(g, u, K) + H = dmp_zz_wang(g, u, K) + factors = dmp_trial_division(f, H, u, K) + + for g, k in dmp_zz_factor(G, u - 1, K)[1]: + factors.insert(0, ([g], k)) + + return cont, _sort_factors(factors) + + +def dup_qq_i_factor(f, K0): + """Factor univariate polynomials into irreducibles in `QQ_I[x]`. """ + # Factor in QQ + K1 = K0.as_AlgebraicField() + f = dup_convert(f, K0, K1) + coeff, factors = dup_factor_list(f, K1) + factors = [(dup_convert(fac, K1, K0), i) for fac, i in factors] + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dup_zz_i_factor(f, K0): + """Factor univariate polynomials into irreducibles in `ZZ_I[x]`. """ + # First factor in QQ_I + K1 = K0.get_field() + f = dup_convert(f, K0, K1) + coeff, factors = dup_qq_i_factor(f, K1) + + new_factors = [] + for fac, i in factors: + # Extract content + fac_denom, fac_num = dup_clear_denoms(fac, K1) + fac_num_ZZ_I = dup_convert(fac_num, K1, K0) + content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, 0, K1) + + coeff = (coeff * content ** i) // fac_denom ** i + new_factors.append((fac_prim, i)) + + factors = new_factors + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dmp_qq_i_factor(f, u, K0): + """Factor multivariate polynomials into irreducibles in `QQ_I[X]`. """ + # Factor in QQ + K1 = K0.as_AlgebraicField() + f = dmp_convert(f, u, K0, K1) + coeff, factors = dmp_factor_list(f, u, K1) + factors = [(dmp_convert(fac, u, K1, K0), i) for fac, i in factors] + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dmp_zz_i_factor(f, u, K0): + """Factor multivariate polynomials into irreducibles in `ZZ_I[X]`. """ + # First factor in QQ_I + K1 = K0.get_field() + f = dmp_convert(f, u, K0, K1) + coeff, factors = dmp_qq_i_factor(f, u, K1) + + new_factors = [] + for fac, i in factors: + # Extract content + fac_denom, fac_num = dmp_clear_denoms(fac, u, K1) + fac_num_ZZ_I = dmp_convert(fac_num, u, K1, K0) + content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, u, K1) + + coeff = (coeff * content ** i) // fac_denom ** i + new_factors.append((fac_prim, i)) + + factors = new_factors + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dup_ext_factor(f, K): + """Factor univariate polynomials over algebraic number fields. """ + n, lc = dup_degree(f), dup_LC(f, K) + + f = dup_monic(f, K) + + if n <= 0: + return lc, [] + if n == 1: + return lc, [(f, 1)] + + f, F = dup_sqf_part(f, K), f + s, g, r = dup_sqf_norm(f, K) + + factors = dup_factor_list_include(r, K.dom) + + if len(factors) == 1: + return lc, [(f, n//dup_degree(f))] + + H = s*K.unit + + for i, (factor, _) in enumerate(factors): + h = dup_convert(factor, K.dom, K) + h, _, g = dup_inner_gcd(h, g, K) + h = dup_shift(h, H, K) + factors[i] = h + + factors = dup_trial_division(F, factors, K) + return lc, factors + + +def dmp_ext_factor(f, u, K): + """Factor multivariate polynomials over algebraic number fields. """ + if not u: + return dup_ext_factor(f, K) + + lc = dmp_ground_LC(f, u, K) + f = dmp_ground_monic(f, u, K) + + if all(d <= 0 for d in dmp_degree_list(f, u)): + return lc, [] + + f, F = dmp_sqf_part(f, u, K), f + s, g, r = dmp_sqf_norm(f, u, K) + + factors = dmp_factor_list_include(r, u, K.dom) + + if len(factors) == 1: + factors = [f] + else: + H = dmp_raise([K.one, s*K.unit], u, 0, K) + + for i, (factor, _) in enumerate(factors): + h = dmp_convert(factor, u, K.dom, K) + h, _, g = dmp_inner_gcd(h, g, u, K) + h = dmp_compose(h, H, u, K) + factors[i] = h + + return lc, dmp_trial_division(F, factors, u, K) + + +def dup_gf_factor(f, K): + """Factor univariate polynomials over finite fields. """ + f = dup_convert(f, K, K.dom) + + coeff, factors = gf_factor(f, K.mod, K.dom) + + for i, (f, k) in enumerate(factors): + factors[i] = (dup_convert(f, K.dom, K), k) + + return K.convert(coeff, K.dom), factors + + +def dmp_gf_factor(f, u, K): + """Factor multivariate polynomials over finite fields. """ + raise NotImplementedError('multivariate polynomials over finite fields') + + +def dup_factor_list(f, K0): + """Factor univariate polynomials into irreducibles in `K[x]`. """ + j, f = dup_terms_gcd(f, K0) + cont, f = dup_primitive(f, K0) + + if K0.is_FiniteField: + coeff, factors = dup_gf_factor(f, K0) + elif K0.is_Algebraic: + coeff, factors = dup_ext_factor(f, K0) + elif K0.is_GaussianRing: + coeff, factors = dup_zz_i_factor(f, K0) + elif K0.is_GaussianField: + coeff, factors = dup_qq_i_factor(f, K0) + else: + if not K0.is_Exact: + K0_inexact, K0 = K0, K0.get_exact() + f = dup_convert(f, K0_inexact, K0) + else: + K0_inexact = None + + if K0.is_Field: + K = K0.get_ring() + + denom, f = dup_clear_denoms(f, K0, K) + f = dup_convert(f, K0, K) + else: + K = K0 + + if K.is_ZZ: + coeff, factors = dup_zz_factor(f, K) + elif K.is_Poly: + f, u = dmp_inject(f, 0, K) + + coeff, factors = dmp_factor_list(f, u, K.dom) + + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_eject(f, u, K), k) + + coeff = K.convert(coeff, K.dom) + else: # pragma: no cover + raise DomainError('factorization not supported over %s' % K0) + + if K0.is_Field: + for i, (f, k) in enumerate(factors): + factors[i] = (dup_convert(f, K, K0), k) + + coeff = K0.convert(coeff, K) + coeff = K0.quo(coeff, denom) + + if K0_inexact: + for i, (f, k) in enumerate(factors): + max_norm = dup_max_norm(f, K0) + f = dup_quo_ground(f, max_norm, K0) + f = dup_convert(f, K0, K0_inexact) + factors[i] = (f, k) + coeff = K0.mul(coeff, K0.pow(max_norm, k)) + + coeff = K0_inexact.convert(coeff, K0) + K0 = K0_inexact + + if j: + factors.insert(0, ([K0.one, K0.zero], j)) + + return coeff*cont, _sort_factors(factors) + + +def dup_factor_list_include(f, K): + """Factor univariate polynomials into irreducibles in `K[x]`. """ + coeff, factors = dup_factor_list(f, K) + + if not factors: + return [(dup_strip([coeff]), 1)] + else: + g = dup_mul_ground(factors[0][0], coeff, K) + return [(g, factors[0][1])] + factors[1:] + + +def dmp_factor_list(f, u, K0): + """Factor multivariate polynomials into irreducibles in `K[X]`. """ + if not u: + return dup_factor_list(f, K0) + + J, f = dmp_terms_gcd(f, u, K0) + cont, f = dmp_ground_primitive(f, u, K0) + + if K0.is_FiniteField: # pragma: no cover + coeff, factors = dmp_gf_factor(f, u, K0) + elif K0.is_Algebraic: + coeff, factors = dmp_ext_factor(f, u, K0) + elif K0.is_GaussianRing: + coeff, factors = dmp_zz_i_factor(f, u, K0) + elif K0.is_GaussianField: + coeff, factors = dmp_qq_i_factor(f, u, K0) + else: + if not K0.is_Exact: + K0_inexact, K0 = K0, K0.get_exact() + f = dmp_convert(f, u, K0_inexact, K0) + else: + K0_inexact = None + + if K0.is_Field: + K = K0.get_ring() + + denom, f = dmp_clear_denoms(f, u, K0, K) + f = dmp_convert(f, u, K0, K) + else: + K = K0 + + if K.is_ZZ: + levels, f, v = dmp_exclude(f, u, K) + coeff, factors = dmp_zz_factor(f, v, K) + + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_include(f, levels, v, K), k) + elif K.is_Poly: + f, v = dmp_inject(f, u, K) + + coeff, factors = dmp_factor_list(f, v, K.dom) + + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_eject(f, v, K), k) + + coeff = K.convert(coeff, K.dom) + else: # pragma: no cover + raise DomainError('factorization not supported over %s' % K0) + + if K0.is_Field: + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_convert(f, u, K, K0), k) + + coeff = K0.convert(coeff, K) + coeff = K0.quo(coeff, denom) + + if K0_inexact: + for i, (f, k) in enumerate(factors): + max_norm = dmp_max_norm(f, u, K0) + f = dmp_quo_ground(f, max_norm, u, K0) + f = dmp_convert(f, u, K0, K0_inexact) + factors[i] = (f, k) + coeff = K0.mul(coeff, K0.pow(max_norm, k)) + + coeff = K0_inexact.convert(coeff, K0) + K0 = K0_inexact + + for i, j in enumerate(reversed(J)): + if not j: + continue + + term = {(0,)*(u - i) + (1,) + (0,)*i: K0.one} + factors.insert(0, (dmp_from_dict(term, u, K0), j)) + + return coeff*cont, _sort_factors(factors) + + +def dmp_factor_list_include(f, u, K): + """Factor multivariate polynomials into irreducibles in `K[X]`. """ + if not u: + return dup_factor_list_include(f, K) + + coeff, factors = dmp_factor_list(f, u, K) + + if not factors: + return [(dmp_ground(coeff, u), 1)] + else: + g = dmp_mul_ground(factors[0][0], coeff, u, K) + return [(g, factors[0][1])] + factors[1:] + + +def dup_irreducible_p(f, K): + """ + Returns ``True`` if a univariate polynomial ``f`` has no factors + over its domain. + """ + return dmp_irreducible_p(f, 0, K) + + +def dmp_irreducible_p(f, u, K): + """ + Returns ``True`` if a multivariate polynomial ``f`` has no factors + over its domain. + """ + _, factors = dmp_factor_list(f, u, K) + + if not factors: + return True + elif len(factors) > 1: + return False + else: + _, k = factors[0] + return k == 1 diff --git a/shared/package-files/02/020f6b521a01c9253a6dadf014b7ae67258c267cfd56401ff53404cd61b88545/_dataset.pxd b/shared/package-files/02/020f6b521a01c9253a6dadf014b7ae67258c267cfd56401ff53404cd61b88545/_dataset.pxd new file mode 100644 index 0000000000000000000000000000000000000000..220ab6b19affe6b520db3a3501fad2772919f5e4 --- /dev/null +++ b/shared/package-files/02/020f6b521a01c9253a6dadf014b7ae67258c267cfd56401ff53404cd61b88545/_dataset.pxd @@ -0,0 +1,183 @@ +# 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. + +# cython: language_level = 3 + +"""Dataset is currently unstable. APIs subject to change without notice.""" + +from pyarrow.includes.common cimport * +from pyarrow.includes.libarrow_dataset cimport * +from pyarrow.lib cimport * +from pyarrow._fs cimport FileSystem, FileInfo + + +cdef CFileSource _make_file_source(object file, FileSystem filesystem=*, object file_size=*) + +cdef class DatasetFactory(_Weakrefable): + + cdef: + SharedPtrNoGIL[CDatasetFactory] wrapped + CDatasetFactory* factory + + cdef init(self, const shared_ptr[CDatasetFactory]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CDatasetFactory]& sp) + + cdef inline shared_ptr[CDatasetFactory] unwrap(self) nogil + + +cdef class Dataset(_Weakrefable): + + cdef: + SharedPtrNoGIL[CDataset] wrapped + CDataset* dataset + public dict _scan_options + + cdef void init(self, const shared_ptr[CDataset]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CDataset]& sp) + + cdef shared_ptr[CDataset] unwrap(self) nogil + + +cdef class Scanner(_Weakrefable): + cdef: + SharedPtrNoGIL[CScanner] wrapped + CScanner* scanner + + cdef void init(self, const shared_ptr[CScanner]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CScanner]& sp) + + cdef shared_ptr[CScanner] unwrap(self) + + @staticmethod + cdef shared_ptr[CScanOptions] _make_scan_options(Dataset dataset, dict py_scanoptions) except * + + +cdef class FragmentScanOptions(_Weakrefable): + + cdef: + shared_ptr[CFragmentScanOptions] wrapped + + cdef void init(self, const shared_ptr[CFragmentScanOptions]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CFragmentScanOptions]& sp) + + +cdef class FileFormat(_Weakrefable): + + cdef: + shared_ptr[CFileFormat] wrapped + CFileFormat* format + + cdef void init(self, const shared_ptr[CFileFormat]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CFileFormat]& sp) + + cdef inline shared_ptr[CFileFormat] unwrap(self) + + cdef _set_default_fragment_scan_options(self, FragmentScanOptions options) + + # Return a WrittenFile after a file was written. + # May be overridden by subclasses, e.g. to add metadata. + cdef WrittenFile _finish_write(self, path, base_dir, + CFileWriter* file_writer) + + +cdef class FileWriteOptions(_Weakrefable): + + cdef: + shared_ptr[CFileWriteOptions] wrapped + CFileWriteOptions* c_options + + cdef void init(self, const shared_ptr[CFileWriteOptions]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CFileWriteOptions]& sp) + + cdef inline shared_ptr[CFileWriteOptions] unwrap(self) + + +cdef class Fragment(_Weakrefable): + + cdef: + SharedPtrNoGIL[CFragment] wrapped + CFragment* fragment + + cdef void init(self, const shared_ptr[CFragment]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CFragment]& sp) + + cdef inline shared_ptr[CFragment] unwrap(self) + + +cdef class FileFragment(Fragment): + + cdef: + CFileFragment* file_fragment + + cdef void init(self, const shared_ptr[CFragment]& sp) + + +cdef class Partitioning(_Weakrefable): + + cdef: + shared_ptr[CPartitioning] wrapped + CPartitioning* partitioning + + cdef init(self, const shared_ptr[CPartitioning]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CPartitioning]& sp) + + cdef inline shared_ptr[CPartitioning] unwrap(self) + + +cdef class PartitioningFactory(_Weakrefable): + + cdef: + shared_ptr[CPartitioningFactory] wrapped + CPartitioningFactory* factory + object constructor + object options + + cdef init(self, const shared_ptr[CPartitioningFactory]& sp) + + @staticmethod + cdef wrap(const shared_ptr[CPartitioningFactory]& sp, + object constructor, object options) + + cdef inline shared_ptr[CPartitioningFactory] unwrap(self) + + +cdef class WrittenFile(_Weakrefable): + + # The full path to the created file + cdef public str path + # Optional Parquet metadata + # This metadata will have the file path attribute set to the path of + # the written file. + cdef public object metadata + # The size of the file in bytes + cdef public int64_t size diff --git a/shared/package-files/02/02108ef43132cac13e3fe40917daf252d275821538ff498e461009e7da6839b5/shape_base.py b/shared/package-files/02/02108ef43132cac13e3fe40917daf252d275821538ff498e461009e7da6839b5/shape_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5d8a41bfe4a9c6d0c5666968a31c78b7c27497dd --- /dev/null +++ b/shared/package-files/02/02108ef43132cac13e3fe40917daf252d275821538ff498e461009e7da6839b5/shape_base.py @@ -0,0 +1,1274 @@ +import functools + +import numpy.core.numeric as _nx +from numpy.core.numeric import asarray, zeros, array, asanyarray +from numpy.core.fromnumeric import reshape, transpose +from numpy.core.multiarray import normalize_axis_index +from numpy.core import overrides +from numpy.core import vstack, atleast_3d +from numpy.core.numeric import normalize_axis_tuple +from numpy.core.shape_base import _arrays_for_stack_dispatcher +from numpy.lib.index_tricks import ndindex +from numpy.matrixlib.defmatrix import matrix # this raises all the right alarm bells + + +__all__ = [ + 'column_stack', 'row_stack', 'dstack', 'array_split', 'split', + 'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims', + 'apply_along_axis', 'kron', 'tile', 'get_array_wrap', 'take_along_axis', + 'put_along_axis' + ] + + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +def _make_along_axis_idx(arr_shape, indices, axis): + # compute dimensions to iterate over + if not _nx.issubdtype(indices.dtype, _nx.integer): + raise IndexError('`indices` must be an integer array') + if len(arr_shape) != indices.ndim: + raise ValueError( + "`indices` and `arr` must have the same number of dimensions") + shape_ones = (1,) * indices.ndim + dest_dims = list(range(axis)) + [None] + list(range(axis+1, indices.ndim)) + + # build a fancy index, consisting of orthogonal aranges, with the + # requested index inserted at the right location + fancy_index = [] + for dim, n in zip(dest_dims, arr_shape): + if dim is None: + fancy_index.append(indices) + else: + ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim+1:] + fancy_index.append(_nx.arange(n).reshape(ind_shape)) + + return tuple(fancy_index) + + +def _take_along_axis_dispatcher(arr, indices, axis): + return (arr, indices) + + +@array_function_dispatch(_take_along_axis_dispatcher) +def take_along_axis(arr, indices, axis): + """ + Take values from the input array by matching 1d index and data slices. + + This iterates over matching 1d slices oriented along the specified axis in + the index and data arrays, and uses the former to look up values in the + latter. These slices can be different lengths. + + Functions returning an index along an axis, like `argsort` and + `argpartition`, produce suitable indices for this function. + + .. versionadded:: 1.15.0 + + Parameters + ---------- + arr : ndarray (Ni..., M, Nk...) + Source array + indices : ndarray (Ni..., J, Nk...) + Indices to take along each 1d slice of `arr`. This must match the + dimension of arr, but dimensions Ni and Nj only need to broadcast + against `arr`. + axis : int + The axis to take 1d slices along. If axis is None, the input array is + treated as if it had first been flattened to 1d, for consistency with + `sort` and `argsort`. + + Returns + ------- + out: ndarray (Ni..., J, Nk...) + The indexed result. + + Notes + ----- + This is equivalent to (but faster than) the following use of `ndindex` and + `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices:: + + Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:] + J = indices.shape[axis] # Need not equal M + out = np.empty(Ni + (J,) + Nk) + + for ii in ndindex(Ni): + for kk in ndindex(Nk): + a_1d = a [ii + s_[:,] + kk] + indices_1d = indices[ii + s_[:,] + kk] + out_1d = out [ii + s_[:,] + kk] + for j in range(J): + out_1d[j] = a_1d[indices_1d[j]] + + Equivalently, eliminating the inner loop, the last two lines would be:: + + out_1d[:] = a_1d[indices_1d] + + See Also + -------- + take : Take along an axis, using the same indices for every 1d slice + put_along_axis : + Put values into the destination array by matching 1d index and data slices + + Examples + -------- + + For this sample array + + >>> a = np.array([[10, 30, 20], [60, 40, 50]]) + + We can sort either by using sort directly, or argsort and this function + + >>> np.sort(a, axis=1) + array([[10, 20, 30], + [40, 50, 60]]) + >>> ai = np.argsort(a, axis=1) + >>> ai + array([[0, 2, 1], + [1, 2, 0]]) + >>> np.take_along_axis(a, ai, axis=1) + array([[10, 20, 30], + [40, 50, 60]]) + + The same works for max and min, if you maintain the trivial dimension + with ``keepdims``: + + >>> np.max(a, axis=1, keepdims=True) + array([[30], + [60]]) + >>> ai = np.argmax(a, axis=1, keepdims=True) + >>> ai + array([[1], + [0]]) + >>> np.take_along_axis(a, ai, axis=1) + array([[30], + [60]]) + + If we want to get the max and min at the same time, we can stack the + indices first + + >>> ai_min = np.argmin(a, axis=1, keepdims=True) + >>> ai_max = np.argmax(a, axis=1, keepdims=True) + >>> ai = np.concatenate([ai_min, ai_max], axis=1) + >>> ai + array([[0, 1], + [1, 0]]) + >>> np.take_along_axis(a, ai, axis=1) + array([[10, 30], + [40, 60]]) + """ + # normalize inputs + if axis is None: + arr = arr.flat + arr_shape = (len(arr),) # flatiter has no .shape + axis = 0 + else: + axis = normalize_axis_index(axis, arr.ndim) + arr_shape = arr.shape + + # use the fancy index + return arr[_make_along_axis_idx(arr_shape, indices, axis)] + + +def _put_along_axis_dispatcher(arr, indices, values, axis): + return (arr, indices, values) + + +@array_function_dispatch(_put_along_axis_dispatcher) +def put_along_axis(arr, indices, values, axis): + """ + Put values into the destination array by matching 1d index and data slices. + + This iterates over matching 1d slices oriented along the specified axis in + the index and data arrays, and uses the former to place values into the + latter. These slices can be different lengths. + + Functions returning an index along an axis, like `argsort` and + `argpartition`, produce suitable indices for this function. + + .. versionadded:: 1.15.0 + + Parameters + ---------- + arr : ndarray (Ni..., M, Nk...) + Destination array. + indices : ndarray (Ni..., J, Nk...) + Indices to change along each 1d slice of `arr`. This must match the + dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast + against `arr`. + values : array_like (Ni..., J, Nk...) + values to insert at those indices. Its shape and dimension are + broadcast to match that of `indices`. + axis : int + The axis to take 1d slices along. If axis is None, the destination + array is treated as if a flattened 1d view had been created of it. + + Notes + ----- + This is equivalent to (but faster than) the following use of `ndindex` and + `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices:: + + Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:] + J = indices.shape[axis] # Need not equal M + + for ii in ndindex(Ni): + for kk in ndindex(Nk): + a_1d = a [ii + s_[:,] + kk] + indices_1d = indices[ii + s_[:,] + kk] + values_1d = values [ii + s_[:,] + kk] + for j in range(J): + a_1d[indices_1d[j]] = values_1d[j] + + Equivalently, eliminating the inner loop, the last two lines would be:: + + a_1d[indices_1d] = values_1d + + See Also + -------- + take_along_axis : + Take values from the input array by matching 1d index and data slices + + Examples + -------- + + For this sample array + + >>> a = np.array([[10, 30, 20], [60, 40, 50]]) + + We can replace the maximum values with: + + >>> ai = np.argmax(a, axis=1, keepdims=True) + >>> ai + array([[1], + [0]]) + >>> np.put_along_axis(a, ai, 99, axis=1) + >>> a + array([[10, 99, 20], + [99, 40, 50]]) + + """ + # normalize inputs + if axis is None: + arr = arr.flat + axis = 0 + arr_shape = (len(arr),) # flatiter has no .shape + else: + axis = normalize_axis_index(axis, arr.ndim) + arr_shape = arr.shape + + # use the fancy index + arr[_make_along_axis_idx(arr_shape, indices, axis)] = values + + +def _apply_along_axis_dispatcher(func1d, axis, arr, *args, **kwargs): + return (arr,) + + +@array_function_dispatch(_apply_along_axis_dispatcher) +def apply_along_axis(func1d, axis, arr, *args, **kwargs): + """ + Apply a function to 1-D slices along the given axis. + + Execute `func1d(a, *args, **kwargs)` where `func1d` operates on 1-D arrays + and `a` is a 1-D slice of `arr` along `axis`. + + This is equivalent to (but faster than) the following use of `ndindex` and + `s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of indices:: + + Ni, Nk = a.shape[:axis], a.shape[axis+1:] + for ii in ndindex(Ni): + for kk in ndindex(Nk): + f = func1d(arr[ii + s_[:,] + kk]) + Nj = f.shape + for jj in ndindex(Nj): + out[ii + jj + kk] = f[jj] + + Equivalently, eliminating the inner loop, this can be expressed as:: + + Ni, Nk = a.shape[:axis], a.shape[axis+1:] + for ii in ndindex(Ni): + for kk in ndindex(Nk): + out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk]) + + Parameters + ---------- + func1d : function (M,) -> (Nj...) + This function should accept 1-D arrays. It is applied to 1-D + slices of `arr` along the specified axis. + axis : integer + Axis along which `arr` is sliced. + arr : ndarray (Ni..., M, Nk...) + Input array. + args : any + Additional arguments to `func1d`. + kwargs : any + Additional named arguments to `func1d`. + + .. versionadded:: 1.9.0 + + + Returns + ------- + out : ndarray (Ni..., Nj..., Nk...) + The output array. The shape of `out` is identical to the shape of + `arr`, except along the `axis` dimension. This axis is removed, and + replaced with new dimensions equal to the shape of the return value + of `func1d`. So if `func1d` returns a scalar `out` will have one + fewer dimensions than `arr`. + + See Also + -------- + apply_over_axes : Apply a function repeatedly over multiple axes. + + Examples + -------- + >>> def my_func(a): + ... \"\"\"Average first and last element of a 1-D array\"\"\" + ... return (a[0] + a[-1]) * 0.5 + >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) + >>> np.apply_along_axis(my_func, 0, b) + array([4., 5., 6.]) + >>> np.apply_along_axis(my_func, 1, b) + array([2., 5., 8.]) + + For a function that returns a 1D array, the number of dimensions in + `outarr` is the same as `arr`. + + >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]]) + >>> np.apply_along_axis(sorted, 1, b) + array([[1, 7, 8], + [3, 4, 9], + [2, 5, 6]]) + + For a function that returns a higher dimensional array, those dimensions + are inserted in place of the `axis` dimension. + + >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) + >>> np.apply_along_axis(np.diag, -1, b) + array([[[1, 0, 0], + [0, 2, 0], + [0, 0, 3]], + [[4, 0, 0], + [0, 5, 0], + [0, 0, 6]], + [[7, 0, 0], + [0, 8, 0], + [0, 0, 9]]]) + """ + # handle negative axes + arr = asanyarray(arr) + nd = arr.ndim + axis = normalize_axis_index(axis, nd) + + # arr, with the iteration axis at the end + in_dims = list(range(nd)) + inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis]) + + # compute indices for the iteration axes, and append a trailing ellipsis to + # prevent 0d arrays decaying to scalars, which fixes gh-8642 + inds = ndindex(inarr_view.shape[:-1]) + inds = (ind + (Ellipsis,) for ind in inds) + + # invoke the function on the first item + try: + ind0 = next(inds) + except StopIteration: + raise ValueError( + 'Cannot apply_along_axis when any iteration dimensions are 0' + ) from None + res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs)) + + # build a buffer for storing evaluations of func1d. + # remove the requested axis, and add the new ones on the end. + # laid out so that each write is contiguous. + # for a tuple index inds, buff[inds] = func1d(inarr_view[inds]) + buff = zeros(inarr_view.shape[:-1] + res.shape, res.dtype) + + # permutation of axes such that out = buff.transpose(buff_permute) + buff_dims = list(range(buff.ndim)) + buff_permute = ( + buff_dims[0 : axis] + + buff_dims[buff.ndim-res.ndim : buff.ndim] + + buff_dims[axis : buff.ndim-res.ndim] + ) + + # matrices have a nasty __array_prepare__ and __array_wrap__ + if not isinstance(res, matrix): + buff = res.__array_prepare__(buff) + + # save the first result, then compute and save all remaining results + buff[ind0] = res + for ind in inds: + buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs)) + + if not isinstance(res, matrix): + # wrap the array, to preserve subclasses + buff = res.__array_wrap__(buff) + + # finally, rotate the inserted axes back to where they belong + return transpose(buff, buff_permute) + + else: + # matrices have to be transposed first, because they collapse dimensions! + out_arr = transpose(buff, buff_permute) + return res.__array_wrap__(out_arr) + + +def _apply_over_axes_dispatcher(func, a, axes): + return (a,) + + +@array_function_dispatch(_apply_over_axes_dispatcher) +def apply_over_axes(func, a, axes): + """ + Apply a function repeatedly over multiple axes. + + `func` is called as `res = func(a, axis)`, where `axis` is the first + element of `axes`. The result `res` of the function call must have + either the same dimensions as `a` or one less dimension. If `res` + has one less dimension than `a`, a dimension is inserted before + `axis`. The call to `func` is then repeated for each axis in `axes`, + with `res` as the first argument. + + Parameters + ---------- + func : function + This function must take two arguments, `func(a, axis)`. + a : array_like + Input array. + axes : array_like + Axes over which `func` is applied; the elements must be integers. + + Returns + ------- + apply_over_axis : ndarray + The output array. The number of dimensions is the same as `a`, + but the shape can be different. This depends on whether `func` + changes the shape of its output with respect to its input. + + See Also + -------- + apply_along_axis : + Apply a function to 1-D slices of an array along the given axis. + + Notes + ----- + This function is equivalent to tuple axis arguments to reorderable ufuncs + with keepdims=True. Tuple axis arguments to ufuncs have been available since + version 1.7.0. + + Examples + -------- + >>> a = np.arange(24).reshape(2,3,4) + >>> a + array([[[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]], + [[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23]]]) + + Sum over axes 0 and 2. The result has same number of dimensions + as the original array: + + >>> np.apply_over_axes(np.sum, a, [0,2]) + array([[[ 60], + [ 92], + [124]]]) + + Tuple axis arguments to ufuncs are equivalent: + + >>> np.sum(a, axis=(0,2), keepdims=True) + array([[[ 60], + [ 92], + [124]]]) + + """ + val = asarray(a) + N = a.ndim + if array(axes).ndim == 0: + axes = (axes,) + for axis in axes: + if axis < 0: + axis = N + axis + args = (val, axis) + res = func(*args) + if res.ndim == val.ndim: + val = res + else: + res = expand_dims(res, axis) + if res.ndim == val.ndim: + val = res + else: + raise ValueError("function is not returning " + "an array of the correct shape") + return val + + +def _expand_dims_dispatcher(a, axis): + return (a,) + + +@array_function_dispatch(_expand_dims_dispatcher) +def expand_dims(a, axis): + """ + Expand the shape of an array. + + Insert a new axis that will appear at the `axis` position in the expanded + array shape. + + Parameters + ---------- + a : array_like + Input array. + axis : int or tuple of ints + Position in the expanded axes where the new axis (or axes) is placed. + + .. deprecated:: 1.13.0 + Passing an axis where ``axis > a.ndim`` will be treated as + ``axis == a.ndim``, and passing ``axis < -a.ndim - 1`` will + be treated as ``axis == 0``. This behavior is deprecated. + + .. versionchanged:: 1.18.0 + A tuple of axes is now supported. Out of range axes as + described above are now forbidden and raise an `AxisError`. + + Returns + ------- + result : ndarray + View of `a` with the number of dimensions increased. + + See Also + -------- + squeeze : The inverse operation, removing singleton dimensions + reshape : Insert, remove, and combine dimensions, and resize existing ones + doc.indexing, atleast_1d, atleast_2d, atleast_3d + + Examples + -------- + >>> x = np.array([1, 2]) + >>> x.shape + (2,) + + The following is equivalent to ``x[np.newaxis, :]`` or ``x[np.newaxis]``: + + >>> y = np.expand_dims(x, axis=0) + >>> y + array([[1, 2]]) + >>> y.shape + (1, 2) + + The following is equivalent to ``x[:, np.newaxis]``: + + >>> y = np.expand_dims(x, axis=1) + >>> y + array([[1], + [2]]) + >>> y.shape + (2, 1) + + ``axis`` may also be a tuple: + + >>> y = np.expand_dims(x, axis=(0, 1)) + >>> y + array([[[1, 2]]]) + + >>> y = np.expand_dims(x, axis=(2, 0)) + >>> y + array([[[1], + [2]]]) + + Note that some examples may use ``None`` instead of ``np.newaxis``. These + are the same objects: + + >>> np.newaxis is None + True + + """ + if isinstance(a, matrix): + a = asarray(a) + else: + a = asanyarray(a) + + if type(axis) not in (tuple, list): + axis = (axis,) + + out_ndim = len(axis) + a.ndim + axis = normalize_axis_tuple(axis, out_ndim) + + shape_it = iter(a.shape) + shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)] + + return a.reshape(shape) + + +row_stack = vstack + + +def _column_stack_dispatcher(tup): + return _arrays_for_stack_dispatcher(tup) + + +@array_function_dispatch(_column_stack_dispatcher) +def column_stack(tup): + """ + Stack 1-D arrays as columns into a 2-D array. + + Take a sequence of 1-D arrays and stack them as columns + to make a single 2-D array. 2-D arrays are stacked as-is, + just like with `hstack`. 1-D arrays are turned into 2-D columns + first. + + Parameters + ---------- + tup : sequence of 1-D or 2-D arrays. + Arrays to stack. All of them must have the same first dimension. + + Returns + ------- + stacked : 2-D array + The array formed by stacking the given arrays. + + See Also + -------- + stack, hstack, vstack, concatenate + + Examples + -------- + >>> a = np.array((1,2,3)) + >>> b = np.array((2,3,4)) + >>> np.column_stack((a,b)) + array([[1, 2], + [2, 3], + [3, 4]]) + + """ + arrays = [] + for v in tup: + arr = asanyarray(v) + if arr.ndim < 2: + arr = array(arr, copy=False, subok=True, ndmin=2).T + arrays.append(arr) + return _nx.concatenate(arrays, 1) + + +def _dstack_dispatcher(tup): + return _arrays_for_stack_dispatcher(tup) + + +@array_function_dispatch(_dstack_dispatcher) +def dstack(tup): + """ + Stack arrays in sequence depth wise (along third axis). + + This is equivalent to concatenation along the third axis after 2-D arrays + of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape + `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by + `dsplit`. + + This function makes most sense for arrays with up to 3 dimensions. For + instance, for pixel-data with a height (first axis), width (second axis), + and r/g/b channels (third axis). The functions `concatenate`, `stack` and + `block` provide more general stacking and concatenation operations. + + Parameters + ---------- + tup : sequence of arrays + The arrays must have the same shape along all but the third axis. + 1-D or 2-D arrays must have the same shape. + + Returns + ------- + stacked : ndarray + The array formed by stacking the given arrays, will be at least 3-D. + + See Also + -------- + concatenate : Join a sequence of arrays along an existing axis. + stack : Join a sequence of arrays along a new axis. + block : Assemble an nd-array from nested lists of blocks. + vstack : Stack arrays in sequence vertically (row wise). + hstack : Stack arrays in sequence horizontally (column wise). + column_stack : Stack 1-D arrays as columns into a 2-D array. + dsplit : Split array along third axis. + + Examples + -------- + >>> a = np.array((1,2,3)) + >>> b = np.array((2,3,4)) + >>> np.dstack((a,b)) + array([[[1, 2], + [2, 3], + [3, 4]]]) + + >>> a = np.array([[1],[2],[3]]) + >>> b = np.array([[2],[3],[4]]) + >>> np.dstack((a,b)) + array([[[1, 2]], + [[2, 3]], + [[3, 4]]]) + + """ + arrs = atleast_3d(*tup) + if not isinstance(arrs, list): + arrs = [arrs] + return _nx.concatenate(arrs, 2) + + +def _replace_zero_by_x_arrays(sub_arys): + for i in range(len(sub_arys)): + if _nx.ndim(sub_arys[i]) == 0: + sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype) + elif _nx.sometrue(_nx.equal(_nx.shape(sub_arys[i]), 0)): + sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype) + return sub_arys + + +def _array_split_dispatcher(ary, indices_or_sections, axis=None): + return (ary, indices_or_sections) + + +@array_function_dispatch(_array_split_dispatcher) +def array_split(ary, indices_or_sections, axis=0): + """ + Split an array into multiple sub-arrays. + + Please refer to the ``split`` documentation. The only difference + between these functions is that ``array_split`` allows + `indices_or_sections` to be an integer that does *not* equally + divide the axis. For an array of length l that should be split + into n sections, it returns l % n sub-arrays of size l//n + 1 + and the rest of size l//n. + + See Also + -------- + split : Split array into multiple sub-arrays of equal size. + + Examples + -------- + >>> x = np.arange(8.0) + >>> np.array_split(x, 3) + [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])] + + >>> x = np.arange(9) + >>> np.array_split(x, 4) + [array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])] + + """ + try: + Ntotal = ary.shape[axis] + except AttributeError: + Ntotal = len(ary) + try: + # handle array case. + Nsections = len(indices_or_sections) + 1 + div_points = [0] + list(indices_or_sections) + [Ntotal] + except TypeError: + # indices_or_sections is a scalar, not an array. + Nsections = int(indices_or_sections) + if Nsections <= 0: + raise ValueError('number sections must be larger than 0.') from None + Neach_section, extras = divmod(Ntotal, Nsections) + section_sizes = ([0] + + extras * [Neach_section+1] + + (Nsections-extras) * [Neach_section]) + div_points = _nx.array(section_sizes, dtype=_nx.intp).cumsum() + + sub_arys = [] + sary = _nx.swapaxes(ary, axis, 0) + for i in range(Nsections): + st = div_points[i] + end = div_points[i + 1] + sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0)) + + return sub_arys + + +def _split_dispatcher(ary, indices_or_sections, axis=None): + return (ary, indices_or_sections) + + +@array_function_dispatch(_split_dispatcher) +def split(ary, indices_or_sections, axis=0): + """ + Split an array into multiple sub-arrays as views into `ary`. + + Parameters + ---------- + ary : ndarray + Array to be divided into sub-arrays. + indices_or_sections : int or 1-D array + If `indices_or_sections` is an integer, N, the array will be divided + into N equal arrays along `axis`. If such a split is not possible, + an error is raised. + + If `indices_or_sections` is a 1-D array of sorted integers, the entries + indicate where along `axis` the array is split. For example, + ``[2, 3]`` would, for ``axis=0``, result in + + - ary[:2] + - ary[2:3] + - ary[3:] + + If an index exceeds the dimension of the array along `axis`, + an empty sub-array is returned correspondingly. + axis : int, optional + The axis along which to split, default is 0. + + Returns + ------- + sub-arrays : list of ndarrays + A list of sub-arrays as views into `ary`. + + Raises + ------ + ValueError + If `indices_or_sections` is given as an integer, but + a split does not result in equal division. + + See Also + -------- + array_split : Split an array into multiple sub-arrays of equal or + near-equal size. Does not raise an exception if + an equal division cannot be made. + hsplit : Split array into multiple sub-arrays horizontally (column-wise). + vsplit : Split array into multiple sub-arrays vertically (row wise). + dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). + concatenate : Join a sequence of arrays along an existing axis. + stack : Join a sequence of arrays along a new axis. + hstack : Stack arrays in sequence horizontally (column wise). + vstack : Stack arrays in sequence vertically (row wise). + dstack : Stack arrays in sequence depth wise (along third dimension). + + Examples + -------- + >>> x = np.arange(9.0) + >>> np.split(x, 3) + [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])] + + >>> x = np.arange(8.0) + >>> np.split(x, [3, 5, 6, 10]) + [array([0., 1., 2.]), + array([3., 4.]), + array([5.]), + array([6., 7.]), + array([], dtype=float64)] + + """ + try: + len(indices_or_sections) + except TypeError: + sections = indices_or_sections + N = ary.shape[axis] + if N % sections: + raise ValueError( + 'array split does not result in an equal division') from None + return array_split(ary, indices_or_sections, axis) + + +def _hvdsplit_dispatcher(ary, indices_or_sections): + return (ary, indices_or_sections) + + +@array_function_dispatch(_hvdsplit_dispatcher) +def hsplit(ary, indices_or_sections): + """ + Split an array into multiple sub-arrays horizontally (column-wise). + + Please refer to the `split` documentation. `hsplit` is equivalent + to `split` with ``axis=1``, the array is always split along the second + axis except for 1-D arrays, where it is split at ``axis=0``. + + See Also + -------- + split : Split an array into multiple sub-arrays of equal size. + + Examples + -------- + >>> x = np.arange(16.0).reshape(4, 4) + >>> x + array([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> np.hsplit(x, 2) + [array([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + array([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])] + >>> np.hsplit(x, np.array([3, 6])) + [array([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + array([[ 3.], + [ 7.], + [11.], + [15.]]), + array([], shape=(4, 0), dtype=float64)] + + With a higher dimensional array the split is still along the second axis. + + >>> x = np.arange(8.0).reshape(2, 2, 2) + >>> x + array([[[0., 1.], + [2., 3.]], + [[4., 5.], + [6., 7.]]]) + >>> np.hsplit(x, 2) + [array([[[0., 1.]], + [[4., 5.]]]), + array([[[2., 3.]], + [[6., 7.]]])] + + With a 1-D array, the split is along axis 0. + + >>> x = np.array([0, 1, 2, 3, 4, 5]) + >>> np.hsplit(x, 2) + [array([0, 1, 2]), array([3, 4, 5])] + + """ + if _nx.ndim(ary) == 0: + raise ValueError('hsplit only works on arrays of 1 or more dimensions') + if ary.ndim > 1: + return split(ary, indices_or_sections, 1) + else: + return split(ary, indices_or_sections, 0) + + +@array_function_dispatch(_hvdsplit_dispatcher) +def vsplit(ary, indices_or_sections): + """ + Split an array into multiple sub-arrays vertically (row-wise). + + Please refer to the ``split`` documentation. ``vsplit`` is equivalent + to ``split`` with `axis=0` (default), the array is always split along the + first axis regardless of the array dimension. + + See Also + -------- + split : Split an array into multiple sub-arrays of equal size. + + Examples + -------- + >>> x = np.arange(16.0).reshape(4, 4) + >>> x + array([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> np.vsplit(x, 2) + [array([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])] + >>> np.vsplit(x, np.array([3, 6])) + [array([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), array([[12., 13., 14., 15.]]), array([], shape=(0, 4), dtype=float64)] + + With a higher dimensional array the split is still along the first axis. + + >>> x = np.arange(8.0).reshape(2, 2, 2) + >>> x + array([[[0., 1.], + [2., 3.]], + [[4., 5.], + [6., 7.]]]) + >>> np.vsplit(x, 2) + [array([[[0., 1.], + [2., 3.]]]), array([[[4., 5.], + [6., 7.]]])] + + """ + if _nx.ndim(ary) < 2: + raise ValueError('vsplit only works on arrays of 2 or more dimensions') + return split(ary, indices_or_sections, 0) + + +@array_function_dispatch(_hvdsplit_dispatcher) +def dsplit(ary, indices_or_sections): + """ + Split array into multiple sub-arrays along the 3rd axis (depth). + + Please refer to the `split` documentation. `dsplit` is equivalent + to `split` with ``axis=2``, the array is always split along the third + axis provided the array dimension is greater than or equal to 3. + + See Also + -------- + split : Split an array into multiple sub-arrays of equal size. + + Examples + -------- + >>> x = np.arange(16.0).reshape(2, 2, 4) + >>> x + array([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> np.dsplit(x, 2) + [array([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), array([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])] + >>> np.dsplit(x, np.array([3, 6])) + [array([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + array([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + array([], shape=(2, 2, 0), dtype=float64)] + """ + if _nx.ndim(ary) < 3: + raise ValueError('dsplit only works on arrays of 3 or more dimensions') + return split(ary, indices_or_sections, 2) + + +def get_array_prepare(*args): + """Find the wrapper for the array with the highest priority. + + In case of ties, leftmost wins. If no wrapper is found, return None + """ + wrappers = sorted((getattr(x, '__array_priority__', 0), -i, + x.__array_prepare__) for i, x in enumerate(args) + if hasattr(x, '__array_prepare__')) + if wrappers: + return wrappers[-1][-1] + return None + + +def get_array_wrap(*args): + """Find the wrapper for the array with the highest priority. + + In case of ties, leftmost wins. If no wrapper is found, return None + """ + wrappers = sorted((getattr(x, '__array_priority__', 0), -i, + x.__array_wrap__) for i, x in enumerate(args) + if hasattr(x, '__array_wrap__')) + if wrappers: + return wrappers[-1][-1] + return None + + +def _kron_dispatcher(a, b): + return (a, b) + + +@array_function_dispatch(_kron_dispatcher) +def kron(a, b): + """ + Kronecker product of two arrays. + + Computes the Kronecker product, a composite array made of blocks of the + second array scaled by the first. + + Parameters + ---------- + a, b : array_like + + Returns + ------- + out : ndarray + + See Also + -------- + outer : The outer product + + 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 + -------- + >>> np.kron([1,10,100], [5,6,7]) + array([ 5, 6, 7, ..., 500, 600, 700]) + >>> np.kron([5,6,7], [1,10,100]) + array([ 5, 50, 500, ..., 7, 70, 700]) + + >>> np.kron(np.eye(2), np.ones((2,2))) + array([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> a = np.arange(100).reshape((2,5,2,5)) + >>> b = np.arange(24).reshape((2,3,4)) + >>> c = np.kron(a,b) + >>> 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(np.array(I) * np.array(S1) + np.array(J1)) + >>> c[K] == a[I]*b[J] + True + + """ + # Working: + # 1. Equalise the shapes by prepending smaller array with 1s + # 2. Expand shapes of both the arrays by adding new axes at + # odd positions for 1st array and even positions for 2nd + # 3. Compute the product of the modified array + # 4. The inner most array elements now contain the rows of + # the Kronecker product + # 5. Reshape the result to kron's shape, which is same as + # product of shapes of the two arrays. + b = asanyarray(b) + a = array(a, copy=False, subok=True, ndmin=b.ndim) + is_any_mat = isinstance(a, matrix) or isinstance(b, matrix) + ndb, nda = b.ndim, a.ndim + nd = max(ndb, nda) + + if (nda == 0 or ndb == 0): + return _nx.multiply(a, b) + + as_ = a.shape + bs = b.shape + if not a.flags.contiguous: + a = reshape(a, as_) + if not b.flags.contiguous: + b = reshape(b, bs) + + # Equalise the shapes by prepending smaller one with 1s + as_ = (1,)*max(0, ndb-nda) + as_ + bs = (1,)*max(0, nda-ndb) + bs + + # Insert empty dimensions + a_arr = expand_dims(a, axis=tuple(range(ndb-nda))) + b_arr = expand_dims(b, axis=tuple(range(nda-ndb))) + + # Compute the product + a_arr = expand_dims(a_arr, axis=tuple(range(1, nd*2, 2))) + b_arr = expand_dims(b_arr, axis=tuple(range(0, nd*2, 2))) + # In case of `mat`, convert result to `array` + result = _nx.multiply(a_arr, b_arr, subok=(not is_any_mat)) + + # Reshape back + result = result.reshape(_nx.multiply(as_, bs)) + + return result if not is_any_mat else matrix(result, copy=False) + + +def _tile_dispatcher(A, reps): + return (A, reps) + + +@array_function_dispatch(_tile_dispatcher) +def tile(A, reps): + """ + Construct an array by repeating A the number of times given by reps. + + If `reps` has length ``d``, the result will have dimension of + ``max(d, A.ndim)``. + + If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new + axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, + or shape (1, 1, 3) for 3-D replication. If this is not the desired + behavior, promote `A` to d-dimensions manually before calling this + function. + + If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it. + Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as + (1, 1, 2, 2). + + Note : Although tile may be used for broadcasting, it is strongly + recommended to use numpy's broadcasting operations and functions. + + Parameters + ---------- + A : array_like + The input array. + reps : array_like + The number of repetitions of `A` along each axis. + + Returns + ------- + c : ndarray + The tiled output array. + + See Also + -------- + repeat : Repeat elements of an array. + broadcast_to : Broadcast an array to a new shape + + Examples + -------- + >>> a = np.array([0, 1, 2]) + >>> np.tile(a, 2) + array([0, 1, 2, 0, 1, 2]) + >>> np.tile(a, (2, 2)) + array([[0, 1, 2, 0, 1, 2], + [0, 1, 2, 0, 1, 2]]) + >>> np.tile(a, (2, 1, 2)) + array([[[0, 1, 2, 0, 1, 2]], + [[0, 1, 2, 0, 1, 2]]]) + + >>> b = np.array([[1, 2], [3, 4]]) + >>> np.tile(b, 2) + array([[1, 2, 1, 2], + [3, 4, 3, 4]]) + >>> np.tile(b, (2, 1)) + array([[1, 2], + [3, 4], + [1, 2], + [3, 4]]) + + >>> c = np.array([1,2,3,4]) + >>> np.tile(c,(4,1)) + array([[1, 2, 3, 4], + [1, 2, 3, 4], + [1, 2, 3, 4], + [1, 2, 3, 4]]) + """ + try: + tup = tuple(reps) + except TypeError: + tup = (reps,) + d = len(tup) + if all(x == 1 for x in tup) and isinstance(A, _nx.ndarray): + # Fixes the problem that the function does not make a copy if A is a + # numpy array and the repetitions are 1 in all dimensions + return _nx.array(A, copy=True, subok=True, ndmin=d) + else: + # Note that no copy of zero-sized arrays is made. However since they + # have no data there is no risk of an inadvertent overwrite. + c = _nx.array(A, copy=False, subok=True, ndmin=d) + if (d < c.ndim): + tup = (1,)*(c.ndim-d) + tup + shape_out = tuple(s*t for s, t in zip(c.shape, tup)) + n = c.size + if n > 0: + for dim_in, nrep in zip(c.shape, tup): + if nrep != 1: + c = c.reshape(-1, n).repeat(nrep, 0) + n //= dim_in + return c.reshape(shape_out) diff --git a/shared/package-files/02/0212b936e3a9743f898c8cd73a5b2c13cfe248bc850001f3c8657fc35053eef0/__init__.pyi b/shared/package-files/02/0212b936e3a9743f898c8cd73a5b2c13cfe248bc850001f3c8657fc35053eef0/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d65860ccb044c7c01ade91327f25a0e94e4c9b32 --- /dev/null +++ b/shared/package-files/02/0212b936e3a9743f898c8cd73a5b2c13cfe248bc850001f3c8657fc35053eef0/__init__.pyi @@ -0,0 +1,50 @@ +from numpy._pytesttester import PytestTester + +from unittest import ( + TestCase as TestCase, +) + +from numpy.testing._private.utils import ( + assert_equal as assert_equal, + assert_almost_equal as assert_almost_equal, + assert_approx_equal as assert_approx_equal, + assert_array_equal as assert_array_equal, + assert_array_less as assert_array_less, + assert_string_equal as assert_string_equal, + assert_array_almost_equal as assert_array_almost_equal, + assert_raises as assert_raises, + build_err_msg as build_err_msg, + decorate_methods as decorate_methods, + jiffies as jiffies, + memusage as memusage, + print_assert_equal as print_assert_equal, + rundocs as rundocs, + runstring as runstring, + verbose as verbose, + measure as measure, + assert_ as assert_, + assert_array_almost_equal_nulp as assert_array_almost_equal_nulp, + assert_raises_regex as assert_raises_regex, + assert_array_max_ulp as assert_array_max_ulp, + assert_warns as assert_warns, + assert_no_warnings as assert_no_warnings, + assert_allclose as assert_allclose, + IgnoreException as IgnoreException, + clear_and_catch_warnings as clear_and_catch_warnings, + SkipTest as SkipTest, + KnownFailureException as KnownFailureException, + temppath as temppath, + tempdir as tempdir, + IS_PYPY as IS_PYPY, + IS_PYSTON as IS_PYSTON, + HAS_REFCOUNT as HAS_REFCOUNT, + suppress_warnings as suppress_warnings, + assert_array_compare as assert_array_compare, + assert_no_gc_cycles as assert_no_gc_cycles, + break_cycles as break_cycles, + HAS_LAPACK64 as HAS_LAPACK64, +) + +__all__: list[str] +__path__: list[str] +test: PytestTester diff --git a/shared/package-files/02/02169eb141a5fbd8adeaebc6e9fb053ceafdca716919a4cc938b795d35fb67f4/urls.py b/shared/package-files/02/02169eb141a5fbd8adeaebc6e9fb053ceafdca716919a4cc938b795d35fb67f4/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..6ba2e04f350792e2c0021cf7ba7f40b25dc6cd51 --- /dev/null +++ b/shared/package-files/02/02169eb141a5fbd8adeaebc6e9fb053ceafdca716919a4cc938b795d35fb67f4/urls.py @@ -0,0 +1,62 @@ +import os +import string +import urllib.parse +import urllib.request +from typing import Optional + +from .compat import WINDOWS + + +def get_url_scheme(url: str) -> Optional[str]: + if ":" not in url: + return None + return url.split(":", 1)[0].lower() + + +def path_to_url(path: str) -> str: + """ + Convert a path to a file: URL. The path will be made absolute and have + quoted path parts. + """ + path = os.path.normpath(os.path.abspath(path)) + url = urllib.parse.urljoin("file:", urllib.request.pathname2url(path)) + return url + + +def url_to_path(url: str) -> str: + """ + Convert a file: URL to a path. + """ + assert url.startswith( + "file:" + ), f"You can only turn file: urls into filenames (not {url!r})" + + _, netloc, path, _, _ = urllib.parse.urlsplit(url) + + if not netloc or netloc == "localhost": + # According to RFC 8089, same as empty authority. + netloc = "" + elif WINDOWS: + # If we have a UNC path, prepend UNC share notation. + netloc = "\\\\" + netloc + else: + raise ValueError( + f"non-local file URIs are not supported on this platform: {url!r}" + ) + + path = urllib.request.url2pathname(netloc + path) + + # On Windows, urlsplit parses the path as something like "/C:/Users/foo". + # This creates issues for path-related functions like io.open(), so we try + # to detect and strip the leading slash. + if ( + WINDOWS + and not netloc # Not UNC. + and len(path) >= 3 + and path[0] == "/" # Leading slash to strip. + and path[1] in string.ascii_letters # Drive letter. + and path[2:4] in (":", ":/") # Colon + end of string, or colon + absolute path. + ): + path = path[1:] + + return path diff --git a/shared/package-files/02/0217e96269b35ecf856e039eb6839d9759618f5ab5398df43a0cfceb9a5ee5ac/_upsample_nearest_exact3d_backward_cuda_dispatch.h b/shared/package-files/02/0217e96269b35ecf856e039eb6839d9759618f5ab5398df43a0cfceb9a5ee5ac/_upsample_nearest_exact3d_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3013f1670251ae69db15d9f1f0299763965d34f2 --- /dev/null +++ b/shared/package-files/02/0217e96269b35ecf856e039eb6839d9759618f5ab5398df43a0cfceb9a5ee5ac/_upsample_nearest_exact3d_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 _upsample_nearest_exact3d_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_nearest_exact3d_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_nearest_exact3d_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_nearest_exact3d_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_nearest_exact3d_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_nearest_exact3d_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 cuda +} // namespace at diff --git a/shared/package-files/02/021afcab2215adef14fc95512c72f405b4a86297498e8d8e51e135503e08d6dc/size_statistics.h b/shared/package-files/02/021afcab2215adef14fc95512c72f405b4a86297498e8d8e51e135503e08d6dc/size_statistics.h new file mode 100644 index 0000000000000000000000000000000000000000..ec79b8c4f8b8c07b69ac92e44d053a3fd821befd --- /dev/null +++ b/shared/package-files/02/021afcab2215adef14fc95512c72f405b4a86297498e8d8e51e135503e08d6dc/size_statistics.h @@ -0,0 +1,102 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/util/span.h" +#include "parquet/platform.h" +#include "parquet/type_fwd.h" + +namespace parquet { + +/// A structure for capturing metadata for estimating the unencoded, +/// uncompressed size of data written. This is useful for readers to estimate +/// how much memory is needed to reconstruct data in their memory model and for +/// fine-grained filter push down on nested structures (the histograms contained +/// in this structure can help determine the number of nulls at a particular +/// nesting level and maximum length of lists). +struct PARQUET_EXPORT SizeStatistics { + /// When present, there is expected to be one element corresponding to each + /// definition (i.e. size=max definition+1) where each element + /// represents the number of times the definition level was observed in the + /// data. + /// + /// This field may be omitted (a.k.a. zero-length vector) if max_definition_level + /// is 0 without loss of information. + std::vector definition_level_histogram; + + /// Same as definition_level_histogram except for repetition levels. + /// + /// This field may be omitted (a.k.a. zero-length vector) if max_repetition_level + /// is 0 without loss of information. + std::vector repetition_level_histogram; + + /// The number of physical bytes stored for BYTE_ARRAY data values assuming + /// no encoding. This is exclusive of the bytes needed to store the length of + /// each byte array. In other words, this field is equivalent to the `(size + /// of PLAIN-ENCODING the byte array values) - (4 bytes * number of values + /// written)`. To determine unencoded sizes of other types readers can use + /// schema information multiplied by the number of non-null and null values. + /// The number of null/non-null values can be inferred from the histograms + /// below. + /// + /// For example, if a column chunk is dictionary-encoded with dictionary + /// ["a", "bc", "cde"], and a data page contains the indices [0, 0, 1, 2], + /// then this value for that data page should be 7 (1 + 1 + 2 + 3). + /// + /// This field should only be set for types that use BYTE_ARRAY as their + /// physical type. + std::optional unencoded_byte_array_data_bytes; + + /// \brief Check if the SizeStatistics is set. + bool is_set() const { + return !repetition_level_histogram.empty() || !definition_level_histogram.empty() || + unencoded_byte_array_data_bytes.has_value(); + } + + /// \brief Increment the unencoded byte array data bytes. + void IncrementUnencodedByteArrayDataBytes(int64_t value); + + /// \brief Merge two SizeStatistics. + /// \throws ParquetException if SizeStatistics to merge is not compatible. + void Merge(const SizeStatistics& other); + + /// \brief Validate the SizeStatistics + /// \throws ParquetException if the histograms don't have the right length, + /// or if unencoded_byte_array_data_bytes is present for a non-BYTE_ARRAY column. + void Validate(const ColumnDescriptor* descr) const; + + /// \brief Reset the SizeStatistics to be empty. + void Reset(); + + /// \brief Make an empty SizeStatistics object for specific type. + static std::unique_ptr Make(const ColumnDescriptor* descr); +}; + +PARQUET_EXPORT +std::ostream& operator<<(std::ostream&, const SizeStatistics&); + +PARQUET_EXPORT +void UpdateLevelHistogram(::arrow::util::span levels, + ::arrow::util::span histogram); + +} // namespace parquet diff --git a/shared/package-files/02/021bb387f2f520bdaa862561ad486d626a69305d3e0ebfd485e5c2a6dce6ff0b/mkldnn_rnn_layer_backward_cpu_dispatch.h b/shared/package-files/02/021bb387f2f520bdaa862561ad486d626a69305d3e0ebfd485e5c2a6dce6ff0b/mkldnn_rnn_layer_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d1dbd18bb708c09ec070b4b558418d1090f7a27b --- /dev/null +++ b/shared/package-files/02/021bb387f2f520bdaa862561ad486d626a69305d3e0ebfd485e5c2a6dce6ff0b/mkldnn_rnn_layer_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 mkldnn_rnn_layer_backward(const at::Tensor & input, const at::Tensor & weight1, const at::Tensor & weight2, const at::Tensor & weight3, const at::Tensor & weight4, const at::Tensor & hx_, const at::Tensor & cx_tmp, const at::Tensor & output, const at::Tensor & hy_, const at::Tensor & cy_, const c10::optional & grad_output, const c10::optional & grad_hy, const c10::optional & grad_cy, bool reverse, int64_t mode, int64_t hidden_size, int64_t num_layers, bool has_biases, bool train, bool bidirectional, at::IntArrayRef batch_sizes, bool batch_first, const at::Tensor & workspace); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/02/021e1390d23f09f62a49783b3454ff24e812e665b75d0c72fc2c266781c15c41/quantized_max_pool3d_compositeexplicitautograd_dispatch.h b/shared/package-files/02/021e1390d23f09f62a49783b3454ff24e812e665b75d0c72fc2c266781c15c41/quantized_max_pool3d_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..fe63b83559d48d5140ef44a2604a4cc5c05a8613 --- /dev/null +++ b/shared/package-files/02/021e1390d23f09f62a49783b3454ff24e812e665b75d0c72fc2c266781c15c41/quantized_max_pool3d_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 & quantized_max_pool3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false); +TORCH_API at::Tensor & quantized_max_pool3d_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/02/021e1e444979d8be58ce9a7762466ff33564350d73bf7b38f2de2a075753c59a/_masked_scale_native.h b/shared/package-files/02/021e1e444979d8be58ce9a7762466ff33564350d73bf7b38f2de2a075753c59a/_masked_scale_native.h new file mode 100644 index 0000000000000000000000000000000000000000..497dfcda9d90ab77fa3d6e4583d6ca0e245ecaed --- /dev/null +++ b/shared/package-files/02/021e1e444979d8be58ce9a7762466ff33564350d73bf7b38f2de2a075753c59a/_masked_scale_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 & _masked_scale_out(const at::Tensor & self, const at::Tensor & mask, double scale, at::Tensor & out); +TORCH_API at::Tensor masked_scale_cuda(const at::Tensor & self, const at::Tensor & mask, double scale); +} // namespace native +} // namespace at diff --git a/shared/package-files/02/021e4cf393e96bccd818eb4b3a2cd6d20ce5b63b376f89c3e7aa8579047bf795/backend_cairo.py b/shared/package-files/02/021e4cf393e96bccd818eb4b3a2cd6d20ce5b63b376f89c3e7aa8579047bf795/backend_cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..7409cd35b394344314ec14de768f77b80e512e8c --- /dev/null +++ b/shared/package-files/02/021e4cf393e96bccd818eb4b3a2cd6d20ce5b63b376f89c3e7aa8579047bf795/backend_cairo.py @@ -0,0 +1,529 @@ +""" +A Cairo backend for Matplotlib +============================== +:Author: Steve Chaplin and others + +This backend depends on cairocffi or pycairo. +""" + +import functools +import gzip +import math + +import numpy as np + +try: + import cairo + if cairo.version_info < (1, 14, 0): # Introduced set_device_scale. + raise ImportError(f"Cairo backend requires cairo>=1.14.0, " + f"but only {cairo.version_info} is available") +except ImportError: + try: + import cairocffi as cairo + except ImportError as err: + raise ImportError( + "cairo backend requires that pycairo>=1.14.0 or cairocffi " + "is installed") from err + +from .. import _api, cbook, font_manager +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, + RendererBase) +from matplotlib.font_manager import ttfFontProperty +from matplotlib.path import Path +from matplotlib.transforms import Affine2D + + +def _set_rgba(ctx, color, alpha, forced_alpha): + if len(color) == 3 or forced_alpha: + ctx.set_source_rgba(*color[:3], alpha) + else: + ctx.set_source_rgba(*color) + + +def _append_path(ctx, path, transform, clip=None): + for points, code in path.iter_segments( + transform, remove_nans=True, clip=clip): + if code == Path.MOVETO: + ctx.move_to(*points) + elif code == Path.CLOSEPOLY: + ctx.close_path() + elif code == Path.LINETO: + ctx.line_to(*points) + elif code == Path.CURVE3: + cur = np.asarray(ctx.get_current_point()) + a = points[:2] + b = points[-2:] + ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b) + elif code == Path.CURVE4: + ctx.curve_to(*points) + + +def _cairo_font_args_from_font_prop(prop): + """ + Convert a `.FontProperties` or a `.FontEntry` to arguments that can be + passed to `.Context.select_font_face`. + """ + def attr(field): + try: + return getattr(prop, f"get_{field}")() + except AttributeError: + return getattr(prop, field) + + name = attr("name") + slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}") + weight = attr("weight") + weight = (cairo.FONT_WEIGHT_NORMAL + if font_manager.weight_dict.get(weight, weight) < 550 + else cairo.FONT_WEIGHT_BOLD) + return name, slant, weight + + +class RendererCairo(RendererBase): + def __init__(self, dpi): + self.dpi = dpi + self.gc = GraphicsContextCairo(renderer=self) + self.width = None + self.height = None + self.text_ctx = cairo.Context( + cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)) + super().__init__() + + def set_context(self, ctx): + surface = ctx.get_target() + if hasattr(surface, "get_width") and hasattr(surface, "get_height"): + size = surface.get_width(), surface.get_height() + elif hasattr(surface, "get_extents"): # GTK4 RecordingSurface. + ext = surface.get_extents() + size = ext.width, ext.height + else: # vector surfaces. + ctx.save() + ctx.reset_clip() + rect, *rest = ctx.copy_clip_rectangle_list() + if rest: + raise TypeError("Cannot infer surface size") + _, _, *size = rect + ctx.restore() + self.gc.ctx = ctx + self.width, self.height = size + + @staticmethod + def _fill_and_stroke(ctx, fill_c, alpha, alpha_overrides): + if fill_c is not None: + ctx.save() + _set_rgba(ctx, fill_c, alpha, alpha_overrides) + ctx.fill_preserve() + ctx.restore() + ctx.stroke() + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + ctx = gc.ctx + # Clip the path to the actual rendering extents if it isn't filled. + clip = (ctx.clip_extents() + if rgbFace is None and gc.get_hatch() is None + else None) + transform = (transform + + Affine2D().scale(1, -1).translate(0, self.height)) + ctx.new_path() + _append_path(ctx, path, transform, clip) + if rgbFace is not None: + ctx.save() + _set_rgba(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) + ctx.fill_preserve() + ctx.restore() + hatch_path = gc.get_hatch_path() + if hatch_path: + dpi = int(self.dpi) + hatch_surface = ctx.get_target().create_similar( + cairo.Content.COLOR_ALPHA, dpi, dpi) + hatch_ctx = cairo.Context(hatch_surface) + _append_path(hatch_ctx, hatch_path, + Affine2D().scale(dpi, -dpi).translate(0, dpi), + None) + hatch_ctx.set_line_width(self.points_to_pixels(gc.get_hatch_linewidth())) + hatch_ctx.set_source_rgba(*gc.get_hatch_color()) + hatch_ctx.fill_preserve() + hatch_ctx.stroke() + hatch_pattern = cairo.SurfacePattern(hatch_surface) + hatch_pattern.set_extend(cairo.Extend.REPEAT) + ctx.save() + ctx.set_source(hatch_pattern) + ctx.fill_preserve() + ctx.restore() + ctx.stroke() + + def draw_markers(self, gc, marker_path, marker_trans, path, transform, + rgbFace=None): + # docstring inherited + + ctx = gc.ctx + ctx.new_path() + # Create the path for the marker; it needs to be flipped here already! + _append_path(ctx, marker_path, marker_trans + Affine2D().scale(1, -1)) + marker_path = ctx.copy_path_flat() + + # Figure out whether the path has a fill + x1, y1, x2, y2 = ctx.fill_extents() + if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0: + filled = False + # No fill, just unset this (so we don't try to fill it later on) + rgbFace = None + else: + filled = True + + transform = (transform + + Affine2D().scale(1, -1).translate(0, self.height)) + + ctx.new_path() + for i, (vertices, codes) in enumerate( + path.iter_segments(transform, simplify=False)): + if len(vertices): + x, y = vertices[-2:] + ctx.save() + + # Translate and apply path + ctx.translate(x, y) + ctx.append_path(marker_path) + + ctx.restore() + + # Slower code path if there is a fill; we need to draw + # the fill and stroke for each marker at the same time. + # Also flush out the drawing every once in a while to + # prevent the paths from getting way too long. + if filled or i % 1000 == 0: + self._fill_and_stroke( + ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) + + # Fast path, if there is no fill, draw everything in one step + if not filled: + self._fill_and_stroke( + ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) + + def draw_image(self, gc, x, y, im): + im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1]) + surface = cairo.ImageSurface.create_for_data( + im.ravel().data, cairo.FORMAT_ARGB32, + im.shape[1], im.shape[0], im.shape[1] * 4) + ctx = gc.ctx + y = self.height - y - im.shape[0] + + ctx.save() + ctx.set_source_surface(surface, float(x), float(y)) + ctx.paint() + ctx.restore() + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + # Note: (x, y) are device/display coords, not user-coords, unlike other + # draw_* methods + if ismath: + self._draw_mathtext(gc, x, y, s, prop, angle) + + else: + ctx = gc.ctx + ctx.new_path() + ctx.move_to(x, y) + + ctx.save() + ctx.select_font_face(*_cairo_font_args_from_font_prop(prop)) + ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points())) + opts = cairo.FontOptions() + opts.set_antialias(gc.get_antialiased()) + ctx.set_font_options(opts) + if angle: + ctx.rotate(np.deg2rad(-angle)) + ctx.show_text(s) + ctx.restore() + + def _draw_mathtext(self, gc, x, y, s, prop, angle): + ctx = gc.ctx + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, self.dpi, prop) + + ctx.save() + ctx.translate(x, y) + if angle: + ctx.rotate(np.deg2rad(-angle)) + + for font, fontsize, idx, ox, oy in glyphs: + ctx.new_path() + ctx.move_to(ox, -oy) + ctx.select_font_face( + *_cairo_font_args_from_font_prop(ttfFontProperty(font))) + ctx.set_font_size(self.points_to_pixels(fontsize)) + ctx.show_text(chr(idx)) + + for ox, oy, w, h in rects: + ctx.new_path() + ctx.rectangle(ox, -oy, w, -h) + ctx.set_source_rgb(0, 0, 0) + ctx.fill_preserve() + + ctx.restore() + + def get_canvas_width_height(self): + # docstring inherited + return self.width, self.height + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + + if ismath == 'TeX': + return super().get_text_width_height_descent(s, prop, ismath) + + if ismath: + width, height, descent, *_ = \ + self._text2path.mathtext_parser.parse(s, self.dpi, prop) + return width, height, descent + + ctx = self.text_ctx + # problem - scale remembers last setting and font can become + # enormous causing program to crash + # save/restore prevents the problem + ctx.save() + ctx.select_font_face(*_cairo_font_args_from_font_prop(prop)) + ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points())) + + y_bearing, w, h = ctx.text_extents(s)[1:4] + ctx.restore() + + return w, h, h + y_bearing + + def new_gc(self): + # docstring inherited + self.gc.ctx.save() + # FIXME: The following doesn't properly implement a stack-like behavior + # and relies instead on the (non-guaranteed) fact that artists never + # rely on nesting gc states, so directly resetting the attributes (IOW + # a single-level stack) is enough. + self.gc._alpha = 1 + self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA + self.gc._hatch = None + return self.gc + + def points_to_pixels(self, points): + # docstring inherited + return points / 72 * self.dpi + + +class GraphicsContextCairo(GraphicsContextBase): + _joind = { + 'bevel': cairo.LINE_JOIN_BEVEL, + 'miter': cairo.LINE_JOIN_MITER, + 'round': cairo.LINE_JOIN_ROUND, + } + + _capd = { + 'butt': cairo.LINE_CAP_BUTT, + 'projecting': cairo.LINE_CAP_SQUARE, + 'round': cairo.LINE_CAP_ROUND, + } + + def __init__(self, renderer): + super().__init__() + self.renderer = renderer + + def restore(self): + self.ctx.restore() + + def set_alpha(self, alpha): + super().set_alpha(alpha) + _set_rgba( + self.ctx, self._rgb, self.get_alpha(), self.get_forced_alpha()) + + def set_antialiased(self, b): + self.ctx.set_antialias( + cairo.ANTIALIAS_DEFAULT if b else cairo.ANTIALIAS_NONE) + + def get_antialiased(self): + return self.ctx.get_antialias() + + def set_capstyle(self, cs): + self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs)) + self._capstyle = cs + + def set_clip_rectangle(self, rectangle): + if not rectangle: + return + x, y, w, h = np.round(rectangle.bounds) + ctx = self.ctx + ctx.new_path() + ctx.rectangle(x, self.renderer.height - h - y, w, h) + ctx.clip() + + def set_clip_path(self, path): + if not path: + return + tpath, affine = path.get_transformed_path_and_affine() + ctx = self.ctx + ctx.new_path() + affine = (affine + + Affine2D().scale(1, -1).translate(0, self.renderer.height)) + _append_path(ctx, tpath, affine) + ctx.clip() + + def set_dashes(self, offset, dashes): + self._dashes = offset, dashes + if dashes is None: + self.ctx.set_dash([], 0) # switch dashes off + else: + self.ctx.set_dash( + list(self.renderer.points_to_pixels(np.asarray(dashes))), + offset) + + def set_foreground(self, fg, isRGBA=None): + super().set_foreground(fg, isRGBA) + if len(self._rgb) == 3: + self.ctx.set_source_rgb(*self._rgb) + else: + self.ctx.set_source_rgba(*self._rgb) + + def get_rgb(self): + return self.ctx.get_source().get_rgba()[:3] + + def set_joinstyle(self, js): + self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js)) + self._joinstyle = js + + def set_linewidth(self, w): + self._linewidth = float(w) + self.ctx.set_line_width(self.renderer.points_to_pixels(w)) + + +class _CairoRegion: + def __init__(self, slices, data): + self._slices = slices + self._data = data + + +class FigureCanvasCairo(FigureCanvasBase): + @property + def _renderer(self): + # In theory, _renderer should be set in __init__, but GUI canvas + # subclasses (FigureCanvasFooCairo) don't always interact well with + # multiple inheritance (FigureCanvasFoo inits but doesn't super-init + # FigureCanvasCairo), so initialize it in the getter instead. + if not hasattr(self, "_cached_renderer"): + self._cached_renderer = RendererCairo(self.figure.dpi) + return self._cached_renderer + + def get_renderer(self): + return self._renderer + + def copy_from_bbox(self, bbox): + surface = self._renderer.gc.ctx.get_target() + if not isinstance(surface, cairo.ImageSurface): + raise RuntimeError( + "copy_from_bbox only works when rendering to an ImageSurface") + sw = surface.get_width() + sh = surface.get_height() + x0 = math.ceil(bbox.x0) + x1 = math.floor(bbox.x1) + y0 = math.ceil(sh - bbox.y1) + y1 = math.floor(sh - bbox.y0) + if not (0 <= x0 and x1 <= sw and bbox.x0 <= bbox.x1 + and 0 <= y0 and y1 <= sh and bbox.y0 <= bbox.y1): + raise ValueError("Invalid bbox") + sls = slice(y0, y0 + max(y1 - y0, 0)), slice(x0, x0 + max(x1 - x0, 0)) + data = (np.frombuffer(surface.get_data(), np.uint32) + .reshape((sh, sw))[sls].copy()) + return _CairoRegion(sls, data) + + def restore_region(self, region): + surface = self._renderer.gc.ctx.get_target() + if not isinstance(surface, cairo.ImageSurface): + raise RuntimeError( + "restore_region only works when rendering to an ImageSurface") + surface.flush() + sw = surface.get_width() + sh = surface.get_height() + sly, slx = region._slices + (np.frombuffer(surface.get_data(), np.uint32) + .reshape((sh, sw))[sly, slx]) = region._data + surface.mark_dirty_rectangle( + slx.start, sly.start, slx.stop - slx.start, sly.stop - sly.start) + + def print_png(self, fobj): + self._get_printed_image_surface().write_to_png(fobj) + + def print_rgba(self, fobj): + width, height = self.get_width_height() + buf = self._get_printed_image_surface().get_data() + fobj.write(cbook._premultiplied_argb32_to_unmultiplied_rgba8888( + np.asarray(buf).reshape((width, height, 4)))) + + print_raw = print_rgba + + def _get_printed_image_surface(self): + self._renderer.dpi = self.figure.dpi + width, height = self.get_width_height() + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) + self._renderer.set_context(cairo.Context(surface)) + self.figure.draw(self._renderer) + return surface + + def _save(self, fmt, fobj, *, orientation='portrait'): + # save PDF/PS/SVG + + dpi = 72 + self.figure.dpi = dpi + w_in, h_in = self.figure.get_size_inches() + width_in_points, height_in_points = w_in * dpi, h_in * dpi + + if orientation == 'landscape': + width_in_points, height_in_points = ( + height_in_points, width_in_points) + + if fmt == 'ps': + if not hasattr(cairo, 'PSSurface'): + raise RuntimeError('cairo has not been compiled with PS ' + 'support enabled') + surface = cairo.PSSurface(fobj, width_in_points, height_in_points) + elif fmt == 'pdf': + if not hasattr(cairo, 'PDFSurface'): + raise RuntimeError('cairo has not been compiled with PDF ' + 'support enabled') + surface = cairo.PDFSurface(fobj, width_in_points, height_in_points) + elif fmt in ('svg', 'svgz'): + if not hasattr(cairo, 'SVGSurface'): + raise RuntimeError('cairo has not been compiled with SVG ' + 'support enabled') + if fmt == 'svgz': + if isinstance(fobj, str): + fobj = gzip.GzipFile(fobj, 'wb') + else: + fobj = gzip.GzipFile(None, 'wb', fileobj=fobj) + surface = cairo.SVGSurface(fobj, width_in_points, height_in_points) + else: + raise ValueError(f"Unknown format: {fmt!r}") + + self._renderer.dpi = self.figure.dpi + self._renderer.set_context(cairo.Context(surface)) + ctx = self._renderer.gc.ctx + + if orientation == 'landscape': + ctx.rotate(np.pi / 2) + ctx.translate(0, -height_in_points) + # Perhaps add an '%%Orientation: Landscape' comment? + + self.figure.draw(self._renderer) + + ctx.show_page() + surface.finish() + if fmt == 'svgz': + fobj.close() + + print_pdf = functools.partialmethod(_save, "pdf") + print_ps = functools.partialmethod(_save, "ps") + print_svg = functools.partialmethod(_save, "svg") + print_svgz = functools.partialmethod(_save, "svgz") + + +@_Backend.export +class _BackendCairo(_Backend): + backend_version = cairo.version + FigureCanvas = FigureCanvasCairo + FigureManager = FigureManagerBase diff --git a/shared/package-files/02/021f73fada072546c4f63f8cf18a7181244ce4280b09cc15cc980b2d1176171a/error.py b/shared/package-files/02/021f73fada072546c4f63f8cf18a7181244ce4280b09cc15cc980b2d1176171a/error.py new file mode 100644 index 0000000000000000000000000000000000000000..b796b4dc519512c4825ff539a2e6aa20f4d370d0 --- /dev/null +++ b/shared/package-files/02/021f73fada072546c4f63f8cf18a7181244ce4280b09cc15cc980b2d1176171a/error.py @@ -0,0 +1,75 @@ + +__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] + +class Mark: + + def __init__(self, name, index, line, column, buffer, pointer): + self.name = name + self.index = index + self.line = line + self.column = column + self.buffer = buffer + self.pointer = pointer + + def get_snippet(self, indent=4, max_length=75): + if self.buffer is None: + return None + head = '' + start = self.pointer + while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': + start -= 1 + if self.pointer-start > max_length/2-1: + head = ' ... ' + start += 5 + break + tail = '' + end = self.pointer + while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': + end += 1 + if end-self.pointer > max_length/2-1: + tail = ' ... ' + end -= 5 + break + snippet = self.buffer[start:end] + return ' '*indent + head + snippet + tail + '\n' \ + + ' '*(indent+self.pointer-start+len(head)) + '^' + + def __str__(self): + snippet = self.get_snippet() + where = " in \"%s\", line %d, column %d" \ + % (self.name, self.line+1, self.column+1) + if snippet is not None: + where += ":\n"+snippet + return where + +class YAMLError(Exception): + pass + +class MarkedYAMLError(YAMLError): + + def __init__(self, context=None, context_mark=None, + problem=None, problem_mark=None, note=None): + self.context = context + self.context_mark = context_mark + self.problem = problem + self.problem_mark = problem_mark + self.note = note + + def __str__(self): + lines = [] + if self.context is not None: + lines.append(self.context) + if self.context_mark is not None \ + and (self.problem is None or self.problem_mark is None + or self.context_mark.name != self.problem_mark.name + or self.context_mark.line != self.problem_mark.line + or self.context_mark.column != self.problem_mark.column): + lines.append(str(self.context_mark)) + if self.problem is not None: + lines.append(self.problem) + if self.problem_mark is not None: + lines.append(str(self.problem_mark)) + if self.note is not None: + lines.append(self.note) + return '\n'.join(lines) + diff --git a/shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/ntconsole-35-nti b/shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/ntconsole-35-nti new file mode 100644 index 0000000000000000000000000000000000000000..1544b68f31cd46607720c4af53c481c52013e2be Binary files /dev/null and b/shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/ntconsole-35-nti differ diff --git a/shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/opennt-35-nti b/shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/opennt-35-nti new file mode 100644 index 0000000000000000000000000000000000000000..1544b68f31cd46607720c4af53c481c52013e2be Binary files /dev/null and b/shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/opennt-35-nti differ diff --git a/shared/package-files/02/02244e7d6c5346b313ef92d9b2b04c25322cde4cbd9f5c779d49d7ccaa5920b3/html.py b/shared/package-files/02/02244e7d6c5346b313ef92d9b2b04c25322cde4cbd9f5c779d49d7ccaa5920b3/html.py new file mode 100644 index 0000000000000000000000000000000000000000..794ce77b3b45ec38d9fa58a708939e53bb8ae629 --- /dev/null +++ b/shared/package-files/02/02244e7d6c5346b313ef92d9b2b04c25322cde4cbd9f5c779d49d7ccaa5920b3/html.py @@ -0,0 +1,646 @@ +""" +Module for formatting output data in HTML. +""" +from __future__ import annotations + +from textwrap import dedent +from typing import ( + TYPE_CHECKING, + Any, + Final, + cast, +) + +from pandas._config import get_option + +from pandas._libs import lib + +from pandas import ( + MultiIndex, + option_context, +) + +from pandas.io.common import is_url +from pandas.io.formats.format import ( + DataFrameFormatter, + get_level_lengths, +) +from pandas.io.formats.printing import pprint_thing + +if TYPE_CHECKING: + from collections.abc import ( + Hashable, + Iterable, + Mapping, + ) + + +class HTMLFormatter: + """ + Internal class for formatting output data in html. + This class is intended for shared functionality between + DataFrame.to_html() and DataFrame._repr_html_(). + Any logic in common with other output formatting methods + should ideally be inherited from classes in format.py + and this class responsible for only producing html markup. + """ + + indent_delta: Final = 2 + + def __init__( + self, + formatter: DataFrameFormatter, + classes: str | list[str] | tuple[str, ...] | None = None, + border: int | bool | None = None, + table_id: str | None = None, + render_links: bool = False, + ) -> None: + self.fmt = formatter + self.classes = classes + + self.frame = self.fmt.frame + self.columns = self.fmt.tr_frame.columns + self.elements: list[str] = [] + self.bold_rows = self.fmt.bold_rows + self.escape = self.fmt.escape + self.show_dimensions = self.fmt.show_dimensions + if border is None or border is True: + border = cast(int, get_option("display.html.border")) + elif not border: + border = None + + self.border = border + self.table_id = table_id + self.render_links = render_links + + self.col_space = {} + is_multi_index = isinstance(self.columns, MultiIndex) + for column, value in self.fmt.col_space.items(): + col_space_value = f"{value}px" if isinstance(value, int) else value + self.col_space[column] = col_space_value + # GH 53885: Handling case where column is index + # Flatten the data in the multi index and add in the map + if is_multi_index and isinstance(column, tuple): + for column_index in column: + self.col_space[str(column_index)] = col_space_value + + def to_string(self) -> str: + lines = self.render() + if any(isinstance(x, str) for x in lines): + lines = [str(x) for x in lines] + return "\n".join(lines) + + def render(self) -> list[str]: + self._write_table() + + if self.should_show_dimensions: + by = chr(215) # × # noqa: RUF003 + self.write( + f"

{len(self.frame)} rows {by} {len(self.frame.columns)} columns

" + ) + + return self.elements + + @property + def should_show_dimensions(self) -> bool: + return self.fmt.should_show_dimensions + + @property + def show_row_idx_names(self) -> bool: + return self.fmt.show_row_idx_names + + @property + def show_col_idx_names(self) -> bool: + return self.fmt.show_col_idx_names + + @property + def row_levels(self) -> int: + if self.fmt.index: + # showing (row) index + return self.frame.index.nlevels + elif self.show_col_idx_names: + # see gh-22579 + # Column misalignment also occurs for + # a standard index when the columns index is named. + # If the row index is not displayed a column of + # blank cells need to be included before the DataFrame values. + return 1 + # not showing (row) index + return 0 + + def _get_columns_formatted_values(self) -> Iterable: + return self.columns + + @property + def is_truncated(self) -> bool: + return self.fmt.is_truncated + + @property + def ncols(self) -> int: + return len(self.fmt.tr_frame.columns) + + def write(self, s: Any, indent: int = 0) -> None: + rs = pprint_thing(s) + self.elements.append(" " * indent + rs) + + def write_th( + self, s: Any, header: bool = False, indent: int = 0, tags: str | None = None + ) -> None: + """ + Method for writing a formatted cell. + + If col_space is set on the formatter then that is used for + the value of min-width. + + Parameters + ---------- + s : object + The data to be written inside the cell. + header : bool, default False + Set to True if the is for use inside . This will + cause min-width to be set if there is one. + indent : int, default 0 + The indentation level of the cell. + tags : str, default None + Tags to include in the cell. + + Returns + ------- + A written cell. + """ + col_space = self.col_space.get(s, None) + + if header and col_space is not None: + tags = tags or "" + tags += f'style="min-width: {col_space};"' + + self._write_cell(s, kind="th", indent=indent, tags=tags) + + def write_td(self, s: Any, indent: int = 0, tags: str | None = None) -> None: + self._write_cell(s, kind="td", indent=indent, tags=tags) + + def _write_cell( + self, s: Any, kind: str = "td", indent: int = 0, tags: str | None = None + ) -> None: + if tags is not None: + start_tag = f"<{kind} {tags}>" + else: + start_tag = f"<{kind}>" + + if self.escape: + # escape & first to prevent double escaping of & + esc = {"&": r"&", "<": r"<", ">": r">"} + else: + esc = {} + + rs = pprint_thing(s, escape_chars=esc).strip() + + if self.render_links and is_url(rs): + rs_unescaped = pprint_thing(s, escape_chars={}).strip() + start_tag += f'' + end_a = "" + else: + end_a = "" + + self.write(f"{start_tag}{rs}{end_a}", indent) + + def write_tr( + self, + line: Iterable, + indent: int = 0, + indent_delta: int = 0, + header: bool = False, + align: str | None = None, + tags: dict[int, str] | None = None, + nindex_levels: int = 0, + ) -> None: + if tags is None: + tags = {} + + if align is None: + self.write("", indent) + else: + self.write(f'', indent) + indent += indent_delta + + for i, s in enumerate(line): + val_tag = tags.get(i, None) + if header or (self.bold_rows and i < nindex_levels): + self.write_th(s, indent=indent, header=header, tags=val_tag) + else: + self.write_td(s, indent, tags=val_tag) + + indent -= indent_delta + self.write("", indent) + + def _write_table(self, indent: int = 0) -> None: + _classes = ["dataframe"] # Default class. + use_mathjax = get_option("display.html.use_mathjax") + if not use_mathjax: + _classes.append("tex2jax_ignore") + if self.classes is not None: + if isinstance(self.classes, str): + self.classes = self.classes.split() + if not isinstance(self.classes, (list, tuple)): + raise TypeError( + "classes must be a string, list, " + f"or tuple, not {type(self.classes)}" + ) + _classes.extend(self.classes) + + if self.table_id is None: + id_section = "" + else: + id_section = f' id="{self.table_id}"' + + if self.border is None: + border_attr = "" + else: + border_attr = f' border="{self.border}"' + + self.write( + f'', + indent, + ) + + if self.fmt.header or self.show_row_idx_names: + self._write_header(indent + self.indent_delta) + + self._write_body(indent + self.indent_delta) + + self.write("", indent) + + def _write_col_header(self, indent: int) -> None: + row: list[Hashable] + is_truncated_horizontally = self.fmt.is_truncated_horizontally + if isinstance(self.columns, MultiIndex): + template = 'colspan="{span:d}" halign="left"' + + sentinel: lib.NoDefault | bool + if self.fmt.sparsify: + # GH3547 + sentinel = lib.no_default + else: + sentinel = False + levels = self.columns._format_multi(sparsify=sentinel, include_names=False) + level_lengths = get_level_lengths(levels, sentinel) + inner_lvl = len(level_lengths) - 1 + for lnum, (records, values) in enumerate(zip(level_lengths, levels)): + if is_truncated_horizontally: + # modify the header lines + ins_col = self.fmt.tr_col_num + if self.fmt.sparsify: + recs_new = {} + # Increment tags after ... col. + for tag, span in list(records.items()): + if tag >= ins_col: + recs_new[tag + 1] = span + elif tag + span > ins_col: + recs_new[tag] = span + 1 + if lnum == inner_lvl: + values = ( + values[:ins_col] + ("...",) + values[ins_col:] + ) + else: + # sparse col headers do not receive a ... + values = ( + values[:ins_col] + + (values[ins_col - 1],) + + values[ins_col:] + ) + else: + recs_new[tag] = span + # if ins_col lies between tags, all col headers + # get ... + if tag + span == ins_col: + recs_new[ins_col] = 1 + values = values[:ins_col] + ("...",) + values[ins_col:] + records = recs_new + inner_lvl = len(level_lengths) - 1 + if lnum == inner_lvl: + records[ins_col] = 1 + else: + recs_new = {} + for tag, span in list(records.items()): + if tag >= ins_col: + recs_new[tag + 1] = span + else: + recs_new[tag] = span + recs_new[ins_col] = 1 + records = recs_new + values = values[:ins_col] + ["..."] + values[ins_col:] + + # see gh-22579 + # Column Offset Bug with to_html(index=False) with + # MultiIndex Columns and Index. + # Initially fill row with blank cells before column names. + # TODO: Refactor to remove code duplication with code + # block below for standard columns index. + row = [""] * (self.row_levels - 1) + if self.fmt.index or self.show_col_idx_names: + # see gh-22747 + # If to_html(index_names=False) do not show columns + # index names. + # TODO: Refactor to use _get_column_name_list from + # DataFrameFormatter class and create a + # _get_formatted_column_labels function for code + # parity with DataFrameFormatter class. + if self.fmt.show_index_names: + name = self.columns.names[lnum] + row.append(pprint_thing(name or "")) + else: + row.append("") + + tags = {} + j = len(row) + for i, v in enumerate(values): + if i in records: + if records[i] > 1: + tags[j] = template.format(span=records[i]) + else: + continue + j += 1 + row.append(v) + self.write_tr(row, indent, self.indent_delta, tags=tags, header=True) + else: + # see gh-22579 + # Column misalignment also occurs for + # a standard index when the columns index is named. + # Initially fill row with blank cells before column names. + # TODO: Refactor to remove code duplication with code block + # above for columns MultiIndex. + row = [""] * (self.row_levels - 1) + if self.fmt.index or self.show_col_idx_names: + # see gh-22747 + # If to_html(index_names=False) do not show columns + # index names. + # TODO: Refactor to use _get_column_name_list from + # DataFrameFormatter class. + if self.fmt.show_index_names: + row.append(self.columns.name or "") + else: + row.append("") + row.extend(self._get_columns_formatted_values()) + align = self.fmt.justify + + if is_truncated_horizontally: + ins_col = self.row_levels + self.fmt.tr_col_num + row.insert(ins_col, "...") + + self.write_tr(row, indent, self.indent_delta, header=True, align=align) + + def _write_row_header(self, indent: int) -> None: + is_truncated_horizontally = self.fmt.is_truncated_horizontally + row = [x if x is not None else "" for x in self.frame.index.names] + [""] * ( + self.ncols + (1 if is_truncated_horizontally else 0) + ) + self.write_tr(row, indent, self.indent_delta, header=True) + + def _write_header(self, indent: int) -> None: + self.write("", indent) + + if self.fmt.header: + self._write_col_header(indent + self.indent_delta) + + if self.show_row_idx_names: + self._write_row_header(indent + self.indent_delta) + + self.write("", indent) + + def _get_formatted_values(self) -> dict[int, list[str]]: + with option_context("display.max_colwidth", None): + fmt_values = {i: self.fmt.format_col(i) for i in range(self.ncols)} + return fmt_values + + def _write_body(self, indent: int) -> None: + self.write("", indent) + fmt_values = self._get_formatted_values() + + # write values + if self.fmt.index and isinstance(self.frame.index, MultiIndex): + self._write_hierarchical_rows(fmt_values, indent + self.indent_delta) + else: + self._write_regular_rows(fmt_values, indent + self.indent_delta) + + self.write("", indent) + + def _write_regular_rows( + self, fmt_values: Mapping[int, list[str]], indent: int + ) -> None: + is_truncated_horizontally = self.fmt.is_truncated_horizontally + is_truncated_vertically = self.fmt.is_truncated_vertically + + nrows = len(self.fmt.tr_frame) + + if self.fmt.index: + fmt = self.fmt._get_formatter("__index__") + if fmt is not None: + index_values = self.fmt.tr_frame.index.map(fmt) + else: + # only reached with non-Multi index + index_values = self.fmt.tr_frame.index._format_flat(include_name=False) + + row: list[str] = [] + for i in range(nrows): + if is_truncated_vertically and i == (self.fmt.tr_row_num): + str_sep_row = ["..."] * len(row) + self.write_tr( + str_sep_row, + indent, + self.indent_delta, + tags=None, + nindex_levels=self.row_levels, + ) + + row = [] + if self.fmt.index: + row.append(index_values[i]) + # see gh-22579 + # Column misalignment also occurs for + # a standard index when the columns index is named. + # Add blank cell before data cells. + elif self.show_col_idx_names: + row.append("") + row.extend(fmt_values[j][i] for j in range(self.ncols)) + + if is_truncated_horizontally: + dot_col_ix = self.fmt.tr_col_num + self.row_levels + row.insert(dot_col_ix, "...") + self.write_tr( + row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels + ) + + def _write_hierarchical_rows( + self, fmt_values: Mapping[int, list[str]], indent: int + ) -> None: + template = 'rowspan="{span}" valign="top"' + + is_truncated_horizontally = self.fmt.is_truncated_horizontally + is_truncated_vertically = self.fmt.is_truncated_vertically + frame = self.fmt.tr_frame + nrows = len(frame) + + assert isinstance(frame.index, MultiIndex) + idx_values = frame.index._format_multi(sparsify=False, include_names=False) + idx_values = list(zip(*idx_values)) + + if self.fmt.sparsify: + # GH3547 + sentinel = lib.no_default + levels = frame.index._format_multi(sparsify=sentinel, include_names=False) + + level_lengths = get_level_lengths(levels, sentinel) + inner_lvl = len(level_lengths) - 1 + if is_truncated_vertically: + # Insert ... row and adjust idx_values and + # level_lengths to take this into account. + ins_row = self.fmt.tr_row_num + inserted = False + for lnum, records in enumerate(level_lengths): + rec_new = {} + for tag, span in list(records.items()): + if tag >= ins_row: + rec_new[tag + 1] = span + elif tag + span > ins_row: + rec_new[tag] = span + 1 + + # GH 14882 - Make sure insertion done once + if not inserted: + dot_row = list(idx_values[ins_row - 1]) + dot_row[-1] = "..." + idx_values.insert(ins_row, tuple(dot_row)) + inserted = True + else: + dot_row = list(idx_values[ins_row]) + dot_row[inner_lvl - lnum] = "..." + idx_values[ins_row] = tuple(dot_row) + else: + rec_new[tag] = span + # If ins_row lies between tags, all cols idx cols + # receive ... + if tag + span == ins_row: + rec_new[ins_row] = 1 + if lnum == 0: + idx_values.insert( + ins_row, tuple(["..."] * len(level_lengths)) + ) + + # GH 14882 - Place ... in correct level + elif inserted: + dot_row = list(idx_values[ins_row]) + dot_row[inner_lvl - lnum] = "..." + idx_values[ins_row] = tuple(dot_row) + level_lengths[lnum] = rec_new + + level_lengths[inner_lvl][ins_row] = 1 + for ix_col in fmt_values: + fmt_values[ix_col].insert(ins_row, "...") + nrows += 1 + + for i in range(nrows): + row = [] + tags = {} + + sparse_offset = 0 + j = 0 + for records, v in zip(level_lengths, idx_values[i]): + if i in records: + if records[i] > 1: + tags[j] = template.format(span=records[i]) + else: + sparse_offset += 1 + continue + + j += 1 + row.append(v) + + row.extend(fmt_values[j][i] for j in range(self.ncols)) + if is_truncated_horizontally: + row.insert( + self.row_levels - sparse_offset + self.fmt.tr_col_num, "..." + ) + self.write_tr( + row, + indent, + self.indent_delta, + tags=tags, + nindex_levels=len(levels) - sparse_offset, + ) + else: + row = [] + for i in range(len(frame)): + if is_truncated_vertically and i == (self.fmt.tr_row_num): + str_sep_row = ["..."] * len(row) + self.write_tr( + str_sep_row, + indent, + self.indent_delta, + tags=None, + nindex_levels=self.row_levels, + ) + + idx_values = list( + zip(*frame.index._format_multi(sparsify=False, include_names=False)) + ) + row = [] + row.extend(idx_values[i]) + row.extend(fmt_values[j][i] for j in range(self.ncols)) + if is_truncated_horizontally: + row.insert(self.row_levels + self.fmt.tr_col_num, "...") + self.write_tr( + row, + indent, + self.indent_delta, + tags=None, + nindex_levels=frame.index.nlevels, + ) + + +class NotebookFormatter(HTMLFormatter): + """ + Internal class for formatting output data in html for display in Jupyter + Notebooks. This class is intended for functionality specific to + DataFrame._repr_html_() and DataFrame.to_html(notebook=True) + """ + + def _get_formatted_values(self) -> dict[int, list[str]]: + return {i: self.fmt.format_col(i) for i in range(self.ncols)} + + def _get_columns_formatted_values(self) -> list[str]: + # only reached with non-Multi Index + return self.columns._format_flat(include_name=False) + + def write_style(self) -> None: + # We use the "scoped" attribute here so that the desired + # style properties for the data frame are not then applied + # throughout the entire notebook. + template_first = """\ + """ + template_select = """\ + .dataframe %s { + %s: %s; + }""" + element_props = [ + ("tbody tr th:only-of-type", "vertical-align", "middle"), + ("tbody tr th", "vertical-align", "top"), + ] + if isinstance(self.columns, MultiIndex): + element_props.append(("thead tr th", "text-align", "left")) + if self.show_row_idx_names: + element_props.append( + ("thead tr:last-of-type th", "text-align", "right") + ) + else: + element_props.append(("thead th", "text-align", "right")) + template_mid = "\n\n".join(template_select % t for t in element_props) + template = dedent(f"{template_first}\n{template_mid}\n{template_last}") + self.write(template) + + def render(self) -> list[str]: + self.write("
") + self.write_style() + super().render() + self.write("
") + return self.elements diff --git a/shared/package-files/02/02273b35c63ac179113f9494ebabc086b716ca5c1ef22efcbb69f37de9e7ec56/webbrowser.pyi b/shared/package-files/02/02273b35c63ac179113f9494ebabc086b716ca5c1ef22efcbb69f37de9e7ec56/webbrowser.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e29238ee07ff83ee4b3d0d38ceb046679582e3c4 --- /dev/null +++ b/shared/package-files/02/02273b35c63ac179113f9494ebabc086b716ca5c1ef22efcbb69f37de9e7ec56/webbrowser.pyi @@ -0,0 +1,105 @@ +import sys +from typing import Callable, List, Optional, Sequence, Text, Union + +class Error(Exception): ... + +if sys.version_info >= (3, 7): + def register( + name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., *, preferred: bool = ... + ) -> None: ... + +else: + def register( + name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., update_tryorder: int = ... + ) -> None: ... + +def get(using: Optional[Text] = ...) -> BaseBrowser: ... +def open(url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... +def open_new(url: Text) -> bool: ... +def open_new_tab(url: Text) -> bool: ... + +class BaseBrowser: + args: List[str] + name: str + basename: str + def __init__(self, name: Text = ...) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open_new(self, url: Text) -> bool: ... + def open_new_tab(self, url: Text) -> bool: ... + +class GenericBrowser(BaseBrowser): + args: List[str] + name: str + basename: str + def __init__(self, name: Union[Text, Sequence[Text]]) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class BackgroundBrowser(GenericBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class UnixBrowser(BaseBrowser): + raise_opts: List[str] + background: bool + redirect_stdout: bool + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class Mozilla(UnixBrowser): + raise_opts: List[str] + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + +class Galeon(UnixBrowser): + raise_opts: List[str] + remote_args: List[str] + remote_action: str + remote_action_newwin: str + background: bool + +class Chrome(UnixBrowser): + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + +class Opera(UnixBrowser): + raise_opts: List[str] + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + +class Elinks(UnixBrowser): + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + redirect_stdout: bool + +class Konqueror(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class Grail(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +if sys.platform == "win32": + class WindowsDefault(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +if sys.platform == "darwin": + class MacOSX(BaseBrowser): + name: str + def __init__(self, name: Text) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + class MacOSXOSAScript(BaseBrowser): + def __init__(self, name: Text) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... diff --git a/shared/package-files/02/0229b075bf5ab357492996853541f63a158854155de9990927f58ae6c358f1c5/enums.py b/shared/package-files/02/0229b075bf5ab357492996853541f63a158854155de9990927f58ae6c358f1c5/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..04512072251c429e63ed110cdbafaf4b3cca3412 --- /dev/null +++ b/shared/package-files/02/0229b075bf5ab357492996853541f63a158854155de9990927f58ae6c358f1c5/enums.py @@ -0,0 +1,76 @@ +""" +All of the Enums that are used throughout the chardet package. + +:author: Dan Blanchard (dan.blanchard@gmail.com) +""" + + +class InputState(object): + """ + This enum represents the different states a universal detector can be in. + """ + PURE_ASCII = 0 + ESC_ASCII = 1 + HIGH_BYTE = 2 + + +class LanguageFilter(object): + """ + This enum represents the different language filters we can apply to a + ``UniversalDetector``. + """ + 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(object): + """ + This enum represents the different states a prober can be in. + """ + DETECTING = 0 + FOUND_IT = 1 + NOT_ME = 2 + + +class MachineState(object): + """ + This enum represents the different states a state machine can be in. + """ + START = 0 + ERROR = 1 + ITS_ME = 2 + + +class SequenceLikelihood(object): + """ + 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): + """:returns: The number of likelihood categories in the enum.""" + return 4 + + +class CharacterCategory(object): + """ + 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/02/022bbf749fe8c6af98d555e7b39379bb92b55a78368730a04604620e14c08952/interpolate.py b/shared/package-files/02/022bbf749fe8c6af98d555e7b39379bb92b55a78368730a04604620e14c08952/interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..341d13954c81130cceb8afe070db023a82550e7a --- /dev/null +++ b/shared/package-files/02/022bbf749fe8c6af98d555e7b39379bb92b55a78368730a04604620e14c08952/interpolate.py @@ -0,0 +1,30 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BPoly', + 'BSpline', + 'NdPPoly', + 'PPoly', + 'RectBivariateSpline', + 'RegularGridInterpolator', + 'interp1d', + 'interp2d', + 'interpn', + 'lagrange', + 'make_interp_spline', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="interpolate", + private_modules=["_interpolate", "fitpack2", "_rgi"], + all=__all__, attribute=name) diff --git a/shared/package-files/02/022c9bf5cde1ba759ce9b93a4ed8d0ce33c3242be07a965c8168601f8346d63c/test_rotation.py b/shared/package-files/02/022c9bf5cde1ba759ce9b93a4ed8d0ce33c3242be07a965c8168601f8346d63c/test_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..8ccd215de9322fda7d09ade0e1355756ed0f11bd --- /dev/null +++ b/shared/package-files/02/022c9bf5cde1ba759ce9b93a4ed8d0ce33c3242be07a965c8168601f8346d63c/test_rotation.py @@ -0,0 +1,2188 @@ +import pytest + +import numpy as np +from numpy.testing import assert_equal, assert_array_almost_equal +from numpy.testing import assert_allclose +from scipy.spatial.transform import Rotation, Slerp +from scipy.stats import special_ortho_group +from itertools import permutations + +import pickle +import copy + +def basis_vec(axis): + if axis == 'x': + return [1, 0, 0] + elif axis == 'y': + return [0, 1, 0] + elif axis == 'z': + return [0, 0, 1] + +def test_generic_quat_matrix(): + x = np.array([[3, 4, 0, 0], [5, 12, 0, 0]]) + r = Rotation.from_quat(x) + expected_quat = x / np.array([[5], [13]]) + assert_array_almost_equal(r.as_quat(), expected_quat) + + +def test_from_single_1d_quaternion(): + x = np.array([3, 4, 0, 0]) + r = Rotation.from_quat(x) + expected_quat = x / 5 + assert_array_almost_equal(r.as_quat(), expected_quat) + + +def test_from_single_2d_quaternion(): + x = np.array([[3, 4, 0, 0]]) + r = Rotation.from_quat(x) + expected_quat = x / 5 + assert_array_almost_equal(r.as_quat(), expected_quat) + + +def test_from_quat_scalar_first(): + rng = np.random.RandomState(0) + + r = Rotation.from_quat([1, 0, 0, 0], scalar_first=True) + assert_allclose(r.as_matrix(), np.eye(3), rtol=1e-15, atol=1e-16) + + r = Rotation.from_quat(np.tile([1, 0, 0, 0], (10, 1)), scalar_first=True) + assert_allclose(r.as_matrix(), np.tile(np.eye(3), (10, 1, 1)), + rtol=1e-15, atol=1e-16) + + q = rng.randn(100, 4) + q /= np.linalg.norm(q, axis=1)[:, None] + for qi in q: + r = Rotation.from_quat(qi, scalar_first=True) + assert_allclose(np.roll(r.as_quat(), 1), qi, rtol=1e-15) + + r = Rotation.from_quat(q, scalar_first=True) + assert_allclose(np.roll(r.as_quat(), 1, axis=1), q, rtol=1e-15) + + +def test_as_quat_scalar_first(): + rng = np.random.RandomState(0) + + r = Rotation.from_euler('xyz', np.zeros(3)) + assert_allclose(r.as_quat(scalar_first=True), [1, 0, 0, 0], + rtol=1e-15, atol=1e-16) + + r = Rotation.from_euler('xyz', np.zeros((10, 3))) + assert_allclose(r.as_quat(scalar_first=True), + np.tile([1, 0, 0, 0], (10, 1)), rtol=1e-15, atol=1e-16) + + q = rng.randn(100, 4) + q /= np.linalg.norm(q, axis=1)[:, None] + for qi in q: + r = Rotation.from_quat(qi) + assert_allclose(r.as_quat(scalar_first=True), np.roll(qi, 1), + rtol=1e-15) + + assert_allclose(r.as_quat(canonical=True, scalar_first=True), + np.roll(r.as_quat(canonical=True), 1), + rtol=1e-15) + + r = Rotation.from_quat(q) + assert_allclose(r.as_quat(scalar_first=True), np.roll(q, 1, axis=1), + rtol=1e-15) + + assert_allclose(r.as_quat(canonical=True, scalar_first=True), + np.roll(r.as_quat(canonical=True), 1, axis=1), rtol=1e-15) + + +def test_from_square_quat_matrix(): + # Ensure proper norm array broadcasting + x = np.array([ + [3, 0, 0, 4], + [5, 0, 12, 0], + [0, 0, 0, 1], + [-1, -1, -1, 1], + [0, 0, 0, -1], # Check double cover + [-1, -1, -1, -1] # Check double cover + ]) + r = Rotation.from_quat(x) + expected_quat = x / np.array([[5], [13], [1], [2], [1], [2]]) + assert_array_almost_equal(r.as_quat(), expected_quat) + + +def test_quat_double_to_canonical_single_cover(): + x = np.array([ + [-1, 0, 0, 0], + [0, -1, 0, 0], + [0, 0, -1, 0], + [0, 0, 0, -1], + [-1, -1, -1, -1] + ]) + r = Rotation.from_quat(x) + expected_quat = np.abs(x) / np.linalg.norm(x, axis=1)[:, None] + assert_allclose(r.as_quat(canonical=True), expected_quat) + + +def test_quat_double_cover(): + # See the Rotation.from_quat() docstring for scope of the quaternion + # double cover property. + # Check from_quat and as_quat(canonical=False) + q = np.array([0, 0, 0, -1]) + r = Rotation.from_quat(q) + assert_equal(q, r.as_quat(canonical=False)) + + # Check composition and inverse + q = np.array([1, 0, 0, 1])/np.sqrt(2) # 90 deg rotation about x + r = Rotation.from_quat(q) + r3 = r*r*r + assert_allclose(r.as_quat(canonical=False)*np.sqrt(2), + [1, 0, 0, 1]) + assert_allclose(r.inv().as_quat(canonical=False)*np.sqrt(2), + [-1, 0, 0, 1]) + assert_allclose(r3.as_quat(canonical=False)*np.sqrt(2), + [1, 0, 0, -1]) + assert_allclose(r3.inv().as_quat(canonical=False)*np.sqrt(2), + [-1, 0, 0, -1]) + + # More sanity checks + assert_allclose((r*r.inv()).as_quat(canonical=False), + [0, 0, 0, 1], atol=2e-16) + assert_allclose((r3*r3.inv()).as_quat(canonical=False), + [0, 0, 0, 1], atol=2e-16) + assert_allclose((r*r3).as_quat(canonical=False), + [0, 0, 0, -1], atol=2e-16) + assert_allclose((r.inv()*r3.inv()).as_quat(canonical=False), + [0, 0, 0, -1], atol=2e-16) + + +def test_from_quat_wrong_shape(): + # Wrong shape 1d array + with pytest.raises(ValueError, match='Expected `quat` to have shape'): + Rotation.from_quat(np.array([1, 2, 3])) + + # Wrong shape 2d array + with pytest.raises(ValueError, match='Expected `quat` to have shape'): + Rotation.from_quat(np.array([ + [1, 2, 3, 4, 5], + [4, 5, 6, 7, 8] + ])) + + # 3d array + with pytest.raises(ValueError, match='Expected `quat` to have shape'): + Rotation.from_quat(np.array([ + [[1, 2, 3, 4]], + [[4, 5, 6, 7]] + ])) + + +def test_zero_norms_from_quat(): + x = np.array([ + [3, 4, 0, 0], + [0, 0, 0, 0], + [5, 0, 12, 0] + ]) + with pytest.raises(ValueError): + Rotation.from_quat(x) + + +def test_as_matrix_single_1d_quaternion(): + quat = [0, 0, 0, 1] + mat = Rotation.from_quat(quat).as_matrix() + # mat.shape == (3,3) due to 1d input + assert_array_almost_equal(mat, np.eye(3)) + + +def test_as_matrix_single_2d_quaternion(): + quat = [[0, 0, 1, 1]] + mat = Rotation.from_quat(quat).as_matrix() + assert_equal(mat.shape, (1, 3, 3)) + expected_mat = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + assert_array_almost_equal(mat[0], expected_mat) + + +def test_as_matrix_from_square_input(): + quats = [ + [0, 0, 1, 1], + [0, 1, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, -1] + ] + mat = Rotation.from_quat(quats).as_matrix() + assert_equal(mat.shape, (4, 3, 3)) + + expected0 = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + assert_array_almost_equal(mat[0], expected0) + + expected1 = np.array([ + [0, 0, 1], + [0, 1, 0], + [-1, 0, 0] + ]) + assert_array_almost_equal(mat[1], expected1) + + assert_array_almost_equal(mat[2], np.eye(3)) + assert_array_almost_equal(mat[3], np.eye(3)) + + +def test_as_matrix_from_generic_input(): + quats = [ + [0, 0, 1, 1], + [0, 1, 0, 1], + [1, 2, 3, 4] + ] + mat = Rotation.from_quat(quats).as_matrix() + assert_equal(mat.shape, (3, 3, 3)) + + expected0 = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + assert_array_almost_equal(mat[0], expected0) + + expected1 = np.array([ + [0, 0, 1], + [0, 1, 0], + [-1, 0, 0] + ]) + assert_array_almost_equal(mat[1], expected1) + + expected2 = np.array([ + [0.4, -2, 2.2], + [2.8, 1, 0.4], + [-1, 2, 2] + ]) / 3 + assert_array_almost_equal(mat[2], expected2) + + +def test_from_single_2d_matrix(): + mat = [ + [0, 0, 1], + [1, 0, 0], + [0, 1, 0] + ] + expected_quat = [0.5, 0.5, 0.5, 0.5] + assert_array_almost_equal( + Rotation.from_matrix(mat).as_quat(), + expected_quat) + + +def test_from_single_3d_matrix(): + mat = np.array([ + [0, 0, 1], + [1, 0, 0], + [0, 1, 0] + ]).reshape((1, 3, 3)) + expected_quat = np.array([0.5, 0.5, 0.5, 0.5]).reshape((1, 4)) + assert_array_almost_equal( + Rotation.from_matrix(mat).as_quat(), + expected_quat) + + +def test_from_matrix_calculation(): + expected_quat = np.array([1, 1, 6, 1]) / np.sqrt(39) + mat = np.array([ + [-0.8974359, -0.2564103, 0.3589744], + [0.3589744, -0.8974359, 0.2564103], + [0.2564103, 0.3589744, 0.8974359] + ]) + assert_array_almost_equal( + Rotation.from_matrix(mat).as_quat(), + expected_quat) + assert_array_almost_equal( + Rotation.from_matrix(mat.reshape((1, 3, 3))).as_quat(), + expected_quat.reshape((1, 4))) + + +def test_matrix_calculation_pipeline(): + mat = special_ortho_group.rvs(3, size=10, random_state=0) + assert_array_almost_equal(Rotation.from_matrix(mat).as_matrix(), mat) + + +def test_from_matrix_ortho_output(): + rnd = np.random.RandomState(0) + mat = rnd.random_sample((100, 3, 3)) + dets = np.linalg.det(mat) + for i in range(len(dets)): + # Make sure we have a right-handed rotation matrix + if dets[i] < 0: + mat[i] = -mat[i] + ortho_mat = Rotation.from_matrix(mat).as_matrix() + + mult_result = np.einsum('...ij,...jk->...ik', ortho_mat, + ortho_mat.transpose((0, 2, 1))) + + eye3d = np.zeros((100, 3, 3)) + for i in range(3): + eye3d[:, i, i] = 1.0 + + assert_array_almost_equal(mult_result, eye3d) + + +def test_from_matrix_normalize(): + mat = np.array([ + [1, 1, 0], + [0, 1, 0], + [0, 0, 1]]) + expected = np.array([[ 0.894427, 0.447214, 0.0], + [-0.447214, 0.894427, 0.0], + [ 0.0, 0.0, 1.0]]) + assert_allclose(Rotation.from_matrix(mat).as_matrix(), expected, atol=1e-6) + + mat = np.array([ + [0, -0.5, 0 ], + [0.5, 0 , 0 ], + [0, 0 , 0.5]]) + expected = np.array([[ 0, -1, 0], + [ 1, 0, 0], + [ 0, 0, 1]]) + assert_allclose(Rotation.from_matrix(mat).as_matrix(), expected, atol=1e-6) + + +def test_from_matrix_non_positive_determinant(): + mat = np.eye(3) + mat[0, 0] = 0 + with pytest.raises(ValueError, match='Non-positive determinant'): + Rotation.from_matrix(mat) + + mat[0, 0] = -1 + with pytest.raises(ValueError, match='Non-positive determinant'): + Rotation.from_matrix(mat) + + +def test_from_1d_single_rotvec(): + rotvec = [1, 0, 0] + expected_quat = np.array([0.4794255, 0, 0, 0.8775826]) + result = Rotation.from_rotvec(rotvec) + assert_array_almost_equal(result.as_quat(), expected_quat) + + +def test_from_2d_single_rotvec(): + rotvec = [[1, 0, 0]] + expected_quat = np.array([[0.4794255, 0, 0, 0.8775826]]) + result = Rotation.from_rotvec(rotvec) + assert_array_almost_equal(result.as_quat(), expected_quat) + + +def test_from_generic_rotvec(): + rotvec = [ + [1, 2, 2], + [1, -1, 0.5], + [0, 0, 0] + ] + expected_quat = np.array([ + [0.3324983, 0.6649967, 0.6649967, 0.0707372], + [0.4544258, -0.4544258, 0.2272129, 0.7316889], + [0, 0, 0, 1] + ]) + assert_array_almost_equal( + Rotation.from_rotvec(rotvec).as_quat(), + expected_quat) + + +def test_from_rotvec_small_angle(): + rotvec = np.array([ + [5e-4 / np.sqrt(3), -5e-4 / np.sqrt(3), 5e-4 / np.sqrt(3)], + [0.2, 0.3, 0.4], + [0, 0, 0] + ]) + + quat = Rotation.from_rotvec(rotvec).as_quat() + # cos(theta/2) ~~ 1 for small theta + assert_allclose(quat[0, 3], 1) + # sin(theta/2) / theta ~~ 0.5 for small theta + assert_allclose(quat[0, :3], rotvec[0] * 0.5) + + assert_allclose(quat[1, 3], 0.9639685) + assert_allclose( + quat[1, :3], + np.array([ + 0.09879603932153465, + 0.14819405898230198, + 0.19759207864306931 + ])) + + assert_equal(quat[2], np.array([0, 0, 0, 1])) + + +def test_degrees_from_rotvec(): + rotvec1 = [1.0 / np.cbrt(3), 1.0 / np.cbrt(3), 1.0 / np.cbrt(3)] + rot1 = Rotation.from_rotvec(rotvec1, degrees=True) + quat1 = rot1.as_quat() + + rotvec2 = np.deg2rad(rotvec1) + rot2 = Rotation.from_rotvec(rotvec2) + quat2 = rot2.as_quat() + + assert_allclose(quat1, quat2) + + +def test_malformed_1d_from_rotvec(): + with pytest.raises(ValueError, match='Expected `rot_vec` to have shape'): + Rotation.from_rotvec([1, 2]) + + +def test_malformed_2d_from_rotvec(): + with pytest.raises(ValueError, match='Expected `rot_vec` to have shape'): + Rotation.from_rotvec([ + [1, 2, 3, 4], + [5, 6, 7, 8] + ]) + + +def test_as_generic_rotvec(): + quat = np.array([ + [1, 2, -1, 0.5], + [1, -1, 1, 0.0003], + [0, 0, 0, 1] + ]) + quat /= np.linalg.norm(quat, axis=1)[:, None] + + rotvec = Rotation.from_quat(quat).as_rotvec() + angle = np.linalg.norm(rotvec, axis=1) + + assert_allclose(quat[:, 3], np.cos(angle/2)) + assert_allclose(np.cross(rotvec, quat[:, :3]), np.zeros((3, 3))) + + +def test_as_rotvec_single_1d_input(): + quat = np.array([1, 2, -3, 2]) + expected_rotvec = np.array([0.5772381, 1.1544763, -1.7317144]) + + actual_rotvec = Rotation.from_quat(quat).as_rotvec() + + assert_equal(actual_rotvec.shape, (3,)) + assert_allclose(actual_rotvec, expected_rotvec) + + +def test_as_rotvec_single_2d_input(): + quat = np.array([[1, 2, -3, 2]]) + expected_rotvec = np.array([[0.5772381, 1.1544763, -1.7317144]]) + + actual_rotvec = Rotation.from_quat(quat).as_rotvec() + + assert_equal(actual_rotvec.shape, (1, 3)) + assert_allclose(actual_rotvec, expected_rotvec) + + +def test_as_rotvec_degrees(): + # x->y, y->z, z->x + mat = [[0, 0, 1], [1, 0, 0], [0, 1, 0]] + rot = Rotation.from_matrix(mat) + rotvec = rot.as_rotvec(degrees=True) + angle = np.linalg.norm(rotvec) + assert_allclose(angle, 120.0) + assert_allclose(rotvec[0], rotvec[1]) + assert_allclose(rotvec[1], rotvec[2]) + + +def test_rotvec_calc_pipeline(): + # Include small angles + rotvec = np.array([ + [0, 0, 0], + [1, -1, 2], + [-3e-4, 3.5e-4, 7.5e-5] + ]) + assert_allclose(Rotation.from_rotvec(rotvec).as_rotvec(), rotvec) + assert_allclose(Rotation.from_rotvec(rotvec, degrees=True).as_rotvec(degrees=True), + rotvec) + + +def test_from_1d_single_mrp(): + mrp = [0, 0, 1.0] + expected_quat = np.array([0, 0, 1, 0]) + result = Rotation.from_mrp(mrp) + assert_array_almost_equal(result.as_quat(), expected_quat) + + +def test_from_2d_single_mrp(): + mrp = [[0, 0, 1.0]] + expected_quat = np.array([[0, 0, 1, 0]]) + result = Rotation.from_mrp(mrp) + assert_array_almost_equal(result.as_quat(), expected_quat) + + +def test_from_generic_mrp(): + mrp = np.array([ + [1, 2, 2], + [1, -1, 0.5], + [0, 0, 0]]) + expected_quat = np.array([ + [0.2, 0.4, 0.4, -0.8], + [0.61538462, -0.61538462, 0.30769231, -0.38461538], + [0, 0, 0, 1]]) + assert_array_almost_equal(Rotation.from_mrp(mrp).as_quat(), expected_quat) + + +def test_malformed_1d_from_mrp(): + with pytest.raises(ValueError, match='Expected `mrp` to have shape'): + Rotation.from_mrp([1, 2]) + + +def test_malformed_2d_from_mrp(): + with pytest.raises(ValueError, match='Expected `mrp` to have shape'): + Rotation.from_mrp([ + [1, 2, 3, 4], + [5, 6, 7, 8] + ]) + + +def test_as_generic_mrp(): + quat = np.array([ + [1, 2, -1, 0.5], + [1, -1, 1, 0.0003], + [0, 0, 0, 1]]) + quat /= np.linalg.norm(quat, axis=1)[:, None] + + expected_mrp = np.array([ + [0.33333333, 0.66666667, -0.33333333], + [0.57725028, -0.57725028, 0.57725028], + [0, 0, 0]]) + assert_array_almost_equal(Rotation.from_quat(quat).as_mrp(), expected_mrp) + +def test_past_180_degree_rotation(): + # ensure that a > 180 degree rotation is returned as a <180 rotation in MRPs + # in this case 270 should be returned as -90 + expected_mrp = np.array([-np.tan(np.pi/2/4), 0.0, 0]) + assert_array_almost_equal( + Rotation.from_euler('xyz', [270, 0, 0], degrees=True).as_mrp(), + expected_mrp + ) + + +def test_as_mrp_single_1d_input(): + quat = np.array([1, 2, -3, 2]) + expected_mrp = np.array([0.16018862, 0.32037724, -0.48056586]) + + actual_mrp = Rotation.from_quat(quat).as_mrp() + + assert_equal(actual_mrp.shape, (3,)) + assert_allclose(actual_mrp, expected_mrp) + + +def test_as_mrp_single_2d_input(): + quat = np.array([[1, 2, -3, 2]]) + expected_mrp = np.array([[0.16018862, 0.32037724, -0.48056586]]) + + actual_mrp = Rotation.from_quat(quat).as_mrp() + + assert_equal(actual_mrp.shape, (1, 3)) + assert_allclose(actual_mrp, expected_mrp) + + +def test_mrp_calc_pipeline(): + actual_mrp = np.array([ + [0, 0, 0], + [1, -1, 2], + [0.41421356, 0, 0], + [0.1, 0.2, 0.1]]) + expected_mrp = np.array([ + [0, 0, 0], + [-0.16666667, 0.16666667, -0.33333333], + [0.41421356, 0, 0], + [0.1, 0.2, 0.1]]) + assert_allclose(Rotation.from_mrp(actual_mrp).as_mrp(), expected_mrp) + + +def test_from_euler_single_rotation(): + quat = Rotation.from_euler('z', 90, degrees=True).as_quat() + expected_quat = np.array([0, 0, 1, 1]) / np.sqrt(2) + assert_allclose(quat, expected_quat) + + +def test_single_intrinsic_extrinsic_rotation(): + extrinsic = Rotation.from_euler('z', 90, degrees=True).as_matrix() + intrinsic = Rotation.from_euler('Z', 90, degrees=True).as_matrix() + assert_allclose(extrinsic, intrinsic) + + +def test_from_euler_rotation_order(): + # Intrinsic rotation is same as extrinsic with order reversed + rnd = np.random.RandomState(0) + a = rnd.randint(low=0, high=180, size=(6, 3)) + b = a[:, ::-1] + x = Rotation.from_euler('xyz', a, degrees=True).as_quat() + y = Rotation.from_euler('ZYX', b, degrees=True).as_quat() + assert_allclose(x, y) + + +def test_from_euler_elementary_extrinsic_rotation(): + # Simple test to check if extrinsic rotations are implemented correctly + mat = Rotation.from_euler('zx', [90, 90], degrees=True).as_matrix() + expected_mat = np.array([ + [0, -1, 0], + [0, 0, -1], + [1, 0, 0] + ]) + assert_array_almost_equal(mat, expected_mat) + + +def test_from_euler_intrinsic_rotation_312(): + angles = [ + [30, 60, 45], + [30, 60, 30], + [45, 30, 60] + ] + mat = Rotation.from_euler('ZXY', angles, degrees=True).as_matrix() + + assert_array_almost_equal(mat[0], np.array([ + [0.3061862, -0.2500000, 0.9185587], + [0.8838835, 0.4330127, -0.1767767], + [-0.3535534, 0.8660254, 0.3535534] + ])) + + assert_array_almost_equal(mat[1], np.array([ + [0.5334936, -0.2500000, 0.8080127], + [0.8080127, 0.4330127, -0.3995191], + [-0.2500000, 0.8660254, 0.4330127] + ])) + + assert_array_almost_equal(mat[2], np.array([ + [0.0473672, -0.6123725, 0.7891491], + [0.6597396, 0.6123725, 0.4355958], + [-0.7500000, 0.5000000, 0.4330127] + ])) + + +def test_from_euler_intrinsic_rotation_313(): + angles = [ + [30, 60, 45], + [30, 60, 30], + [45, 30, 60] + ] + mat = Rotation.from_euler('ZXZ', angles, degrees=True).as_matrix() + + assert_array_almost_equal(mat[0], np.array([ + [0.43559574, -0.78914913, 0.4330127], + [0.65973961, -0.04736717, -0.750000], + [0.61237244, 0.61237244, 0.500000] + ])) + + assert_array_almost_equal(mat[1], np.array([ + [0.6250000, -0.64951905, 0.4330127], + [0.64951905, 0.1250000, -0.750000], + [0.4330127, 0.750000, 0.500000] + ])) + + assert_array_almost_equal(mat[2], np.array([ + [-0.1767767, -0.91855865, 0.35355339], + [0.88388348, -0.30618622, -0.35355339], + [0.4330127, 0.25000000, 0.8660254] + ])) + + +def test_from_euler_extrinsic_rotation_312(): + angles = [ + [30, 60, 45], + [30, 60, 30], + [45, 30, 60] + ] + mat = Rotation.from_euler('zxy', angles, degrees=True).as_matrix() + + assert_array_almost_equal(mat[0], np.array([ + [0.91855865, 0.1767767, 0.35355339], + [0.25000000, 0.4330127, -0.8660254], + [-0.30618622, 0.88388348, 0.35355339] + ])) + + assert_array_almost_equal(mat[1], np.array([ + [0.96650635, -0.0580127, 0.2500000], + [0.25000000, 0.4330127, -0.8660254], + [-0.0580127, 0.89951905, 0.4330127] + ])) + + assert_array_almost_equal(mat[2], np.array([ + [0.65973961, -0.04736717, 0.7500000], + [0.61237244, 0.61237244, -0.5000000], + [-0.43559574, 0.78914913, 0.4330127] + ])) + + +def test_from_euler_extrinsic_rotation_313(): + angles = [ + [30, 60, 45], + [30, 60, 30], + [45, 30, 60] + ] + mat = Rotation.from_euler('zxz', angles, degrees=True).as_matrix() + + assert_array_almost_equal(mat[0], np.array([ + [0.43559574, -0.65973961, 0.61237244], + [0.78914913, -0.04736717, -0.61237244], + [0.4330127, 0.75000000, 0.500000] + ])) + + assert_array_almost_equal(mat[1], np.array([ + [0.62500000, -0.64951905, 0.4330127], + [0.64951905, 0.12500000, -0.750000], + [0.4330127, 0.75000000, 0.500000] + ])) + + assert_array_almost_equal(mat[2], np.array([ + [-0.1767767, -0.88388348, 0.4330127], + [0.91855865, -0.30618622, -0.250000], + [0.35355339, 0.35355339, 0.8660254] + ])) + + +@pytest.mark.parametrize("seq_tuple", permutations("xyz")) +@pytest.mark.parametrize("intrinsic", (False, True)) +def test_as_euler_asymmetric_axes(seq_tuple, intrinsic): + # helper function for mean error tests + def test_stats(error, mean_max, rms_max): + mean = np.mean(error, axis=0) + std = np.std(error, axis=0) + rms = np.hypot(mean, std) + assert np.all(np.abs(mean) < mean_max) + assert np.all(rms < rms_max) + + rnd = np.random.RandomState(0) + n = 1000 + angles = np.empty((n, 3)) + angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + angles[:, 1] = rnd.uniform(low=-np.pi / 2, high=np.pi / 2, size=(n,)) + angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + + seq = "".join(seq_tuple) + if intrinsic: + # Extrinsic rotation (wrt to global world) at lower case + # intrinsic (WRT the object itself) lower case. + seq = seq.upper() + rotation = Rotation.from_euler(seq, angles) + angles_quat = rotation.as_euler(seq) + angles_mat = rotation._as_euler_from_matrix(seq) + assert_allclose(angles, angles_quat, atol=0, rtol=1e-12) + assert_allclose(angles, angles_mat, atol=0, rtol=1e-12) + test_stats(angles_quat - angles, 1e-15, 1e-14) + test_stats(angles_mat - angles, 1e-15, 1e-14) + + + +@pytest.mark.parametrize("seq_tuple", permutations("xyz")) +@pytest.mark.parametrize("intrinsic", (False, True)) +def test_as_euler_symmetric_axes(seq_tuple, intrinsic): + # helper function for mean error tests + def test_stats(error, mean_max, rms_max): + mean = np.mean(error, axis=0) + std = np.std(error, axis=0) + rms = np.hypot(mean, std) + assert np.all(np.abs(mean) < mean_max) + assert np.all(rms < rms_max) + + rnd = np.random.RandomState(0) + n = 1000 + angles = np.empty((n, 3)) + angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + angles[:, 1] = rnd.uniform(low=0, high=np.pi, size=(n,)) + angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + + # Rotation of the form A/B/A are rotation around symmetric axes + seq = "".join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) + if intrinsic: + seq = seq.upper() + rotation = Rotation.from_euler(seq, angles) + angles_quat = rotation.as_euler(seq) + angles_mat = rotation._as_euler_from_matrix(seq) + assert_allclose(angles, angles_quat, atol=0, rtol=1e-13) + assert_allclose(angles, angles_mat, atol=0, rtol=1e-9) + test_stats(angles_quat - angles, 1e-16, 1e-14) + test_stats(angles_mat - angles, 1e-15, 1e-13) + + +@pytest.mark.thread_unsafe +@pytest.mark.parametrize("seq_tuple", permutations("xyz")) +@pytest.mark.parametrize("intrinsic", (False, True)) +def test_as_euler_degenerate_asymmetric_axes(seq_tuple, intrinsic): + # Since we cannot check for angle equality, we check for rotation matrix + # equality + angles = np.array([ + [45, 90, 35], + [35, -90, 20], + [35, 90, 25], + [25, -90, 15]]) + + seq = "".join(seq_tuple) + if intrinsic: + # Extrinsic rotation (wrt to global world) at lower case + # Intrinsic (WRT the object itself) upper case. + seq = seq.upper() + rotation = Rotation.from_euler(seq, angles, degrees=True) + mat_expected = rotation.as_matrix() + + with pytest.warns(UserWarning, match="Gimbal lock"): + angle_estimates = rotation.as_euler(seq, degrees=True) + mat_estimated = Rotation.from_euler(seq, angle_estimates, degrees=True).as_matrix() + + assert_array_almost_equal(mat_expected, mat_estimated) + + +@pytest.mark.thread_unsafe +@pytest.mark.parametrize("seq_tuple", permutations("xyz")) +@pytest.mark.parametrize("intrinsic", (False, True)) +def test_as_euler_degenerate_symmetric_axes(seq_tuple, intrinsic): + # Since we cannot check for angle equality, we check for rotation matrix + # equality + angles = np.array([ + [15, 0, 60], + [35, 0, 75], + [60, 180, 35], + [15, -180, 25]]) + + # Rotation of the form A/B/A are rotation around symmetric axes + seq = "".join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) + if intrinsic: + # Extrinsic rotation (wrt to global world) at lower case + # Intrinsic (WRT the object itself) upper case. + seq = seq.upper() + rotation = Rotation.from_euler(seq, angles, degrees=True) + mat_expected = rotation.as_matrix() + + with pytest.warns(UserWarning, match="Gimbal lock"): + angle_estimates = rotation.as_euler(seq, degrees=True) + mat_estimated = Rotation.from_euler(seq, angle_estimates, degrees=True).as_matrix() + + assert_array_almost_equal(mat_expected, mat_estimated) + + +@pytest.mark.thread_unsafe +@pytest.mark.parametrize("seq_tuple", permutations("xyz")) +@pytest.mark.parametrize("intrinsic", (False, True)) +def test_as_euler_degenerate_compare_algorithms(seq_tuple, intrinsic): + # this test makes sure that both algorithms are doing the same choices + # in degenerate cases + + # asymmetric axes + angles = np.array([ + [45, 90, 35], + [35, -90, 20], + [35, 90, 25], + [25, -90, 15]]) + + seq = "".join(seq_tuple) + if intrinsic: + # Extrinsic rotation (wrt to global world at lower case + # Intrinsic (WRT the object itself) upper case. + seq = seq.upper() + + rot = Rotation.from_euler(seq, angles, degrees=True) + with pytest.warns(UserWarning, match="Gimbal lock"): + estimates_matrix = rot._as_euler_from_matrix(seq, degrees=True) + with pytest.warns(UserWarning, match="Gimbal lock"): + estimates_quat = rot.as_euler(seq, degrees=True) + assert_allclose( + estimates_matrix[:, [0, 2]], estimates_quat[:, [0, 2]], atol=0, rtol=1e-12 + ) + assert_allclose(estimates_matrix[:, 1], estimates_quat[:, 1], atol=0, rtol=1e-7) + + # symmetric axes + # Absolute error tolerance must be looser to directly compare the results + # from both algorithms, because of numerical loss of precision for the + # method _as_euler_from_matrix near a zero angle value + + angles = np.array([ + [15, 0, 60], + [35, 0, 75], + [60, 180, 35], + [15, -180, 25]]) + + idx = angles[:, 1] == 0 # find problematic angles indices + + # Rotation of the form A/B/A are rotation around symmetric axes + seq = "".join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) + if intrinsic: + # Extrinsic rotation (wrt to global world) at lower case + # Intrinsic (WRT the object itself) upper case. + seq = seq.upper() + + rot = Rotation.from_euler(seq, angles, degrees=True) + with pytest.warns(UserWarning, match="Gimbal lock"): + estimates_matrix = rot._as_euler_from_matrix(seq, degrees=True) + with pytest.warns(UserWarning, match="Gimbal lock"): + estimates_quat = rot.as_euler(seq, degrees=True) + assert_allclose( + estimates_matrix[:, [0, 2]], estimates_quat[:, [0, 2]], atol=0, rtol=1e-12 + ) + + assert_allclose( + estimates_matrix[~idx, 1], estimates_quat[~idx, 1], atol=0, rtol=1e-7 + ) + + assert_allclose( + estimates_matrix[idx, 1], estimates_quat[idx, 1], atol=1e-6 + ) # problematic, angles[1] = 0 + + +def test_inv(): + rnd = np.random.RandomState(0) + n = 10 + # preserve use of old random_state during SPEC 7 transition + p = Rotation.random(num=n, random_state=rnd) + q = p.inv() + + p_mat = p.as_matrix() + q_mat = q.as_matrix() + result1 = np.einsum('...ij,...jk->...ik', p_mat, q_mat) + result2 = np.einsum('...ij,...jk->...ik', q_mat, p_mat) + + eye3d = np.empty((n, 3, 3)) + eye3d[:] = np.eye(3) + + assert_array_almost_equal(result1, eye3d) + assert_array_almost_equal(result2, eye3d) + + +def test_inv_single_rotation(): + rng = np.random.default_rng(146972845698875399755764481408308808739) + p = Rotation.random(rng=rng) + q = p.inv() + + p_mat = p.as_matrix() + q_mat = q.as_matrix() + res1 = np.dot(p_mat, q_mat) + res2 = np.dot(q_mat, p_mat) + + eye = np.eye(3) + + assert_array_almost_equal(res1, eye) + assert_array_almost_equal(res2, eye) + + x = Rotation.random(num=1, rng=rng) + y = x.inv() + + x_matrix = x.as_matrix() + y_matrix = y.as_matrix() + result1 = np.einsum('...ij,...jk->...ik', x_matrix, y_matrix) + result2 = np.einsum('...ij,...jk->...ik', y_matrix, x_matrix) + + eye3d = np.empty((1, 3, 3)) + eye3d[:] = np.eye(3) + + assert_array_almost_equal(result1, eye3d) + assert_array_almost_equal(result2, eye3d) + + +def test_identity_magnitude(): + n = 10 + assert_allclose(Rotation.identity(n).magnitude(), 0) + assert_allclose(Rotation.identity(n).inv().magnitude(), 0) + + +def test_single_identity_magnitude(): + assert Rotation.identity().magnitude() == 0 + assert Rotation.identity().inv().magnitude() == 0 + + +def test_identity_invariance(): + n = 10 + p = Rotation.random(n, rng=0) + + result = p * Rotation.identity(n) + assert_array_almost_equal(p.as_quat(), result.as_quat()) + + result = result * p.inv() + assert_array_almost_equal(result.magnitude(), np.zeros(n)) + + +def test_single_identity_invariance(): + n = 10 + p = Rotation.random(n, rng=0) + + result = p * Rotation.identity() + assert_array_almost_equal(p.as_quat(), result.as_quat()) + + result = result * p.inv() + assert_array_almost_equal(result.magnitude(), np.zeros(n)) + + +def test_magnitude(): + r = Rotation.from_quat(np.eye(4)) + result = r.magnitude() + assert_array_almost_equal(result, [np.pi, np.pi, np.pi, 0]) + + r = Rotation.from_quat(-np.eye(4)) + result = r.magnitude() + assert_array_almost_equal(result, [np.pi, np.pi, np.pi, 0]) + + +def test_magnitude_single_rotation(): + r = Rotation.from_quat(np.eye(4)) + result1 = r[0].magnitude() + assert_allclose(result1, np.pi) + + result2 = r[3].magnitude() + assert_allclose(result2, 0) + + +def test_approx_equal(): + rng = np.random.default_rng(146972845698875399755764481408308808739) + p = Rotation.random(10, rng=rng) + q = Rotation.random(10, rng=rng) + r = p * q.inv() + r_mag = r.magnitude() + atol = np.median(r_mag) # ensure we get mix of Trues and Falses + assert_equal(p.approx_equal(q, atol), (r_mag < atol)) + + +@pytest.mark.thread_unsafe +def test_approx_equal_single_rotation(): + # also tests passing single argument to approx_equal + p = Rotation.from_rotvec([0, 0, 1e-9]) # less than default atol of 1e-8 + q = Rotation.from_quat(np.eye(4)) + assert p.approx_equal(q[3]) + assert not p.approx_equal(q[0]) + + # test passing atol and using degrees + assert not p.approx_equal(q[3], atol=1e-10) + assert not p.approx_equal(q[3], atol=1e-8, degrees=True) + with pytest.warns(UserWarning, match="atol must be set"): + assert p.approx_equal(q[3], degrees=True) + + +def test_mean(): + axes = np.concatenate((-np.eye(3), np.eye(3))) + thetas = np.linspace(0, np.pi / 2, 100) + for t in thetas: + r = Rotation.from_rotvec(t * axes) + assert_allclose(r.mean().magnitude(), 0, atol=1E-10) + + +def test_weighted_mean(): + # test that doubling a weight is equivalent to including a rotation twice. + axes = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0]]) + thetas = np.linspace(0, np.pi / 2, 100) + for t in thetas: + rw = Rotation.from_rotvec(t * axes[:2]) + mw = rw.mean(weights=[1, 2]) + + r = Rotation.from_rotvec(t * axes) + m = r.mean() + assert_allclose((m * mw.inv()).magnitude(), 0, atol=1E-10) + + +def test_mean_invalid_weights(): + with pytest.raises(ValueError, match="non-negative"): + r = Rotation.from_quat(np.eye(4)) + r.mean(weights=-np.ones(4)) + + +def test_reduction_no_indices(): + result = Rotation.identity().reduce(return_indices=False) + assert isinstance(result, Rotation) + + +def test_reduction_none_indices(): + result = Rotation.identity().reduce(return_indices=True) + assert type(result) is tuple + assert len(result) == 3 + + reduced, left_best, right_best = result + assert left_best is None + assert right_best is None + + +def test_reduction_scalar_calculation(): + rng = np.random.default_rng(146972845698875399755764481408308808739) + l = Rotation.random(5, rng=rng) + r = Rotation.random(10, rng=rng) + p = Rotation.random(7, rng=rng) + reduced, left_best, right_best = p.reduce(l, r, return_indices=True) + + # Loop implementation of the vectorized calculation in Rotation.reduce + scalars = np.zeros((len(l), len(p), len(r))) + for i, li in enumerate(l): + for j, pj in enumerate(p): + for k, rk in enumerate(r): + scalars[i, j, k] = np.abs((li * pj * rk).as_quat()[3]) + scalars = np.reshape(np.moveaxis(scalars, 1, 0), (scalars.shape[1], -1)) + + max_ind = np.argmax(np.reshape(scalars, (len(p), -1)), axis=1) + left_best_check = max_ind // len(r) + right_best_check = max_ind % len(r) + assert (left_best == left_best_check).all() + assert (right_best == right_best_check).all() + + reduced_check = l[left_best_check] * p * r[right_best_check] + mag = (reduced.inv() * reduced_check).magnitude() + assert_array_almost_equal(mag, np.zeros(len(p))) + + +def test_apply_single_rotation_single_point(): + mat = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + r_1d = Rotation.from_matrix(mat) + r_2d = Rotation.from_matrix(np.expand_dims(mat, axis=0)) + + v_1d = np.array([1, 2, 3]) + v_2d = np.expand_dims(v_1d, axis=0) + v1d_rotated = np.array([-2, 1, 3]) + v2d_rotated = np.expand_dims(v1d_rotated, axis=0) + + assert_allclose(r_1d.apply(v_1d), v1d_rotated) + assert_allclose(r_1d.apply(v_2d), v2d_rotated) + assert_allclose(r_2d.apply(v_1d), v2d_rotated) + assert_allclose(r_2d.apply(v_2d), v2d_rotated) + + v1d_inverse = np.array([2, -1, 3]) + v2d_inverse = np.expand_dims(v1d_inverse, axis=0) + + assert_allclose(r_1d.apply(v_1d, inverse=True), v1d_inverse) + assert_allclose(r_1d.apply(v_2d, inverse=True), v2d_inverse) + assert_allclose(r_2d.apply(v_1d, inverse=True), v2d_inverse) + assert_allclose(r_2d.apply(v_2d, inverse=True), v2d_inverse) + + +def test_apply_single_rotation_multiple_points(): + mat = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + r1 = Rotation.from_matrix(mat) + r2 = Rotation.from_matrix(np.expand_dims(mat, axis=0)) + + v = np.array([[1, 2, 3], [4, 5, 6]]) + v_rotated = np.array([[-2, 1, 3], [-5, 4, 6]]) + + assert_allclose(r1.apply(v), v_rotated) + assert_allclose(r2.apply(v), v_rotated) + + v_inverse = np.array([[2, -1, 3], [5, -4, 6]]) + + assert_allclose(r1.apply(v, inverse=True), v_inverse) + assert_allclose(r2.apply(v, inverse=True), v_inverse) + + +def test_apply_multiple_rotations_single_point(): + mat = np.empty((2, 3, 3)) + mat[0] = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + mat[1] = np.array([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0] + ]) + r = Rotation.from_matrix(mat) + + v1 = np.array([1, 2, 3]) + v2 = np.expand_dims(v1, axis=0) + + v_rotated = np.array([[-2, 1, 3], [1, -3, 2]]) + + assert_allclose(r.apply(v1), v_rotated) + assert_allclose(r.apply(v2), v_rotated) + + v_inverse = np.array([[2, -1, 3], [1, 3, -2]]) + + assert_allclose(r.apply(v1, inverse=True), v_inverse) + assert_allclose(r.apply(v2, inverse=True), v_inverse) + + +def test_apply_multiple_rotations_multiple_points(): + mat = np.empty((2, 3, 3)) + mat[0] = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + mat[1] = np.array([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0] + ]) + r = Rotation.from_matrix(mat) + + v = np.array([[1, 2, 3], [4, 5, 6]]) + v_rotated = np.array([[-2, 1, 3], [4, -6, 5]]) + assert_allclose(r.apply(v), v_rotated) + + v_inverse = np.array([[2, -1, 3], [4, 6, -5]]) + assert_allclose(r.apply(v, inverse=True), v_inverse) + + +def test_getitem(): + mat = np.empty((2, 3, 3)) + mat[0] = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + mat[1] = np.array([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0] + ]) + r = Rotation.from_matrix(mat) + + assert_allclose(r[0].as_matrix(), mat[0], atol=1e-15) + assert_allclose(r[1].as_matrix(), mat[1], atol=1e-15) + assert_allclose(r[:-1].as_matrix(), np.expand_dims(mat[0], axis=0), atol=1e-15) + + +def test_getitem_single(): + with pytest.raises(TypeError, match='not subscriptable'): + Rotation.identity()[0] + + +def test_setitem_single(): + r = Rotation.identity() + with pytest.raises(TypeError, match='not subscriptable'): + r[0] = Rotation.identity() + + +def test_setitem_slice(): + rng = np.random.default_rng(146972845698875399755764481408308808739) + r1 = Rotation.random(10, rng=rng) + r2 = Rotation.random(5, rng=rng) + r1[1:6] = r2 + assert_equal(r1[1:6].as_quat(), r2.as_quat()) + + +def test_setitem_integer(): + rng = np.random.default_rng(146972845698875399755764481408308808739) + r1 = Rotation.random(10, rng=rng) + r2 = Rotation.random(rng=rng) + r1[1] = r2 + assert_equal(r1[1].as_quat(), r2.as_quat()) + + +def test_setitem_wrong_type(): + r = Rotation.random(10, rng=0) + with pytest.raises(TypeError, match='Rotation object'): + r[0] = 1 + + +def test_n_rotations(): + mat = np.empty((2, 3, 3)) + mat[0] = np.array([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ]) + mat[1] = np.array([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0] + ]) + r = Rotation.from_matrix(mat) + + assert_equal(len(r), 2) + assert_equal(len(r[:-1]), 1) + + +def test_random_rotation_shape(): + rng = np.random.default_rng(146972845698875399755764481408308808739) + assert_equal(Rotation.random(rng=rng).as_quat().shape, (4,)) + assert_equal(Rotation.random(None, rng=rng).as_quat().shape, (4,)) + + assert_equal(Rotation.random(1, rng=rng).as_quat().shape, (1, 4)) + assert_equal(Rotation.random(5, rng=rng).as_quat().shape, (5, 4)) + + +def test_align_vectors_no_rotation(): + x = np.array([[1, 2, 3], [4, 5, 6]]) + y = x.copy() + + r, rssd = Rotation.align_vectors(x, y) + assert_array_almost_equal(r.as_matrix(), np.eye(3)) + assert_allclose(rssd, 0, atol=1e-6) + + +def test_align_vectors_no_noise(): + rng = np.random.default_rng(14697284569885399755764481408308808739) + c = Rotation.random(rng=rng) + b = rng.normal(size=(5, 3)) + a = c.apply(b) + + est, rssd = Rotation.align_vectors(a, b) + assert_allclose(c.as_quat(), est.as_quat()) + assert_allclose(rssd, 0, atol=1e-7) + + +def test_align_vectors_improper_rotation(): + # Tests correct logic for issue #10444 + x = np.array([[0.89299824, -0.44372674, 0.0752378], + [0.60221789, -0.47564102, -0.6411702]]) + y = np.array([[0.02386536, -0.82176463, 0.5693271], + [-0.27654929, -0.95191427, -0.1318321]]) + + est, rssd = Rotation.align_vectors(x, y) + assert_allclose(x, est.apply(y), atol=1e-6) + assert_allclose(rssd, 0, atol=1e-7) + + +def test_align_vectors_rssd_sensitivity(): + rssd_expected = 0.141421356237308 + sens_expected = np.array([[0.2, 0. , 0.], + [0. , 1.5, 1.], + [0. , 1. , 1.]]) + atol = 1e-6 + a = [[0, 1, 0], [0, 1, 1], [0, 1, 1]] + b = [[1, 0, 0], [1, 1.1, 0], [1, 0.9, 0]] + rot, rssd, sens = Rotation.align_vectors(a, b, return_sensitivity=True) + assert np.isclose(rssd, rssd_expected, atol=atol) + assert np.allclose(sens, sens_expected, atol=atol) + + +def test_align_vectors_scaled_weights(): + n = 10 + a = Rotation.random(n, rng=0).apply([1, 0, 0]) + b = Rotation.random(n, rng=1).apply([1, 0, 0]) + scale = 2 + + est1, rssd1, cov1 = Rotation.align_vectors(a, b, np.ones(n), True) + est2, rssd2, cov2 = Rotation.align_vectors(a, b, scale * np.ones(n), True) + + assert_allclose(est1.as_matrix(), est2.as_matrix()) + assert_allclose(np.sqrt(scale) * rssd1, rssd2, atol=1e-6) + assert_allclose(cov1, cov2) + + +def test_align_vectors_noise(): + rng = np.random.default_rng(146972845698875399755764481408308808739) + n_vectors = 100 + rot = Rotation.random(rng=rng) + vectors = rng.normal(size=(n_vectors, 3)) + result = rot.apply(vectors) + + # The paper adds noise as independently distributed angular errors + sigma = np.deg2rad(1) + tolerance = 1.5 * sigma + noise = Rotation.from_rotvec( + rng.normal( + size=(n_vectors, 3), + scale=sigma + ) + ) + + # Attitude errors must preserve norm. Hence apply individual random + # rotations to each vector. + noisy_result = noise.apply(result) + + est, rssd, cov = Rotation.align_vectors(noisy_result, vectors, + return_sensitivity=True) + + # Use rotation compositions to find out closeness + error_vector = (rot * est.inv()).as_rotvec() + assert_allclose(error_vector[0], 0, atol=tolerance) + assert_allclose(error_vector[1], 0, atol=tolerance) + assert_allclose(error_vector[2], 0, atol=tolerance) + + # Check error bounds using covariance matrix + cov *= sigma + assert_allclose(cov[0, 0], 0, atol=tolerance) + assert_allclose(cov[1, 1], 0, atol=tolerance) + assert_allclose(cov[2, 2], 0, atol=tolerance) + + assert_allclose(rssd, np.sum((noisy_result - est.apply(vectors))**2)**0.5) + + +def test_align_vectors_invalid_input(): + with pytest.raises(ValueError, match="Expected input `a` to have shape"): + Rotation.align_vectors([1, 2, 3, 4], [1, 2, 3]) + + with pytest.raises(ValueError, match="Expected input `b` to have shape"): + Rotation.align_vectors([1, 2, 3], [1, 2, 3, 4]) + + with pytest.raises(ValueError, match="Expected inputs `a` and `b` " + "to have same shapes"): + Rotation.align_vectors([[1, 2, 3],[4, 5, 6]], [[1, 2, 3]]) + + with pytest.raises(ValueError, + match="Expected `weights` to be 1 dimensional"): + Rotation.align_vectors([[1, 2, 3]], [[1, 2, 3]], weights=[[1]]) + + with pytest.raises(ValueError, + match="Expected `weights` to have number of values"): + Rotation.align_vectors([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], + weights=[1, 2, 3]) + + with pytest.raises(ValueError, + match="`weights` may not contain negative values"): + Rotation.align_vectors([[1, 2, 3]], [[1, 2, 3]], weights=[-1]) + + with pytest.raises(ValueError, + match="Only one infinite weight is allowed"): + Rotation.align_vectors([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], + weights=[np.inf, np.inf]) + + with pytest.raises(ValueError, + match="Cannot align zero length primary vectors"): + Rotation.align_vectors([[0, 0, 0]], [[1, 2, 3]]) + + with pytest.raises(ValueError, + match="Cannot return sensitivity matrix"): + Rotation.align_vectors([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], + return_sensitivity=True, weights=[np.inf, 1]) + + with pytest.raises(ValueError, + match="Cannot return sensitivity matrix"): + Rotation.align_vectors([[1, 2, 3]], [[1, 2, 3]], + return_sensitivity=True) + + +def test_align_vectors_align_constrain(): + # Align the primary +X B axis with the primary +Y A axis, and rotate about + # it such that the +Y B axis (residual of the [1, 1, 0] secondary b vector) + # is aligned with the +Z A axis (residual of the [0, 1, 1] secondary a + # vector) + atol = 1e-12 + b = [[1, 0, 0], [1, 1, 0]] + a = [[0, 1, 0], [0, 1, 1]] + m_expected = np.array([[0, 0, 1], + [1, 0, 0], + [0, 1, 0]]) + R, rssd = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + assert_allclose(R.as_matrix(), m_expected, atol=atol) + assert_allclose(R.apply(b), a, atol=atol) # Pri and sec align exactly + assert np.isclose(rssd, 0, atol=atol) + + # Do the same but with an inexact secondary rotation + b = [[1, 0, 0], [1, 2, 0]] + rssd_expected = 1.0 + R, rssd = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + assert_allclose(R.as_matrix(), m_expected, atol=atol) + assert_allclose(R.apply(b)[0], a[0], atol=atol) # Only pri aligns exactly + assert np.isclose(rssd, rssd_expected, atol=atol) + a_expected = [[0, 1, 0], [0, 1, 2]] + assert_allclose(R.apply(b), a_expected, atol=atol) + + # Check random vectors + b = [[1, 2, 3], [-2, 3, -1]] + a = [[-1, 3, 2], [1, -1, 2]] + rssd_expected = 1.3101595297515016 + R, rssd = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + assert_allclose(R.apply(b)[0], a[0], atol=atol) # Only pri aligns exactly + assert np.isclose(rssd, rssd_expected, atol=atol) + + +def test_align_vectors_near_inf(): + # align_vectors should return near the same result for high weights as for + # infinite weights. rssd will be different with floating point error on the + # exactly aligned vector being multiplied by a large non-infinite weight + n = 100 + mats = [] + for i in range(6): + mats.append(Rotation.random(n, rng=10 + i).as_matrix()) + + for i in range(n): + # Get random pairs of 3-element vectors + a = [1*mats[0][i][0], 2*mats[1][i][0]] + b = [3*mats[2][i][0], 4*mats[3][i][0]] + + R, _ = Rotation.align_vectors(a, b, weights=[1e10, 1]) + R2, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + assert_allclose(R.as_matrix(), R2.as_matrix(), atol=1e-4) + + for i in range(n): + # Get random triplets of 3-element vectors + a = [1*mats[0][i][0], 2*mats[1][i][0], 3*mats[2][i][0]] + b = [4*mats[3][i][0], 5*mats[4][i][0], 6*mats[5][i][0]] + + R, _ = Rotation.align_vectors(a, b, weights=[1e10, 2, 1]) + R2, _ = Rotation.align_vectors(a, b, weights=[np.inf, 2, 1]) + assert_allclose(R.as_matrix(), R2.as_matrix(), atol=1e-4) + + +def test_align_vectors_parallel(): + atol = 1e-12 + a = [[1, 0, 0], [0, 1, 0]] + b = [[0, 1, 0], [0, 1, 0]] + m_expected = np.array([[0, 1, 0], + [-1, 0, 0], + [0, 0, 1]]) + R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + assert_allclose(R.as_matrix(), m_expected, atol=atol) + R, _ = Rotation.align_vectors(a[0], b[0]) + assert_allclose(R.as_matrix(), m_expected, atol=atol) + assert_allclose(R.apply(b[0]), a[0], atol=atol) + + b = [[1, 0, 0], [1, 0, 0]] + m_expected = np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + assert_allclose(R.as_matrix(), m_expected, atol=atol) + R, _ = Rotation.align_vectors(a[0], b[0]) + assert_allclose(R.as_matrix(), m_expected, atol=atol) + assert_allclose(R.apply(b[0]), a[0], atol=atol) + + +def test_align_vectors_antiparallel(): + # Test exact 180 deg rotation + atol = 1e-12 + as_to_test = np.array([[[1, 0, 0], [0, 1, 0]], + [[0, 1, 0], [1, 0, 0]], + [[0, 0, 1], [0, 1, 0]]]) + bs_to_test = [[-a[0], a[1]] for a in as_to_test] + for a, b in zip(as_to_test, bs_to_test): + R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + assert_allclose(R.magnitude(), np.pi, atol=atol) + assert_allclose(R.apply(b[0]), a[0], atol=atol) + + # Test exact rotations near 180 deg + Rs = Rotation.random(100, rng=0) + dRs = Rotation.from_rotvec(Rs.as_rotvec()*1e-4) # scale down to small angle + a = [[ 1, 0, 0], [0, 1, 0]] + b = [[-1, 0, 0], [0, 1, 0]] + as_to_test = [] + for dR in dRs: + as_to_test.append([dR.apply(a[0]), a[1]]) + for a in as_to_test: + R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1]) + R2, _ = Rotation.align_vectors(a, b, weights=[1e10, 1]) + assert_allclose(R.as_matrix(), R2.as_matrix(), atol=atol) + + +def test_align_vectors_primary_only(): + atol = 1e-12 + mats_a = Rotation.random(100, rng=0).as_matrix() + mats_b = Rotation.random(100, rng=1).as_matrix() + for mat_a, mat_b in zip(mats_a, mats_b): + # Get random 3-element unit vectors + a = mat_a[0] + b = mat_b[0] + + # Compare to align_vectors with primary only + R, rssd = Rotation.align_vectors(a, b) + assert_allclose(R.apply(b), a, atol=atol) + assert np.isclose(rssd, 0, atol=atol) + + +def test_slerp(): + rnd = np.random.RandomState(0) + + key_rots = Rotation.from_quat(rnd.uniform(size=(5, 4))) + key_quats = key_rots.as_quat() + + key_times = [0, 1, 2, 3, 4] + interpolator = Slerp(key_times, key_rots) + + times = [0, 0.5, 0.25, 1, 1.5, 2, 2.75, 3, 3.25, 3.60, 4] + interp_rots = interpolator(times) + interp_quats = interp_rots.as_quat() + + # Dot products are affected by sign of quaternions + interp_quats[interp_quats[:, -1] < 0] *= -1 + # Checking for quaternion equality, perform same operation + key_quats[key_quats[:, -1] < 0] *= -1 + + # Equality at keyframes, including both endpoints + assert_allclose(interp_quats[0], key_quats[0]) + assert_allclose(interp_quats[3], key_quats[1]) + assert_allclose(interp_quats[5], key_quats[2]) + assert_allclose(interp_quats[7], key_quats[3]) + assert_allclose(interp_quats[10], key_quats[4]) + + # Constant angular velocity between keyframes. Check by equating + # cos(theta) between quaternion pairs with equal time difference. + cos_theta1 = np.sum(interp_quats[0] * interp_quats[2]) + cos_theta2 = np.sum(interp_quats[2] * interp_quats[1]) + assert_allclose(cos_theta1, cos_theta2) + + cos_theta4 = np.sum(interp_quats[3] * interp_quats[4]) + cos_theta5 = np.sum(interp_quats[4] * interp_quats[5]) + assert_allclose(cos_theta4, cos_theta5) + + # theta1: 0 -> 0.25, theta3 : 0.5 -> 1 + # Use double angle formula for double the time difference + cos_theta3 = np.sum(interp_quats[1] * interp_quats[3]) + assert_allclose(cos_theta3, 2 * (cos_theta1**2) - 1) + + # Miscellaneous checks + assert_equal(len(interp_rots), len(times)) + + +def test_slerp_rot_is_rotation(): + with pytest.raises(TypeError, match="must be a `Rotation` instance"): + r = np.array([[1,2,3,4], + [0,0,0,1]]) + t = np.array([0, 1]) + Slerp(t, r) + +SLERP_EXCEPTION_MESSAGE = "must be a sequence of at least 2 rotations" + +def test_slerp_single_rot(): + r = Rotation.from_quat([1, 2, 3, 4]) + with pytest.raises(ValueError, match=SLERP_EXCEPTION_MESSAGE): + Slerp([1], r) + + +def test_slerp_rot_len0(): + r = Rotation.random() + with pytest.raises(ValueError, match=SLERP_EXCEPTION_MESSAGE): + Slerp([], r) + + +def test_slerp_rot_len1(): + r = Rotation.random(1) + with pytest.raises(ValueError, match=SLERP_EXCEPTION_MESSAGE): + Slerp([1], r) + + +def test_slerp_time_dim_mismatch(): + with pytest.raises(ValueError, + match="times to be specified in a 1 dimensional array"): + rnd = np.random.RandomState(0) + r = Rotation.from_quat(rnd.uniform(size=(2, 4))) + t = np.array([[1], + [2]]) + Slerp(t, r) + + +def test_slerp_num_rotations_mismatch(): + with pytest.raises(ValueError, match="number of rotations to be equal to " + "number of timestamps"): + rnd = np.random.RandomState(0) + r = Rotation.from_quat(rnd.uniform(size=(5, 4))) + t = np.arange(7) + Slerp(t, r) + + +def test_slerp_equal_times(): + with pytest.raises(ValueError, match="strictly increasing order"): + rnd = np.random.RandomState(0) + r = Rotation.from_quat(rnd.uniform(size=(5, 4))) + t = [0, 1, 2, 2, 4] + Slerp(t, r) + + +def test_slerp_decreasing_times(): + with pytest.raises(ValueError, match="strictly increasing order"): + rnd = np.random.RandomState(0) + r = Rotation.from_quat(rnd.uniform(size=(5, 4))) + t = [0, 1, 3, 2, 4] + Slerp(t, r) + + +def test_slerp_call_time_dim_mismatch(): + rnd = np.random.RandomState(0) + r = Rotation.from_quat(rnd.uniform(size=(5, 4))) + t = np.arange(5) + s = Slerp(t, r) + + with pytest.raises(ValueError, + match="`times` must be at most 1-dimensional."): + interp_times = np.array([[3.5], + [4.2]]) + s(interp_times) + + +def test_slerp_call_time_out_of_range(): + rnd = np.random.RandomState(0) + r = Rotation.from_quat(rnd.uniform(size=(5, 4))) + t = np.arange(5) + 1 + s = Slerp(t, r) + + with pytest.raises(ValueError, match="times must be within the range"): + s([0, 1, 2]) + with pytest.raises(ValueError, match="times must be within the range"): + s([1, 2, 6]) + + +def test_slerp_call_scalar_time(): + r = Rotation.from_euler('X', [0, 80], degrees=True) + s = Slerp([0, 1], r) + + r_interpolated = s(0.25) + r_interpolated_expected = Rotation.from_euler('X', 20, degrees=True) + + delta = r_interpolated * r_interpolated_expected.inv() + + assert_allclose(delta.magnitude(), 0, atol=1e-16) + + +def test_multiplication_stability(): + qs = Rotation.random(50, rng=0) + rs = Rotation.random(1000, rng=1) + for q in qs: + rs *= q * rs + assert_allclose(np.linalg.norm(rs.as_quat(), axis=1), 1) + + +def test_pow(): + atol = 1e-14 + p = Rotation.random(10, rng=0) + p_inv = p.inv() + # Test the short-cuts and other integers + for n in [-5, -2, -1, 0, 1, 2, 5]: + # Test accuracy + q = p ** n + r = Rotation.identity(10) + for _ in range(abs(n)): + if n > 0: + r = r * p + else: + r = r * p_inv + ang = (q * r.inv()).magnitude() + assert np.all(ang < atol) + + # Test shape preservation + r = Rotation.from_quat([0, 0, 0, 1]) + assert (r**n).as_quat().shape == (4,) + r = Rotation.from_quat([[0, 0, 0, 1]]) + assert (r**n).as_quat().shape == (1, 4) + + # Large angle fractional + for n in [-1.5, -0.5, -0.0, 0.0, 0.5, 1.5]: + q = p ** n + r = Rotation.from_rotvec(n * p.as_rotvec()) + assert_allclose(q.as_quat(), r.as_quat(), atol=atol) + + # Small angle + p = Rotation.from_rotvec([1e-12, 0, 0]) + n = 3 + q = p ** n + r = Rotation.from_rotvec(n * p.as_rotvec()) + assert_allclose(q.as_quat(), r.as_quat(), atol=atol) + + +def test_pow_errors(): + p = Rotation.random(rng=0) + with pytest.raises(NotImplementedError, match='modulus not supported'): + pow(p, 1, 1) + + +def test_rotation_within_numpy_array(): + single = Rotation.random(rng=0) + multiple = Rotation.random(2, rng=1) + + array = np.array(single) + assert_equal(array.shape, ()) + + array = np.array(multiple) + assert_equal(array.shape, (2,)) + assert_allclose(array[0].as_matrix(), multiple[0].as_matrix()) + assert_allclose(array[1].as_matrix(), multiple[1].as_matrix()) + + array = np.array([single]) + assert_equal(array.shape, (1,)) + assert_equal(array[0], single) + + array = np.array([multiple]) + assert_equal(array.shape, (1, 2)) + assert_allclose(array[0, 0].as_matrix(), multiple[0].as_matrix()) + assert_allclose(array[0, 1].as_matrix(), multiple[1].as_matrix()) + + array = np.array([single, multiple], dtype=object) + assert_equal(array.shape, (2,)) + assert_equal(array[0], single) + assert_equal(array[1], multiple) + + array = np.array([multiple, multiple, multiple]) + assert_equal(array.shape, (3, 2)) + + +def test_pickling(): + r = Rotation.from_quat([0, 0, np.sin(np.pi/4), np.cos(np.pi/4)]) + pkl = pickle.dumps(r) + unpickled = pickle.loads(pkl) + assert_allclose(r.as_matrix(), unpickled.as_matrix(), atol=1e-15) + + +def test_deepcopy(): + r = Rotation.from_quat([0, 0, np.sin(np.pi/4), np.cos(np.pi/4)]) + r1 = copy.deepcopy(r) + assert_allclose(r.as_matrix(), r1.as_matrix(), atol=1e-15) + + +def test_as_euler_contiguous(): + r = Rotation.from_quat([0, 0, 0, 1]) + e1 = r.as_euler('xyz') # extrinsic euler rotation + e2 = r.as_euler('XYZ') # intrinsic + assert e1.flags['C_CONTIGUOUS'] is True + assert e2.flags['C_CONTIGUOUS'] is True + assert all(i >= 0 for i in e1.strides) + assert all(i >= 0 for i in e2.strides) + + +def test_concatenate(): + rotation = Rotation.random(10, rng=0) + sizes = [1, 2, 3, 1, 3] + starts = [0] + list(np.cumsum(sizes)) + split = [rotation[i:i + n] for i, n in zip(starts, sizes)] + result = Rotation.concatenate(split) + assert_equal(rotation.as_quat(), result.as_quat()) + + # Test Rotation input for multiple rotations + result = Rotation.concatenate(rotation) + assert_equal(rotation.as_quat(), result.as_quat()) + + # Test that a copy is returned + assert rotation is not result + + # Test Rotation input for single rotations + result = Rotation.concatenate(Rotation.identity()) + assert_equal(Rotation.identity().as_quat(), result.as_quat()) + + +def test_concatenate_wrong_type(): + with pytest.raises(TypeError, match='Rotation objects only'): + Rotation.concatenate([Rotation.identity(), 1, None]) + + +# Regression test for gh-16663 +def test_len_and_bool(): + rotation_multi_one = Rotation([[0, 0, 0, 1]]) + rotation_multi = Rotation([[0, 0, 0, 1], [0, 0, 0, 1]]) + rotation_single = Rotation([0, 0, 0, 1]) + + assert len(rotation_multi_one) == 1 + assert len(rotation_multi) == 2 + with pytest.raises(TypeError, match="Single rotation has no len()."): + len(rotation_single) + + # Rotation should always be truthy. See gh-16663 + assert rotation_multi_one + assert rotation_multi + assert rotation_single + + +def test_from_davenport_single_rotation(): + axis = [0, 0, 1] + quat = Rotation.from_davenport(axis, 'extrinsic', 90, + degrees=True).as_quat() + expected_quat = np.array([0, 0, 1, 1]) / np.sqrt(2) + assert_allclose(quat, expected_quat) + + +def test_from_davenport_one_or_two_axes(): + ez = [0, 0, 1] + ey = [0, 1, 0] + + # Single rotation, single axis, axes.shape == (3, ) + rot = Rotation.from_rotvec(np.array(ez) * np.pi/4) + rot_dav = Rotation.from_davenport(ez, 'e', np.pi/4) + assert_allclose(rot.as_quat(canonical=True), + rot_dav.as_quat(canonical=True)) + + # Single rotation, single axis, axes.shape == (1, 3) + rot = Rotation.from_rotvec([np.array(ez) * np.pi/4]) + rot_dav = Rotation.from_davenport([ez], 'e', [np.pi/4]) + assert_allclose(rot.as_quat(canonical=True), + rot_dav.as_quat(canonical=True)) + + # Single rotation, two axes, axes.shape == (2, 3) + rot = Rotation.from_rotvec([np.array(ez) * np.pi/4, + np.array(ey) * np.pi/6]) + rot = rot[0] * rot[1] + rot_dav = Rotation.from_davenport([ey, ez], 'e', [np.pi/6, np.pi/4]) + assert_allclose(rot.as_quat(canonical=True), + rot_dav.as_quat(canonical=True)) + + # Two rotations, single axis, axes.shape == (3, ) + rot = Rotation.from_rotvec([np.array(ez) * np.pi/6, + np.array(ez) * np.pi/4]) + rot_dav = Rotation.from_davenport([ez], 'e', [np.pi/6, np.pi/4]) + assert_allclose(rot.as_quat(canonical=True), + rot_dav.as_quat(canonical=True)) + + +def test_from_davenport_invalid_input(): + ez = [0, 0, 1] + ey = [0, 1, 0] + ezy = [0, 1, 1] + with pytest.raises(ValueError, match="must be orthogonal"): + Rotation.from_davenport([ez, ezy], 'e', [0, 0]) + with pytest.raises(ValueError, match="must be orthogonal"): + Rotation.from_davenport([ez, ey, ezy], 'e', [0, 0, 0]) + with pytest.raises(ValueError, match="order should be"): + Rotation.from_davenport([ez], 'xyz', [0]) + with pytest.raises(ValueError, match="Expected `angles`"): + Rotation.from_davenport([ez, ey, ez], 'e', [0, 1, 2, 3]) + + +def test_as_davenport(): + rnd = np.random.RandomState(0) + n = 100 + angles = np.empty((n, 3)) + angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + angles_middle = rnd.uniform(low=0, high=np.pi, size=(n,)) + angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + lambdas = rnd.uniform(low=0, high=np.pi, size=(20,)) + + e1 = np.array([1, 0, 0]) + e2 = np.array([0, 1, 0]) + + for lamb in lambdas: + ax_lamb = [e1, e2, Rotation.from_rotvec(lamb*e2).apply(e1)] + angles[:, 1] = angles_middle - lamb + for order in ['extrinsic', 'intrinsic']: + ax = ax_lamb if order == 'intrinsic' else ax_lamb[::-1] + rot = Rotation.from_davenport(ax, order, angles) + angles_dav = rot.as_davenport(ax, order) + assert_allclose(angles_dav, angles) + + +@pytest.mark.thread_unsafe +def test_as_davenport_degenerate(): + # Since we cannot check for angle equality, we check for rotation matrix + # equality + rnd = np.random.RandomState(0) + n = 5 + angles = np.empty((n, 3)) + + # symmetric sequences + angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + angles_middle = [rnd.choice([0, np.pi]) for i in range(n)] + angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + lambdas = rnd.uniform(low=0, high=np.pi, size=(5,)) + + e1 = np.array([1, 0, 0]) + e2 = np.array([0, 1, 0]) + + for lamb in lambdas: + ax_lamb = [e1, e2, Rotation.from_rotvec(lamb*e2).apply(e1)] + angles[:, 1] = angles_middle - lamb + for order in ['extrinsic', 'intrinsic']: + ax = ax_lamb if order == 'intrinsic' else ax_lamb[::-1] + rot = Rotation.from_davenport(ax, order, angles) + with pytest.warns(UserWarning, match="Gimbal lock"): + angles_dav = rot.as_davenport(ax, order) + mat_expected = rot.as_matrix() + mat_estimated = Rotation.from_davenport(ax, order, angles_dav).as_matrix() + assert_array_almost_equal(mat_expected, mat_estimated) + + +def test_compare_from_davenport_from_euler(): + rnd = np.random.RandomState(0) + n = 100 + angles = np.empty((n, 3)) + + # symmetric sequences + angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + angles[:, 1] = rnd.uniform(low=0, high=np.pi, size=(n,)) + angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + for order in ['extrinsic', 'intrinsic']: + for seq_tuple in permutations('xyz'): + seq = ''.join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) + ax = [basis_vec(i) for i in seq] + if order == 'intrinsic': + seq = seq.upper() + eul = Rotation.from_euler(seq, angles) + dav = Rotation.from_davenport(ax, order, angles) + assert_allclose(eul.as_quat(canonical=True), dav.as_quat(canonical=True), + rtol=1e-12) + + # asymmetric sequences + angles[:, 1] -= np.pi / 2 + for order in ['extrinsic', 'intrinsic']: + for seq_tuple in permutations('xyz'): + seq = ''.join(seq_tuple) + ax = [basis_vec(i) for i in seq] + if order == 'intrinsic': + seq = seq.upper() + eul = Rotation.from_euler(seq, angles) + dav = Rotation.from_davenport(ax, order, angles) + assert_allclose(eul.as_quat(), dav.as_quat(), rtol=1e-12) + + +def test_compare_as_davenport_as_euler(): + rnd = np.random.RandomState(0) + n = 100 + angles = np.empty((n, 3)) + + # symmetric sequences + angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + angles[:, 1] = rnd.uniform(low=0, high=np.pi, size=(n,)) + angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,)) + for order in ['extrinsic', 'intrinsic']: + for seq_tuple in permutations('xyz'): + seq = ''.join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) + ax = [basis_vec(i) for i in seq] + if order == 'intrinsic': + seq = seq.upper() + rot = Rotation.from_euler(seq, angles) + eul = rot.as_euler(seq) + dav = rot.as_davenport(ax, order) + assert_allclose(eul, dav, rtol=1e-12) + + # asymmetric sequences + angles[:, 1] -= np.pi / 2 + for order in ['extrinsic', 'intrinsic']: + for seq_tuple in permutations('xyz'): + seq = ''.join(seq_tuple) + ax = [basis_vec(i) for i in seq] + if order == 'intrinsic': + seq = seq.upper() + rot = Rotation.from_euler(seq, angles) + eul = rot.as_euler(seq) + dav = rot.as_davenport(ax, order) + assert_allclose(eul, dav, rtol=1e-12) + + +def test_zero_rotation_construction(): + r = Rotation.random(num=0) + assert len(r) == 0 + + r_ide = Rotation.identity(num=0) + assert len(r_ide) == 0 + + r_get = Rotation.random(num=3)[[]] + assert len(r_get) == 0 + + r_quat = Rotation.from_quat(np.zeros((0, 4))) + assert len(r_quat) == 0 + + r_matrix = Rotation.from_matrix(np.zeros((0, 3, 3))) + assert len(r_matrix) == 0 + + r_euler = Rotation.from_euler("xyz", np.zeros((0, 3))) + assert len(r_euler) == 0 + + r_vec = Rotation.from_rotvec(np.zeros((0, 3))) + assert len(r_vec) == 0 + + r_dav = Rotation.from_davenport(np.eye(3), "extrinsic", np.zeros((0, 3))) + assert len(r_dav) == 0 + + r_mrp = Rotation.from_mrp(np.zeros((0, 3))) + assert len(r_mrp) == 0 + + +def test_zero_rotation_representation(): + r = Rotation.random(num=0) + assert r.as_quat().shape == (0, 4) + assert r.as_matrix().shape == (0, 3, 3) + assert r.as_euler("xyz").shape == (0, 3) + assert r.as_rotvec().shape == (0, 3) + assert r.as_mrp().shape == (0, 3) + assert r.as_davenport(np.eye(3), "extrinsic").shape == (0, 3) + + +def test_zero_rotation_array_rotation(): + r = Rotation.random(num=0) + + v = np.array([1, 2, 3]) + v_rotated = r.apply(v) + assert v_rotated.shape == (0, 3) + + v0 = np.zeros((0, 3)) + v0_rot = r.apply(v0) + assert v0_rot.shape == (0, 3) + + v2 = np.ones((2, 3)) + with pytest.raises( + ValueError, match="Expected equal numbers of rotations and vectors"): + r.apply(v2) + + +def test_zero_rotation_multiplication(): + r = Rotation.random(num=0) + + r_single = Rotation.random() + r_mult_left = r * r_single + assert len(r_mult_left) == 0 + + r_mult_right = r_single * r + assert len(r_mult_right) == 0 + + r0 = Rotation.random(0) + r_mult = r * r0 + assert len(r_mult) == 0 + + msg_rotation_error = "Expected equal number of rotations" + r2 = Rotation.random(2) + with pytest.raises(ValueError, match=msg_rotation_error): + r0 * r2 + + with pytest.raises(ValueError, match=msg_rotation_error): + r2 * r0 + + +def test_zero_rotation_concatentation(): + r = Rotation.random(num=0) + + r0 = Rotation.concatenate([r, r]) + assert len(r0) == 0 + + r1 = r.concatenate([Rotation.random(), r]) + assert len(r1) == 1 + + r3 = r.concatenate([Rotation.random(3), r]) + assert len(r3) == 3 + + r4 = r.concatenate([r, Rotation.random(4)]) + assert len(r4) == 4 + + +def test_zero_rotation_power(): + r = Rotation.random(num=0) + for pp in [-1.5, -1, 0, 1, 1.5]: + pow0 = r**pp + assert len(pow0) == 0 + + +def test_zero_rotation_inverse(): + r = Rotation.random(num=0) + r_inv = r.inv() + assert len(r_inv) == 0 + + +def test_zero_rotation_magnitude(): + r = Rotation.random(num=0) + magnitude = r.magnitude() + assert magnitude.shape == (0,) + + +def test_zero_rotation_mean(): + r = Rotation.random(num=0) + with pytest.raises(ValueError, match="Mean of an empty rotation set is undefined."): + r.mean() + + +def test_zero_rotation_approx_equal(): + r = Rotation.random(0) + assert r.approx_equal(Rotation.random(0)).shape == (0,) + assert r.approx_equal(Rotation.random()).shape == (0,) + assert Rotation.random().approx_equal(r).shape == (0,) + + approx_msg = "Expected equal number of rotations" + r3 = Rotation.random(2) + with pytest.raises(ValueError, match=approx_msg): + r.approx_equal(r3) + + with pytest.raises(ValueError, match=approx_msg): + r3.approx_equal(r) + + +def test_zero_rotation_get_set(): + r = Rotation.random(0) + + r_get = r[[]] + assert len(r_get) == 0 + + r_slice = r[:0] + assert len(r_slice) == 0 + + with pytest.raises(IndexError): + r[[0]] + + with pytest.raises(IndexError): + r[[True]] + + with pytest.raises(IndexError): + r[0] = Rotation.random() + + +def test_boolean_indexes(): + r = Rotation.random(3) + + r0 = r[[False, False, False]] + assert len(r0) == 0 + + r1 = r[[False, True, False]] + assert len(r1) == 1 + + r3 = r[[True, True, True]] + assert len(r3) == 3 + + with pytest.raises(IndexError): + r[[True, True]] diff --git a/shared/package-files/02/022dbf37ea549879e024ddeeb2231334eea47cb5855506b758e7addd585e844f/logic.py b/shared/package-files/02/022dbf37ea549879e024ddeeb2231334eea47cb5855506b758e7addd585e844f/logic.py new file mode 100644 index 0000000000000000000000000000000000000000..73b525b4b07cb06de0751340614eff15ca3bb510 --- /dev/null +++ b/shared/package-files/02/022dbf37ea549879e024ddeeb2231334eea47cb5855506b758e7addd585e844f/logic.py @@ -0,0 +1,427 @@ +"""Logic expressions handling + +NOTE +---- + +at present this is mainly needed for facts.py, feel free however to improve +this stuff for general purpose. +""" + +from __future__ import annotations +from typing import Optional + +# Type of a fuzzy bool +FuzzyBool = Optional[bool] + + +def _torf(args): + """Return True if all args are True, False if they + are all False, else None. + + >>> from sympy.core.logic import _torf + >>> _torf((True, True)) + True + >>> _torf((False, False)) + False + >>> _torf((True, False)) + """ + sawT = sawF = False + for a in args: + if a is True: + if sawF: + return + sawT = True + elif a is False: + if sawT: + return + sawF = True + else: + return + return sawT + + +def _fuzzy_group(args, quick_exit=False): + """Return True if all args are True, None if there is any None else False + unless ``quick_exit`` is True (then return None as soon as a second False + is seen. + + ``_fuzzy_group`` is like ``fuzzy_and`` except that it is more + conservative in returning a False, waiting to make sure that all + arguments are True or False and returning None if any arguments are + None. It also has the capability of permiting only a single False and + returning None if more than one is seen. For example, the presence of a + single transcendental amongst rationals would indicate that the group is + no longer rational; but a second transcendental in the group would make the + determination impossible. + + + Examples + ======== + + >>> from sympy.core.logic import _fuzzy_group + + By default, multiple Falses mean the group is broken: + + >>> _fuzzy_group([False, False, True]) + False + + If multiple Falses mean the group status is unknown then set + `quick_exit` to True so None can be returned when the 2nd False is seen: + + >>> _fuzzy_group([False, False, True], quick_exit=True) + + But if only a single False is seen then the group is known to + be broken: + + >>> _fuzzy_group([False, True, True], quick_exit=True) + False + + """ + saw_other = False + for a in args: + if a is True: + continue + if a is None: + return + if quick_exit and saw_other: + return + saw_other = True + return not saw_other + + +def fuzzy_bool(x): + """Return True, False or None according to x. + + Whereas bool(x) returns True or False, fuzzy_bool allows + for the None value and non-false values (which become None), too. + + Examples + ======== + + >>> from sympy.core.logic import fuzzy_bool + >>> from sympy.abc import x + >>> fuzzy_bool(x), fuzzy_bool(None) + (None, None) + >>> bool(x), bool(None) + (True, False) + + """ + if x is None: + return None + if x in (True, False): + return bool(x) + + +def fuzzy_and(args): + """Return True (all True), False (any False) or None. + + Examples + ======== + + >>> from sympy.core.logic import fuzzy_and + >>> from sympy import Dummy + + If you had a list of objects to test the commutivity of + and you want the fuzzy_and logic applied, passing an + iterator will allow the commutativity to only be computed + as many times as necessary. With this list, False can be + returned after analyzing the first symbol: + + >>> syms = [Dummy(commutative=False), Dummy()] + >>> fuzzy_and(s.is_commutative for s in syms) + False + + That False would require less work than if a list of pre-computed + items was sent: + + >>> fuzzy_and([s.is_commutative for s in syms]) + False + """ + + rv = True + for ai in args: + ai = fuzzy_bool(ai) + if ai is False: + return False + if rv: # this will stop updating if a None is ever trapped + rv = ai + return rv + + +def fuzzy_not(v): + """ + Not in fuzzy logic + + Return None if `v` is None else `not v`. + + Examples + ======== + + >>> from sympy.core.logic import fuzzy_not + >>> fuzzy_not(True) + False + >>> fuzzy_not(None) + >>> fuzzy_not(False) + True + + """ + if v is None: + return v + else: + return not v + + +def fuzzy_or(args): + """ + Or in fuzzy logic. Returns True (any True), False (all False), or None + + See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is + related to the two by the standard De Morgan's law. + + >>> from sympy.core.logic import fuzzy_or + >>> fuzzy_or([True, False]) + True + >>> fuzzy_or([True, None]) + True + >>> fuzzy_or([False, False]) + False + >>> print(fuzzy_or([False, None])) + None + + """ + rv = False + for ai in args: + ai = fuzzy_bool(ai) + if ai is True: + return True + if rv is False: # this will stop updating if a None is ever trapped + rv = ai + return rv + + +def fuzzy_xor(args): + """Return None if any element of args is not True or False, else + True (if there are an odd number of True elements), else False.""" + t = f = 0 + for a in args: + ai = fuzzy_bool(a) + if ai: + t += 1 + elif ai is False: + f += 1 + else: + return + return t % 2 == 1 + + +def fuzzy_nand(args): + """Return False if all args are True, True if they are all False, + else None.""" + return fuzzy_not(fuzzy_and(args)) + + +class Logic: + """Logical expression""" + # {} 'op' -> LogicClass + op_2class: dict[str, type[Logic]] = {} + + def __new__(cls, *args): + obj = object.__new__(cls) + obj.args = args + return obj + + def __getnewargs__(self): + return self.args + + def __hash__(self): + return hash((type(self).__name__,) + tuple(self.args)) + + def __eq__(a, b): + if not isinstance(b, type(a)): + return False + else: + return a.args == b.args + + def __ne__(a, b): + if not isinstance(b, type(a)): + return True + else: + return a.args != b.args + + def __lt__(self, other): + if self.__cmp__(other) == -1: + return True + return False + + def __cmp__(self, other): + if type(self) is not type(other): + a = str(type(self)) + b = str(type(other)) + else: + a = self.args + b = other.args + return (a > b) - (a < b) + + def __str__(self): + return '%s(%s)' % (self.__class__.__name__, + ', '.join(str(a) for a in self.args)) + + __repr__ = __str__ + + @staticmethod + def fromstring(text): + """Logic from string with space around & and | but none after !. + + e.g. + + !a & b | c + """ + lexpr = None # current logical expression + schedop = None # scheduled operation + for term in text.split(): + # operation symbol + if term in '&|': + if schedop is not None: + raise ValueError( + 'double op forbidden: "%s %s"' % (term, schedop)) + if lexpr is None: + raise ValueError( + '%s cannot be in the beginning of expression' % term) + schedop = term + continue + if '&' in term or '|' in term: + raise ValueError('& and | must have space around them') + if term[0] == '!': + if len(term) == 1: + raise ValueError('do not include space after "!"') + term = Not(term[1:]) + + # already scheduled operation, e.g. '&' + if schedop: + lexpr = Logic.op_2class[schedop](lexpr, term) + schedop = None + continue + + # this should be atom + if lexpr is not None: + raise ValueError( + 'missing op between "%s" and "%s"' % (lexpr, term)) + + lexpr = term + + # let's check that we ended up in correct state + if schedop is not None: + raise ValueError('premature end-of-expression in "%s"' % text) + if lexpr is None: + raise ValueError('"%s" is empty' % text) + + # everything looks good now + return lexpr + + +class AndOr_Base(Logic): + + def __new__(cls, *args): + bargs = [] + for a in args: + if a == cls.op_x_notx: + return a + elif a == (not cls.op_x_notx): + continue # skip this argument + bargs.append(a) + + args = sorted(set(cls.flatten(bargs)), key=hash) + + for a in args: + if Not(a) in args: + return cls.op_x_notx + + if len(args) == 1: + return args.pop() + elif len(args) == 0: + return not cls.op_x_notx + + return Logic.__new__(cls, *args) + + @classmethod + def flatten(cls, args): + # quick-n-dirty flattening for And and Or + args_queue = list(args) + res = [] + + while True: + try: + arg = args_queue.pop(0) + except IndexError: + break + if isinstance(arg, Logic): + if isinstance(arg, cls): + args_queue.extend(arg.args) + continue + res.append(arg) + + args = tuple(res) + return args + + +class And(AndOr_Base): + op_x_notx = False + + def _eval_propagate_not(self): + # !(a&b&c ...) == !a | !b | !c ... + return Or(*[Not(a) for a in self.args]) + + # (a|b|...) & c == (a&c) | (b&c) | ... + def expand(self): + + # first locate Or + for i, arg in enumerate(self.args): + if isinstance(arg, Or): + arest = self.args[:i] + self.args[i + 1:] + + orterms = [And(*(arest + (a,))) for a in arg.args] + for j in range(len(orterms)): + if isinstance(orterms[j], Logic): + orterms[j] = orterms[j].expand() + + res = Or(*orterms) + return res + + return self + + +class Or(AndOr_Base): + op_x_notx = True + + def _eval_propagate_not(self): + # !(a|b|c ...) == !a & !b & !c ... + return And(*[Not(a) for a in self.args]) + + +class Not(Logic): + + def __new__(cls, arg): + if isinstance(arg, str): + return Logic.__new__(cls, arg) + + elif isinstance(arg, bool): + return not arg + elif isinstance(arg, Not): + return arg.args[0] + + elif isinstance(arg, Logic): + # XXX this is a hack to expand right from the beginning + arg = arg._eval_propagate_not() + return arg + + else: + raise ValueError('Not: unknown argument %r' % (arg,)) + + @property + def arg(self): + return self.args[0] + + +Logic.op_2class['&'] = And +Logic.op_2class['|'] = Or +Logic.op_2class['!'] = Not diff --git a/shared/package-files/02/022e9d78388697050747d995be59086d76335990031ee3cb95a0630cad11db05/test_libfrequencies.py b/shared/package-files/02/022e9d78388697050747d995be59086d76335990031ee3cb95a0630cad11db05/test_libfrequencies.py new file mode 100644 index 0000000000000000000000000000000000000000..effd3b4b8b4e5fa113f1b20506997efc54d3c9d2 --- /dev/null +++ b/shared/package-files/02/022e9d78388697050747d995be59086d76335990031ee3cb95a0630cad11db05/test_libfrequencies.py @@ -0,0 +1,27 @@ +import pytest + +from pandas._libs.tslibs.parsing import get_rule_month + +from pandas.tseries import offsets + + +@pytest.mark.parametrize( + "obj,expected", + [ + ("W", "DEC"), + (offsets.Week().freqstr, "DEC"), + ("D", "DEC"), + (offsets.Day().freqstr, "DEC"), + ("Q", "DEC"), + (offsets.QuarterEnd(startingMonth=12).freqstr, "DEC"), + ("Q-JAN", "JAN"), + (offsets.QuarterEnd(startingMonth=1).freqstr, "JAN"), + ("Y-DEC", "DEC"), + (offsets.YearEnd().freqstr, "DEC"), + ("Y-MAY", "MAY"), + (offsets.YearEnd(month=5).freqstr, "MAY"), + ], +) +def test_get_rule_month(obj, expected): + result = get_rule_month(obj) + assert result == expected diff --git a/shared/package-files/02/02318a5a89979435f62358c277844e909afc9d1b6bde87e6dcc757447dd84d3a/_utils.py b/shared/package-files/02/02318a5a89979435f62358c277844e909afc9d1b6bde87e6dcc757447dd84d3a/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cde4c5c33b2f7229a10efacc47b070e0ac96a1 --- /dev/null +++ b/shared/package-files/02/02318a5a89979435f62358c277844e909afc9d1b6bde87e6dcc757447dd84d3a/_utils.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +import collections.abc +import numbers +from contextlib import suppress + +from typing import Any, Callable, Dict, List, Literal, Sequence, Tuple, Type, Union + +import PIL.Image +import torch + +from torchvision import tv_tensors + +from torchvision._utils import sequence_to_str + +from torchvision.transforms.transforms import _check_sequence_input, _setup_angle, _setup_size # noqa: F401 +from torchvision.transforms.v2.functional import get_dimensions, get_size, is_pure_tensor +from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT + + +def _setup_number_or_seq(arg: Union[int, float, Sequence[Union[int, float]]], name: str) -> Sequence[float]: + if not isinstance(arg, (int, float, Sequence)): + raise TypeError(f"{name} should be a number or a sequence of numbers. Got {type(arg)}") + if isinstance(arg, Sequence) and len(arg) not in (1, 2): + raise ValueError(f"If {name} is a sequence its length should be 1 or 2. Got {len(arg)}") + if isinstance(arg, Sequence): + for element in arg: + if not isinstance(element, (int, float)): + raise ValueError(f"{name} should be a sequence of numbers. Got {type(element)}") + + if isinstance(arg, (int, float)): + arg = [float(arg), float(arg)] + elif isinstance(arg, Sequence): + if len(arg) == 1: + arg = [float(arg[0]), float(arg[0])] + else: + arg = [float(arg[0]), float(arg[1])] + return arg + + +def _check_fill_arg(fill: Union[_FillType, Dict[Union[Type, str], _FillType]]) -> None: + if isinstance(fill, dict): + for value in fill.values(): + _check_fill_arg(value) + else: + if fill is not None and not isinstance(fill, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate fill arg, only Numbers, tuples, lists and dicts are allowed.") + + +def _convert_fill_arg(fill: _FillType) -> _FillTypeJIT: + # Fill = 0 is not equivalent to None, https://github.com/pytorch/vision/issues/6517 + # So, we can't reassign fill to 0 + # if fill is None: + # fill = 0 + if fill is None: + return fill + + if not isinstance(fill, (int, float)): + fill = [float(v) for v in list(fill)] + return fill # type: ignore[return-value] + + +def _setup_fill_arg(fill: Union[_FillType, Dict[Union[Type, str], _FillType]]) -> Dict[Union[Type, str], _FillTypeJIT]: + _check_fill_arg(fill) + + if isinstance(fill, dict): + for k, v in fill.items(): + fill[k] = _convert_fill_arg(v) + return fill # type: ignore[return-value] + else: + return {"others": _convert_fill_arg(fill)} + + +def _get_fill(fill_dict, inpt_type): + if inpt_type in fill_dict: + return fill_dict[inpt_type] + elif "others" in fill_dict: + return fill_dict["others"] + else: + RuntimeError("This should never happen, please open an issue on the torchvision repo if you hit this.") + + +def _check_padding_arg(padding: Union[int, Sequence[int]]) -> None: + if not isinstance(padding, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate padding arg") + + if isinstance(padding, (tuple, list)) and 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") + + +# TODO: let's use torchvision._utils.StrEnum to have the best of both worlds (strings and enums) +# https://github.com/pytorch/vision/issues/6250 +def _check_padding_mode_arg(padding_mode: Literal["constant", "edge", "reflect", "symmetric"]) -> None: + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + +def _find_labels_default_heuristic(inputs: Any) -> torch.Tensor: + """ + This heuristic covers three cases: + + 1. The input is tuple or list whose second item is a labels tensor. This happens for already batched + classification inputs for MixUp and CutMix (typically after the Dataloder). + 2. The input is a tuple or list whose second item is a dictionary that contains the labels tensor + under a label-like (see below) key. This happens for the inputs of detection models. + 3. The input is a dictionary that is structured as the one from 2. + + What is "label-like" key? We first search for an case-insensitive match of 'labels' inside the keys of the + dictionary. This is the name our detection models expect. If we can't find that, we look for a case-insensitive + match of the term 'label' anywhere inside the key, i.e. 'FooLaBeLBar'. If we can't find that either, the dictionary + contains no "label-like" key. + """ + + if isinstance(inputs, (tuple, list)): + inputs = inputs[1] + + # MixUp, CutMix + if is_pure_tensor(inputs): + return inputs + + if not isinstance(inputs, collections.abc.Mapping): + raise ValueError( + f"When using the default labels_getter, the input passed to forward must be a dictionary or a two-tuple " + f"whose second item is a dictionary or a tensor, but got {inputs} instead." + ) + + candidate_key = None + with suppress(StopIteration): + candidate_key = next(key for key in inputs.keys() if key.lower() == "labels") + if candidate_key is None: + with suppress(StopIteration): + candidate_key = next(key for key in inputs.keys() if "label" in key.lower()) + if candidate_key is None: + raise ValueError( + "Could not infer where the labels are in the sample. Try passing a callable as the labels_getter parameter?" + "If there are no labels in the sample by design, pass labels_getter=None." + ) + + return inputs[candidate_key] + + +def _parse_labels_getter(labels_getter: Union[str, Callable[[Any], Any], None]) -> Callable[[Any], Any]: + if labels_getter == "default": + return _find_labels_default_heuristic + elif callable(labels_getter): + return labels_getter + elif labels_getter is None: + return lambda _: None + else: + raise ValueError(f"labels_getter should either be 'default', a callable, or None, but got {labels_getter}.") + + +def get_bounding_boxes(flat_inputs: List[Any]) -> tv_tensors.BoundingBoxes: + # This assumes there is only one bbox per sample as per the general convention + try: + return next(inpt for inpt in flat_inputs if isinstance(inpt, tv_tensors.BoundingBoxes)) + except StopIteration: + raise ValueError("No bounding boxes were found in the sample") + + +def query_chw(flat_inputs: List[Any]) -> Tuple[int, int, int]: + chws = { + tuple(get_dimensions(inpt)) + for inpt in flat_inputs + if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video)) + } + if not chws: + raise TypeError("No image or video was found in the sample") + elif len(chws) > 1: + raise ValueError(f"Found multiple CxHxW dimensions in the sample: {sequence_to_str(sorted(chws))}") + c, h, w = chws.pop() + return c, h, w + + +def query_size(flat_inputs: List[Any]) -> Tuple[int, int]: + sizes = { + tuple(get_size(inpt)) + for inpt in flat_inputs + if check_type( + inpt, + ( + is_pure_tensor, + tv_tensors.Image, + PIL.Image.Image, + tv_tensors.Video, + tv_tensors.Mask, + tv_tensors.BoundingBoxes, + ), + ) + } + if not sizes: + raise TypeError("No image, video, mask or bounding box was found in the sample") + elif len(sizes) > 1: + raise ValueError(f"Found multiple HxW dimensions in the sample: {sequence_to_str(sorted(sizes))}") + h, w = sizes.pop() + return h, w + + +def check_type(obj: Any, types_or_checks: Tuple[Union[Type, Callable[[Any], bool]], ...]) -> bool: + for type_or_check in types_or_checks: + if isinstance(obj, type_or_check) if isinstance(type_or_check, type) else type_or_check(obj): + return True + return False + + +def has_any(flat_inputs: List[Any], *types_or_checks: Union[Type, Callable[[Any], bool]]) -> bool: + for inpt in flat_inputs: + if check_type(inpt, types_or_checks): + return True + return False + + +def has_all(flat_inputs: List[Any], *types_or_checks: Union[Type, Callable[[Any], bool]]) -> bool: + for type_or_check in types_or_checks: + for inpt in flat_inputs: + if isinstance(inpt, type_or_check) if isinstance(type_or_check, type) else type_or_check(inpt): + break + else: + return False + return True diff --git a/shared/package-files/02/02320a4c11fda2fa2de2aef6eae7132a8bb5cb53acf065ed195a7369572d7b57/fill_ops.h b/shared/package-files/02/02320a4c11fda2fa2de2aef6eae7132a8bb5cb53acf065ed195a7369572d7b57/fill_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..5e3bc28c26c919cf0db25dd9c6706933cc030a59 --- /dev/null +++ b/shared/package-files/02/02320a4c11fda2fa2de2aef6eae7132a8bb5cb53acf065ed195a7369572d7b57/fill_ops.h @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fill_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::fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Scalar(Tensor self, Scalar value) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & value); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & value); +}; + +struct TORCH_API fill_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::fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Tensor(Tensor self, Tensor value) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & value); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & value); +}; + +struct TORCH_API fill__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::fill_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & value); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & value); +}; + +struct TORCH_API fill__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::fill_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & value); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & value); +}; + +struct TORCH_API fill_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::fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Scalar_out(Tensor self, Scalar value, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & value, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & value, at::Tensor & out); +}; + +struct TORCH_API fill_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::fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Tensor_out(Tensor self, Tensor value, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & value, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & value, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/02/02361b49af673a5bffc9c64e4627dd9bb07e6fd29d282d4757e7062c3b6b27ec/test_multiprocessing.py b/shared/package-files/02/02361b49af673a5bffc9c64e4627dd9bb07e6fd29d282d4757e7062c3b6b27ec/test_multiprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..04a1234b471309574d7e94a8776be9d68a8d97a1 --- /dev/null +++ b/shared/package-files/02/02361b49af673a5bffc9c64e4627dd9bb07e6fd29d282d4757e7062c3b6b27ec/test_multiprocessing.py @@ -0,0 +1,46 @@ +import os +import multiprocessing as mp + +import numpy as np + +from numba import cuda +from numba.cuda.testing import skip_on_cudasim, CUDATestCase +import unittest + +has_mp_get_context = hasattr(mp, 'get_context') +is_unix = os.name == 'posix' + + +def fork_test(q): + from numba.cuda.cudadrv.error import CudaDriverError + try: + cuda.to_device(np.arange(1)) + except CudaDriverError as e: + q.put(e) + else: + q.put(None) + + +@skip_on_cudasim('disabled for cudasim') +class TestMultiprocessing(CUDATestCase): + @unittest.skipUnless(has_mp_get_context, 'requires mp.get_context') + @unittest.skipUnless(is_unix, 'requires Unix') + def test_fork(self): + """ + Test fork detection. + """ + cuda.current_context() # force cuda initialize + # fork in process that also uses CUDA + ctx = mp.get_context('fork') + q = ctx.Queue() + proc = ctx.Process(target=fork_test, args=[q]) + proc.start() + exc = q.get() + proc.join() + # there should be an exception raised in the child process + self.assertIsNotNone(exc) + self.assertIn('CUDA initialized before forking', str(exc)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/02/023872fe9f03a25387cf2c17fc950cf0f990353df66e603c3a1cd3199dbccd86/fix_operator.py b/shared/package-files/02/023872fe9f03a25387cf2c17fc950cf0f990353df66e603c3a1cd3199dbccd86/fix_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..d303cd2018befb0745f2868068becf9f350b9b3d --- /dev/null +++ b/shared/package-files/02/023872fe9f03a25387cf2c17fc950cf0f990353df66e603c3a1cd3199dbccd86/fix_operator.py @@ -0,0 +1,97 @@ +"""Fixer for operator functions. + +operator.isCallable(obj) -> callable(obj) +operator.sequenceIncludes(obj) -> operator.contains(obj) +operator.isSequenceType(obj) -> isinstance(obj, collections.abc.Sequence) +operator.isMappingType(obj) -> isinstance(obj, collections.abc.Mapping) +operator.isNumberType(obj) -> isinstance(obj, numbers.Number) +operator.repeat(obj, n) -> operator.mul(obj, n) +operator.irepeat(obj, n) -> operator.imul(obj, n) +""" + +import collections.abc + +# Local imports +from lib2to3 import fixer_base +from lib2to3.fixer_util import Call, Name, String, touch_import + + +def invocation(s): + def dec(f): + f.invocation = s + return f + return dec + + +class FixOperator(fixer_base.BaseFix): + BM_compatible = True + order = "pre" + + methods = """ + method=('isCallable'|'sequenceIncludes' + |'isSequenceType'|'isMappingType'|'isNumberType' + |'repeat'|'irepeat') + """ + obj = "'(' obj=any ')'" + PATTERN = """ + power< module='operator' + trailer< '.' %(methods)s > trailer< %(obj)s > > + | + power< %(methods)s trailer< %(obj)s > > + """ % dict(methods=methods, obj=obj) + + def transform(self, node, results): + method = self._check_method(node, results) + if method is not None: + return method(node, results) + + @invocation("operator.contains(%s)") + def _sequenceIncludes(self, node, results): + return self._handle_rename(node, results, "contains") + + @invocation("callable(%s)") + def _isCallable(self, node, results): + obj = results["obj"] + return Call(Name("callable"), [obj.clone()], prefix=node.prefix) + + @invocation("operator.mul(%s)") + def _repeat(self, node, results): + return self._handle_rename(node, results, "mul") + + @invocation("operator.imul(%s)") + def _irepeat(self, node, results): + return self._handle_rename(node, results, "imul") + + @invocation("isinstance(%s, collections.abc.Sequence)") + def _isSequenceType(self, node, results): + return self._handle_type2abc(node, results, "collections.abc", "Sequence") + + @invocation("isinstance(%s, collections.abc.Mapping)") + def _isMappingType(self, node, results): + return self._handle_type2abc(node, results, "collections.abc", "Mapping") + + @invocation("isinstance(%s, numbers.Number)") + def _isNumberType(self, node, results): + return self._handle_type2abc(node, results, "numbers", "Number") + + def _handle_rename(self, node, results, name): + method = results["method"][0] + method.value = name + method.changed() + + def _handle_type2abc(self, node, results, module, abc): + touch_import(None, module, node) + obj = results["obj"] + args = [obj.clone(), String(", " + ".".join([module, abc]))] + return Call(Name("isinstance"), args, prefix=node.prefix) + + def _check_method(self, node, results): + method = getattr(self, "_" + results["method"][0].value) + if isinstance(method, collections.abc.Callable): + if "module" in results: + return method + else: + sub = (str(results["obj"]),) + invocation_str = method.invocation % sub + self.warning(node, "You should use '%s' here." % invocation_str) + return None diff --git a/shared/package-files/02/023c3bb9dead92eb49f431aadc435a69e5ef7fa8e88e82ad34f426eabf0f0701/fft_fftn_compositeimplicitautograd_dispatch.h b/shared/package-files/02/023c3bb9dead92eb49f431aadc435a69e5ef7fa8e88e82ad34f426eabf0f0701/fft_fftn_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..5123627879e168151a8b9a22440101658c9ac0e4 --- /dev/null +++ b/shared/package-files/02/023c3bb9dead92eb49f431aadc435a69e5ef7fa8e88e82ad34f426eabf0f0701/fft_fftn_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 fft_fftn(const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor fft_fftn_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor & fft_fftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor & fft_fftn_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm, at::Tensor & out); +TORCH_API at::Tensor & fft_fftn_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor & fft_fftn_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/02/023c4e4d6552b9693e65e86713a27315531459a94e8b54493faaca5f5031ce7d/_slow_conv2d_backward_cpu_dispatch.h b/shared/package-files/02/023c4e4d6552b9693e65e86713a27315531459a94e8b54493faaca5f5031ce7d/_slow_conv2d_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2acaafc1a4732379ef134c9018fb14574bb68857 --- /dev/null +++ b/shared/package-files/02/023c4e4d6552b9693e65e86713a27315531459a94e8b54493faaca5f5031ce7d/_slow_conv2d_backward_cpu_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 cpu { + +TORCH_API ::std::tuple _slow_conv2d_backward_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding); +TORCH_API ::std::tuple _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias); +TORCH_API ::std::tuple _slow_conv2d_backward_symint_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding); +TORCH_API ::std::tuple _slow_conv2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias); +TORCH_API ::std::tuple _slow_conv2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array output_mask); +TORCH_API ::std::tuple _slow_conv2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/02/023d292c442b3477106e4b6755abaed01afc7b80c6878f4084d3478832a140e4/direct_url.json b/shared/package-files/02/023d292c442b3477106e4b6755abaed01afc7b80c6878f4084d3478832a140e4/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..76212767040ee5dc3d1c4ea5c47772e11c033b4e --- /dev/null +++ b/shared/package-files/02/023d292c442b3477106e4b6755abaed01afc7b80c6878f4084d3478832a140e4/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/pytz_1695131579487/work"} \ No newline at end of file diff --git a/shared/package-files/02/023e5dc747d51d3fc1ecdaa58958424c0f690bf440912ad93eba18eff584d1fd/memory_snapshot.h b/shared/package-files/02/023e5dc747d51d3fc1ecdaa58958424c0f690bf440912ad93eba18eff584d1fd/memory_snapshot.h new file mode 100644 index 0000000000000000000000000000000000000000..f5f9bdbed1620e9777ade18fe70690fd0cc01892 --- /dev/null +++ b/shared/package-files/02/023e5dc747d51d3fc1ecdaa58958424c0f690bf440912ad93eba18eff584d1fd/memory_snapshot.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::cuda { + +// C++-only versions of these, for python use +// those defined in cuda/Module.cpp which also record python state. +TORCH_CUDA_CU_API void _record_memory_history( + bool enabled, + bool record_context = true, + int64_t trace_alloc_max_entries = 1, + bool trace_alloc_record_context = false, + bool record_cpp_context = false); + +TORCH_CUDA_CU_API void _record_memory_history( + c10::optional enabled = "all", + c10::optional context = "all", + const std::string& stacks = "all", + size_t max_entries = SIZE_MAX); + +TORCH_CUDA_CU_API std::string _memory_snapshot_pickled(); + +} // namespace torch::cuda diff --git a/shared/package-files/02/02400a365357a04774bb02b8365809e39390d72c9c6f1a69bdd60be41923fe9e/import_export_helpers.h b/shared/package-files/02/02400a365357a04774bb02b8365809e39390d72c9c6f1a69bdd60be41923fe9e/import_export_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..c94993207e6a3cd0c9277496ee4dbe2ee547b345 --- /dev/null +++ b/shared/package-files/02/02400a365357a04774bb02b8365809e39390d72c9c6f1a69bdd60be41923fe9e/import_export_helpers.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include + +namespace caffe2 { +namespace serialize { +class PyTorchStreamReader; +} +} // namespace caffe2 + +namespace torch { +namespace jit { + +struct Source; + +// Convert a class type's qualifier name to the corresponding path the source +// file it should be written to. +// +// Qualifier is like: foo.bar.baz +// Returns: libs/foo/bar/baz.py +std::string qualifierToArchivePath( + const std::string& qualifier, + const std::string& export_prefix); + +std::shared_ptr findSourceInArchiveFromQualifier( + caffe2::serialize::PyTorchStreamReader& reader, + const std::string& export_prefix, + const std::string& qualifier); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/02/024983a51d08171a34adeb7dd6d44f614aab8107d0dfaee8913b7611ed959bad/test_partitions.py b/shared/package-files/02/024983a51d08171a34adeb7dd6d44f614aab8107d0dfaee8913b7611ed959bad/test_partitions.py new file mode 100644 index 0000000000000000000000000000000000000000..1a347899c2efc8ae2b8a417dbb422a83cd529c61 --- /dev/null +++ b/shared/package-files/02/024983a51d08171a34adeb7dd6d44f614aab8107d0dfaee8913b7611ed959bad/test_partitions.py @@ -0,0 +1,12 @@ +from sympy.ntheory import npartitions + + +def test_partitions(): + assert [npartitions(k) for k in range(13)] == \ + [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77] + assert npartitions(100) == 190569292 + assert npartitions(200) == 3972999029388 + assert npartitions(1000) == 24061467864032622473692149727991 + assert npartitions(2000) == 4720819175619413888601432406799959512200344166 + assert npartitions(10000) % 10**10 == 6916435144 + assert npartitions(100000) % 10**10 == 9421098519 diff --git a/shared/package-files/02/024e76301aa38fc4e4c57e4cb51abbccb0d1fe8ddcd3f49d4095d4d550ef6d37/cudnn_convolution_transpose_compositeexplicitautograd_dispatch.h b/shared/package-files/02/024e76301aa38fc4e4c57e4cb51abbccb0d1fe8ddcd3f49d4095d4d550ef6d37/cudnn_convolution_transpose_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d04e9214806b006d335ee0fe689a0285f72fcca2 --- /dev/null +++ b/shared/package-files/02/024e76301aa38fc4e4c57e4cb51abbccb0d1fe8ddcd3f49d4095d4d550ef6d37/cudnn_convolution_transpose_compositeexplicitautograd_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 compositeexplicitautograd { + +TORCH_API at::Tensor & cudnn_convolution_transpose_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, bool allow_tf32); +TORCH_API at::Tensor & cudnn_convolution_transpose_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out); +TORCH_API at::Tensor & cudnn_convolution_transpose_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32); +TORCH_API at::Tensor & cudnn_convolution_transpose_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/02/0250ba18275c1b7b4d54a7e5e5b2353d0408b938baae10783661d24123dc31d0/test_register.py b/shared/package-files/02/0250ba18275c1b7b4d54a7e5e5b2353d0408b938baae10783661d24123dc31d0/test_register.py new file mode 100644 index 0000000000000000000000000000000000000000..bba48633c9c14ab7cc6647751156ffeebbaf41a6 --- /dev/null +++ b/shared/package-files/02/0250ba18275c1b7b4d54a7e5e5b2353d0408b938baae10783661d24123dc31d0/test_register.py @@ -0,0 +1,324 @@ +"""Tests for distutils.command.register.""" +import os +import unittest +import getpass +import urllib +import warnings + +from test.support import run_unittest +from test.support.warnings_helper import check_warnings + +from distutils.command import register as register_module +from distutils.command.register import register +from distutils.errors import DistutilsSetupError +from distutils.log import INFO + +from distutils.tests.test_config import BasePyPIRCCommandTestCase + +try: + import docutils +except ImportError: + docutils = None + +PYPIRC_NOPASSWORD = """\ +[distutils] + +index-servers = + server1 + +[server1] +username:me +""" + +WANTED_PYPIRC = """\ +[distutils] +index-servers = + pypi + +[pypi] +username:tarek +password:password +""" + +class Inputs(object): + """Fakes user inputs.""" + def __init__(self, *answers): + self.answers = answers + self.index = 0 + + def __call__(self, prompt=''): + try: + return self.answers[self.index] + finally: + self.index += 1 + +class FakeOpener(object): + """Fakes a PyPI server""" + def __init__(self): + self.reqs = [] + + def __call__(self, *args): + return self + + def open(self, req, data=None, timeout=None): + self.reqs.append(req) + return self + + def read(self): + return b'xxx' + + def getheader(self, name, default=None): + return { + 'content-type': 'text/plain; charset=utf-8', + }.get(name.lower(), default) + + +class RegisterTestCase(BasePyPIRCCommandTestCase): + + def setUp(self): + super(RegisterTestCase, self).setUp() + # patching the password prompt + self._old_getpass = getpass.getpass + def _getpass(prompt): + return 'password' + getpass.getpass = _getpass + urllib.request._opener = None + self.old_opener = urllib.request.build_opener + self.conn = urllib.request.build_opener = FakeOpener() + + def tearDown(self): + getpass.getpass = self._old_getpass + urllib.request._opener = None + urllib.request.build_opener = self.old_opener + super(RegisterTestCase, self).tearDown() + + def _get_cmd(self, metadata=None): + if metadata is None: + metadata = {'url': 'xxx', 'author': 'xxx', + 'author_email': 'xxx', + 'name': 'xxx', 'version': 'xxx'} + pkg_info, dist = self.create_dist(**metadata) + return register(dist) + + def test_create_pypirc(self): + # this test makes sure a .pypirc file + # is created when requested. + + # let's create a register instance + cmd = self._get_cmd() + + # we shouldn't have a .pypirc file yet + self.assertFalse(os.path.exists(self.rc)) + + # patching input and getpass.getpass + # so register gets happy + # + # Here's what we are faking : + # use your existing login (choice 1.) + # Username : 'tarek' + # Password : 'password' + # Save your login (y/N)? : 'y' + inputs = Inputs('1', 'tarek', 'y') + register_module.input = inputs.__call__ + # let's run the command + try: + cmd.run() + finally: + del register_module.input + + # we should have a brand new .pypirc file + self.assertTrue(os.path.exists(self.rc)) + + # with the content similar to WANTED_PYPIRC + f = open(self.rc) + try: + content = f.read() + self.assertEqual(content, WANTED_PYPIRC) + finally: + f.close() + + # now let's make sure the .pypirc file generated + # really works : we shouldn't be asked anything + # if we run the command again + def _no_way(prompt=''): + raise AssertionError(prompt) + register_module.input = _no_way + + cmd.show_response = 1 + cmd.run() + + # let's see what the server received : we should + # have 2 similar requests + self.assertEqual(len(self.conn.reqs), 2) + req1 = dict(self.conn.reqs[0].headers) + req2 = dict(self.conn.reqs[1].headers) + + self.assertEqual(req1['Content-length'], '1374') + self.assertEqual(req2['Content-length'], '1374') + self.assertIn(b'xxx', self.conn.reqs[1].data) + + def test_password_not_in_file(self): + + self.write_file(self.rc, PYPIRC_NOPASSWORD) + cmd = self._get_cmd() + cmd._set_config() + cmd.finalize_options() + cmd.send_metadata() + + # dist.password should be set + # therefore used afterwards by other commands + self.assertEqual(cmd.distribution.password, 'password') + + def test_registering(self): + # this test runs choice 2 + cmd = self._get_cmd() + inputs = Inputs('2', 'tarek', 'tarek@ziade.org') + register_module.input = inputs.__call__ + try: + # let's run the command + cmd.run() + finally: + del register_module.input + + # we should have send a request + self.assertEqual(len(self.conn.reqs), 1) + req = self.conn.reqs[0] + headers = dict(req.headers) + self.assertEqual(headers['Content-length'], '608') + self.assertIn(b'tarek', req.data) + + def test_password_reset(self): + # this test runs choice 3 + cmd = self._get_cmd() + inputs = Inputs('3', 'tarek@ziade.org') + register_module.input = inputs.__call__ + try: + # let's run the command + cmd.run() + finally: + del register_module.input + + # we should have send a request + self.assertEqual(len(self.conn.reqs), 1) + req = self.conn.reqs[0] + headers = dict(req.headers) + self.assertEqual(headers['Content-length'], '290') + self.assertIn(b'tarek', req.data) + + @unittest.skipUnless(docutils is not None, 'needs docutils') + def test_strict(self): + # testing the script option + # when on, the register command stops if + # the metadata is incomplete or if + # long_description is not reSt compliant + + # empty metadata + cmd = self._get_cmd({}) + cmd.ensure_finalized() + cmd.strict = 1 + self.assertRaises(DistutilsSetupError, cmd.run) + + # metadata are OK but long_description is broken + metadata = {'url': 'xxx', 'author': 'xxx', + 'author_email': 'éxéxé', + 'name': 'xxx', 'version': 'xxx', + 'long_description': 'title\n==\n\ntext'} + + cmd = self._get_cmd(metadata) + cmd.ensure_finalized() + cmd.strict = 1 + self.assertRaises(DistutilsSetupError, cmd.run) + + # now something that works + metadata['long_description'] = 'title\n=====\n\ntext' + cmd = self._get_cmd(metadata) + cmd.ensure_finalized() + cmd.strict = 1 + inputs = Inputs('1', 'tarek', 'y') + register_module.input = inputs.__call__ + # let's run the command + try: + cmd.run() + finally: + del register_module.input + + # strict is not by default + cmd = self._get_cmd() + cmd.ensure_finalized() + inputs = Inputs('1', 'tarek', 'y') + register_module.input = inputs.__call__ + # let's run the command + try: + cmd.run() + finally: + del register_module.input + + # and finally a Unicode test (bug #12114) + metadata = {'url': 'xxx', 'author': '\u00c9ric', + 'author_email': 'xxx', 'name': 'xxx', + 'version': 'xxx', + 'description': 'Something about esszet \u00df', + 'long_description': 'More things about esszet \u00df'} + + cmd = self._get_cmd(metadata) + cmd.ensure_finalized() + cmd.strict = 1 + inputs = Inputs('1', 'tarek', 'y') + register_module.input = inputs.__call__ + # let's run the command + try: + cmd.run() + finally: + del register_module.input + + @unittest.skipUnless(docutils is not None, 'needs docutils') + def test_register_invalid_long_description(self): + description = ':funkie:`str`' # mimic Sphinx-specific markup + metadata = {'url': 'xxx', 'author': 'xxx', + 'author_email': 'xxx', + 'name': 'xxx', 'version': 'xxx', + 'long_description': description} + cmd = self._get_cmd(metadata) + cmd.ensure_finalized() + cmd.strict = True + inputs = Inputs('2', 'tarek', 'tarek@ziade.org') + register_module.input = inputs + self.addCleanup(delattr, register_module, 'input') + + self.assertRaises(DistutilsSetupError, cmd.run) + + def test_check_metadata_deprecated(self): + # makes sure make_metadata is deprecated + cmd = self._get_cmd() + with check_warnings() as w: + warnings.simplefilter("always") + cmd.check_metadata() + self.assertEqual(len(w.warnings), 1) + + def test_list_classifiers(self): + cmd = self._get_cmd() + cmd.list_classifiers = 1 + cmd.run() + results = self.get_logs(INFO) + self.assertEqual(results, ['running check', 'xxx']) + + def test_show_response(self): + # test that the --show-response option return a well formatted response + cmd = self._get_cmd() + inputs = Inputs('1', 'tarek', 'y') + register_module.input = inputs.__call__ + cmd.show_response = 1 + try: + cmd.run() + finally: + del register_module.input + + results = self.get_logs(INFO) + self.assertEqual(results[3], 75 * '-' + '\nxxx\n' + 75 * '-') + + +def test_suite(): + return unittest.makeSuite(RegisterTestCase) + +if __name__ == "__main__": + run_unittest(test_suite()) diff --git a/shared/package-files/02/0258ffb6181b7487bacc36f2af8c1e88469f25fe6819e5f66167ade2c027eece/_sparse_sum_ops.h b/shared/package-files/02/0258ffb6181b7487bacc36f2af8c1e88469f25fe6819e5f66167ade2c027eece/_sparse_sum_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d4d73a86f7699930e471a193545016ce990ec9ee --- /dev/null +++ b/shared/package-files/02/0258ffb6181b7487bacc36f2af8c1e88469f25fe6819e5f66167ade2c027eece/_sparse_sum_ops.h @@ -0,0 +1,72 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _sparse_sum { + 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::_sparse_sum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum(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 _sparse_sum_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::_sparse_sum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dtype") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dtype(Tensor self, *, ScalarType dtype) -> Tensor") + 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); +}; + +struct TORCH_API _sparse_sum_dim { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_sum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dim(Tensor self, int[1] dim) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim); +}; + +struct TORCH_API _sparse_sum_dim_dtype { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::ScalarType); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_sum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_dtype") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dim_dtype(Tensor self, int[1] dim, *, ScalarType dtype) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim, at::ScalarType dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, at::ScalarType dtype); +}; + +struct TORCH_API _sparse_sum_dim_out { + using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_sum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dim_out(Tensor self, int[1] dim, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::IntArrayRef dim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/02/025a9531e3046e52d3e039c0be04f9a5a74651d7683a13c7c7ebd4c7dfb5996a/hz.py b/shared/package-files/02/025a9531e3046e52d3e039c0be04f9a5a74651d7683a13c7c7ebd4c7dfb5996a/hz.py new file mode 100644 index 0000000000000000000000000000000000000000..383442a3c9ac9ae5d093d972f1ff26fe758897d5 --- /dev/null +++ b/shared/package-files/02/025a9531e3046e52d3e039c0be04f9a5a74651d7683a13c7c7ebd4c7dfb5996a/hz.py @@ -0,0 +1,39 @@ +# +# hz.py: Python Unicode Codec for HZ +# +# Written by Hye-Shik Chang +# + +import _codecs_cn, codecs +import _multibytecodec as mbc + +codec = _codecs_cn.getcodec('hz') + +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='hz', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) diff --git a/shared/package-files/02/025b702d601b96948b6bedb82af36ec58c4cd88795979a7677e928cc0f5027ed/test_cluster.py b/shared/package-files/02/025b702d601b96948b6bedb82af36ec58c4cd88795979a7677e928cc0f5027ed/test_cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..d69f036ff6cc87e179af5fde6ce7ee21b6c193c4 --- /dev/null +++ b/shared/package-files/02/025b702d601b96948b6bedb82af36ec58c4cd88795979a7677e928cc0f5027ed/test_cluster.py @@ -0,0 +1,543 @@ +import pytest + +import networkx as nx + + +class TestTriangles: + def test_empty(self): + G = nx.Graph() + assert list(nx.triangles(G).values()) == [] + + def test_path(self): + G = nx.path_graph(10) + assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + assert nx.triangles(G) == { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + } + + def test_cubical(self): + G = nx.cubical_graph() + assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0] + assert nx.triangles(G, 1) == 0 + assert list(nx.triangles(G, [1, 2]).values()) == [0, 0] + assert nx.triangles(G, 1) == 0 + assert nx.triangles(G, [1, 2]) == {1: 0, 2: 0} + + def test_k5(self): + G = nx.complete_graph(5) + assert list(nx.triangles(G).values()) == [6, 6, 6, 6, 6] + assert sum(nx.triangles(G).values()) / 3 == 10 + assert nx.triangles(G, 1) == 6 + G.remove_edge(1, 2) + assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5] + assert nx.triangles(G, 1) == 3 + G.add_edge(3, 3) # ignore self-edges + assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5] + assert nx.triangles(G, 3) == 5 + + +class TestDirectedClustering: + def test_clustering(self): + G = nx.DiGraph() + assert list(nx.clustering(G).values()) == [] + assert nx.clustering(G) == {} + + def test_path(self): + G = nx.path_graph(10, create_using=nx.DiGraph()) + assert list(nx.clustering(G).values()) == [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + assert nx.clustering(G) == { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + } + assert nx.clustering(G, 0) == 0 + + def test_k5(self): + G = nx.complete_graph(5, create_using=nx.DiGraph()) + assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1] + assert nx.average_clustering(G) == 1 + G.remove_edge(1, 2) + assert list(nx.clustering(G).values()) == [ + 11 / 12, + 1, + 1, + 11 / 12, + 11 / 12, + ] + assert nx.clustering(G, [1, 4]) == {1: 1, 4: 11 / 12} + G.remove_edge(2, 1) + assert list(nx.clustering(G).values()) == [ + 5 / 6, + 1, + 1, + 5 / 6, + 5 / 6, + ] + assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337} + assert nx.clustering(G, 4) == 5 / 6 + + def test_triangle_and_edge(self): + G = nx.cycle_graph(3, create_using=nx.DiGraph()) + G.add_edge(0, 4) + assert nx.clustering(G)[0] == 1 / 6 + + +class TestDirectedWeightedClustering: + @classmethod + def setup_class(cls): + global np + np = pytest.importorskip("numpy") + + def test_clustering(self): + G = nx.DiGraph() + assert list(nx.clustering(G, weight="weight").values()) == [] + assert nx.clustering(G) == {} + + def test_path(self): + G = nx.path_graph(10, create_using=nx.DiGraph()) + assert list(nx.clustering(G, weight="weight").values()) == [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + assert nx.clustering(G, weight="weight") == { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + } + + def test_k5(self): + G = nx.complete_graph(5, create_using=nx.DiGraph()) + assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1] + assert nx.average_clustering(G, weight="weight") == 1 + G.remove_edge(1, 2) + assert list(nx.clustering(G, weight="weight").values()) == [ + 11 / 12, + 1, + 1, + 11 / 12, + 11 / 12, + ] + assert nx.clustering(G, [1, 4], weight="weight") == {1: 1, 4: 11 / 12} + G.remove_edge(2, 1) + assert list(nx.clustering(G, weight="weight").values()) == [ + 5 / 6, + 1, + 1, + 5 / 6, + 5 / 6, + ] + assert nx.clustering(G, [1, 4], weight="weight") == { + 1: 1, + 4: 0.83333333333333337, + } + + def test_triangle_and_edge(self): + G = nx.cycle_graph(3, create_using=nx.DiGraph()) + G.add_edge(0, 4, weight=2) + assert nx.clustering(G)[0] == 1 / 6 + # Relaxed comparisons to allow graphblas-algorithms to pass tests + np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 12) + np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 12) + + +class TestWeightedClustering: + @classmethod + def setup_class(cls): + global np + np = pytest.importorskip("numpy") + + def test_clustering(self): + G = nx.Graph() + assert list(nx.clustering(G, weight="weight").values()) == [] + assert nx.clustering(G) == {} + + def test_path(self): + G = nx.path_graph(10) + assert list(nx.clustering(G, weight="weight").values()) == [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + assert nx.clustering(G, weight="weight") == { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + } + + def test_cubical(self): + G = nx.cubical_graph() + assert list(nx.clustering(G, weight="weight").values()) == [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + assert nx.clustering(G, 1) == 0 + assert list(nx.clustering(G, [1, 2], weight="weight").values()) == [0, 0] + assert nx.clustering(G, 1, weight="weight") == 0 + assert nx.clustering(G, [1, 2], weight="weight") == {1: 0, 2: 0} + + def test_k5(self): + G = nx.complete_graph(5) + assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1] + assert nx.average_clustering(G, weight="weight") == 1 + G.remove_edge(1, 2) + assert list(nx.clustering(G, weight="weight").values()) == [ + 5 / 6, + 1, + 1, + 5 / 6, + 5 / 6, + ] + assert nx.clustering(G, [1, 4], weight="weight") == { + 1: 1, + 4: 0.83333333333333337, + } + + def test_triangle_and_edge(self): + G = nx.cycle_graph(3) + G.add_edge(0, 4, weight=2) + assert nx.clustering(G)[0] == 1 / 3 + np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 6) + np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 6) + + def test_triangle_and_signed_edge(self): + G = nx.cycle_graph(3) + G.add_edge(0, 1, weight=-1) + G.add_edge(3, 0, weight=0) + assert nx.clustering(G)[0] == 1 / 3 + assert nx.clustering(G, weight="weight")[0] == -1 / 3 + + +class TestClustering: + @classmethod + def setup_class(cls): + pytest.importorskip("numpy") + + def test_clustering(self): + G = nx.Graph() + assert list(nx.clustering(G).values()) == [] + assert nx.clustering(G) == {} + + def test_path(self): + G = nx.path_graph(10) + assert list(nx.clustering(G).values()) == [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + assert nx.clustering(G) == { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + } + + def test_cubical(self): + G = nx.cubical_graph() + assert list(nx.clustering(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0] + assert nx.clustering(G, 1) == 0 + assert list(nx.clustering(G, [1, 2]).values()) == [0, 0] + assert nx.clustering(G, 1) == 0 + assert nx.clustering(G, [1, 2]) == {1: 0, 2: 0} + + def test_k5(self): + G = nx.complete_graph(5) + assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1] + assert nx.average_clustering(G) == 1 + G.remove_edge(1, 2) + assert list(nx.clustering(G).values()) == [ + 5 / 6, + 1, + 1, + 5 / 6, + 5 / 6, + ] + assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337} + + def test_k5_signed(self): + G = nx.complete_graph(5) + assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1] + assert nx.average_clustering(G) == 1 + G.remove_edge(1, 2) + G.add_edge(0, 1, weight=-1) + assert list(nx.clustering(G, weight="weight").values()) == [ + 1 / 6, + -1 / 3, + 1, + 3 / 6, + 3 / 6, + ] + + +class TestTransitivity: + def test_transitivity(self): + G = nx.Graph() + assert nx.transitivity(G) == 0 + + def test_path(self): + G = nx.path_graph(10) + assert nx.transitivity(G) == 0 + + def test_cubical(self): + G = nx.cubical_graph() + assert nx.transitivity(G) == 0 + + def test_k5(self): + G = nx.complete_graph(5) + assert nx.transitivity(G) == 1 + G.remove_edge(1, 2) + assert nx.transitivity(G) == 0.875 + + +class TestSquareClustering: + def test_clustering(self): + G = nx.Graph() + assert list(nx.square_clustering(G).values()) == [] + assert nx.square_clustering(G) == {} + + def test_path(self): + G = nx.path_graph(10) + assert list(nx.square_clustering(G).values()) == [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + assert nx.square_clustering(G) == { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + } + + def test_cubical(self): + G = nx.cubical_graph() + assert list(nx.square_clustering(G).values()) == [ + 1 / 3, + 1 / 3, + 1 / 3, + 1 / 3, + 1 / 3, + 1 / 3, + 1 / 3, + 1 / 3, + ] + assert list(nx.square_clustering(G, [1, 2]).values()) == [1 / 3, 1 / 3] + assert nx.square_clustering(G, [1])[1] == 1 / 3 + assert nx.square_clustering(G, 1) == 1 / 3 + assert nx.square_clustering(G, [1, 2]) == {1: 1 / 3, 2: 1 / 3} + + def test_k5(self): + G = nx.complete_graph(5) + assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1] + + def test_bipartite_k5(self): + G = nx.complete_bipartite_graph(5, 5) + assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + + def test_lind_square_clustering(self): + """Test C4 for figure 1 Lind et al (2005)""" + G = nx.Graph( + [ + (1, 2), + (1, 3), + (1, 6), + (1, 7), + (2, 4), + (2, 5), + (3, 4), + (3, 5), + (6, 7), + (7, 8), + (6, 8), + (7, 9), + (7, 10), + (6, 11), + (6, 12), + (2, 13), + (2, 14), + (3, 15), + (3, 16), + ] + ) + G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16]) + G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12]) + assert nx.square_clustering(G, [1])[1] == 3 / 43 + assert nx.square_clustering(G1, [1])[1] == 2 / 6 + assert nx.square_clustering(G2, [1])[1] == 1 / 5 + + def test_peng_square_clustering(self): + """Test eq2 for figure 1 Peng et al (2008)""" + G = nx.Graph([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (3, 6)]) + assert nx.square_clustering(G, [1])[1] == 1 / 3 + + +class TestAverageClustering: + @classmethod + def setup_class(cls): + pytest.importorskip("numpy") + + def test_empty(self): + G = nx.Graph() + with pytest.raises(ZeroDivisionError): + nx.average_clustering(G) + + def test_average_clustering(self): + G = nx.cycle_graph(3) + G.add_edge(2, 3) + assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 4 + assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 4 + assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 3 + assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 3 + assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 3 + assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 2 + + def test_average_clustering_signed(self): + G = nx.cycle_graph(3) + G.add_edge(2, 3) + G.add_edge(0, 1, weight=-1) + assert nx.average_clustering(G, weight="weight") == (-1 - 1 - 1 / 3) / 4 + assert ( + nx.average_clustering(G, weight="weight", count_zeros=True) + == (-1 - 1 - 1 / 3) / 4 + ) + assert ( + nx.average_clustering(G, weight="weight", count_zeros=False) + == (-1 - 1 - 1 / 3) / 3 + ) + + +class TestDirectedAverageClustering: + @classmethod + def setup_class(cls): + pytest.importorskip("numpy") + + def test_empty(self): + G = nx.DiGraph() + with pytest.raises(ZeroDivisionError): + nx.average_clustering(G) + + def test_average_clustering(self): + G = nx.cycle_graph(3, create_using=nx.DiGraph()) + G.add_edge(2, 3) + assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 8 + assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 8 + assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 6 + assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 6 + assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 6 + assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 4 + + +class TestGeneralizedDegree: + def test_generalized_degree(self): + G = nx.Graph() + assert nx.generalized_degree(G) == {} + + def test_path(self): + G = nx.path_graph(5) + assert nx.generalized_degree(G, 0) == {0: 1} + assert nx.generalized_degree(G, 1) == {0: 2} + + def test_cubical(self): + G = nx.cubical_graph() + assert nx.generalized_degree(G, 0) == {0: 3} + + def test_k5(self): + G = nx.complete_graph(5) + assert nx.generalized_degree(G, 0) == {3: 4} + G.remove_edge(0, 1) + assert nx.generalized_degree(G, 0) == {2: 3} + assert nx.generalized_degree(G, [1, 2]) == {1: {2: 3}, 2: {2: 2, 3: 2}} + assert nx.generalized_degree(G) == { + 0: {2: 3}, + 1: {2: 3}, + 2: {2: 2, 3: 2}, + 3: {2: 2, 3: 2}, + 4: {2: 2, 3: 2}, + } diff --git a/shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/Perth b/shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/Perth new file mode 100644 index 0000000000000000000000000000000000000000..f8ddbdf215d34b022af11c3d1930dd6ea4dca87e Binary files /dev/null and b/shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/Perth differ diff --git a/shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/West b/shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/West new file mode 100644 index 0000000000000000000000000000000000000000..f8ddbdf215d34b022af11c3d1930dd6ea4dca87e Binary files /dev/null and b/shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/West differ diff --git a/shared/package-files/02/025d8146a57a50508862173f59f39378ccb975b89ef392b45b4bd345cb66b013/test_impute.py b/shared/package-files/02/025d8146a57a50508862173f59f39378ccb975b89ef392b45b4bd345cb66b013/test_impute.py new file mode 100644 index 0000000000000000000000000000000000000000..4116964c49a7a3be21771593e60e24515a7b475c --- /dev/null +++ b/shared/package-files/02/025d8146a57a50508862173f59f39378ccb975b89ef392b45b4bd345cb66b013/test_impute.py @@ -0,0 +1,1955 @@ +import io +import re +import warnings +from itertools import product + +import numpy as np +import pytest +from scipy import sparse +from scipy.stats import kstest + +from sklearn import tree +from sklearn.datasets import load_diabetes +from sklearn.dummy import DummyRegressor +from sklearn.exceptions import ConvergenceWarning + +# make IterativeImputer available +from sklearn.experimental import enable_iterative_imputer # noqa: F401 +from sklearn.impute import IterativeImputer, KNNImputer, MissingIndicator, SimpleImputer +from sklearn.impute._base import _most_frequent +from sklearn.linear_model import ARDRegression, BayesianRidge, RidgeCV +from sklearn.model_selection import GridSearchCV +from sklearn.pipeline import Pipeline, make_union +from sklearn.random_projection import _sparse_random_matrix +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_allclose_dense_sparse, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.fixes import ( + BSR_CONTAINERS, + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + LIL_CONTAINERS, +) + + +def _assert_array_equal_and_same_dtype(x, y): + assert_array_equal(x, y) + assert x.dtype == y.dtype + + +def _assert_allclose_and_same_dtype(x, y): + assert_allclose(x, y) + assert x.dtype == y.dtype + + +def _check_statistics( + X, X_true, strategy, statistics, missing_values, sparse_container +): + """Utility function for testing imputation for a given strategy. + + Test with dense and sparse arrays + + Check that: + - the statistics (mean, median, mode) are correct + - the missing values are imputed correctly""" + + err_msg = "Parameters: strategy = %s, missing_values = %s, sparse = {0}" % ( + strategy, + missing_values, + ) + + assert_ae = assert_array_equal + + if X.dtype.kind == "f" or X_true.dtype.kind == "f": + assert_ae = assert_array_almost_equal + + # Normal matrix + imputer = SimpleImputer(missing_values=missing_values, strategy=strategy) + X_trans = imputer.fit(X).transform(X.copy()) + assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(False)) + assert_ae(X_trans, X_true, err_msg=err_msg.format(False)) + + # Sparse matrix + imputer = SimpleImputer(missing_values=missing_values, strategy=strategy) + imputer.fit(sparse_container(X)) + X_trans = imputer.transform(sparse_container(X.copy())) + + if sparse.issparse(X_trans): + X_trans = X_trans.toarray() + + assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(True)) + assert_ae(X_trans, X_true, err_msg=err_msg.format(True)) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_imputation_shape(strategy, csr_container): + # Verify the shapes of the imputed matrix for different strategies. + X = np.random.randn(10, 2) + X[::2] = np.nan + + imputer = SimpleImputer(strategy=strategy) + X_imputed = imputer.fit_transform(csr_container(X)) + assert X_imputed.shape == (10, 2) + X_imputed = imputer.fit_transform(X) + assert X_imputed.shape == (10, 2) + + iterative_imputer = IterativeImputer(initial_strategy=strategy) + X_imputed = iterative_imputer.fit_transform(X) + assert X_imputed.shape == (10, 2) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +def test_imputation_deletion_warning(strategy): + X = np.ones((3, 5)) + X[:, 0] = np.nan + imputer = SimpleImputer(strategy=strategy).fit(X) + + with pytest.warns(UserWarning, match="Skipping"): + imputer.transform(X) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +def test_imputation_deletion_warning_feature_names(strategy): + pd = pytest.importorskip("pandas") + + missing_values = np.nan + feature_names = np.array(["a", "b", "c", "d"], dtype=object) + X = pd.DataFrame( + [ + [missing_values, missing_values, 1, missing_values], + [4, missing_values, 2, 10], + ], + columns=feature_names, + ) + + imputer = SimpleImputer(strategy=strategy).fit(X) + + # check SimpleImputer returning feature name attribute correctly + assert_array_equal(imputer.feature_names_in_, feature_names) + + # ensure that skipped feature warning includes feature name + with pytest.warns( + UserWarning, match=r"Skipping features without any observed values: \['b'\]" + ): + imputer.transform(X) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_error_sparse_0(strategy, csc_container): + # check that error are raised when missing_values = 0 and input is sparse + X = np.ones((3, 5)) + X[0] = 0 + X = csc_container(X) + + imputer = SimpleImputer(strategy=strategy, missing_values=0) + with pytest.raises(ValueError, match="Provide a dense array"): + imputer.fit(X) + + imputer.fit(X.toarray()) + with pytest.raises(ValueError, match="Provide a dense array"): + imputer.transform(X) + + +def safe_median(arr, *args, **kwargs): + # np.median([]) raises a TypeError for numpy >= 1.10.1 + length = arr.size if hasattr(arr, "size") else len(arr) + return np.nan if length == 0 else np.median(arr, *args, **kwargs) + + +def safe_mean(arr, *args, **kwargs): + # np.mean([]) raises a RuntimeWarning for numpy >= 1.10.1 + length = arr.size if hasattr(arr, "size") else len(arr) + return np.nan if length == 0 else np.mean(arr, *args, **kwargs) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_mean_median(csc_container): + # Test imputation using the mean and median strategies, when + # missing_values != 0. + rng = np.random.RandomState(0) + + dim = 10 + dec = 10 + shape = (dim * dim, dim + dec) + + zeros = np.zeros(shape[0]) + values = np.arange(1, shape[0] + 1) + values[4::2] = -values[4::2] + + tests = [ + ("mean", np.nan, lambda z, v, p: safe_mean(np.hstack((z, v)))), + ("median", np.nan, lambda z, v, p: safe_median(np.hstack((z, v)))), + ] + + for strategy, test_missing_values, true_value_fun in tests: + X = np.empty(shape) + X_true = np.empty(shape) + true_statistics = np.empty(shape[1]) + + # Create a matrix X with columns + # - with only zeros, + # - with only missing values + # - with zeros, missing values and values + # And a matrix X_true containing all true values + for j in range(shape[1]): + nb_zeros = (j - dec + 1 > 0) * (j - dec + 1) * (j - dec + 1) + nb_missing_values = max(shape[0] + dec * dec - (j + dec) * (j + dec), 0) + nb_values = shape[0] - nb_zeros - nb_missing_values + + z = zeros[:nb_zeros] + p = np.repeat(test_missing_values, nb_missing_values) + v = values[rng.permutation(len(values))[:nb_values]] + + true_statistics[j] = true_value_fun(z, v, p) + + # Create the columns + X[:, j] = np.hstack((v, z, p)) + + if 0 == test_missing_values: + # XXX unreached code as of v0.22 + X_true[:, j] = np.hstack( + (v, np.repeat(true_statistics[j], nb_missing_values + nb_zeros)) + ) + else: + X_true[:, j] = np.hstack( + (v, z, np.repeat(true_statistics[j], nb_missing_values)) + ) + + # Shuffle them the same way + np.random.RandomState(j).shuffle(X[:, j]) + np.random.RandomState(j).shuffle(X_true[:, j]) + + # Mean doesn't support columns containing NaNs, median does + if strategy == "median": + cols_to_keep = ~np.isnan(X_true).any(axis=0) + else: + cols_to_keep = ~np.isnan(X_true).all(axis=0) + + X_true = X_true[:, cols_to_keep] + + _check_statistics( + X, X_true, strategy, true_statistics, test_missing_values, csc_container + ) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_median_special_cases(csc_container): + # Test median imputation with sparse boundary cases + X = np.array( + [ + [0, np.nan, np.nan], # odd: implicit zero + [5, np.nan, np.nan], # odd: explicit nonzero + [0, 0, np.nan], # even: average two zeros + [-5, 0, np.nan], # even: avg zero and neg + [0, 5, np.nan], # even: avg zero and pos + [4, 5, np.nan], # even: avg nonzeros + [-4, -5, np.nan], # even: avg negatives + [-1, 2, np.nan], # even: crossing neg and pos + ] + ).transpose() + + X_imputed_median = np.array( + [ + [0, 0, 0], + [5, 5, 5], + [0, 0, 0], + [-5, 0, -2.5], + [0, 5, 2.5], + [4, 5, 4.5], + [-4, -5, -4.5], + [-1, 2, 0.5], + ] + ).transpose() + statistics_median = [0, 5, 0, -2.5, 2.5, 4.5, -4.5, 0.5] + + _check_statistics( + X, X_imputed_median, "median", statistics_median, np.nan, csc_container + ) + + +@pytest.mark.parametrize("strategy", ["mean", "median"]) +@pytest.mark.parametrize("dtype", [None, object, str]) +def test_imputation_mean_median_error_invalid_type(strategy, dtype): + X = np.array([["a", "b", 3], [4, "e", 6], ["g", "h", 9]], dtype=dtype) + msg = "non-numeric data:\ncould not convert string to float:" + with pytest.raises(ValueError, match=msg): + imputer = SimpleImputer(strategy=strategy) + imputer.fit_transform(X) + + +@pytest.mark.parametrize("strategy", ["mean", "median"]) +@pytest.mark.parametrize("type", ["list", "dataframe"]) +def test_imputation_mean_median_error_invalid_type_list_pandas(strategy, type): + X = [["a", "b", 3], [4, "e", 6], ["g", "h", 9]] + if type == "dataframe": + pd = pytest.importorskip("pandas") + X = pd.DataFrame(X) + msg = "non-numeric data:\ncould not convert string to float:" + with pytest.raises(ValueError, match=msg): + imputer = SimpleImputer(strategy=strategy) + imputer.fit_transform(X) + + +@pytest.mark.parametrize("strategy", ["constant", "most_frequent"]) +@pytest.mark.parametrize("dtype", [str, np.dtype("U"), np.dtype("S")]) +def test_imputation_const_mostf_error_invalid_types(strategy, dtype): + # Test imputation on non-numeric data using "most_frequent" and "constant" + # strategy + X = np.array( + [ + [np.nan, np.nan, "a", "f"], + [np.nan, "c", np.nan, "d"], + [np.nan, "b", "d", np.nan], + [np.nan, "c", "d", "h"], + ], + dtype=dtype, + ) + + err_msg = "SimpleImputer does not support data" + with pytest.raises(ValueError, match=err_msg): + imputer = SimpleImputer(strategy=strategy) + imputer.fit(X).transform(X) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_most_frequent(csc_container): + # Test imputation using the most-frequent strategy. + X = np.array( + [ + [-1, -1, 0, 5], + [-1, 2, -1, 3], + [-1, 1, 3, -1], + [-1, 2, 3, 7], + ] + ) + + X_true = np.array( + [ + [2, 0, 5], + [2, 3, 3], + [1, 3, 3], + [2, 3, 7], + ] + ) + + # scipy.stats.mode, used in SimpleImputer, doesn't return the first most + # frequent as promised in the doc but the lowest most frequent. When this + # test will fail after an update of scipy, SimpleImputer will need to be + # updated to be consistent with the new (correct) behaviour + _check_statistics(X, X_true, "most_frequent", [np.nan, 2, 3, 3], -1, csc_container) + + +@pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0]) +def test_imputation_most_frequent_objects(marker): + # Test imputation using the most-frequent strategy. + X = np.array( + [ + [marker, marker, "a", "f"], + [marker, "c", marker, "d"], + [marker, "b", "d", marker], + [marker, "c", "d", "h"], + ], + dtype=object, + ) + + X_true = np.array( + [ + ["c", "a", "f"], + ["c", "d", "d"], + ["b", "d", "d"], + ["c", "d", "h"], + ], + dtype=object, + ) + + imputer = SimpleImputer(missing_values=marker, strategy="most_frequent") + X_trans = imputer.fit(X).transform(X) + + assert_array_equal(X_trans, X_true) + + +@pytest.mark.parametrize("dtype", [object, "category"]) +def test_imputation_most_frequent_pandas(dtype): + # Test imputation using the most frequent strategy on pandas df + pd = pytest.importorskip("pandas") + + f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n,i,x,\na,,y,\na,j,,\nb,j,x,") + + df = pd.read_csv(f, dtype=dtype) + + X_true = np.array( + [["a", "i", "x"], ["a", "j", "y"], ["a", "j", "x"], ["b", "j", "x"]], + dtype=object, + ) + + imputer = SimpleImputer(strategy="most_frequent") + X_trans = imputer.fit_transform(df) + + assert_array_equal(X_trans, X_true) + + +@pytest.mark.parametrize("X_data, missing_value", [(1, 0), (1.0, np.nan)]) +def test_imputation_constant_error_invalid_type(X_data, missing_value): + # Verify that exceptions are raised on invalid fill_value type + X = np.full((3, 5), X_data, dtype=float) + X[0, 0] = missing_value + + fill_value = "x" + err_msg = f"fill_value={fill_value!r} (of type {type(fill_value)!r}) cannot be cast" + with pytest.raises(ValueError, match=re.escape(err_msg)): + imputer = SimpleImputer( + missing_values=missing_value, strategy="constant", fill_value=fill_value + ) + imputer.fit_transform(X) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +def test_imputation_constant_integer(): + # Test imputation using the constant strategy on integers + X = np.array([[-1, 2, 3, -1], [4, -1, 5, -1], [6, 7, -1, -1], [8, 9, 0, -1]]) + + X_true = np.array([[0, 2, 3, 0], [4, 0, 5, 0], [6, 7, 0, 0], [8, 9, 0, 0]]) + + imputer = SimpleImputer( + missing_values=-1, strategy="constant", fill_value=0, keep_empty_features=True + ) + X_trans = imputer.fit_transform(X) + + assert_array_equal(X_trans, X_true) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +@pytest.mark.parametrize("array_constructor", CSR_CONTAINERS + [np.asarray]) +def test_imputation_constant_float(array_constructor): + # Test imputation using the constant strategy on floats + X = np.array( + [ + [np.nan, 1.1, 0, np.nan], + [1.2, np.nan, 1.3, np.nan], + [0, 0, np.nan, np.nan], + [1.4, 1.5, 0, np.nan], + ] + ) + + X_true = np.array( + [[-1, 1.1, 0, -1], [1.2, -1, 1.3, -1], [0, 0, -1, -1], [1.4, 1.5, 0, -1]] + ) + + X = array_constructor(X) + + X_true = array_constructor(X_true) + + imputer = SimpleImputer( + strategy="constant", fill_value=-1, keep_empty_features=True + ) + X_trans = imputer.fit_transform(X) + + assert_allclose_dense_sparse(X_trans, X_true) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +@pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0]) +def test_imputation_constant_object(marker): + # Test imputation using the constant strategy on objects + X = np.array( + [ + [marker, "a", "b", marker], + ["c", marker, "d", marker], + ["e", "f", marker, marker], + ["g", "h", "i", marker], + ], + dtype=object, + ) + + X_true = np.array( + [ + ["missing", "a", "b", "missing"], + ["c", "missing", "d", "missing"], + ["e", "f", "missing", "missing"], + ["g", "h", "i", "missing"], + ], + dtype=object, + ) + + imputer = SimpleImputer( + missing_values=marker, + strategy="constant", + fill_value="missing", + keep_empty_features=True, + ) + X_trans = imputer.fit_transform(X) + + assert_array_equal(X_trans, X_true) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +@pytest.mark.parametrize("dtype", [object, "category"]) +def test_imputation_constant_pandas(dtype): + # Test imputation using the constant strategy on pandas df + pd = pytest.importorskip("pandas") + + f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n,i,x,\na,,y,\na,j,,\nb,j,x,") + + df = pd.read_csv(f, dtype=dtype) + + X_true = np.array( + [ + ["missing_value", "i", "x", "missing_value"], + ["a", "missing_value", "y", "missing_value"], + ["a", "j", "missing_value", "missing_value"], + ["b", "j", "x", "missing_value"], + ], + dtype=object, + ) + + imputer = SimpleImputer(strategy="constant", keep_empty_features=True) + X_trans = imputer.fit_transform(df) + + assert_array_equal(X_trans, X_true) + + +@pytest.mark.parametrize("X", [[[1], [2]], [[1], [np.nan]]]) +def test_iterative_imputer_one_feature(X): + # check we exit early when there is a single feature + imputer = IterativeImputer().fit(X) + assert imputer.n_iter_ == 0 + imputer = IterativeImputer() + imputer.fit([[1], [2]]) + assert imputer.n_iter_ == 0 + imputer.fit([[1], [np.nan]]) + assert imputer.n_iter_ == 0 + + +def test_imputation_pipeline_grid_search(): + # Test imputation within a pipeline + gridsearch. + X = _sparse_random_matrix(100, 100, density=0.10) + missing_values = X.data[0] + + pipeline = Pipeline( + [ + ("imputer", SimpleImputer(missing_values=missing_values)), + ("tree", tree.DecisionTreeRegressor(random_state=0)), + ] + ) + + parameters = {"imputer__strategy": ["mean", "median", "most_frequent"]} + + Y = _sparse_random_matrix(100, 1, density=0.10).toarray() + gs = GridSearchCV(pipeline, parameters) + gs.fit(X, Y) + + +def test_imputation_copy(): + # Test imputation with copy + X_orig = _sparse_random_matrix(5, 5, density=0.75, random_state=0) + + # copy=True, dense => copy + X = X_orig.copy().toarray() + imputer = SimpleImputer(missing_values=0, strategy="mean", copy=True) + Xt = imputer.fit(X).transform(X) + Xt[0, 0] = -1 + assert not np.all(X == Xt) + + # copy=True, sparse csr => copy + X = X_orig.copy() + imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=True) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert not np.all(X.data == Xt.data) + + # copy=False, dense => no copy + X = X_orig.copy().toarray() + imputer = SimpleImputer(missing_values=0, strategy="mean", copy=False) + Xt = imputer.fit(X).transform(X) + Xt[0, 0] = -1 + assert_array_almost_equal(X, Xt) + + # copy=False, sparse csc => no copy + X = X_orig.copy().tocsc() + imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert_array_almost_equal(X.data, Xt.data) + + # copy=False, sparse csr => copy + X = X_orig.copy() + imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert not np.all(X.data == Xt.data) + + # Note: If X is sparse and if missing_values=0, then a (dense) copy of X is + # made, even if copy=False. + + +def test_iterative_imputer_zero_iters(): + rng = np.random.RandomState(0) + + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + missing_flag = X == 0 + X[missing_flag] = np.nan + + imputer = IterativeImputer(max_iter=0) + X_imputed = imputer.fit_transform(X) + # with max_iter=0, only initial imputation is performed + assert_allclose(X_imputed, imputer.initial_imputer_.transform(X)) + + # repeat but force n_iter_ to 0 + imputer = IterativeImputer(max_iter=5).fit(X) + # transformed should not be equal to initial imputation + assert not np.all(imputer.transform(X) == imputer.initial_imputer_.transform(X)) + + imputer.n_iter_ = 0 + # now they should be equal as only initial imputation is done + assert_allclose(imputer.transform(X), imputer.initial_imputer_.transform(X)) + + +def test_iterative_imputer_verbose(): + rng = np.random.RandomState(0) + + n = 100 + d = 3 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=1) + imputer.fit(X) + imputer.transform(X) + imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=2) + imputer.fit(X) + imputer.transform(X) + + +def test_iterative_imputer_all_missing(): + n = 100 + d = 3 + X = np.zeros((n, d)) + imputer = IterativeImputer(missing_values=0, max_iter=1) + X_imputed = imputer.fit_transform(X) + assert_allclose(X_imputed, imputer.initial_imputer_.transform(X)) + + +@pytest.mark.parametrize( + "imputation_order", ["random", "roman", "ascending", "descending", "arabic"] +) +def test_iterative_imputer_imputation_order(imputation_order): + rng = np.random.RandomState(0) + n = 100 + d = 10 + max_iter = 2 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + X[:, 0] = 1 # this column should not be discarded by IterativeImputer + + imputer = IterativeImputer( + missing_values=0, + max_iter=max_iter, + n_nearest_features=5, + sample_posterior=False, + skip_complete=True, + min_value=0, + max_value=1, + verbose=1, + imputation_order=imputation_order, + random_state=rng, + ) + imputer.fit_transform(X) + ordered_idx = [i.feat_idx for i in imputer.imputation_sequence_] + + assert len(ordered_idx) // imputer.n_iter_ == imputer.n_features_with_missing_ + + if imputation_order == "roman": + assert np.all(ordered_idx[: d - 1] == np.arange(1, d)) + elif imputation_order == "arabic": + assert np.all(ordered_idx[: d - 1] == np.arange(d - 1, 0, -1)) + elif imputation_order == "random": + ordered_idx_round_1 = ordered_idx[: d - 1] + ordered_idx_round_2 = ordered_idx[d - 1 :] + assert ordered_idx_round_1 != ordered_idx_round_2 + elif "ending" in imputation_order: + assert len(ordered_idx) == max_iter * (d - 1) + + +@pytest.mark.parametrize( + "estimator", [None, DummyRegressor(), BayesianRidge(), ARDRegression(), RidgeCV()] +) +def test_iterative_imputer_estimators(estimator): + rng = np.random.RandomState(0) + + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + + imputer = IterativeImputer( + missing_values=0, max_iter=1, estimator=estimator, random_state=rng + ) + imputer.fit_transform(X) + + # check that types are correct for estimators + hashes = [] + for triplet in imputer.imputation_sequence_: + expected_type = ( + type(estimator) if estimator is not None else type(BayesianRidge()) + ) + assert isinstance(triplet.estimator, expected_type) + hashes.append(id(triplet.estimator)) + + # check that each estimator is unique + assert len(set(hashes)) == len(hashes) + + +def test_iterative_imputer_clip(): + rng = np.random.RandomState(0) + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + + imputer = IterativeImputer( + missing_values=0, max_iter=1, min_value=0.1, max_value=0.2, random_state=rng + ) + + Xt = imputer.fit_transform(X) + assert_allclose(np.min(Xt[X == 0]), 0.1) + assert_allclose(np.max(Xt[X == 0]), 0.2) + assert_allclose(Xt[X != 0], X[X != 0]) + + +def test_iterative_imputer_clip_truncnorm(): + rng = np.random.RandomState(0) + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + X[:, 0] = 1 + + imputer = IterativeImputer( + missing_values=0, + max_iter=2, + n_nearest_features=5, + sample_posterior=True, + min_value=0.1, + max_value=0.2, + verbose=1, + imputation_order="random", + random_state=rng, + ) + Xt = imputer.fit_transform(X) + assert_allclose(np.min(Xt[X == 0]), 0.1) + assert_allclose(np.max(Xt[X == 0]), 0.2) + assert_allclose(Xt[X != 0], X[X != 0]) + + +def test_iterative_imputer_truncated_normal_posterior(): + # test that the values that are imputed using `sample_posterior=True` + # with boundaries (`min_value` and `max_value` are not None) are drawn + # from a distribution that looks gaussian via the Kolmogorov Smirnov test. + # note that starting from the wrong random seed will make this test fail + # because random sampling doesn't occur at all when the imputation + # is outside of the (min_value, max_value) range + rng = np.random.RandomState(42) + + X = rng.normal(size=(5, 5)) + X[0][0] = np.nan + + imputer = IterativeImputer( + min_value=0, max_value=0.5, sample_posterior=True, random_state=rng + ) + + imputer.fit_transform(X) + # generate multiple imputations for the single missing value + imputations = np.array([imputer.transform(X)[0][0] for _ in range(100)]) + + assert all(imputations >= 0) + assert all(imputations <= 0.5) + + mu, sigma = imputations.mean(), imputations.std() + ks_statistic, p_value = kstest((imputations - mu) / sigma, "norm") + if sigma == 0: + sigma += 1e-12 + ks_statistic, p_value = kstest((imputations - mu) / sigma, "norm") + # we want to fail to reject null hypothesis + # null hypothesis: distributions are the same + assert ks_statistic < 0.2 or p_value > 0.1, "The posterior does appear to be normal" + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +def test_iterative_imputer_missing_at_transform(strategy): + rng = np.random.RandomState(0) + n = 100 + d = 10 + X_train = rng.randint(low=0, high=3, size=(n, d)) + X_test = rng.randint(low=0, high=3, size=(n, d)) + + X_train[:, 0] = 1 # definitely no missing values in 0th column + X_test[0, 0] = 0 # definitely missing value in 0th column + + imputer = IterativeImputer( + missing_values=0, max_iter=1, initial_strategy=strategy, random_state=rng + ).fit(X_train) + initial_imputer = SimpleImputer(missing_values=0, strategy=strategy).fit(X_train) + + # if there were no missing values at time of fit, then imputer will + # only use the initial imputer for that feature at transform + assert_allclose( + imputer.transform(X_test)[:, 0], initial_imputer.transform(X_test)[:, 0] + ) + + +def test_iterative_imputer_transform_stochasticity(): + rng1 = np.random.RandomState(0) + rng2 = np.random.RandomState(1) + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng1).toarray() + + # when sample_posterior=True, two transforms shouldn't be equal + imputer = IterativeImputer( + missing_values=0, max_iter=1, sample_posterior=True, random_state=rng1 + ) + imputer.fit(X) + + X_fitted_1 = imputer.transform(X) + X_fitted_2 = imputer.transform(X) + + # sufficient to assert that the means are not the same + assert np.mean(X_fitted_1) != pytest.approx(np.mean(X_fitted_2)) + + # when sample_posterior=False, and n_nearest_features=None + # and imputation_order is not random + # the two transforms should be identical even if rng are different + imputer1 = IterativeImputer( + missing_values=0, + max_iter=1, + sample_posterior=False, + n_nearest_features=None, + imputation_order="ascending", + random_state=rng1, + ) + + imputer2 = IterativeImputer( + missing_values=0, + max_iter=1, + sample_posterior=False, + n_nearest_features=None, + imputation_order="ascending", + random_state=rng2, + ) + imputer1.fit(X) + imputer2.fit(X) + + X_fitted_1a = imputer1.transform(X) + X_fitted_1b = imputer1.transform(X) + X_fitted_2 = imputer2.transform(X) + + assert_allclose(X_fitted_1a, X_fitted_1b) + assert_allclose(X_fitted_1a, X_fitted_2) + + +def test_iterative_imputer_no_missing(): + rng = np.random.RandomState(0) + X = rng.rand(100, 100) + X[:, 0] = np.nan + m1 = IterativeImputer(max_iter=10, random_state=rng) + m2 = IterativeImputer(max_iter=10, random_state=rng) + pred1 = m1.fit(X).transform(X) + pred2 = m2.fit_transform(X) + # should exclude the first column entirely + assert_allclose(X[:, 1:], pred1) + # fit and fit_transform should both be identical + assert_allclose(pred1, pred2) + + +def test_iterative_imputer_rank_one(): + rng = np.random.RandomState(0) + d = 50 + A = rng.rand(d, 1) + B = rng.rand(1, d) + X = np.dot(A, B) + nan_mask = rng.rand(d, d) < 0.5 + X_missing = X.copy() + X_missing[nan_mask] = np.nan + + imputer = IterativeImputer(max_iter=5, verbose=1, random_state=rng) + X_filled = imputer.fit_transform(X_missing) + assert_allclose(X_filled, X, atol=0.02) + + +@pytest.mark.parametrize("rank", [3, 5]) +def test_iterative_imputer_transform_recovery(rank): + rng = np.random.RandomState(0) + n = 70 + d = 70 + A = rng.rand(n, rank) + B = rng.rand(rank, d) + X_filled = np.dot(A, B) + nan_mask = rng.rand(n, d) < 0.5 + X_missing = X_filled.copy() + X_missing[nan_mask] = np.nan + + # split up data in half + n = n // 2 + X_train = X_missing[:n] + X_test_filled = X_filled[n:] + X_test = X_missing[n:] + + imputer = IterativeImputer( + max_iter=5, imputation_order="descending", verbose=1, random_state=rng + ).fit(X_train) + X_test_est = imputer.transform(X_test) + assert_allclose(X_test_filled, X_test_est, atol=0.1) + + +def test_iterative_imputer_additive_matrix(): + rng = np.random.RandomState(0) + n = 100 + d = 10 + A = rng.randn(n, d) + B = rng.randn(n, d) + X_filled = np.zeros(A.shape) + for i in range(d): + for j in range(d): + X_filled[:, (i + j) % d] += (A[:, i] + B[:, j]) / 2 + # a quarter is randomly missing + nan_mask = rng.rand(n, d) < 0.25 + X_missing = X_filled.copy() + X_missing[nan_mask] = np.nan + + # split up data + n = n // 2 + X_train = X_missing[:n] + X_test_filled = X_filled[n:] + X_test = X_missing[n:] + + imputer = IterativeImputer(max_iter=10, verbose=1, random_state=rng).fit(X_train) + X_test_est = imputer.transform(X_test) + assert_allclose(X_test_filled, X_test_est, rtol=1e-3, atol=0.01) + + +def test_iterative_imputer_early_stopping(): + rng = np.random.RandomState(0) + n = 50 + d = 5 + A = rng.rand(n, 1) + B = rng.rand(1, d) + X = np.dot(A, B) + nan_mask = rng.rand(n, d) < 0.5 + X_missing = X.copy() + X_missing[nan_mask] = np.nan + + imputer = IterativeImputer( + max_iter=100, tol=1e-2, sample_posterior=False, verbose=1, random_state=rng + ) + X_filled_100 = imputer.fit_transform(X_missing) + assert len(imputer.imputation_sequence_) == d * imputer.n_iter_ + + imputer = IterativeImputer( + max_iter=imputer.n_iter_, sample_posterior=False, verbose=1, random_state=rng + ) + X_filled_early = imputer.fit_transform(X_missing) + assert_allclose(X_filled_100, X_filled_early, atol=1e-7) + + imputer = IterativeImputer( + max_iter=100, tol=0, sample_posterior=False, verbose=1, random_state=rng + ) + imputer.fit(X_missing) + assert imputer.n_iter_ == imputer.max_iter + + +def test_iterative_imputer_catch_warning(): + # check that we catch a RuntimeWarning due to a division by zero when a + # feature is constant in the dataset + X, y = load_diabetes(return_X_y=True) + n_samples, n_features = X.shape + + # simulate that a feature only contain one category during fit + X[:, 3] = 1 + + # add some missing values + rng = np.random.RandomState(0) + missing_rate = 0.15 + for feat in range(n_features): + sample_idx = rng.choice( + np.arange(n_samples), size=int(n_samples * missing_rate), replace=False + ) + X[sample_idx, feat] = np.nan + + imputer = IterativeImputer(n_nearest_features=5, sample_posterior=True) + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + X_fill = imputer.fit_transform(X, y) + assert not np.any(np.isnan(X_fill)) + + +@pytest.mark.parametrize( + "min_value, max_value, correct_output", + [ + (0, 100, np.array([[0] * 3, [100] * 3])), + (None, None, np.array([[-np.inf] * 3, [np.inf] * 3])), + (-np.inf, np.inf, np.array([[-np.inf] * 3, [np.inf] * 3])), + ([-5, 5, 10], [100, 200, 300], np.array([[-5, 5, 10], [100, 200, 300]])), + ( + [-5, -np.inf, 10], + [100, 200, np.inf], + np.array([[-5, -np.inf, 10], [100, 200, np.inf]]), + ), + ], + ids=["scalars", "None-default", "inf", "lists", "lists-with-inf"], +) +def test_iterative_imputer_min_max_array_like(min_value, max_value, correct_output): + # check that passing scalar or array-like + # for min_value and max_value in IterativeImputer works + X = np.random.RandomState(0).randn(10, 3) + imputer = IterativeImputer(min_value=min_value, max_value=max_value) + imputer.fit(X) + + assert isinstance(imputer._min_value, np.ndarray) and isinstance( + imputer._max_value, np.ndarray + ) + assert (imputer._min_value.shape[0] == X.shape[1]) and ( + imputer._max_value.shape[0] == X.shape[1] + ) + + assert_allclose(correct_output[0, :], imputer._min_value) + assert_allclose(correct_output[1, :], imputer._max_value) + + +@pytest.mark.parametrize( + "min_value, max_value, err_msg", + [ + (100, 0, "min_value >= max_value."), + (np.inf, -np.inf, "min_value >= max_value."), + ([-5, 5], [100, 200, 0], "_value' should be of shape"), + ([-5, 5, 5], [100, 200], "_value' should be of shape"), + ], +) +def test_iterative_imputer_catch_min_max_error(min_value, max_value, err_msg): + # check that passing scalar or array-like + # for min_value and max_value in IterativeImputer works + X = np.random.random((10, 3)) + imputer = IterativeImputer(min_value=min_value, max_value=max_value) + with pytest.raises(ValueError, match=err_msg): + imputer.fit(X) + + +@pytest.mark.parametrize( + "min_max_1, min_max_2", + [([None, None], [-np.inf, np.inf]), ([-10, 10], [[-10] * 4, [10] * 4])], + ids=["None-vs-inf", "Scalar-vs-vector"], +) +def test_iterative_imputer_min_max_array_like_imputation(min_max_1, min_max_2): + # Test that None/inf and scalar/vector give the same imputation + X_train = np.array( + [ + [np.nan, 2, 2, 1], + [10, np.nan, np.nan, 7], + [3, 1, np.nan, 1], + [np.nan, 4, 2, np.nan], + ] + ) + X_test = np.array( + [[np.nan, 2, np.nan, 5], [2, 4, np.nan, np.nan], [np.nan, 1, 10, 1]] + ) + imputer1 = IterativeImputer( + min_value=min_max_1[0], max_value=min_max_1[1], random_state=0 + ) + imputer2 = IterativeImputer( + min_value=min_max_2[0], max_value=min_max_2[1], random_state=0 + ) + X_test_imputed1 = imputer1.fit(X_train).transform(X_test) + X_test_imputed2 = imputer2.fit(X_train).transform(X_test) + assert_allclose(X_test_imputed1[:, 0], X_test_imputed2[:, 0]) + + +@pytest.mark.parametrize("skip_complete", [True, False]) +def test_iterative_imputer_skip_non_missing(skip_complete): + # check the imputing strategy when missing data are present in the + # testing set only. + # taken from: https://github.com/scikit-learn/scikit-learn/issues/14383 + rng = np.random.RandomState(0) + X_train = np.array([[5, 2, 2, 1], [10, 1, 2, 7], [3, 1, 1, 1], [8, 4, 2, 2]]) + X_test = np.array([[np.nan, 2, 4, 5], [np.nan, 4, 1, 2], [np.nan, 1, 10, 1]]) + imputer = IterativeImputer( + initial_strategy="mean", skip_complete=skip_complete, random_state=rng + ) + X_test_est = imputer.fit(X_train).transform(X_test) + if skip_complete: + # impute with the initial strategy: 'mean' + assert_allclose(X_test_est[:, 0], np.mean(X_train[:, 0])) + else: + assert_allclose(X_test_est[:, 0], [11, 7, 12], rtol=1e-4) + + +@pytest.mark.parametrize("rs_imputer", [None, 1, np.random.RandomState(seed=1)]) +@pytest.mark.parametrize("rs_estimator", [None, 1, np.random.RandomState(seed=1)]) +def test_iterative_imputer_dont_set_random_state(rs_imputer, rs_estimator): + class ZeroEstimator: + def __init__(self, random_state): + self.random_state = random_state + + def fit(self, *args, **kgards): + return self + + def predict(self, X): + return np.zeros(X.shape[0]) + + estimator = ZeroEstimator(random_state=rs_estimator) + imputer = IterativeImputer(random_state=rs_imputer) + X_train = np.zeros((10, 3)) + imputer.fit(X_train) + assert estimator.random_state == rs_estimator + + +@pytest.mark.parametrize( + "X_fit, X_trans, params, msg_err", + [ + ( + np.array([[-1, 1], [1, 2]]), + np.array([[-1, 1], [1, -1]]), + {"features": "missing-only", "sparse": "auto"}, + "have missing values in transform but have no missing values in fit", + ), + ( + np.array([["a", "b"], ["c", "a"]], dtype=str), + np.array([["a", "b"], ["c", "a"]], dtype=str), + {}, + "MissingIndicator does not support data with dtype", + ), + ], +) +def test_missing_indicator_error(X_fit, X_trans, params, msg_err): + indicator = MissingIndicator(missing_values=-1) + indicator.set_params(**params) + with pytest.raises(ValueError, match=msg_err): + indicator.fit(X_fit).transform(X_trans) + + +def _generate_missing_indicator_cases(): + missing_values_dtypes = [(0, np.int32), (np.nan, np.float64), (-1, np.int32)] + arr_types = ( + [np.array] + + CSC_CONTAINERS + + CSR_CONTAINERS + + COO_CONTAINERS + + LIL_CONTAINERS + + BSR_CONTAINERS + ) + return [ + (arr_type, missing_values, dtype) + for arr_type, (missing_values, dtype) in product( + arr_types, missing_values_dtypes + ) + if not (missing_values == 0 and arr_type is not np.array) + ] + + +@pytest.mark.parametrize( + "arr_type, missing_values, dtype", _generate_missing_indicator_cases() +) +@pytest.mark.parametrize( + "param_features, n_features, features_indices", + [("missing-only", 3, np.array([0, 1, 2])), ("all", 3, np.array([0, 1, 2]))], +) +def test_missing_indicator_new( + missing_values, arr_type, dtype, param_features, n_features, features_indices +): + X_fit = np.array([[missing_values, missing_values, 1], [4, 2, missing_values]]) + X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) + X_fit_expected = np.array([[1, 1, 0], [0, 0, 1]]) + X_trans_expected = np.array([[1, 1, 0], [0, 0, 0]]) + + # convert the input to the right array format and right dtype + X_fit = arr_type(X_fit).astype(dtype) + X_trans = arr_type(X_trans).astype(dtype) + X_fit_expected = X_fit_expected.astype(dtype) + X_trans_expected = X_trans_expected.astype(dtype) + + indicator = MissingIndicator( + missing_values=missing_values, features=param_features, sparse=False + ) + X_fit_mask = indicator.fit_transform(X_fit) + X_trans_mask = indicator.transform(X_trans) + + assert X_fit_mask.shape[1] == n_features + assert X_trans_mask.shape[1] == n_features + + assert_array_equal(indicator.features_, features_indices) + assert_allclose(X_fit_mask, X_fit_expected[:, features_indices]) + assert_allclose(X_trans_mask, X_trans_expected[:, features_indices]) + + assert X_fit_mask.dtype == bool + assert X_trans_mask.dtype == bool + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + + indicator.set_params(sparse=True) + X_fit_mask_sparse = indicator.fit_transform(X_fit) + X_trans_mask_sparse = indicator.transform(X_trans) + + assert X_fit_mask_sparse.dtype == bool + assert X_trans_mask_sparse.dtype == bool + assert X_fit_mask_sparse.format == "csc" + assert X_trans_mask_sparse.format == "csc" + assert_allclose(X_fit_mask_sparse.toarray(), X_fit_mask) + assert_allclose(X_trans_mask_sparse.toarray(), X_trans_mask) + + +@pytest.mark.parametrize( + "arr_type", + CSC_CONTAINERS + CSR_CONTAINERS + COO_CONTAINERS + LIL_CONTAINERS + BSR_CONTAINERS, +) +def test_missing_indicator_raise_on_sparse_with_missing_0(arr_type): + # test for sparse input and missing_value == 0 + + missing_values = 0 + X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]]) + X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) + + # convert the input to the right array format + X_fit_sparse = arr_type(X_fit) + X_trans_sparse = arr_type(X_trans) + + indicator = MissingIndicator(missing_values=missing_values) + + with pytest.raises(ValueError, match="Sparse input with missing_values=0"): + indicator.fit_transform(X_fit_sparse) + + indicator.fit_transform(X_fit) + with pytest.raises(ValueError, match="Sparse input with missing_values=0"): + indicator.transform(X_trans_sparse) + + +@pytest.mark.parametrize("param_sparse", [True, False, "auto"]) +@pytest.mark.parametrize( + "arr_type, missing_values", + [(np.array, 0)] + + list( + product( + CSC_CONTAINERS + + CSR_CONTAINERS + + COO_CONTAINERS + + LIL_CONTAINERS + + BSR_CONTAINERS, + [np.nan], + ) + ), +) +def test_missing_indicator_sparse_param(arr_type, missing_values, param_sparse): + # check the format of the output with different sparse parameter + X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]]) + X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) + X_fit = arr_type(X_fit).astype(np.float64) + X_trans = arr_type(X_trans).astype(np.float64) + + indicator = MissingIndicator(missing_values=missing_values, sparse=param_sparse) + X_fit_mask = indicator.fit_transform(X_fit) + X_trans_mask = indicator.transform(X_trans) + + if param_sparse is True: + assert X_fit_mask.format == "csc" + assert X_trans_mask.format == "csc" + elif param_sparse == "auto" and missing_values == 0: + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + elif param_sparse is False: + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + else: + if sparse.issparse(X_fit): + assert X_fit_mask.format == "csc" + assert X_trans_mask.format == "csc" + else: + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + + +def test_missing_indicator_string(): + X = np.array([["a", "b", "c"], ["b", "c", "a"]], dtype=object) + indicator = MissingIndicator(missing_values="a", features="all") + X_trans = indicator.fit_transform(X) + assert_array_equal(X_trans, np.array([[True, False, False], [False, False, True]])) + + +@pytest.mark.parametrize( + "X, missing_values, X_trans_exp", + [ + ( + np.array([["a", "b"], ["b", "a"]], dtype=object), + "a", + np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object), + ), + ( + np.array([[np.nan, 1.0], [1.0, np.nan]]), + np.nan, + np.array([[1.0, 1.0, True, False], [1.0, 1.0, False, True]]), + ), + ( + np.array([[np.nan, "b"], ["b", np.nan]], dtype=object), + np.nan, + np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object), + ), + ( + np.array([[None, "b"], ["b", None]], dtype=object), + None, + np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object), + ), + ], +) +def test_missing_indicator_with_imputer(X, missing_values, X_trans_exp): + trans = make_union( + SimpleImputer(missing_values=missing_values, strategy="most_frequent"), + MissingIndicator(missing_values=missing_values), + ) + X_trans = trans.fit_transform(X) + assert_array_equal(X_trans, X_trans_exp) + + +@pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer]) +@pytest.mark.parametrize( + "imputer_missing_values, missing_value, err_msg", + [ + ("NaN", np.nan, "Input X contains NaN"), + ("-1", -1, "types are expected to be both numerical."), + ], +) +def test_inconsistent_dtype_X_missing_values( + imputer_constructor, imputer_missing_values, missing_value, err_msg +): + # regression test for issue #11390. Comparison between incoherent dtype + # for X and missing_values was not raising a proper error. + rng = np.random.RandomState(42) + X = rng.randn(10, 10) + X[0, 0] = missing_value + + imputer = imputer_constructor(missing_values=imputer_missing_values) + + with pytest.raises(ValueError, match=err_msg): + imputer.fit_transform(X) + + +def test_missing_indicator_no_missing(): + # check that all features are dropped if there are no missing values when + # features='missing-only' (#13491) + X = np.array([[1, 1], [1, 1]]) + + mi = MissingIndicator(features="missing-only", missing_values=-1) + Xt = mi.fit_transform(X) + + assert Xt.shape[1] == 0 + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_missing_indicator_sparse_no_explicit_zeros(csr_container): + # Check that non missing values don't become explicit zeros in the mask + # generated by missing indicator when X is sparse. (#13491) + X = csr_container([[0, 1, 2], [1, 2, 0], [2, 0, 1]]) + + mi = MissingIndicator(features="all", missing_values=1) + Xt = mi.fit_transform(X) + + assert Xt.nnz == Xt.sum() + + +@pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer]) +def test_imputer_without_indicator(imputer_constructor): + X = np.array([[1, 1], [1, 1]]) + imputer = imputer_constructor() + imputer.fit(X) + + assert imputer.indicator_ is None + + +@pytest.mark.parametrize( + "arr_type", + CSC_CONTAINERS + CSR_CONTAINERS + COO_CONTAINERS + LIL_CONTAINERS + BSR_CONTAINERS, +) +def test_simple_imputation_add_indicator_sparse_matrix(arr_type): + X_sparse = arr_type([[np.nan, 1, 5], [2, np.nan, 1], [6, 3, np.nan], [1, 2, 9]]) + X_true = np.array( + [ + [3.0, 1.0, 5.0, 1.0, 0.0, 0.0], + [2.0, 2.0, 1.0, 0.0, 1.0, 0.0], + [6.0, 3.0, 5.0, 0.0, 0.0, 1.0], + [1.0, 2.0, 9.0, 0.0, 0.0, 0.0], + ] + ) + + imputer = SimpleImputer(missing_values=np.nan, add_indicator=True) + X_trans = imputer.fit_transform(X_sparse) + + assert sparse.issparse(X_trans) + assert X_trans.shape == X_true.shape + assert_allclose(X_trans.toarray(), X_true) + + +@pytest.mark.parametrize( + "strategy, expected", [("most_frequent", "b"), ("constant", "missing_value")] +) +def test_simple_imputation_string_list(strategy, expected): + X = [["a", "b"], ["c", np.nan]] + + X_true = np.array([["a", "b"], ["c", expected]], dtype=object) + + imputer = SimpleImputer(strategy=strategy) + X_trans = imputer.fit_transform(X) + + assert_array_equal(X_trans, X_true) + + +@pytest.mark.parametrize( + "order, idx_order", + [("ascending", [3, 4, 2, 0, 1]), ("descending", [1, 0, 2, 4, 3])], +) +def test_imputation_order(order, idx_order): + # regression test for #15393 + rng = np.random.RandomState(42) + X = rng.rand(100, 5) + X[:50, 1] = np.nan + X[:30, 0] = np.nan + X[:20, 2] = np.nan + X[:10, 4] = np.nan + + with pytest.warns(ConvergenceWarning): + trs = IterativeImputer(max_iter=1, imputation_order=order, random_state=0).fit( + X + ) + idx = [x.feat_idx for x in trs.imputation_sequence_] + assert idx == idx_order + + +@pytest.mark.parametrize("missing_value", [-1, np.nan]) +def test_simple_imputation_inverse_transform(missing_value): + # Test inverse_transform feature for np.nan + X_1 = np.array( + [ + [9, missing_value, 3, -1], + [4, -1, 5, 4], + [6, 7, missing_value, -1], + [8, 9, 0, missing_value], + ] + ) + + X_2 = np.array( + [ + [5, 4, 2, 1], + [2, 1, missing_value, 3], + [9, missing_value, 7, 1], + [6, 4, 2, missing_value], + ] + ) + + X_3 = np.array( + [ + [1, missing_value, 5, 9], + [missing_value, 4, missing_value, missing_value], + [2, missing_value, 7, missing_value], + [missing_value, 3, missing_value, 8], + ] + ) + + X_4 = np.array( + [ + [1, 1, 1, 3], + [missing_value, 2, missing_value, 1], + [2, 3, 3, 4], + [missing_value, 4, missing_value, 2], + ] + ) + + imputer = SimpleImputer( + missing_values=missing_value, strategy="mean", add_indicator=True + ) + + X_1_trans = imputer.fit_transform(X_1) + X_1_inv_trans = imputer.inverse_transform(X_1_trans) + + X_2_trans = imputer.transform(X_2) # test on new data + X_2_inv_trans = imputer.inverse_transform(X_2_trans) + + assert_array_equal(X_1_inv_trans, X_1) + assert_array_equal(X_2_inv_trans, X_2) + + for X in [X_3, X_4]: + X_trans = imputer.fit_transform(X) + X_inv_trans = imputer.inverse_transform(X_trans) + assert_array_equal(X_inv_trans, X) + + +@pytest.mark.parametrize("missing_value", [-1, np.nan]) +def test_simple_imputation_inverse_transform_exceptions(missing_value): + X_1 = np.array( + [ + [9, missing_value, 3, -1], + [4, -1, 5, 4], + [6, 7, missing_value, -1], + [8, 9, 0, missing_value], + ] + ) + + imputer = SimpleImputer(missing_values=missing_value, strategy="mean") + X_1_trans = imputer.fit_transform(X_1) + with pytest.raises( + ValueError, match=f"Got 'add_indicator={imputer.add_indicator}'" + ): + imputer.inverse_transform(X_1_trans) + + +@pytest.mark.parametrize( + "expected,array,dtype,extra_value,n_repeat", + [ + # array of object dtype + ("extra_value", ["a", "b", "c"], object, "extra_value", 2), + ( + "most_frequent_value", + ["most_frequent_value", "most_frequent_value", "value"], + object, + "extra_value", + 1, + ), + ("a", ["min_value", "min_valuevalue"], object, "a", 2), + ("min_value", ["min_value", "min_value", "value"], object, "z", 2), + # array of numeric dtype + (10, [1, 2, 3], int, 10, 2), + (1, [1, 1, 2], int, 10, 1), + (10, [20, 20, 1], int, 10, 2), + (1, [1, 1, 20], int, 10, 2), + ], +) +def test_most_frequent(expected, array, dtype, extra_value, n_repeat): + assert expected == _most_frequent( + np.array(array, dtype=dtype), extra_value, n_repeat + ) + + +@pytest.mark.parametrize( + "expected,array", + [ + ("a", ["a", "b"]), + (1, [1, 2]), + (None, [None, "a"]), + (None, [None, 1]), + (None, [None, "a", 1]), + (1, [1, "1"]), + (1, ["1", 1]), + ], +) +def test_most_frequent_tie_object(expected, array): + """Check the tie breaking behavior of the most frequent strategy. + + Non-regression test for issue #31717. + """ + assert expected == _most_frequent(np.array(array, dtype=object), None, 0) + + +@pytest.mark.parametrize( + "initial_strategy", ["mean", "median", "most_frequent", "constant"] +) +def test_iterative_imputer_keep_empty_features(initial_strategy): + """Check the behaviour of the iterative imputer with different initial strategy + and keeping empty features (i.e. features containing only missing values). + """ + X = np.array([[1, np.nan, 2], [3, np.nan, np.nan]]) + + imputer = IterativeImputer( + initial_strategy=initial_strategy, keep_empty_features=True + ) + X_imputed = imputer.fit_transform(X) + assert_allclose(X_imputed[:, 1], 0) + X_imputed = imputer.transform(X) + assert_allclose(X_imputed[:, 1], 0) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +def test_iterative_imputer_constant_fill_value(): + """Check that we propagate properly the parameter `fill_value`.""" + X = np.array([[-1, 2, 3, -1], [4, -1, 5, -1], [6, 7, -1, -1], [8, 9, 0, -1]]) + + fill_value = 100 + imputer = IterativeImputer( + missing_values=-1, + initial_strategy="constant", + fill_value=fill_value, + max_iter=0, + keep_empty_features=True, + ) + imputer.fit_transform(X) + assert_array_equal(imputer.initial_imputer_.statistics_, fill_value) + + +def test_iterative_imputer_min_max_value_remove_empty(): + """Check that we properly apply the empty feature mask to `min_value` and + `max_value`. + + Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29355 + """ + # Intentionally make column 2 as a missing column, then the bound of the imputed + # value of column 3 should be (4, 5) + X = np.array( + [ + [1, 2, np.nan, np.nan], + [4, 5, np.nan, 6], + [7, 8, np.nan, np.nan], + [10, 11, np.nan, 12], + ] + ) + min_value = [-np.inf, -np.inf, -np.inf, 4] + max_value = [np.inf, np.inf, np.inf, 5] + + X_imputed = IterativeImputer( + min_value=min_value, + max_value=max_value, + keep_empty_features=False, + ).fit_transform(X) + + X_without_missing_column = np.delete(X, 2, axis=1) + assert X_imputed.shape == X_without_missing_column.shape + assert np.min(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(4) + assert np.max(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(5) + + # Intentionally make column 3 as a missing column, then the bound of the imputed + # value of column 2 should be (3.5, 6) + X = np.array( + [ + [1, 2, np.nan, np.nan], + [4, 5, 6, np.nan], + [7, 8, np.nan, np.nan], + [10, 11, 12, np.nan], + ] + ) + min_value = [-np.inf, -np.inf, 3.5, -np.inf] + max_value = [np.inf, np.inf, 6, np.inf] + + X_imputed = IterativeImputer( + min_value=min_value, + max_value=max_value, + keep_empty_features=False, + ).fit_transform(X) + + X_without_missing_column = X[:, :3] + assert X_imputed.shape == X_without_missing_column.shape + assert np.min(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(3.5) + assert np.max(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(6) + + +@pytest.mark.parametrize("keep_empty_features", [True, False]) +def test_knn_imputer_keep_empty_features(keep_empty_features): + """Check the behaviour of `keep_empty_features` for `KNNImputer`.""" + X = np.array([[1, np.nan, 2], [3, np.nan, np.nan]]) + + imputer = KNNImputer(keep_empty_features=keep_empty_features) + + for method in ["fit_transform", "transform"]: + X_imputed = getattr(imputer, method)(X) + if keep_empty_features: + assert X_imputed.shape == X.shape + assert_array_equal(X_imputed[:, 1], 0) + else: + assert X_imputed.shape == (X.shape[0], X.shape[1] - 1) + + +def test_simple_impute_pd_na(): + pd = pytest.importorskip("pandas") + + # Impute pandas array of string types. + df = pd.DataFrame({"feature": pd.Series(["abc", None, "de"], dtype="string")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value="na") + _assert_array_equal_and_same_dtype( + imputer.fit_transform(df), np.array([["abc"], ["na"], ["de"]], dtype=object) + ) + + # Impute pandas array of string types without any missing values. + df = pd.DataFrame({"feature": pd.Series(["abc", "de", "fgh"], dtype="string")}) + imputer = SimpleImputer(fill_value="ok", strategy="constant") + _assert_array_equal_and_same_dtype( + imputer.fit_transform(df), np.array([["abc"], ["de"], ["fgh"]], dtype=object) + ) + + # Impute pandas array of integer types. + df = pd.DataFrame({"feature": pd.Series([1, None, 3], dtype="Int64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value=-1) + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [-1], [3]], dtype="float64") + ) + + # Use `np.nan` also works. + imputer = SimpleImputer(missing_values=np.nan, strategy="constant", fill_value=-1) + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [-1], [3]], dtype="float64") + ) + + # Impute pandas array of integer types with 'median' strategy. + df = pd.DataFrame({"feature": pd.Series([1, None, 2, 3], dtype="Int64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="median") + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [2], [2], [3]], dtype="float64") + ) + + # Impute pandas array of integer types with 'mean' strategy. + df = pd.DataFrame({"feature": pd.Series([1, None, 2], dtype="Int64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="mean") + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [1.5], [2]], dtype="float64") + ) + + # Impute pandas array of float types. + df = pd.DataFrame({"feature": pd.Series([1.0, None, 3.0], dtype="float64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value=-2.0) + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1.0], [-2.0], [3.0]], dtype="float64") + ) + + # Impute pandas array of float types with 'median' strategy. + df = pd.DataFrame({"feature": pd.Series([1.0, None, 2.0, 3.0], dtype="float64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="median") + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), + np.array([[1.0], [2.0], [2.0], [3.0]], dtype="float64"), + ) + + +def test_missing_indicator_feature_names_out(): + """Check that missing indicator return the feature names with a prefix.""" + pd = pytest.importorskip("pandas") + + missing_values = np.nan + X = pd.DataFrame( + [ + [missing_values, missing_values, 1, missing_values], + [4, missing_values, 2, 10], + ], + columns=["a", "b", "c", "d"], + ) + + indicator = MissingIndicator(missing_values=missing_values).fit(X) + feature_names = indicator.get_feature_names_out() + expected_names = ["missingindicator_a", "missingindicator_b", "missingindicator_d"] + assert_array_equal(expected_names, feature_names) + + +def test_imputer_lists_fit_transform(): + """Check transform uses object dtype when fitted on an object dtype. + + Non-regression test for #19572. + """ + + X = [["a", "b"], ["c", "b"], ["a", "a"]] + imp_frequent = SimpleImputer(strategy="most_frequent").fit(X) + X_trans = imp_frequent.transform([[np.nan, np.nan]]) + assert X_trans.dtype == object + assert_array_equal(X_trans, [["a", "b"]]) + + +@pytest.mark.parametrize("dtype_test", [np.float32, np.float64]) +def test_imputer_transform_preserves_numeric_dtype(dtype_test): + """Check transform preserves numeric dtype independent of fit dtype.""" + X = np.asarray( + [[1.2, 3.4, np.nan], [np.nan, 1.2, 1.3], [4.2, 2, 1]], dtype=np.float64 + ) + imp = SimpleImputer().fit(X) + + X_test = np.asarray([[np.nan, np.nan, np.nan]], dtype=dtype_test) + X_trans = imp.transform(X_test) + assert X_trans.dtype == dtype_test + + +@pytest.mark.parametrize("array_type", ["array", "sparse"]) +@pytest.mark.parametrize("keep_empty_features", [True, False]) +def test_simple_imputer_constant_keep_empty_features(array_type, keep_empty_features): + """Check the behaviour of `keep_empty_features` with `strategy='constant'. + For backward compatibility, a column full of missing values will always be + fill and never dropped. + """ + X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]]) + X = _convert_container(X, array_type) + fill_value = 10 + imputer = SimpleImputer( + strategy="constant", + fill_value=fill_value, + keep_empty_features=keep_empty_features, + ) + + for method in ["fit_transform", "transform"]: + # TODO(1.8): Remove the condition and still call getattr(imputer, method)(X) + if method.startswith("fit") and not keep_empty_features: + warn_msg = '`strategy="constant"`, empty features are not dropped. ' + with pytest.warns(FutureWarning, match=warn_msg): + X_imputed = getattr(imputer, method)(X) + else: + X_imputed = getattr(imputer, method)(X) + assert X_imputed.shape == X.shape + constant_feature = ( + X_imputed[:, 0].toarray() if array_type == "sparse" else X_imputed[:, 0] + ) + assert_array_equal(constant_feature, fill_value) + + +@pytest.mark.parametrize("array_type", ["array", "sparse"]) +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +@pytest.mark.parametrize("keep_empty_features", [True, False]) +def test_simple_imputer_keep_empty_features(strategy, array_type, keep_empty_features): + """Check the behaviour of `keep_empty_features` with all strategies but + 'constant'. + """ + X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]]) + X = _convert_container(X, array_type) + imputer = SimpleImputer(strategy=strategy, keep_empty_features=keep_empty_features) + + for method in ["fit_transform", "transform"]: + X_imputed = getattr(imputer, method)(X) + if keep_empty_features: + assert X_imputed.shape == X.shape + constant_feature = ( + X_imputed[:, 0].toarray() if array_type == "sparse" else X_imputed[:, 0] + ) + assert_array_equal(constant_feature, 0) + else: + assert X_imputed.shape == (X.shape[0], X.shape[1] - 1) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_custom(csc_container): + X = np.array( + [ + [1.1, 1.1, 1.1], + [3.9, 1.2, np.nan], + [np.nan, 1.3, np.nan], + [0.1, 1.4, 1.4], + [4.9, 1.5, 1.5], + [np.nan, 1.6, 1.6], + ] + ) + + X_true = np.array( + [ + [1.1, 1.1, 1.1], + [3.9, 1.2, 1.1], + [0.1, 1.3, 1.1], + [0.1, 1.4, 1.4], + [4.9, 1.5, 1.5], + [0.1, 1.6, 1.6], + ] + ) + + imputer = SimpleImputer(missing_values=np.nan, strategy=np.min) + X_trans = imputer.fit_transform(X) + assert_array_equal(X_trans, X_true) + + # Sparse matrix + imputer = SimpleImputer(missing_values=np.nan, strategy=np.min) + X_trans = imputer.fit_transform(csc_container(X)) + assert_array_equal(X_trans.toarray(), X_true) + + +def test_simple_imputer_constant_fill_value_casting(): + """Check that we raise a proper error message when we cannot cast the fill value + to the input data type. Otherwise, check that the casting is done properly. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/28309 + """ + # cannot cast fill_value at fit + fill_value = 1.5 + X_int64 = np.array([[1, 2, 3], [2, 3, 4]], dtype=np.int64) + imputer = SimpleImputer( + strategy="constant", fill_value=fill_value, missing_values=2 + ) + err_msg = f"fill_value={fill_value!r} (of type {type(fill_value)!r}) cannot be cast" + with pytest.raises(ValueError, match=re.escape(err_msg)): + imputer.fit(X_int64) + + # cannot cast fill_value at transform + X_float64 = np.array([[1, 2, 3], [2, 3, 4]], dtype=np.float64) + imputer.fit(X_float64) + err_msg = ( + f"The dtype of the filling value (i.e. {imputer.statistics_.dtype!r}) " + "cannot be cast" + ) + with pytest.raises(ValueError, match=re.escape(err_msg)): + imputer.transform(X_int64) + + # check that no error is raised when having the same kind of dtype + fill_value_list = [np.float64(1.5), 1.5, 1] + X_float32 = X_float64.astype(np.float32) + + for fill_value in fill_value_list: + imputer = SimpleImputer( + strategy="constant", fill_value=fill_value, missing_values=2 + ) + X_trans = imputer.fit_transform(X_float32) + assert X_trans.dtype == X_float32.dtype + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +def test_iterative_imputer_no_empty_features(strategy): + """Check the behaviour of `keep_empty_features` with no empty features. + + With no-empty features, we should get the same imputation whatever the + parameter `keep_empty_features`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/29375 + """ + X = np.array([[np.nan, 0, 1], [2, np.nan, 3], [4, 5, np.nan]]) + + imputer_drop_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=1, keep_empty_features=False + ) + + imputer_keep_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=1, keep_empty_features=True + ) + + assert_allclose( + imputer_drop_empty_features.fit_transform(X), + imputer_keep_empty_features.fit_transform(X), + ) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +@pytest.mark.parametrize( + "X_test", + [ + np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), # without empty feature + np.array([[np.nan, 2, 3, 4], [np.nan, 6, 7, 8]]), # empty feature at column 0 + np.array([[1, 2, 3, np.nan], [5, 6, 7, np.nan]]), # empty feature at column 3 + ], +) +def test_iterative_imputer_with_empty_features(strategy, X_test): + """Check the behaviour of `keep_empty_features` in the presence of empty features. + + With `keep_empty_features=True`, the empty feature will be imputed with the value + defined by the initial imputation. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/29375 + """ + X_train = np.array( + [[np.nan, np.nan, 0, 1], [np.nan, 2, np.nan, 3], [np.nan, 4, 5, np.nan]] + ) + + imputer_drop_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=0, keep_empty_features=False + ) + X_train_drop_empty_features = imputer_drop_empty_features.fit_transform(X_train) + X_test_drop_empty_features = imputer_drop_empty_features.transform(X_test) + + imputer_keep_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=0, keep_empty_features=True + ) + X_train_keep_empty_features = imputer_keep_empty_features.fit_transform(X_train) + X_test_keep_empty_features = imputer_keep_empty_features.transform(X_test) + + assert_allclose(X_train_drop_empty_features, X_train_keep_empty_features[:, 1:]) + assert_allclose(X_train_keep_empty_features[:, 0], 0) + + assert X_train_drop_empty_features.shape[1] == X_test_drop_empty_features.shape[1] + assert X_train_keep_empty_features.shape[1] == X_test_keep_empty_features.shape[1] diff --git a/shared/package-files/02/025ded03bcca34b5f15007866b57b59ddb28690b529bca2e3d84fbff389f7a32/mock.pyi b/shared/package-files/02/025ded03bcca34b5f15007866b57b59ddb28690b529bca2e3d84fbff389f7a32/mock.pyi new file mode 100644 index 0000000000000000000000000000000000000000..013a22a2d570c04261edcea5a1e88026410e1cd3 --- /dev/null +++ b/shared/package-files/02/025ded03bcca34b5f15007866b57b59ddb28690b529bca2e3d84fbff389f7a32/mock.pyi @@ -0,0 +1,441 @@ +import sys +from typing import Any, Callable, Generic, List, Mapping, Optional, Sequence, Text, Tuple, Type, TypeVar, Union, overload + +_F = TypeVar("_F", bound=Callable[..., Any]) +_T = TypeVar("_T") +_TT = TypeVar("_TT", bound=Type[Any]) +_R = TypeVar("_R") + +__all__ = [ + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", +] +__version__: str + +FILTER_DIR: Any + +class _slotted: ... + +class _SentinelObject: + name: Any + def __init__(self, name: Any) -> None: ... + +class _Sentinel: + def __init__(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + +sentinel: Any +DEFAULT: Any + +class _Call(Tuple[Any, ...]): + def __new__( + cls, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ... + ) -> Any: ... + name: Any + parent: Any + from_kall: Any + def __init__( + self, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ... + ) -> None: ... + def __eq__(self, other: Any) -> bool: ... + __ne__: Any + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... + def __getattr__(self, attr: Any) -> Any: ... + def count(self, *args: Any, **kwargs: Any) -> Any: ... + def index(self, *args: Any, **kwargs: Any) -> Any: ... + def call_list(self) -> Any: ... + +call: _Call + +class _CallList(List[_Call]): + def __contains__(self, value: Any) -> bool: ... + +class _MockIter: + obj: Any + def __init__(self, obj: Any) -> None: ... + def __iter__(self) -> Any: ... + def __next__(self) -> Any: ... + +class Base: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +class NonCallableMock(Base, Any): # type: ignore + def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ... + def __init__( + self, + spec: Union[List[str], object, Type[object], None] = ..., + wraps: Optional[Any] = ..., + name: Optional[str] = ..., + spec_set: Union[List[str], object, Type[object], None] = ..., + parent: Optional[NonCallableMock] = ..., + _spec_state: Optional[Any] = ..., + _new_name: str = ..., + _new_parent: Optional[NonCallableMock] = ..., + _spec_as_instance: bool = ..., + _eat_self: Optional[bool] = ..., + unsafe: bool = ..., + **kwargs: Any, + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + if sys.version_info >= (3, 8): + def _calls_repr(self, prefix: str = ...) -> str: ... + def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(self) -> None: ... + def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = ...) -> str: ... + elif sys.version_info >= (3, 5): + def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(_mock_self) -> None: ... + def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any) -> str: ... + if sys.version_info >= (3, 8): + def assert_called(self) -> None: ... + def assert_called_once(self) -> None: ... + elif sys.version_info >= (3, 6): + def assert_called(_mock_self) -> None: ... + def assert_called_once(_mock_self) -> None: ... + if sys.version_info >= (3, 6): + def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... + elif sys.version_info >= (3, 5): + def reset_mock(self, visited: Any = ...) -> None: ... + if sys.version_info >= (3, 7): + def _extract_mock_name(self) -> str: ... + def _get_call_signature_from_name(self, name: str) -> Any: ... + def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = ...) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ... + def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... + def configure_mock(self, **kwargs: Any) -> None: ... + return_value: Any + side_effect: Any + called: bool + call_count: int + call_args: Any + call_args_list: _CallList + mock_calls: _CallList + def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... + def _call_matcher(self, _call: Tuple[_Call, ...]) -> _Call: ... + def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... + +class CallableMixin(Base): + side_effect: Any + def __init__( + self, + spec: Optional[Any] = ..., + side_effect: Optional[Any] = ..., + return_value: Any = ..., + wraps: Optional[Any] = ..., + name: Optional[Any] = ..., + spec_set: Optional[Any] = ..., + parent: Optional[Any] = ..., + _spec_state: Optional[Any] = ..., + _new_name: Any = ..., + _new_parent: Optional[Any] = ..., + **kwargs: Any, + ) -> None: ... + def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + +class Mock(CallableMixin, NonCallableMock): ... + +class _patch(Generic[_T]): + attribute_name: Any + getter: Callable[[], Any] + attribute: str + new: _T + new_callable: Any + spec: Any + create: bool + has_local: Any + spec_set: Any + autospec: Any + kwargs: Mapping[str, Any] + additional_patchers: Any + if sys.version_info >= (3, 8): + @overload + def __init__( + self: _patch[Union[MagicMock, AsyncMock]], + getter: Callable[[], Any], + attribute: str, + *, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + # This overload also covers the case, where new==DEFAULT. In this case, self is _patch[Any]. + # Ideally we'd be able to add an overload for it so that self is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + else: + @overload + def __init__( + self: _patch[MagicMock], + getter: Callable[[], Any], + attribute: str, + *, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + @overload + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + def copy(self) -> _patch[_T]: ... + def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + def decorate_class(self, klass: _TT) -> _TT: ... + def decorate_callable(self, func: _F) -> _F: ... + def get_original(self) -> Tuple[Any, bool]: ... + target: Any + temp_original: Any + is_local: bool + def __enter__(self) -> _T: ... + def __exit__(self, *exc_info: Any) -> None: ... + def start(self) -> _T: ... + def stop(self) -> None: ... + +class _patch_dict: + in_dict: Any + values: Any + clear: Any + def __init__(self, in_dict: Any, values: Any = ..., clear: Any = ..., **kwargs: Any) -> None: ... + def __call__(self, f: Any) -> Any: ... + def decorate_class(self, klass: Any) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, *args: Any) -> Any: ... + start: Any + stop: Any + +class _patcher: + TEST_PREFIX: str + dict: Type[_patch_dict] + if sys.version_info >= (3, 8): + @overload + def __call__( # type: ignore + self, + target: Any, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[Union[MagicMock, AsyncMock]]: ... + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __call__( + self, + target: Any, + new: _T, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + else: + @overload + def __call__( # type: ignore + self, + target: Any, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[MagicMock]: ... + @overload + def __call__( + self, + target: Any, + new: _T, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + if sys.version_info >= (3, 8): + @overload + def object( # type: ignore + self, + target: Any, + attribute: Text, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[Union[MagicMock, AsyncMock]]: ... + @overload + def object( + self, + target: Any, + attribute: Text, + new: _T = ..., + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + else: + @overload + def object( # type: ignore + self, + target: Any, + attribute: Text, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[MagicMock]: ... + @overload + def object( + self, + target: Any, + attribute: Text, + new: _T = ..., + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + def multiple( + self, + target: Any, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: _T, + ) -> _patch[_T]: ... + def stopall(self) -> None: ... + +patch: _patcher + +class MagicMixin: + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class NonCallableMagicMock(MagicMixin, NonCallableMock): + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + +class MagicMock(MagicMixin, Mock): + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + +if sys.version_info >= (3, 8): + class AsyncMockMixin(Base): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... + def assert_awaited(self) -> None: ... + def assert_awaited_once(self) -> None: ... + def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(self, calls: _CallList, any_order: bool = ...) -> None: ... + def assert_not_awaited(self) -> None: ... + def reset_mock(self, *args, **kwargs) -> None: ... + await_count: int + await_args: Optional[_Call] + await_args_list: _CallList + class AsyncMagicMixin(MagicMixin): + def __init__(self, *args: Any, **kw: Any) -> None: ... + class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... + +class MagicProxy: + name: Any + parent: Any + def __init__(self, name: Any, parent: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type: Optional[Any] = ...) -> Any: ... + +class _ANY: + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +ANY: Any + +def create_autospec( + spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Optional[Any] = ..., _name: Optional[Any] = ..., **kwargs: Any +) -> Any: ... + +class _SpecState: + spec: Any + ids: Any + spec_set: Any + parent: Any + instance: Any + name: Any + def __init__( + self, + spec: Any, + spec_set: Any = ..., + parent: Optional[Any] = ..., + name: Optional[Any] = ..., + ids: Optional[Any] = ..., + instance: Any = ..., + ) -> None: ... + +def mock_open(mock: Optional[Any] = ..., read_data: Any = ...) -> Any: ... + +PropertyMock = Any + +if sys.version_info >= (3, 7): + def seal(mock: Any) -> None: ... diff --git a/shared/package-files/02/025ff8ea6f9aed99288b5e08134d130901b618c4f99511b3a362a36dcdc9e24a/RECORD b/shared/package-files/02/025ff8ea6f9aed99288b5e08134d130901b618c4f99511b3a362a36dcdc9e24a/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c4d4a6e56a24f2a7b1414a5a6cc7da22a3b16405 --- /dev/null +++ b/shared/package-files/02/025ff8ea6f9aed99288b5e08134d130901b618c4f99511b3a362a36dcdc9e24a/RECORD @@ -0,0 +1,8 @@ +dataclasses-stubs/METADATA.toml,sha256=JjTFy_QNEkWvIlz9vpt31Xc3KZzezZGnvaZONQr7aCg,41 +dataclasses-stubs/__init__.pyi,sha256=NuLHZD_EMBmcw4fwKbl3Y91kgyCnYYTMNf5Z2ktGcm0,2673 +types_dataclasses-0.6.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +types_dataclasses-0.6.6.dist-info/METADATA,sha256=0N7UcFhQ9fS3oOnLGnNxDlsHjgDm31QwXZjIPDBluwU,1290 +types_dataclasses-0.6.6.dist-info/RECORD,, +types_dataclasses-0.6.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +types_dataclasses-0.6.6.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 +types_dataclasses-0.6.6.dist-info/top_level.txt,sha256=bvzFv5M-GN5qFBod3DjQDX3DvorwTP9CCs6Dq-3j3Vg,18 diff --git a/shared/package-files/02/0260a8adba1cab755fa9526753ac2d5721844a096cd5af9678f3f9065dd58b71/autocomplete.pyi b/shared/package-files/02/0260a8adba1cab755fa9526753ac2d5721844a096cd5af9678f3f9065dd58b71/autocomplete.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e7f2675f33bd32e178cec21981fa267844e7bfc5 --- /dev/null +++ b/shared/package-files/02/0260a8adba1cab755fa9526753ac2d5721844a096cd5af9678f3f9065dd58b71/autocomplete.pyi @@ -0,0 +1,10 @@ +from typing import Any + +from django.contrib.admin.options import ModelAdmin +from django.core.handlers.wsgi import WSGIRequest +from django.views.generic.list import BaseListView + +class AutocompleteJsonView(BaseListView): + model_admin: ModelAdmin = ... + term: Any = ... + def has_perm(self, request: WSGIRequest, obj: None = ...) -> bool: ... diff --git a/shared/package-files/02/026149be336a491d5dedde9fd3d1620efc18c07141ed8ccece4b80ee7d5ba43a/_triton_ops.py b/shared/package-files/02/026149be336a491d5dedde9fd3d1620efc18c07141ed8ccece4b80ee7d5ba43a/_triton_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..0a1b055352e5fbec809da64fa9e7ede76d114c18 --- /dev/null +++ b/shared/package-files/02/026149be336a491d5dedde9fd3d1620efc18c07141ed8ccece4b80ee7d5ba43a/_triton_ops.py @@ -0,0 +1,1928 @@ +import math +import os +import torch +import weakref +from functools import lru_cache +from torch.utils._triton import has_triton +from ._triton_ops_meta import get_meta +from typing import Optional, Tuple + +TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE = int(os.getenv('TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE', 2)) + + +def check(cond, msg): + if not cond: + raise ValueError(msg) + + +def check_bsr_layout(f_name, t): + check( + t.layout == torch.sparse_bsr, + f"{f_name}(): only BSR sparse format is supported for the sparse argument.", + ) + + +def check_device(f_name, t, device): + check( + t.device == device and t.device.type == "cuda", + f"{f_name}(): all inputs are expected to be on the same GPU device.", + ) + + +def check_mm_compatible_shapes(f_name, lhs, rhs): + check( + lhs.dim() >= 2 and rhs.dim() >= 2, + f"{f_name}(): all inputs involved in the matrix product are expected to be at least 2D, " + f"but got lhs.dim() == {lhs.dim()} and rhs.dim() == {rhs.dim()}." + ) + + m, kl = lhs.shape[-2:] + kr, n = rhs.shape[-2:] + + check( + kl == kr, + f"{f_name}(): arguments' sizes involved in the matrix product are not compatible for matrix multiplication, " + f"got lhs.shape[-1] == {kl} which is not equal to rhs.shape[-2] == {kr}.", + ) + + +def check_dtype(f_name, t, dtype, *additional_dtypes): + check( + t.dtype == dtype + and t.dtype in ((torch.half, torch.bfloat16, torch.float) + tuple(*additional_dtypes)), + f"{f_name}(): all inputs are expected to be of the same dtype " + f"and one of (half, bfloat16, float32) or {additional_dtypes}, " + f"but got dtype == {t.dtype}.", + ) + + +def check_blocksize(f_name, blocksize): + assert len(blocksize) == 2 + + def is_power_of_two(v): + return not (v & (v - 1)) + + def is_compatible_blocksize(b): + res = True + for blocksize in b: + # Triton loads only blocks which are at least 16 and powers of 2. + res = (blocksize >= 16 and is_power_of_two(blocksize)) and res + return res + + check( + is_compatible_blocksize(blocksize), + f"{f_name}(): sparse inputs' blocksize ({blocksize[0]}, {blocksize[1]}) " + "should be at least 16 and a power of 2 in each dimension.", + ) + + +def make_triton_contiguous(t): + """Return input as a triton-contiguous tensor. + + A triton-contiguous tensor is defined as a tensor that has strides + with minimal value equal to 1. + + While triton kernels support triton-non-contiguous tensors (all + strides being greater than 1 or having 0 strides) arguments, a + considerable slow-down occurs because tensor data is copied + element-wise rather than chunk-wise. + """ + if min(t.stride()) != 1: + # TODO: investigate if contiguity along other axes than the + # last one can be beneficial for performance + return t.contiguous() + else: + return t + + +def broadcast_batch_dims(f_name, *tensors): + try: + return torch.broadcast_shapes(*(t.shape[:-2] for t in tensors)) + except Exception: + check(False, f"{f_name}(): inputs' batch dimensions are not broadcastable!") + + +def slicer(dim, slice_range, *tensors): + for t in tensors: + slices = [slice(None)] * t.dim() + slices[dim] = slice_range + yield t[slices] + + +def multidim_slicer(dims, slices, *tensors): + for t in tensors: + s = [slice(None)] * t.dim() + for d, d_slice in zip(dims, slices): + if d is not None: + s[d] = d_slice + yield t[s] + + +def ptr_stride_extractor(*tensors): + for t in tensors: + yield t + yield from t.stride() + + +def grid_partitioner(full_grid, grid_blocks, tensor_dims_map): + assert 0 <= len(full_grid) <= 3 + assert 0 <= len(grid_blocks) <= 3 + + import itertools + + def generate_grid_points(): + for fg, mg in zip(full_grid, grid_blocks): + yield range(0, fg, mg) + + def generate_sliced_tensors(slices): + for t, t_dims in tensor_dims_map.items(): + yield next(multidim_slicer(t_dims, slices, t)) + + for grid_point in itertools.product(*generate_grid_points()): + grid = [min(fg - gp, mg) for fg, gp, mg in zip(full_grid, grid_point, grid_blocks)] + slices = [slice(gp, gp + g) for gp, g in zip(grid_point, grid)] + # grid_points are iterated in a "contiguous" order, i.e. + # left dimensions traversed slower than right dimensions. + # This order is reversed for CUDA grids. + yield grid[::-1], *generate_sliced_tensors(slices) + + +def launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks=None): + # cuda_max_grid = (2 ** 31 - 1, 2 ** 16 - 1, 2 ** 16 - 1) + cuda_max_grid = (2147483647, 65535, 65535)[::-1] + if grid_blocks is None: + grid_blocks = cuda_max_grid + else: + + def valid_grid_dim(g, mg): + if g is None: + return mg + else: + # grid must be at least 1 and no greater than mg + return max(1, min(g, mg)) + + grid_blocks = tuple( + valid_grid_dim(g, mg) for g, mg in zip(grid_blocks, cuda_max_grid) + ) # type: ignore[assignment] + + for grid, *sliced_tensors in grid_partitioner(full_grid, grid_blocks, tensor_dims_map): + kernel(grid, *sliced_tensors) + + +def prepare_inputs(bsr, *dense_tensors): + # Introduce fake batch dimension if not present for convenience. + crow_indices = bsr.crow_indices().unsqueeze(0) + col_indices = bsr.col_indices().unsqueeze(0) + values = make_triton_contiguous(bsr.values().unsqueeze(0)) + tensors = [make_triton_contiguous(t.unsqueeze(0)) for t in dense_tensors] + + # Compute broadcasted batch dimension + batch_dims_broadcasted = torch.broadcast_shapes(values.shape[:-3], *(t.shape[:-2] for t in tensors)) + + # Broadcast batch dimensions and squash. + # The result can be either a view or a copy. + def batch_broadcast_and_squash(t, batch_dims, invariant_dims): + return t.broadcast_to(batch_dims + invariant_dims).flatten( + 0, len(batch_dims) - 1 + ) + + crow_indices = batch_broadcast_and_squash( + crow_indices, batch_dims_broadcasted, (-1,) + ) + + col_indices = batch_broadcast_and_squash( + col_indices, batch_dims_broadcasted, (-1,) + ) + values = batch_broadcast_and_squash( + values, batch_dims_broadcasted, values.shape[-3:] + ) + tensors = [ + batch_broadcast_and_squash(t, batch_dims_broadcasted, t.shape[-2:]) for t in tensors + ] + + return crow_indices, col_indices, values, *tensors + + +def broadcast_batch_dims_bsr(f_name, bsr, *tensors): + batch_shape = broadcast_batch_dims(f_name, bsr, *tensors) + + crow_indices = bsr.crow_indices().broadcast_to(batch_shape + (-1,)) + col_indices = bsr.col_indices().broadcast_to(batch_shape + (-1,)) + values = bsr.values().broadcast_to(batch_shape + bsr.values().shape[-3:]) + size = batch_shape + bsr.shape[-2:] + return torch.sparse_compressed_tensor(crow_indices, col_indices, values, size=size, layout=bsr.layout) + + +# NOTE: this function will ALWAYS create a view +def tile_to_blocksize(t, blocksize): + *rest, m, n = t.shape + new_shape = rest + [ + m // blocksize[0], + blocksize[0], + n // blocksize[1], + blocksize[1], + ] + # using .view instead of .reshape to ensure that the result is + # indeed a view: + return t.view(new_shape).transpose(-3, -2) + + +def as1Dbatch(tensor): + """Return tensor as 3D tensor by either prepending new dimensions to + the tensor shape (when ``tensor.ndim < 3``), or by collapsing + starting dimensions into the first dimension (when ``tensor.ndim > + 3``). + """ + while tensor.ndim < 3: + tensor = tensor.unsqueeze(0) + if tensor.ndim > 3: + tensor = tensor.flatten(0, tensor.ndim - 3) + assert tensor.ndim == 3, tensor.shape + return tensor + + +def scatter_mm(blocks, others, indices_data, *, accumulators=None): + """Scattered matrix multiplication of tensors. + + A scattered matrix multiplication is defined as a series of matrix + multiplications applied to input tensors according to the input + and output mappings specified by indices data. + + The following indices data formats are supported for defining a + scattered matrix multiplication operation (:attr:`indices_data[0]` + holds the name of the indices data format as specified below): + + - ``"scatter_mm"`` - matrix multiplications scattered in batches + of tensors. + + If :attr:`blocks` is a :math:`(* \times M \times K) tensor, + :attr:`others` is a :math:`(* \times K \times N)` tensor, + :attr:`accumulators` is a :math:`(* \times M \times N)` tensor, + and :attr:`indices = indices_data['indices']` is a :math:`(* + \times 3)` tensor, then the operation is equivalent to the + following code:: + + c_offsets, pq = indices_data[1:] + for r in range(len(c_offsets) - 1): + for g in range(c_offsets[r], c_offsets[r + 1]): + p, q = pq[g] + accumulators[r] += blocks[p] @ others[q] + + - ``"bsr_strided_mm"`` - matrix multiplications scattered in + batches of tensors and a tensor. + + If :attr:`blocks` is a :math:`(Ms \times Ks) tensor, + :attr:`others` is a :math:`(* \times K \times N)` tensor, + :attr:`accumulators` is a :math:`(* \times M \times N)` tensor, then + the operation is equivalent to the following code:: + + c_indices, r_offsets, p_offsets, q_offsets, meta = indices_data[1:] + for b in range(nbatches): + for i, r in enumerate(r_offsets): + r0, r1 = divmod(r, N) + acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns] + for g in range(c_indices[i], c_indices[i+1]): + p = p_offsets[g] + q0, q1 = divmod(q_offsets[g], N) + acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns] + + where ``Ns = N // meta['SPLIT_N']``, and ``M`` and ``K`` are + integer multiples of ``Ms`` and ``Ks``, respectively. + + - ``"bsr_strided_mm_compressed"`` - matrix multiplications + scattered in batches of tensors and a tensor. A memory and + processor efficient version of ``"bsr_strided_mm"`` format. If + :attr:`blocks` is a :math:`(Ms \times Ks) tensor, :attr:`others` + is a :math:`(* \times K \times N)` tensor, :attr:`accumulators` + is a :math:`(* \times M \times N)` tensor, then the operation is + equivalent to the following code:: + + c_indices, r_offsets, q_offsets, meta = indices_data[1:] + for b in range(nbatches): + for r in r_offsets: + m = (r // N) // Ms + n = (r % N) // Ns + r0, r1 = divmod(r, N) + c0, c1 = c_indices[m], c_indices[m + 1] + acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns] + for i, p in enumerate(range(c0, c1)): + q = q_offsets[n * c1 + (SPLIT_N - n) * c0 + i] + q0, q1 = divmod(q, N) + acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns] + + where ``Ns = N // meta['SPLIT_N']``, and ``M`` and ``K`` are + integer multiples of ``Ms`` and ``Ks``, respectively. + + Notice that the order of ``r_offsets`` items can be arbitrary; + this property enables defining swizzle operators via + rearrangements of ``r_offsets`` items.. + + Auxilary functions are provided for pre-computing + :attr:`indices_data`. For example, + :func:`bsr_scatter_mm_indices_data` is used to define indices data + for matrix multiplication of BSR and strided tensors. + + Parameters + ---------- + blocks (Tensor): a 3-D tensor of first matrices to be multiplied + + others (Tensor): a tensor of second matrices to be multiplied. If + ``indices_data[0]=="scatter_mm"``, the tensor is a 1-D batch + tensor of second input matrices to be multiplied. Otherwise, the + second input matrices are slices of the :attr:`others` tensor. + indices_data (tuple): a format data that defines the inputs and + outputs of scattered matrix multiplications. + + Keyword arguments + ----------------- + + accumulators (Tensor, optional): a tensor of matrix product + accumulators. If ``indices_data[0]=="scatter_mm"``, the tensor + is a 1-D batch tensor of output matrices. Otherwise, output + matrices are slices of the :attr:`accumulators` tensor. + """ + indices_format = indices_data[0] + + assert blocks.ndim == 3 + P, Ms, Ks = blocks.shape + + if indices_format == 'scatter_mm': + c_offsets, pq = indices_data[1:] + + assert others.ndim == 3 + Q, Ks_, Ns = others.shape + assert Ks == Ks_ + + if accumulators is None: + R = c_offsets.shape[0] - 1 + accumulators = torch.zeros((R, Ms, Ns), dtype=blocks.dtype, device=blocks.device) + else: + R, Ms_, Ns_ = accumulators.shape + assert Ms_ == Ms + assert Ns_ == Ns + + if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm2 is None: + for r in range(c_offsets.shape[0] - 1): + g0 = c_offsets[r] + g1 = c_offsets[r + 1] + for g in range(g0, g1): + p, q = pq[g] + accumulators[r] += blocks[p] @ others[q] + else: + _scatter_mm2(blocks, others, c_offsets, pq, accumulators) + return accumulators + + elif indices_format == 'bsr_strided_mm': + others_shape = others.shape + others = as1Dbatch(others) + + B, K, N = others.shape + assert K % Ks == 0 + + c_indices, r_offsets, p_offsets, q_offsets, meta = indices_data[1:] + SPLIT_N = meta['SPLIT_N'] + + if accumulators is None: + M = Ms + (r_offsets.max().item() + 1) // N + accumulators = torch.zeros((*others_shape[:-2], M, N), dtype=blocks.dtype, device=blocks.device) + else: + M, N_ = accumulators.shape[-2:] + assert N_ == N + + accumulators_shape = accumulators.shape + accumulators = as1Dbatch(accumulators) + + Ns = N // SPLIT_N + + if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm6 is None: + accumulators.zero_() + for b in range(B): + for r in range(r_offsets.shape[0]): + r_ = r_offsets[r].item() + g0 = c_indices[r].item() + g1 = c_indices[r + 1].item() + r0, r1 = divmod(r_, N) + acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns] + for g in range(g0, g1): + p, q = p_offsets[g], q_offsets[g] + q0, q1 = divmod(q.item(), N) + acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns] + else: + _scatter_mm6(blocks, others, c_indices, r_offsets, p_offsets, q_offsets, meta, accumulators) + return accumulators.view(accumulators_shape) + + elif indices_format == 'bsr_strided_mm_compressed': + others_shape = others.shape + others = as1Dbatch(others) + + B, K, N = others.shape + assert K % Ks == 0 + + c_indices, r_offsets, q_offsets, meta = indices_data[1:] + SPLIT_N = meta['SPLIT_N'] + + if accumulators is None: + M = Ms + (r_offsets.max().item() + 1) // N + accumulators = torch.zeros((*others_shape[:-2], M, N), dtype=blocks.dtype, device=blocks.device) + else: + M, N_ = accumulators.shape[-2:] + assert N_ == N + + accumulators_shape = accumulators.shape + accumulators = as1Dbatch(accumulators) + + Ns = N // SPLIT_N + + if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm6 is None: + for b in range(B): + for j in range(len(r_offsets)): + r0, r1 = divmod(r_offsets[j].item(), N) + m = r0 // Ms + n = r1 // Ns + c0 = c_indices[m].item() + c1 = c_indices[m + 1].item() + acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns] + for i, p in enumerate(range(c0, c1)): + q = q_offsets[n * c1 + (SPLIT_N - n) * c0 + i].item() + q0, q1 = divmod(q, N) + acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns] + else: + p_offsets = torch.empty((0, ), dtype=q_offsets.dtype, device=q_offsets.device) + _scatter_mm6(blocks, others, c_indices, r_offsets, p_offsets, q_offsets, meta, accumulators) + return accumulators.view(accumulators_shape) + + else: + raise NotImplementedError(indices_format) + + +def scatter_mm_meta(M, K, N, Ms, Ks, + GROUP_SIZE=None, TILE_M=None, TILE_N=None, SPLIT_N=None, num_warps=None, num_stages=None, **extra): + if {TILE_M, TILE_N, SPLIT_N, num_warps, num_stages, GROUP_SIZE} == {None}: + device_name = torch.cuda.get_device_name() + meta = get_meta('scatter_mm', (M, K, N, Ms, Ks), device_name, + version=(0, torch.float16, 0.5)) + if meta is not None: + meta.update(**extra) + return meta + # The following parameters are optimized for the performance + # equilibrium points of bsr-dense and dense-dense matrix + # multiplications when using GPU card NVIDIA GeForce RTX 2060 + # SUPER. For points far from the performance equilibrium + # points as well as for other GPU cards, the optimal + # parameters are likely different from what specified below. + if (M, K, N) == (256,) * 3: + if (Ms, Ks) == (16, 16): + SPLIT_N=1;TILE_M=16;TILE_N=16;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (Ms, Ks) == (32, 32): + SPLIT_N=2;TILE_M=32;TILE_N=16;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (Ms, Ks) == (64, 64): + SPLIT_N=1;TILE_M=32;TILE_N=32;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (Ms, Ks) == (128, 128): + SPLIT_N=1;TILE_M=32;TILE_N=32;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (M, K, N) == (512,) * 3: + if (Ms, Ks) == (16, 16): + SPLIT_N=8;TILE_M=16;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=2 # noqa: E225,E231,E702 + elif (Ms, Ks) == (32, 32): + SPLIT_N=8;TILE_M=32;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=2 # noqa: E225,E231,E702 + elif (Ms, Ks) == (64, 64): + SPLIT_N=4;TILE_M=32;TILE_N=128;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (Ms, Ks) == (128, 128): + SPLIT_N=8;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (M, K, N) == (1024,) * 3: + if (Ms, Ks) == (16, 16): + SPLIT_N=4;TILE_M=16;TILE_N=128;GROUP_SIZE=2;num_stages=1;num_warps=1 # noqa: E225,E231,E702 + elif (Ms, Ks) == (32, 32): + SPLIT_N=8;TILE_M=32;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=1 # noqa: E225,E231,E702 + elif (Ms, Ks) == (64, 64): + SPLIT_N=16;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=2 # noqa: E225,E231,E702 + elif (Ms, Ks) == (128, 128): + SPLIT_N=16;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (Ms, Ks) == (256, 256): + SPLIT_N=16;TILE_M=64;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (M, K, N) == (2048,) * 3: + if (Ms, Ks) == (16, 16): + SPLIT_N=4;TILE_M=16;TILE_N=128;GROUP_SIZE=8;num_stages=1;num_warps=1 # noqa: E225,E231,E702 + elif (Ms, Ks) == (32, 32): + SPLIT_N=4;TILE_M=32;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=1 # noqa: E225,E231,E702 + elif (Ms, Ks) == (64, 64): + SPLIT_N=4;TILE_M=64;TILE_N=128;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (Ms, Ks) == (128, 128): + SPLIT_N=8;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (Ms, Ks) == (256, 256): + SPLIT_N=4;TILE_M=64;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + elif (M, K, N) == (4096,) * 3: + if (Ms, Ks) == (16, 16): + SPLIT_N=2;TILE_M=16;TILE_N=256;GROUP_SIZE=2;num_stages=1;num_warps=2 # noqa: E225,E231,E702 + elif (Ms, Ks) == (32, 32): + SPLIT_N=2;TILE_M=32;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=1 # noqa: E225,E231,E702 + elif (Ms, Ks) == (64, 64): + SPLIT_N=2;TILE_M=64;TILE_N=128;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702 + + if SPLIT_N is None: + # Assume NVIDIA GeForce RTX 2060 SUPER: + # With the probality of 92% (99.9% when N > 512), the + # performance will not be worse more than 2% from the + # performance when using an optimal value. Otherwise, when N + # <= 512, using the following heuristics may give upto 15% + # lower performance. + SPLIT_N = {16: 1, 32: 2, 64: 4, 128: 8, 256: 16, 512: 8, 1024: 16, 4096: 32, 8192: 64}.get(N, 16) + if Ms >= 512 and N >= 2048: + SPLIT_N = 1 + Ns = N // SPLIT_N + if TILE_M is None: + TILE_M = min(64 if Ns < 512 else 32, Ms) + if TILE_N is None: + TILE_N = min(64 if Ns < 512 else 32, Ns) + num_stages = num_stages or 1 + if num_warps is None: + if min(M, N) > 1024: + num_warps = {16: 1, 32: 1, 64: 2}.get(Ms, 4) + elif min(M, N) == 1024: + num_warps = {16: 1, 32: 1, 64: 2}.get(Ms, 4) + elif min(M, N) == 256: + num_warps = {16: 1, 32: 4}.get(Ms, 4) + else: + num_warps = {16: 1, 32: 2}.get(Ms, 4) + GROUP_SIZE = GROUP_SIZE or 4 + + assert TILE_M <= Ms, dict(TILE_M=TILE_M, Ms=Ms) + assert TILE_N <= Ns, dict(TILE_N=TILE_N, Ns=Ns) + assert Ms <= M, dict(M=M, Ms=Ms) + assert Ns <= N, dict(N=N, Ns=Ns) + assert Ks <= K, dict(K=K, Ks=Ks) + + return dict(TILE_M=TILE_M, TILE_N=TILE_N, GROUP_SIZE=GROUP_SIZE, + num_stages=num_stages, num_warps=num_warps, SPLIT_N=SPLIT_N, **extra) + + +def bsr_dense_addmm_meta(M, K, N, Ms, Ks, beta, alpha, + SPLIT_N=None, GROUP_SIZE_ROW=None, num_warps=None, num_stages=None, sparsity=None, dtype=None, **extra): + if dtype is None: + dtype = torch.float16 + if sparsity is None: + sparsity = 0.5 + if {SPLIT_N, num_warps, num_stages, GROUP_SIZE_ROW} == {None}: + device_name = torch.cuda.get_device_name() + key = (M, K, N, Ms, Ks, beta == 0, beta == 1, alpha == 1) + meta = get_meta('bsr_dense_addmm', key, + device_name, version=(0, dtype, sparsity)) + if meta is None and sparsity != 0.5: + meta = get_meta('bsr_dense_addmm', key, + device_name, version=(0, dtype, 0.5)) + if meta is not None: + meta.update(**extra) + return meta + SPLIT_N = SPLIT_N or max(N // Ms, 1) + GROUP_SIZE_ROW = GROUP_SIZE_ROW or 4 + num_stages = num_stages or 1 + num_warps = num_warps or 4 + return dict(SPLIT_N=SPLIT_N, GROUP_SIZE_ROW=GROUP_SIZE_ROW, num_stages=num_stages, num_warps=num_warps, **extra) + + +class TensorAsKey: + """A light-weight wrapper of a tensor that enables storing tensors as + keys with efficient memory reference based comparision as an + approximation to data equality based keys. + + Motivation: the hash value of a torch tensor is tensor instance + based that does not use data equality and makes the usage of + tensors as keys less useful. For instance, the result of + ``len({a.crow_indices(), a.crow_indices()})`` is `2`, although, + the tensor results from `crow_indices` method call are equal, in + fact, these share the same data storage. + On the other hand, for efficient caching of tensors we want to + avoid calling torch.equal that compares tensors item-wise. + + TensorAsKey offers a compromise in that it guarantees key equality + of tensors that references data in the same storage in the same + manner and without accessing underlying data. However, this + approach does not always guarantee correctness. For instance, for + a complex tensor ``x``, we have ``TensorAsKey(x) == + TensorAsKey(x.conj())`` while ``torch.equal(x, x.conj())`` would + return False. + """ + + def __init__(self, obj): + + def get_tensor_key(obj): + # Warning: TensorAsKey does not track negative nor + # conjugate bits of its input object because in the use + # case of wrapping compressed/plain indices of compressed + # sparse tensors (that are always integer tensors with + # non-negative items) these bits are never set. However, + # when extending the use of TensorAsKey to float or + # complex tensors, the values of these bits (see is_neg + # and is_conj methods) must be included in the key as + # well. + assert not (obj.dtype.is_floating_point or obj.dtype.is_complex), obj.dtype + return (obj.data_ptr(), obj.storage_offset(), obj.shape, obj.stride(), obj.dtype) + + self._obj_ref = weakref.ref(obj) + if obj.layout is torch.strided: + self.key = get_tensor_key(obj) + elif obj.layout in {torch.sparse_csr, torch.sparse_bsr}: + self.key = (get_tensor_key(obj.crow_indices()), get_tensor_key(obj.col_indices())) + elif obj.layout in {torch.sparse_csc, torch.sparse_bsc}: + self.key = (get_tensor_key(obj.ccol_indices()), get_tensor_key(obj.row_indices())) + else: + raise NotImplementedError(obj.layout) + self._hash = hash(self.key) + + def __hash__(self): + return self._hash + + def __eq__(self, other): + if not isinstance(other, TensorAsKey): + return False + if self.obj is None or other.obj is None: + # dead objects always compare unequal unless these are + # same objects + return self is other + return self.key == other.key + + @property + def obj(self): + """Return object if alive, otherwise None.""" + return self._obj_ref() + + +@lru_cache(maxsize=TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE) +def _bsr_scatter_mm_indices_data(indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, compressed_sparse_tensor_as_key): + bsr = compressed_sparse_tensor_as_key.obj + assert bsr is not None + crow_indices, col_indices = bsr.crow_indices(), bsr.col_indices() + device = crow_indices.device + indices_dtype = torch.int32 + + if indices_format == 'bsr_strided_mm_compressed': + Ns = N // SPLIT_N + q_offsets_lst = [] + b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns + for m in range(M // Ms): + r0 = crow_indices[m].item() + r1 = crow_indices[m + 1].item() + if r1 == r0: + continue + q_offsets_lst.append((col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0)) + q_offsets = torch.cat(q_offsets_lst) + crow_indices_diff = crow_indices.diff() + non_zero_row_indices = crow_indices_diff.nonzero() + a = non_zero_row_indices * (Ms * N) + r_offsets = (a + b).view(-1) + c_indices = crow_indices + # swizzle operation: mm elements with longer sums are computed first: + nnz_per_row = crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N) + nnz_per_row, indices = nnz_per_row.sort(descending=True, stable=True) + r_offsets = r_offsets[indices] + return (indices_format, c_indices, r_offsets, q_offsets) + + elif indices_format == 'bsr_strided_mm': + Ns = N // SPLIT_N + p_offsets_lst = [] + q_offsets_lst = [] + b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns + for m in range(M // Ms): + r0 = crow_indices[m].item() + r1 = crow_indices[m + 1].item() + if r1 == r0: + continue + p_offsets_lst.append(torch.arange(r0, r1, dtype=indices_dtype, device=device).repeat(SPLIT_N)) + q_offsets_lst.append((col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0)) + q_offsets = torch.cat(q_offsets_lst) + crow_indices_diff = crow_indices.diff() + non_zero_row_indices = crow_indices_diff.nonzero() + a = non_zero_row_indices * (Ms * N) + r_offsets = (a + b).view(-1) + c_indices = torch.cat((crow_indices[:1], + torch.cumsum(crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N), 0))) + p_offsets = torch.cat(p_offsets_lst) + return (indices_format, c_indices, r_offsets, p_offsets, q_offsets) + + elif indices_format == 'scatter_mm': + Ns = Ms + c_indices = [0] + pq_offsets = [] + # todo: eliminate inner for-loops for efficiency + for b in range(nbatches): + for m in range(M // Ms): + r0 = crow_indices[m].item() + r1 = crow_indices[m + 1].item() + for n in range(N // Ns): + c_indices.append(c_indices[-1] + r1 - r0) + for t in range(r1 - r0): + p = r0 + t + q = (col_indices[p].item() + b * (K // Ks)) * (N // Ns) + n + pq_offsets.append([p, q]) + + return (indices_format, + torch.tensor(c_indices, dtype=indices_dtype, device=device), + torch.tensor(pq_offsets, dtype=indices_dtype, device=device)) + + else: + raise ValueError(f'Invalid {indices_format=}. Expected bsr_strided_mm_compressed|bsr_strided_mm|scatter_mm') + + +def bsr_scatter_mm_indices_data(bsr, other, indices_format='bsr_strided_mm_compressed', **meta_input): + """Computes indices data for :func:`scatter_mm` used in BSR and + strided tensor matrix multiplication. + """ + assert bsr.dense_dim() == 0 + assert bsr.ndim == 2 # no batch dims + crow_indices = bsr.crow_indices() + col_indices = bsr.col_indices() + blocksize = bsr.values().shape[-2:] + M, K = bsr.shape + Ms, Ks = blocksize + K_, N = other.shape[-2:] + assert K_ == K + nbatches = other.shape[:-2].numel() + + meta = scatter_mm_meta(M, K, N, Ms, Ks, **meta_input) + if 'allow_tf32' not in meta_input: + meta.update(allow_tf32=bsr.dtype in {torch.float16, torch.bfloat16}) + SPLIT_N = meta['SPLIT_N'] + indices_data = _bsr_scatter_mm_indices_data( + indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, TensorAsKey(bsr)) + + if indices_format == 'bsr_strided_mm_compressed': + meta.update(is_compressed=True) + return indices_data + (meta,) + elif indices_format == 'bsr_strided_mm': + meta.update(is_compressed=False) + return indices_data + (meta,) + else: + return indices_data + + +def bsr_scatter_mm(bsr, other, indices_data=None, out=None): + """BSR @ strided -> strided + """ + + assert bsr.ndim == 2 + assert other.ndim >= 2 + + Ms, Ks, Ns = bsr.shape[-2], bsr.shape[-1], other.shape[-1] + blocksize = bsr.values().shape[-2:] + + if indices_data is None: + indices_data = bsr_scatter_mm_indices_data(bsr, other, indices_format='bsr_strided_mm_compressed') + + indices_format = indices_data[0] + + if out is None: + out = torch.empty((*other.shape[:-2], Ms, Ns), dtype=bsr.dtype, device=bsr.device) + out_shape = out.shape + out = as1Dbatch(out) + + if bsr._nnz() == 0: + out.zero_() + elif indices_format in {'bsr_strided_mm_compressed', 'bsr_strided_mm'}: + out.zero_() + scatter_mm(bsr.values(), other, indices_data, accumulators=out) + elif indices_format == 'scatter_mm': + nbatches = other.shape[:-2].numel() + accumulators = torch.zeros((nbatches * Ms // blocksize[0] * Ns // blocksize[0], blocksize[0], blocksize[0]), + dtype=bsr.dtype, device=bsr.device) + others = (as1Dbatch(other) + .transpose(-2, -1) + .view(nbatches, Ns // blocksize[0], blocksize[0], Ks // blocksize[1], blocksize[1]) + .movedim((3, 1, 4, 2), (1, 2, 3, 4)) # equivalent to .transpose(-3, -2).transpose(-2, -1).transpose(-4, -3) + .flatten(0, 2) + ) + scatter_mm(bsr.values(), others, indices_data, accumulators=accumulators) + out.copy_(accumulators + .unflatten(0, (nbatches, Ms // blocksize[0], Ns // blocksize[0])) + .movedim((1, 2, 3, 4), (3, 1, 4, 2)) # equivalent to .transpose(-4, -3).transpose(-2, -1).transpose(-3, -2) + .reshape(nbatches, Ns, Ms) + .transpose(-2, -1)) + else: + raise NotImplementedError(indices_format) + + return out.view(out_shape) + + +def bsr_dense_addmm( + input: torch.Tensor, + bsr: torch.Tensor, + dense: torch.Tensor, + *, + beta=1, + alpha=1, + out: Optional[torch.Tensor] = None, + skip_checks: bool = False, + max_grid: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None, + meta: Optional[dict] = None): + f_name = 'bsr_dense_addmm' + values = bsr.values() + crow_indices = bsr.crow_indices() + col_indices = bsr.col_indices() + batch_ndim = crow_indices.dim() - 1 + M, K = bsr.shape[batch_ndim:batch_ndim + 2] + blocksize = values.shape[batch_ndim + 1:batch_ndim + 3] + N = dense.shape[-1] + + # todo: implement checks + + if out is None: + original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense) + out = dense.new_empty(original_batch_dims_broadcasted + (M, N)) + + if bsr._nnz() == 0 or alpha == 0 or N == 0 or M == 0 or K == 0: + if beta == 0: + out.zero_() + else: + out.copy_(input) + if beta != 1: + out.mul_(beta) + return out + + if meta is None: + sparsity = round(1 - bsr._nnz() * blocksize[0] * blocksize[1] / (M * K), 2) + meta = bsr_dense_addmm_meta(M, K, N, blocksize[0], blocksize[1], beta, alpha, sparsity=sparsity, dtype=out.dtype) + out_backup = out + + crow_indices, col_indices, values, input, dense, out = prepare_inputs(bsr, input, dense, out) + + BM, BK = blocksize + SPLIT_N = meta.get('SPLIT_N', N // BM) + BN = N // SPLIT_N + + out_untiled = out + out = tile_to_blocksize(out, (BM, BN)) + dense = tile_to_blocksize(dense, (BK, BN)) + input = tile_to_blocksize(input, (BM, BN)) + + dot_out_dtype = {torch.float16: tl.float32, + torch.bfloat16: tl.float32, + torch.float32: tl.float64, + torch.float64: tl.float64}[out.dtype] + + n_batches = dense.size(0) + n_block_rows = crow_indices.size(-1) - 1 + n_block_cols = dense.size(-3) + + full_grid = (n_batches, n_block_cols, n_block_rows) + if max_grid is not None: + grid_blocks = tuple(max_grid[:3][::-1]) + (None,) * (3 - len(max_grid[:3])) + else: + grid_blocks = None + + tensor_dims_map = { + values: (0, None, None), + crow_indices: (0, None, -1), + col_indices: (0, None, None), + input: (0, -3, -4), + dense: (0, -3, None), + out: (0, -3, -4), + } + + assert alpha != 0 + + def kernel(grid, *sliced_tensors): + _bsr_strided_addmm_kernel[grid]( + *ptr_stride_extractor(*sliced_tensors), + beta, alpha, + beta_is_one=beta == 1, + beta_is_nonzero=beta != 0, + alpha_is_one=alpha == 1, + BLOCKSIZE_ROW=BM, + BLOCKSIZE_INNER=BK, + BLOCKSIZE_COL=BN, + allow_tf32=dot_out_dtype == tl.float32, + acc_dtype=dot_out_dtype, + **meta) + + launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks) + + if out.data_ptr() != out_backup.data_ptr(): + # prepare_inputs has made a copy of out, copy its content back + # to out_backup: + out_backup.copy_(out_untiled.view(out_backup.shape)) + + return out_backup + + +if has_triton(): + import triton + import triton.language as tl + + @triton.jit + def _sampled_addmm_kernel( + alpha, + beta, + IS_BETA_ZERO: tl.constexpr, + BLOCKSIZE_ROW: tl.constexpr, + BLOCKSIZE_COL: tl.constexpr, + k, + TILE_K: tl.constexpr, + values_ptr, + values_batch_stride, + values_nnz_stride, + values_row_block_stride, + values_col_block_stride, + crow_indices_ptr, + crow_indices_batch_stride, + crow_indices_stride, + col_indices_ptr, + col_indices_batch_stride, + col_indices_stride, + mat1_ptr, + mat1_batch_stride, + mat1_tiled_row_stride, + mat1_tiled_col_stride, + mat1_row_block_stride, + mat1_col_block_stride, + mat2_ptr, + mat2_batch_stride, + mat2_tiled_row_stride, + mat2_tiled_col_stride, + mat2_row_block_stride, + mat2_col_block_stride, + acc_dtype: tl.constexpr, + allow_tf32: tl.constexpr, + ): + batch_pid = tl.program_id(axis=1) + row_block_pid = tl.program_id(axis=0) + + crow_indices_offset_ptr = ( + crow_indices_ptr + + crow_indices_batch_stride * batch_pid + + crow_indices_stride * row_block_pid + ) + nnz_offset = tl.load(crow_indices_offset_ptr) + nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) + + # Compute nnz for the row with number row_block_pid. + # If it is zero, skip the row. + row_nnz = nnz_offset_next - nnz_offset + if row_nnz == 0: + return + + row_block_arange = tl.arange(0, BLOCKSIZE_ROW) + col_block_arange = tl.arange(0, BLOCKSIZE_COL) + + # Pointers are set to the first block of the current row. + values_block_ptrs = ( + values_ptr + + values_batch_stride * batch_pid + + values_nnz_stride * nnz_offset + + values_row_block_stride * row_block_arange[:, None] + + values_col_block_stride * col_block_arange[None, :] + ) + + col_index_nnz_ptr = ( + col_indices_ptr + + col_indices_batch_stride * batch_pid + + col_indices_stride * nnz_offset + ) + + # Advance mat1 to the current tiled row, ignore columns. + mat1_block_ptrs = ( + mat1_ptr + + mat1_batch_stride * batch_pid + + mat1_tiled_row_stride * row_block_pid + + mat1_row_block_stride * row_block_arange[:, None] + ) + + # Advance mat2 in batch and block col dimension. + mat2_block_ptrs = ( + mat2_ptr + + mat2_batch_stride * batch_pid + + mat2_col_block_stride * col_block_arange[None, :] + ) + + k_tile_arange = tl.arange(0, TILE_K) + for _ in range(row_nnz): + acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype) + + # find column block index + col_block = tl.load(col_index_nnz_ptr) + + for k_tile in range(0, k, TILE_K): + k_offsets = k_tile + k_tile_arange + mask_k = k_offsets < k + + mat1_block = tl.load( + mat1_block_ptrs + + mat1_col_block_stride * k_offsets[None, :], + mask=mask_k[None, :], other=0.0 + ) + + mat2_block = tl.load( + mat2_block_ptrs + + mat2_tiled_col_stride * col_block + + mat2_row_block_stride * k_offsets[:, None], + mask=mask_k[:, None], other=0.0 + ) + + acc_block += tl.dot(mat1_block, mat2_block, allow_tf32=allow_tf32, out_dtype=acc_dtype) + + if IS_BETA_ZERO: + acc_block *= alpha + else: + acc_block = alpha * acc_block + beta * tl.load(values_block_ptrs) + + # write result + tl.store(values_block_ptrs, acc_block.to(values_ptr.dtype.element_ty)) + + # advance val/col_index ptrs to the next block in the row. + values_block_ptrs += values_nnz_stride + col_index_nnz_ptr += col_indices_stride + + @triton.jit + def _bsr_strided_dense_rowspace_kernel( + # values prologue + values_ptr, + values_batch_stride, + values_nnz_stride, + values_row_block_stride, + values_col_block_stride, + # values epilogue + # crow_indices prologue + crow_indices_ptr, + crow_indices_batch_stride, + crow_indices_stride, + # crow_indices epilogue + # col_indices prologue + col_indices_ptr, + col_indices_batch_stride, + col_indices_stride, + # col_indices epilogue + # dense prologue + dense_ptr, + dense_batch_stride, + dense_tiled_row_stride, + dense_tiled_col_stride, + dense_row_block_stride, + dense_col_block_stride, + # dense epilogue + # output prologue + output_ptr, + output_batch_stride, + output_tiled_row_stride, + output_tiled_col_stride, + output_row_block_stride, + output_col_block_stride, + # output epilogue + # + # gh-113754: Always keep all constexpr arguments at the end of + # triton kernel arguments list because with triton 2.1 or + # earlier non-contiguous outputs will corrupt CUDA state due + # to a triton bug (fixed in openai/triton#2262). + BLOCKSIZE_ROW: tl.constexpr, + BLOCKSIZE_COL: tl.constexpr, + acc_dtype: tl.constexpr, + allow_tf32: tl.constexpr, + GROUP_SIZE_ROW: tl.constexpr, + ): + batch_pid = tl.program_id(axis=2) + row_block_pid = tl.program_id(axis=0) + col_block_pid = tl.program_id(axis=1) + n_block_rows = tl.num_programs(axis=0) + n_block_cols = tl.num_programs(axis=1) + + row_block_pid, col_block_pid = tl.swizzle2d( + row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW + ) + + crow_indices_offset_ptr = ( + crow_indices_ptr + + crow_indices_batch_stride * batch_pid + + crow_indices_stride * row_block_pid + ) + nnz_offset = tl.load(crow_indices_offset_ptr) + nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) + + # Compute nnz for the row with number row_block_pid. + # If it is zero, skip the row. + row_nnz = nnz_offset_next - nnz_offset + if row_nnz == 0: + return + + row_block_arange = tl.arange(0, BLOCKSIZE_ROW) + col_block_arange = tl.arange(0, BLOCKSIZE_COL) + + # Pointers are set to the first block of the current row. + values_block_ptrs = ( + values_ptr + + values_batch_stride * batch_pid + + values_nnz_stride * nnz_offset + + values_row_block_stride * row_block_arange[:, None] + + values_col_block_stride * col_block_arange[None, :] + ) + + # NOTE: dense is advanced into all dimensions but the tiled row one. + # That will be advanced in the loop according to values in col_indices. + dense_block_ptrs = ( + dense_ptr + + dense_batch_stride * batch_pid + + dense_tiled_col_stride * col_block_pid + + dense_row_block_stride * col_block_arange[:, None] + + dense_col_block_stride * row_block_arange[None, :] + ) + + # Pointers are set to exact write-to locations + output_ptrs = ( + output_ptr + + output_batch_stride * batch_pid + + output_tiled_row_stride * row_block_pid + + output_tiled_col_stride * col_block_pid + + output_row_block_stride * row_block_arange[:, None] + + output_col_block_stride * row_block_arange[None, :] + ) + + # Set pointer to the first nonzero element in the current row + col_index_nnz_ptr = ( + col_indices_ptr + + col_indices_batch_stride * batch_pid + + col_indices_stride * nnz_offset + ) + + output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype) + for _ in range(row_nnz): + values_block = tl.load(values_block_ptrs) + + # find which row of dense needs to get loaded + # for multiplication with values_block. + dense_row_idx = tl.load(col_index_nnz_ptr) + dense_block = tl.load(dense_block_ptrs + dense_tiled_row_stride * dense_row_idx) + + # do block mm + output_acc_block += tl.dot(values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype) + + # move val/col_index ptrs to the next block in the row + values_block_ptrs += values_nnz_stride + col_index_nnz_ptr += col_indices_stride + + # write back the result + tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty)) + + + def _run_sampled_addmm_kernel( + alpha, beta, is_beta_zero, + blocksize, k, tile_k, + values, crow_indices, col_indices, + mat1, mat2, + max_grid + ): + n_batches = values.size(0) + n_block_rows = crow_indices.size(-1) - 1 + + full_grid = (n_batches, n_block_rows) + if max_grid is not None: + grid_blocks = tuple(max_grid[:2][::-1]) + (None,) * (2 - len(max_grid[:2])) + else: + grid_blocks = None + tensor_dims_map = { + values: (0, None), + crow_indices: (0, -1), + col_indices: (0, None), + mat1: (0, -4), + mat2: (0, None), + } + if values.dtype in (torch.half, torch.bfloat16): + acc_dtype = tl.float32 + allow_tf32 = True + else: + acc_dtype = tl.float64 + allow_tf32 = False + + def kernel(grid, *sliced_tensors): + _sampled_addmm_kernel[grid]( + alpha, beta, is_beta_zero, + *blocksize, k, tile_k, + *ptr_stride_extractor(*sliced_tensors), + acc_dtype=acc_dtype, + allow_tf32=allow_tf32, + num_stages=1, + num_warps=4 + ) + + launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks) + + + def sampled_addmm( + input: torch.Tensor, + mat1: torch.Tensor, + mat2: torch.Tensor, + *, + beta=1.0, + alpha=1.0, + out: Optional[torch.Tensor] = None, + skip_checks: bool = False, + max_grid: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None, + ): + f_name = "sampled_addmm" + + check_bsr_layout(f_name, input) + input_broadcasted = broadcast_batch_dims_bsr(f_name, input, mat1, mat2) + + if not skip_checks: + check_device(f_name, mat1, input.device) + check_device(f_name, mat2, input.device) + if beta != 0.0 and input.dtype is torch.bool: + check( + False, + f"{f_name}(): having beta == {beta} not equal to 0.0 with boolean mask is not allowed." + ) + if input.dtype is not torch.bool: + check_dtype(f_name, mat1, input.dtype) + check_dtype(f_name, mat2, input.dtype) + else: + check_dtype(f_name, mat1, mat2.dtype) + check_mm_compatible_shapes(f_name, mat1, mat2) + if out is not None: + check_bsr_layout(f_name, out) + check_device(f_name, out, mat1.device) + check_dtype(f_name, out, input.dtype) + check( + out.shape == input_broadcasted.shape + and out._nnz() == input._nnz(), + f"{f_name}(): Expects `out` to be of shape {input_broadcasted.shape} " + f"and with nnz equal to {input_broadcasted._nnz()} " + f"but got out.shape = {out.shape} and out.nnz = {out._nnz()}" + ) + + if out is None: + out = input_broadcasted.to(mat1.dtype, copy=True) + else: + out.copy_(input_broadcasted) + + if out.numel() == 0 or out._nnz() == 0: + return out + + blocksize = out.values().shape[-2:] + m = mat1.size(-2) + n = mat2.size(-1) + k = mat1.size(-1) + + # NOTE: (m, 0) @ (0, n) == zeros(m, n) + if alpha == 0.0 or k == 0: + out.values().mul_(beta) + return out + + # prepare inputs by reshaping them to be kernel-compatible + out_backup = out + crow_indices, col_indices, values, mat1, mat2 = prepare_inputs(out, mat1, mat2) + + mat1 = tile_to_blocksize(mat1, (blocksize[0], k)) + mat2 = tile_to_blocksize(mat2, (k, blocksize[1])) + tile_k = max(*blocksize) + + _run_sampled_addmm_kernel( + alpha, beta, beta == 0.0, + blocksize, k, tile_k, + values, crow_indices, col_indices, + mat1, mat2, + max_grid + ) + + # If nnz x block strides are not the same in out_backup.values and values, + # it means that out_backup.values and values are not the views of each other, + # so we have to copy. + if out_backup.values().stride()[-3:] != values.stride()[-3:]: + out_backup.values().copy_(values.reshape(out_backup.values().shape)) + return out_backup + + + def bsr_dense_mm( + bsr: torch.Tensor, + dense: torch.Tensor, + *, + out: Optional[torch.Tensor] = None, + skip_checks: bool = False, + max_grid: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None, + meta: Optional[dict] = None + ): + f_name = "bsr_dense_mm" + m, kl = bsr.shape[-2:] + if not skip_checks: + check_bsr_layout(f_name, bsr) + check_device(f_name, bsr, dense.device) + check_dtype(f_name, bsr, dense.dtype) + check_mm_compatible_shapes(f_name, bsr, dense) + + n = dense.size(-1) + row_block, col_block = bsr.values().shape[-2:] + check_blocksize(f_name, (row_block, col_block)) + check( + not n % 16, + f"{f_name}(): dense.size(-1) == {n} should be divisible by 16" + ) + else: + kr, n = dense.shape[-2:] + + original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense) + + if out is not None and not skip_checks: + expected_out_shape = original_batch_dims_broadcasted + (m, n) + check( + out.shape == expected_out_shape, + "bsr_dense_mm(): `out` argument has wrong shape, " + f"expected {expected_out_shape}, but got {out.shape}.", + ) + check( + out.is_contiguous() or out.transpose(-2, -1).is_contiguous(), + "bsr_dense_mm(): only row-major/col-major `out` arguments are supported, " + "i.e. (out.is_contiguous() or out.transpose(-2, -1).is_contiguous()) " + "should be True.", + ) + + # Allocate out + if out is None: + out = dense.new_empty(original_batch_dims_broadcasted + (m, n)) + + # Short circuit if lhs is zero + if bsr._nnz() == 0: + return out.zero_() + + # with beta==0, addmm ignores input content, so we can use out + # as a placeholder for input because their shapes match: + return bsr_dense_addmm(out, bsr, dense, alpha=1, beta=0, out=out) + + + @triton.jit + def _bsr_softmax_kernel( + crow_indices_ptr, + crow_indices_batch_stride, + crow_indices_stride, + values_ptr, + values_batch_stride, + values_row_block_stride, + values_nnz_col_block_stride, + row_block, col_block, + MAX_ROW_NNZ: tl.constexpr, + TILE: tl.constexpr + ): + batch_pid = tl.program_id(axis=2) + row_block_offset_pid = tl.program_id(axis=1) + row_block_pid = tl.program_id(axis=0) + + crow_indices_offset_ptr = ( + crow_indices_ptr + + crow_indices_batch_stride * batch_pid + + crow_indices_stride * row_block_pid + ) + nnz_offset = tl.load(crow_indices_offset_ptr) + nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) + + # Compute nnz for the row with number row_block_pid. + # If it is zero, skip the row. + row_nnz = nnz_offset_next - nnz_offset + if row_nnz == 0: + return + + row_arange = tl.arange(0, TILE) + mask = row_arange < row_nnz * col_block + + curr_row_values_ptrs = ( + values_ptr + + values_batch_stride * batch_pid + + values_row_block_stride * row_block_offset_pid + + nnz_offset * col_block + ) + + # find max in the row + row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32) + max_row_value = tl.max(row_tile, axis=0) + for _ in range(TILE, MAX_ROW_NNZ, TILE): + row_arange += TILE + mask = row_arange < row_nnz * col_block + row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32) + curr_max_row_value = tl.max(row_tile, axis=0) + max_row_value = tl.where(max_row_value > curr_max_row_value, max_row_value, curr_max_row_value) + + # find denominator for stable softmax + num = tl.exp(row_tile - max_row_value) + denom = tl.sum(num, axis=0) + for _ in range(TILE, MAX_ROW_NNZ, TILE): + row_arange -= TILE + mask = row_arange < row_nnz * col_block + row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32) + num = tl.exp(row_tile - max_row_value) + denom += tl.sum(num, axis=0) + + # populate output + tl.store(curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask) + for _ in range(TILE, MAX_ROW_NNZ, TILE): + row_arange += TILE + mask = row_arange < row_nnz * col_block + row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32) + num = tl.exp(row_tile - max_row_value) + tl.store(curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask) + + + def bsr_softmax(input, max_row_nnz=None): + f_name = "bsr_softmax" + + check_bsr_layout(f_name, input) + check_dtype(f_name, input, input.dtype) + + if input._nnz() == 0 or input.numel() == 0: + return input.clone() + + m, n = input.shape[-2:] + nnz = input._nnz() + row_block, col_block = input.values().shape[-2:] + + if max_row_nnz is None: + max_row_nnz = triton.next_power_of_2(n) + else: + max_row_nnz = triton.next_power_of_2(max_row_nnz) + + crow_indices = input.crow_indices().unsqueeze(0).flatten(0, -2) + # reshape values from + # (b1, ..., bn, nnz, row_block, col_block) to + # (b1 * ... * bn, row_block, nnz * col_block). + # This simplifies batch dim manipulation and unlocks + # the possibility to access all nnzs in any given row. + if input.values().transpose(-3, -2).is_contiguous(): + # Need to clone to avoid `contiguous` returning a view. + values = input.values().clone() + else: + values = input.values() + values = values.transpose(-3, -2).contiguous().unsqueeze(0).flatten(0, -4).reshape(-1, row_block, nnz * col_block) + full_grid = (values.shape[0], row_block, m // row_block) + grid_blocks = None + tensor_dims_map = { + # We span nnz number of blocks, not nnz + 1, + # hence crow_indices[..., :-1] + crow_indices[..., :-1]: (0, None, -1), + values: (0, None, None), + } + + def kernel(grid, *sliced_tensors): + _bsr_softmax_kernel[grid]( + *ptr_stride_extractor(*sliced_tensors), + row_block, col_block, + max_row_nnz, + # Triton's max numel is bounded by 2 ** 17. + min(2 ** 17, max_row_nnz) + ) + + launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks) + + values = values.reshape(-1, row_block, nnz, col_block).transpose(-3, -2).reshape(*input.values().shape) + + return torch.sparse_compressed_tensor( + input.crow_indices().clone(), + input.col_indices().clone(), + values, + size=input.shape, + layout=input.layout + ) + + def _scaled_dot_product_attention( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_mask: Optional[torch.Tensor], + dropout_p: float = 0.0, + is_causal: bool = False, + scale: Optional[float] = None + ): + f_name = "_scaled_dot_product_attention" + check( + not is_causal, + f"{f_name}(): is_causal == True is not supported." + ) + check( + attn_mask is not None, + f"{f_name}(): attn_mask == None is not supported." + ) + assert attn_mask is not None + + check( + attn_mask.layout == torch.sparse_bsr, + f"{f_name}(): " + f"attn_mask.layout must be {torch.sparse_bsr}, but got " + f"attn_mask.layout == {attn_mask.layout}." + ) + + check_device(f_name, key, query.device) + check_device(f_name, value, query.device) + check_device(f_name, attn_mask, query.device) + + check_dtype(f_name, key, query.dtype) + check_dtype(f_name, value, query.dtype) + if attn_mask.dtype is not torch.bool: + check_dtype(f_name, attn_mask, query.dtype) + + sdpa = sampled_addmm(attn_mask, query, key.transpose(-2, -1), beta=0.0, skip_checks=False) + if scale is None and query.size(-1) == 0 or scale == 0.0: + check( + False, + f"{f_name}(): current value of scale == {scale} " + "results in division by zero." + ) + scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale + sdpa.values().mul_(scale_factor) + sdpa = bsr_softmax(sdpa) + torch.nn.functional.dropout(sdpa.values(), p=dropout_p, inplace=True) + sdpa = bsr_dense_mm(sdpa, value) + return sdpa + + @triton.jit + def _scatter_mm2_kernel( + M: tl.constexpr, K: tl.constexpr, N: tl.constexpr, + blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K, + others_ptr, others_stride_Q, others_stride_K, others_stride_N, + accumulators_ptr, accumulators_stride_R, accumulators_stride_M, accumulators_stride_N, + pq_offsets_ptr, pq_offsets_stride, + pq_ptr, pq_stride_T, pq_stride_1, + dot_out_dtype: tl.constexpr, + TILE_M: tl.constexpr, + TILE_N: tl.constexpr, + allow_tf32: tl.constexpr): + + Ms = M // TILE_M + Ns = N // TILE_N + + pid_t = tl.program_id(axis=0) + + pid = tl.program_id(axis=1) + pid_m = pid // Ms + pid_n = pid % Ms + + rm = (pid_m * TILE_M + tl.arange(0, TILE_M)) + rn = (pid_n * TILE_N + tl.arange(0, TILE_N)) + rk = tl.arange(0, K) + + A_ptr = blocks_ptr + (rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K) + B_ptr = others_ptr + (rk[:, None] * others_stride_K + rn[None, :] * others_stride_N) + + g0 = tl.load(pq_offsets_ptr + pid_t * pq_offsets_stride) + g1 = tl.load(pq_offsets_ptr + (pid_t + 1) * pq_offsets_stride) + + if g0 == g1: + return + + acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype) + + for i in range(g0, g1): + p = tl.load(pq_ptr + i * pq_stride_T) + q = tl.load(pq_ptr + i * pq_stride_T + pq_stride_1) + A = tl.load(A_ptr + p * blocks_stride_P) + B = tl.load(B_ptr + q * others_stride_Q) + acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32) + + C_ptr = accumulators_ptr + pid_t * accumulators_stride_R + ( + rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N) + tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty)) + + def _scatter_mm2( + blocks: torch.Tensor, + others: torch.Tensor, + pq_offsets: torch.Tensor, + pq_indices: torch.Tensor, + accumulators: torch.Tensor + ): + P, M, K = blocks.shape + Q, _, N = others.shape + R, _, _ = accumulators.shape + + meta = dict(TILE_M=max(16, M // 4), TILE_N=max(16, N // 4), num_stages=1, num_warps=2) + + def grid(META): + return (pq_offsets.shape[0] - 1, triton.cdiv(M, META['TILE_M']) * triton.cdiv(N, META['TILE_N']), 1) + + dot_out_dtype = {torch.float16: tl.float32, + torch.bfloat16: tl.float32, + torch.float32: tl.float64, + torch.float64: tl.float64}[accumulators.dtype] + if 'allow_tf32' not in meta: + meta.update(allow_tf32=dot_out_dtype == tl.float32) + _scatter_mm2_kernel[grid]( + M, K, N, + blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2), + others, others.stride(0), others.stride(1), others.stride(2), + accumulators, accumulators.stride(0), accumulators.stride(1), accumulators.stride(2), + pq_offsets, pq_offsets.stride(0), + pq_indices, pq_indices.stride(0), pq_indices.stride(1), + dot_out_dtype=dot_out_dtype, + **meta + ) + + @triton.jit + def _scatter_mm6_kernel( + nbatches, Ms, Ks: tl.constexpr, N, + blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K, + others_ptr, others_stride_B, others_stride_K, others_stride_N, + accumulators_ptr, accumulators_stride_B, accumulators_stride_M, accumulators_stride_N, + c_indices_ptr, r_offsets_ptr, + p_offsets_ptr, q_offsets_ptr, + is_compressed: tl.constexpr, + dot_out_dtype: tl.constexpr, + SPLIT_N: tl.constexpr, + TILE_M: tl.constexpr, + TILE_N: tl.constexpr, + GROUP_SIZE: tl.constexpr, + allow_tf32: tl.constexpr): + Ns = N // SPLIT_N + BLOCKS_M = Ms // TILE_M + BLOCKS_N = Ns // TILE_N + + pid_t_ = tl.program_id(axis=0) + pid = tl.program_id(axis=1) + pid_b = pid_t_ % nbatches + pid_t = pid_t_ // nbatches + + num_pid_in_group = GROUP_SIZE * BLOCKS_N + group_id = pid // num_pid_in_group + first_pid_m = group_id * GROUP_SIZE + group_size_m = min(BLOCKS_M - first_pid_m, GROUP_SIZE) + pid_m = first_pid_m + (pid % group_size_m) + pid_n = (pid % num_pid_in_group) // group_size_m + + rm = (pid_m * TILE_M + tl.arange(0, TILE_M)) + rn = (pid_n * TILE_N + tl.arange(0, TILE_N)) + rk = tl.arange(0, Ks) + A_ptr = blocks_ptr + (rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K) + B_ptr = others_ptr + pid_b * others_stride_B + (rk[:, None] * others_stride_K + rn[None, :] * others_stride_N) + + # When is_compressed is True, r is the only variable that + # depends on pid_t. This property allows sorting r values + # before calling the kernel. The sorting of r is equivalent to + # defining swizzle operator outside of the kernel. + r = tl.load(r_offsets_ptr + pid_t) + + if is_compressed: + m = (r // N) // Ms + n = (r % N) // Ns + r0 = tl.load(c_indices_ptr + m) + r1 = tl.load(c_indices_ptr + m + 1) + g0 = n * r1 + (SPLIT_N - n) * r0 + nnz = r1 - r0 + else: + g0 = tl.load(c_indices_ptr + pid_t) + g1 = tl.load(c_indices_ptr + pid_t + 1) + nnz = g1 - g0 + + q_ptr = q_offsets_ptr + g0 + acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype) + + if is_compressed: + A_ptr += r0 * blocks_stride_P # type: ignore[possibly-undefined] + for _ in range(nnz): + q = tl.load(q_ptr) + B = tl.load(B_ptr + q) + A = tl.load(A_ptr) + acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32) + A_ptr += blocks_stride_P + q_ptr += 1 + else: + p_ptr = p_offsets_ptr + g0 + for _ in range(nnz): + q = tl.load(q_ptr) + B = tl.load(B_ptr + q) + p = tl.load(p_ptr) + A = tl.load(A_ptr + p * blocks_stride_P) + p_ptr += 1 + q_ptr += 1 + acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32) + + C_ptr = accumulators_ptr + r + pid_b * accumulators_stride_B + ( + rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N) + tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty)) + + def _scatter_mm6( + blocks: torch.Tensor, + others: torch.Tensor, + c_indices: torch.Tensor, + r_offsets: torch.Tensor, + p_offsets: torch.Tensor, + q_offsets: torch.Tensor, + meta: dict, + accumulators: torch.Tensor, + force_contiguous: bool = True, + ): + SPLIT_N = meta['SPLIT_N'] + P, Ms, Ks = blocks.shape + B, K_, N = others.shape + B_, M, N_ = accumulators.shape + assert N_ == N + Ns = N // SPLIT_N + assert B_ == B + + def grid(META): + return (r_offsets.shape[0] * B, triton.cdiv(Ms, META['TILE_M']) * triton.cdiv(Ns, META['TILE_N'])) + + dot_out_dtype = {torch.float16: tl.float32, + torch.bfloat16: tl.float32, + torch.float32: tl.float64, + torch.float64: tl.float64}[accumulators.dtype] + if 'allow_tf32' not in meta: + meta.update(allow_tf32=dot_out_dtype == tl.float32) + + assert c_indices.stride(0) == 1 + assert r_offsets.stride(0) == 1 + assert p_offsets.stride(0) == 1 + assert q_offsets.stride(0) == 1 + + # Re non-contiguous tensor arguments. Sometimes triton kernel + # launches may fail with + # + # RuntimeError: Triton Error [CUDA]: an illegal memory access was encountered + # + # that appears to be case when the size of a non-contiguous + # tensor argument is larger than a certain threshold. Could + # this be related to shared memory or L1 cache size of a GPU + # card? In anycase, ensuring that tensor arguments are + # contiguous seems to avoid the above exception. So, in the + # following we'll always convert tensor arguments to + # C-contiguous tensors. + + if force_contiguous: + blocks = blocks.contiguous() + others = others.contiguous() + if not accumulators.is_contiguous(): + accumulators_ = accumulators.contiguous() + else: + accumulators_ = accumulators + else: + accumulators_ = accumulators + + _scatter_mm6_kernel[grid]( + B, Ms, Ks, N, + blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2), + others, others.stride(0), others.stride(1), others.stride(2), + accumulators_, accumulators_.stride(0), accumulators_.stride(1), accumulators_.stride(2), + c_indices, + r_offsets, + p_offsets, + q_offsets, + dot_out_dtype=dot_out_dtype, + **meta + ) + + if force_contiguous and not accumulators.is_contiguous(): + accumulators.copy_(accumulators_) + + @triton.jit + def _bsr_strided_addmm_kernel( + # values prologue + values_ptr, + values_batch_stride, + values_nnz_stride, + values_row_block_stride, + values_col_block_stride, + # values epilogue + # crow_indices prologue + crow_indices_ptr, + crow_indices_batch_stride, + crow_indices_stride, + # crow_indices epilogue + # col_indices prologue + col_indices_ptr, + col_indices_batch_stride, + col_indices_stride, + # col_indices epilogue + # input prologue + input_ptr, + input_batch_stride, + input_tiled_row_stride, + input_tiled_col_stride, + input_row_block_stride, + input_col_block_stride, + # input epilogue + # dense prologue + dense_ptr, + dense_batch_stride, + dense_tiled_row_stride, + dense_tiled_col_stride, + dense_row_block_stride, + dense_col_block_stride, + # dense epilogue + # output prologue + output_ptr, + output_batch_stride, + output_tiled_row_stride, + output_tiled_col_stride, + output_row_block_stride, + output_col_block_stride, + # output epilogue + beta, + alpha, + beta_is_one: tl.constexpr, + beta_is_nonzero: tl.constexpr, + alpha_is_one: tl.constexpr, + BLOCKSIZE_ROW: tl.constexpr, + BLOCKSIZE_COL: tl.constexpr, + BLOCKSIZE_INNER: tl.constexpr, + acc_dtype: tl.constexpr, + allow_tf32: tl.constexpr, + GROUP_SIZE_ROW: tl.constexpr, + SPLIT_N: tl.constexpr + ): + + batch_pid = tl.program_id(axis=2) + row_block_pid = tl.program_id(axis=0) + col_block_pid = tl.program_id(axis=1) + n_block_rows = tl.num_programs(axis=0) + n_block_cols = tl.num_programs(axis=1) + + row_block_pid, col_block_pid = tl.swizzle2d( + row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW + ) + + crow_indices_offset_ptr = ( + crow_indices_ptr + + crow_indices_batch_stride * batch_pid + + crow_indices_stride * row_block_pid + ) + nnz_offset = tl.load(crow_indices_offset_ptr) + nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) + + # Compute nnz for the row with number row_block_pid. + row_nnz = nnz_offset_next - nnz_offset + + row_block_arange = tl.arange(0, BLOCKSIZE_ROW) + inner_block_arange = tl.arange(0, BLOCKSIZE_INNER) + col_block_arange = tl.arange(0, BLOCKSIZE_COL) + + if beta_is_nonzero: + # Pointers are set to exact write-to locations + input_ptrs = ( + input_ptr + + input_batch_stride * batch_pid + + input_tiled_row_stride * row_block_pid + + input_tiled_col_stride * col_block_pid + + input_row_block_stride * row_block_arange[:, None] + + input_col_block_stride * col_block_arange[None, :] + ) + + # Pointers are set to the first block of the current row. + values_block_ptrs = ( + values_ptr + + values_batch_stride * batch_pid + + values_nnz_stride * nnz_offset + + values_row_block_stride * row_block_arange[:, None] + + values_col_block_stride * inner_block_arange[None, :] + ) + + # NOTE: dense is advanced into all dimensions but the tiled row one. + # That will be advanced in the loop according to values in col_indices. + dense_block_ptrs = ( + dense_ptr + + dense_batch_stride * batch_pid + + dense_tiled_col_stride * col_block_pid + + dense_row_block_stride * inner_block_arange[:, None] + + dense_col_block_stride * col_block_arange[None, :] + ) + + # Pointers are set to exact write-to locations + output_ptrs = ( + output_ptr + + output_batch_stride * batch_pid + + output_tiled_row_stride * row_block_pid + + output_tiled_col_stride * col_block_pid + + output_row_block_stride * row_block_arange[:, None] + + output_col_block_stride * col_block_arange[None, :] + ) + + # Set pointer to the first nonzero element in the current row + col_index_nnz_ptr = ( + col_indices_ptr + + col_indices_batch_stride * batch_pid + + col_indices_stride * nnz_offset + ) + + # alpha is never 0 + if beta_is_nonzero: + output_acc_block = tl.load(input_ptrs).to(acc_dtype) # type: ignore[possibly-undefined] + if not (beta_is_one and alpha_is_one): + beta_alpha = beta / alpha + output_acc_block *= beta_alpha + else: + output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype) + + for _ in range(row_nnz): + values_block = tl.load(values_block_ptrs) + + # find which row of dense needs to get loaded + # for multiplication with values_block. + dense_row_idx = tl.load(col_index_nnz_ptr) + dense_block = tl.load(dense_block_ptrs + dense_tiled_row_stride * dense_row_idx) + + # do block mm + output_acc_block += tl.dot(values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype) + + # move val/col_index ptrs to the next block in the row + values_block_ptrs += values_nnz_stride + col_index_nnz_ptr += col_indices_stride + + if not alpha_is_one: + output_acc_block *= alpha + + # write back the result + tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty)) + + +else: + bsr_softmax = None # type: ignore[assignment] + bsr_dense_mm = None # type: ignore[assignment] + sampled_addmm = None # type: ignore[assignment] + _scaled_dot_product_attention = None # type: ignore[assignment] + _scatter_mm2 = None # type: ignore[assignment] + _scatter_mm6 = None # type: ignore[assignment] + _bsr_strided_addmm_kernel = None # type: ignore[assignment] diff --git a/shared/package-files/02/02626d8a4274da23b9e9b62ac145513df5b0249a905506b9671d8b94a20d5bc8/logaddexp2_ops.h b/shared/package-files/02/02626d8a4274da23b9e9b62ac145513df5b0249a905506b9671d8b94a20d5bc8/logaddexp2_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..175d42d9973e19b376104b3804796f04468beb27 --- /dev/null +++ b/shared/package-files/02/02626d8a4274da23b9e9b62ac145513df5b0249a905506b9671d8b94a20d5bc8/logaddexp2_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 logaddexp2_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::logaddexp2") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logaddexp2.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 logaddexp2 { + 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::logaddexp2") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logaddexp2(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/02/026283dbf8f6ab28f1aede20d07f13ec60653293e7da495eac2fd13aa3f6e289/exceptions.py b/shared/package-files/02/026283dbf8f6ab28f1aede20d07f13ec60653293e7da495eac2fd13aa3f6e289/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f07e4486577381616e7e2f7f05747ed7374316a1 --- /dev/null +++ b/shared/package-files/02/026283dbf8f6ab28f1aede20d07f13ec60653293e7da495eac2fd13aa3f6e289/exceptions.py @@ -0,0 +1,58 @@ +"""asyncio exceptions.""" + + +__all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError', + 'IncompleteReadError', 'LimitOverrunError', + 'SendfileNotAvailableError') + + +class CancelledError(BaseException): + """The Future or Task was cancelled.""" + + +class TimeoutError(Exception): + """The operation exceeded the given deadline.""" + + +class InvalidStateError(Exception): + """The operation is not allowed in this state.""" + + +class SendfileNotAvailableError(RuntimeError): + """Sendfile syscall is not available. + + Raised if OS does not support sendfile syscall for given socket or + file type. + """ + + +class IncompleteReadError(EOFError): + """ + Incomplete read error. Attributes: + + - partial: read bytes string before the end of stream was reached + - expected: total number of expected bytes (or None if unknown) + """ + def __init__(self, partial, expected): + r_expected = 'undefined' if expected is None else repr(expected) + super().__init__(f'{len(partial)} bytes read on a total of ' + f'{r_expected} expected bytes') + self.partial = partial + self.expected = expected + + def __reduce__(self): + return type(self), (self.partial, self.expected) + + +class LimitOverrunError(Exception): + """Reached the buffer limit while looking for a separator. + + Attributes: + - consumed: total number of to be consumed bytes. + """ + def __init__(self, message, consumed): + super().__init__(message) + self.consumed = consumed + + def __reduce__(self): + return type(self), (self.args[0], self.consumed) diff --git a/shared/package-files/02/0265538f01680aa1f77a46a16c0af7dae9629177abaed07bc9c3480de5f7da55/Types.h b/shared/package-files/02/0265538f01680aa1f77a46a16c0af7dae9629177abaed07bc9c3480de5f7da55/Types.h new file mode 100644 index 0000000000000000000000000000000000000000..01a20cb01dff68de245f3c8b16ca1914beb76a1c --- /dev/null +++ b/shared/package-files/02/0265538f01680aa1f77a46a16c0af7dae9629177abaed07bc9c3480de5f7da55/Types.h @@ -0,0 +1,13 @@ +#ifndef THP_TYPES_INC +#define THP_TYPES_INC + +#include + +#ifndef INT64_MAX +#include +#endif + +template +struct THPTypeInfo {}; + +#endif diff --git a/shared/package-files/02/0266bbdcc7720565d8662c3abd5a4ec4dfe69cd3307122108393eacd63d214b6/test_old_base.py b/shared/package-files/02/0266bbdcc7720565d8662c3abd5a4ec4dfe69cd3307122108393eacd63d214b6/test_old_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae9b4e108448d1140e85da5cb1164152558740ad --- /dev/null +++ b/shared/package-files/02/0266bbdcc7720565d8662c3abd5a4ec4dfe69cd3307122108393eacd63d214b6/test_old_base.py @@ -0,0 +1,1063 @@ +from __future__ import annotations + +from datetime import datetime +import weakref + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp + +from pandas.core.dtypes.common import ( + is_integer_dtype, + is_numeric_dtype, +) +from pandas.core.dtypes.dtypes import CategoricalDtype + +import pandas as pd +from pandas import ( + CategoricalIndex, + DatetimeIndex, + DatetimeTZDtype, + Index, + IntervalIndex, + MultiIndex, + PeriodIndex, + RangeIndex, + Series, + StringDtype, + TimedeltaIndex, + isna, + period_range, +) +import pandas._testing as tm +import pandas.core.algorithms as algos +from pandas.core.arrays import BaseMaskedArray + + +class TestBase: + @pytest.fixture( + params=[ + RangeIndex(start=0, stop=20, step=2), + Index(np.arange(5, dtype=np.float64)), + Index(np.arange(5, dtype=np.float32)), + Index(np.arange(5, dtype=np.uint64)), + Index(range(0, 20, 2), dtype=np.int64), + Index(range(0, 20, 2), dtype=np.int32), + Index(range(0, 20, 2), dtype=np.int16), + Index(range(0, 20, 2), dtype=np.int8), + Index(list("abcde")), + Index([0, "a", 1, "b", 2, "c"]), + period_range("20130101", periods=5, freq="D"), + TimedeltaIndex( + [ + "0 days 01:00:00", + "1 days 01:00:00", + "2 days 01:00:00", + "3 days 01:00:00", + "4 days 01:00:00", + ], + dtype="timedelta64[ns]", + freq="D", + ), + DatetimeIndex( + ["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"], + dtype="datetime64[ns]", + freq="D", + ), + IntervalIndex.from_breaks(range(11), closed="right"), + ] + ) + def simple_index(self, request): + return request.param + + def test_pickle_compat_construction(self, simple_index): + # need an object to create with + if isinstance(simple_index, RangeIndex): + pytest.skip("RangeIndex() is a valid constructor") + msg = "|".join( + [ + r"Index\(\.\.\.\) must be called with a collection of some " + r"kind, None was passed", + r"DatetimeIndex\(\) must be called with a collection of some " + r"kind, None was passed", + r"TimedeltaIndex\(\) must be called with a collection of some " + r"kind, None was passed", + r"__new__\(\) missing 1 required positional argument: 'data'", + r"__new__\(\) takes at least 2 arguments \(1 given\)", + ] + ) + with pytest.raises(TypeError, match=msg): + type(simple_index)() + + def test_shift(self, simple_index): + # GH8083 test the base class for shift + if isinstance(simple_index, (DatetimeIndex, TimedeltaIndex, PeriodIndex)): + pytest.skip("Tested in test_ops/test_arithmetic") + idx = simple_index + msg = ( + f"This method is only implemented for DatetimeIndex, PeriodIndex and " + f"TimedeltaIndex; Got type {type(idx).__name__}" + ) + with pytest.raises(NotImplementedError, match=msg): + idx.shift(1) + with pytest.raises(NotImplementedError, match=msg): + idx.shift(1, 2) + + def test_constructor_name_unhashable(self, simple_index): + # GH#29069 check that name is hashable + # See also same-named test in tests.series.test_constructors + idx = simple_index + with pytest.raises(TypeError, match="Index.name must be a hashable type"): + type(idx)(idx, name=[]) + + def test_create_index_existing_name(self, simple_index): + # GH11193, when an existing index is passed, and a new name is not + # specified, the new index should inherit the previous object name + expected = simple_index.copy() + if not isinstance(expected, MultiIndex): + expected.name = "foo" + result = Index(expected) + tm.assert_index_equal(result, expected) + + result = Index(expected, name="bar") + expected.name = "bar" + tm.assert_index_equal(result, expected) + else: + expected.names = ["foo", "bar"] + result = Index(expected) + tm.assert_index_equal( + result, + Index( + Index( + [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ], + dtype="object", + ), + names=["foo", "bar"], + ), + ) + + result = Index(expected, names=["A", "B"]) + tm.assert_index_equal( + result, + Index( + Index( + [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ], + dtype="object", + ), + names=["A", "B"], + ), + ) + + def test_numeric_compat(self, simple_index): + idx = simple_index + # Check that this doesn't cover MultiIndex case, if/when it does, + # we can remove multi.test_compat.test_numeric_compat + assert not isinstance(idx, MultiIndex) + if type(idx) is Index: + pytest.skip("Not applicable for Index") + if is_numeric_dtype(simple_index.dtype) or isinstance( + simple_index, TimedeltaIndex + ): + pytest.skip("Tested elsewhere.") + + typ = type(idx._data).__name__ + cls = type(idx).__name__ + lmsg = "|".join( + [ + rf"unsupported operand type\(s\) for \*: '{typ}' and 'int'", + "cannot perform (__mul__|__truediv__|__floordiv__) with " + f"this index type: ({cls}|{typ})", + ] + ) + with pytest.raises(TypeError, match=lmsg): + idx * 1 + rmsg = "|".join( + [ + rf"unsupported operand type\(s\) for \*: 'int' and '{typ}'", + "cannot perform (__rmul__|__rtruediv__|__rfloordiv__) with " + f"this index type: ({cls}|{typ})", + ] + ) + with pytest.raises(TypeError, match=rmsg): + 1 * idx + + div_err = lmsg.replace("*", "/") + with pytest.raises(TypeError, match=div_err): + idx / 1 + div_err = rmsg.replace("*", "/") + with pytest.raises(TypeError, match=div_err): + 1 / idx + + floordiv_err = lmsg.replace("*", "//") + with pytest.raises(TypeError, match=floordiv_err): + idx // 1 + floordiv_err = rmsg.replace("*", "//") + with pytest.raises(TypeError, match=floordiv_err): + 1 // idx + + def test_logical_compat(self, simple_index): + if simple_index.dtype in (object, "string"): + pytest.skip("Tested elsewhere.") + idx = simple_index + if idx.dtype.kind in "iufcbm": + assert idx.all() == idx._values.all() + assert idx.all() == idx.to_series().all() + assert idx.any() == idx._values.any() + assert idx.any() == idx.to_series().any() + else: + msg = "cannot perform (any|all)" + if isinstance(idx, IntervalIndex): + msg = ( + r"'IntervalArray' with dtype interval\[.*\] does " + "not support reduction '(any|all)'" + ) + with pytest.raises(TypeError, match=msg): + idx.all() + with pytest.raises(TypeError, match=msg): + idx.any() + + def test_repr_roundtrip(self, simple_index): + if isinstance(simple_index, IntervalIndex): + pytest.skip(f"Not a valid repr for {type(simple_index).__name__}") + idx = simple_index + tm.assert_index_equal(eval(repr(idx)), idx) + + def test_repr_max_seq_item_setting(self, simple_index): + # GH10182 + if isinstance(simple_index, IntervalIndex): + pytest.skip(f"Not a valid repr for {type(simple_index).__name__}") + idx = simple_index + idx = idx.repeat(50) + with pd.option_context("display.max_seq_items", None): + repr(idx) + assert "..." not in str(idx) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_ensure_copied_data(self, index): + # Check the "copy" argument of each Index.__new__ is honoured + # GH12309 + init_kwargs = {} + if isinstance(index, PeriodIndex): + # Needs "freq" specification: + init_kwargs["freq"] = index.freq + elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)): + pytest.skip( + "RangeIndex cannot be initialized from data, " + "MultiIndex and CategoricalIndex are tested separately" + ) + elif index.dtype == object and index.inferred_type in ["boolean", "string"]: + init_kwargs["dtype"] = index.dtype + + index_type = type(index) + result = index_type(index.values, copy=True, **init_kwargs) + if isinstance(index.dtype, DatetimeTZDtype): + result = result.tz_localize("UTC").tz_convert(index.tz) + if isinstance(index, (DatetimeIndex, TimedeltaIndex)): + index = index._with_freq(None) + + tm.assert_index_equal(index, result) + + if isinstance(index, PeriodIndex): + # .values an object array of Period, thus copied + depr_msg = "The 'ordinal' keyword in PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = index_type(ordinal=index.asi8, copy=False, **init_kwargs) + tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same") + elif isinstance(index, IntervalIndex): + # checked in test_interval.py + pass + elif type(index) is Index and not isinstance(index.dtype, np.dtype): + result = index_type(index.values, copy=False, **init_kwargs) + tm.assert_index_equal(result, index) + + if isinstance(index._values, BaseMaskedArray): + assert np.shares_memory(index._values._data, result._values._data) + tm.assert_numpy_array_equal( + index._values._data, result._values._data, check_same="same" + ) + assert np.shares_memory(index._values._mask, result._values._mask) + tm.assert_numpy_array_equal( + index._values._mask, result._values._mask, check_same="same" + ) + elif ( + isinstance(index.dtype, StringDtype) and index.dtype.storage == "python" + ): + assert np.shares_memory(index._values._ndarray, result._values._ndarray) + tm.assert_numpy_array_equal( + index._values._ndarray, result._values._ndarray, check_same="same" + ) + elif ( + isinstance(index.dtype, StringDtype) + and index.dtype.storage == "pyarrow" + ): + assert tm.shares_memory(result._values, index._values) + else: + raise NotImplementedError(index.dtype) + else: + result = index_type(index.values, copy=False, **init_kwargs) + tm.assert_numpy_array_equal(index.values, result.values, check_same="same") + + def test_memory_usage(self, index): + index._engine.clear_mapping() + result = index.memory_usage() + if index.empty: + # we report 0 for no-length + assert result == 0 + return + + # non-zero length + index.get_loc(index[0]) + result2 = index.memory_usage() + result3 = index.memory_usage(deep=True) + + # RangeIndex, IntervalIndex + # don't have engines + # Index[EA] has engine but it does not have a Hashtable .mapping + if not isinstance(index, (RangeIndex, IntervalIndex)) and not ( + type(index) is Index and not isinstance(index.dtype, np.dtype) + ): + assert result2 > result + + if index.inferred_type == "object": + assert result3 > result2 + + def test_argsort(self, index): + if isinstance(index, CategoricalIndex): + pytest.skip(f"{type(self).__name__} separately tested") + + result = index.argsort() + expected = np.array(index).argsort() + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + + def test_numpy_argsort(self, index): + result = np.argsort(index) + expected = index.argsort() + tm.assert_numpy_array_equal(result, expected) + + result = np.argsort(index, kind="mergesort") + expected = index.argsort(kind="mergesort") + tm.assert_numpy_array_equal(result, expected) + + # these are the only two types that perform + # pandas compatibility input validation - the + # rest already perform separate (or no) such + # validation via their 'values' attribute as + # defined in pandas.core.indexes/base.py - they + # cannot be changed at the moment due to + # backwards compatibility concerns + if isinstance(index, (CategoricalIndex, RangeIndex)): + msg = "the 'axis' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.argsort(index, axis=1) + + msg = "the 'order' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.argsort(index, order=("a", "b")) + + def test_repeat(self, simple_index): + rep = 2 + idx = simple_index.copy() + new_index_cls = idx._constructor + expected = new_index_cls(idx.values.repeat(rep), name=idx.name) + tm.assert_index_equal(idx.repeat(rep), expected) + + idx = simple_index + rep = np.arange(len(idx)) + expected = new_index_cls(idx.values.repeat(rep), name=idx.name) + tm.assert_index_equal(idx.repeat(rep), expected) + + def test_numpy_repeat(self, simple_index): + rep = 2 + idx = simple_index + expected = idx.repeat(rep) + tm.assert_index_equal(np.repeat(idx, rep), expected) + + msg = "the 'axis' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.repeat(idx, rep, axis=0) + + def test_where(self, listlike_box, simple_index): + if isinstance(simple_index, (IntervalIndex, PeriodIndex)) or is_numeric_dtype( + simple_index.dtype + ): + pytest.skip("Tested elsewhere.") + klass = listlike_box + + idx = simple_index + if isinstance(idx, (DatetimeIndex, TimedeltaIndex)): + # where does not preserve freq + idx = idx._with_freq(None) + + cond = [True] * len(idx) + result = idx.where(klass(cond)) + expected = idx + tm.assert_index_equal(result, expected) + + cond = [False] + [True] * len(idx[1:]) + expected = Index([idx._na_value] + idx[1:].tolist(), dtype=idx.dtype) + result = idx.where(klass(cond)) + tm.assert_index_equal(result, expected) + + def test_insert_base(self, index): + trimmed = index[1:4] + + if not len(index): + pytest.skip("Not applicable for empty index") + + # test 0th element + warn = None + if index.dtype == object and index.inferred_type == "boolean": + # GH#51363 + warn = FutureWarning + msg = "The behavior of Index.insert with object-dtype is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = trimmed.insert(0, index[0]) + assert index[0:4].equals(result) + + def test_insert_out_of_bounds(self, index, using_infer_string): + # TypeError/IndexError matches what np.insert raises in these cases + + if len(index) > 0: + err = TypeError + else: + err = IndexError + if len(index) == 0: + # 0 vs 0.5 in error message varies with numpy version + msg = "index (0|0.5) is out of bounds for axis 0 with size 0" + else: + msg = "slice indices must be integers or None or have an __index__ method" + + if using_infer_string: + if index.dtype == "string" or index.dtype == "category": # noqa: PLR1714 + msg = "loc must be an integer between" + elif index.dtype == "object" and len(index) == 0: + msg = "loc must be an integer between" + err = TypeError + + with pytest.raises(err, match=msg): + index.insert(0.5, "foo") + + msg = "|".join( + [ + r"index -?\d+ is out of bounds for axis 0 with size \d+", + "loc must be an integer between", + ] + ) + with pytest.raises(IndexError, match=msg): + index.insert(len(index) + 1, 1) + + with pytest.raises(IndexError, match=msg): + index.insert(-len(index) - 1, 1) + + def test_delete_base(self, index): + if not len(index): + pytest.skip("Not applicable for empty index") + + if isinstance(index, RangeIndex): + # tested in class + pytest.skip(f"{type(self).__name__} tested elsewhere") + + expected = index[1:] + result = index.delete(0) + assert result.equals(expected) + assert result.name == expected.name + + expected = index[:-1] + result = index.delete(-1) + assert result.equals(expected) + assert result.name == expected.name + + length = len(index) + msg = f"index {length} is out of bounds for axis 0 with size {length}" + with pytest.raises(IndexError, match=msg): + index.delete(length) + + @pytest.mark.filterwarnings(r"ignore:Dtype inference:FutureWarning") + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_equals(self, index): + if isinstance(index, IntervalIndex): + pytest.skip(f"{type(index).__name__} tested elsewhere") + + is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype) + + assert index.equals(index) + assert index.equals(index.copy()) + if not is_ea_idx: + # doesn't hold for e.g. IntegerDtype + assert index.equals(index.astype(object)) + + assert not index.equals(list(index)) + assert not index.equals(np.array(index)) + + # Cannot pass in non-int64 dtype to RangeIndex + if not isinstance(index, RangeIndex) and not is_ea_idx: + same_values = Index(index, dtype=object) + assert index.equals(same_values) + assert same_values.equals(index) + + if index.nlevels == 1: + # do not test MultiIndex + assert not index.equals(Series(index)) + + def test_equals_op(self, simple_index): + # GH9947, GH10637 + index_a = simple_index + + n = len(index_a) + index_b = index_a[0:-1] + index_c = index_a[0:-1].append(index_a[-2:-1]) + index_d = index_a[0:1] + + msg = "Lengths must match|could not be broadcast" + with pytest.raises(ValueError, match=msg): + index_a == index_b + expected1 = np.array([True] * n) + expected2 = np.array([True] * (n - 1) + [False]) + tm.assert_numpy_array_equal(index_a == index_a, expected1) + tm.assert_numpy_array_equal(index_a == index_c, expected2) + + # test comparisons with numpy arrays + array_a = np.array(index_a) + array_b = np.array(index_a[0:-1]) + array_c = np.array(index_a[0:-1].append(index_a[-2:-1])) + array_d = np.array(index_a[0:1]) + with pytest.raises(ValueError, match=msg): + index_a == array_b + tm.assert_numpy_array_equal(index_a == array_a, expected1) + tm.assert_numpy_array_equal(index_a == array_c, expected2) + + # test comparisons with Series + series_a = Series(array_a) + series_b = Series(array_b) + series_c = Series(array_c) + series_d = Series(array_d) + with pytest.raises(ValueError, match=msg): + index_a == series_b + + tm.assert_numpy_array_equal(index_a == series_a, expected1) + tm.assert_numpy_array_equal(index_a == series_c, expected2) + + # cases where length is 1 for one of them + with pytest.raises(ValueError, match="Lengths must match"): + index_a == index_d + with pytest.raises(ValueError, match="Lengths must match"): + index_a == series_d + with pytest.raises(ValueError, match="Lengths must match"): + index_a == array_d + msg = "Can only compare identically-labeled Series objects" + with pytest.raises(ValueError, match=msg): + series_a == series_d + with pytest.raises(ValueError, match="Lengths must match"): + series_a == array_d + + # comparing with a scalar should broadcast; note that we are excluding + # MultiIndex because in this case each item in the index is a tuple of + # length 2, and therefore is considered an array of length 2 in the + # comparison instead of a scalar + if not isinstance(index_a, MultiIndex): + expected3 = np.array([False] * (len(index_a) - 2) + [True, False]) + # assuming the 2nd to last item is unique in the data + item = index_a[-2] + tm.assert_numpy_array_equal(index_a == item, expected3) + tm.assert_series_equal(series_a == item, Series(expected3)) + + def test_format(self, simple_index): + # GH35439 + if is_numeric_dtype(simple_index.dtype) or isinstance( + simple_index, DatetimeIndex + ): + pytest.skip("Tested elsewhere.") + idx = simple_index + expected = [str(x) for x in idx] + msg = r"Index\.format is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert idx.format() == expected + + def test_format_empty(self, simple_index): + # GH35712 + if isinstance(simple_index, (PeriodIndex, RangeIndex)): + pytest.skip("Tested elsewhere") + empty_idx = type(simple_index)([]) + msg = r"Index\.format is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert empty_idx.format() == [] + with tm.assert_produces_warning(FutureWarning, match=msg): + assert empty_idx.format(name=True) == [""] + + def test_fillna(self, index): + # GH 11343 + if len(index) == 0: + pytest.skip("Not relevant for empty index") + elif index.dtype == bool: + pytest.skip(f"{index.dtype} cannot hold NAs") + elif isinstance(index, Index) and is_integer_dtype(index.dtype): + pytest.skip(f"Not relevant for Index with {index.dtype}") + elif isinstance(index, MultiIndex): + idx = index.copy(deep=True) + msg = "isna is not defined for MultiIndex" + with pytest.raises(NotImplementedError, match=msg): + idx.fillna(idx[0]) + else: + idx = index.copy(deep=True) + result = idx.fillna(idx[0]) + tm.assert_index_equal(result, idx) + assert result is not idx + + msg = "'value' must be a scalar, passed: " + with pytest.raises(TypeError, match=msg): + idx.fillna([idx[0]]) + + idx = index.copy(deep=True) + values = idx._values + + values[1] = np.nan + + idx = type(index)(values) + + msg = "does not support 'downcast'" + msg2 = r"The 'downcast' keyword in .*Index\.fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg2): + with pytest.raises(NotImplementedError, match=msg): + # For now at least, we only raise if there are NAs present + idx.fillna(idx[0], downcast="infer") + + expected = np.array([False] * len(idx), dtype=bool) + expected[1] = True + tm.assert_numpy_array_equal(idx._isnan, expected) + assert idx.hasnans is True + + def test_nulls(self, index): + # this is really a smoke test for the methods + # as these are adequately tested for function elsewhere + if len(index) == 0: + tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool)) + elif isinstance(index, MultiIndex): + idx = index.copy() + msg = "isna is not defined for MultiIndex" + with pytest.raises(NotImplementedError, match=msg): + idx.isna() + elif not index.hasnans: + tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool)) + tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool)) + else: + result = isna(index) + tm.assert_numpy_array_equal(index.isna(), result) + tm.assert_numpy_array_equal(index.notna(), ~result) + + def test_empty(self, simple_index): + # GH 15270 + idx = simple_index + assert not idx.empty + assert idx[:0].empty + + def test_join_self_unique(self, join_type, simple_index): + idx = simple_index + if idx.is_unique: + joined = idx.join(idx, how=join_type) + expected = simple_index + if join_type == "outer": + expected = algos.safe_sort(expected) + tm.assert_index_equal(joined, expected) + + def test_map(self, simple_index): + # callable + if isinstance(simple_index, (TimedeltaIndex, PeriodIndex)): + pytest.skip("Tested elsewhere.") + idx = simple_index + + result = idx.map(lambda x: x) + # RangeIndex are equivalent to the similar Index with int64 dtype + tm.assert_index_equal(result, idx, exact="equiv") + + @pytest.mark.parametrize( + "mapper", + [ + lambda values, index: {i: e for e, i in zip(values, index)}, + lambda values, index: Series(values, index), + ], + ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_map_dictlike(self, mapper, simple_index, request): + idx = simple_index + if isinstance(idx, (DatetimeIndex, TimedeltaIndex, PeriodIndex)): + pytest.skip("Tested elsewhere.") + + identity = mapper(idx.values, idx) + + result = idx.map(identity) + # RangeIndex are equivalent to the similar Index with int64 dtype + tm.assert_index_equal(result, idx, exact="equiv") + + # empty mappable + dtype = None + if idx.dtype.kind == "f": + dtype = idx.dtype + + expected = Index([np.nan] * len(idx), dtype=dtype) + result = idx.map(mapper(expected, idx)) + tm.assert_index_equal(result, expected) + + def test_map_str(self, simple_index): + # GH 31202 + if isinstance(simple_index, CategoricalIndex): + pytest.skip("See test_map.py") + idx = simple_index + result = idx.map(str) + expected = Index([str(x) for x in idx]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("copy", [True, False]) + @pytest.mark.parametrize("name", [None, "foo"]) + @pytest.mark.parametrize("ordered", [True, False]) + def test_astype_category(self, copy, name, ordered, simple_index): + # GH 18630 + idx = simple_index + if name: + idx = idx.rename(name) + + # standard categories + dtype = CategoricalDtype(ordered=ordered) + result = idx.astype(dtype, copy=copy) + expected = CategoricalIndex(idx, name=name, ordered=ordered) + tm.assert_index_equal(result, expected, exact=True) + + # non-standard categories + dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered) + result = idx.astype(dtype, copy=copy) + expected = CategoricalIndex(idx, name=name, dtype=dtype) + tm.assert_index_equal(result, expected, exact=True) + + if ordered is False: + # dtype='category' defaults to ordered=False, so only test once + result = idx.astype("category", copy=copy) + expected = CategoricalIndex(idx, name=name) + tm.assert_index_equal(result, expected, exact=True) + + def test_is_unique(self, simple_index): + # initialize a unique index + index = simple_index.drop_duplicates() + assert index.is_unique is True + + # empty index should be unique + index_empty = index[:0] + assert index_empty.is_unique is True + + # test basic dupes + index_dup = index.insert(0, index[0]) + assert index_dup.is_unique is False + + # single NA should be unique + index_na = index.insert(0, np.nan) + assert index_na.is_unique is True + + # multiple NA should not be unique + index_na_dup = index_na.insert(0, np.nan) + assert index_na_dup.is_unique is False + + @pytest.mark.arm_slow + def test_engine_reference_cycle(self, simple_index): + # GH27585 + index = simple_index.copy() + ref = weakref.ref(index) + index._engine + del index + assert ref() is None + + def test_getitem_2d_deprecated(self, simple_index): + # GH#30588, GH#31479 + if isinstance(simple_index, IntervalIndex): + pytest.skip("Tested elsewhere") + idx = simple_index + msg = "Multi-dimensional indexing|too many|only" + with pytest.raises((ValueError, IndexError), match=msg): + idx[:, None] + + if not isinstance(idx, RangeIndex): + # GH#44051 RangeIndex already raised pre-2.0 with a different message + with pytest.raises((ValueError, IndexError), match=msg): + idx[True] + with pytest.raises((ValueError, IndexError), match=msg): + idx[False] + else: + msg = "only integers, slices" + with pytest.raises(IndexError, match=msg): + idx[True] + with pytest.raises(IndexError, match=msg): + idx[False] + + def test_copy_shares_cache(self, simple_index): + # GH32898, GH36840 + idx = simple_index + idx.get_loc(idx[0]) # populates the _cache. + copy = idx.copy() + + assert copy._cache is idx._cache + + def test_shallow_copy_shares_cache(self, simple_index): + # GH32669, GH36840 + idx = simple_index + idx.get_loc(idx[0]) # populates the _cache. + shallow_copy = idx._view() + + assert shallow_copy._cache is idx._cache + + shallow_copy = idx._shallow_copy(idx._data) + assert shallow_copy._cache is not idx._cache + assert shallow_copy._cache == {} + + def test_index_groupby(self, simple_index): + idx = simple_index[:5] + to_groupby = np.array([1, 2, np.nan, 2, 1]) + tm.assert_dict_equal( + idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]} + ) + + to_groupby = DatetimeIndex( + [ + datetime(2011, 11, 1), + datetime(2011, 12, 1), + pd.NaT, + datetime(2011, 12, 1), + datetime(2011, 11, 1), + ], + tz="UTC", + ).values + + ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")] + expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]} + tm.assert_dict_equal(idx.groupby(to_groupby), expected) + + def test_append_preserves_dtype(self, simple_index): + # In particular Index with dtype float32 + index = simple_index + N = len(index) + + result = index.append(index) + assert result.dtype == index.dtype + tm.assert_index_equal(result[:N], index, check_exact=True) + tm.assert_index_equal(result[N:], index, check_exact=True) + + alt = index.take(list(range(N)) * 2) + tm.assert_index_equal(result, alt, check_exact=True) + + def test_inv(self, simple_index, using_infer_string): + idx = simple_index + + if idx.dtype.kind in ["i", "u"]: + res = ~idx + expected = Index(~idx.values, name=idx.name) + tm.assert_index_equal(res, expected) + + # check that we are matching Series behavior + res2 = ~Series(idx) + tm.assert_series_equal(res2, Series(expected)) + else: + if idx.dtype.kind == "f": + msg = "ufunc 'invert' not supported for the input types" + else: + msg = "bad operand|__invert__ is not supported for string dtype" + with pytest.raises(TypeError, match=msg): + ~idx + + # check that we get the same behavior with Series + with pytest.raises(TypeError, match=msg): + ~Series(idx) + + def test_is_boolean_is_deprecated(self, simple_index): + # GH50042 + idx = simple_index + with tm.assert_produces_warning(FutureWarning): + idx.is_boolean() + + def test_is_floating_is_deprecated(self, simple_index): + # GH50042 + idx = simple_index + with tm.assert_produces_warning(FutureWarning): + idx.is_floating() + + def test_is_integer_is_deprecated(self, simple_index): + # GH50042 + idx = simple_index + with tm.assert_produces_warning(FutureWarning): + idx.is_integer() + + def test_holds_integer_deprecated(self, simple_index): + # GH50243 + idx = simple_index + msg = f"{type(idx).__name__}.holds_integer is deprecated. " + with tm.assert_produces_warning(FutureWarning, match=msg): + idx.holds_integer() + + def test_is_numeric_is_deprecated(self, simple_index): + # GH50042 + idx = simple_index + with tm.assert_produces_warning( + FutureWarning, + match=f"{type(idx).__name__}.is_numeric is deprecated. ", + ): + idx.is_numeric() + + def test_is_categorical_is_deprecated(self, simple_index): + # GH50042 + idx = simple_index + with tm.assert_produces_warning( + FutureWarning, + match=r"Use pandas\.api\.types\.is_categorical_dtype instead", + ): + idx.is_categorical() + + def test_is_interval_is_deprecated(self, simple_index): + # GH50042 + idx = simple_index + with tm.assert_produces_warning(FutureWarning): + idx.is_interval() + + def test_is_object_is_deprecated(self, simple_index): + # GH50042 + idx = simple_index + with tm.assert_produces_warning(FutureWarning): + idx.is_object() + + +class TestNumericBase: + @pytest.fixture( + params=[ + RangeIndex(start=0, stop=20, step=2), + Index(np.arange(5, dtype=np.float64)), + Index(np.arange(5, dtype=np.float32)), + Index(np.arange(5, dtype=np.uint64)), + Index(range(0, 20, 2), dtype=np.int64), + Index(range(0, 20, 2), dtype=np.int32), + Index(range(0, 20, 2), dtype=np.int16), + Index(range(0, 20, 2), dtype=np.int8), + ] + ) + def simple_index(self, request): + return request.param + + def test_constructor_unwraps_index(self, simple_index): + if isinstance(simple_index, RangeIndex): + pytest.skip("Tested elsewhere.") + index_cls = type(simple_index) + dtype = simple_index.dtype + + idx = Index([1, 2], dtype=dtype) + result = index_cls(idx) + expected = np.array([1, 2], dtype=idx.dtype) + tm.assert_numpy_array_equal(result._data, expected) + + def test_can_hold_identifiers(self, simple_index): + idx = simple_index + key = idx[0] + assert idx._can_hold_identifiers_and_holds_name(key) is False + + def test_view(self, simple_index): + if isinstance(simple_index, RangeIndex): + pytest.skip("Tested elsewhere.") + index_cls = type(simple_index) + dtype = simple_index.dtype + + idx = index_cls([], dtype=dtype, name="Foo") + idx_view = idx.view() + assert idx_view.name == "Foo" + + idx_view = idx.view(dtype) + tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True) + + msg = "Passing a type in .*Index.view is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx_view = idx.view(index_cls) + tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True) + + def test_format(self, simple_index): + # GH35439 + if isinstance(simple_index, DatetimeIndex): + pytest.skip("Tested elsewhere") + idx = simple_index + max_width = max(len(str(x)) for x in idx) + expected = [str(x).ljust(max_width) for x in idx] + msg = r"Index\.format is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert idx.format() == expected + + def test_insert_non_na(self, simple_index): + # GH#43921 inserting an element that we know we can hold should + # not change dtype or type (except for RangeIndex) + index = simple_index + + result = index.insert(0, index[0]) + + expected = Index([index[0]] + list(index), dtype=index.dtype) + tm.assert_index_equal(result, expected, exact=True) + + def test_insert_na(self, nulls_fixture, simple_index): + # GH 18295 (test missing) + index = simple_index + na_val = nulls_fixture + + if na_val is pd.NaT: + expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object) + else: + expected = Index([index[0], np.nan] + list(index[1:])) + # GH#43921 we preserve float dtype + if index.dtype.kind == "f": + expected = Index(expected, dtype=index.dtype) + + result = index.insert(1, na_val) + tm.assert_index_equal(result, expected, exact=True) + + def test_arithmetic_explicit_conversions(self, simple_index): + # GH 8608 + # add/sub are overridden explicitly for Float/Int Index + index_cls = type(simple_index) + if index_cls is RangeIndex: + idx = RangeIndex(5) + else: + idx = index_cls(np.arange(5, dtype="int64")) + + # float conversions + arr = np.arange(5, dtype="int64") * 3.2 + expected = Index(arr, dtype=np.float64) + fidx = idx * 3.2 + tm.assert_index_equal(fidx, expected) + fidx = 3.2 * idx + tm.assert_index_equal(fidx, expected) + + # interops with numpy arrays + expected = Index(arr, dtype=np.float64) + a = np.zeros(5, dtype="float64") + result = fidx - a + tm.assert_index_equal(result, expected) + + expected = Index(-arr, dtype=np.float64) + a = np.zeros(5, dtype="float64") + result = a - fidx + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("complex_dtype", [np.complex64, np.complex128]) + def test_astype_to_complex(self, complex_dtype, simple_index): + result = simple_index.astype(complex_dtype) + + assert type(result) is Index and result.dtype == complex_dtype + + def test_cast_string(self, simple_index): + if isinstance(simple_index, RangeIndex): + pytest.skip("casting of strings not relevant for RangeIndex") + result = type(simple_index)(["0", "1", "2"], dtype=simple_index.dtype) + expected = type(simple_index)([0, 1, 2], dtype=simple_index.dtype) + tm.assert_index_equal(result, expected) diff --git a/shared/package-files/02/0269528a106152fb44e9ce73f8c47675c24f880691ea5591ae9087ea6ae17fce/sun-cgsix b/shared/package-files/02/0269528a106152fb44e9ce73f8c47675c24f880691ea5591ae9087ea6ae17fce/sun-cgsix new file mode 100644 index 0000000000000000000000000000000000000000..821fee8187a949614cdb7ba5118c88d2d7a26537 Binary files /dev/null and b/shared/package-files/02/0269528a106152fb44e9ce73f8c47675c24f880691ea5591ae9087ea6ae17fce/sun-cgsix differ diff --git a/shared/package-files/02/0269528a106152fb44e9ce73f8c47675c24f880691ea5591ae9087ea6ae17fce/sun-ss5 b/shared/package-files/02/0269528a106152fb44e9ce73f8c47675c24f880691ea5591ae9087ea6ae17fce/sun-ss5 new file mode 100644 index 0000000000000000000000000000000000000000..821fee8187a949614cdb7ba5118c88d2d7a26537 Binary files /dev/null and b/shared/package-files/02/0269528a106152fb44e9ce73f8c47675c24f880691ea5591ae9087ea6ae17fce/sun-ss5 differ diff --git a/shared/package-files/02/026e59e8b99faf65da1ff9e921f249f0c757b56b1b2e33142d926e953023df41/tests.py b/shared/package-files/02/026e59e8b99faf65da1ff9e921f249f0c757b56b1b2e33142d926e953023df41/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..a467cf08b54879ee734617611aef72ed946d4566 --- /dev/null +++ b/shared/package-files/02/026e59e8b99faf65da1ff9e921f249f0c757b56b1b2e33142d926e953023df41/tests.py @@ -0,0 +1,255 @@ +"""Built-in template tests used with the ``is`` operator.""" +import operator +import typing as t +from collections import abc +from numbers import Number + +from .runtime import Undefined +from .utils import pass_environment + +if t.TYPE_CHECKING: + from .environment import Environment + + +def test_odd(value: int) -> bool: + """Return true if the variable is odd.""" + return value % 2 == 1 + + +def test_even(value: int) -> bool: + """Return true if the variable is even.""" + return value % 2 == 0 + + +def test_divisibleby(value: int, num: int) -> bool: + """Check if a variable is divisible by a number.""" + return value % num == 0 + + +def test_defined(value: t.Any) -> bool: + """Return true if the variable is defined: + + .. sourcecode:: jinja + + {% if variable is defined %} + value of variable: {{ variable }} + {% else %} + variable is not defined + {% endif %} + + See the :func:`default` filter for a simple way to set undefined + variables. + """ + return not isinstance(value, Undefined) + + +def test_undefined(value: t.Any) -> bool: + """Like :func:`defined` but the other way round.""" + return isinstance(value, Undefined) + + +@pass_environment +def test_filter(env: "Environment", value: str) -> bool: + """Check if a filter exists by name. Useful if a filter may be + optionally available. + + .. code-block:: jinja + + {% if 'markdown' is filter %} + {{ value | markdown }} + {% else %} + {{ value }} + {% endif %} + + .. versionadded:: 3.0 + """ + return value in env.filters + + +@pass_environment +def test_test(env: "Environment", value: str) -> bool: + """Check if a test exists by name. Useful if a test may be + optionally available. + + .. code-block:: jinja + + {% if 'loud' is test %} + {% if value is loud %} + {{ value|upper }} + {% else %} + {{ value|lower }} + {% endif %} + {% else %} + {{ value }} + {% endif %} + + .. versionadded:: 3.0 + """ + return value in env.tests + + +def test_none(value: t.Any) -> bool: + """Return true if the variable is none.""" + return value is None + + +def test_boolean(value: t.Any) -> bool: + """Return true if the object is a boolean value. + + .. versionadded:: 2.11 + """ + return value is True or value is False + + +def test_false(value: t.Any) -> bool: + """Return true if the object is False. + + .. versionadded:: 2.11 + """ + return value is False + + +def test_true(value: t.Any) -> bool: + """Return true if the object is True. + + .. versionadded:: 2.11 + """ + return value is True + + +# NOTE: The existing 'number' test matches booleans and floats +def test_integer(value: t.Any) -> bool: + """Return true if the object is an integer. + + .. versionadded:: 2.11 + """ + return isinstance(value, int) and value is not True and value is not False + + +# NOTE: The existing 'number' test matches booleans and integers +def test_float(value: t.Any) -> bool: + """Return true if the object is a float. + + .. versionadded:: 2.11 + """ + return isinstance(value, float) + + +def test_lower(value: str) -> bool: + """Return true if the variable is lowercased.""" + return str(value).islower() + + +def test_upper(value: str) -> bool: + """Return true if the variable is uppercased.""" + return str(value).isupper() + + +def test_string(value: t.Any) -> bool: + """Return true if the object is a string.""" + return isinstance(value, str) + + +def test_mapping(value: t.Any) -> bool: + """Return true if the object is a mapping (dict etc.). + + .. versionadded:: 2.6 + """ + return isinstance(value, abc.Mapping) + + +def test_number(value: t.Any) -> bool: + """Return true if the variable is a number.""" + return isinstance(value, Number) + + +def test_sequence(value: t.Any) -> bool: + """Return true if the variable is a sequence. Sequences are variables + that are iterable. + """ + try: + len(value) + value.__getitem__ + except Exception: + return False + + return True + + +def test_sameas(value: t.Any, other: t.Any) -> bool: + """Check if an object points to the same memory address than another + object: + + .. sourcecode:: jinja + + {% if foo.attribute is sameas false %} + the foo attribute really is the `False` singleton + {% endif %} + """ + return value is other + + +def test_iterable(value: t.Any) -> bool: + """Check if it's possible to iterate over an object.""" + try: + iter(value) + except TypeError: + return False + + return True + + +def test_escaped(value: t.Any) -> bool: + """Check if the value is escaped.""" + return hasattr(value, "__html__") + + +def test_in(value: t.Any, seq: t.Container) -> bool: + """Check if value is in seq. + + .. versionadded:: 2.10 + """ + return value in seq + + +TESTS = { + "odd": test_odd, + "even": test_even, + "divisibleby": test_divisibleby, + "defined": test_defined, + "undefined": test_undefined, + "filter": test_filter, + "test": test_test, + "none": test_none, + "boolean": test_boolean, + "false": test_false, + "true": test_true, + "integer": test_integer, + "float": test_float, + "lower": test_lower, + "upper": test_upper, + "string": test_string, + "mapping": test_mapping, + "number": test_number, + "sequence": test_sequence, + "iterable": test_iterable, + "callable": callable, + "sameas": test_sameas, + "escaped": test_escaped, + "in": test_in, + "==": operator.eq, + "eq": operator.eq, + "equalto": operator.eq, + "!=": operator.ne, + "ne": operator.ne, + ">": operator.gt, + "gt": operator.gt, + "greaterthan": operator.gt, + "ge": operator.ge, + ">=": operator.ge, + "<": operator.lt, + "lt": operator.lt, + "lessthan": operator.lt, + "<=": operator.le, + "le": operator.le, +} diff --git a/shared/package-files/02/026f5ccb9bbbdf60792a670d2d56ff011cba7318aad8c21752eb7a254ddee97f/_parquet_encryption.pyx b/shared/package-files/02/026f5ccb9bbbdf60792a670d2d56ff011cba7318aad8c21752eb7a254ddee97f/_parquet_encryption.pyx new file mode 100644 index 0000000000000000000000000000000000000000..6185d5f2392cfe98e9d1ebbb400039e492a3d311 --- /dev/null +++ b/shared/package-files/02/026f5ccb9bbbdf60792a670d2d56ff011cba7318aad8c21752eb7a254ddee97f/_parquet_encryption.pyx @@ -0,0 +1,710 @@ +# 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. + +# cython: profile=False +# distutils: language = c++ + +from datetime import timedelta + +from cpython.bytes cimport PyBytes_FromStringAndSize +from cython.operator cimport dereference as deref + +from pyarrow.includes.common cimport * +from pyarrow.includes.libarrow cimport * +from pyarrow.lib cimport check_status +from pyarrow.lib cimport _Weakrefable +from pyarrow.lib import tobytes, frombytes +from pyarrow._fs cimport FileSystem +from pyarrow.fs import _resolve_filesystem_and_path + +cdef ParquetCipher cipher_from_name(name): + name = name.upper() + if name == 'AES_GCM_V1': + return ParquetCipher_AES_GCM_V1 + elif name == 'AES_GCM_CTR_V1': + return ParquetCipher_AES_GCM_CTR_V1 + else: + raise ValueError(f'Invalid cipher name: {name!r}') + + +cdef cipher_to_name(ParquetCipher cipher): + if ParquetCipher_AES_GCM_V1 == cipher: + return 'AES_GCM_V1' + elif ParquetCipher_AES_GCM_CTR_V1 == cipher: + return 'AES_GCM_CTR_V1' + else: + raise ValueError(f'Invalid cipher value: {cipher}') + +cdef class EncryptionConfiguration(_Weakrefable): + """Configuration of the encryption, such as which columns to encrypt""" + # Avoid mistakingly creating attributes + __slots__ = () + + def __init__(self, footer_key, *, column_keys=None, + uniform_encryption=None, + encryption_algorithm=None, + plaintext_footer=None, double_wrapping=None, + cache_lifetime=None, internal_key_material=None, + data_key_length_bits=None): + self.configuration.reset( + new CEncryptionConfiguration(tobytes(footer_key))) + if column_keys is not None: + self.column_keys = column_keys + if uniform_encryption is not None: + self.uniform_encryption = uniform_encryption + if encryption_algorithm is not None: + self.encryption_algorithm = encryption_algorithm + if plaintext_footer is not None: + self.plaintext_footer = plaintext_footer + if double_wrapping is not None: + self.double_wrapping = double_wrapping + if cache_lifetime is not None: + self.cache_lifetime = cache_lifetime + if internal_key_material is not None: + self.internal_key_material = internal_key_material + if data_key_length_bits is not None: + self.data_key_length_bits = data_key_length_bits + + @property + def footer_key(self): + """ID of the master key for footer encryption/signing""" + return frombytes(self.configuration.get().footer_key) + + @property + def column_keys(self): + """ + List of columns to encrypt, with master key IDs. + """ + column_keys_str = frombytes(self.configuration.get().column_keys) + # Convert from "masterKeyID:colName,colName;masterKeyID:colName..." + # (see HIVE-21848) to dictionary of master key ID to column name lists + column_keys_to_key_list_str = dict(subString.replace(" ", "").split( + ":") for subString in column_keys_str.split(";")) + column_keys_dict = {k: v.split( + ",") for k, v in column_keys_to_key_list_str.items()} + return column_keys_dict + + @column_keys.setter + def column_keys(self, dict value): + if value is not None: + # convert a dictionary such as + # '{"key1": ["col1 ", "col2"], "key2": ["col3 ", "col4"]}'' + # to the string defined by the spec + # 'key1: col1 , col2; key2: col3 , col4' + column_keys = "; ".join( + [f"{k}: {', '.join(v)}" for k, v in value.items()]) + self.configuration.get().column_keys = tobytes(column_keys) + + @property + def uniform_encryption(self): + """Whether to encrypt footer and all columns with the same encryption key. + + This cannot be used together with column_keys. + """ + return self.configuration.get().uniform_encryption + + @uniform_encryption.setter + def uniform_encryption(self, value): + self.configuration.get().uniform_encryption = value + + @property + def encryption_algorithm(self): + """Parquet encryption algorithm. + Can be "AES_GCM_V1" (default), or "AES_GCM_CTR_V1".""" + return cipher_to_name(self.configuration.get().encryption_algorithm) + + @encryption_algorithm.setter + def encryption_algorithm(self, value): + cipher = cipher_from_name(value) + self.configuration.get().encryption_algorithm = cipher + + @property + def plaintext_footer(self): + """Write files with plaintext footer.""" + return self.configuration.get().plaintext_footer + + @plaintext_footer.setter + def plaintext_footer(self, value): + self.configuration.get().plaintext_footer = value + + @property + def double_wrapping(self): + """Use double wrapping - where data encryption keys (DEKs) are + encrypted with key encryption keys (KEKs), which in turn are + encrypted with master keys. + If set to false, use single wrapping - where DEKs are + encrypted directly with master keys.""" + return self.configuration.get().double_wrapping + + @double_wrapping.setter + def double_wrapping(self, value): + self.configuration.get().double_wrapping = value + + @property + def cache_lifetime(self): + """Lifetime of cached entities (key encryption keys, + local wrapping keys, KMS client objects).""" + return timedelta( + seconds=self.configuration.get().cache_lifetime_seconds) + + @cache_lifetime.setter + def cache_lifetime(self, value): + if not isinstance(value, timedelta): + raise TypeError("cache_lifetime should be a timedelta") + self.configuration.get().cache_lifetime_seconds = value.total_seconds() + + @property + def internal_key_material(self): + """Store key material inside Parquet file footers; this mode doesn’t + produce additional files. If set to false, key material is stored in + separate files in the same folder, which enables key rotation for + immutable Parquet files.""" + return self.configuration.get().internal_key_material + + @internal_key_material.setter + def internal_key_material(self, value): + self.configuration.get().internal_key_material = value + + @property + def data_key_length_bits(self): + """Length of data encryption keys (DEKs), randomly generated by parquet key + management tools. Can be 128, 192 or 256 bits.""" + return self.configuration.get().data_key_length_bits + + @data_key_length_bits.setter + def data_key_length_bits(self, value): + self.configuration.get().data_key_length_bits = value + + cdef inline shared_ptr[CEncryptionConfiguration] unwrap(self) nogil: + return self.configuration + + +cdef class DecryptionConfiguration(_Weakrefable): + """Configuration of the decryption, such as cache timeout.""" + # Avoid mistakingly creating attributes + __slots__ = () + + def __init__(self, *, cache_lifetime=None): + self.configuration.reset(new CDecryptionConfiguration()) + + @property + def cache_lifetime(self): + """Lifetime of cached entities (key encryption keys, + local wrapping keys, KMS client objects).""" + return timedelta( + seconds=self.configuration.get().cache_lifetime_seconds) + + @cache_lifetime.setter + def cache_lifetime(self, value): + self.configuration.get().cache_lifetime_seconds = value.total_seconds() + + cdef inline shared_ptr[CDecryptionConfiguration] unwrap(self) nogil: + return self.configuration + + +cdef class KmsConnectionConfig(_Weakrefable): + """Configuration of the connection to the Key Management Service (KMS)""" + # Avoid mistakingly creating attributes + __slots__ = () + + def __init__(self, *, kms_instance_id=None, kms_instance_url=None, + key_access_token=None, custom_kms_conf=None): + self.configuration.reset(new CKmsConnectionConfig()) + if kms_instance_id is not None: + self.kms_instance_id = kms_instance_id + if kms_instance_url is not None: + self.kms_instance_url = kms_instance_url + if key_access_token is None: + self.key_access_token = b'DEFAULT' + else: + self.key_access_token = key_access_token + if custom_kms_conf is not None: + self.custom_kms_conf = custom_kms_conf + + @property + def kms_instance_id(self): + """ID of the KMS instance that will be used for encryption + (if multiple KMS instances are available).""" + return frombytes(self.configuration.get().kms_instance_id) + + @kms_instance_id.setter + def kms_instance_id(self, value): + self.configuration.get().kms_instance_id = tobytes(value) + + @property + def kms_instance_url(self): + """URL of the KMS instance.""" + return frombytes(self.configuration.get().kms_instance_url) + + @kms_instance_url.setter + def kms_instance_url(self, value): + self.configuration.get().kms_instance_url = tobytes(value) + + @property + def key_access_token(self): + """Authorization token that will be passed to KMS.""" + return frombytes(self.configuration.get() + .refreshable_key_access_token.get().value()) + + @key_access_token.setter + def key_access_token(self, value): + self.refresh_key_access_token(value) + + @property + def custom_kms_conf(self): + """A dictionary with KMS-type-specific configuration""" + custom_kms_conf = { + frombytes(k): frombytes(v) + for k, v in self.configuration.get().custom_kms_conf + } + return custom_kms_conf + + @custom_kms_conf.setter + def custom_kms_conf(self, dict value): + if value is not None: + for k, v in value.items(): + if isinstance(k, str) and isinstance(v, str): + self.configuration.get().custom_kms_conf[tobytes(k)] = \ + tobytes(v) + else: + raise TypeError("Expected custom_kms_conf to be " + + "a dictionary of strings") + + def refresh_key_access_token(self, value): + cdef: + shared_ptr[CKeyAccessToken] c_key_access_token = \ + self.configuration.get().refreshable_key_access_token + + c_key_access_token.get().Refresh(tobytes(value)) + + cdef inline shared_ptr[CKmsConnectionConfig] unwrap(self) nogil: + return self.configuration + + @staticmethod + cdef wrap(const CKmsConnectionConfig& config): + result = KmsConnectionConfig() + result.configuration = make_shared[CKmsConnectionConfig](move(config)) + return result + + +# Callback definitions for CPyKmsClientVtable +cdef void _cb_wrap_key( + handler, const CSecureString& key, + const c_string& master_key_identifier, c_string* out) except *: + view = key.as_view() + key_bytes = PyBytes_FromStringAndSize(view.data(), view.size()) + mkid_str = frombytes(master_key_identifier) + wrapped_key = handler.wrap_key(key_bytes, mkid_str) + out[0] = tobytes(wrapped_key) + + +cdef void _cb_unwrap_key( + handler, const c_string& wrapped_key, + const c_string& master_key_identifier, CSecureString* out) except *: + mkid_str = frombytes(master_key_identifier) + wk_str = frombytes(wrapped_key) + key = handler.unwrap_key(wk_str, mkid_str) + cstr = tobytes(key) + out[0] = CSecureString(move(cstr)) + + +cdef class KmsClient(_Weakrefable): + """The abstract base class for KmsClient implementations.""" + cdef: + shared_ptr[CKmsClient] client + + def __init__(self): + self.init() + + cdef init(self): + cdef: + CPyKmsClientVtable vtable = CPyKmsClientVtable() + + vtable.wrap_key = _cb_wrap_key + vtable.unwrap_key = _cb_unwrap_key + + self.client.reset(new CPyKmsClient(self, vtable)) + + def wrap_key(self, key_bytes, master_key_identifier): + """Wrap a key - encrypt it with the master key.""" + raise NotImplementedError() + + def unwrap_key(self, wrapped_key, master_key_identifier): + """Unwrap a key - decrypt it with the master key.""" + raise NotImplementedError() + + cdef inline shared_ptr[CKmsClient] unwrap(self) nogil: + return self.client + + +# Callback definition for CPyKmsClientFactoryVtable +cdef void _cb_create_kms_client( + handler, + const CKmsConnectionConfig& kms_connection_config, + shared_ptr[CKmsClient]* out) except *: + connection_config = KmsConnectionConfig.wrap(kms_connection_config) + + result = handler(connection_config) + if not isinstance(result, KmsClient): + raise TypeError( + f"callable must return KmsClient instances, but got {type(result)}") + + out[0] = ( result).unwrap() + + +cdef inline shared_ptr[CFileSystem] _unwrap_fs(filesystem: FileSystem | None): + if isinstance(filesystem, FileSystem): + return filesystem.unwrap() + else: + return nullptr + + +cdef class CryptoFactory(_Weakrefable): + """ A factory that produces the low-level FileEncryptionProperties and + FileDecryptionProperties objects, from the high-level parameters.""" + # Avoid mistakingly creating attributes + __slots__ = () + + def __init__(self, kms_client_factory): + """Create CryptoFactory. + + Parameters + ---------- + kms_client_factory : a callable that accepts KmsConnectionConfig + and returns a KmsClient + """ + self.factory.reset(new CPyCryptoFactory()) + + if callable(kms_client_factory): + self.init(kms_client_factory) + else: + raise TypeError("Parameter kms_client_factory must be a callable") + + cdef init(self, callable_client_factory): + cdef: + CPyKmsClientFactoryVtable vtable + shared_ptr[CPyKmsClientFactory] kms_client_factory + + vtable.create_kms_client = _cb_create_kms_client + kms_client_factory.reset( + new CPyKmsClientFactory(callable_client_factory, vtable)) + # A KmsClientFactory object must be registered + # via this method before calling any of + # file_encryption_properties()/file_decryption_properties() methods. + self.factory.get().RegisterKmsClientFactory( + static_pointer_cast[CKmsClientFactory, CPyKmsClientFactory]( + kms_client_factory)) + + def file_encryption_properties(self, + KmsConnectionConfig kms_connection_config, + EncryptionConfiguration encryption_config, + parquet_file_path=None, + FileSystem filesystem=None): + """Create file encryption properties. + + Parameters + ---------- + kms_connection_config : KmsConnectionConfig + Configuration of connection to KMS + + encryption_config : EncryptionConfiguration + Configuration of the encryption, such as which columns to encrypt + + parquet_file_path : str, pathlib.Path, or None, default None + Path to the parquet file to be encrypted. Only required when the + internal_key_material attribute of EncryptionConfiguration is set + to False. Used to derive the path for storing key material + specific to this parquet file. + + filesystem : FileSystem or None, default None + Used only when internal_key_material is set to False on + EncryptionConfiguration. If None, the file system will be inferred + based on parquet_file_path. + + Returns + ------- + file_encryption_properties : FileEncryptionProperties + File encryption properties. + """ + cdef: + CResult[shared_ptr[CFileEncryptionProperties]] \ + file_encryption_properties_result + c_string c_parquet_file_path + shared_ptr[CFileSystem] c_filesystem + + filesystem, parquet_file_path = _resolve_filesystem_and_path( + parquet_file_path, filesystem) + if parquet_file_path is not None: + c_parquet_file_path = tobytes(parquet_file_path) + else: + c_parquet_file_path = tobytes("") + c_filesystem = _unwrap_fs(filesystem) + + with nogil: + file_encryption_properties_result = \ + self.factory.get().SafeGetFileEncryptionProperties( + deref(kms_connection_config.unwrap().get()), + deref(encryption_config.unwrap().get()), + c_parquet_file_path, c_filesystem) + file_encryption_properties = GetResultValue( + file_encryption_properties_result) + return FileEncryptionProperties.wrap(file_encryption_properties) + + def file_decryption_properties( + self, + KmsConnectionConfig kms_connection_config, + DecryptionConfiguration decryption_config=None, + parquet_file_path=None, + FileSystem filesystem=None): + """Create file decryption properties. + + Parameters + ---------- + kms_connection_config : KmsConnectionConfig + Configuration of connection to KMS + + decryption_config : DecryptionConfiguration, default None + Configuration of the decryption, such as cache timeout. + Can be None. + + parquet_file_path : str, pathlib.Path, or None, default None + Path to the parquet file to be decrypted. Only required when + the parquet file uses external key material. Used to derive + the path to the external key material file. + + filesystem : FileSystem or None, default None + Used only when the parquet file uses external key material. If + None, the file system will be inferred based on parquet_file_path. + + Returns + ------- + file_decryption_properties : FileDecryptionProperties + File decryption properties. + """ + cdef: + CDecryptionConfiguration c_decryption_config + CResult[shared_ptr[CFileDecryptionProperties]] \ + c_file_decryption_properties + c_string c_parquet_file_path + shared_ptr[CFileSystem] c_filesystem + + filesystem, parquet_file_path = _resolve_filesystem_and_path( + parquet_file_path, filesystem) + if parquet_file_path is not None: + c_parquet_file_path = tobytes(parquet_file_path) + else: + c_parquet_file_path = tobytes("") + c_filesystem = _unwrap_fs(filesystem) + + if decryption_config is None: + c_decryption_config = CDecryptionConfiguration() + else: + c_decryption_config = deref(decryption_config.unwrap().get()) + with nogil: + c_file_decryption_properties = \ + self.factory.get().SafeGetFileDecryptionProperties( + deref(kms_connection_config.unwrap().get()), + c_decryption_config, c_parquet_file_path, c_filesystem) + file_decryption_properties = GetResultValue( + c_file_decryption_properties) + return FileDecryptionProperties.wrap(file_decryption_properties) + + def remove_cache_entries_for_token(self, access_token): + self.factory.get().RemoveCacheEntriesForToken(tobytes(access_token)) + + def remove_cache_entries_for_all_tokens(self): + self.factory.get().RemoveCacheEntriesForAllTokens() + + def rotate_master_keys( + self, + KmsConnectionConfig kms_connection_config, + parquet_file_path, + FileSystem filesystem=None, + double_wrapping=True, + cache_lifetime_seconds=600): + """ Rotates master encryption keys for a Parquet file that uses + external key material. + + Parameters + ---------- + kms_connection_config : KmsConnectionConfig + Configuration of connection to KMS + + parquet_file_path : str or pathlib.Path + Path to a parquet file using external key material. + + filesystem : FileSystem or None, default None + Used only when the parquet file uses external key material. If + None, the file system will be inferred based on parquet_file_path. + + double_wrapping : bool, default True + In the single wrapping mode, encrypts data encryption keys with + new master keys. In the double wrapping mode, generates new + KEKs (key encryption keys) and uses these to encrypt the data keys, + and encrypts the KEKs with the new master keys. + + cache_lifetime_seconds : int or float, default 600 + During key rotation, KMS Client and Key Encryption Keys will be + cached for this duration. + """ + cdef: + c_string c_parquet_file_path + shared_ptr[CFileSystem] c_filesystem + + if parquet_file_path != "": + filesystem, parquet_file_path = _resolve_filesystem_and_path( + parquet_file_path, filesystem) + + c_parquet_file_path = tobytes(parquet_file_path) + c_filesystem = _unwrap_fs(filesystem) + + status = self.factory.get().SafeRotateMasterKeys( + deref(kms_connection_config.unwrap().get()), + c_parquet_file_path, + c_filesystem, + double_wrapping, + cache_lifetime_seconds) + + check_status(status) + + cdef inline shared_ptr[CPyCryptoFactory] unwrap(self): + return self.factory + +cdef class KeyMaterial(_Weakrefable): + + @property + def is_footer_key(self): + return self.key_material.get().is_footer_key() + + @property + def is_double_wrapped(self): + return self.key_material.get().is_double_wrapped() + + @property + def master_key_id(self): + return frombytes(self.key_material.get().master_key_id()) + + @property + def wrapped_dek(self): + return frombytes(self.key_material.get().wrapped_dek()) + + @property + def kek_id(self): + return frombytes(self.key_material.get().kek_id()) + + @property + def wrapped_kek(self): + return frombytes(self.key_material.get().wrapped_kek()) + + @property + def kms_instance_id(self): + return frombytes(self.key_material.get().kms_instance_id()) + + @property + def kms_instance_url(self): + return frombytes(self.key_material.get().kms_instance_url()) + + @staticmethod + cdef inline KeyMaterial wrap(shared_ptr[CKeyMaterial] key_material): + wrapper = KeyMaterial() + wrapper.key_material = key_material + return wrapper + + @staticmethod + def parse( + const c_string key_material_string): + cdef: + shared_ptr[CKeyMaterial] c_key_material + c_key_material = make_shared[CKeyMaterial](move( + CKeyMaterial.Parse(key_material_string) + )) + return KeyMaterial.wrap(c_key_material) + +cdef class FileSystemKeyMaterialStore(_Weakrefable): + + def get_key_material(self, key_id): + cdef: + c_string c_key_id = tobytes(key_id) + c_string c_key_material_string + + c_key_material_string = self.store.get().GetKeyMaterial(c_key_id) + if c_key_material_string.empty(): + raise KeyError("Invalid key id") + return KeyMaterial.parse(c_key_material_string) + + def get_key_id_set(self): + return self.store.get().GetKeyIDSet() + + @classmethod + def for_file(cls, parquet_file_path, + FileSystem filesystem=None): + """Creates a FileSystemKeyMaterialStore for a parquet file that + was created with external key material. + + Parameters + ---------- + parquet_file_path : str or pathlib.Path + Path to a parquet file using external key material. + + filesystem : FileSystem, default None + FileSystem where the parquet file is located. If None, + will be inferred based on parquet_file_path. + + Returns + ------- + FileSystemKeyMaterialStore + A FileSystemKeyMaterialStore wrapping the external key material. + """ + cdef: + c_string c_parquet_file_path + shared_ptr[CFileSystem] c_filesystem + shared_ptr[CFileSystemKeyMaterialStore] c_store + FileSystemKeyMaterialStore store = cls() + + filesystem, parquet_file_path = _resolve_filesystem_and_path( + parquet_file_path, filesystem) + c_parquet_file_path = tobytes(parquet_file_path) + c_filesystem = _unwrap_fs(filesystem) + + c_store = CFileSystemKeyMaterialStore.Make( + c_parquet_file_path, c_filesystem, False) + store.store = c_store + return store + +cdef shared_ptr[CCryptoFactory] pyarrow_unwrap_cryptofactory(object crypto_factory) except *: + if isinstance(crypto_factory, CryptoFactory): + pycf = ( crypto_factory).unwrap() + return static_pointer_cast[CCryptoFactory, CPyCryptoFactory](pycf) + raise TypeError("Expected CryptoFactory, got %s" % type(crypto_factory)) + + +cdef shared_ptr[CKmsConnectionConfig] pyarrow_unwrap_kmsconnectionconfig(object kmsconnectionconfig) except *: + if isinstance(kmsconnectionconfig, KmsConnectionConfig): + return ( kmsconnectionconfig).unwrap() + raise TypeError("Expected KmsConnectionConfig, got %s" % type(kmsconnectionconfig)) + + +cdef shared_ptr[CEncryptionConfiguration] pyarrow_unwrap_encryptionconfig(object encryptionconfig) except *: + if isinstance(encryptionconfig, EncryptionConfiguration): + return ( encryptionconfig).unwrap() + raise TypeError("Expected EncryptionConfiguration, got %s" % type(encryptionconfig)) + + +cdef shared_ptr[CDecryptionConfiguration] pyarrow_unwrap_decryptionconfig(object decryptionconfig) except *: + if isinstance(decryptionconfig, DecryptionConfiguration): + return ( decryptionconfig).unwrap() + raise TypeError("Expected DecryptionConfiguration, got %s" % type(decryptionconfig)) diff --git a/shared/package-files/02/026fecf02ff604ffa58a61ee76a94c60bee7705f99f42384e2b67a43b1f2c2c0/dropout_native.h b/shared/package-files/02/026fecf02ff604ffa58a61ee76a94c60bee7705f99f42384e2b67a43b1f2c2c0/dropout_native.h new file mode 100644 index 0000000000000000000000000000000000000000..fdc59661fafaa00a81f1ac6b692e56f5c89e0823 --- /dev/null +++ b/shared/package-files/02/026fecf02ff604ffa58a61ee76a94c60bee7705f99f42384e2b67a43b1f2c2c0/dropout_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 dropout(const at::Tensor & input, double p, bool train); +TORCH_API at::Tensor & dropout_(at::Tensor & self, double p, bool train); +} // namespace native +} // namespace at diff --git a/shared/package-files/02/0279dc2c84d2a83b5d9984f90d46a85af82101d3d08488f3964f74494c65eb88/source_range.h b/shared/package-files/02/0279dc2c84d2a83b5d9984f90d46a85af82101d3d08488f3964f74494c65eb88/source_range.h new file mode 100644 index 0000000000000000000000000000000000000000..72710a94ed21000580cd5a7282bf0051e5d99928 --- /dev/null +++ b/shared/package-files/02/0279dc2c84d2a83b5d9984f90d46a85af82101d3d08488f3964f74494c65eb88/source_range.h @@ -0,0 +1,457 @@ +#pragma once +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +class SourceRangeUnpickler; +struct SourceRange; + +// A stringlike class backed by a vector of string_view +// the string represented are logically the concatenation of the string_views +// This has advantage of not needing continues memory. +struct TORCH_API StringCordView { + StringCordView(); + StringCordView(const StringCordView&) = default; + StringCordView(StringCordView&&) noexcept = default; + StringCordView( + std::vector inputs, + std::vector> ownerships); + + StringCordView& operator=(const StringCordView&) = default; + StringCordView& operator=(StringCordView&&) noexcept = default; + + size_t size() const { + return accumulated_sizes_.back(); + } + + size_t find(const std::string& tok, size_t start) const; + size_t find_regex(const std::string& tok, size_t start) const; + StringCordView substr(size_t start, size_t size) const; + + char at(size_t index) const { + return *iter_for_pos(index); + } + char operator[](size_t index) const { + return at(index); + } + + std::string str() const { + std::stringstream ss; + for (auto s : pieces_) { + ss << std::string(s); + } + return ss.str(); + } + + bool operator==(const std::string& rhs) const; + + bool operator==(const StringCordView& rhs) const; + + c10::string_view piece(size_t index) const { + return pieces_[index]; + } + + struct Iterator { + Iterator( + const StringCordView* str, + size_t start_line, + size_t start_pos, + size_t size) + : line_(start_line), pos_(start_pos), str_(str), size_(size) {} + explicit Iterator(const StringCordView* str) + : Iterator(str, 0, 0, str->size()) {} + + Iterator() : Iterator(nullptr, 0, 0, 0) {} + + Iterator(const Iterator&) = default; + Iterator(Iterator&&) = default; + Iterator& operator=(const Iterator&) = default; + Iterator& operator=(Iterator&&) = default; + + Iterator operator++() { + if (size_ == 0) { + return *this; + } + if ((pos_ + 1) < str_->pieces_[line_].size()) { + pos_++; + } else { + line_++; + pos_ = 0; + } + return *this; + } + + Iterator operator++(int) { + Iterator prev(*this); + ++(*this); + return prev; + } + + Iterator next_iter() const { + Iterator next(*this); + ++next; + return next; + } + + Iterator& operator+=(size_t num) { + if (!has_next()) { + return *this; + } + size_t target_pos = pos_ + num; + if (target_pos >= str_->accumulated_sizes_[line_] && + (line_ + 1) < str_->accumulated_sizes_.size() && + target_pos < str_->accumulated_sizes_[line_ + 1]) { + pos_ = target_pos; + return *this; + } + + size_t target_abs_pos = pos() + num; + *this = str_->iter_for_pos(target_abs_pos); + return *this; + } + + bool operator==(const Iterator& rhs) const { + if (!has_next() && !rhs.has_next()) { + return true; + } + return (str_ == rhs.str_) && (line_ == rhs.line_) && (pos_ == rhs.pos_); + } + bool operator!=(const Iterator& rhs) { + return !((*this) == rhs); + } + bool has_next() const { + return size_ > 0 && (line_ < str_->pieces_.size()); + } + + char operator*() const { + TORCH_INTERNAL_ASSERT(line_ < str_->pieces_.size()); + TORCH_INTERNAL_ASSERT(pos_ < str_->pieces_[line_].size()); + return str_->pieces_[line_].at(pos_); + } + + // returns rest of the line of the current iterator + c10::string_view rest_line() const { + if (line_ >= str_->pieces_.size()) { + return ""; + } + + c10::string_view cur_line = str_->pieces_[line_]; + return cur_line.substr(pos_, std::string::npos); + } + + size_t pos() const { + if (size_ == 0) { + return 0; + } + return str_->accumulated_sizes_[line_] + pos_; + } + + private: + size_t line_; + size_t pos_; + const StringCordView* str_; + size_t size_; + friend struct StringCordView; + }; + + Iterator begin() const { + return Iterator(this, 0, 0, size()); + } + Iterator end() const { + return Iterator(this, pieces_.size(), 0, 0); + } + Iterator iter_for_pos(size_t pos) const; + + private: + std::vector pieces_; + std::vector accumulated_sizes_; + std::vector> owned_strings_; +}; + +// Source represents a code segment. It keeps track of: +// - text_view : the view into text of the code segment +// - filename (optional) : if present, represents the name of the file from +// which the code segment originated. +// - starting_line_no : represents the line in the original file where the +// code segment started. +struct TORCH_API Source { + // Whether or not Source should copy the string passed in the constructor. + enum CopiesString { COPIES_STRING, DONT_COPY }; + + explicit Source( + c10::string_view text_view, + c10::optional filename = c10::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr, + CopiesString copies_str = COPIES_STRING) + : filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + if (copies_str == COPIES_STRING) { + std::shared_ptr allocated_str = + std::make_shared(text_view.data(), text_view.size()); + text_view_ = StringCordView({*allocated_str}, {allocated_str}); + } else { + text_view_ = StringCordView({text_view}, {}); + } + + calc_line_start_offsets(); + } + + explicit Source( + StringCordView str, + c10::optional filename = c10::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr) + : text_view_(std::move(str)), + filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + calc_line_start_offsets(); + } + // Given a line number (within source_), return the byte offset of the + // beginning of that line. + size_t offset_for_line(size_t line) const { + return line_starting_offsets_.at(line); + } + + // Returns number of lines present. + size_t num_lines() const { + return line_starting_offsets_.size(); + } + + // Calculate the line (within the code segment) on which `offset` resides. + size_t lineno_for_offset(size_t offset) const { + auto iter = std::upper_bound( + line_starting_offsets_.begin(), line_starting_offsets_.end(), offset); + return iter - line_starting_offsets_.begin() - 1; + } + + // Calculate the line (within the original source file, if present) on which + // `lineno` resides. + size_t lineno_to_source_lineno(size_t lineno) const { + if (filename_) { + return lineno + starting_line_no_; + } else { + return lineno; + } + } + + StringCordView get_line(size_t lineno) const { + auto start = offset_for_line(lineno); + auto size = (lineno + 1) < num_lines() ? offset_for_line(lineno + 1) - start + : text_view_.size() - start; + return text_view_.substr(start, size); + } + + const StringCordView& text_str() const { + return text_view_; + } + + char char_at(size_t index) const { + return text_view_.at(index); + } + + size_t size() const { + return text_view_.size(); + } + + c10::optional& filename() { + return filename_; + } + + size_t starting_line_no() const { + return starting_line_no_; + } + + c10::optional findSourceRangeThatGenerated( + const SourceRange& range); + + ~Source() = default; + + private: + void calc_line_start_offsets() { + line_starting_offsets_.clear(); + line_starting_offsets_.push_back(0); + size_t pos = 0; + while ((pos = text_view_.find("\n", pos)) != std::string::npos) { + line_starting_offsets_.push_back(++pos); + } + } + + StringCordView text_view_; + + c10::optional filename_; + // If filename_ is not present, starting_line_no_ is don't care + size_t starting_line_no_; + // Starting offsets for lines into the source. e.g. line 0 starts at + // line_starting_offsets_[0], etc. + std::vector line_starting_offsets_; + + std::shared_ptr gen_ranges_; +}; + +// A SourceRange is a reference to subset of a Source, specified by `start` and +// `end` byte offsets into the source text. +struct TORCH_API SourceRange { + SourceRange(std::shared_ptr source_view, size_t start_, size_t end_) + : source_view_(std::move(source_view)), start_(start_), end_(end_) { + if (source_view_) { + start_iter_ = source_view_->text_str().iter_for_pos(start_); + } + } + + SourceRange() : source_view_(nullptr), start_(0), end_(0) {} + + SourceRange( + std::shared_ptr source_view_, + StringCordView::Iterator start_iter, + size_t end_) + : source_view_(std::move(source_view_)), + start_(start_iter.pos()), + end_(end_), + start_iter_(start_iter) {} + + const c10::string_view token_text() const { + size_t size = end() - start(); + return start_iter_.rest_line().substr(0, size); + } + + const StringCordView text() const { + return source_view_->text_str().substr(start(), end() - start()); + } + size_t size() const { + return end() - start(); + } + static const size_t CONTEXT = 3; + void highlight(std::ostream& out) const; + + // Customizable version of 'highlight' method. + void print_with_context( + std::ostream& out, + size_t context, + bool highlight, + const std::string& funcname) const; + + const std::shared_ptr& source() const { + return source_view_; + } + size_t start() const { + return start_; + } + size_t end() const { + return end_; + } + std::string str() const { + std::stringstream ss; + highlight(ss); + return ss.str(); + } + + c10::optional> file_line_col() const { + if (!source_view_ || !source()->filename()) { + return c10::nullopt; + } + + auto lineno = source_view_->lineno_for_offset(start_); + auto col_offset = (int)start_ - (int)source_view_->offset_for_line(lineno); + // TODO: c10::optional<>::value returns an rvalue ref so can't use it here?? + return std::make_tuple( + source_view_->filename().value_or(""), + source_view_->lineno_to_source_lineno(lineno), + (size_t)col_offset); + } + + bool operator==(const SourceRange& rhs) const { + return start() == rhs.start() && end() == rhs.end() && + source() == rhs.source(); + } + + bool operator!=(const SourceRange& rhs) const { + return !(*this == rhs); + } + + c10::optional findSourceRangeThatGenerated() const { + if (!source_view_) { + return c10::nullopt; + } + return source_view_->findSourceRangeThatGenerated(*this); + } + + protected: + std::shared_ptr source_view_; + + private: + size_t start_; + size_t end_; + StringCordView::Iterator start_iter_; +}; + +// OwnedSourceRange is just like a SourceRange except that it owns a `Source` +// instead of `Source`. Thus OwnedSourceRange owns a copy of source text. +struct OwnedSourceRange : public SourceRange { + explicit OwnedSourceRange(const SourceRange& source_range) + : SourceRange(source_range) { + const auto& source = source_range.source(); + if (source) { + source_view_ = std::make_shared( + source->text_str().str(), + source->filename(), + source->starting_line_no()); + } + } +}; + +struct TORCH_API SourceRangeHasher { + public: + size_t operator()(const torch::jit::SourceRange& key) const; +}; + +struct StackEntry { + std::string filename; + SourceRange range; +}; + +TORCH_API void format_stack_trace( + std::ostream& out, + const std::vector& entries); + +inline std::ostream& operator<<(std::ostream& out, const SourceRange& range) { + range.highlight(out); + return out; +} + +// A pair of (byte offset, SourceRange) describing a specific segment +// of the output stream +struct TaggedRange { + TaggedRange(size_t bytes, SourceRange range) + : bytes(bytes), range(std::move(range)) {} + size_t bytes; + SourceRange range; +}; +using SourceRangeRecords = std::vector; +using SourceRangeTagMap = + std::unordered_map; + +} // namespace torch::jit + +namespace std { +template <> +struct iterator_traits { + using value_type = char; + using difference_type = ptrdiff_t; + using pointer = char*; + using reference = char&; + using iterator_category = std::forward_iterator_tag; +}; +} // namespace std diff --git a/shared/package-files/02/027b274ebcbceb9ff1d42c3fe94ca368a2e34d90a018a5d5db6dd76cc8da73f8/int_repr_native.h b/shared/package-files/02/027b274ebcbceb9ff1d42c3fe94ca368a2e34d90a018a5d5db6dd76cc8da73f8/int_repr_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2835cad8658c03a36792f905646a876c5eedc0ba --- /dev/null +++ b/shared/package-files/02/027b274ebcbceb9ff1d42c3fe94ca368a2e34d90a018a5d5db6dd76cc8da73f8/int_repr_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 & int_repr_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor int_repr_quantized_cpu(const at::Tensor & self); +TORCH_API at::Tensor int_repr_quantized_cuda(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/02/027d610c5848edec9fda29dd9f46e92458c4139416170f85983faed3724c1535/catalog.py b/shared/package-files/02/027d610c5848edec9fda29dd9f46e92458c4139416170f85983faed3724c1535/catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..70fc7b18e19194dd5010ad02ec55d0d7e87738ab --- /dev/null +++ b/shared/package-files/02/027d610c5848edec9fda29dd9f46e92458c4139416170f85983faed3724c1535/catalog.py @@ -0,0 +1,79 @@ +from typing import NamedTuple, Optional, Union # noqa: D100 + +from .session import SparkSession + + +class Database(NamedTuple): # noqa: D101 + name: str + description: Optional[str] + locationUri: str + + +class Table(NamedTuple): # noqa: D101 + name: str + database: Optional[str] + description: Optional[str] + tableType: str + isTemporary: bool + + +class Column(NamedTuple): # noqa: D101 + name: str + description: Optional[str] + dataType: str + nullable: bool + isPartition: bool + isBucket: bool + + +class Function(NamedTuple): # noqa: D101 + name: str + description: Optional[str] + className: str + isTemporary: bool + + +class Catalog: # noqa: D101 + def __init__(self, session: SparkSession) -> None: # noqa: D107 + self._session = session + + def listDatabases(self) -> list[Database]: # noqa: D102 + res = self._session.conn.sql("select database_name from duckdb_databases()").fetchall() + + def transform_to_database(x: list[str]) -> Database: + return Database(name=x[0], description=None, locationUri="") + + databases = [transform_to_database(x) for x in res] + return databases + + def listTables(self) -> list[Table]: # noqa: D102 + res = self._session.conn.sql("select table_name, database_name, sql, temporary from duckdb_tables()").fetchall() + + def transform_to_table(x: list[str]) -> Table: + return Table(name=x[0], database=x[1], description=x[2], tableType="", isTemporary=x[3]) + + tables = [transform_to_table(x) for x in res] + return tables + + def listColumns(self, tableName: str, dbName: Optional[str] = None) -> list[Column]: # noqa: D102 + query = f""" + select column_name, data_type, is_nullable from duckdb_columns() where table_name = '{tableName}' + """ + if dbName: + query += f" and database_name = '{dbName}'" + res = self._session.conn.sql(query).fetchall() + + def transform_to_column(x: list[Union[str, bool]]) -> Column: + return Column(name=x[0], description=None, dataType=x[1], nullable=x[2], isPartition=False, isBucket=False) + + columns = [transform_to_column(x) for x in res] + return columns + + def listFunctions(self, dbName: Optional[str] = None) -> list[Function]: # noqa: D102 + raise NotImplementedError + + def setCurrentDatabase(self, dbName: str) -> None: # noqa: D102 + raise NotImplementedError + + +__all__ = ["Catalog", "Column", "Database", "Function", "Table"] diff --git a/shared/package-files/02/027d6642308f741f94d44fc79c23e4d1a1c275159823720ccb05b0a8e705450a/util.py b/shared/package-files/02/027d6642308f741f94d44fc79c23e4d1a1c275159823720ccb05b0a8e705450a/util.py new file mode 100644 index 0000000000000000000000000000000000000000..9e07a4e93e597e853fab59f355419fa5ac282fb2 --- /dev/null +++ b/shared/package-files/02/027d6642308f741f94d44fc79c23e4d1a1c275159823720ccb05b0a8e705450a/util.py @@ -0,0 +1,489 @@ +# +# Module providing various facilities to other parts of the package +# +# multiprocessing/util.py +# +# Copyright (c) 2006-2008, R Oudkerk +# Licensed to PSF under a Contributor Agreement. +# + +import os +import itertools +import sys +import weakref +import atexit +import threading # we want threading to install it's + # cleanup function before multiprocessing does +from subprocess import _args_from_interpreter_flags + +from . import process + +__all__ = [ + 'sub_debug', 'debug', 'info', 'sub_warning', 'get_logger', + 'log_to_stderr', 'get_temp_dir', 'register_after_fork', + 'is_exiting', 'Finalize', 'ForkAwareThreadLock', 'ForkAwareLocal', + 'close_all_fds_except', 'SUBDEBUG', 'SUBWARNING', + ] + +# +# Logging +# + +NOTSET = 0 +SUBDEBUG = 5 +DEBUG = 10 +INFO = 20 +SUBWARNING = 25 + +LOGGER_NAME = 'multiprocessing' +DEFAULT_LOGGING_FORMAT = '[%(levelname)s/%(processName)s] %(message)s' + +_logger = None +_log_to_stderr = False + +def sub_debug(msg, *args): + if _logger: + _logger.log(SUBDEBUG, msg, *args) + +def debug(msg, *args): + if _logger: + _logger.log(DEBUG, msg, *args) + +def info(msg, *args): + if _logger: + _logger.log(INFO, msg, *args) + +def sub_warning(msg, *args): + if _logger: + _logger.log(SUBWARNING, msg, *args) + +def get_logger(): + ''' + Returns logger used by multiprocessing + ''' + global _logger + import logging + + logging._acquireLock() + try: + if not _logger: + + _logger = logging.getLogger(LOGGER_NAME) + _logger.propagate = 0 + + # XXX multiprocessing should cleanup before logging + if hasattr(atexit, 'unregister'): + atexit.unregister(_exit_function) + atexit.register(_exit_function) + else: + atexit._exithandlers.remove((_exit_function, (), {})) + atexit._exithandlers.append((_exit_function, (), {})) + + finally: + logging._releaseLock() + + return _logger + +def log_to_stderr(level=None): + ''' + Turn on logging and add a handler which prints to stderr + ''' + global _log_to_stderr + import logging + + logger = get_logger() + formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT) + handler = logging.StreamHandler() + handler.setFormatter(formatter) + logger.addHandler(handler) + + if level: + logger.setLevel(level) + _log_to_stderr = True + return _logger + + +# Abstract socket support + +def _platform_supports_abstract_sockets(): + if sys.platform == "linux": + return True + if hasattr(sys, 'getandroidapilevel'): + return True + return False + + +def is_abstract_socket_namespace(address): + if not address: + return False + if isinstance(address, bytes): + return address[0] == 0 + elif isinstance(address, str): + return address[0] == "\0" + raise TypeError(f'address type of {address!r} unrecognized') + + +abstract_sockets_supported = _platform_supports_abstract_sockets() + +# +# Function returning a temp directory which will be removed on exit +# + +def _remove_temp_dir(rmtree, tempdir): + rmtree(tempdir) + + current_process = process.current_process() + # current_process() can be None if the finalizer is called + # late during Python finalization + if current_process is not None: + current_process._config['tempdir'] = None + +def get_temp_dir(): + # get name of a temp directory which will be automatically cleaned up + tempdir = process.current_process()._config.get('tempdir') + if tempdir is None: + import shutil, tempfile + tempdir = tempfile.mkdtemp(prefix='pymp-') + info('created temp directory %s', tempdir) + # keep a strong reference to shutil.rmtree(), since the finalizer + # can be called late during Python shutdown + Finalize(None, _remove_temp_dir, args=(shutil.rmtree, tempdir), + exitpriority=-100) + process.current_process()._config['tempdir'] = tempdir + return tempdir + +# +# Support for reinitialization of objects when bootstrapping a child process +# + +_afterfork_registry = weakref.WeakValueDictionary() +_afterfork_counter = itertools.count() + +def _run_after_forkers(): + items = list(_afterfork_registry.items()) + items.sort() + for (index, ident, func), obj in items: + try: + func(obj) + except Exception as e: + info('after forker raised exception %s', e) + +def register_after_fork(obj, func): + _afterfork_registry[(next(_afterfork_counter), id(obj), func)] = obj + +# +# Finalization using weakrefs +# + +_finalizer_registry = {} +_finalizer_counter = itertools.count() + + +class Finalize(object): + ''' + Class which supports object finalization using weakrefs + ''' + def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None): + if (exitpriority is not None) and not isinstance(exitpriority,int): + raise TypeError( + "Exitpriority ({0!r}) must be None or int, not {1!s}".format( + exitpriority, type(exitpriority))) + + if obj is not None: + self._weakref = weakref.ref(obj, self) + elif exitpriority is None: + raise ValueError("Without object, exitpriority cannot be None") + + self._callback = callback + self._args = args + self._kwargs = kwargs or {} + self._key = (exitpriority, next(_finalizer_counter)) + self._pid = os.getpid() + + _finalizer_registry[self._key] = self + + def __call__(self, wr=None, + # Need to bind these locally because the globals can have + # been cleared at shutdown + _finalizer_registry=_finalizer_registry, + sub_debug=sub_debug, getpid=os.getpid): + ''' + Run the callback unless it has already been called or cancelled + ''' + try: + del _finalizer_registry[self._key] + except KeyError: + sub_debug('finalizer no longer registered') + else: + if self._pid != getpid(): + sub_debug('finalizer ignored because different process') + res = None + else: + sub_debug('finalizer calling %s with args %s and kwargs %s', + self._callback, self._args, self._kwargs) + res = self._callback(*self._args, **self._kwargs) + self._weakref = self._callback = self._args = \ + self._kwargs = self._key = None + return res + + def cancel(self): + ''' + Cancel finalization of the object + ''' + try: + del _finalizer_registry[self._key] + except KeyError: + pass + else: + self._weakref = self._callback = self._args = \ + self._kwargs = self._key = None + + def still_active(self): + ''' + Return whether this finalizer is still waiting to invoke callback + ''' + return self._key in _finalizer_registry + + def __repr__(self): + try: + obj = self._weakref() + except (AttributeError, TypeError): + obj = None + + if obj is None: + return '<%s object, dead>' % self.__class__.__name__ + + x = '<%s object, callback=%s' % ( + self.__class__.__name__, + getattr(self._callback, '__name__', self._callback)) + if self._args: + x += ', args=' + str(self._args) + if self._kwargs: + x += ', kwargs=' + str(self._kwargs) + if self._key[0] is not None: + x += ', exitpriority=' + str(self._key[0]) + return x + '>' + + +def _run_finalizers(minpriority=None): + ''' + Run all finalizers whose exit priority is not None and at least minpriority + + Finalizers with highest priority are called first; finalizers with + the same priority will be called in reverse order of creation. + ''' + if _finalizer_registry is None: + # This function may be called after this module's globals are + # destroyed. See the _exit_function function in this module for more + # notes. + return + + if minpriority is None: + f = lambda p : p[0] is not None + else: + f = lambda p : p[0] is not None and p[0] >= minpriority + + # Careful: _finalizer_registry may be mutated while this function + # is running (either by a GC run or by another thread). + + # list(_finalizer_registry) should be atomic, while + # list(_finalizer_registry.items()) is not. + keys = [key for key in list(_finalizer_registry) if f(key)] + keys.sort(reverse=True) + + for key in keys: + finalizer = _finalizer_registry.get(key) + # key may have been removed from the registry + if finalizer is not None: + sub_debug('calling %s', finalizer) + try: + finalizer() + except Exception: + import traceback + traceback.print_exc() + + if minpriority is None: + _finalizer_registry.clear() + +# +# Clean up on exit +# + +def is_exiting(): + ''' + Returns true if the process is shutting down + ''' + return _exiting or _exiting is None + +_exiting = False + +def _exit_function(info=info, debug=debug, _run_finalizers=_run_finalizers, + active_children=process.active_children, + current_process=process.current_process): + # We hold on to references to functions in the arglist due to the + # situation described below, where this function is called after this + # module's globals are destroyed. + + global _exiting + + if not _exiting: + _exiting = True + + info('process shutting down') + debug('running all "atexit" finalizers with priority >= 0') + _run_finalizers(0) + + if current_process() is not None: + # We check if the current process is None here because if + # it's None, any call to ``active_children()`` will raise + # an AttributeError (active_children winds up trying to + # get attributes from util._current_process). One + # situation where this can happen is if someone has + # manipulated sys.modules, causing this module to be + # garbage collected. The destructor for the module type + # then replaces all values in the module dict with None. + # For instance, after setuptools runs a test it replaces + # sys.modules with a copy created earlier. See issues + # #9775 and #15881. Also related: #4106, #9205, and + # #9207. + + for p in active_children(): + if p.daemon: + info('calling terminate() for daemon %s', p.name) + p._popen.terminate() + + for p in active_children(): + info('calling join() for process %s', p.name) + p.join() + + debug('running the remaining "atexit" finalizers') + _run_finalizers() + +atexit.register(_exit_function) + +# +# Some fork aware types +# + +class ForkAwareThreadLock(object): + def __init__(self): + self._lock = threading.Lock() + self.acquire = self._lock.acquire + self.release = self._lock.release + register_after_fork(self, ForkAwareThreadLock._at_fork_reinit) + + def _at_fork_reinit(self): + self._lock._at_fork_reinit() + + def __enter__(self): + return self._lock.__enter__() + + def __exit__(self, *args): + return self._lock.__exit__(*args) + + +class ForkAwareLocal(threading.local): + def __init__(self): + register_after_fork(self, lambda obj : obj.__dict__.clear()) + def __reduce__(self): + return type(self), () + +# +# Close fds except those specified +# + +try: + MAXFD = os.sysconf("SC_OPEN_MAX") +except Exception: + MAXFD = 256 + +def close_all_fds_except(fds): + fds = list(fds) + [-1, MAXFD] + fds.sort() + assert fds[-1] == MAXFD, 'fd too large' + for i in range(len(fds) - 1): + os.closerange(fds[i]+1, fds[i+1]) +# +# Close sys.stdin and replace stdin with os.devnull +# + +def _close_stdin(): + if sys.stdin is None: + return + + try: + sys.stdin.close() + except (OSError, ValueError): + pass + + try: + fd = os.open(os.devnull, os.O_RDONLY) + try: + sys.stdin = open(fd, encoding="utf-8", closefd=False) + except: + os.close(fd) + raise + except (OSError, ValueError): + pass + +# +# Flush standard streams, if any +# + +def _flush_std_streams(): + try: + sys.stdout.flush() + except (AttributeError, ValueError): + pass + try: + sys.stderr.flush() + except (AttributeError, ValueError): + pass + +# +# Start a program with only specified fds kept open +# + +def spawnv_passfds(path, args, passfds): + import _posixsubprocess + passfds = tuple(sorted(map(int, passfds))) + errpipe_read, errpipe_write = os.pipe() + try: + return _posixsubprocess.fork_exec( + args, [os.fsencode(path)], True, passfds, None, None, + -1, -1, -1, -1, -1, -1, errpipe_read, errpipe_write, + False, False, None, None, None, -1, None) + finally: + os.close(errpipe_read) + os.close(errpipe_write) + + +def close_fds(*fds): + """Close each file descriptor given as an argument""" + for fd in fds: + os.close(fd) + + +def _cleanup_tests(): + """Cleanup multiprocessing resources when multiprocessing tests + completed.""" + + from test import support + + # cleanup multiprocessing + process._cleanup() + + # Stop the ForkServer process if it's running + from multiprocessing import forkserver + forkserver._forkserver._stop() + + # Stop the ResourceTracker process if it's running + from multiprocessing import resource_tracker + resource_tracker._resource_tracker._stop() + + # bpo-37421: Explicitly call _run_finalizers() to remove immediately + # temporary directories created by multiprocessing.util.get_temp_dir(). + _run_finalizers() + support.gc_collect() + + support.reap_children() diff --git a/shared/package-files/02/027dc4b3528f32d138ec62be1ca57f5a7b86ee47e84f96e1f9b9ff49f390e4f7/_thread.pyi b/shared/package-files/02/027dc4b3528f32d138ec62be1ca57f5a7b86ee47e84f96e1f9b9ff49f390e4f7/_thread.pyi new file mode 100644 index 0000000000000000000000000000000000000000..25952a61494f5bfd1d8590b0d8c0bc6463b2a557 --- /dev/null +++ b/shared/package-files/02/027dc4b3528f32d138ec62be1ca57f5a7b86ee47e84f96e1f9b9ff49f390e4f7/_thread.pyi @@ -0,0 +1 @@ +from _thread import * diff --git a/shared/package-files/02/027f64e96db1d090a68b6d5bd95f94251484df9428c6c7dd4f7dd8d56f14716e/capsule.h b/shared/package-files/02/027f64e96db1d090a68b6d5bd95f94251484df9428c6c7dd4f7dd8d56f14716e/capsule.h new file mode 100644 index 0000000000000000000000000000000000000000..dbc9b557774f631e0fb52d2cca95d0b3a3e2cb1a --- /dev/null +++ b/shared/package-files/02/027f64e96db1d090a68b6d5bd95f94251484df9428c6c7dd4f7dd8d56f14716e/capsule.h @@ -0,0 +1,24 @@ +/* partially cribbed from numpy/core/include/numpy/npy_3kcompat.h +*/ + +#include + +#if PY_VERSION_HEX >= 0x03000000 + +void* Capsule_AsVoidPtr(PyObject *obj) +{ + void *ret = PyCapsule_GetPointer(obj, NULL); + if (ret == NULL) { + PyErr_Clear(); + } + return ret; +} + +#else + +void* Capsule_AsVoidPtr(PyObject *ptr) +{ + return PyCObject_AsVoidPtr(ptr); +} + +#endif diff --git a/shared/package-files/02/02819273c6ba857fe2bef8f83203ffb2d4cbbb66a7b7800b7649cf318425699d/meson.build b/shared/package-files/02/02819273c6ba857fe2bef8f83203ffb2d4cbbb66a7b7800b7649cf318425699d/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..88f23170ac0bbe382d8470bd22a42a92d9473008 --- /dev/null +++ b/shared/package-files/02/02819273c6ba857fe2bef8f83203ffb2d4cbbb66a7b7800b7649cf318425699d/meson.build @@ -0,0 +1,27 @@ +project('random-build-examples', 'c', 'cpp', 'cython') + +fs = import('fs') + +py3 = import('python').find_installation(pure: false) + +cy = meson.get_compiler('cython') + +if not cy.version().version_compare('>=3.0.8') + error('tests requires Cython >= 3.0.8') +endif + +py3.extension_module( + 'extending', + 'extending.pyx', + install: false, + c_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this +) + +extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx') +py3.extension_module( + 'extending_cpp', + extending_cpp, + install: false, + override_options : ['cython_language=cpp'], + cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this +) diff --git a/shared/package-files/02/0281e1bfdb220ce542a33730ee6fd0d4463c72b65b2e117d5d8ef7c508212c75/ones_like_compositeexplicitautograd_dispatch.h b/shared/package-files/02/0281e1bfdb220ce542a33730ee6fd0d4463c72b65b2e117d5d8ef7c508212c75/ones_like_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1f898c485d4a3125a7f98bbe0b14eb29824b165f --- /dev/null +++ b/shared/package-files/02/0281e1bfdb220ce542a33730ee6fd0d4463c72b65b2e117d5d8ef7c508212c75/ones_like_compositeexplicitautograd_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 compositeexplicitautograd { + +TORCH_API at::Tensor ones_like(const at::Tensor & self, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor ones_like(const at::Tensor & self, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format); +TORCH_API at::Tensor & ones_like_out(at::Tensor & out, const at::Tensor & self, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor & ones_like_outf(const at::Tensor & self, c10::optional memory_format, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/02/0283c2ab0373e32610426d73e9608331dc5c5ab054471d48e623ec1c942f74ea/findstatic.pyi b/shared/package-files/02/0283c2ab0373e32610426d73e9608331dc5c5ab054471d48e623ec1c942f74ea/findstatic.pyi new file mode 100644 index 0000000000000000000000000000000000000000..be61bcbcfce71a9d136924278f848f5d6580b962 --- /dev/null +++ b/shared/package-files/02/0283c2ab0373e32610426d73e9608331dc5c5ab054471d48e623ec1c942f74ea/findstatic.pyi @@ -0,0 +1,3 @@ +from django.core.management.base import LabelCommand + +class Command(LabelCommand): ... diff --git a/shared/package-files/02/02844c58dbc2253887e4bfa590890274f96b3cb51d26fbdf5e922f7f51a6c693/x448.pyi b/shared/package-files/02/02844c58dbc2253887e4bfa590890274f96b3cb51d26fbdf5e922f7f51a6c693/x448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e51cfebe15f67688e17284341d8c6e710b321164 --- /dev/null +++ b/shared/package-files/02/02844c58dbc2253887e4bfa590890274f96b3cb51d26fbdf5e922f7f51a6c693/x448.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 x448 + +class X448PrivateKey: ... +class X448PublicKey: ... + +def generate_key() -> x448.X448PrivateKey: ... +def from_private_bytes(data: bytes) -> x448.X448PrivateKey: ... +def from_public_bytes(data: bytes) -> x448.X448PublicKey: ... diff --git a/shared/package-files/02/0287a1d0f5f6ca22c34f0931304c99fc2357da624766fc9fb85265f35ee90357/testsimplecell.mat b/shared/package-files/02/0287a1d0f5f6ca22c34f0931304c99fc2357da624766fc9fb85265f35ee90357/testsimplecell.mat new file mode 100644 index 0000000000000000000000000000000000000000..2a98f48917f8f275e541eeac5ef1fe741c40bb0b Binary files /dev/null and b/shared/package-files/02/0287a1d0f5f6ca22c34f0931304c99fc2357da624766fc9fb85265f35ee90357/testsimplecell.mat differ diff --git a/shared/package-files/02/0287a8001a2ab5a39b4ff522dca7071bdf3b42701a8fcf5b586a401c694ca1e5/replication_pad3d_backward.h b/shared/package-files/02/0287a8001a2ab5a39b4ff522dca7071bdf3b42701a8fcf5b586a401c694ca1e5/replication_pad3d_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..ebabc03f2eca5038ea2c6cb39b335bae53e2f959 --- /dev/null +++ b/shared/package-files/02/0287a8001a2ab5a39b4ff522dca7071bdf3b42701a8fcf5b586a401c694ca1e5/replication_pad3d_backward.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::replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); + } +} + +// aten::replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); + } +} + +// aten::replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad3d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, padding, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, padding, grad_input); + } +} + +// aten::replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad3d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, padding, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad3d_backward_grad_input::call(grad_output, self, padding, grad_input); + } +} + +// aten::replication_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor +inline at::Tensor replication_pad3d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad3d_backward::call(grad_output, self, c10::fromIntArrayRefSlow(padding)); +} +namespace symint { + template ::value>> + at::Tensor replication_pad3d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad3d_backward::call(grad_output, self, c10::fromIntArrayRefSlow(padding)); + } +} + +// aten::replication_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor +inline at::Tensor replication_pad3d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad3d_backward::call(grad_output, self, padding); +} +namespace symint { + template ::value>> + at::Tensor replication_pad3d_backward(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad3d_backward::call(grad_output, self, padding); + } +} + +} diff --git a/shared/package-files/02/028a5c4d90c251730f704288644d5ba2d7379848662dbda9d7f7a396ad422ea6/getlimits.py b/shared/package-files/02/028a5c4d90c251730f704288644d5ba2d7379848662dbda9d7f7a396ad422ea6/getlimits.py new file mode 100644 index 0000000000000000000000000000000000000000..13414c2a64d688aa96c9cece79bc187210e19589 --- /dev/null +++ b/shared/package-files/02/028a5c4d90c251730f704288644d5ba2d7379848662dbda9d7f7a396ad422ea6/getlimits.py @@ -0,0 +1,735 @@ +"""Machine limits for Float32 and Float64 and (long double) if available... + +""" +__all__ = ['finfo', 'iinfo'] + +import warnings + +from .._utils import set_module +from ._machar import MachAr +from . import numeric +from . import numerictypes as ntypes +from .numeric import array, inf, NaN +from .umath import log10, exp2, nextafter, isnan + + +def _fr0(a): + """fix rank-0 --> rank-1""" + if a.ndim == 0: + a = a.copy() + a.shape = (1,) + return a + + +def _fr1(a): + """fix rank > 0 --> rank-0""" + if a.size == 1: + a = a.copy() + a.shape = () + return a + + +class MachArLike: + """ Object to simulate MachAr instance """ + def __init__(self, ftype, *, eps, epsneg, huge, tiny, + ibeta, smallest_subnormal=None, **kwargs): + self.params = _MACHAR_PARAMS[ftype] + self.ftype = ftype + self.title = self.params['title'] + # Parameter types same as for discovered MachAr object. + if not smallest_subnormal: + self._smallest_subnormal = nextafter( + self.ftype(0), self.ftype(1), dtype=self.ftype) + else: + self._smallest_subnormal = smallest_subnormal + self.epsilon = self.eps = self._float_to_float(eps) + self.epsneg = self._float_to_float(epsneg) + self.xmax = self.huge = self._float_to_float(huge) + self.xmin = self._float_to_float(tiny) + self.smallest_normal = self.tiny = self._float_to_float(tiny) + self.ibeta = self.params['itype'](ibeta) + self.__dict__.update(kwargs) + self.precision = int(-log10(self.eps)) + self.resolution = self._float_to_float( + self._float_conv(10) ** (-self.precision)) + self._str_eps = self._float_to_str(self.eps) + self._str_epsneg = self._float_to_str(self.epsneg) + self._str_xmin = self._float_to_str(self.xmin) + self._str_xmax = self._float_to_str(self.xmax) + self._str_resolution = self._float_to_str(self.resolution) + self._str_smallest_normal = self._float_to_str(self.xmin) + + @property + def smallest_subnormal(self): + """Return the value for the smallest subnormal. + + Returns + ------- + smallest_subnormal : float + value for the smallest subnormal. + + Warns + ----- + UserWarning + If the calculated value for the smallest subnormal is zero. + """ + # Check that the calculated value is not zero, in case it raises a + # warning. + value = self._smallest_subnormal + if self.ftype(0) == value: + warnings.warn( + 'The value of the smallest subnormal for {} type ' + 'is zero.'.format(self.ftype), UserWarning, stacklevel=2) + + return self._float_to_float(value) + + @property + def _str_smallest_subnormal(self): + """Return the string representation of the smallest subnormal.""" + return self._float_to_str(self.smallest_subnormal) + + def _float_to_float(self, value): + """Converts float to float. + + Parameters + ---------- + value : float + value to be converted. + """ + return _fr1(self._float_conv(value)) + + def _float_conv(self, value): + """Converts float to conv. + + Parameters + ---------- + value : float + value to be converted. + """ + return array([value], self.ftype) + + def _float_to_str(self, value): + """Converts float to str. + + Parameters + ---------- + value : float + value to be converted. + """ + return self.params['fmt'] % array(_fr0(value)[0], self.ftype) + + +_convert_to_float = { + ntypes.csingle: ntypes.single, + ntypes.complex_: ntypes.float_, + ntypes.clongfloat: ntypes.longfloat + } + +# Parameters for creating MachAr / MachAr-like objects +_title_fmt = 'numpy {} precision floating point number' +_MACHAR_PARAMS = { + ntypes.double: dict( + itype = ntypes.int64, + fmt = '%24.16e', + title = _title_fmt.format('double')), + ntypes.single: dict( + itype = ntypes.int32, + fmt = '%15.7e', + title = _title_fmt.format('single')), + ntypes.longdouble: dict( + itype = ntypes.longlong, + fmt = '%s', + title = _title_fmt.format('long double')), + ntypes.half: dict( + itype = ntypes.int16, + fmt = '%12.5e', + title = _title_fmt.format('half'))} + +# Key to identify the floating point type. Key is result of +# ftype('-0.1').newbyteorder('<').tobytes() +# +# 20230201 - use (ftype(-1.0) / ftype(10.0)).newbyteorder('<').tobytes() +# instead because stold may have deficiencies on some platforms. +# See: +# https://perl5.git.perl.org/perl.git/blob/3118d7d684b56cbeb702af874f4326683c45f045:/Configure + +_KNOWN_TYPES = {} +def _register_type(machar, bytepat): + _KNOWN_TYPES[bytepat] = machar +_float_ma = {} + + +def _register_known_types(): + # Known parameters for float16 + # See docstring of MachAr class for description of parameters. + f16 = ntypes.float16 + float16_ma = MachArLike(f16, + machep=-10, + negep=-11, + minexp=-14, + maxexp=16, + it=10, + iexp=5, + ibeta=2, + irnd=5, + ngrd=0, + eps=exp2(f16(-10)), + epsneg=exp2(f16(-11)), + huge=f16(65504), + tiny=f16(2 ** -14)) + _register_type(float16_ma, b'f\xae') + _float_ma[16] = float16_ma + + # Known parameters for float32 + f32 = ntypes.float32 + float32_ma = MachArLike(f32, + machep=-23, + negep=-24, + minexp=-126, + maxexp=128, + it=23, + iexp=8, + ibeta=2, + irnd=5, + ngrd=0, + eps=exp2(f32(-23)), + epsneg=exp2(f32(-24)), + huge=f32((1 - 2 ** -24) * 2**128), + tiny=exp2(f32(-126))) + _register_type(float32_ma, b'\xcd\xcc\xcc\xbd') + _float_ma[32] = float32_ma + + # Known parameters for float64 + f64 = ntypes.float64 + epsneg_f64 = 2.0 ** -53.0 + tiny_f64 = 2.0 ** -1022.0 + float64_ma = MachArLike(f64, + machep=-52, + negep=-53, + minexp=-1022, + maxexp=1024, + it=52, + iexp=11, + ibeta=2, + irnd=5, + ngrd=0, + eps=2.0 ** -52.0, + epsneg=epsneg_f64, + huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4), + tiny=tiny_f64) + _register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf') + _float_ma[64] = float64_ma + + # Known parameters for IEEE 754 128-bit binary float + ld = ntypes.longdouble + epsneg_f128 = exp2(ld(-113)) + tiny_f128 = exp2(ld(-16382)) + # Ignore runtime error when this is not f128 + with numeric.errstate(all='ignore'): + huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4) + float128_ma = MachArLike(ld, + machep=-112, + negep=-113, + minexp=-16382, + maxexp=16384, + it=112, + iexp=15, + ibeta=2, + irnd=5, + ngrd=0, + eps=exp2(ld(-112)), + epsneg=epsneg_f128, + huge=huge_f128, + tiny=tiny_f128) + # IEEE 754 128-bit binary float + _register_type(float128_ma, + b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf') + _float_ma[128] = float128_ma + + # Known parameters for float80 (Intel 80-bit extended precision) + epsneg_f80 = exp2(ld(-64)) + tiny_f80 = exp2(ld(-16382)) + # Ignore runtime error when this is not f80 + with numeric.errstate(all='ignore'): + huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4) + float80_ma = MachArLike(ld, + machep=-63, + negep=-64, + minexp=-16382, + maxexp=16384, + it=63, + iexp=15, + ibeta=2, + irnd=5, + ngrd=0, + eps=exp2(ld(-63)), + epsneg=epsneg_f80, + huge=huge_f80, + tiny=tiny_f80) + # float80, first 10 bytes containing actual storage + _register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf') + _float_ma[80] = float80_ma + + # Guessed / known parameters for double double; see: + # https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format#Double-double_arithmetic + # These numbers have the same exponent range as float64, but extended number of + # digits in the significand. + huge_dd = nextafter(ld(inf), ld(0), dtype=ld) + # As the smallest_normal in double double is so hard to calculate we set + # it to NaN. + smallest_normal_dd = NaN + # Leave the same value for the smallest subnormal as double + smallest_subnormal_dd = ld(nextafter(0., 1.)) + float_dd_ma = MachArLike(ld, + machep=-105, + negep=-106, + minexp=-1022, + maxexp=1024, + it=105, + iexp=11, + ibeta=2, + irnd=5, + ngrd=0, + eps=exp2(ld(-105)), + epsneg=exp2(ld(-106)), + huge=huge_dd, + tiny=smallest_normal_dd, + smallest_subnormal=smallest_subnormal_dd) + # double double; low, high order (e.g. PPC 64) + _register_type(float_dd_ma, + b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf') + # double double; high, low order (e.g. PPC 64 le) + _register_type(float_dd_ma, + b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<') + _float_ma['dd'] = float_dd_ma + + +def _get_machar(ftype): + """ Get MachAr instance or MachAr-like instance + + Get parameters for floating point type, by first trying signatures of + various known floating point types, then, if none match, attempting to + identify parameters by analysis. + + Parameters + ---------- + ftype : class + Numpy floating point type class (e.g. ``np.float64``) + + Returns + ------- + ma_like : instance of :class:`MachAr` or :class:`MachArLike` + Object giving floating point parameters for `ftype`. + + Warns + ----- + UserWarning + If the binary signature of the float type is not in the dictionary of + known float types. + """ + params = _MACHAR_PARAMS.get(ftype) + if params is None: + raise ValueError(repr(ftype)) + # Detect known / suspected types + # ftype(-1.0) / ftype(10.0) is better than ftype('-0.1') because stold + # may be deficient + key = (ftype(-1.0) / ftype(10.)).newbyteorder('<').tobytes() + ma_like = None + if ftype == ntypes.longdouble: + # Could be 80 bit == 10 byte extended precision, where last bytes can + # be random garbage. + # Comparing first 10 bytes to pattern first to avoid branching on the + # random garbage. + ma_like = _KNOWN_TYPES.get(key[:10]) + if ma_like is None: + # see if the full key is known. + ma_like = _KNOWN_TYPES.get(key) + if ma_like is None and len(key) == 16: + # machine limits could be f80 masquerading as np.float128, + # find all keys with length 16 and make new dict, but make the keys + # only 10 bytes long, the last bytes can be random garbage + _kt = {k[:10]: v for k, v in _KNOWN_TYPES.items() if len(k) == 16} + ma_like = _kt.get(key[:10]) + if ma_like is not None: + return ma_like + # Fall back to parameter discovery + warnings.warn( + f'Signature {key} for {ftype} does not match any known type: ' + 'falling back to type probe function.\n' + 'This warnings indicates broken support for the dtype!', + UserWarning, stacklevel=2) + return _discovered_machar(ftype) + + +def _discovered_machar(ftype): + """ Create MachAr instance with found information on float types + + TODO: MachAr should be retired completely ideally. We currently only + ever use it system with broken longdouble (valgrind, WSL). + """ + params = _MACHAR_PARAMS[ftype] + return MachAr(lambda v: array([v], ftype), + lambda v:_fr0(v.astype(params['itype']))[0], + lambda v:array(_fr0(v)[0], ftype), + lambda v: params['fmt'] % array(_fr0(v)[0], ftype), + params['title']) + + +@set_module('numpy') +class finfo: + """ + finfo(dtype) + + Machine limits for floating point types. + + Attributes + ---------- + bits : int + The number of bits occupied by the type. + dtype : dtype + Returns the dtype for which `finfo` returns information. For complex + input, the returned dtype is the associated ``float*`` dtype for its + real and complex components. + eps : float + The difference between 1.0 and the next smallest representable float + larger than 1.0. For example, for 64-bit binary floats in the IEEE-754 + standard, ``eps = 2**-52``, approximately 2.22e-16. + epsneg : float + The difference between 1.0 and the next smallest representable float + less than 1.0. For example, for 64-bit binary floats in the IEEE-754 + standard, ``epsneg = 2**-53``, approximately 1.11e-16. + iexp : int + The number of bits in the exponent portion of the floating point + representation. + machep : int + The exponent that yields `eps`. + max : floating point number of the appropriate type + The largest representable number. + maxexp : int + The smallest positive power of the base (2) that causes overflow. + min : floating point number of the appropriate type + The smallest representable number, typically ``-max``. + minexp : int + The most negative power of the base (2) consistent with there + being no leading 0's in the mantissa. + negep : int + The exponent that yields `epsneg`. + nexp : int + The number of bits in the exponent including its sign and bias. + nmant : int + The number of bits in the mantissa. + precision : int + The approximate number of decimal digits to which this kind of + float is precise. + resolution : floating point number of the appropriate type + The approximate decimal resolution of this type, i.e., + ``10**-precision``. + tiny : float + An alias for `smallest_normal`, kept for backwards compatibility. + smallest_normal : float + The smallest positive floating point number with 1 as leading bit in + the mantissa following IEEE-754 (see Notes). + smallest_subnormal : float + The smallest positive floating point number with 0 as leading bit in + the mantissa following IEEE-754. + + Parameters + ---------- + dtype : float, dtype, or instance + Kind of floating point or complex floating point + data-type about which to get information. + + See Also + -------- + iinfo : The equivalent for integer data types. + spacing : The distance between a value and the nearest adjacent number + nextafter : The next floating point value after x1 towards x2 + + Notes + ----- + For developers of NumPy: do not instantiate this at the module level. + The initial calculation of these parameters is expensive and negatively + impacts import times. These objects are cached, so calling ``finfo()`` + repeatedly inside your functions is not a problem. + + Note that ``smallest_normal`` is not actually the smallest positive + representable value in a NumPy floating point type. As in the IEEE-754 + standard [1]_, NumPy floating point types make use of subnormal numbers to + fill the gap between 0 and ``smallest_normal``. However, subnormal numbers + may have significantly reduced precision [2]_. + + This function can also be used for complex data types as well. If used, + the output will be the same as the corresponding real float type + (e.g. numpy.finfo(numpy.csingle) is the same as numpy.finfo(numpy.single)). + However, the output is true for the real and imaginary components. + + References + ---------- + .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008, + pp.1-70, 2008, http://www.doi.org/10.1109/IEEESTD.2008.4610935 + .. [2] Wikipedia, "Denormal Numbers", + https://en.wikipedia.org/wiki/Denormal_number + + Examples + -------- + >>> np.finfo(np.float64).dtype + dtype('float64') + >>> np.finfo(np.complex64).dtype + dtype('float32') + + """ + + _finfo_cache = {} + + def __new__(cls, dtype): + try: + obj = cls._finfo_cache.get(dtype) # most common path + if obj is not None: + return obj + except TypeError: + pass + + if dtype is None: + # Deprecated in NumPy 1.25, 2023-01-16 + warnings.warn( + "finfo() dtype cannot be None. This behavior will " + "raise an error in the future. (Deprecated in NumPy 1.25)", + DeprecationWarning, + stacklevel=2 + ) + + try: + dtype = numeric.dtype(dtype) + except TypeError: + # In case a float instance was given + dtype = numeric.dtype(type(dtype)) + + obj = cls._finfo_cache.get(dtype) + if obj is not None: + return obj + dtypes = [dtype] + newdtype = numeric.obj2sctype(dtype) + if newdtype is not dtype: + dtypes.append(newdtype) + dtype = newdtype + if not issubclass(dtype, numeric.inexact): + raise ValueError("data type %r not inexact" % (dtype)) + obj = cls._finfo_cache.get(dtype) + if obj is not None: + return obj + if not issubclass(dtype, numeric.floating): + newdtype = _convert_to_float[dtype] + if newdtype is not dtype: + # dtype changed, for example from complex128 to float64 + dtypes.append(newdtype) + dtype = newdtype + + obj = cls._finfo_cache.get(dtype, None) + if obj is not None: + # the original dtype was not in the cache, but the new + # dtype is in the cache. we add the original dtypes to + # the cache and return the result + for dt in dtypes: + cls._finfo_cache[dt] = obj + return obj + obj = object.__new__(cls)._init(dtype) + for dt in dtypes: + cls._finfo_cache[dt] = obj + return obj + + def _init(self, dtype): + self.dtype = numeric.dtype(dtype) + machar = _get_machar(dtype) + + for word in ['precision', 'iexp', + 'maxexp', 'minexp', 'negep', + 'machep']: + setattr(self, word, getattr(machar, word)) + for word in ['resolution', 'epsneg', 'smallest_subnormal']: + setattr(self, word, getattr(machar, word).flat[0]) + self.bits = self.dtype.itemsize * 8 + self.max = machar.huge.flat[0] + self.min = -self.max + self.eps = machar.eps.flat[0] + self.nexp = machar.iexp + self.nmant = machar.it + self._machar = machar + self._str_tiny = machar._str_xmin.strip() + self._str_max = machar._str_xmax.strip() + self._str_epsneg = machar._str_epsneg.strip() + self._str_eps = machar._str_eps.strip() + self._str_resolution = machar._str_resolution.strip() + self._str_smallest_normal = machar._str_smallest_normal.strip() + self._str_smallest_subnormal = machar._str_smallest_subnormal.strip() + return self + + def __str__(self): + fmt = ( + 'Machine parameters for %(dtype)s\n' + '---------------------------------------------------------------\n' + 'precision = %(precision)3s resolution = %(_str_resolution)s\n' + 'machep = %(machep)6s eps = %(_str_eps)s\n' + 'negep = %(negep)6s epsneg = %(_str_epsneg)s\n' + 'minexp = %(minexp)6s tiny = %(_str_tiny)s\n' + 'maxexp = %(maxexp)6s max = %(_str_max)s\n' + 'nexp = %(nexp)6s min = -max\n' + 'smallest_normal = %(_str_smallest_normal)s ' + 'smallest_subnormal = %(_str_smallest_subnormal)s\n' + '---------------------------------------------------------------\n' + ) + return fmt % self.__dict__ + + def __repr__(self): + c = self.__class__.__name__ + d = self.__dict__.copy() + d['klass'] = c + return (("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s," + " max=%(_str_max)s, dtype=%(dtype)s)") % d) + + @property + def smallest_normal(self): + """Return the value for the smallest normal. + + Returns + ------- + smallest_normal : float + Value for the smallest normal. + + Warns + ----- + UserWarning + If the calculated value for the smallest normal is requested for + double-double. + """ + # This check is necessary because the value for smallest_normal is + # platform dependent for longdouble types. + if isnan(self._machar.smallest_normal.flat[0]): + warnings.warn( + 'The value of smallest normal is undefined for double double', + UserWarning, stacklevel=2) + return self._machar.smallest_normal.flat[0] + + @property + def tiny(self): + """Return the value for tiny, alias of smallest_normal. + + Returns + ------- + tiny : float + Value for the smallest normal, alias of smallest_normal. + + Warns + ----- + UserWarning + If the calculated value for the smallest normal is requested for + double-double. + """ + return self.smallest_normal + + +@set_module('numpy') +class iinfo: + """ + iinfo(type) + + Machine limits for integer types. + + Attributes + ---------- + bits : int + The number of bits occupied by the type. + dtype : dtype + Returns the dtype for which `iinfo` returns information. + min : int + The smallest integer expressible by the type. + max : int + The largest integer expressible by the type. + + Parameters + ---------- + int_type : integer type, dtype, or instance + The kind of integer data type to get information about. + + See Also + -------- + finfo : The equivalent for floating point data types. + + Examples + -------- + With types: + + >>> ii16 = np.iinfo(np.int16) + >>> ii16.min + -32768 + >>> ii16.max + 32767 + >>> ii32 = np.iinfo(np.int32) + >>> ii32.min + -2147483648 + >>> ii32.max + 2147483647 + + With instances: + + >>> ii32 = np.iinfo(np.int32(10)) + >>> ii32.min + -2147483648 + >>> ii32.max + 2147483647 + + """ + + _min_vals = {} + _max_vals = {} + + def __init__(self, int_type): + try: + self.dtype = numeric.dtype(int_type) + except TypeError: + self.dtype = numeric.dtype(type(int_type)) + self.kind = self.dtype.kind + self.bits = self.dtype.itemsize * 8 + self.key = "%s%d" % (self.kind, self.bits) + if self.kind not in 'iu': + raise ValueError("Invalid integer data type %r." % (self.kind,)) + + @property + def min(self): + """Minimum value of given dtype.""" + if self.kind == 'u': + return 0 + else: + try: + val = iinfo._min_vals[self.key] + except KeyError: + val = int(-(1 << (self.bits-1))) + iinfo._min_vals[self.key] = val + return val + + @property + def max(self): + """Maximum value of given dtype.""" + try: + val = iinfo._max_vals[self.key] + except KeyError: + if self.kind == 'u': + val = int((1 << self.bits) - 1) + else: + val = int((1 << (self.bits-1)) - 1) + iinfo._max_vals[self.key] = val + return val + + def __str__(self): + """String representation.""" + fmt = ( + 'Machine parameters for %(dtype)s\n' + '---------------------------------------------------------------\n' + 'min = %(min)s\n' + 'max = %(max)s\n' + '---------------------------------------------------------------\n' + ) + return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max} + + def __repr__(self): + return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__, + self.min, self.max, self.dtype) diff --git a/shared/package-files/02/028c3305b672e31f048ab0010dd2522c964c909ff9de221a83cc5f291e83ee42/top_level.txt b/shared/package-files/02/028c3305b672e31f048ab0010dd2522c964c909ff9de221a83cc5f291e83ee42/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..79236f25cda563eb57cd7b5838256d9f3fdf18ab --- /dev/null +++ b/shared/package-files/02/028c3305b672e31f048ab0010dd2522c964c909ff9de221a83cc5f291e83ee42/top_level.txt @@ -0,0 +1 @@ +chardet diff --git a/shared/package-files/02/028da5b2041e509ea3653416e71fcc4f87bff6b8d531d76506164aaad4a9eb58/quantile_regression.py b/shared/package-files/02/028da5b2041e509ea3653416e71fcc4f87bff6b8d531d76506164aaad4a9eb58/quantile_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..270e094ae7b1c47960320e954deb774013eef77b --- /dev/null +++ b/shared/package-files/02/028da5b2041e509ea3653416e71fcc4f87bff6b8d531d76506164aaad4a9eb58/quantile_regression.py @@ -0,0 +1,485 @@ +""" +Quantile regression model + +Model parameters are estimated using iterated reweighted least squares. The +asymptotic covariance matrix estimated using kernel density estimation. + +Author: Vincent Arel-Bundock +License: BSD-3 +Created: 2013-03-19 + +The original IRLS function was written for Matlab by Shapour Mohammadi, +University of Tehran, 2008 (shmohammadi@gmail.com), with some lines based on +code written by James P. Lesage in Applied Econometrics Using MATLAB(1999).PP. +73-4. Translated to python with permission from original author by Christian +Prinoth (christian at prinoth dot name). +""" + +import warnings + +import numpy as np +from numpy.linalg import pinv +from scipy import stats +from scipy.stats import norm + +from statsmodels.regression.linear_model import ( + RegressionModel, + RegressionResults, + RegressionResultsWrapper, +) +from statsmodels.tools._decorators import cache_readonly, cache_writable +from statsmodels.tools.sm_exceptions import ConvergenceWarning, IterationLimitWarning +from statsmodels.tools.validation import string_like + + +class QuantReg(RegressionModel): + """ + Quantile Regression + + Estimate a quantile regression model using iterative reweighted least + squares. + + Parameters + ---------- + endog : array_like + Endogenous/response variable. + exog : array_like + Exogenous/explanatory variable(s). + + Notes + ----- + The Least Absolute Deviation (LAD) estimator is a special case where + quantile is set to 0.5 (q argument of the fit method). + + The asymptotic covariance matrix is estimated following the procedure in + Greene (2008, p.407-408), using either the logistic or gaussian kernels + (kernel argument of the fit method). + + References + ---------- + General: + + * Birkes, D. and Y. Dodge (1993). Alternative Methods of Regression, John Wiley and Sons. + * Green, W. H. (2008). Econometric Analysis. Sixth Edition. International Student Edition. + * Koenker, R. (2005). Quantile Regression. New York: Cambridge University Press. + * LeSage, J. P. (1999). Applied Econometrics Using MATLAB, + + Kernels (used by the fit method): + + * Green (2008) Table 14.2 + + Bandwidth selection (used by the fit method): + + * Bofinger, E. (1975). Estimation of a density function using order statistics. Australian Journal of Statistics 17: 1-17. + * Chamberlain, G. (1994). Quantile regression, censoring, and the structure of wages. In Advances in Econometrics, Vol. 1: Sixth World Congress, ed. C. A. Sims, 171-209. Cambridge: Cambridge University Press. + * Hall, P., and S. Sheather. (1988). On the distribution of the Studentized quantile. Journal of the Royal Statistical Society, Series B 50: 381-391. + + Keywords: Least Absolute Deviation(LAD) Regression, Quantile Regression, + Regression, Robust Estimation. + + """ + + def __init__(self, endog, exog, **kwargs): + self._check_kwargs(kwargs) + super().__init__(endog, exog, **kwargs) + + def whiten(self, data): + """QuantReg model whitener does nothing: returns data""" + return data + + def fit( + self, + q=0.5, + vcov="robust", + kernel="epa", + bandwidth="hsheather", + max_iter=1000, + p_tol=1e-6, + **kwargs, + ): + """ + Solve by Iterative Weighted Least Squares + + Parameters + ---------- + q : float, optional + Quantile must be strictly between 0 and 1. + vcov : {'robust', 'iid'}, optional + Method used to calculate the variance-covariance matrix + of the parameters. Default is ``robust``: + + - robust : heteroskedasticity robust standard errors (as suggested + in Greene 6th edition) + - iid : iid errors (as in Stata 12) + + kernel : {'biw', 'cos', 'epa', 'gau', 'par'}, optional + Kernel to use in the kernel density estimation for the + asymptotic covariance matrix: + + - biw: Biweight + - epa: Epanechnikov + - cos: Cosine + - gau: Gaussian + - par: Parzen + + bandwidth : {'hsheather', 'bofinger', 'chamberlain'}, optional + Bandwidth selection method in kernel density + estimation for asymptotic covariance estimate (full + references in QuantReg docstring): + + - hsheather: Hall-Sheather (1988) + - bofinger: Bofinger (1975) + - chamberlain: Chamberlain (1994) + max_iter : int, optional + Maximum number of iterations. + p_tol : float, optional + Convergence tolerance for the iterative parameter estimates. + **kwargs + Additional keyword arguments, accepted for API compatibility. + + Returns + ------- + RegressionResultsWrapper + Results instance for the fitted quantile regression, with + additional ``q``, ``iterations``, ``sparsity``, ``bandwidth``, + and ``history`` attributes. + """ + if q <= 0 or q >= 1: + raise ValueError("q must be strictly between 0 and 1") + + kernel = string_like( + kernel, "kernel", options=("biw", "cos", "epa", "gau", "par"), + lower=False, + ) + kernel = kernels[kernel] + + bandwidth = string_like( + bandwidth, "bandwidth", + options=("hsheather", "bofinger", "chamberlain"), lower=False, + ) + if bandwidth == "hsheather": + bandwidth = hall_sheather + elif bandwidth == "bofinger": + bandwidth = bofinger + else: # bandwidth == "chamberlain" + bandwidth = chamberlain + + endog = self.endog + exog = self.exog + nobs = self.nobs + exog_rank = np.linalg.matrix_rank(self.exog) + self.rank = exog_rank + self.df_model = float(self.rank - self.k_constant) + self.df_resid = self.nobs - self.rank + n_iter = 0 + xstar = exog + + beta = np.ones(exog.shape[1]) + # TODO: better start, initial beta is used only for convergence check + + # Note the following does not work yet, + # the iteration loop always starts with OLS as initial beta + # if start_params is not None: + # if len(start_params) != rank: + # raise ValueError('start_params has wrong length') + # beta = start_params + # else: + # # start with OLS + # beta = np.dot(np.linalg.pinv(exog), endog) + + diff = 10 + cycle = False + + history = dict(params=[], mse=[]) + while n_iter < max_iter and diff > p_tol and not cycle: + n_iter += 1 + beta0 = beta + xtx = np.dot(xstar.T, exog) + xty = np.dot(xstar.T, endog) + beta = np.dot(pinv(xtx), xty) + resid = endog - np.dot(exog, beta) + + mask = np.abs(resid) < 0.000001 + resid[mask] = ((resid[mask] >= 0) * 2 - 1) * 0.000001 + resid = np.where(resid < 0, q * resid, (1 - q) * resid) + resid = np.abs(resid) + xstar = exog / resid[:, np.newaxis] + diff = np.max(np.abs(beta - beta0)) + history["params"].append(beta) + history["mse"].append(np.mean(resid * resid)) + + if (n_iter >= 300) and (n_iter % 100 == 0): + # check for convergence circle, should not happen + for ii in range(2, 10): + if np.all(beta == history["params"][-ii]): + cycle = True + warnings.warn( + "Convergence cycle detected", + ConvergenceWarning, + stacklevel=2, + ) + break + + if n_iter == max_iter: + warnings.warn( + "Maximum number of iterations (" + str(max_iter) + ") reached.", + IterationLimitWarning, + stacklevel=2, + ) + + e = endog - np.dot(exog, beta) + # Greene (2008, p.407) writes that Stata 6 uses this bandwidth: + # h = 0.9 * np.std(e) / (nobs**0.2) + # Instead, we calculate bandwidth as in Stata 12 + iqre = stats.scoreatpercentile(e, 75) - stats.scoreatpercentile(e, 25) + h = bandwidth(nobs, q) + h = min(np.std(endog), iqre / 1.34) * (norm.ppf(q + h) - norm.ppf(q - h)) + + fhat0 = 1.0 / (nobs * h) * np.sum(kernel(e / h)) + + vcov = string_like(vcov, "vcov", options=("robust", "iid"), lower=False) + if vcov == "robust": + d = np.where(e > 0, (q / fhat0) ** 2, ((1 - q) / fhat0) ** 2) + xtxi = pinv(np.dot(exog.T, exog)) + xtdx = np.dot(exog.T * d[np.newaxis, :], exog) + vcov = xtxi @ xtdx @ xtxi + else: # vcov == "iid" + vcov = (1.0 / fhat0) ** 2 * q * (1 - q) * pinv(np.dot(exog.T, exog)) + + lfit = QuantRegResults(self, beta, normalized_cov_params=vcov) + + lfit.q = q + lfit.iterations = n_iter + lfit.sparsity = 1.0 / fhat0 + lfit.bandwidth = h + lfit.history = history + + return RegressionResultsWrapper(lfit) + + +def _parzen(u): + z = np.where( + np.abs(u) <= 0.5, + 4.0 / 3 - 8.0 * u**2 + 8.0 * np.abs(u) ** 3, + 8.0 * (1 - np.abs(u)) ** 3 / 3.0, + ) + z[np.abs(u) > 1] = 0 + return z + + +kernels = {} +kernels["biw"] = lambda u: 15.0 / 16 * (1 - u**2) ** 2 * np.where(np.abs(u) <= 1, 1, 0) +kernels["cos"] = lambda u: np.where(np.abs(u) <= 0.5, 1 + np.cos(2 * np.pi * u), 0) +kernels["epa"] = lambda u: 3.0 / 4 * (1 - u**2) * np.where(np.abs(u) <= 1, 1, 0) +kernels["gau"] = norm.pdf +kernels["par"] = _parzen +# kernels['bet'] = lambda u: np.where(np.abs(u) <= 1, .75 * (1 - u) * (1 + u), 0) +# kernels['log'] = lambda u: logistic.pdf(u) * (1 - logistic.pdf(u)) +# kernels['tri'] = lambda u: np.where(np.abs(u) <= 1, 1 - np.abs(u), 0) +# kernels['trw'] = lambda u: 35. / 32 * (1 - u**2)**3 * np.where(np.abs(u) <= 1, 1, 0) +# kernels['uni'] = lambda u: 1. / 2 * np.where(np.abs(u) <= 1, 1, 0) + + +def hall_sheather(n, q, alpha=0.05): + z = norm.ppf(q) + num = 1.5 * norm.pdf(z) ** 2.0 + den = 2.0 * z**2.0 + 1.0 + h = ( + n ** (-1.0 / 3) + * norm.ppf(1.0 - alpha / 2.0) ** (2.0 / 3) + * (num / den) ** (1.0 / 3) + ) + return h + + +def bofinger(n, q): + num = 9.0 / 2 * norm.pdf(2 * norm.ppf(q)) ** 4 + den = (2 * norm.ppf(q) ** 2 + 1) ** 2 + h = n ** (-1.0 / 5) * (num / den) ** (1.0 / 5) + return h + + +def chamberlain(n, q, alpha=0.05): + return norm.ppf(1 - alpha / 2) * np.sqrt(q * (1 - q) / n) + + +class QuantRegResults(RegressionResults): + """Results instance for the QuantReg model""" + + @cache_readonly + def prsquared(self): + q = self.q + endog = self.model.endog + e = self.resid + e = np.where(e < 0, (1 - q) * e, q * e) + e = np.abs(e) + ered = endog - stats.scoreatpercentile(endog, q * 100) + ered = np.where(ered < 0, (1 - q) * ered, q * ered) + ered = np.abs(ered) + return 1 - np.sum(e) / np.sum(ered) + + @cache_writable() + def scale(self): + return 1.0 + + @cache_readonly + def bic(self): + return np.nan + + @cache_readonly + def aic(self): + return np.nan + + @cache_readonly + def llf(self): + return np.nan + + @cache_readonly + def rsquared(self): + return np.nan + + @cache_readonly + def rsquared_adj(self): + return np.nan + + @cache_readonly + def mse(self): + return np.nan + + @cache_readonly + def mse_model(self): + return np.nan + + @cache_readonly + def mse_total(self): + return np.nan + + @cache_readonly + def centered_tss(self): + return np.nan + + @cache_readonly + def uncentered_tss(self): + return np.nan + + @cache_readonly + def HC0_se(self): + raise NotImplementedError + + @cache_readonly + def HC1_se(self): + raise NotImplementedError + + @cache_readonly + def HC2_se(self): + raise NotImplementedError + + @cache_readonly + def HC3_se(self): + raise NotImplementedError + + 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[str], optional + Names for the exogenous variables. Default is `var_##` where + `##` is the 0-based index of the regressor. 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 + """ + # Cache the data-dependent scalars computed below as a plain dict + # (not cache_readonly) so that summary() keeps working after + # remove_data() has cleared resid/model.exog and the like. + cache = self.__dict__.setdefault("_summary_cache", {}) + + def cached(key, compute): + if key not in cache: + cache[key] = compute() + return cache[key] + + eigvals = cached("eigvals", lambda: self.eigenvals) + condno = cached("condno", lambda: self.condition_number) + prsquared = cached("prsquared", lambda: self.prsquared) + + top_left = [ + ("Dep. Variable:", None), + ("Model:", None), + ("Method:", ["Least Squares"]), + ("Date:", None), + ("Time:", None), + ] + + top_right = [ + ("Pseudo R-squared:", [f"{prsquared:#8.4g}"]), + ("Bandwidth:", [f"{self.bandwidth:#8.4g}"]), + ("Sparsity:", [f"{self.sparsity:#8.4g}"]), + ("No. Observations:", None), + ("Df Residuals:", None), + ("Df Model:", None), + ] + + if title is None: + title = self.model.__class__.__name__ + " " + "Regression 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 + ) + + # add warnings/notes, added to text format only + etext = [] + if eigvals[-1] < 1e-10: + wstr = "The smallest eigenvalue is %6.3g. This might indicate " + wstr += "that there are\n" + wstr += "strong multicollinearity problems or that the design " + wstr += "matrix is singular." + wstr = wstr % eigvals[-1] + etext.append(wstr) + elif condno > 1000: # TODO: what is recommended + wstr = "The condition number is large, %6.3g. This might " + wstr += "indicate that there are\n" + wstr += "strong multicollinearity or other numerical " + wstr += "problems." + wstr = wstr % condno + etext.append(wstr) + + if etext: + smry.add_extra_txt(etext) + + return smry diff --git a/shared/package-files/02/028f08005071c5998eb6ef4414009fb391bcb2fc73f8e18584f6f1d0a9b4059d/_gb.py b/shared/package-files/02/028f08005071c5998eb6ef4414009fb391bcb2fc73f8e18584f6f1d0a9b4059d/_gb.py new file mode 100644 index 0000000000000000000000000000000000000000..55c8e79e062dfd41be23162d9bdb90afc71b4381 --- /dev/null +++ b/shared/package-files/02/028f08005071c5998eb6ef4414009fb391bcb2fc73f8e18584f6f1d0a9b4059d/_gb.py @@ -0,0 +1,2196 @@ +"""Gradient Boosted Regression Trees. + +This module contains methods for fitting gradient boosted regression trees for +both classification and regression. + +The module structure is the following: + +- The ``BaseGradientBoosting`` base class implements a common ``fit`` method + for all the estimators in the module. Regression and classification + only differ in the concrete ``LossFunction`` used. + +- ``GradientBoostingClassifier`` implements gradient boosting for + classification problems. + +- ``GradientBoostingRegressor`` implements gradient boosting for + regression problems. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import math +import warnings +from abc import ABCMeta, abstractmethod +from numbers import Integral, Real +from time import time + +import numpy as np +from scipy.sparse import csc_matrix, csr_matrix, issparse + +from .._loss.loss import ( + _LOSSES, + AbsoluteError, + ExponentialLoss, + HalfBinomialLoss, + HalfMultinomialLoss, + HalfSquaredError, + HuberLoss, + PinballLoss, +) +from ..base import ClassifierMixin, RegressorMixin, _fit_context, is_classifier +from ..dummy import DummyClassifier, DummyRegressor +from ..exceptions import NotFittedError +from ..model_selection import train_test_split +from ..preprocessing import LabelEncoder +from ..tree import DecisionTreeRegressor +from ..tree._tree import DOUBLE, DTYPE, TREE_LEAF +from ..utils import check_array, check_random_state, column_or_1d +from ..utils._param_validation import HasMethods, Interval, StrOptions +from ..utils.multiclass import check_classification_targets +from ..utils.stats import _weighted_percentile +from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data +from ._base import BaseEnsemble +from ._gradient_boosting import _random_sample_mask, predict_stage, predict_stages + +_LOSSES = _LOSSES.copy() +_LOSSES.update( + { + "quantile": PinballLoss, + "huber": HuberLoss, + } +) + + +def _safe_divide(numerator, denominator): + """Prevents overflow and division by zero.""" + # This is used for classifiers where the denominator might become zero exactly. + # For instance for log loss, HalfBinomialLoss, if proba=0 or proba=1 exactly, then + # denominator = hessian = 0, and we should set the node value in the line search to + # zero as there is no improvement of the loss possible. + # For numerical safety, we do this already for extremely tiny values. + if abs(denominator) < 1e-150: + return 0.0 + else: + # Cast to Python float to trigger Python errors, e.g. ZeroDivisionError, + # without relying on `np.errstate` that is not supported by Pyodide. + result = float(numerator) / float(denominator) + # Cast to Python float to trigger a ZeroDivisionError without relying + # on `np.errstate` that is not supported by Pyodide. + result = float(numerator) / float(denominator) + if math.isinf(result): + warnings.warn("overflow encountered in _safe_divide", RuntimeWarning) + return result + + +def _init_raw_predictions(X, estimator, loss, use_predict_proba): + """Return the initial raw predictions. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The data array. + estimator : object + The estimator to use to compute the predictions. + loss : BaseLoss + An instance of a loss function class. + use_predict_proba : bool + Whether estimator.predict_proba is used instead of estimator.predict. + + Returns + ------- + raw_predictions : ndarray of shape (n_samples, K) + The initial raw predictions. K is equal to 1 for binary + classification and regression, and equal to the number of classes + for multiclass classification. ``raw_predictions`` is casted + into float64. + """ + # TODO: Use loss.fit_intercept_only where appropriate instead of + # DummyRegressor which is the default given by the `init` parameter, + # see also _init_state. + if use_predict_proba: + # Our parameter validation, set via _fit_context and _parameter_constraints + # already guarantees that estimator has a predict_proba method. + predictions = estimator.predict_proba(X) + if not loss.is_multiclass: + predictions = predictions[:, 1] # probability of positive class + eps = np.finfo(np.float32).eps # FIXME: This is quite large! + predictions = np.clip(predictions, eps, 1 - eps, dtype=np.float64) + else: + predictions = estimator.predict(X).astype(np.float64) + + if predictions.ndim == 1: + return loss.link.link(predictions).reshape(-1, 1) + else: + return loss.link.link(predictions) + + +def _update_terminal_regions( + loss, + tree, + X, + y, + neg_gradient, + raw_prediction, + sample_weight, + sample_mask, + learning_rate=0.1, + k=0, +): + """Update the leaf values to be predicted by the tree and raw_prediction. + + The current raw predictions of the model (of this stage) are updated. + + Additionally, the terminal regions (=leaves) of the given tree are updated as well. + This corresponds to the line search step in "Greedy Function Approximation" by + Friedman, Algorithm 1 step 5. + + Update equals: + argmin_{x} loss(y_true, raw_prediction_old + x * tree.value) + + For non-trivial cases like the Binomial loss, the update has no closed formula and + is an approximation, again, see the Friedman paper. + + Also note that the update formula for the SquaredError is the identity. Therefore, + in this case, the leaf values don't need an update and only the raw_predictions are + updated (with the learning rate included). + + Parameters + ---------- + loss : BaseLoss + tree : tree.Tree + The tree object. + X : ndarray of shape (n_samples, n_features) + The data array. + y : ndarray of shape (n_samples,) + The target labels. + neg_gradient : ndarray of shape (n_samples,) + The negative gradient. + raw_prediction : ndarray of shape (n_samples, n_trees_per_iteration) + The raw predictions (i.e. values from the tree leaves) of the + tree ensemble at iteration ``i - 1``. + sample_weight : ndarray of shape (n_samples,) + The weight of each sample. + sample_mask : ndarray of shape (n_samples,) + The sample mask to be used. + learning_rate : float, default=0.1 + Learning rate shrinks the contribution of each tree by + ``learning_rate``. + k : int, default=0 + The index of the estimator being updated. + """ + # compute leaf for each sample in ``X``. + terminal_regions = tree.apply(X) + + if not isinstance(loss, HalfSquaredError): + # mask all which are not in sample mask. + masked_terminal_regions = terminal_regions.copy() + masked_terminal_regions[~sample_mask] = -1 + + if isinstance(loss, HalfBinomialLoss): + + def compute_update(y_, indices, neg_gradient, raw_prediction, k): + # Make a single Newton-Raphson step, see "Additive Logistic Regression: + # A Statistical View of Boosting" FHT00 and note that we use a slightly + # different version (factor 2) of "F" with proba=expit(raw_prediction). + # Our node estimate is given by: + # sum(w * (y - prob)) / sum(w * prob * (1 - prob)) + # we take advantage that: y - prob = neg_gradient + neg_g = neg_gradient.take(indices, axis=0) + prob = y_ - neg_g + # numerator = negative gradient = y - prob + numerator = np.average(neg_g, weights=sw) + # denominator = hessian = prob * (1 - prob) + denominator = np.average(prob * (1 - prob), weights=sw) + return _safe_divide(numerator, denominator) + + elif isinstance(loss, HalfMultinomialLoss): + + def compute_update(y_, indices, neg_gradient, raw_prediction, k): + # we take advantage that: y - prob = neg_gradient + neg_g = neg_gradient.take(indices, axis=0) + prob = y_ - neg_g + K = loss.n_classes + # numerator = negative gradient * (k - 1) / k + # Note: The factor (k - 1)/k appears in the original papers "Greedy + # Function Approximation" by Friedman and "Additive Logistic + # Regression" by Friedman, Hastie, Tibshirani. This factor is, however, + # wrong or at least arbitrary as it directly multiplies the + # learning_rate. We keep it for backward compatibility. + numerator = np.average(neg_g, weights=sw) + numerator *= (K - 1) / K + # denominator = (diagonal) hessian = prob * (1 - prob) + denominator = np.average(prob * (1 - prob), weights=sw) + return _safe_divide(numerator, denominator) + + elif isinstance(loss, ExponentialLoss): + + def compute_update(y_, indices, neg_gradient, raw_prediction, k): + neg_g = neg_gradient.take(indices, axis=0) + # numerator = negative gradient = y * exp(-raw) - (1-y) * exp(raw) + numerator = np.average(neg_g, weights=sw) + # denominator = hessian = y * exp(-raw) + (1-y) * exp(raw) + # if y=0: hessian = exp(raw) = -neg_g + # y=1: hessian = exp(-raw) = neg_g + hessian = neg_g.copy() + hessian[y_ == 0] *= -1 + denominator = np.average(hessian, weights=sw) + return _safe_divide(numerator, denominator) + + else: + + def compute_update(y_, indices, neg_gradient, raw_prediction, k): + return loss.fit_intercept_only( + y_true=y_ - raw_prediction[indices, k], + sample_weight=sw, + ) + + # update each leaf (= perform line search) + for leaf in np.nonzero(tree.children_left == TREE_LEAF)[0]: + indices = np.nonzero(masked_terminal_regions == leaf)[ + 0 + ] # of terminal regions + y_ = y.take(indices, axis=0) + sw = None if sample_weight is None else sample_weight[indices] + update = compute_update(y_, indices, neg_gradient, raw_prediction, k) + + # TODO: Multiply here by learning rate instead of everywhere else. + tree.value[leaf, 0, 0] = update + + # update predictions (both in-bag and out-of-bag) + raw_prediction[:, k] += learning_rate * tree.value[:, 0, 0].take( + terminal_regions, axis=0 + ) + + +def set_huber_delta(loss, y_true, raw_prediction, sample_weight=None): + """Calculate and set self.closs.delta based on self.quantile.""" + abserr = np.abs(y_true - raw_prediction.squeeze()) + # sample_weight is always a ndarray, never None. + delta = _weighted_percentile(abserr, sample_weight, 100 * loss.quantile) + loss.closs.delta = float(delta) + + +class VerboseReporter: + """Reports verbose output to stdout. + + Parameters + ---------- + verbose : int + Verbosity level. If ``verbose==1`` output is printed once in a while + (when iteration mod verbose_mod is zero).; if larger than 1 then output + is printed for each update. + """ + + def __init__(self, verbose): + self.verbose = verbose + + def init(self, est, begin_at_stage=0): + """Initialize reporter + + Parameters + ---------- + est : Estimator + The estimator + + begin_at_stage : int, default=0 + stage at which to begin reporting + """ + # header fields and line format str + header_fields = ["Iter", "Train Loss"] + verbose_fmt = ["{iter:>10d}", "{train_score:>16.4f}"] + # do oob? + if est.subsample < 1: + header_fields.append("OOB Improve") + verbose_fmt.append("{oob_impr:>16.4f}") + header_fields.append("Remaining Time") + verbose_fmt.append("{remaining_time:>16s}") + + # print the header line + print(("%10s " + "%16s " * (len(header_fields) - 1)) % tuple(header_fields)) + + self.verbose_fmt = " ".join(verbose_fmt) + # plot verbose info each time i % verbose_mod == 0 + self.verbose_mod = 1 + self.start_time = time() + self.begin_at_stage = begin_at_stage + + def update(self, j, est): + """Update reporter with new iteration. + + Parameters + ---------- + j : int + The new iteration. + est : Estimator + The estimator. + """ + do_oob = est.subsample < 1 + # we need to take into account if we fit additional estimators. + i = j - self.begin_at_stage # iteration relative to the start iter + if (i + 1) % self.verbose_mod == 0: + oob_impr = est.oob_improvement_[j] if do_oob else 0 + remaining_time = ( + (est.n_estimators - (j + 1)) * (time() - self.start_time) / float(i + 1) + ) + if remaining_time > 60: + remaining_time = "{0:.2f}m".format(remaining_time / 60.0) + else: + remaining_time = "{0:.2f}s".format(remaining_time) + print( + self.verbose_fmt.format( + iter=j + 1, + train_score=est.train_score_[j], + oob_impr=oob_impr, + remaining_time=remaining_time, + ) + ) + if self.verbose == 1 and ((i + 1) // (self.verbose_mod * 10) > 0): + # adjust verbose frequency (powers of 10) + self.verbose_mod *= 10 + + +class BaseGradientBoosting(BaseEnsemble, metaclass=ABCMeta): + """Abstract base class for Gradient Boosting.""" + + _parameter_constraints: dict = { + **DecisionTreeRegressor._parameter_constraints, + "learning_rate": [Interval(Real, 0.0, None, closed="left")], + "n_estimators": [Interval(Integral, 1, None, closed="left")], + "criterion": [StrOptions({"friedman_mse", "squared_error"})], + "subsample": [Interval(Real, 0.0, 1.0, closed="right")], + "verbose": ["verbose"], + "warm_start": ["boolean"], + "validation_fraction": [Interval(Real, 0.0, 1.0, closed="neither")], + "n_iter_no_change": [Interval(Integral, 1, None, closed="left"), None], + "tol": [Interval(Real, 0.0, None, closed="left")], + } + _parameter_constraints.pop("splitter") + _parameter_constraints.pop("monotonic_cst") + + @abstractmethod + def __init__( + self, + *, + loss, + learning_rate, + n_estimators, + criterion, + min_samples_split, + min_samples_leaf, + min_weight_fraction_leaf, + max_depth, + min_impurity_decrease, + init, + subsample, + max_features, + ccp_alpha, + random_state, + alpha=0.9, + verbose=0, + max_leaf_nodes=None, + warm_start=False, + validation_fraction=0.1, + n_iter_no_change=None, + tol=1e-4, + ): + self.n_estimators = n_estimators + self.learning_rate = learning_rate + self.loss = loss + self.criterion = criterion + self.min_samples_split = min_samples_split + self.min_samples_leaf = min_samples_leaf + self.min_weight_fraction_leaf = min_weight_fraction_leaf + self.subsample = subsample + self.max_features = max_features + self.max_depth = max_depth + self.min_impurity_decrease = min_impurity_decrease + self.ccp_alpha = ccp_alpha + self.init = init + self.random_state = random_state + self.alpha = alpha + self.verbose = verbose + self.max_leaf_nodes = max_leaf_nodes + self.warm_start = warm_start + self.validation_fraction = validation_fraction + self.n_iter_no_change = n_iter_no_change + self.tol = tol + + @abstractmethod + def _encode_y(self, y=None, sample_weight=None): + """Called by fit to validate and encode y.""" + + @abstractmethod + def _get_loss(self, sample_weight): + """Get loss object from sklearn._loss.loss.""" + + def _fit_stage( + self, + i, + X, + y, + raw_predictions, + sample_weight, + sample_mask, + random_state, + X_csc=None, + X_csr=None, + ): + """Fit another stage of ``n_trees_per_iteration_`` trees.""" + original_y = y + + if isinstance(self._loss, HuberLoss): + set_huber_delta( + loss=self._loss, + y_true=y, + raw_prediction=raw_predictions, + sample_weight=sample_weight, + ) + # TODO: Without oob, i.e. with self.subsample = 1.0, we could call + # self._loss.loss_gradient and use it to set train_score_. + # But note that train_score_[i] is the score AFTER fitting the i-th tree. + # Note: We need the negative gradient! + neg_gradient = -self._loss.gradient( + y_true=y, + raw_prediction=raw_predictions, + sample_weight=None, # We pass sample_weights to the tree directly. + ) + # 2-d views of shape (n_samples, n_trees_per_iteration_) or (n_samples, 1) + # on neg_gradient to simplify the loop over n_trees_per_iteration_. + if neg_gradient.ndim == 1: + neg_g_view = neg_gradient.reshape((-1, 1)) + else: + neg_g_view = neg_gradient + + for k in range(self.n_trees_per_iteration_): + if self._loss.is_multiclass: + y = np.array(original_y == k, dtype=np.float64) + + # induce regression tree on the negative gradient + tree = DecisionTreeRegressor( + criterion=self.criterion, + splitter="best", + max_depth=self.max_depth, + min_samples_split=self.min_samples_split, + min_samples_leaf=self.min_samples_leaf, + min_weight_fraction_leaf=self.min_weight_fraction_leaf, + min_impurity_decrease=self.min_impurity_decrease, + max_features=self.max_features, + max_leaf_nodes=self.max_leaf_nodes, + random_state=random_state, + ccp_alpha=self.ccp_alpha, + ) + + if self.subsample < 1.0: + # no inplace multiplication! + sample_weight = sample_weight * sample_mask.astype(np.float64) + + X = X_csc if X_csc is not None else X + tree.fit( + X, neg_g_view[:, k], sample_weight=sample_weight, check_input=False + ) + + # update tree leaves + X_for_tree_update = X_csr if X_csr is not None else X + _update_terminal_regions( + self._loss, + tree.tree_, + X_for_tree_update, + y, + neg_g_view[:, k], + raw_predictions, + sample_weight, + sample_mask, + learning_rate=self.learning_rate, + k=k, + ) + + # add tree to ensemble + self.estimators_[i, k] = tree + + return raw_predictions + + def _set_max_features(self): + """Set self.max_features_.""" + if isinstance(self.max_features, str): + if self.max_features == "auto": + if is_classifier(self): + max_features = max(1, int(np.sqrt(self.n_features_in_))) + else: + max_features = self.n_features_in_ + elif self.max_features == "sqrt": + max_features = max(1, int(np.sqrt(self.n_features_in_))) + else: # self.max_features == "log2" + max_features = max(1, int(np.log2(self.n_features_in_))) + elif self.max_features is None: + max_features = self.n_features_in_ + elif isinstance(self.max_features, Integral): + max_features = self.max_features + else: # float + max_features = max(1, int(self.max_features * self.n_features_in_)) + + self.max_features_ = max_features + + def _init_state(self): + """Initialize model state and allocate model state data structures.""" + + self.init_ = self.init + if self.init_ is None: + if is_classifier(self): + self.init_ = DummyClassifier(strategy="prior") + elif isinstance(self._loss, (AbsoluteError, HuberLoss)): + self.init_ = DummyRegressor(strategy="quantile", quantile=0.5) + elif isinstance(self._loss, PinballLoss): + self.init_ = DummyRegressor(strategy="quantile", quantile=self.alpha) + else: + self.init_ = DummyRegressor(strategy="mean") + + self.estimators_ = np.empty( + (self.n_estimators, self.n_trees_per_iteration_), dtype=object + ) + self.train_score_ = np.zeros((self.n_estimators,), dtype=np.float64) + # do oob? + if self.subsample < 1.0: + self.oob_improvement_ = np.zeros((self.n_estimators), dtype=np.float64) + self.oob_scores_ = np.zeros((self.n_estimators), dtype=np.float64) + self.oob_score_ = np.nan + + def _clear_state(self): + """Clear the state of the gradient boosting model.""" + if hasattr(self, "estimators_"): + self.estimators_ = np.empty((0, 0), dtype=object) + if hasattr(self, "train_score_"): + del self.train_score_ + if hasattr(self, "oob_improvement_"): + del self.oob_improvement_ + if hasattr(self, "oob_scores_"): + del self.oob_scores_ + if hasattr(self, "oob_score_"): + del self.oob_score_ + if hasattr(self, "init_"): + del self.init_ + if hasattr(self, "_rng"): + del self._rng + + def _resize_state(self): + """Add additional ``n_estimators`` entries to all attributes.""" + # self.n_estimators is the number of additional est to fit + total_n_estimators = self.n_estimators + if total_n_estimators < self.estimators_.shape[0]: + raise ValueError( + "resize with smaller n_estimators %d < %d" + % (total_n_estimators, self.estimators_[0]) + ) + + self.estimators_ = np.resize( + self.estimators_, (total_n_estimators, self.n_trees_per_iteration_) + ) + self.train_score_ = np.resize(self.train_score_, total_n_estimators) + if self.subsample < 1 or hasattr(self, "oob_improvement_"): + # if do oob resize arrays or create new if not available + if hasattr(self, "oob_improvement_"): + self.oob_improvement_ = np.resize( + self.oob_improvement_, total_n_estimators + ) + self.oob_scores_ = np.resize(self.oob_scores_, total_n_estimators) + self.oob_score_ = np.nan + else: + self.oob_improvement_ = np.zeros( + (total_n_estimators,), dtype=np.float64 + ) + self.oob_scores_ = np.zeros((total_n_estimators,), dtype=np.float64) + self.oob_score_ = np.nan + + def _is_fitted(self): + return len(getattr(self, "estimators_", [])) > 0 + + def _check_initialized(self): + """Check that the estimator is initialized, raising an error if not.""" + check_is_fitted(self) + + @_fit_context( + # GradientBoosting*.init is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y, sample_weight=None, monitor=None): + """Fit the gradient boosting model. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + y : array-like of shape (n_samples,) + Target values (strings or integers in classification, real numbers + in regression) + For classification, labels must correspond to classes. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If None, then samples are equally weighted. Splits + that would create child nodes with net zero or negative weight are + ignored while searching for a split in each node. In the case of + classification, splits are also ignored if they would result in any + single class carrying a negative weight in either child node. + + monitor : callable, default=None + The monitor is called after each iteration with the current + iteration, a reference to the estimator and the local variables of + ``_fit_stages`` as keyword arguments ``callable(i, self, + locals())``. If the callable returns ``True`` the fitting procedure + is stopped. The monitor can be used for various things such as + computing held-out estimates, early stopping, model introspect, and + snapshotting. + + Returns + ------- + self : object + Fitted estimator. + """ + if not self.warm_start: + self._clear_state() + + # Check input + # Since check_array converts both X and y to the same dtype, but the + # trees use different types for X and y, checking them separately. + + X, y = validate_data( + self, + X, + y, + accept_sparse=["csr", "csc", "coo"], + dtype=DTYPE, + multi_output=True, + ) + sample_weight_is_none = sample_weight is None + sample_weight = _check_sample_weight(sample_weight, X) + if sample_weight_is_none: + y = self._encode_y(y=y, sample_weight=None) + else: + y = self._encode_y(y=y, sample_weight=sample_weight) + y = column_or_1d(y, warn=True) # TODO: Is this still required? + + self._set_max_features() + + # self.loss is guaranteed to be a string + self._loss = self._get_loss(sample_weight=sample_weight) + + if self.n_iter_no_change is not None: + stratify = y if is_classifier(self) else None + ( + X_train, + X_val, + y_train, + y_val, + sample_weight_train, + sample_weight_val, + ) = train_test_split( + X, + y, + sample_weight, + random_state=self.random_state, + test_size=self.validation_fraction, + stratify=stratify, + ) + if is_classifier(self): + if self.n_classes_ != np.unique(y_train).shape[0]: + # We choose to error here. The problem is that the init + # estimator would be trained on y, which has some missing + # classes now, so its predictions would not have the + # correct shape. + raise ValueError( + "The training data after the early stopping split " + "is missing some classes. Try using another random " + "seed." + ) + else: + X_train, y_train, sample_weight_train = X, y, sample_weight + X_val = y_val = sample_weight_val = None + + n_samples = X_train.shape[0] + + # First time calling fit. + if not self._is_fitted(): + # init state + self._init_state() + + # fit initial model and initialize raw predictions + if self.init_ == "zero": + raw_predictions = np.zeros( + shape=(n_samples, self.n_trees_per_iteration_), + dtype=np.float64, + ) + else: + # XXX clean this once we have a support_sample_weight tag + if sample_weight_is_none: + self.init_.fit(X_train, y_train) + else: + msg = ( + "The initial estimator {} does not support sample " + "weights.".format(self.init_.__class__.__name__) + ) + try: + self.init_.fit( + X_train, y_train, sample_weight=sample_weight_train + ) + except TypeError as e: + if "unexpected keyword argument 'sample_weight'" in str(e): + # regular estimator without SW support + raise ValueError(msg) from e + else: # regular estimator whose input checking failed + raise + except ValueError as e: + if ( + "pass parameters to specific steps of " + "your pipeline using the " + "stepname__parameter" in str(e) + ): # pipeline + raise ValueError(msg) from e + else: # regular estimator whose input checking failed + raise + + raw_predictions = _init_raw_predictions( + X_train, self.init_, self._loss, is_classifier(self) + ) + + begin_at_stage = 0 + + # The rng state must be preserved if warm_start is True + self._rng = check_random_state(self.random_state) + + # warm start: this is not the first time fit was called + else: + # add more estimators to fitted model + # invariant: warm_start = True + if self.n_estimators < self.estimators_.shape[0]: + raise ValueError( + "n_estimators=%d must be larger or equal to " + "estimators_.shape[0]=%d when " + "warm_start==True" % (self.n_estimators, self.estimators_.shape[0]) + ) + begin_at_stage = self.estimators_.shape[0] + # The requirements of _raw_predict + # are more constrained than fit. It accepts only CSR + # matrices. Finite values have already been checked in _validate_data. + X_train = check_array( + X_train, + dtype=DTYPE, + order="C", + accept_sparse="csr", + ensure_all_finite=False, + ) + raw_predictions = self._raw_predict(X_train) + self._resize_state() + + # fit the boosting stages + n_stages = self._fit_stages( + X_train, + y_train, + raw_predictions, + sample_weight_train, + self._rng, + X_val, + y_val, + sample_weight_val, + begin_at_stage, + monitor, + ) + + # change shape of arrays after fit (early-stopping or additional ests) + if n_stages != self.estimators_.shape[0]: + self.estimators_ = self.estimators_[:n_stages] + self.train_score_ = self.train_score_[:n_stages] + if hasattr(self, "oob_improvement_"): + # OOB scores were computed + self.oob_improvement_ = self.oob_improvement_[:n_stages] + self.oob_scores_ = self.oob_scores_[:n_stages] + self.oob_score_ = self.oob_scores_[-1] + self.n_estimators_ = n_stages + return self + + def _fit_stages( + self, + X, + y, + raw_predictions, + sample_weight, + random_state, + X_val, + y_val, + sample_weight_val, + begin_at_stage=0, + monitor=None, + ): + """Iteratively fits the stages. + + For each stage it computes the progress (OOB, train score) + and delegates to ``_fit_stage``. + Returns the number of stages fit; might differ from ``n_estimators`` + due to early stopping. + """ + n_samples = X.shape[0] + do_oob = self.subsample < 1.0 + sample_mask = np.ones((n_samples,), dtype=bool) + n_inbag = max(1, int(self.subsample * n_samples)) + + if self.verbose: + verbose_reporter = VerboseReporter(verbose=self.verbose) + verbose_reporter.init(self, begin_at_stage) + + X_csc = csc_matrix(X) if issparse(X) else None + X_csr = csr_matrix(X) if issparse(X) else None + + if self.n_iter_no_change is not None: + loss_history = np.full(self.n_iter_no_change, np.inf) + # We create a generator to get the predictions for X_val after + # the addition of each successive stage + y_val_pred_iter = self._staged_raw_predict(X_val, check_input=False) + + # Older versions of GBT had its own loss functions. With the new common + # private loss function submodule _loss, we often are a factor of 2 + # away from the old version. Here we keep backward compatibility for + # oob_scores_ and oob_improvement_, even if the old way is quite + # inconsistent (sometimes the gradient is half the gradient, sometimes + # not). + if isinstance( + self._loss, + ( + HalfSquaredError, + HalfBinomialLoss, + ), + ): + factor = 2 + else: + factor = 1 + + # perform boosting iterations + i = begin_at_stage + for i in range(begin_at_stage, self.n_estimators): + # subsampling + if do_oob: + sample_mask = _random_sample_mask(n_samples, n_inbag, random_state) + y_oob_masked = y[~sample_mask] + sample_weight_oob_masked = sample_weight[~sample_mask] + if i == 0: # store the initial loss to compute the OOB score + initial_loss = factor * self._loss( + y_true=y_oob_masked, + raw_prediction=raw_predictions[~sample_mask], + sample_weight=sample_weight_oob_masked, + ) + + # fit next stage of trees + raw_predictions = self._fit_stage( + i, + X, + y, + raw_predictions, + sample_weight, + sample_mask, + random_state, + X_csc=X_csc, + X_csr=X_csr, + ) + + # track loss + if do_oob: + self.train_score_[i] = factor * self._loss( + y_true=y[sample_mask], + raw_prediction=raw_predictions[sample_mask], + sample_weight=sample_weight[sample_mask], + ) + self.oob_scores_[i] = factor * self._loss( + y_true=y_oob_masked, + raw_prediction=raw_predictions[~sample_mask], + sample_weight=sample_weight_oob_masked, + ) + previous_loss = initial_loss if i == 0 else self.oob_scores_[i - 1] + self.oob_improvement_[i] = previous_loss - self.oob_scores_[i] + self.oob_score_ = self.oob_scores_[-1] + else: + # no need to fancy index w/ no subsampling + self.train_score_[i] = factor * self._loss( + y_true=y, + raw_prediction=raw_predictions, + sample_weight=sample_weight, + ) + + if self.verbose > 0: + verbose_reporter.update(i, self) + + if monitor is not None: + early_stopping = monitor(i, self, locals()) + if early_stopping: + break + + # We also provide an early stopping based on the score from + # validation set (X_val, y_val), if n_iter_no_change is set + if self.n_iter_no_change is not None: + # By calling next(y_val_pred_iter), we get the predictions + # for X_val after the addition of the current stage + validation_loss = factor * self._loss( + y_val, next(y_val_pred_iter), sample_weight_val + ) + + # Require validation_score to be better (less) than at least + # one of the last n_iter_no_change evaluations + if np.any(validation_loss + self.tol < loss_history): + loss_history[i % len(loss_history)] = validation_loss + else: + break + + return i + 1 + + def _make_estimator(self, append=True): + # we don't need _make_estimator + raise NotImplementedError() + + def _raw_predict_init(self, X): + """Check input and compute raw predictions of the init estimator.""" + self._check_initialized() + X = self.estimators_[0, 0]._validate_X_predict(X, check_input=True) + if self.init_ == "zero": + raw_predictions = np.zeros( + shape=(X.shape[0], self.n_trees_per_iteration_), dtype=np.float64 + ) + else: + raw_predictions = _init_raw_predictions( + X, self.init_, self._loss, is_classifier(self) + ) + return raw_predictions + + def _raw_predict(self, X): + """Return the sum of the trees raw predictions (+ init estimator).""" + check_is_fitted(self) + raw_predictions = self._raw_predict_init(X) + predict_stages(self.estimators_, X, self.learning_rate, raw_predictions) + return raw_predictions + + def _staged_raw_predict(self, X, check_input=True): + """Compute raw predictions of ``X`` for each iteration. + + This method allows monitoring (i.e. determine error on testing set) + after each stage. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + check_input : bool, default=True + If False, the input arrays X will not be checked. + + Returns + ------- + raw_predictions : generator of ndarray of shape (n_samples, k) + The raw predictions of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + Regression and binary classification are special cases with + ``k == 1``, otherwise ``k==n_classes``. + """ + if check_input: + X = validate_data( + self, X, dtype=DTYPE, order="C", accept_sparse="csr", reset=False + ) + raw_predictions = self._raw_predict_init(X) + for i in range(self.estimators_.shape[0]): + predict_stage(self.estimators_, i, X, self.learning_rate, raw_predictions) + yield raw_predictions.copy() + + @property + def feature_importances_(self): + """The impurity-based feature importances. + + The higher, the more important the feature. + The importance of a feature is computed as the (normalized) + total reduction of the criterion brought by that feature. It is also + known as the Gini importance. + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + Returns + ------- + feature_importances_ : ndarray of shape (n_features,) + The values of this array sum to 1, unless all trees are single node + trees consisting of only the root node, in which case it will be an + array of zeros. + """ + self._check_initialized() + + relevant_trees = [ + tree + for stage in self.estimators_ + for tree in stage + if tree.tree_.node_count > 1 + ] + if not relevant_trees: + # degenerate case where all trees have only one node + return np.zeros(shape=self.n_features_in_, dtype=np.float64) + + relevant_feature_importances = [ + tree.tree_.compute_feature_importances(normalize=False) + for tree in relevant_trees + ] + avg_feature_importances = np.mean( + relevant_feature_importances, axis=0, dtype=np.float64 + ) + return avg_feature_importances / np.sum(avg_feature_importances) + + def _compute_partial_dependence_recursion(self, grid, target_features): + """Fast partial dependence computation. + + Parameters + ---------- + grid : ndarray of shape (n_samples, n_target_features), dtype=np.float32 + The grid points on which the partial dependence should be + evaluated. + target_features : ndarray of shape (n_target_features,), dtype=np.intp + The set of target features for which the partial dependence + should be evaluated. + + Returns + ------- + averaged_predictions : ndarray of shape \ + (n_trees_per_iteration_, n_samples) + The value of the partial dependence function on each grid point. + """ + if self.init is not None: + warnings.warn( + "Using recursion method with a non-constant init predictor " + "will lead to incorrect partial dependence values. " + "Got init=%s." % self.init, + UserWarning, + ) + grid = np.asarray(grid, dtype=DTYPE, order="C") + n_estimators, n_trees_per_stage = self.estimators_.shape + averaged_predictions = np.zeros( + (n_trees_per_stage, grid.shape[0]), dtype=np.float64, order="C" + ) + target_features = np.asarray(target_features, dtype=np.intp, order="C") + + for stage in range(n_estimators): + for k in range(n_trees_per_stage): + tree = self.estimators_[stage, k].tree_ + tree.compute_partial_dependence( + grid, target_features, averaged_predictions[k] + ) + averaged_predictions *= self.learning_rate + + return averaged_predictions + + def apply(self, X): + """Apply trees in the ensemble to X, return leaf indices. + + .. versionadded:: 0.17 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, its dtype will be converted to + ``dtype=np.float32``. If a sparse matrix is provided, it will + be converted to a sparse ``csr_matrix``. + + Returns + ------- + X_leaves : array-like of shape (n_samples, n_estimators, n_classes) + For each datapoint x in X and for each tree in the ensemble, + return the index of the leaf x ends up in each estimator. + In the case of binary classification n_classes is 1. + """ + + self._check_initialized() + X = self.estimators_[0, 0]._validate_X_predict(X, check_input=True) + + # n_classes will be equal to 1 in the binary classification or the + # regression case. + n_estimators, n_classes = self.estimators_.shape + leaves = np.zeros((X.shape[0], n_estimators, n_classes)) + + for i in range(n_estimators): + for j in range(n_classes): + estimator = self.estimators_[i, j] + leaves[:, i, j] = estimator.apply(X, check_input=False) + + return leaves + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class GradientBoostingClassifier(ClassifierMixin, BaseGradientBoosting): + """Gradient Boosting for classification. + + This algorithm builds an additive model in a forward stage-wise fashion; it + allows for the optimization of arbitrary differentiable loss functions. In + each stage ``n_classes_`` regression trees are fit on the negative gradient + of the loss function, e.g. binary or multiclass log loss. Binary + classification is a special case where only a single regression tree is + induced. + + :class:`~sklearn.ensemble.HistGradientBoostingClassifier` is a much faster variant + of this algorithm for intermediate and large datasets (`n_samples >= 10_000`) and + supports monotonic constraints. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + loss : {'log_loss', 'exponential'}, default='log_loss' + The loss function to be optimized. 'log_loss' refers to binomial and + multinomial deviance, the same as used in logistic regression. + It is a good choice for classification with probabilistic outputs. + For loss 'exponential', gradient boosting recovers the AdaBoost algorithm. + + learning_rate : float, default=0.1 + Learning rate shrinks the contribution of each tree by `learning_rate`. + There is a trade-off between learning_rate and n_estimators. + Values must be in the range `[0.0, inf)`. + + For an example of the effects of this parameter and its interaction with + ``subsample``, see + :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_regularization.py`. + + n_estimators : int, default=100 + The number of boosting stages to perform. Gradient boosting + is fairly robust to over-fitting so a large number usually + results in better performance. + Values must be in the range `[1, inf)`. + + subsample : float, default=1.0 + The fraction of samples to be used for fitting the individual base + learners. If smaller than 1.0 this results in Stochastic Gradient + Boosting. `subsample` interacts with the parameter `n_estimators`. + Choosing `subsample < 1.0` leads to a reduction of variance + and an increase in bias. + Values must be in the range `(0.0, 1.0]`. + + criterion : {'friedman_mse', 'squared_error'}, default='friedman_mse' + The function to measure the quality of a split. Supported criteria are + 'friedman_mse' for the mean squared error with improvement score by + Friedman, 'squared_error' for mean squared error. The default value of + 'friedman_mse' is generally the best as it can provide a better + approximation in some cases. + + .. versionadded:: 0.18 + + min_samples_split : int or float, default=2 + The minimum number of samples required to split an internal node: + + - If int, values must be in the range `[2, inf)`. + - If float, values must be in the range `(0.0, 1.0]` and `min_samples_split` + will be `ceil(min_samples_split * n_samples)`. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_samples_leaf : int or float, default=1 + The minimum number of samples required to be at a leaf node. + A split point at any depth will only be considered if it leaves at + least ``min_samples_leaf`` training samples in each of the left and + right branches. This may have the effect of smoothing the model, + especially in regression. + + - If int, values must be in the range `[1, inf)`. + - If float, values must be in the range `(0.0, 1.0)` and `min_samples_leaf` + will be `ceil(min_samples_leaf * n_samples)`. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_weight_fraction_leaf : float, default=0.0 + The minimum weighted fraction of the sum total of weights (of all + the input samples) required to be at a leaf node. Samples have + equal weight when sample_weight is not provided. + Values must be in the range `[0.0, 0.5]`. + + max_depth : int or None, default=3 + Maximum depth of the individual regression estimators. The maximum + depth limits the number of nodes in the tree. Tune this parameter + for best performance; the best value depends on the interaction + of the input variables. If None, then nodes are expanded until + all leaves are pure or until all leaves contain less than + min_samples_split samples. + If int, values must be in the range `[1, inf)`. + + min_impurity_decrease : float, default=0.0 + A node will be split if this split induces a decrease of the impurity + greater than or equal to this value. + Values must be in the range `[0.0, inf)`. + + The weighted impurity decrease equation is the following:: + + N_t / N * (impurity - N_t_R / N_t * right_impurity + - N_t_L / N_t * left_impurity) + + where ``N`` is the total number of samples, ``N_t`` is the number of + samples at the current node, ``N_t_L`` is the number of samples in the + left child, and ``N_t_R`` is the number of samples in the right child. + + ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, + if ``sample_weight`` is passed. + + .. versionadded:: 0.19 + + init : estimator or 'zero', default=None + An estimator object that is used to compute the initial predictions. + ``init`` has to provide :term:`fit` and :term:`predict_proba`. If + 'zero', the initial raw predictions are set to zero. By default, a + ``DummyEstimator`` predicting the classes priors is used. + + random_state : int, RandomState instance or None, default=None + Controls the random seed given to each Tree estimator at each + boosting iteration. + In addition, it controls the random permutation of the features at + each split (see Notes for more details). + It also controls the random splitting of the training data to obtain a + validation set if `n_iter_no_change` is not None. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + max_features : {'sqrt', 'log2'}, int or float, default=None + The number of features to consider when looking for the best split: + + - If int, values must be in the range `[1, inf)`. + - If float, values must be in the range `(0.0, 1.0]` and the features + considered at each split will be `max(1, int(max_features * n_features_in_))`. + - If 'sqrt', then `max_features=sqrt(n_features)`. + - If 'log2', then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Choosing `max_features < n_features` leads to a reduction of variance + and an increase in bias. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + verbose : int, default=0 + Enable verbose output. If 1 then it prints progress and performance + once in a while (the more trees the lower the frequency). If greater + than 1 then it prints progress and performance for every tree. + Values must be in the range `[0, inf)`. + + max_leaf_nodes : int, default=None + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + Values must be in the range `[2, inf)`. + If `None`, then unlimited number of leaf nodes. + + warm_start : bool, default=False + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just erase the + previous solution. See :term:`the Glossary `. + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Values must be in the range `(0.0, 1.0)`. + Only used if ``n_iter_no_change`` is set to an integer. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=None + ``n_iter_no_change`` is used to decide if early stopping will be used + to terminate training when validation score is not improving. By + default it is set to None to disable early stopping. If set to a + number, it will set aside ``validation_fraction`` size of the training + data as validation and terminate training when validation score is not + improving in all of the previous ``n_iter_no_change`` numbers of + iterations. The split is stratified. + Values must be in the range `[1, inf)`. + See + :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_early_stopping.py`. + + .. versionadded:: 0.20 + + tol : float, default=1e-4 + Tolerance for the early stopping. When the loss is not improving + by at least tol for ``n_iter_no_change`` iterations (if set to a + number), the training stops. + Values must be in the range `[0.0, inf)`. + + .. versionadded:: 0.20 + + ccp_alpha : non-negative float, default=0.0 + Complexity parameter used for Minimal Cost-Complexity Pruning. The + subtree with the largest cost complexity that is smaller than + ``ccp_alpha`` will be chosen. By default, no pruning is performed. + Values must be in the range `[0.0, inf)`. + See :ref:`minimal_cost_complexity_pruning` for details. See + :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` + for an example of such pruning. + + .. versionadded:: 0.22 + + Attributes + ---------- + n_estimators_ : int + The number of estimators as selected by early stopping (if + ``n_iter_no_change`` is specified). Otherwise it is set to + ``n_estimators``. + + .. versionadded:: 0.20 + + n_trees_per_iteration_ : int + The number of trees that are built at each iteration. For binary classifiers, + this is always 1. + + .. versionadded:: 1.4.0 + + feature_importances_ : ndarray of shape (n_features,) + The impurity-based feature importances. + The higher, the more important the feature. + The importance of a feature is computed as the (normalized) + total reduction of the criterion brought by that feature. It is also + known as the Gini importance. + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + oob_improvement_ : ndarray of shape (n_estimators,) + The improvement in loss on the out-of-bag samples + relative to the previous iteration. + ``oob_improvement_[0]`` is the improvement in + loss of the first stage over the ``init`` estimator. + Only available if ``subsample < 1.0``. + + oob_scores_ : ndarray of shape (n_estimators,) + The full history of the loss values on the out-of-bag + samples. Only available if `subsample < 1.0`. + + .. versionadded:: 1.3 + + oob_score_ : float + The last value of the loss on the out-of-bag samples. It is + the same as `oob_scores_[-1]`. Only available if `subsample < 1.0`. + + .. versionadded:: 1.3 + + train_score_ : ndarray of shape (n_estimators,) + The i-th score ``train_score_[i]`` is the loss of the + model at iteration ``i`` on the in-bag sample. + If ``subsample == 1`` this is the loss on the training data. + + init_ : estimator + The estimator that provides the initial predictions. Set via the ``init`` + argument. + + estimators_ : ndarray of DecisionTreeRegressor of \ + shape (n_estimators, ``n_trees_per_iteration_``) + The collection of fitted sub-estimators. ``n_trees_per_iteration_`` is 1 for + binary classification, otherwise ``n_classes``. + + classes_ : ndarray of shape (n_classes,) + The classes labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_classes_ : int + The number of classes. + + max_features_ : int + The inferred value of max_features. + + See Also + -------- + HistGradientBoostingClassifier : Histogram-based Gradient Boosting + Classification Tree. + sklearn.tree.DecisionTreeClassifier : A decision tree classifier. + RandomForestClassifier : A meta-estimator that fits a number of decision + tree classifiers on various sub-samples of the dataset and uses + averaging to improve the predictive accuracy and control over-fitting. + AdaBoostClassifier : A meta-estimator that begins by fitting a classifier + on the original dataset and then fits additional copies of the + classifier on the same dataset where the weights of incorrectly + classified instances are adjusted such that subsequent classifiers + focus more on difficult cases. + + Notes + ----- + The features are always randomly permuted at each split. Therefore, + the best found split may vary, even with the same training data and + ``max_features=n_features``, if the improvement of the criterion is + identical for several splits enumerated during the search of the best + split. To obtain a deterministic behaviour during fitting, + ``random_state`` has to be fixed. + + References + ---------- + J. Friedman, Greedy Function Approximation: A Gradient Boosting + Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. + + J. Friedman, Stochastic Gradient Boosting, 1999 + + T. Hastie, R. Tibshirani and J. Friedman. + Elements of Statistical Learning Ed. 2, Springer, 2009. + + Examples + -------- + The following example shows how to fit a gradient boosting classifier with + 100 decision stumps as weak learners. + + >>> from sklearn.datasets import make_hastie_10_2 + >>> from sklearn.ensemble import GradientBoostingClassifier + + >>> X, y = make_hastie_10_2(random_state=0) + >>> X_train, X_test = X[:2000], X[2000:] + >>> y_train, y_test = y[:2000], y[2000:] + + >>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, + ... max_depth=1, random_state=0).fit(X_train, y_train) + >>> clf.score(X_test, y_test) + 0.913 + """ + + _parameter_constraints: dict = { + **BaseGradientBoosting._parameter_constraints, + "loss": [StrOptions({"log_loss", "exponential"})], + "init": [StrOptions({"zero"}), None, HasMethods(["fit", "predict_proba"])], + } + + def __init__( + self, + *, + loss="log_loss", + learning_rate=0.1, + n_estimators=100, + subsample=1.0, + criterion="friedman_mse", + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0.0, + max_depth=3, + min_impurity_decrease=0.0, + init=None, + random_state=None, + max_features=None, + verbose=0, + max_leaf_nodes=None, + warm_start=False, + validation_fraction=0.1, + n_iter_no_change=None, + tol=1e-4, + ccp_alpha=0.0, + ): + super().__init__( + loss=loss, + learning_rate=learning_rate, + n_estimators=n_estimators, + criterion=criterion, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_depth=max_depth, + init=init, + subsample=subsample, + max_features=max_features, + random_state=random_state, + verbose=verbose, + max_leaf_nodes=max_leaf_nodes, + min_impurity_decrease=min_impurity_decrease, + warm_start=warm_start, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + tol=tol, + ccp_alpha=ccp_alpha, + ) + + def _encode_y(self, y, sample_weight): + # encode classes into 0 ... n_classes - 1 and sets attributes classes_ + # and n_trees_per_iteration_ + check_classification_targets(y) + + label_encoder = LabelEncoder() + encoded_y_int = label_encoder.fit_transform(y) + self.classes_ = label_encoder.classes_ + n_classes = self.classes_.shape[0] + # only 1 tree for binary classification. For multiclass classification, + # we build 1 tree per class. + self.n_trees_per_iteration_ = 1 if n_classes <= 2 else n_classes + encoded_y = encoded_y_int.astype(float, copy=False) + + # From here on, it is additional to the HGBT case. + # expose n_classes_ attribute + self.n_classes_ = n_classes + if sample_weight is None: + n_trim_classes = n_classes + else: + n_trim_classes = np.count_nonzero(np.bincount(encoded_y_int, sample_weight)) + + if n_trim_classes < 2: + raise ValueError( + "y contains %d class after sample_weight " + "trimmed classes with zero weights, while a " + "minimum of 2 classes are required." % n_trim_classes + ) + return encoded_y + + def _get_loss(self, sample_weight): + if self.loss == "log_loss": + if self.n_classes_ == 2: + return HalfBinomialLoss(sample_weight=sample_weight) + else: + return HalfMultinomialLoss( + sample_weight=sample_weight, n_classes=self.n_classes_ + ) + elif self.loss == "exponential": + if self.n_classes_ > 2: + raise ValueError( + f"loss='{self.loss}' is only suitable for a binary classification " + f"problem, you have n_classes={self.n_classes_}. " + "Please use loss='log_loss' instead." + ) + else: + return ExponentialLoss(sample_weight=sample_weight) + + def decision_function(self, X): + """Compute the decision function of ``X``. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + score : ndarray of shape (n_samples, n_classes) or (n_samples,) + The decision function of the input samples, which corresponds to + the raw values predicted from the trees of the ensemble . The + order of the classes corresponds to that in the attribute + :term:`classes_`. Regression and binary classification produce an + array of shape (n_samples,). + """ + X = validate_data( + self, X, dtype=DTYPE, order="C", accept_sparse="csr", reset=False + ) + raw_predictions = self._raw_predict(X) + if raw_predictions.shape[1] == 1: + return raw_predictions.ravel() + return raw_predictions + + def staged_decision_function(self, X): + """Compute decision function of ``X`` for each iteration. + + This method allows monitoring (i.e. determine error on testing set) + after each stage. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Yields + ------ + score : generator of ndarray of shape (n_samples, k) + The decision function of the input samples, which corresponds to + the raw values predicted from the trees of the ensemble . The + classes corresponds to that in the attribute :term:`classes_`. + Regression and binary classification are special cases with + ``k == 1``, otherwise ``k==n_classes``. + """ + yield from self._staged_raw_predict(X) + + def predict(self, X): + """Predict class for X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + y : ndarray of shape (n_samples,) + The predicted values. + """ + raw_predictions = self.decision_function(X) + if raw_predictions.ndim == 1: # decision_function already squeezed it + encoded_classes = (raw_predictions >= 0).astype(int) + else: + encoded_classes = np.argmax(raw_predictions, axis=1) + return self.classes_[encoded_classes] + + def staged_predict(self, X): + """Predict class at each stage for X. + + This method allows monitoring (i.e. determine error on testing set) + after each stage. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Yields + ------ + y : generator of ndarray of shape (n_samples,) + The predicted value of the input samples. + """ + if self.n_classes_ == 2: # n_trees_per_iteration_ = 1 + for raw_predictions in self._staged_raw_predict(X): + encoded_classes = (raw_predictions.squeeze() >= 0).astype(int) + yield self.classes_.take(encoded_classes, axis=0) + else: + for raw_predictions in self._staged_raw_predict(X): + encoded_classes = np.argmax(raw_predictions, axis=1) + yield self.classes_.take(encoded_classes, axis=0) + + def predict_proba(self, X): + """Predict class probabilities for X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + p : ndarray of shape (n_samples, n_classes) + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + + Raises + ------ + AttributeError + If the ``loss`` does not support probabilities. + """ + raw_predictions = self.decision_function(X) + return self._loss.predict_proba(raw_predictions) + + def predict_log_proba(self, X): + """Predict class log-probabilities for X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + p : ndarray of shape (n_samples, n_classes) + The class log-probabilities of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + + Raises + ------ + AttributeError + If the ``loss`` does not support probabilities. + """ + proba = self.predict_proba(X) + return np.log(proba) + + def staged_predict_proba(self, X): + """Predict class probabilities at each stage for X. + + This method allows monitoring (i.e. determine error on testing set) + after each stage. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Yields + ------ + y : generator of ndarray of shape (n_samples,) + The predicted value of the input samples. + """ + try: + for raw_predictions in self._staged_raw_predict(X): + yield self._loss.predict_proba(raw_predictions) + except NotFittedError: + raise + except AttributeError as e: + raise AttributeError( + "loss=%r does not support predict_proba" % self.loss + ) from e + + +class GradientBoostingRegressor(RegressorMixin, BaseGradientBoosting): + """Gradient Boosting for regression. + + This estimator builds an additive model in a forward stage-wise fashion; it + allows for the optimization of arbitrary differentiable loss functions. In + each stage a regression tree is fit on the negative gradient of the given + loss function. + + :class:`~sklearn.ensemble.HistGradientBoostingRegressor` is a much faster variant + of this algorithm for intermediate and large datasets (`n_samples >= 10_000`) and + supports monotonic constraints. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + loss : {'squared_error', 'absolute_error', 'huber', 'quantile'}, \ + default='squared_error' + Loss function to be optimized. 'squared_error' refers to the squared + error for regression. 'absolute_error' refers to the absolute error of + regression and is a robust loss function. 'huber' is a + combination of the two. 'quantile' allows quantile regression (use + `alpha` to specify the quantile). + See + :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_quantile.py` + for an example that demonstrates quantile regression for creating + prediction intervals with `loss='quantile'`. + + learning_rate : float, default=0.1 + Learning rate shrinks the contribution of each tree by `learning_rate`. + There is a trade-off between learning_rate and n_estimators. + Values must be in the range `[0.0, inf)`. + + n_estimators : int, default=100 + The number of boosting stages to perform. Gradient boosting + is fairly robust to over-fitting so a large number usually + results in better performance. + Values must be in the range `[1, inf)`. + + subsample : float, default=1.0 + The fraction of samples to be used for fitting the individual base + learners. If smaller than 1.0 this results in Stochastic Gradient + Boosting. `subsample` interacts with the parameter `n_estimators`. + Choosing `subsample < 1.0` leads to a reduction of variance + and an increase in bias. + Values must be in the range `(0.0, 1.0]`. + + criterion : {'friedman_mse', 'squared_error'}, default='friedman_mse' + The function to measure the quality of a split. Supported criteria are + "friedman_mse" for the mean squared error with improvement score by + Friedman, "squared_error" for mean squared error. The default value of + "friedman_mse" is generally the best as it can provide a better + approximation in some cases. + + .. versionadded:: 0.18 + + min_samples_split : int or float, default=2 + The minimum number of samples required to split an internal node: + + - If int, values must be in the range `[2, inf)`. + - If float, values must be in the range `(0.0, 1.0]` and `min_samples_split` + will be `ceil(min_samples_split * n_samples)`. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_samples_leaf : int or float, default=1 + The minimum number of samples required to be at a leaf node. + A split point at any depth will only be considered if it leaves at + least ``min_samples_leaf`` training samples in each of the left and + right branches. This may have the effect of smoothing the model, + especially in regression. + + - If int, values must be in the range `[1, inf)`. + - If float, values must be in the range `(0.0, 1.0)` and `min_samples_leaf` + will be `ceil(min_samples_leaf * n_samples)`. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_weight_fraction_leaf : float, default=0.0 + The minimum weighted fraction of the sum total of weights (of all + the input samples) required to be at a leaf node. Samples have + equal weight when sample_weight is not provided. + Values must be in the range `[0.0, 0.5]`. + + max_depth : int or None, default=3 + Maximum depth of the individual regression estimators. The maximum + depth limits the number of nodes in the tree. Tune this parameter + for best performance; the best value depends on the interaction + of the input variables. If None, then nodes are expanded until + all leaves are pure or until all leaves contain less than + min_samples_split samples. + If int, values must be in the range `[1, inf)`. + + min_impurity_decrease : float, default=0.0 + A node will be split if this split induces a decrease of the impurity + greater than or equal to this value. + Values must be in the range `[0.0, inf)`. + + The weighted impurity decrease equation is the following:: + + N_t / N * (impurity - N_t_R / N_t * right_impurity + - N_t_L / N_t * left_impurity) + + where ``N`` is the total number of samples, ``N_t`` is the number of + samples at the current node, ``N_t_L`` is the number of samples in the + left child, and ``N_t_R`` is the number of samples in the right child. + + ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, + if ``sample_weight`` is passed. + + .. versionadded:: 0.19 + + init : estimator or 'zero', default=None + An estimator object that is used to compute the initial predictions. + ``init`` has to provide :term:`fit` and :term:`predict`. If 'zero', the + initial raw predictions are set to zero. By default a + ``DummyEstimator`` is used, predicting either the average target value + (for loss='squared_error'), or a quantile for the other losses. + + random_state : int, RandomState instance or None, default=None + Controls the random seed given to each Tree estimator at each + boosting iteration. + In addition, it controls the random permutation of the features at + each split (see Notes for more details). + It also controls the random splitting of the training data to obtain a + validation set if `n_iter_no_change` is not None. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + max_features : {'sqrt', 'log2'}, int or float, default=None + The number of features to consider when looking for the best split: + + - If int, values must be in the range `[1, inf)`. + - If float, values must be in the range `(0.0, 1.0]` and the features + considered at each split will be `max(1, int(max_features * n_features_in_))`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Choosing `max_features < n_features` leads to a reduction of variance + and an increase in bias. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + alpha : float, default=0.9 + The alpha-quantile of the huber loss function and the quantile + loss function. Only if ``loss='huber'`` or ``loss='quantile'``. + Values must be in the range `(0.0, 1.0)`. + + verbose : int, default=0 + Enable verbose output. If 1 then it prints progress and performance + once in a while (the more trees the lower the frequency). If greater + than 1 then it prints progress and performance for every tree. + Values must be in the range `[0, inf)`. + + max_leaf_nodes : int, default=None + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + Values must be in the range `[2, inf)`. + If None, then unlimited number of leaf nodes. + + warm_start : bool, default=False + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just erase the + previous solution. See :term:`the Glossary `. + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Values must be in the range `(0.0, 1.0)`. + Only used if ``n_iter_no_change`` is set to an integer. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=None + ``n_iter_no_change`` is used to decide if early stopping will be used + to terminate training when validation score is not improving. By + default it is set to None to disable early stopping. If set to a + number, it will set aside ``validation_fraction`` size of the training + data as validation and terminate training when validation score is not + improving in all of the previous ``n_iter_no_change`` numbers of + iterations. + Values must be in the range `[1, inf)`. + See + :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_early_stopping.py`. + + .. versionadded:: 0.20 + + tol : float, default=1e-4 + Tolerance for the early stopping. When the loss is not improving + by at least tol for ``n_iter_no_change`` iterations (if set to a + number), the training stops. + Values must be in the range `[0.0, inf)`. + + .. versionadded:: 0.20 + + ccp_alpha : non-negative float, default=0.0 + Complexity parameter used for Minimal Cost-Complexity Pruning. The + subtree with the largest cost complexity that is smaller than + ``ccp_alpha`` will be chosen. By default, no pruning is performed. + Values must be in the range `[0.0, inf)`. + See :ref:`minimal_cost_complexity_pruning` for details. See + :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` + for an example of such pruning. + + .. versionadded:: 0.22 + + Attributes + ---------- + n_estimators_ : int + The number of estimators as selected by early stopping (if + ``n_iter_no_change`` is specified). Otherwise it is set to + ``n_estimators``. + + n_trees_per_iteration_ : int + The number of trees that are built at each iteration. For regressors, this is + always 1. + + .. versionadded:: 1.4.0 + + feature_importances_ : ndarray of shape (n_features,) + The impurity-based feature importances. + The higher, the more important the feature. + The importance of a feature is computed as the (normalized) + total reduction of the criterion brought by that feature. It is also + known as the Gini importance. + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + oob_improvement_ : ndarray of shape (n_estimators,) + The improvement in loss on the out-of-bag samples + relative to the previous iteration. + ``oob_improvement_[0]`` is the improvement in + loss of the first stage over the ``init`` estimator. + Only available if ``subsample < 1.0``. + + oob_scores_ : ndarray of shape (n_estimators,) + The full history of the loss values on the out-of-bag + samples. Only available if `subsample < 1.0`. + + .. versionadded:: 1.3 + + oob_score_ : float + The last value of the loss on the out-of-bag samples. It is + the same as `oob_scores_[-1]`. Only available if `subsample < 1.0`. + + .. versionadded:: 1.3 + + train_score_ : ndarray of shape (n_estimators,) + The i-th score ``train_score_[i]`` is the loss of the + model at iteration ``i`` on the in-bag sample. + If ``subsample == 1`` this is the loss on the training data. + + init_ : estimator + The estimator that provides the initial predictions. Set via the ``init`` + argument. + + estimators_ : ndarray of DecisionTreeRegressor of shape (n_estimators, 1) + The collection of fitted sub-estimators. + + 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 + + max_features_ : int + The inferred value of max_features. + + See Also + -------- + HistGradientBoostingRegressor : Histogram-based Gradient Boosting + Classification Tree. + sklearn.tree.DecisionTreeRegressor : A decision tree regressor. + sklearn.ensemble.RandomForestRegressor : A random forest regressor. + + Notes + ----- + The features are always randomly permuted at each split. Therefore, + the best found split may vary, even with the same training data and + ``max_features=n_features``, if the improvement of the criterion is + identical for several splits enumerated during the search of the best + split. To obtain a deterministic behaviour during fitting, + ``random_state`` has to be fixed. + + References + ---------- + J. Friedman, Greedy Function Approximation: A Gradient Boosting + Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. + + J. Friedman, Stochastic Gradient Boosting, 1999 + + T. Hastie, R. Tibshirani and J. Friedman. + Elements of Statistical Learning Ed. 2, Springer, 2009. + + Examples + -------- + >>> from sklearn.datasets import make_regression + >>> from sklearn.ensemble import GradientBoostingRegressor + >>> from sklearn.model_selection import train_test_split + >>> X, y = make_regression(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> reg = GradientBoostingRegressor(random_state=0) + >>> reg.fit(X_train, y_train) + GradientBoostingRegressor(random_state=0) + >>> reg.predict(X_test[1:2]) + array([-61.1]) + >>> reg.score(X_test, y_test) + 0.4... + + For a detailed example of utilizing + :class:`~sklearn.ensemble.GradientBoostingRegressor` + to fit an ensemble of weak predictive models, please refer to + :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_regression.py`. + """ + + _parameter_constraints: dict = { + **BaseGradientBoosting._parameter_constraints, + "loss": [StrOptions({"squared_error", "absolute_error", "huber", "quantile"})], + "init": [StrOptions({"zero"}), None, HasMethods(["fit", "predict"])], + "alpha": [Interval(Real, 0.0, 1.0, closed="neither")], + } + + def __init__( + self, + *, + loss="squared_error", + learning_rate=0.1, + n_estimators=100, + subsample=1.0, + criterion="friedman_mse", + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0.0, + max_depth=3, + min_impurity_decrease=0.0, + init=None, + random_state=None, + max_features=None, + alpha=0.9, + verbose=0, + max_leaf_nodes=None, + warm_start=False, + validation_fraction=0.1, + n_iter_no_change=None, + tol=1e-4, + ccp_alpha=0.0, + ): + super().__init__( + loss=loss, + learning_rate=learning_rate, + n_estimators=n_estimators, + criterion=criterion, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_depth=max_depth, + init=init, + subsample=subsample, + max_features=max_features, + min_impurity_decrease=min_impurity_decrease, + random_state=random_state, + alpha=alpha, + verbose=verbose, + max_leaf_nodes=max_leaf_nodes, + warm_start=warm_start, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + tol=tol, + ccp_alpha=ccp_alpha, + ) + + def _encode_y(self, y=None, sample_weight=None): + # Just convert y to the expected dtype + self.n_trees_per_iteration_ = 1 + y = y.astype(DOUBLE, copy=False) + return y + + def _get_loss(self, sample_weight): + if self.loss in ("quantile", "huber"): + return _LOSSES[self.loss](sample_weight=sample_weight, quantile=self.alpha) + else: + return _LOSSES[self.loss](sample_weight=sample_weight) + + def predict(self, X): + """Predict regression target for X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + y : ndarray of shape (n_samples,) + The predicted values. + """ + X = validate_data( + self, X, dtype=DTYPE, order="C", accept_sparse="csr", reset=False + ) + # In regression we can directly return the raw value from the trees. + return self._raw_predict(X).ravel() + + def staged_predict(self, X): + """Predict regression target at each stage for X. + + This method allows monitoring (i.e. determine error on testing set) + after each stage. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Yields + ------ + y : generator of ndarray of shape (n_samples,) + The predicted value of the input samples. + """ + for raw_predictions in self._staged_raw_predict(X): + yield raw_predictions.ravel() + + def apply(self, X): + """Apply trees in the ensemble to X, return leaf indices. + + .. versionadded:: 0.17 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, its dtype will be converted to + ``dtype=np.float32``. If a sparse matrix is provided, it will + be converted to a sparse ``csr_matrix``. + + Returns + ------- + X_leaves : array-like of shape (n_samples, n_estimators) + For each datapoint x in X and for each tree in the ensemble, + return the index of the leaf x ends up in each estimator. + """ + + leaves = super().apply(X) + leaves = leaves.reshape(X.shape[0], self.estimators_.shape[0]) + return leaves diff --git a/shared/package-files/02/02908541c673434f33577d9227ce97cafffb8dace5dd728c9899942ed36ab89f/arraysetops.pyi b/shared/package-files/02/02908541c673434f33577d9227ce97cafffb8dace5dd728c9899942ed36ab89f/arraysetops.pyi new file mode 100644 index 0000000000000000000000000000000000000000..877ea667d5202ca06a5e00f3cf75f109585942b1 --- /dev/null +++ b/shared/package-files/02/02908541c673434f33577d9227ce97cafffb8dace5dd728c9899942ed36ab89f/arraysetops.pyi @@ -0,0 +1,68 @@ +import sys +from typing import Any + +import numpy as np +import numpy.typing as npt + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +AR_b: npt.NDArray[np.bool_] +AR_i8: npt.NDArray[np.int64] +AR_f8: npt.NDArray[np.float64] +AR_M: npt.NDArray[np.datetime64] +AR_O: npt.NDArray[np.object_] + +AR_LIKE_f8: list[float] + +assert_type(np.ediff1d(AR_b), npt.NDArray[np.int8]) +assert_type(np.ediff1d(AR_i8, to_end=[1, 2, 3]), npt.NDArray[np.int64]) +assert_type(np.ediff1d(AR_M), npt.NDArray[np.timedelta64]) +assert_type(np.ediff1d(AR_O), npt.NDArray[np.object_]) +assert_type(np.ediff1d(AR_LIKE_f8, to_begin=[1, 1.5]), npt.NDArray[Any]) + +assert_type(np.intersect1d(AR_i8, AR_i8), npt.NDArray[np.int64]) +assert_type(np.intersect1d(AR_M, AR_M, assume_unique=True), npt.NDArray[np.datetime64]) +assert_type(np.intersect1d(AR_f8, AR_i8), npt.NDArray[Any]) +assert_type(np.intersect1d(AR_f8, AR_f8, return_indices=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp], npt.NDArray[np.intp]]) + +assert_type(np.setxor1d(AR_i8, AR_i8), npt.NDArray[np.int64]) +assert_type(np.setxor1d(AR_M, AR_M, assume_unique=True), npt.NDArray[np.datetime64]) +assert_type(np.setxor1d(AR_f8, AR_i8), npt.NDArray[Any]) + +assert_type(np.in1d(AR_i8, AR_i8), npt.NDArray[np.bool_]) +assert_type(np.in1d(AR_M, AR_M, assume_unique=True), npt.NDArray[np.bool_]) +assert_type(np.in1d(AR_f8, AR_i8), npt.NDArray[np.bool_]) +assert_type(np.in1d(AR_f8, AR_LIKE_f8, invert=True), npt.NDArray[np.bool_]) + +assert_type(np.isin(AR_i8, AR_i8), npt.NDArray[np.bool_]) +assert_type(np.isin(AR_M, AR_M, assume_unique=True), npt.NDArray[np.bool_]) +assert_type(np.isin(AR_f8, AR_i8), npt.NDArray[np.bool_]) +assert_type(np.isin(AR_f8, AR_LIKE_f8, invert=True), npt.NDArray[np.bool_]) + +assert_type(np.union1d(AR_i8, AR_i8), npt.NDArray[np.int64]) +assert_type(np.union1d(AR_M, AR_M), npt.NDArray[np.datetime64]) +assert_type(np.union1d(AR_f8, AR_i8), npt.NDArray[Any]) + +assert_type(np.setdiff1d(AR_i8, AR_i8), npt.NDArray[np.int64]) +assert_type(np.setdiff1d(AR_M, AR_M, assume_unique=True), npt.NDArray[np.datetime64]) +assert_type(np.setdiff1d(AR_f8, AR_i8), npt.NDArray[Any]) + +assert_type(np.unique(AR_f8), npt.NDArray[np.float64]) +assert_type(np.unique(AR_LIKE_f8, axis=0), npt.NDArray[Any]) +assert_type(np.unique(AR_f8, return_index=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_LIKE_f8, return_index=True), tuple[npt.NDArray[Any], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_f8, return_inverse=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_LIKE_f8, return_inverse=True), tuple[npt.NDArray[Any], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_f8, return_counts=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_LIKE_f8, return_counts=True), tuple[npt.NDArray[Any], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_f8, return_index=True, return_inverse=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_LIKE_f8, return_index=True, return_inverse=True), tuple[npt.NDArray[Any], npt.NDArray[np.intp], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_f8, return_index=True, return_counts=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_LIKE_f8, return_index=True, return_counts=True), tuple[npt.NDArray[Any], npt.NDArray[np.intp], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_f8, return_inverse=True, return_counts=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_LIKE_f8, return_inverse=True, return_counts=True), tuple[npt.NDArray[Any], npt.NDArray[np.intp], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_f8, return_index=True, return_inverse=True, return_counts=True), tuple[npt.NDArray[np.float64], npt.NDArray[np.intp], npt.NDArray[np.intp], npt.NDArray[np.intp]]) +assert_type(np.unique(AR_LIKE_f8, return_index=True, return_inverse=True, return_counts=True), tuple[npt.NDArray[Any], npt.NDArray[np.intp], npt.NDArray[np.intp], npt.NDArray[np.intp]]) diff --git a/shared/package-files/02/029270fc45bc87c98649a9a21322b6388b6eb92ce5415fcb827d117480279ab4/supported_ops.py b/shared/package-files/02/029270fc45bc87c98649a9a21322b6388b6eb92ce5415fcb827d117480279ab4/supported_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7a670c722744e770767f6c91ac0082b6994e9782 --- /dev/null +++ b/shared/package-files/02/029270fc45bc87c98649a9a21322b6388b6eb92ce5415fcb827d117480279ab4/supported_ops.py @@ -0,0 +1,342 @@ +import inspect +import textwrap + +import torch.jit +from torch.jit._builtins import _find_builtin + +# this file is for generating documentation using sphinx autodoc +# > help(torch.jit.supported_ops) will also give a nice listed of the +# supported ops programmatically + + +def _hidden(name): + return name.startswith("_") and not name.startswith("__") + + +def _emit_type(type): + return str(type) + + +def _emit_arg(indent, i, arg): + v = f"{arg.name} : {_emit_type(arg.type)}" + default = arg.default_value + if default is not None: + v = f"{v}={str(default)}" + if i > 0: + v = f"\n{' ' * indent}{v}" + return v + + +def _emit_args(indent, arguments): + return ",".join(_emit_arg(indent, i, arg) for i, arg in enumerate(arguments)) + + +def _emit_ret(ret): + return _emit_type(ret.type) + + +def _emit_rets(returns): + if len(returns) == 1: + return _emit_ret(returns[0]) + return f"Tuple[{', '.join(_emit_ret(r) for r in returns)}]" + + +def _emit_schema(mod, name, schema, arg_start=0, padding=4): + if mod is None: + qualified_name = name + else: + qualified_name = f"{mod}.{name}" + schema_str = "{}({}) -> {}".format( + qualified_name, + _emit_args(len(qualified_name) + 1 + padding, schema.arguments[arg_start:]), + _emit_rets(schema.returns), + ) + return schema_str + + +def _get_tensor_ops(): + def is_tensor_method(schema): + if len(schema.arguments) == 0: + return False + self = schema.arguments[0] + if self.name != "self": + return False + if not self.type.isSubtypeOf(torch._C.TensorType.get()): + return False + return True + + methods = [] + # discover methods + for elem in dir(torch.Tensor): + if not _hidden(elem): + schemas = torch._C._jit_get_schemas_for_operator("aten::" + elem) + for schema in schemas: + if is_tensor_method(schema): + methods.append(_emit_schema("Tensor", elem, schema, arg_start=1)) + + return "Supported Tensor Methods", methods + + +def _get_nn_functional_ops(): + functions = [] + + # Iterate over torch.nn.functional + mod = torch.nn.functional + name = mod.__name__ + for elem in dir(torch.nn.functional): + attr = getattr(mod, elem) + if not inspect.isfunction(attr) or _hidden(elem[0]): + # Ignore non-functions and internal methods + continue + + attr_module = inspect.getmodule(attr) + if not attr_module: + raise RuntimeError(f"Module for {attr} not found") + + if "torch.nn.functional" not in attr_module.__name__: + # Ignore functions from outside torch.nn.functional + continue + + try: + # compile fn, get schema + scripted = torch.jit.script(attr) + scripted_schema = scripted.schema + functions.append(_emit_schema(name, elem, scripted_schema)) + except: # noqa: B001,E722 + # Skip interpolate / boolean dispatched things + pass + + # Iterate over modules that we know contain a lot of builtins + for mod in torch.jit._builtins._modules_containing_builtins: + name = mod.__name__ + for elem in dir(mod): + builtin = _find_builtin(getattr(mod, elem)) + if builtin is not None: + schemas = torch._C._jit_get_schemas_for_operator(builtin) + for schema in schemas: + # remove _tan but not __and__ + if not _hidden(elem): + functions.append(_emit_schema(name, elem, schema)) + return "Supported PyTorch Functions", functions + + +def _get_builtins_helper(): + builtins = [] + for fn, _builtin_name in torch.jit._builtins._builtin_ops: + mod = inspect.getmodule(fn) + + if not hasattr(fn, "__name__"): + # typing classes + continue + if not mod: + continue + if _hidden(fn.__name__) or _hidden(fn.__qualname__) or _hidden(mod.__name__): + # skip internal-only methods + continue + + if "torch._C" in mod.__name__: + continue + + builtins.append((fn, _builtin_name)) + + return builtins + + +def _is_math_fn(fn): + mod = inspect.getmodule(fn) + if not mod: + raise RuntimeError(f"Module for {fn} not found") + + return mod.__name__ == "math" + + +def _get_torchscript_builtins(): + functions = [] + builtins = filter(lambda fn: not _is_math_fn(fn[0]), _get_builtins_helper()) + builtins_list = list(builtins) + # Iterate over the specially added builtins + for fn, _builtin_name in builtins_list: + mod = inspect.getmodule(fn) + if not mod: + raise RuntimeError(f"Module for {fn} not found") + builtin = _find_builtin(fn) + if builtin is not None: + schemas = torch._C._jit_get_schemas_for_operator(builtin) + for schema in schemas: + functions.append(_emit_schema(mod.__name__, fn.__name__, schema)) + pass + + return "TorchScript Builtin Functions", functions + + +def _get_math_builtins(): + functions = [] + builtins = filter(lambda fn: _is_math_fn(fn[0]), _get_builtins_helper()) + builtins_list = list(builtins) + # Iterate over the specially added builtins + for fn, _builtin_name in builtins_list: + mod = inspect.getmodule(fn) + if not mod: + raise RuntimeError(f"Module for {fn} not found") + builtin = _find_builtin(fn) + if builtin is not None: + schemas = torch._C._jit_get_schemas_for_operator(builtin) + for schema in schemas: + schema_str = _emit_schema(mod.__name__, fn.__name__, schema) + if "Tensor" in schema_str: + # Skip Tensor ops that have the same name as math functions + # (they will show up in the tensor methods section) + continue + functions.append(schema) + pass + + return "``math`` Module", functions + + +def _get_global_builtins(): + # Taken from the 'globals' map in torch/csrc/jit/frontend/ir_emitter.cpp + supported_builtins = [ + "print", + "tuple", + "float", + "complex", + "int", + "bool", + "str", + "getattr", + "hasattr", + "isinstance", + "len", + "hex", + "oct", + "round", + "hash", + "min", + "max", + "abs", + "all", + "divmod", + "list", + "ord", + "chr", + "bin", + "range", + "zip", + "enumerate", + "sorted", + ] + + op_renames = { + "bool": "aten::Bool", + "int": "aten::Int", + "float": "aten::Float", + "complex": "aten::Complex", + "abs": "prim::abs", + "max": "prim::max", + "min": "prim::min", + "range": "fake::does_not_exist", + } + + schemaless_op_explanations = { + "print": "Print any value", + "tuple": "Lists cannot be converted to tuples with this method since their size is not statically known", + "getattr": "Attribute name must be a literal string", + "hasattr": "Attribute name must be a literal string", + "isinstance": "Result is static", + "zip": "Arguments must be iterable. See :ref:`Iterables ` for details.", + "enumerate": "Arguments must be iterable. See :ref:`Iterables ` for details.", + "range": "Can only be used as an iterator in a for loop", + } + + magic_methods = [ + ("complex", "__complex__"), + ("float", "__float__"), + ("int", "__int__"), + ("bool", "__bool__"), + ("str", "__str__"), + ("len", "__len__"), + ("hex", "__hex__"), + ("oct", "__oct__"), + ] + + magic_methods_rows = [] + for fn, magic_method in magic_methods: + magic_methods_rows.append(f'"{fn}", "``{magic_method}``"') + + schematized_ops = [] + schemaless_ops = [] + + for fn in supported_builtins: + op_name = f"aten::{fn}" + if fn in op_renames: + op_name = op_renames[fn] + schemas = torch._C._jit_get_schemas_for_operator(op_name) + for s in schemas: + schematized_ops.append(_emit_schema(None, fn, s, padding=0)) + if len(schemas) > 0: + schematized_ops.append("") + else: + table_row = f'":any:`{fn}`", "{schemaless_op_explanations[fn]}"' + schemaless_ops.append(table_row) + + schematized_ops_str = "\n".join(schematized_ops) + schemaless_ops_str = "\n".join(schemaless_ops) + magic_methods_rows_str = "\n".join(magic_methods_rows) + schematized_ops_str = textwrap.indent(schematized_ops_str, "\t") + schemaless_ops_str = textwrap.indent(schemaless_ops_str, "\t") + magic_methods_rows_str = textwrap.indent(magic_methods_rows_str, "\t") + section = f""" +The functions in the following table are supported but do not have a static schema + +.. csv-table:: + :header: "Function", "Note" + +{schemaless_ops_str} + +The following functions will use the corresponding magic method on :any:`TorchScript classes` + +.. csv-table:: + :header: "Function", "Magic Method" + +{magic_methods_rows_str} + +These built-in functions use the schema + +.. rst-class:: codeblock-height-limiter + +:: + +{schematized_ops_str} + """ + + return "Python Built-in Functions", section + + +def _list_supported_ops(): + def emit_block(decls): + return "\n.. rst-class:: codeblock-height-limiter\n\n::\n\n{}\n".format( + "".join(f" {d}\n\n" for d in decls) + ) + + body = "" + op_gathering_fns = ( + _get_tensor_ops, + _get_nn_functional_ops, + _get_torchscript_builtins, + _get_global_builtins, + _get_math_builtins, + ) + for fn in op_gathering_fns: + header, items = fn() + link_target = header.replace("`", "").replace("-", "").lower().replace(" ", "-") + if isinstance(items, str): + section = f"{header}\n{'~' * len(header)}\n{items}\n" + else: + section = f"{header}\n{'~' * len(header)}\n{emit_block(items)}" + section = f".. _{link_target}:" + "\n\n" + section + body += section + + return body + + +__doc__ = _list_supported_ops() diff --git a/shared/package-files/02/029529be8190e14197388bce4c52247d7c74f939d6b19c4645230dbe5c0241b4/package_streaming.py b/shared/package-files/02/029529be8190e14197388bce4c52247d7c74f939d6b19c4645230dbe5c0241b4/package_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c5b78a0ef6da525d5ee212e01ff355af3231d3 --- /dev/null +++ b/shared/package-files/02/029529be8190e14197388bce4c52247d7c74f939d6b19c4645230dbe5c0241b4/package_streaming.py @@ -0,0 +1,142 @@ +""" +Unpack conda packages without using a temporary file. +""" + +from __future__ import annotations + +import bz2 +import os +import os.path +import tarfile +import zipfile +from enum import Enum +from typing import Generator + +# acquire umask taking advantage of import system lock, instead of possibly in +# multiple threads at once. +UMASK = os.umask(0) +os.umask(UMASK) + +try: + import zstandard +except ImportError: + import warnings + + warnings.warn("zstandard could not be imported. Running without .conda support.") + + zstandard = None + + +class CondaComponent(Enum): + pkg = "pkg" + info = "info" + + def __str__(self): + return self.value + + +class TarfileNoSameOwner(tarfile.TarFile): + def __init__(self, *args, umask=UMASK, **kwargs): + """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to + read from an existing archive, 'a' to append data to an existing + file or 'w' to create a new file overwriting an existing one. `mode' + defaults to 'r'. + If `fileobj' is given, it is used for reading or writing data. If it + can be determined, `mode' is overridden by `fileobj's mode. + `fileobj' is not closed, when TarFile is closed. + """ + super().__init__(*args, **kwargs) + self.umask = umask + + def chown(self, tarinfo, targetpath, numeric_owner): + """ + Override chown to be a no-op, since we don't want to preserve ownership + here. (tarfile.TarFile only lets us toggle all of (chown, chmod, mtime)) + """ + return + + def chmod(self, tarinfo, targetpath): + """ + Set file permissions of targetpath according to tarinfo, respecting + umask. + """ + try: + os.chmod(targetpath, tarinfo.mode & (0o777 - self.umask)) + except OSError as e: + raise tarfile.ExtractError("could not change mode") from e + + +def tar_generator( + fileobj, tarfile_open=TarfileNoSameOwner.open, closefd=False +) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo], None, None]: + """ + Yield (tar, member) from fileobj. + """ + # tarfile will not close fileobj because _extfileobj is True + # caller should take care to close files all the way back to the http request... + try: + with tarfile_open(fileobj=fileobj, mode="r|") as tar: + for member in tar: + yield tar, member + finally: + if closefd: + fileobj.close() + + +def stream_conda_info( + filename, fileobj=None +) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo], None, None]: + """ + Yield members from conda's embedded info/ tarball. + + For .tar.bz2 packages, yield all members. + + Yields (tar, member) tuples. You must only use the current member to + prevent tar seeks and scans. + + To extract to disk, it's possible to call ``tar.extractall(path)`` on the + first result and then ignore the rest of this generator. ``extractall`` takes + care of some directory permissions/mtime issues, compared to ``extract`` or + writing out the file objects yourself. + """ + component = "info" + return stream_conda_component(filename, fileobj, component) + + +def stream_conda_component( + filename, fileobj=None, component: CondaComponent | str = CondaComponent.pkg +) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo], None, None]: + """ + Yield members from .conda's embedded {component}- tarball. "info" or "pkg". + + For .tar.bz2 packages, yield all members. + + Yields (tar, member) tuples. You must only use the current member to + prevent tar seeks and scans. + + To extract to disk, it's possible to call ``tar.extractall(path)`` on the + first result and then ignore the rest of this generator. ``extractall`` takes + care of some directory permissions/mtime issues, compared to ``extract`` or + writing out the file objects yourself. + """ + if str(filename).endswith(".conda"): + if zstandard is None: + raise RuntimeError("Cannot unpack `.conda` without zstandard") + + zf = zipfile.ZipFile(fileobj or filename) + file_id, _, _ = os.path.basename(filename).rpartition(".") + component_name = f"{component}-{file_id}" + component_filename = [ + info for info in zf.infolist() if info.filename.startswith(component_name) + ] + if not component_filename: + raise LookupError(f"didn't find {component_name} component in {filename}") + assert len(component_filename) == 1 + reader = zstandard.ZstdDecompressor().stream_reader( + zf.open(component_filename[0]) + ) + elif str(filename).endswith(".tar.bz2"): + reader = bz2.open(fileobj or filename, mode="rb") + else: + raise ValueError("unsupported file extension") + return tar_generator(reader, closefd=fileobj is None) diff --git a/shared/package-files/02/0295da66c294f24365247a7e43184f766973885bf7a2869ead47e254f9872348/__init__.py b/shared/package-files/02/0295da66c294f24365247a7e43184f766973885bf7a2869ead47e254f9872348/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7be705ac97d431e0c400f4a2499532ab35de5a7d --- /dev/null +++ b/shared/package-files/02/0295da66c294f24365247a7e43184f766973885bf7a2869ead47e254f9872348/__init__.py @@ -0,0 +1,29 @@ +from ...deprecations import deprecated +deprecated.module("23.3", "23.9", addendum="Use `toolz`/`cytoolz` instead.") + +try: + from cytoolz import __version__ as cytoolz_version + if tuple(int(x) for x in cytoolz_version.split(".")) < (0, 8, 2): + raise ImportError() + from cytoolz.itertoolz import * + from cytoolz.dicttoolz import * + from cytoolz.functoolz import excepts +except (ImportError, ValueError): + from .itertoolz import * + from .dicttoolz import * + + # Importing from toolz.functoolz is slow since it imports inspect. + # Copy the relevant part of excepts' implementation instead: + class excepts(object): + def __init__(self, exc, func, handler=lambda exc: None): + self.exc = exc + self.func = func + self.handler = handler + + def __call__(self, *args, **kwargs): + try: + return self.func(*args, **kwargs) + except self.exc as e: + return self.handler(e) + +__version__ = '0.9.0' diff --git a/shared/package-files/02/02995399957b4d2ee78af53cbde81bb2d30de4c74cbf8534249759e0879e0393/false_positives.pyi b/shared/package-files/02/02995399957b4d2ee78af53cbde81bb2d30de4c74cbf8534249759e0879e0393/false_positives.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7a2e016245a60cd163bf64222f3a6c8fb7514283 --- /dev/null +++ b/shared/package-files/02/02995399957b4d2ee78af53cbde81bb2d30de4c74cbf8534249759e0879e0393/false_positives.pyi @@ -0,0 +1,18 @@ +import sys +from typing import Any + +import numpy as np +import numpy.typing as npt + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +AR_Any: npt.NDArray[Any] + +# Mypy bug where overload ambiguity is ignored for `Any`-parametrized types; +# xref numpy/numpy#20099 and python/mypy#11347 +# +# The expected output would be something akin to `npt.NDArray[Any]` +assert_type(AR_Any + 2, npt.NDArray[np.signedinteger[Any]]) diff --git a/shared/package-files/02/029a9d47414c9db83d15da6981a909e4b5f13eca7215fc0a5cd89af07baededf/_async.py b/shared/package-files/02/029a9d47414c9db83d15da6981a909e4b5f13eca7215fc0a5cd89af07baededf/_async.py new file mode 100644 index 0000000000000000000000000000000000000000..2134975bb953be85414f9a950c59d483df4847d7 --- /dev/null +++ b/shared/package-files/02/029a9d47414c9db83d15da6981a909e4b5f13eca7215fc0a5cd89af07baededf/_async.py @@ -0,0 +1,101 @@ +"""Async API. + +This module contains the API for parallelism in TorchScript, notably: + * torch.jit.fork + * torch.jit.wait + +This is not intended to be imported directly; please use the exposed +functionalities in `torch.jit`. +""" + +import torch +from torch._jit_internal import Future +from torch.jit._builtins import _register_builtin + +from torch.utils import set_module + +set_module(Future, "torch.jit") + + +def fork(func, *args, **kwargs): + r""" + Create an asynchronous task executing `func` and a reference to the value of the result of this execution. + + `fork` will return immediately, so the return value of `func` may not have been computed yet. To force completion + of the task and access the return value invoke `torch.jit.wait` on the Future. `fork` invoked + with a `func` which returns `T` is typed as `torch.jit.Future[T]`. `fork` calls can be arbitrarily + nested, and may be invoked with positional and keyword arguments. + Asynchronous execution will only occur when run in TorchScript. If run in pure python, + `fork` will not execute in parallel. `fork` will also not execute in parallel when invoked + while tracing, however the `fork` and `wait` calls will be captured in the exported IR Graph. + + .. warning:: + `fork` tasks will execute non-deterministically. We recommend only spawning + parallel fork tasks for pure functions that do not modify their inputs, + module attributes, or global state. + + Args: + func (callable or torch.nn.Module): A Python function or `torch.nn.Module` + that will be invoked. If executed in TorchScript, it will execute asynchronously, + otherwise it will not. Traced invocations of fork will be captured in the IR. + ``*args``, ``**kwargs``: arguments to invoke `func` with. + Returns: + `torch.jit.Future[T]`: a reference to the execution of `func`. The value `T` + can only be accessed by forcing completion of `func` through `torch.jit.wait`. + + Example (fork a free function): + + .. code-block:: python + + import torch + from torch import Tensor + def foo(a : Tensor, b : int) -> Tensor: + return a + b + def bar(a): + fut : torch.jit.Future[Tensor] = torch.jit.fork(foo, a, b=2) + return torch.jit.wait(fut) + script_bar = torch.jit.script(bar) + input = torch.tensor(2) + # only the scripted version executes asynchronously + assert script_bar(input) == bar(input) + # trace is not run asynchronously, but fork is captured in IR + graph = torch.jit.trace(bar, (input,)).graph + assert "fork" in str(graph) + + Example (fork a module method): + + .. code-block:: python + + import torch + from torch import Tensor + class AddMod(torch.nn.Module): + def forward(self, a: Tensor, b : int): + return a + b + class Mod(torch.nn.Module): + def __init__(self): + super(self).__init__() + self.mod = AddMod() + def forward(self, input): + fut = torch.jit.fork(self.mod, a, b=2) + return torch.jit.wait(fut) + input = torch.tensor(2) + mod = Mod() + assert mod(input) == torch.jit.script(mod).forward(input) + """ + return torch._C.fork(func, *args, **kwargs) + + +def wait(future): + r""" + Force completion of a `torch.jit.Future[T]` asynchronous task, returning the result of the task. + + See :func:`~fork` for docs and examples. + Args: + future (torch.jit.Future[T]): an asynchronous task reference, created through `torch.jit.fork` + Returns: + `T`: the return value of the completed task + """ + return torch._C.wait(future) + + +_register_builtin(wait, "aten::wait") diff --git a/shared/package-files/02/029bb47715d5c8f7723c49f02985edd5f6690c0ca2cdd8cfb110f95b8876e20e/Functions.h b/shared/package-files/02/029bb47715d5c8f7723c49f02985edd5f6690c0ca2cdd8cfb110f95b8876e20e/Functions.h new file mode 100644 index 0000000000000000000000000000000000000000..8327d00ece5c0f2b2c1e81f88e54fa0c76d9e97d --- /dev/null +++ b/shared/package-files/02/029bb47715d5c8f7723c49f02985edd5f6690c0ca2cdd8cfb110f95b8876e20e/Functions.h @@ -0,0 +1,1427 @@ +#pragma once + +// @generated by torchgen/gen.py from Functions.h + +#ifdef TORCH_ASSERT_NO_OPERATORS +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if your change would be better placed in \ + another file, or if a more specific header might achieve the same goal. \ + See NOTE: [Tensor vs. TensorBase] +#endif + +#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS) +#error This change adds a dependency on all pytorch operators, meaning the \ + file will need to be re-compiled every time an operator is changed or added. \ + Consider including a specific operator from and \ + see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS]. +#endif + +// NOTE: [TORCH_ASSERT_ONLY_METHOD_OPERATORS] +// +// In ATen, certain generated headers files include the definitions of +// every single operator in PyTorch. Unfortunately this means every +// time an operator signature is updated or changed in +// native_functions.yaml, you (and every other PyTorch developer) need +// to recompile every source file that includes any of these headers. +// +// To break up these header dependencies, and improve incremental +// build times for all PyTorch developers. These headers are split +// into per-operator headers in the `ATen/ops` folder. This limits +// incremental builds to only changes to methods of `Tensor`, or files +// that use the specific operator being changed. With `at::sum` as an +// example, you should include +// +// // instead of ATen/Functions.h +// // instead of ATen/NativeFunctions.h +// // instead of ATen/Operators.h +// // instead of ATen/CPUFunctions.h +// +// However, even if you're careful to use this in your own code. +// `Functions.h` might be included indirectly through another header +// without you realising. To avoid this, you can add +// +// #define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// +// to the top of your source file. This way any time the non-specific +// headers are included, the compiler will error out. +// +// Also, be aware that `ops` are not available in all build +// configurations (namely fb-internal) so you must guard these +// includes with `#ifdef AT_PER_OPERATOR_HEADERS`. e.g. +// +// #ifndef AT_PER_OPERATOR_HEADERS +// #include +// #else +// #include +// #endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 + +namespace at { + + + +// Special C++ only overloads for std()-like functions (See gh-40287) +// These are needed because int -> bool conversion takes precedence over int -> IntArrayRef +// So, for example std(0) would select the std(unbiased=False) overload +TORCH_API inline Tensor var(const Tensor& self, int dim) { + return at::var(self, IntArrayRef{dim}); +} +TORCH_API inline std::tuple var_mean(const Tensor& self, int dim) { + return at::var_mean(self, IntArrayRef{dim}); +} +TORCH_API inline Tensor std(const Tensor& self, int dim) { + return at::std(self, IntArrayRef{dim}); +} +TORCH_API inline std::tuple std_mean(const Tensor& self, int dim) { + return at::std_mean(self, IntArrayRef{dim}); +} + +inline int64_t numel(const Tensor& tensor) { + return tensor.numel(); +} + +inline int64_t size(const Tensor& tensor, int64_t dim) { + return tensor.size(dim); +} + +inline int64_t stride(const Tensor& tensor, int64_t dim) { + return tensor.stride(dim); +} + +inline bool is_complex(const Tensor& tensor) { + return tensor.is_complex(); +} + +inline bool is_floating_point(const Tensor& tensor) { + return tensor.is_floating_point(); +} + +inline bool is_signed(const Tensor& tensor) { + return tensor.is_signed(); +} + +inline bool is_inference(const Tensor& tensor) { + return tensor.is_inference(); +} + +inline bool _is_zerotensor(const Tensor& tensor) { + return tensor._is_zerotensor(); +} + +inline bool is_conj(const Tensor& tensor) { + return tensor.is_conj(); +} + +inline Tensor conj(const Tensor& tensor) { + return tensor.conj(); +} + +inline bool is_neg(const Tensor& tensor) { + return tensor.is_neg(); +} + +} diff --git a/shared/package-files/02/029dbb1f5804138ddf2d1b51e11aad2790670525a8c5e50a6218f8bb63ada875/_reachability.pyx b/shared/package-files/02/029dbb1f5804138ddf2d1b51e11aad2790670525a8c5e50a6218f8bb63ada875/_reachability.pyx new file mode 100644 index 0000000000000000000000000000000000000000..bff686ae0a6369a7891525433a3fd79341dd2022 --- /dev/null +++ b/shared/package-files/02/029dbb1f5804138ddf2d1b51e11aad2790670525a8c5e50a6218f8bb63ada875/_reachability.pyx @@ -0,0 +1,210 @@ +# mutual reachability distance computations + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +cimport numpy as cnp + +import numpy as np +from scipy.sparse import issparse +from cython cimport floating, integral +from libc.math cimport isfinite, INFINITY +from ...utils._typedefs cimport intp_t +cnp.import_array() + + +def mutual_reachability_graph( + distance_matrix, min_samples=5, max_distance=0.0 +): + """Compute the weighted adjacency matrix of the mutual reachability graph. + + The mutual reachability distance used to build the graph is defined as:: + + max(d_core(x_p), d_core(x_q), d(x_p, x_q)) + + and the core distance `d_core` is defined as the distance between a point + `x_p` and its k-th nearest neighbor. + + Note that all computations are done in-place. + + Parameters + ---------- + distance_matrix : {ndarray, sparse matrix} of shape (n_samples, n_samples) + Array of distances between samples. If sparse, the array must be in + `CSR` format. + + min_samples : int, default=5 + The parameter `k` used to calculate the distance between a point + `x_p` and its k-th nearest neighbor. + + max_distance : float, default=0.0 + The distance which `np.inf` is replaced with. When the true mutual- + reachability distance is measured to be infinite, it is instead + truncated to `max_dist`. Only used when `distance_matrix` is a sparse + matrix. + + Returns + ------- + mututal_reachability_graph: {ndarray, sparse matrix} of shape \ + (n_samples, n_samples) + Weighted adjacency matrix of the mutual reachability graph. + + References + ---------- + .. [1] Campello, R. J., Moulavi, D., & Sander, J. (2013, April). + Density-based clustering based on hierarchical density estimates. + In Pacific-Asia Conference on Knowledge Discovery and Data Mining + (pp. 160-172). Springer Berlin Heidelberg. + """ + further_neighbor_idx = min_samples - 1 + if issparse(distance_matrix): + if distance_matrix.format != "csr": + raise ValueError( + "Only sparse CSR matrices are supported for `distance_matrix`." + ) + _sparse_mutual_reachability_graph( + distance_matrix.data, + distance_matrix.indices, + distance_matrix.indptr, + distance_matrix.shape[0], + further_neighbor_idx=further_neighbor_idx, + max_distance=max_distance, + ) + else: + _dense_mutual_reachability_graph( + distance_matrix, further_neighbor_idx=further_neighbor_idx + ) + return distance_matrix + + +def _dense_mutual_reachability_graph( + floating[:, :] distance_matrix, + intp_t further_neighbor_idx, +): + """Dense implementation of mutual reachability graph. + + The computation is done in-place, i.e. the distance matrix is modified + directly. + + Parameters + ---------- + distance_matrix : ndarray of shape (n_samples, n_samples) + Array of distances between samples. + + further_neighbor_idx : int + The index of the furthest neighbor to use to define the core distances. + """ + cdef: + intp_t i, j, n_samples = distance_matrix.shape[0] + floating mutual_reachability_distance + floating[::1] core_distances + + # We assume that the distance matrix is symmetric. We choose to sort every + # row to have the same implementation than the sparse case that requires + # CSR matrix. + core_distances = np.ascontiguousarray( + np.partition( + distance_matrix, further_neighbor_idx, axis=1 + )[:, further_neighbor_idx] + ) + + with nogil: + # TODO: Update w/ prange with thread count based on + # _openmp_effective_n_threads + for i in range(n_samples): + for j in range(n_samples): + mutual_reachability_distance = max( + core_distances[i], + core_distances[j], + distance_matrix[i, j], + ) + distance_matrix[i, j] = mutual_reachability_distance + + +def _sparse_mutual_reachability_graph( + cnp.ndarray[floating, ndim=1, mode="c"] data, + cnp.ndarray[integral, ndim=1, mode="c"] indices, + cnp.ndarray[integral, ndim=1, mode="c"] indptr, + intp_t n_samples, + intp_t further_neighbor_idx, + floating max_distance, +): + """Sparse implementation of mutual reachability graph. + + The computation is done in-place, i.e. the distance matrix is modified + directly. This implementation only accepts `CSR` format sparse matrices. + + Parameters + ---------- + distance_matrix : sparse matrix of shape (n_samples, n_samples) + Sparse matrix of distances between samples. The sparse format should + be `CSR`. + + further_neighbor_idx : int + The index of the furthest neighbor to use to define the core distances. + + max_distance : float + The distance which `np.inf` is replaced with. When the true mutual- + reachability distance is measured to be infinite, it is instead + truncated to `max_dist`. Only used when `distance_matrix` is a sparse + matrix. + """ + cdef: + integral i, col_ind, row_ind + floating mutual_reachability_distance + floating[:] core_distances + floating[:] row_data + + if floating is float: + dtype = np.float32 + else: + dtype = np.float64 + + core_distances = np.empty(n_samples, dtype=dtype) + + for i in range(n_samples): + row_data = data[indptr[i]:indptr[i + 1]] + if further_neighbor_idx < row_data.size: + core_distances[i] = np.partition( + row_data, further_neighbor_idx + )[further_neighbor_idx] + else: + core_distances[i] = INFINITY + + with nogil: + for row_ind in range(n_samples): + for i in range(indptr[row_ind], indptr[row_ind + 1]): + col_ind = indices[i] + mutual_reachability_distance = max( + core_distances[row_ind], core_distances[col_ind], data[i] + ) + if isfinite(mutual_reachability_distance): + data[i] = mutual_reachability_distance + elif max_distance > 0: + data[i] = max_distance diff --git a/shared/package-files/02/02a08581dae2119447caac10a900313398e82c3e36a154ecc6ac2c9831728bcc/errors.py b/shared/package-files/02/02a08581dae2119447caac10a900313398e82c3e36a154ecc6ac2c9831728bcc/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..ac397e1bfdefcb3762210759691362ec331797dc --- /dev/null +++ b/shared/package-files/02/02a08581dae2119447caac10a900313398e82c3e36a154ecc6ac2c9831728bcc/errors.py @@ -0,0 +1,60 @@ +# Top-level error and warning classes + + +class FormulaicError(Exception): + pass + + +class FormulaicWarning(Warning): + pass + + +# Formula parsing errors + + +class FormulaInvalidError(FormulaicError): + """ + Provided formula specification is not a valid format. + """ + + +class FormulaParsingError(FormulaicError): + """ + An error occured during the parsing of a formula specification. + """ + + +class FormulaSyntaxError(FormulaParsingError): + """ + Could not tokenize the nominated formula specification. + """ + + +# Formula materializer meta-errors + + +class FormulaMaterializerInvalidError(FormulaicError): + pass + + +class FormulaMaterializerNotFoundError(FormulaicError): + pass + + +# Data materialization errors and warnings + + +class FormulaMaterializationError(FormulaicError): + pass + + +class FactorEncodingError(FormulaMaterializationError): + pass + + +class FactorEvaluationError(FormulaMaterializationError): + pass + + +class DataMismatchWarning(FormulaicWarning): + pass diff --git a/shared/package-files/02/02a15295b631a70a2c5f982f229afb97576d35182fa2b0fc0fdfdd6a0c2a7554/hooks.py b/shared/package-files/02/02a15295b631a70a2c5f982f229afb97576d35182fa2b0fc0fdfdd6a0c2a7554/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..f73c5657638605ae62a5969559ccb80e882134b9 --- /dev/null +++ b/shared/package-files/02/02a15295b631a70a2c5f982f229afb97576d35182fa2b0fc0fdfdd6a0c2a7554/hooks.py @@ -0,0 +1,173 @@ +"""Hooks for IPython. + +In Python, it is possible to overwrite any method of any object if you really +want to. But IPython exposes a few 'hooks', methods which are *designed* to +be overwritten by users for customization purposes. This module defines the +default versions of all such hooks, which get used by IPython if not +overridden by the user. + +Hooks are simple functions, but they should be declared with ``self`` as their +first argument, because when activated they are registered into IPython as +instance methods. The self argument will be the IPython running instance +itself, so hooks have full access to the entire IPython object. + +If you wish to define a new hook and activate it, you can make an :doc:`extension +` or a :ref:`startup script `. For +example, you could use a startup file like this:: + + import os + + def calljed(self,filename, linenum): + "My editor hook calls the jed editor directly." + print "Calling my own editor, jed ..." + if os.system('jed +%d %s' % (linenum,filename)) != 0: + raise TryNext() + + def load_ipython_extension(ip): + ip.set_hook('editor', calljed) + +""" + +#***************************************************************************** +# Copyright (C) 2005 Fernando Perez. +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#***************************************************************************** + +import os +import subprocess +import sys + +from .error import TryNext + +# List here all the default hooks. For now it's just the editor functions +# but over time we'll move here all the public API for user-accessible things. + +__all__ = [ + "editor", + "synchronize_with_editor", + "show_in_pager", + "pre_prompt_hook", + "clipboard_get", +] + +deprecated = {'pre_run_code_hook': "a callback for the 'pre_execute' or 'pre_run_cell' event", + 'late_startup_hook': "a callback for the 'shell_initialized' event", + 'shutdown_hook': "the atexit module", + } + +def editor(self, filename, linenum=None, wait=True): + """Open the default editor at the given filename and linenumber. + + This is IPython's default editor hook, you can use it as an example to + write your own modified one. To set your own editor function as the + new editor hook, call ip.set_hook('editor',yourfunc).""" + + # IPython configures a default editor at startup by reading $EDITOR from + # the environment, and falling back on vi (unix) or notepad (win32). + editor = self.editor + + # marker for at which line to open the file (for existing objects) + if linenum is None or editor=='notepad': + linemark = '' + else: + linemark = '+%d' % int(linenum) + + # Enclose in quotes if necessary and legal + if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': + editor = '"%s"' % editor + + # Call the actual editor + proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename), + shell=True) + if wait and proc.wait() != 0: + raise TryNext() + + +def synchronize_with_editor(self, filename, linenum, column): + pass + + +class CommandChainDispatcher: + """ Dispatch calls to a chain of commands until some func can handle it + + Usage: instantiate, execute "add" to add commands (with optional + priority), execute normally via f() calling mechanism. + + """ + def __init__(self,commands=None): + if commands is None: + self.chain = [] + else: + self.chain = commands + + + def __call__(self,*args, **kw): + """ Command chain is called just like normal func. + + This will call all funcs in chain with the same args as were given to + this function, and return the result of first func that didn't raise + TryNext""" + last_exc = TryNext() + for prio,cmd in self.chain: + #print "prio",prio,"cmd",cmd #dbg + try: + return cmd(*args, **kw) + except TryNext as exc: + last_exc = exc + # if no function will accept it, raise TryNext up to the caller + raise last_exc + + def __str__(self): + return str(self.chain) + + def add(self, func, priority=0): + """ Add a func to the cmd chain with given priority """ + self.chain.append((priority, func)) + self.chain.sort(key=lambda x: x[0]) + + def __iter__(self): + """ Return all objects in chain. + + Handy if the objects are not callable. + """ + return iter(self.chain) + + +def show_in_pager(self, data, start, screen_lines): + """ Run a string through pager """ + # raising TryNext here will use the default paging functionality + raise TryNext + + +def pre_prompt_hook(self): + """ Run before displaying the next prompt + + Use this e.g. to display output from asynchronous operations (in order + to not mess up text entry) + """ + + return None + + +def clipboard_get(self): + """ Get text from the clipboard. + """ + from ..lib.clipboard import ( + osx_clipboard_get, + tkinter_clipboard_get, + win32_clipboard_get, + wayland_clipboard_get, + ) + if sys.platform == 'win32': + chain = [win32_clipboard_get, tkinter_clipboard_get] + elif sys.platform == 'darwin': + chain = [osx_clipboard_get, tkinter_clipboard_get] + else: + chain = [wayland_clipboard_get, tkinter_clipboard_get] + dispatcher = CommandChainDispatcher() + for func in chain: + dispatcher.add(func) + text = dispatcher() + return text diff --git a/shared/package-files/02/02a353f89c0380371c9b541a799691c8dffc81e98459c8a4bcc1c841084dbc7c/ecoutils.py b/shared/package-files/02/02a353f89c0380371c9b541a799691c8dffc81e98459c8a4bcc1c841084dbc7c/ecoutils.py new file mode 100644 index 0000000000000000000000000000000000000000..91b9412dbbeabc59dd14089ccb31e2a0594531ed --- /dev/null +++ b/shared/package-files/02/02a353f89c0380371c9b541a799691c8dffc81e98459c8a4bcc1c841084dbc7c/ecoutils.py @@ -0,0 +1,521 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""As a programming ecosystem grows, so do the chances of runtime +variability. + +Python boasts one of the widest deployments for a high-level +programming environment, making it a viable target for all manner of +application. But with breadth comes variance, so it's important to +know what you're working with. + +Some basic variations that are common among development machines: + +* **Executable runtime**: CPython, PyPy, Jython, etc., plus build date and compiler +* **Language version**: 2.4, 2.5, 2.6, 2.7... 3.4, 3.5, 3.6 +* **Host operating system**: Windows, OS X, Ubuntu, Debian, CentOS, RHEL, etc. +* **Features**: 64-bit, IPv6, Unicode character support (UCS-2/UCS-4) +* **Built-in library support**: OpenSSL, threading, SQLite, zlib +* **User environment**: umask, ulimit, working directory path +* **Machine info**: CPU count, hostname, filesystem encoding + +See the full example profile below for more. + +ecoutils was created to quantify that variability. ecoutils quickly +produces an information-dense description of critical runtime factors, +with minimal side effects. In short, ecoutils is like browser and user +agent analytics, but for Python environments. + +Transmission and collection +--------------------------- + +The data is all JSON serializable, and is suitable for sending to a +central analytics server. An HTTP-backed service for this can be found +at: https://github.com/mahmoud/espymetrics/ + +Notable omissions +----------------- + +Due to space constraints (and possibly latency constraints), the +following information is deemed not dense enough, and thus omitted: + +* :data:`sys.path` +* full :mod:`sysconfig` +* environment variables (:data:`os.environ`) + +Compatibility +------------- + +So far ecoutils has has been tested on Python 2.4, 2.5, 2.6, 2.7, 3.4, +3.5, and PyPy. Various versions have been tested on Ubuntu, Debian, +RHEL, OS X, FreeBSD, and Windows 7. + +.. note:: Boltons typically only support back to Python 2.6, but due + to its nature, ecoutils extends backwards compatibility to Python + 2.4 and 2.5. + +Profile generation +------------------ + +Profiles are generated by :func:`ecoutils.get_profile`. + +When run as a module, ecoutils will call :func:`~ecoutils.get_profile` +and print a profile in JSON format:: + + $ python -m boltons.ecoutils + { + "_eco_version": "1.0.0", + "cpu_count": 4, + "cwd": "/home/mahmoud/projects/boltons", + "fs_encoding": "UTF-8", + "guid": "6b139e7bbf5ad4ed8d4063bf6235b4d2", + "hostfqdn": "mahmoud-host", + "hostname": "mahmoud-host", + "linux_dist_name": "Ubuntu", + "linux_dist_version": "14.04", + "python": { + "argv": "boltons/ecoutils.py", + "bin": "/usr/bin/python", + "build_date": "Jun 22 2015 17:58:13", + "compiler": "GCC 4.8.2", + "features": { + "64bit": true, + "expat": "expat_2.1.0", + "ipv6": true, + "openssl": "OpenSSL 1.0.1f 6 Jan 2014", + "readline": true, + "sqlite": "3.8.2", + "threading": true, + "tkinter": "8.6", + "unicode_wide": true, + "zlib": "1.2.8" + }, + "version": "2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]", + "version_info": [ + 2, + 7, + 6, + "final", + 0 + ] + }, + "time_utc": "2016-05-24 07:59:40.473140", + "time_utc_offset": -8.0, + "ulimit_hard": 4096, + "ulimit_soft": 1024, + "umask": "002", + "uname": { + "machine": "x86_64", + "node": "mahmoud-host", + "processor": "x86_64", + "release": "3.13.0-85-generic", + "system": "Linux", + "version": "#129-Ubuntu SMP Thu Mar 17 20:50:15 UTC 2016" + }, + "username": "mahmoud" + } + +``pip install boltons`` and try it yourself! + +""" + +import re +import os +import sys +import time +import pprint +import random +import socket +import struct +import getpass +import datetime +import platform + +ECO_VERSION = '1.0.1' # see version history below + +PY_GT_2 = sys.version_info[0] > 2 + +try: + getrandbits = random.SystemRandom().getrandbits + HAVE_URANDOM = True +except Exception: + HAVE_URANDOM = False + getrandbits = random.getrandbits + + +# 128-bit GUID just like a UUID, but backwards compatible to 2.4 +INSTANCE_ID = hex(getrandbits(128))[2:-1].lower() + +IS_64BIT = struct.calcsize("P") > 4 +HAVE_UCS4 = getattr(sys, 'maxunicode', 0) > 65536 +HAVE_READLINE = True + +try: + import readline +except Exception: + HAVE_READLINE = False + +try: + import sqlite3 + SQLITE_VERSION = sqlite3.sqlite_version +except Exception: + # note: 2.5 and older have sqlite, but not sqlite3 + SQLITE_VERSION = '' + + +try: + + import ssl + try: + OPENSSL_VERSION = ssl.OPENSSL_VERSION + except AttributeError: + # This is a conservative estimate for Python <2.6 + # SSL module added in 2006, when 0.9.7 was standard + OPENSSL_VERSION = 'OpenSSL >0.8.0' +except Exception: + OPENSSL_VERSION = '' + + +try: + if PY_GT_2: + import tkinter + else: + import Tkinter as tkinter + TKINTER_VERSION = str(tkinter.TkVersion) +except Exception: + TKINTER_VERSION = '' + + +try: + import zlib + ZLIB_VERSION = zlib.ZLIB_VERSION +except Exception: + ZLIB_VERSION = '' + + +try: + from xml.parsers import expat + EXPAT_VERSION = expat.EXPAT_VERSION +except Exception: + EXPAT_VERSION = '' + + +try: + from multiprocessing import cpu_count + CPU_COUNT = cpu_count() +except Exception: + CPU_COUNT = 0 + +try: + import threading + HAVE_THREADING = True +except Exception: + HAVE_THREADING = False + + +try: + HAVE_IPV6 = socket.has_ipv6 +except Exception: + HAVE_IPV6 = False + + +try: + from resource import getrlimit, RLIMIT_NOFILE + RLIMIT_FDS_SOFT, RLIMIT_FDS_HARD = getrlimit(RLIMIT_NOFILE) +except Exception: + RLIMIT_FDS_SOFT, RLIMIT_FDS_HARD = 0, 0 + + +START_TIME_INFO = {'time_utc': str(datetime.datetime.utcnow()), + 'time_utc_offset': -time.timezone / 3600.0} + + +def get_python_info(): + ret = {} + ret['argv'] = _escape_shell_args(sys.argv) + ret['bin'] = sys.executable + + # Even though compiler/build_date are already here, they're + # actually parsed from the version string. So, in the rare case of + # the unparsable version string, we're still transmitting it. + ret['version'] = ' '.join(sys.version.split()) + + ret['compiler'] = platform.python_compiler() + ret['build_date'] = platform.python_build()[1] + ret['version_info'] = list(sys.version_info) + + ret['features'] = {'openssl': OPENSSL_VERSION, + 'expat': EXPAT_VERSION, + 'sqlite': SQLITE_VERSION, + 'tkinter': TKINTER_VERSION, + 'zlib': ZLIB_VERSION, + 'unicode_wide': HAVE_UCS4, + 'readline': HAVE_READLINE, + '64bit': IS_64BIT, + 'ipv6': HAVE_IPV6, + 'threading': HAVE_THREADING, + 'urandom': HAVE_URANDOM} + + return ret + + +def get_profile(**kwargs): + """The main entrypoint to ecoutils. Calling this will return a + JSON-serializable dictionary of information about the current + process. + + It is very unlikely that the information returned will change + during the lifetime of the process, and in most cases the majority + of the information stays the same between runs as well. + + :func:`get_profile` takes one optional keyword argument, *scrub*, + a :class:`bool` that, if True, blanks out identifiable + information. This includes current working directory, hostname, + Python executable path, command-line arguments, and + username. Values are replaced with '-', but for compatibility keys + remain in place. + + """ + scrub = kwargs.pop('scrub', False) + if kwargs: + raise TypeError('unexpected keyword arguments: %r' % (kwargs.keys(),)) + ret = {} + try: + ret['username'] = getpass.getuser() + except Exception: + ret['username'] = '' + ret['guid'] = str(INSTANCE_ID) + ret['hostname'] = socket.gethostname() + ret['hostfqdn'] = socket.getfqdn() + uname = platform.uname() + ret['uname'] = {'system': uname[0], + 'node': uname[1], + 'release': uname[2], # linux: distro name + 'version': uname[3], # linux: kernel version + 'machine': uname[4], + 'processor': uname[5]} + try: + linux_dist = platform.linux_distribution() + except Exception: + linux_dist = ('', '', '') + ret['linux_dist_name'] = linux_dist[0] + ret['linux_dist_version'] = linux_dist[1] + ret['cpu_count'] = CPU_COUNT + + ret['fs_encoding'] = sys.getfilesystemencoding() + ret['ulimit_soft'] = RLIMIT_FDS_SOFT + ret['ulimit_hard'] = RLIMIT_FDS_HARD + ret['cwd'] = os.getcwd() + ret['umask'] = oct(os.umask(os.umask(2))).rjust(3, '0') + + ret['python'] = get_python_info() + ret.update(START_TIME_INFO) + ret['_eco_version'] = ECO_VERSION + + if scrub: + # mask identifiable information + ret['cwd'] = '-' + ret['hostname'] = '-' + ret['hostfqdn'] = '-' + ret['python']['bin'] = '-' + ret['python']['argv'] = '-' + ret['uname']['node'] = '-' + ret['username'] = '-' + + return ret + + +try: + import json + + def dumps(val, indent): + if indent: + return json.dumps(val, sort_keys=True, indent=indent) + return json.dumps(val, sort_keys=True) + +except ImportError: + _real_safe_repr = pprint._safe_repr + + def _fake_json_dumps(val, indent=2): + # never do this. this is a hack for Python 2.4. Python 2.5 added + # the json module for a reason. + def _fake_safe_repr(*a, **kw): + res, is_read, is_rec = _real_safe_repr(*a, **kw) + if res == 'None': + res = 'null' + if res == 'True': + res = 'true' + if res == 'False': + res = 'false' + if not (res.startswith("'") or res.startswith("u'")): + res = res + else: + if res.startswith('u'): + res = res[1:] + + contents = res[1:-1] + contents = contents.replace('"', '').replace(r'\"', '') + res = '"' + contents + '"' + return res, is_read, is_rec + + pprint._safe_repr = _fake_safe_repr + try: + ret = pprint.pformat(val, indent=indent) + finally: + pprint._safe_repr = _real_safe_repr + + return ret + + def dumps(val, indent): + ret = _fake_json_dumps(val, indent=indent) + if not indent: + ret = re.sub(r'\n\s*', ' ', ret) + return ret + + + +def get_profile_json(indent=False): + if indent: + indent = 2 + else: + indent = 0 + + data_dict = get_profile() + return dumps(data_dict, indent) + + +def main(): + print(get_profile_json(indent=True)) + +############################################# +# The shell escaping copied in from strutils +############################################# + + +def _escape_shell_args(args, sep=' ', style=None): + if not style: + if sys.platform == 'win32': + style = 'cmd' + else: + style = 'sh' + + if style == 'sh': + return _args2sh(args, sep=sep) + elif style == 'cmd': + return _args2cmd(args, sep=sep) + + raise ValueError("style expected one of 'cmd' or 'sh', not %r" % style) + + +_find_sh_unsafe = re.compile(r'[^a-zA-Z0-9_@%+=:,./-]').search + + +def _args2sh(args, sep=' '): + # see strutils + ret_list = [] + + for arg in args: + if not arg: + ret_list.append("''") + continue + if _find_sh_unsafe(arg) is None: + ret_list.append(arg) + continue + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + ret_list.append("'" + arg.replace("'", "'\"'\"'") + "'") + + return ' '.join(ret_list) + + +def _args2cmd(args, sep=' '): + # see strutils + result = [] + needquote = False + for arg in args: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) or not arg + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + + +############################ +# End shell escaping code +############################ + +if __name__ == '__main__': + main() + + +""" + +ecoutils protocol version history +--------------------------------- + +The version is ECO_VERSION module-level constant, and _eco_version key +in the dictionary returned from ecoutils.get_profile(). + +1.0.1 - (boltons version 16.3.2+) Remove uuid dependency and add HAVE_URANDOM +1.0.0 - (boltons version 16.3.0-16.3.1) Initial release + +""" diff --git a/shared/package-files/02/02a3697a8755b97ccebe108bfd3cacf67f2358e36fc4f91cf2c69b68be0d7985/_nnpack_available_ops.h b/shared/package-files/02/02a3697a8755b97ccebe108bfd3cacf67f2358e36fc4f91cf2c69b68be0d7985/_nnpack_available_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..da277eb8cda19949d51efb2af3c20594f9b887ba --- /dev/null +++ b/shared/package-files/02/02a3697a8755b97ccebe108bfd3cacf67f2358e36fc4f91cf2c69b68be0d7985/_nnpack_available_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 _nnpack_available { + using schema = bool (); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nnpack_available") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nnpack_available() -> bool") + static bool call(); + static bool redispatch(c10::DispatchKeySet dispatchKeySet); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/02/02a8737928e943093556b8ff393e6328324ca2707dd12af4d66337abdd161958/graphics.py b/shared/package-files/02/02a8737928e943093556b8ff393e6328324ca2707dd12af4d66337abdd161958/graphics.py new file mode 100644 index 0000000000000000000000000000000000000000..8c112f5e8094ba90efe788a218164c4b456adf38 --- /dev/null +++ b/shared/package-files/02/02a8737928e943093556b8ff393e6328324ca2707dd12af4d66337abdd161958/graphics.py @@ -0,0 +1,798 @@ +""" + pygments.lexers.graphics + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for computer graphics and plotting related languages. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, words, include, bygroups, using, \ + this, default +from pygments.token import Text, Comment, Operator, Keyword, Name, \ + Number, Punctuation, String, Whitespace + +__all__ = ['GLShaderLexer', 'PostScriptLexer', 'AsymptoteLexer', 'GnuplotLexer', + 'PovrayLexer', 'HLSLShaderLexer'] + + +class GLShaderLexer(RegexLexer): + """ + GLSL (OpenGL Shader) lexer. + + .. versionadded:: 1.1 + """ + name = 'GLSL' + aliases = ['glsl'] + filenames = ['*.vert', '*.frag', '*.geo'] + mimetypes = ['text/x-glslsrc'] + + tokens = { + 'root': [ + (r'#(?:.*\\\n)*.*$', Comment.Preproc), + (r'//.*$', Comment.Single), + (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), + (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?', + Operator), + (r'[?:]', Operator), # quick hack for ternary + (r'\bdefined\b', Operator), + (r'[;{}(),\[\]]', Punctuation), + # FIXME when e is present, no decimal point needed + (r'[+-]?\d*\.\d+([eE][-+]?\d+)?', Number.Float), + (r'[+-]?\d+\.\d*([eE][-+]?\d+)?', Number.Float), + (r'0[xX][0-9a-fA-F]*', Number.Hex), + (r'0[0-7]*', Number.Oct), + (r'[1-9][0-9]*', Number.Integer), + (words(( + # Storage qualifiers + 'attribute', 'const', 'uniform', 'varying', + 'buffer', 'shared', 'in', 'out', + # Layout qualifiers + 'layout', + # Interpolation qualifiers + 'flat', 'smooth', 'noperspective', + # Auxiliary qualifiers + 'centroid', 'sample', 'patch', + # Parameter qualifiers. Some double as Storage qualifiers + 'inout', + # Precision qualifiers + 'lowp', 'mediump', 'highp', 'precision', + # Invariance qualifiers + 'invariant', + # Precise qualifiers + 'precise', + # Memory qualifiers + 'coherent', 'volatile', 'restrict', 'readonly', 'writeonly', + # Statements + 'break', 'continue', 'do', 'for', 'while', 'switch', + 'case', 'default', 'if', 'else', 'subroutine', + 'discard', 'return', 'struct'), + prefix=r'\b', suffix=r'\b'), + Keyword), + (words(( + # Boolean values + 'true', 'false'), + prefix=r'\b', suffix=r'\b'), + Keyword.Constant), + (words(( + # Miscellaneous types + 'void', 'atomic_uint', + # Floating-point scalars and vectors + 'float', 'vec2', 'vec3', 'vec4', + 'double', 'dvec2', 'dvec3', 'dvec4', + # Integer scalars and vectors + 'int', 'ivec2', 'ivec3', 'ivec4', + 'uint', 'uvec2', 'uvec3', 'uvec4', + # Boolean scalars and vectors + 'bool', 'bvec2', 'bvec3', 'bvec4', + # Matrices + 'mat2', 'mat3', 'mat4', 'dmat2', 'dmat3', 'dmat4', + 'mat2x2', 'mat2x3', 'mat2x4', 'dmat2x2', 'dmat2x3', 'dmat2x4', + 'mat3x2', 'mat3x3', 'mat3x4', 'dmat3x2', 'dmat3x3', + 'dmat3x4', 'mat4x2', 'mat4x3', 'mat4x4', 'dmat4x2', 'dmat4x3', 'dmat4x4', + # Floating-point samplers + 'sampler1D', 'sampler2D', 'sampler3D', 'samplerCube', + 'sampler1DArray', 'sampler2DArray', 'samplerCubeArray', + 'sampler2DRect', 'samplerBuffer', + 'sampler2DMS', 'sampler2DMSArray', + # Shadow samplers + 'sampler1DShadow', 'sampler2DShadow', 'samplerCubeShadow', + 'sampler1DArrayShadow', 'sampler2DArrayShadow', + 'samplerCubeArrayShadow', 'sampler2DRectShadow', + # Signed integer samplers + 'isampler1D', 'isampler2D', 'isampler3D', 'isamplerCube', + 'isampler1DArray', 'isampler2DArray', 'isamplerCubeArray', + 'isampler2DRect', 'isamplerBuffer', + 'isampler2DMS', 'isampler2DMSArray', + # Unsigned integer samplers + 'usampler1D', 'usampler2D', 'usampler3D', 'usamplerCube', + 'usampler1DArray', 'usampler2DArray', 'usamplerCubeArray', + 'usampler2DRect', 'usamplerBuffer', + 'usampler2DMS', 'usampler2DMSArray', + # Floating-point image types + 'image1D', 'image2D', 'image3D', 'imageCube', + 'image1DArray', 'image2DArray', 'imageCubeArray', + 'image2DRect', 'imageBuffer', + 'image2DMS', 'image2DMSArray', + # Signed integer image types + 'iimage1D', 'iimage2D', 'iimage3D', 'iimageCube', + 'iimage1DArray', 'iimage2DArray', 'iimageCubeArray', + 'iimage2DRect', 'iimageBuffer', + 'iimage2DMS', 'iimage2DMSArray', + # Unsigned integer image types + 'uimage1D', 'uimage2D', 'uimage3D', 'uimageCube', + 'uimage1DArray', 'uimage2DArray', 'uimageCubeArray', + 'uimage2DRect', 'uimageBuffer', + 'uimage2DMS', 'uimage2DMSArray'), + prefix=r'\b', suffix=r'\b'), + Keyword.Type), + (words(( + # Reserved for future use. + 'common', 'partition', 'active', 'asm', 'class', + 'union', 'enum', 'typedef', 'template', 'this', + 'resource', 'goto', 'inline', 'noinline', 'public', + 'static', 'extern', 'external', 'interface', 'long', + 'short', 'half', 'fixed', 'unsigned', 'superp', 'input', + 'output', 'hvec2', 'hvec3', 'hvec4', 'fvec2', 'fvec3', + 'fvec4', 'sampler3DRect', 'filter', 'sizeof', 'cast', + 'namespace', 'using'), + prefix=r'\b', suffix=r'\b'), + Keyword.Reserved), + # All names beginning with "gl_" are reserved. + (r'gl_\w*', Name.Builtin), + (r'[a-zA-Z_]\w*', Name), + (r'\.', Punctuation), + (r'\s+', Whitespace), + ], + } + + +class HLSLShaderLexer(RegexLexer): + """ + HLSL (Microsoft Direct3D Shader) lexer. + + .. versionadded:: 2.3 + """ + name = 'HLSL' + aliases = ['hlsl'] + filenames = ['*.hlsl', '*.hlsli'] + mimetypes = ['text/x-hlsl'] + + tokens = { + 'root': [ + (r'#(?:.*\\\n)*.*$', Comment.Preproc), + (r'//.*$', Comment.Single), + (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), + (r'\+|-|~|!=?|\*|/|%|<<|>>|<=?|>=?|==?|&&?|\^|\|\|?', + Operator), + (r'[?:]', Operator), # quick hack for ternary + (r'\bdefined\b', Operator), + (r'[;{}(),.\[\]]', Punctuation), + # FIXME when e is present, no decimal point needed + (r'[+-]?\d*\.\d+([eE][-+]?\d+)?f?', Number.Float), + (r'[+-]?\d+\.\d*([eE][-+]?\d+)?f?', Number.Float), + (r'0[xX][0-9a-fA-F]*', Number.Hex), + (r'0[0-7]*', Number.Oct), + (r'[1-9][0-9]*', Number.Integer), + (r'"', String, 'string'), + (words(( + 'asm','asm_fragment','break','case','cbuffer','centroid','class', + 'column_major','compile','compile_fragment','const','continue', + 'default','discard','do','else','export','extern','for','fxgroup', + 'globallycoherent','groupshared','if','in','inline','inout', + 'interface','line','lineadj','linear','namespace','nointerpolation', + 'noperspective','NULL','out','packoffset','pass','pixelfragment', + 'point','precise','return','register','row_major','sample', + 'sampler','shared','stateblock','stateblock_state','static', + 'struct','switch','tbuffer','technique','technique10', + 'technique11','texture','typedef','triangle','triangleadj', + 'uniform','vertexfragment','volatile','while'), + prefix=r'\b', suffix=r'\b'), + Keyword), + (words(('true','false'), prefix=r'\b', suffix=r'\b'), + Keyword.Constant), + (words(( + 'auto','catch','char','const_cast','delete','dynamic_cast','enum', + 'explicit','friend','goto','long','mutable','new','operator', + 'private','protected','public','reinterpret_cast','short','signed', + 'sizeof','static_cast','template','this','throw','try','typename', + 'union','unsigned','using','virtual'), + prefix=r'\b', suffix=r'\b'), + Keyword.Reserved), + (words(( + 'dword','matrix','snorm','string','unorm','unsigned','void','vector', + 'BlendState','Buffer','ByteAddressBuffer','ComputeShader', + 'DepthStencilState','DepthStencilView','DomainShader', + 'GeometryShader','HullShader','InputPatch','LineStream', + 'OutputPatch','PixelShader','PointStream','RasterizerState', + 'RenderTargetView','RasterizerOrderedBuffer', + 'RasterizerOrderedByteAddressBuffer', + 'RasterizerOrderedStructuredBuffer','RasterizerOrderedTexture1D', + 'RasterizerOrderedTexture1DArray','RasterizerOrderedTexture2D', + 'RasterizerOrderedTexture2DArray','RasterizerOrderedTexture3D', + 'RWBuffer','RWByteAddressBuffer','RWStructuredBuffer', + 'RWTexture1D','RWTexture1DArray','RWTexture2D','RWTexture2DArray', + 'RWTexture3D','SamplerState','SamplerComparisonState', + 'StructuredBuffer','Texture1D','Texture1DArray','Texture2D', + 'Texture2DArray','Texture2DMS','Texture2DMSArray','Texture3D', + 'TextureCube','TextureCubeArray','TriangleStream','VertexShader'), + prefix=r'\b', suffix=r'\b'), + Keyword.Type), + (words(( + 'bool','double','float','int','half','min16float','min10float', + 'min16int','min12int','min16uint','uint'), + prefix=r'\b', suffix=r'([1-4](x[1-4])?)?\b'), + Keyword.Type), # vector and matrix types + (words(( + 'abort','abs','acos','all','AllMemoryBarrier', + 'AllMemoryBarrierWithGroupSync','any','AppendStructuredBuffer', + 'asdouble','asfloat','asin','asint','asuint','asuint','atan', + 'atan2','ceil','CheckAccessFullyMapped','clamp','clip', + 'CompileShader','ConsumeStructuredBuffer','cos','cosh','countbits', + 'cross','D3DCOLORtoUBYTE4','ddx','ddx_coarse','ddx_fine','ddy', + 'ddy_coarse','ddy_fine','degrees','determinant', + 'DeviceMemoryBarrier','DeviceMemoryBarrierWithGroupSync','distance', + 'dot','dst','errorf','EvaluateAttributeAtCentroid', + 'EvaluateAttributeAtSample','EvaluateAttributeSnapped','exp', + 'exp2','f16tof32','f32tof16','faceforward','firstbithigh', + 'firstbitlow','floor','fma','fmod','frac','frexp','fwidth', + 'GetRenderTargetSampleCount','GetRenderTargetSamplePosition', + 'GlobalOrderedCountIncrement','GroupMemoryBarrier', + 'GroupMemoryBarrierWithGroupSync','InterlockedAdd','InterlockedAnd', + 'InterlockedCompareExchange','InterlockedCompareStore', + 'InterlockedExchange','InterlockedMax','InterlockedMin', + 'InterlockedOr','InterlockedXor','isfinite','isinf','isnan', + 'ldexp','length','lerp','lit','log','log10','log2','mad','max', + 'min','modf','msad4','mul','noise','normalize','pow','printf', + 'Process2DQuadTessFactorsAvg','Process2DQuadTessFactorsMax', + 'Process2DQuadTessFactorsMin','ProcessIsolineTessFactors', + 'ProcessQuadTessFactorsAvg','ProcessQuadTessFactorsMax', + 'ProcessQuadTessFactorsMin','ProcessTriTessFactorsAvg', + 'ProcessTriTessFactorsMax','ProcessTriTessFactorsMin', + 'QuadReadLaneAt','QuadSwapX','QuadSwapY','radians','rcp', + 'reflect','refract','reversebits','round','rsqrt','saturate', + 'sign','sin','sincos','sinh','smoothstep','sqrt','step','tan', + 'tanh','tex1D','tex1D','tex1Dbias','tex1Dgrad','tex1Dlod', + 'tex1Dproj','tex2D','tex2D','tex2Dbias','tex2Dgrad','tex2Dlod', + 'tex2Dproj','tex3D','tex3D','tex3Dbias','tex3Dgrad','tex3Dlod', + 'tex3Dproj','texCUBE','texCUBE','texCUBEbias','texCUBEgrad', + 'texCUBElod','texCUBEproj','transpose','trunc','WaveAllBitAnd', + 'WaveAllMax','WaveAllMin','WaveAllBitOr','WaveAllBitXor', + 'WaveAllEqual','WaveAllProduct','WaveAllSum','WaveAllTrue', + 'WaveAnyTrue','WaveBallot','WaveGetLaneCount','WaveGetLaneIndex', + 'WaveGetOrderedIndex','WaveIsHelperLane','WaveOnce', + 'WavePrefixProduct','WavePrefixSum','WaveReadFirstLane', + 'WaveReadLaneAt'), + prefix=r'\b', suffix=r'\b'), + Name.Builtin), # built-in functions + (words(( + 'SV_ClipDistance','SV_ClipDistance0','SV_ClipDistance1', + 'SV_Culldistance','SV_CullDistance0','SV_CullDistance1', + 'SV_Coverage','SV_Depth','SV_DepthGreaterEqual', + 'SV_DepthLessEqual','SV_DispatchThreadID','SV_DomainLocation', + 'SV_GroupID','SV_GroupIndex','SV_GroupThreadID','SV_GSInstanceID', + 'SV_InnerCoverage','SV_InsideTessFactor','SV_InstanceID', + 'SV_IsFrontFace','SV_OutputControlPointID','SV_Position', + 'SV_PrimitiveID','SV_RenderTargetArrayIndex','SV_SampleIndex', + 'SV_StencilRef','SV_TessFactor','SV_VertexID', + 'SV_ViewportArrayIndex'), + prefix=r'\b', suffix=r'\b'), + Name.Decorator), # system-value semantics + (r'\bSV_Target[0-7]?\b', Name.Decorator), + (words(( + 'allow_uav_condition','branch','call','domain','earlydepthstencil', + 'fastopt','flatten','forcecase','instance','loop','maxtessfactor', + 'numthreads','outputcontrolpoints','outputtopology','partitioning', + 'patchconstantfunc','unroll'), + prefix=r'\b', suffix=r'\b'), + Name.Decorator), # attributes + (r'[a-zA-Z_]\w*', Name), + (r'\\$', Comment.Preproc), # backslash at end of line -- usually macro continuation + (r'\s+', Whitespace), + ], + 'string': [ + (r'"', String, '#pop'), + (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' + r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), + (r'[^\\"\n]+', String), # all other characters + (r'\\\n', String), # line continuation + (r'\\', String), # stray backslash + ], + } + + +class PostScriptLexer(RegexLexer): + """ + Lexer for PostScript files. + + .. versionadded:: 1.4 + """ + name = 'PostScript' + url = 'https://en.wikipedia.org/wiki/PostScript' + aliases = ['postscript', 'postscr'] + filenames = ['*.ps', '*.eps'] + mimetypes = ['application/postscript'] + + delimiter = r'()<>\[\]{}/%\s' + delimiter_end = r'(?=[%s])' % delimiter + + valid_name_chars = r'[^%s]' % delimiter + valid_name = r"%s+%s" % (valid_name_chars, delimiter_end) + + tokens = { + 'root': [ + # All comment types + (r'^%!.+$', Comment.Preproc), + (r'%%.*$', Comment.Special), + (r'(^%.*\n){2,}', Comment.Multiline), + (r'%.*$', Comment.Single), + + # String literals are awkward; enter separate state. + (r'\(', String, 'stringliteral'), + + (r'[{}<>\[\]]', Punctuation), + + # Numbers + (r'<[0-9A-Fa-f]+>' + delimiter_end, Number.Hex), + # Slight abuse: use Oct to signify any explicit base system + (r'[0-9]+\#(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)' + r'((e|E)[0-9]+)?' + delimiter_end, Number.Oct), + (r'(\-|\+)?([0-9]+\.?|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)((e|E)[0-9]+)?' + + delimiter_end, Number.Float), + (r'(\-|\+)?[0-9]+' + delimiter_end, Number.Integer), + + # References + (r'\/%s' % valid_name, Name.Variable), + + # Names + (valid_name, Name.Function), # Anything else is executed + + # These keywords taken from + # + # Is there an authoritative list anywhere that doesn't involve + # trawling documentation? + + (r'(false|true)' + delimiter_end, Keyword.Constant), + + # Conditionals / flow control + (r'(eq|ne|g[et]|l[et]|and|or|not|if(?:else)?|for(?:all)?)' + + delimiter_end, Keyword.Reserved), + + (words(( + 'abs', 'add', 'aload', 'arc', 'arcn', 'array', 'atan', 'begin', + 'bind', 'ceiling', 'charpath', 'clip', 'closepath', 'concat', + 'concatmatrix', 'copy', 'cos', 'currentlinewidth', 'currentmatrix', + 'currentpoint', 'curveto', 'cvi', 'cvs', 'def', 'defaultmatrix', + 'dict', 'dictstackoverflow', 'div', 'dtransform', 'dup', 'end', + 'exch', 'exec', 'exit', 'exp', 'fill', 'findfont', 'floor', 'get', + 'getinterval', 'grestore', 'gsave', 'gt', 'identmatrix', 'idiv', + 'idtransform', 'index', 'invertmatrix', 'itransform', 'length', + 'lineto', 'ln', 'load', 'log', 'loop', 'matrix', 'mod', 'moveto', + 'mul', 'neg', 'newpath', 'pathforall', 'pathbbox', 'pop', 'print', + 'pstack', 'put', 'quit', 'rand', 'rangecheck', 'rcurveto', 'repeat', + 'restore', 'rlineto', 'rmoveto', 'roll', 'rotate', 'round', 'run', + 'save', 'scale', 'scalefont', 'setdash', 'setfont', 'setgray', + 'setlinecap', 'setlinejoin', 'setlinewidth', 'setmatrix', + 'setrgbcolor', 'shfill', 'show', 'showpage', 'sin', 'sqrt', + 'stack', 'stringwidth', 'stroke', 'strokepath', 'sub', 'syntaxerror', + 'transform', 'translate', 'truncate', 'typecheck', 'undefined', + 'undefinedfilename', 'undefinedresult'), suffix=delimiter_end), + Name.Builtin), + + (r'\s+', Whitespace), + ], + + 'stringliteral': [ + (r'[^()\\]+', String), + (r'\\', String.Escape, 'escape'), + (r'\(', String, '#push'), + (r'\)', String, '#pop'), + ], + + 'escape': [ + (r'[0-8]{3}|n|r|t|b|f|\\|\(|\)', String.Escape, '#pop'), + default('#pop'), + ], + } + + +class AsymptoteLexer(RegexLexer): + """ + For Asymptote source code. + + .. versionadded:: 1.2 + """ + name = 'Asymptote' + url = 'http://asymptote.sf.net/' + aliases = ['asymptote', 'asy'] + filenames = ['*.asy'] + mimetypes = ['text/x-asymptote'] + + #: optional Comment or Whitespace + _ws = r'(?:\s|//.*?\n|/\*.*?\*/)+' + + tokens = { + 'whitespace': [ + (r'\n', Whitespace), + (r'\s+', Whitespace), + (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation + (r'//(\n|(.|\n)*?[^\\]\n)', Comment), + (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment), + ], + 'statements': [ + # simple string (TeX friendly) + (r'"(\\\\|\\[^\\]|[^"\\])*"', String), + # C style string (with character escapes) + (r"'", String, 'string'), + (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'[~!%^&*+=|?:<>/-]', Operator), + (r'[()\[\],.]', Punctuation), + (r'\b(case)(.+?)(:)', bygroups(Keyword, using(this), Text)), + (r'(and|controls|tension|atleast|curl|if|else|while|for|do|' + r'return|break|continue|struct|typedef|new|access|import|' + r'unravel|from|include|quote|static|public|private|restricted|' + r'this|explicit|true|false|null|cycle|newframe|operator)\b', Keyword), + # Since an asy-type-name can be also an asy-function-name, + # in the following we test if the string " [a-zA-Z]" follows + # the Keyword.Type. + # Of course it is not perfect ! + (r'(Braid|FitResult|Label|Legend|TreeNode|abscissa|arc|arrowhead|' + r'binarytree|binarytreeNode|block|bool|bool3|bounds|bqe|circle|' + r'conic|coord|coordsys|cputime|ellipse|file|filltype|frame|grid3|' + r'guide|horner|hsv|hyperbola|indexedTransform|int|inversion|key|' + r'light|line|linefit|marginT|marker|mass|object|pair|parabola|path|' + r'path3|pen|picture|point|position|projection|real|revolution|' + r'scaleT|scientific|segment|side|slice|splitface|string|surface|' + r'tensionSpecifier|ticklocate|ticksgridT|tickvalues|transform|' + r'transformation|tree|triangle|trilinear|triple|vector|' + r'vertex|void)(?=\s+[a-zA-Z])', Keyword.Type), + # Now the asy-type-name which are not asy-function-name + # except yours ! + # Perhaps useless + (r'(Braid|FitResult|TreeNode|abscissa|arrowhead|block|bool|bool3|' + r'bounds|coord|frame|guide|horner|int|linefit|marginT|pair|pen|' + r'picture|position|real|revolution|slice|splitface|ticksgridT|' + r'tickvalues|tree|triple|vertex|void)\b', Keyword.Type), + (r'[a-zA-Z_]\w*:(?!:)', Name.Label), + (r'[a-zA-Z_]\w*', Name), + ], + 'root': [ + include('whitespace'), + # functions + (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments + r'([a-zA-Z_]\w*)' # method name + r'(\s*\([^;]*?\))' # signature + r'(' + _ws + r')(\{)', + bygroups(using(this), Name.Function, using(this), using(this), + Punctuation), + 'function'), + # function declarations + (r'((?:[\w*\s])+?(?:\s|\*))' # return arguments + r'([a-zA-Z_]\w*)' # method name + r'(\s*\([^;]*?\))' # signature + r'(' + _ws + r')(;)', + bygroups(using(this), Name.Function, using(this), using(this), + Punctuation)), + default('statement'), + ], + 'statement': [ + include('whitespace'), + include('statements'), + ('[{}]', Punctuation), + (';', Punctuation, '#pop'), + ], + 'function': [ + include('whitespace'), + include('statements'), + (';', Punctuation), + (r'\{', Punctuation, '#push'), + (r'\}', Punctuation, '#pop'), + ], + 'string': [ + (r"'", String, '#pop'), + (r'\\([\\abfnrtv"\'?]|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), + (r'\n', String), + (r"[^\\'\n]+", String), # all other characters + (r'\\\n', String), + (r'\\n', String), # line continuation + (r'\\', String), # stray backslash + ], + } + + def get_tokens_unprocessed(self, text): + from pygments.lexers._asy_builtins import ASYFUNCNAME, ASYVARNAME + for index, token, value in \ + RegexLexer.get_tokens_unprocessed(self, text): + if token is Name and value in ASYFUNCNAME: + token = Name.Function + elif token is Name and value in ASYVARNAME: + token = Name.Variable + yield index, token, value + + +def _shortened(word): + dpos = word.find('$') + return '|'.join(word[:dpos] + word[dpos+1:i] + r'\b' + for i in range(len(word), dpos, -1)) + + +def _shortened_many(*words): + return '|'.join(map(_shortened, words)) + + +class GnuplotLexer(RegexLexer): + """ + For Gnuplot plotting scripts. + + .. versionadded:: 0.11 + """ + + name = 'Gnuplot' + url = 'http://gnuplot.info/' + aliases = ['gnuplot'] + filenames = ['*.plot', '*.plt'] + mimetypes = ['text/x-gnuplot'] + + tokens = { + 'root': [ + include('whitespace'), + (_shortened('bi$nd'), Keyword, 'bind'), + (_shortened_many('ex$it', 'q$uit'), Keyword, 'quit'), + (_shortened('f$it'), Keyword, 'fit'), + (r'(if)(\s*)(\()', bygroups(Keyword, Text, Punctuation), 'if'), + (r'else\b', Keyword), + (_shortened('pa$use'), Keyword, 'pause'), + (_shortened_many('p$lot', 'rep$lot', 'sp$lot'), Keyword, 'plot'), + (_shortened('sa$ve'), Keyword, 'save'), + (_shortened('se$t'), Keyword, ('genericargs', 'optionarg')), + (_shortened_many('sh$ow', 'uns$et'), + Keyword, ('noargs', 'optionarg')), + (_shortened_many('low$er', 'ra$ise', 'ca$ll', 'cd$', 'cl$ear', + 'h$elp', '\\?$', 'hi$story', 'l$oad', 'pr$int', + 'pwd$', 're$read', 'res$et', 'scr$eendump', + 'she$ll', 'sy$stem', 'up$date'), + Keyword, 'genericargs'), + (_shortened_many('pwd$', 're$read', 'res$et', 'scr$eendump', + 'she$ll', 'test$'), + Keyword, 'noargs'), + (r'([a-zA-Z_]\w*)(\s*)(=)', + bygroups(Name.Variable, Whitespace, Operator), 'genericargs'), + (r'([a-zA-Z_]\w*)(\s*)(\()(.*?)(\))(\s*)(=)', + bygroups(Name.Function, Whitespace, Punctuation, + Text, Punctuation, Whitespace, Operator), 'genericargs'), + (r'@[a-zA-Z_]\w*', Name.Constant), # macros + (r';', Keyword), + ], + 'comment': [ + (r'[^\\\n]+', Comment), + (r'\\\n', Comment), + (r'\\', Comment), + # don't add the newline to the Comment token + default('#pop'), + ], + 'whitespace': [ + ('#', Comment, 'comment'), + (r'[ \t\v\f]+', Whitespace), + ], + 'noargs': [ + include('whitespace'), + # semicolon and newline end the argument list + (r';', Punctuation, '#pop'), + (r'\n', Whitespace, '#pop'), + ], + 'dqstring': [ + (r'"', String, '#pop'), + (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), + (r'[^\\"\n]+', String), # all other characters + (r'\\\n', String), # line continuation + (r'\\', String), # stray backslash + (r'\n', Whitespace, '#pop'), # newline ends the string too + ], + 'sqstring': [ + (r"''", String), # escaped single quote + (r"'", String, '#pop'), + (r"[^\\'\n]+", String), # all other characters + (r'\\\n', String), # line continuation + (r'\\', String), # normal backslash + (r'\n', Whitespace, '#pop'), # newline ends the string too + ], + 'genericargs': [ + include('noargs'), + (r'"', String, 'dqstring'), + (r"'", String, 'sqstring'), + (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float), + (r'(\d+\.\d*|\.\d+)', Number.Float), + (r'-?\d+', Number.Integer), + ('[,.~!%^&*+=|?:<>/-]', Operator), + (r'[{}()\[\]]', Punctuation), + (r'(eq|ne)\b', Operator.Word), + (r'([a-zA-Z_]\w*)(\s*)(\()', + bygroups(Name.Function, Text, Punctuation)), + (r'[a-zA-Z_]\w*', Name), + (r'@[a-zA-Z_]\w*', Name.Constant), # macros + (r'(\\)(\n)', bygroups(Text, Whitespace)), + ], + 'optionarg': [ + include('whitespace'), + (_shortened_many( + "a$ll", "an$gles", "ar$row", "au$toscale", "b$ars", "bor$der", + "box$width", "cl$abel", "c$lip", "cn$trparam", "co$ntour", "da$ta", + "data$file", "dg$rid3d", "du$mmy", "enc$oding", "dec$imalsign", + "fit$", "font$path", "fo$rmat", "fu$nction", "fu$nctions", "g$rid", + "hid$den3d", "his$torysize", "is$osamples", "k$ey", "keyt$itle", + "la$bel", "li$nestyle", "ls$", "loa$dpath", "loc$ale", "log$scale", + "mac$ros", "map$ping", "map$ping3d", "mar$gin", "lmar$gin", + "rmar$gin", "tmar$gin", "bmar$gin", "mo$use", "multi$plot", + "mxt$ics", "nomxt$ics", "mx2t$ics", "nomx2t$ics", "myt$ics", + "nomyt$ics", "my2t$ics", "nomy2t$ics", "mzt$ics", "nomzt$ics", + "mcbt$ics", "nomcbt$ics", "of$fsets", "or$igin", "o$utput", + "pa$rametric", "pm$3d", "pal$ette", "colorb$ox", "p$lot", + "poi$ntsize", "pol$ar", "pr$int", "obj$ect", "sa$mples", "si$ze", + "st$yle", "su$rface", "table$", "t$erminal", "termo$ptions", "ti$cs", + "ticsc$ale", "ticsl$evel", "timef$mt", "tim$estamp", "tit$le", + "v$ariables", "ve$rsion", "vi$ew", "xyp$lane", "xda$ta", "x2da$ta", + "yda$ta", "y2da$ta", "zda$ta", "cbda$ta", "xl$abel", "x2l$abel", + "yl$abel", "y2l$abel", "zl$abel", "cbl$abel", "xti$cs", "noxti$cs", + "x2ti$cs", "nox2ti$cs", "yti$cs", "noyti$cs", "y2ti$cs", "noy2ti$cs", + "zti$cs", "nozti$cs", "cbti$cs", "nocbti$cs", "xdti$cs", "noxdti$cs", + "x2dti$cs", "nox2dti$cs", "ydti$cs", "noydti$cs", "y2dti$cs", + "noy2dti$cs", "zdti$cs", "nozdti$cs", "cbdti$cs", "nocbdti$cs", + "xmti$cs", "noxmti$cs", "x2mti$cs", "nox2mti$cs", "ymti$cs", + "noymti$cs", "y2mti$cs", "noy2mti$cs", "zmti$cs", "nozmti$cs", + "cbmti$cs", "nocbmti$cs", "xr$ange", "x2r$ange", "yr$ange", + "y2r$ange", "zr$ange", "cbr$ange", "rr$ange", "tr$ange", "ur$ange", + "vr$ange", "xzeroa$xis", "x2zeroa$xis", "yzeroa$xis", "y2zeroa$xis", + "zzeroa$xis", "zeroa$xis", "z$ero"), Name.Builtin, '#pop'), + ], + 'bind': [ + ('!', Keyword, '#pop'), + (_shortened('all$windows'), Name.Builtin), + include('genericargs'), + ], + 'quit': [ + (r'gnuplot\b', Keyword), + include('noargs'), + ], + 'fit': [ + (r'via\b', Name.Builtin), + include('plot'), + ], + 'if': [ + (r'\)', Punctuation, '#pop'), + include('genericargs'), + ], + 'pause': [ + (r'(mouse|any|button1|button2|button3)\b', Name.Builtin), + (_shortened('key$press'), Name.Builtin), + include('genericargs'), + ], + 'plot': [ + (_shortened_many('ax$es', 'axi$s', 'bin$ary', 'ev$ery', 'i$ndex', + 'mat$rix', 's$mooth', 'thru$', 't$itle', + 'not$itle', 'u$sing', 'w$ith'), + Name.Builtin), + include('genericargs'), + ], + 'save': [ + (_shortened_many('f$unctions', 's$et', 't$erminal', 'v$ariables'), + Name.Builtin), + include('genericargs'), + ], + } + + +class PovrayLexer(RegexLexer): + """ + For Persistence of Vision Raytracer files. + + .. versionadded:: 0.11 + """ + name = 'POVRay' + url = 'http://www.povray.org/' + aliases = ['pov'] + filenames = ['*.pov', '*.inc'] + mimetypes = ['text/x-povray'] + + tokens = { + 'root': [ + (r'/\*[\w\W]*?\*/', Comment.Multiline), + (r'//.*$', Comment.Single), + (r'(?s)"(?:\\.|[^"\\])+"', String.Double), + (words(( + 'break', 'case', 'debug', 'declare', 'default', 'define', 'else', + 'elseif', 'end', 'error', 'fclose', 'fopen', 'for', 'if', 'ifdef', + 'ifndef', 'include', 'local', 'macro', 'range', 'read', 'render', + 'statistics', 'switch', 'undef', 'version', 'warning', 'while', + 'write'), prefix=r'#', suffix=r'\b'), + Comment.Preproc), + (words(( + 'aa_level', 'aa_threshold', 'abs', 'acos', 'acosh', 'adaptive', 'adc_bailout', + 'agate', 'agate_turb', 'all', 'alpha', 'ambient', 'ambient_light', 'angle', + 'aperture', 'arc_angle', 'area_light', 'asc', 'asin', 'asinh', 'assumed_gamma', + 'atan', 'atan2', 'atanh', 'atmosphere', 'atmospheric_attenuation', + 'attenuating', 'average', 'background', 'black_hole', 'blue', 'blur_samples', + 'bounded_by', 'box_mapping', 'bozo', 'break', 'brick', 'brick_size', + 'brightness', 'brilliance', 'bumps', 'bumpy1', 'bumpy2', 'bumpy3', 'bump_map', + 'bump_size', 'case', 'caustics', 'ceil', 'checker', 'chr', 'clipped_by', 'clock', + 'color', 'color_map', 'colour', 'colour_map', 'component', 'composite', 'concat', + 'confidence', 'conic_sweep', 'constant', 'control0', 'control1', 'cos', 'cosh', + 'count', 'crackle', 'crand', 'cube', 'cubic_spline', 'cylindrical_mapping', + 'debug', 'declare', 'default', 'degrees', 'dents', 'diffuse', 'direction', + 'distance', 'distance_maximum', 'div', 'dust', 'dust_type', 'eccentricity', + 'else', 'emitting', 'end', 'error', 'error_bound', 'exp', 'exponent', + 'fade_distance', 'fade_power', 'falloff', 'falloff_angle', 'false', + 'file_exists', 'filter', 'finish', 'fisheye', 'flatness', 'flip', 'floor', + 'focal_point', 'fog', 'fog_alt', 'fog_offset', 'fog_type', 'frequency', 'gif', + 'global_settings', 'glowing', 'gradient', 'granite', 'gray_threshold', + 'green', 'halo', 'hexagon', 'hf_gray_16', 'hierarchy', 'hollow', 'hypercomplex', + 'if', 'ifdef', 'iff', 'image_map', 'incidence', 'include', 'int', 'interpolate', + 'inverse', 'ior', 'irid', 'irid_wavelength', 'jitter', 'lambda', 'leopard', + 'linear', 'linear_spline', 'linear_sweep', 'location', 'log', 'looks_like', + 'look_at', 'low_error_factor', 'mandel', 'map_type', 'marble', 'material_map', + 'matrix', 'max', 'max_intersections', 'max_iteration', 'max_trace_level', + 'max_value', 'metallic', 'min', 'minimum_reuse', 'mod', 'mortar', + 'nearest_count', 'no', 'normal', 'normal_map', 'no_shadow', 'number_of_waves', + 'octaves', 'off', 'offset', 'omega', 'omnimax', 'on', 'once', 'onion', 'open', + 'orthographic', 'panoramic', 'pattern1', 'pattern2', 'pattern3', + 'perspective', 'pgm', 'phase', 'phong', 'phong_size', 'pi', 'pigment', + 'pigment_map', 'planar_mapping', 'png', 'point_at', 'pot', 'pow', 'ppm', + 'precision', 'pwr', 'quadratic_spline', 'quaternion', 'quick_color', + 'quick_colour', 'quilted', 'radial', 'radians', 'radiosity', 'radius', 'rainbow', + 'ramp_wave', 'rand', 'range', 'reciprocal', 'recursion_limit', 'red', + 'reflection', 'refraction', 'render', 'repeat', 'rgb', 'rgbf', 'rgbft', 'rgbt', + 'right', 'ripples', 'rotate', 'roughness', 'samples', 'scale', 'scallop_wave', + 'scattering', 'seed', 'shadowless', 'sin', 'sine_wave', 'sinh', 'sky', 'sky_sphere', + 'slice', 'slope_map', 'smooth', 'specular', 'spherical_mapping', 'spiral', + 'spiral1', 'spiral2', 'spotlight', 'spotted', 'sqr', 'sqrt', 'statistics', 'str', + 'strcmp', 'strength', 'strlen', 'strlwr', 'strupr', 'sturm', 'substr', 'switch', 'sys', + 't', 'tan', 'tanh', 'test_camera_1', 'test_camera_2', 'test_camera_3', + 'test_camera_4', 'texture', 'texture_map', 'tga', 'thickness', 'threshold', + 'tightness', 'tile2', 'tiles', 'track', 'transform', 'translate', 'transmit', + 'triangle_wave', 'true', 'ttf', 'turbulence', 'turb_depth', 'type', + 'ultra_wide_angle', 'up', 'use_color', 'use_colour', 'use_index', 'u_steps', + 'val', 'variance', 'vaxis_rotate', 'vcross', 'vdot', 'version', 'vlength', + 'vnormalize', 'volume_object', 'volume_rendered', 'vol_with_light', + 'vrotate', 'v_steps', 'warning', 'warp', 'water_level', 'waves', 'while', 'width', + 'wood', 'wrinkles', 'yes'), prefix=r'\b', suffix=r'\b'), + Keyword), + (words(( + 'bicubic_patch', 'blob', 'box', 'camera', 'cone', 'cubic', 'cylinder', 'difference', + 'disc', 'height_field', 'intersection', 'julia_fractal', 'lathe', + 'light_source', 'merge', 'mesh', 'object', 'plane', 'poly', 'polygon', 'prism', + 'quadric', 'quartic', 'smooth_triangle', 'sor', 'sphere', 'superellipsoid', + 'text', 'torus', 'triangle', 'union'), suffix=r'\b'), + Name.Builtin), + (r'\b(x|y|z|u|v)\b', Name.Builtin.Pseudo), + (r'[a-zA-Z_]\w*', Name), + (r'[0-9]*\.[0-9]+', Number.Float), + (r'[0-9]+', Number.Integer), + (r'[\[\](){}<>;,]', Punctuation), + (r'[-+*/=.|&]|<=|>=|!=', Operator), + (r'"(\\\\|\\[^\\]|[^"\\])*"', String), + (r'\s+', Whitespace), + ] + } + + def analyse_text(text): + """POVRAY is similar to JSON/C, but the combination of camera and + light_source is probably not very likely elsewhere. HLSL or GLSL + are similar (GLSL even has #version), but they miss #declare, and + light_source/camera are not keywords anywhere else -- it's fair + to assume though that any POVRAY scene must have a camera and + lightsource.""" + result = 0 + if '#version' in text: + result += 0.05 + if '#declare' in text: + result += 0.05 + if 'camera' in text: + result += 0.05 + if 'light_source' in text: + result += 0.1 + + return result diff --git a/shared/package-files/02/02ab00f952867174907899e30832d2836e3c99403d45d5dab94b5be90e8c8cc1/mm.py b/shared/package-files/02/02ab00f952867174907899e30832d2836e3c99403d45d5dab94b5be90e8c8cc1/mm.py new file mode 100644 index 0000000000000000000000000000000000000000..8021720b01d2761e0aa758a1feb2ac4d3effa320 --- /dev/null +++ b/shared/package-files/02/02ab00f952867174907899e30832d2836e3c99403d45d5dab94b5be90e8c8cc1/mm.py @@ -0,0 +1,312 @@ +import functools +import logging +from typing import Any, Dict, List, Optional + +import torch +from torch._inductor.virtualized import V +from .. import config as inductor_config +from ..codegen.cuda.gemm_template import CUTLASSGemmTemplate +from ..lowering import register_lowering +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + TritonTemplate, +) +from ..utils import ( + use_aten_gemm_kernels, + use_cutlass_template, + use_max_autotune, + use_triton_template, +) +from .mm_common import ( + addmm_epilogue, + int8_mm_configs, + mm_args, + mm_configs, + mm_grid, + mm_options, +) + +log = logging.getLogger(__name__) +aten = torch.ops.aten + +mm_template = TritonTemplate( + name="mm", + grid=mm_grid, + source=r""" +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.) + b = tl.load(B, mask=rk[:, None] < k, other=0.) + if B_PROLOGUE_CAST_TYPE is not None: + b = b.to(B_PROLOGUE_CAST_TYPE) + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask")}} +""", +) + +aten_mm = ExternKernelChoice(torch.mm, "at::mm_out") + + +aten_addmm = ExternKernelChoice( + torch.addmm, "at::addmm_out", op_overload=aten.addmm.default +) + +aten__int_mm = ExternKernelChoice(torch._int_mm, "at::_int_mm") + + +def _is_int8_mat(mat): + return mat.get_dtype() in (torch.int8, torch.uint8) + + +def bias_addmm(inp, mat1, mat2, *, out=None, alpha=1, beta=1): + """ + Giving torch.addmm a 1D tensor calls a different (faster) cublasLt + kernel under the hood. There are a few shapes where this is slower, + but they are rare. + """ + if inp.stride(0) == 0 or inp.size(0) == 1: + return torch.addmm(inp[0], mat1, mat2, out=out, alpha=alpha, beta=beta) + return torch.addmm(inp, mat1, mat2, out=out, alpha=alpha, beta=beta) + + +aten_bias_addmm = ExternKernelChoice(bias_addmm, None) + + +@register_lowering(aten.mm, type_promotion_kind=None) +def tuned_mm(mat1, mat2, *, layout=None): + m, n, k, layout, mat1, mat2 = mm_args(mat1, mat2, layout=layout) + + # options to tune from + choices = [aten_mm.bind((mat1, mat2), layout)] if use_aten_gemm_kernels() else [] + + if m * n != 0 and use_triton_template(layout): + for config in mm_configs(m, n, k): + mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout), + ) + + if m * n != 0 and use_cutlass_template(layout): + CUTLASSGemmTemplate.add_cutlass_gemm_choices( + choices, layout, [mat1, mat2], fuseable=True, non_fuseable=True + ) + + from torch._inductor.ir import FixedLayout, FlexibleLayout + + if ( + len(choices) == 1 + and use_aten_gemm_kernels() + and isinstance(layout, FixedLayout) + ): + # If we are not autotuning, we can swap to a FlexibleLayout + # in order to get fusion optimizations to kick in, e.g. ConcatFusion + layout = FlexibleLayout( + device=layout.device, dtype=layout.dtype, size=layout.size + ) + choices = [aten_mm.bind((mat1, mat2), layout)] + + return autotune_select_algorithm("mm", choices, [mat1, mat2], layout) + + +@register_lowering(aten._int_mm, type_promotion_kind=None) +def tuned_int_mm(mat1, mat2, *, layout=None): + m, n, k, layout, mat1, mat2 = mm_args( + mat1, mat2, layout=layout, out_dtype=torch.int32 + ) + choices = ( + [aten__int_mm.bind((mat1, mat2), layout)] if use_aten_gemm_kernels() else [] + ) + if m * n != 0 and use_triton_template(layout, enable_int32=True): + # TODO: Re-enable eager mode implementation once cuBLAS is fixed + choices = [] + for config in int8_mm_configs(m, n, k): + mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout), + ) + return autotune_select_algorithm("int_mm", choices, [mat1, mat2], layout) + + +@register_lowering(aten.addmm, type_promotion_kind=None) +def tuned_addmm(inp, mat1, mat2, *, alpha=1, beta=1, layout=None): + m, n, k, layout, mat1, mat2, inp_expanded = mm_args(mat1, mat2, inp, layout=layout) + if m * n == 0 or not use_max_autotune(): + choices = ( + [ + aten_addmm.bind( + (inp, mat1, mat2), + layout, + alpha=alpha, + beta=beta, + ) + ] + if use_aten_gemm_kernels() + else [] + ) + return autotune_select_algorithm("addmm", choices, [inp, mat1, mat2], layout) + + choices = ( + [ + aten_addmm.bind( + (inp_expanded, mat1, mat2), + layout, + alpha=alpha, + beta=beta, + ) + ] + if use_aten_gemm_kernels() + else [] + ) + + if ( + use_aten_gemm_kernels() + and inp_expanded.get_stride()[0] == 0 + and inp_expanded.get_device().type == "cuda" + and inductor_config.triton.autotune_cublasLt + ): + # unexpand inp to make sure fused addmm from cublasLt is used + choices.insert( + 0, + aten_bias_addmm.bind( + (inp_expanded, mat1, mat2), layout, alpha=alpha, beta=beta + ), + ) + + if use_triton_template(layout): + for config in mm_configs(m, n, k): + mm_template.maybe_append_choice( + choices, + input_nodes=(inp_expanded, mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout), + prefix_args=1, + epilogue_fn=addmm_epilogue(layout.dtype, alpha, beta), + ) + + if use_cutlass_template(layout): + CUTLASSGemmTemplate.add_cutlass_gemm_choices( + choices, + layout, + [mat1, mat2, inp_expanded], + alpha=alpha, + beta=beta, + input_reorder=[2, 0, 1], + fuseable=False, + ) + + return autotune_select_algorithm( + "addmm", choices, [inp_expanded, mat1, mat2], layout + ) + + +def fallback_mixed_mm(mat1, mat2, *, out): + return torch.mm(mat1, mat2.to(mat1.dtype), out=out) + + +aten_fallback_mixed_mm = ExternKernelChoice(fallback_mixed_mm, None) + + +@functools.lru_cache(None) +def _is_sm7x_or_older_gpu(index: Optional[int]) -> bool: + props = torch.cuda.get_device_properties(index or 0) + return props.major <= 7 + + +def tuned_mixed_mm(mat1, mat2, mat2_dtype): + m, n, k, layout, mat1, mat2 = mm_args(mat1, mat2, layout=None) + choices = [aten_fallback_mixed_mm.bind((mat1, mat2), layout)] + if ( + mat1.layout.dtype != torch.float32 and not mat2.layout.is_contiguous() + ) or _is_sm7x_or_older_gpu(layout.device.index): + # can't use triton kernel unless one of these is true or if running on v100 (numerical issues) + return autotune_select_algorithm("mixed_mm", choices, [mat1, mat2], layout) + if inductor_config.force_mixed_mm: + choices = [] + b_prologue_cast_type = f"tl.{mat2_dtype}".replace("torch.", "") + has_int8_tensor = _is_int8_mat(mat1) or _is_int8_mat(mat2) + for config in mm_configs(m, n, k, has_int8_tensor=has_int8_tensor): + mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout, b_prologue_cast_type), + ) + return autotune_select_algorithm("mixed_mm", choices, [mat1, mat2], layout) + + +# This op is a special case of the int_mm op which we use based on the pattern +# _int_mm -> mul (defined in ../fx_passes/post_grad.py) in order to prevent +# realization of the int32 _int_mm output by forcing fusion with the mul op. +# This is only used when config.force_fuse_int_mm_with_mul = True +def tuned_fused_int_mm_mul(mat1, mat2, mat3, out_dtype, *, layout=None): + out_dtype = ( + torch.promote_types(mat3.get_dtype(), torch.int32) + if out_dtype is None + else out_dtype + ) + m, n, k, layout, mat1, mat2, mat3 = mm_args( + mat1, mat2, mat3, layout=layout, out_dtype=out_dtype + ) + choices: List[Dict[Any, Any]] = [] + for config in int8_mm_configs(m, n, k): + mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2, mat3), + layout=layout, + **dict(mm_options(config, m, n, k, layout), ACC_TYPE="tl.int32"), + suffix_args=1, + epilogue_fn=V.ops.mul, + ) + return autotune_select_algorithm("int_mm", choices, [mat1, mat2, mat3], layout) diff --git a/shared/package-files/02/02ab77e64affa7271244adb9344ecaa6a7e299bc8bce0b41302ad820d987253a/_sparse_csr_prod_compositeexplicitautograd_dispatch.h b/shared/package-files/02/02ab77e64affa7271244adb9344ecaa6a7e299bc8bce0b41302ad820d987253a/_sparse_csr_prod_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1a72c61e577cc0118e2b160ba7587428dfc06de9 --- /dev/null +++ b/shared/package-files/02/02ab77e64affa7271244adb9344ecaa6a7e299bc8bce0b41302ad820d987253a/_sparse_csr_prod_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 & _sparse_csr_prod_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef dim, bool keepdim=false, c10::optional dtype=c10::nullopt); +TORCH_API at::Tensor & _sparse_csr_prod_outf(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/02/02abcb4fa33cd63635dd86e95feb3e84ecc2573d0018d91927da26dffb69e159/page_index.h b/shared/package-files/02/02abcb4fa33cd63635dd86e95feb3e84ecc2573d0018d91927da26dffb69e159/page_index.h new file mode 100644 index 0000000000000000000000000000000000000000..3083159783ba793763f221c4b01c91ff6efef304 --- /dev/null +++ b/shared/package-files/02/02abcb4fa33cd63635dd86e95feb3e84ecc2573d0018d91927da26dffb69e159/page_index.h @@ -0,0 +1,386 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/io/interfaces.h" +#include "parquet/encryption/type_fwd.h" +#include "parquet/type_fwd.h" +#include "parquet/types.h" + +#include +#include + +namespace parquet { + +/// \brief ColumnIndex is a proxy around format::ColumnIndex. +class PARQUET_EXPORT ColumnIndex { + public: + /// \brief Create a ColumnIndex from a serialized thrift message. + static std::unique_ptr Make(const ColumnDescriptor& descr, + const void* serialized_index, + uint32_t index_len, + const ReaderProperties& properties, + Decryptor* decryptor = NULLPTR); + + virtual ~ColumnIndex() = default; + + /// \brief A bitmap with a bit set for each data page that has only null values. + /// + /// The length of this vector is equal to the number of data pages in the column. + virtual const std::vector& null_pages() const = 0; + + /// \brief A vector of encoded lower bounds for each data page in this column. + /// + /// `null_pages` should be inspected first, as only pages with non-null values + /// may have their lower bounds populated. + virtual const std::vector& encoded_min_values() const = 0; + + /// \brief A vector of encoded upper bounds for each data page in this column. + /// + /// `null_pages` should be inspected first, as only pages with non-null values + /// may have their upper bounds populated. + virtual const std::vector& encoded_max_values() const = 0; + + /// \brief The ordering of lower and upper bounds. + /// + /// The boundary order applies across all lower bounds, and all upper bounds, + /// respectively. However, the order between lower bounds and upper bounds + /// cannot be derived from this. + virtual BoundaryOrder::type boundary_order() const = 0; + + /// \brief Whether per-page null count information is available. + virtual bool has_null_counts() const = 0; + + /// \brief An optional vector with the number of null values in each data page. + /// + /// `has_null_counts` should be called first to determine if this information is + /// available. + virtual const std::vector& null_counts() const = 0; + + /// \brief A vector of page indices for non-null pages. + virtual const std::vector& non_null_page_indices() const = 0; + + /// \brief Whether definition level histogram is available. + virtual bool has_definition_level_histograms() const = 0; + + /// \brief Whether repetition level histogram is available. + virtual bool has_repetition_level_histograms() const = 0; + + /// \brief List of definition level histograms for each page concatenated together. + virtual const std::vector& definition_level_histograms() const = 0; + + /// \brief List of repetition level histograms for each page concatenated together. + virtual const std::vector& repetition_level_histograms() const = 0; +}; + +/// \brief Typed implementation of ColumnIndex. +template +class PARQUET_EXPORT TypedColumnIndex : public ColumnIndex { + public: + using T = typename DType::c_type; + + /// \brief A vector of lower bounds for each data page in this column. + /// + /// This is like `encoded_min_values`, but with the values decoded according to + /// the column's physical type. + /// `min_values` and `max_values` can be used together with `boundary_order` + /// in order to prune some data pages when searching for specific values. + virtual const std::vector& min_values() const = 0; + + /// \brief A vector of upper bounds for each data page in this column. + /// + /// Just like `min_values`, but for upper bounds instead of lower bounds. + virtual const std::vector& max_values() const = 0; +}; + +using BoolColumnIndex = TypedColumnIndex; +using Int32ColumnIndex = TypedColumnIndex; +using Int64ColumnIndex = TypedColumnIndex; +using FloatColumnIndex = TypedColumnIndex; +using DoubleColumnIndex = TypedColumnIndex; +using ByteArrayColumnIndex = TypedColumnIndex; +using FLBAColumnIndex = TypedColumnIndex; + +/// \brief PageLocation is a proxy around format::PageLocation. +struct PARQUET_EXPORT PageLocation { + /// File offset of the data page. + int64_t offset; + /// Total compressed size of the data page and header. + int32_t compressed_page_size; + /// Row id of the first row in the page within the row group. + int64_t first_row_index; +}; + +/// \brief OffsetIndex is a proxy around format::OffsetIndex. +class PARQUET_EXPORT OffsetIndex { + public: + /// \brief Create a OffsetIndex from a serialized thrift message. + static std::unique_ptr Make(const void* serialized_index, + uint32_t index_len, + const ReaderProperties& properties, + Decryptor* decryptor = NULLPTR); + + virtual ~OffsetIndex() = default; + + /// \brief A vector of locations for each data page in this column. + virtual const std::vector& page_locations() const = 0; + + /// \brief A vector of unencoded/uncompressed size of each page for BYTE_ARRAY types, + /// or empty for other types. + virtual const std::vector& unencoded_byte_array_data_bytes() const = 0; +}; + +/// \brief Interface for reading the page index for a Parquet row group. +class PARQUET_EXPORT RowGroupPageIndexReader { + public: + virtual ~RowGroupPageIndexReader() = default; + + /// \brief Read column index of a column chunk. + /// + /// \param[in] i column ordinal of the column chunk. + /// \returns column index of the column or nullptr if it does not exist. + /// \throws ParquetException if the index is out of bound. + virtual std::shared_ptr GetColumnIndex(int32_t i) = 0; + + /// \brief Read offset index of a column chunk. + /// + /// \param[in] i column ordinal of the column chunk. + /// \returns offset index of the column or nullptr if it does not exist. + /// \throws ParquetException if the index is out of bound. + virtual std::shared_ptr GetOffsetIndex(int32_t i) = 0; +}; + +struct PageIndexSelection { + /// Specifies whether to read the column index. + bool column_index = false; + /// Specifies whether to read the offset index. + bool offset_index = false; +}; + +PARQUET_EXPORT +std::ostream& operator<<(std::ostream& out, const PageIndexSelection& params); + +struct RowGroupIndexReadRange { + /// Base start and total size of column index of all column chunks in a row group. + /// If none of the column chunks have column index, it is set to std::nullopt. + std::optional<::arrow::io::ReadRange> column_index = std::nullopt; + /// Base start and total size of offset index of all column chunks in a row group. + /// If none of the column chunks have offset index, it is set to std::nullopt. + std::optional<::arrow::io::ReadRange> offset_index = std::nullopt; +}; + +/// \brief Interface for reading the page index for a Parquet file. +class PARQUET_EXPORT PageIndexReader { + public: + virtual ~PageIndexReader() = default; + + /// \brief Create a PageIndexReader instance. + /// \returns a PageIndexReader instance. + /// WARNING: The returned PageIndexReader references to all the input parameters, so + /// it must not outlive all of the input parameters. Usually these input parameters + /// come from the same ParquetFileReader object, so it must not outlive the reader + /// that creates this PageIndexReader. + static std::shared_ptr Make( + ::arrow::io::RandomAccessFile* input, std::shared_ptr file_metadata, + const ReaderProperties& properties, + InternalFileDecryptor* file_decryptor = NULLPTR); + + /// \brief Get the page index reader of a specific row group. + /// \param[in] i row group ordinal to get page index reader. + /// \returns RowGroupPageIndexReader of the specified row group. A nullptr may or may + /// not be returned if the page index for the row group is unavailable. It is + /// the caller's responsibility to check the return value of follow-up calls + /// to the RowGroupPageIndexReader. + /// \throws ParquetException if the index is out of bound. + virtual std::shared_ptr RowGroup(int i) = 0; + + /// \brief Advise the reader which part of page index will be read later. + /// + /// The PageIndexReader can optionally prefetch and cache page index that + /// may be read later to get better performance. + /// + /// The contract of this function is as below: + /// 1) If WillNeed() has not been called for a specific row group and the page index + /// exists, follow-up calls to get column index or offset index of all columns in + /// this row group SHOULD NOT FAIL, but the performance may not be optimal. + /// 2) If WillNeed() has been called for a specific row group, follow-up calls to get + /// page index are limited to columns and index type requested by WillNeed(). + /// So it MAY FAIL if columns that are not requested by WillNeed() are requested. + /// 3) Later calls to WillNeed() MAY OVERRIDE previous calls of same row groups. + /// For example, + /// 1) If WillNeed() is not called for row group 0, then follow-up calls to read + /// column index and/or offset index of all columns of row group 0 should not + /// fail if its page index exists. + /// 2) If WillNeed() is called for columns 0 and 1 for row group 0, then follow-up + /// call to read page index of column 2 for row group 0 MAY FAIL even if its + /// page index exists. + /// 3) If WillNeed() is called for row group 0 with offset index only, then + /// follow-up call to read column index of row group 0 MAY FAIL even if + /// the column index of this column exists. + /// 4) If WillNeed() is called for columns 0 and 1 for row group 0, then later + /// call to WillNeed() for columns 1 and 2 for row group 0. The later one + /// overrides previous call and only columns 1 and 2 of row group 0 are allowed + /// to access. + /// + /// \param[in] row_group_indices list of row group ordinal to read page index later. + /// \param[in] column_indices list of column ordinal to read page index later. If it is + /// empty, it means all columns in the row group will be read. + /// \param[in] selection which kind of page index is required later. + virtual void WillNeed(const std::vector& row_group_indices, + const std::vector& column_indices, + const PageIndexSelection& selection) = 0; + + /// \brief Advise the reader page index of these row groups will not be read anymore. + /// + /// The PageIndexReader implementation has the opportunity to cancel any prefetch or + /// release resource that are related to these row groups. + /// + /// \param[in] row_group_indices list of row group ordinal that whose page index will + /// not be accessed anymore. + virtual void WillNotNeed(const std::vector& row_group_indices) = 0; + + /// \brief Determine the column index and offset index ranges for the given row group. + /// + /// \param[in] row_group_metadata row group metadata to get column chunk metadata. + /// \param[in] columns list of column ordinals to get page index. If the list is empty, + /// it means all columns in the row group. + /// \returns RowGroupIndexReadRange of the specified row group. Throws ParquetException + /// if the selected column ordinal is out of bound or metadata of page index + /// is corrupted. + static RowGroupIndexReadRange DeterminePageIndexRangesInRowGroup( + const RowGroupMetaData& row_group_metadata, const std::vector& columns); +}; + +/// \brief Interface for collecting column index of data pages in a column chunk. +class PARQUET_EXPORT ColumnIndexBuilder { + public: + /// \brief API convenience to create a ColumnIndexBuilder. + static std::unique_ptr Make(const ColumnDescriptor* descr); + + virtual ~ColumnIndexBuilder() = default; + + /// \brief Add statistics of a data page. + /// + /// If the ColumnIndexBuilder has seen any corrupted statistics, it will + /// not update statistics anymore. + /// + /// \param stats Page statistics in the encoded form. + /// \param size_stats Size statistics of the page if available. + virtual void AddPage(const EncodedStatistics& stats, + const SizeStatistics& size_stats) = 0; + + /// \brief Complete the column index. + /// + /// Once called, AddPage() can no longer be called. + /// WriteTo() and Build() can only called after Finish() has been called. + virtual void Finish() = 0; + + /// \brief Serialize the column index thrift message. + /// + /// If the ColumnIndexBuilder has seen any corrupted statistics, it will + /// not write any data to the sink. + /// + /// \param[out] sink output stream to write the serialized message. + /// \param[in] encryptor encryptor to encrypt the serialized column index. + virtual void WriteTo(::arrow::io::OutputStream* sink, + Encryptor* encryptor = NULLPTR) const = 0; + + /// \brief Create a ColumnIndex directly. + /// + /// \return If the ColumnIndexBuilder has seen any corrupted statistics, it simply + /// returns nullptr. Otherwise the column index is built and returned. + virtual std::unique_ptr Build() const = 0; +}; + +/// \brief Interface for collecting offset index of data pages in a column chunk. +class PARQUET_EXPORT OffsetIndexBuilder { + public: + /// \brief API convenience to create a OffsetIndexBuilder. + static std::unique_ptr Make(); + + virtual ~OffsetIndexBuilder() = default; + + /// \brief Add page location and size stats of a data page. + virtual void AddPage(int64_t offset, int32_t compressed_page_size, + int64_t first_row_index, + std::optional unencoded_byte_array_length = {}) = 0; + + /// \brief Add page location and size stats of a data page. + void AddPage(const PageLocation& page_location, const SizeStatistics& size_stats); + + /// \brief Complete the offset index. + /// + /// In the buffered row group mode, data pages are flushed into memory + /// sink and the OffsetIndexBuilder has only collected the relative offset + /// which requires adjustment once they are flushed to the file. + /// + /// \param final_position Final stream offset to add for page offset adjustment. + virtual void Finish(int64_t final_position) = 0; + + /// \brief Serialize the offset index thrift message. + /// + /// \param[out] sink output stream to write the serialized message. + /// \param[in] encryptor encryptor to encrypt the serialized offset index. + virtual void WriteTo(::arrow::io::OutputStream* sink, + Encryptor* encryptor = NULLPTR) const = 0; + + /// \brief Create an OffsetIndex directly. + virtual std::unique_ptr Build() const = 0; +}; + +/// \brief Interface for collecting page index of a parquet file. +class PARQUET_EXPORT PageIndexBuilder { + public: + /// \brief API convenience to create a PageIndexBuilder. + static std::unique_ptr Make( + const SchemaDescriptor* schema, InternalFileEncryptor* file_encryptor = NULLPTR); + + virtual ~PageIndexBuilder() = default; + + /// \brief Start a new row group. + virtual void AppendRowGroup() = 0; + + /// \brief Get the ColumnIndexBuilder from column ordinal. + /// + /// \param i Column ordinal. + /// \return ColumnIndexBuilder for the column and its memory ownership belongs to + /// the PageIndexBuilder. + virtual ColumnIndexBuilder* GetColumnIndexBuilder(int32_t i) = 0; + + /// \brief Get the OffsetIndexBuilder from column ordinal. + /// + /// \param i Column ordinal. + /// \return OffsetIndexBuilder for the column and its memory ownership belongs to + /// the PageIndexBuilder. + virtual OffsetIndexBuilder* GetOffsetIndexBuilder(int32_t i) = 0; + + /// \brief Complete the page index builder and no more write is allowed. + virtual void Finish() = 0; + + /// \brief Serialize the page index thrift message. + /// + /// Only valid column indexes and offset indexes are serialized and their locations + /// are set. + /// + /// \param[out] sink The output stream to write the page index. + /// \param[out] location The location of all page index to the start of sink. + virtual void WriteTo(::arrow::io::OutputStream* sink, + PageIndexLocation* location) const = 0; +}; + +} // namespace parquet diff --git a/shared/package-files/02/02ac97a40d854050fb93e6ee06dcbfee2b461189219956bc5f4f4d2d1ba5dd03/escsm.py b/shared/package-files/02/02ac97a40d854050fb93e6ee06dcbfee2b461189219956bc5f4f4d2d1ba5dd03/escsm.py new file mode 100644 index 0000000000000000000000000000000000000000..11d4adf771f3f90bb5f1cc11043599b48e955c22 --- /dev/null +++ b/shared/package-files/02/02ac97a40d854050fb93e6ee06dcbfee2b461189219956bc5f4f4d2d1ba5dd03/escsm.py @@ -0,0 +1,261 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library 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 2.1 of the License, or (at your option) any later version. +# +# This library 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 this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .codingstatemachinedict import CodingStateMachineDict +from .enums import MachineState + +# fmt: off +HZ_CLS = ( + 1, 0, 0, 0, 0, 0, 0, 0, # 00 - 07 + 0, 0, 0, 0, 0, 0, 0, 0, # 08 - 0f + 0, 0, 0, 0, 0, 0, 0, 0, # 10 - 17 + 0, 0, 0, 1, 0, 0, 0, 0, # 18 - 1f + 0, 0, 0, 0, 0, 0, 0, 0, # 20 - 27 + 0, 0, 0, 0, 0, 0, 0, 0, # 28 - 2f + 0, 0, 0, 0, 0, 0, 0, 0, # 30 - 37 + 0, 0, 0, 0, 0, 0, 0, 0, # 38 - 3f + 0, 0, 0, 0, 0, 0, 0, 0, # 40 - 47 + 0, 0, 0, 0, 0, 0, 0, 0, # 48 - 4f + 0, 0, 0, 0, 0, 0, 0, 0, # 50 - 57 + 0, 0, 0, 0, 0, 0, 0, 0, # 58 - 5f + 0, 0, 0, 0, 0, 0, 0, 0, # 60 - 67 + 0, 0, 0, 0, 0, 0, 0, 0, # 68 - 6f + 0, 0, 0, 0, 0, 0, 0, 0, # 70 - 77 + 0, 0, 0, 4, 0, 5, 2, 0, # 78 - 7f + 1, 1, 1, 1, 1, 1, 1, 1, # 80 - 87 + 1, 1, 1, 1, 1, 1, 1, 1, # 88 - 8f + 1, 1, 1, 1, 1, 1, 1, 1, # 90 - 97 + 1, 1, 1, 1, 1, 1, 1, 1, # 98 - 9f + 1, 1, 1, 1, 1, 1, 1, 1, # a0 - a7 + 1, 1, 1, 1, 1, 1, 1, 1, # a8 - af + 1, 1, 1, 1, 1, 1, 1, 1, # b0 - b7 + 1, 1, 1, 1, 1, 1, 1, 1, # b8 - bf + 1, 1, 1, 1, 1, 1, 1, 1, # c0 - c7 + 1, 1, 1, 1, 1, 1, 1, 1, # c8 - cf + 1, 1, 1, 1, 1, 1, 1, 1, # d0 - d7 + 1, 1, 1, 1, 1, 1, 1, 1, # d8 - df + 1, 1, 1, 1, 1, 1, 1, 1, # e0 - e7 + 1, 1, 1, 1, 1, 1, 1, 1, # e8 - ef + 1, 1, 1, 1, 1, 1, 1, 1, # f0 - f7 + 1, 1, 1, 1, 1, 1, 1, 1, # f8 - ff +) + +HZ_ST = ( +MachineState.START, MachineState.ERROR, 3, MachineState.START, MachineState.START, MachineState.START, MachineState.ERROR, MachineState.ERROR, # 00-07 +MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 08-0f +MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.START, MachineState.START, 4, MachineState.ERROR, # 10-17 + 5, MachineState.ERROR, 6, MachineState.ERROR, 5, 5, 4, MachineState.ERROR, # 18-1f + 4, MachineState.ERROR, 4, 4, 4, MachineState.ERROR, 4, MachineState.ERROR, # 20-27 + 4, MachineState.ITS_ME, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 28-2f +) +# fmt: on + +HZ_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0) + +HZ_SM_MODEL: CodingStateMachineDict = { + "class_table": HZ_CLS, + "class_factor": 6, + "state_table": HZ_ST, + "char_len_table": HZ_CHAR_LEN_TABLE, + "name": "HZ-GB-2312", + "language": "Chinese", +} + +# fmt: off +ISO2022CN_CLS = ( + 2, 0, 0, 0, 0, 0, 0, 0, # 00 - 07 + 0, 0, 0, 0, 0, 0, 0, 0, # 08 - 0f + 0, 0, 0, 0, 0, 0, 0, 0, # 10 - 17 + 0, 0, 0, 1, 0, 0, 0, 0, # 18 - 1f + 0, 0, 0, 0, 0, 0, 0, 0, # 20 - 27 + 0, 3, 0, 0, 0, 0, 0, 0, # 28 - 2f + 0, 0, 0, 0, 0, 0, 0, 0, # 30 - 37 + 0, 0, 0, 0, 0, 0, 0, 0, # 38 - 3f + 0, 0, 0, 4, 0, 0, 0, 0, # 40 - 47 + 0, 0, 0, 0, 0, 0, 0, 0, # 48 - 4f + 0, 0, 0, 0, 0, 0, 0, 0, # 50 - 57 + 0, 0, 0, 0, 0, 0, 0, 0, # 58 - 5f + 0, 0, 0, 0, 0, 0, 0, 0, # 60 - 67 + 0, 0, 0, 0, 0, 0, 0, 0, # 68 - 6f + 0, 0, 0, 0, 0, 0, 0, 0, # 70 - 77 + 0, 0, 0, 0, 0, 0, 0, 0, # 78 - 7f + 2, 2, 2, 2, 2, 2, 2, 2, # 80 - 87 + 2, 2, 2, 2, 2, 2, 2, 2, # 88 - 8f + 2, 2, 2, 2, 2, 2, 2, 2, # 90 - 97 + 2, 2, 2, 2, 2, 2, 2, 2, # 98 - 9f + 2, 2, 2, 2, 2, 2, 2, 2, # a0 - a7 + 2, 2, 2, 2, 2, 2, 2, 2, # a8 - af + 2, 2, 2, 2, 2, 2, 2, 2, # b0 - b7 + 2, 2, 2, 2, 2, 2, 2, 2, # b8 - bf + 2, 2, 2, 2, 2, 2, 2, 2, # c0 - c7 + 2, 2, 2, 2, 2, 2, 2, 2, # c8 - cf + 2, 2, 2, 2, 2, 2, 2, 2, # d0 - d7 + 2, 2, 2, 2, 2, 2, 2, 2, # d8 - df + 2, 2, 2, 2, 2, 2, 2, 2, # e0 - e7 + 2, 2, 2, 2, 2, 2, 2, 2, # e8 - ef + 2, 2, 2, 2, 2, 2, 2, 2, # f0 - f7 + 2, 2, 2, 2, 2, 2, 2, 2, # f8 - ff +) + +ISO2022CN_ST = ( + MachineState.START, 3, MachineState.ERROR, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 00-07 + MachineState.START, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 08-0f + MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 10-17 + MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, 4, MachineState.ERROR, # 18-1f + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 20-27 + 5, 6, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 28-2f + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 30-37 + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.START, # 38-3f +) +# fmt: on + +ISO2022CN_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0, 0, 0, 0) + +ISO2022CN_SM_MODEL: CodingStateMachineDict = { + "class_table": ISO2022CN_CLS, + "class_factor": 9, + "state_table": ISO2022CN_ST, + "char_len_table": ISO2022CN_CHAR_LEN_TABLE, + "name": "ISO-2022-CN", + "language": "Chinese", +} + +# fmt: off +ISO2022JP_CLS = ( + 2, 0, 0, 0, 0, 0, 0, 0, # 00 - 07 + 0, 0, 0, 0, 0, 0, 2, 2, # 08 - 0f + 0, 0, 0, 0, 0, 0, 0, 0, # 10 - 17 + 0, 0, 0, 1, 0, 0, 0, 0, # 18 - 1f + 0, 0, 0, 0, 7, 0, 0, 0, # 20 - 27 + 3, 0, 0, 0, 0, 0, 0, 0, # 28 - 2f + 0, 0, 0, 0, 0, 0, 0, 0, # 30 - 37 + 0, 0, 0, 0, 0, 0, 0, 0, # 38 - 3f + 6, 0, 4, 0, 8, 0, 0, 0, # 40 - 47 + 0, 9, 5, 0, 0, 0, 0, 0, # 48 - 4f + 0, 0, 0, 0, 0, 0, 0, 0, # 50 - 57 + 0, 0, 0, 0, 0, 0, 0, 0, # 58 - 5f + 0, 0, 0, 0, 0, 0, 0, 0, # 60 - 67 + 0, 0, 0, 0, 0, 0, 0, 0, # 68 - 6f + 0, 0, 0, 0, 0, 0, 0, 0, # 70 - 77 + 0, 0, 0, 0, 0, 0, 0, 0, # 78 - 7f + 2, 2, 2, 2, 2, 2, 2, 2, # 80 - 87 + 2, 2, 2, 2, 2, 2, 2, 2, # 88 - 8f + 2, 2, 2, 2, 2, 2, 2, 2, # 90 - 97 + 2, 2, 2, 2, 2, 2, 2, 2, # 98 - 9f + 2, 2, 2, 2, 2, 2, 2, 2, # a0 - a7 + 2, 2, 2, 2, 2, 2, 2, 2, # a8 - af + 2, 2, 2, 2, 2, 2, 2, 2, # b0 - b7 + 2, 2, 2, 2, 2, 2, 2, 2, # b8 - bf + 2, 2, 2, 2, 2, 2, 2, 2, # c0 - c7 + 2, 2, 2, 2, 2, 2, 2, 2, # c8 - cf + 2, 2, 2, 2, 2, 2, 2, 2, # d0 - d7 + 2, 2, 2, 2, 2, 2, 2, 2, # d8 - df + 2, 2, 2, 2, 2, 2, 2, 2, # e0 - e7 + 2, 2, 2, 2, 2, 2, 2, 2, # e8 - ef + 2, 2, 2, 2, 2, 2, 2, 2, # f0 - f7 + 2, 2, 2, 2, 2, 2, 2, 2, # f8 - ff +) + +ISO2022JP_ST = ( + MachineState.START, 3, MachineState.ERROR, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 00-07 + MachineState.START, MachineState.START, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 08-0f + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 10-17 + MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, # 18-1f + MachineState.ERROR, 5, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, 4, MachineState.ERROR, MachineState.ERROR, # 20-27 + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, 6, MachineState.ITS_ME, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, # 28-2f + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, # 30-37 + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 38-3f + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.START, MachineState.START, # 40-47 +) +# fmt: on + +ISO2022JP_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + +ISO2022JP_SM_MODEL: CodingStateMachineDict = { + "class_table": ISO2022JP_CLS, + "class_factor": 10, + "state_table": ISO2022JP_ST, + "char_len_table": ISO2022JP_CHAR_LEN_TABLE, + "name": "ISO-2022-JP", + "language": "Japanese", +} + +# fmt: off +ISO2022KR_CLS = ( + 2, 0, 0, 0, 0, 0, 0, 0, # 00 - 07 + 0, 0, 0, 0, 0, 0, 0, 0, # 08 - 0f + 0, 0, 0, 0, 0, 0, 0, 0, # 10 - 17 + 0, 0, 0, 1, 0, 0, 0, 0, # 18 - 1f + 0, 0, 0, 0, 3, 0, 0, 0, # 20 - 27 + 0, 4, 0, 0, 0, 0, 0, 0, # 28 - 2f + 0, 0, 0, 0, 0, 0, 0, 0, # 30 - 37 + 0, 0, 0, 0, 0, 0, 0, 0, # 38 - 3f + 0, 0, 0, 5, 0, 0, 0, 0, # 40 - 47 + 0, 0, 0, 0, 0, 0, 0, 0, # 48 - 4f + 0, 0, 0, 0, 0, 0, 0, 0, # 50 - 57 + 0, 0, 0, 0, 0, 0, 0, 0, # 58 - 5f + 0, 0, 0, 0, 0, 0, 0, 0, # 60 - 67 + 0, 0, 0, 0, 0, 0, 0, 0, # 68 - 6f + 0, 0, 0, 0, 0, 0, 0, 0, # 70 - 77 + 0, 0, 0, 0, 0, 0, 0, 0, # 78 - 7f + 2, 2, 2, 2, 2, 2, 2, 2, # 80 - 87 + 2, 2, 2, 2, 2, 2, 2, 2, # 88 - 8f + 2, 2, 2, 2, 2, 2, 2, 2, # 90 - 97 + 2, 2, 2, 2, 2, 2, 2, 2, # 98 - 9f + 2, 2, 2, 2, 2, 2, 2, 2, # a0 - a7 + 2, 2, 2, 2, 2, 2, 2, 2, # a8 - af + 2, 2, 2, 2, 2, 2, 2, 2, # b0 - b7 + 2, 2, 2, 2, 2, 2, 2, 2, # b8 - bf + 2, 2, 2, 2, 2, 2, 2, 2, # c0 - c7 + 2, 2, 2, 2, 2, 2, 2, 2, # c8 - cf + 2, 2, 2, 2, 2, 2, 2, 2, # d0 - d7 + 2, 2, 2, 2, 2, 2, 2, 2, # d8 - df + 2, 2, 2, 2, 2, 2, 2, 2, # e0 - e7 + 2, 2, 2, 2, 2, 2, 2, 2, # e8 - ef + 2, 2, 2, 2, 2, 2, 2, 2, # f0 - f7 + 2, 2, 2, 2, 2, 2, 2, 2, # f8 - ff +) + +ISO2022KR_ST = ( + MachineState.START, 3, MachineState.ERROR, MachineState.START, MachineState.START, MachineState.START, MachineState.ERROR, MachineState.ERROR, # 00-07 + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 08-0f + MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, 4, MachineState.ERROR, MachineState.ERROR, # 10-17 + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, 5, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 18-1f + MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 20-27 +) +# fmt: on + +ISO2022KR_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0) + +ISO2022KR_SM_MODEL: CodingStateMachineDict = { + "class_table": ISO2022KR_CLS, + "class_factor": 6, + "state_table": ISO2022KR_ST, + "char_len_table": ISO2022KR_CHAR_LEN_TABLE, + "name": "ISO-2022-KR", + "language": "Korean", +} diff --git a/shared/package-files/02/02acf7b279d2afc61cd52ebb0170e937047e6c778f79a5d6807ead107395fc79/fmax_cuda_dispatch.h b/shared/package-files/02/02acf7b279d2afc61cd52ebb0170e937047e6c778f79a5d6807ead107395fc79/fmax_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..97054aebdf2a440f0f51abf4f003663fc6d05c32 --- /dev/null +++ b/shared/package-files/02/02acf7b279d2afc61cd52ebb0170e937047e6c778f79a5d6807ead107395fc79/fmax_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 fmax(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & fmax_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & fmax_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/02/02b17245e8675290cf2a25f5732ca39e8ffa4f279c97a482e177a0694491d956/square_compositeimplicitautograd_dispatch.h b/shared/package-files/02/02b17245e8675290cf2a25f5732ca39e8ffa4f279c97a482e177a0694491d956/square_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..82e8a9f3909816ffca6d42ea8319030a2f9064b8 --- /dev/null +++ b/shared/package-files/02/02b17245e8675290cf2a25f5732ca39e8ffa4f279c97a482e177a0694491d956/square_compositeimplicitautograd_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 compositeimplicitautograd { + +TORCH_API at::Tensor square(const at::Tensor & self); +TORCH_API at::Tensor & square_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & square_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & square_(at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/02/02b59342720a8710d568c2358f45a1829934722e9d3f49a95221b0311a8476d6/__init__.py b/shared/package-files/02/02b59342720a8710d568c2358f45a1829934722e9d3f49a95221b0311a8476d6/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4e7a62834b57c151189cdd2994a55d1ad9f7de --- /dev/null +++ b/shared/package-files/02/02b59342720a8710d568c2358f45a1829934722e9d3f49a95221b0311a8476d6/__init__.py @@ -0,0 +1,15 @@ +from pandas.io.json._json import ( + read_json, + to_json, + ujson_dumps, + ujson_loads, +) +from pandas.io.json._table_schema import build_table_schema + +__all__ = [ + "ujson_dumps", + "ujson_loads", + "read_json", + "to_json", + "build_table_schema", +] diff --git a/shared/package-files/02/02b8bdb5addc5d40b6458afe2ad39594b805eaab580d5ef4162907b992c84a93/_test_warn_in_autograd_native.h b/shared/package-files/02/02b8bdb5addc5d40b6458afe2ad39594b805eaab580d5ef4162907b992c84a93/_test_warn_in_autograd_native.h new file mode 100644 index 0000000000000000000000000000000000000000..52a0ee9ecf4085641ffe3dae61d30e162d2a13b6 --- /dev/null +++ b/shared/package-files/02/02b8bdb5addc5d40b6458afe2ad39594b805eaab580d5ef4162907b992c84a93/_test_warn_in_autograd_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 _test_warn_in_autograd(const at::Tensor & self); +TORCH_API at::Tensor & _test_warn_in_autograd_out(const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/02/02b9cbca40360206050281b16e3954423f5bcb5683e41ceee8102706d092f558/rxvt-16color b/shared/package-files/02/02b9cbca40360206050281b16e3954423f5bcb5683e41ceee8102706d092f558/rxvt-16color new file mode 100644 index 0000000000000000000000000000000000000000..6fcc3e8746dbc4462ee7179f9c88d02c54004550 Binary files /dev/null and b/shared/package-files/02/02b9cbca40360206050281b16e3954423f5bcb5683e41ceee8102706d092f558/rxvt-16color differ diff --git a/shared/package-files/02/02bb17b868bed59c3670b4344c7de94251c7fada6f12c8fd14484d049f160fb6/test_break_on_symbol.py b/shared/package-files/02/02bb17b868bed59c3670b4344c7de94251c7fada6f12c8fd14484d049f160fb6/test_break_on_symbol.py new file mode 100644 index 0000000000000000000000000000000000000000..7743aafc3bebc87db5257452c34ada5b1cf5b682 --- /dev/null +++ b/shared/package-files/02/02bb17b868bed59c3670b4344c7de94251c7fada6f12c8fd14484d049f160fb6/test_break_on_symbol.py @@ -0,0 +1,34 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit, types +from numba.tests.gdb_support import GdbMIDriver +from numba.tests.support import TestCase, needs_subprocess +import unittest + + +@njit(debug=True) +def foo(x): + z = 7 + x + return x, z + + +@needs_subprocess +class Test(TestCase): + + def test(self): + foo(120) + sz = types.intp.bitwidth + driver = GdbMIDriver(__file__) + driver.set_breakpoint(symbol="__main__::foo") + driver.run() # will hit cpython symbol match + driver.check_hit_breakpoint(number=1) + driver.cont() # will hit njit symbol match + driver.check_hit_breakpoint(number=1, line=10) # Ensure line number + driver.stack_list_arguments(2) + expect = ('[frame={level="0",args=[{name="x",type="int%s",' + 'value="120"}]}]' % sz) + driver.assert_output(expect) + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/02/02bbfd58b6df84d72946c5231c353be7b044770969d3c1addf4022c46de0674e/Menominee b/shared/package-files/02/02bbfd58b6df84d72946c5231c353be7b044770969d3c1addf4022c46de0674e/Menominee new file mode 100644 index 0000000000000000000000000000000000000000..314613866de53e1457f6cbf2fb617be7e4955edf Binary files /dev/null and b/shared/package-files/02/02bbfd58b6df84d72946c5231c353be7b044770969d3c1addf4022c46de0674e/Menominee differ diff --git a/shared/package-files/02/02bcf2537526355483490f3fe1f5d9ea48fad958bac7e32bfb562b886a1c31c5/mod24 b/shared/package-files/02/02bcf2537526355483490f3fe1f5d9ea48fad958bac7e32bfb562b886a1c31c5/mod24 new file mode 100644 index 0000000000000000000000000000000000000000..82943877827a843ffbf24d989b1c99bed58e65ce Binary files /dev/null and b/shared/package-files/02/02bcf2537526355483490f3fe1f5d9ea48fad958bac7e32bfb562b886a1c31c5/mod24 differ diff --git a/shared/package-files/02/02bcf2537526355483490f3fe1f5d9ea48fad958bac7e32bfb562b886a1c31c5/modgraph b/shared/package-files/02/02bcf2537526355483490f3fe1f5d9ea48fad958bac7e32bfb562b886a1c31c5/modgraph new file mode 100644 index 0000000000000000000000000000000000000000..82943877827a843ffbf24d989b1c99bed58e65ce Binary files /dev/null and b/shared/package-files/02/02bcf2537526355483490f3fe1f5d9ea48fad958bac7e32bfb562b886a1c31c5/modgraph differ diff --git a/shared/package-files/02/02be867bd513db9c9b0ac32713c478d2f0e91ee7caf33873295456dd8c00daf0/stencilparfor.py b/shared/package-files/02/02be867bd513db9c9b0ac32713c478d2f0e91ee7caf33873295456dd8c00daf0/stencilparfor.py new file mode 100644 index 0000000000000000000000000000000000000000..3b80635d7586135b170c080fe396581ca014f75d --- /dev/null +++ b/shared/package-files/02/02be867bd513db9c9b0ac32713c478d2f0e91ee7caf33873295456dd8c00daf0/stencilparfor.py @@ -0,0 +1,957 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import numbers +import copy +import types as pytypes +from operator import add +import operator + +import numpy as np + +import numba.parfors.parfor +from numba.core import types, ir, rewrites, config, ir_utils +from numba.core.typing.templates import infer_global, AbstractTemplate +from numba.core.typing import signature +from numba.core import utils, typing +from numba.core.ir_utils import (get_call_table, mk_unique_var, + compile_to_numba_ir, replace_arg_nodes, guard, + find_callname, require, find_const, GuardException) +from numba.core.errors import NumbaValueError +from numba.core.utils import OPERATORS_TO_BUILTINS +from numba.np import numpy_support + + +def _compute_last_ind(dim_size, index_const): + if index_const > 0: + return dim_size - index_const + else: + return dim_size + +class StencilPass(object): + def __init__(self, func_ir, typemap, calltypes, array_analysis, typingctx, + targetctx, flags): + self.func_ir = func_ir + self.typemap = typemap + self.calltypes = calltypes + self.array_analysis = array_analysis + self.typingctx = typingctx + self.targetctx = targetctx + self.flags = flags + + def run(self): + """ Finds all calls to StencilFuncs in the IR and converts them to parfor. + """ + from numba.stencils.stencil import StencilFunc + + # Get all the calls in the function IR. + call_table, _ = get_call_table(self.func_ir.blocks) + stencil_calls = [] + stencil_dict = {} + for call_varname, call_list in call_table.items(): + for one_call in call_list: + if isinstance(one_call, StencilFunc): + # Remember all calls to StencilFuncs. + stencil_calls.append(call_varname) + stencil_dict[call_varname] = one_call + if not stencil_calls: + return # return early if no stencil calls found + + # find and transform stencil calls + for label, block in self.func_ir.blocks.items(): + for i, stmt in reversed(list(enumerate(block.body))): + # Found a call to a StencilFunc. + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'call' + and stmt.value.func.name in stencil_calls): + kws = dict(stmt.value.kws) + # Create dictionary of input argument number to + # the argument itself. + input_dict = {i: stmt.value.args[i] for i in + range(len(stmt.value.args))} + in_args = stmt.value.args + arg_typemap = tuple(self.typemap[i.name] for i in in_args) + for arg_type in arg_typemap: + if isinstance(arg_type, types.BaseTuple): + raise NumbaValueError("Tuple parameters not " \ + "supported for stencil " \ + "kernels in parallel=True " \ + "mode.") + + out_arr = kws.get('out') + + # Get the StencilFunc object corresponding to this call. + sf = stencil_dict[stmt.value.func.name] + stencil_ir, rt, arg_to_arr_dict = get_stencil_ir(sf, + self.typingctx, arg_typemap, + block.scope, block.loc, input_dict, + self.typemap, self.calltypes) + index_offsets = sf.options.get('index_offsets', None) + gen_nodes = self._mk_stencil_parfor(label, in_args, out_arr, + stencil_ir, index_offsets, stmt.target, rt, sf, + arg_to_arr_dict) + block.body = block.body[:i] + gen_nodes + block.body[i+1:] + # Found a call to a stencil via numba.stencil(). + elif (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'call' + and guard(find_callname, self.func_ir, stmt.value) + == ('stencil', 'numba')): + # remove dummy stencil() call + stmt.value = ir.Const(0, stmt.loc) + + def replace_return_with_setitem(self, blocks, exit_value_var, + parfor_body_exit_label): + """ + Find return statements in the IR and replace them with a SetItem + call of the value "returned" by the kernel into the result array. + Returns the block labels that contained return statements. + """ + for label, block in blocks.items(): + scope = block.scope + loc = block.loc + new_body = [] + for stmt in block.body: + if isinstance(stmt, ir.Return): + # previous stmt should have been a cast + prev_stmt = new_body.pop() + assert (isinstance(prev_stmt, ir.Assign) + and isinstance(prev_stmt.value, ir.Expr) + and prev_stmt.value.op == 'cast') + + new_body.append(ir.Assign(prev_stmt.value.value, exit_value_var, loc)) + new_body.append(ir.Jump(parfor_body_exit_label, loc)) + else: + new_body.append(stmt) + block.body = new_body + + def _mk_stencil_parfor(self, label, in_args, out_arr, stencil_ir, + index_offsets, target, return_type, stencil_func, + arg_to_arr_dict): + """ Converts a set of stencil kernel blocks to a parfor. + """ + gen_nodes = [] + stencil_blocks = stencil_ir.blocks + + if config.DEBUG_ARRAY_OPT >= 1: + print("_mk_stencil_parfor", label, in_args, out_arr, index_offsets, + return_type, stencil_func, stencil_blocks) + ir_utils.dump_blocks(stencil_blocks) + + in_arr = in_args[0] + # run copy propagate to replace in_args copies (e.g. a = A) + in_arr_typ = self.typemap[in_arr.name] + in_cps, out_cps = ir_utils.copy_propagate(stencil_blocks, self.typemap) + name_var_table = ir_utils.get_name_var_table(stencil_blocks) + + ir_utils.apply_copy_propagate( + stencil_blocks, + in_cps, + name_var_table, + self.typemap, + self.calltypes) + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after copy_propagate") + ir_utils.dump_blocks(stencil_blocks) + ir_utils.remove_dead(stencil_blocks, self.func_ir.arg_names, stencil_ir, + self.typemap) + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after removing dead code") + ir_utils.dump_blocks(stencil_blocks) + + # create parfor vars + ndims = self.typemap[in_arr.name].ndim + scope = in_arr.scope + loc = in_arr.loc + parfor_vars = [] + for i in range(ndims): + parfor_var = ir.Var(scope, mk_unique_var( + "$parfor_index_var"), loc) + self.typemap[parfor_var.name] = types.intp + parfor_vars.append(parfor_var) + + start_lengths, end_lengths = self._replace_stencil_accesses( + stencil_ir, parfor_vars, in_args, index_offsets, stencil_func, + arg_to_arr_dict) + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after replace stencil accesses") + print("start_lengths:", start_lengths) + print("end_lengths:", end_lengths) + ir_utils.dump_blocks(stencil_blocks) + + # create parfor loop nests + loopnests = [] + equiv_set = self.array_analysis.get_equiv_set(label) + in_arr_dim_sizes = equiv_set.get_shape(in_arr) + + assert ndims == len(in_arr_dim_sizes) + start_inds = [] + last_inds = [] + for i in range(ndims): + last_ind = self._get_stencil_last_ind(in_arr_dim_sizes[i], + end_lengths[i], gen_nodes, scope, loc) + start_ind = self._get_stencil_start_ind( + start_lengths[i], gen_nodes, scope, loc) + start_inds.append(start_ind) + last_inds.append(last_ind) + # start from stencil size to avoid invalid array access + loopnests.append(numba.parfors.parfor.LoopNest(parfor_vars[i], + start_ind, last_ind, 1)) + + # We have to guarantee that the exit block has maximum label and that + # there's only one exit block for the parfor body. + # So, all return statements will change to jump to the parfor exit block. + parfor_body_exit_label = max(stencil_blocks.keys()) + 1 + stencil_blocks[parfor_body_exit_label] = ir.Block(scope, loc) + exit_value_var = ir.Var(scope, mk_unique_var("$parfor_exit_value"), loc) + self.typemap[exit_value_var.name] = return_type.dtype + + # create parfor index var + for_replacing_ret = [] + if ndims == 1: + parfor_ind_var = parfor_vars[0] + else: + parfor_ind_var = ir.Var(scope, mk_unique_var( + "$parfor_index_tuple_var"), loc) + self.typemap[parfor_ind_var.name] = types.containers.UniTuple( + types.intp, ndims) + tuple_call = ir.Expr.build_tuple(parfor_vars, loc) + tuple_assign = ir.Assign(tuple_call, parfor_ind_var, loc) + for_replacing_ret.append(tuple_assign) + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after creating parfor index var") + ir_utils.dump_blocks(stencil_blocks) + + # empty init block + init_block = ir.Block(scope, loc) + if out_arr is None: + in_arr_typ = self.typemap[in_arr.name] + + shape_name = ir_utils.mk_unique_var("in_arr_shape") + shape_var = ir.Var(scope, shape_name, loc) + shape_getattr = ir.Expr.getattr(in_arr, "shape", loc) + self.typemap[shape_name] = types.containers.UniTuple(types.intp, + in_arr_typ.ndim) + init_block.body.extend([ir.Assign(shape_getattr, shape_var, loc)]) + + zero_name = ir_utils.mk_unique_var("zero_val") + zero_var = ir.Var(scope, zero_name, loc) + if "cval" in stencil_func.options: + cval = stencil_func.options["cval"] + # TODO: Loosen this restriction to adhere to casting rules. + cval_ty = typing.typeof.typeof(cval) + if not self.typingctx.can_convert(cval_ty, return_type.dtype): + raise NumbaValueError("cval type does not match stencil " \ + "return type.") + + temp2 = return_type.dtype(cval) + else: + temp2 = return_type.dtype(0) + full_const = ir.Const(temp2, loc) + self.typemap[zero_name] = return_type.dtype + init_block.body.extend([ir.Assign(full_const, zero_var, loc)]) + + so_name = ir_utils.mk_unique_var("stencil_output") + out_arr = ir.Var(scope, so_name, loc) + self.typemap[out_arr.name] = numba.core.types.npytypes.Array( + return_type.dtype, + in_arr_typ.ndim, + in_arr_typ.layout) + dtype_g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + self.typemap[dtype_g_np_var.name] = types.misc.Module(np) + dtype_g_np = ir.Global('np', np, loc) + dtype_g_np_assign = ir.Assign(dtype_g_np, dtype_g_np_var, loc) + init_block.body.append(dtype_g_np_assign) + + return_type_name = numpy_support.as_dtype( + return_type.dtype).type.__name__ + if return_type_name == 'bool': + return_type_name = 'bool_' + dtype_np_attr_call = ir.Expr.getattr(dtype_g_np_var, return_type_name, loc) + dtype_attr_var = ir.Var(scope, mk_unique_var("$np_attr_attr"), loc) + self.typemap[dtype_attr_var.name] = types.functions.NumberClass(return_type.dtype) + dtype_attr_assign = ir.Assign(dtype_np_attr_call, dtype_attr_var, loc) + init_block.body.append(dtype_attr_assign) + + stmts = ir_utils.gen_np_call("empty", + np.empty, + out_arr, + [shape_var, dtype_attr_var], + self.typingctx, + self.typemap, + self.calltypes) + # ------------------ + # Generate the code to fill just the border with zero_var. + + # Generate a none var to use in slicing. + none_var = ir.Var(scope, mk_unique_var("$none_var"), loc) + none_assign = ir.Assign(ir.Const(None, loc), none_var, loc) + stmts.append(none_assign) + self.typemap[none_var.name] = types.none + # Generate a zero var to use in slicing. + zero_index_var = ir.Var(scope, mk_unique_var("$zero_index_var"), loc) + zero_index_assign = ir.Assign(ir.Const(0, loc), zero_index_var, loc) + stmts.append(zero_index_assign) + self.typemap[zero_index_var.name] = types.intp + # Generate generic ":" slice. + # ---- Generate var to hold slice func var. + slice_func_var = ir.Var(scope, mk_unique_var("$slice_func_var"), loc) + slice_fn_ty = self.typingctx.resolve_value_type(slice) + self.typemap[slice_func_var.name] = slice_fn_ty + slice_g = ir.Global('slice', slice, loc) + slice_assign = ir.Assign(slice_g, slice_func_var, loc) + stmts.append(slice_assign) + # ---- Generate call to slice func. + sig = self.typingctx.resolve_function_type(slice_fn_ty, + (types.none,) * 2, + {}) + slice_callexpr = ir.Expr.call(func=slice_func_var, + args=(none_var, none_var), + kws=(), + loc=loc) + self.calltypes[slice_callexpr] = sig + # ---- Generate slice var + slice_var = ir.Var(scope, mk_unique_var("$slice"), loc) + self.typemap[slice_var.name] = types.slice2_type + slice_assign = ir.Assign(slice_callexpr, slice_var, loc) + stmts.append(slice_assign) + + def handle_border(slice_fn_ty, + dim, + scope, + loc, + slice_func_var, + stmts, + border_inds, + border_tuple_items, + other_arg, + other_first): + # Handle the border for start or end of the index range. + # ---- Generate call to slice func. + sig = self.typingctx.resolve_function_type( + slice_fn_ty, + (types.intp,) * 2, + {}) + si = border_inds[dim] + assert(isinstance(si, (int, ir.Var))) + si_var = ir.Var(scope, mk_unique_var("$border_ind"), loc) + self.typemap[si_var.name] = types.intp + if isinstance(si, int): + si_assign = ir.Assign(ir.Const(si, loc), si_var, loc) + else: + si_assign = ir.Assign(si, si_var, loc) + stmts.append(si_assign) + + slice_callexpr = ir.Expr.call( + func=slice_func_var, + args=(other_arg, si_var) if other_first else (si_var, other_arg), + kws=(), + loc=loc) + self.calltypes[slice_callexpr] = sig + # ---- Generate slice var + border_slice_var = ir.Var(scope, mk_unique_var("$slice"), loc) + self.typemap[border_slice_var.name] = types.slice2_type + slice_assign = ir.Assign(slice_callexpr, border_slice_var, loc) + stmts.append(slice_assign) + + border_tuple_items[dim] = border_slice_var + border_ind_var = ir.Var(scope, mk_unique_var( + "$border_index_tuple_var"), loc) + self.typemap[border_ind_var.name] = types.containers.UniTuple( + types.slice2_type, ndims) + tuple_call = ir.Expr.build_tuple(border_tuple_items, loc) + tuple_assign = ir.Assign(tuple_call, border_ind_var, loc) + stmts.append(tuple_assign) + + setitem_call = ir.SetItem(out_arr, border_ind_var, zero_var, loc) + self.calltypes[setitem_call] = signature( + types.none, self.typemap[out_arr.name], + self.typemap[border_ind_var.name], + self.typemap[out_arr.name].dtype + ) + stmts.append(setitem_call) + + # For each dimension, add setitem to set border values. + for dim in range(in_arr_typ.ndim): + # First, fill all entries with ":". + start_tuple_items = [slice_var] * in_arr_typ.ndim + last_tuple_items = [slice_var] * in_arr_typ.ndim + + handle_border(slice_fn_ty, + dim, + scope, + loc, + slice_func_var, + stmts, + start_inds, + start_tuple_items, + zero_index_var, + True) + handle_border(slice_fn_ty, + dim, + scope, + loc, + slice_func_var, + stmts, + last_inds, + last_tuple_items, + in_arr_dim_sizes[dim], + False) + + # ------------------ + + equiv_set.insert_equiv(out_arr, in_arr_dim_sizes) + init_block.body.extend(stmts) + else: # out is present + if "cval" in stencil_func.options: # do out[:] = cval + cval = stencil_func.options["cval"] + # TODO: Loosen this restriction to adhere to casting rules. + cval_ty = typing.typeof.typeof(cval) + if not self.typingctx.can_convert(cval_ty, return_type.dtype): + msg = "cval type does not match stencil return type." + raise NumbaValueError(msg) + + # get slice ref + slice_var = ir.Var(scope, mk_unique_var("$py_g_var"), loc) + slice_fn_ty = self.typingctx.resolve_value_type(slice) + self.typemap[slice_var.name] = slice_fn_ty + slice_g = ir.Global('slice', slice, loc) + slice_assigned = ir.Assign(slice_g, slice_var, loc) + init_block.body.append(slice_assigned) + + sig = self.typingctx.resolve_function_type(slice_fn_ty, + (types.none,) * 2, + {}) + + callexpr = ir.Expr.call(func=slice_var, args=(), kws=(), + loc=loc) + + self.calltypes[callexpr] = sig + slice_inst_var = ir.Var(scope, mk_unique_var("$slice_inst"), + loc) + self.typemap[slice_inst_var.name] = types.slice2_type + slice_assign = ir.Assign(callexpr, slice_inst_var, loc) + init_block.body.append(slice_assign) + + # get const val for cval + cval_const_val = ir.Const(return_type.dtype(cval), loc) + cval_const_var = ir.Var(scope, mk_unique_var("$cval_const"), + loc) + self.typemap[cval_const_var.name] = return_type.dtype + cval_const_assign = ir.Assign(cval_const_val, + cval_const_var, loc) + init_block.body.append(cval_const_assign) + + # do setitem on `out` array + setitemexpr = ir.StaticSetItem(out_arr, slice(None, None), + slice_inst_var, cval_const_var, + loc) + init_block.body.append(setitemexpr) + sig = signature(types.none, self.typemap[out_arr.name], + self.typemap[slice_inst_var.name], + self.typemap[out_arr.name].dtype) + self.calltypes[setitemexpr] = sig + + + self.replace_return_with_setitem(stencil_blocks, exit_value_var, + parfor_body_exit_label) + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after replacing return") + ir_utils.dump_blocks(stencil_blocks) + + setitem_call = ir.SetItem(out_arr, parfor_ind_var, exit_value_var, loc) + self.calltypes[setitem_call] = signature( + types.none, self.typemap[out_arr.name], + self.typemap[parfor_ind_var.name], + self.typemap[out_arr.name].dtype + ) + stencil_blocks[parfor_body_exit_label].body.extend(for_replacing_ret) + stencil_blocks[parfor_body_exit_label].body.append(setitem_call) + + # simplify CFG of parfor body (exit block could be simplified often) + # add dummy return to enable CFG + dummy_loc = ir.Loc("stencilparfor_dummy", -1) + ret_const_var = ir.Var(scope, mk_unique_var("$cval_const"), dummy_loc) + cval_const_assign = ir.Assign(ir.Const(0, loc=dummy_loc), ret_const_var, dummy_loc) + stencil_blocks[parfor_body_exit_label].body.append(cval_const_assign) + + stencil_blocks[parfor_body_exit_label].body.append( + ir.Return(ret_const_var, dummy_loc), + ) + stencil_blocks = ir_utils.simplify_CFG(stencil_blocks) + stencil_blocks[max(stencil_blocks.keys())].body.pop() + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after adding SetItem") + ir_utils.dump_blocks(stencil_blocks) + + pattern = ('stencil', [start_lengths, end_lengths]) + parfor = numba.parfors.parfor.Parfor(loopnests, init_block, stencil_blocks, + loc, parfor_ind_var, equiv_set, pattern, self.flags) + gen_nodes.append(parfor) + gen_nodes.append(ir.Assign(out_arr, target, loc)) + return gen_nodes + + def _get_stencil_last_ind(self, dim_size, end_length, gen_nodes, scope, + loc): + last_ind = dim_size + if end_length != 0: + # set last index to size minus stencil size to avoid invalid + # memory access + index_const = ir.Var(scope, mk_unique_var("stencil_const_var"), + loc) + self.typemap[index_const.name] = types.intp + if isinstance(end_length, numbers.Number): + const_assign = ir.Assign(ir.Const(end_length, loc), + index_const, loc) + else: + const_assign = ir.Assign(end_length, index_const, loc) + + gen_nodes.append(const_assign) + last_ind = ir.Var(scope, mk_unique_var("last_ind"), loc) + self.typemap[last_ind.name] = types.intp + + g_var = ir.Var(scope, mk_unique_var("compute_last_ind_var"), loc) + check_func = numba.njit(_compute_last_ind) + func_typ = types.functions.Dispatcher(check_func) + self.typemap[g_var.name] = func_typ + g_obj = ir.Global("_compute_last_ind", check_func, loc) + g_assign = ir.Assign(g_obj, g_var, loc) + gen_nodes.append(g_assign) + index_call = ir.Expr.call(g_var, [dim_size, index_const], (), loc) + self.calltypes[index_call] = func_typ.get_call_type( + self.typingctx, [types.intp, types.intp], {}) + index_assign = ir.Assign(index_call, last_ind, loc) + gen_nodes.append(index_assign) + + return last_ind + + def _get_stencil_start_ind(self, start_length, gen_nodes, scope, loc): + if isinstance(start_length, int): + return abs(min(start_length, 0)) + def get_start_ind(s_length): + return abs(min(s_length, 0)) + f_ir = compile_to_numba_ir(get_start_ind, {}, self.typingctx, + self.targetctx, (types.intp,), self.typemap, + self.calltypes) + assert len(f_ir.blocks) == 1 + block = f_ir.blocks.popitem()[1] + replace_arg_nodes(block, [start_length]) + gen_nodes += block.body[:-2] + ret_var = block.body[-2].value.value + return ret_var + + def _replace_stencil_accesses(self, stencil_ir, parfor_vars, in_args, + index_offsets, stencil_func, arg_to_arr_dict): + """ Convert relative indexing in the stencil kernel to standard indexing + by adding the loop index variables to the corresponding dimensions + of the array index tuples. + """ + stencil_blocks = stencil_ir.blocks + in_arr = in_args[0] + in_arg_names = [x.name for x in in_args] + + if "standard_indexing" in stencil_func.options: + for x in stencil_func.options["standard_indexing"]: + if x not in arg_to_arr_dict: + raise NumbaValueError("Standard indexing requested for " \ + "an array name not present in the " \ + "stencil kernel definition.") + standard_indexed = [arg_to_arr_dict[x] for x in + stencil_func.options["standard_indexing"]] + else: + standard_indexed = [] + + if in_arr.name in standard_indexed: + raise NumbaValueError("The first argument to a stencil kernel " \ + "must use relative indexing, not standard " \ + "indexing.") + + ndims = self.typemap[in_arr.name].ndim + scope = in_arr.scope + loc = in_arr.loc + # replace access indices, find access lengths in each dimension + need_to_calc_kernel = stencil_func.neighborhood is None + + # If we need to infer the kernel size then initialize the minimum and + # maximum seen indices for each dimension to 0. If we already have + # the neighborhood calculated then just convert from neighborhood format + # to the separate start and end lengths format used here. + if need_to_calc_kernel: + start_lengths = ndims*[0] + end_lengths = ndims*[0] + else: + start_lengths = [x[0] for x in stencil_func.neighborhood] + end_lengths = [x[1] for x in stencil_func.neighborhood] + + # Get all the tuples defined in the stencil blocks. + tuple_table = ir_utils.get_tuple_table(stencil_blocks) + + found_relative_index = False + + # For all blocks in the stencil kernel... + for label, block in stencil_blocks.items(): + new_body = [] + # For all statements in those blocks... + for stmt in block.body: + # Reject assignments to input arrays. + if ((isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op in ['setitem', 'static_setitem'] + and stmt.value.value.name in in_arg_names) or + ((isinstance(stmt, ir.SetItem) or + isinstance(stmt, ir.StaticSetItem)) + and stmt.target.name in in_arg_names)): + raise NumbaValueError("Assignments to arrays passed to " \ + "stencil kernels is not allowed.") + # We found a getitem for some array. If that array is an input + # array and isn't in the list of standard indexed arrays then + # update min and max seen indices if we are inferring the + # kernel size and create a new tuple where the relative offsets + # are added to loop index vars to get standard indexing. + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op in ['static_getitem', 'getitem'] + and stmt.value.value.name in in_arg_names + and stmt.value.value.name not in standard_indexed): + index_list = stmt.value.index + # handle 1D case + if ndims == 1: + index_list = [index_list] + else: + if hasattr(index_list, 'name') and index_list.name in tuple_table: + index_list = tuple_table[index_list.name] + # indices can be inferred as constant in simple expressions + # like -c where c is constant + # handled here since this is a common stencil index pattern + stencil_ir._definitions = ir_utils.build_definitions(stencil_blocks) + index_list = [_get_const_index_expr( + stencil_ir, self.func_ir, v) for v in index_list] + if index_offsets: + index_list = self._add_index_offsets(index_list, + list(index_offsets), new_body, scope, loc) + + # update min and max indices + if need_to_calc_kernel: + # all indices should be integer to be able to calculate + # neighborhood automatically + if (isinstance(index_list, ir.Var) or + any([not isinstance(v, int) for v in index_list])): + raise NumbaValueError("Variable stencil index " \ + "only possible with known " \ + "neighborhood") + start_lengths = list(map(min, start_lengths, + index_list)) + end_lengths = list(map(max, end_lengths, index_list)) + found_relative_index = True + + # update access indices + index_vars = self._add_index_offsets(parfor_vars, + list(index_list), new_body, scope, loc) + + # new access index tuple + if ndims == 1: + ind_var = index_vars[0] + else: + ind_var = ir.Var(scope, mk_unique_var( + "$parfor_index_ind_var"), loc) + self.typemap[ind_var.name] = types.containers.UniTuple( + types.intp, ndims) + tuple_call = ir.Expr.build_tuple(index_vars, loc) + tuple_assign = ir.Assign(tuple_call, ind_var, loc) + new_body.append(tuple_assign) + + # getitem return type is scalar if all indices are integer + if all([self.typemap[v.name] == types.intp + for v in index_vars]): + getitem_return_typ = self.typemap[ + stmt.value.value.name].dtype + else: + # getitem returns an array + getitem_return_typ = self.typemap[stmt.value.value.name] + # new getitem with the new index var + getitem_call = ir.Expr.getitem(stmt.value.value, ind_var, + loc) + self.calltypes[getitem_call] = signature( + getitem_return_typ, + self.typemap[stmt.value.value.name], + self.typemap[ind_var.name]) + stmt.value = getitem_call + + new_body.append(stmt) + block.body = new_body + if need_to_calc_kernel and not found_relative_index: + raise NumbaValueError("Stencil kernel with no accesses to " \ + "relatively indexed arrays.") + + return start_lengths, end_lengths + + def _add_index_offsets(self, index_list, index_offsets, new_body, + scope, loc): + """ Does the actual work of adding loop index variables to the + relative index constants or variables. + """ + assert len(index_list) == len(index_offsets) + + # shortcut if all values are integer + if all([isinstance(v, int) for v in index_list+index_offsets]): + # add offsets in all dimensions + return list(map(add, index_list, index_offsets)) + + out_nodes = [] + index_vars = [] + for i in range(len(index_list)): + # new_index = old_index + offset + old_index_var = index_list[i] + if isinstance(old_index_var, int): + old_index_var = ir.Var(scope, + mk_unique_var("old_index_var"), loc) + self.typemap[old_index_var.name] = types.intp + const_assign = ir.Assign(ir.Const(index_list[i], loc), + old_index_var, loc) + out_nodes.append(const_assign) + + offset_var = index_offsets[i] + if isinstance(offset_var, int): + offset_var = ir.Var(scope, + mk_unique_var("offset_var"), loc) + self.typemap[offset_var.name] = types.intp + const_assign = ir.Assign(ir.Const(index_offsets[i], loc), + offset_var, loc) + out_nodes.append(const_assign) + + if (isinstance(old_index_var, slice) + or isinstance(self.typemap[old_index_var.name], + types.misc.SliceType)): + # only one arg can be slice + assert self.typemap[offset_var.name] == types.intp + index_var = self._add_offset_to_slice(old_index_var, offset_var, + out_nodes, scope, loc) + index_vars.append(index_var) + continue + + if (isinstance(offset_var, slice) + or isinstance(self.typemap[offset_var.name], + types.misc.SliceType)): + # only one arg can be slice + assert self.typemap[old_index_var.name] == types.intp + index_var = self._add_offset_to_slice(offset_var, old_index_var, + out_nodes, scope, loc) + index_vars.append(index_var) + continue + + index_var = ir.Var(scope, + mk_unique_var("offset_stencil_index"), loc) + self.typemap[index_var.name] = types.intp + index_call = ir.Expr.binop(operator.add, old_index_var, + offset_var, loc) + self.calltypes[index_call] = self.typingctx.resolve_function_type( + operator.add, (types.intp, types.intp), {}) + index_assign = ir.Assign(index_call, index_var, loc) + out_nodes.append(index_assign) + index_vars.append(index_var) + + new_body.extend(out_nodes) + return index_vars + + def _add_offset_to_slice(self, slice_var, offset_var, out_nodes, scope, + loc): + if isinstance(slice_var, slice): + f_text = """def f(offset): + return slice({} + offset, {} + offset) + """.format(slice_var.start, slice_var.stop) + loc = {} + exec(f_text, {}, loc) + f = loc['f'] + args = [offset_var] + arg_typs = (types.intp,) + else: + def f(old_slice, offset): + return slice(old_slice.start + offset, old_slice.stop + offset) + args = [slice_var, offset_var] + slice_type = self.typemap[slice_var.name] + arg_typs = (slice_type, types.intp,) + _globals = self.func_ir.func_id.func.__globals__ + f_ir = compile_to_numba_ir(f, _globals, self.typingctx, self.targetctx, + arg_typs, self.typemap, self.calltypes) + _, block = f_ir.blocks.popitem() + replace_arg_nodes(block, args) + new_index = block.body[-2].value.value + out_nodes.extend(block.body[:-2]) # ignore return nodes + return new_index + +def get_stencil_ir(sf, typingctx, args, scope, loc, input_dict, typemap, + calltypes): + """get typed IR from stencil bytecode + """ + from numba.core.cpu import CPUContext + from numba.core.registry import cpu_target + from numba.core.annotations import type_annotations + from numba.core.typed_passes import type_inference_stage + + # get untyped IR + stencil_func_ir = sf.kernel_ir.copy() + # copy the IR nodes to avoid changing IR in the StencilFunc object + stencil_blocks = copy.deepcopy(stencil_func_ir.blocks) + stencil_func_ir.blocks = stencil_blocks + + name_var_table = ir_utils.get_name_var_table(stencil_func_ir.blocks) + if "out" in name_var_table: + raise NumbaValueError("Cannot use the reserved word 'out' in stencil " \ + "kernels.") + + # get typed IR with a dummy pipeline (similar to test_parfors.py) + from numba.core.registry import cpu_target + targetctx = cpu_target.target_context + + tp = DummyPipeline(typingctx, targetctx, args, stencil_func_ir) + + rewrites.rewrite_registry.apply('before-inference', tp.state) + + tp.state.typemap, tp.state.return_type, tp.state.calltypes, _ = 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) + + # make block labels unique + stencil_blocks = ir_utils.add_offset_to_labels(stencil_blocks, + ir_utils.next_label()) + min_label = min(stencil_blocks.keys()) + max_label = max(stencil_blocks.keys()) + ir_utils._the_max_label.update(max_label) + + if config.DEBUG_ARRAY_OPT >= 1: + print("Initial stencil_blocks") + ir_utils.dump_blocks(stencil_blocks) + + # rename variables, + var_dict = {} + for v, typ in tp.state.typemap.items(): + new_var = ir.Var(scope, mk_unique_var(v), loc) + var_dict[v] = new_var + typemap[new_var.name] = typ # add new var type for overall function + ir_utils.replace_vars(stencil_blocks, var_dict) + + if config.DEBUG_ARRAY_OPT >= 1: + print("After replace_vars") + ir_utils.dump_blocks(stencil_blocks) + + # add call types to overall function + for call, call_typ in tp.state.calltypes.items(): + calltypes[call] = call_typ + + arg_to_arr_dict = {} + # replace arg with arr + for block in stencil_blocks.values(): + for stmt in block.body: + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Arg): + if config.DEBUG_ARRAY_OPT >= 1: + print("input_dict", input_dict, stmt.value.index, + stmt.value.name, stmt.value.index in input_dict) + arg_to_arr_dict[stmt.value.name] = input_dict[stmt.value.index].name + stmt.value = input_dict[stmt.value.index] + + if config.DEBUG_ARRAY_OPT >= 1: + print("arg_to_arr_dict", arg_to_arr_dict) + print("After replace arg with arr") + ir_utils.dump_blocks(stencil_blocks) + + ir_utils.remove_dels(stencil_blocks) + stencil_func_ir.blocks = stencil_blocks + return stencil_func_ir, sf.get_return_type(args)[0], arg_to_arr_dict + +class DummyPipeline(object): + def __init__(self, typingctx, targetctx, args, f_ir): + from numba.core.compiler import StateDict + self.state = StateDict() + self.state.typingctx = typingctx + self.state.targetctx = targetctx + self.state.args = args + self.state.func_ir = f_ir + self.state.typemap = None + self.state.return_type = None + self.state.calltypes = None + + +def _get_const_index_expr(stencil_ir, func_ir, index_var): + """ + infer index_var as constant if it is of a expression form like c-1 where c + is a constant in the outer function. + index_var is assumed to be inside stencil kernel + """ + const_val = guard( + _get_const_index_expr_inner, stencil_ir, func_ir, index_var) + if const_val is not None: + return const_val + return index_var + +def _get_const_index_expr_inner(stencil_ir, func_ir, index_var): + """inner constant inference function that calls constant, unary and binary + cases. + """ + require(isinstance(index_var, ir.Var)) + # case where the index is a const itself in outer function + var_const = guard(_get_const_two_irs, stencil_ir, func_ir, index_var) + if var_const is not None: + return var_const + # get index definition + index_def = ir_utils.get_definition(stencil_ir, index_var) + # match inner_var = unary(index_var) + var_const = guard( + _get_const_unary_expr, stencil_ir, func_ir, index_def) + if var_const is not None: + return var_const + # match inner_var = arg1 + arg2 + var_const = guard( + _get_const_binary_expr, stencil_ir, func_ir, index_def) + if var_const is not None: + return var_const + raise GuardException + +def _get_const_two_irs(ir1, ir2, var): + """get constant in either of two IRs if available + otherwise, throw GuardException + """ + var_const = guard(find_const, ir1, var) + if var_const is not None: + return var_const + var_const = guard(find_const, ir2, var) + if var_const is not None: + return var_const + raise GuardException + +def _get_const_unary_expr(stencil_ir, func_ir, index_def): + """evaluate constant unary expr if possible + otherwise, raise GuardException + """ + require(isinstance(index_def, ir.Expr) and index_def.op == 'unary') + inner_var = index_def.value + # return -c as constant + const_val = _get_const_index_expr_inner(stencil_ir, func_ir, inner_var) + op = OPERATORS_TO_BUILTINS[index_def.fn] + return eval("{}{}".format(op, const_val)) + +def _get_const_binary_expr(stencil_ir, func_ir, index_def): + """evaluate constant binary expr if possible + otherwise, raise GuardException + """ + require(isinstance(index_def, ir.Expr) and index_def.op == 'binop') + arg1 = _get_const_index_expr_inner(stencil_ir, func_ir, index_def.lhs) + arg2 = _get_const_index_expr_inner(stencil_ir, func_ir, index_def.rhs) + op = OPERATORS_TO_BUILTINS[index_def.fn] + return eval("{}{}{}".format(arg1, op, arg2)) diff --git a/shared/package-files/02/02c28e705d3b27af99632f679030f19c06e5538dccae5c2caa2530ffe84c611c/kernighan_lin.py b/shared/package-files/02/02c28e705d3b27af99632f679030f19c06e5538dccae5c2caa2530ffe84c611c/kernighan_lin.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae22e363615a625d5abd7b410a896b4b1f68206 --- /dev/null +++ b/shared/package-files/02/02c28e705d3b27af99632f679030f19c06e5538dccae5c2caa2530ffe84c611c/kernighan_lin.py @@ -0,0 +1,137 @@ +"""Functions for computing the Kernighan–Lin bipartition algorithm.""" + +from itertools import count + +import networkx as nx +from networkx.algorithms.community.community_utils import is_partition +from networkx.utils import BinaryHeap, not_implemented_for, py_random_state + +__all__ = ["kernighan_lin_bisection"] + + +def _kernighan_lin_sweep(edges, side): + """ + This is a modified form of Kernighan-Lin, which moves single nodes at a + time, alternating between sides to keep the bisection balanced. We keep + two min-heaps of swap costs to make optimal-next-move selection fast. + """ + costs0, costs1 = costs = BinaryHeap(), BinaryHeap() + for u, side_u, edges_u in zip(count(), side, edges): + cost_u = sum(w if side[v] else -w for v, w in edges_u) + costs[side_u].insert(u, cost_u if side_u else -cost_u) + + def _update_costs(costs_x, x): + for y, w in edges[x]: + costs_y = costs[side[y]] + cost_y = costs_y.get(y) + if cost_y is not None: + cost_y += 2 * (-w if costs_x is costs_y else w) + costs_y.insert(y, cost_y, True) + + i = 0 + totcost = 0 + while costs0 and costs1: + u, cost_u = costs0.pop() + _update_costs(costs0, u) + v, cost_v = costs1.pop() + _update_costs(costs1, v) + totcost += cost_u + cost_v + i += 1 + yield totcost, i, (u, v) + + +@py_random_state(4) +@not_implemented_for("directed") +def kernighan_lin_bisection(G, partition=None, max_iter=10, weight="weight", seed=None): + """Partition a graph into two blocks using the Kernighan–Lin + algorithm. + + This algorithm partitions a network into two sets by iteratively + swapping pairs of nodes to reduce the edge cut between the two sets. The + pairs are chosen according to a modified form of Kernighan-Lin, which + moves node individually, alternating between sides to keep the bisection + balanced. + + Parameters + ---------- + G : graph + + partition : tuple + Pair of iterables containing an initial partition. If not + specified, a random balanced partition is used. + + max_iter : int + Maximum number of times to attempt swaps to find an + improvemement before giving up. + + weight : key + Edge data key to use as weight. If None, the weights are all + set to one. + + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + Only used if partition is None + + Returns + ------- + partition : tuple + A pair of sets of nodes representing the bipartition. + + Raises + ------ + NetworkXError + If partition is not a valid partition of the nodes of the graph. + + References + ---------- + .. [1] Kernighan, B. W.; Lin, Shen (1970). + "An efficient heuristic procedure for partitioning graphs." + *Bell Systems Technical Journal* 49: 291--307. + Oxford University Press 2011. + + """ + n = len(G) + labels = list(G) + seed.shuffle(labels) + index = {v: i for i, v in enumerate(labels)} + + if partition is None: + side = [0] * (n // 2) + [1] * ((n + 1) // 2) + else: + try: + A, B = partition + except (TypeError, ValueError) as err: + raise nx.NetworkXError("partition must be two sets") from err + if not is_partition(G, (A, B)): + raise nx.NetworkXError("partition invalid") + side = [0] * n + for a in A: + side[index[a]] = 1 + + if G.is_multigraph(): + edges = [ + [ + (index[u], sum(e.get(weight, 1) for e in d.values())) + for u, d in G[v].items() + ] + for v in labels + ] + else: + edges = [ + [(index[u], e.get(weight, 1)) for u, e in G[v].items()] for v in labels + ] + + for i in range(max_iter): + costs = list(_kernighan_lin_sweep(edges, side)) + min_cost, min_i, _ = min(costs) + if min_cost >= 0: + break + + for _, _, (u, v) in costs[:min_i]: + side[u] = 1 + side[v] = 0 + + A = {u for u, s in zip(labels, side) if s == 0} + B = {u for u, s in zip(labels, side) if s == 1} + return A, B diff --git a/shared/package-files/02/02c478fa459b3676c95a04334732c7a11fd10161d5f29b5b6a9ee45f4386fb11/rename.h b/shared/package-files/02/02c478fa459b3676c95a04334732c7a11fd10161d5f29b5b6a9ee45f4386fb11/rename.h new file mode 100644 index 0000000000000000000000000000000000000000..ca54880234fb691e97a12b220bc45257ba8430a7 --- /dev/null +++ b/shared/package-files/02/02c478fa459b3676c95a04334732c7a11fd10161d5f29b5b6a9ee45f4386fb11/rename.h @@ -0,0 +1,26 @@ +#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 { + + + +} diff --git a/shared/package-files/02/02c600307863c977d3f3b9d94545a090cb2df8786d776046cb42ea0dd491f406/termite b/shared/package-files/02/02c600307863c977d3f3b9d94545a090cb2df8786d776046cb42ea0dd491f406/termite new file mode 100644 index 0000000000000000000000000000000000000000..40015dc470e99249d87272bc27eb40c2a1cf0ce6 Binary files /dev/null and b/shared/package-files/02/02c600307863c977d3f3b9d94545a090cb2df8786d776046cb42ea0dd491f406/termite differ diff --git a/shared/package-files/02/02c61459443a7ee14023a30f2887a96e9865806bb57a0b39fb1ad370248d215b/_upsample_bilinear2d_aa_backward_cpu_dispatch.h b/shared/package-files/02/02c61459443a7ee14023a30f2887a96e9865806bb57a0b39fb1ad370248d215b/_upsample_bilinear2d_aa_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4c018784687e831c9c885d31236b085f09cc805a --- /dev/null +++ b/shared/package-files/02/02c61459443a7ee14023a30f2887a96e9865806bb57a0b39fb1ad370248d215b/_upsample_bilinear2d_aa_backward_cpu_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 cpu { + +TORCH_API at::Tensor _upsample_bilinear2d_aa_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor _upsample_bilinear2d_aa_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/02/02c744eb87a94e5ebd94e5966e103dcf29da97b458543600f3aa79c8158d47a9/test_util.py b/shared/package-files/02/02c744eb87a94e5ebd94e5966e103dcf29da97b458543600f3aa79c8158d47a9/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c613972dac7ed2d07bfff2d1af98c32260ce4f --- /dev/null +++ b/shared/package-files/02/02c744eb87a94e5ebd94e5966e103dcf29da97b458543600f3aa79c8158d47a9/test_util.py @@ -0,0 +1,591 @@ +""" Test suite for the code in fixer_util """ + +# Testing imports +from . import support + +# Local imports +from lib2to3.pytree import Node, Leaf +from lib2to3 import fixer_util +from lib2to3.fixer_util import Attr, Name, Call, Comma +from lib2to3.pgen2 import token + +def parse(code, strip_levels=0): + # The topmost node is file_input, which we don't care about. + # The next-topmost node is a *_stmt node, which we also don't care about + tree = support.parse_string(code) + for i in range(strip_levels): + tree = tree.children[0] + tree.parent = None + return tree + +class MacroTestCase(support.TestCase): + def assertStr(self, node, string): + if isinstance(node, (tuple, list)): + node = Node(fixer_util.syms.simple_stmt, node) + self.assertEqual(str(node), string) + + +class Test_is_tuple(support.TestCase): + def is_tuple(self, string): + return fixer_util.is_tuple(parse(string, strip_levels=2)) + + def test_valid(self): + self.assertTrue(self.is_tuple("(a, b)")) + self.assertTrue(self.is_tuple("(a, (b, c))")) + self.assertTrue(self.is_tuple("((a, (b, c)),)")) + self.assertTrue(self.is_tuple("(a,)")) + self.assertTrue(self.is_tuple("()")) + + def test_invalid(self): + self.assertFalse(self.is_tuple("(a)")) + self.assertFalse(self.is_tuple("('foo') % (b, c)")) + + +class Test_is_list(support.TestCase): + def is_list(self, string): + return fixer_util.is_list(parse(string, strip_levels=2)) + + def test_valid(self): + self.assertTrue(self.is_list("[]")) + self.assertTrue(self.is_list("[a]")) + self.assertTrue(self.is_list("[a, b]")) + self.assertTrue(self.is_list("[a, [b, c]]")) + self.assertTrue(self.is_list("[[a, [b, c]],]")) + + def test_invalid(self): + self.assertFalse(self.is_list("[]+[]")) + + +class Test_Attr(MacroTestCase): + def test(self): + call = parse("foo()", strip_levels=2) + + self.assertStr(Attr(Name("a"), Name("b")), "a.b") + self.assertStr(Attr(call, Name("b")), "foo().b") + + def test_returns(self): + attr = Attr(Name("a"), Name("b")) + self.assertEqual(type(attr), list) + + +class Test_Name(MacroTestCase): + def test(self): + self.assertStr(Name("a"), "a") + self.assertStr(Name("foo.foo().bar"), "foo.foo().bar") + self.assertStr(Name("a", prefix="b"), "ba") + + +class Test_Call(MacroTestCase): + def _Call(self, name, args=None, prefix=None): + """Help the next test""" + children = [] + if isinstance(args, list): + for arg in args: + children.append(arg) + children.append(Comma()) + children.pop() + return Call(Name(name), children, prefix) + + def test(self): + kids = [None, + [Leaf(token.NUMBER, 1), Leaf(token.NUMBER, 2), + Leaf(token.NUMBER, 3)], + [Leaf(token.NUMBER, 1), Leaf(token.NUMBER, 3), + Leaf(token.NUMBER, 2), Leaf(token.NUMBER, 4)], + [Leaf(token.STRING, "b"), Leaf(token.STRING, "j", prefix=" ")] + ] + self.assertStr(self._Call("A"), "A()") + self.assertStr(self._Call("b", kids[1]), "b(1,2,3)") + self.assertStr(self._Call("a.b().c", kids[2]), "a.b().c(1,3,2,4)") + self.assertStr(self._Call("d", kids[3], prefix=" "), " d(b, j)") + + +class Test_does_tree_import(support.TestCase): + def _find_bind_rec(self, name, node): + # Search a tree for a binding -- used to find the starting + # point for these tests. + c = fixer_util.find_binding(name, node) + if c: return c + for child in node.children: + c = self._find_bind_rec(name, child) + if c: return c + + def does_tree_import(self, package, name, string): + node = parse(string) + # Find the binding of start -- that's what we'll go from + node = self._find_bind_rec('start', node) + return fixer_util.does_tree_import(package, name, node) + + def try_with(self, string): + failing_tests = (("a", "a", "from a import b"), + ("a.d", "a", "from a.d import b"), + ("d.a", "a", "from d.a import b"), + (None, "a", "import b"), + (None, "a", "import b, c, d")) + for package, name, import_ in failing_tests: + n = self.does_tree_import(package, name, import_ + "\n" + string) + self.assertFalse(n) + n = self.does_tree_import(package, name, string + "\n" + import_) + self.assertFalse(n) + + passing_tests = (("a", "a", "from a import a"), + ("x", "a", "from x import a"), + ("x", "a", "from x import b, c, a, d"), + ("x.b", "a", "from x.b import a"), + ("x.b", "a", "from x.b import b, c, a, d"), + (None, "a", "import a"), + (None, "a", "import b, c, a, d")) + for package, name, import_ in passing_tests: + n = self.does_tree_import(package, name, import_ + "\n" + string) + self.assertTrue(n) + n = self.does_tree_import(package, name, string + "\n" + import_) + self.assertTrue(n) + + def test_in_function(self): + self.try_with("def foo():\n\tbar.baz()\n\tstart=3") + +class Test_find_binding(support.TestCase): + def find_binding(self, name, string, package=None): + return fixer_util.find_binding(name, parse(string), package) + + def test_simple_assignment(self): + self.assertTrue(self.find_binding("a", "a = b")) + self.assertTrue(self.find_binding("a", "a = [b, c, d]")) + self.assertTrue(self.find_binding("a", "a = foo()")) + self.assertTrue(self.find_binding("a", "a = foo().foo.foo[6][foo]")) + self.assertFalse(self.find_binding("a", "foo = a")) + self.assertFalse(self.find_binding("a", "foo = (a, b, c)")) + + def test_tuple_assignment(self): + self.assertTrue(self.find_binding("a", "(a,) = b")) + self.assertTrue(self.find_binding("a", "(a, b, c) = [b, c, d]")) + self.assertTrue(self.find_binding("a", "(c, (d, a), b) = foo()")) + self.assertTrue(self.find_binding("a", "(a, b) = foo().foo[6][foo]")) + self.assertFalse(self.find_binding("a", "(foo, b) = (b, a)")) + self.assertFalse(self.find_binding("a", "(foo, (b, c)) = (a, b, c)")) + + def test_list_assignment(self): + self.assertTrue(self.find_binding("a", "[a] = b")) + self.assertTrue(self.find_binding("a", "[a, b, c] = [b, c, d]")) + self.assertTrue(self.find_binding("a", "[c, [d, a], b] = foo()")) + self.assertTrue(self.find_binding("a", "[a, b] = foo().foo[a][foo]")) + self.assertFalse(self.find_binding("a", "[foo, b] = (b, a)")) + self.assertFalse(self.find_binding("a", "[foo, [b, c]] = (a, b, c)")) + + def test_invalid_assignments(self): + self.assertFalse(self.find_binding("a", "foo.a = 5")) + self.assertFalse(self.find_binding("a", "foo[a] = 5")) + self.assertFalse(self.find_binding("a", "foo(a) = 5")) + self.assertFalse(self.find_binding("a", "foo(a, b) = 5")) + + def test_simple_import(self): + self.assertTrue(self.find_binding("a", "import a")) + self.assertTrue(self.find_binding("a", "import b, c, a, d")) + self.assertFalse(self.find_binding("a", "import b")) + self.assertFalse(self.find_binding("a", "import b, c, d")) + + def test_from_import(self): + self.assertTrue(self.find_binding("a", "from x import a")) + self.assertTrue(self.find_binding("a", "from a import a")) + self.assertTrue(self.find_binding("a", "from x import b, c, a, d")) + self.assertTrue(self.find_binding("a", "from x.b import a")) + self.assertTrue(self.find_binding("a", "from x.b import b, c, a, d")) + self.assertFalse(self.find_binding("a", "from a import b")) + self.assertFalse(self.find_binding("a", "from a.d import b")) + self.assertFalse(self.find_binding("a", "from d.a import b")) + + def test_import_as(self): + self.assertTrue(self.find_binding("a", "import b as a")) + self.assertTrue(self.find_binding("a", "import b as a, c, a as f, d")) + self.assertFalse(self.find_binding("a", "import a as f")) + self.assertFalse(self.find_binding("a", "import b, c as f, d as e")) + + def test_from_import_as(self): + self.assertTrue(self.find_binding("a", "from x import b as a")) + self.assertTrue(self.find_binding("a", "from x import g as a, d as b")) + self.assertTrue(self.find_binding("a", "from x.b import t as a")) + self.assertTrue(self.find_binding("a", "from x.b import g as a, d")) + self.assertFalse(self.find_binding("a", "from a import b as t")) + self.assertFalse(self.find_binding("a", "from a.d import b as t")) + self.assertFalse(self.find_binding("a", "from d.a import b as t")) + + def test_simple_import_with_package(self): + self.assertTrue(self.find_binding("b", "import b")) + self.assertTrue(self.find_binding("b", "import b, c, d")) + self.assertFalse(self.find_binding("b", "import b", "b")) + self.assertFalse(self.find_binding("b", "import b, c, d", "c")) + + def test_from_import_with_package(self): + self.assertTrue(self.find_binding("a", "from x import a", "x")) + self.assertTrue(self.find_binding("a", "from a import a", "a")) + self.assertTrue(self.find_binding("a", "from x import *", "x")) + self.assertTrue(self.find_binding("a", "from x import b, c, a, d", "x")) + self.assertTrue(self.find_binding("a", "from x.b import a", "x.b")) + self.assertTrue(self.find_binding("a", "from x.b import *", "x.b")) + self.assertTrue(self.find_binding("a", "from x.b import b, c, a, d", "x.b")) + self.assertFalse(self.find_binding("a", "from a import b", "a")) + self.assertFalse(self.find_binding("a", "from a.d import b", "a.d")) + self.assertFalse(self.find_binding("a", "from d.a import b", "a.d")) + self.assertFalse(self.find_binding("a", "from x.y import *", "a.b")) + + def test_import_as_with_package(self): + self.assertFalse(self.find_binding("a", "import b.c as a", "b.c")) + self.assertFalse(self.find_binding("a", "import a as f", "f")) + self.assertFalse(self.find_binding("a", "import a as f", "a")) + + def test_from_import_as_with_package(self): + # Because it would take a lot of special-case code in the fixers + # to deal with from foo import bar as baz, we'll simply always + # fail if there is an "from ... import ... as ..." + self.assertFalse(self.find_binding("a", "from x import b as a", "x")) + self.assertFalse(self.find_binding("a", "from x import g as a, d as b", "x")) + self.assertFalse(self.find_binding("a", "from x.b import t as a", "x.b")) + self.assertFalse(self.find_binding("a", "from x.b import g as a, d", "x.b")) + self.assertFalse(self.find_binding("a", "from a import b as t", "a")) + self.assertFalse(self.find_binding("a", "from a import b as t", "b")) + self.assertFalse(self.find_binding("a", "from a import b as t", "t")) + + def test_function_def(self): + self.assertTrue(self.find_binding("a", "def a(): pass")) + self.assertTrue(self.find_binding("a", "def a(b, c, d): pass")) + self.assertTrue(self.find_binding("a", "def a(): b = 7")) + self.assertFalse(self.find_binding("a", "def d(b, (c, a), e): pass")) + self.assertFalse(self.find_binding("a", "def d(a=7): pass")) + self.assertFalse(self.find_binding("a", "def d(a): pass")) + self.assertFalse(self.find_binding("a", "def d(): a = 7")) + + s = """ + def d(): + def a(): + pass""" + self.assertFalse(self.find_binding("a", s)) + + def test_class_def(self): + self.assertTrue(self.find_binding("a", "class a: pass")) + self.assertTrue(self.find_binding("a", "class a(): pass")) + self.assertTrue(self.find_binding("a", "class a(b): pass")) + self.assertTrue(self.find_binding("a", "class a(b, c=8): pass")) + self.assertFalse(self.find_binding("a", "class d: pass")) + self.assertFalse(self.find_binding("a", "class d(a): pass")) + self.assertFalse(self.find_binding("a", "class d(b, a=7): pass")) + self.assertFalse(self.find_binding("a", "class d(b, *a): pass")) + self.assertFalse(self.find_binding("a", "class d(b, **a): pass")) + self.assertFalse(self.find_binding("a", "class d: a = 7")) + + s = """ + class d(): + class a(): + pass""" + self.assertFalse(self.find_binding("a", s)) + + def test_for(self): + self.assertTrue(self.find_binding("a", "for a in r: pass")) + self.assertTrue(self.find_binding("a", "for a, b in r: pass")) + self.assertTrue(self.find_binding("a", "for (a, b) in r: pass")) + self.assertTrue(self.find_binding("a", "for c, (a,) in r: pass")) + self.assertTrue(self.find_binding("a", "for c, (a, b) in r: pass")) + self.assertTrue(self.find_binding("a", "for c in r: a = c")) + self.assertFalse(self.find_binding("a", "for c in a: pass")) + + def test_for_nested(self): + s = """ + for b in r: + for a in b: + pass""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + for b in r: + for a, c in b: + pass""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + for b in r: + for (a, c) in b: + pass""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + for b in r: + for (a,) in b: + pass""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + for b in r: + for c, (a, d) in b: + pass""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + for b in r: + for c in b: + a = 7""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + for b in r: + for c in b: + d = a""" + self.assertFalse(self.find_binding("a", s)) + + s = """ + for b in r: + for c in a: + d = 7""" + self.assertFalse(self.find_binding("a", s)) + + def test_if(self): + self.assertTrue(self.find_binding("a", "if b in r: a = c")) + self.assertFalse(self.find_binding("a", "if a in r: d = e")) + + def test_if_nested(self): + s = """ + if b in r: + if c in d: + a = c""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + if b in r: + if c in d: + c = a""" + self.assertFalse(self.find_binding("a", s)) + + def test_while(self): + self.assertTrue(self.find_binding("a", "while b in r: a = c")) + self.assertFalse(self.find_binding("a", "while a in r: d = e")) + + def test_while_nested(self): + s = """ + while b in r: + while c in d: + a = c""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + while b in r: + while c in d: + c = a""" + self.assertFalse(self.find_binding("a", s)) + + def test_try_except(self): + s = """ + try: + a = 6 + except: + b = 8""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + except: + a = 6""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + except KeyError: + pass + except: + a = 6""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + except: + b = 6""" + self.assertFalse(self.find_binding("a", s)) + + def test_try_except_nested(self): + s = """ + try: + try: + a = 6 + except: + pass + except: + b = 8""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + except: + try: + a = 6 + except: + pass""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + except: + try: + pass + except: + a = 6""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + try: + b = 8 + except KeyError: + pass + except: + a = 6 + except: + pass""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + pass + except: + try: + b = 8 + except KeyError: + pass + except: + a = 6""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + except: + b = 6""" + self.assertFalse(self.find_binding("a", s)) + + s = """ + try: + try: + b = 8 + except: + c = d + except: + try: + b = 6 + except: + t = 8 + except: + o = y""" + self.assertFalse(self.find_binding("a", s)) + + def test_try_except_finally(self): + s = """ + try: + c = 6 + except: + b = 8 + finally: + a = 9""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + finally: + a = 6""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + finally: + b = 6""" + self.assertFalse(self.find_binding("a", s)) + + s = """ + try: + b = 8 + except: + b = 9 + finally: + b = 6""" + self.assertFalse(self.find_binding("a", s)) + + def test_try_except_finally_nested(self): + s = """ + try: + c = 6 + except: + b = 8 + finally: + try: + a = 9 + except: + b = 9 + finally: + c = 9""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + finally: + try: + pass + finally: + a = 6""" + self.assertTrue(self.find_binding("a", s)) + + s = """ + try: + b = 8 + finally: + try: + b = 6 + finally: + b = 7""" + self.assertFalse(self.find_binding("a", s)) + +class Test_touch_import(support.TestCase): + + def test_after_docstring(self): + node = parse('"""foo"""\nbar()') + fixer_util.touch_import(None, "foo", node) + self.assertEqual(str(node), '"""foo"""\nimport foo\nbar()\n\n') + + def test_after_imports(self): + node = parse('"""foo"""\nimport bar\nbar()') + fixer_util.touch_import(None, "foo", node) + self.assertEqual(str(node), '"""foo"""\nimport bar\nimport foo\nbar()\n\n') + + def test_beginning(self): + node = parse('bar()') + fixer_util.touch_import(None, "foo", node) + self.assertEqual(str(node), 'import foo\nbar()\n\n') + + def test_from_import(self): + node = parse('bar()') + fixer_util.touch_import("html", "escape", node) + self.assertEqual(str(node), 'from html import escape\nbar()\n\n') + + def test_name_import(self): + node = parse('bar()') + fixer_util.touch_import(None, "cgi", node) + self.assertEqual(str(node), 'import cgi\nbar()\n\n') + +class Test_find_indentation(support.TestCase): + + def test_nothing(self): + fi = fixer_util.find_indentation + node = parse("node()") + self.assertEqual(fi(node), "") + node = parse("") + self.assertEqual(fi(node), "") + + def test_simple(self): + fi = fixer_util.find_indentation + node = parse("def f():\n x()") + self.assertEqual(fi(node), "") + self.assertEqual(fi(node.children[0].children[4].children[2]), " ") + node = parse("def f():\n x()\n y()") + self.assertEqual(fi(node.children[0].children[4].children[4]), " ") diff --git a/shared/package-files/02/02d145b9a3f81ce73fd6bb69be433bdb7924694e41d727c0aaed843a3d0f9265/_log_softmax_backward_data_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/02/02d145b9a3f81ce73fd6bb69be433bdb7924694e41d727c0aaed843a3d0f9265/_log_softmax_backward_data_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1cc4d4de5cdaebd7d31037da7853a329edcbf63a --- /dev/null +++ b/shared/package-files/02/02d145b9a3f81ce73fd6bb69be433bdb7924694e41d727c0aaed843a3d0f9265/_log_softmax_backward_data_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 _log_softmax_backward_data(const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, at::ScalarType input_dtype); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/02/02d474101a1394e6c8cccd9ced5408f899ff016b23b7460aa783584d63a98ab1/typeshed.py b/shared/package-files/02/02d474101a1394e6c8cccd9ced5408f899ff016b23b7460aa783584d63a98ab1/typeshed.py new file mode 100644 index 0000000000000000000000000000000000000000..50217cd34b495d311cbe0ff1fad02bb4a613646e --- /dev/null +++ b/shared/package-files/02/02d474101a1394e6c8cccd9ced5408f899ff016b23b7460aa783584d63a98ab1/typeshed.py @@ -0,0 +1,310 @@ +import os +import re +from functools import wraps +from collections import namedtuple +from typing import Dict, Mapping, Tuple +from pathlib import Path + +from jedi import settings +from jedi.file_io import FileIO +from jedi.parser_utils import get_cached_code_lines +from jedi.inference.base_value import ValueSet, NO_VALUES +from jedi.inference.gradual.stub_value import TypingModuleWrapper, StubModuleValue +from jedi.inference.value import ModuleValue + +_jedi_path = Path(__file__).parent.parent.parent +TYPESHED_PATH = _jedi_path.joinpath('third_party', 'typeshed') +DJANGO_INIT_PATH = _jedi_path.joinpath('third_party', 'django-stubs', + 'django-stubs', '__init__.pyi') + +_IMPORT_MAP = dict( + _collections='collections', + _socket='socket', +) + +PathInfo = namedtuple('PathInfo', 'path is_third_party') + + +def _merge_create_stub_map(path_infos): + map_ = {} + for directory_path_info in path_infos: + map_.update(_create_stub_map(directory_path_info)) + return map_ + + +def _create_stub_map(directory_path_info): + """ + Create a mapping of an importable name in Python to a stub file. + """ + def generate(): + try: + listed = os.listdir(directory_path_info.path) + except (FileNotFoundError, NotADirectoryError): + return + + for entry in listed: + path = os.path.join(directory_path_info.path, entry) + if os.path.isdir(path): + init = os.path.join(path, '__init__.pyi') + if os.path.isfile(init): + yield entry, PathInfo(init, directory_path_info.is_third_party) + elif entry.endswith('.pyi') and os.path.isfile(path): + name = entry[:-4] + if name != '__init__': + yield name, PathInfo(path, directory_path_info.is_third_party) + + # Create a dictionary from the tuple generator. + return dict(generate()) + + +def _get_typeshed_directories(version_info): + check_version_list = ['2and3', '3'] + for base in ['stdlib', 'third_party']: + base_path = TYPESHED_PATH.joinpath(base) + base_list = os.listdir(base_path) + for base_list_entry in base_list: + match = re.match(r'(\d+)\.(\d+)$', base_list_entry) + if match is not None: + if match.group(1) == '3' and int(match.group(2)) <= version_info.minor: + check_version_list.append(base_list_entry) + + for check_version in check_version_list: + is_third_party = base != 'stdlib' + yield PathInfo(str(base_path.joinpath(check_version)), is_third_party) + + +_version_cache: Dict[Tuple[int, int], Mapping[str, PathInfo]] = {} + + +def _cache_stub_file_map(version_info): + """ + Returns a map of an importable name in Python to a stub file. + """ + # TODO this caches the stub files indefinitely, maybe use a time cache + # for that? + version = version_info[:2] + try: + return _version_cache[version] + except KeyError: + pass + + _version_cache[version] = file_set = \ + _merge_create_stub_map(_get_typeshed_directories(version_info)) + return file_set + + +def import_module_decorator(func): + @wraps(func) + def wrapper(inference_state, import_names, parent_module_value, sys_path, prefer_stubs): + python_value_set = inference_state.module_cache.get(import_names) + if python_value_set is None: + if parent_module_value is not None and parent_module_value.is_stub(): + parent_module_values = parent_module_value.non_stub_value_set + else: + parent_module_values = [parent_module_value] + if import_names == ('os', 'path'): + # This is a huge exception, we follow a nested import + # ``os.path``, because it's a very important one in Python + # that is being achieved by messing with ``sys.modules`` in + # ``os``. + python_value_set = ValueSet.from_sets( + func(inference_state, (n,), None, sys_path,) + for n in ['posixpath', 'ntpath', 'macpath', 'os2emxpath'] + ) + else: + python_value_set = ValueSet.from_sets( + func(inference_state, import_names, p, sys_path,) + for p in parent_module_values + ) + inference_state.module_cache.add(import_names, python_value_set) + + if not prefer_stubs or import_names[0] in settings.auto_import_modules: + return python_value_set + + stub = try_to_load_stub_cached(inference_state, import_names, python_value_set, + parent_module_value, sys_path) + if stub is not None: + return ValueSet([stub]) + return python_value_set + + return wrapper + + +def try_to_load_stub_cached(inference_state, import_names, *args, **kwargs): + if import_names is None: + return None + + try: + return inference_state.stub_module_cache[import_names] + except KeyError: + pass + + # TODO is this needed? where are the exceptions coming from that make this + # necessary? Just remove this line. + inference_state.stub_module_cache[import_names] = None + inference_state.stub_module_cache[import_names] = result = \ + _try_to_load_stub(inference_state, import_names, *args, **kwargs) + return result + + +def _try_to_load_stub(inference_state, import_names, python_value_set, + parent_module_value, sys_path): + """ + Trying to load a stub for a set of import_names. + + This is modelled to work like "PEP 561 -- Distributing and Packaging Type + Information", see https://www.python.org/dev/peps/pep-0561. + """ + if parent_module_value is None and len(import_names) > 1: + try: + parent_module_value = try_to_load_stub_cached( + inference_state, import_names[:-1], NO_VALUES, + parent_module_value=None, sys_path=sys_path) + except KeyError: + pass + + # 1. Try to load foo-stubs folders on path for import name foo. + if len(import_names) == 1: + # foo-stubs + for p in sys_path: + init = os.path.join(p, *import_names) + '-stubs' + os.path.sep + '__init__.pyi' + m = _try_to_load_stub_from_file( + inference_state, + python_value_set, + file_io=FileIO(init), + import_names=import_names, + ) + if m is not None: + return m + if import_names[0] == 'django' and python_value_set: + return _try_to_load_stub_from_file( + inference_state, + python_value_set, + file_io=FileIO(str(DJANGO_INIT_PATH)), + import_names=import_names, + ) + + # 2. Try to load pyi files next to py files. + for c in python_value_set: + try: + method = c.py__file__ + except AttributeError: + pass + else: + file_path = method() + file_paths = [] + if c.is_namespace(): + file_paths = [os.path.join(p, '__init__.pyi') for p in c.py__path__()] + elif file_path is not None and file_path.suffix == '.py': + file_paths = [str(file_path) + 'i'] + + for file_path in file_paths: + m = _try_to_load_stub_from_file( + inference_state, + python_value_set, + # The file path should end with .pyi + file_io=FileIO(file_path), + import_names=import_names, + ) + if m is not None: + return m + + # 3. Try to load typeshed + m = _load_from_typeshed(inference_state, python_value_set, parent_module_value, import_names) + if m is not None: + return m + + # 4. Try to load pyi file somewhere if python_value_set was not defined. + if not python_value_set: + if parent_module_value is not None: + check_path = parent_module_value.py__path__() or [] + # In case import_names + names_for_path = (import_names[-1],) + else: + check_path = sys_path + names_for_path = import_names + + for p in check_path: + m = _try_to_load_stub_from_file( + inference_state, + python_value_set, + file_io=FileIO(os.path.join(p, *names_for_path) + '.pyi'), + import_names=import_names, + ) + if m is not None: + return m + + # If no stub is found, that's fine, the calling function has to deal with + # it. + return None + + +def _load_from_typeshed(inference_state, python_value_set, parent_module_value, import_names): + import_name = import_names[-1] + map_ = None + if len(import_names) == 1: + map_ = _cache_stub_file_map(inference_state.grammar.version_info) + import_name = _IMPORT_MAP.get(import_name, import_name) + elif isinstance(parent_module_value, ModuleValue): + if not parent_module_value.is_package(): + # Only if it's a package (= a folder) something can be + # imported. + return None + paths = parent_module_value.py__path__() + # Once the initial package has been loaded, the sub packages will + # always be loaded, regardless if they are there or not. This makes + # sense, IMO, because stubs take preference, even if the original + # library doesn't provide a module (it could be dynamic). ~dave + map_ = _merge_create_stub_map([PathInfo(p, is_third_party=False) for p in paths]) + + if map_ is not None: + path_info = map_.get(import_name) + if path_info is not None and (not path_info.is_third_party or python_value_set): + return _try_to_load_stub_from_file( + inference_state, + python_value_set, + file_io=FileIO(path_info.path), + import_names=import_names, + ) + + +def _try_to_load_stub_from_file(inference_state, python_value_set, file_io, import_names): + try: + stub_module_node = parse_stub_module(inference_state, file_io) + except OSError: + # The file that you're looking for doesn't exist (anymore). + return None + else: + return create_stub_module( + inference_state, inference_state.latest_grammar, python_value_set, + stub_module_node, file_io, import_names + ) + + +def parse_stub_module(inference_state, file_io): + return inference_state.parse( + file_io=file_io, + cache=True, + diff_cache=settings.fast_parser, + cache_path=settings.cache_directory, + use_latest_grammar=True + ) + + +def create_stub_module(inference_state, grammar, python_value_set, + stub_module_node, file_io, import_names): + if import_names == ('typing',): + module_cls = TypingModuleWrapper + else: + module_cls = StubModuleValue + file_name = os.path.basename(file_io.path) + stub_module_value = module_cls( + python_value_set, inference_state, stub_module_node, + file_io=file_io, + string_names=import_names, + # The code was loaded with latest_grammar, so use + # that. + code_lines=get_cached_code_lines(grammar, file_io.path), + is_package=file_name == '__init__.pyi', + ) + return stub_module_value diff --git a/shared/package-files/02/02d517a991b1e0fa5bc273b0faa545fd671bc43008d5793ee9df5c95ddb45d95/mkldnn_linear_backward_input_native.h b/shared/package-files/02/02d517a991b1e0fa5bc273b0faa545fd671bc43008d5793ee9df5c95ddb45d95/mkldnn_linear_backward_input_native.h new file mode 100644 index 0000000000000000000000000000000000000000..c0bf1ed0f1b5b2404a1a39375067e7dc93fedeff --- /dev/null +++ b/shared/package-files/02/02d517a991b1e0fa5bc273b0faa545fd671bc43008d5793ee9df5c95ddb45d95/mkldnn_linear_backward_input_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 & mkldnn_linear_backward_input_out(at::IntArrayRef input_size, const at::Tensor & grad_output, const at::Tensor & weight, at::Tensor & out); +TORCH_API at::Tensor mkldnn_linear_backward_input(at::IntArrayRef input_size, const at::Tensor & grad_output, const at::Tensor & weight); +} // namespace native +} // namespace at diff --git a/shared/package-files/02/02d6530d1cc7101ed09cac455efb56b0d508d5c0827b6eec01fa437d07743306/Damascus b/shared/package-files/02/02d6530d1cc7101ed09cac455efb56b0d508d5c0827b6eec01fa437d07743306/Damascus new file mode 100644 index 0000000000000000000000000000000000000000..bd1624de5148d5670e4585dfcb445d8b270c02df Binary files /dev/null and b/shared/package-files/02/02d6530d1cc7101ed09cac455efb56b0d508d5c0827b6eec01fa437d07743306/Damascus differ diff --git a/shared/package-files/02/02d7738657f2a3990cbd9df24bea9465047e5a10212b1679e3542bb369ddc772/dynamic_factor_mq.py b/shared/package-files/02/02d7738657f2a3990cbd9df24bea9465047e5a10212b1679e3542bb369ddc772/dynamic_factor_mq.py new file mode 100644 index 0000000000000000000000000000000000000000..2733dc9c56bd98c65507ff3024881408f6eb2dd5 --- /dev/null +++ b/shared/package-files/02/02d7738657f2a3990cbd9df24bea9465047e5a10212b1679e3542bb369ddc772/dynamic_factor_mq.py @@ -0,0 +1,4441 @@ +""" +Dynamic factor model + +Author: Chad Fulton +License: BSD-3 +""" +from statsmodels.compat.pandas import MONTH_END, QUARTER_END + +from collections import OrderedDict +from warnings import warn + +import numpy as np +import pandas as pd +from scipy.linalg import LinAlgError, cho_factor, cho_solve + +from statsmodels.base.data import PandasData +from statsmodels.genmod.generalized_linear_model import GLM +from statsmodels.iolib.summary import Summary +from statsmodels.iolib.table import SimpleTable +from statsmodels.iolib.tableformatting import fmt_params +from statsmodels.multivariate.pca import PCA +from statsmodels.regression.linear_model import OLS +from statsmodels.tools._decorators import cache_readonly +from statsmodels.tools.data import _is_using_pandas +from statsmodels.tools.sm_exceptions import ConvergenceWarning, EstimationWarning +from statsmodels.tools.tools import Bunch +from statsmodels.tools.validation import int_like, string_like +from statsmodels.tsa.statespace import initialization, mlemodel +from statsmodels.tsa.statespace._quarterly_ar1 import QuarterlyAR1 +from statsmodels.tsa.statespace.kalman_smoother import ( + SMOOTHER_STATE, + SMOOTHER_STATE_AUTOCOV, + SMOOTHER_STATE_COV, +) +from statsmodels.tsa.statespace.sarimax import SARIMAX +from statsmodels.tsa.statespace.tools import ( + companion_matrix, + constrain_stationary_multivariate, + constrain_stationary_univariate, + is_invertible, + unconstrain_stationary_multivariate, + unconstrain_stationary_univariate, +) +from statsmodels.tsa.tsatools import lagmat +from statsmodels.tsa.vector_ar.var_model import VAR + + +class FactorBlock(dict): + """ + Helper class for describing and indexing a block of factors + + Parameters + ---------- + factor_names : tuple of str + Tuple of factor names in the block (in the order that they will appear + in the state vector). + factor_order : int + Order of the vector autoregression governing the factor block dynamics. + endog_factor_map : DataFrame + Mapping from endog variable names to factor names. + state_offset : int + Offset of this factor block in the state vector. + k_endog_Q : int + Number of quarterly variables. + + Notes + ----- + The goal of this class is, in particular, to make it easier to retrieve + indexes of subsets of the state vector that are associated with a + particular block of factors. + + - `factors_ix` is a matrix of indices, with rows corresponding to factors + in the block and columns corresponding to lags + - `factors` is vec(factors_ix) (i.e., it stacks columns, so that it is + `factors_ix.ravel(order='F')`). Thinking about a VAR system, the first + k*p elements correspond to the equation for the first variable. The next + k*p elements correspond to the equation for the second variable, and so + on. It contains all of the lags in the state vector, which is max(5, p) + - `factors_ar` is the subset of `factors` that have nonzero coefficients, + so it contains lags up to p. + - `factors_L1` only contains the first lag of the factors + - `factors_L1_5` contains the first - fifth lags of the factors + + """ + + def __init__(self, factor_names, factor_order, endog_factor_map, + state_offset, k_endog_Q): + self.factor_names = factor_names + self.k_factors = len(self.factor_names) + self.factor_order = factor_order + self.endog_factor_map = endog_factor_map.loc[:, factor_names] + self.state_offset = state_offset + self.k_endog_Q = k_endog_Q + if self.k_endog_Q > 0: + self._factor_order = max(5, self.factor_order) + else: + self._factor_order = self.factor_order + self.k_states = self.k_factors * self._factor_order + + # Save items + self["factors"] = self.factors + self["factors_ar"] = self.factors_ar + self["factors_ix"] = self.factors_ix + self["factors_L1"] = self.factors_L1 + self["factors_L1_5"] = self.factors_L1_5 + + @property + def factors_ix(self): + """Factor state index array, shaped (k_factors, lags)""" + # i.e., the position in the state vector of the second lag of the third + # factor is factors_ix[2, 1] + # ravel(order='F') gives e.g (f0.L1, f1.L1, f0.L2, f1.L2, f0.L3, ...) + # while + # ravel(order='C') gives e.g (f0.L1, f0.L2, f0.L3, f1.L1, f1.L2, ...) + o = self.state_offset + return np.reshape(o + np.arange(self.k_factors * self._factor_order), + (self._factor_order, self.k_factors)).T + + @property + def factors(self): + """Factors and all lags in the state vector (max(5, p))""" + # Note that this is equivalent to factors_ix with ravel(order='F') + o = self.state_offset + return np.s_[o:o + self.k_factors * self._factor_order] + + @property + def factors_ar(self): + """Factors and all lags used in the factor autoregression (p)""" + o = self.state_offset + return np.s_[o:o + self.k_factors * self.factor_order] + + @property + def factors_L1(self): + """Factors (first block / lag only)""" + o = self.state_offset + return np.s_[o:o + self.k_factors] + + @property + def factors_L1_5(self): + """Factors plus four lags""" + o = self.state_offset + return np.s_[o:o + self.k_factors * 5] + + +class DynamicFactorMQStates(dict): + """ + Helper class for describing and indexing the state vector + + Parameters + ---------- + k_endog_M : int + Number of monthly (or non-time-specific, if k_endog_Q=0) variables. + k_endog_Q : int + Number of quarterly variables. + endog_names : list of str + Names of the endogenous variables. + factors : int, list of str, or dict + Integer giving the number of (global) factors, a list with the names of + (global) factors, or a dictionary with: + + - keys : names of endogenous variables + - values : lists of factor names. + + If this is an integer, then the factor names will be 0, 1, .... + factor_orders : int or dict + Integer describing the order of the vector autoregression (VAR) + governing all factor block dynamics or dictionary with: + + - keys : factor name or tuples of factor names in a block + - values : integer describing the VAR order for that factor block + + If a dictionary, this defines the order of the factor blocks in the + state vector. Otherwise, factors are ordered so that factors that load + on more variables come first (and then alphabetically, to break ties). + factor_multiplicities : int or dict + This argument provides a convenient way to specify multiple factors + that load identically on variables. For example, one may want two + "global" factors (factors that load on all variables) that evolve + jointly according to a VAR. One could specify two global factors in the + `factors` argument and specify that they are in the same block in the + `factor_orders` argument, but it is easier to specify a single global + factor in the `factors` argument, and set the order in the + `factor_orders` argument, and then set the factor multiplicity to 2. + + This argument must be an integer describing the factor multiplicity for + all factors or dictionary with: + + - keys : factor name + - values : integer describing the factor multiplicity for the factors + in the given block + idiosyncratic_ar1 : bool + Whether or not to model the idiosyncratic component for each series as + an AR(1) process. If False, the idiosyncratic component is instead + modeled as white noise. + + Attributes + ---------- + k_endog : int + Total number of endogenous variables. + k_states : int + Total number of state variables (those associated with the factors and + those associated with the idiosyncratic disturbances). + k_posdef : int + Total number of state disturbance terms (those associated with the + factors and those associated with the idiosyncratic disturbances). + k_endog_M : int + Number of monthly (or non-time-specific, if k_endog_Q=0) variables. + k_endog_Q : int + Number of quarterly variables. + k_factors : int + Total number of factors. Note that factor multiplicities will have + already been expanded. + k_states_factors : int + The number of state variables associated with factors (includes both + factors and lags of factors included in the state vector). + k_posdef_factors : int + The number of state disturbance terms associated with factors. + k_states_idio : int + Total number of state variables associated with idiosyncratic + disturbances. + k_posdef_idio : int + Total number of state disturbance terms associated with idiosyncratic + disturbances. + k_states_idio_M : int + The number of state variables associated with idiosyncratic + disturbances for monthly (or non-time-specific if there are no + quarterly variables) variables. If the disturbances are AR(1), then + this will be equal to `k_endog_M`, otherwise it will be equal to zero. + k_states_idio_Q : int + The number of state variables associated with idiosyncratic + disturbances for quarterly variables. This will always be equal to + `k_endog_Q * 5`, even if the disturbances are not AR(1). + k_posdef_idio_M : int + The number of state disturbance terms associated with idiosyncratic + disturbances for monthly (or non-time-specific if there are no + quarterly variables) variables. If the disturbances are AR(1), then + this will be equal to `k_endog_M`, otherwise it will be equal to zero. + k_posdef_idio_Q : int + The number of state disturbance terms associated with idiosyncratic + disturbances for quarterly variables. This will always be equal to + `k_endog_Q`, even if the disturbances are not AR(1). + idiosyncratic_ar1 : bool + Whether or not to model the idiosyncratic component for each series as + an AR(1) process. + factor_blocks : list of FactorBlock + List of `FactorBlock` helper instances for each factor block. + factor_names : list of str + List of factor names. + factors : dict + Dictionary with: + + - keys : names of endogenous variables + - values : lists of factor names. + + Note that factor multiplicities will have already been expanded. + factor_orders : dict + Dictionary with: + + - keys : tuple of factor names + - values : integer describing autoregression order + + Note that factor multiplicities will have already been expanded. + max_factor_order : int + Maximum autoregression order across all factor blocks. + factor_block_orders : Series + Series containing lag orders, with the factor block (a tuple of factor + names) as the index. + factor_multiplicities : dict + Dictionary with: + + - keys : factor name + - values : integer describing the factor multiplicity for the factors + in the given block + endog_factor_map : dict + Dictionary with: + + - keys : endog name + - values : list of factor names + loading_counts : Series + Series containing number of endogenous variables loading on each + factor, with the factor name as the index. + block_loading_counts : dict + Dictionary with: + + - keys : tuple of factor names + - values : average number of endogenous variables loading on the block + (note that average is over the factors in the block) + + Notes + ----- + The goal of this class is, in particular, to make it easier to retrieve + indexes of subsets of the state vector. + + Note that the ordering of the factor blocks in the state vector is + determined by the `factor_orders` argument if a dictionary. Otherwise, + factors are ordered so that factors that load on more variables come first + (and then alphabetically, to break ties). + + - `factors_L1` is an array with the indexes of first lag of the factors + from each block. Ordered first by block, and then by lag. + - `factors_L1_5` is an array with the indexes contains the first - fifth + lags of the factors from each block. Ordered first by block, and then by + lag. + - `factors_L1_5_ix` is an array shaped (5, k_factors) with the indexes + of the first - fifth lags of the factors from each block. + - `idio_ar_L1` is an array with the indexes of the first lag of the + idiosyncratic AR states, both monthly (if appliable) and quarterly. + - `idio_ar_M` is a slice with the indexes of the idiosyncratic disturbance + states for the monthly (or non-time-specific if there are no quarterly + variables) variables. It is an empty slice if + `idiosyncratic_ar1 = False`. + - `idio_ar_Q` is a slice with the indexes of the idiosyncratic disturbance + states and all lags, for the quarterly variables. It is an empty slice if + there are no quarterly variables. + - `idio_ar_Q_ix` is an array shaped (k_endog_Q, 5) with the indexes of the + first - fifth lags of the idiosyncratic disturbance states for the + quarterly variables. + - `endog_factor_iloc` is a list of lists, with entries for each endogenous + variable. The entry for variable `i`, `endog_factor_iloc[i]` is a list of + indexes of the factors that variable `i` loads on. This does not include + any lags, but it can be used with e.g., `factors_L1_5_ix` to get lags. + + """ + + def __init__(self, k_endog_M, k_endog_Q, endog_names, factors, + factor_orders, factor_multiplicities, idiosyncratic_ar1): + # Save model parameterization + self.k_endog_M = k_endog_M + self.k_endog_Q = k_endog_Q + self.k_endog = self.k_endog_M + self.k_endog_Q + self.idiosyncratic_ar1 = idiosyncratic_ar1 + + # Validate factor-related inputs + factors_is_int = np.issubdtype(type(factors), np.integer) + factors_is_list = isinstance(factors, (list, tuple)) + orders_is_int = np.issubdtype(type(factor_orders), np.integer) + if factor_multiplicities is None: + factor_multiplicities = 1 + mult_is_int = np.issubdtype(type(factor_multiplicities), np.integer) + + if not (factors_is_int or factors_is_list or + isinstance(factors, dict)): + raise ValueError("`factors` argument must an integer number of" + " factors, a list of global factor names, or a" + " dictionary, mapping observed variables to" + " factors.") + if not (orders_is_int or isinstance(factor_orders, dict)): + raise ValueError("`factor_orders` argument must either be an" + " integer or a dictionary.") + if not (mult_is_int or isinstance(factor_multiplicities, dict)): + raise ValueError("`factor_multiplicities` argument must either be" + " an integer or a dictionary.") + + # Expand integers + # If `factors` is an integer, we assume that it denotes the number of + # global factors (factors that load on each variable) + if factors_is_int or factors_is_list: + # Validate this here for a more informative error message + if ((factors_is_int and factors == 0) or + (factors_is_list and len(factors) == 0)): + raise ValueError("The model must contain at least one factor.") + + if factors_is_list: + factor_names = list(factors) + else: + factor_names = [f"{i}" for i in range(factors)] + factors = dict.fromkeys(endog_names, factor_names[:]) + _factor_names = [] + for val in factors.values(): + _factor_names.extend(val) + factor_names = set(_factor_names) + if orders_is_int: + factor_orders = dict.fromkeys(factor_names, factor_orders) + if mult_is_int: + factor_multiplicities = dict.fromkeys(factor_names, factor_multiplicities) + + # Apply the factor multiplicities + factors, factor_orders = self._apply_factor_multiplicities( + factors, factor_orders, factor_multiplicities) + + # Save the (potentially expanded) variables + self.factors = factors + self.factor_orders = factor_orders + self.factor_multiplicities = factor_multiplicities + + # Get the mapping between endog and factors + self.endog_factor_map = self._construct_endog_factor_map( + factors, endog_names) + self.k_factors = self.endog_factor_map.shape[1] + + # Validate number of factors + # TODO: could do more extensive validation here. + if self.k_factors > self.k_endog_M: + raise ValueError(f"Number of factors ({self.k_factors}) cannot be" + " greater than the number of monthly endogenous" + f" variables ({self.k_endog_M}).") + + # Get `loading_counts`: factor -> # endog loading on the factor + self.loading_counts = ( + self.endog_factor_map.sum(axis=0).rename("count") + .reset_index().sort_values(["count", "factor"], + ascending=[False, True]) + .set_index("factor")) + # `block_loading_counts`: block -> average of (# loading on factor) + # across each factor in the block + block_loading_counts = { + block: np.atleast_1d( + self.loading_counts.loc[list(block), "count"]).mean(axis=0) + for block in factor_orders} + ix = pd.Index(block_loading_counts.keys(), tupleize_cols=False, + name="block") + self.block_loading_counts = pd.Series( + list(block_loading_counts.values()), + index=ix, name="count").to_frame().sort_values( + ["count", "block"], ascending=[False, True])["count"] + + # Get the mapping between factor blocks and VAR order + + # `factor_block_orders`: pd.Series of factor block -> lag order + ix = pd.Index(factor_orders.keys(), tupleize_cols=False, name="block") + self.factor_block_orders = pd.Series( + list(factor_orders.values()), index=ix, name="order") + + # If the `factor_orders` variable was an integer, then it did not + # define an ordering for the factor blocks. In this case, we use the + # loading counts to do so. This ensures that e.g., global factors are + # listed first. + if orders_is_int: + keys = self.block_loading_counts.keys() + self.factor_block_orders = self.factor_block_orders.loc[keys] + self.factor_block_orders.index.name = "block" + + # Define factor_names based on factor_block_orders (instead of on those + # from `endog_factor_map`) to (a) make sure that factors are allocated + # to only one block, and (b) order the factor names to be consistent + # with the block definitions. + factor_names = pd.Series( + np.concatenate(list(self.factor_block_orders.index))) + missing = [name for name in self.endog_factor_map.columns + if name not in factor_names.tolist()] + if missing: + ix = pd.Index([(factor_name,) for factor_name in missing], + tupleize_cols=False, name="block") + default_block_orders = pd.Series(np.ones(len(ix), dtype=int), + index=ix, name="order") + self.factor_block_orders = pd.concat( + [self.factor_block_orders, default_block_orders]) + factor_names = pd.Series( + np.concatenate(list(self.factor_block_orders.index))) + duplicates = factor_names.duplicated() + if duplicates.any(): + duplicate_names = set(factor_names[duplicates]) + raise ValueError("Each factor can be assigned to at most one" + " block of factors in `factor_orders`." + f" Duplicate entries for {duplicate_names}") + self.factor_names = factor_names.tolist() + self.max_factor_order = np.max(self.factor_block_orders) + + # Re-order the columns of the endog factor mapping to reflect the + # orderings of endog_names and factor_names + self.endog_factor_map = ( + self.endog_factor_map.loc[endog_names, factor_names]) + + # Create factor block helpers, and get factor-related state and posdef + # dimensions + self.k_states_factors = 0 + self.k_posdef_factors = 0 + state_offset = 0 + self.factor_blocks = [] + for factor_names, factor_order in self.factor_block_orders.items(): + block = FactorBlock(factor_names, factor_order, + self.endog_factor_map, state_offset, + self.k_endog_Q) + self.k_states_factors += block.k_states + self.k_posdef_factors += block.k_factors + state_offset += block.k_states + + self.factor_blocks.append(block) + + # Idiosyncratic state dimensions + self.k_states_idio_M = self.k_endog_M if idiosyncratic_ar1 else 0 + self.k_states_idio_Q = self.k_endog_Q * 5 + self.k_states_idio = self.k_states_idio_M + self.k_states_idio_Q + + # Idiosyncratic posdef dimensions + self.k_posdef_idio_M = self.k_endog_M if self.idiosyncratic_ar1 else 0 + self.k_posdef_idio_Q = self.k_endog_Q + self.k_posdef_idio = self.k_posdef_idio_M + self.k_posdef_idio_Q + + # Total states, posdef + self.k_states = self.k_states_factors + self.k_states_idio + self.k_posdef = self.k_posdef_factors + self.k_posdef_idio + + # Cache + self._endog_factor_iloc = None + + def _apply_factor_multiplicities(self, factors, factor_orders, + factor_multiplicities): + """ + Expand `factors` and `factor_orders` to account for factor multiplicity + + For example, if there is a `global` factor with multiplicity 2, then + this method expands that into `global.1` and `global.2` in both the + `factors` and `factor_orders` dictionaries. + + Parameters + ---------- + factors : dict + Dictionary of {endog_name: list of factor names} + factor_orders : dict + Dictionary of {tuple of factor names: factor order} + factor_multiplicities : dict + Dictionary of {factor name: factor multiplicity} + + Returns + ------- + new_factors : dict + Dictionary of {endog_name: list of factor names}, with factor names + expanded to incorporate multiplicities. + new_factor_orders : dict + Dictionary of {tuple of factor names: factor order}, with factor + names in each tuple expanded to incorporate multiplicities. + """ + # Expand the factors to account for the multiplicities + new_factors = {} + for endog_name, factors_list in factors.items(): + new_factor_list = [] + for factor_name in factors_list: + n = factor_multiplicities.get(factor_name, 1) + if n > 1: + new_factor_list += [f"{factor_name}.{i + 1}" + for i in range(n)] + else: + new_factor_list.append(factor_name) + new_factors[endog_name] = new_factor_list + + # Expand the factor orders to account for the multiplicities + new_factor_orders = {} + for block, factor_order in factor_orders.items(): + block_tuple = block if isinstance(block, tuple) else (block,) + new_block = [] + for factor_name in block_tuple: + n = factor_multiplicities.get(factor_name, 1) + if n > 1: + new_block += [f"{factor_name}.{i + 1}" + for i in range(n)] + else: + new_block += [factor_name] + new_factor_orders[tuple(new_block)] = factor_order + + return new_factors, new_factor_orders + + def _construct_endog_factor_map(self, factors, endog_names): + """ + Construct mapping of observed variables to factors + + Parameters + ---------- + factors : dict + Dictionary of {endog_name: list of factor names} + endog_names : list of str + List of the names of the observed variables. + + Returns + ------- + endog_factor_map : DataFrame + Boolean dataframe with `endog_names` as the index and the factor + names (computed from the `factors` input) as the columns. Each cell + is True if the associated factor is allowed to load on the + associated observed variable. + + """ + # Validate that all entries in the factors dictionary have associated + # factors + missing = [] + for key, value in factors.items(): + if not isinstance(value, (list, tuple)) or len(value) == 0: + missing.append(key) + if missing: + raise ValueError("Each observed variable must be mapped to at" + " least one factor in the `factors` dictionary." + f" Variables missing factors are: {missing}.") + + # Validate that we have been told about the factors for each endog + # variable. This is because it doesn't make sense to include an + # observed variable that doesn't load on any factor + missing = set(endog_names).difference(set(factors.keys())) + if len(missing): + raise ValueError("If a `factors` dictionary is provided, then" + " it must include entries for each observed" + f" variable. Missing variables are: {missing}.") + + # Figure out the set of factor names + # (0 is just a dummy value for the dict - we just do it this way to + # collect the keys, in order, without duplicates.) + factor_names = {} + for value in factors.values(): + if isinstance(value, str): + factor_names[value] = 0 + else: + factor_names.update(dict.fromkeys(value, 0)) + factor_names = list(factor_names.keys()) + k_factors = len(factor_names) + + endog_factor_map = pd.DataFrame( + np.zeros((self.k_endog, k_factors), dtype=bool), + index=pd.Index(endog_names, name="endog"), + columns=pd.Index(factor_names, name="factor")) + for key, value in factors.items(): + endog_factor_map.loc[key, value] = True + + return endog_factor_map + + @property + def factors_L1(self): + """Factors""" + ix = np.arange(self.k_states_factors) + iloc = tuple(ix[block.factors_L1] for block in self.factor_blocks) + return np.concatenate(iloc) + + @property + def factors_L1_5_ix(self): + """Factors plus any lags, index shaped (5, k_factors)""" + ix = np.arange(self.k_states_factors) + iloc = [ + ix[block.factors_L1_5].reshape(5, block.k_factors) + for block in self.factor_blocks + ] + return np.concatenate(iloc, axis=1) + + @property + def idio_ar_L1(self): + """Idiosyncratic AR states, (first block / lag only)""" + ix1 = self.k_states_factors + if self.idiosyncratic_ar1: + ix2 = ix1 + self.k_endog + else: + ix2 = ix1 + self.k_endog_Q + return np.s_[ix1:ix2] + + @property + def idio_ar_M(self): + """Idiosyncratic AR states for monthly variables""" + ix1 = self.k_states_factors + ix2 = ix1 + if self.idiosyncratic_ar1: + ix2 += self.k_endog_M + return np.s_[ix1:ix2] + + @property + def idio_ar_Q(self): + """Idiosyncratic AR states and all lags for quarterly variables""" + # Note that this is equivalent to idio_ar_Q_ix with ravel(order='F') + ix1 = self.k_states_factors + if self.idiosyncratic_ar1: + ix1 += self.k_endog_M + ix2 = ix1 + self.k_endog_Q * 5 + return np.s_[ix1:ix2] + + @property + def idio_ar_Q_ix(self): + """Idiosyncratic AR (quarterly) state index, (k_endog_Q, lags)""" + # i.e., the position in the state vector of the second lag of the third + # quarterly variable is idio_ar_Q_ix[2, 1] + # ravel(order='F') gives e.g (y1.L1, y2.L1, y1.L2, y2.L3, y1.L3, ...) + # while + # ravel(order='C') gives e.g (y1.L1, y1.L2, y1.L3, y2.L1, y2.L2, ...) + start = self.k_states_factors + if self.idiosyncratic_ar1: + start += self.k_endog_M + return (start + np.reshape( + np.arange(5 * self.k_endog_Q), (5, self.k_endog_Q)).T) + + @property + def endog_factor_iloc(self): + """List of list of int, factor indexes for each observed variable""" + # i.e., endog_factor_iloc[i] is a list of integer locations of the + # factors that load on the ith observed variable + if self._endog_factor_iloc is None: + ilocs = [ + np.where(self.endog_factor_map.iloc[i])[0] + for i in range(self.k_endog) + ] + self._endog_factor_iloc = ilocs + return self._endog_factor_iloc + + def __getitem__(self, key): + """ + Use square brackets to access index / slice elements + + This is convenient in highlighting the indexing / slice quality of + these attributes in the code below. + """ + if key in ["factors_L1", "factors_L1_5_ix", "idio_ar_L1", "idio_ar_M", + "idio_ar_Q", "idio_ar_Q_ix"]: + return getattr(self, key) + else: + raise KeyError(key) + + +class DynamicFactorMQ(mlemodel.MLEModel): + r""" + Dynamic factor model with EM algorithm; option for monthly/quarterly data + + Implementation of the dynamic factor model of Bańbura and Modugno (2014) + ([1]_) and Bańbura, Giannone, and Reichlin (2011) ([2]_). Uses the EM + algorithm for parameter fitting, and so can accommodate a large number of + left-hand-side variables. Specifications can include any collection of + blocks of factors, including different factor autoregression orders, and + can include AR(1) processes for idiosyncratic disturbances. Can + incorporate monthly/quarterly mixed frequency data along the lines of + Mariano and Murasawa (2011) ([4]_). A special case of this model is the + Nowcasting model of Bok et al. (2017) ([3]_). Moreover, this model can be + used to compute the news associated with updated data releases. + + Parameters + ---------- + endog : array_like + Observed time-series process :math:`y`. See the "Notes" section for + details on how to set up a model with monthly/quarterly mixed frequency + data. + k_endog_monthly : int, optional + If specifying a monthly/quarterly mixed frequency model in which the + provided `endog` dataset contains both the monthly and quarterly data, + this variable should be used to indicate how many of the variables + are monthly. Note that when using the `k_endog_monthly` argument, the + columns with monthly variables in `endog` should be ordered first, and + the columns with quarterly variables should come afterwards. See the + "Notes" section for details on how to set up a model with + monthly/quarterly mixed frequency data. + factors : int, list of str, or dict, optional + Integer giving the number of (global) factors, a list with the names of + (global) factors, or a dictionary with: + + - keys : names of endogenous variables + - values : lists of factor names. + + If this is an integer, then the factor names will be 0, 1, .... The + default is a single factor that loads on all variables. Note that there + cannot be more factors specified than there are monthly variables. + factor_orders : int or dict, optional + Integer describing the order of the vector autoregression (VAR) + governing all factor block dynamics or dictionary with: + + - keys : factor name or tuples of factor names in a block + - values : integer describing the VAR order for that factor block + + If a dictionary, this defines the order of the factor blocks in the + state vector. Otherwise, factors are ordered so that factors that load + on more variables come first (and then alphabetically, to break ties). + factor_multiplicities : int or dict, optional + This argument provides a convenient way to specify multiple factors + that load identically on variables. For example, one may want two + "global" factors (factors that load on all variables) that evolve + jointly according to a VAR. One could specify two global factors in the + `factors` argument and specify that they are in the same block in the + `factor_orders` argument, but it is easier to specify a single global + factor in the `factors` argument, and set the order in the + `factor_orders` argument, and then set the factor multiplicity to 2. + + This argument must be an integer describing the factor multiplicity for + all factors or dictionary with: + + - keys : factor name + - values : integer describing the factor multiplicity for the factors + in the given block + + idiosyncratic_ar1 : bool, optional + Whether or not to model the idiosyncratic component for each series as + an AR(1) process. If False, the idiosyncratic component is instead + modeled as white noise. + standardize : bool or tuple, optional + If a boolean, whether or not to standardize each endogenous variable to + have mean zero and standard deviation 1 before fitting the model. See + "Notes" for details about how this option works with postestimation + output. If a tuple (usually only used internally), then the tuple must + have length 2, with each element containing a Pandas series with index + equal to the names of the endogenous variables. The first element + should contain the mean values and the second element should contain + the standard deviations. Default is True. + endog_quarterly : pandas.Series or pandas.DataFrame, optional + Observed quarterly variables. If provided, must be a Pandas Series or + DataFrame with a DatetimeIndex or PeriodIndex at the quarterly + frequency. See the "Notes" section for details on how to set up a model + with monthly/quarterly mixed frequency data. + init_t0 : bool, optional + If True, this option initializes the Kalman filter with the + distribution for :math:`\alpha_0` rather than :math:`\alpha_1`. See + the "Notes" section for more details. This option is rarely used except + for testing. Default is False. + obs_cov_diag : bool, optional + If True and if `idiosyncratic_ar1 is True`, then this option puts small + positive values in the observation disturbance covariance matrix. This + is not required for estimation and is rarely used except for testing. + (It is sometimes used to prevent numerical errors, for example those + associated with a positive semi-definite forecast error covariance + matrix at the first time step when using EM initialization, but state + space models in Statsmodels switch to the univariate approach in those + cases, and so do not need to use this trick). Default is False. + + Notes + ----- + The basic model is: + + .. math:: + + y_t & = \Lambda f_t + \epsilon_t \\ + f_t & = A_1 f_{t-1} + \dots + A_p f_{t-p} + u_t + + where: + + - :math:`y_t` is observed data at time t + - :math:`\epsilon_t` is idiosyncratic disturbance at time t (see below for + details, including modeling serial correlation in this term) + - :math:`f_t` is the unobserved factor at time t + - :math:`u_t \sim N(0, Q)` is the factor disturbance at time t + + and: + + - :math:`\Lambda` is referred to as the matrix of factor loadings + - :math:`A_i` are matrices of autoregression coefficients + + Furthermore, we allow the idiosyncratic disturbances to be serially + correlated, so that, if `idiosyncratic_ar1=True`, + :math:`\epsilon_{i,t} = \rho_i \epsilon_{i,t-1} + e_{i,t}`, where + :math:`e_{i,t} \sim N(0, \sigma_i^2)`. If `idiosyncratic_ar1=False`, + then we instead have :math:`\epsilon_{i,t} = e_{i,t}`. + + This basic setup can be found in [1]_, [2]_, [3]_, and [4]_. + + We allow for two generalizations of this model: + + 1. Following [2]_, we allow multiple "blocks" of factors, which are + independent from the other blocks of factors. Different blocks can be + set to load on different subsets of the observed variables, and can be + specified with different lag orders. + 2. Following [4]_ and [2]_, we allow mixed frequency models in which both + monthly and quarterly data are used. See the section on "Mixed frequency + models", below, for more details. + + Additional notes: + + - The observed data may contain arbitrary patterns of missing entries. + + **EM algorithm** + + This model contains a potentially very large number of parameters, and it + can be difficult and take a prohibitively long time to numerically optimize + the likelihood function using quasi-Newton methods. Instead, the default + fitting method in this model uses the EM algorithm, as detailed in [1]_. + As a result, the model can accommodate datasets with hundreds of + observed variables. + + **Mixed frequency data** + + This model can handle mixed frequency data in two ways. In this section, + we only briefly describe this, and refer readers to [2]_ and [4]_ for all + details. + + First, because there can be arbitrary patterns of missing data in the + observed vector, one can simply include lower frequency variables as + observed in a particular higher frequency period, and missing otherwise. + For example, in a monthly model, one could include quarterly data as + occurring on the third month of each quarter. To use this method, one + simply needs to combine the data into a single dataset at the higher + frequency that can be passed to this model as the `endog` argument. + However, depending on the type of variables used in the analysis and the + assumptions about the data generating process, this approach may not be + valid. + + For example, suppose that we are interested in the growth rate of real GDP, + which is measured at a quarterly frequency. If the basic factor model is + specified at a monthly frequency, then the quarterly growth rate in the + third month of each quarter -- which is what we actually observe -- is + approximated by a particular weighted average of unobserved monthly growth + rates. We need to take this particular weight moving average into account + in constructing our model, and this is what the second approach does. + + The second approach follows [2]_ and [4]_ in constructing a state space + form to explicitly model the quarterly growth rates in terms of the + unobserved monthly growth rates. To use this approach, there are two + methods: + + 1. Combine the monthly and quarterly data into a single dataset at the + monthly frequency, with the monthly data in the first columns and the + quarterly data in the last columns. Pass this dataset to the model as + the `endog` argument and give the number of the variables that are + monthly as the `k_endog_monthly` argument. + 2. Construct a monthly dataset as a Pandas DataFrame with a DatetimeIndex + or PeriodIndex at the monthly frequency and separately construct a + quarterly dataset as a Pandas DataFrame with a DatetimeIndex or + PeriodIndex at the quarterly frequency. Pass the monthly DataFrame to + the model as the `endog` argument and pass the quarterly DataFrame to + the model as the `endog_quarterly` argument. + + Note that this only incorporates one particular type of mixed frequency + data. See also Banbura et al. (2013). "Now-Casting and the Real-Time Data + Flow." for discussion about other types of mixed frequency data that are + not supported by this framework. + + **Nowcasting and the news** + + Through its support for monthly/quarterly mixed frequency data, this model + can allow for the nowcasting of quarterly variables based on monthly + observations. In particular, [2]_ and [3]_ use this model to construct + nowcasts of real GDP and analyze the impacts of "the news", derived from + incoming data on a real-time basis. This latter functionality can be + accessed through the `news` method of the results object. + + **Standardizing data** + + As is often the case in formulating a dynamic factor model, we do not + explicitly account for the mean of each observed variable. Instead, the + default behavior is to standardize each variable prior to estimation. Thus + if :math:`y_t` are the given observed data, the dynamic factor model is + actually estimated on the standardized data defined by: + + .. math:: + + x_{i, t} = (y_{i, t} - \bar y_i) / s_i + + where :math:`\bar y_i` is the sample mean and :math:`s_i` is the sample + standard deviation. + + By default, if standardization is applied prior to estimation, results such + as in-sample predictions, out-of-sample forecasts, and the computation of + the "news" are reported in the scale of the original data (i.e., the model + output has the reverse transformation applied before it is returned to the + user). + + Standardization can be disabled by passing `standardization=False` to the + model constructor. + + **Identification of factors and loadings** + + The estimated factors and the factor loadings in this model are only + identified up to an invertible transformation. As described in (the working + paper version of) [2]_, while it is possible to impose normalizations to + achieve identification, the EM algorithm will converge regardless. + Moreover, for nowcasting and forecasting purposes, identification is not + required. This model does not impose any normalization to identify the + factors and the factor loadings. + + **Miscellaneous** + + There are two arguments available in the model constructor that are rarely + used but which deserve a brief mention: `init_t0` and `obs_cov_diag`. These + arguments are provided to allow exactly matching the output of other + packages that have slight differences in how the underlying state space + model is set up / applied. + + - `init_t0`: state space models in Statsmodels follow Durbin and Koopman in + initializing the model with :math:`\alpha_1 \sim N(a_1, P_1)`. Other + implementations sometimes initialize instead with + :math:`\alpha_0 \sim N(a_0, P_0)`. We can accommodate this by prepending + a row of NaNs to the observed dataset. + - `obs_cov_diag`: the state space form in [1]_ incorporates non-zero (but + very small) diagonal elements for the observation disturbance covariance + matrix. + + References + ---------- + .. [1] Bańbura, Marta, and Michele Modugno. + "Maximum likelihood estimation of factor models on datasets with + arbitrary pattern of missing data." + Journal of Applied Econometrics 29, no. 1 (2014): 133-160. + .. [2] Bańbura, Marta, Domenico Giannone, and Lucrezia Reichlin. + "Nowcasting." + The Oxford Handbook of Economic Forecasting. July 8, 2011. + .. [3] Bok, Brandyn, Daniele Caratelli, Domenico Giannone, + Argia M. Sbordone, and Andrea Tambalotti. 2018. + "Macroeconomic Nowcasting and Forecasting with Big Data." + Annual Review of Economics 10 (1): 615-43. + https://doi.org/10.1146/annurev-economics-080217-053214. + .. [4] Mariano, Roberto S., and Yasutomo Murasawa. + "A coincident index, common factors, and monthly real GDP." + Oxford Bulletin of Economics and Statistics 72, no. 1 (2010): 27-46. + + Examples + -------- + Constructing and fitting a `DynamicFactorMQ` model. + + >>> data = sm.datasets.macrodata.load_pandas().data.iloc[-100:] + >>> data.index = pd.period_range(start='1984Q4', end='2009Q3', freq='Q') + >>> endog = data[['infl', 'tbilrate']].resample('M').last() + >>> endog_Q = np.log(data[['realgdp', 'realcons']]).diff().iloc[1:] * 400 + + **Basic usage** + + In the simplest case, passing only the `endog` argument results in a model + with a single factor that follows an AR(1) process. Note that because we + are not also providing an `endog_quarterly` dataset, `endog` can be a numpy + array or Pandas DataFrame with any index (it does not have to be monthly). + + The `summary` method can be useful in checking the model specification. + + >>> mod = sm.tsa.DynamicFactorMQ(endog) + >>> print(mod.summary()) + Model Specification: Dynamic Factor Model + ========================================================================== + Model: Dynamic Factor Model # of monthly variables: 2 + + 1 factors in 1 blocks # of factors: 1 + + AR(1) idiosyncratic Idiosyncratic disturbances: AR(1) + Sample: 1984-10 Standardize variables: True + - 2009-09 + Observed variables / factor loadings + ======================== + Dep. variable 0 + ------------------------ + infl X + tbilrate X + Factor blocks: + ===================== + block order + --------------------- + 0 1 + ===================== + + **Factors** + + With `factors=2`, there will be two independent factors that will each + evolve according to separate AR(1) processes. + + >>> mod = sm.tsa.DynamicFactorMQ(endog, factors=2) + >>> print(mod.summary()) + Model Specification: Dynamic Factor Model + ========================================================================== + Model: Dynamic Factor Model # of monthly variables: 2 + + 2 factors in 2 blocks # of factors: 2 + + AR(1) idiosyncratic Idiosyncratic disturbances: AR(1) + Sample: 1984-10 Standardize variables: True + - 2009-09 + Observed variables / factor loadings + =================================== + Dep. variable 0 1 + ----------------------------------- + infl X X + tbilrate X X + Factor blocks: + ===================== + block order + --------------------- + 0 1 + 1 1 + ===================== + + **Factor multiplicities** + + By instead specifying `factor_multiplicities=2`, we would still have two + factors, but they would be dependent and would evolve jointly according + to a VAR(1) process. + + >>> mod = sm.tsa.DynamicFactorMQ(endog, factor_multiplicities=2) + >>> print(mod.summary()) + Model Specification: Dynamic Factor Model + ========================================================================== + Model: Dynamic Factor Model # of monthly variables: 2 + + 2 factors in 1 blocks # of factors: 2 + + AR(1) idiosyncratic Idiosyncratic disturbances: AR(1) + Sample: 1984-10 Standardize variables: True + - 2009-09 + Observed variables / factor loadings + =================================== + Dep. variable 0.1 0.2 + ----------------------------------- + infl X X + tbilrate X X + Factor blocks: + ===================== + block order + --------------------- + 0.1, 0.2 1 + ===================== + + **Factor orders** + + In either of the above cases, we could extend the order of the (vector) + autoregressions by using the `factor_orders` argument. For example, the + below model would contain two independent factors that each evolve + according to a separate AR(2) process: + + >>> mod = sm.tsa.DynamicFactorMQ(endog, factors=2, factor_orders=2) + >>> print(mod.summary()) + Model Specification: Dynamic Factor Model + ========================================================================== + Model: Dynamic Factor Model # of monthly variables: 2 + + 2 factors in 2 blocks # of factors: 2 + + AR(1) idiosyncratic Idiosyncratic disturbances: AR(1) + Sample: 1984-10 Standardize variables: True + - 2009-09 + Observed variables / factor loadings + =================================== + Dep. variable 0 1 + ----------------------------------- + infl X X + tbilrate X X + Factor blocks: + ===================== + block order + --------------------- + 0 2 + 1 2 + ===================== + + **Serial correlation in the idiosyncratic disturbances** + + By default, the model allows each idiosyncratic disturbance term to evolve + according to an AR(1) process. If preferred, they can instead be specified + to be serially independent by passing `idiosyncratic_ar1=False`. + + >>> mod = sm.tsa.DynamicFactorMQ(endog, idiosyncratic_ar1=False) + >>> print(mod.summary()) + Model Specification: Dynamic Factor Model + ========================================================================== + Model: Dynamic Factor Model # of monthly variables: 2 + + 1 factors in 1 blocks # of factors: 1 + + iid idiosyncratic Idiosyncratic disturbances: iid + Sample: 1984-10 Standardize variables: True + - 2009-09 + Observed variables / factor loadings + ======================== + Dep. variable 0 + ------------------------ + infl X + tbilrate X + Factor blocks: + ===================== + block order + --------------------- + 0 1 + ===================== + + *Monthly / Quarterly mixed frequency* + + To specify a monthly / quarterly mixed frequency model see the (Notes + section for more details about these models): + + >>> mod = sm.tsa.DynamicFactorMQ(endog, endog_quarterly=endog_Q) + >>> print(mod.summary()) + Model Specification: Dynamic Factor Model + ========================================================================== + Model: Dynamic Factor Model # of monthly variables: 2 + + 1 factors in 1 blocks # of quarterly variables: 2 + + Mixed frequency (M/Q) # of factors: 1 + + AR(1) idiosyncratic Idiosyncratic disturbances: AR(1) + Sample: 1984-10 Standardize variables: True + - 2009-09 + Observed variables / factor loadings + ======================== + Dep. variable 0 + ------------------------ + infl X + tbilrate X + realgdp X + realcons X + Factor blocks: + ===================== + block order + --------------------- + 0 1 + ===================== + + *Customize observed variable / factor loadings* + + To specify that certain observed variables only load on + certain factors, it is possible to pass a dictionary to the `factors` + argument. + + >>> factors = {'infl': ['global'] + ... 'tbilrate': ['global'] + ... 'realgdp': ['global', 'real'] + ... 'realcons': ['global', 'real']} + >>> mod = sm.tsa.DynamicFactorMQ(endog, endog_quarterly=endog_Q) + >>> print(mod.summary()) + Model Specification: Dynamic Factor Model + ========================================================================== + Model: Dynamic Factor Model # of monthly variables: 2 + + 2 factors in 2 blocks # of quarterly variables: 2 + + Mixed frequency (M/Q) # of factor blocks: 2 + + AR(1) idiosyncratic Idiosyncratic disturbances: AR(1) + Sample: 1984-10 Standardize variables: True + - 2009-09 + Observed variables / factor loadings + =================================== + Dep. variable global real + ----------------------------------- + infl X + tbilrate X + realgdp X X + realcons X X + Factor blocks: + ===================== + block order + --------------------- + global 1 + real 1 + ===================== + + **Fitting parameters** + + To fit the model, use the `fit` method. This method uses the EM algorithm + by default. + + >>> mod = sm.tsa.DynamicFactorMQ(endog) + >>> res = mod.fit() + >>> print(res.summary()) + Dynamic Factor Results + ========================================================================== + Dep. Variable: ['infl', 'tbilrate'] No. Observations: 300 + Model: Dynamic Factor Model Log Likelihood -127.909 + + 1 factors in 1 blocks AIC 271.817 + + AR(1) idiosyncratic BIC 301.447 + Date: Tue, 04 Aug 2020 HQIC 283.675 + Time: 15:59:11 EM Iterations 83 + Sample: 10-31-1984 + - 09-30-2009 + Covariance Type: Not computed + Observation equation: + ============================================================== + Factor loadings: 0 idiosyncratic: AR(1) var. + -------------------------------------------------------------- + infl -0.67 0.39 0.73 + tbilrate -0.63 0.99 0.01 + Transition: Factor block 0 + ======================================= + L1.0 error variance + --------------------------------------- + 0 0.98 0.01 + ======================================= + Warnings: + [1] Covariance matrix not calculated. + + *Displaying iteration progress* + + To display information about the EM iterations, use the `disp` argument. + + >>> mod = sm.tsa.DynamicFactorMQ(endog) + >>> res = mod.fit(disp=10) + EM start iterations, llf=-291.21 + EM iteration 10, llf=-157.17, convergence criterion=0.053801 + EM iteration 20, llf=-128.99, convergence criterion=0.0035545 + EM iteration 30, llf=-127.97, convergence criterion=0.00010224 + EM iteration 40, llf=-127.93, convergence criterion=1.3281e-05 + EM iteration 50, llf=-127.92, convergence criterion=5.4725e-06 + EM iteration 60, llf=-127.91, convergence criterion=2.8665e-06 + EM iteration 70, llf=-127.91, convergence criterion=1.6999e-06 + EM iteration 80, llf=-127.91, convergence criterion=1.1085e-06 + EM converged at iteration 83, llf=-127.91, + convergence criterion=9.9004e-07 < tolerance=1e-06 + + **Results: forecasting, impulse responses, and more** + + Once the model is fitted, there are a number of methods available from the + results object. Some examples include: + + *Forecasting* + + >>> mod = sm.tsa.DynamicFactorMQ(endog) + >>> res = mod.fit() + >>> print(res.forecast(steps=5)) + infl tbilrate + 2009-10 1.784169 0.260401 + 2009-11 1.735848 0.305981 + 2009-12 1.730674 0.350968 + 2010-01 1.742110 0.395369 + 2010-02 1.759786 0.439194 + + *Impulse responses* + + >>> mod = sm.tsa.DynamicFactorMQ(endog) + >>> res = mod.fit() + >>> print(res.impulse_responses(steps=5)) + infl tbilrate + 0 -1.511956 -1.341498 + 1 -1.483172 -1.315960 + 2 -1.454937 -1.290908 + 3 -1.427240 -1.266333 + 4 -1.400069 -1.242226 + 5 -1.373416 -1.218578 + + For other available methods (including in-sample prediction, simulation of + time series, extending the results to incorporate new data, and the news), + see the documentation for state space models. + + """ + + def __init__(self, endog, k_endog_monthly=None, factors=1, factor_orders=1, + factor_multiplicities=None, idiosyncratic_ar1=True, + standardize=True, endog_quarterly=None, init_t0=False, + obs_cov_diag=False, **kwargs): + # Handle endog variables + if endog_quarterly is not None: + if k_endog_monthly is not None: + raise ValueError("If `endog_quarterly` is specified, then" + " `endog` must contain only monthly" + " variables, and so `k_endog_monthly` cannot" + " be specified since it will be inferred from" + " the shape of `endog`.") + endog, k_endog_monthly = self.construct_endog( + endog, endog_quarterly) + endog_is_pandas = _is_using_pandas(endog, None) + + if endog_is_pandas: + if isinstance(endog, pd.Series): + endog = endog.to_frame() + elif np.ndim(endog) < 2: + endog = np.atleast_2d(endog).T + + if k_endog_monthly is None: + k_endog_monthly = endog.shape[1] + + if endog_is_pandas: + endog_names = endog.columns.tolist() + elif endog.shape[1] == 1: + endog_names = ["y"] + else: + endog_names = [f"y{i + 1}" for i in range(endog.shape[1])] + + self.k_endog_M = int_like(k_endog_monthly, "k_endog_monthly") + self.k_endog_Q = endog.shape[1] - self.k_endog_M + + # Compute helper for handling factors / state indexing + s = self._s = DynamicFactorMQStates( + self.k_endog_M, self.k_endog_Q, endog_names, factors, + factor_orders, factor_multiplicities, idiosyncratic_ar1) + + # Save parameterization + self.factors = factors + self.factor_orders = factor_orders + self.factor_multiplicities = factor_multiplicities + + self.endog_factor_map = self._s.endog_factor_map + self.factor_block_orders = self._s.factor_block_orders + self.factor_names = self._s.factor_names + self.k_factors = self._s.k_factors + self.k_factor_blocks = len(self.factor_block_orders) + self.max_factor_order = self._s.max_factor_order + self.idiosyncratic_ar1 = idiosyncratic_ar1 + self.init_t0 = init_t0 + self.obs_cov_diag = obs_cov_diag + + if self.init_t0: + # TODO: test each of these options + if endog_is_pandas: + ix = pd.period_range(endog.index[0] - 1, endog.index[-1], + freq=endog.index.freq) + endog = endog.reindex(ix) + else: + endog = np.c_[[np.nan] * endog.shape[1], endog.T].T + + # Standardize endog, if requested + # Note: endog_mean and endog_std will always each be 1-dimensional with + # length equal to the number of endog variables + if isinstance(standardize, tuple) and len(standardize) == 2: + endog_mean, endog_std = standardize + + # Validate the input + n = endog.shape[1] + if (isinstance(endog_mean, pd.Series) and not + endog_mean.index.equals(pd.Index(endog_names))): + raise ValueError("Invalid value passed for `standardize`:" + " if a Pandas Series, must have index" + f" {endog_names}. Got {endog_mean.index}.") + else: + endog_mean = np.atleast_1d(endog_mean) + if (isinstance(endog_std, pd.Series) and not + endog_std.index.equals(pd.Index(endog_names))): + raise ValueError("Invalid value passed for `standardize`:" + " if a Pandas Series, must have index" + f" {endog_names}. Got {endog_std.index}.") + else: + endog_std = np.atleast_1d(endog_std) + + if (np.shape(endog_mean) != (n,) or np.shape(endog_std) != (n,)): + raise ValueError("Invalid value passed for `standardize`: each" + f" element must be shaped ({n},).") + standardize = True + + # Make sure we have Pandas if endog is Pandas + if endog_is_pandas: + endog_mean = pd.Series(endog_mean, index=endog_names) + endog_std = pd.Series(endog_std, index=endog_names) + + elif standardize in [1, True]: + endog_mean = endog.mean(axis=0) + endog_std = endog.std(axis=0) + elif standardize in [0, False]: + endog_mean = np.zeros(endog.shape[1]) + endog_std = np.ones(endog.shape[1]) + else: + raise ValueError("Invalid value passed for `standardize`.") + self._endog_mean = endog_mean + self._endog_std = endog_std + self.standardize = standardize + if np.any(self._endog_std < 1e-10): + ix = np.where(self._endog_std < 1e-10) + names = np.array(endog_names)[ix[0]].tolist() + raise ValueError("Constant variable(s) found in observed" + " variables, but constants cannot be included" + f" in this model. These variables are: {names}.") + + if self.standardize: + endog = (endog - self._endog_mean) / self._endog_std + + # Observation / states slices + o = self._o = { + "M": np.s_[:self.k_endog_M], + "Q": np.s_[self.k_endog_M:]} + + # Construct the basic state space representation + super().__init__(endog, k_states=s.k_states, k_posdef=s.k_posdef, + **kwargs) + + # Revert the standardization for orig_endog + if self.standardize: + self.data.orig_endog = ( + self.data.orig_endog * self._endog_std + self._endog_mean) + + # State initialization + # Note: we could just initialize the entire thing as stationary, but + # doing each block separately should be faster and avoid numerical + # issues + if "initialization" not in kwargs: + self.ssm.initialize(self._default_initialization()) + + # Fixed components of the state space representation + + # > design + if self.idiosyncratic_ar1: + self["design", o["M"], s["idio_ar_M"]] = np.eye(self.k_endog_M) + multipliers = [1, 2, 3, 2, 1] + for i in range(len(multipliers)): + m = multipliers[i] + self["design", o["Q"], s["idio_ar_Q_ix"][:, i]] = ( + m * np.eye(self.k_endog_Q)) + + # > obs cov + if self.obs_cov_diag: + self["obs_cov"] = np.eye(self.k_endog) * 1e-4 + + # > transition + for block in s.factor_blocks: + if block.k_factors == 1: + tmp = 0 + else: + tmp = np.zeros((block.k_factors, block.k_factors)) + self["transition", block["factors"], block["factors"]] = ( + companion_matrix([1] + [tmp] * block._factor_order).T) + if self.k_endog_Q == 1: + tmp = 0 + else: + tmp = np.zeros((self.k_endog_Q, self.k_endog_Q)) + self["transition", s["idio_ar_Q"], s["idio_ar_Q"]] = ( + companion_matrix([1] + [tmp] * 5).T) + + # > selection + ix1 = ix2 = 0 + for block in s.factor_blocks: + ix2 += block.k_factors + self["selection", block["factors_ix"][:, 0], ix1:ix2] = ( + np.eye(block.k_factors)) + ix1 = ix2 + if self.idiosyncratic_ar1: + ix2 = ix1 + self.k_endog_M + self["selection", s["idio_ar_M"], ix1:ix2] = np.eye(self.k_endog_M) + ix1 = ix2 + + ix2 = ix1 + self.k_endog_Q + self["selection", s["idio_ar_Q_ix"][:, 0], ix1:ix2] = ( + np.eye(self.k_endog_Q)) + + # Parameters + self.params = OrderedDict([ + ("loadings", np.sum(self.endog_factor_map.values)), + ("factor_ar", np.sum([block.k_factors**2 * block.factor_order + for block in s.factor_blocks])), + ("factor_cov", np.sum([block.k_factors * (block.k_factors + 1) // 2 + for block in s.factor_blocks])), + ("idiosyncratic_ar1", + self.k_endog if self.idiosyncratic_ar1 else 0), + ("idiosyncratic_var", self.k_endog)]) + self.k_params = np.sum(list(self.params.values())) + + # Parameter slices + ix = np.split(np.arange(self.k_params), + np.cumsum(list(self.params.values()))[:-1]) + self._p = dict(zip(self.params.keys(), ix, strict=True)) + + # Cache + self._loading_constraints = {} + + # Initialization kwarg keys, e.g., for cloning + self._init_keys += [ + "factors", "factor_orders", "factor_multiplicities", + "idiosyncratic_ar1", "standardize", "init_t0", + "obs_cov_diag"] + list(kwargs.keys()) + + @classmethod + def construct_endog(cls, endog_monthly, endog_quarterly): + """ + Construct a combined dataset from separate monthly and quarterly data + + Parameters + ---------- + endog_monthly : array_like + Monthly dataset. If a quarterly dataset is given, then this must + be a Pandas object with a PeriodIndex or DatetimeIndex at a monthly + frequency. + endog_quarterly : array_like or None + Quarterly dataset. If not None, then this must be a Pandas object + with a PeriodIndex or DatetimeIndex at a quarterly frequency. + + Returns + ------- + endog : array_like + If both endog_monthly and endog_quarterly were given, this is a + Pandas DataFrame with a PeriodIndex at the monthly frequency, with + all of the columns from `endog_monthly` ordered first and the + columns from `endog_quarterly` ordered afterwards. Otherwise it is + simply the input `endog_monthly` dataset. + k_endog_monthly : int + The number of monthly variables (which are ordered first) in the + returned `endog` dataset. + """ + # Create combined dataset + if endog_quarterly is not None: + # Validate endog_monthly + base_msg = ("If given both monthly and quarterly data" + " then the monthly dataset must be a Pandas" + " object with a date index at a monthly frequency.") + if not isinstance(endog_monthly, (pd.Series, pd.DataFrame)): + raise ValueError("Given monthly dataset is not a" + " Pandas object. " + base_msg) + elif endog_monthly.index.inferred_type not in ("datetime64", + "period"): + raise ValueError("Given monthly dataset has an" + " index with non-date values. " + base_msg) + elif not getattr(endog_monthly.index, "freqstr", "N")[0] == "M": + freqstr = getattr(endog_monthly.index, "freqstr", "None") + raise ValueError("Index of given monthly dataset has a" + " non-monthly frequency (to check this," + " examine the `freqstr` attribute of the" + " index of the dataset - it should start with" + " M if it is monthly)." + f" Got {freqstr}. " + base_msg) + + # Validate endog_quarterly + base_msg = ("If a quarterly dataset is given, then it must be a" + " Pandas object with a date index at a quarterly" + " frequency.") + if not isinstance(endog_quarterly, (pd.Series, pd.DataFrame)): + raise ValueError("Given quarterly dataset is not a" + " Pandas object. " + base_msg) + elif endog_quarterly.index.inferred_type not in ("datetime64", + "period"): + raise ValueError("Given quarterly dataset has an" + " index with non-date values. " + base_msg) + elif not getattr(endog_quarterly.index, "freqstr", "N")[0] == "Q": + freqstr = getattr(endog_quarterly.index, "freqstr", "None") + raise ValueError("Index of given quarterly dataset" + " has a non-quarterly frequency (to check" + " this, examine the `freqstr` attribute of" + " the index of the dataset - it should start" + " with Q if it is quarterly)." + f" Got {freqstr}. " + base_msg) + + # Convert to PeriodIndex, if applicable + if hasattr(endog_monthly.index, "to_period"): + endog_monthly = endog_monthly.to_period("M") + if hasattr(endog_quarterly.index, "to_period"): + endog_quarterly = endog_quarterly.to_period("Q") + + # Combine the datasets + quarterly_resamp = endog_quarterly.copy() + quarterly_resamp.index = quarterly_resamp.index.to_timestamp() + quarterly_resamp = quarterly_resamp.resample(QUARTER_END).first() + quarterly_resamp = quarterly_resamp.resample(MONTH_END).first() + quarterly_resamp.index = quarterly_resamp.index.to_period() + + endog = pd.concat([endog_monthly, quarterly_resamp], axis=1) + + # Make sure we didn't accidentally get duplicate column names + column_counts = endog.columns.value_counts() + if column_counts.max() > 1: + columns = endog.columns.values.astype(object) + for name in column_counts.index: + count = column_counts.loc[name] + if count == 1: + continue + mask = columns == name + columns[mask] = [f"{name}{i + 1}" for i in range(count)] + endog.columns = columns + else: + endog = endog_monthly.copy() + shape = endog_monthly.shape + k_endog_monthly = shape[1] if len(shape) == 2 else 1 + + return endog, k_endog_monthly + + def clone(self, endog, k_endog_monthly=None, endog_quarterly=None, + retain_standardization=False, **kwargs): + """ + Clone state space model with new data and optionally new specification + + Parameters + ---------- + endog : array_like + The observed time-series process :math:`y` + k_endog_monthly : int, optional + If specifying a monthly/quarterly mixed frequency model in which + the provided `endog` dataset contains both the monthly and + quarterly data, this variable should be used to indicate how many + of the variables are monthly. + endog_quarterly : array_like, optional + Observations of quarterly variables. If provided, must be a + Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at + the quarterly frequency. + retain_standardization : bool, optional + Whether or not to use the mean and standard deviation from the + original model to standardize the new data. Default is False. + kwargs + Keyword arguments to pass to the new model class to change the + model specification. + + Returns + ------- + model : DynamicFactorMQ instance + """ + if retain_standardization and self.standardize: + kwargs["standardize"] = (self._endog_mean, self._endog_std) + mod = self._clone_from_init_kwds( + endog, k_endog_monthly=k_endog_monthly, + endog_quarterly=endog_quarterly, **kwargs) + return mod + + @property + def _res_classes(self): + return {"fit": (DynamicFactorMQResults, mlemodel.MLEResultsWrapper)} + + def _default_initialization(self): + s = self._s + init = initialization.Initialization(self.k_states) + for block in s.factor_blocks: + init.set(block["factors"], "stationary") + if self.idiosyncratic_ar1: + for i in range(s["idio_ar_M"].start, s["idio_ar_M"].stop): + init.set(i, "stationary") + init.set(s["idio_ar_Q"], "stationary") + return init + + def _get_endog_names(self, truncate=None, as_string=None): + if truncate is None: + truncate = False if as_string is False or self.k_endog == 1 else 24 + if as_string is False and truncate is not False: + raise ValueError("Can only truncate endog names if they" + " are returned as a string.") + if as_string is None: + as_string = truncate is not False + + # The base `endog_names` property is only a list if there are at least + # two variables; often, we need it to be a list + endog_names = self.endog_names + if not isinstance(endog_names, list): + endog_names = [endog_names] + + if as_string: + endog_names = [str(name) for name in endog_names] + + if truncate is not False: + n = truncate + endog_names = [name if len(name) <= n else name[:n] + "..." + for name in endog_names] + + return endog_names + + @property + def _model_name(self): + model_name = [ + "Dynamic Factor Model", + f"{self.k_factors} factors in {self.k_factor_blocks} blocks"] + if self.k_endog_Q > 0: + model_name.append("Mixed frequency (M/Q)") + + error_type = "AR(1)" if self.idiosyncratic_ar1 else "iid" + model_name.append(f"{error_type} idiosyncratic") + + return model_name + + def summary(self, truncate_endog_names=None): + """ + Create a summary table describing the model + + Parameters + ---------- + truncate_endog_names : int, optional + The number of characters to show for names of observed variables. + Default is 24 if there is more than one observed variable, or + an unlimited number of there is only one. + """ + # Get endog names + endog_names = self._get_endog_names(truncate=truncate_endog_names, + as_string=True) + + title = "Model Specification: Dynamic Factor Model" + + if self._index_dates: + ix = self._index + d = ix[0] + sample = [f"{d}"] + d = ix[-1] + sample += ["- " + f"{d}"] + else: + sample = [str(0), " - " + str(self.nobs)] + + # Standardize the model name as a list of str + model_name = self._model_name + + # - Top summary table ------------------------------------------------ + top_left = [("Model:", [model_name[0]])] + top_left.extend( + ("", ["+ " + model_name[i]]) for i in range(1, len(model_name)) + ) + top_left += [ + ("Sample:", [sample[0]]), + ("", [sample[1]])] + + top_right = [] + if self.k_endog_Q > 0: + top_right += [ + ("# of monthly variables:", [self.k_endog_M]), + ("# of quarterly variables:", [self.k_endog_Q])] + else: + top_right += [("# of observed variables:", [self.k_endog])] + if self.k_factor_blocks == 1: + top_right += [("# of factors:", [self.k_factors])] + else: + top_right += [("# of factor blocks:", [self.k_factor_blocks])] + top_right += [("Idiosyncratic disturbances:", + ["AR(1)" if self.idiosyncratic_ar1 else "iid"]), + ("Standardize variables:", [self.standardize])] + + summary = Summary() + self.model = self + summary.add_table_2cols(self, gleft=top_left, gright=top_right, + title=title) + table_ix = 1 + del self.model + + # - Endog / factor map ----------------------------------------------- + data = self.endog_factor_map.replace({True: "X", False: ""}) + data.index = endog_names + for name, _ in data.items(): + data[name] = data[name] + (" " * (len(name) // 2)) + data.index.name = "Dep. variable" + data = data.reset_index() + + params_data = data.values + params_header = data.columns.map(str).tolist() + params_stubs = None + + title = "Observed variables / factor loadings" + table = SimpleTable( + params_data, params_header, params_stubs, + txt_fmt=fmt_params, title=title) + + summary.tables.insert(table_ix, table) + table_ix += 1 + + # - Factor blocks summary table -------------------------------------- + data = self.factor_block_orders.reset_index() + data["block"] = data["block"].map(", ".join) + try: + data[["order"]] = data[["order"]].map(str) + except AttributeError: + data[["order"]] = data[["order"]].applymap(str) + + params_data = data.values + params_header = data.columns.map(str).tolist() + params_stubs = None + + title = "Factor blocks:" + table = SimpleTable( + params_data, params_header, params_stubs, + txt_fmt=fmt_params, title=title) + + summary.tables.insert(table_ix, table) + table_ix += 1 + + return summary + + def __str__(self): + """Summary tables showing model specification""" + return str(self.summary()) + + @property + def state_names(self): + """(list of str) List of human readable names for unobserved states""" + # Factors + state_names = [] + for block in self._s.factor_blocks: + state_names += [f"{name}" for name in block.factor_names[:]] + for s in range(1, block._factor_order): + state_names += [f"L{s}.{name}" + for name in block.factor_names] + + # Monthly error + endog_names = self._get_endog_names() + if self.idiosyncratic_ar1: + endog_names_M = endog_names[self._o["M"]] + state_names += [f"eps_M.{name}" for name in endog_names_M] + endog_names_Q = endog_names[self._o["Q"]] + + # Quarterly error + state_names += [f"eps_Q.{name}" for name in endog_names_Q] + for s in range(1, 5): + state_names += [f"L{s}.eps_Q.{name}" for name in endog_names_Q] + return state_names + + @property + def param_names(self): + """(list of str) List of human readable parameter names""" + param_names = [] + # Loadings + # So that Lambda = params[ix].reshape(self.k_endog, self.k_factors) + # (where Lambda stacks Lambda_M and Lambda_Q) + endog_names = self._get_endog_names(as_string=False) + for endog_name in endog_names: + for block in self._s.factor_blocks: + param_names.extend( + f"loading.{factor_name}->{endog_name}" + for factor_name in block.factor_names + if self.endog_factor_map.loc[endog_name, factor_name] + ) + + # Factor VAR + for block in self._s.factor_blocks: + for to_factor in block.factor_names: + param_names += [f"L{i}.{from_factor}->{to_factor}" + for i in range(1, block.factor_order + 1) + for from_factor in block.factor_names] + + # Factor covariance + for i in range(len(self._s.factor_blocks)): + block = self._s.factor_blocks[i] + param_names += [f"fb({i}).cov.chol[{j + 1},{k + 1}]" + for j in range(block.k_factors) + for k in range(j + 1)] + + # Error AR(1) + if self.idiosyncratic_ar1: + endog_names_M = endog_names[self._o["M"]] + param_names += [f"L1.eps_M.{name}" for name in endog_names_M] + + endog_names_Q = endog_names[self._o["Q"]] + param_names += [f"L1.eps_Q.{name}" for name in endog_names_Q] + + # Error innovation variances + param_names += [f"sigma2.{name}" for name in endog_names] + + return param_names + + @property + def start_params(self): + """(array) Starting parameters for maximum likelihood estimation""" + params = np.zeros(self.k_params, dtype=np.float64) + + # (1) estimate factors one at a time, where the first step uses + # PCA on all `endog` variables that load on the first factor, and + # subsequent steps use residuals from the previous steps. + # TODO: what about factors that only load on quarterly variables? + endog_factor_map_M = self.endog_factor_map.iloc[:self.k_endog_M] + factors = [] + endog = np.require( + pd.DataFrame(self.endog).interpolate().bfill(), + requirements="W" + ) + for name in self.factor_names: + # Try to retrieve this from monthly variables, which is most + # consistent + endog_ix = np.where(endog_factor_map_M.loc[:, name])[0] + # But fall back to quarterly if necessary + if len(endog_ix) == 0: + endog_ix = np.where(self.endog_factor_map.loc[:, name])[0] + factor_endog = endog[:, endog_ix] + + res_pca = PCA(factor_endog, ncomp=1, method="eig", normalize=False) + factors.append(res_pca.factors) + endog[:, endog_ix] -= res_pca.projection + factors = np.concatenate(factors, axis=1) + + # (2) Estimate coefficients for each endog, one at a time (OLS for + # monthly variables, restricted OLS for quarterly). Also, compute + # residuals. + loadings = [] + resid = [] + for i in range(self.k_endog_M): + factor_ix = self._s.endog_factor_iloc[i] + factor_exog = factors[:, factor_ix] + mod_ols = OLS(self.endog[:, i], exog=factor_exog, missing="drop") + res_ols = mod_ols.fit() + loadings += res_ols.params.tolist() + resid.append(res_ols.resid) + for i in range(self.k_endog_M, self.k_endog): + factor_ix = self._s.endog_factor_iloc[i] + factor_exog = lagmat(factors[:, factor_ix], 4, original="in") + mod_glm = GLM(self.endog[:, i], factor_exog, missing="drop") + res_glm = mod_glm.fit_constrained(self.loading_constraints(i)) + loadings += res_glm.params[:len(factor_ix)].tolist() + resid.append(res_glm.resid_response) + params[self._p["loadings"]] = loadings + + # (3) For each factor block, use an AR or VAR model to get coefficients + # and covariance estimate + # Factor transitions + stationary = True + + factor_ar = [] + factor_cov = [] + i = 0 + for block in self._s.factor_blocks: + factors_endog = factors[:, i:i + block.k_factors] + i += block.k_factors + + if block.factor_order == 0: + continue + + if block.k_factors == 1: + mod_factors = SARIMAX(factors_endog, + order=(block.factor_order, 0, 0)) + sp = mod_factors.start_params + block_factor_ar = sp[:-1] + block_factor_cov = sp[-1:] + + coefficient_matrices = mod_factors.start_params[:-1] + elif block.k_factors > 1: + mod_factors = VAR(factors_endog) + res_factors = mod_factors.fit( + maxlags=block.factor_order, ic=None, trend="n") + + block_factor_ar = res_factors.params.T.ravel() + L = np.linalg.cholesky(res_factors.sigma_u) + block_factor_cov = L[np.tril_indices_from(L)] + + coefficient_matrices = np.transpose( + np.reshape(block_factor_ar, + (block.k_factors, block.k_factors, + block.factor_order)), (2, 0, 1)) + + # Test for stationarity + stationary = is_invertible([1] + list(-coefficient_matrices)) + + # Check for stationarity + if not stationary: + warn("Non-stationary starting factor autoregressive" + " parameters found for factor block" + f" {block.factor_names}. Using zeros as starting" + " parameters.", EstimationWarning, stacklevel=2) + block_factor_ar[:] = 0 + cov_factor = np.diag(factors_endog.std(axis=0)) + block_factor_cov = ( + cov_factor[np.tril_indices(block.k_factors)]) + factor_ar += block_factor_ar.tolist() + factor_cov += block_factor_cov.tolist() + params[self._p["factor_ar"]] = factor_ar + params[self._p["factor_cov"]] = factor_cov + + # (4) Use residuals from step (2) to estimate the idiosyncratic + # component + # Idiosyncratic component + if self.idiosyncratic_ar1: + idio_ar1 = [] + idio_var = [] + for i in range(self.k_endog_M): + mod_idio = SARIMAX(resid[i], order=(1, 0, 0), trend="c") + sp = mod_idio.start_params + idio_ar1.append(np.clip(sp[1], -0.99, 0.99)) + idio_var.append(np.clip(sp[-1], 1e-5, np.inf)) + for i in range(self.k_endog_M, self.k_endog): + y = self.endog[:, i].copy() + y[~np.isnan(y)] = resid[i] + mod_idio = QuarterlyAR1(y) + res_idio = mod_idio.fit(maxiter=10, return_params=True, + disp=False) + res_idio = mod_idio.fit_em(res_idio, maxiter=5, + return_params=True) + idio_ar1.append(np.clip(res_idio[0], -0.99, 0.99)) + idio_var.append(np.clip(res_idio[1], 1e-5, np.inf)) + params[self._p["idiosyncratic_ar1"]] = idio_ar1 + params[self._p["idiosyncratic_var"]] = idio_var + else: + idio_var = [np.var(resid[i]) for i in range(self.k_endog_M)] + for i in range(self.k_endog_M, self.k_endog): + y = self.endog[:, i].copy() + y[~np.isnan(y)] = resid[i] + mod_idio = QuarterlyAR1(y) + res_idio = mod_idio.fit(return_params=True, disp=False) + idio_var.append(np.clip(res_idio[1], 1e-5, np.inf)) + params[self._p["idiosyncratic_var"]] = idio_var + + return params + + def transform_params(self, unconstrained): + """ + Transform parameters from optimizer space to model space + + Transform unconstrained parameters used by the optimizer to constrained + parameters used in likelihood evaluation. + + Parameters + ---------- + unconstrained : array_like + Array of unconstrained parameters used by the optimizer, to be + transformed. + + Returns + ------- + constrained : array_like + Array of constrained parameters which may be used in likelihood + evaluation. + """ + constrained = unconstrained.copy() + + # Stationary factor VAR + unconstrained_factor_ar = unconstrained[self._p["factor_ar"]] + constrained_factor_ar = [] + i = 0 + for block in self._s.factor_blocks: + length = block.k_factors**2 * block.factor_order + tmp_coeff = np.reshape( + unconstrained_factor_ar[i:i + length], + (block.k_factors, block.k_factors * block.factor_order)) + tmp_cov = np.eye(block.k_factors) + tmp_coeff, _ = constrain_stationary_multivariate(tmp_coeff, + tmp_cov) + constrained_factor_ar += tmp_coeff.ravel().tolist() + i += length + constrained[self._p["factor_ar"]] = constrained_factor_ar + + # Stationary idiosyncratic AR(1) + if self.idiosyncratic_ar1: + idio_ar1 = unconstrained[self._p["idiosyncratic_ar1"]] + constrained[self._p["idiosyncratic_ar1"]] = [ + constrain_stationary_univariate(idio_ar1[i:i + 1])[0] + for i in range(self.k_endog)] + + # Positive idiosyncratic variances + constrained[self._p["idiosyncratic_var"]] = ( + constrained[self._p["idiosyncratic_var"]]**2) + + return constrained + + def untransform_params(self, constrained): + """ + Transform parameters from model space to optimizer space + + Transform constrained parameters used in likelihood evaluation + to unconstrained parameters used by the optimizer. + + Parameters + ---------- + constrained : array_like + Array of constrained parameters used in likelihood evaluation, to + be transformed. + + Returns + ------- + unconstrained : array_like + Array of unconstrained parameters used by the optimizer. + """ + unconstrained = constrained.copy() + + # Stationary factor VAR + constrained_factor_ar = constrained[self._p["factor_ar"]] + unconstrained_factor_ar = [] + i = 0 + for block in self._s.factor_blocks: + length = block.k_factors**2 * block.factor_order + tmp_coeff = np.reshape( + constrained_factor_ar[i:i + length], + (block.k_factors, block.k_factors * block.factor_order)) + tmp_cov = np.eye(block.k_factors) + tmp_coeff, _ = unconstrain_stationary_multivariate(tmp_coeff, + tmp_cov) + unconstrained_factor_ar += tmp_coeff.ravel().tolist() + i += length + unconstrained[self._p["factor_ar"]] = unconstrained_factor_ar + + # Stationary idiosyncratic AR(1) + if self.idiosyncratic_ar1: + idio_ar1 = constrained[self._p["idiosyncratic_ar1"]] + unconstrained[self._p["idiosyncratic_ar1"]] = [ + unconstrain_stationary_univariate(idio_ar1[i:i + 1])[0] + for i in range(self.k_endog)] + + # Positive idiosyncratic variances + unconstrained[self._p["idiosyncratic_var"]] = ( + unconstrained[self._p["idiosyncratic_var"]]**0.5) + + return unconstrained + + def update(self, params, **kwargs): + """ + Update the parameters of the model + + Parameters + ---------- + params : array_like + Array of new parameters. + transformed : bool, optional + Whether or not `params` is already transformed. If set to False, + `transform_params` is called. Default is True. + + """ + params = super().update(params, **kwargs) + + # Local copies + o = self._o + s = self._s + p = self._p + + # Loadings + loadings = params[p["loadings"]] + start = 0 + for i in range(self.k_endog_M): + iloc = self._s.endog_factor_iloc[i] + k_factors = len(iloc) + factor_ix = s["factors_L1"][iloc] + self["design", i, factor_ix] = loadings[start:start + k_factors] + start += k_factors + multipliers = np.array([1, 2, 3, 2, 1])[:, None] + for i in range(self.k_endog_M, self.k_endog): + iloc = self._s.endog_factor_iloc[i] + k_factors = len(iloc) + factor_ix = s["factors_L1_5_ix"][:, iloc] + self["design", i, factor_ix.ravel()] = np.ravel( + loadings[start:start + k_factors] * multipliers) + start += k_factors + + # Factor VAR + factor_ar = params[p["factor_ar"]] + start = 0 + for block in s.factor_blocks: + k_params = block.k_factors**2 * block.factor_order + A = np.reshape( + factor_ar[start:start + k_params], + (block.k_factors, block.k_factors * block.factor_order)) + start += k_params + self["transition", block["factors_L1"], block["factors_ar"]] = A + + # Factor covariance + factor_cov = params[p["factor_cov"]] + start = 0 + ix1 = 0 + for block in s.factor_blocks: + k_params = block.k_factors * (block.k_factors + 1) // 2 + L = np.zeros((block.k_factors, block.k_factors), + dtype=params.dtype) + L[np.tril_indices_from(L)] = factor_cov[start:start + k_params] + start += k_params + Q = L @ L.T + ix2 = ix1 + block.k_factors + self["state_cov", ix1:ix2, ix1:ix2] = Q + ix1 = ix2 + + # Error AR(1) + if self.idiosyncratic_ar1: + alpha = np.diag(params[p["idiosyncratic_ar1"]]) + self["transition", s["idio_ar_L1"], s["idio_ar_L1"]] = alpha + + # Error variances + if self.idiosyncratic_ar1: + self["state_cov", self.k_factors:, self.k_factors:] = ( + np.diag(params[p["idiosyncratic_var"]])) + else: + idio_var = params[p["idiosyncratic_var"]] + self["obs_cov", o["M"], o["M"]] = np.diag(idio_var[o["M"]]) + self["state_cov", self.k_factors:, self.k_factors:] = ( + np.diag(idio_var[o["Q"]])) + + @property + def loglike_constant(self): + """ + Constant term in the joint log-likelihood function + + Useful in facilitating comparisons to other packages that exclude the + constant from the log-likelihood computation. + """ + return -0.5 * (1 - np.isnan(self.endog)).sum() * np.log(2 * np.pi) + + def loading_constraints(self, i): + r""" + Matrix formulation of quarterly variables' factor loading constraints + + Parameters + ---------- + i : int + Index of the `endog` variable to compute constraints for. + + Returns + ------- + R : ndarray + Constraint matrix, shaped `(k_constraints, k_factors * 5)`. + q : ndarray + Constraint values, shaped `(k_constraints,)`. + + Notes + ----- + If the factors were known, then the factor loadings for the ith + quarterly variable would be computed by a linear regression of the form + + y_i = A_i' f + B_i' L1.f + C_i' L2.f + D_i' L3.f + E_i' L4.f + + where: + + - f is (k_i x 1) and collects all of the factors that load on y_i + - L{j}.f is (k_i x 1) and collects the jth lag of each factor + - A_i, ..., E_i are (k_i x 1) and collect factor loadings + + As the observed variable is quarterly while the factors are monthly, we + want to restrict the estimated regression coefficients to be: + + y_i = A_i f + 2 A_i L1.f + 3 A_i L2.f + 2 A_i L3.f + A_i L4.f + + Stack the unconstrained coefficients: \Lambda_i = [A_i' B_i' ... E_i']' + + Then the constraints can be written as follows, for l = 1, ..., k_i + + - 2 A_{i,l} - B_{i,l} = 0 + - 3 A_{i,l} - C_{i,l} = 0 + - 2 A_{i,l} - D_{i,l} = 0 + - A_{i,l} - E_{i,l} = 0 + + So that k_constraints = 4 * k_i. In matrix form the constraints are: + + .. math:: + + R \Lambda_i = q + + where :math:`\Lambda_i` is shaped `(k_i * 5,)`, :math:`R` is shaped + `(k_constraints, k_i * 5)`, and :math:`q` is shaped `(k_constraints,)`. + + + For example, for the case that k_i = 2, we can write: + + | 2 0 -1 0 0 0 0 0 0 0 | | A_{i,1} | | 0 | + | 0 2 0 -1 0 0 0 0 0 0 | | A_{i,2} | | 0 | + | 3 0 0 0 -1 0 0 0 0 0 | | B_{i,1} | | 0 | + | 0 3 0 0 0 -1 0 0 0 0 | | B_{i,2} | | 0 | + | 2 0 0 0 0 0 -1 0 0 0 | | C_{i,1} | = | 0 | + | 0 2 0 0 0 0 0 -1 0 0 | | C_{i,2} | | 0 | + | 1 0 0 0 0 0 0 0 -1 0 | | D_{i,1} | | 0 | + | 0 1 0 0 0 0 0 0 0 -1 | | D_{i,2} | | 0 | + | E_{i,1} | | 0 | + | E_{i,2} | | 0 | + + """ + if i < self.k_endog_M: + raise ValueError("No constraints for monthly variables.") + if i not in self._loading_constraints: + k_factors = self.endog_factor_map.iloc[i].sum() + + R = np.zeros((k_factors * 4, k_factors * 5)) + q = np.zeros(R.shape[0]) + + # Let R = [R_1 R_2] + # Then R_1 is multiples of the identity matrix + multipliers = np.array([1, 2, 3, 2, 1]) + R[:, :k_factors] = np.reshape( + (multipliers[1:] * np.eye(k_factors)[..., None]).T, + (k_factors * 4, k_factors)) + + # And R_2 is the identity + R[:, k_factors:] = np.diag([-1] * (k_factors * 4)) + + self._loading_constraints[i] = (R, q) + return self._loading_constraints[i] + + def fit(self, start_params=None, transformed=True, includes_fixed=False, + cov_type="none", cov_kwds=None, method="em", maxiter=500, + tolerance=1e-6, em_initialization=True, mstep_method=None, + full_output=1, disp=False, callback=None, return_params=False, + optim_score=None, optim_complex_step=None, optim_hessian=None, + flags=None, low_memory=False, llf_decrease_action="revert", + llf_decrease_tolerance=1e-4, **kwargs): + """ + Fits the model by maximum likelihood via Kalman filter + + Parameters + ---------- + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + If None, the default is given by Model.start_params. + transformed : bool, optional + Whether or not `start_params` is already transformed. Default is + True. + includes_fixed : bool, optional + If parameters were previously fixed with the `fix_params` method, + this argument describes whether or not `start_params` also includes + the fixed parameters, in addition to the free parameters. Default + is False. + cov_type : str, optional + The `cov_type` keyword governs the method for calculating the + covariance matrix of parameter estimates. Can be one of: + + - 'opg' for the outer product of gradient estimator + - 'oim' for the observed information matrix estimator, calculated + using the method of Harvey (1989) + - 'approx' for the observed information matrix estimator, + calculated using a numerical approximation of the Hessian matrix. + - 'robust' for an approximate (quasi-maximum likelihood) covariance + matrix that may be valid even in the presence of some + misspecifications. Intermediate calculations use the 'oim' + method. + - 'robust_approx' is the same as 'robust' except that the + intermediate calculations use the 'approx' method. + - 'none' for no covariance matrix calculation. + + Default is 'none', since computing this matrix can be very slow + when there are a large number of parameters. + cov_kwds : dict, optional + A dictionary of arguments affecting covariance matrix computation. + + **opg, oim, approx, robust, robust_approx** + + - 'approx_complex_step' : bool, optional - If True, numerical + approximations are computed using complex-step methods. If False, + numerical approximations are computed using finite difference + methods. Default is True. + - 'approx_centered' : bool, optional - If True, numerical + approximations computed using finite difference methods use a + centered approximation. Default is False. + method : str, optional + The `method` determines which solver from `scipy.optimize` + is used, and it can be chosen from among the following strings: + + - 'em' for the EM algorithm + - '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 + + 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. + tolerance : float, optional + Tolerance to use for convergence checking when using the EM + algorithm. To set the tolerance for other methods, pass + the optimizer-specific keyword argument(s). + em_initialization : bool, optional + Whether or not to also update the Kalman filter initialization + using the EM algorithm, if the EM algorithm is used for fitting. + Default is True. + mstep_method : {None, 'missing', 'nonmissing'}, optional + The EM algorithm maximization step, if the EM algorithm is used + for fitting. If there are no NaN values in the dataset, this can + be set to "nonmissing" (which is slightly faster) or "missing", + otherwise it must be "missing". Default is "nonmissing" if there + are no NaN values or "missing" if there are. + 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. + callback : callable callback(xk), optional + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + return_params : bool, optional + Whether or not to return only the array of maximizing parameters. + Default is False. + optim_score : {'harvey', 'approx'} or None, optional + The method by which the score vector is calculated. 'harvey' uses + the method from Harvey (1989), 'approx' uses either finite + difference or complex step differentiation depending upon the + value of `optim_complex_step`, and None uses the built-in gradient + approximation of the optimizer. Default is None. This keyword is + only relevant if the optimization method uses the score. + optim_complex_step : bool, optional + Whether or not to use complex step differentiation when + approximating the score; if False, finite difference approximation + is used. Default is True. This keyword is only relevant if + `optim_score` is set to 'harvey' or 'approx'. + optim_hessian : {'opg','oim','approx'}, optional + The method by which the Hessian is numerically approximated. 'opg' + uses outer product of gradients, 'oim' uses the information + matrix formula from Harvey (1989), and 'approx' uses numerical + approximation. This keyword is only relevant if the + optimization method uses the Hessian matrix. + flags : dict, optional + A dictionary of method flags to pass to the loglikelihood, score, + and Hessian functions used during optimization (for example + `transformed`, `includes_fixed`, `score_method`, and + `approx_complex_step`). These are constructed automatically from + the other arguments to `fit`, so this keyword is not typically + used directly. Default is None. + low_memory : bool, optional + If set to True, techniques are applied to substantially reduce + memory usage. If used, some features of the results object will + not be available (including smoothed results and in-sample + prediction), although out-of-sample forecasting is possible. + Note that this option is not available when using the EM algorithm + (which is the default for this model). Default is False. + llf_decrease_action : {'ignore', 'warn', 'revert'}, optional + Action to take if the log-likelihood decreases in an EM iteration. + 'ignore' continues the iterations, 'warn' issues a warning but + continues the iterations, while 'revert' ends the iterations and + returns the result from the last good iteration. Default is 'revert'. + llf_decrease_tolerance : float, optional + Minimum size of the log-likelihood decrease required to trigger a + warning or to end the EM iterations. Setting this value slightly + larger than zero allows small decreases in the log-likelihood that + may be caused by numerical issues. If set to zero, then any + decrease will trigger the `llf_decrease_action`. Default is 1e-4. + **kwargs + Additional keyword arguments to pass to the optimizer. + + Returns + ------- + MLEResults + + See Also + -------- + statsmodels.base.model.LikelihoodModel.fit + statsmodels.tsa.statespace.mlemodel.MLEResults + """ + if method == "em": + return self.fit_em( + start_params=start_params, transformed=transformed, + cov_type=cov_type, cov_kwds=cov_kwds, maxiter=maxiter, + tolerance=tolerance, em_initialization=em_initialization, + mstep_method=mstep_method, full_output=full_output, disp=disp, + return_params=return_params, low_memory=low_memory, + llf_decrease_action=llf_decrease_action, + llf_decrease_tolerance=llf_decrease_tolerance, **kwargs) + else: + return super().fit( + start_params=start_params, transformed=transformed, + includes_fixed=includes_fixed, cov_type=cov_type, + cov_kwds=cov_kwds, method=method, maxiter=maxiter, + full_output=full_output, disp=disp, + callback=callback, return_params=return_params, + optim_score=optim_score, + optim_complex_step=optim_complex_step, + optim_hessian=optim_hessian, flags=flags, + low_memory=low_memory, **kwargs) + + def fit_em(self, start_params=None, transformed=True, cov_type="none", + cov_kwds=None, maxiter=500, tolerance=1e-6, disp=False, + em_initialization=True, mstep_method=None, full_output=True, + return_params=False, low_memory=False, + llf_decrease_action="revert", llf_decrease_tolerance=1e-4): + """ + Fits the model by maximum likelihood via the EM algorithm + + Parameters + ---------- + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is to use `DynamicFactorMQ.start_params`. + transformed : bool, optional + Whether or not `start_params` is already transformed. Default is + True. + cov_type : str, optional + The `cov_type` keyword governs the method for calculating the + covariance matrix of parameter estimates. Can be one of: + + - 'opg' for the outer product of gradient estimator + - 'oim' for the observed information matrix estimator, calculated + using the method of Harvey (1989) + - 'approx' for the observed information matrix estimator, + calculated using a numerical approximation of the Hessian matrix. + - 'robust' for an approximate (quasi-maximum likelihood) covariance + matrix that may be valid even in the presence of some + misspecifications. Intermediate calculations use the 'oim' + method. + - 'robust_approx' is the same as 'robust' except that the + intermediate calculations use the 'approx' method. + - 'none' for no covariance matrix calculation. + + Default is 'none', since computing this matrix can be very slow + when there are a large number of parameters. + cov_kwds : dict, optional + A dictionary of arguments affecting covariance matrix computation. + + **opg, oim, approx, robust, robust_approx** + + - 'approx_complex_step' : bool, optional - If True, numerical + approximations are computed using complex-step methods. If False, + numerical approximations are computed using finite difference + methods. Default is True. + - 'approx_centered' : bool, optional - If True, numerical + approximations computed using finite difference methods use a + centered approximation. Default is False. + maxiter : int, optional + The maximum number of EM iterations to perform. + tolerance : float, optional + Parameter governing convergence of the EM algorithm. The + `tolerance` is the minimum relative increase in the likelihood + for which convergence will be declared. A smaller value for the + `tolerance` will typically yield more precise parameter estimates, + but will typically require more EM iterations. Default is 1e-6. + disp : int or bool, optional + Controls printing of EM iteration progress. If an integer, progress + is printed at every `disp` iterations. A value of True is + interpreted as the value of 1. Default is False (nothing will be + printed). + em_initialization : bool, optional + Whether or not to also update the Kalman filter initialization + using the EM algorithm. Default is True. + mstep_method : {None, 'missing', 'nonmissing'}, optional + The EM algorithm maximization step. If there are no NaN values + in the dataset, this can be set to "nonmissing" (which is slightly + faster) or "missing", otherwise it must be "missing". Default is + "nonmissing" if there are no NaN values or "missing" if there are. + full_output : bool, optional + Set to True to have all available output from EM iterations in + the Results object's mle_retvals attribute. + return_params : bool, optional + Whether or not to return only the array of maximizing parameters. + Default is False. + low_memory : bool, optional + This option cannot be used with the EM algorithm and will raise an + error if set to True. Default is False. + llf_decrease_action : {'ignore', 'warn', 'revert'}, optional + Action to take if the log-likelihood decreases in an EM iteration. + 'ignore' continues the iterations, 'warn' issues a warning but + continues the iterations, while 'revert' ends the iterations and + returns the result from the last good iteration. Default is 'revert'. + llf_decrease_tolerance : float, optional + Minimum size of the log-likelihood decrease required to trigger a + warning or to end the EM iterations. Setting this value slightly + larger than zero allows small decreases in the log-likelihood that + may be caused by numerical issues. If set to zero, then any + decrease will trigger the `llf_decrease_action`. Default is 1e-4. + + Returns + ------- + DynamicFactorMQResults + + See Also + -------- + statsmodels.tsa.statespace.mlemodel.MLEModel.fit + statsmodels.tsa.statespace.mlemodel.MLEResults + """ + if self._has_fixed_params: + raise NotImplementedError("Cannot fit using the EM algorithm while" + " holding some parameters fixed.") + if low_memory: + raise ValueError("Cannot fit using the EM algorithm when using" + " low_memory option.") + + if start_params is None: + start_params = self.start_params + transformed = True + else: + start_params = np.array(start_params, ndmin=1) + + if not transformed: + start_params = self.transform_params(start_params) + + llf_decrease_action = string_like( + llf_decrease_action, "llf_decrease_action", + options=["ignore", "warn", "revert"]) + + disp = int(disp) + + # Perform expectation-maximization + s = self._s + llf = [] + params = [start_params] + init = None + inits = [self.ssm.initialization] + i = 0 + delta = 0 + terminate = False + # init_stationary = None if em_initialization else True + while i < maxiter and not terminate and (i < 1 or (delta > tolerance)): + out = self._em_iteration(params[-1], init=init, + mstep_method=mstep_method) + new_llf = out[0].llf_obs.sum() + + # If we are not using EM initialization, then we need to check for + # non-stationary parameters + if not em_initialization: + self.update(out[1]) + switch_init = [] + T = self["transition"] + init = self.ssm.initialization + iloc = np.arange(self.k_states) + + # We may only have global initialization if we have no + # quarterly variables and idiosyncratic_ar1=False + if self.k_endog_Q == 0 and not self.idiosyncratic_ar1: + block = s.factor_blocks[0] + if init.initialization_type == "stationary": + Tb = T[block["factors"], block["factors"]] + if not np.all(np.linalg.eigvals(Tb) < (1 - 1e-10)): + init.set(block["factors"], "diffuse") + switch_init.append( + "factor block:" + f" {tuple(block.factor_names)}") + else: + # Factor blocks + for block in s.factor_blocks: + b = tuple(iloc[block["factors"]]) + init_type = init.blocks[b].initialization_type + if init_type == "stationary": + Tb = T[block["factors"], block["factors"]] + if not np.all(np.linalg.eigvals(Tb) < (1 - 1e-10)): + init.set(block["factors"], "diffuse") + switch_init.append( + "factor block:" + f" {tuple(block.factor_names)}") + + if self.idiosyncratic_ar1: + endog_names = self._get_endog_names(as_string=True) + # Monthly variables + for j in range(s["idio_ar_M"].start, s["idio_ar_M"].stop): + init_type = init.blocks[(j,)].initialization_type + if init_type == "stationary": + if not np.abs(T[j, j]) < (1 - 1e-10): + init.set(j, "diffuse") + name = endog_names[j - s["idio_ar_M"].start] + switch_init.append( + "idiosyncratic AR(1) for monthly" + f" variable: {name}") + + # Quarterly variables + if self.k_endog_Q > 0: + b = tuple(iloc[s["idio_ar_Q"]]) + init_type = init.blocks[b].initialization_type + if init_type == "stationary": + Tb = T[s["idio_ar_Q"], s["idio_ar_Q"]] + if not np.all(np.linalg.eigvals(Tb) < (1 - 1e-10)): + init.set(s["idio_ar_Q"], "diffuse") + switch_init.append( + "idiosyncratic AR(1) for the" + " block of quarterly variables") + + if len(switch_init) > 0: + warn("Non-stationary parameters found at EM iteration" + f" {i + 1}, which is not compatible with" + " stationary initialization. Initialization was" + " switched to diffuse for the following: " + f" {switch_init}, and fitting was restarted.", + EstimationWarning, stacklevel=2) + results = self.fit_em( + start_params=params[-1], transformed=transformed, + cov_type=cov_type, cov_kwds=cov_kwds, + maxiter=maxiter, tolerance=tolerance, + em_initialization=em_initialization, + mstep_method=mstep_method, full_output=full_output, + disp=disp, return_params=return_params, + low_memory=low_memory, + llf_decrease_action=llf_decrease_action, + llf_decrease_tolerance=llf_decrease_tolerance) + self.ssm.initialize(self._default_initialization()) + return results + + # Check for decrease in the log-likelihood + # Note: allow a little numerical error before declaring a decrease + llf_decrease = ( + i > 0 and (new_llf - llf[-1]) < -llf_decrease_tolerance) + + if llf_decrease_action == "revert" and llf_decrease: + warn(f"Log-likelihood decreased at EM iteration {i + 1}." + f" Reverting to the results from EM iteration {i}" + " (prior to the decrease) and returning the solution.", + EstimationWarning, + stacklevel=2) + # Terminated iteration + i -= 1 + terminate = True + else: + if llf_decrease_action == "warn" and llf_decrease: + warn(f"Log-likelihood decreased at EM iteration {i + 1}," + " which can indicate numerical issues.", + EstimationWarning, + stacklevel=2) + llf.append(new_llf) + params.append(out[1]) + if em_initialization: + init = initialization.Initialization( + self.k_states, "known", + constant=out[0].smoothed_state[..., 0], + stationary_cov=out[0].smoothed_state_cov[..., 0]) + inits.append(init) + if i > 0: + delta = (2 * np.abs(llf[-1] - llf[-2]) / + (np.abs(llf[-1]) + np.abs(llf[-2]))) + else: + delta = np.inf + + # If `disp` is not False, display the first iteration + if disp and i == 0: + print(f"EM start iterations, llf={llf[-1]:.5g}") + # Print output every `disp` observations + elif disp and ((i + 1) % disp) == 0: + print(f"EM iteration {i + 1}, llf={llf[-1]:.5g}," + f" convergence criterion={delta:.5g}") + + # Advance the iteration counter + i += 1 + + # Check for convergence + not_converged = (i == maxiter and delta > tolerance) + + # If no convergence without explicit termination, warn users + if not_converged: + warn(f"EM reached maximum number of iterations ({maxiter})," + f" without achieving convergence: llf={llf[-1]:.5g}," + f" convergence criterion={delta:.5g}" + f" (while specified tolerance was {tolerance:.5g})", + ConvergenceWarning, + stacklevel=2) + + # If `disp` is not False, display the final iteration + if disp: + if terminate: + print(f"EM terminated at iteration {i}, llf={llf[-1]:.5g}," + f" convergence criterion={delta:.5g}" + f" (while specified tolerance was {tolerance:.5g})") + elif not_converged: + print(f"EM reached maximum number of iterations ({maxiter})," + f" without achieving convergence: llf={llf[-1]:.5g}," + f" convergence criterion={delta:.5g}" + f" (while specified tolerance was {tolerance:.5g})") + else: + print(f"EM converged at iteration {i}, llf={llf[-1]:.5g}," + f" convergence criterion={delta:.5g}" + f" < tolerance={tolerance:.5g}") + + # Just return the fitted parameters if requested + if return_params: + result = params[-1] + # Otherwise construct the results class if desired + else: + if em_initialization: + base_init = self.ssm.initialization + self.ssm.initialization = init + # Note that because we are using params[-1], we are actually using + # the results from one additional iteration compared to the + # iteration at which we declared convergence. + result = self.smooth(params[-1], transformed=True, + cov_type=cov_type, cov_kwds=cov_kwds) + if em_initialization: + self.ssm.initialization = base_init + + # Save the output + if full_output: + llf.append(result.llf) + em_retvals = Bunch(params=np.array(params), llf=np.array(llf), iter=i, inits=inits) + em_settings = Bunch(method="em", tolerance=tolerance, maxiter=maxiter) + else: + em_retvals = None + em_settings = None + + result._results.mle_retvals = em_retvals + result._results.mle_settings = em_settings + + return result + + def _em_iteration(self, params0, init=None, mstep_method=None): + """EM iteration""" + # (E)xpectation step + res = self._em_expectation_step(params0, init=init) + + # (M)aximization step + params1 = self._em_maximization_step(res, params0, + mstep_method=mstep_method) + + return res, params1 + + def _em_expectation_step(self, params0, init=None): + """EM expectation step""" + # (E)xpectation step + self.update(params0) + # Re-initialize state, if new initialization is given + if init is not None: + base_init = self.ssm.initialization + self.ssm.initialization = init + # Perform smoothing, only saving what is required + res = self.ssm.smooth( + SMOOTHER_STATE | SMOOTHER_STATE_COV | SMOOTHER_STATE_AUTOCOV, + update_filter=False) + res.llf_obs = np.array( + self.ssm._kalman_filter.loglikelihood, copy=True) + # Reset initialization + if init is not None: + self.ssm.initialization = base_init + + return res + + def _em_maximization_step(self, res, params0, mstep_method=None): + """EM maximization step""" + s = self._s + + a = res.smoothed_state.T[..., None] + cov_a = res.smoothed_state_cov.transpose(2, 0, 1) + acov_a = res.smoothed_state_autocov.transpose(2, 0, 1) + + # E[a_t a_t'], t = 0, ..., T + Eaa = cov_a.copy() + np.matmul(a, a.transpose(0, 2, 1)) + # E[a_t a_{t-1}'], t = 1, ..., T + Eaa1 = acov_a[:-1] + np.matmul(a[1:], a[:-1].transpose(0, 2, 1)) + + # Observation equation + has_missing = np.any(res.nmissing) + if mstep_method is None: + mstep_method = "missing" if has_missing else "nonmissing" + mstep_method = string_like( + mstep_method, "mstep_method", options=("missing", "nonmissing") + ) + if mstep_method == "nonmissing" and has_missing: + raise ValueError('Cannot use EM algorithm option' + ' `mstep_method="nonmissing"` with missing data.') + + if mstep_method == "nonmissing": + func = self._em_maximization_obs_nonmissing + else: # mstep_method == "missing" + func = self._em_maximization_obs_missing + # TODO: compute H is pretty slow + Lambda, H = func(res, Eaa, a, compute_H=(not self.idiosyncratic_ar1)) + + # Factor VAR and covariance + factor_ar = [] + factor_cov = [] + for b in s.factor_blocks: + A = Eaa[:-1, b["factors_ar"], b["factors_ar"]].sum(axis=0) + B = Eaa1[:, b["factors_L1"], b["factors_ar"]].sum(axis=0) + C = Eaa[1:, b["factors_L1"], b["factors_L1"]].sum(axis=0) + nobs = Eaa.shape[0] - 1 + + # want: x = B A^{-1}, so solve: x A = B or solve: A' x' = B' + try: + f_A = cho_solve(cho_factor(A), B.T).T + except LinAlgError: + # Fall back to general solver if there are problems with + # positive-definiteness + f_A = np.linalg.solve(A, B.T).T + + f_Q = (C - f_A @ B.T) / nobs + factor_ar += f_A.ravel().tolist() + factor_cov += ( + np.linalg.cholesky(f_Q)[np.tril_indices_from(f_Q)].tolist()) + + # Idiosyncratic AR(1) and variances + if self.idiosyncratic_ar1: + ix = s["idio_ar_L1"] + + Ad = Eaa[:-1, ix, ix].sum(axis=0).diagonal() + Bd = Eaa1[:, ix, ix].sum(axis=0).diagonal() + Cd = Eaa[1:, ix, ix].sum(axis=0).diagonal() + nobs = Eaa.shape[0] - 1 + + alpha = Bd / Ad + sigma2 = (Cd - alpha * Bd) / nobs + else: + ix = s["idio_ar_L1"] + C = Eaa[:, ix, ix].sum(axis=0) + sigma2 = np.r_[H.diagonal()[self._o["M"]], + C.diagonal() / Eaa.shape[0]] + + # Save parameters + params1 = np.zeros_like(params0) + loadings = [] + for i in range(self.k_endog): + iloc = self._s.endog_factor_iloc[i] + factor_ix = s["factors_L1"][iloc] + loadings += Lambda[i, factor_ix].tolist() + params1[self._p["loadings"]] = loadings + params1[self._p["factor_ar"]] = factor_ar + params1[self._p["factor_cov"]] = factor_cov + if self.idiosyncratic_ar1: + params1[self._p["idiosyncratic_ar1"]] = alpha + params1[self._p["idiosyncratic_var"]] = sigma2 + + return params1 + + def _em_maximization_obs_nonmissing(self, res, Eaa, a, compute_H=False): + """EM maximization step, observation equation without missing data""" + s = self._s + dtype = Eaa.dtype + + # Observation equation (non-missing) + # Note: we only compute loadings for monthly variables because + # quarterly variables will always have missing entries, so we would + # never choose this method in that case + k = s.k_states_factors + Lambda = np.zeros((self.k_endog, k), dtype=dtype) + for i in range(self.k_endog): + y = self.endog[:, i:i + 1] + iloc = self._s.endog_factor_iloc[i] + factor_ix = s["factors_L1"][iloc] + + ix = (np.s_[:],) + np.ix_(factor_ix, factor_ix) + A = Eaa[ix].sum(axis=0) + B = y.T @ a[:, factor_ix, 0] + if self.idiosyncratic_ar1: + ix1 = s.k_states_factors + i + ix2 = ix1 + 1 + B -= Eaa[:, ix1:ix2, factor_ix].sum(axis=0) + + # want: x = B A^{-1}, so solve: x A = B or solve: A' x' = B' + try: + Lambda[i, factor_ix] = cho_solve(cho_factor(A), B.T).T + except LinAlgError: + # Fall back to general solver if there are problems with + # positive-definiteness + Lambda[i, factor_ix] = np.linalg.solve(A, B.T).T + + # Compute new obs cov + # Note: this is unnecessary if `idiosyncratic_ar1=True`. + # This is written in a slightly more general way than + # Banbura and Modugno (2014), equation (7); see instead equation (13) + # of Wu et al. (1996) + # "An algorithm for estimating parameters of state-space models" + if compute_H: + Z = self["design"].copy() + Z[:, :k] = Lambda + BL = self.endog.T @ a[..., 0] @ Z.T + C = self.endog.T @ self.endog + + H = (C + -BL - BL.T + Z @ Eaa.sum(axis=0) @ Z.T) / self.nobs + else: + H = np.zeros((self.k_endog, self.k_endog), dtype=dtype) * np.nan + + return Lambda, H + + def _em_maximization_obs_missing(self, res, Eaa, a, compute_H=False): + """EM maximization step, observation equation with missing data""" + s = self._s + dtype = Eaa.dtype + + # Observation equation (missing) + k = s.k_states_factors + Lambda = np.zeros((self.k_endog, k), dtype=dtype) + + W = (1 - res.missing.T) + mask = W.astype(bool) + + # Compute design for monthly + # Note: the relevant A changes for each i + for i in range(self.k_endog_M): + iloc = self._s.endog_factor_iloc[i] + factor_ix = s["factors_L1"][iloc] + + m = mask[:, i] + yt = self.endog[m, i:i + 1] + + ix = np.ix_(m, factor_ix, factor_ix) + Ai = Eaa[ix].sum(axis=0) + Bi = yt.T @ a[np.ix_(m, factor_ix)][..., 0] + if self.idiosyncratic_ar1: + ix1 = s.k_states_factors + i + ix2 = ix1 + 1 + Bi -= Eaa[m, ix1:ix2][..., factor_ix].sum(axis=0) + # want: x = B A^{-1}, so solve: x A = B or solve: A' x' = B' + try: + Lambda[i, factor_ix] = cho_solve(cho_factor(Ai), Bi.T).T + except LinAlgError: + # Fall back to general solver if there are problems with + # positive-definiteness + Lambda[i, factor_ix] = np.linalg.solve(Ai, Bi.T).T + + # Compute unrestricted design for quarterly + # See Banbura at al. (2011), where this is described in Appendix C, + # between equations (13) and (14). + if self.k_endog_Q > 0: + # Note: the relevant A changes for each i + multipliers = np.array([1, 2, 3, 2, 1])[:, None] + for i in range(self.k_endog_M, self.k_endog): + iloc = self._s.endog_factor_iloc[i] + factor_ix = s["factors_L1_5_ix"][:, iloc].ravel().tolist() + + R, _ = self.loading_constraints(i) + + iQ = i - self.k_endog_M + m = mask[:, i] + yt = self.endog[m, i:i + 1] + ix = np.ix_(m, factor_ix, factor_ix) + Ai = Eaa[ix].sum(axis=0) + BiQ = yt.T @ a[np.ix_(m, factor_ix)][..., 0] + if self.idiosyncratic_ar1: + ix = (np.s_[:],) + np.ix_(s["idio_ar_Q_ix"][iQ], factor_ix) + Eepsf = Eaa[ix] + BiQ -= (multipliers * Eepsf[m].sum(axis=0)).sum(axis=0) + + # Note that there was a typo in Banbura et al. (2011) for + # the formula applying the restrictions. In their notation, + # they show (C D C')^{-1} while it should be (C D^{-1} C')^{-1} + # Note: in reality, this is: + # unrestricted - Aii @ R.T @ RARi @ (R @ unrestricted - q) + # where the restrictions are defined as: R @ unrestricted = q + # However, here q = 0, so we can simplify. + try: + L_and_lower = cho_factor(Ai) + # x = BQ A^{-1}, or x A = BQ, so solve A' x' = (BQ)' + unrestricted = cho_solve(L_and_lower, BiQ.T).T[0] + AiiRT = cho_solve(L_and_lower, R.T) + + L_and_lower = cho_factor(R @ AiiRT) + RAiiRTiR = cho_solve(L_and_lower, R) + restricted = unrestricted - AiiRT @ RAiiRTiR @ unrestricted + except LinAlgError: + # Fall back to slower method if there are problems with + # positive-definiteness + Aii = np.linalg.inv(Ai) + unrestricted = (BiQ @ Aii)[0] + RARi = np.linalg.inv(R @ Aii @ R.T) + restricted = (unrestricted - + Aii @ R.T @ RARi @ R @ unrestricted) + Lambda[i, factor_ix] = restricted + + # Compute new obs cov + # Note: this is unnecessary if `idiosyncratic_ar1=True`. + # See Banbura and Modugno (2014), equation (12) + # This does not literally follow their formula, e.g., multiplying by the + # W_t selection matrices, because those formulas require loops that are + # relatively slow. The formulation here is vectorized. + if compute_H: + Z = self["design"].copy() + Z[:, :Lambda.shape[1]] = Lambda + + y = np.nan_to_num(self.endog) + C = y.T @ y + W = W[..., None] + IW = 1 - W + + WL = W * Z + WLT = WL.transpose(0, 2, 1) + BL = y[..., None] @ a.transpose(0, 2, 1) @ WLT + A = Eaa + + BLT = BL.transpose(0, 2, 1) + IWT = IW.transpose(0, 2, 1) + + H = (C + (-BL - BLT + WL @ A @ WLT + + IW * self["obs_cov"] * IWT).sum(axis=0)) / self.nobs + else: + H = np.zeros((self.k_endog, self.k_endog), dtype=dtype) * np.nan + + return Lambda, H + + def smooth(self, params, transformed=True, includes_fixed=False, + complex_step=False, cov_type="none", cov_kwds=None, + return_ssm=False, results_class=None, + results_wrapper_class=None, **kwargs): + """ + Kalman smoothing + + Parameters + ---------- + params : array_like + Array of parameters at which to evaluate the loglikelihood + function. + transformed : bool, optional + Whether or not `params` is already transformed. Default is True. + includes_fixed : bool, optional + If parameters were previously fixed with the `fix_params` method, + this argument describes whether or not `params` also includes + the fixed parameters, in addition to the free parameters. Default + is False. + complex_step : bool, optional + Whether or not to compute the smoothed output using complex step + differentiation. Default is False. + return_ssm : bool, optional + Whether or not to return only the state space output or a full + results object. Default is to return a full results object. + cov_type : str, optional + See `MLEResults.fit` for a description of covariance matrix types + for results object. Default is None. + cov_kwds : dict, optional + See `MLEResults.get_robustcov_results` for a description of required + keywords for alternative covariance estimators + results_class : type, optional + A results class to use for results object. Default is + `MLEResults`. + results_wrapper_class : type, optional + A results wrapper class to use for the results object. Default is + `MLEResultsWrapper`. + **kwargs + Additional keyword arguments to pass to the Kalman filter. See + `KalmanFilter.filter` for more details. + """ + return super().smooth( + params, transformed=transformed, includes_fixed=includes_fixed, + complex_step=complex_step, cov_type=cov_type, cov_kwds=cov_kwds, + return_ssm=return_ssm, results_class=results_class, + results_wrapper_class=results_wrapper_class, **kwargs) + + def filter(self, params, transformed=True, includes_fixed=False, + complex_step=False, cov_type="none", cov_kwds=None, + return_ssm=False, results_class=None, + results_wrapper_class=None, low_memory=False, **kwargs): + """ + Kalman filtering + + Parameters + ---------- + params : array_like + Array of parameters at which to evaluate the loglikelihood + function. + transformed : bool, optional + Whether or not `params` is already transformed. Default is True. + includes_fixed : bool, optional + If parameters were previously fixed with the `fix_params` method, + this argument describes whether or not `params` also includes + the fixed parameters, in addition to the free parameters. Default + is False. + complex_step : bool, optional + Whether or not to compute the filtered output using complex step + differentiation. Default is False. + return_ssm : bool, optional + Whether or not to return only the state space output or a full + results object. Default is to return a full results object. + cov_type : str, optional + See `MLEResults.fit` for a description of covariance matrix types + for results object. Default is 'none'. + cov_kwds : dict, optional + See `MLEResults.get_robustcov_results` for a description of required + keywords for alternative covariance estimators + results_class : type, optional + A results class to use for results object. Default is + `MLEResults`. + results_wrapper_class : type, optional + A results wrapper class to use for the results object. Default is + `MLEResultsWrapper`. + low_memory : bool, optional + If set to True, techniques are applied to substantially reduce + memory usage. If used, some features of the results object will + not be available (including in-sample prediction), although + out-of-sample forecasting is possible. Default is False. + **kwargs + Additional keyword arguments to pass to the Kalman filter. See + `KalmanFilter.filter` for more details. + """ + return super().filter( + params, transformed=transformed, includes_fixed=includes_fixed, + complex_step=complex_step, cov_type=cov_type, cov_kwds=cov_kwds, + return_ssm=return_ssm, results_class=results_class, + results_wrapper_class=results_wrapper_class, **kwargs) + + def simulate(self, params, nsimulations, measurement_shocks=None, + state_shocks=None, initial_state=None, anchor=None, + repetitions=None, exog=None, extend_model=None, + extend_kwargs=None, transformed=True, includes_fixed=False, + original_scale=True, **kwargs): + r""" + Simulate a new time series following the state space model + + Parameters + ---------- + params : array_like + Array of parameters to use in constructing the state space + representation to use when simulating. + nsimulations : int + The number of observations to simulate. If the model is + time-invariant this can be any number. If the model is + time-varying, then this number must be less than or equal to the + number of observations. + measurement_shocks : array_like, optional + If specified, these are the shocks to the measurement equation, + :math:`\varepsilon_t`. If unspecified, these are automatically + generated using a pseudo-random number generator. If specified, + must be shaped `nsimulations` x `k_endog`, where `k_endog` is the + same as in the state space model. + state_shocks : array_like, optional + If specified, these are the shocks to the state equation, + :math:`\eta_t`. If unspecified, these are automatically + generated using a pseudo-random number generator. If specified, + must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the + same as in the state space model. + initial_state : array_like, optional + If specified, this is the initial state vector to use in + simulation, which should be shaped (`k_states` x 1), where + `k_states` is the same as in the state space model. If unspecified, + but the model has been initialized, then that initialization is + used. This must be specified if `anchor` is anything other than + "start" or 0 (or else you can use the `simulate` method on a + results object rather than on the model object). + anchor : int, str, or datetime, optional + First period for simulation. The simulation will be conditional on + all existing datapoints prior to the `anchor`. Type depends on the + index of the given `endog` in the model. Two special cases are the + strings 'start' and 'end'. `start` refers to beginning the + simulation at the first period of the sample, and `end` refers to + beginning the simulation at the first period after the sample. + Integer values can run from 0 to `nobs`, or can be negative to + apply negative indexing. Finally, if a date/time index was provided + to the model, then this argument can be a date string to parse or a + datetime type. Default is 'start'. + repetitions : int, optional + Number of simulated paths to generate. Default is 1 simulated path. + exog : array_like, optional + New observations of exogenous regressors, if applicable. + extend_model : bool, optional + Whether or not to extend the model to accommodate simulating + periods outside of the sample. Default is to extend the model if + a new `exog` array is provided or if the model is time-varying. + extend_kwargs : dict, optional + Dictionary of keyword arguments to pass to the state space model + constructor. For example, for an SARIMAX state space model, this + could be used to pass the `concentrate_scale=True` keyword + argument during extension. + transformed : bool, optional + Whether or not `params` is already transformed. Default is + True. + includes_fixed : bool, optional + If parameters were previously fixed with the `fix_params` method, + this argument describes whether or not `params` also includes + the fixed parameters, in addition to the free parameters. Default + is False. + original_scale : bool, optional + If the model specification standardized the data, whether or not + to return simulations in the original scale of the data (i.e. + before it was standardized by the model). Default is True. + + Returns + ------- + simulated_obs : ndarray + An array of simulated observations. If `repetitions=None`, then it + will be shaped (nsimulations x k_endog) or (nsimulations,) if + `k_endog=1`. Otherwise it will be shaped + (nsimulations x k_endog x repetitions). If the model was given + Pandas input then the output will be a Pandas object. If + `k_endog > 1` and `repetitions` is not None, then the output will + be a Pandas DataFrame that has a MultiIndex for the columns, with + the first level containing the names of the `endog` variables and + the second level containing the repetition number. + """ + # Get usual simulations (in the possibly-standardized scale) + sim = super().simulate( + params, nsimulations, measurement_shocks=measurement_shocks, + state_shocks=state_shocks, initial_state=initial_state, + anchor=anchor, repetitions=repetitions, exog=exog, + extend_model=extend_model, extend_kwargs=extend_kwargs, + transformed=transformed, includes_fixed=includes_fixed, **kwargs) + + # If applicable, convert predictions back to original space + if self.standardize and original_scale: + use_pandas = isinstance(self.data, PandasData) + shape = sim.shape + + if use_pandas: + # pd.Series (k_endog=1, replications=None) + if len(shape) == 1: + std = self._endog_std.iloc[0] + mean = self._endog_mean.iloc[0] + sim = sim * std + mean + # pd.DataFrame (k_endog > 1, replications=None) + # [or] + # pd.DataFrame with MultiIndex (replications > 0) + elif len(shape) == 2: + sim = (sim.multiply(self._endog_std, axis=1, level=0) + .add(self._endog_mean, axis=1, level=0)) + # 1-dim array (k_endog=1, replications=None) + elif len(shape) == 1 or len(shape) == 2: + sim = sim * self._endog_std + self._endog_mean + # 3-dim array with MultiIndex (replications > 0) + else: + # Get arrays into the form that can be used for + # broadcasting + std = np.atleast_2d(self._endog_std)[..., None] + mean = np.atleast_2d(self._endog_mean)[..., None] + sim = sim * std + mean + + return sim + + def impulse_responses(self, params, steps=1, impulse=0, + orthogonalized=False, cumulative=False, anchor=None, + exog=None, extend_model=None, extend_kwargs=None, + transformed=True, includes_fixed=False, + original_scale=True, **kwargs): + """ + Impulse response function + + Parameters + ---------- + params : array_like + Array of model parameters. + steps : int, optional + The number of steps for which impulse responses are calculated. + Default is 1. Note that for time-invariant models, the initial + impulse is not counted as a step, so if `steps=1`, the output will + have 2 entries. + impulse : int or array_like, optional + If an integer, the state innovation to pulse; must be between 0 + and `k_posdef-1`. Alternatively, a custom impulse vector may be + provided; must be shaped `k_posdef x 1`. Default is 0. + orthogonalized : bool, optional + Whether or not to perform impulse using orthogonalized innovations. + Note that this will also affect custum `impulse` vectors. Default + is False. + cumulative : bool, optional + Whether or not to return cumulative impulse responses. Default is + False. + anchor : int, str, or datetime, optional + Time point within the sample for the state innovation impulse. Type + depends on the index of the given `endog` in the model. Two special + cases are the strings 'start' and 'end', which refer to setting the + impulse at the first and last points of the sample, respectively. + Integer values can run from 0 to `nobs - 1`, or can be negative to + apply negative indexing. Finally, if a date/time index was provided + to the model, then this argument can be a date string to parse or a + datetime type. Default is 'start'. + exog : array_like, optional + New observations of exogenous regressors for out-of-sample periods, + if applicable. + extend_model : bool, optional + Whether or not to extend the model to accommodate calculating + impulse responses in periods outside of the sample. Default is to + extend the model if a new `exog` array is provided or if the model + is time-varying. + extend_kwargs : dict, optional + Dictionary of keyword arguments to pass to the state space model + constructor. For example, for an SARIMAX state space model, this + could be used to pass the `concentrate_scale=True` keyword + argument during extension. + transformed : bool, optional + Whether or not `params` is already transformed. Default is + True. + includes_fixed : bool, optional + If parameters were previously fixed with the `fix_params` method, + this argument describes whether or not `params` also includes + the fixed parameters, in addition to the free parameters. Default + is False. + original_scale : bool, optional + If the model specification standardized the data, whether or not + to return impulse responses in the original scale of the data (i.e. + before it was standardized by the model). Default is True. + **kwargs + If the model has time-varying design or transition matrices and the + combination of `anchor` and `steps` implies creating impulse + responses for the out-of-sample period, then these matrices must + have updated values provided for the out-of-sample steps. For + example, if `design` is a time-varying component, `nobs` is 10, + `anchor=1`, and `steps` is 15, a (`k_endog` x `k_states` x 7) + matrix must be provided with the new design matrix values. + + Returns + ------- + impulse_responses : ndarray + Responses for each endogenous variable due to the impulse + given by the `impulse` argument. For a time-invariant model, the + impulse responses are given for `steps + 1` elements (this gives + the "initial impulse" followed by `steps` responses for the + important cases of VAR and SARIMAX models), while for time-varying + models the impulse responses are only given for `steps` elements + (to avoid having to unexpectedly provide updated time-varying + matrices). + + """ + # Get usual simulations (in the possibly-standardized scale) + irfs = super().impulse_responses( + params, steps=steps, impulse=impulse, + orthogonalized=orthogonalized, cumulative=cumulative, + anchor=anchor, exog=exog, extend_model=extend_model, + extend_kwargs=extend_kwargs, transformed=transformed, + includes_fixed=includes_fixed, **kwargs) + + # If applicable, convert predictions back to original space + if self.standardize and original_scale: + use_pandas = isinstance(self.data, PandasData) + shape = irfs.shape + + if use_pandas: + # pd.Series (k_endog=1, replications=None) + if len(shape) == 1: + irfs = irfs * self._endog_std.iloc[0] + # pd.DataFrame (k_endog > 1) + # [or] + # pd.DataFrame with MultiIndex (replications > 0) + elif len(shape) == 2: + irfs = irfs.multiply(self._endog_std, axis=1, level=0) + # 1-dim array (k_endog=1) + elif len(shape) == 1 or len(shape) == 2: + irfs = irfs * self._endog_std + + return irfs + + +class DynamicFactorMQResults(mlemodel.MLEResults): + """ + Results from fitting a dynamic factor model + """ + def __init__(self, model, params, filter_results, cov_type=None, **kwargs): + super().__init__( + model, params, filter_results, cov_type, **kwargs) + + @property + def factors(self): + """ + Estimates of unobserved factors + + Returns + ------- + out : Bunch + A bunch with the following attributes: + + - `filtered`: a time series array with the filtered estimate of + the component + - `filtered_cov`: a time series array with the filtered estimate + of the variance/covariance of the component + - `smoothed`: a time series array with the smoothed estimate of + the component + - `smoothed_cov`: a time series array with the smoothed estimate + of the variance/covariance of the component + - `offset`: an integer giving the offset in the state vector + where this component begins + """ + out = None + if self.model.k_factors > 0: + iloc = self.model._s.factors_L1 + ix = np.array(self.model.state_names)[iloc].tolist() + out = Bunch( + filtered=self.states.filtered.loc[:, ix], + filtered_cov=self.states.filtered_cov.loc[np.s_[ix, :], ix], + smoothed=None, smoothed_cov=None) + if self.smoothed_state is not None: + out.smoothed = self.states.smoothed.loc[:, ix] + if self.smoothed_state_cov is not None: + out.smoothed_cov = ( + self.states.smoothed_cov.loc[np.s_[ix, :], ix]) + return out + + def get_coefficients_of_determination(self, method="individual", + which=None): + """ + Get coefficients of determination (R-squared) for variables / factors + + Parameters + ---------- + method : {'individual', 'joint', 'cumulative'}, optional + The type of R-squared values to generate. "individual" plots + the R-squared of each variable on each factor; "joint" plots the + R-squared of each variable on each factor that it loads on; + "cumulative" plots the successive R-squared values as each + additional factor is added to the regression, for each variable. + Default is 'individual'. + which : {None, 'filtered', 'smoothed'}, optional + Whether to compute R-squared values based on filtered or smoothed + estimates of the factors. Default is 'smoothed' if smoothed results + are available and 'filtered' otherwise. + + Returns + ------- + rsquared : DataFrame or Series + The R-squared values from regressions of observed variables on + one or more of the factors. If method='individual' or + method='cumulative', this will be a Pandas DataFrame with observed + variables as the index and factors as the columns . If + method='joint', will be a Pandas Series with observed variables as + the index. + + See Also + -------- + plot_coefficients_of_determination + coefficients_of_determination + """ + from statsmodels.tools import add_constant + + method = string_like(method, "method", options=["individual", "joint", + "cumulative"]) + if which is None: + which = "filtered" if self.smoothed_state is None else "smoothed" + which = string_like(which, "which", options=("filtered", "smoothed")) + + k_endog = self.model.k_endog + k_factors = self.model.k_factors + ef_map = self.model._s.endog_factor_map + endog_names = self.model.endog_names + factor_names = self.model.factor_names + + if method == "individual": + coefficients = np.zeros((k_endog, k_factors)) + + for i in range(k_factors): + exog = add_constant(self.factors[which].iloc[:, i]) + for j in range(k_endog): + if ef_map.iloc[j, i]: + endog = self.filter_results.endog[j] + coefficients[j, i] = ( + OLS(endog, exog, missing="drop").fit().rsquared) + else: + coefficients[j, i] = np.nan + + coefficients = pd.DataFrame(coefficients, index=endog_names, + columns=factor_names) + elif method == "joint": + coefficients = np.zeros((k_endog,)) + exog = add_constant(self.factors[which]) + for j in range(k_endog): + endog = self.filter_results.endog[j] + ix = np.r_[True, ef_map.iloc[j]].tolist() + X = exog.loc[:, ix] + coefficients[j] = ( + OLS(endog, X, missing="drop").fit().rsquared) + coefficients = pd.Series(coefficients, index=endog_names) + elif method == "cumulative": + coefficients = np.zeros((k_endog, k_factors)) + exog = add_constant(self.factors[which]) + for j in range(k_endog): + endog = self.filter_results.endog[j] + + for i in range(k_factors): + if self.model._s.endog_factor_map.iloc[j, i]: + ix = np.r_[True, ef_map.iloc[j, :i + 1], + [False] * (k_factors - i - 1)] + X = exog.loc[:, ix.astype(bool).tolist()] + coefficients[j, i] = ( + OLS(endog, X, missing="drop").fit().rsquared) + else: + coefficients[j, i] = np.nan + coefficients = pd.DataFrame(coefficients, index=endog_names, + columns=factor_names) + + return coefficients + + @cache_readonly + def coefficients_of_determination(self): + """ + Individual coefficients of determination (:math:`R^2`) + + Coefficients of determination (:math:`R^2`) from regressions of + endogenous variables on individual estimated factors. + + Returns + ------- + coefficients_of_determination : ndarray + A `k_endog` x `k_factors` array, where + `coefficients_of_determination[i, j]` represents the :math:`R^2` + value from a regression of factor `j` and a constant on endogenous + variable `i`. + + See Also + -------- + get_coefficients_of_determination + plot_coefficients_of_determination + """ + return self.get_coefficients_of_determination(method="individual") + + def plot_coefficients_of_determination(self, method="individual", + which=None, endog_labels=None, + fig=None, figsize=None): + """ + Plot coefficients of determination (R-squared) for variables / factors + + Parameters + ---------- + method : {'individual', 'joint', 'cumulative'}, optional + The type of R-squared values to generate. "individual" plots + the R-squared of each variable on each factor; "joint" plots the + R-squared of each variable on each factor that it loads on; + "cumulative" plots the successive R-squared values as each + additional factor is added to the regression, for each variable. + Default is 'individual'. + which : {None, 'filtered', 'smoothed'}, optional + Whether to compute R-squared values based on filtered or smoothed + estimates of the factors. Default is 'smoothed' if smoothed results + are available and 'filtered' otherwise. + endog_labels : bool, optional + Whether or not to label the endogenous variables along the x-axis + of the plots. Default is to include labels if there are 5 or fewer + endogenous variables. + fig : Figure, optional + If given, subplots are created in this figure instead of in a new + figure. Note that the grid will be created in the provided + figure using `fig.add_subplot()`. + figsize : tuple, optional + If a figure is created, this argument allows specifying a size. + The tuple is (width, height). + + See Also + -------- + get_coefficients_of_determination + + Notes + ----- + The endogenous variables are arranged along the x-axis according to + their position in the model's `endog` array. + """ + from statsmodels.graphics.utils import _import_mpl, create_mpl_fig + _import_mpl() + fig = create_mpl_fig(fig, figsize) + + method = string_like(method, "method", options=["individual", "joint", + "cumulative"]) + + # Should we label endogenous variables? + if endog_labels is None: + endog_labels = self.model.k_endog <= 5 + + # Plot the coefficients of determination + rsquared = self.get_coefficients_of_determination(method=method, + which=which) + + if method in ["individual", "cumulative"]: + plot_idx = 1 + for factor_name, coeffs in rsquared.T.iterrows(): + # Create the new axis + ax = fig.add_subplot(self.model.k_factors, 1, plot_idx) + ax.set_ylim((0, 1)) + ax.set(title=f"{factor_name}", ylabel=r"$R^2$") + + coeffs.plot(ax=ax, kind="bar") + if plot_idx < len(rsquared.columns) or not endog_labels: + ax.xaxis.set_ticklabels([]) + + plot_idx += 1 + elif method == "joint": + ax = fig.add_subplot(1, 1, 1) + ax.set_ylim((0, 1)) + ax.set(title=r"$R^2$ - regression on all loaded factors", + ylabel=r"$R^2$") + rsquared.plot(ax=ax, kind="bar") + if not endog_labels: + ax.xaxis.set_ticklabels([]) + + return fig + + def get_prediction(self, start=None, end=None, dynamic=False, + information_set="predicted", signal_only=False, + original_scale=True, index=None, exog=None, + extend_model=None, extend_kwargs=None, **kwargs): + r""" + In-sample prediction and out-of-sample forecasting + + Parameters + ---------- + start : int, str, or datetime, optional + Zero-indexed observation number at which to start forecasting, + i.e., the first forecast is start. Can also be a date string to + parse or a datetime type. Default is the zeroth observation. + end : int, str, or datetime, optional + Zero-indexed observation number at which to end forecasting, i.e., + the last forecast is end. Can also be a date string to + parse or a datetime type. However, if the dates index does not + have a fixed frequency, end must be an integer index if you + want out of sample prediction. Default is the last observation in + the sample. + dynamic : bool, int, str, or datetime, optional + Integer offset relative to `start` at which to begin dynamic + prediction. Can also be an absolute date string to parse or a + datetime type (these are not interpreted as offsets). + Prior to this observation, true endogenous values will be used for + prediction; starting with this observation and continuing through + the end of prediction, forecasted endogenous values will be used + instead. + information_set : str, optional + The information set to condition each prediction on. Default is + "predicted", which computes predictions of period t values + conditional on observed data through period t-1; these are + one-step-ahead predictions, and correspond with the typical + `fittedvalues` results attribute. Alternatives are "filtered", + which computes predictions of period t values conditional on + observed data through period t, and "smoothed", which computes + predictions of period t values conditional on the entire dataset + (including also future observations t+1, t+2, ...). + signal_only : bool, optional + Whether to compute forecasts of only the "signal" component of + the observation equation. Default is False. For example, the + observation equation of a time-invariant model is + :math:`y_t = d + Z \alpha_t + \varepsilon_t`, and the "signal" + component is then :math:`Z \alpha_t`. If this argument is set to + True, then forecasts of the "signal" :math:`Z \alpha_t` will be + returned. Otherwise, the default is for forecasts of :math:`y_t` + to be returned. + original_scale : bool, optional + If the model specification standardized the data, whether or not + to return predictions in the original scale of the data (i.e. + before it was standardized by the model). Default is True. + index : array_like, optional + Optional index to use for the new results object. + exog : array_like, optional + New observations of exogenous regressors, if applicable. + extend_model : bool, optional + Whether or not to extend the model to accommodate out-of-sample + forecasting. Default is to extend the model if a new `exog` array + is provided or if the model is time-varying. + extend_kwargs : dict, optional + Dictionary of keyword arguments to pass to the state space model + constructor. For example, for an SARIMAX state space model, this + could be used to pass the `concentrate_scale=True` keyword + argument. Any arguments that are not explicitly set in this + dictionary will be copied from the current model instance. + **kwargs + Additional arguments may required for forecasting beyond the end + of the sample. See `FilterResults.predict` for more details. + + Returns + ------- + forecast : ndarray + Array of out of in-sample predictions and / or out-of-sample + forecasts. An (npredict x k_endog) array. + """ + # Get usual predictions (in the possibly-standardized scale) + res = super().get_prediction(start=start, end=end, dynamic=dynamic, + information_set=information_set, + signal_only=signal_only, + index=index, exog=exog, + extend_model=extend_model, + extend_kwargs=extend_kwargs, **kwargs) + + # If applicable, convert predictions back to original space + if self.model.standardize and original_scale: + prediction_results = res.prediction_results + k_endog, _ = prediction_results.endog.shape + + mean = np.array(self.model._endog_mean) + std = np.array(self.model._endog_std) + + if self.model.k_endog > 1: + mean = mean[None, :] + std = std[None, :] + + res._results._predicted_mean = ( + res._results._predicted_mean * std + mean) + + if k_endog == 1: + res._results._var_pred_mean *= std**2 + else: + res._results._var_pred_mean = ( + std * res._results._var_pred_mean * std.T) + + return res + + def news(self, comparison, impact_date=None, impacted_variable=None, + start=None, end=None, periods=None, exog=None, + comparison_type=None, revisions_details_start=False, + state_index=None, return_raw=False, tolerance=1e-10, + endog_quarterly=None, original_scale=True, **kwargs): + """ + Compute impacts from updated data (news and revisions) + + Parameters + ---------- + comparison : array_like or MLEResults + An updated dataset with updated and/or revised data from which the + news can be computed, or an updated or previous results object + to use in computing the news. + impact_date : int, str, or datetime, optional + A single specific period of impacts from news and revisions to + compute. Can also be a date string to parse or a datetime type. + This argument cannot be used in combination with `start`, `end`, or + `periods`. Default is the first out-of-sample observation. + impacted_variable : str, list, array, or slice, optional + Observation variable label or slice of labels specifying that only + specific impacted variables should be shown in the News output. The + impacted variable(s) describe the variables that were *affected* by + the news. If you do not know the labels for the variables, check + the `endog_names` attribute of the model instance. + start : int, str, or datetime, optional + The first period of impacts from news and revisions to compute. + Can also be a date string to parse or a datetime type. Default is + the first out-of-sample observation. + end : int, str, or datetime, optional + The last period of impacts from news and revisions to compute. + Can also be a date string to parse or a datetime type. Default is + the first out-of-sample observation. + periods : int, optional + The number of periods of impacts from news and revisions to + compute. + exog : array_like, optional + Array of exogenous regressors for the out-of-sample period, if + applicable. + comparison_type : {None, 'previous', 'updated'}, optional + This denotes whether the `comparison` argument represents a + *previous* results object or dataset or an *updated* results object + or dataset. If not specified, then an attempt is made to determine + the comparison type. + revisions_details_start : bool, int, str, or datetime, optional + The period at which to begin computing the detailed impacts of + data revisions. Any revisions prior to this period will have their + impacts grouped together. If a negative integer, interpreted as + an offset from the end of the dataset. If set to True, detailed + impacts are computed for all revisions, while if set to False, all + revisions are grouped together. Default is False. + state_index : array_like or "common", optional + An optional index specifying a subset of states to use when + constructing the impacts of revisions and news. For example, if + `state_index=[0, 1]` is passed, then only the impacts to the + observed variables arising from the impacts to the first two + states will be returned. If the string "common" is passed and the + model includes idiosyncratic AR(1) components, news will only be + computed based on the common states. Default is to use all states. + return_raw : bool, optional + Whether or not to return only the specific output or a full + results object. Default is to return a full results object. + tolerance : float, optional + The numerical threshold for determining zero impact. Default is + that any impact less than 1e-10 is assumed to be zero. + endog_quarterly : array_like, optional + New observations of quarterly variables, if `comparison` was + provided as an updated monthly dataset. If this argument is + provided, it must be a Pandas Series or DataFrame with a + DatetimeIndex or PeriodIndex at the quarterly frequency. + original_scale : bool, optional + If the model specification standardized the data, whether or not + to return impacts in the original scale of the data (i.e., before + it was standardized by the model). Default is True. + **kwargs + Keyword arguments to pass to the base `news` method, and/or to + construct `comparison` if it is not already a results object. + + References + ---------- + .. [1] Bańbura, Marta, and Michele Modugno. + "Maximum likelihood estimation of factor models on datasets with + arbitrary pattern of missing data." + Journal of Applied Econometrics 29, no. 1 (2014): 133-160. + .. [2] Bańbura, Marta, Domenico Giannone, and Lucrezia Reichlin. + "Nowcasting." + The Oxford Handbook of Economic Forecasting. July 8, 2011. + .. [3] Bańbura, Marta, Domenico Giannone, Michele Modugno, and Lucrezia + Reichlin. + "Now-casting and the real-time data flow." + In Handbook of economic forecasting, vol. 2, pp. 195-237. + Elsevier, 2013. + """ + if state_index == "common": + state_index = ( + np.arange(self.model.k_states - self.model.k_endog)) + + news_results = super().news( + comparison, impact_date=impact_date, + impacted_variable=impacted_variable, start=start, end=end, + periods=periods, exog=exog, comparison_type=comparison_type, + revisions_details_start=revisions_details_start, + state_index=state_index, return_raw=return_raw, + tolerance=tolerance, endog_quarterly=endog_quarterly, **kwargs) + + # If we have standardized the data, we may want to report the news in + # the original scale. If so, we need to modify the data to "undo" the + # standardization. + if not return_raw and self.model.standardize and original_scale: + endog_mean = self.model._endog_mean + endog_std = self.model._endog_std + + # Don't need to add in the mean for the impacts, since they are + # the difference of two forecasts + news_results.total_impacts = ( + news_results.total_impacts * endog_std) + news_results.update_impacts = ( + news_results.update_impacts * endog_std) + if news_results.revision_impacts is not None: + news_results.revision_impacts = ( + news_results.revision_impacts * endog_std) + if news_results.revision_detailed_impacts is not None: + news_results.revision_detailed_impacts = ( + news_results.revision_detailed_impacts * endog_std) + if news_results.revision_grouped_impacts is not None: + news_results.revision_grouped_impacts = ( + news_results.revision_grouped_impacts * endog_std) + + # Update forecasts + for name in ["prev_impacted_forecasts", "news", "revisions", + "update_realized", "update_forecasts", + "revised", "revised_prev", "post_impacted_forecasts", + "revisions_all", "revised_all", "revised_prev_all"]: + dta = getattr(news_results, name) + + # for pd.Series, dta.multiply(...) and (sometimes) dta.add(...) + # remove the name attribute; save it now so that we can add it + # back in + orig_name = None + if hasattr(dta, "name"): + orig_name = dta.name + + dta = dta.multiply(endog_std, level=1) + + if name not in ["news", "revisions"]: + dta = dta.add(endog_mean, level=1) + + # add back in the name attribute if it was removed + if orig_name is not None: + dta.name = orig_name + + setattr(news_results, name, dta) + + # For the weights: rows correspond to update (date, variable) and + # columns correspond to the impacted variable. + # 1. Because we have modified the updates (realized, forecasts, and + # forecast errors) to be in the scale of the original updated + # variable, we need to essentially reverse that change for each + # row of the weights by dividing by the standard deviation of + # that row's updated variable + # 2. Because we want the impacts to be in the scale of the original + # impacted variable, we need to multiply each column by the + # standard deviation of that column's impacted variable + news_results.weights = ( + news_results.weights.divide(endog_std, axis=0, level=1) + .multiply(endog_std, axis=1, level=1)) + news_results.revision_weights = ( + news_results.revision_weights + .divide(endog_std, axis=0, level=1) + .multiply(endog_std, axis=1, level=1)) + + return news_results + + def get_smoothed_decomposition(self, decomposition_of="smoothed_state", + state_index=None, original_scale=True): + r""" + Decompose smoothed output into contributions from observations + + Parameters + ---------- + decomposition_of : {"smoothed_state", "smoothed_signal"}, optional + The object to perform a decomposition of. If it is set to + "smoothed_state", then the elements of the smoothed state vector + are decomposed into the contributions of each observation. If it + is set to "smoothed_signal", then the predictions of the + observation vector based on the smoothed state vector are + decomposed. Default is "smoothed_state". + state_index : array_like, optional + An optional index specifying a subset of states to use when + constructing the decomposition of the "smoothed_signal". For + example, if `state_index=[0, 1]` is passed, then only the + contributions of observed variables to the smoothed signal arising + from the first two states will be returned. Note that if not all + states are used, the contributions will not sum to the smoothed + signal. Default is to use all states. + original_scale : bool, optional + If the model specification standardized the data, whether or not + to return simulations in the original scale of the data (i.e. + before it was standardized by the model). Default is True. + + Returns + ------- + data_contributions : DataFrame + Contributions of observations to the decomposed object. If the + smoothed state is being decomposed, then `data_contributions` is + shaped `(k_states x nobs, k_endog x nobs)` with a `pd.MultiIndex` + index corresponding to `state_to x date_to` and `pd.MultiIndex` + columns corresponding to `variable_from x date_from`. If the + smoothed signal is being decomposed, then `data_contributions` is + shaped `(k_endog x nobs, k_endog x nobs)` with `pd.MultiIndex`-es + corresponding to `variable_to x date_to` and + `variable_from x date_from`. + obs_intercept_contributions : DataFrame + Contributions of the observation intercept to the decomposed + object. If the smoothed state is being decomposed, then + `obs_intercept_contributions` is + shaped `(k_states x nobs, k_endog x nobs)` with a `pd.MultiIndex` + index corresponding to `state_to x date_to` and `pd.MultiIndex` + columns corresponding to `obs_intercept_from x date_from`. If the + smoothed signal is being decomposed, then + `obs_intercept_contributions` is shaped + `(k_endog x nobs, k_endog x nobs)` with `pd.MultiIndex`-es + corresponding to `variable_to x date_to` and + `obs_intercept_from x date_from`. + state_intercept_contributions : DataFrame + Contributions of the state intercept to the decomposed + object. If the smoothed state is being decomposed, then + `state_intercept_contributions` is + shaped `(k_states x nobs, k_states x nobs)` with a `pd.MultiIndex` + index corresponding to `state_to x date_to` and `pd.MultiIndex` + columns corresponding to `state_intercept_from x date_from`. If the + smoothed signal is being decomposed, then + `state_intercept_contributions` is shaped + `(k_endog x nobs, k_states x nobs)` with `pd.MultiIndex`-es + corresponding to `variable_to x date_to` and + `state_intercept_from x date_from`. + prior_contributions : DataFrame + Contributions of the prior to the decomposed object. If the + smoothed state is being decomposed, then `prior_contributions` is + shaped `(nobs x k_states, k_states)`, with a `pd.MultiIndex` + index corresponding to `state_to x date_to` and columns + corresponding to elements of the prior mean (aka "initial state"). + If the smoothed signal is being decomposed, then + `prior_contributions` is shaped `(nobs x k_endog, k_states)`, + with a `pd.MultiIndex` index corresponding to + `variable_to x date_to` and columns corresponding to elements of + the prior mean. + + Notes + ----- + Denote the smoothed state at time :math:`t` by :math:`\alpha_t`. Then + the smoothed signal is :math:`Z_t \alpha_t`, where :math:`Z_t` is the + design matrix operative at time :math:`t`. + """ + # De-meaning the data is like putting the mean into the observation + # intercept. To compute the decomposition correctly in the original + # scale, we need to account for this, so we fill in the observation + # intercept temporarily + if self.model.standardize and original_scale: + cache_obs_intercept = self.model["obs_intercept"] + self.model["obs_intercept"] = self.model._endog_mean + + # Compute the contributions + (data_contributions, obs_intercept_contributions, + state_intercept_contributions, prior_contributions) = ( + super().get_smoothed_decomposition( + decomposition_of=decomposition_of, state_index=state_index)) + + # Replace the original observation intercept + if self.model.standardize and original_scale: + self.model["obs_intercept"] = cache_obs_intercept + + # Reverse the effect of dividing by the standard deviation + if (decomposition_of == "smoothed_signal" + and self.model.standardize and original_scale): + endog_std = self.model._endog_std + + data_contributions = ( + data_contributions.multiply(endog_std, axis=0, level=0)) + obs_intercept_contributions = ( + obs_intercept_contributions.multiply( + endog_std, axis=0, level=0)) + state_intercept_contributions = ( + state_intercept_contributions.multiply( + endog_std, axis=0, level=0)) + prior_contributions = ( + prior_contributions.multiply(endog_std, axis=0, level=0)) + + return (data_contributions, obs_intercept_contributions, + state_intercept_contributions, prior_contributions) + + def append(self, endog, endog_quarterly=None, refit=False, fit_kwargs=None, + copy_initialization=True, retain_standardization=True, + **kwargs): + """ + Recreate the results object with new data appended to original data + + Creates a new result object applied to a dataset that is created by + appending new data to the end of the model's original data. The new + results can then be used for analysis or forecasting. + + Parameters + ---------- + endog : array_like + New observations from the modeled time-series process. + endog_quarterly : array_like, optional + New observations of quarterly variables. If provided, must be a + Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at + the quarterly frequency. + refit : bool, optional + Whether to re-fit the parameters, based on the combined dataset. + Default is False (so parameters from the current results object + are used to create the new results object). + fit_kwargs : dict, optional + Keyword arguments to pass to `fit` (if `refit=True`) or `filter` / + `smooth`. + copy_initialization : bool, optional + Whether or not to copy the initialization from the current results + set to the new model. Default is True. + retain_standardization : bool, optional + Whether or not to use the mean and standard deviations that were + used to standardize the data in the current model in the new model. + Default is True. + **kwargs + Keyword arguments may be used to modify model specification + arguments when creating the new model object. + + Returns + ------- + results + Updated Results object, that includes results from both the + original dataset and the new dataset. + + See Also + -------- + extend + apply + + Notes + ----- + The `endog` and `exog` arguments to this method must be formatted in + the same way (e.g., Pandas Series versus Numpy array) as were the + `endog` and `exog` arrays passed to the original model. + + The `endog` (and, if applicable, `endog_quarterly`) arguments to this + method should consist of new observations that occurred directly after + the last element of `endog`. For any other kind of dataset, see the + `apply` method. + + This method will apply filtering to all of the original data as well + as to the new data. To apply filtering only to the new data (which + can be much faster if the original dataset is large), see the `extend` + method. + """ + # Construct the combined dataset, if necessary + endog, k_endog_monthly = DynamicFactorMQ.construct_endog( + endog, endog_quarterly) + + # Check for compatible dimensions + k_endog = endog.shape[1] if len(endog.shape) == 2 else 1 + if (k_endog_monthly != self.model.k_endog_M or + k_endog != self.model.k_endog): + raise ValueError("Cannot append data of a different dimension to" + " a model.") + + kwargs["k_endog_monthly"] = k_endog_monthly + + return super().append( + endog, refit=refit, fit_kwargs=fit_kwargs, + copy_initialization=copy_initialization, + retain_standardization=retain_standardization, **kwargs) + + def extend(self, endog, endog_quarterly=None, fit_kwargs=None, + retain_standardization=True, **kwargs): + """ + Recreate the results object for new data that extends original data + + Creates a new result object applied to a new dataset that is assumed to + follow directly from the end of the model's original data. The new + results can then be used for analysis or forecasting. + + Parameters + ---------- + endog : array_like + New observations from the modeled time-series process. + endog_quarterly : array_like, optional + New observations of quarterly variables. If provided, must be a + Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at + the quarterly frequency. + fit_kwargs : dict, optional + Keyword arguments to pass to `filter` or `smooth`. + retain_standardization : bool, optional + Whether or not to use the mean and standard deviations that were + used to standardize the data in the current model in the new model. + Default is True. + **kwargs + Keyword arguments may be used to modify model specification + arguments when creating the new model object. + + Returns + ------- + results + Updated Results object, that includes results only for the new + dataset. + + See Also + -------- + append + apply + + Notes + ----- + The `endog` argument to this method should consist of new observations + that occurred directly after the last element of the model's original + `endog` array. For any other kind of dataset, see the `apply` method. + + This method will apply filtering only to the new data provided by the + `endog` argument, which can be much faster than re-filtering the entire + dataset. However, the returned results object will only have results + for the new data. To retrieve results for both the new data and the + original data, see the `append` method. + """ + # Construct the combined dataset, if necessary + endog, k_endog_monthly = DynamicFactorMQ.construct_endog( + endog, endog_quarterly) + + # Check for compatible dimensions + k_endog = endog.shape[1] if len(endog.shape) == 2 else 1 + if (k_endog_monthly != self.model.k_endog_M or + k_endog != self.model.k_endog): + raise ValueError("Cannot append data of a different dimension to" + " a model.") + + kwargs["k_endog_monthly"] = k_endog_monthly + return super().extend( + endog, fit_kwargs=fit_kwargs, + retain_standardization=retain_standardization, **kwargs) + + def apply(self, endog, k_endog_monthly=None, endog_quarterly=None, + refit=False, fit_kwargs=None, copy_initialization=False, + retain_standardization=True, **kwargs): + """ + Apply the fitted parameters to new data unrelated to the original data + + Creates a new result object using the current fitted parameters, + applied to a completely new dataset that is assumed to be unrelated to + the model's original data. The new results can then be used for + analysis or forecasting. + + Parameters + ---------- + endog : array_like + New observations from the modeled time-series process. + k_endog_monthly : int, optional + If specifying a monthly/quarterly mixed frequency model in which + the provided `endog` dataset contains both the monthly and + quarterly data, this variable should be used to indicate how many + of the variables are monthly. + endog_quarterly : array_like, optional + New observations of quarterly variables. If provided, must be a + Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at + the quarterly frequency. + refit : bool, optional + Whether to re-fit the parameters, using the new dataset. + Default is False (so parameters from the current results object + are used to create the new results object). + fit_kwargs : dict, optional + Keyword arguments to pass to `fit` (if `refit=True`) or `filter` / + `smooth`. + copy_initialization : bool, optional + Whether or not to copy the initialization from the current results + set to the new model. Default is False. + retain_standardization : bool, optional + Whether or not to use the mean and standard deviations that were + used to standardize the data in the current model in the new model. + Default is True. + **kwargs + Keyword arguments may be used to modify model specification + arguments when creating the new model object. + + Returns + ------- + results + Updated Results object, that includes results only for the new + dataset. + + See Also + -------- + statsmodels.tsa.statespace.mlemodel.MLEResults.append + statsmodels.tsa.statespace.mlemodel.MLEResults.apply + + Notes + ----- + The `endog` argument to this method should consist of new observations + that are not necessarily related to the original model's `endog` + dataset. For observations that continue that original dataset by follow + directly after its last element, see the `append` and `extend` methods. + """ + mod = self.model.clone(endog, k_endog_monthly=k_endog_monthly, + endog_quarterly=endog_quarterly, + retain_standardization=retain_standardization, + **kwargs) + if copy_initialization: + init = initialization.Initialization.from_results( + self.filter_results) + mod.ssm.initialization = init + + res = self._apply(mod, refit=refit, fit_kwargs=fit_kwargs) + + return res + + def summary(self, alpha=.05, start=None, title=None, model_name=None, + display_params=True, display_diagnostics=False, + display_params_as_list=False, truncate_endog_names=None, + display_max_endog=3): + """ + Summarize the Model + + Parameters + ---------- + alpha : float, optional + Significance level for the confidence intervals. Default is 0.05. + start : int, optional + Integer of the start observation. Default is 0. + title : str, optional + The title used for the summary table. + model_name : str, optional + The name of the model used. Default is to use model class name. + display_params : bool, optional + Whether or not to display the estimated parameters. Default is + True. + display_diagnostics : bool, optional + Whether or not to display the standard set of diagnostic tests. + Default is False. + display_params_as_list : bool, optional + Whether or not to display the estimated parameters in a single + list, rather than in the model-specific tables of factor loadings + and factor transitions. Default is False. + truncate_endog_names : int, optional + The number of characters to show for names of observed variables. + Default is 24 if there is more than one observed variable, or + an unlimited number if there is only one. + display_max_endog : int, optional + The maximum number of endogenous variables to display when using + the model-specific tables. Default is 3. + + Returns + ------- + summary : Summary instance + This holds the summary table and text, which can be printed or + converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary.Summary + """ + mod = self.model + + # Default title / model name + if title is None: + title = "Dynamic Factor Results" + if model_name is None: + model_name = self.model._model_name + + # Get endog names + endog_names = self.model._get_endog_names( + truncate=truncate_endog_names) + + # Get extra elements for top summary table + extra_top_left = None + extra_top_right = [] + mle_retvals = getattr(self, "mle_retvals", None) + mle_settings = getattr(self, "mle_settings", None) + if mle_settings is not None and mle_settings.method == "em": + extra_top_right += [("EM Iterations", [f"{mle_retvals.iter}"])] + + # Get the basic summary tables + summary = super().summary( + alpha=alpha, start=start, title=title, model_name=model_name, + display_params=(display_params and display_params_as_list), + display_diagnostics=display_diagnostics, + truncate_endog_names=truncate_endog_names, + display_max_endog=display_max_endog, + extra_top_left=extra_top_left, extra_top_right=extra_top_right) + + # Get tables of parameters + table_ix = 1 + if not display_params_as_list: + + # Observation equation table + design = self._summary_cache( + "design", + lambda: self.filter_results.design[:, mod._s["factors_L1"], 0] + ) + data = pd.DataFrame(design, index=endog_names, columns=mod.factor_names) + try: + data = data.map(lambda s: f"{s:.2f}") + except AttributeError: + data = data.applymap(lambda s: f"{s:.2f}") + + # Idiosyncratic terms + # data[' '] = ' ' + k_idio = 1 + if mod.idiosyncratic_ar1: + data[" idiosyncratic: AR(1)"] = ( + self.params[mod._p["idiosyncratic_ar1"]]) + k_idio += 1 + data["var."] = self.params[mod._p["idiosyncratic_var"]] + # Ensure object dtype for string assignment + cols_to_cast = data.columns[-k_idio:] + data[cols_to_cast] = data[cols_to_cast].astype(object) + try: + data.iloc[:, -k_idio:] = data.iloc[:, -k_idio:].map( + lambda s: f"{s:.2f}") + except AttributeError: + data.iloc[:, -k_idio:] = data.iloc[:, -k_idio:].applymap( + lambda s: f"{s:.2f}") + + data.index.name = "Factor loadings:" + + # Clear entries for non-loading factors + base_iloc = np.arange(mod.k_factors) + for i in range(mod.k_endog): + iloc = [j for j in base_iloc + if j not in mod._s.endog_factor_iloc[i]] + data.iloc[i, iloc] = "." + + data = data.reset_index() + + # Build the table + params_data = data.values + params_header = data.columns.tolist() + params_stubs = None + + title = "Observation equation:" + table = SimpleTable( + params_data, params_header, params_stubs, + txt_fmt=fmt_params, title=title) + summary.tables.insert(table_ix, table) + table_ix += 1 + + # Factor transitions + ix1 = 0 + ix2 = 0 + + # Both T and Q are looped over and so must be retained + # to ensure that summary works after remove data + T = self._summary_cache( + "transition", lambda: self.filter_results.transition + ) + Q = self._summary_cache( + "state_cov", lambda: self.filter_results.state_cov + ) + for i in range(len(mod._s.factor_blocks)): + block = mod._s.factor_blocks[i] + ix2 += block.k_factors + lag_names = [] + for j in range(block.factor_order): + lag_names += [f"L{j + 1}.{name}" + for name in block.factor_names] + data = pd.DataFrame( + T[block.factors_L1, block.factors_ar, 0], + index=block.factor_names, + columns=lag_names + ) + data.index.name = "" + try: + data = data.map(lambda s: f"{s:.2f}") + except AttributeError: + data = data.applymap(lambda s: f"{s:.2f}") + + if block.k_factors == 1: + data[" error variance"] = Q[ix1, ix1] + else: + data[" error covariance"] = block.factor_names + for j in range(block.k_factors): + data[block.factor_names[j]] = Q[ix1:ix2, ix1 + j] + cols_to_cast = data.columns[-block.k_factors:] + data[cols_to_cast] = data[cols_to_cast].astype(object) + try: + formatted_vals = data.iloc[:, -block.k_factors:].map( + lambda s: f"{s:.2f}" + ) + except AttributeError: + formatted_vals = data.iloc[:, -block.k_factors:].applymap( + lambda s: f"{s:.2f}" + ) + data.iloc[:, -block.k_factors:] = formatted_vals + + data = data.reset_index() + + params_data = data.values + params_header = data.columns.tolist() + params_stubs = None + + title = f"Transition: Factor block {i}" + table = SimpleTable( + params_data, params_header, params_stubs, + txt_fmt=fmt_params, title=title) + summary.tables.insert(table_ix, table) + table_ix += 1 + + ix1 = ix2 + + return summary diff --git a/shared/package-files/02/02d906829515a8f1ecf59f139b4ef26f6ccdff03ad6f672f95ffb9c450647389/platform.h b/shared/package-files/02/02d906829515a8f1ecf59f139b4ef26f6ccdff03ad6f672f95ffb9c450647389/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..04fb9fb8089944ea41b3ef5bfb3addaac710f39e --- /dev/null +++ b/shared/package-files/02/02d906829515a8f1ecf59f139b4ef26f6ccdff03ad6f672f95ffb9c450647389/platform.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. + +// Functions for converting between pandas's NumPy-based data representation +// and Arrow data structures + +#pragma once + +// If PY_SSIZE_T_CLEAN is defined, argument parsing functions treat #-specifier +// to mean Py_ssize_t (defining this to suppress deprecation warning) +#define PY_SSIZE_T_CLEAN + +#include // IWYU pragma: export +#include + +// Work around C2528 error +#ifdef _MSC_VER +# if _MSC_VER >= 1900 +# undef timezone +# endif +#endif diff --git a/shared/package-files/02/02d9077ed27786e7eeb92959851c51d111fd22eade11eb77f3bae99f5877f175/linalg.py b/shared/package-files/02/02d9077ed27786e7eeb92959851c51d111fd22eade11eb77f3bae99f5877f175/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..0825386ed5dc3418d06b3bbe04e7ddac5945ed82 --- /dev/null +++ b/shared/package-files/02/02d9077ed27786e7eeb92959851c51d111fd22eade11eb77f3bae99f5877f175/linalg.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from typing import Literal + +import dask.array as da + +# The `matmul` and `tensordot` functions are in both the main and linalg namespaces +from dask.array import matmul, outer, tensordot + +# Exports +from dask.array.linalg import * # noqa: F403 + +from ..._internal import get_xp +from ...common import _linalg +from ...common._typing import Array as _Array +from ._aliases import matrix_transpose, vecdot + +# dask.array.linalg doesn't have __all__. If it is added, replace this with +# +# from dask.array.linalg import __all__ as linalg_all +_n = {} +exec('from dask.array.linalg import *', _n) +for k in ('__builtins__', 'annotations', 'operator', 'warnings', 'Array'): + _n.pop(k, None) +linalg_all = list(_n) +del _n, k + +EighResult = _linalg.EighResult +QRResult = _linalg.QRResult +SlogdetResult = _linalg.SlogdetResult +SVDResult = _linalg.SVDResult +# TODO: use the QR wrapper once dask +# supports the mode keyword on QR +# https://github.com/dask/dask/issues/10388 +#qr = get_xp(da)(_linalg.qr) +def qr( + x: _Array, + mode: Literal["reduced", "complete"] = "reduced", + **kwargs: object, +) -> QRResult: + if mode != "reduced": + raise ValueError("dask arrays only support using mode='reduced'") + return QRResult(*da.linalg.qr(x, **kwargs)) +trace = get_xp(da)(_linalg.trace) +cholesky = get_xp(da)(_linalg.cholesky) +matrix_rank = get_xp(da)(_linalg.matrix_rank) +matrix_norm = get_xp(da)(_linalg.matrix_norm) + + +# Wrap the svd functions to not pass full_matrices to dask +# when full_matrices=False (as that is the default behavior for dask), +# and dask doesn't have the full_matrices keyword +def svd(x: _Array, full_matrices: bool = True, **kwargs) -> SVDResult: + if full_matrices: + raise ValueError("full_matrics=True is not supported by dask.") + return da.linalg.svd(x, coerce_signs=False, **kwargs) + +def svdvals(x: _Array) -> _Array: + # TODO: can't avoid computing U or V for dask + _, s, _ = svd(x) + return s + +vector_norm = get_xp(da)(_linalg.vector_norm) +diagonal = get_xp(da)(_linalg.diagonal) + +__all__ = linalg_all + ["trace", "outer", "matmul", "tensordot", + "matrix_transpose", "vecdot", "EighResult", + "QRResult", "SlogdetResult", "SVDResult", "qr", + "cholesky", "matrix_rank", "matrix_norm", "svdvals", + "vector_norm", "diagonal"] + +_all_ignore = ['get_xp', 'da', 'linalg_all', 'warnings'] diff --git a/shared/package-files/02/02de14255de2c629129d261b3e736a4d591c91995849a406f28d9beff373509c/calculus.py b/shared/package-files/02/02de14255de2c629129d261b3e736a4d591c91995849a406f28d9beff373509c/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..b245c2d3444c60be2b725866c184c1662d3bd144 --- /dev/null +++ b/shared/package-files/02/02de14255de2c629129d261b3e736a4d591c91995849a406f28d9beff373509c/calculus.py @@ -0,0 +1,115 @@ +from collections.abc import Iterable +from typing import cast + +from formulaic.parser.types import Factor, Term +from formulaic.parser.types.ordered_set import OrderedSet + + +def differentiate_term( + term: Term, + wrt: Iterable[str], # pylint: disable=redefined-builtin + use_sympy: bool = False, +) -> Term: + """ + Symbolically differentiate a `Term` instance with respect to one or more `wrt`. + + Args: + term: The `Term` instance to differentiate. + wrt: The variables by which to differentiate. + use_sympy: Whether to interpret factor token strings using sympy. If + `True`, symbolic factors like `log(x)` can be differentiated with + respect to `x`. If `False`, factor token strings must match the + variable exactly in order to be detected. + + Returns: + A new `Term` instance representing the differentiated term. + + Notes: + - This method takes into account the chain rule/etc. + - Care must be taken to make sure that the symbolic representation of + the factors can be properly interpreted by `sympy`. For example, `I(x)` + would not be understood. + """ + factors = OrderedSet(term.factors) + + for var in wrt: + affected_factors = set( + factor + for factor in factors + if var in _factor_symbols(factor, use_sympy=use_sympy) + ) + if not affected_factors: + return Term({Factor("0", eval_method="literal")}) + factors = cast( + OrderedSet, + (factors - affected_factors) + | (_differentiate_factors(affected_factors, var, use_sympy=use_sympy)), + ) + + return Term(factors or {Factor("1", eval_method="literal")}) + + +def _factor_symbols(factor: Factor, use_sympy: bool = False) -> set[str]: + """ + Extract the symbols represented in a factor. + + Args: + factor: The `Factor` instance from which symbols should be extracted. + use_sympy: Whether to interpret the string representation of the + factor using `sympy`. + + Returns: + The set of string symbols represented by the factor. + """ + if use_sympy: + try: + import sympy + + return {str(s) for s in sympy.S(factor.expr).free_symbols} + except ImportError as e: # pragma: no cover + raise ImportError( + "`sympy` is not available. Install it using `pip install formulaic[calculus]` or `pip install sympy`." + ) from e + return {factor.expr} + + +def _differentiate_factors( + factors: set[Factor], var: str, use_sympy: bool = False +) -> set[Factor]: + """ + Differentiate the nominated `factors` by `var`. + + Args: + factors: The set of factors which should be differentiated (taking for + granted that they are multiplied together). + var: The variable by which to differentiate. + use_sympy: Whether to perform the differentiation using sympy, allowing + for symbolic differentiations like `log(x)` -> `1/x`. + + Returns: + A set containing the new factors to replace the incoming factors in a + term. + """ + if use_sympy: + try: + import sympy + + expr = sympy.S( + "(" + ") * (".join(factor.expr for factor in factors) + ")" + ).diff(var) + eval_method = Factor.EvalMethod.PYTHON + except ImportError as e: # pragma: no cover + raise ImportError( + "`sympy` is not available. Install it using `pip install formulaic[calculus]` or `pip install sympy`." + ) from e + else: + if len(factors) != 1: + raise RuntimeError( + "Cannot differentiate non-trivial factors without `sympy`." + ) + expr = 1 + eval_method = next(iter(factors)).eval_method + + if expr == 1: + return set() + return {Factor(f"({str(expr)})", eval_method=eval_method)} diff --git a/shared/package-files/02/02dfe06333aa80d1919b0f68eec9edb2a461aec5170b71e80a206ddec78cf5f8/any_namespace.py b/shared/package-files/02/02dfe06333aa80d1919b0f68eec9edb2a461aec5170b71e80a206ddec78cf5f8/any_namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..6bc604206759c179928b8ee6fa907fcaa149d2c6 --- /dev/null +++ b/shared/package-files/02/02dfe06333aa80d1919b0f68eec9edb2a461aec5170b71e80a206ddec78cf5f8/any_namespace.py @@ -0,0 +1,120 @@ +"""`Expr` and `Series` namespace accessor protocols.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, ClassVar, Protocol, TypeVar + +from narwhals._utils import CompliantT_co, _StoresCompliant + +if TYPE_CHECKING: + from collections.abc import Callable + + from narwhals._compliant.typing import Accessor + from narwhals.typing import NonNestedLiteral, TimeUnit + +T = TypeVar("T") + +__all__ = [ + "CatNamespace", + "DateTimeNamespace", + "ListNamespace", + "NameNamespace", + "NamespaceAccessor", + "StringNamespace", + "StructNamespace", +] + + +class NamespaceAccessor(_StoresCompliant[CompliantT_co], Protocol[CompliantT_co]): + _accessor: ClassVar[Accessor] + + +class CatNamespace(NamespaceAccessor[CompliantT_co], Protocol[CompliantT_co]): + _accessor: ClassVar[Accessor] = "cat" + + def get_categories(self) -> CompliantT_co: ... + + +class DateTimeNamespace(_StoresCompliant[CompliantT_co], Protocol[CompliantT_co]): + _accessor: ClassVar[Accessor] = "dt" + + def to_string(self, format: str) -> CompliantT_co: ... + def replace_time_zone(self, time_zone: str | None) -> CompliantT_co: ... + def convert_time_zone(self, time_zone: str) -> CompliantT_co: ... + def timestamp(self, time_unit: TimeUnit) -> CompliantT_co: ... + def date(self) -> CompliantT_co: ... + def year(self) -> CompliantT_co: ... + def month(self) -> CompliantT_co: ... + def day(self) -> CompliantT_co: ... + def hour(self) -> CompliantT_co: ... + def minute(self) -> CompliantT_co: ... + def second(self) -> CompliantT_co: ... + def millisecond(self) -> CompliantT_co: ... + def microsecond(self) -> CompliantT_co: ... + def nanosecond(self) -> CompliantT_co: ... + def ordinal_day(self) -> CompliantT_co: ... + def weekday(self) -> CompliantT_co: ... + def total_minutes(self) -> CompliantT_co: ... + def total_seconds(self) -> CompliantT_co: ... + def total_milliseconds(self) -> CompliantT_co: ... + def total_microseconds(self) -> CompliantT_co: ... + def total_nanoseconds(self) -> CompliantT_co: ... + def truncate(self, every: str) -> CompliantT_co: ... + def offset_by(self, by: str) -> CompliantT_co: ... + + +class ListNamespace(_StoresCompliant[CompliantT_co], Protocol[CompliantT_co]): + _accessor: ClassVar[Accessor] = "list" + + def get(self, index: int) -> CompliantT_co: ... + def len(self) -> CompliantT_co: ... + def unique(self, *, maintain_order: bool) -> CompliantT_co: ... + def contains(self, item: NonNestedLiteral) -> CompliantT_co: ... + def min(self) -> CompliantT_co: ... + def max(self) -> CompliantT_co: ... + def mean(self) -> CompliantT_co: ... + def median(self) -> CompliantT_co: ... + def sum(self) -> CompliantT_co: ... + def sort(self, *, descending: bool, nulls_last: bool) -> CompliantT_co: ... + + +class NameNamespace(_StoresCompliant[CompliantT_co], Protocol[CompliantT_co]): + _accessor: ClassVar[Accessor] = "name" + + def keep(self) -> CompliantT_co: ... + def map(self, function: Callable[[str], str]) -> CompliantT_co: ... + def prefix(self, prefix: str) -> CompliantT_co: ... + def suffix(self, suffix: str) -> CompliantT_co: ... + def to_lowercase(self) -> CompliantT_co: ... + def to_uppercase(self) -> CompliantT_co: ... + + +class StringNamespace(_StoresCompliant[T], Protocol[T]): + _accessor: ClassVar[Accessor] = "str" + + def len_chars(self) -> T: ... + def replace(self, value: T, pattern: str, *, literal: bool, n: int) -> T: ... + def replace_all(self, value: T, pattern: str, *, literal: bool) -> T: ... + def strip_chars(self, characters: str | None) -> T: ... + def strip_chars_start(self, characters: str) -> T: ... + def strip_chars_end(self, characters: str) -> T: ... + def starts_with(self, prefix: T) -> T: ... + def ends_with(self, suffix: T) -> T: ... + def contains(self, pattern: T, *, literal: bool) -> T: ... + def slice(self, offset: int, length: int | None) -> T: ... + def split(self, by: str) -> T: ... + def to_datetime(self, format: str | None) -> T: ... + def to_time(self, format: str | None) -> T: ... + def to_date(self, format: str | None) -> T: ... + def to_lowercase(self) -> T: ... + def to_titlecase(self) -> T: ... + def to_uppercase(self) -> T: ... + def zfill(self, width: int) -> T: ... + def pad_start(self, length: int, fill_char: str) -> T: ... + def pad_end(self, length: int, fill_char: str) -> T: ... + + +class StructNamespace(_StoresCompliant[CompliantT_co], Protocol[CompliantT_co]): + _accessor: ClassVar[Accessor] = "struct" + + def field(self, name: str) -> CompliantT_co: ... diff --git a/shared/package-files/02/02e0a60424c93269a002de594d2fc8e324bc756c8af73112df5a5af7dc3e1453/linalg_lu_factor_ex_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/02/02e0a60424c93269a002de594d2fc8e324bc756c8af73112df5a5af7dc3e1453/linalg_lu_factor_ex_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..fb39fd7369f28c7dc6608c99d58114572245c83c --- /dev/null +++ b/shared/package-files/02/02e0a60424c93269a002de594d2fc8e324bc756c8af73112df5a5af7dc3e1453/linalg_lu_factor_ex_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 linalg_lu_factor_ex(const at::Tensor & A, bool pivot=true, bool check_errors=false); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/02/02e0d24797046cebebd6b00c3924f57f50ef3cd89b03e3f367208361dd17c11e/_search_successive_halving.py b/shared/package-files/02/02e0d24797046cebebd6b00c3924f57f50ef3cd89b03e3f367208361dd17c11e/_search_successive_halving.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd9a83e6dc4394c1ab75713a4373dd0709e90cf --- /dev/null +++ b/shared/package-files/02/02e0d24797046cebebd6b00c3924f57f50ef3cd89b03e3f367208361dd17c11e/_search_successive_halving.py @@ -0,0 +1,1095 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from abc import abstractmethod +from math import ceil, floor, log +from numbers import Integral, Real + +import numpy as np + +from ..base import _fit_context, is_classifier +from ..metrics._scorer import get_scorer_names +from ..utils import resample +from ..utils._param_validation import Interval, StrOptions +from ..utils.multiclass import check_classification_targets +from ..utils.validation import _num_samples, validate_data +from . import ParameterGrid, ParameterSampler +from ._search import BaseSearchCV +from ._split import _yields_constant_splits, check_cv + +__all__ = ["HalvingGridSearchCV", "HalvingRandomSearchCV"] + + +class _SubsampleMetaSplitter: + """Splitter that subsamples a given fraction of the dataset""" + + def __init__(self, *, base_cv, fraction, subsample_test, random_state): + self.base_cv = base_cv + self.fraction = fraction + self.subsample_test = subsample_test + self.random_state = random_state + + def split(self, X, y, **kwargs): + for train_idx, test_idx in self.base_cv.split(X, y, **kwargs): + train_idx = resample( + train_idx, + replace=False, + random_state=self.random_state, + n_samples=int(self.fraction * len(train_idx)), + ) + if self.subsample_test: + test_idx = resample( + test_idx, + replace=False, + random_state=self.random_state, + n_samples=int(self.fraction * len(test_idx)), + ) + yield train_idx, test_idx + + +def _top_k(results, k, itr): + # Return the best candidates of a given iteration + iteration, mean_test_score, params = ( + np.asarray(a) + for a in (results["iter"], results["mean_test_score"], results["params"]) + ) + iter_indices = np.flatnonzero(iteration == itr) + scores = mean_test_score[iter_indices] + # argsort() places NaNs at the end of the array so we move NaNs to the + # front of the array so the last `k` items are the those with the + # highest scores. + sorted_indices = np.roll(np.argsort(scores), np.count_nonzero(np.isnan(scores))) + return np.array(params[iter_indices][sorted_indices[-k:]]) + + +class BaseSuccessiveHalving(BaseSearchCV): + """Implements successive halving. + + Ref: + Almost optimal exploration in multi-armed bandits, ICML 13 + Zohar Karnin, Tomer Koren, Oren Somekh + """ + + _parameter_constraints: dict = { + **BaseSearchCV._parameter_constraints, + # overwrite `scoring` since multi-metrics are not supported + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "random_state": ["random_state"], + "max_resources": [ + Interval(Integral, 0, None, closed="neither"), + StrOptions({"auto"}), + ], + "min_resources": [ + Interval(Integral, 0, None, closed="neither"), + StrOptions({"exhaust", "smallest"}), + ], + "resource": [str], + "factor": [Interval(Real, 0, None, closed="neither")], + "aggressive_elimination": ["boolean"], + } + _parameter_constraints.pop("pre_dispatch") # not used in this class + + def __init__( + self, + estimator, + *, + scoring=None, + n_jobs=None, + refit=True, + cv=5, + verbose=0, + random_state=None, + error_score=np.nan, + return_train_score=True, + max_resources="auto", + min_resources="exhaust", + resource="n_samples", + factor=3, + aggressive_elimination=False, + ): + super().__init__( + estimator, + scoring=scoring, + n_jobs=n_jobs, + refit=refit, + cv=cv, + verbose=verbose, + error_score=error_score, + return_train_score=return_train_score, + ) + + self.random_state = random_state + self.max_resources = max_resources + self.resource = resource + self.factor = factor + self.min_resources = min_resources + self.aggressive_elimination = aggressive_elimination + + def _check_input_parameters(self, X, y, split_params): + # We need to enforce that successive calls to cv.split() yield the same + # splits: see https://github.com/scikit-learn/scikit-learn/issues/15149 + if not _yields_constant_splits(self._checked_cv_orig): + raise ValueError( + "The cv parameter must yield consistent folds across " + "calls to split(). Set its random_state to an int, or set " + "shuffle=False." + ) + + if ( + self.resource != "n_samples" + and self.resource not in self.estimator.get_params() + ): + raise ValueError( + f"Cannot use resource={self.resource} which is not supported " + f"by estimator {self.estimator.__class__.__name__}" + ) + + if isinstance(self, HalvingRandomSearchCV): + if self.min_resources == self.n_candidates == "exhaust": + # for n_candidates=exhaust to work, we need to know what + # min_resources is. Similarly min_resources=exhaust needs to + # know the actual number of candidates. + raise ValueError( + "n_candidates and min_resources cannot be both set to 'exhaust'." + ) + + self.min_resources_ = self.min_resources + if self.min_resources_ in ("smallest", "exhaust"): + if self.resource == "n_samples": + n_splits = self._checked_cv_orig.get_n_splits(X, y, **split_params) + # please see https://gph.is/1KjihQe for a justification + magic_factor = 2 + self.min_resources_ = n_splits * magic_factor + if is_classifier(self.estimator): + y = validate_data(self, X="no_validation", y=y) + check_classification_targets(y) + n_classes = np.unique(y).shape[0] + self.min_resources_ *= n_classes + else: + self.min_resources_ = 1 + # if 'exhaust', min_resources_ might be set to a higher value later + # in _run_search + + self.max_resources_ = self.max_resources + if self.max_resources_ == "auto": + if not self.resource == "n_samples": + raise ValueError( + "resource can only be 'n_samples' when max_resources='auto'" + ) + self.max_resources_ = _num_samples(X) + + if self.min_resources_ > self.max_resources_: + raise ValueError( + f"min_resources_={self.min_resources_} is greater " + f"than max_resources_={self.max_resources_}." + ) + + if self.min_resources_ == 0: + raise ValueError( + f"min_resources_={self.min_resources_}: you might have passed " + "an empty dataset X." + ) + + @staticmethod + def _select_best_index(refit, refit_metric, results): + """Custom refit callable to return the index of the best candidate. + + We want the best candidate out of the last iteration. By default + BaseSearchCV would return the best candidate out of all iterations. + + Currently, we only support for a single metric thus `refit` and + `refit_metric` are not required. + """ + last_iter = np.max(results["iter"]) + last_iter_indices = np.flatnonzero(results["iter"] == last_iter) + + test_scores = results["mean_test_score"][last_iter_indices] + # If all scores are NaNs there is no way to pick between them, + # so we (arbitrarily) declare the zero'th entry the best one + if np.isnan(test_scores).all(): + best_idx = 0 + else: + best_idx = np.nanargmax(test_scores) + + return last_iter_indices[best_idx] + + @_fit_context( + # Halving*SearchCV.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None, **params): + """Run fit with all sets of parameters. + + Parameters + ---------- + + X : array-like, shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like, shape (n_samples,) or (n_samples, n_output), optional + Target relative to X for classification or regression; + None for unsupervised learning. + + **params : dict of string -> object + Parameters passed to the ``fit`` method of the estimator. + + Returns + ------- + self : object + Instance of fitted estimator. + """ + self._checked_cv_orig = check_cv( + self.cv, y, classifier=is_classifier(self.estimator) + ) + + routed_params = self._get_routed_params_for_fit(params) + self._check_input_parameters( + X=X, y=y, split_params=routed_params.splitter.split + ) + + self._n_samples_orig = _num_samples(X) + + super().fit(X, y=y, **params) + + # Set best_score_: BaseSearchCV does not set it, as refit is a callable + self.best_score_ = self.cv_results_["mean_test_score"][self.best_index_] + + return self + + def _run_search(self, evaluate_candidates): + candidate_params = self._generate_candidate_params() + + if self.resource != "n_samples" and any( + self.resource in candidate for candidate in candidate_params + ): + # Can only check this now since we need the candidates list + raise ValueError( + f"Cannot use parameter {self.resource} as the resource since " + "it is part of the searched parameters." + ) + + # n_required_iterations is the number of iterations needed so that the + # last iterations evaluates less than `factor` candidates. + n_required_iterations = 1 + floor(log(len(candidate_params), self.factor)) + + if self.min_resources == "exhaust": + # To exhaust the resources, we want to start with the biggest + # min_resources possible so that the last (required) iteration + # uses as many resources as possible + last_iteration = n_required_iterations - 1 + self.min_resources_ = max( + self.min_resources_, + self.max_resources_ // self.factor**last_iteration, + ) + + # n_possible_iterations is the number of iterations that we can + # actually do starting from min_resources and without exceeding + # max_resources. Depending on max_resources and the number of + # candidates, this may be higher or smaller than + # n_required_iterations. + n_possible_iterations = 1 + floor( + log(self.max_resources_ // self.min_resources_, self.factor) + ) + + if self.aggressive_elimination: + n_iterations = n_required_iterations + else: + n_iterations = min(n_possible_iterations, n_required_iterations) + + if self.verbose: + print(f"n_iterations: {n_iterations}") + print(f"n_required_iterations: {n_required_iterations}") + print(f"n_possible_iterations: {n_possible_iterations}") + print(f"min_resources_: {self.min_resources_}") + print(f"max_resources_: {self.max_resources_}") + print(f"aggressive_elimination: {self.aggressive_elimination}") + print(f"factor: {self.factor}") + + self.n_resources_ = [] + self.n_candidates_ = [] + + for itr in range(n_iterations): + power = itr # default + if self.aggressive_elimination: + # this will set n_resources to the initial value (i.e. the + # value of n_resources at the first iteration) for as many + # iterations as needed (while candidates are being + # eliminated), and then go on as usual. + power = max(0, itr - n_required_iterations + n_possible_iterations) + + n_resources = int(self.factor**power * self.min_resources_) + # guard, probably not needed + n_resources = min(n_resources, self.max_resources_) + self.n_resources_.append(n_resources) + + n_candidates = len(candidate_params) + self.n_candidates_.append(n_candidates) + + if self.verbose: + print("-" * 10) + print(f"iter: {itr}") + print(f"n_candidates: {n_candidates}") + print(f"n_resources: {n_resources}") + + if self.resource == "n_samples": + # subsampling will be done in cv.split() + cv = _SubsampleMetaSplitter( + base_cv=self._checked_cv_orig, + fraction=n_resources / self._n_samples_orig, + subsample_test=True, + random_state=self.random_state, + ) + + else: + # Need copy so that the n_resources of next iteration does + # not overwrite + candidate_params = [c.copy() for c in candidate_params] + for candidate in candidate_params: + candidate[self.resource] = n_resources + cv = self._checked_cv_orig + + more_results = { + "iter": [itr] * n_candidates, + "n_resources": [n_resources] * n_candidates, + } + + results = evaluate_candidates( + candidate_params, cv, more_results=more_results + ) + + n_candidates_to_keep = ceil(n_candidates / self.factor) + candidate_params = _top_k(results, n_candidates_to_keep, itr) + + self.n_remaining_candidates_ = len(candidate_params) + self.n_required_iterations_ = n_required_iterations + self.n_possible_iterations_ = n_possible_iterations + self.n_iterations_ = n_iterations + + @abstractmethod + def _generate_candidate_params(self): + pass + + +class HalvingGridSearchCV(BaseSuccessiveHalving): + """Search over specified parameter values with successive halving. + + The search strategy starts evaluating all the candidates with a small + amount of resources and iteratively selects the best candidates, using + more and more resources. + + Read more in the :ref:`User guide `. + + .. note:: + + This estimator is still **experimental** for now: the predictions + and the API might change without any deprecation cycle. To use it, + you need to explicitly import ``enable_halving_search_cv``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_halving_search_cv # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingGridSearchCV + + Parameters + ---------- + estimator : estimator object + This is assumed to implement the scikit-learn estimator interface. + Either estimator needs to provide a ``score`` function, + or ``scoring`` must be passed. + + param_grid : dict or list of dictionaries + Dictionary with parameters names (string) as keys and lists of + parameter settings to try as values, or a list of such + dictionaries, in which case the grids spanned by each dictionary + in the list are explored. This enables searching over any sequence + of parameter settings. + + factor : int or float, default=3 + The 'halving' parameter, which determines the proportion of candidates + that are selected for each subsequent iteration. For example, + ``factor=3`` means that only one third of the candidates are selected. + + resource : ``'n_samples'`` or str, default='n_samples' + Defines the resource that increases with each iteration. By default, + the resource is the number of samples. It can also be set to any + parameter of the base estimator that accepts positive integer + values, e.g. 'n_iterations' or 'n_estimators' for a gradient + boosting estimator. In this case ``max_resources`` cannot be 'auto' + and must be set explicitly. + + max_resources : int, default='auto' + The maximum amount of resource that any candidate is allowed to use + for a given iteration. By default, this is set to ``n_samples`` when + ``resource='n_samples'`` (default), else an error is raised. + + min_resources : {'exhaust', 'smallest'} or int, default='exhaust' + The minimum amount of resource that any candidate is allowed to use + for a given iteration. Equivalently, this defines the amount of + resources `r0` that are allocated for each candidate at the first + iteration. + + - 'smallest' is a heuristic that sets `r0` to a small value: + + - ``n_splits * 2`` when ``resource='n_samples'`` for a regression problem + - ``n_classes * n_splits * 2`` when ``resource='n_samples'`` for a + classification problem + - ``1`` when ``resource != 'n_samples'`` + + - 'exhaust' will set `r0` such that the **last** iteration uses as + much resources as possible. Namely, the last iteration will use the + highest value smaller than ``max_resources`` that is a multiple of + both ``min_resources`` and ``factor``. In general, using 'exhaust' + leads to a more accurate estimator, but is slightly more time + consuming. + + Note that the amount of resources used at each iteration is always a + multiple of ``min_resources``. + + aggressive_elimination : bool, default=False + This is only relevant in cases where there isn't enough resources to + reduce the remaining candidates to at most `factor` after the last + iteration. If ``True``, then the search process will 'replay' the + first iteration for as long as needed until the number of candidates + is small enough. This is ``False`` by default, which means that the + last iteration may evaluate more than ``factor`` candidates. See + :ref:`aggressive_elimination` for more details. + + cv : int, cross-validation generator or iterable, default=5 + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. note:: + Due to implementation details, the folds produced by `cv` must be + the same across multiple calls to `cv.split()`. For + built-in `scikit-learn` iterators, this can be achieved by + deactivating shuffling (`shuffle=False`), or by setting the + `cv`'s `random_state` parameter to an integer. + + scoring : str or callable, default=None + Scoring method to use to evaluate the predictions on the test set. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + refit : bool or callable, default=True + Refit an estimator using the best found parameters on the whole + dataset. + + Where there are considerations other than maximum score in + choosing a best estimator, ``refit`` can be set to a function which + returns the selected ``best_index_`` given ``cv_results_``. In that + case, the ``best_estimator_`` and ``best_params_`` will be set + according to the returned ``best_index_`` while the ``best_score_`` + attribute will not be available. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``HalvingGridSearchCV`` instance. + + See :ref:`this example + ` + for an example of how to use ``refit=callable`` to balance model + complexity and cross-validated score. + + error_score : 'raise' or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. Default is ``np.nan``. + + return_train_score : bool, default=False + If ``False``, the ``cv_results_`` attribute will not include training + scores. + Computing training scores is used to get insights on how different + parameter settings impact the overfitting/underfitting trade-off. + However computing the scores on the training set can be computationally + expensive and is not strictly required to select the parameters that + yield the best generalization performance. + + random_state : int, RandomState instance or None, default=None + Pseudo random number generator state used for subsampling the dataset + when `resources != 'n_samples'`. Ignored otherwise. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + n_jobs : int or None, 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. + + verbose : int + Controls the verbosity: the higher, the more messages. + + Attributes + ---------- + n_resources_ : list of int + The amount of resources used at each iteration. + + n_candidates_ : list of int + The number of candidate parameters that were evaluated at each + iteration. + + n_remaining_candidates_ : int + The number of candidate parameters that are left after the last + iteration. It corresponds to `ceil(n_candidates[-1] / factor)` + + max_resources_ : int + The maximum number of resources that any candidate is allowed to use + for a given iteration. Note that since the number of resources used + at each iteration must be a multiple of ``min_resources_``, the + actual number of resources used at the last iteration may be smaller + than ``max_resources_``. + + min_resources_ : int + The amount of resources that are allocated for each candidate at the + first iteration. + + n_iterations_ : int + The actual number of iterations that were run. This is equal to + ``n_required_iterations_`` if ``aggressive_elimination`` is ``True``. + Else, this is equal to ``min(n_possible_iterations_, + n_required_iterations_)``. + + n_possible_iterations_ : int + The number of iterations that are possible starting with + ``min_resources_`` resources and without exceeding + ``max_resources_``. + + n_required_iterations_ : int + The number of iterations that are required to end up with less than + ``factor`` candidates at the last iteration, starting with + ``min_resources_`` resources. This will be smaller than + ``n_possible_iterations_`` when there isn't enough resources. + + cv_results_ : dict of numpy (masked) ndarrays + A dict with keys as column headers and values as columns, that can be + imported into a pandas ``DataFrame``. It contains lots of information + for analysing the results of a search. + Please refer to the :ref:`User guide` + for details. + + best_estimator_ : estimator or dict + Estimator that was chosen by the search, i.e. estimator + which gave highest score (or smallest loss if specified) + on the left out data. Not available if ``refit=False``. + + best_score_ : float + Mean cross-validated score of the best_estimator. + + best_params_ : dict + Parameter setting that gave the best results on the hold out data. + + best_index_ : int + The index (of the ``cv_results_`` arrays) which corresponds to the best + candidate parameter setting. + + The dict at ``search.cv_results_['params'][search.best_index_]`` gives + the parameter setting for the best model, that gives the highest + mean score (``search.best_score_``). + + scorer_ : function or a dict + Scorer function used on the held out data to choose the best + parameters for the model. + + n_splits_ : int + The number of cross-validation splits (folds/iterations). + + refit_time_ : float + Seconds used for refitting the best model on the whole dataset. + + This is present only if ``refit`` is not False. + + multimetric_ : bool + Whether or not the scorers compute several metrics. + + classes_ : ndarray of shape (n_classes,) + The classes labels. This is present only if ``refit`` is specified and + the underlying estimator is a classifier. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `n_features_in_` when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `feature_names_in_` when fit. + + .. versionadded:: 1.0 + + See Also + -------- + :class:`HalvingRandomSearchCV`: + Random search over a set of parameters using successive halving. + + Notes + ----- + The parameters selected are those that maximize the score of the held-out + data, according to the scoring parameter. + + All parameter combinations scored with a NaN will share the lowest rank. + + Examples + -------- + + >>> from sklearn.datasets import load_iris + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_halving_search_cv # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + ... + >>> X, y = load_iris(return_X_y=True) + >>> clf = RandomForestClassifier(random_state=0) + ... + >>> param_grid = {"max_depth": [3, None], + ... "min_samples_split": [5, 10]} + >>> search = HalvingGridSearchCV(clf, param_grid, resource='n_estimators', + ... max_resources=10, + ... random_state=0).fit(X, y) + >>> search.best_params_ # doctest: +SKIP + {'max_depth': None, 'min_samples_split': 10, 'n_estimators': 9} + """ + + _parameter_constraints: dict = { + **BaseSuccessiveHalving._parameter_constraints, + "param_grid": [dict, list], + } + + def __init__( + self, + estimator, + param_grid, + *, + factor=3, + resource="n_samples", + max_resources="auto", + min_resources="exhaust", + aggressive_elimination=False, + cv=5, + scoring=None, + refit=True, + error_score=np.nan, + return_train_score=True, + random_state=None, + n_jobs=None, + verbose=0, + ): + super().__init__( + estimator, + scoring=scoring, + n_jobs=n_jobs, + refit=refit, + verbose=verbose, + cv=cv, + random_state=random_state, + error_score=error_score, + return_train_score=return_train_score, + max_resources=max_resources, + resource=resource, + factor=factor, + min_resources=min_resources, + aggressive_elimination=aggressive_elimination, + ) + self.param_grid = param_grid + + def _generate_candidate_params(self): + return ParameterGrid(self.param_grid) + + +class HalvingRandomSearchCV(BaseSuccessiveHalving): + """Randomized search on hyper parameters. + + The search strategy starts evaluating all the candidates with a small + amount of resources and iteratively selects the best candidates, using more + and more resources. + + The candidates are sampled at random from the parameter space and the + number of sampled candidates is determined by ``n_candidates``. + + Read more in the :ref:`User guide`. + + .. note:: + + This estimator is still **experimental** for now: the predictions + and the API might change without any deprecation cycle. To use it, + you need to explicitly import ``enable_halving_search_cv``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_halving_search_cv # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingRandomSearchCV + + Parameters + ---------- + estimator : estimator object + This is assumed to implement the scikit-learn estimator interface. + Either estimator needs to provide a ``score`` function, + or ``scoring`` must be passed. + + param_distributions : dict or list of dicts + Dictionary with parameters names (`str`) as keys and distributions + or lists of parameters to try. Distributions must provide a ``rvs`` + method for sampling (such as those from scipy.stats.distributions). + If a list is given, it is sampled uniformly. + If a list of dicts is given, first a dict is sampled uniformly, and + then a parameter is sampled using that dict as above. + + n_candidates : "exhaust" or int, default="exhaust" + The number of candidate parameters to sample, at the first + iteration. Using 'exhaust' will sample enough candidates so that the + last iteration uses as many resources as possible, based on + `min_resources`, `max_resources` and `factor`. In this case, + `min_resources` cannot be 'exhaust'. + + factor : int or float, default=3 + The 'halving' parameter, which determines the proportion of candidates + that are selected for each subsequent iteration. For example, + ``factor=3`` means that only one third of the candidates are selected. + + resource : ``'n_samples'`` or str, default='n_samples' + Defines the resource that increases with each iteration. By default, + the resource is the number of samples. It can also be set to any + parameter of the base estimator that accepts positive integer + values, e.g. 'n_iterations' or 'n_estimators' for a gradient + boosting estimator. In this case ``max_resources`` cannot be 'auto' + and must be set explicitly. + + max_resources : int, default='auto' + The maximum number of resources that any candidate is allowed to use + for a given iteration. By default, this is set ``n_samples`` when + ``resource='n_samples'`` (default), else an error is raised. + + min_resources : {'exhaust', 'smallest'} or int, default='smallest' + The minimum amount of resource that any candidate is allowed to use + for a given iteration. Equivalently, this defines the amount of + resources `r0` that are allocated for each candidate at the first + iteration. + + - 'smallest' is a heuristic that sets `r0` to a small value: + + - ``n_splits * 2`` when ``resource='n_samples'`` for a regression problem + - ``n_classes * n_splits * 2`` when ``resource='n_samples'`` for a + classification problem + - ``1`` when ``resource != 'n_samples'`` + + - 'exhaust' will set `r0` such that the **last** iteration uses as + much resources as possible. Namely, the last iteration will use the + highest value smaller than ``max_resources`` that is a multiple of + both ``min_resources`` and ``factor``. In general, using 'exhaust' + leads to a more accurate estimator, but is slightly more time + consuming. 'exhaust' isn't available when `n_candidates='exhaust'`. + + Note that the amount of resources used at each iteration is always a + multiple of ``min_resources``. + + aggressive_elimination : bool, default=False + This is only relevant in cases where there isn't enough resources to + reduce the remaining candidates to at most `factor` after the last + iteration. If ``True``, then the search process will 'replay' the + first iteration for as long as needed until the number of candidates + is small enough. This is ``False`` by default, which means that the + last iteration may evaluate more than ``factor`` candidates. See + :ref:`aggressive_elimination` for more details. + + cv : int, cross-validation generator or an iterable, default=5 + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. note:: + Due to implementation details, the folds produced by `cv` must be + the same across multiple calls to `cv.split()`. For + built-in `scikit-learn` iterators, this can be achieved by + deactivating shuffling (`shuffle=False`), or by setting the + `cv`'s `random_state` parameter to an integer. + + scoring : str or callable, default=None + Scoring method to use to evaluate the predictions on the test set. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + refit : bool or callable, default=True + Refit an estimator using the best found parameters on the whole + dataset. + + Where there are considerations other than maximum score in + choosing a best estimator, ``refit`` can be set to a function which + returns the selected ``best_index_`` given ``cv_results_``. In that + case, the ``best_estimator_`` and ``best_params_`` will be set + according to the returned ``best_index_`` while the ``best_score_`` + attribute will not be available. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``HalvingRandomSearchCV`` instance. + + See :ref:`this example + ` + for an example of how to use ``refit=callable`` to balance model + complexity and cross-validated score. + + error_score : 'raise' or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. Default is ``np.nan``. + + return_train_score : bool, default=False + If ``False``, the ``cv_results_`` attribute will not include training + scores. + Computing training scores is used to get insights on how different + parameter settings impact the overfitting/underfitting trade-off. + However computing the scores on the training set can be computationally + expensive and is not strictly required to select the parameters that + yield the best generalization performance. + + random_state : int, RandomState instance or None, default=None + Pseudo random number generator state used for subsampling the dataset + when `resources != 'n_samples'`. Also used for random uniform + sampling from lists of possible values instead of scipy.stats + distributions. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + n_jobs : int or None, 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. + + verbose : int + Controls the verbosity: the higher, the more messages. + + Attributes + ---------- + n_resources_ : list of int + The amount of resources used at each iteration. + + n_candidates_ : list of int + The number of candidate parameters that were evaluated at each + iteration. + + n_remaining_candidates_ : int + The number of candidate parameters that are left after the last + iteration. It corresponds to `ceil(n_candidates[-1] / factor)` + + max_resources_ : int + The maximum number of resources that any candidate is allowed to use + for a given iteration. Note that since the number of resources used at + each iteration must be a multiple of ``min_resources_``, the actual + number of resources used at the last iteration may be smaller than + ``max_resources_``. + + min_resources_ : int + The amount of resources that are allocated for each candidate at the + first iteration. + + n_iterations_ : int + The actual number of iterations that were run. This is equal to + ``n_required_iterations_`` if ``aggressive_elimination`` is ``True``. + Else, this is equal to ``min(n_possible_iterations_, + n_required_iterations_)``. + + n_possible_iterations_ : int + The number of iterations that are possible starting with + ``min_resources_`` resources and without exceeding + ``max_resources_``. + + n_required_iterations_ : int + The number of iterations that are required to end up with less than + ``factor`` candidates at the last iteration, starting with + ``min_resources_`` resources. This will be smaller than + ``n_possible_iterations_`` when there isn't enough resources. + + cv_results_ : dict of numpy (masked) ndarrays + A dict with keys as column headers and values as columns, that can be + imported into a pandas ``DataFrame``. It contains lots of information + for analysing the results of a search. + Please refer to the :ref:`User guide` + for details. + + best_estimator_ : estimator or dict + Estimator that was chosen by the search, i.e. estimator + which gave highest score (or smallest loss if specified) + on the left out data. Not available if ``refit=False``. + + best_score_ : float + Mean cross-validated score of the best_estimator. + + best_params_ : dict + Parameter setting that gave the best results on the hold out data. + + best_index_ : int + The index (of the ``cv_results_`` arrays) which corresponds to the best + candidate parameter setting. + + The dict at ``search.cv_results_['params'][search.best_index_]`` gives + the parameter setting for the best model, that gives the highest + mean score (``search.best_score_``). + + scorer_ : function or a dict + Scorer function used on the held out data to choose the best + parameters for the model. + + n_splits_ : int + The number of cross-validation splits (folds/iterations). + + refit_time_ : float + Seconds used for refitting the best model on the whole dataset. + + This is present only if ``refit`` is not False. + + multimetric_ : bool + Whether or not the scorers compute several metrics. + + classes_ : ndarray of shape (n_classes,) + The classes labels. This is present only if ``refit`` is specified and + the underlying estimator is a classifier. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `n_features_in_` when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `feature_names_in_` when fit. + + .. versionadded:: 1.0 + + See Also + -------- + :class:`HalvingGridSearchCV`: + Search over a grid of parameters using successive halving. + + Notes + ----- + The parameters selected are those that maximize the score of the held-out + data, according to the scoring parameter. + + All parameter combinations scored with a NaN will share the lowest rank. + + Examples + -------- + + >>> from sklearn.datasets import load_iris + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_halving_search_cv # noqa + >>> from sklearn.model_selection import HalvingRandomSearchCV + >>> from scipy.stats import randint + >>> import numpy as np + ... + >>> X, y = load_iris(return_X_y=True) + >>> clf = RandomForestClassifier(random_state=0) + >>> np.random.seed(0) + ... + >>> param_distributions = {"max_depth": [3, None], + ... "min_samples_split": randint(2, 11)} + >>> search = HalvingRandomSearchCV(clf, param_distributions, + ... resource='n_estimators', + ... max_resources=10, + ... random_state=0).fit(X, y) + >>> search.best_params_ # doctest: +SKIP + {'max_depth': None, 'min_samples_split': 10, 'n_estimators': 9} + """ + + _parameter_constraints: dict = { + **BaseSuccessiveHalving._parameter_constraints, + "param_distributions": [dict, list], + "n_candidates": [ + Interval(Integral, 0, None, closed="neither"), + StrOptions({"exhaust"}), + ], + } + + def __init__( + self, + estimator, + param_distributions, + *, + n_candidates="exhaust", + factor=3, + resource="n_samples", + max_resources="auto", + min_resources="smallest", + aggressive_elimination=False, + cv=5, + scoring=None, + refit=True, + error_score=np.nan, + return_train_score=True, + random_state=None, + n_jobs=None, + verbose=0, + ): + super().__init__( + estimator, + scoring=scoring, + n_jobs=n_jobs, + refit=refit, + verbose=verbose, + cv=cv, + random_state=random_state, + error_score=error_score, + return_train_score=return_train_score, + max_resources=max_resources, + resource=resource, + factor=factor, + min_resources=min_resources, + aggressive_elimination=aggressive_elimination, + ) + self.param_distributions = param_distributions + self.n_candidates = n_candidates + + def _generate_candidate_params(self): + n_candidates_first_iter = self.n_candidates + if n_candidates_first_iter == "exhaust": + # This will generate enough candidate so that the last iteration + # uses as much resources as possible + n_candidates_first_iter = self.max_resources_ // self.min_resources_ + return ParameterSampler( + self.param_distributions, + n_candidates_first_iter, + random_state=self.random_state, + ) diff --git a/shared/package-files/02/02e181585934c9b2296966d79397d6cabc52492ae0cd8a785fa9c5783f68a5a4/__init__.py b/shared/package-files/02/02e181585934c9b2296966d79397d6cabc52492ae0cd8a785fa9c5783f68a5a4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bdcb913867a735374cb1df625bbacfc2802b5c1e --- /dev/null +++ b/shared/package-files/02/02e181585934c9b2296966d79397d6cabc52492ae0cd8a785fa9c5783f68a5a4/__init__.py @@ -0,0 +1,11 @@ +# Copyright 2019 Kakao Brain +# +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +"""Supports efficiency with skip connections.""" +from .namespace import Namespace +from .skippable import pop, skippable, stash, verify_skippables + +__all__ = ["skippable", "stash", "pop", "verify_skippables", "Namespace"] diff --git a/shared/package-files/02/02e36f0e51fc9a700949cc9c8f8995f88ab53346d7c6276963856e77f9512653/basic.py b/shared/package-files/02/02e36f0e51fc9a700949cc9c8f8995f88ab53346d7c6276963856e77f9512653/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..04ef3645a2ed6a22106ed8ca1acf9e9ac93df5cf --- /dev/null +++ b/shared/package-files/02/02e36f0e51fc9a700949cc9c8f8995f88ab53346d7c6276963856e77f9512653/basic.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'solve', 'solve_triangular', 'solveh_banded', 'solve_banded', + 'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq', + 'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz', + 'get_lapack_funcs', 'LinAlgError', 'LinAlgWarning', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="basic", + private_modules=["_basic"], all=__all__, + attribute=name) diff --git a/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun b/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun new file mode 100644 index 0000000000000000000000000000000000000000..52a27310747325b14902b2874b80ab99b933e2e1 Binary files /dev/null and b/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun differ diff --git a/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun1 b/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun1 new file mode 100644 index 0000000000000000000000000000000000000000..52a27310747325b14902b2874b80ab99b933e2e1 Binary files /dev/null and b/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun1 differ diff --git a/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun2 b/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun2 new file mode 100644 index 0000000000000000000000000000000000000000..52a27310747325b14902b2874b80ab99b933e2e1 Binary files /dev/null and b/shared/package-files/02/02e392161cb23f49a8fb1ba2f1a6583e013c0c26672f58c5eaca828db3b19914/sun2 differ diff --git a/shared/package-files/02/02e6a6d6ef0b0b91ce9204cc77f73468c975b2701cf14eb9a54ae73e2b1b4132/version.py b/shared/package-files/02/02e6a6d6ef0b0b91ce9204cc77f73468c975b2701cf14eb9a54ae73e2b1b4132/version.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6c589cf79c51f7ed91aea0ae25fbb647f9703f --- /dev/null +++ b/shared/package-files/02/02e6a6d6ef0b0b91ce9204cc77f73468c975b2701cf14eb9a54ae73e2b1b4132/version.py @@ -0,0 +1,2 @@ +"""`tqdm` version detector. Precedence: installed dist, git, 'UNKNOWN'.""" +__version__ = '4.61.1' diff --git a/shared/package-files/02/02e88f0ea3f66b00b8525589aec7cd0a7d65dce010b9997ae1623e944d8ce43b/rde.py b/shared/package-files/02/02e88f0ea3f66b00b8525589aec7cd0a7d65dce010b9997ae1623e944d8ce43b/rde.py new file mode 100644 index 0000000000000000000000000000000000000000..975b8db328976aa0c22659d6643138e34ef5b623 --- /dev/null +++ b/shared/package-files/02/02e88f0ea3f66b00b8525589aec7cd0a7d65dce010b9997ae1623e944d8ce43b/rde.py @@ -0,0 +1,800 @@ +""" +Algorithms for solving the Risch differential equation. + +Given a differential field K of characteristic 0 that is a simple +monomial extension of a base field k and f, g in K, the Risch +Differential Equation problem is to decide if there exist y in K such +that Dy + f*y == g and to find one if there are some. If t is a +monomial over k and the coefficients of f and g are in k(t), then y is +in k(t), and the outline of the algorithm here is given as: + +1. Compute the normal part n of the denominator of y. The problem is +then reduced to finding y' in k, where y == y'/n. +2. Compute the special part s of the denominator of y. The problem is +then reduced to finding y'' in k[t], where y == y''/(n*s) +3. Bound the degree of y''. +4. Reduce the equation Dy + f*y == g to a similar equation with f, g in +k[t]. +5. Find the solutions in k[t] of bounded degree of the reduced equation. + +See Chapter 6 of "Symbolic Integration I: Transcendental Functions" by +Manuel Bronstein. See also the docstring of risch.py. +""" + +from operator import mul +from functools import reduce + +from sympy.core import oo +from sympy.core.symbol import Dummy + +from sympy.polys import Poly, gcd, ZZ, cancel + +from sympy.functions.elementary.complexes import (im, re) +from sympy.functions.elementary.miscellaneous import sqrt + +from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation, + splitfactor, NonElementaryIntegralException, DecrementLevel, recognize_log_derivative) + +# TODO: Add messages to NonElementaryIntegralException errors + + +def order_at(a, p, t): + """ + Computes the order of a at p, with respect to t. + + Explanation + =========== + + For a, p in k[t], the order of a at p is defined as nu_p(a) = max({n + in Z+ such that p**n|a}), where a != 0. If a == 0, nu_p(a) = +oo. + + To compute the order at a rational function, a/b, use the fact that + nu_p(a/b) == nu_p(a) - nu_p(b). + """ + if a.is_zero: + return oo + if p == Poly(t, t): + return a.as_poly(t).ET()[0][0] + + # Uses binary search for calculating the power. power_list collects the tuples + # (p^k,k) where each k is some power of 2. After deciding the largest k + # such that k is power of 2 and p^k|a the loop iteratively calculates + # the actual power. + power_list = [] + p1 = p + r = a.rem(p1) + tracks_power = 1 + while r.is_zero: + power_list.append((p1,tracks_power)) + p1 = p1*p1 + tracks_power *= 2 + r = a.rem(p1) + n = 0 + product = Poly(1, t) + while len(power_list) != 0: + final = power_list.pop() + productf = product*final[0] + r = a.rem(productf) + if r.is_zero: + n += final[1] + product = productf + return n + + +def order_at_oo(a, d, t): + """ + Computes the order of a/d at oo (infinity), with respect to t. + + For f in k(t), the order or f at oo is defined as deg(d) - deg(a), where + f == a/d. + """ + if a.is_zero: + return oo + return d.degree(t) - a.degree(t) + + +def weak_normalizer(a, d, DE, z=None): + """ + Weak normalization. + + Explanation + =========== + + Given a derivation D on k[t] and f == a/d in k(t), return q in k[t] + such that f - Dq/q is weakly normalized with respect to t. + + f in k(t) is said to be "weakly normalized" with respect to t if + residue_p(f) is not a positive integer for any normal irreducible p + in k[t] such that f is in R_p (Definition 6.1.1). If f has an + elementary integral, this is equivalent to no logarithm of + integral(f) whose argument depends on t has a positive integer + coefficient, where the arguments of the logarithms not in k(t) are + in k[t]. + + Returns (q, f - Dq/q) + """ + z = z or Dummy('z') + dn, ds = splitfactor(d, DE) + + # Compute d1, where dn == d1*d2**2*...*dn**n is a square-free + # factorization of d. + g = gcd(dn, dn.diff(DE.t)) + d_sqf_part = dn.quo(g) + d1 = d_sqf_part.quo(gcd(d_sqf_part, g)) + + a1, b = gcdex_diophantine(d.quo(d1).as_poly(DE.t), d1.as_poly(DE.t), + a.as_poly(DE.t)) + r = (a - Poly(z, DE.t)*derivation(d1, DE)).as_poly(DE.t).resultant( + d1.as_poly(DE.t)) + r = Poly(r, z) + + if not r.expr.has(z): + return (Poly(1, DE.t), (a, d)) + + N = [i for i in r.real_roots() if i in ZZ and i > 0] + + q = reduce(mul, [gcd(a - Poly(n, DE.t)*derivation(d1, DE), d1) for n in N], + Poly(1, DE.t)) + + dq = derivation(q, DE) + sn = q*a - d*dq + sd = q*d + sn, sd = sn.cancel(sd, include=True) + + return (q, (sn, sd)) + + +def normal_denom(fa, fd, ga, gd, DE): + """ + Normal part of the denominator. + + Explanation + =========== + + Given a derivation D on k[t] and f, g in k(t) with f weakly + normalized with respect to t, either raise NonElementaryIntegralException, + in which case the equation Dy + f*y == g has no solution in k(t), or the + quadruplet (a, b, c, h) such that a, h in k[t], b, c in k, and for any + solution y in k(t) of Dy + f*y == g, q = y*h in k satisfies + a*Dq + b*q == c. + + This constitutes step 1 in the outline given in the rde.py docstring. + """ + dn, ds = splitfactor(fd, DE) + en, es = splitfactor(gd, DE) + + p = dn.gcd(en) + h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t))) + + a = dn*h + c = a*h + if c.div(en)[1]: + # en does not divide dn*h**2 + raise NonElementaryIntegralException + ca = c*ga + ca, cd = ca.cancel(gd, include=True) + + ba = a*fa - dn*derivation(h, DE)*fd + ba, bd = ba.cancel(fd, include=True) + + # (dn*h, dn*h*f - dn*Dh, dn*h**2*g, h) + return (a, (ba, bd), (ca, cd), h) + + +def special_denom(a, ba, bd, ca, cd, DE, case='auto'): + """ + Special part of the denominator. + + Explanation + =========== + + case is one of {'exp', 'tan', 'primitive'} for the hyperexponential, + hypertangent, and primitive cases, respectively. For the + hyperexponential (resp. hypertangent) case, given a derivation D on + k[t] and a in k[t], b, c, in k with Dt/t in k (resp. Dt/(t**2 + 1) in + k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp. + gcd(a, t**2 + 1) == 1), return the quadruplet (A, B, C, 1/h) such that + A, B, C, h in k[t] and for any solution q in k of a*Dq + b*q == c, + r = qh in k[t] satisfies A*Dr + B*r == C. + + For ``case == 'primitive'``, k == k[t], so it returns (a, b, c, 1) in + this case. + + This constitutes step 2 of the outline given in the rde.py docstring. + """ + # TODO: finish writing this and write tests + + if case == 'auto': + case = DE.case + + if case == 'exp': + p = Poly(DE.t, DE.t) + elif case == 'tan': + p = Poly(DE.t**2 + 1, DE.t) + elif case in ('primitive', 'base'): + B = ba.to_field().quo(bd) + C = ca.to_field().quo(cd) + return (a, B, C, Poly(1, DE.t)) + else: + raise ValueError("case must be one of {'exp', 'tan', 'primitive', " + "'base'}, not %s." % case) + + nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t) + nc = order_at(ca, p, DE.t) - order_at(cd, p, DE.t) + + n = min(0, nc - min(0, nb)) + if not nb: + # Possible cancellation. + from .prde import parametric_log_deriv + if case == 'exp': + dcoeff = DE.d.quo(Poly(DE.t, DE.t)) + with DecrementLevel(DE): # We are guaranteed to not have problems, + # because case != 'base'. + alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t) + etaa, etad = frac_in(dcoeff, DE.t) + A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE) + if A is not None: + Q, m, z = A + if Q == 1: + n = min(n, m) + + elif case == 'tan': + dcoeff = DE.d.quo(Poly(DE.t**2+1, DE.t)) + with DecrementLevel(DE): # We are guaranteed to not have problems, + # because case != 'base'. + alphaa, alphad = frac_in(im(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t) + betaa, betad = frac_in(re(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t) + etaa, etad = frac_in(dcoeff, DE.t) + + if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE): + A = parametric_log_deriv(alphaa*Poly(sqrt(-1), DE.t)*betad+alphad*betaa, alphad*betad, etaa, etad, DE) + if A is not None: + Q, m, z = A + if Q == 1: + n = min(n, m) + N = max(0, -nb, n - nc) + pN = p**N + pn = p**-n + + A = a*pN + B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN + C = (ca*pN*pn).quo(cd) + h = pn + + # (a*p**N, (b + n*a*Dp/p)*p**N, c*p**(N - n), p**-n) + return (A, B, C, h) + + +def bound_degree(a, b, cQ, DE, case='auto', parametric=False): + """ + Bound on polynomial solutions. + + Explanation + =========== + + Given a derivation D on k[t] and ``a``, ``b``, ``c`` in k[t] with ``a != 0``, return + n in ZZ such that deg(q) <= n for any solution q in k[t] of + a*Dq + b*q == c, when parametric=False, or deg(q) <= n for any solution + c1, ..., cm in Const(k) and q in k[t] of a*Dq + b*q == Sum(ci*gi, (i, 1, m)) + when parametric=True. + + For ``parametric=False``, ``cQ`` is ``c``, a ``Poly``; for ``parametric=True``, ``cQ`` is Q == + [q1, ..., qm], a list of Polys. + + This constitutes step 3 of the outline given in the rde.py docstring. + """ + # TODO: finish writing this and write tests + + if case == 'auto': + case = DE.case + + da = a.degree(DE.t) + db = b.degree(DE.t) + + # The parametric and regular cases are identical, except for this part + if parametric: + dc = max([i.degree(DE.t) for i in cQ]) + else: + dc = cQ.degree(DE.t) + + alpha = cancel(-b.as_poly(DE.t).LC().as_expr()/ + a.as_poly(DE.t).LC().as_expr()) + + if case == 'base': + n = max(0, dc - max(db, da - 1)) + if db == da - 1 and alpha.is_Integer: + n = max(0, alpha, dc - db) + + elif case == 'primitive': + if db > da: + n = max(0, dc - db) + else: + n = max(0, dc - da + 1) + + etaa, etad = frac_in(DE.d, DE.T[DE.level - 1]) + + t1 = DE.t + with DecrementLevel(DE): + alphaa, alphad = frac_in(alpha, DE.t) + if db == da - 1: + from .prde import limited_integrate + # if alpha == m*Dt + Dz for z in k and m in ZZ: + try: + (za, zd), m = limited_integrate(alphaa, alphad, [(etaa, etad)], + DE) + except NonElementaryIntegralException: + pass + else: + if len(m) != 1: + raise ValueError("Length of m should be 1") + n = max(n, m[0]) + + elif db == da: + # if alpha == Dz/z for z in k*: + # beta = -lc(a*Dz + b*z)/(z*lc(a)) + # if beta == m*Dt + Dw for w in k and m in ZZ: + # n = max(n, m) + from .prde import is_log_deriv_k_t_radical_in_field + A = is_log_deriv_k_t_radical_in_field(alphaa, alphad, DE) + if A is not None: + aa, z = A + if aa == 1: + beta = -(a*derivation(z, DE).as_poly(t1) + + b*z.as_poly(t1)).LC()/(z.as_expr()*a.LC()) + betaa, betad = frac_in(beta, DE.t) + from .prde import limited_integrate + try: + (za, zd), m = limited_integrate(betaa, betad, + [(etaa, etad)], DE) + except NonElementaryIntegralException: + pass + else: + if len(m) != 1: + raise ValueError("Length of m should be 1") + n = max(n, m[0].as_expr()) + + elif case == 'exp': + from .prde import parametric_log_deriv + + n = max(0, dc - max(db, da)) + if da == db: + etaa, etad = frac_in(DE.d.quo(Poly(DE.t, DE.t)), DE.T[DE.level - 1]) + with DecrementLevel(DE): + alphaa, alphad = frac_in(alpha, DE.t) + A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE) + if A is not None: + # if alpha == m*Dt/t + Dz/z for z in k* and m in ZZ: + # n = max(n, m) + a, m, z = A + if a == 1: + n = max(n, m) + + elif case in ('tan', 'other_nonlinear'): + delta = DE.d.degree(DE.t) + lam = DE.d.LC() + alpha = cancel(alpha/lam) + n = max(0, dc - max(da + delta - 1, db)) + if db == da + delta - 1 and alpha.is_Integer: + n = max(0, alpha, dc - db) + + else: + raise ValueError("case must be one of {'exp', 'tan', 'primitive', " + "'other_nonlinear', 'base'}, not %s." % case) + + return n + + +def spde(a, b, c, n, DE): + """ + Rothstein's Special Polynomial Differential Equation algorithm. + + Explanation + =========== + + Given a derivation D on k[t], an integer n and ``a``,``b``,``c`` in k[t] with + ``a != 0``, either raise NonElementaryIntegralException, in which case the + equation a*Dq + b*q == c has no solution of degree at most ``n`` in + k[t], or return the tuple (B, C, m, alpha, beta) such that B, C, + alpha, beta in k[t], m in ZZ, and any solution q in k[t] of degree + at most n of a*Dq + b*q == c must be of the form + q == alpha*h + beta, where h in k[t], deg(h) <= m, and Dh + B*h == C. + + This constitutes step 4 of the outline given in the rde.py docstring. + """ + zero = Poly(0, DE.t) + + alpha = Poly(1, DE.t) + beta = Poly(0, DE.t) + + while True: + if c.is_zero: + return (zero, zero, 0, zero, beta) # -1 is more to the point + if (n < 0) is True: + raise NonElementaryIntegralException + + g = a.gcd(b) + if not c.rem(g).is_zero: # g does not divide c + raise NonElementaryIntegralException + + a, b, c = a.quo(g), b.quo(g), c.quo(g) + + if a.degree(DE.t) == 0: + b = b.to_field().quo(a) + c = c.to_field().quo(a) + return (b, c, n, alpha, beta) + + r, z = gcdex_diophantine(b, a, c) + b += derivation(a, DE) + c = z - derivation(r, DE) + n -= a.degree(DE.t) + + beta += alpha * r + alpha *= a + +def no_cancel_b_large(b, c, n, DE): + """ + Poly Risch Differential Equation - No cancellation: deg(b) large enough. + + Explanation + =========== + + Given a derivation D on k[t], ``n`` either an integer or +oo, and ``b``,``c`` + in k[t] with ``b != 0`` and either D == d/dt or + deg(b) > max(0, deg(D) - 1), either raise NonElementaryIntegralException, in + which case the equation ``Dq + b*q == c`` has no solution of degree at + most n in k[t], or a solution q in k[t] of this equation with + ``deg(q) < n``. + """ + q = Poly(0, DE.t) + + while not c.is_zero: + m = c.degree(DE.t) - b.degree(DE.t) + if not 0 <= m <= n: # n < 0 or m < 0 or m > n + raise NonElementaryIntegralException + + p = Poly(c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC()*DE.t**m, DE.t, + expand=False) + q = q + p + n = m - 1 + c = c - derivation(p, DE) - b*p + + return q + + +def no_cancel_b_small(b, c, n, DE): + """ + Poly Risch Differential Equation - No cancellation: deg(b) small enough. + + Explanation + =========== + + Given a derivation D on k[t], ``n`` either an integer or +oo, and ``b``,``c`` + in k[t] with deg(b) < deg(D) - 1 and either D == d/dt or + deg(D) >= 2, either raise NonElementaryIntegralException, in which case the + equation Dq + b*q == c has no solution of degree at most n in k[t], + or a solution q in k[t] of this equation with deg(q) <= n, or the + tuple (h, b0, c0) such that h in k[t], b0, c0, in k, and for any + solution q in k[t] of degree at most n of Dq + bq == c, y == q - h + is a solution in k of Dy + b0*y == c0. + """ + q = Poly(0, DE.t) + + while not c.is_zero: + if n == 0: + m = 0 + else: + m = c.degree(DE.t) - DE.d.degree(DE.t) + 1 + + if not 0 <= m <= n: # n < 0 or m < 0 or m > n + raise NonElementaryIntegralException + + if m > 0: + p = Poly(c.as_poly(DE.t).LC()/(m*DE.d.as_poly(DE.t).LC())*DE.t**m, + DE.t, expand=False) + else: + if b.degree(DE.t) != c.degree(DE.t): + raise NonElementaryIntegralException + if b.degree(DE.t) == 0: + return (q, b.as_poly(DE.T[DE.level - 1]), + c.as_poly(DE.T[DE.level - 1])) + p = Poly(c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC(), DE.t, + expand=False) + + q = q + p + n = m - 1 + c = c - derivation(p, DE) - b*p + + return q + + +# TODO: better name for this function +def no_cancel_equal(b, c, n, DE): + """ + Poly Risch Differential Equation - No cancellation: deg(b) == deg(D) - 1 + + Explanation + =========== + + Given a derivation D on k[t] with deg(D) >= 2, n either an integer + or +oo, and b, c in k[t] with deg(b) == deg(D) - 1, either raise + NonElementaryIntegralException, in which case the equation Dq + b*q == c has + no solution of degree at most n in k[t], or a solution q in k[t] of + this equation with deg(q) <= n, or the tuple (h, m, C) such that h + in k[t], m in ZZ, and C in k[t], and for any solution q in k[t] of + degree at most n of Dq + b*q == c, y == q - h is a solution in k[t] + of degree at most m of Dy + b*y == C. + """ + q = Poly(0, DE.t) + lc = cancel(-b.as_poly(DE.t).LC()/DE.d.as_poly(DE.t).LC()) + if lc.is_Integer and lc.is_positive: + M = lc + else: + M = -1 + + while not c.is_zero: + m = max(M, c.degree(DE.t) - DE.d.degree(DE.t) + 1) + + if not 0 <= m <= n: # n < 0 or m < 0 or m > n + raise NonElementaryIntegralException + + u = cancel(m*DE.d.as_poly(DE.t).LC() + b.as_poly(DE.t).LC()) + if u.is_zero: + return (q, m, c) + if m > 0: + p = Poly(c.as_poly(DE.t).LC()/u*DE.t**m, DE.t, expand=False) + else: + if c.degree(DE.t) != DE.d.degree(DE.t) - 1: + raise NonElementaryIntegralException + else: + p = c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC() + + q = q + p + n = m - 1 + c = c - derivation(p, DE) - b*p + + return q + + +def cancel_primitive(b, c, n, DE): + """ + Poly Risch Differential Equation - Cancellation: Primitive case. + + Explanation + =========== + + Given a derivation D on k[t], n either an integer or +oo, ``b`` in k, and + ``c`` in k[t] with Dt in k and ``b != 0``, either raise + NonElementaryIntegralException, in which case the equation Dq + b*q == c + has no solution of degree at most n in k[t], or a solution q in k[t] of + this equation with deg(q) <= n. + """ + # Delayed imports + from .prde import is_log_deriv_k_t_radical_in_field + with DecrementLevel(DE): + ba, bd = frac_in(b, DE.t) + A = is_log_deriv_k_t_radical_in_field(ba, bd, DE) + if A is not None: + n, z = A + if n == 1: # b == Dz/z + raise NotImplementedError("is_deriv_in_field() is required to " + " solve this problem.") + # if z*c == Dp for p in k[t] and deg(p) <= n: + # return p/z + # else: + # raise NonElementaryIntegralException + + if c.is_zero: + return c # return 0 + + if n < c.degree(DE.t): + raise NonElementaryIntegralException + + q = Poly(0, DE.t) + while not c.is_zero: + m = c.degree(DE.t) + if n < m: + raise NonElementaryIntegralException + with DecrementLevel(DE): + a2a, a2d = frac_in(c.LC(), DE.t) + sa, sd = rischDE(ba, bd, a2a, a2d, DE) + stm = Poly(sa.as_expr()/sd.as_expr()*DE.t**m, DE.t, expand=False) + q += stm + n = m - 1 + c -= b*stm + derivation(stm, DE) + + return q + + +def cancel_exp(b, c, n, DE): + """ + Poly Risch Differential Equation - Cancellation: Hyperexponential case. + + Explanation + =========== + + Given a derivation D on k[t], n either an integer or +oo, ``b`` in k, and + ``c`` in k[t] with Dt/t in k and ``b != 0``, either raise + NonElementaryIntegralException, in which case the equation Dq + b*q == c + has no solution of degree at most n in k[t], or a solution q in k[t] of + this equation with deg(q) <= n. + """ + from .prde import parametric_log_deriv + eta = DE.d.quo(Poly(DE.t, DE.t)).as_expr() + + with DecrementLevel(DE): + etaa, etad = frac_in(eta, DE.t) + ba, bd = frac_in(b, DE.t) + A = parametric_log_deriv(ba, bd, etaa, etad, DE) + if A is not None: + a, m, z = A + if a == 1: + raise NotImplementedError("is_deriv_in_field() is required to " + "solve this problem.") + # if c*z*t**m == Dp for p in k and q = p/(z*t**m) in k[t] and + # deg(q) <= n: + # return q + # else: + # raise NonElementaryIntegralException + + if c.is_zero: + return c # return 0 + + if n < c.degree(DE.t): + raise NonElementaryIntegralException + + q = Poly(0, DE.t) + while not c.is_zero: + m = c.degree(DE.t) + if n < m: + raise NonElementaryIntegralException + # a1 = b + m*Dt/t + a1 = b.as_expr() + with DecrementLevel(DE): + # TODO: Write a dummy function that does this idiom + a1a, a1d = frac_in(a1, DE.t) + a1a = a1a*etad + etaa*a1d*Poly(m, DE.t) + a1d = a1d*etad + + a2a, a2d = frac_in(c.LC(), DE.t) + + sa, sd = rischDE(a1a, a1d, a2a, a2d, DE) + stm = Poly(sa.as_expr()/sd.as_expr()*DE.t**m, DE.t, expand=False) + q += stm + n = m - 1 + c -= b*stm + derivation(stm, DE) # deg(c) becomes smaller + return q + + +def solve_poly_rde(b, cQ, n, DE, parametric=False): + """ + Solve a Polynomial Risch Differential Equation with degree bound ``n``. + + This constitutes step 4 of the outline given in the rde.py docstring. + + For parametric=False, cQ is c, a Poly; for parametric=True, cQ is Q == + [q1, ..., qm], a list of Polys. + """ + # No cancellation + if not b.is_zero and (DE.case == 'base' or + b.degree(DE.t) > max(0, DE.d.degree(DE.t) - 1)): + + if parametric: + # Delayed imports + from .prde import prde_no_cancel_b_large + return prde_no_cancel_b_large(b, cQ, n, DE) + return no_cancel_b_large(b, cQ, n, DE) + + elif (b.is_zero or b.degree(DE.t) < DE.d.degree(DE.t) - 1) and \ + (DE.case == 'base' or DE.d.degree(DE.t) >= 2): + + if parametric: + from .prde import prde_no_cancel_b_small + return prde_no_cancel_b_small(b, cQ, n, DE) + + R = no_cancel_b_small(b, cQ, n, DE) + + if isinstance(R, Poly): + return R + else: + # XXX: Might k be a field? (pg. 209) + h, b0, c0 = R + with DecrementLevel(DE): + b0, c0 = b0.as_poly(DE.t), c0.as_poly(DE.t) + if b0 is None: # See above comment + raise ValueError("b0 should be a non-Null value") + if c0 is None: + raise ValueError("c0 should be a non-Null value") + y = solve_poly_rde(b0, c0, n, DE).as_poly(DE.t) + return h + y + + elif DE.d.degree(DE.t) >= 2 and b.degree(DE.t) == DE.d.degree(DE.t) - 1 and \ + n > -b.as_poly(DE.t).LC()/DE.d.as_poly(DE.t).LC(): + + # TODO: Is this check necessary, and if so, what should it do if it fails? + # b comes from the first element returned from spde() + if not b.as_poly(DE.t).LC().is_number: + raise TypeError("Result should be a number") + + if parametric: + raise NotImplementedError("prde_no_cancel_b_equal() is not yet " + "implemented.") + + R = no_cancel_equal(b, cQ, n, DE) + + if isinstance(R, Poly): + return R + else: + h, m, C = R + # XXX: Or should it be rischDE()? + y = solve_poly_rde(b, C, m, DE) + return h + y + + else: + # Cancellation + if b.is_zero: + raise NotImplementedError("Remaining cases for Poly (P)RDE are " + "not yet implemented (is_deriv_in_field() required).") + else: + if DE.case == 'exp': + if parametric: + raise NotImplementedError("Parametric RDE cancellation " + "hyperexponential case is not yet implemented.") + return cancel_exp(b, cQ, n, DE) + + elif DE.case == 'primitive': + if parametric: + raise NotImplementedError("Parametric RDE cancellation " + "primitive case is not yet implemented.") + return cancel_primitive(b, cQ, n, DE) + + else: + raise NotImplementedError("Other Poly (P)RDE cancellation " + "cases are not yet implemented (%s)." % DE.case) + + if parametric: + raise NotImplementedError("Remaining cases for Poly PRDE not yet " + "implemented.") + raise NotImplementedError("Remaining cases for Poly RDE not yet " + "implemented.") + + +def rischDE(fa, fd, ga, gd, DE): + """ + Solve a Risch Differential Equation: Dy + f*y == g. + + Explanation + =========== + + See the outline in the docstring of rde.py for more information + about the procedure used. Either raise NonElementaryIntegralException, in + which case there is no solution y in the given differential field, + or return y in k(t) satisfying Dy + f*y == g, or raise + NotImplementedError, in which case, the algorithms necessary to + solve the given Risch Differential Equation have not yet been + implemented. + """ + _, (fa, fd) = weak_normalizer(fa, fd, DE) + a, (ba, bd), (ca, cd), hn = normal_denom(fa, fd, ga, gd, DE) + A, B, C, hs = special_denom(a, ba, bd, ca, cd, DE) + try: + # Until this is fully implemented, use oo. Note that this will almost + # certainly cause non-termination in spde() (unless A == 1), and + # *might* lead to non-termination in the next step for a nonelementary + # integral (I don't know for certain yet). Fortunately, spde() is + # currently written recursively, so this will just give + # RuntimeError: maximum recursion depth exceeded. + n = bound_degree(A, B, C, DE) + except NotImplementedError: + # Useful for debugging: + # import warnings + # warnings.warn("rischDE: Proceeding with n = oo; may cause " + # "non-termination.") + n = oo + + B, C, m, alpha, beta = spde(A, B, C, n, DE) + if C.is_zero: + y = C + else: + y = solve_poly_rde(B, C, m, DE) + + return (alpha*y + beta, hn*hs) diff --git a/shared/package-files/02/02eb303b89f622472d77156cbe99aafe57e4089bcc4fb0886a5fd4fdb43be3c2/binary_constrict.csv b/shared/package-files/02/02eb303b89f622472d77156cbe99aafe57e4089bcc4fb0886a5fd4fdb43be3c2/binary_constrict.csv new file mode 100644 index 0000000000000000000000000000000000000000..76087073d3144e7a83c394902cd9db8931ca33ce --- /dev/null +++ b/shared/package-files/02/02eb303b89f622472d77156cbe99aafe57e4089bcc4fb0886a5fd4fdb43be3c2/binary_constrict.csv @@ -0,0 +1,40 @@ +Case,diagnosis,rate,volumne,constrict,const,log_rate,log_volumne +1,constrict,0.825,3.7,1,1.0,-0.19237189264745613,1.308332819650179 +2,constrict,1.09,3.5,1,1.0,0.08617769624105241,1.252762968495368 +3,constrict,2.5,1.25,1,1.0,0.9162907318741551,0.22314355131420976 +4,constrict,1.5,0.75,1,1.0,0.4054651081081644,-0.2876820724517809 +5,constrict,3.2,0.8,1,1.0,1.1631508098056809,-0.2231435513142097 +6,constrict,3.5,0.7,1,1.0,1.252762968495368,-0.35667494393873245 +7,no_constrict,0.75,0.6,0,1.0,-0.2876820724517809,-0.5108256237659907 +8,no_constrict,1.7,1.1,0,1.0,0.5306282510621704,0.09531017980432493 +9,no_constrict,0.75,0.9,0,1.0,-0.2876820724517809,-0.10536051565782628 +10,no_constrict,0.45,0.9,0,1.0,-0.7985076962177716,-0.10536051565782628 +11,no_constrict,0.57,0.8,0,1.0,-0.5621189181535413,-0.2231435513142097 +12,no_constrict,2.75,0.55,0,1.0,1.0116009116784799,-0.5978370007556204 +13,no_constrict,3.0,0.6,0,1.0,1.0986122886681098,-0.5108256237659907 +14,constrict,2.33,1.4,1,1.0,0.8458682675776092,0.3364722366212129 +15,constrict,3.75,0.75,1,1.0,1.3217558399823195,-0.2876820724517809 +16,constrict,1.64,2.3,1,1.0,0.494696241836107,0.8329091229351039 +17,constrict,1.6,3.2,1,1.0,0.47000362924573563,1.1631508098056809 +18,constrict,1.415,0.85,1,1.0,0.34712953109520095,-0.16251892949777494 +19,no_constrict,1.06,1.7,0,1.0,0.058268908123975824,0.5306282510621704 +20,constrict,1.8,1.8,1,1.0,0.5877866649021191,0.5877866649021191 +21,no_constrict,2.0,0.4,0,1.0,0.6931471805599453,-0.916290731874155 +22,no_constrict,1.36,0.95,0,1.0,0.3074846997479607,-0.05129329438755058 +23,no_constrict,1.35,1.35,0,1.0,0.30010459245033816,0.30010459245033816 +24,no_constrict,1.36,1.5,0,1.0,0.3074846997479607,0.4054651081081644 +25,constrict,1.78,1.6,1,1.0,0.5766133643039938,0.47000362924573563 +26,no_constrict,1.5,0.6,0,1.0,0.4054651081081644,-0.5108256237659907 +27,constrict,1.5,1.8,1,1.0,0.4054651081081644,0.5877866649021191 +28,no_constrict,1.9,0.95,0,1.0,0.6418538861723947,-0.05129329438755058 +29,constrict,0.95,1.9,1,1.0,-0.05129329438755058,0.6418538861723947 +30,no_constrict,0.4,1.6,0,1.0,-0.916290731874155,0.47000362924573563 +31,constrict,0.75,2.7,1,1.0,-0.2876820724517809,0.9932517730102834 +32,no_constrict,0.03,2.35,0,1.0,-3.506557897319982,0.8544153281560676 +33,no_constrict,1.83,1.1,0,1.0,0.6043159668533296,0.09531017980432493 +34,constrict,2.2,1.1,1,1.0,0.7884573603642703,0.09531017980432493 +35,constrict,2.0,1.2,1,1.0,0.6931471805599453,0.1823215567939546 +36,constrict,3.33,0.8,1,1.0,1.2029723039923526,-0.2231435513142097 +37,no_constrict,1.9,0.95,0,1.0,0.6418538861723947,-0.05129329438755058 +38,no_constrict,1.9,0.75,0,1.0,0.6418538861723947,-0.2876820724517809 +39,constrict,1.625,1.3,1,1.0,0.4855078157817008,0.26236426446749106 diff --git a/shared/package-files/02/02eccac8c13cfa51aeb31856370f86cb88b93a22b9f0151fdf8d46ac9c08bda7/BlpImagePlugin.py b/shared/package-files/02/02eccac8c13cfa51aeb31856370f86cb88b93a22b9f0151fdf8d46ac9c08bda7/BlpImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f38b78a2ee18853e9f6553d74b033e6947afb2 --- /dev/null +++ b/shared/package-files/02/02eccac8c13cfa51aeb31856370f86cb88b93a22b9f0151fdf8d46ac9c08bda7/BlpImagePlugin.py @@ -0,0 +1,475 @@ +""" +Blizzard Mipmap Format (.blp) +Jerome Leclanche + +The contents of this file are hereby released in the public domain (CC0) +Full text of the CC0 license: + https://creativecommons.org/publicdomain/zero/1.0/ + +BLP1 files, used mostly in Warcraft III, are not fully supported. +All types of BLP2 files used in World of Warcraft are supported. + +The BLP file structure consists of a header, up to 16 mipmaps of the +texture + +Texture sizes must be powers of two, though the two dimensions do +not have to be equal; 512x256 is valid, but 512x200 is not. +The first mipmap (mipmap #0) is the full size image; each subsequent +mipmap halves both dimensions. The final mipmap should be 1x1. + +BLP files come in many different flavours: +* JPEG-compressed (type == 0) - only supported for BLP1. +* RAW images (type == 1, encoding == 1). Each mipmap is stored as an + array of 8-bit values, one per pixel, left to right, top to bottom. + Each value is an index to the palette. +* DXT-compressed (type == 1, encoding == 2): +- DXT1 compression is used if alpha_encoding == 0. + - An additional alpha bit is used if alpha_depth == 1. + - DXT3 compression is used if alpha_encoding == 1. + - DXT5 compression is used if alpha_encoding == 7. +""" +from __future__ import annotations + +import os +import struct +from enum import IntEnum +from io import BytesIO + +from . import Image, ImageFile + + +class Format(IntEnum): + JPEG = 0 + + +class Encoding(IntEnum): + UNCOMPRESSED = 1 + DXT = 2 + UNCOMPRESSED_RAW_BGRA = 3 + + +class AlphaEncoding(IntEnum): + DXT1 = 0 + DXT3 = 1 + DXT5 = 7 + + +def unpack_565(i): + return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3 + + +def decode_dxt1(data, alpha=False): + """ + input: one "row" of data (i.e. will produce 4*width pixels) + """ + + blocks = len(data) // 8 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block in range(blocks): + # Decode next 8-byte block. + idx = block * 8 + color0, color1, bits = struct.unpack_from("> 2 + + a = 0xFF + if control == 0: + r, g, b = r0, g0, b0 + elif control == 1: + r, g, b = r1, g1, b1 + elif control == 2: + if color0 > color1: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + else: + r = (r0 + r1) // 2 + g = (g0 + g1) // 2 + b = (b0 + b1) // 2 + elif control == 3: + if color0 > color1: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + else: + r, g, b, a = 0, 0, 0, 0 + + if alpha: + ret[j].extend([r, g, b, a]) + else: + ret[j].extend([r, g, b]) + + return ret + + +def decode_dxt3(data): + """ + input: one "row" of data (i.e. will produce 4*width pixels) + """ + + blocks = len(data) // 16 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block in range(blocks): + idx = block * 16 + block = data[idx : idx + 16] + # Decode next 16-byte block. + bits = struct.unpack_from("<8B", block) + color0, color1 = struct.unpack_from(">= 4 + else: + high = True + a &= 0xF + a *= 17 # We get a value between 0 and 15 + + color_code = (code >> 2 * (4 * j + i)) & 0x03 + + if color_code == 0: + r, g, b = r0, g0, b0 + elif color_code == 1: + r, g, b = r1, g1, b1 + elif color_code == 2: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + elif color_code == 3: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + + ret[j].extend([r, g, b, a]) + + return ret + + +def decode_dxt5(data): + """ + input: one "row" of data (i.e. will produce 4 * width pixels) + """ + + blocks = len(data) // 16 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block in range(blocks): + idx = block * 16 + block = data[idx : idx + 16] + # Decode next 16-byte block. + a0, a1 = struct.unpack_from("> alphacode_index) & 0x07 + elif alphacode_index == 15: + alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06) + else: # alphacode_index >= 18 and alphacode_index <= 45 + alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07 + + if alphacode == 0: + a = a0 + elif alphacode == 1: + a = a1 + elif a0 > a1: + a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7 + elif alphacode == 6: + a = 0 + elif alphacode == 7: + a = 255 + else: + a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5 + + color_code = (code >> 2 * (4 * j + i)) & 0x03 + + if color_code == 0: + r, g, b = r0, g0, b0 + elif color_code == 1: + r, g, b = r1, g1, b1 + elif color_code == 2: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + elif color_code == 3: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + + ret[j].extend([r, g, b, a]) + + return ret + + +class BLPFormatError(NotImplementedError): + pass + + +def _accept(prefix): + return prefix[:4] in (b"BLP1", b"BLP2") + + +class BlpImageFile(ImageFile.ImageFile): + """ + Blizzard Mipmap Format + """ + + format = "BLP" + format_description = "Blizzard Mipmap Format" + + def _open(self): + self.magic = self.fp.read(4) + + self.fp.seek(5, os.SEEK_CUR) + (self._blp_alpha_depth,) = struct.unpack(" +#include + +namespace at { namespace native { + +using stack_serial_fn = void(*)(Tensor &, TensorList, int64_t); +DECLARE_DISPATCH(stack_serial_fn, stack_serial_stub); + +}} // namespace at::native diff --git a/shared/package-files/02/02ef0a7bb467c712d9435fa1d45c7af35f9cecb0f55f259c22ad97dc05181af3/record_stream.h b/shared/package-files/02/02ef0a7bb467c712d9435fa1d45c7af35f9cecb0f55f259c22ad97dc05181af3/record_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..5d4f573d05fe2c1ae9ba6db2e5551dbe38cd9228 --- /dev/null +++ b/shared/package-files/02/02ef0a7bb467c712d9435fa1d45c7af35f9cecb0f55f259c22ad97dc05181af3/record_stream.h @@ -0,0 +1,26 @@ +#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 { + + + +} diff --git a/shared/package-files/02/02ef511df46e7e92349e04f84742b409456d00c162f4183e6210ee9e58ff2e4a/backend_nbagg.py b/shared/package-files/02/02ef511df46e7e92349e04f84742b409456d00c162f4183e6210ee9e58ff2e4a/backend_nbagg.py new file mode 100644 index 0000000000000000000000000000000000000000..4d18e1e9fb88bd89cf5146d2c3f48bf3a54c9bca --- /dev/null +++ b/shared/package-files/02/02ef511df46e7e92349e04f84742b409456d00c162f4183e6210ee9e58ff2e4a/backend_nbagg.py @@ -0,0 +1,243 @@ +"""Interactive figures in the IPython notebook.""" +# Note: There is a notebook in +# lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify +# that changes made maintain expected behaviour. + +from base64 import b64encode +import io +import json +import pathlib +import uuid + +from ipykernel.comm import Comm +from IPython.display import display, Javascript, HTML + +from matplotlib import is_interactive +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2 +from .backend_webagg_core import ( + FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg) +from .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611 + TimerTornado, TimerAsyncio) + + +def connection_info(): + """ + Return a string showing the figure and connection status for the backend. + + This is intended as a diagnostic tool, and not for general use. + """ + result = [ + '{fig} - {socket}'.format( + fig=(manager.canvas.figure.get_label() + or f"Figure {manager.num}"), + socket=manager.web_sockets) + for manager in Gcf.get_all_fig_managers() + ] + if not is_interactive(): + result.append(f'Figures pending show: {len(Gcf.figs)}') + return '\n'.join(result) + + +_FONT_AWESOME_CLASSES = { # font-awesome 4 names + 'home': 'fa fa-home', + 'back': 'fa fa-arrow-left', + 'forward': 'fa fa-arrow-right', + 'zoom_to_rect': 'fa fa-square-o', + 'move': 'fa fa-arrows', + 'download': 'fa fa-floppy-o', + None: None +} + + +class NavigationIPy(NavigationToolbar2WebAgg): + + # Use the standard toolbar items + download button + toolitems = [(text, tooltip_text, + _FONT_AWESOME_CLASSES[image_file], name_of_method) + for text, tooltip_text, image_file, name_of_method + in (NavigationToolbar2.toolitems + + (('Download', 'Download plot', 'download', 'download'),)) + if image_file in _FONT_AWESOME_CLASSES] + + +class FigureManagerNbAgg(FigureManagerWebAgg): + _toolbar2_class = ToolbarCls = NavigationIPy + + def __init__(self, canvas, num): + self._shown = False + super().__init__(canvas, num) + + @classmethod + def create_with_canvas(cls, canvas_class, figure, num): + canvas = canvas_class(figure) + manager = cls(canvas, num) + if is_interactive(): + manager.show() + canvas.draw_idle() + + def destroy(event): + canvas.mpl_disconnect(cid) + Gcf.destroy(manager) + + cid = canvas.mpl_connect('close_event', destroy) + return manager + + def display_js(self): + # XXX How to do this just once? It has to deal with multiple + # browser instances using the same kernel (require.js - but the + # file isn't static?). + display(Javascript(FigureManagerNbAgg.get_javascript())) + + def show(self): + if not self._shown: + self.display_js() + self._create_comm() + else: + self.canvas.draw_idle() + self._shown = True + # plt.figure adds an event which makes the figure in focus the active + # one. Disable this behaviour, as it results in figures being put as + # the active figure after they have been shown, even in non-interactive + # mode. + if hasattr(self, '_cidgcf'): + self.canvas.mpl_disconnect(self._cidgcf) + if not is_interactive(): + from matplotlib._pylab_helpers import Gcf + Gcf.figs.pop(self.num, None) + + def reshow(self): + """ + A special method to re-show the figure in the notebook. + + """ + self._shown = False + self.show() + + @property + def connected(self): + return bool(self.web_sockets) + + @classmethod + def get_javascript(cls, stream=None): + if stream is None: + output = io.StringIO() + else: + output = stream + super().get_javascript(stream=output) + output.write((pathlib.Path(__file__).parent + / "web_backend/js/nbagg_mpl.js") + .read_text(encoding="utf-8")) + if stream is None: + return output.getvalue() + + def _create_comm(self): + comm = CommSocket(self) + self.add_web_socket(comm) + return comm + + def destroy(self): + self._send_event('close') + # need to copy comms as callbacks will modify this list + for comm in list(self.web_sockets): + comm.on_close() + self.clearup_closed() + + def clearup_closed(self): + """Clear up any closed Comms.""" + self.web_sockets = {socket for socket in self.web_sockets + if socket.is_open()} + + if len(self.web_sockets) == 0: + CloseEvent("close_event", self.canvas)._process() + + def remove_comm(self, comm_id): + self.web_sockets = {socket for socket in self.web_sockets + if socket.comm.comm_id != comm_id} + + +class FigureCanvasNbAgg(FigureCanvasWebAggCore): + manager_class = FigureManagerNbAgg + + +class CommSocket: + """ + Manages the Comm connection between IPython and the browser (client). + + Comms are 2 way, with the CommSocket being able to publish a message + via the send_json method, and handle a message with on_message. On the + JS side figure.send_message and figure.ws.onmessage do the sending and + receiving respectively. + + """ + def __init__(self, manager): + self.supports_binary = None + self.manager = manager + self.uuid = str(uuid.uuid4()) + # Publish an output area with a unique ID. The javascript can then + # hook into this area. + display(HTML("
" % self.uuid)) + try: + self.comm = Comm('matplotlib', data={'id': self.uuid}) + except AttributeError as err: + raise RuntimeError('Unable to create an IPython notebook Comm ' + 'instance. Are you in the IPython ' + 'notebook?') from err + self.comm.on_msg(self.on_message) + + manager = self.manager + self._ext_close = False + + def _on_close(close_message): + self._ext_close = True + manager.remove_comm(close_message['content']['comm_id']) + manager.clearup_closed() + + self.comm.on_close(_on_close) + + def is_open(self): + return not (self._ext_close or self.comm._closed) + + def on_close(self): + # When the socket is closed, deregister the websocket with + # the FigureManager. + if self.is_open(): + try: + self.comm.close() + except KeyError: + # apparently already cleaned it up? + pass + + def send_json(self, content): + self.comm.send({'data': json.dumps(content)}) + + def send_binary(self, blob): + if self.supports_binary: + self.comm.send({'blob': 'image/png'}, buffers=[blob]) + else: + # The comm is ASCII, so we send the image in base64 encoded data + # URL form. + data = b64encode(blob).decode('ascii') + data_uri = f"data:image/png;base64,{data}" + self.comm.send({'data': data_uri}) + + def on_message(self, message): + # The 'supports_binary' message is relevant to the + # websocket itself. The other messages get passed along + # to matplotlib as-is. + + # Every message has a "type" and a "figure_id". + message = json.loads(message['content']['data']) + if message['type'] == 'closing': + self.on_close() + self.manager.clearup_closed() + elif message['type'] == 'supports_binary': + self.supports_binary = message['value'] + else: + self.manager.handle_json(message) + + +@_Backend.export +class _BackendNbAgg(_Backend): + FigureCanvas = FigureCanvasNbAgg + FigureManager = FigureManagerNbAgg diff --git a/shared/package-files/02/02f02348a288d500399fd9a24bd0dee66093e818d5308c5e226c07fb01d67fe9/erf_cpu_dispatch.h b/shared/package-files/02/02f02348a288d500399fd9a24bd0dee66093e818d5308c5e226c07fb01d67fe9/erf_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b30469b8d7f1b86ce805ae7e744ba678b93db520 --- /dev/null +++ b/shared/package-files/02/02f02348a288d500399fd9a24bd0dee66093e818d5308c5e226c07fb01d67fe9/erf_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 erf(const at::Tensor & self); +TORCH_API at::Tensor & erf_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & erf_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & erf_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/02/02f469df40ed6892bd37952ccce327d383dba7bbbd67b1cfaea6a2616c4da0fa/_upsample_bicubic2d_aa_meta_dispatch.h b/shared/package-files/02/02f469df40ed6892bd37952ccce327d383dba7bbbd67b1cfaea6a2616c4da0fa/_upsample_bicubic2d_aa_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..030f463b2347802cb42dd2feeba397c77cc42666 --- /dev/null +++ b/shared/package-files/02/02f469df40ed6892bd37952ccce327d383dba7bbbd67b1cfaea6a2616c4da0fa/_upsample_bicubic2d_aa_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_bicubic2d_aa(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor _upsample_bicubic2d_aa_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/02/02f58e67180302a12b805c24735b36c1532877c8f8941bf91f8696e972106419/WrapFunctionIntoFunctor.h b/shared/package-files/02/02f58e67180302a12b805c24735b36c1532877c8f8941bf91f8696e972106419/WrapFunctionIntoFunctor.h new file mode 100644 index 0000000000000000000000000000000000000000..c8d7687cde3f74348ad1f73deacc2af1d03c8da9 --- /dev/null +++ b/shared/package-files/02/02f58e67180302a12b805c24735b36c1532877c8f8941bf91f8696e972106419/WrapFunctionIntoFunctor.h @@ -0,0 +1,32 @@ +#pragma once + +#include + +namespace c10 { +namespace impl { + namespace detail { + template class WrapFunctionIntoFunctor_ {}; + template + class WrapFunctionIntoFunctor_> final : public c10::OperatorKernel { + public: + C10_ALWAYS_INLINE decltype(auto) operator()(Parameters... args) { + return (*FuncPtr::func_ptr())(std::forward(args)...); + } + }; + } + + // WrapFunctionIntoFunctor: Wraps a compile time function pointer into a kernel functor. + // Since it is a compile time function pointer, many compilers can inline it + // into the wrapper and you don't get any performance overhead for wrapping. + template + struct WrapFunctionIntoFunctor final { + static_assert(c10::is_compile_time_function_pointer::value, "WrapFunctionIntoFunctor can only wrap functions created with TORCH_FN."); + using type = detail::WrapFunctionIntoFunctor_< + FuncPtr, + typename guts::function_traits::return_type, + typename guts::function_traits::parameter_types + >; + }; +} + +} diff --git a/shared/package-files/02/02f9c5012398110268a8d9983fae2e4b958a7b443d8889727441b960e5e64c01/frobenius_norm_ops.h b/shared/package-files/02/02f9c5012398110268a8d9983fae2e4b958a7b443d8889727441b960e5e64c01/frobenius_norm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..75a9fed675d8c191464e5d3d0ccf742309e189e8 --- /dev/null +++ b/shared/package-files/02/02f9c5012398110268a8d9983fae2e4b958a7b443d8889727441b960e5e64c01/frobenius_norm_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 frobenius_norm_dim { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::frobenius_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "frobenius_norm.dim(Tensor self, int[1] dim, bool keepdim=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim); +}; + +struct TORCH_API frobenius_norm_out { + using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, 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::frobenius_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "frobenius_norm.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/02/02fb2a311e58ad50250057e12f49471c06486b35e7cc8d5592856e3ee88312ba/test_rolling_quantile.py b/shared/package-files/02/02fb2a311e58ad50250057e12f49471c06486b35e7cc8d5592856e3ee88312ba/test_rolling_quantile.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a7010923563c99b335fd9a309a1d8762d21651 --- /dev/null +++ b/shared/package-files/02/02fb2a311e58ad50250057e12f49471c06486b35e7cc8d5592856e3ee88312ba/test_rolling_quantile.py @@ -0,0 +1,182 @@ +from functools import partial + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Series, + concat, + isna, + notna, +) +import pandas._testing as tm + +from pandas.tseries import offsets + + +def scoreatpercentile(a, per): + values = np.sort(a, axis=0) + + idx = int(per / 1.0 * (values.shape[0] - 1)) + + if idx == values.shape[0] - 1: + retval = values[-1] + + else: + qlow = idx / (values.shape[0] - 1) + qhig = (idx + 1) / (values.shape[0] - 1) + vlow = values[idx] + vhig = values[idx + 1] + retval = vlow + (vhig - vlow) * (per - qlow) / (qhig - qlow) + + return retval + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_series(series, q, step): + compare_func = partial(scoreatpercentile, per=q) + result = series.rolling(50, step=step).quantile(q) + assert isinstance(result, Series) + end = range(0, len(series), step or 1)[-1] + 1 + tm.assert_almost_equal(result.iloc[-1], compare_func(series[end - 50 : end])) + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_frame(raw, frame, q, step): + compare_func = partial(scoreatpercentile, per=q) + result = frame.rolling(50, step=step).quantile(q) + assert isinstance(result, DataFrame) + end = range(0, len(frame), step or 1)[-1] + 1 + tm.assert_series_equal( + result.iloc[-1, :], + frame.iloc[end - 50 : end, :].apply(compare_func, axis=0, raw=raw), + check_names=False, + ) + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_time_rule_series(series, q): + compare_func = partial(scoreatpercentile, per=q) + win = 25 + ser = series[::2].resample("B").mean() + series_result = ser.rolling(window=win, min_periods=10).quantile(q) + last_date = series_result.index[-1] + prev_date = last_date - 24 * offsets.BDay() + + trunc_series = series[::2].truncate(prev_date, last_date) + tm.assert_almost_equal(series_result.iloc[-1], compare_func(trunc_series)) + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_time_rule_frame(raw, frame, q): + compare_func = partial(scoreatpercentile, per=q) + win = 25 + frm = frame[::2].resample("B").mean() + frame_result = frm.rolling(window=win, min_periods=10).quantile(q) + last_date = frame_result.index[-1] + prev_date = last_date - 24 * offsets.BDay() + + trunc_frame = frame[::2].truncate(prev_date, last_date) + tm.assert_series_equal( + frame_result.xs(last_date), + trunc_frame.apply(compare_func, raw=raw), + check_names=False, + ) + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_nans(q): + compare_func = partial(scoreatpercentile, per=q) + obj = Series(np.random.default_rng(2).standard_normal(50)) + obj[:10] = np.nan + obj[-10:] = np.nan + + result = obj.rolling(50, min_periods=30).quantile(q) + tm.assert_almost_equal(result.iloc[-1], compare_func(obj[10:-10])) + + # min_periods is working correctly + result = obj.rolling(20, min_periods=15).quantile(q) + assert isna(result.iloc[23]) + assert not isna(result.iloc[24]) + + assert not isna(result.iloc[-6]) + assert isna(result.iloc[-5]) + + obj2 = Series(np.random.default_rng(2).standard_normal(20)) + result = obj2.rolling(10, min_periods=5).quantile(q) + assert isna(result.iloc[3]) + assert notna(result.iloc[4]) + + result0 = obj.rolling(20, min_periods=0).quantile(q) + result1 = obj.rolling(20, min_periods=1).quantile(q) + tm.assert_almost_equal(result0, result1) + + +@pytest.mark.parametrize("minp", [0, 99, 100]) +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_min_periods(series, minp, q, step): + result = series.rolling(len(series) + 1, min_periods=minp, step=step).quantile(q) + expected = series.rolling(len(series), min_periods=minp, step=step).quantile(q) + nan_mask = isna(result) + tm.assert_series_equal(nan_mask, isna(expected)) + + nan_mask = ~nan_mask + tm.assert_almost_equal(result[nan_mask], expected[nan_mask]) + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_center(q): + obj = Series(np.random.default_rng(2).standard_normal(50)) + obj[:10] = np.nan + obj[-10:] = np.nan + + result = obj.rolling(20, center=True).quantile(q) + expected = ( + concat([obj, Series([np.nan] * 9)]) + .rolling(20) + .quantile(q) + .iloc[9:] + .reset_index(drop=True) + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_center_reindex_series(series, q): + # shifter index + s = [f"x{x:d}" for x in range(12)] + + series_xp = ( + series.reindex(list(series.index) + s) + .rolling(window=25) + .quantile(q) + .shift(-12) + .reindex(series.index) + ) + + series_rs = series.rolling(window=25, center=True).quantile(q) + tm.assert_series_equal(series_xp, series_rs) + + +@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0]) +def test_center_reindex_frame(frame, q): + # shifter index + s = [f"x{x:d}" for x in range(12)] + + frame_xp = ( + frame.reindex(list(frame.index) + s) + .rolling(window=25) + .quantile(q) + .shift(-12) + .reindex(frame.index) + ) + frame_rs = frame.rolling(window=25, center=True).quantile(q) + tm.assert_frame_equal(frame_xp, frame_rs) + + +def test_keyword_quantile_deprecated(): + # GH #52550 + s = Series([1, 2, 3, 4]) + with tm.assert_produces_warning(FutureWarning): + s.rolling(2).quantile(quantile=0.4) diff --git a/shared/package-files/02/02fbbd853894a97ae0ce5b4da1c65e72f16d5718ed48fd86b46d3737cd81224f/deviceufunc.py b/shared/package-files/02/02fbbd853894a97ae0ce5b4da1c65e72f16d5718ed48fd86b46d3737cd81224f/deviceufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..52851e1e4fdfaa7666a614b3e54e290e33f87382 --- /dev/null +++ b/shared/package-files/02/02fbbd853894a97ae0ce5b4da1c65e72f16d5718ed48fd86b46d3737cd81224f/deviceufunc.py @@ -0,0 +1,919 @@ +""" +Implements custom ufunc dispatch mechanism for non-CPU devices. +""" + +from abc import ABCMeta, abstractmethod +from collections import OrderedDict +import operator +import warnings +from functools import reduce + +import numpy as np + +from numba.np.ufunc.ufuncbuilder import _BaseUFuncBuilder, parse_identity +from numba.core import types, sigutils +from numba.core.typing import signature +from numba.np.ufunc.sigparse import parse_signature + + +def _broadcast_axis(a, b): + """ + Raises + ------ + ValueError if broadcast fails + """ + if a == b: + return a + elif a == 1: + return b + elif b == 1: + return a + else: + raise ValueError("failed to broadcast {0} and {1}".format(a, b)) + + +def _pairwise_broadcast(shape1, shape2): + """ + Raises + ------ + ValueError if broadcast fails + """ + shape1, shape2 = map(tuple, [shape1, shape2]) + + while len(shape1) < len(shape2): + shape1 = (1,) + shape1 + + while len(shape1) > len(shape2): + shape2 = (1,) + shape2 + + return tuple(_broadcast_axis(a, b) for a, b in zip(shape1, shape2)) + + +def _multi_broadcast(*shapelist): + """ + Raises + ------ + ValueError if broadcast fails + """ + assert shapelist + + result = shapelist[0] + others = shapelist[1:] + try: + for i, each in enumerate(others, start=1): + result = _pairwise_broadcast(result, each) + except ValueError: + raise ValueError("failed to broadcast argument #{0}".format(i)) + else: + return result + + +class UFuncMechanism(object): + """ + Prepare ufunc arguments for vectorize. + """ + DEFAULT_STREAM = None + SUPPORT_DEVICE_SLICING = False + + def __init__(self, typemap, args): + """Never used directly by user. Invoke by UFuncMechanism.call(). + """ + self.typemap = typemap + self.args = args + nargs = len(self.args) + self.argtypes = [None] * nargs + self.scalarpos = [] + self.signature = None + self.arrays = [None] * nargs + + def _fill_arrays(self): + """ + Get all arguments in array form + """ + for i, arg in enumerate(self.args): + if self.is_device_array(arg): + self.arrays[i] = self.as_device_array(arg) + elif isinstance(arg, (int, float, complex, np.number)): + # Is scalar + self.scalarpos.append(i) + else: + self.arrays[i] = np.asarray(arg) + + def _fill_argtypes(self): + """ + Get dtypes + """ + for i, ary in enumerate(self.arrays): + if ary is not None: + dtype = getattr(ary, 'dtype') + if dtype is None: + dtype = np.asarray(ary).dtype + self.argtypes[i] = dtype + + def _resolve_signature(self): + """Resolve signature. + May have ambiguous case. + """ + matches = [] + # Resolve scalar args exact match first + if self.scalarpos: + # Try resolve scalar arguments + for formaltys in self.typemap: + match_map = [] + for i, (formal, actual) in enumerate(zip(formaltys, + self.argtypes)): + if actual is None: + actual = np.asarray(self.args[i]).dtype + + match_map.append(actual == formal) + + if all(match_map): + matches.append(formaltys) + + # No matching with exact match; try coercing the scalar arguments + if not matches: + matches = [] + for formaltys in self.typemap: + all_matches = all(actual is None or formal == actual + for formal, actual in + zip(formaltys, self.argtypes)) + if all_matches: + matches.append(formaltys) + + if not matches: + raise TypeError("No matching version. GPU ufunc requires array " + "arguments to have the exact types. This behaves " + "like regular ufunc with casting='no'.") + + if len(matches) > 1: + raise TypeError("Failed to resolve ufunc due to ambiguous " + "signature. Too many untyped scalars. " + "Use numpy dtype object to type tag.") + + # Try scalar arguments + self.argtypes = matches[0] + + def _get_actual_args(self): + """Return the actual arguments + Casts scalar arguments to np.array. + """ + for i in self.scalarpos: + self.arrays[i] = np.array([self.args[i]], dtype=self.argtypes[i]) + + return self.arrays + + def _broadcast(self, arys): + """Perform numpy ufunc broadcasting + """ + shapelist = [a.shape for a in arys] + shape = _multi_broadcast(*shapelist) + + for i, ary in enumerate(arys): + if ary.shape == shape: + pass + + else: + if self.is_device_array(ary): + arys[i] = self.broadcast_device(ary, shape) + + else: + ax_differs = [ax for ax in range(len(shape)) + if ax >= ary.ndim + or ary.shape[ax] != shape[ax]] + + missingdim = len(shape) - len(ary.shape) + strides = [0] * missingdim + list(ary.strides) + + for ax in ax_differs: + strides[ax] = 0 + + strided = np.lib.stride_tricks.as_strided(ary, + shape=shape, + strides=strides) + + arys[i] = self.force_array_layout(strided) + + return arys + + def get_arguments(self): + """Prepare and return the arguments for the ufunc. + Does not call to_device(). + """ + self._fill_arrays() + self._fill_argtypes() + self._resolve_signature() + arys = self._get_actual_args() + return self._broadcast(arys) + + def get_function(self): + """Returns (result_dtype, function) + """ + return self.typemap[self.argtypes] + + def is_device_array(self, obj): + """Is the `obj` a device array? + Override in subclass + """ + return False + + def as_device_array(self, obj): + """Convert the `obj` to a device array + Override in subclass + + Default implementation is an identity function + """ + return obj + + def broadcast_device(self, ary, shape): + """Handles ondevice broadcasting + + Override in subclass to add support. + """ + raise NotImplementedError("broadcasting on device is not supported") + + def force_array_layout(self, ary): + """Ensures array layout met device requirement. + + Override in sublcass + """ + return ary + + @classmethod + def call(cls, typemap, args, kws): + """Perform the entire ufunc call mechanism. + """ + # Handle keywords + stream = kws.pop('stream', cls.DEFAULT_STREAM) + out = kws.pop('out', None) + + if kws: + warnings.warn("unrecognized keywords: %s" % ', '.join(kws)) + + # Begin call resolution + cr = cls(typemap, args) + args = cr.get_arguments() + resty, func = cr.get_function() + + outshape = args[0].shape + + # Adjust output value + if out is not None and cr.is_device_array(out): + out = cr.as_device_array(out) + + def attempt_ravel(a): + if cr.SUPPORT_DEVICE_SLICING: + raise NotImplementedError + + try: + # Call the `.ravel()` method + return a.ravel() + except NotImplementedError: + # If it is not a device array + if not cr.is_device_array(a): + raise + # For device array, retry ravel on the host by first + # copying it back. + else: + hostary = cr.to_host(a, stream).ravel() + return cr.to_device(hostary, stream) + + if args[0].ndim > 1: + args = [attempt_ravel(a) for a in args] + + # Prepare argument on the device + devarys = [] + any_device = False + for a in args: + if cr.is_device_array(a): + devarys.append(a) + any_device = True + else: + dev_a = cr.to_device(a, stream=stream) + devarys.append(dev_a) + + # Launch + shape = args[0].shape + if out is None: + # No output is provided + devout = cr.allocate_device_array(shape, resty, stream=stream) + + devarys.extend([devout]) + cr.launch(func, shape[0], stream, devarys) + + if any_device: + # If any of the arguments are on device, + # Keep output on the device + return devout.reshape(outshape) + else: + # Otherwise, transfer output back to host + return devout.copy_to_host().reshape(outshape) + + elif cr.is_device_array(out): + # If output is provided and it is a device array, + # Return device array + if out.ndim > 1: + out = attempt_ravel(out) + devout = out + devarys.extend([devout]) + cr.launch(func, shape[0], stream, devarys) + return devout.reshape(outshape) + + else: + # If output is provided and it is a host array, + # Return host array + assert out.shape == shape + assert out.dtype == resty + devout = cr.allocate_device_array(shape, resty, stream=stream) + devarys.extend([devout]) + cr.launch(func, shape[0], stream, devarys) + return devout.copy_to_host(out, stream=stream).reshape(outshape) + + def to_device(self, hostary, stream): + """Implement to device transfer + Override in subclass + """ + raise NotImplementedError + + def to_host(self, devary, stream): + """Implement to host transfer + Override in subclass + """ + raise NotImplementedError + + def allocate_device_array(self, shape, dtype, stream): + """Implements device allocation + Override in subclass + """ + raise NotImplementedError + + def launch(self, func, count, stream, args): + """Implements device function invocation + Override in subclass + """ + raise NotImplementedError + + +def to_dtype(ty): + if isinstance(ty, types.EnumMember): + ty = ty.dtype + return np.dtype(str(ty)) + + +class DeviceVectorize(_BaseUFuncBuilder): + def __init__(self, func, identity=None, cache=False, targetoptions=None): + if targetoptions is None: + targetoptions = {} + if cache: + raise TypeError("caching is not supported") + for opt in targetoptions: + if opt == 'nopython': + warnings.warn("nopython kwarg for cuda target is redundant", + RuntimeWarning) + else: + fmt = "Unrecognized options. " + fmt += "cuda vectorize target does not support option: '%s'" + raise KeyError(fmt % opt) + self.py_func = func + self.identity = parse_identity(identity) + # { arg_dtype: (return_dtype), cudakernel } + self.kernelmap = OrderedDict() + + @property + def pyfunc(self): + return self.py_func + + def add(self, sig=None): + # compile core as device function + args, return_type = sigutils.normalize_signature(sig) + devfnsig = signature(return_type, *args) + + funcname = self.pyfunc.__name__ + kernelsource = self._get_kernel_source(self._kernel_template, + devfnsig, funcname) + corefn, return_type = self._compile_core(devfnsig) + glbl = self._get_globals(corefn) + sig = signature(types.void, *([a[:] for a in args] + [return_type[:]])) + exec(kernelsource, glbl) + + stager = glbl['__vectorized_%s' % funcname] + kernel = self._compile_kernel(stager, sig) + + argdtypes = tuple(to_dtype(t) for t in devfnsig.args) + resdtype = to_dtype(return_type) + self.kernelmap[tuple(argdtypes)] = resdtype, kernel + + def build_ufunc(self): + raise NotImplementedError + + def _get_kernel_source(self, template, sig, funcname): + args = ['a%d' % i for i in range(len(sig.args))] + fmts = dict(name=funcname, + args=', '.join(args), + argitems=', '.join('%s[__tid__]' % i for i in args)) + return template.format(**fmts) + + def _compile_core(self, sig): + raise NotImplementedError + + def _get_globals(self, corefn): + raise NotImplementedError + + def _compile_kernel(self, fnobj, sig): + raise NotImplementedError + + +class DeviceGUFuncVectorize(_BaseUFuncBuilder): + def __init__( + self, + func, + sig, + identity=None, + cache=False, + targetoptions=None, + writable_args=(), + ): + if targetoptions is None: + targetoptions = {} + if cache: + raise TypeError("caching is not supported") + if writable_args: + raise TypeError("writable_args are not supported") + + # Allow nopython flag to be set. + if not targetoptions.pop('nopython', True): + raise TypeError("nopython flag must be True") + # Are there any more target options? + if targetoptions: + opts = ', '.join([repr(k) for k in targetoptions.keys()]) + fmt = "The following target options are not supported: {0}" + raise TypeError(fmt.format(opts)) + + self.py_func = func + self.identity = parse_identity(identity) + self.signature = sig + self.inputsig, self.outputsig = parse_signature(self.signature) + + # Maps from a tuple of input_dtypes to (output_dtypes, kernel) + self.kernelmap = OrderedDict() + + @property + def pyfunc(self): + return self.py_func + + def add(self, sig=None): + indims = [len(x) for x in self.inputsig] + outdims = [len(x) for x in self.outputsig] + args, return_type = sigutils.normalize_signature(sig) + + # It is only valid to specify types.none as a return type, or to not + # specify the return type (where the "Python None" is the return type) + valid_return_type = return_type in (types.none, None) + if not valid_return_type: + raise TypeError('guvectorized functions cannot return values: ' + f'signature {sig} specifies {return_type} return ' + 'type') + + funcname = self.py_func.__name__ + src = expand_gufunc_template(self._kernel_template, indims, + outdims, funcname, args) + + glbls = self._get_globals(sig) + + exec(src, glbls) + fnobj = glbls['__gufunc_{name}'.format(name=funcname)] + + outertys = list(_determine_gufunc_outer_types(args, indims + outdims)) + kernel = self._compile_kernel(fnobj, sig=tuple(outertys)) + + nout = len(outdims) + dtypes = [np.dtype(str(t.dtype)) for t in outertys] + indtypes = tuple(dtypes[:-nout]) + outdtypes = tuple(dtypes[-nout:]) + + self.kernelmap[indtypes] = outdtypes, kernel + + def _compile_kernel(self, fnobj, sig): + raise NotImplementedError + + def _get_globals(self, sig): + raise NotImplementedError + + +def _determine_gufunc_outer_types(argtys, dims): + for at, nd in zip(argtys, dims): + if isinstance(at, types.Array): + yield at.copy(ndim=nd + 1) + else: + if nd > 0: + raise ValueError("gufunc signature mismatch: ndim>0 for scalar") + yield types.Array(dtype=at, ndim=1, layout='A') + + +def expand_gufunc_template(template, indims, outdims, funcname, argtypes): + """Expand gufunc source template + """ + argdims = indims + outdims + argnames = ["arg{0}".format(i) for i in range(len(argdims))] + checkedarg = "min({0})".format(', '.join(["{0}.shape[0]".format(a) + for a in argnames])) + inputs = [_gen_src_for_indexing(aref, adims, atype) + for aref, adims, atype in zip(argnames, indims, argtypes)] + outputs = [_gen_src_for_indexing(aref, adims, atype) + for aref, adims, atype in zip(argnames[len(indims):], outdims, + argtypes[len(indims):])] + argitems = inputs + outputs + src = template.format(name=funcname, args=', '.join(argnames), + checkedarg=checkedarg, + argitems=', '.join(argitems)) + return src + + +def _gen_src_for_indexing(aref, adims, atype): + return "{aref}[{sliced}]".format(aref=aref, + sliced=_gen_src_index(adims, atype)) + + +def _gen_src_index(adims, atype): + if adims > 0: + return ','.join(['__tid__'] + [':'] * adims) + elif isinstance(atype, types.Array) and atype.ndim - 1 == adims: + # Special case for 0-nd in shape-signature but + # 1d array in type signature. + # Slice it so that the result has the same dimension. + return '__tid__:(__tid__ + 1)' + else: + return '__tid__' + + +class GUFuncEngine(object): + '''Determine how to broadcast and execute a gufunc + base on input shape and signature + ''' + + @classmethod + def from_signature(cls, signature): + return cls(*parse_signature(signature)) + + def __init__(self, inputsig, outputsig): + # signatures + self.sin = inputsig + self.sout = outputsig + # argument count + self.nin = len(self.sin) + self.nout = len(self.sout) + + def schedule(self, ishapes): + if len(ishapes) != self.nin: + raise TypeError('invalid number of input argument') + + # associate symbol values for input signature + symbolmap = {} + outer_shapes = [] + inner_shapes = [] + + for argn, (shape, symbols) in enumerate(zip(ishapes, self.sin)): + argn += 1 # start from 1 for human + inner_ndim = len(symbols) + if len(shape) < inner_ndim: + fmt = "arg #%d: insufficient inner dimension" + raise ValueError(fmt % (argn,)) + if inner_ndim: + inner_shape = shape[-inner_ndim:] + outer_shape = shape[:-inner_ndim] + else: + inner_shape = () + outer_shape = shape + + for axis, (dim, sym) in enumerate(zip(inner_shape, symbols)): + axis += len(outer_shape) + if sym in symbolmap: + if symbolmap[sym] != dim: + fmt = "arg #%d: shape[%d] mismatch argument" + raise ValueError(fmt % (argn, axis)) + symbolmap[sym] = dim + + outer_shapes.append(outer_shape) + inner_shapes.append(inner_shape) + + # solve output shape + oshapes = [] + for outsig in self.sout: + oshape = [] + for sym in outsig: + oshape.append(symbolmap[sym]) + oshapes.append(tuple(oshape)) + + # find the biggest outershape as looping dimension + sizes = [reduce(operator.mul, s, 1) for s in outer_shapes] + largest_i = np.argmax(sizes) + loopdims = outer_shapes[largest_i] + + pinned = [False] * self.nin # same argument for each iteration + for i, d in enumerate(outer_shapes): + if d != loopdims: + if d == (1,) or d == (): + pinned[i] = True + else: + fmt = "arg #%d: outer dimension mismatch" + raise ValueError(fmt % (i + 1,)) + + return GUFuncSchedule(self, inner_shapes, oshapes, loopdims, pinned) + + +class GUFuncSchedule(object): + def __init__(self, parent, ishapes, oshapes, loopdims, pinned): + self.parent = parent + # core shapes + self.ishapes = ishapes + self.oshapes = oshapes + # looping dimension + self.loopdims = loopdims + self.loopn = reduce(operator.mul, loopdims, 1) + # flags + self.pinned = pinned + + self.output_shapes = [loopdims + s for s in oshapes] + + def __str__(self): + import pprint + + attrs = 'ishapes', 'oshapes', 'loopdims', 'loopn', 'pinned' + values = [(k, getattr(self, k)) for k in attrs] + return pprint.pformat(dict(values)) + + +class GeneralizedUFunc(object): + def __init__(self, kernelmap, engine): + self.kernelmap = kernelmap + self.engine = engine + self.max_blocksize = 2 ** 30 + + def __call__(self, *args, **kws): + callsteps = self._call_steps(self.engine.nin, self.engine.nout, + args, kws) + indtypes, schedule, outdtypes, kernel = self._schedule( + callsteps.inputs, callsteps.outputs) + callsteps.adjust_input_types(indtypes) + + outputs = callsteps.prepare_outputs(schedule, outdtypes) + inputs = callsteps.prepare_inputs() + parameters = self._broadcast(schedule, inputs, outputs) + + callsteps.launch_kernel(kernel, schedule.loopn, parameters) + + return callsteps.post_process_outputs(outputs) + + def _schedule(self, inputs, outs): + input_shapes = [a.shape for a in inputs] + schedule = self.engine.schedule(input_shapes) + + # find kernel + indtypes = tuple(i.dtype for i in inputs) + try: + outdtypes, kernel = self.kernelmap[indtypes] + except KeyError: + # No exact match, then use the first compatible. + # This does not match the numpy dispatching exactly. + # Later, we may just jit a new version for the missing signature. + indtypes = self._search_matching_signature(indtypes) + # Select kernel + outdtypes, kernel = self.kernelmap[indtypes] + + # check output + for sched_shape, out in zip(schedule.output_shapes, outs): + if out is not None and sched_shape != out.shape: + raise ValueError('output shape mismatch') + + return indtypes, schedule, outdtypes, kernel + + def _search_matching_signature(self, idtypes): + """ + Given the input types in `idtypes`, return a compatible sequence of + types that is defined in `kernelmap`. + + Note: Ordering is guaranteed by `kernelmap` being a OrderedDict + """ + for sig in self.kernelmap.keys(): + if all(np.can_cast(actual, desired) + for actual, desired in zip(sig, idtypes)): + return sig + else: + raise TypeError("no matching signature") + + def _broadcast(self, schedule, params, retvals): + assert schedule.loopn > 0, "zero looping dimension" + + odim = 1 if not schedule.loopdims else schedule.loopn + newparams = [] + for p, cs in zip(params, schedule.ishapes): + if not cs and p.size == 1: + # Broadcast scalar input + devary = self._broadcast_scalar_input(p, odim) + newparams.append(devary) + else: + # Broadcast vector input + newparams.append(self._broadcast_array(p, odim, cs)) + + newretvals = [] + for retval, oshape in zip(retvals, schedule.oshapes): + newretvals.append(retval.reshape(odim, *oshape)) + return tuple(newparams) + tuple(newretvals) + + def _broadcast_array(self, ary, newdim, innerdim): + newshape = (newdim,) + innerdim + # No change in shape + if ary.shape == newshape: + return ary + + # Creating new dimension + elif len(ary.shape) < len(newshape): + assert newshape[-len(ary.shape):] == ary.shape, \ + "cannot add dim and reshape at the same time" + return self._broadcast_add_axis(ary, newshape) + + # Collapsing dimension + else: + return ary.reshape(*newshape) + + def _broadcast_add_axis(self, ary, newshape): + raise NotImplementedError("cannot add new axis") + + def _broadcast_scalar_input(self, ary, shape): + raise NotImplementedError + + +class GUFuncCallSteps(metaclass=ABCMeta): + """ + Implements memory management and kernel launch operations for GUFunc calls. + + One instance of this class is instantiated for each call, and the instance + is specific to the arguments given to the GUFunc call. + + The base class implements the overall logic; subclasses provide + target-specific implementations of individual functions. + """ + + # The base class uses these slots; subclasses may provide additional slots. + __slots__ = [ + 'outputs', + 'inputs', + '_copy_result_to_host', + ] + + @abstractmethod + def launch_kernel(self, kernel, nelem, args): + """Implement the kernel launch""" + + @abstractmethod + def is_device_array(self, obj): + """ + Return True if `obj` is a device array for this target, False + otherwise. + """ + + @abstractmethod + def as_device_array(self, obj): + """ + Return `obj` as a device array on this target. + + May return `obj` directly if it is already on the target. + """ + + @abstractmethod + def to_device(self, hostary): + """ + Copy `hostary` to the device and return the device array. + """ + + @abstractmethod + def allocate_device_array(self, shape, dtype): + """ + Allocate a new uninitialized device array with the given shape and + dtype. + """ + + def __init__(self, nin, nout, args, kwargs): + outputs = kwargs.get('out') + + # Ensure the user has passed a correct number of arguments + if outputs is None and len(args) not in (nin, (nin + nout)): + def pos_argn(n): + return f'{n} positional argument{"s" * (n != 1)}' + + msg = (f'This gufunc accepts {pos_argn(nin)} (when providing ' + f'input only) or {pos_argn(nin + nout)} (when providing ' + f'input and output). Got {pos_argn(len(args))}.') + raise TypeError(msg) + + if outputs is not None and len(args) > nin: + raise ValueError("cannot specify argument 'out' as both positional " + "and keyword") + else: + # If the user did not pass outputs either in the out kwarg or as + # positional arguments, then we need to generate an initial list of + # "placeholder" outputs using None as a sentry value + outputs = [outputs] * nout + + # Ensure all output device arrays are Numba device arrays - for + # example, any output passed in that supports the CUDA Array Interface + # is converted to a Numba CUDA device array; others are left untouched. + all_user_outputs_are_host = True + self.outputs = [] + for output in outputs: + if self.is_device_array(output): + self.outputs.append(self.as_device_array(output)) + all_user_outputs_are_host = False + else: + self.outputs.append(output) + + all_host_arrays = not any([self.is_device_array(a) for a in args]) + + # - If any of the arguments are device arrays, we leave the output on + # the device. + self._copy_result_to_host = (all_host_arrays and + all_user_outputs_are_host) + + # Normalize arguments - ensure they are either device- or host-side + # arrays (as opposed to lists, tuples, etc). + def normalize_arg(a): + if self.is_device_array(a): + convert = self.as_device_array + else: + convert = np.asarray + + return convert(a) + + normalized_args = [normalize_arg(a) for a in args] + self.inputs = normalized_args[:nin] + + # Check if there are extra arguments for outputs. + unused_inputs = normalized_args[nin:] + if unused_inputs: + self.outputs = unused_inputs + + def adjust_input_types(self, indtypes): + """ + Attempt to cast the inputs to the required types if necessary + and if they are not device arrays. + + Side effect: Only affects the elements of `inputs` that require + a type cast. + """ + for i, (ity, val) in enumerate(zip(indtypes, self.inputs)): + if ity != val.dtype: + if not hasattr(val, 'astype'): + msg = ("compatible signature is possible by casting but " + "{0} does not support .astype()").format(type(val)) + raise TypeError(msg) + # Cast types + self.inputs[i] = val.astype(ity) + + def prepare_outputs(self, schedule, outdtypes): + """ + Returns a list of output parameters that all reside on the target + device. + + Outputs that were passed-in to the GUFunc are used if they reside on the + device; other outputs are allocated as necessary. + """ + outputs = [] + for shape, dtype, output in zip(schedule.output_shapes, outdtypes, + self.outputs): + if output is None or self._copy_result_to_host: + output = self.allocate_device_array(shape, dtype) + outputs.append(output) + + return outputs + + def prepare_inputs(self): + """ + Returns a list of input parameters that all reside on the target device. + """ + def ensure_device(parameter): + if self.is_device_array(parameter): + convert = self.as_device_array + else: + convert = self.to_device + + return convert(parameter) + + return [ensure_device(p) for p in self.inputs] + + def post_process_outputs(self, outputs): + """ + Moves the given output(s) to the host if necessary. + + Returns a single value (e.g. an array) if there was one output, or a + tuple of arrays if there were multiple. Although this feels a little + jarring, it is consistent with the behavior of GUFuncs in general. + """ + if self._copy_result_to_host: + outputs = [self.to_host(output, self_output) + for output, self_output in zip(outputs, self.outputs)] + elif self.outputs[0] is not None: + outputs = self.outputs + + if len(outputs) == 1: + return outputs[0] + else: + return tuple(outputs) diff --git a/shared/package-files/02/02fbf9d840d0eccf24529895535055b16fc68f91c30b300ea232eda05a2329bc/test_gammainc.py b/shared/package-files/02/02fbf9d840d0eccf24529895535055b16fc68f91c30b300ea232eda05a2329bc/test_gammainc.py new file mode 100644 index 0000000000000000000000000000000000000000..aae34e5c23f2d293f362abd825f1dad454371ae0 --- /dev/null +++ b/shared/package-files/02/02fbf9d840d0eccf24529895535055b16fc68f91c30b300ea232eda05a2329bc/test_gammainc.py @@ -0,0 +1,136 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal + +import scipy.special as sc +from scipy.special._testutils import FuncData + + +INVALID_POINTS = [ + (1, -1), + (0, 0), + (-1, 1), + (np.nan, 1), + (1, np.nan) +] + + +class TestGammainc: + + @pytest.mark.parametrize('a, x', INVALID_POINTS) + def test_domain(self, a, x): + assert np.isnan(sc.gammainc(a, x)) + + def test_a_eq_0_x_gt_0(self): + assert sc.gammainc(0, 1) == 1 + + @pytest.mark.parametrize('a, x, desired', [ + (np.inf, 1, 0), + (np.inf, 0, 0), + (np.inf, np.inf, np.nan), + (1, np.inf, 1) + ]) + def test_infinite_arguments(self, a, x, desired): + result = sc.gammainc(a, x) + if np.isnan(desired): + assert np.isnan(result) + else: + assert result == desired + + def test_infinite_limits(self): + # Test that large arguments converge to the hard-coded limits + # at infinity. + assert_allclose( + sc.gammainc(1000, 100), + sc.gammainc(np.inf, 100), + atol=1e-200, # Use `atol` since the function converges to 0. + rtol=0 + ) + assert sc.gammainc(100, 1000) == sc.gammainc(100, np.inf) + + def test_x_zero(self): + a = np.arange(1, 10) + assert_array_equal(sc.gammainc(a, 0), 0) + + def test_limit_check(self): + result = sc.gammainc(1e-10, 1) + limit = sc.gammainc(0, 1) + assert np.isclose(result, limit) + + def gammainc_line(self, x): + # The line a = x where a simpler asymptotic expansion (analog + # of DLMF 8.12.15) is available. + c = np.array([-1/3, -1/540, 25/6048, 101/155520, + -3184811/3695155200, -2745493/8151736420]) + res = 0 + xfac = 1 + for ck in c: + res -= ck*xfac + xfac /= x + res /= np.sqrt(2*np.pi*x) + res += 0.5 + return res + + def test_line(self): + x = np.logspace(np.log10(25), 300, 500) + a = x + dataset = np.vstack((a, x, self.gammainc_line(x))).T + FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-11).check() + + def test_roundtrip(self): + a = np.logspace(-5, 10, 100) + x = np.logspace(-5, 10, 100) + + y = sc.gammaincinv(a, sc.gammainc(a, x)) + assert_allclose(x, y, rtol=1e-10) + + +class TestGammaincc: + + @pytest.mark.parametrize('a, x', INVALID_POINTS) + def test_domain(self, a, x): + assert np.isnan(sc.gammaincc(a, x)) + + def test_a_eq_0_x_gt_0(self): + assert sc.gammaincc(0, 1) == 0 + + @pytest.mark.parametrize('a, x, desired', [ + (np.inf, 1, 1), + (np.inf, 0, 1), + (np.inf, np.inf, np.nan), + (1, np.inf, 0) + ]) + def test_infinite_arguments(self, a, x, desired): + result = sc.gammaincc(a, x) + if np.isnan(desired): + assert np.isnan(result) + else: + assert result == desired + + def test_infinite_limits(self): + # Test that large arguments converge to the hard-coded limits + # at infinity. + assert sc.gammaincc(1000, 100) == sc.gammaincc(np.inf, 100) + assert_allclose( + sc.gammaincc(100, 1000), + sc.gammaincc(100, np.inf), + atol=1e-200, # Use `atol` since the function converges to 0. + rtol=0 + ) + + def test_limit_check(self): + result = sc.gammaincc(1e-10,1) + limit = sc.gammaincc(0,1) + assert np.isclose(result, limit) + + def test_x_zero(self): + a = np.arange(1, 10) + assert_array_equal(sc.gammaincc(a, 0), 1) + + def test_roundtrip(self): + a = np.logspace(-5, 10, 100) + x = np.logspace(-5, 10, 100) + + y = sc.gammainccinv(a, sc.gammaincc(a, x)) + assert_allclose(x, y, rtol=1e-14) diff --git a/shared/package-files/02/02fc67ea3bcfe7eb5ab3293d5a028919127afb38f5895f1b398612060d5e36e3/scipy_fft.py b/shared/package-files/02/02fc67ea3bcfe7eb5ab3293d5a028919127afb38f5895f1b398612060d5e36e3/scipy_fft.py new file mode 100644 index 0000000000000000000000000000000000000000..94f98ac45a1b5e41a8321163d3b8fb3a1abd373b --- /dev/null +++ b/shared/package-files/02/02fc67ea3bcfe7eb5ab3293d5a028919127afb38f5895f1b398612060d5e36e3/scipy_fft.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# Copyright (c) 2017-2023, Intel Corporation +# +# 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 Intel Corporation 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. + +from .._scipy_fft_backend import * diff --git a/shared/package-files/02/02fcea85273a9d6522ae2bb88ddeb63c042defb7c9d34e262030eebb35a926ed/subqueries.pyi b/shared/package-files/02/02fcea85273a9d6522ae2bb88ddeb63c042defb7c9d34e262030eebb35a926ed/subqueries.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ba3d7e82a9ef4de64824c0fa23ab572a457c2508 --- /dev/null +++ b/shared/package-files/02/02fcea85273a9d6522ae2bb88ddeb63c042defb7c9d34e262030eebb35a926ed/subqueries.pyi @@ -0,0 +1,45 @@ +from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union + +from django.db.models.base import Model +from django.db.models.expressions import Case +from django.db.models.query import QuerySet +from django.db.models.sql.query import Query +from django.db.models.sql.where import WhereNode + +from django.db.models.fields import Field + +class DeleteQuery(Query): + select: Tuple + where_class: Type[WhereNode] + where: WhereNode = ... + def do_query(self, table: str, where: WhereNode, using: str) -> int: ... + def delete_batch(self, pk_list: Union[List[int], List[str]], using: str) -> int: ... + def delete_qs(self, query: QuerySet, using: str) -> int: ... + +class UpdateQuery(Query): + select: Tuple + where_class: Type[WhereNode] + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + where: WhereNode = ... + def update_batch(self, pk_list: List[int], values: Dict[str, Optional[int]], using: str) -> None: ... + def add_update_values(self, values: Dict[str, Any]) -> None: ... + def add_update_fields(self, values_seq: List[Tuple[Field, Optional[Type[Model]], Case]]) -> None: ... + def add_related_update(self, model: Type[Model], field: Field, value: Union[int, str]) -> None: ... + def get_related_updates(self) -> List[UpdateQuery]: ... + +class InsertQuery(Query): + select: Tuple + where: WhereNode + where_class: Type[WhereNode] + fields: Iterable[Field] = ... + objs: List[Model] = ... + raw: bool = ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def insert_values(self, fields: Iterable[Field], objs: List[Model], raw: bool = ...) -> None: ... + +class AggregateQuery(Query): + select: Tuple + sub_params: Tuple + where: WhereNode + where_class: Type[WhereNode] + def add_subquery(self, query: Query, using: str) -> None: ... diff --git a/shared/package-files/28/2804cc15e171509f18351682fa377f7533adde8a73da783a9478247b9bb908e9/fromnumeric.pyi b/shared/package-files/28/2804cc15e171509f18351682fa377f7533adde8a73da783a9478247b9bb908e9/fromnumeric.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5438b2700bd56cb404a319c2d9880d448cdb857c --- /dev/null +++ b/shared/package-files/28/2804cc15e171509f18351682fa377f7533adde8a73da783a9478247b9bb908e9/fromnumeric.pyi @@ -0,0 +1,1060 @@ +import datetime as dt +from collections.abc import Sequence +from typing import Union, Any, overload, TypeVar, Literal, SupportsIndex + +from numpy import ( + ndarray, + number, + uint64, + int_, + int64, + intp, + float16, + bool_, + floating, + complexfloating, + object_, + generic, + _OrderKACF, + _OrderACF, + _ModeKind, + _PartitionKind, + _SortKind, + _SortSide, + _CastingKind, +) +from numpy._typing import ( + DTypeLike, + _DTypeLike, + ArrayLike, + _ArrayLike, + NDArray, + _ShapeLike, + _Shape, + _ArrayLikeBool_co, + _ArrayLikeUInt_co, + _ArrayLikeInt_co, + _ArrayLikeFloat_co, + _ArrayLikeComplex_co, + _ArrayLikeObject_co, + _IntLike_co, + _BoolLike_co, + _ComplexLike_co, + _NumberLike_co, + _ScalarLike_co, +) + +_SCT = TypeVar("_SCT", bound=generic) +_SCT_uifcO = TypeVar("_SCT_uifcO", bound=number[Any] | object_) +_ArrayType = TypeVar("_ArrayType", bound=NDArray[Any]) + +__all__: list[str] + +@overload +def take( + a: _ArrayLike[_SCT], + indices: _IntLike_co, + axis: None = ..., + out: None = ..., + mode: _ModeKind = ..., +) -> _SCT: ... +@overload +def take( + a: ArrayLike, + indices: _IntLike_co, + axis: None | SupportsIndex = ..., + out: None = ..., + mode: _ModeKind = ..., +) -> Any: ... +@overload +def take( + a: _ArrayLike[_SCT], + indices: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., + out: None = ..., + mode: _ModeKind = ..., +) -> NDArray[_SCT]: ... +@overload +def take( + a: ArrayLike, + indices: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., + out: None = ..., + mode: _ModeKind = ..., +) -> NDArray[Any]: ... +@overload +def take( + a: ArrayLike, + indices: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., + out: _ArrayType = ..., + mode: _ModeKind = ..., +) -> _ArrayType: ... + +@overload +def reshape( + a: _ArrayLike[_SCT], + newshape: _ShapeLike, + order: _OrderACF = ..., +) -> NDArray[_SCT]: ... +@overload +def reshape( + a: ArrayLike, + newshape: _ShapeLike, + order: _OrderACF = ..., +) -> NDArray[Any]: ... + +@overload +def choose( + a: _IntLike_co, + choices: ArrayLike, + out: None = ..., + mode: _ModeKind = ..., +) -> Any: ... +@overload +def choose( + a: _ArrayLikeInt_co, + choices: _ArrayLike[_SCT], + out: None = ..., + mode: _ModeKind = ..., +) -> NDArray[_SCT]: ... +@overload +def choose( + a: _ArrayLikeInt_co, + choices: ArrayLike, + out: None = ..., + mode: _ModeKind = ..., +) -> NDArray[Any]: ... +@overload +def choose( + a: _ArrayLikeInt_co, + choices: ArrayLike, + out: _ArrayType = ..., + mode: _ModeKind = ..., +) -> _ArrayType: ... + +@overload +def repeat( + a: _ArrayLike[_SCT], + repeats: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., +) -> NDArray[_SCT]: ... +@overload +def repeat( + a: ArrayLike, + repeats: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., +) -> NDArray[Any]: ... + +def put( + a: NDArray[Any], + ind: _ArrayLikeInt_co, + v: ArrayLike, + mode: _ModeKind = ..., +) -> None: ... + +@overload +def swapaxes( + a: _ArrayLike[_SCT], + axis1: SupportsIndex, + axis2: SupportsIndex, +) -> NDArray[_SCT]: ... +@overload +def swapaxes( + a: ArrayLike, + axis1: SupportsIndex, + axis2: SupportsIndex, +) -> NDArray[Any]: ... + +@overload +def transpose( + a: _ArrayLike[_SCT], + axes: None | _ShapeLike = ... +) -> NDArray[_SCT]: ... +@overload +def transpose( + a: ArrayLike, + axes: None | _ShapeLike = ... +) -> NDArray[Any]: ... + +@overload +def partition( + a: _ArrayLike[_SCT], + kth: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., + kind: _PartitionKind = ..., + order: None | str | Sequence[str] = ..., +) -> NDArray[_SCT]: ... +@overload +def partition( + a: ArrayLike, + kth: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., + kind: _PartitionKind = ..., + order: None | str | Sequence[str] = ..., +) -> NDArray[Any]: ... + +def argpartition( + a: ArrayLike, + kth: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., + kind: _PartitionKind = ..., + order: None | str | Sequence[str] = ..., +) -> NDArray[intp]: ... + +@overload +def sort( + a: _ArrayLike[_SCT], + axis: None | SupportsIndex = ..., + kind: None | _SortKind = ..., + order: None | str | Sequence[str] = ..., +) -> NDArray[_SCT]: ... +@overload +def sort( + a: ArrayLike, + axis: None | SupportsIndex = ..., + kind: None | _SortKind = ..., + order: None | str | Sequence[str] = ..., +) -> NDArray[Any]: ... + +def argsort( + a: ArrayLike, + axis: None | SupportsIndex = ..., + kind: None | _SortKind = ..., + order: None | str | Sequence[str] = ..., +) -> NDArray[intp]: ... + +@overload +def argmax( + a: ArrayLike, + axis: None = ..., + out: None = ..., + *, + keepdims: Literal[False] = ..., +) -> intp: ... +@overload +def argmax( + a: ArrayLike, + axis: None | SupportsIndex = ..., + out: None = ..., + *, + keepdims: bool = ..., +) -> Any: ... +@overload +def argmax( + a: ArrayLike, + axis: None | SupportsIndex = ..., + out: _ArrayType = ..., + *, + keepdims: bool = ..., +) -> _ArrayType: ... + +@overload +def argmin( + a: ArrayLike, + axis: None = ..., + out: None = ..., + *, + keepdims: Literal[False] = ..., +) -> intp: ... +@overload +def argmin( + a: ArrayLike, + axis: None | SupportsIndex = ..., + out: None = ..., + *, + keepdims: bool = ..., +) -> Any: ... +@overload +def argmin( + a: ArrayLike, + axis: None | SupportsIndex = ..., + out: _ArrayType = ..., + *, + keepdims: bool = ..., +) -> _ArrayType: ... + +@overload +def searchsorted( + a: ArrayLike, + v: _ScalarLike_co, + side: _SortSide = ..., + sorter: None | _ArrayLikeInt_co = ..., # 1D int array +) -> intp: ... +@overload +def searchsorted( + a: ArrayLike, + v: ArrayLike, + side: _SortSide = ..., + sorter: None | _ArrayLikeInt_co = ..., # 1D int array +) -> NDArray[intp]: ... + +@overload +def resize( + a: _ArrayLike[_SCT], + new_shape: _ShapeLike, +) -> NDArray[_SCT]: ... +@overload +def resize( + a: ArrayLike, + new_shape: _ShapeLike, +) -> NDArray[Any]: ... + +@overload +def squeeze( + a: _SCT, + axis: None | _ShapeLike = ..., +) -> _SCT: ... +@overload +def squeeze( + a: _ArrayLike[_SCT], + axis: None | _ShapeLike = ..., +) -> NDArray[_SCT]: ... +@overload +def squeeze( + a: ArrayLike, + axis: None | _ShapeLike = ..., +) -> NDArray[Any]: ... + +@overload +def diagonal( + a: _ArrayLike[_SCT], + offset: SupportsIndex = ..., + axis1: SupportsIndex = ..., + axis2: SupportsIndex = ..., # >= 2D array +) -> NDArray[_SCT]: ... +@overload +def diagonal( + a: ArrayLike, + offset: SupportsIndex = ..., + axis1: SupportsIndex = ..., + axis2: SupportsIndex = ..., # >= 2D array +) -> NDArray[Any]: ... + +@overload +def trace( + a: ArrayLike, # >= 2D array + offset: SupportsIndex = ..., + axis1: SupportsIndex = ..., + axis2: SupportsIndex = ..., + dtype: DTypeLike = ..., + out: None = ..., +) -> Any: ... +@overload +def trace( + a: ArrayLike, # >= 2D array + offset: SupportsIndex = ..., + axis1: SupportsIndex = ..., + axis2: SupportsIndex = ..., + dtype: DTypeLike = ..., + out: _ArrayType = ..., +) -> _ArrayType: ... + +@overload +def ravel(a: _ArrayLike[_SCT], order: _OrderKACF = ...) -> NDArray[_SCT]: ... +@overload +def ravel(a: ArrayLike, order: _OrderKACF = ...) -> NDArray[Any]: ... + +def nonzero(a: ArrayLike) -> tuple[NDArray[intp], ...]: ... + +def shape(a: ArrayLike) -> _Shape: ... + +@overload +def compress( + condition: _ArrayLikeBool_co, # 1D bool array + a: _ArrayLike[_SCT], + axis: None | SupportsIndex = ..., + out: None = ..., +) -> NDArray[_SCT]: ... +@overload +def compress( + condition: _ArrayLikeBool_co, # 1D bool array + a: ArrayLike, + axis: None | SupportsIndex = ..., + out: None = ..., +) -> NDArray[Any]: ... +@overload +def compress( + condition: _ArrayLikeBool_co, # 1D bool array + a: ArrayLike, + axis: None | SupportsIndex = ..., + out: _ArrayType = ..., +) -> _ArrayType: ... + +@overload +def clip( + a: _SCT, + a_min: None | ArrayLike, + a_max: None | ArrayLike, + out: None = ..., + *, + dtype: None = ..., + where: None | _ArrayLikeBool_co = ..., + order: _OrderKACF = ..., + subok: bool = ..., + signature: str | tuple[None | str, ...] = ..., + extobj: list[Any] = ..., + casting: _CastingKind = ..., +) -> _SCT: ... +@overload +def clip( + a: _ScalarLike_co, + a_min: None | ArrayLike, + a_max: None | ArrayLike, + out: None = ..., + *, + dtype: None = ..., + where: None | _ArrayLikeBool_co = ..., + order: _OrderKACF = ..., + subok: bool = ..., + signature: str | tuple[None | str, ...] = ..., + extobj: list[Any] = ..., + casting: _CastingKind = ..., +) -> Any: ... +@overload +def clip( + a: _ArrayLike[_SCT], + a_min: None | ArrayLike, + a_max: None | ArrayLike, + out: None = ..., + *, + dtype: None = ..., + where: None | _ArrayLikeBool_co = ..., + order: _OrderKACF = ..., + subok: bool = ..., + signature: str | tuple[None | str, ...] = ..., + extobj: list[Any] = ..., + casting: _CastingKind = ..., +) -> NDArray[_SCT]: ... +@overload +def clip( + a: ArrayLike, + a_min: None | ArrayLike, + a_max: None | ArrayLike, + out: None = ..., + *, + dtype: None = ..., + where: None | _ArrayLikeBool_co = ..., + order: _OrderKACF = ..., + subok: bool = ..., + signature: str | tuple[None | str, ...] = ..., + extobj: list[Any] = ..., + casting: _CastingKind = ..., +) -> NDArray[Any]: ... +@overload +def clip( + a: ArrayLike, + a_min: None | ArrayLike, + a_max: None | ArrayLike, + out: _ArrayType = ..., + *, + dtype: DTypeLike, + where: None | _ArrayLikeBool_co = ..., + order: _OrderKACF = ..., + subok: bool = ..., + signature: str | tuple[None | str, ...] = ..., + extobj: list[Any] = ..., + casting: _CastingKind = ..., +) -> Any: ... +@overload +def clip( + a: ArrayLike, + a_min: None | ArrayLike, + a_max: None | ArrayLike, + out: _ArrayType, + *, + dtype: DTypeLike = ..., + where: None | _ArrayLikeBool_co = ..., + order: _OrderKACF = ..., + subok: bool = ..., + signature: str | tuple[None | str, ...] = ..., + extobj: list[Any] = ..., + casting: _CastingKind = ..., +) -> _ArrayType: ... + +@overload +def sum( + a: _ArrayLike[_SCT], + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _SCT: ... +@overload +def sum( + a: ArrayLike, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: None = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def sum( + a: ArrayLike, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +@overload +def all( + a: ArrayLike, + axis: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> bool_: ... +@overload +def all( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: None = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def all( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +@overload +def any( + a: ArrayLike, + axis: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> bool_: ... +@overload +def any( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: None = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def any( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +@overload +def cumsum( + a: _ArrayLike[_SCT], + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[_SCT]: ... +@overload +def cumsum( + a: ArrayLike, + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[Any]: ... +@overload +def cumsum( + a: ArrayLike, + axis: None | SupportsIndex = ..., + dtype: _DTypeLike[_SCT] = ..., + out: None = ..., +) -> NDArray[_SCT]: ... +@overload +def cumsum( + a: ArrayLike, + axis: None | SupportsIndex = ..., + dtype: DTypeLike = ..., + out: None = ..., +) -> NDArray[Any]: ... +@overload +def cumsum( + a: ArrayLike, + axis: None | SupportsIndex = ..., + dtype: DTypeLike = ..., + out: _ArrayType = ..., +) -> _ArrayType: ... + +@overload +def ptp( + a: _ArrayLike[_SCT], + axis: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., +) -> _SCT: ... +@overload +def ptp( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: None = ..., + keepdims: bool = ..., +) -> Any: ... +@overload +def ptp( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., +) -> _ArrayType: ... + +@overload +def amax( + a: _ArrayLike[_SCT], + axis: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _SCT: ... +@overload +def amax( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: None = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def amax( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +@overload +def amin( + a: _ArrayLike[_SCT], + axis: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _SCT: ... +@overload +def amin( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: None = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def amin( + a: ArrayLike, + axis: None | _ShapeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +# TODO: `np.prod()``: For object arrays `initial` does not necessarily +# have to be a numerical scalar. +# The only requirement is that it is compatible +# with the `.__mul__()` method(s) of the passed array's elements. + +# Note that the same situation holds for all wrappers around +# `np.ufunc.reduce`, e.g. `np.sum()` (`.__add__()`). +@overload +def prod( + a: _ArrayLikeBool_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> int_: ... +@overload +def prod( + a: _ArrayLikeUInt_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> uint64: ... +@overload +def prod( + a: _ArrayLikeInt_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> int64: ... +@overload +def prod( + a: _ArrayLikeFloat_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> floating[Any]: ... +@overload +def prod( + a: _ArrayLikeComplex_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> complexfloating[Any, Any]: ... +@overload +def prod( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: None = ..., + out: None = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def prod( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None = ..., + dtype: _DTypeLike[_SCT] = ..., + out: None = ..., + keepdims: Literal[False] = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _SCT: ... +@overload +def prod( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: None | DTypeLike = ..., + out: None = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def prod( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: None | DTypeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., + initial: _NumberLike_co = ..., + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +@overload +def cumprod( + a: _ArrayLikeBool_co, + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[int_]: ... +@overload +def cumprod( + a: _ArrayLikeUInt_co, + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[uint64]: ... +@overload +def cumprod( + a: _ArrayLikeInt_co, + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[int64]: ... +@overload +def cumprod( + a: _ArrayLikeFloat_co, + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[floating[Any]]: ... +@overload +def cumprod( + a: _ArrayLikeComplex_co, + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[complexfloating[Any, Any]]: ... +@overload +def cumprod( + a: _ArrayLikeObject_co, + axis: None | SupportsIndex = ..., + dtype: None = ..., + out: None = ..., +) -> NDArray[object_]: ... +@overload +def cumprod( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | SupportsIndex = ..., + dtype: _DTypeLike[_SCT] = ..., + out: None = ..., +) -> NDArray[_SCT]: ... +@overload +def cumprod( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | SupportsIndex = ..., + dtype: DTypeLike = ..., + out: None = ..., +) -> NDArray[Any]: ... +@overload +def cumprod( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | SupportsIndex = ..., + dtype: DTypeLike = ..., + out: _ArrayType = ..., +) -> _ArrayType: ... + +def ndim(a: ArrayLike) -> int: ... + +def size(a: ArrayLike, axis: None | int = ...) -> int: ... + +@overload +def around( + a: _BoolLike_co, + decimals: SupportsIndex = ..., + out: None = ..., +) -> float16: ... +@overload +def around( + a: _SCT_uifcO, + decimals: SupportsIndex = ..., + out: None = ..., +) -> _SCT_uifcO: ... +@overload +def around( + a: _ComplexLike_co | object_, + decimals: SupportsIndex = ..., + out: None = ..., +) -> Any: ... +@overload +def around( + a: _ArrayLikeBool_co, + decimals: SupportsIndex = ..., + out: None = ..., +) -> NDArray[float16]: ... +@overload +def around( + a: _ArrayLike[_SCT_uifcO], + decimals: SupportsIndex = ..., + out: None = ..., +) -> NDArray[_SCT_uifcO]: ... +@overload +def around( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + decimals: SupportsIndex = ..., + out: None = ..., +) -> NDArray[Any]: ... +@overload +def around( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + decimals: SupportsIndex = ..., + out: _ArrayType = ..., +) -> _ArrayType: ... + +@overload +def mean( + a: _ArrayLikeFloat_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> floating[Any]: ... +@overload +def mean( + a: _ArrayLikeComplex_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> complexfloating[Any, Any]: ... +@overload +def mean( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: None = ..., + out: None = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def mean( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None = ..., + dtype: _DTypeLike[_SCT] = ..., + out: None = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _SCT: ... +@overload +def mean( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: None = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def mean( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: _ArrayType = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +@overload +def std( + a: _ArrayLikeComplex_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + ddof: float = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> floating[Any]: ... +@overload +def std( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: None = ..., + out: None = ..., + ddof: float = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def std( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None = ..., + dtype: _DTypeLike[_SCT] = ..., + out: None = ..., + ddof: float = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _SCT: ... +@overload +def std( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: None = ..., + ddof: float = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def std( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: _ArrayType = ..., + ddof: float = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +@overload +def var( + a: _ArrayLikeComplex_co, + axis: None = ..., + dtype: None = ..., + out: None = ..., + ddof: float = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> floating[Any]: ... +@overload +def var( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: None = ..., + out: None = ..., + ddof: float = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def var( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None = ..., + dtype: _DTypeLike[_SCT] = ..., + out: None = ..., + ddof: float = ..., + keepdims: Literal[False] = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _SCT: ... +@overload +def var( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: None = ..., + ddof: float = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> Any: ... +@overload +def var( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: _ArrayType = ..., + ddof: float = ..., + keepdims: bool = ..., + *, + where: _ArrayLikeBool_co = ..., +) -> _ArrayType: ... + +max = amax +min = amin +round = around diff --git a/shared/package-files/28/28071058e61f65e0211104c829697d59388bb55dd1ebfc9b039c3ef1cca0bff2/__init__.py b/shared/package-files/28/28071058e61f65e0211104c829697d59388bb55dd1ebfc9b039c3ef1cca0bff2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e8cb037053ccdb0da56f640972228d288de6ded8 --- /dev/null +++ b/shared/package-files/28/28071058e61f65e0211104c829697d59388bb55dd1ebfc9b039c3ef1cca0bff2/__init__.py @@ -0,0 +1,294 @@ +import warnings + +from contextlib import contextmanager +from typing import Any, Iterator + +import torch._C + +# These are imported so users can access them from the `torch.jit` module +from torch._jit_internal import ( + _Await, + _drop, + _IgnoreContextManager, + _isinstance, + _overload, + _overload_method, + export, + Final, + Future, + ignore, + is_scripting, + unused, +) +from torch.jit._async import fork, wait +from torch.jit._await import _awaitable, _awaitable_nowait, _awaitable_wait +from torch.jit._decomposition_utils import _register_decomposition +from torch.jit._freeze import freeze, optimize_for_inference, run_frozen_optimizations +from torch.jit._fuser import ( + fuser, + last_executed_optimized_graph, + optimized_execution, + set_fusion_strategy, +) +from torch.jit._ir_utils import _InsertPoint +from torch.jit._script import ( + _ScriptProfile, + _unwrap_optional, + Attribute, + CompilationUnit, + interface, + RecursiveScriptClass, + RecursiveScriptModule, + script, + script_method, + ScriptFunction, + ScriptModule, + ScriptWarning, +) +from torch.jit._serialization import ( + jit_module_from_flatbuffer, + load, + save, + save_jit_module_to_flatbuffer, +) +from torch.jit._trace import ( + _flatten, + _get_trace_graph, + _script_if_tracing, + _unique_state_dict, + is_tracing, + ONNXTracedModule, + TopLevelTracedModule, + trace, + trace_module, + TracedModule, + TracerWarning, + TracingCheckError, +) + +from torch.utils import set_module + +__all__ = [ + "Attribute", + "CompilationUnit", + "Error", + "Future", + "ScriptFunction", + "ScriptModule", + "annotate", + "enable_onednn_fusion", + "export", + "export_opnames", + "fork", + "freeze", + "ignore", + "isinstance", + "load", + "onednn_fusion_enabled", + "optimize_for_inference", + "save", + "script", + "script_if_tracing", + "set_fusion_strategy", + "strict_fusion", + "trace", + "trace_module", + "unused", + "wait", +] + +# For backwards compatibility +_fork = fork +_wait = wait +_set_fusion_strategy = set_fusion_strategy + + +def export_opnames(m): + r""" + Generate new bytecode for a Script module. + + Returns what the op list would be for a Script Module based off the current code base. + + If you have a LiteScriptModule and want to get the currently present + list of ops call _export_operator_list instead. + """ + return torch._C._export_opnames(m._c) + + +# torch.jit.Error +Error = torch._C.JITException +set_module(Error, "torch.jit") +# This is not perfect but works in common cases +Error.__name__ = "Error" +Error.__qualname__ = "Error" + + +# for use in python if using annotate +def annotate(the_type, the_value): + """Use to give type of `the_value` in TorchScript compiler. + + This method is a pass-through function that returns `the_value`, used to hint TorchScript + compiler the type of `the_value`. It is a no-op when running outside of TorchScript. + + Though TorchScript can infer correct type for most Python expressions, there are some cases where + type inference can be wrong, including: + + - Empty containers like `[]` and `{}`, which TorchScript assumes to be container of `Tensor` + - Optional types like `Optional[T]` but assigned a valid value of type `T`, TorchScript would assume + it is type `T` rather than `Optional[T]` + + Note that `annotate()` does not help in `__init__` method of `torch.nn.Module` subclasses because it + is executed in eager mode. To annotate types of `torch.nn.Module` attributes, + use :meth:`~torch.jit.Annotate` instead. + + Example: + + .. testcode:: + + import torch + from typing import Dict + + @torch.jit.script + def fn(): + # Telling TorchScript that this empty dictionary is a (str -> int) dictionary + # instead of default dictionary type of (str -> Tensor). + d = torch.jit.annotate(Dict[str, int], {}) + + # Without `torch.jit.annotate` above, following statement would fail because of + # type mismatch. + d["name"] = 20 + + .. testcleanup:: + + del fn + + Args: + the_type: Python type that should be passed to TorchScript compiler as type hint for `the_value` + the_value: Value or expression to hint type for. + + Returns: + `the_value` is passed back as return value. + """ + return the_value + + +def script_if_tracing(fn): + """ + Compiles ``fn`` when it is first called during tracing. + + ``torch.jit.script`` has a non-negligible start up time when it is first called due to + lazy-initializations of many compiler builtins. Therefore you should not use + it in library code. However, you may want to have parts of your library work + in tracing even if they use control flow. In these cases, you should use + ``@torch.jit.script_if_tracing`` to substitute for + ``torch.jit.script``. + + Args: + fn: A function to compile. + + Returns: + If called during tracing, a :class:`ScriptFunction` created by `torch.jit.script` is returned. + Otherwise, the original function `fn` is returned. + """ + return _script_if_tracing(fn) + + +# for torch.jit.isinstance +def isinstance(obj, target_type): + """ + Provide container type refinement in TorchScript. + + It can refine parameterized containers of the List, Dict, Tuple, and Optional types. E.g. ``List[str]``, + ``Dict[str, List[torch.Tensor]]``, ``Optional[Tuple[int,str,int]]``. It can also + refine basic types such as bools and ints that are available in TorchScript. + + Args: + obj: object to refine the type of + target_type: type to try to refine obj to + Returns: + ``bool``: True if obj was successfully refined to the type of target_type, + False otherwise with no new type refinement + + + Example (using ``torch.jit.isinstance`` for type refinement): + .. testcode:: + + import torch + from typing import Any, Dict, List + + class MyModule(torch.nn.Module): + def __init__(self): + super().__init__() + + def forward(self, input: Any): # note the Any type + if torch.jit.isinstance(input, List[torch.Tensor]): + for t in input: + y = t.clamp(0, 0.5) + elif torch.jit.isinstance(input, Dict[str, str]): + for val in input.values(): + print(val) + + m = torch.jit.script(MyModule()) + x = [torch.rand(3,3), torch.rand(4,3)] + m(x) + y = {"key1":"val1","key2":"val2"} + m(y) + """ + return _isinstance(obj, target_type) + + +class strict_fusion: + """ + Give errors if not all nodes have been fused in inference, or symbolically differentiated in training. + + Example: + Forcing fusion of additions. + + .. code-block:: python + + @torch.jit.script + def foo(x): + with torch.jit.strict_fusion(): + return x + x + x + + """ + + def __init__(self): + if not torch._jit_internal.is_scripting(): + warnings.warn("Only works in script mode") + pass + + def __enter__(self): + pass + + def __exit__(self, type: Any, value: Any, tb: Any) -> None: + pass + + +# Context manager for globally hiding source ranges when printing graphs. +# Note that these functions are exposed to Python as static members of the +# Graph class, so mypy checks need to be skipped. +@contextmanager +def _hide_source_ranges() -> Iterator[None]: + old_enable_source_ranges = torch._C.Graph.global_print_source_ranges # type: ignore[attr-defined] + try: + torch._C.Graph.set_global_print_source_ranges(False) # type: ignore[attr-defined] + yield + finally: + torch._C.Graph.set_global_print_source_ranges(old_enable_source_ranges) # type: ignore[attr-defined] + + +def enable_onednn_fusion(enabled: bool): + """Enable or disables onednn JIT fusion based on the parameter `enabled`.""" + torch._C._jit_set_llga_enabled(enabled) + + +def onednn_fusion_enabled(): + """Return whether onednn JIT fusion is enabled.""" + return torch._C._jit_llga_enabled() + + +del Any + +if not torch._C._jit_init(): + raise RuntimeError("JIT initialization failed") diff --git a/shared/package-files/28/2808531d4277839452966b14e6609372fbad3829b73aa71ddfae37bb71cda888/cmuarctic.py b/shared/package-files/28/2808531d4277839452966b14e6609372fbad3829b73aa71ddfae37bb71cda888/cmuarctic.py new file mode 100644 index 0000000000000000000000000000000000000000..96f498f00f04a2f1b6d7d3e33510eafcb9ffe6bc --- /dev/null +++ b/shared/package-files/28/2808531d4277839452966b14e6609372fbad3829b73aa71ddfae37bb71cda888/cmuarctic.py @@ -0,0 +1,157 @@ +import csv +import os +from pathlib import Path +from typing import Tuple, Union + +import torchaudio +from torch import Tensor +from torch.utils.data import Dataset +from torchaudio._internal import download_url_to_file +from torchaudio.datasets.utils import _extract_tar + +URL = "aew" +FOLDER_IN_ARCHIVE = "ARCTIC" +_CHECKSUMS = { + "http://festvox.org/cmu_arctic/packed/cmu_us_aew_arctic.tar.bz2": "645cb33c0f0b2ce41384fdd8d3db2c3f5fc15c1e688baeb74d2e08cab18ab406", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_ahw_arctic.tar.bz2": "024664adeb892809d646a3efd043625b46b5bfa3e6189b3500b2d0d59dfab06c", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_aup_arctic.tar.bz2": "2c55bc3050caa996758869126ad10cf42e1441212111db034b3a45189c18b6fc", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_awb_arctic.tar.bz2": "d74a950c9739a65f7bfc4dfa6187f2730fa03de5b8eb3f2da97a51b74df64d3c", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_axb_arctic.tar.bz2": "dd65c3d2907d1ee52f86e44f578319159e60f4bf722a9142be01161d84e330ff", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_bdl_arctic.tar.bz2": "26b91aaf48b2799b2956792b4632c2f926cd0542f402b5452d5adecb60942904", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_clb_arctic.tar.bz2": "3f16dc3f3b97955ea22623efb33b444341013fc660677b2e170efdcc959fa7c6", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_eey_arctic.tar.bz2": "8a0ee4e5acbd4b2f61a4fb947c1730ab3adcc9dc50b195981d99391d29928e8a", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_fem_arctic.tar.bz2": "3fcff629412b57233589cdb058f730594a62c4f3a75c20de14afe06621ef45e2", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_gka_arctic.tar.bz2": "dc82e7967cbd5eddbed33074b0699128dbd4482b41711916d58103707e38c67f", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_jmk_arctic.tar.bz2": "3a37c0e1dfc91e734fdbc88b562d9e2ebca621772402cdc693bbc9b09b211d73", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_ksp_arctic.tar.bz2": "8029cafce8296f9bed3022c44ef1e7953332b6bf6943c14b929f468122532717", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_ljm_arctic.tar.bz2": "b23993765cbf2b9e7bbc3c85b6c56eaf292ac81ee4bb887b638a24d104f921a0", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_lnh_arctic.tar.bz2": "4faf34d71aa7112813252fb20c5433e2fdd9a9de55a00701ffcbf05f24a5991a", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_rms_arctic.tar.bz2": "c6dc11235629c58441c071a7ba8a2d067903dfefbaabc4056d87da35b72ecda4", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_rxr_arctic.tar.bz2": "1fa4271c393e5998d200e56c102ff46fcfea169aaa2148ad9e9469616fbfdd9b", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_slp_arctic.tar.bz2": "54345ed55e45c23d419e9a823eef427f1cc93c83a710735ec667d068c916abf1", # noqa: E501 + "http://festvox.org/cmu_arctic/packed/cmu_us_slt_arctic.tar.bz2": "7c173297916acf3cc7fcab2713be4c60b27312316765a90934651d367226b4ea", # noqa: E501 +} + + +def load_cmuarctic_item(line: str, path: str, folder_audio: str, ext_audio: str) -> Tuple[Tensor, int, str, str]: + + utterance_id, transcript = line[0].strip().split(" ", 2)[1:] + + # Remove space, double quote, and single parenthesis from transcript + transcript = transcript[1:-3] + + file_audio = os.path.join(path, folder_audio, utterance_id + ext_audio) + + # Load audio + waveform, sample_rate = torchaudio.load(file_audio) + + return (waveform, sample_rate, transcript, utterance_id.split("_")[1]) + + +class CMUARCTIC(Dataset): + """*CMU ARCTIC* :cite:`Kominek03cmuarctic` dataset. + + Args: + root (str or Path): Path to the directory where the dataset is found or downloaded. + url (str, optional): + The URL to download the dataset from or the type of the dataset to download. + (default: ``"aew"``) + Allowed type values are ``"aew"``, ``"ahw"``, ``"aup"``, ``"awb"``, ``"axb"``, ``"bdl"``, + ``"clb"``, ``"eey"``, ``"fem"``, ``"gka"``, ``"jmk"``, ``"ksp"``, ``"ljm"``, ``"lnh"``, + ``"rms"``, ``"rxr"``, ``"slp"`` or ``"slt"``. + folder_in_archive (str, optional): + The top-level directory of the dataset. (default: ``"ARCTIC"``) + download (bool, optional): + Whether to download the dataset if it is not found at root path. (default: ``False``). + """ + + _file_text = "txt.done.data" + _folder_text = "etc" + _ext_audio = ".wav" + _folder_audio = "wav" + + def __init__( + self, root: Union[str, Path], url: str = URL, folder_in_archive: str = FOLDER_IN_ARCHIVE, download: bool = False + ) -> None: + + if url in [ + "aew", + "ahw", + "aup", + "awb", + "axb", + "bdl", + "clb", + "eey", + "fem", + "gka", + "jmk", + "ksp", + "ljm", + "lnh", + "rms", + "rxr", + "slp", + "slt", + ]: + + url = "cmu_us_" + url + "_arctic" + ext_archive = ".tar.bz2" + base_url = "http://www.festvox.org/cmu_arctic/packed/" + + url = os.path.join(base_url, url + ext_archive) + + # Get string representation of 'root' in case Path object is passed + root = os.fspath(root) + + basename = os.path.basename(url) + root = os.path.join(root, folder_in_archive) + if not os.path.isdir(root): + os.mkdir(root) + archive = os.path.join(root, basename) + + basename = basename.split(".")[0] + + self._path = os.path.join(root, basename) + + if download: + if not os.path.isdir(self._path): + if not os.path.isfile(archive): + checksum = _CHECKSUMS.get(url, None) + download_url_to_file(url, archive, hash_prefix=checksum) + _extract_tar(archive) + else: + if not os.path.exists(self._path): + raise RuntimeError( + f"The path {self._path} doesn't exist. " + "Please check the ``root`` path or set `download=True` to download it" + ) + self._text = os.path.join(self._path, self._folder_text, self._file_text) + + with open(self._text, "r") as text: + walker = csv.reader(text, delimiter="\n") + self._walker = list(walker) + + def __getitem__(self, n: int) -> Tuple[Tensor, int, str, str]: + """Load the n-th sample from the dataset. + + Args: + n (int): The index of the sample to be loaded + + Returns: + Tuple of the following items; + + Tensor: + Waveform + int: + Sample rate + str: + Transcript + str: + Utterance ID + """ + line = self._walker[n] + return load_cmuarctic_item(line, self._path, self._folder_audio, self._ext_audio) + + def __len__(self) -> int: + return len(self._walker) diff --git a/shared/package-files/28/28093f927a433df20e7e88e21c6bcf6c5a50e4869c3e8bcf1596bb9edc9b095a/__init__.py b/shared/package-files/28/28093f927a433df20e7e88e21c6bcf6c5a50e4869c3e8bcf1596bb9edc9b095a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4cbe9d36ae89868372c9561922192a4c97b28087 --- /dev/null +++ b/shared/package-files/28/28093f927a433df20e7e88e21c6bcf6c5a50e4869c3e8bcf1596bb9edc9b095a/__init__.py @@ -0,0 +1,4 @@ +""" Unified slicing for data. +Less API, less think. +""" +from .slicer import Slicer, Alias, Obj diff --git a/shared/package-files/28/280b1439856c70aee6ce169ff0e5065a75e776baa75bddd2d49c2983d461273b/stata_lbw_glm.csv b/shared/package-files/28/280b1439856c70aee6ce169ff0e5065a75e776baa75bddd2d49c2983d461273b/stata_lbw_glm.csv new file mode 100644 index 0000000000000000000000000000000000000000..e083b5b37e42c6954d2a51fc1fb8e28a219224c6 --- /dev/null +++ b/shared/package-files/28/280b1439856c70aee6ce169ff0e5065a75e776baa75bddd2d49c2983d461273b/stata_lbw_glm.csv @@ -0,0 +1,191 @@ +id,low,age,lwt,race,smoke,ptl,ht,ui,ftv,bwt +85,0,19,182,"black",0,0,0,1,0,2523 +86,0,33,155,"other",0,0,0,0,3,2551 +87,0,20,105,"white",1,0,0,0,1,2557 +88,0,21,108,"white",1,0,0,1,2,2594 +89,0,18,107,"white",1,0,0,1,0,2600 +91,0,21,124,"other",0,0,0,0,0,2622 +92,0,22,118,"white",0,0,0,0,1,2637 +93,0,17,103,"other",0,0,0,0,1,2637 +94,0,29,123,"white",1,0,0,0,1,2663 +95,0,26,113,"white",1,0,0,0,0,2665 +96,0,19,95,"other",0,0,0,0,0,2722 +97,0,19,150,"other",0,0,0,0,1,2733 +98,0,22,95,"other",0,0,1,0,0,2750 +99,0,30,107,"other",0,1,0,1,2,2750 +100,0,18,100,"white",1,0,0,0,0,2769 +101,0,18,100,"white",1,0,0,0,0,2769 +102,0,15,98,"black",0,0,0,0,0,2778 +103,0,25,118,"white",1,0,0,0,3,2782 +104,0,20,120,"other",0,0,0,1,0,2807 +105,0,28,120,"white",1,0,0,0,1,2821 +106,0,32,121,"other",0,0,0,0,2,2835 +107,0,31,100,"white",0,0,0,1,3,2835 +108,0,36,202,"white",0,0,0,0,1,2836 +109,0,28,120,"other",0,0,0,0,0,2863 +111,0,25,120,"other",0,0,0,1,2,2877 +112,0,28,167,"white",0,0,0,0,0,2877 +113,0,17,122,"white",1,0,0,0,0,2906 +114,0,29,150,"white",0,0,0,0,2,2920 +115,0,26,168,"black",1,0,0,0,0,2920 +116,0,17,113,"black",0,0,0,0,1,2920 +117,0,17,113,"black",0,0,0,0,1,2920 +118,0,24,90,"white",1,1,0,0,1,2948 +119,0,35,121,"black",1,1,0,0,1,2948 +120,0,25,155,"white",0,0,0,0,1,2977 +121,0,25,125,"black",0,0,0,0,0,2977 +123,0,29,140,"white",1,0,0,0,2,2977 +124,0,19,138,"white",1,0,0,0,2,2977 +125,0,27,124,"white",1,0,0,0,0,2922 +126,0,31,215,"white",1,0,0,0,2,3005 +127,0,33,109,"white",1,0,0,0,1,3033 +128,0,21,185,"black",1,0,0,0,2,3042 +129,0,19,189,"white",0,0,0,0,2,3062 +130,0,23,130,"black",0,0,0,0,1,3062 +131,0,21,160,"white",0,0,0,0,0,3062 +132,0,18,90,"white",1,0,0,1,0,3076 +133,0,18,90,"white",1,0,0,1,0,3076 +134,0,32,132,"white",0,0,0,0,4,3080 +135,0,19,132,"other",0,0,0,0,0,3090 +136,0,24,115,"white",0,0,0,0,2,3090 +137,0,22,85,"other",1,0,0,0,0,3090 +138,0,22,120,"white",0,0,1,0,1,3100 +139,0,23,128,"other",0,0,0,0,0,3104 +140,0,22,130,"white",1,0,0,0,0,3132 +141,0,30,95,"white",1,0,0,0,2,3147 +142,0,19,115,"other",0,0,0,0,0,3175 +143,0,16,110,"other",0,0,0,0,0,3175 +144,0,21,110,"other",1,0,0,1,0,3203 +145,0,30,153,"other",0,0,0,0,0,3203 +146,0,20,103,"other",0,0,0,0,0,3203 +147,0,17,119,"other",0,0,0,0,0,3225 +148,0,17,119,"other",0,0,0,0,0,3225 +149,0,23,119,"other",0,0,0,0,2,3232 +150,0,24,110,"other",0,0,0,0,0,3232 +151,0,28,140,"white",0,0,0,0,0,3234 +154,0,26,133,"other",1,2,0,0,0,3260 +155,0,20,169,"other",0,1,0,1,1,3274 +156,0,24,115,"other",0,0,0,0,2,3274 +159,0,28,250,"other",1,0,0,0,6,3303 +160,0,20,141,"white",0,2,0,1,1,3317 +161,0,22,158,"black",0,1,0,0,2,3317 +162,0,22,112,"white",1,2,0,0,0,3317 +163,0,31,150,"other",1,0,0,0,2,3321 +164,0,23,115,"other",1,0,0,0,1,3331 +166,0,16,112,"black",0,0,0,0,0,3374 +167,0,16,135,"white",1,0,0,0,0,3374 +168,0,18,229,"black",0,0,0,0,0,3402 +169,0,25,140,"white",0,0,0,0,1,3416 +170,0,32,134,"white",1,1,0,0,4,3430 +172,0,20,121,"black",1,0,0,0,0,3444 +173,0,23,190,"white",0,0,0,0,0,3459 +174,0,22,131,"white",0,0,0,0,1,3460 +175,0,32,170,"white",0,0,0,0,0,3473 +176,0,30,110,"other",0,0,0,0,0,3475 +177,0,20,127,"other",0,0,0,0,0,3487 +179,0,23,123,"other",0,0,0,0,0,3544 +180,0,17,120,"other",1,0,0,0,0,3572 +181,0,19,105,"other",0,0,0,0,0,3572 +182,0,23,130,"white",0,0,0,0,0,3586 +183,0,36,175,"white",0,0,0,0,0,3600 +184,0,22,125,"white",0,0,0,0,1,3614 +185,0,24,133,"white",0,0,0,0,0,3614 +186,0,21,134,"other",0,0,0,0,2,3629 +187,0,19,235,"white",1,0,1,0,0,3629 +188,0,25,95,"white",1,3,0,1,0,3637 +189,0,16,135,"white",1,0,0,0,0,3643 +190,0,29,135,"white",0,0,0,0,1,3651 +191,0,29,154,"white",0,0,0,0,1,3651 +192,0,19,147,"white",1,0,0,0,0,3651 +193,0,19,147,"white",1,0,0,0,0,3651 +195,0,30,137,"white",0,0,0,0,1,3699 +196,0,24,110,"white",0,0,0,0,1,3728 +197,0,19,184,"white",1,0,1,0,0,3756 +199,0,24,110,"other",0,1,0,0,0,3770 +200,0,23,110,"white",0,0,0,0,1,3770 +201,0,20,120,"other",0,0,0,0,0,3770 +202,0,25,241,"black",0,0,1,0,0,3790 +203,0,30,112,"white",0,0,0,0,1,3799 +204,0,22,169,"white",0,0,0,0,0,3827 +205,0,18,120,"white",1,0,0,0,2,3856 +206,0,16,170,"black",0,0,0,0,4,3860 +207,0,32,186,"white",0,0,0,0,2,3860 +208,0,18,120,"other",0,0,0,0,1,3884 +209,0,29,130,"white",1,0,0,0,2,3884 +210,0,33,117,"white",0,0,0,1,1,3912 +211,0,20,170,"white",1,0,0,0,0,3940 +212,0,28,134,"other",0,0,0,0,1,3941 +213,0,14,135,"white",0,0,0,0,0,3941 +214,0,28,130,"other",0,0,0,0,0,3969 +215,0,25,120,"white",0,0,0,0,2,3983 +216,0,16,95,"other",0,0,0,0,1,3997 +217,0,20,158,"white",0,0,0,0,1,3997 +218,0,26,160,"other",0,0,0,0,0,4054 +219,0,21,115,"white",0,0,0,0,1,4054 +220,0,22,129,"white",0,0,0,0,0,4111 +221,0,25,130,"white",0,0,0,0,2,4153 +222,0,31,120,"white",0,0,0,0,2,4167 +223,0,35,170,"white",0,1,0,0,1,4174 +224,0,19,120,"white",1,0,0,0,0,4238 +225,0,24,116,"white",0,0,0,0,1,4593 +226,0,45,123,"white",0,0,0,0,1,4990 +4,1,28,120,"other",1,1,0,1,0,709 +10,1,29,130,"white",0,0,0,1,2,1021 +11,1,34,187,"black",1,0,1,0,0,1135 +13,1,25,105,"other",0,1,1,0,0,1330 +15,1,25,85,"other",0,0,0,1,0,1474 +16,1,27,150,"other",0,0,0,0,0,1588 +17,1,23,97,"other",0,0,0,1,1,1588 +18,1,24,128,"black",0,1,0,0,1,1701 +19,1,24,132,"other",0,0,1,0,0,1729 +20,1,21,165,"white",1,0,1,0,1,1790 +22,1,32,105,"white",1,0,0,0,0,1818 +23,1,19,91,"white",1,2,0,1,0,1885 +24,1,25,115,"other",0,0,0,0,0,1893 +25,1,16,130,"other",0,0,0,0,1,1899 +26,1,25,92,"white",1,0,0,0,0,1928 +27,1,20,150,"white",1,0,0,0,2,1928 +28,1,21,200,"black",0,0,0,1,2,1928 +29,1,24,155,"white",1,1,0,0,0,1936 +30,1,21,103,"other",0,0,0,0,0,1970 +31,1,20,125,"other",0,0,0,1,0,2055 +32,1,25,89,"other",0,2,0,0,1,2055 +33,1,19,102,"white",0,0,0,0,2,2082 +34,1,19,112,"white",1,0,0,1,0,2084 +35,1,26,117,"white",1,1,0,0,0,2084 +36,1,24,138,"white",0,0,0,0,0,2100 +37,1,17,130,"other",1,1,0,1,0,2125 +40,1,20,120,"black",1,0,0,0,3,2126 +42,1,22,130,"white",1,1,0,1,1,2187 +43,1,27,130,"black",0,0,0,1,0,2187 +44,1,20,80,"other",1,0,0,1,0,2211 +45,1,17,110,"white",1,0,0,0,0,2225 +46,1,25,105,"other",0,1,0,0,1,2240 +47,1,20,109,"other",0,0,0,0,0,2240 +49,1,18,148,"other",0,0,0,0,0,2282 +50,1,18,110,"black",1,1,0,0,0,2296 +51,1,20,121,"white",1,1,0,1,0,2296 +52,1,21,100,"other",0,1,0,0,4,2301 +54,1,26,96,"other",0,0,0,0,0,2325 +56,1,31,102,"white",1,1,0,0,1,2353 +57,1,15,110,"white",0,0,0,0,0,2353 +59,1,23,187,"black",1,0,0,0,1,2367 +60,1,20,122,"black",1,0,0,0,0,2381 +61,1,24,105,"black",1,0,0,0,0,2381 +62,1,15,115,"other",0,0,0,1,0,2381 +63,1,23,120,"other",0,0,0,0,0,2395 +65,1,30,142,"white",1,1,0,0,0,2410 +67,1,22,130,"white",1,0,0,0,1,2410 +68,1,17,120,"white",1,0,0,0,3,2414 +69,1,23,110,"white",1,1,0,0,0,2424 +71,1,17,120,"black",0,0,0,0,2,2438 +75,1,26,154,"other",0,1,1,0,1,2442 +76,1,20,106,"other",0,0,0,0,3,2450 +77,1,26,190,"white",1,0,0,0,0,2466 +78,1,14,101,"other",1,1,0,0,0,2466 +79,1,28,95,"white",1,0,0,0,2,2466 +81,1,14,100,"other",0,0,0,0,2,2495 +82,1,23,94,"other",1,0,0,0,0,2495 +83,1,17,142,"black",0,0,1,0,0,2495 +84,1,21,130,"white",1,0,1,0,3,2495 + diff --git a/shared/package-files/28/280cac9b0bb3520a8a2119b73c1ece0c9b90d8e299654c9f3f2a79659c787e3d/linalg_householder_product_ops.h b/shared/package-files/28/280cac9b0bb3520a8a2119b73c1ece0c9b90d8e299654c9f3f2a79659c787e3d/linalg_householder_product_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f4abedf4910d3717b83d1631888a7bd4ce7d39c4 --- /dev/null +++ b/shared/package-files/28/280cac9b0bb3520a8a2119b73c1ece0c9b90d8e299654c9f3f2a79659c787e3d/linalg_householder_product_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 linalg_householder_product { + 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::linalg_householder_product") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_householder_product(Tensor input, Tensor tau) -> Tensor") + static at::Tensor call(const at::Tensor & input, const at::Tensor & tau); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & tau); +}; + +struct TORCH_API linalg_householder_product_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::linalg_householder_product") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_householder_product.out(Tensor input, Tensor tau, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & input, const at::Tensor & tau, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & tau, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/28/280fb0fe7a5f9c733fd5ce6daed26d91ddce0fd8fc86ab684006381820b95202/html.tpl b/shared/package-files/28/280fb0fe7a5f9c733fd5ce6daed26d91ddce0fd8fc86ab684006381820b95202/html.tpl new file mode 100644 index 0000000000000000000000000000000000000000..8c63be3ad788a8abddf3588b2b9dd6d6126f5df3 --- /dev/null +++ b/shared/package-files/28/280fb0fe7a5f9c733fd5ce6daed26d91ddce0fd8fc86ab684006381820b95202/html.tpl @@ -0,0 +1,16 @@ +{# Update the html_style/table_structure.html documentation too #} +{% if doctype_html %} + + + + +{% if not exclude_styles %}{% include html_style_tpl %}{% endif %} + + +{% include html_table_tpl %} + + +{% elif not doctype_html %} +{% if not exclude_styles %}{% include html_style_tpl %}{% endif %} +{% include html_table_tpl %} +{% endif %} diff --git a/shared/package-files/28/280fe1576c72d9345c70cca4b12cd0add1fdfeb746a37b50c87388beb5966014/schema_util.h b/shared/package-files/28/280fe1576c72d9345c70cca4b12cd0add1fdfeb746a37b50c87388beb5966014/schema_util.h new file mode 100644 index 0000000000000000000000000000000000000000..db3076a58841a6cb85fcc3d5033ef3b74ed18898 --- /dev/null +++ b/shared/package-files/28/280fe1576c72d9345c70cca4b12cd0add1fdfeb746a37b50c87388beb5966014/schema_util.h @@ -0,0 +1,226 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/type.h" // for DataType, FieldRef, Field and Schema + +namespace arrow { + +using internal::checked_cast; + +namespace acero { + +// Identifiers for all different row schemas that are used in a join +// +enum class HashJoinProjection : int { + INPUT = 0, + KEY = 1, + PAYLOAD = 2, + FILTER = 3, + OUTPUT = 4 +}; + +struct SchemaProjectionMap { + static constexpr int kMissingField = -1; + int num_cols; + const int* source_to_base; + const int* base_to_target; + inline int get(int i) const { + assert(i >= 0 && i < num_cols); + assert(source_to_base[i] != kMissingField); + return base_to_target[source_to_base[i]]; + } +}; + +/// Helper class for managing different projections of the same row schema. +/// Used to efficiently map any field in one projection to a corresponding field in +/// another projection. +/// Materialized mappings are generated lazily at the time of the first access. +/// Thread-safe apart from initialization. +template +class SchemaProjectionMaps { + public: + static constexpr int kMissingField = -1; + + Status Init(ProjectionIdEnum full_schema_handle, const Schema& schema, + const std::vector& projection_handles, + const std::vector*>& projections) { + assert(projection_handles.size() == projections.size()); + ARROW_RETURN_NOT_OK(RegisterSchema(full_schema_handle, schema)); + for (size_t i = 0; i < projections.size(); ++i) { + ARROW_RETURN_NOT_OK( + RegisterProjectedSchema(projection_handles[i], *(projections[i]), schema)); + } + RegisterEnd(); + return Status::OK(); + } + + int num_cols(ProjectionIdEnum schema_handle) const { + int id = schema_id(schema_handle); + return static_cast(schemas_[id].second.data_types.size()); + } + + bool is_empty(ProjectionIdEnum schema_handle) const { + return num_cols(schema_handle) == 0; + } + + const std::string& field_name(ProjectionIdEnum schema_handle, int field_id) const { + int id = schema_id(schema_handle); + return schemas_[id].second.field_names[field_id]; + } + + const std::shared_ptr& data_type(ProjectionIdEnum schema_handle, + int field_id) const { + int id = schema_id(schema_handle); + return schemas_[id].second.data_types[field_id]; + } + + const std::vector>& data_types( + ProjectionIdEnum schema_handle) const { + int id = schema_id(schema_handle); + return schemas_[id].second.data_types; + } + + SchemaProjectionMap map(ProjectionIdEnum from, ProjectionIdEnum to) const { + int id_from = schema_id(from); + int id_to = schema_id(to); + SchemaProjectionMap result; + result.num_cols = num_cols(from); + result.source_to_base = mappings_[id_from].data(); + result.base_to_target = inverse_mappings_[id_to].data(); + return result; + } + + protected: + struct FieldInfos { + std::vector field_paths; + std::vector field_names; + std::vector> data_types; + }; + + Status RegisterSchema(ProjectionIdEnum handle, const Schema& schema) { + FieldInfos out_fields; + const FieldVector& in_fields = schema.fields(); + out_fields.field_paths.resize(in_fields.size()); + out_fields.field_names.resize(in_fields.size()); + out_fields.data_types.resize(in_fields.size()); + for (size_t i = 0; i < in_fields.size(); ++i) { + const std::string& name = in_fields[i]->name(); + const std::shared_ptr& type = in_fields[i]->type(); + out_fields.field_paths[i] = static_cast(i); + out_fields.field_names[i] = name; + out_fields.data_types[i] = type; + } + schemas_.push_back(std::make_pair(handle, out_fields)); + return Status::OK(); + } + + Status RegisterProjectedSchema(ProjectionIdEnum handle, + const std::vector& selected_fields, + const Schema& full_schema) { + FieldInfos out_fields; + const FieldVector& in_fields = full_schema.fields(); + out_fields.field_paths.resize(selected_fields.size()); + out_fields.field_names.resize(selected_fields.size()); + out_fields.data_types.resize(selected_fields.size()); + for (size_t i = 0; i < selected_fields.size(); ++i) { + // All fields must be found in schema without ambiguity + ARROW_ASSIGN_OR_RAISE(auto match, selected_fields[i].FindOne(full_schema)); + const std::string& name = in_fields[match[0]]->name(); + const std::shared_ptr& type = in_fields[match[0]]->type(); + out_fields.field_paths[i] = match[0]; + out_fields.field_names[i] = name; + out_fields.data_types[i] = type; + } + schemas_.push_back(std::make_pair(handle, out_fields)); + return Status::OK(); + } + + void RegisterEnd() { + size_t size = schemas_.size(); + mappings_.resize(size); + inverse_mappings_.resize(size); + int id_base = 0; + for (size_t i = 0; i < size; ++i) { + GenerateMapForProjection(static_cast(i), id_base); + } + } + + int schema_id(ProjectionIdEnum schema_handle) const { + for (size_t i = 0; i < schemas_.size(); ++i) { + if (schemas_[i].first == schema_handle) { + return static_cast(i); + } + } + // We should never get here + assert(false); + return -1; + } + + void GenerateMapForProjection(int id_proj, int id_base) { + int num_cols_proj = static_cast(schemas_[id_proj].second.data_types.size()); + int num_cols_base = static_cast(schemas_[id_base].second.data_types.size()); + + std::vector& mapping = mappings_[id_proj]; + std::vector& inverse_mapping = inverse_mappings_[id_proj]; + mapping.resize(num_cols_proj); + inverse_mapping.resize(num_cols_base); + + if (id_proj == id_base) { + for (int i = 0; i < num_cols_base; ++i) { + mapping[i] = inverse_mapping[i] = i; + } + } else { + const FieldInfos& fields_proj = schemas_[id_proj].second; + const FieldInfos& fields_base = schemas_[id_base].second; + for (int i = 0; i < num_cols_base; ++i) { + inverse_mapping[i] = SchemaProjectionMap::kMissingField; + } + for (int i = 0; i < num_cols_proj; ++i) { + int field_id = SchemaProjectionMap::kMissingField; + for (int j = 0; j < num_cols_base; ++j) { + if (fields_proj.field_paths[i] == fields_base.field_paths[j]) { + field_id = j; + // If there are multiple matches for the same input field, + // it will be mapped to the first match. + break; + } + } + assert(field_id != SchemaProjectionMap::kMissingField); + mapping[i] = field_id; + inverse_mapping[field_id] = i; + } + } + } + + // vector used as a mapping from ProjectionIdEnum to fields + std::vector> schemas_; + std::vector> mappings_; + std::vector> inverse_mappings_; +}; + +using HashJoinProjectionMaps = SchemaProjectionMaps; + +} // namespace acero +} // namespace arrow diff --git a/shared/package-files/28/28125c2d1006d8c7880fd577f3e1818a97e9b055861abc4e2a481f4909a08d71/_typing.py b/shared/package-files/28/28125c2d1006d8c7880fd577f3e1818a97e9b055861abc4e2a481f4909a08d71/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..07f3850d21fade94814f9fe1e638286c72a1c552 --- /dev/null +++ b/shared/package-files/28/28125c2d1006d8c7880fd577f3e1818a97e9b055861abc4e2a481f4909a08d71/_typing.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +__all__ = [ + "NestedSequence", + "SupportsBufferProtocol", +] + +from typing import ( + Any, + TypeVar, + Protocol, +) + +_T_co = TypeVar("_T_co", covariant=True) + +class NestedSequence(Protocol[_T_co]): + def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ... + def __len__(self, /) -> int: ... + +SupportsBufferProtocol = Any + +Array = Any +Device = Any diff --git a/shared/package-files/28/2814673cc36e08829fce3840c0c14832ef333f24c15097254725b9ac9e2cde93/eq_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/28/2814673cc36e08829fce3840c0c14832ef333f24c15097254725b9ac9e2cde93/eq_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e425e5a5f0b35240cd8c309ed4aae6877e5d6e2c --- /dev/null +++ b/shared/package-files/28/2814673cc36e08829fce3840c0c14832ef333f24c15097254725b9ac9e2cde93/eq_compositeexplicitautogradnonfunctional_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 compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor eq(const at::Tensor & self, const at::Scalar & other); +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_(at::Tensor & self, const at::Tensor & other); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/28/2817aef832190676c0593be50c83cd200ecf318df014e0c76c047497e913a0b7/Generator.h b/shared/package-files/28/2817aef832190676c0593be50c83cd200ecf318df014e0c76c047497e913a0b7/Generator.h new file mode 100644 index 0000000000000000000000000000000000000000..48c25e141dcb8c0264ca9435352889c7a250f74d --- /dev/null +++ b/shared/package-files/28/2817aef832190676c0593be50c83cd200ecf318df014e0c76c047497e913a0b7/Generator.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/shared/package-files/28/28186bd275a4d5fb3bc037da932cda61124f82e9ca90777a613ad97930d09fc7/gnpdef.csv b/shared/package-files/28/28186bd275a4d5fb3bc037da932cda61124f82e9ca90777a613ad97930d09fc7/gnpdef.csv new file mode 100644 index 0000000000000000000000000000000000000000..bf5ad98b66eab0794168b08d72ad792628d85313 --- /dev/null +++ b/shared/package-files/28/28186bd275a4d5fb3bc037da932cda61124f82e9ca90777a613ad97930d09fc7/gnpdef.csv @@ -0,0 +1,83 @@ +GNP_DEFLATOR +3.254242969 +3.234749174 +3.214867803 +3.17805383 +3.198673118 +3.135494216 +3.122364924 +3.095577609 +3.100092289 +3.131136911 +3.161246712 +3.206803244 +3.198673118 +3.234749174 +3.246490992 +3.258096538 +3.277144733 +3.303216973 +3.342861805 +3.335769576 +3.370738174 +3.39785848 +3.391147046 +3.430756184 +3.437207819 +3.446807893 +3.481240089 +3.597312261 +3.80666249 +3.96271612 +3.985273467 +4.115779843 +3.955082495 +3.90197267 +3.925925911 +3.914021008 +3.931825633 +3.935739532 +3.912023005 +3.919991175 +3.923951576 +3.897924081 +3.802208139 +3.693866996 +3.671224519 +3.742420221 +3.751854253 +3.75419892 +3.795489189 +3.78191432 +3.765840495 +3.78191432 +3.854393893 +3.970291914 +4.039536326 +4.063885355 +4.08933202 +4.200204953 +4.312140507 +4.377014093 +4.370712875 +4.384523515 +4.449685283 +4.471638793 +4.480740108 +4.49535532 +4.509760001 +4.543294782 +4.579852378 +4.605170186 +4.621043535 +4.637637376 +4.650143552 +4.661550519 +4.674696249 +4.689511334 +4.708628894 +4.73532087 +4.767289035 +4.806477043 +4.853591544 +4.907494535 diff --git a/shared/package-files/28/2819983c8178f52ab7e256f36c5099458592c887619d1dc02b7abe55b53a82b5/test_constants.py b/shared/package-files/28/2819983c8178f52ab7e256f36c5099458592c887619d1dc02b7abe55b53a82b5/test_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..48a773ea6b5afbaf956143b50b16b3b18aaf5beb --- /dev/null +++ b/shared/package-files/28/2819983c8178f52ab7e256f36c5099458592c887619d1dc02b7abe55b53a82b5/test_constants.py @@ -0,0 +1,13 @@ +from sympy.core.numbers import Float + +from sympy.physics.quantum.constants import hbar + + +def test_hbar(): + assert hbar.is_commutative is True + assert hbar.is_real is True + assert hbar.is_positive is True + assert hbar.is_negative is False + assert hbar.is_irrational is True + + assert hbar.evalf() == Float(1.05457162e-34) diff --git a/shared/package-files/28/2819dd523b396154b7dbe21dddf7e50df620a5d5b53ebc7acdfa3c133e506ebb/libmpc.py b/shared/package-files/28/2819dd523b396154b7dbe21dddf7e50df620a5d5b53ebc7acdfa3c133e506ebb/libmpc.py new file mode 100644 index 0000000000000000000000000000000000000000..cc22d0e73674676c8a9249ebc2d48da7f3be8b0d --- /dev/null +++ b/shared/package-files/28/2819dd523b396154b7dbe21dddf7e50df620a5d5b53ebc7acdfa3c133e506ebb/libmpc.py @@ -0,0 +1,835 @@ +""" +Low-level functions for complex arithmetic. +""" + +import sys + +from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, BACKEND + +from .libmpf import (\ + round_floor, round_ceiling, round_down, round_up, + round_nearest, round_fast, bitcount, + bctable, normalize, normalize1, reciprocal_rnd, rshift, lshift, giant_steps, + negative_rnd, + to_str, to_fixed, from_man_exp, from_float, to_float, from_int, to_int, + fzero, fone, ftwo, fhalf, finf, fninf, fnan, fnone, + mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, + mpf_div, mpf_mul_int, mpf_shift, mpf_sqrt, mpf_hypot, + mpf_rdiv_int, mpf_floor, mpf_ceil, mpf_nint, mpf_frac, + mpf_sign, mpf_hash, + ComplexResult +) + +from .libelefun import (\ + mpf_pi, mpf_exp, mpf_log, mpf_cos_sin, mpf_cosh_sinh, mpf_tan, mpf_pow_int, + mpf_log_hypot, + mpf_cos_sin_pi, mpf_phi, + mpf_cos, mpf_sin, mpf_cos_pi, mpf_sin_pi, + mpf_atan, mpf_atan2, mpf_cosh, mpf_sinh, mpf_tanh, + mpf_asin, mpf_acos, mpf_acosh, mpf_nthroot, mpf_fibonacci +) + +# An mpc value is a (real, imag) tuple +mpc_one = fone, fzero +mpc_zero = fzero, fzero +mpc_two = ftwo, fzero +mpc_half = (fhalf, fzero) + +_infs = (finf, fninf) +_infs_nan = (finf, fninf, fnan) + +def mpc_is_inf(z): + """Check if either real or imaginary part is infinite""" + re, im = z + if re in _infs: return True + if im in _infs: return True + return False + +def mpc_is_infnan(z): + """Check if either real or imaginary part is infinite or nan""" + re, im = z + if re in _infs_nan: return True + if im in _infs_nan: return True + return False + +def mpc_to_str(z, dps, **kwargs): + re, im = z + rs = to_str(re, dps) + if im[0]: + return rs + " - " + to_str(mpf_neg(im), dps, **kwargs) + "j" + else: + return rs + " + " + to_str(im, dps, **kwargs) + "j" + +def mpc_to_complex(z, strict=False, rnd=round_fast): + re, im = z + return complex(to_float(re, strict, rnd), to_float(im, strict, rnd)) + +def mpc_hash(z): + if sys.version_info >= (3, 2): + re, im = z + h = mpf_hash(re) + sys.hash_info.imag * mpf_hash(im) + # Need to reduce either module 2^32 or 2^64 + h = h % (2**sys.hash_info.width) + return int(h) + else: + try: + return hash(mpc_to_complex(z, strict=True)) + except OverflowError: + return hash(z) + +def mpc_conjugate(z, prec, rnd=round_fast): + re, im = z + return re, mpf_neg(im, prec, rnd) + +def mpc_is_nonzero(z): + return z != mpc_zero + +def mpc_add(z, w, prec, rnd=round_fast): + a, b = z + c, d = w + return mpf_add(a, c, prec, rnd), mpf_add(b, d, prec, rnd) + +def mpc_add_mpf(z, x, prec, rnd=round_fast): + a, b = z + return mpf_add(a, x, prec, rnd), b + +def mpc_sub(z, w, prec=0, rnd=round_fast): + a, b = z + c, d = w + return mpf_sub(a, c, prec, rnd), mpf_sub(b, d, prec, rnd) + +def mpc_sub_mpf(z, p, prec=0, rnd=round_fast): + a, b = z + return mpf_sub(a, p, prec, rnd), b + +def mpc_pos(z, prec, rnd=round_fast): + a, b = z + return mpf_pos(a, prec, rnd), mpf_pos(b, prec, rnd) + +def mpc_neg(z, prec=None, rnd=round_fast): + a, b = z + return mpf_neg(a, prec, rnd), mpf_neg(b, prec, rnd) + +def mpc_shift(z, n): + a, b = z + return mpf_shift(a, n), mpf_shift(b, n) + +def mpc_abs(z, prec, rnd=round_fast): + """Absolute value of a complex number, |a+bi|. + Returns an mpf value.""" + a, b = z + return mpf_hypot(a, b, prec, rnd) + +def mpc_arg(z, prec, rnd=round_fast): + """Argument of a complex number. Returns an mpf value.""" + a, b = z + return mpf_atan2(b, a, prec, rnd) + +def mpc_floor(z, prec, rnd=round_fast): + a, b = z + return mpf_floor(a, prec, rnd), mpf_floor(b, prec, rnd) + +def mpc_ceil(z, prec, rnd=round_fast): + a, b = z + return mpf_ceil(a, prec, rnd), mpf_ceil(b, prec, rnd) + +def mpc_nint(z, prec, rnd=round_fast): + a, b = z + return mpf_nint(a, prec, rnd), mpf_nint(b, prec, rnd) + +def mpc_frac(z, prec, rnd=round_fast): + a, b = z + return mpf_frac(a, prec, rnd), mpf_frac(b, prec, rnd) + + +def mpc_mul(z, w, prec, rnd=round_fast): + """ + Complex multiplication. + + Returns the real and imaginary part of (a+bi)*(c+di), rounded to + the specified precision. The rounding mode applies to the real and + imaginary parts separately. + """ + a, b = z + c, d = w + p = mpf_mul(a, c) + q = mpf_mul(b, d) + r = mpf_mul(a, d) + s = mpf_mul(b, c) + re = mpf_sub(p, q, prec, rnd) + im = mpf_add(r, s, prec, rnd) + return re, im + +def mpc_square(z, prec, rnd=round_fast): + # (a+b*I)**2 == a**2 - b**2 + 2*I*a*b + a, b = z + p = mpf_mul(a,a) + q = mpf_mul(b,b) + r = mpf_mul(a,b, prec, rnd) + re = mpf_sub(p, q, prec, rnd) + im = mpf_shift(r, 1) + return re, im + +def mpc_mul_mpf(z, p, prec, rnd=round_fast): + a, b = z + re = mpf_mul(a, p, prec, rnd) + im = mpf_mul(b, p, prec, rnd) + return re, im + +def mpc_mul_imag_mpf(z, x, prec, rnd=round_fast): + """ + Multiply the mpc value z by I*x where x is an mpf value. + """ + a, b = z + re = mpf_neg(mpf_mul(b, x, prec, rnd)) + im = mpf_mul(a, x, prec, rnd) + return re, im + +def mpc_mul_int(z, n, prec, rnd=round_fast): + a, b = z + re = mpf_mul_int(a, n, prec, rnd) + im = mpf_mul_int(b, n, prec, rnd) + return re, im + +def mpc_div(z, w, prec, rnd=round_fast): + a, b = z + c, d = w + wp = prec + 10 + # mag = c*c + d*d + mag = mpf_add(mpf_mul(c, c), mpf_mul(d, d), wp) + # (a*c+b*d)/mag, (b*c-a*d)/mag + t = mpf_add(mpf_mul(a,c), mpf_mul(b,d), wp) + u = mpf_sub(mpf_mul(b,c), mpf_mul(a,d), wp) + return mpf_div(t,mag,prec,rnd), mpf_div(u,mag,prec,rnd) + +def mpc_div_mpf(z, p, prec, rnd=round_fast): + """Calculate z/p where p is real""" + a, b = z + re = mpf_div(a, p, prec, rnd) + im = mpf_div(b, p, prec, rnd) + return re, im + +def mpc_reciprocal(z, prec, rnd=round_fast): + """Calculate 1/z efficiently""" + a, b = z + m = mpf_add(mpf_mul(a,a),mpf_mul(b,b),prec+10) + re = mpf_div(a, m, prec, rnd) + im = mpf_neg(mpf_div(b, m, prec, rnd)) + return re, im + +def mpc_mpf_div(p, z, prec, rnd=round_fast): + """Calculate p/z where p is real efficiently""" + a, b = z + m = mpf_add(mpf_mul(a,a),mpf_mul(b,b), prec+10) + re = mpf_div(mpf_mul(a,p), m, prec, rnd) + im = mpf_div(mpf_neg(mpf_mul(b,p)), m, prec, rnd) + return re, im + +def complex_int_pow(a, b, n): + """Complex integer power: computes (a+b*I)**n exactly for + nonnegative n (a and b must be Python ints).""" + wre = 1 + wim = 0 + while n: + if n & 1: + wre, wim = wre*a - wim*b, wim*a + wre*b + n -= 1 + a, b = a*a - b*b, 2*a*b + n //= 2 + return wre, wim + +def mpc_pow(z, w, prec, rnd=round_fast): + if w[1] == fzero: + return mpc_pow_mpf(z, w[0], prec, rnd) + return mpc_exp(mpc_mul(mpc_log(z, prec+10), w, prec+10), prec, rnd) + +def mpc_pow_mpf(z, p, prec, rnd=round_fast): + psign, pman, pexp, pbc = p + if pexp >= 0: + return mpc_pow_int(z, (-1)**psign * (pman< 0: + aman <<= de + aexp = bexp + else: + bman <<= (-de) + bexp = aexp + re, im = complex_int_pow(aman, bman, n) + re = from_man_exp(re, int(n*aexp), prec, rnd) + im = from_man_exp(im, int(n*bexp), prec, rnd) + return re, im + return mpc_exp(mpc_mul_int(mpc_log(z, prec+10), n, prec+10), prec, rnd) + +def mpc_sqrt(z, prec, rnd=round_fast): + """Complex square root (principal branch). + + We have sqrt(a+bi) = sqrt((r+a)/2) + b/sqrt(2*(r+a))*i where + r = abs(a+bi), when a+bi is not a negative real number.""" + a, b = z + if b == fzero: + if a == fzero: + return (a, b) + # When a+bi is a negative real number, we get a real sqrt times i + if a[0]: + im = mpf_sqrt(mpf_neg(a), prec, rnd) + return (fzero, im) + else: + re = mpf_sqrt(a, prec, rnd) + return (re, fzero) + wp = prec+20 + if not a[0]: # case a positive + t = mpf_add(mpc_abs((a, b), wp), a, wp) # t = abs(a+bi) + a + u = mpf_shift(t, -1) # u = t/2 + re = mpf_sqrt(u, prec, rnd) # re = sqrt(u) + v = mpf_shift(t, 1) # v = 2*t + w = mpf_sqrt(v, wp) # w = sqrt(v) + im = mpf_div(b, w, prec, rnd) # im = b / w + else: # case a negative + t = mpf_sub(mpc_abs((a, b), wp), a, wp) # t = abs(a+bi) - a + u = mpf_shift(t, -1) # u = t/2 + im = mpf_sqrt(u, prec, rnd) # im = sqrt(u) + v = mpf_shift(t, 1) # v = 2*t + w = mpf_sqrt(v, wp) # w = sqrt(v) + re = mpf_div(b, w, prec, rnd) # re = b/w + if b[0]: + re = mpf_neg(re) + im = mpf_neg(im) + return re, im + +def mpc_nthroot_fixed(a, b, n, prec): + # a, b signed integers at fixed precision prec + start = 50 + a1 = int(rshift(a, prec - n*start)) + b1 = int(rshift(b, prec - n*start)) + try: + r = (a1 + 1j * b1)**(1.0/n) + re = r.real + im = r.imag + re = MPZ(int(re)) + im = MPZ(int(im)) + except OverflowError: + a1 = from_int(a1, start) + b1 = from_int(b1, start) + fn = from_int(n) + nth = mpf_rdiv_int(1, fn, start) + re, im = mpc_pow((a1, b1), (nth, fzero), start) + re = to_int(re) + im = to_int(im) + extra = 10 + prevp = start + extra1 = n + for p in giant_steps(start, prec+extra): + # this is slow for large n, unlike int_pow_fixed + re2, im2 = complex_int_pow(re, im, n-1) + re2 = rshift(re2, (n-1)*prevp - p - extra1) + im2 = rshift(im2, (n-1)*prevp - p - extra1) + r4 = (re2*re2 + im2*im2) >> (p + extra1) + ap = rshift(a, prec - p) + bp = rshift(b, prec - p) + rec = (ap * re2 + bp * im2) >> p + imc = (-ap * im2 + bp * re2) >> p + reb = (rec << p) // r4 + imb = (imc << p) // r4 + re = (reb + (n-1)*lshift(re, p-prevp))//n + im = (imb + (n-1)*lshift(im, p-prevp))//n + prevp = p + return re, im + +def mpc_nthroot(z, n, prec, rnd=round_fast): + """ + Complex n-th root. + + Use Newton method as in the real case when it is faster, + otherwise use z**(1/n) + """ + a, b = z + if a[0] == 0 and b == fzero: + re = mpf_nthroot(a, n, prec, rnd) + return (re, fzero) + if n < 2: + if n == 0: + return mpc_one + if n == 1: + return mpc_pos((a, b), prec, rnd) + if n == -1: + return mpc_div(mpc_one, (a, b), prec, rnd) + inverse = mpc_nthroot((a, b), -n, prec+5, reciprocal_rnd[rnd]) + return mpc_div(mpc_one, inverse, prec, rnd) + if n <= 20: + prec2 = int(1.2 * (prec + 10)) + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + pf = mpc_abs((a,b), prec) + if pf[-2] + pf[-1] > -10 and pf[-2] + pf[-1] < prec: + af = to_fixed(a, prec2) + bf = to_fixed(b, prec2) + re, im = mpc_nthroot_fixed(af, bf, n, prec2) + extra = 10 + re = from_man_exp(re, -prec2-extra, prec2, rnd) + im = from_man_exp(im, -prec2-extra, prec2, rnd) + return re, im + fn = from_int(n) + prec2 = prec+10 + 10 + nth = mpf_rdiv_int(1, fn, prec2) + re, im = mpc_pow((a, b), (nth, fzero), prec2, rnd) + re = normalize(re[0], re[1], re[2], re[3], prec, rnd) + im = normalize(im[0], im[1], im[2], im[3], prec, rnd) + return re, im + +def mpc_cbrt(z, prec, rnd=round_fast): + """ + Complex cubic root. + """ + return mpc_nthroot(z, 3, prec, rnd) + +def mpc_exp(z, prec, rnd=round_fast): + """ + Complex exponential function. + + We use the direct formula exp(a+bi) = exp(a) * (cos(b) + sin(b)*i) + for the computation. This formula is very nice because it is + pefectly stable; since we just do real multiplications, the only + numerical errors that can creep in are single-ulp rounding errors. + + The formula is efficient since mpmath's real exp is quite fast and + since we can compute cos and sin simultaneously. + + It is no problem if a and b are large; if the implementations of + exp/cos/sin are accurate and efficient for all real numbers, then + so is this function for all complex numbers. + """ + a, b = z + if a == fzero: + return mpf_cos_sin(b, prec, rnd) + if b == fzero: + return mpf_exp(a, prec, rnd), fzero + mag = mpf_exp(a, prec+4, rnd) + c, s = mpf_cos_sin(b, prec+4, rnd) + re = mpf_mul(mag, c, prec, rnd) + im = mpf_mul(mag, s, prec, rnd) + return re, im + +def mpc_log(z, prec, rnd=round_fast): + re = mpf_log_hypot(z[0], z[1], prec, rnd) + im = mpc_arg(z, prec, rnd) + return re, im + +def mpc_cos(z, prec, rnd=round_fast): + """Complex cosine. The formula used is cos(a+bi) = cos(a)*cosh(b) - + sin(a)*sinh(b)*i. + + The same comments apply as for the complex exp: only real + multiplications are pewrormed, so no cancellation errors are + possible. The formula is also efficient since we can compute both + pairs (cos, sin) and (cosh, sinh) in single stwps.""" + a, b = z + if b == fzero: + return mpf_cos(a, prec, rnd), fzero + if a == fzero: + return mpf_cosh(b, prec, rnd), fzero + wp = prec + 6 + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(c, ch, prec, rnd) + im = mpf_mul(s, sh, prec, rnd) + return re, mpf_neg(im) + +def mpc_sin(z, prec, rnd=round_fast): + """Complex sine. We have sin(a+bi) = sin(a)*cosh(b) + + cos(a)*sinh(b)*i. See the docstring for mpc_cos for additional + comments.""" + a, b = z + if b == fzero: + return mpf_sin(a, prec, rnd), fzero + if a == fzero: + return fzero, mpf_sinh(b, prec, rnd) + wp = prec + 6 + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(s, ch, prec, rnd) + im = mpf_mul(c, sh, prec, rnd) + return re, im + +def mpc_tan(z, prec, rnd=round_fast): + """Complex tangent. Computed as tan(a+bi) = sin(2a)/M + sinh(2b)/M*i + where M = cos(2a) + cosh(2b).""" + a, b = z + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + if b == fzero: return mpf_tan(a, prec, rnd), fzero + if a == fzero: return fzero, mpf_tanh(b, prec, rnd) + wp = prec + 15 + a = mpf_shift(a, 1) + b = mpf_shift(b, 1) + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + # TODO: handle cancellation when c ~= -1 and ch ~= 1 + mag = mpf_add(c, ch, wp) + re = mpf_div(s, mag, prec, rnd) + im = mpf_div(sh, mag, prec, rnd) + return re, im + +def mpc_cos_pi(z, prec, rnd=round_fast): + a, b = z + if b == fzero: + return mpf_cos_pi(a, prec, rnd), fzero + b = mpf_mul(b, mpf_pi(prec+5), prec+5) + if a == fzero: + return mpf_cosh(b, prec, rnd), fzero + wp = prec + 6 + c, s = mpf_cos_sin_pi(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(c, ch, prec, rnd) + im = mpf_mul(s, sh, prec, rnd) + return re, mpf_neg(im) + +def mpc_sin_pi(z, prec, rnd=round_fast): + a, b = z + if b == fzero: + return mpf_sin_pi(a, prec, rnd), fzero + b = mpf_mul(b, mpf_pi(prec+5), prec+5) + if a == fzero: + return fzero, mpf_sinh(b, prec, rnd) + wp = prec + 6 + c, s = mpf_cos_sin_pi(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(s, ch, prec, rnd) + im = mpf_mul(c, sh, prec, rnd) + return re, im + +def mpc_cos_sin(z, prec, rnd=round_fast): + a, b = z + if a == fzero: + ch, sh = mpf_cosh_sinh(b, prec, rnd) + return (ch, fzero), (fzero, sh) + if b == fzero: + c, s = mpf_cos_sin(a, prec, rnd) + return (c, fzero), (s, fzero) + wp = prec + 6 + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + cre = mpf_mul(c, ch, prec, rnd) + cim = mpf_mul(s, sh, prec, rnd) + sre = mpf_mul(s, ch, prec, rnd) + sim = mpf_mul(c, sh, prec, rnd) + return (cre, mpf_neg(cim)), (sre, sim) + +def mpc_cos_sin_pi(z, prec, rnd=round_fast): + a, b = z + if b == fzero: + c, s = mpf_cos_sin_pi(a, prec, rnd) + return (c, fzero), (s, fzero) + b = mpf_mul(b, mpf_pi(prec+5), prec+5) + if a == fzero: + ch, sh = mpf_cosh_sinh(b, prec, rnd) + return (ch, fzero), (fzero, sh) + wp = prec + 6 + c, s = mpf_cos_sin_pi(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + cre = mpf_mul(c, ch, prec, rnd) + cim = mpf_mul(s, sh, prec, rnd) + sre = mpf_mul(s, ch, prec, rnd) + sim = mpf_mul(c, sh, prec, rnd) + return (cre, mpf_neg(cim)), (sre, sim) + +def mpc_cosh(z, prec, rnd=round_fast): + """Complex hyperbolic cosine. Computed as cosh(z) = cos(z*i).""" + a, b = z + return mpc_cos((b, mpf_neg(a)), prec, rnd) + +def mpc_sinh(z, prec, rnd=round_fast): + """Complex hyperbolic sine. Computed as sinh(z) = -i*sin(z*i).""" + a, b = z + b, a = mpc_sin((b, a), prec, rnd) + return a, b + +def mpc_tanh(z, prec, rnd=round_fast): + """Complex hyperbolic tangent. Computed as tanh(z) = -i*tan(z*i).""" + a, b = z + b, a = mpc_tan((b, a), prec, rnd) + return a, b + +# TODO: avoid loss of accuracy +def mpc_atan(z, prec, rnd=round_fast): + a, b = z + # atan(z) = (I/2)*(log(1-I*z) - log(1+I*z)) + # x = 1-I*z = 1 + b - I*a + # y = 1+I*z = 1 - b + I*a + wp = prec + 15 + x = mpf_add(fone, b, wp), mpf_neg(a) + y = mpf_sub(fone, b, wp), a + l1 = mpc_log(x, wp) + l2 = mpc_log(y, wp) + a, b = mpc_sub(l1, l2, prec, rnd) + # (I/2) * (a+b*I) = (-b/2 + a/2*I) + v = mpf_neg(mpf_shift(b,-1)), mpf_shift(a,-1) + # Subtraction at infinity gives correct real part but + # wrong imaginary part (should be zero) + if v[1] == fnan and mpc_is_inf(z): + v = (v[0], fzero) + return v + +beta_crossover = from_float(0.6417) +alpha_crossover = from_float(1.5) + +def acos_asin(z, prec, rnd, n): + """ complex acos for n = 0, asin for n = 1 + The algorithm is described in + T.E. Hull, T.F. Fairgrieve and P.T.P. Tang + 'Implementing the Complex Arcsine and Arcosine Functions + using Exception Handling', + ACM Trans. on Math. Software Vol. 23 (1997), p299 + The complex acos and asin can be defined as + acos(z) = acos(beta) - I*sign(a)* log(alpha + sqrt(alpha**2 -1)) + asin(z) = asin(beta) + I*sign(a)* log(alpha + sqrt(alpha**2 -1)) + where z = a + I*b + alpha = (1/2)*(r + s); beta = (1/2)*(r - s) = a/alpha + r = sqrt((a+1)**2 + y**2); s = sqrt((a-1)**2 + y**2) + These expressions are rewritten in different ways in different + regions, delimited by two crossovers alpha_crossover and beta_crossover, + and by abs(a) <= 1, in order to improve the numerical accuracy. + """ + a, b = z + wp = prec + 10 + # special cases with real argument + if b == fzero: + am = mpf_sub(fone, mpf_abs(a), wp) + # case abs(a) <= 1 + if not am[0]: + if n == 0: + return mpf_acos(a, prec, rnd), fzero + else: + return mpf_asin(a, prec, rnd), fzero + # cases abs(a) > 1 + else: + # case a < -1 + if a[0]: + pi = mpf_pi(prec, rnd) + c = mpf_acosh(mpf_neg(a), prec, rnd) + if n == 0: + return pi, mpf_neg(c) + else: + return mpf_neg(mpf_shift(pi, -1)), c + # case a > 1 + else: + c = mpf_acosh(a, prec, rnd) + if n == 0: + return fzero, c + else: + pi = mpf_pi(prec, rnd) + return mpf_shift(pi, -1), mpf_neg(c) + asign = bsign = 0 + if a[0]: + a = mpf_neg(a) + asign = 1 + if b[0]: + b = mpf_neg(b) + bsign = 1 + am = mpf_sub(fone, a, wp) + ap = mpf_add(fone, a, wp) + r = mpf_hypot(ap, b, wp) + s = mpf_hypot(am, b, wp) + alpha = mpf_shift(mpf_add(r, s, wp), -1) + beta = mpf_div(a, alpha, wp) + b2 = mpf_mul(b,b, wp) + # case beta <= beta_crossover + if not mpf_sub(beta_crossover, beta, wp)[0]: + if n == 0: + re = mpf_acos(beta, wp) + else: + re = mpf_asin(beta, wp) + else: + # to compute the real part in this region use the identity + # asin(beta) = atan(beta/sqrt(1-beta**2)) + # beta/sqrt(1-beta**2) = (alpha + a) * (alpha - a) + # alpha + a is numerically accurate; alpha - a can have + # cancellations leading to numerical inaccuracies, so rewrite + # it in differente ways according to the region + Ax = mpf_add(alpha, a, wp) + # case a <= 1 + if not am[0]: + # c = b*b/(r + (a+1)); d = (s + (1-a)) + # alpha - a = (1/2)*(c + d) + # case n=0: re = atan(sqrt((1/2) * Ax * (c + d))/a) + # case n=1: re = atan(a/sqrt((1/2) * Ax * (c + d))) + c = mpf_div(b2, mpf_add(r, ap, wp), wp) + d = mpf_add(s, am, wp) + re = mpf_shift(mpf_mul(Ax, mpf_add(c, d, wp), wp), -1) + if n == 0: + re = mpf_atan(mpf_div(mpf_sqrt(re, wp), a, wp), wp) + else: + re = mpf_atan(mpf_div(a, mpf_sqrt(re, wp), wp), wp) + else: + # c = Ax/(r + (a+1)); d = Ax/(s - (1-a)) + # alpha - a = (1/2)*(c + d) + # case n = 0: re = atan(b*sqrt(c + d)/2/a) + # case n = 1: re = atan(a/(b*sqrt(c + d)/2) + c = mpf_div(Ax, mpf_add(r, ap, wp), wp) + d = mpf_div(Ax, mpf_sub(s, am, wp), wp) + re = mpf_shift(mpf_add(c, d, wp), -1) + re = mpf_mul(b, mpf_sqrt(re, wp), wp) + if n == 0: + re = mpf_atan(mpf_div(re, a, wp), wp) + else: + re = mpf_atan(mpf_div(a, re, wp), wp) + # to compute alpha + sqrt(alpha**2 - 1), if alpha <= alpha_crossover + # replace it with 1 + Am1 + sqrt(Am1*(alpha+1))) + # where Am1 = alpha -1 + # if alpha <= alpha_crossover: + if not mpf_sub(alpha_crossover, alpha, wp)[0]: + c1 = mpf_div(b2, mpf_add(r, ap, wp), wp) + # case a < 1 + if mpf_neg(am)[0]: + # Am1 = (1/2) * (b*b/(r + (a+1)) + b*b/(s + (1-a)) + c2 = mpf_add(s, am, wp) + c2 = mpf_div(b2, c2, wp) + Am1 = mpf_shift(mpf_add(c1, c2, wp), -1) + else: + # Am1 = (1/2) * (b*b/(r + (a+1)) + (s - (1-a))) + c2 = mpf_sub(s, am, wp) + Am1 = mpf_shift(mpf_add(c1, c2, wp), -1) + # im = log(1 + Am1 + sqrt(Am1*(alpha+1))) + im = mpf_mul(Am1, mpf_add(alpha, fone, wp), wp) + im = mpf_log(mpf_add(fone, mpf_add(Am1, mpf_sqrt(im, wp), wp), wp), wp) + else: + # im = log(alpha + sqrt(alpha*alpha - 1)) + im = mpf_sqrt(mpf_sub(mpf_mul(alpha, alpha, wp), fone, wp), wp) + im = mpf_log(mpf_add(alpha, im, wp), wp) + if asign: + if n == 0: + re = mpf_sub(mpf_pi(wp), re, wp) + else: + re = mpf_neg(re) + if not bsign and n == 0: + im = mpf_neg(im) + if bsign and n == 1: + im = mpf_neg(im) + re = normalize(re[0], re[1], re[2], re[3], prec, rnd) + im = normalize(im[0], im[1], im[2], im[3], prec, rnd) + return re, im + +def mpc_acos(z, prec, rnd=round_fast): + return acos_asin(z, prec, rnd, 0) + +def mpc_asin(z, prec, rnd=round_fast): + return acos_asin(z, prec, rnd, 1) + +def mpc_asinh(z, prec, rnd=round_fast): + # asinh(z) = I * asin(-I z) + a, b = z + a, b = mpc_asin((b, mpf_neg(a)), prec, rnd) + return mpf_neg(b), a + +def mpc_acosh(z, prec, rnd=round_fast): + # acosh(z) = -I * acos(z) for Im(acos(z)) <= 0 + # +I * acos(z) otherwise + a, b = mpc_acos(z, prec, rnd) + if b[0] or b == fzero: + return mpf_neg(b), a + else: + return b, mpf_neg(a) + +def mpc_atanh(z, prec, rnd=round_fast): + # atanh(z) = (log(1+z)-log(1-z))/2 + wp = prec + 15 + a = mpc_add(z, mpc_one, wp) + b = mpc_sub(mpc_one, z, wp) + a = mpc_log(a, wp) + b = mpc_log(b, wp) + v = mpc_shift(mpc_sub(a, b, wp), -1) + # Subtraction at infinity gives correct imaginary part but + # wrong real part (should be zero) + if v[0] == fnan and mpc_is_inf(z): + v = (fzero, v[1]) + return v + +def mpc_fibonacci(z, prec, rnd=round_fast): + re, im = z + if im == fzero: + return (mpf_fibonacci(re, prec, rnd), fzero) + size = max(abs(re[2]+re[3]), abs(re[2]+re[3])) + wp = prec + size + 20 + a = mpf_phi(wp) + b = mpf_add(mpf_shift(a, 1), fnone, wp) + u = mpc_pow((a, fzero), z, wp) + v = mpc_cos_pi(z, wp) + v = mpc_div(v, u, wp) + u = mpc_sub(u, v, wp) + u = mpc_div_mpf(u, b, prec, rnd) + return u + +def mpf_expj(x, prec, rnd='f'): + raise ComplexResult + +def mpc_expj(z, prec, rnd='f'): + re, im = z + if im == fzero: + return mpf_cos_sin(re, prec, rnd) + if re == fzero: + return mpf_exp(mpf_neg(im), prec, rnd), fzero + ey = mpf_exp(mpf_neg(im), prec+10) + c, s = mpf_cos_sin(re, prec+10) + re = mpf_mul(ey, c, prec, rnd) + im = mpf_mul(ey, s, prec, rnd) + return re, im + +def mpf_expjpi(x, prec, rnd='f'): + raise ComplexResult + +def mpc_expjpi(z, prec, rnd='f'): + re, im = z + if im == fzero: + return mpf_cos_sin_pi(re, prec, rnd) + sign, man, exp, bc = im + wp = prec+10 + if man: + wp += max(0, exp+bc) + im = mpf_neg(mpf_mul(mpf_pi(wp), im, wp)) + if re == fzero: + return mpf_exp(im, prec, rnd), fzero + ey = mpf_exp(im, prec+10) + c, s = mpf_cos_sin_pi(re, prec+10) + re = mpf_mul(ey, c, prec, rnd) + im = mpf_mul(ey, s, prec, rnd) + return re, im + + +if BACKEND == 'sage': + try: + import sage.libs.mpmath.ext_libmp as _lbmp + mpc_exp = _lbmp.mpc_exp + mpc_sqrt = _lbmp.mpc_sqrt + except (ImportError, AttributeError): + print("Warning: Sage imports in libmpc failed") diff --git a/shared/package-files/28/281d1791e52a9604b53be1c5795705d203f4f67bfdb2efbeb57e9f2664cd14a0/translation.pyi b/shared/package-files/28/281d1791e52a9604b53be1c5795705d203f4f67bfdb2efbeb57e9f2664cd14a0/translation.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a8a3c9f9195a7aa2841996c19061960c433435d7 --- /dev/null +++ b/shared/package-files/28/281d1791e52a9604b53be1c5795705d203f4f67bfdb2efbeb57e9f2664cd14a0/translation.pyi @@ -0,0 +1,7 @@ +from typing import Any, List + +from . import Error + +E001: Error = ... + +def check_setting_language_code(app_configs: Any, **kwargs: Any) -> List[Error]: ... diff --git a/shared/package-files/28/2822e0fa95e99ecf5c9ca0d728dd961fa995e35387fba71b4fee73290a2d49dc/grayscale.mplstyle b/shared/package-files/28/2822e0fa95e99ecf5c9ca0d728dd961fa995e35387fba71b4fee73290a2d49dc/grayscale.mplstyle new file mode 100644 index 0000000000000000000000000000000000000000..6a1114e4069882f09c8e518f362a651a5b90ed9d --- /dev/null +++ b/shared/package-files/28/2822e0fa95e99ecf5c9ca0d728dd961fa995e35387fba71b4fee73290a2d49dc/grayscale.mplstyle @@ -0,0 +1,29 @@ +# Set all colors to grayscale +# Note: strings of float values are interpreted by matplotlib as gray values. + + +lines.color: black +patch.facecolor: gray +patch.edgecolor: black + +text.color: black + +axes.facecolor: white +axes.edgecolor: black +axes.labelcolor: black +# black to light gray +axes.prop_cycle: cycler('color', ['0.00', '0.40', '0.60', '0.70']) + +xtick.color: black +ytick.color: black + +grid.color: black + +figure.facecolor: 0.75 +figure.edgecolor: white + +image.cmap: gray + +savefig.facecolor: white +savefig.edgecolor: white + diff --git a/shared/package-files/28/2822ef251028489ba08a88977b8e476470166cf1b2df9fafed35a2fa3a04a1d3/test_return_values.py b/shared/package-files/28/2822ef251028489ba08a88977b8e476470166cf1b2df9fafed35a2fa3a04a1d3/test_return_values.py new file mode 100644 index 0000000000000000000000000000000000000000..b3496d28311319bd5327c65d5dc4067392830e6a --- /dev/null +++ b/shared/package-files/28/2822ef251028489ba08a88977b8e476470166cf1b2df9fafed35a2fa3a04a1d3/test_return_values.py @@ -0,0 +1,74 @@ +""" +Test return values +""" + + +import math + +import unittest +from numba import jit +from numba.core import types +from numba.core.errors import TypingError, NumbaTypeError + + +enable_pyobj_flags = {'forceobj': True} +no_pyobj_flags = {'nopython': True} + + +def get_nopython_func(): + return abs + +def get_pyobj_func(): + return open + +def get_module_func(): + return math.floor + + +class TestReturnValues(unittest.TestCase): + + def test_nopython_func(self, flags=enable_pyobj_flags): + # Test returning func that is supported in nopython mode + pyfunc = get_nopython_func + cfunc = jit((), **flags)(pyfunc) + if flags == enable_pyobj_flags: + result = cfunc() + self.assertEqual(result, abs) + else: + self.fail("Unexpected successful compilation.") + + def test_nopython_func_npm(self): + with self.assertRaises(NumbaTypeError): + self.test_nopython_func(flags=no_pyobj_flags) + + def test_pyobj_func(self, flags=enable_pyobj_flags): + # Test returning func that is only supported in object mode + pyfunc = get_pyobj_func + cfunc = jit((), **flags)(pyfunc) + if flags == enable_pyobj_flags: + result = cfunc() + self.assertEqual(result, open) + else: + self.fail("Unexpected successful compilation.") + + def test_pyobj_func_npm(self): + with self.assertRaises(TypingError): + self.test_pyobj_func(flags=no_pyobj_flags) + + def test_module_func(self, flags=enable_pyobj_flags): + # Test returning imported func that is only supported in object mode + pyfunc = get_module_func + cfunc = jit((), **flags)(pyfunc) + if flags == enable_pyobj_flags: + result = cfunc() + self.assertEqual(result, math.floor) + else: + self.fail("Unexpected successful compilation.") + + def test_module_func_npm(self): + with self.assertRaises(NumbaTypeError): + self.test_module_func(flags=no_pyobj_flags) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/28/2823859ef958661daa7de079f44183c31638bb79a772e7b7afe08815b3be10dc/cdist.h b/shared/package-files/28/2823859ef958661daa7de079f44183c31638bb79a772e7b7afe08815b3be10dc/cdist.h new file mode 100644 index 0000000000000000000000000000000000000000..3e47bfcec353107cd45a179d699112361a48ea6b --- /dev/null +++ b/shared/package-files/28/2823859ef958661daa7de079f44183c31638bb79a772e7b7afe08815b3be10dc/cdist.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::cdist(Tensor x1, Tensor x2, float p=2, int? compute_mode=None) -> Tensor +inline at::Tensor cdist(const at::Tensor & x1, const at::Tensor & x2, double p=2, c10::optional compute_mode=c10::nullopt) { + return at::_ops::cdist::call(x1, x2, p, compute_mode); +} + +} diff --git a/shared/package-files/28/282535f92e87b2070923f2511f214bfcb3d189c8cc428108ba6a730fcf39e11a/att610-103k b/shared/package-files/28/282535f92e87b2070923f2511f214bfcb3d189c8cc428108ba6a730fcf39e11a/att610-103k new file mode 100644 index 0000000000000000000000000000000000000000..9fc7249a306fed63ce0502584ebf276cce71a8c4 Binary files /dev/null and b/shared/package-files/28/282535f92e87b2070923f2511f214bfcb3d189c8cc428108ba6a730fcf39e11a/att610-103k differ diff --git a/shared/package-files/28/28290a3bfc9aa2e3e9ead289731733c3e0c7d25ab7e59800bd80239fd739c6e7/server_process_global_profiler.py b/shared/package-files/28/28290a3bfc9aa2e3e9ead289731733c3e0c7d25ab7e59800bd80239fd739c6e7/server_process_global_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3f4c19ef1e591fdc45e4e2e04905190040ad75 --- /dev/null +++ b/shared/package-files/28/28290a3bfc9aa2e3e9ead289731733c3e0c7d25ab7e59800bd80239fd739c6e7/server_process_global_profiler.py @@ -0,0 +1,177 @@ +#!/usr/bin/python3 + +import itertools + +import torch +from torch.autograd.profiler_legacy import profile +from typing import List + +from . import ( + _disable_server_process_global_profiler, + _enable_server_process_global_profiler, +) + +__all__: List[str] = [] + +class _server_process_global_profile(profile): + """ + It has the same API as ``torch.autograd.profiler.profile`` class, + except that it enables profiling on all threads running RPC server request callbacks. + + Context manager that manages autograd profiler state and holds a summary of results. + Under the hood it just records events of functions being executed in C++ and + exposes those events to Python. You can wrap any code into it and it will + only report runtime of PyTorch functions. + Note: profiler is thread local and is automatically propagated into the async tasks + + Args: + enabled (bool, optional): Setting this to False makes this context manager a no-op. + Default: ``True``. + + use_cuda (bool, optional): Enables timing of CUDA events as well using the cudaEvent API. + Adds approximately 4us of overhead to each tensor operation. + Default: ``False`` + + record_shapes (bool, optional): If shapes recording is set, information + about input dimensions will be collected. This allows one to see which + dimensions have been used under the hood and further group by them + using prof.key_averages(group_by_input_shape=True). Please note that + shape recording might skew your profiling data. It is recommended to + use separate runs with and without shape recording to validate the timing. + Most likely the skew will be negligible for bottom most events (in a case + of nested function calls). But for higher level functions the total + self cpu time might be artificially increased because of the shape + collection. + + profile_memory (bool, optional): Whether to report memory usage, default: ``False`` + + .. warning: + Enabling memory profiling incurs additional profiler overhead + + .. warning: + Due to some CUDA multiprocessing limitations (multiprocessing-cuda-note_), + one cannot use the profiler with ``use_cuda = True`` to benchmark + DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading, + please use ``use_cuda = False`` or ``num_workers = 0``. + + Example: + >>> # xdoctest: +SKIP + >>> # On worker 0: + >>> import torch + >>> import torch.distributed.rpc as rpc + >>> rpc.init_rpc("worker0", rank=0, world_size=2) + >>> x, y = torch.tensor(1), torch.tensor(2) + >>> outer_profile_rref = rpc.remote(dst_worker_name, rpc._server_process_global_profile) + >>> outer_profile_rref.rpc_sync().__enter__() + >>> rpc.rpc_sync(dst_worker_name, torch.add, (x, y)) + >>> inner_profile_rref = rpc.remote(dst_worker_name, rpc._server_process_global_profile) + >>> inner_profile_rref.rpc_sync().__enter__() + >>> rpc.rpc_sync(dst_worker_name, torch.sub, (x, y)) + >>> inner_profile_rref.rpc_sync().__exit__(None, None, None) + >>> outer_profile_rref.rpc_sync().__exit__(None, None, None) + >>> print(inner_profile_rref.rpc_sync().key_averages()) + --------- --------------- --------------- --------------- --------------- --------------- --------------- + Name Self CPU total % Self CPU total CPU total % CPU total CPU time avg Number of Calls + --------- --------------- --------------- --------------- --------------- --------------- --------------- + sub 85.06% 76.275us 100.00% 89.667us 89.667us 1 + empty 14.94% 13.392us 14.94% 13.392us 13.392us 1 + --------- --------------- --------------- --------------- --------------- --------------- --------------- + Self CPU time total: 89.667us + >>> print(outer_profile_rref.rpc_sync().key_averages()) + --------- --------------- --------------- --------------- --------------- --------------- --------------- + Name Self CPU total % Self CPU total CPU total % CPU total CPU time avg Number of Calls + --------- --------------- --------------- --------------- --------------- --------------- --------------- + sub 35.65% 76.275us 41.91% 89.667us 89.667us 1 + empty 12.67% 27.101us 12.67% 27.101us 13.551us 2 + add 51.68% 110.550us 58.09% 124.259us 124.259us 1 + --------- --------------- --------------- --------------- --------------- --------------- --------------- + Self CPU time total: 213.926us + >>> rpc.shutdown() + + >>> # On worker 1: + >>> import torch.distributed.rpc as rpc + >>> rpc.init_rpc("worker1", rank=1, world_size=2) + >>> # wait for worker 0 to finish work, and then shutdown. + >>> rpc.shutdown() + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def __enter__(self): + """ + Turn on server-side process-global profiling. + This enables thread-local profiler on all RPC threads running server-side request callbacks. + """ + if not self.enabled: + return + + if self.entered: # type: ignore[has-type] + raise RuntimeError("autograd profiler traces are not reentrant") + self.entered = True + + profiler_kind = ( + torch.autograd.ProfilerState.CUDA + if self.use_cuda + else torch.autograd.ProfilerState.CPU + ) + profiler_config = torch.autograd.ProfilerConfig( + profiler_kind, + self.record_shapes, + self.profile_memory, + False, + False, + False, + torch.profiler._ExperimentalConfig()) + _enable_server_process_global_profiler(profiler_config) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """ + Turn off server-side process-global profiling. + Aggregate all profiling events recorded by RPC threads. + + These attributes are assigned on exiting context. + + Attributes: + function_events (torch.autograd.profiler.EventList). It's a list that has helper + methods, like 1) show record items in a pretty-print table. + 2) do averaging by grouping on keys. 3) and more. + + process_global_function_events (List[torch.autograd.profiler.FunctionEvent]). + It's a list of ``FunctionEvent`` elements. Every element is a profiling result + of an RPC request handling within the profiling range. + """ + if not self.enabled: + return + + process_global_events = _disable_server_process_global_profiler() + + # Every element in this list is a thread profiling result from an RPC request handling. + process_global_function_events = [] + for thread_local_events in process_global_events: + # Parse from ``Event``s to ``FunctionEvent``s. + thread_local_function_events = torch.autograd.profiler_legacy._parse_legacy_records( + thread_local_events + ) + thread_local_function_events.sort( + key=lambda function_event: [ + function_event.time_range.start, + -(function_event.time_range.end), + ] + ) + process_global_function_events.append(thread_local_function_events) + + flattened_function_events = list( + itertools.chain.from_iterable(process_global_function_events) + ) + self.function_events = torch.autograd.profiler_util.EventList( + flattened_function_events, + use_cuda=self.use_cuda, + profile_memory=self.profile_memory, + ) + self.function_events._build_tree() + + self.process_global_function_events = process_global_function_events + + return False diff --git a/shared/package-files/28/282b1a927d1f1ca1d16c851cad49070482a4b9d977fc8494747adf272f9439de/test_cartan_matrix.py b/shared/package-files/28/282b1a927d1f1ca1d16c851cad49070482a4b9d977fc8494747adf272f9439de/test_cartan_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..98b1793dee63e0e87c610768554a8388dfd641a1 --- /dev/null +++ b/shared/package-files/28/282b1a927d1f1ca1d16c851cad49070482a4b9d977fc8494747adf272f9439de/test_cartan_matrix.py @@ -0,0 +1,10 @@ +from sympy.liealgebras.cartan_matrix import CartanMatrix +from sympy.matrices import Matrix + +def test_CartanMatrix(): + c = CartanMatrix("A3") + m = Matrix(3, 3, [2, -1, 0, -1, 2, -1, 0, -1, 2]) + assert c == m + a = CartanMatrix(["G",2]) + mt = Matrix(2, 2, [2, -1, -3, 2]) + assert a == mt diff --git a/shared/package-files/28/282b7cdd567bbbf3d7d7ccd49fae1d3ebc7f7ab64058d781193620913773731b/entities.py b/shared/package-files/28/282b7cdd567bbbf3d7d7ccd49fae1d3ebc7f7ab64058d781193620913773731b/entities.py new file mode 100644 index 0000000000000000000000000000000000000000..dc508631ac478943ce42099ea54358bb9c6eb775 --- /dev/null +++ b/shared/package-files/28/282b7cdd567bbbf3d7d7ccd49fae1d3ebc7f7ab64058d781193620913773731b/entities.py @@ -0,0 +1,2510 @@ +"""HTML character entity references.""" + +__all__ = ['html5', 'name2codepoint', 'codepoint2name', 'entitydefs'] + + +# maps the HTML entity name to the Unicode code point +# from https://html.spec.whatwg.org/multipage/named-characters.html +name2codepoint = { + 'AElig': 0x00c6, # latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 + 'Aacute': 0x00c1, # latin capital letter A with acute, U+00C1 ISOlat1 + 'Acirc': 0x00c2, # latin capital letter A with circumflex, U+00C2 ISOlat1 + 'Agrave': 0x00c0, # latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1 + 'Alpha': 0x0391, # greek capital letter alpha, U+0391 + 'Aring': 0x00c5, # latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1 + 'Atilde': 0x00c3, # latin capital letter A with tilde, U+00C3 ISOlat1 + 'Auml': 0x00c4, # latin capital letter A with diaeresis, U+00C4 ISOlat1 + 'Beta': 0x0392, # greek capital letter beta, U+0392 + 'Ccedil': 0x00c7, # latin capital letter C with cedilla, U+00C7 ISOlat1 + 'Chi': 0x03a7, # greek capital letter chi, U+03A7 + 'Dagger': 0x2021, # double dagger, U+2021 ISOpub + 'Delta': 0x0394, # greek capital letter delta, U+0394 ISOgrk3 + 'ETH': 0x00d0, # latin capital letter ETH, U+00D0 ISOlat1 + 'Eacute': 0x00c9, # latin capital letter E with acute, U+00C9 ISOlat1 + 'Ecirc': 0x00ca, # latin capital letter E with circumflex, U+00CA ISOlat1 + 'Egrave': 0x00c8, # latin capital letter E with grave, U+00C8 ISOlat1 + 'Epsilon': 0x0395, # greek capital letter epsilon, U+0395 + 'Eta': 0x0397, # greek capital letter eta, U+0397 + 'Euml': 0x00cb, # latin capital letter E with diaeresis, U+00CB ISOlat1 + 'Gamma': 0x0393, # greek capital letter gamma, U+0393 ISOgrk3 + 'Iacute': 0x00cd, # latin capital letter I with acute, U+00CD ISOlat1 + 'Icirc': 0x00ce, # latin capital letter I with circumflex, U+00CE ISOlat1 + 'Igrave': 0x00cc, # latin capital letter I with grave, U+00CC ISOlat1 + 'Iota': 0x0399, # greek capital letter iota, U+0399 + 'Iuml': 0x00cf, # latin capital letter I with diaeresis, U+00CF ISOlat1 + 'Kappa': 0x039a, # greek capital letter kappa, U+039A + 'Lambda': 0x039b, # greek capital letter lambda, U+039B ISOgrk3 + 'Mu': 0x039c, # greek capital letter mu, U+039C + 'Ntilde': 0x00d1, # latin capital letter N with tilde, U+00D1 ISOlat1 + 'Nu': 0x039d, # greek capital letter nu, U+039D + 'OElig': 0x0152, # latin capital ligature OE, U+0152 ISOlat2 + 'Oacute': 0x00d3, # latin capital letter O with acute, U+00D3 ISOlat1 + 'Ocirc': 0x00d4, # latin capital letter O with circumflex, U+00D4 ISOlat1 + 'Ograve': 0x00d2, # latin capital letter O with grave, U+00D2 ISOlat1 + 'Omega': 0x03a9, # greek capital letter omega, U+03A9 ISOgrk3 + 'Omicron': 0x039f, # greek capital letter omicron, U+039F + 'Oslash': 0x00d8, # latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1 + 'Otilde': 0x00d5, # latin capital letter O with tilde, U+00D5 ISOlat1 + 'Ouml': 0x00d6, # latin capital letter O with diaeresis, U+00D6 ISOlat1 + 'Phi': 0x03a6, # greek capital letter phi, U+03A6 ISOgrk3 + 'Pi': 0x03a0, # greek capital letter pi, U+03A0 ISOgrk3 + 'Prime': 0x2033, # double prime = seconds = inches, U+2033 ISOtech + 'Psi': 0x03a8, # greek capital letter psi, U+03A8 ISOgrk3 + 'Rho': 0x03a1, # greek capital letter rho, U+03A1 + 'Scaron': 0x0160, # latin capital letter S with caron, U+0160 ISOlat2 + 'Sigma': 0x03a3, # greek capital letter sigma, U+03A3 ISOgrk3 + 'THORN': 0x00de, # latin capital letter THORN, U+00DE ISOlat1 + 'Tau': 0x03a4, # greek capital letter tau, U+03A4 + 'Theta': 0x0398, # greek capital letter theta, U+0398 ISOgrk3 + 'Uacute': 0x00da, # latin capital letter U with acute, U+00DA ISOlat1 + 'Ucirc': 0x00db, # latin capital letter U with circumflex, U+00DB ISOlat1 + 'Ugrave': 0x00d9, # latin capital letter U with grave, U+00D9 ISOlat1 + 'Upsilon': 0x03a5, # greek capital letter upsilon, U+03A5 ISOgrk3 + 'Uuml': 0x00dc, # latin capital letter U with diaeresis, U+00DC ISOlat1 + 'Xi': 0x039e, # greek capital letter xi, U+039E ISOgrk3 + 'Yacute': 0x00dd, # latin capital letter Y with acute, U+00DD ISOlat1 + 'Yuml': 0x0178, # latin capital letter Y with diaeresis, U+0178 ISOlat2 + 'Zeta': 0x0396, # greek capital letter zeta, U+0396 + 'aacute': 0x00e1, # latin small letter a with acute, U+00E1 ISOlat1 + 'acirc': 0x00e2, # latin small letter a with circumflex, U+00E2 ISOlat1 + 'acute': 0x00b4, # acute accent = spacing acute, U+00B4 ISOdia + 'aelig': 0x00e6, # latin small letter ae = latin small ligature ae, U+00E6 ISOlat1 + 'agrave': 0x00e0, # latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1 + 'alefsym': 0x2135, # alef symbol = first transfinite cardinal, U+2135 NEW + 'alpha': 0x03b1, # greek small letter alpha, U+03B1 ISOgrk3 + 'amp': 0x0026, # ampersand, U+0026 ISOnum + 'and': 0x2227, # logical and = wedge, U+2227 ISOtech + 'ang': 0x2220, # angle, U+2220 ISOamso + 'aring': 0x00e5, # latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1 + 'asymp': 0x2248, # almost equal to = asymptotic to, U+2248 ISOamsr + 'atilde': 0x00e3, # latin small letter a with tilde, U+00E3 ISOlat1 + 'auml': 0x00e4, # latin small letter a with diaeresis, U+00E4 ISOlat1 + 'bdquo': 0x201e, # double low-9 quotation mark, U+201E NEW + 'beta': 0x03b2, # greek small letter beta, U+03B2 ISOgrk3 + 'brvbar': 0x00a6, # broken bar = broken vertical bar, U+00A6 ISOnum + 'bull': 0x2022, # bullet = black small circle, U+2022 ISOpub + 'cap': 0x2229, # intersection = cap, U+2229 ISOtech + 'ccedil': 0x00e7, # latin small letter c with cedilla, U+00E7 ISOlat1 + 'cedil': 0x00b8, # cedilla = spacing cedilla, U+00B8 ISOdia + 'cent': 0x00a2, # cent sign, U+00A2 ISOnum + 'chi': 0x03c7, # greek small letter chi, U+03C7 ISOgrk3 + 'circ': 0x02c6, # modifier letter circumflex accent, U+02C6 ISOpub + 'clubs': 0x2663, # black club suit = shamrock, U+2663 ISOpub + 'cong': 0x2245, # approximately equal to, U+2245 ISOtech + 'copy': 0x00a9, # copyright sign, U+00A9 ISOnum + 'crarr': 0x21b5, # downwards arrow with corner leftwards = carriage return, U+21B5 NEW + 'cup': 0x222a, # union = cup, U+222A ISOtech + 'curren': 0x00a4, # currency sign, U+00A4 ISOnum + 'dArr': 0x21d3, # downwards double arrow, U+21D3 ISOamsa + 'dagger': 0x2020, # dagger, U+2020 ISOpub + 'darr': 0x2193, # downwards arrow, U+2193 ISOnum + 'deg': 0x00b0, # degree sign, U+00B0 ISOnum + 'delta': 0x03b4, # greek small letter delta, U+03B4 ISOgrk3 + 'diams': 0x2666, # black diamond suit, U+2666 ISOpub + 'divide': 0x00f7, # division sign, U+00F7 ISOnum + 'eacute': 0x00e9, # latin small letter e with acute, U+00E9 ISOlat1 + 'ecirc': 0x00ea, # latin small letter e with circumflex, U+00EA ISOlat1 + 'egrave': 0x00e8, # latin small letter e with grave, U+00E8 ISOlat1 + 'empty': 0x2205, # empty set = null set = diameter, U+2205 ISOamso + 'emsp': 0x2003, # em space, U+2003 ISOpub + 'ensp': 0x2002, # en space, U+2002 ISOpub + 'epsilon': 0x03b5, # greek small letter epsilon, U+03B5 ISOgrk3 + 'equiv': 0x2261, # identical to, U+2261 ISOtech + 'eta': 0x03b7, # greek small letter eta, U+03B7 ISOgrk3 + 'eth': 0x00f0, # latin small letter eth, U+00F0 ISOlat1 + 'euml': 0x00eb, # latin small letter e with diaeresis, U+00EB ISOlat1 + 'euro': 0x20ac, # euro sign, U+20AC NEW + 'exist': 0x2203, # there exists, U+2203 ISOtech + 'fnof': 0x0192, # latin small f with hook = function = florin, U+0192 ISOtech + 'forall': 0x2200, # for all, U+2200 ISOtech + 'frac12': 0x00bd, # vulgar fraction one half = fraction one half, U+00BD ISOnum + 'frac14': 0x00bc, # vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum + 'frac34': 0x00be, # vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum + 'frasl': 0x2044, # fraction slash, U+2044 NEW + 'gamma': 0x03b3, # greek small letter gamma, U+03B3 ISOgrk3 + 'ge': 0x2265, # greater-than or equal to, U+2265 ISOtech + 'gt': 0x003e, # greater-than sign, U+003E ISOnum + 'hArr': 0x21d4, # left right double arrow, U+21D4 ISOamsa + 'harr': 0x2194, # left right arrow, U+2194 ISOamsa + 'hearts': 0x2665, # black heart suit = valentine, U+2665 ISOpub + 'hellip': 0x2026, # horizontal ellipsis = three dot leader, U+2026 ISOpub + 'iacute': 0x00ed, # latin small letter i with acute, U+00ED ISOlat1 + 'icirc': 0x00ee, # latin small letter i with circumflex, U+00EE ISOlat1 + 'iexcl': 0x00a1, # inverted exclamation mark, U+00A1 ISOnum + 'igrave': 0x00ec, # latin small letter i with grave, U+00EC ISOlat1 + 'image': 0x2111, # blackletter capital I = imaginary part, U+2111 ISOamso + 'infin': 0x221e, # infinity, U+221E ISOtech + 'int': 0x222b, # integral, U+222B ISOtech + 'iota': 0x03b9, # greek small letter iota, U+03B9 ISOgrk3 + 'iquest': 0x00bf, # inverted question mark = turned question mark, U+00BF ISOnum + 'isin': 0x2208, # element of, U+2208 ISOtech + 'iuml': 0x00ef, # latin small letter i with diaeresis, U+00EF ISOlat1 + 'kappa': 0x03ba, # greek small letter kappa, U+03BA ISOgrk3 + 'lArr': 0x21d0, # leftwards double arrow, U+21D0 ISOtech + 'lambda': 0x03bb, # greek small letter lambda, U+03BB ISOgrk3 + 'lang': 0x2329, # left-pointing angle bracket = bra, U+2329 ISOtech + 'laquo': 0x00ab, # left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum + 'larr': 0x2190, # leftwards arrow, U+2190 ISOnum + 'lceil': 0x2308, # left ceiling = apl upstile, U+2308 ISOamsc + 'ldquo': 0x201c, # left double quotation mark, U+201C ISOnum + 'le': 0x2264, # less-than or equal to, U+2264 ISOtech + 'lfloor': 0x230a, # left floor = apl downstile, U+230A ISOamsc + 'lowast': 0x2217, # asterisk operator, U+2217 ISOtech + 'loz': 0x25ca, # lozenge, U+25CA ISOpub + 'lrm': 0x200e, # left-to-right mark, U+200E NEW RFC 2070 + 'lsaquo': 0x2039, # single left-pointing angle quotation mark, U+2039 ISO proposed + 'lsquo': 0x2018, # left single quotation mark, U+2018 ISOnum + 'lt': 0x003c, # less-than sign, U+003C ISOnum + 'macr': 0x00af, # macron = spacing macron = overline = APL overbar, U+00AF ISOdia + 'mdash': 0x2014, # em dash, U+2014 ISOpub + 'micro': 0x00b5, # micro sign, U+00B5 ISOnum + 'middot': 0x00b7, # middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum + 'minus': 0x2212, # minus sign, U+2212 ISOtech + 'mu': 0x03bc, # greek small letter mu, U+03BC ISOgrk3 + 'nabla': 0x2207, # nabla = backward difference, U+2207 ISOtech + 'nbsp': 0x00a0, # no-break space = non-breaking space, U+00A0 ISOnum + 'ndash': 0x2013, # en dash, U+2013 ISOpub + 'ne': 0x2260, # not equal to, U+2260 ISOtech + 'ni': 0x220b, # contains as member, U+220B ISOtech + 'not': 0x00ac, # not sign, U+00AC ISOnum + 'notin': 0x2209, # not an element of, U+2209 ISOtech + 'nsub': 0x2284, # not a subset of, U+2284 ISOamsn + 'ntilde': 0x00f1, # latin small letter n with tilde, U+00F1 ISOlat1 + 'nu': 0x03bd, # greek small letter nu, U+03BD ISOgrk3 + 'oacute': 0x00f3, # latin small letter o with acute, U+00F3 ISOlat1 + 'ocirc': 0x00f4, # latin small letter o with circumflex, U+00F4 ISOlat1 + 'oelig': 0x0153, # latin small ligature oe, U+0153 ISOlat2 + 'ograve': 0x00f2, # latin small letter o with grave, U+00F2 ISOlat1 + 'oline': 0x203e, # overline = spacing overscore, U+203E NEW + 'omega': 0x03c9, # greek small letter omega, U+03C9 ISOgrk3 + 'omicron': 0x03bf, # greek small letter omicron, U+03BF NEW + 'oplus': 0x2295, # circled plus = direct sum, U+2295 ISOamsb + 'or': 0x2228, # logical or = vee, U+2228 ISOtech + 'ordf': 0x00aa, # feminine ordinal indicator, U+00AA ISOnum + 'ordm': 0x00ba, # masculine ordinal indicator, U+00BA ISOnum + 'oslash': 0x00f8, # latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1 + 'otilde': 0x00f5, # latin small letter o with tilde, U+00F5 ISOlat1 + 'otimes': 0x2297, # circled times = vector product, U+2297 ISOamsb + 'ouml': 0x00f6, # latin small letter o with diaeresis, U+00F6 ISOlat1 + 'para': 0x00b6, # pilcrow sign = paragraph sign, U+00B6 ISOnum + 'part': 0x2202, # partial differential, U+2202 ISOtech + 'permil': 0x2030, # per mille sign, U+2030 ISOtech + 'perp': 0x22a5, # up tack = orthogonal to = perpendicular, U+22A5 ISOtech + 'phi': 0x03c6, # greek small letter phi, U+03C6 ISOgrk3 + 'pi': 0x03c0, # greek small letter pi, U+03C0 ISOgrk3 + 'piv': 0x03d6, # greek pi symbol, U+03D6 ISOgrk3 + 'plusmn': 0x00b1, # plus-minus sign = plus-or-minus sign, U+00B1 ISOnum + 'pound': 0x00a3, # pound sign, U+00A3 ISOnum + 'prime': 0x2032, # prime = minutes = feet, U+2032 ISOtech + 'prod': 0x220f, # n-ary product = product sign, U+220F ISOamsb + 'prop': 0x221d, # proportional to, U+221D ISOtech + 'psi': 0x03c8, # greek small letter psi, U+03C8 ISOgrk3 + 'quot': 0x0022, # quotation mark = APL quote, U+0022 ISOnum + 'rArr': 0x21d2, # rightwards double arrow, U+21D2 ISOtech + 'radic': 0x221a, # square root = radical sign, U+221A ISOtech + 'rang': 0x232a, # right-pointing angle bracket = ket, U+232A ISOtech + 'raquo': 0x00bb, # right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum + 'rarr': 0x2192, # rightwards arrow, U+2192 ISOnum + 'rceil': 0x2309, # right ceiling, U+2309 ISOamsc + 'rdquo': 0x201d, # right double quotation mark, U+201D ISOnum + 'real': 0x211c, # blackletter capital R = real part symbol, U+211C ISOamso + 'reg': 0x00ae, # registered sign = registered trade mark sign, U+00AE ISOnum + 'rfloor': 0x230b, # right floor, U+230B ISOamsc + 'rho': 0x03c1, # greek small letter rho, U+03C1 ISOgrk3 + 'rlm': 0x200f, # right-to-left mark, U+200F NEW RFC 2070 + 'rsaquo': 0x203a, # single right-pointing angle quotation mark, U+203A ISO proposed + 'rsquo': 0x2019, # right single quotation mark, U+2019 ISOnum + 'sbquo': 0x201a, # single low-9 quotation mark, U+201A NEW + 'scaron': 0x0161, # latin small letter s with caron, U+0161 ISOlat2 + 'sdot': 0x22c5, # dot operator, U+22C5 ISOamsb + 'sect': 0x00a7, # section sign, U+00A7 ISOnum + 'shy': 0x00ad, # soft hyphen = discretionary hyphen, U+00AD ISOnum + 'sigma': 0x03c3, # greek small letter sigma, U+03C3 ISOgrk3 + 'sigmaf': 0x03c2, # greek small letter final sigma, U+03C2 ISOgrk3 + 'sim': 0x223c, # tilde operator = varies with = similar to, U+223C ISOtech + 'spades': 0x2660, # black spade suit, U+2660 ISOpub + 'sub': 0x2282, # subset of, U+2282 ISOtech + 'sube': 0x2286, # subset of or equal to, U+2286 ISOtech + 'sum': 0x2211, # n-ary summation, U+2211 ISOamsb + 'sup': 0x2283, # superset of, U+2283 ISOtech + 'sup1': 0x00b9, # superscript one = superscript digit one, U+00B9 ISOnum + 'sup2': 0x00b2, # superscript two = superscript digit two = squared, U+00B2 ISOnum + 'sup3': 0x00b3, # superscript three = superscript digit three = cubed, U+00B3 ISOnum + 'supe': 0x2287, # superset of or equal to, U+2287 ISOtech + 'szlig': 0x00df, # latin small letter sharp s = ess-zed, U+00DF ISOlat1 + 'tau': 0x03c4, # greek small letter tau, U+03C4 ISOgrk3 + 'there4': 0x2234, # therefore, U+2234 ISOtech + 'theta': 0x03b8, # greek small letter theta, U+03B8 ISOgrk3 + 'thetasym': 0x03d1, # greek small letter theta symbol, U+03D1 NEW + 'thinsp': 0x2009, # thin space, U+2009 ISOpub + 'thorn': 0x00fe, # latin small letter thorn with, U+00FE ISOlat1 + 'tilde': 0x02dc, # small tilde, U+02DC ISOdia + 'times': 0x00d7, # multiplication sign, U+00D7 ISOnum + 'trade': 0x2122, # trade mark sign, U+2122 ISOnum + 'uArr': 0x21d1, # upwards double arrow, U+21D1 ISOamsa + 'uacute': 0x00fa, # latin small letter u with acute, U+00FA ISOlat1 + 'uarr': 0x2191, # upwards arrow, U+2191 ISOnum + 'ucirc': 0x00fb, # latin small letter u with circumflex, U+00FB ISOlat1 + 'ugrave': 0x00f9, # latin small letter u with grave, U+00F9 ISOlat1 + 'uml': 0x00a8, # diaeresis = spacing diaeresis, U+00A8 ISOdia + 'upsih': 0x03d2, # greek upsilon with hook symbol, U+03D2 NEW + 'upsilon': 0x03c5, # greek small letter upsilon, U+03C5 ISOgrk3 + 'uuml': 0x00fc, # latin small letter u with diaeresis, U+00FC ISOlat1 + 'weierp': 0x2118, # script capital P = power set = Weierstrass p, U+2118 ISOamso + 'xi': 0x03be, # greek small letter xi, U+03BE ISOgrk3 + 'yacute': 0x00fd, # latin small letter y with acute, U+00FD ISOlat1 + 'yen': 0x00a5, # yen sign = yuan sign, U+00A5 ISOnum + 'yuml': 0x00ff, # latin small letter y with diaeresis, U+00FF ISOlat1 + 'zeta': 0x03b6, # greek small letter zeta, U+03B6 ISOgrk3 + 'zwj': 0x200d, # zero width joiner, U+200D NEW RFC 2070 + 'zwnj': 0x200c, # zero width non-joiner, U+200C NEW RFC 2070 +} + + +# maps the HTML5 named character references to the equivalent Unicode character(s) +html5 = { + 'Aacute': '\xc1', + 'aacute': '\xe1', + 'Aacute;': '\xc1', + 'aacute;': '\xe1', + 'Abreve;': '\u0102', + 'abreve;': '\u0103', + 'ac;': '\u223e', + 'acd;': '\u223f', + 'acE;': '\u223e\u0333', + 'Acirc': '\xc2', + 'acirc': '\xe2', + 'Acirc;': '\xc2', + 'acirc;': '\xe2', + 'acute': '\xb4', + 'acute;': '\xb4', + 'Acy;': '\u0410', + 'acy;': '\u0430', + 'AElig': '\xc6', + 'aelig': '\xe6', + 'AElig;': '\xc6', + 'aelig;': '\xe6', + 'af;': '\u2061', + 'Afr;': '\U0001d504', + 'afr;': '\U0001d51e', + 'Agrave': '\xc0', + 'agrave': '\xe0', + 'Agrave;': '\xc0', + 'agrave;': '\xe0', + 'alefsym;': '\u2135', + 'aleph;': '\u2135', + 'Alpha;': '\u0391', + 'alpha;': '\u03b1', + 'Amacr;': '\u0100', + 'amacr;': '\u0101', + 'amalg;': '\u2a3f', + 'AMP': '&', + 'amp': '&', + 'AMP;': '&', + 'amp;': '&', + 'And;': '\u2a53', + 'and;': '\u2227', + 'andand;': '\u2a55', + 'andd;': '\u2a5c', + 'andslope;': '\u2a58', + 'andv;': '\u2a5a', + 'ang;': '\u2220', + 'ange;': '\u29a4', + 'angle;': '\u2220', + 'angmsd;': '\u2221', + 'angmsdaa;': '\u29a8', + 'angmsdab;': '\u29a9', + 'angmsdac;': '\u29aa', + 'angmsdad;': '\u29ab', + 'angmsdae;': '\u29ac', + 'angmsdaf;': '\u29ad', + 'angmsdag;': '\u29ae', + 'angmsdah;': '\u29af', + 'angrt;': '\u221f', + 'angrtvb;': '\u22be', + 'angrtvbd;': '\u299d', + 'angsph;': '\u2222', + 'angst;': '\xc5', + 'angzarr;': '\u237c', + 'Aogon;': '\u0104', + 'aogon;': '\u0105', + 'Aopf;': '\U0001d538', + 'aopf;': '\U0001d552', + 'ap;': '\u2248', + 'apacir;': '\u2a6f', + 'apE;': '\u2a70', + 'ape;': '\u224a', + 'apid;': '\u224b', + 'apos;': "'", + 'ApplyFunction;': '\u2061', + 'approx;': '\u2248', + 'approxeq;': '\u224a', + 'Aring': '\xc5', + 'aring': '\xe5', + 'Aring;': '\xc5', + 'aring;': '\xe5', + 'Ascr;': '\U0001d49c', + 'ascr;': '\U0001d4b6', + 'Assign;': '\u2254', + 'ast;': '*', + 'asymp;': '\u2248', + 'asympeq;': '\u224d', + 'Atilde': '\xc3', + 'atilde': '\xe3', + 'Atilde;': '\xc3', + 'atilde;': '\xe3', + 'Auml': '\xc4', + 'auml': '\xe4', + 'Auml;': '\xc4', + 'auml;': '\xe4', + 'awconint;': '\u2233', + 'awint;': '\u2a11', + 'backcong;': '\u224c', + 'backepsilon;': '\u03f6', + 'backprime;': '\u2035', + 'backsim;': '\u223d', + 'backsimeq;': '\u22cd', + 'Backslash;': '\u2216', + 'Barv;': '\u2ae7', + 'barvee;': '\u22bd', + 'Barwed;': '\u2306', + 'barwed;': '\u2305', + 'barwedge;': '\u2305', + 'bbrk;': '\u23b5', + 'bbrktbrk;': '\u23b6', + 'bcong;': '\u224c', + 'Bcy;': '\u0411', + 'bcy;': '\u0431', + 'bdquo;': '\u201e', + 'becaus;': '\u2235', + 'Because;': '\u2235', + 'because;': '\u2235', + 'bemptyv;': '\u29b0', + 'bepsi;': '\u03f6', + 'bernou;': '\u212c', + 'Bernoullis;': '\u212c', + 'Beta;': '\u0392', + 'beta;': '\u03b2', + 'beth;': '\u2136', + 'between;': '\u226c', + 'Bfr;': '\U0001d505', + 'bfr;': '\U0001d51f', + 'bigcap;': '\u22c2', + 'bigcirc;': '\u25ef', + 'bigcup;': '\u22c3', + 'bigodot;': '\u2a00', + 'bigoplus;': '\u2a01', + 'bigotimes;': '\u2a02', + 'bigsqcup;': '\u2a06', + 'bigstar;': '\u2605', + 'bigtriangledown;': '\u25bd', + 'bigtriangleup;': '\u25b3', + 'biguplus;': '\u2a04', + 'bigvee;': '\u22c1', + 'bigwedge;': '\u22c0', + 'bkarow;': '\u290d', + 'blacklozenge;': '\u29eb', + 'blacksquare;': '\u25aa', + 'blacktriangle;': '\u25b4', + 'blacktriangledown;': '\u25be', + 'blacktriangleleft;': '\u25c2', + 'blacktriangleright;': '\u25b8', + 'blank;': '\u2423', + 'blk12;': '\u2592', + 'blk14;': '\u2591', + 'blk34;': '\u2593', + 'block;': '\u2588', + 'bne;': '=\u20e5', + 'bnequiv;': '\u2261\u20e5', + 'bNot;': '\u2aed', + 'bnot;': '\u2310', + 'Bopf;': '\U0001d539', + 'bopf;': '\U0001d553', + 'bot;': '\u22a5', + 'bottom;': '\u22a5', + 'bowtie;': '\u22c8', + 'boxbox;': '\u29c9', + 'boxDL;': '\u2557', + 'boxDl;': '\u2556', + 'boxdL;': '\u2555', + 'boxdl;': '\u2510', + 'boxDR;': '\u2554', + 'boxDr;': '\u2553', + 'boxdR;': '\u2552', + 'boxdr;': '\u250c', + 'boxH;': '\u2550', + 'boxh;': '\u2500', + 'boxHD;': '\u2566', + 'boxHd;': '\u2564', + 'boxhD;': '\u2565', + 'boxhd;': '\u252c', + 'boxHU;': '\u2569', + 'boxHu;': '\u2567', + 'boxhU;': '\u2568', + 'boxhu;': '\u2534', + 'boxminus;': '\u229f', + 'boxplus;': '\u229e', + 'boxtimes;': '\u22a0', + 'boxUL;': '\u255d', + 'boxUl;': '\u255c', + 'boxuL;': '\u255b', + 'boxul;': '\u2518', + 'boxUR;': '\u255a', + 'boxUr;': '\u2559', + 'boxuR;': '\u2558', + 'boxur;': '\u2514', + 'boxV;': '\u2551', + 'boxv;': '\u2502', + 'boxVH;': '\u256c', + 'boxVh;': '\u256b', + 'boxvH;': '\u256a', + 'boxvh;': '\u253c', + 'boxVL;': '\u2563', + 'boxVl;': '\u2562', + 'boxvL;': '\u2561', + 'boxvl;': '\u2524', + 'boxVR;': '\u2560', + 'boxVr;': '\u255f', + 'boxvR;': '\u255e', + 'boxvr;': '\u251c', + 'bprime;': '\u2035', + 'Breve;': '\u02d8', + 'breve;': '\u02d8', + 'brvbar': '\xa6', + 'brvbar;': '\xa6', + 'Bscr;': '\u212c', + 'bscr;': '\U0001d4b7', + 'bsemi;': '\u204f', + 'bsim;': '\u223d', + 'bsime;': '\u22cd', + 'bsol;': '\\', + 'bsolb;': '\u29c5', + 'bsolhsub;': '\u27c8', + 'bull;': '\u2022', + 'bullet;': '\u2022', + 'bump;': '\u224e', + 'bumpE;': '\u2aae', + 'bumpe;': '\u224f', + 'Bumpeq;': '\u224e', + 'bumpeq;': '\u224f', + 'Cacute;': '\u0106', + 'cacute;': '\u0107', + 'Cap;': '\u22d2', + 'cap;': '\u2229', + 'capand;': '\u2a44', + 'capbrcup;': '\u2a49', + 'capcap;': '\u2a4b', + 'capcup;': '\u2a47', + 'capdot;': '\u2a40', + 'CapitalDifferentialD;': '\u2145', + 'caps;': '\u2229\ufe00', + 'caret;': '\u2041', + 'caron;': '\u02c7', + 'Cayleys;': '\u212d', + 'ccaps;': '\u2a4d', + 'Ccaron;': '\u010c', + 'ccaron;': '\u010d', + 'Ccedil': '\xc7', + 'ccedil': '\xe7', + 'Ccedil;': '\xc7', + 'ccedil;': '\xe7', + 'Ccirc;': '\u0108', + 'ccirc;': '\u0109', + 'Cconint;': '\u2230', + 'ccups;': '\u2a4c', + 'ccupssm;': '\u2a50', + 'Cdot;': '\u010a', + 'cdot;': '\u010b', + 'cedil': '\xb8', + 'cedil;': '\xb8', + 'Cedilla;': '\xb8', + 'cemptyv;': '\u29b2', + 'cent': '\xa2', + 'cent;': '\xa2', + 'CenterDot;': '\xb7', + 'centerdot;': '\xb7', + 'Cfr;': '\u212d', + 'cfr;': '\U0001d520', + 'CHcy;': '\u0427', + 'chcy;': '\u0447', + 'check;': '\u2713', + 'checkmark;': '\u2713', + 'Chi;': '\u03a7', + 'chi;': '\u03c7', + 'cir;': '\u25cb', + 'circ;': '\u02c6', + 'circeq;': '\u2257', + 'circlearrowleft;': '\u21ba', + 'circlearrowright;': '\u21bb', + 'circledast;': '\u229b', + 'circledcirc;': '\u229a', + 'circleddash;': '\u229d', + 'CircleDot;': '\u2299', + 'circledR;': '\xae', + 'circledS;': '\u24c8', + 'CircleMinus;': '\u2296', + 'CirclePlus;': '\u2295', + 'CircleTimes;': '\u2297', + 'cirE;': '\u29c3', + 'cire;': '\u2257', + 'cirfnint;': '\u2a10', + 'cirmid;': '\u2aef', + 'cirscir;': '\u29c2', + 'ClockwiseContourIntegral;': '\u2232', + 'CloseCurlyDoubleQuote;': '\u201d', + 'CloseCurlyQuote;': '\u2019', + 'clubs;': '\u2663', + 'clubsuit;': '\u2663', + 'Colon;': '\u2237', + 'colon;': ':', + 'Colone;': '\u2a74', + 'colone;': '\u2254', + 'coloneq;': '\u2254', + 'comma;': ',', + 'commat;': '@', + 'comp;': '\u2201', + 'compfn;': '\u2218', + 'complement;': '\u2201', + 'complexes;': '\u2102', + 'cong;': '\u2245', + 'congdot;': '\u2a6d', + 'Congruent;': '\u2261', + 'Conint;': '\u222f', + 'conint;': '\u222e', + 'ContourIntegral;': '\u222e', + 'Copf;': '\u2102', + 'copf;': '\U0001d554', + 'coprod;': '\u2210', + 'Coproduct;': '\u2210', + 'COPY': '\xa9', + 'copy': '\xa9', + 'COPY;': '\xa9', + 'copy;': '\xa9', + 'copysr;': '\u2117', + 'CounterClockwiseContourIntegral;': '\u2233', + 'crarr;': '\u21b5', + 'Cross;': '\u2a2f', + 'cross;': '\u2717', + 'Cscr;': '\U0001d49e', + 'cscr;': '\U0001d4b8', + 'csub;': '\u2acf', + 'csube;': '\u2ad1', + 'csup;': '\u2ad0', + 'csupe;': '\u2ad2', + 'ctdot;': '\u22ef', + 'cudarrl;': '\u2938', + 'cudarrr;': '\u2935', + 'cuepr;': '\u22de', + 'cuesc;': '\u22df', + 'cularr;': '\u21b6', + 'cularrp;': '\u293d', + 'Cup;': '\u22d3', + 'cup;': '\u222a', + 'cupbrcap;': '\u2a48', + 'CupCap;': '\u224d', + 'cupcap;': '\u2a46', + 'cupcup;': '\u2a4a', + 'cupdot;': '\u228d', + 'cupor;': '\u2a45', + 'cups;': '\u222a\ufe00', + 'curarr;': '\u21b7', + 'curarrm;': '\u293c', + 'curlyeqprec;': '\u22de', + 'curlyeqsucc;': '\u22df', + 'curlyvee;': '\u22ce', + 'curlywedge;': '\u22cf', + 'curren': '\xa4', + 'curren;': '\xa4', + 'curvearrowleft;': '\u21b6', + 'curvearrowright;': '\u21b7', + 'cuvee;': '\u22ce', + 'cuwed;': '\u22cf', + 'cwconint;': '\u2232', + 'cwint;': '\u2231', + 'cylcty;': '\u232d', + 'Dagger;': '\u2021', + 'dagger;': '\u2020', + 'daleth;': '\u2138', + 'Darr;': '\u21a1', + 'dArr;': '\u21d3', + 'darr;': '\u2193', + 'dash;': '\u2010', + 'Dashv;': '\u2ae4', + 'dashv;': '\u22a3', + 'dbkarow;': '\u290f', + 'dblac;': '\u02dd', + 'Dcaron;': '\u010e', + 'dcaron;': '\u010f', + 'Dcy;': '\u0414', + 'dcy;': '\u0434', + 'DD;': '\u2145', + 'dd;': '\u2146', + 'ddagger;': '\u2021', + 'ddarr;': '\u21ca', + 'DDotrahd;': '\u2911', + 'ddotseq;': '\u2a77', + 'deg': '\xb0', + 'deg;': '\xb0', + 'Del;': '\u2207', + 'Delta;': '\u0394', + 'delta;': '\u03b4', + 'demptyv;': '\u29b1', + 'dfisht;': '\u297f', + 'Dfr;': '\U0001d507', + 'dfr;': '\U0001d521', + 'dHar;': '\u2965', + 'dharl;': '\u21c3', + 'dharr;': '\u21c2', + 'DiacriticalAcute;': '\xb4', + 'DiacriticalDot;': '\u02d9', + 'DiacriticalDoubleAcute;': '\u02dd', + 'DiacriticalGrave;': '`', + 'DiacriticalTilde;': '\u02dc', + 'diam;': '\u22c4', + 'Diamond;': '\u22c4', + 'diamond;': '\u22c4', + 'diamondsuit;': '\u2666', + 'diams;': '\u2666', + 'die;': '\xa8', + 'DifferentialD;': '\u2146', + 'digamma;': '\u03dd', + 'disin;': '\u22f2', + 'div;': '\xf7', + 'divide': '\xf7', + 'divide;': '\xf7', + 'divideontimes;': '\u22c7', + 'divonx;': '\u22c7', + 'DJcy;': '\u0402', + 'djcy;': '\u0452', + 'dlcorn;': '\u231e', + 'dlcrop;': '\u230d', + 'dollar;': '$', + 'Dopf;': '\U0001d53b', + 'dopf;': '\U0001d555', + 'Dot;': '\xa8', + 'dot;': '\u02d9', + 'DotDot;': '\u20dc', + 'doteq;': '\u2250', + 'doteqdot;': '\u2251', + 'DotEqual;': '\u2250', + 'dotminus;': '\u2238', + 'dotplus;': '\u2214', + 'dotsquare;': '\u22a1', + 'doublebarwedge;': '\u2306', + 'DoubleContourIntegral;': '\u222f', + 'DoubleDot;': '\xa8', + 'DoubleDownArrow;': '\u21d3', + 'DoubleLeftArrow;': '\u21d0', + 'DoubleLeftRightArrow;': '\u21d4', + 'DoubleLeftTee;': '\u2ae4', + 'DoubleLongLeftArrow;': '\u27f8', + 'DoubleLongLeftRightArrow;': '\u27fa', + 'DoubleLongRightArrow;': '\u27f9', + 'DoubleRightArrow;': '\u21d2', + 'DoubleRightTee;': '\u22a8', + 'DoubleUpArrow;': '\u21d1', + 'DoubleUpDownArrow;': '\u21d5', + 'DoubleVerticalBar;': '\u2225', + 'DownArrow;': '\u2193', + 'Downarrow;': '\u21d3', + 'downarrow;': '\u2193', + 'DownArrowBar;': '\u2913', + 'DownArrowUpArrow;': '\u21f5', + 'DownBreve;': '\u0311', + 'downdownarrows;': '\u21ca', + 'downharpoonleft;': '\u21c3', + 'downharpoonright;': '\u21c2', + 'DownLeftRightVector;': '\u2950', + 'DownLeftTeeVector;': '\u295e', + 'DownLeftVector;': '\u21bd', + 'DownLeftVectorBar;': '\u2956', + 'DownRightTeeVector;': '\u295f', + 'DownRightVector;': '\u21c1', + 'DownRightVectorBar;': '\u2957', + 'DownTee;': '\u22a4', + 'DownTeeArrow;': '\u21a7', + 'drbkarow;': '\u2910', + 'drcorn;': '\u231f', + 'drcrop;': '\u230c', + 'Dscr;': '\U0001d49f', + 'dscr;': '\U0001d4b9', + 'DScy;': '\u0405', + 'dscy;': '\u0455', + 'dsol;': '\u29f6', + 'Dstrok;': '\u0110', + 'dstrok;': '\u0111', + 'dtdot;': '\u22f1', + 'dtri;': '\u25bf', + 'dtrif;': '\u25be', + 'duarr;': '\u21f5', + 'duhar;': '\u296f', + 'dwangle;': '\u29a6', + 'DZcy;': '\u040f', + 'dzcy;': '\u045f', + 'dzigrarr;': '\u27ff', + 'Eacute': '\xc9', + 'eacute': '\xe9', + 'Eacute;': '\xc9', + 'eacute;': '\xe9', + 'easter;': '\u2a6e', + 'Ecaron;': '\u011a', + 'ecaron;': '\u011b', + 'ecir;': '\u2256', + 'Ecirc': '\xca', + 'ecirc': '\xea', + 'Ecirc;': '\xca', + 'ecirc;': '\xea', + 'ecolon;': '\u2255', + 'Ecy;': '\u042d', + 'ecy;': '\u044d', + 'eDDot;': '\u2a77', + 'Edot;': '\u0116', + 'eDot;': '\u2251', + 'edot;': '\u0117', + 'ee;': '\u2147', + 'efDot;': '\u2252', + 'Efr;': '\U0001d508', + 'efr;': '\U0001d522', + 'eg;': '\u2a9a', + 'Egrave': '\xc8', + 'egrave': '\xe8', + 'Egrave;': '\xc8', + 'egrave;': '\xe8', + 'egs;': '\u2a96', + 'egsdot;': '\u2a98', + 'el;': '\u2a99', + 'Element;': '\u2208', + 'elinters;': '\u23e7', + 'ell;': '\u2113', + 'els;': '\u2a95', + 'elsdot;': '\u2a97', + 'Emacr;': '\u0112', + 'emacr;': '\u0113', + 'empty;': '\u2205', + 'emptyset;': '\u2205', + 'EmptySmallSquare;': '\u25fb', + 'emptyv;': '\u2205', + 'EmptyVerySmallSquare;': '\u25ab', + 'emsp13;': '\u2004', + 'emsp14;': '\u2005', + 'emsp;': '\u2003', + 'ENG;': '\u014a', + 'eng;': '\u014b', + 'ensp;': '\u2002', + 'Eogon;': '\u0118', + 'eogon;': '\u0119', + 'Eopf;': '\U0001d53c', + 'eopf;': '\U0001d556', + 'epar;': '\u22d5', + 'eparsl;': '\u29e3', + 'eplus;': '\u2a71', + 'epsi;': '\u03b5', + 'Epsilon;': '\u0395', + 'epsilon;': '\u03b5', + 'epsiv;': '\u03f5', + 'eqcirc;': '\u2256', + 'eqcolon;': '\u2255', + 'eqsim;': '\u2242', + 'eqslantgtr;': '\u2a96', + 'eqslantless;': '\u2a95', + 'Equal;': '\u2a75', + 'equals;': '=', + 'EqualTilde;': '\u2242', + 'equest;': '\u225f', + 'Equilibrium;': '\u21cc', + 'equiv;': '\u2261', + 'equivDD;': '\u2a78', + 'eqvparsl;': '\u29e5', + 'erarr;': '\u2971', + 'erDot;': '\u2253', + 'Escr;': '\u2130', + 'escr;': '\u212f', + 'esdot;': '\u2250', + 'Esim;': '\u2a73', + 'esim;': '\u2242', + 'Eta;': '\u0397', + 'eta;': '\u03b7', + 'ETH': '\xd0', + 'eth': '\xf0', + 'ETH;': '\xd0', + 'eth;': '\xf0', + 'Euml': '\xcb', + 'euml': '\xeb', + 'Euml;': '\xcb', + 'euml;': '\xeb', + 'euro;': '\u20ac', + 'excl;': '!', + 'exist;': '\u2203', + 'Exists;': '\u2203', + 'expectation;': '\u2130', + 'ExponentialE;': '\u2147', + 'exponentiale;': '\u2147', + 'fallingdotseq;': '\u2252', + 'Fcy;': '\u0424', + 'fcy;': '\u0444', + 'female;': '\u2640', + 'ffilig;': '\ufb03', + 'fflig;': '\ufb00', + 'ffllig;': '\ufb04', + 'Ffr;': '\U0001d509', + 'ffr;': '\U0001d523', + 'filig;': '\ufb01', + 'FilledSmallSquare;': '\u25fc', + 'FilledVerySmallSquare;': '\u25aa', + 'fjlig;': 'fj', + 'flat;': '\u266d', + 'fllig;': '\ufb02', + 'fltns;': '\u25b1', + 'fnof;': '\u0192', + 'Fopf;': '\U0001d53d', + 'fopf;': '\U0001d557', + 'ForAll;': '\u2200', + 'forall;': '\u2200', + 'fork;': '\u22d4', + 'forkv;': '\u2ad9', + 'Fouriertrf;': '\u2131', + 'fpartint;': '\u2a0d', + 'frac12': '\xbd', + 'frac12;': '\xbd', + 'frac13;': '\u2153', + 'frac14': '\xbc', + 'frac14;': '\xbc', + 'frac15;': '\u2155', + 'frac16;': '\u2159', + 'frac18;': '\u215b', + 'frac23;': '\u2154', + 'frac25;': '\u2156', + 'frac34': '\xbe', + 'frac34;': '\xbe', + 'frac35;': '\u2157', + 'frac38;': '\u215c', + 'frac45;': '\u2158', + 'frac56;': '\u215a', + 'frac58;': '\u215d', + 'frac78;': '\u215e', + 'frasl;': '\u2044', + 'frown;': '\u2322', + 'Fscr;': '\u2131', + 'fscr;': '\U0001d4bb', + 'gacute;': '\u01f5', + 'Gamma;': '\u0393', + 'gamma;': '\u03b3', + 'Gammad;': '\u03dc', + 'gammad;': '\u03dd', + 'gap;': '\u2a86', + 'Gbreve;': '\u011e', + 'gbreve;': '\u011f', + 'Gcedil;': '\u0122', + 'Gcirc;': '\u011c', + 'gcirc;': '\u011d', + 'Gcy;': '\u0413', + 'gcy;': '\u0433', + 'Gdot;': '\u0120', + 'gdot;': '\u0121', + 'gE;': '\u2267', + 'ge;': '\u2265', + 'gEl;': '\u2a8c', + 'gel;': '\u22db', + 'geq;': '\u2265', + 'geqq;': '\u2267', + 'geqslant;': '\u2a7e', + 'ges;': '\u2a7e', + 'gescc;': '\u2aa9', + 'gesdot;': '\u2a80', + 'gesdoto;': '\u2a82', + 'gesdotol;': '\u2a84', + 'gesl;': '\u22db\ufe00', + 'gesles;': '\u2a94', + 'Gfr;': '\U0001d50a', + 'gfr;': '\U0001d524', + 'Gg;': '\u22d9', + 'gg;': '\u226b', + 'ggg;': '\u22d9', + 'gimel;': '\u2137', + 'GJcy;': '\u0403', + 'gjcy;': '\u0453', + 'gl;': '\u2277', + 'gla;': '\u2aa5', + 'glE;': '\u2a92', + 'glj;': '\u2aa4', + 'gnap;': '\u2a8a', + 'gnapprox;': '\u2a8a', + 'gnE;': '\u2269', + 'gne;': '\u2a88', + 'gneq;': '\u2a88', + 'gneqq;': '\u2269', + 'gnsim;': '\u22e7', + 'Gopf;': '\U0001d53e', + 'gopf;': '\U0001d558', + 'grave;': '`', + 'GreaterEqual;': '\u2265', + 'GreaterEqualLess;': '\u22db', + 'GreaterFullEqual;': '\u2267', + 'GreaterGreater;': '\u2aa2', + 'GreaterLess;': '\u2277', + 'GreaterSlantEqual;': '\u2a7e', + 'GreaterTilde;': '\u2273', + 'Gscr;': '\U0001d4a2', + 'gscr;': '\u210a', + 'gsim;': '\u2273', + 'gsime;': '\u2a8e', + 'gsiml;': '\u2a90', + 'GT': '>', + 'gt': '>', + 'GT;': '>', + 'Gt;': '\u226b', + 'gt;': '>', + 'gtcc;': '\u2aa7', + 'gtcir;': '\u2a7a', + 'gtdot;': '\u22d7', + 'gtlPar;': '\u2995', + 'gtquest;': '\u2a7c', + 'gtrapprox;': '\u2a86', + 'gtrarr;': '\u2978', + 'gtrdot;': '\u22d7', + 'gtreqless;': '\u22db', + 'gtreqqless;': '\u2a8c', + 'gtrless;': '\u2277', + 'gtrsim;': '\u2273', + 'gvertneqq;': '\u2269\ufe00', + 'gvnE;': '\u2269\ufe00', + 'Hacek;': '\u02c7', + 'hairsp;': '\u200a', + 'half;': '\xbd', + 'hamilt;': '\u210b', + 'HARDcy;': '\u042a', + 'hardcy;': '\u044a', + 'hArr;': '\u21d4', + 'harr;': '\u2194', + 'harrcir;': '\u2948', + 'harrw;': '\u21ad', + 'Hat;': '^', + 'hbar;': '\u210f', + 'Hcirc;': '\u0124', + 'hcirc;': '\u0125', + 'hearts;': '\u2665', + 'heartsuit;': '\u2665', + 'hellip;': '\u2026', + 'hercon;': '\u22b9', + 'Hfr;': '\u210c', + 'hfr;': '\U0001d525', + 'HilbertSpace;': '\u210b', + 'hksearow;': '\u2925', + 'hkswarow;': '\u2926', + 'hoarr;': '\u21ff', + 'homtht;': '\u223b', + 'hookleftarrow;': '\u21a9', + 'hookrightarrow;': '\u21aa', + 'Hopf;': '\u210d', + 'hopf;': '\U0001d559', + 'horbar;': '\u2015', + 'HorizontalLine;': '\u2500', + 'Hscr;': '\u210b', + 'hscr;': '\U0001d4bd', + 'hslash;': '\u210f', + 'Hstrok;': '\u0126', + 'hstrok;': '\u0127', + 'HumpDownHump;': '\u224e', + 'HumpEqual;': '\u224f', + 'hybull;': '\u2043', + 'hyphen;': '\u2010', + 'Iacute': '\xcd', + 'iacute': '\xed', + 'Iacute;': '\xcd', + 'iacute;': '\xed', + 'ic;': '\u2063', + 'Icirc': '\xce', + 'icirc': '\xee', + 'Icirc;': '\xce', + 'icirc;': '\xee', + 'Icy;': '\u0418', + 'icy;': '\u0438', + 'Idot;': '\u0130', + 'IEcy;': '\u0415', + 'iecy;': '\u0435', + 'iexcl': '\xa1', + 'iexcl;': '\xa1', + 'iff;': '\u21d4', + 'Ifr;': '\u2111', + 'ifr;': '\U0001d526', + 'Igrave': '\xcc', + 'igrave': '\xec', + 'Igrave;': '\xcc', + 'igrave;': '\xec', + 'ii;': '\u2148', + 'iiiint;': '\u2a0c', + 'iiint;': '\u222d', + 'iinfin;': '\u29dc', + 'iiota;': '\u2129', + 'IJlig;': '\u0132', + 'ijlig;': '\u0133', + 'Im;': '\u2111', + 'Imacr;': '\u012a', + 'imacr;': '\u012b', + 'image;': '\u2111', + 'ImaginaryI;': '\u2148', + 'imagline;': '\u2110', + 'imagpart;': '\u2111', + 'imath;': '\u0131', + 'imof;': '\u22b7', + 'imped;': '\u01b5', + 'Implies;': '\u21d2', + 'in;': '\u2208', + 'incare;': '\u2105', + 'infin;': '\u221e', + 'infintie;': '\u29dd', + 'inodot;': '\u0131', + 'Int;': '\u222c', + 'int;': '\u222b', + 'intcal;': '\u22ba', + 'integers;': '\u2124', + 'Integral;': '\u222b', + 'intercal;': '\u22ba', + 'Intersection;': '\u22c2', + 'intlarhk;': '\u2a17', + 'intprod;': '\u2a3c', + 'InvisibleComma;': '\u2063', + 'InvisibleTimes;': '\u2062', + 'IOcy;': '\u0401', + 'iocy;': '\u0451', + 'Iogon;': '\u012e', + 'iogon;': '\u012f', + 'Iopf;': '\U0001d540', + 'iopf;': '\U0001d55a', + 'Iota;': '\u0399', + 'iota;': '\u03b9', + 'iprod;': '\u2a3c', + 'iquest': '\xbf', + 'iquest;': '\xbf', + 'Iscr;': '\u2110', + 'iscr;': '\U0001d4be', + 'isin;': '\u2208', + 'isindot;': '\u22f5', + 'isinE;': '\u22f9', + 'isins;': '\u22f4', + 'isinsv;': '\u22f3', + 'isinv;': '\u2208', + 'it;': '\u2062', + 'Itilde;': '\u0128', + 'itilde;': '\u0129', + 'Iukcy;': '\u0406', + 'iukcy;': '\u0456', + 'Iuml': '\xcf', + 'iuml': '\xef', + 'Iuml;': '\xcf', + 'iuml;': '\xef', + 'Jcirc;': '\u0134', + 'jcirc;': '\u0135', + 'Jcy;': '\u0419', + 'jcy;': '\u0439', + 'Jfr;': '\U0001d50d', + 'jfr;': '\U0001d527', + 'jmath;': '\u0237', + 'Jopf;': '\U0001d541', + 'jopf;': '\U0001d55b', + 'Jscr;': '\U0001d4a5', + 'jscr;': '\U0001d4bf', + 'Jsercy;': '\u0408', + 'jsercy;': '\u0458', + 'Jukcy;': '\u0404', + 'jukcy;': '\u0454', + 'Kappa;': '\u039a', + 'kappa;': '\u03ba', + 'kappav;': '\u03f0', + 'Kcedil;': '\u0136', + 'kcedil;': '\u0137', + 'Kcy;': '\u041a', + 'kcy;': '\u043a', + 'Kfr;': '\U0001d50e', + 'kfr;': '\U0001d528', + 'kgreen;': '\u0138', + 'KHcy;': '\u0425', + 'khcy;': '\u0445', + 'KJcy;': '\u040c', + 'kjcy;': '\u045c', + 'Kopf;': '\U0001d542', + 'kopf;': '\U0001d55c', + 'Kscr;': '\U0001d4a6', + 'kscr;': '\U0001d4c0', + 'lAarr;': '\u21da', + 'Lacute;': '\u0139', + 'lacute;': '\u013a', + 'laemptyv;': '\u29b4', + 'lagran;': '\u2112', + 'Lambda;': '\u039b', + 'lambda;': '\u03bb', + 'Lang;': '\u27ea', + 'lang;': '\u27e8', + 'langd;': '\u2991', + 'langle;': '\u27e8', + 'lap;': '\u2a85', + 'Laplacetrf;': '\u2112', + 'laquo': '\xab', + 'laquo;': '\xab', + 'Larr;': '\u219e', + 'lArr;': '\u21d0', + 'larr;': '\u2190', + 'larrb;': '\u21e4', + 'larrbfs;': '\u291f', + 'larrfs;': '\u291d', + 'larrhk;': '\u21a9', + 'larrlp;': '\u21ab', + 'larrpl;': '\u2939', + 'larrsim;': '\u2973', + 'larrtl;': '\u21a2', + 'lat;': '\u2aab', + 'lAtail;': '\u291b', + 'latail;': '\u2919', + 'late;': '\u2aad', + 'lates;': '\u2aad\ufe00', + 'lBarr;': '\u290e', + 'lbarr;': '\u290c', + 'lbbrk;': '\u2772', + 'lbrace;': '{', + 'lbrack;': '[', + 'lbrke;': '\u298b', + 'lbrksld;': '\u298f', + 'lbrkslu;': '\u298d', + 'Lcaron;': '\u013d', + 'lcaron;': '\u013e', + 'Lcedil;': '\u013b', + 'lcedil;': '\u013c', + 'lceil;': '\u2308', + 'lcub;': '{', + 'Lcy;': '\u041b', + 'lcy;': '\u043b', + 'ldca;': '\u2936', + 'ldquo;': '\u201c', + 'ldquor;': '\u201e', + 'ldrdhar;': '\u2967', + 'ldrushar;': '\u294b', + 'ldsh;': '\u21b2', + 'lE;': '\u2266', + 'le;': '\u2264', + 'LeftAngleBracket;': '\u27e8', + 'LeftArrow;': '\u2190', + 'Leftarrow;': '\u21d0', + 'leftarrow;': '\u2190', + 'LeftArrowBar;': '\u21e4', + 'LeftArrowRightArrow;': '\u21c6', + 'leftarrowtail;': '\u21a2', + 'LeftCeiling;': '\u2308', + 'LeftDoubleBracket;': '\u27e6', + 'LeftDownTeeVector;': '\u2961', + 'LeftDownVector;': '\u21c3', + 'LeftDownVectorBar;': '\u2959', + 'LeftFloor;': '\u230a', + 'leftharpoondown;': '\u21bd', + 'leftharpoonup;': '\u21bc', + 'leftleftarrows;': '\u21c7', + 'LeftRightArrow;': '\u2194', + 'Leftrightarrow;': '\u21d4', + 'leftrightarrow;': '\u2194', + 'leftrightarrows;': '\u21c6', + 'leftrightharpoons;': '\u21cb', + 'leftrightsquigarrow;': '\u21ad', + 'LeftRightVector;': '\u294e', + 'LeftTee;': '\u22a3', + 'LeftTeeArrow;': '\u21a4', + 'LeftTeeVector;': '\u295a', + 'leftthreetimes;': '\u22cb', + 'LeftTriangle;': '\u22b2', + 'LeftTriangleBar;': '\u29cf', + 'LeftTriangleEqual;': '\u22b4', + 'LeftUpDownVector;': '\u2951', + 'LeftUpTeeVector;': '\u2960', + 'LeftUpVector;': '\u21bf', + 'LeftUpVectorBar;': '\u2958', + 'LeftVector;': '\u21bc', + 'LeftVectorBar;': '\u2952', + 'lEg;': '\u2a8b', + 'leg;': '\u22da', + 'leq;': '\u2264', + 'leqq;': '\u2266', + 'leqslant;': '\u2a7d', + 'les;': '\u2a7d', + 'lescc;': '\u2aa8', + 'lesdot;': '\u2a7f', + 'lesdoto;': '\u2a81', + 'lesdotor;': '\u2a83', + 'lesg;': '\u22da\ufe00', + 'lesges;': '\u2a93', + 'lessapprox;': '\u2a85', + 'lessdot;': '\u22d6', + 'lesseqgtr;': '\u22da', + 'lesseqqgtr;': '\u2a8b', + 'LessEqualGreater;': '\u22da', + 'LessFullEqual;': '\u2266', + 'LessGreater;': '\u2276', + 'lessgtr;': '\u2276', + 'LessLess;': '\u2aa1', + 'lesssim;': '\u2272', + 'LessSlantEqual;': '\u2a7d', + 'LessTilde;': '\u2272', + 'lfisht;': '\u297c', + 'lfloor;': '\u230a', + 'Lfr;': '\U0001d50f', + 'lfr;': '\U0001d529', + 'lg;': '\u2276', + 'lgE;': '\u2a91', + 'lHar;': '\u2962', + 'lhard;': '\u21bd', + 'lharu;': '\u21bc', + 'lharul;': '\u296a', + 'lhblk;': '\u2584', + 'LJcy;': '\u0409', + 'ljcy;': '\u0459', + 'Ll;': '\u22d8', + 'll;': '\u226a', + 'llarr;': '\u21c7', + 'llcorner;': '\u231e', + 'Lleftarrow;': '\u21da', + 'llhard;': '\u296b', + 'lltri;': '\u25fa', + 'Lmidot;': '\u013f', + 'lmidot;': '\u0140', + 'lmoust;': '\u23b0', + 'lmoustache;': '\u23b0', + 'lnap;': '\u2a89', + 'lnapprox;': '\u2a89', + 'lnE;': '\u2268', + 'lne;': '\u2a87', + 'lneq;': '\u2a87', + 'lneqq;': '\u2268', + 'lnsim;': '\u22e6', + 'loang;': '\u27ec', + 'loarr;': '\u21fd', + 'lobrk;': '\u27e6', + 'LongLeftArrow;': '\u27f5', + 'Longleftarrow;': '\u27f8', + 'longleftarrow;': '\u27f5', + 'LongLeftRightArrow;': '\u27f7', + 'Longleftrightarrow;': '\u27fa', + 'longleftrightarrow;': '\u27f7', + 'longmapsto;': '\u27fc', + 'LongRightArrow;': '\u27f6', + 'Longrightarrow;': '\u27f9', + 'longrightarrow;': '\u27f6', + 'looparrowleft;': '\u21ab', + 'looparrowright;': '\u21ac', + 'lopar;': '\u2985', + 'Lopf;': '\U0001d543', + 'lopf;': '\U0001d55d', + 'loplus;': '\u2a2d', + 'lotimes;': '\u2a34', + 'lowast;': '\u2217', + 'lowbar;': '_', + 'LowerLeftArrow;': '\u2199', + 'LowerRightArrow;': '\u2198', + 'loz;': '\u25ca', + 'lozenge;': '\u25ca', + 'lozf;': '\u29eb', + 'lpar;': '(', + 'lparlt;': '\u2993', + 'lrarr;': '\u21c6', + 'lrcorner;': '\u231f', + 'lrhar;': '\u21cb', + 'lrhard;': '\u296d', + 'lrm;': '\u200e', + 'lrtri;': '\u22bf', + 'lsaquo;': '\u2039', + 'Lscr;': '\u2112', + 'lscr;': '\U0001d4c1', + 'Lsh;': '\u21b0', + 'lsh;': '\u21b0', + 'lsim;': '\u2272', + 'lsime;': '\u2a8d', + 'lsimg;': '\u2a8f', + 'lsqb;': '[', + 'lsquo;': '\u2018', + 'lsquor;': '\u201a', + 'Lstrok;': '\u0141', + 'lstrok;': '\u0142', + 'LT': '<', + 'lt': '<', + 'LT;': '<', + 'Lt;': '\u226a', + 'lt;': '<', + 'ltcc;': '\u2aa6', + 'ltcir;': '\u2a79', + 'ltdot;': '\u22d6', + 'lthree;': '\u22cb', + 'ltimes;': '\u22c9', + 'ltlarr;': '\u2976', + 'ltquest;': '\u2a7b', + 'ltri;': '\u25c3', + 'ltrie;': '\u22b4', + 'ltrif;': '\u25c2', + 'ltrPar;': '\u2996', + 'lurdshar;': '\u294a', + 'luruhar;': '\u2966', + 'lvertneqq;': '\u2268\ufe00', + 'lvnE;': '\u2268\ufe00', + 'macr': '\xaf', + 'macr;': '\xaf', + 'male;': '\u2642', + 'malt;': '\u2720', + 'maltese;': '\u2720', + 'Map;': '\u2905', + 'map;': '\u21a6', + 'mapsto;': '\u21a6', + 'mapstodown;': '\u21a7', + 'mapstoleft;': '\u21a4', + 'mapstoup;': '\u21a5', + 'marker;': '\u25ae', + 'mcomma;': '\u2a29', + 'Mcy;': '\u041c', + 'mcy;': '\u043c', + 'mdash;': '\u2014', + 'mDDot;': '\u223a', + 'measuredangle;': '\u2221', + 'MediumSpace;': '\u205f', + 'Mellintrf;': '\u2133', + 'Mfr;': '\U0001d510', + 'mfr;': '\U0001d52a', + 'mho;': '\u2127', + 'micro': '\xb5', + 'micro;': '\xb5', + 'mid;': '\u2223', + 'midast;': '*', + 'midcir;': '\u2af0', + 'middot': '\xb7', + 'middot;': '\xb7', + 'minus;': '\u2212', + 'minusb;': '\u229f', + 'minusd;': '\u2238', + 'minusdu;': '\u2a2a', + 'MinusPlus;': '\u2213', + 'mlcp;': '\u2adb', + 'mldr;': '\u2026', + 'mnplus;': '\u2213', + 'models;': '\u22a7', + 'Mopf;': '\U0001d544', + 'mopf;': '\U0001d55e', + 'mp;': '\u2213', + 'Mscr;': '\u2133', + 'mscr;': '\U0001d4c2', + 'mstpos;': '\u223e', + 'Mu;': '\u039c', + 'mu;': '\u03bc', + 'multimap;': '\u22b8', + 'mumap;': '\u22b8', + 'nabla;': '\u2207', + 'Nacute;': '\u0143', + 'nacute;': '\u0144', + 'nang;': '\u2220\u20d2', + 'nap;': '\u2249', + 'napE;': '\u2a70\u0338', + 'napid;': '\u224b\u0338', + 'napos;': '\u0149', + 'napprox;': '\u2249', + 'natur;': '\u266e', + 'natural;': '\u266e', + 'naturals;': '\u2115', + 'nbsp': '\xa0', + 'nbsp;': '\xa0', + 'nbump;': '\u224e\u0338', + 'nbumpe;': '\u224f\u0338', + 'ncap;': '\u2a43', + 'Ncaron;': '\u0147', + 'ncaron;': '\u0148', + 'Ncedil;': '\u0145', + 'ncedil;': '\u0146', + 'ncong;': '\u2247', + 'ncongdot;': '\u2a6d\u0338', + 'ncup;': '\u2a42', + 'Ncy;': '\u041d', + 'ncy;': '\u043d', + 'ndash;': '\u2013', + 'ne;': '\u2260', + 'nearhk;': '\u2924', + 'neArr;': '\u21d7', + 'nearr;': '\u2197', + 'nearrow;': '\u2197', + 'nedot;': '\u2250\u0338', + 'NegativeMediumSpace;': '\u200b', + 'NegativeThickSpace;': '\u200b', + 'NegativeThinSpace;': '\u200b', + 'NegativeVeryThinSpace;': '\u200b', + 'nequiv;': '\u2262', + 'nesear;': '\u2928', + 'nesim;': '\u2242\u0338', + 'NestedGreaterGreater;': '\u226b', + 'NestedLessLess;': '\u226a', + 'NewLine;': '\n', + 'nexist;': '\u2204', + 'nexists;': '\u2204', + 'Nfr;': '\U0001d511', + 'nfr;': '\U0001d52b', + 'ngE;': '\u2267\u0338', + 'nge;': '\u2271', + 'ngeq;': '\u2271', + 'ngeqq;': '\u2267\u0338', + 'ngeqslant;': '\u2a7e\u0338', + 'nges;': '\u2a7e\u0338', + 'nGg;': '\u22d9\u0338', + 'ngsim;': '\u2275', + 'nGt;': '\u226b\u20d2', + 'ngt;': '\u226f', + 'ngtr;': '\u226f', + 'nGtv;': '\u226b\u0338', + 'nhArr;': '\u21ce', + 'nharr;': '\u21ae', + 'nhpar;': '\u2af2', + 'ni;': '\u220b', + 'nis;': '\u22fc', + 'nisd;': '\u22fa', + 'niv;': '\u220b', + 'NJcy;': '\u040a', + 'njcy;': '\u045a', + 'nlArr;': '\u21cd', + 'nlarr;': '\u219a', + 'nldr;': '\u2025', + 'nlE;': '\u2266\u0338', + 'nle;': '\u2270', + 'nLeftarrow;': '\u21cd', + 'nleftarrow;': '\u219a', + 'nLeftrightarrow;': '\u21ce', + 'nleftrightarrow;': '\u21ae', + 'nleq;': '\u2270', + 'nleqq;': '\u2266\u0338', + 'nleqslant;': '\u2a7d\u0338', + 'nles;': '\u2a7d\u0338', + 'nless;': '\u226e', + 'nLl;': '\u22d8\u0338', + 'nlsim;': '\u2274', + 'nLt;': '\u226a\u20d2', + 'nlt;': '\u226e', + 'nltri;': '\u22ea', + 'nltrie;': '\u22ec', + 'nLtv;': '\u226a\u0338', + 'nmid;': '\u2224', + 'NoBreak;': '\u2060', + 'NonBreakingSpace;': '\xa0', + 'Nopf;': '\u2115', + 'nopf;': '\U0001d55f', + 'not': '\xac', + 'Not;': '\u2aec', + 'not;': '\xac', + 'NotCongruent;': '\u2262', + 'NotCupCap;': '\u226d', + 'NotDoubleVerticalBar;': '\u2226', + 'NotElement;': '\u2209', + 'NotEqual;': '\u2260', + 'NotEqualTilde;': '\u2242\u0338', + 'NotExists;': '\u2204', + 'NotGreater;': '\u226f', + 'NotGreaterEqual;': '\u2271', + 'NotGreaterFullEqual;': '\u2267\u0338', + 'NotGreaterGreater;': '\u226b\u0338', + 'NotGreaterLess;': '\u2279', + 'NotGreaterSlantEqual;': '\u2a7e\u0338', + 'NotGreaterTilde;': '\u2275', + 'NotHumpDownHump;': '\u224e\u0338', + 'NotHumpEqual;': '\u224f\u0338', + 'notin;': '\u2209', + 'notindot;': '\u22f5\u0338', + 'notinE;': '\u22f9\u0338', + 'notinva;': '\u2209', + 'notinvb;': '\u22f7', + 'notinvc;': '\u22f6', + 'NotLeftTriangle;': '\u22ea', + 'NotLeftTriangleBar;': '\u29cf\u0338', + 'NotLeftTriangleEqual;': '\u22ec', + 'NotLess;': '\u226e', + 'NotLessEqual;': '\u2270', + 'NotLessGreater;': '\u2278', + 'NotLessLess;': '\u226a\u0338', + 'NotLessSlantEqual;': '\u2a7d\u0338', + 'NotLessTilde;': '\u2274', + 'NotNestedGreaterGreater;': '\u2aa2\u0338', + 'NotNestedLessLess;': '\u2aa1\u0338', + 'notni;': '\u220c', + 'notniva;': '\u220c', + 'notnivb;': '\u22fe', + 'notnivc;': '\u22fd', + 'NotPrecedes;': '\u2280', + 'NotPrecedesEqual;': '\u2aaf\u0338', + 'NotPrecedesSlantEqual;': '\u22e0', + 'NotReverseElement;': '\u220c', + 'NotRightTriangle;': '\u22eb', + 'NotRightTriangleBar;': '\u29d0\u0338', + 'NotRightTriangleEqual;': '\u22ed', + 'NotSquareSubset;': '\u228f\u0338', + 'NotSquareSubsetEqual;': '\u22e2', + 'NotSquareSuperset;': '\u2290\u0338', + 'NotSquareSupersetEqual;': '\u22e3', + 'NotSubset;': '\u2282\u20d2', + 'NotSubsetEqual;': '\u2288', + 'NotSucceeds;': '\u2281', + 'NotSucceedsEqual;': '\u2ab0\u0338', + 'NotSucceedsSlantEqual;': '\u22e1', + 'NotSucceedsTilde;': '\u227f\u0338', + 'NotSuperset;': '\u2283\u20d2', + 'NotSupersetEqual;': '\u2289', + 'NotTilde;': '\u2241', + 'NotTildeEqual;': '\u2244', + 'NotTildeFullEqual;': '\u2247', + 'NotTildeTilde;': '\u2249', + 'NotVerticalBar;': '\u2224', + 'npar;': '\u2226', + 'nparallel;': '\u2226', + 'nparsl;': '\u2afd\u20e5', + 'npart;': '\u2202\u0338', + 'npolint;': '\u2a14', + 'npr;': '\u2280', + 'nprcue;': '\u22e0', + 'npre;': '\u2aaf\u0338', + 'nprec;': '\u2280', + 'npreceq;': '\u2aaf\u0338', + 'nrArr;': '\u21cf', + 'nrarr;': '\u219b', + 'nrarrc;': '\u2933\u0338', + 'nrarrw;': '\u219d\u0338', + 'nRightarrow;': '\u21cf', + 'nrightarrow;': '\u219b', + 'nrtri;': '\u22eb', + 'nrtrie;': '\u22ed', + 'nsc;': '\u2281', + 'nsccue;': '\u22e1', + 'nsce;': '\u2ab0\u0338', + 'Nscr;': '\U0001d4a9', + 'nscr;': '\U0001d4c3', + 'nshortmid;': '\u2224', + 'nshortparallel;': '\u2226', + 'nsim;': '\u2241', + 'nsime;': '\u2244', + 'nsimeq;': '\u2244', + 'nsmid;': '\u2224', + 'nspar;': '\u2226', + 'nsqsube;': '\u22e2', + 'nsqsupe;': '\u22e3', + 'nsub;': '\u2284', + 'nsubE;': '\u2ac5\u0338', + 'nsube;': '\u2288', + 'nsubset;': '\u2282\u20d2', + 'nsubseteq;': '\u2288', + 'nsubseteqq;': '\u2ac5\u0338', + 'nsucc;': '\u2281', + 'nsucceq;': '\u2ab0\u0338', + 'nsup;': '\u2285', + 'nsupE;': '\u2ac6\u0338', + 'nsupe;': '\u2289', + 'nsupset;': '\u2283\u20d2', + 'nsupseteq;': '\u2289', + 'nsupseteqq;': '\u2ac6\u0338', + 'ntgl;': '\u2279', + 'Ntilde': '\xd1', + 'ntilde': '\xf1', + 'Ntilde;': '\xd1', + 'ntilde;': '\xf1', + 'ntlg;': '\u2278', + 'ntriangleleft;': '\u22ea', + 'ntrianglelefteq;': '\u22ec', + 'ntriangleright;': '\u22eb', + 'ntrianglerighteq;': '\u22ed', + 'Nu;': '\u039d', + 'nu;': '\u03bd', + 'num;': '#', + 'numero;': '\u2116', + 'numsp;': '\u2007', + 'nvap;': '\u224d\u20d2', + 'nVDash;': '\u22af', + 'nVdash;': '\u22ae', + 'nvDash;': '\u22ad', + 'nvdash;': '\u22ac', + 'nvge;': '\u2265\u20d2', + 'nvgt;': '>\u20d2', + 'nvHarr;': '\u2904', + 'nvinfin;': '\u29de', + 'nvlArr;': '\u2902', + 'nvle;': '\u2264\u20d2', + 'nvlt;': '<\u20d2', + 'nvltrie;': '\u22b4\u20d2', + 'nvrArr;': '\u2903', + 'nvrtrie;': '\u22b5\u20d2', + 'nvsim;': '\u223c\u20d2', + 'nwarhk;': '\u2923', + 'nwArr;': '\u21d6', + 'nwarr;': '\u2196', + 'nwarrow;': '\u2196', + 'nwnear;': '\u2927', + 'Oacute': '\xd3', + 'oacute': '\xf3', + 'Oacute;': '\xd3', + 'oacute;': '\xf3', + 'oast;': '\u229b', + 'ocir;': '\u229a', + 'Ocirc': '\xd4', + 'ocirc': '\xf4', + 'Ocirc;': '\xd4', + 'ocirc;': '\xf4', + 'Ocy;': '\u041e', + 'ocy;': '\u043e', + 'odash;': '\u229d', + 'Odblac;': '\u0150', + 'odblac;': '\u0151', + 'odiv;': '\u2a38', + 'odot;': '\u2299', + 'odsold;': '\u29bc', + 'OElig;': '\u0152', + 'oelig;': '\u0153', + 'ofcir;': '\u29bf', + 'Ofr;': '\U0001d512', + 'ofr;': '\U0001d52c', + 'ogon;': '\u02db', + 'Ograve': '\xd2', + 'ograve': '\xf2', + 'Ograve;': '\xd2', + 'ograve;': '\xf2', + 'ogt;': '\u29c1', + 'ohbar;': '\u29b5', + 'ohm;': '\u03a9', + 'oint;': '\u222e', + 'olarr;': '\u21ba', + 'olcir;': '\u29be', + 'olcross;': '\u29bb', + 'oline;': '\u203e', + 'olt;': '\u29c0', + 'Omacr;': '\u014c', + 'omacr;': '\u014d', + 'Omega;': '\u03a9', + 'omega;': '\u03c9', + 'Omicron;': '\u039f', + 'omicron;': '\u03bf', + 'omid;': '\u29b6', + 'ominus;': '\u2296', + 'Oopf;': '\U0001d546', + 'oopf;': '\U0001d560', + 'opar;': '\u29b7', + 'OpenCurlyDoubleQuote;': '\u201c', + 'OpenCurlyQuote;': '\u2018', + 'operp;': '\u29b9', + 'oplus;': '\u2295', + 'Or;': '\u2a54', + 'or;': '\u2228', + 'orarr;': '\u21bb', + 'ord;': '\u2a5d', + 'order;': '\u2134', + 'orderof;': '\u2134', + 'ordf': '\xaa', + 'ordf;': '\xaa', + 'ordm': '\xba', + 'ordm;': '\xba', + 'origof;': '\u22b6', + 'oror;': '\u2a56', + 'orslope;': '\u2a57', + 'orv;': '\u2a5b', + 'oS;': '\u24c8', + 'Oscr;': '\U0001d4aa', + 'oscr;': '\u2134', + 'Oslash': '\xd8', + 'oslash': '\xf8', + 'Oslash;': '\xd8', + 'oslash;': '\xf8', + 'osol;': '\u2298', + 'Otilde': '\xd5', + 'otilde': '\xf5', + 'Otilde;': '\xd5', + 'otilde;': '\xf5', + 'Otimes;': '\u2a37', + 'otimes;': '\u2297', + 'otimesas;': '\u2a36', + 'Ouml': '\xd6', + 'ouml': '\xf6', + 'Ouml;': '\xd6', + 'ouml;': '\xf6', + 'ovbar;': '\u233d', + 'OverBar;': '\u203e', + 'OverBrace;': '\u23de', + 'OverBracket;': '\u23b4', + 'OverParenthesis;': '\u23dc', + 'par;': '\u2225', + 'para': '\xb6', + 'para;': '\xb6', + 'parallel;': '\u2225', + 'parsim;': '\u2af3', + 'parsl;': '\u2afd', + 'part;': '\u2202', + 'PartialD;': '\u2202', + 'Pcy;': '\u041f', + 'pcy;': '\u043f', + 'percnt;': '%', + 'period;': '.', + 'permil;': '\u2030', + 'perp;': '\u22a5', + 'pertenk;': '\u2031', + 'Pfr;': '\U0001d513', + 'pfr;': '\U0001d52d', + 'Phi;': '\u03a6', + 'phi;': '\u03c6', + 'phiv;': '\u03d5', + 'phmmat;': '\u2133', + 'phone;': '\u260e', + 'Pi;': '\u03a0', + 'pi;': '\u03c0', + 'pitchfork;': '\u22d4', + 'piv;': '\u03d6', + 'planck;': '\u210f', + 'planckh;': '\u210e', + 'plankv;': '\u210f', + 'plus;': '+', + 'plusacir;': '\u2a23', + 'plusb;': '\u229e', + 'pluscir;': '\u2a22', + 'plusdo;': '\u2214', + 'plusdu;': '\u2a25', + 'pluse;': '\u2a72', + 'PlusMinus;': '\xb1', + 'plusmn': '\xb1', + 'plusmn;': '\xb1', + 'plussim;': '\u2a26', + 'plustwo;': '\u2a27', + 'pm;': '\xb1', + 'Poincareplane;': '\u210c', + 'pointint;': '\u2a15', + 'Popf;': '\u2119', + 'popf;': '\U0001d561', + 'pound': '\xa3', + 'pound;': '\xa3', + 'Pr;': '\u2abb', + 'pr;': '\u227a', + 'prap;': '\u2ab7', + 'prcue;': '\u227c', + 'prE;': '\u2ab3', + 'pre;': '\u2aaf', + 'prec;': '\u227a', + 'precapprox;': '\u2ab7', + 'preccurlyeq;': '\u227c', + 'Precedes;': '\u227a', + 'PrecedesEqual;': '\u2aaf', + 'PrecedesSlantEqual;': '\u227c', + 'PrecedesTilde;': '\u227e', + 'preceq;': '\u2aaf', + 'precnapprox;': '\u2ab9', + 'precneqq;': '\u2ab5', + 'precnsim;': '\u22e8', + 'precsim;': '\u227e', + 'Prime;': '\u2033', + 'prime;': '\u2032', + 'primes;': '\u2119', + 'prnap;': '\u2ab9', + 'prnE;': '\u2ab5', + 'prnsim;': '\u22e8', + 'prod;': '\u220f', + 'Product;': '\u220f', + 'profalar;': '\u232e', + 'profline;': '\u2312', + 'profsurf;': '\u2313', + 'prop;': '\u221d', + 'Proportion;': '\u2237', + 'Proportional;': '\u221d', + 'propto;': '\u221d', + 'prsim;': '\u227e', + 'prurel;': '\u22b0', + 'Pscr;': '\U0001d4ab', + 'pscr;': '\U0001d4c5', + 'Psi;': '\u03a8', + 'psi;': '\u03c8', + 'puncsp;': '\u2008', + 'Qfr;': '\U0001d514', + 'qfr;': '\U0001d52e', + 'qint;': '\u2a0c', + 'Qopf;': '\u211a', + 'qopf;': '\U0001d562', + 'qprime;': '\u2057', + 'Qscr;': '\U0001d4ac', + 'qscr;': '\U0001d4c6', + 'quaternions;': '\u210d', + 'quatint;': '\u2a16', + 'quest;': '?', + 'questeq;': '\u225f', + 'QUOT': '"', + 'quot': '"', + 'QUOT;': '"', + 'quot;': '"', + 'rAarr;': '\u21db', + 'race;': '\u223d\u0331', + 'Racute;': '\u0154', + 'racute;': '\u0155', + 'radic;': '\u221a', + 'raemptyv;': '\u29b3', + 'Rang;': '\u27eb', + 'rang;': '\u27e9', + 'rangd;': '\u2992', + 'range;': '\u29a5', + 'rangle;': '\u27e9', + 'raquo': '\xbb', + 'raquo;': '\xbb', + 'Rarr;': '\u21a0', + 'rArr;': '\u21d2', + 'rarr;': '\u2192', + 'rarrap;': '\u2975', + 'rarrb;': '\u21e5', + 'rarrbfs;': '\u2920', + 'rarrc;': '\u2933', + 'rarrfs;': '\u291e', + 'rarrhk;': '\u21aa', + 'rarrlp;': '\u21ac', + 'rarrpl;': '\u2945', + 'rarrsim;': '\u2974', + 'Rarrtl;': '\u2916', + 'rarrtl;': '\u21a3', + 'rarrw;': '\u219d', + 'rAtail;': '\u291c', + 'ratail;': '\u291a', + 'ratio;': '\u2236', + 'rationals;': '\u211a', + 'RBarr;': '\u2910', + 'rBarr;': '\u290f', + 'rbarr;': '\u290d', + 'rbbrk;': '\u2773', + 'rbrace;': '}', + 'rbrack;': ']', + 'rbrke;': '\u298c', + 'rbrksld;': '\u298e', + 'rbrkslu;': '\u2990', + 'Rcaron;': '\u0158', + 'rcaron;': '\u0159', + 'Rcedil;': '\u0156', + 'rcedil;': '\u0157', + 'rceil;': '\u2309', + 'rcub;': '}', + 'Rcy;': '\u0420', + 'rcy;': '\u0440', + 'rdca;': '\u2937', + 'rdldhar;': '\u2969', + 'rdquo;': '\u201d', + 'rdquor;': '\u201d', + 'rdsh;': '\u21b3', + 'Re;': '\u211c', + 'real;': '\u211c', + 'realine;': '\u211b', + 'realpart;': '\u211c', + 'reals;': '\u211d', + 'rect;': '\u25ad', + 'REG': '\xae', + 'reg': '\xae', + 'REG;': '\xae', + 'reg;': '\xae', + 'ReverseElement;': '\u220b', + 'ReverseEquilibrium;': '\u21cb', + 'ReverseUpEquilibrium;': '\u296f', + 'rfisht;': '\u297d', + 'rfloor;': '\u230b', + 'Rfr;': '\u211c', + 'rfr;': '\U0001d52f', + 'rHar;': '\u2964', + 'rhard;': '\u21c1', + 'rharu;': '\u21c0', + 'rharul;': '\u296c', + 'Rho;': '\u03a1', + 'rho;': '\u03c1', + 'rhov;': '\u03f1', + 'RightAngleBracket;': '\u27e9', + 'RightArrow;': '\u2192', + 'Rightarrow;': '\u21d2', + 'rightarrow;': '\u2192', + 'RightArrowBar;': '\u21e5', + 'RightArrowLeftArrow;': '\u21c4', + 'rightarrowtail;': '\u21a3', + 'RightCeiling;': '\u2309', + 'RightDoubleBracket;': '\u27e7', + 'RightDownTeeVector;': '\u295d', + 'RightDownVector;': '\u21c2', + 'RightDownVectorBar;': '\u2955', + 'RightFloor;': '\u230b', + 'rightharpoondown;': '\u21c1', + 'rightharpoonup;': '\u21c0', + 'rightleftarrows;': '\u21c4', + 'rightleftharpoons;': '\u21cc', + 'rightrightarrows;': '\u21c9', + 'rightsquigarrow;': '\u219d', + 'RightTee;': '\u22a2', + 'RightTeeArrow;': '\u21a6', + 'RightTeeVector;': '\u295b', + 'rightthreetimes;': '\u22cc', + 'RightTriangle;': '\u22b3', + 'RightTriangleBar;': '\u29d0', + 'RightTriangleEqual;': '\u22b5', + 'RightUpDownVector;': '\u294f', + 'RightUpTeeVector;': '\u295c', + 'RightUpVector;': '\u21be', + 'RightUpVectorBar;': '\u2954', + 'RightVector;': '\u21c0', + 'RightVectorBar;': '\u2953', + 'ring;': '\u02da', + 'risingdotseq;': '\u2253', + 'rlarr;': '\u21c4', + 'rlhar;': '\u21cc', + 'rlm;': '\u200f', + 'rmoust;': '\u23b1', + 'rmoustache;': '\u23b1', + 'rnmid;': '\u2aee', + 'roang;': '\u27ed', + 'roarr;': '\u21fe', + 'robrk;': '\u27e7', + 'ropar;': '\u2986', + 'Ropf;': '\u211d', + 'ropf;': '\U0001d563', + 'roplus;': '\u2a2e', + 'rotimes;': '\u2a35', + 'RoundImplies;': '\u2970', + 'rpar;': ')', + 'rpargt;': '\u2994', + 'rppolint;': '\u2a12', + 'rrarr;': '\u21c9', + 'Rrightarrow;': '\u21db', + 'rsaquo;': '\u203a', + 'Rscr;': '\u211b', + 'rscr;': '\U0001d4c7', + 'Rsh;': '\u21b1', + 'rsh;': '\u21b1', + 'rsqb;': ']', + 'rsquo;': '\u2019', + 'rsquor;': '\u2019', + 'rthree;': '\u22cc', + 'rtimes;': '\u22ca', + 'rtri;': '\u25b9', + 'rtrie;': '\u22b5', + 'rtrif;': '\u25b8', + 'rtriltri;': '\u29ce', + 'RuleDelayed;': '\u29f4', + 'ruluhar;': '\u2968', + 'rx;': '\u211e', + 'Sacute;': '\u015a', + 'sacute;': '\u015b', + 'sbquo;': '\u201a', + 'Sc;': '\u2abc', + 'sc;': '\u227b', + 'scap;': '\u2ab8', + 'Scaron;': '\u0160', + 'scaron;': '\u0161', + 'sccue;': '\u227d', + 'scE;': '\u2ab4', + 'sce;': '\u2ab0', + 'Scedil;': '\u015e', + 'scedil;': '\u015f', + 'Scirc;': '\u015c', + 'scirc;': '\u015d', + 'scnap;': '\u2aba', + 'scnE;': '\u2ab6', + 'scnsim;': '\u22e9', + 'scpolint;': '\u2a13', + 'scsim;': '\u227f', + 'Scy;': '\u0421', + 'scy;': '\u0441', + 'sdot;': '\u22c5', + 'sdotb;': '\u22a1', + 'sdote;': '\u2a66', + 'searhk;': '\u2925', + 'seArr;': '\u21d8', + 'searr;': '\u2198', + 'searrow;': '\u2198', + 'sect': '\xa7', + 'sect;': '\xa7', + 'semi;': ';', + 'seswar;': '\u2929', + 'setminus;': '\u2216', + 'setmn;': '\u2216', + 'sext;': '\u2736', + 'Sfr;': '\U0001d516', + 'sfr;': '\U0001d530', + 'sfrown;': '\u2322', + 'sharp;': '\u266f', + 'SHCHcy;': '\u0429', + 'shchcy;': '\u0449', + 'SHcy;': '\u0428', + 'shcy;': '\u0448', + 'ShortDownArrow;': '\u2193', + 'ShortLeftArrow;': '\u2190', + 'shortmid;': '\u2223', + 'shortparallel;': '\u2225', + 'ShortRightArrow;': '\u2192', + 'ShortUpArrow;': '\u2191', + 'shy': '\xad', + 'shy;': '\xad', + 'Sigma;': '\u03a3', + 'sigma;': '\u03c3', + 'sigmaf;': '\u03c2', + 'sigmav;': '\u03c2', + 'sim;': '\u223c', + 'simdot;': '\u2a6a', + 'sime;': '\u2243', + 'simeq;': '\u2243', + 'simg;': '\u2a9e', + 'simgE;': '\u2aa0', + 'siml;': '\u2a9d', + 'simlE;': '\u2a9f', + 'simne;': '\u2246', + 'simplus;': '\u2a24', + 'simrarr;': '\u2972', + 'slarr;': '\u2190', + 'SmallCircle;': '\u2218', + 'smallsetminus;': '\u2216', + 'smashp;': '\u2a33', + 'smeparsl;': '\u29e4', + 'smid;': '\u2223', + 'smile;': '\u2323', + 'smt;': '\u2aaa', + 'smte;': '\u2aac', + 'smtes;': '\u2aac\ufe00', + 'SOFTcy;': '\u042c', + 'softcy;': '\u044c', + 'sol;': '/', + 'solb;': '\u29c4', + 'solbar;': '\u233f', + 'Sopf;': '\U0001d54a', + 'sopf;': '\U0001d564', + 'spades;': '\u2660', + 'spadesuit;': '\u2660', + 'spar;': '\u2225', + 'sqcap;': '\u2293', + 'sqcaps;': '\u2293\ufe00', + 'sqcup;': '\u2294', + 'sqcups;': '\u2294\ufe00', + 'Sqrt;': '\u221a', + 'sqsub;': '\u228f', + 'sqsube;': '\u2291', + 'sqsubset;': '\u228f', + 'sqsubseteq;': '\u2291', + 'sqsup;': '\u2290', + 'sqsupe;': '\u2292', + 'sqsupset;': '\u2290', + 'sqsupseteq;': '\u2292', + 'squ;': '\u25a1', + 'Square;': '\u25a1', + 'square;': '\u25a1', + 'SquareIntersection;': '\u2293', + 'SquareSubset;': '\u228f', + 'SquareSubsetEqual;': '\u2291', + 'SquareSuperset;': '\u2290', + 'SquareSupersetEqual;': '\u2292', + 'SquareUnion;': '\u2294', + 'squarf;': '\u25aa', + 'squf;': '\u25aa', + 'srarr;': '\u2192', + 'Sscr;': '\U0001d4ae', + 'sscr;': '\U0001d4c8', + 'ssetmn;': '\u2216', + 'ssmile;': '\u2323', + 'sstarf;': '\u22c6', + 'Star;': '\u22c6', + 'star;': '\u2606', + 'starf;': '\u2605', + 'straightepsilon;': '\u03f5', + 'straightphi;': '\u03d5', + 'strns;': '\xaf', + 'Sub;': '\u22d0', + 'sub;': '\u2282', + 'subdot;': '\u2abd', + 'subE;': '\u2ac5', + 'sube;': '\u2286', + 'subedot;': '\u2ac3', + 'submult;': '\u2ac1', + 'subnE;': '\u2acb', + 'subne;': '\u228a', + 'subplus;': '\u2abf', + 'subrarr;': '\u2979', + 'Subset;': '\u22d0', + 'subset;': '\u2282', + 'subseteq;': '\u2286', + 'subseteqq;': '\u2ac5', + 'SubsetEqual;': '\u2286', + 'subsetneq;': '\u228a', + 'subsetneqq;': '\u2acb', + 'subsim;': '\u2ac7', + 'subsub;': '\u2ad5', + 'subsup;': '\u2ad3', + 'succ;': '\u227b', + 'succapprox;': '\u2ab8', + 'succcurlyeq;': '\u227d', + 'Succeeds;': '\u227b', + 'SucceedsEqual;': '\u2ab0', + 'SucceedsSlantEqual;': '\u227d', + 'SucceedsTilde;': '\u227f', + 'succeq;': '\u2ab0', + 'succnapprox;': '\u2aba', + 'succneqq;': '\u2ab6', + 'succnsim;': '\u22e9', + 'succsim;': '\u227f', + 'SuchThat;': '\u220b', + 'Sum;': '\u2211', + 'sum;': '\u2211', + 'sung;': '\u266a', + 'sup1': '\xb9', + 'sup1;': '\xb9', + 'sup2': '\xb2', + 'sup2;': '\xb2', + 'sup3': '\xb3', + 'sup3;': '\xb3', + 'Sup;': '\u22d1', + 'sup;': '\u2283', + 'supdot;': '\u2abe', + 'supdsub;': '\u2ad8', + 'supE;': '\u2ac6', + 'supe;': '\u2287', + 'supedot;': '\u2ac4', + 'Superset;': '\u2283', + 'SupersetEqual;': '\u2287', + 'suphsol;': '\u27c9', + 'suphsub;': '\u2ad7', + 'suplarr;': '\u297b', + 'supmult;': '\u2ac2', + 'supnE;': '\u2acc', + 'supne;': '\u228b', + 'supplus;': '\u2ac0', + 'Supset;': '\u22d1', + 'supset;': '\u2283', + 'supseteq;': '\u2287', + 'supseteqq;': '\u2ac6', + 'supsetneq;': '\u228b', + 'supsetneqq;': '\u2acc', + 'supsim;': '\u2ac8', + 'supsub;': '\u2ad4', + 'supsup;': '\u2ad6', + 'swarhk;': '\u2926', + 'swArr;': '\u21d9', + 'swarr;': '\u2199', + 'swarrow;': '\u2199', + 'swnwar;': '\u292a', + 'szlig': '\xdf', + 'szlig;': '\xdf', + 'Tab;': '\t', + 'target;': '\u2316', + 'Tau;': '\u03a4', + 'tau;': '\u03c4', + 'tbrk;': '\u23b4', + 'Tcaron;': '\u0164', + 'tcaron;': '\u0165', + 'Tcedil;': '\u0162', + 'tcedil;': '\u0163', + 'Tcy;': '\u0422', + 'tcy;': '\u0442', + 'tdot;': '\u20db', + 'telrec;': '\u2315', + 'Tfr;': '\U0001d517', + 'tfr;': '\U0001d531', + 'there4;': '\u2234', + 'Therefore;': '\u2234', + 'therefore;': '\u2234', + 'Theta;': '\u0398', + 'theta;': '\u03b8', + 'thetasym;': '\u03d1', + 'thetav;': '\u03d1', + 'thickapprox;': '\u2248', + 'thicksim;': '\u223c', + 'ThickSpace;': '\u205f\u200a', + 'thinsp;': '\u2009', + 'ThinSpace;': '\u2009', + 'thkap;': '\u2248', + 'thksim;': '\u223c', + 'THORN': '\xde', + 'thorn': '\xfe', + 'THORN;': '\xde', + 'thorn;': '\xfe', + 'Tilde;': '\u223c', + 'tilde;': '\u02dc', + 'TildeEqual;': '\u2243', + 'TildeFullEqual;': '\u2245', + 'TildeTilde;': '\u2248', + 'times': '\xd7', + 'times;': '\xd7', + 'timesb;': '\u22a0', + 'timesbar;': '\u2a31', + 'timesd;': '\u2a30', + 'tint;': '\u222d', + 'toea;': '\u2928', + 'top;': '\u22a4', + 'topbot;': '\u2336', + 'topcir;': '\u2af1', + 'Topf;': '\U0001d54b', + 'topf;': '\U0001d565', + 'topfork;': '\u2ada', + 'tosa;': '\u2929', + 'tprime;': '\u2034', + 'TRADE;': '\u2122', + 'trade;': '\u2122', + 'triangle;': '\u25b5', + 'triangledown;': '\u25bf', + 'triangleleft;': '\u25c3', + 'trianglelefteq;': '\u22b4', + 'triangleq;': '\u225c', + 'triangleright;': '\u25b9', + 'trianglerighteq;': '\u22b5', + 'tridot;': '\u25ec', + 'trie;': '\u225c', + 'triminus;': '\u2a3a', + 'TripleDot;': '\u20db', + 'triplus;': '\u2a39', + 'trisb;': '\u29cd', + 'tritime;': '\u2a3b', + 'trpezium;': '\u23e2', + 'Tscr;': '\U0001d4af', + 'tscr;': '\U0001d4c9', + 'TScy;': '\u0426', + 'tscy;': '\u0446', + 'TSHcy;': '\u040b', + 'tshcy;': '\u045b', + 'Tstrok;': '\u0166', + 'tstrok;': '\u0167', + 'twixt;': '\u226c', + 'twoheadleftarrow;': '\u219e', + 'twoheadrightarrow;': '\u21a0', + 'Uacute': '\xda', + 'uacute': '\xfa', + 'Uacute;': '\xda', + 'uacute;': '\xfa', + 'Uarr;': '\u219f', + 'uArr;': '\u21d1', + 'uarr;': '\u2191', + 'Uarrocir;': '\u2949', + 'Ubrcy;': '\u040e', + 'ubrcy;': '\u045e', + 'Ubreve;': '\u016c', + 'ubreve;': '\u016d', + 'Ucirc': '\xdb', + 'ucirc': '\xfb', + 'Ucirc;': '\xdb', + 'ucirc;': '\xfb', + 'Ucy;': '\u0423', + 'ucy;': '\u0443', + 'udarr;': '\u21c5', + 'Udblac;': '\u0170', + 'udblac;': '\u0171', + 'udhar;': '\u296e', + 'ufisht;': '\u297e', + 'Ufr;': '\U0001d518', + 'ufr;': '\U0001d532', + 'Ugrave': '\xd9', + 'ugrave': '\xf9', + 'Ugrave;': '\xd9', + 'ugrave;': '\xf9', + 'uHar;': '\u2963', + 'uharl;': '\u21bf', + 'uharr;': '\u21be', + 'uhblk;': '\u2580', + 'ulcorn;': '\u231c', + 'ulcorner;': '\u231c', + 'ulcrop;': '\u230f', + 'ultri;': '\u25f8', + 'Umacr;': '\u016a', + 'umacr;': '\u016b', + 'uml': '\xa8', + 'uml;': '\xa8', + 'UnderBar;': '_', + 'UnderBrace;': '\u23df', + 'UnderBracket;': '\u23b5', + 'UnderParenthesis;': '\u23dd', + 'Union;': '\u22c3', + 'UnionPlus;': '\u228e', + 'Uogon;': '\u0172', + 'uogon;': '\u0173', + 'Uopf;': '\U0001d54c', + 'uopf;': '\U0001d566', + 'UpArrow;': '\u2191', + 'Uparrow;': '\u21d1', + 'uparrow;': '\u2191', + 'UpArrowBar;': '\u2912', + 'UpArrowDownArrow;': '\u21c5', + 'UpDownArrow;': '\u2195', + 'Updownarrow;': '\u21d5', + 'updownarrow;': '\u2195', + 'UpEquilibrium;': '\u296e', + 'upharpoonleft;': '\u21bf', + 'upharpoonright;': '\u21be', + 'uplus;': '\u228e', + 'UpperLeftArrow;': '\u2196', + 'UpperRightArrow;': '\u2197', + 'Upsi;': '\u03d2', + 'upsi;': '\u03c5', + 'upsih;': '\u03d2', + 'Upsilon;': '\u03a5', + 'upsilon;': '\u03c5', + 'UpTee;': '\u22a5', + 'UpTeeArrow;': '\u21a5', + 'upuparrows;': '\u21c8', + 'urcorn;': '\u231d', + 'urcorner;': '\u231d', + 'urcrop;': '\u230e', + 'Uring;': '\u016e', + 'uring;': '\u016f', + 'urtri;': '\u25f9', + 'Uscr;': '\U0001d4b0', + 'uscr;': '\U0001d4ca', + 'utdot;': '\u22f0', + 'Utilde;': '\u0168', + 'utilde;': '\u0169', + 'utri;': '\u25b5', + 'utrif;': '\u25b4', + 'uuarr;': '\u21c8', + 'Uuml': '\xdc', + 'uuml': '\xfc', + 'Uuml;': '\xdc', + 'uuml;': '\xfc', + 'uwangle;': '\u29a7', + 'vangrt;': '\u299c', + 'varepsilon;': '\u03f5', + 'varkappa;': '\u03f0', + 'varnothing;': '\u2205', + 'varphi;': '\u03d5', + 'varpi;': '\u03d6', + 'varpropto;': '\u221d', + 'vArr;': '\u21d5', + 'varr;': '\u2195', + 'varrho;': '\u03f1', + 'varsigma;': '\u03c2', + 'varsubsetneq;': '\u228a\ufe00', + 'varsubsetneqq;': '\u2acb\ufe00', + 'varsupsetneq;': '\u228b\ufe00', + 'varsupsetneqq;': '\u2acc\ufe00', + 'vartheta;': '\u03d1', + 'vartriangleleft;': '\u22b2', + 'vartriangleright;': '\u22b3', + 'Vbar;': '\u2aeb', + 'vBar;': '\u2ae8', + 'vBarv;': '\u2ae9', + 'Vcy;': '\u0412', + 'vcy;': '\u0432', + 'VDash;': '\u22ab', + 'Vdash;': '\u22a9', + 'vDash;': '\u22a8', + 'vdash;': '\u22a2', + 'Vdashl;': '\u2ae6', + 'Vee;': '\u22c1', + 'vee;': '\u2228', + 'veebar;': '\u22bb', + 'veeeq;': '\u225a', + 'vellip;': '\u22ee', + 'Verbar;': '\u2016', + 'verbar;': '|', + 'Vert;': '\u2016', + 'vert;': '|', + 'VerticalBar;': '\u2223', + 'VerticalLine;': '|', + 'VerticalSeparator;': '\u2758', + 'VerticalTilde;': '\u2240', + 'VeryThinSpace;': '\u200a', + 'Vfr;': '\U0001d519', + 'vfr;': '\U0001d533', + 'vltri;': '\u22b2', + 'vnsub;': '\u2282\u20d2', + 'vnsup;': '\u2283\u20d2', + 'Vopf;': '\U0001d54d', + 'vopf;': '\U0001d567', + 'vprop;': '\u221d', + 'vrtri;': '\u22b3', + 'Vscr;': '\U0001d4b1', + 'vscr;': '\U0001d4cb', + 'vsubnE;': '\u2acb\ufe00', + 'vsubne;': '\u228a\ufe00', + 'vsupnE;': '\u2acc\ufe00', + 'vsupne;': '\u228b\ufe00', + 'Vvdash;': '\u22aa', + 'vzigzag;': '\u299a', + 'Wcirc;': '\u0174', + 'wcirc;': '\u0175', + 'wedbar;': '\u2a5f', + 'Wedge;': '\u22c0', + 'wedge;': '\u2227', + 'wedgeq;': '\u2259', + 'weierp;': '\u2118', + 'Wfr;': '\U0001d51a', + 'wfr;': '\U0001d534', + 'Wopf;': '\U0001d54e', + 'wopf;': '\U0001d568', + 'wp;': '\u2118', + 'wr;': '\u2240', + 'wreath;': '\u2240', + 'Wscr;': '\U0001d4b2', + 'wscr;': '\U0001d4cc', + 'xcap;': '\u22c2', + 'xcirc;': '\u25ef', + 'xcup;': '\u22c3', + 'xdtri;': '\u25bd', + 'Xfr;': '\U0001d51b', + 'xfr;': '\U0001d535', + 'xhArr;': '\u27fa', + 'xharr;': '\u27f7', + 'Xi;': '\u039e', + 'xi;': '\u03be', + 'xlArr;': '\u27f8', + 'xlarr;': '\u27f5', + 'xmap;': '\u27fc', + 'xnis;': '\u22fb', + 'xodot;': '\u2a00', + 'Xopf;': '\U0001d54f', + 'xopf;': '\U0001d569', + 'xoplus;': '\u2a01', + 'xotime;': '\u2a02', + 'xrArr;': '\u27f9', + 'xrarr;': '\u27f6', + 'Xscr;': '\U0001d4b3', + 'xscr;': '\U0001d4cd', + 'xsqcup;': '\u2a06', + 'xuplus;': '\u2a04', + 'xutri;': '\u25b3', + 'xvee;': '\u22c1', + 'xwedge;': '\u22c0', + 'Yacute': '\xdd', + 'yacute': '\xfd', + 'Yacute;': '\xdd', + 'yacute;': '\xfd', + 'YAcy;': '\u042f', + 'yacy;': '\u044f', + 'Ycirc;': '\u0176', + 'ycirc;': '\u0177', + 'Ycy;': '\u042b', + 'ycy;': '\u044b', + 'yen': '\xa5', + 'yen;': '\xa5', + 'Yfr;': '\U0001d51c', + 'yfr;': '\U0001d536', + 'YIcy;': '\u0407', + 'yicy;': '\u0457', + 'Yopf;': '\U0001d550', + 'yopf;': '\U0001d56a', + 'Yscr;': '\U0001d4b4', + 'yscr;': '\U0001d4ce', + 'YUcy;': '\u042e', + 'yucy;': '\u044e', + 'yuml': '\xff', + 'Yuml;': '\u0178', + 'yuml;': '\xff', + 'Zacute;': '\u0179', + 'zacute;': '\u017a', + 'Zcaron;': '\u017d', + 'zcaron;': '\u017e', + 'Zcy;': '\u0417', + 'zcy;': '\u0437', + 'Zdot;': '\u017b', + 'zdot;': '\u017c', + 'zeetrf;': '\u2128', + 'ZeroWidthSpace;': '\u200b', + 'Zeta;': '\u0396', + 'zeta;': '\u03b6', + 'Zfr;': '\u2128', + 'zfr;': '\U0001d537', + 'ZHcy;': '\u0416', + 'zhcy;': '\u0436', + 'zigrarr;': '\u21dd', + 'Zopf;': '\u2124', + 'zopf;': '\U0001d56b', + 'Zscr;': '\U0001d4b5', + 'zscr;': '\U0001d4cf', + 'zwj;': '\u200d', + 'zwnj;': '\u200c', +} + +# maps the Unicode code point to the HTML entity name +codepoint2name = {} + +# maps the HTML entity name to the character +# (or a character reference if the character is outside the Latin-1 range) +entitydefs = {} + +for (name, codepoint) in name2codepoint.items(): + codepoint2name[codepoint] = name + entitydefs[name] = chr(codepoint) + +del name, codepoint diff --git a/shared/package-files/28/2834b97334d06545a4ce5129f575a77e2fe21a4adfd6dcf5739b51e55040e971/canonicalize_modified_loop.h b/shared/package-files/28/2834b97334d06545a4ce5129f575a77e2fe21a4adfd6dcf5739b51e55040e971/canonicalize_modified_loop.h new file mode 100644 index 0000000000000000000000000000000000000000..f8a3a4ecc2690138fc3b2c836b2a56f4bee46215 --- /dev/null +++ b/shared/package-files/28/2834b97334d06545a4ce5129f575a77e2fe21a4adfd6dcf5739b51e55040e971/canonicalize_modified_loop.h @@ -0,0 +1,16 @@ +#pragma once +#include + +#include + +namespace torch { +namespace jit { + +struct Graph; + +// Transforms loops so that they can be represented as python +// for or while loops +TORCH_API void CanonicalizeModifiedLoops(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/28/2837565063efc3b3da5d4179aaa65b49b2af2c5cf1a25f008f404839088f5b5b/att620 b/shared/package-files/28/2837565063efc3b3da5d4179aaa65b49b2af2c5cf1a25f008f404839088f5b5b/att620 new file mode 100644 index 0000000000000000000000000000000000000000..9e7cdc8106fd7b68095158f25560a6b053cecc2d Binary files /dev/null and b/shared/package-files/28/2837565063efc3b3da5d4179aaa65b49b2af2c5cf1a25f008f404839088f5b5b/att620 differ diff --git a/shared/package-files/28/2837e4e8055c64a8fbe6f414f2379ac5b8e6f4a6428087e32ad3b39ef3f974a1/area.py b/shared/package-files/28/2837e4e8055c64a8fbe6f414f2379ac5b8e6f4a6428087e32ad3b39ef3f974a1/area.py new file mode 100644 index 0000000000000000000000000000000000000000..7514a6d13b7a373ff3c89ccbe06abec77442c0f2 --- /dev/null +++ b/shared/package-files/28/2837e4e8055c64a8fbe6f414f2379ac5b8e6f4a6428087e32ad3b39ef3f974a1/area.py @@ -0,0 +1,170 @@ +from __future__ import annotations +from collections import defaultdict +from dataclasses import dataclass + +import numpy as np +import matplotlib as mpl + +from seaborn._marks.base import ( + Mark, + Mappable, + MappableBool, + MappableFloat, + MappableColor, + MappableStyle, + resolve_properties, + resolve_color, + document_properties, +) + + +class AreaBase: + + def _plot(self, split_gen, scales, orient): + + patches = defaultdict(list) + + for keys, data, ax in split_gen(): + + kws = {} + data = self._standardize_coordinate_parameters(data, orient) + resolved = resolve_properties(self, keys, scales) + verts = self._get_verts(data, orient) + ax.update_datalim(verts) + + # TODO should really move this logic into resolve_color + fc = resolve_color(self, keys, "", scales) + if not resolved["fill"]: + fc = mpl.colors.to_rgba(fc, 0) + + kws["facecolor"] = fc + kws["edgecolor"] = resolve_color(self, keys, "edge", scales) + kws["linewidth"] = resolved["edgewidth"] + kws["linestyle"] = resolved["edgestyle"] + + patches[ax].append(mpl.patches.Polygon(verts, **kws)) + + for ax, ax_patches in patches.items(): + + for patch in ax_patches: + self._postprocess_artist(patch, ax, orient) + ax.add_patch(patch) + + def _standardize_coordinate_parameters(self, data, orient): + return data + + def _postprocess_artist(self, artist, ax, orient): + pass + + def _get_verts(self, data, orient): + + dv = {"x": "y", "y": "x"}[orient] + data = data.sort_values(orient, kind="mergesort") + verts = np.concatenate([ + data[[orient, f"{dv}min"]].to_numpy(), + data[[orient, f"{dv}max"]].to_numpy()[::-1], + ]) + if orient == "y": + verts = verts[:, ::-1] + return verts + + def _legend_artist(self, variables, value, scales): + + keys = {v: value for v in variables} + resolved = resolve_properties(self, keys, scales) + + fc = resolve_color(self, keys, "", scales) + if not resolved["fill"]: + fc = mpl.colors.to_rgba(fc, 0) + + return mpl.patches.Patch( + facecolor=fc, + edgecolor=resolve_color(self, keys, "edge", scales), + linewidth=resolved["edgewidth"], + linestyle=resolved["edgestyle"], + **self.artist_kws, + ) + + +@document_properties +@dataclass +class Area(AreaBase, Mark): + """ + A fill mark drawn from a baseline to data values. + + See also + -------- + Band : A fill mark representing an interval between values. + + Examples + -------- + .. include:: ../docstrings/objects.Area.rst + + """ + color: MappableColor = Mappable("C0", ) + alpha: MappableFloat = Mappable(.2, ) + fill: MappableBool = Mappable(True, ) + edgecolor: MappableColor = Mappable(depend="color") + edgealpha: MappableFloat = Mappable(1, ) + edgewidth: MappableFloat = Mappable(rc="patch.linewidth", ) + edgestyle: MappableStyle = Mappable("-", ) + + # TODO should this be settable / mappable? + baseline: MappableFloat = Mappable(0, grouping=False) + + def _standardize_coordinate_parameters(self, data, orient): + dv = {"x": "y", "y": "x"}[orient] + return data.rename(columns={"baseline": f"{dv}min", dv: f"{dv}max"}) + + def _postprocess_artist(self, artist, ax, orient): + + # TODO copying a lot of code from Bar, let's abstract this + # See comments there, I am not going to repeat them too + + artist.set_linewidth(artist.get_linewidth() * 2) + + linestyle = artist.get_linestyle() + if linestyle[1]: + linestyle = (linestyle[0], tuple(x / 2 for x in linestyle[1])) + artist.set_linestyle(linestyle) + + artist.set_clip_path(artist.get_path(), artist.get_transform() + ax.transData) + if self.artist_kws.get("clip_on", True): + artist.set_clip_box(ax.bbox) + + val_idx = ["y", "x"].index(orient) + artist.sticky_edges[val_idx][:] = (0, np.inf) + + +@document_properties +@dataclass +class Band(AreaBase, Mark): + """ + A fill mark representing an interval between values. + + See also + -------- + Area : A fill mark drawn from a baseline to data values. + + Examples + -------- + .. include:: ../docstrings/objects.Band.rst + + """ + color: MappableColor = Mappable("C0", ) + alpha: MappableFloat = Mappable(.2, ) + fill: MappableBool = Mappable(True, ) + edgecolor: MappableColor = Mappable(depend="color", ) + edgealpha: MappableFloat = Mappable(1, ) + edgewidth: MappableFloat = Mappable(0, ) + edgestyle: MappableFloat = Mappable("-", ) + + def _standardize_coordinate_parameters(self, data, orient): + # dv = {"x": "y", "y": "x"}[orient] + # TODO assert that all(ymax >= ymin)? + # TODO what if only one exist? + other = {"x": "y", "y": "x"}[orient] + if not set(data.columns) & {f"{other}min", f"{other}max"}: + agg = {f"{other}min": (other, "min"), f"{other}max": (other, "max")} + data = data.groupby(orient).agg(**agg).reset_index() + return data diff --git a/shared/package-files/28/2838e525392dd6c75caf01a02e43cc6654b0cf50e9d1792de8fa849ea70b6566/errno.pyi b/shared/package-files/28/2838e525392dd6c75caf01a02e43cc6654b0cf50e9d1792de8fa849ea70b6566/errno.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b053604fc33a385fc081afca2da4cdae8bc082a0 --- /dev/null +++ b/shared/package-files/28/2838e525392dd6c75caf01a02e43cc6654b0cf50e9d1792de8fa849ea70b6566/errno.pyi @@ -0,0 +1,137 @@ +from typing import Mapping + +errorcode: Mapping[int, str] + +EPERM: int +ENOENT: int +ESRCH: int +EINTR: int +EIO: int +ENXIO: int +E2BIG: int +ENOEXEC: int +EBADF: int +ECHILD: int +EAGAIN: int +ENOMEM: int +EACCES: int +EFAULT: int +ENOTBLK: int +EBUSY: int +EEXIST: int +EXDEV: int +ENODEV: int +ENOTDIR: int +EISDIR: int +EINVAL: int +ENFILE: int +EMFILE: int +ENOTTY: int +ETXTBSY: int +EFBIG: int +ENOSPC: int +ESPIPE: int +EROFS: int +EMLINK: int +EPIPE: int +EDOM: int +ERANGE: int +EDEADLCK: int +ENAMETOOLONG: int +ENOLCK: int +ENOSYS: int +ENOTEMPTY: int +ELOOP: int +EWOULDBLOCK: int +ENOMSG: int +EIDRM: int +ECHRNG: int +EL2NSYNC: int +EL3HLT: int +EL3RST: int +ELNRNG: int +EUNATCH: int +ENOCSI: int +EL2HLT: int +EBADE: int +EBADR: int +EXFULL: int +ENOANO: int +EBADRQC: int +EBADSLT: int +EDEADLOCK: int +EBFONT: int +ENOSTR: int +ENODATA: int +ETIME: int +ENOSR: int +ENONET: int +ENOPKG: int +EREMOTE: int +ENOLINK: int +EADV: int +ESRMNT: int +ECOMM: int +EPROTO: int +EMULTIHOP: int +EDOTDOT: int +EBADMSG: int +EOVERFLOW: int +ENOTUNIQ: int +EBADFD: int +EREMCHG: int +ELIBACC: int +ELIBBAD: int +ELIBSCN: int +ELIBMAX: int +ELIBEXEC: int +EILSEQ: int +ERESTART: int +ESTRPIPE: int +EUSERS: int +ENOTSOCK: int +EDESTADDRREQ: int +EMSGSIZE: int +EPROTOTYPE: int +ENOPROTOOPT: int +EPROTONOSUPPORT: int +ESOCKTNOSUPPORT: int +ENOTSUP: int +EOPNOTSUPP: int +EPFNOSUPPORT: int +EAFNOSUPPORT: int +EADDRINUSE: int +EADDRNOTAVAIL: int +ENETDOWN: int +ENETUNREACH: int +ENETRESET: int +ECONNABORTED: int +ECONNRESET: int +ENOBUFS: int +EISCONN: int +ENOTCONN: int +ESHUTDOWN: int +ETOOMANYREFS: int +ETIMEDOUT: int +ECONNREFUSED: int +EHOSTDOWN: int +EHOSTUNREACH: int +EALREADY: int +EINPROGRESS: int +ESTALE: int +EUCLEAN: int +ENOTNAM: int +ENAVAIL: int +EISNAM: int +EREMOTEIO: int +EDQUOT: int +ECANCELED: int # undocumented +EKEYEXPIRED: int # undocumented +EKEYREJECTED: int # undocumented +EKEYREVOKED: int # undocumented +EMEDIUMTYPE: int # undocumented +ENOKEY: int # undocumented +ENOMEDIUM: int # undocumented +ENOTRECOVERABLE: int # undocumented +EOWNERDEAD: int # undocumented +ERFKILL: int # undocumented diff --git a/shared/package-files/28/2839df90d3949e6dc5d77c03fe3dd83413af61a759e3419fff4d7bd21164269d/D__e_b_g.py b/shared/package-files/28/2839df90d3949e6dc5d77c03fe3dd83413af61a759e3419fff4d7bd21164269d/D__e_b_g.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1653d79d4f99ad729b25c96346459c40a4681e --- /dev/null +++ b/shared/package-files/28/2839df90d3949e6dc5d77c03fe3dd83413af61a759e3419fff4d7bd21164269d/D__e_b_g.py @@ -0,0 +1,35 @@ +import json +from textwrap import indent + +from . import DefaultTable +from fontTools.misc.textTools import tostr + + +class table_D__e_b_g(DefaultTable.DefaultTable): + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.data = {} + + def decompile(self, data, ttFont): + self.data = json.loads(data) + + def compile(self, ttFont): + return json.dumps(self.data).encode("utf-8") + + def toXML(self, writer, ttFont): + # make sure json indentation inside CDATA block matches XMLWriter's + data = json.dumps(self.data, indent=len(writer.indentwhite)) + prefix = tostr(writer.indentwhite) * (writer.indentlevel + 1) + # but don't indent the first json line so it's adjacent to ` +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::cartesian_prod(Tensor[] tensors) -> Tensor +inline at::Tensor cartesian_prod(at::TensorList tensors) { + return at::_ops::cartesian_prod::call(tensors); +} + +} diff --git a/shared/package-files/28/283dbaa1348586509558ecc7da3ce8031d4eaa19dcc7969251deb249ddea4743/helpers.pyi b/shared/package-files/28/283dbaa1348586509558ecc7da3ce8031d4eaa19dcc7969251deb249ddea4743/helpers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..32d14338e7ace7927b2f8399bc9a8ec5549e1f15 --- /dev/null +++ b/shared/package-files/28/283dbaa1348586509558ecc7da3ce8031d4eaa19dcc7969251deb249ddea4743/helpers.pyi @@ -0,0 +1,155 @@ +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union, Iterable + +from django.forms.boundfield import BoundField +from django.forms.forms import BaseForm +from django.forms.utils import ErrorDict +from django.forms.widgets import Media, Widget +from django.utils.safestring import SafeText + +from django import forms +from django.db.models.fields import AutoField + +ACTION_CHECKBOX_NAME: str + +class ActionForm(forms.Form): + action: Any = ... + select_across: Any = ... + +checkbox: Any + +class AdminForm: + prepopulated_fields: Any = ... + model_admin: Any = ... + readonly_fields: Any = ... + def __init__( + self, + form: BaseForm, + fieldsets: List[Tuple[None, Dict[str, List[str]]]], + prepopulated_fields: Dict[Any, Any], + readonly_fields: Optional[Iterable[Any]] = ..., + model_admin: Any = ..., + ) -> None: ... + def __iter__(self) -> Iterator[Fieldset]: ... + @property + def errors(self) -> ErrorDict: ... + @property + def non_field_errors(self) -> Callable: ... + @property + def media(self) -> Media: ... + +class Fieldset: + form: Any = ... + classes: Any = ... + description: Any = ... + model_admin: Any = ... + readonly_fields: Any = ... + def __init__( + self, + form: Any, + name: Optional[Any] = ..., + readonly_fields: Optional[Iterable[Any]] = ..., + fields: Any = ..., + classes: Any = ..., + description: Optional[Any] = ..., + model_admin: Optional[Any] = ..., + ) -> None: ... + @property + def media(self) -> Media: ... + def __iter__(self) -> Iterator[Fieldline]: ... + +class Fieldline: + form: Any = ... + fields: Any = ... + has_visible_field: Any = ... + model_admin: Any = ... + readonly_fields: Any = ... + def __init__( + self, form: Any, field: Any, readonly_fields: Optional[Iterable[Any]] = ..., model_admin: Optional[Any] = ... + ) -> None: ... + def __iter__(self) -> Iterator[Union[AdminField, AdminReadonlyField]]: ... + def errors(self) -> SafeText: ... + +class AdminField: + field: BoundField = ... + is_first: bool = ... + is_checkbox: bool = ... + is_readonly: bool = ... + def __init__(self, form: Any, field: Any, is_first: Any) -> None: ... + def label_tag(self) -> SafeText: ... + def errors(self) -> SafeText: ... + +class AdminReadonlyField: + field: Any = ... + form: Any = ... + model_admin: Any = ... + is_first: Any = ... + is_checkbox: bool = ... + is_readonly: bool = ... + empty_value_display: Any = ... + def __init__(self, form: Any, field: Any, is_first: Any, model_admin: Optional[Any] = ...) -> None: ... + def label_tag(self) -> SafeText: ... + def contents(self) -> SafeText: ... + +class InlineAdminFormSet: + opts: Any = ... + formset: Any = ... + fieldsets: Any = ... + model_admin: Any = ... + readonly_fields: Any = ... + prepopulated_fields: Any = ... + classes: Any = ... + has_add_permission: Any = ... + has_change_permission: Any = ... + has_delete_permission: Any = ... + has_view_permission: Any = ... + def __init__( + self, + inline: Any, + formset: Any, + fieldsets: Any, + prepopulated_fields: Optional[Any] = ..., + readonly_fields: Optional[Any] = ..., + model_admin: Optional[Any] = ..., + has_add_permission: bool = ..., + has_change_permission: bool = ..., + has_delete_permission: bool = ..., + has_view_permission: bool = ..., + ) -> None: ... + def __iter__(self) -> Iterator[InlineAdminForm]: ... + def fields(self) -> Iterator[Dict[str, Union[Dict[str, bool], bool, Widget, str]]]: ... + def inline_formset_data(self) -> str: ... + @property + def forms(self): ... + @property + def non_form_errors(self) -> Callable: ... + @property + def media(self) -> Media: ... + +class InlineAdminForm(AdminForm): + formset: Any = ... + original: Any = ... + show_url: Any = ... + absolute_url: Any = ... + def __init__( + self, + formset: Any, + form: Any, + fieldsets: Any, + prepopulated_fields: Any, + original: Any, + readonly_fields: Optional[Any] = ..., + model_admin: Optional[Any] = ..., + view_on_site_url: Optional[Any] = ..., + ) -> None: ... + def needs_explicit_pk_field(self) -> Union[bool, AutoField]: ... + def pk_field(self) -> AdminField: ... + def fk_field(self) -> AdminField: ... + def deletion_field(self) -> AdminField: ... + def ordering_field(self): ... + +class InlineFieldset(Fieldset): + formset: Any = ... + def __init__(self, formset: Any, *args: Any, **kwargs: Any) -> None: ... + +class AdminErrorList(forms.utils.ErrorList): + def __init__(self, form: Any, inline_formsets: Any) -> None: ... diff --git a/shared/package-files/28/2841539710984ea3af03e543c78c146fc1ba1da603e476dfe462a63d9c2cb02b/color_depth.py b/shared/package-files/28/2841539710984ea3af03e543c78c146fc1ba1da603e476dfe462a63d9c2cb02b/color_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..f66d2bea301da9963918c28ba5ee277b755ceb5e --- /dev/null +++ b/shared/package-files/28/2841539710984ea3af03e543c78c146fc1ba1da603e476dfe462a63d9c2cb02b/color_depth.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import os +from enum import Enum + +__all__ = [ + "ColorDepth", +] + + +class ColorDepth(str, Enum): + """ + Possible color depth values for the output. + """ + + value: str + + #: One color only. + DEPTH_1_BIT = "DEPTH_1_BIT" + + #: ANSI Colors. + DEPTH_4_BIT = "DEPTH_4_BIT" + + #: The default. + DEPTH_8_BIT = "DEPTH_8_BIT" + + #: 24 bit True color. + DEPTH_24_BIT = "DEPTH_24_BIT" + + # Aliases. + MONOCHROME = DEPTH_1_BIT + ANSI_COLORS_ONLY = DEPTH_4_BIT + DEFAULT = DEPTH_8_BIT + TRUE_COLOR = DEPTH_24_BIT + + @classmethod + def from_env(cls) -> ColorDepth | None: + """ + Return the color depth if the $PROMPT_TOOLKIT_COLOR_DEPTH environment + variable has been set. + + This is a way to enforce a certain color depth in all prompt_toolkit + applications. + """ + # Disable color if a `NO_COLOR` environment variable is set. + # See: https://no-color.org/ + if os.environ.get("NO_COLOR"): + return cls.DEPTH_1_BIT + + # Check the `PROMPT_TOOLKIT_COLOR_DEPTH` environment variable. + all_values = [i.value for i in ColorDepth] + if os.environ.get("PROMPT_TOOLKIT_COLOR_DEPTH") in all_values: + return cls(os.environ["PROMPT_TOOLKIT_COLOR_DEPTH"]) + + return None + + @classmethod + def default(cls) -> ColorDepth: + """ + Return the default color depth for the default output. + """ + from .defaults import create_output + + return create_output().get_default_color_depth() diff --git a/shared/package-files/28/284178f3364b9f74d250299df2d85da380f362f279cda08aeb48585fa9f3c992/algos.pyi b/shared/package-files/28/284178f3364b9f74d250299df2d85da380f362f279cda08aeb48585fa9f3c992/algos.pyi new file mode 100644 index 0000000000000000000000000000000000000000..caf5425dfc7b44cbb2fea103e56d4584709eca1e --- /dev/null +++ b/shared/package-files/28/284178f3364b9f74d250299df2d85da380f362f279cda08aeb48585fa9f3c992/algos.pyi @@ -0,0 +1,416 @@ +from typing import Any + +import numpy as np + +from pandas._typing import npt + +class Infinity: + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __lt__(self, other) -> bool: ... + def __le__(self, other) -> bool: ... + def __gt__(self, other) -> bool: ... + def __ge__(self, other) -> bool: ... + +class NegInfinity: + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __lt__(self, other) -> bool: ... + def __le__(self, other) -> bool: ... + def __gt__(self, other) -> bool: ... + def __ge__(self, other) -> bool: ... + +def unique_deltas( + arr: np.ndarray, # const int64_t[:] +) -> np.ndarray: ... # np.ndarray[np.int64, ndim=1] +def is_lexsorted(list_of_arrays: list[npt.NDArray[np.int64]]) -> bool: ... +def groupsort_indexer( + index: np.ndarray, # const int64_t[:] + ngroups: int, +) -> tuple[ + np.ndarray, # ndarray[int64_t, ndim=1] + np.ndarray, # ndarray[int64_t, ndim=1] +]: ... +def kth_smallest( + arr: np.ndarray, # numeric[:] + k: int, +) -> Any: ... # numeric + +# ---------------------------------------------------------------------- +# Pairwise correlation/covariance + +def nancorr( + mat: npt.NDArray[np.float64], # const float64_t[:, :] + cov: bool = ..., + minp: int | None = ..., +) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2] +def nancorr_spearman( + mat: npt.NDArray[np.float64], # ndarray[float64_t, ndim=2] + minp: int = ..., +) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2] + +# ---------------------------------------------------------------------- + +def validate_limit(nobs: int | None, limit=...) -> int: ... +def get_fill_indexer( + mask: npt.NDArray[np.bool_], + limit: int | None = None, +) -> npt.NDArray[np.intp]: ... +def pad( + old: np.ndarray, # ndarray[numeric_object_t] + new: np.ndarray, # ndarray[numeric_object_t] + limit=..., +) -> npt.NDArray[np.intp]: ... # np.ndarray[np.intp, ndim=1] +def pad_inplace( + values: np.ndarray, # numeric_object_t[:] + mask: np.ndarray, # uint8_t[:] + limit=..., +) -> None: ... +def pad_2d_inplace( + values: np.ndarray, # numeric_object_t[:, :] + mask: np.ndarray, # const uint8_t[:, :] + limit=..., +) -> None: ... +def backfill( + old: np.ndarray, # ndarray[numeric_object_t] + new: np.ndarray, # ndarray[numeric_object_t] + limit=..., +) -> npt.NDArray[np.intp]: ... # np.ndarray[np.intp, ndim=1] +def backfill_inplace( + values: np.ndarray, # numeric_object_t[:] + mask: np.ndarray, # uint8_t[:] + limit=..., +) -> None: ... +def backfill_2d_inplace( + values: np.ndarray, # numeric_object_t[:, :] + mask: np.ndarray, # const uint8_t[:, :] + limit=..., +) -> None: ... +def is_monotonic( + arr: np.ndarray, # ndarray[numeric_object_t, ndim=1] + timelike: bool, +) -> tuple[bool, bool, bool]: ... + +# ---------------------------------------------------------------------- +# rank_1d, rank_2d +# ---------------------------------------------------------------------- + +def rank_1d( + values: np.ndarray, # ndarray[numeric_object_t, ndim=1] + labels: np.ndarray | None = ..., # const int64_t[:]=None + is_datetimelike: bool = ..., + ties_method=..., + ascending: bool = ..., + pct: bool = ..., + na_option=..., + mask: npt.NDArray[np.bool_] | None = ..., +) -> np.ndarray: ... # np.ndarray[float64_t, ndim=1] +def rank_2d( + in_arr: np.ndarray, # ndarray[numeric_object_t, ndim=2] + axis: int = ..., + is_datetimelike: bool = ..., + ties_method=..., + ascending: bool = ..., + na_option=..., + pct: bool = ..., +) -> np.ndarray: ... # np.ndarray[float64_t, ndim=1] +def diff_2d( + arr: np.ndarray, # ndarray[diff_t, ndim=2] + out: np.ndarray, # ndarray[out_t, ndim=2] + periods: int, + axis: int, + datetimelike: bool = ..., +) -> None: ... +def ensure_platform_int(arr: object) -> npt.NDArray[np.intp]: ... +def ensure_object(arr: object) -> npt.NDArray[np.object_]: ... +def ensure_float64(arr: object) -> npt.NDArray[np.float64]: ... +def ensure_int8(arr: object) -> npt.NDArray[np.int8]: ... +def ensure_int16(arr: object) -> npt.NDArray[np.int16]: ... +def ensure_int32(arr: object) -> npt.NDArray[np.int32]: ... +def ensure_int64(arr: object) -> npt.NDArray[np.int64]: ... +def ensure_uint64(arr: object) -> npt.NDArray[np.uint64]: ... +def take_1d_int8_int8( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int8_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int8_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int8_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int16_int16( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int16_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int16_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int16_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int32_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int32_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int32_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int64_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_int64_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_float32_float32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_float32_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_float64_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_object_object( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_bool_bool( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_1d_bool_object( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int8_int8( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int8_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int8_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int8_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int16_int16( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int16_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int16_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int16_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int32_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int32_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int32_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int64_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_int64_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_float32_float32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_float32_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_float64_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_object_object( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_bool_bool( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis0_bool_object( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int8_int8( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int8_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int8_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int8_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int16_int16( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int16_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int16_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int16_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int32_int32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int32_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int32_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int64_int64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_int64_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_float32_float32( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_float32_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_float64_float64( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_object_object( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_bool_bool( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_axis1_bool_object( + values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=... +) -> None: ... +def take_2d_multi_int8_int8( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int8_int32( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int8_int64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int8_float64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int16_int16( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int16_int32( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int16_int64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int16_float64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int32_int32( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int32_int64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int32_float64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int64_float64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_float32_float32( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_float32_float64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_float64_float64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_object_object( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_bool_bool( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_bool_object( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... +def take_2d_multi_int64_int64( + values: np.ndarray, + indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], + out: np.ndarray, + fill_value=..., +) -> None: ... diff --git a/shared/package-files/28/2844272f45bbee27bf8656678030366e33ed73fc9f6a8a61e2abe28f056ba502/_masked_scale_compositeexplicitautograd_dispatch.h b/shared/package-files/28/2844272f45bbee27bf8656678030366e33ed73fc9f6a8a61e2abe28f056ba502/_masked_scale_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c6370180e6de0d79865cd7782f387e710164a82a --- /dev/null +++ b/shared/package-files/28/2844272f45bbee27bf8656678030366e33ed73fc9f6a8a61e2abe28f056ba502/_masked_scale_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 & _masked_scale_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mask, double scale); +TORCH_API at::Tensor & _masked_scale_outf(const at::Tensor & self, const at::Tensor & mask, double scale, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/28/284852d5c31a05b7f853447428c457665f8270290f7cdab1a55cfc053b5bd336/_test_decorators.py b/shared/package-files/28/284852d5c31a05b7f853447428c457665f8270290f7cdab1a55cfc053b5bd336/_test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..2c1912bce856dd2694447d820ea2c5124be9c1a0 --- /dev/null +++ b/shared/package-files/28/284852d5c31a05b7f853447428c457665f8270290f7cdab1a55cfc053b5bd336/_test_decorators.py @@ -0,0 +1,173 @@ +""" +This module provides decorator functions which can be applied to test objects +in order to skip those objects when certain conditions occur. A sample use case +is to detect if the platform is missing ``matplotlib``. If so, any test objects +which require ``matplotlib`` and decorated with ``@td.skip_if_no("matplotlib")`` +will be skipped by ``pytest`` during the execution of the test suite. + +To illustrate, after importing this module: + +import pandas.util._test_decorators as td + +The decorators can be applied to classes: + +@td.skip_if_no("package") +class Foo: + ... + +Or individual functions: + +@td.skip_if_no("package") +def test_foo(): + ... + +For more information, refer to the ``pytest`` documentation on ``skipif``. +""" +from __future__ import annotations + +import locale +from typing import ( + TYPE_CHECKING, + Callable, +) + +import pytest + +from pandas._config import get_option + +if TYPE_CHECKING: + from pandas._typing import F + +from pandas._config.config import _get_option + +from pandas.compat import ( + IS64, + is_platform_windows, +) +from pandas.compat._optional import import_optional_dependency + + +def skip_if_installed(package: str) -> pytest.MarkDecorator: + """ + Skip a test if a package is installed. + + Parameters + ---------- + package : str + The name of the package. + + Returns + ------- + pytest.MarkDecorator + a pytest.mark.skipif to use as either a test decorator or a + parametrization mark. + """ + return pytest.mark.skipif( + bool(import_optional_dependency(package, errors="ignore")), + reason=f"Skipping because {package} is installed.", + ) + + +def skip_if_no(package: str, min_version: str | None = None) -> pytest.MarkDecorator: + """ + Generic function to help skip tests when required packages are not + present on the testing system. + + This function returns a pytest mark with a skip condition that will be + evaluated during test collection. An attempt will be made to import the + specified ``package`` and optionally ensure it meets the ``min_version`` + + The mark can be used as either a decorator for a test class or to be + applied to parameters in pytest.mark.parametrize calls or parametrized + fixtures. Use pytest.importorskip if an imported moduled is later needed + or for test functions. + + If the import and version check are unsuccessful, then the test function + (or test case when used in conjunction with parametrization) will be + skipped. + + Parameters + ---------- + package: str + The name of the required package. + min_version: str or None, default None + Optional minimum version of the package. + + Returns + ------- + pytest.MarkDecorator + a pytest.mark.skipif to use as either a test decorator or a + parametrization mark. + """ + msg = f"Could not import '{package}'" + if min_version: + msg += f" satisfying a min_version of {min_version}" + return pytest.mark.skipif( + not bool( + import_optional_dependency( + package, errors="ignore", min_version=min_version + ) + ), + reason=msg, + ) + + +skip_if_32bit = pytest.mark.skipif(not IS64, reason="skipping for 32 bit") +skip_if_windows = pytest.mark.skipif(is_platform_windows(), reason="Running on Windows") +skip_if_not_us_locale = pytest.mark.skipif( + locale.getlocale()[0] != "en_US", + reason=f"Set local {locale.getlocale()[0]} is not en_US", +) + + +def parametrize_fixture_doc(*args) -> Callable[[F], F]: + """ + Intended for use as a decorator for parametrized fixture, + this function will wrap the decorated function with a pytest + ``parametrize_fixture_doc`` mark. That mark will format + initial fixture docstring by replacing placeholders {0}, {1} etc + with parameters passed as arguments. + + Parameters + ---------- + args: iterable + Positional arguments for docstring. + + Returns + ------- + function + The decorated function wrapped within a pytest + ``parametrize_fixture_doc`` mark + """ + + def documented_fixture(fixture): + fixture.__doc__ = fixture.__doc__.format(*args) + return fixture + + return documented_fixture + + +def mark_array_manager_not_yet_implemented(request) -> None: + mark = pytest.mark.xfail(reason="Not yet implemented for ArrayManager") + request.applymarker(mark) + + +skip_array_manager_not_yet_implemented = pytest.mark.xfail( + _get_option("mode.data_manager", silent=True) == "array", + reason="Not yet implemented for ArrayManager", +) + +skip_array_manager_invalid_test = pytest.mark.skipif( + _get_option("mode.data_manager", silent=True) == "array", + reason="Test that relies on BlockManager internals or specific behaviour", +) + +skip_copy_on_write_not_yet_implemented = pytest.mark.xfail( + get_option("mode.copy_on_write") is True, + reason="Not yet implemented/adapted for Copy-on-Write mode", +) + +skip_copy_on_write_invalid_test = pytest.mark.skipif( + get_option("mode.copy_on_write") is True, + reason="Test not valid for Copy-on-Write mode", +) diff --git a/shared/package-files/28/2848c9c18f61ec78619855d9081e933902c0c3ff303c8e99bb98db8b5ce3fbf1/test_gof.py b/shared/package-files/28/2848c9c18f61ec78619855d9081e933902c0c3ff303c8e99bb98db8b5ce3fbf1/test_gof.py new file mode 100644 index 0000000000000000000000000000000000000000..80ef6d208a49daf77605a569c8e5b0106e0930d3 --- /dev/null +++ b/shared/package-files/28/2848c9c18f61ec78619855d9081e933902c0c3ff303c8e99bb98db8b5ce3fbf1/test_gof.py @@ -0,0 +1,180 @@ +""" + +Created on Thu Feb 28 13:24:59 2013 + +Author: Josef Perktold +""" +import numpy as np +from numpy.testing import assert_allclose, assert_almost_equal, assert_equal +import pytest +from scipy import stats + +from statsmodels.stats.gof import ( + chisquare, + chisquare_effectsize, + chisquare_power, + gof_binning_discrete, + gof_chisquare_discrete, + powerdiscrepancy, +) +from statsmodels.tools.testing import Holder + + +def test_powerdiscrepancy_lambd_aliases(): + observed = np.array([2.0, 4.0, 2.0, 1.0, 1.0]) + expected = np.array([0.2, 0.2, 0.2, 0.2, 0.2]) + + lambd_and_a = [ + ("loglikeratio", 0), + ("freeman_tukey", -0.5), + ("pearson", 1), + ("modified_loglikeratio", -1), + ("cressie_read", 2 / 3.0), + ] + for lambd, a in lambd_and_a: + d_str, p_str = powerdiscrepancy(observed, expected, lambd=lambd) + d_num, p_num = powerdiscrepancy(observed, expected, lambd=a) + assert_almost_equal(d_str, d_num, decimal=13) + assert_almost_equal(p_str, p_num, decimal=13) + + with pytest.raises(ValueError, match="lambd"): + powerdiscrepancy(observed, expected, lambd="not-a-lambd") + + +def test_gof_binning_discrete_bernoulli(): + # With nsupp=20 and a 2-point support, each mass (0.7, 0.3) already + # exceeds the minimum bin mass 1/20, so the algorithm's bins align + # exactly with the distribution's support: bin 0 catches rvs==0 and + # bin 1 catches rvs==1. This lets freq/expfreq be hand-verified + # directly from the sample and from the Bernoulli pmf, independently + # of the general binning algorithm. + rng = np.random.default_rng(12345) + p = 0.3 + n = 500 + rvs = (rng.random(n) < p).astype(int) + distfn = stats.bernoulli + arg = (p,) + + freq, expfreq, histsupp = gof_binning_discrete(rvs, distfn, arg, nsupp=20) + + assert_equal(freq, np.array([(rvs == 0).sum(), (rvs == 1).sum()])) + assert_allclose(expfreq, n * np.array([1 - p, p])) + assert freq.sum() == n + assert_allclose(histsupp, np.array([0.0, 1e-8, 1 + 1e-8])) + + +def test_gof_chisquare_discrete_bernoulli(): + # gof_chisquare_discrete duplicates gof_binning_discrete's binning + # internally (see the module docstring/comments) and then calls + # scipy.stats.chisquare on the result; check its output against doing + # exactly that using the independently-verified binning above. + rng = np.random.default_rng(12345) + p = 0.3 + n = 500 + rvs = (rng.random(n) < p).astype(int) + distfn = stats.bernoulli + arg = (p,) + alpha = 0.05 + + chis, pval, truefalse, outstr = gof_chisquare_discrete( + distfn, arg, rvs, alpha, "bernoulli test" + ) + + freq, expfreq, _ = gof_binning_discrete(rvs, distfn, arg, nsupp=20) + chis_expected, pval_expected = stats.chisquare(freq, expfreq) + + assert_almost_equal(chis, chis_expected, decimal=12) + assert_almost_equal(pval, pval_expected, decimal=12) + assert truefalse == (pval_expected > alpha) + assert "bernoulli test" in outstr + assert str(arg) in outstr + assert str(pval) in outstr + + +def test_chisquare_power(): + from .results.results_power import pwr_chisquare + for case in pwr_chisquare.values(): + power = chisquare_power(case.w, case.N, case.df + 1, + alpha=case.sig_level) + assert_almost_equal(power, case.power, decimal=6, + err_msg=repr(vars(case))) + + +def test_chisquare(): + # TODO: no tests for ``value`` yet + res1 = Holder() + res2 = Holder() + # > freq = c(1048, 660, 510, 420, 362) + # > pr1 = c(1020, 690, 510, 420, 360) + # > pr2 = c(1050, 660, 510, 420, 360) + # > c = chisq.test(freq, p=pr1, rescale.p = TRUE) + # > cat_items(c, "res1.") + res1.statistic = 2.084086388178453 + res1.parameter = 4 + res1.p_value = 0.72029651761105 + res1.method = "Chi-squared test for given probabilities" + res1.data_name = "freq" + res1.observed = np.array([ + 1048, 660, 510, 420, 362 + ]) + res1.expected = np.array([ + 1020, 690, 510, 420, 360 + ]) + res1.residuals = np.array([ + 0.876714007519206, -1.142080481440321, -2.517068894406109e-15, + -2.773674830645328e-15, 0.105409255338946 + ]) + + # > c = chisq.test(freq, p=pr2, rescale.p = TRUE) + # > cat_items(c, "res2.") + res2.statistic = 0.01492063492063492 + res2.parameter = 4 + res2.p_value = 0.999972309849908 + res2.method = "Chi-squared test for given probabilities" + res2.data_name = "freq" + res2.observed = np.array([ + 1048, 660, 510, 420, 362 + ]) + res2.expected = np.array([ + 1050, 660, 510, 420, 360 + ]) + res2.residuals = np.array([ + -0.06172133998483677, 0, -2.517068894406109e-15, + -2.773674830645328e-15, 0.105409255338946 + ]) + + freq = np.array([1048, 660, 510, 420, 362]) + pr1 = np.array([1020, 690, 510, 420, 360]) + pr2 = np.array([1050, 660, 510, 420, 360]) + + for pr, res in zip([pr1, pr2], [res1, res2], strict=True): + stat, pval = chisquare(freq, pr) + assert_almost_equal(stat, res.statistic, decimal=12) + assert_almost_equal(pval, res.p_value, decimal=13) + + +def test_chisquare_effectsize(): + + pr1 = np.array([1020, 690, 510, 420, 360]) + pr2 = np.array([1050, 660, 510, 420, 360]) + # > library(pwr) + # > ES.w1(pr1/3000, pr2/3000) + es_r = 0.02699815282115563 + es1 = chisquare_effectsize(pr1, pr2) + es2 = chisquare_effectsize(pr1, pr2, cohen=False) + assert_almost_equal(es1, es_r, decimal=14) + assert_almost_equal(es2, es_r**2, decimal=14) + + # regression tests for correction + res1 = chisquare_effectsize(pr1, pr2, cohen=False, + correction=(3000, len(pr1)-1)) + res0 = 0 # -0.00059994422693327625 + assert_equal(res1, res0) + pr3 = pr2 + [0, 0, 0, 50, 50] + res1 = chisquare_effectsize(pr1, pr3, cohen=False, + correction=(3000, len(pr1)-1)) + res0 = 0.0023106468846296755 + assert_almost_equal(res1, res0, decimal=14) + # compare + # res_nc = chisquare_effectsize(pr1, pr3, cohen=False) + # 0.0036681143072077533 diff --git a/shared/package-files/28/28494d8b61a5242b462e13697fcae5f1b90384c710f62b6dc9176c5f8add4b1a/test_lines.py b/shared/package-files/28/28494d8b61a5242b462e13697fcae5f1b90384c710f62b6dc9176c5f8add4b1a/test_lines.py new file mode 100644 index 0000000000000000000000000000000000000000..81252198cd8f56242e41cccfbc8a34bbe3f9c4cf --- /dev/null +++ b/shared/package-files/28/28494d8b61a5242b462e13697fcae5f1b90384c710f62b6dc9176c5f8add4b1a/test_lines.py @@ -0,0 +1,452 @@ +""" +Tests specific to the lines module. +""" + +import itertools +import platform +import timeit +from types import SimpleNamespace + +from cycler import cycler +import numpy as np +from numpy.testing import assert_array_equal +import pytest + +import matplotlib +import matplotlib as mpl +from matplotlib import _path +import matplotlib.lines as mlines +from matplotlib.markers import MarkerStyle +from matplotlib.path import Path +import matplotlib.pyplot as plt +import matplotlib.transforms as mtransforms +from matplotlib.testing.decorators import image_comparison, check_figures_equal + + +def test_segment_hits(): + """Test a problematic case.""" + cx, cy = 553, 902 + x, y = np.array([553., 553.]), np.array([95., 947.]) + radius = 6.94 + assert_array_equal(mlines.segment_hits(cx, cy, x, y, radius), [0]) + + +# Runtimes on a loaded system are inherently flaky. Not so much that a rerun +# won't help, hopefully. +@pytest.mark.flaky(reruns=3) +def test_invisible_Line_rendering(): + """ + GitHub issue #1256 identified a bug in Line.draw method + + Despite visibility attribute set to False, the draw method was not + returning early enough and some pre-rendering code was executed + though not necessary. + + Consequence was an excessive draw time for invisible Line instances + holding a large number of points (Npts> 10**6) + """ + # Creates big x and y data: + N = 10**7 + x = np.linspace(0, 1, N) + y = np.random.normal(size=N) + + # Create a plot figure: + fig = plt.figure() + ax = plt.subplot() + + # Create a "big" Line instance: + l = mlines.Line2D(x, y) + l.set_visible(False) + # but don't add it to the Axis instance `ax` + + # [here Interactive panning and zooming is pretty responsive] + # Time the canvas drawing: + t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3)) + # (gives about 25 ms) + + # Add the big invisible Line: + ax.add_line(l) + + # [Now interactive panning and zooming is very slow] + # Time the canvas drawing: + t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3)) + # gives about 290 ms for N = 10**7 pts + + slowdown_factor = t_invisible_line / t_no_line + slowdown_threshold = 2 # trying to avoid false positive failures + assert slowdown_factor < slowdown_threshold + + +def test_set_line_coll_dash(): + fig, ax = plt.subplots() + np.random.seed(0) + # Testing setting linestyles for line collections. + # This should not produce an error. + ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) + + +def test_invalid_line_data(): + with pytest.raises(RuntimeError, match='xdata must be'): + mlines.Line2D(0, []) + with pytest.raises(RuntimeError, match='ydata must be'): + mlines.Line2D([], 1) + + line = mlines.Line2D([], []) + with pytest.raises(RuntimeError, match='x must be'): + line.set_xdata(0) + with pytest.raises(RuntimeError, match='y must be'): + line.set_ydata(0) + + +@image_comparison(['line_dashes'], remove_text=True, tol=0.003) +def test_line_dashes(): + # Tolerance introduced after reordering of floating-point operations + # Remove when regenerating the images + fig, ax = plt.subplots() + + ax.plot(range(10), linestyle=(0, (3, 3)), lw=5) + + +def test_line_colors(): + fig, ax = plt.subplots() + ax.plot(range(10), color='none') + ax.plot(range(10), color='r') + ax.plot(range(10), color='.3') + ax.plot(range(10), color=(1, 0, 0, 1)) + ax.plot(range(10), color=(1, 0, 0)) + fig.canvas.draw() + + +def test_valid_colors(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_color("foobar") + + +def test_linestyle_variants(): + fig, ax = plt.subplots() + for ls in ["-", "solid", "--", "dashed", + "-.", "dashdot", ":", "dotted", + (0, None), (0, ()), (0, []), # gh-22930 + ]: + ax.plot(range(10), linestyle=ls) + fig.canvas.draw() + + +def test_valid_linestyles(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_linestyle('aardvark') + + +@image_comparison(['drawstyle_variants.png'], remove_text=True, + tol=0 if platform.machine() == 'x86_64' else 0.03) +def test_drawstyle_variants(): + fig, axs = plt.subplots(6) + dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None] + # We want to check that drawstyles are properly handled even for very long + # lines (for which the subslice optimization is on); however, we need + # to zoom in so that the difference between the drawstyles is actually + # visible. + for ax, ds in zip(axs.flat, dss): + ax.plot(range(2000), drawstyle=ds) + ax.set(xlim=(0, 2), ylim=(0, 2)) + + +@check_figures_equal(extensions=('png',)) +def test_no_subslice_with_transform(fig_ref, fig_test): + ax = fig_ref.add_subplot() + x = np.arange(2000) + ax.plot(x + 2000, x) + + ax = fig_test.add_subplot() + t = mtransforms.Affine2D().translate(2000.0, 0.0) + ax.plot(x, x, transform=t+ax.transData) + + +def test_valid_drawstyles(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_drawstyle('foobar') + + +def test_set_drawstyle(): + x = np.linspace(0, 2*np.pi, 10) + y = np.sin(x) + + fig, ax = plt.subplots() + line, = ax.plot(x, y) + line.set_drawstyle("steps-pre") + assert len(line.get_path().vertices) == 2*len(x)-1 + + line.set_drawstyle("default") + assert len(line.get_path().vertices) == len(x) + + +@image_comparison(['line_collection_dashes'], remove_text=True, style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.65) +def test_set_line_coll_dash_image(): + fig, ax = plt.subplots() + np.random.seed(0) + ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) + + +@image_comparison(['marker_fill_styles.png'], remove_text=True) +def test_marker_fill_styles(): + colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y', + np.array([0, 0, 0])]) + altcolor = 'lightgreen' + + y = np.array([1, 1]) + x = np.array([0, 9]) + fig, ax = plt.subplots() + + # This hard-coded list of markers correspond to an earlier iteration of + # MarkerStyle.filled_markers; the value of that attribute has changed but + # we kept the old value here to not regenerate the baseline image. + # Replace with mlines.Line2D.filled_markers when the image is regenerated. + for j, marker in enumerate("ov^<>8sp*hHDdPX"): + for i, fs in enumerate(mlines.Line2D.fillStyles): + color = next(colors) + ax.plot(j * 10 + x, y + i + .5 * (j % 2), + marker=marker, + markersize=20, + markerfacecoloralt=altcolor, + fillstyle=fs, + label=fs, + linewidth=5, + color=color, + markeredgecolor=color, + markeredgewidth=2) + + ax.set_ylim([0, 7.5]) + ax.set_xlim([-5, 155]) + + +def test_markerfacecolor_fillstyle(): + """Test that markerfacecolor does not override fillstyle='none'.""" + l, = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'), + markerfacecolor='red') + assert l.get_fillstyle() == 'none' + assert l.get_markerfacecolor() == 'none' + + +@image_comparison(['scaled_lines'], style='default') +def test_lw_scaling(): + th = np.linspace(0, 32) + fig, ax = plt.subplots() + lins_styles = ['dashed', 'dotted', 'dashdot'] + cy = cycler(matplotlib.rcParams['axes.prop_cycle']) + for j, (ls, sty) in enumerate(zip(lins_styles, cy)): + for lw in np.linspace(.5, 10, 10): + ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty) + + +def test_is_sorted_and_has_non_nan(): + assert _path.is_sorted_and_has_non_nan(np.array([1, 2, 3])) + assert _path.is_sorted_and_has_non_nan(np.array([1, np.nan, 3])) + assert not _path.is_sorted_and_has_non_nan([3, 5] + [np.nan] * 100 + [0, 2]) + # [2, 256] byteswapped: + assert not _path.is_sorted_and_has_non_nan(np.array([33554432, 65536], ">i4")) + n = 2 * mlines.Line2D._subslice_optim_min_size + plt.plot([np.nan] * n, range(n)) + + +@check_figures_equal(extensions=['png']) +def test_step_markers(fig_test, fig_ref): + fig_test.subplots().step([0, 1], "-o") + fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2]) + + +@pytest.mark.parametrize("parent", ["figure", "axes"]) +@check_figures_equal(extensions=('png',)) +def test_markevery(fig_test, fig_ref, parent): + np.random.seed(42) + x = np.linspace(0, 1, 14) + y = np.random.rand(len(x)) + + cases_test = [None, 4, (2, 5), [1, 5, 11], + [0, -1], slice(5, 10, 2), + np.arange(len(x))[y > 0.5], + 0.3, (0.3, 0.4)] + cases_ref = ["11111111111111", "10001000100010", "00100001000010", + "01000100000100", "10000000000001", "00000101010000", + "01110001110110", "11011011011110", "01010011011101"] + + if parent == "figure": + # float markevery ("relative to axes size") is not supported. + cases_test = cases_test[:-2] + cases_ref = cases_ref[:-2] + + def add_test(x, y, *, markevery): + fig_test.add_artist( + mlines.Line2D(x, y, marker="o", markevery=markevery)) + + def add_ref(x, y, *, markevery): + fig_ref.add_artist( + mlines.Line2D(x, y, marker="o", markevery=markevery)) + + elif parent == "axes": + axs_test = iter(fig_test.subplots(3, 3).flat) + axs_ref = iter(fig_ref.subplots(3, 3).flat) + + def add_test(x, y, *, markevery): + next(axs_test).plot(x, y, "-gD", markevery=markevery) + + def add_ref(x, y, *, markevery): + next(axs_ref).plot(x, y, "-gD", markevery=markevery) + + for case in cases_test: + add_test(x, y, markevery=case) + + for case in cases_ref: + me = np.array(list(case)).astype(int).astype(bool) + add_ref(x, y, markevery=me) + + +def test_markevery_figure_line_unsupported_relsize(): + fig = plt.figure() + fig.add_artist(mlines.Line2D([0, 1], [0, 1], marker="o", markevery=.5)) + with pytest.raises(ValueError): + fig.canvas.draw() + + +def test_marker_as_markerstyle(): + fig, ax = plt.subplots() + line, = ax.plot([2, 4, 3], marker=MarkerStyle("D")) + fig.canvas.draw() + assert line.get_marker() == "D" + + # continue with smoke tests: + line.set_marker("s") + fig.canvas.draw() + line.set_marker(MarkerStyle("o")) + fig.canvas.draw() + # test Path roundtrip + triangle1 = Path._create_closed([[-1, -1], [1, -1], [0, 2]]) + line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22) + line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22) + + assert_array_equal(line2.get_marker().vertices, triangle1.vertices) + assert_array_equal(line3.get_marker().vertices, triangle1.vertices) + + +@image_comparison(['striped_line.png'], remove_text=True, style='mpl20') +def test_striped_lines(): + rng = np.random.default_rng(19680801) + _, ax = plt.subplots() + ax.plot(rng.uniform(size=12), color='orange', gapcolor='blue', + linestyle='--', lw=5, label=' ') + ax.plot(rng.uniform(size=12), color='red', gapcolor='black', + linestyle=(0, (2, 5, 4, 2)), lw=5, label=' ', alpha=0.5) + ax.legend(handlelength=5) + + +@check_figures_equal(extensions=['png']) +def test_odd_dashes(fig_test, fig_ref): + fig_test.add_subplot().plot([1, 2], dashes=[1, 2, 3]) + fig_ref.add_subplot().plot([1, 2], dashes=[1, 2, 3, 1, 2, 3]) + + +def test_picking(): + fig, ax = plt.subplots() + mouse_event = SimpleNamespace(x=fig.bbox.width // 2, + y=fig.bbox.height // 2 + 15) + + # Default pickradius is 5, so event should not pick this line. + l0, = ax.plot([0, 1], [0, 1], picker=True) + found, indices = l0.contains(mouse_event) + assert not found + + # But with a larger pickradius, this should be picked. + l1, = ax.plot([0, 1], [0, 1], picker=True, pickradius=20) + found, indices = l1.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + # And if we modify the pickradius after creation, it should work as well. + l2, = ax.plot([0, 1], [0, 1], picker=True) + found, indices = l2.contains(mouse_event) + assert not found + l2.set_pickradius(20) + found, indices = l2.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + +@check_figures_equal(extensions=['png']) +def test_input_copy(fig_test, fig_ref): + + t = np.arange(0, 6, 2) + l, = fig_test.add_subplot().plot(t, t, ".-") + t[:] = range(3) + # Trigger cache invalidation + l.set_drawstyle("steps") + fig_ref.add_subplot().plot([0, 2, 4], [0, 2, 4], ".-", drawstyle="steps") + + +@check_figures_equal(extensions=["png"]) +def test_markevery_prop_cycle(fig_test, fig_ref): + """Test that we can set markevery prop_cycle.""" + cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], + slice(100, 200, 3), 0.1, 0.3, 1.5, + (0.0, 0.1), (0.45, 0.1)] + + cmap = mpl.colormaps['jet'] + colors = cmap(np.linspace(0.2, 0.8, len(cases))) + + x = np.linspace(-1, 1) + y = 5 * x**2 + + axs = fig_ref.add_subplot() + for i, markevery in enumerate(cases): + axs.plot(y - i, 'o-', markevery=markevery, color=colors[i]) + + matplotlib.rcParams['axes.prop_cycle'] = cycler(markevery=cases, + color=colors) + + ax = fig_test.add_subplot() + for i, _ in enumerate(cases): + ax.plot(y - i, 'o-') + + +def test_axline_setters(): + fig, ax = plt.subplots() + line1 = ax.axline((.1, .1), slope=0.6) + line2 = ax.axline((.1, .1), (.8, .4)) + # Testing xy1, xy2 and slope setters. + # This should not produce an error. + line1.set_xy1((.2, .3)) + line1.set_slope(2.4) + line2.set_xy1((.3, .2)) + line2.set_xy2((.6, .8)) + # Testing xy1, xy2 and slope getters. + # Should return the modified values. + assert line1.get_xy1() == (.2, .3) + assert line1.get_slope() == 2.4 + assert line2.get_xy1() == (.3, .2) + assert line2.get_xy2() == (.6, .8) + with pytest.warns(mpl.MatplotlibDeprecationWarning): + line1.set_xy1(.2, .3) + with pytest.warns(mpl.MatplotlibDeprecationWarning): + line2.set_xy2(.6, .8) + # Testing setting xy2 and slope together. + # These test should raise a ValueError + with pytest.raises(ValueError, + match="Cannot set an 'xy2' value while 'slope' is set"): + line1.set_xy2(.2, .3) + + with pytest.raises(ValueError, + match="Cannot set a 'slope' value while 'xy2' is set"): + line2.set_slope(3) + + +def test_axline_small_slope(): + """Test that small slopes are not coerced to zero in the transform.""" + line = plt.axline((0, 0), slope=1e-14) + p1 = line.get_transform().transform_point((0, 0)) + p2 = line.get_transform().transform_point((1, 1)) + # y-values must be slightly different + dy = p2[1] - p1[1] + assert dy > 0 + assert dy < 4e-12 diff --git a/shared/package-files/28/284acd052027b622bc696be5fd2068fb149cb82a10e6dd15537175604c1a212e/test_msvc9compiler.py b/shared/package-files/28/284acd052027b622bc696be5fd2068fb149cb82a10e6dd15537175604c1a212e/test_msvc9compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..77a07ef39dd1a6fe26ada95099d824c89f1ac54c --- /dev/null +++ b/shared/package-files/28/284acd052027b622bc696be5fd2068fb149cb82a10e6dd15537175604c1a212e/test_msvc9compiler.py @@ -0,0 +1,184 @@ +"""Tests for distutils.msvc9compiler.""" +import sys +import unittest +import os + +from distutils.errors import DistutilsPlatformError +from distutils.tests import support +from test.support import run_unittest + +# A manifest with the only assembly reference being the msvcrt assembly, so +# should have the assembly completely stripped. Note that although the +# assembly has a reference the assembly is removed - that is +# currently a "feature", not a bug :) +_MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\ + + + + + + + + + + + + + + + + + +""" + +# A manifest with references to assemblies other than msvcrt. When processed, +# this assembly should be returned with just the msvcrt part removed. +_MANIFEST_WITH_MULTIPLE_REFERENCES = """\ + + + + + + + + + + + + + + + + + + + + + + +""" + +_CLEANED_MANIFEST = """\ + + + + + + + + + + + + + + + + + + +""" + +if sys.platform=="win32": + from distutils.msvccompiler import get_build_version + if get_build_version()>=8.0: + SKIP_MESSAGE = None + else: + SKIP_MESSAGE = "These tests are only for MSVC8.0 or above" +else: + SKIP_MESSAGE = "These tests are only for win32" + +@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE) +class msvc9compilerTestCase(support.TempdirManager, + unittest.TestCase): + + def test_no_compiler(self): + # makes sure query_vcvarsall raises + # a DistutilsPlatformError if the compiler + # is not found + from distutils.msvc9compiler import query_vcvarsall + def _find_vcvarsall(version): + return None + + from distutils import msvc9compiler + old_find_vcvarsall = msvc9compiler.find_vcvarsall + msvc9compiler.find_vcvarsall = _find_vcvarsall + try: + self.assertRaises(DistutilsPlatformError, query_vcvarsall, + 'wont find this version') + finally: + msvc9compiler.find_vcvarsall = old_find_vcvarsall + + def test_reg_class(self): + from distutils.msvc9compiler import Reg + self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx') + + # looking for values that should exist on all + # windows registry versions. + path = r'Control Panel\Desktop' + v = Reg.get_value(path, 'dragfullwindows') + self.assertIn(v, ('0', '1', '2')) + + import winreg + HKCU = winreg.HKEY_CURRENT_USER + keys = Reg.read_keys(HKCU, 'xxxx') + self.assertEqual(keys, None) + + keys = Reg.read_keys(HKCU, r'Control Panel') + self.assertIn('Desktop', keys) + + def test_remove_visual_c_ref(self): + from distutils.msvc9compiler import MSVCCompiler + tempdir = self.mkdtemp() + manifest = os.path.join(tempdir, 'manifest') + f = open(manifest, 'w') + try: + f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES) + finally: + f.close() + + compiler = MSVCCompiler() + compiler._remove_visual_c_ref(manifest) + + # see what we got + f = open(manifest) + try: + # removing trailing spaces + content = '\n'.join([line.rstrip() for line in f.readlines()]) + finally: + f.close() + + # makes sure the manifest was properly cleaned + self.assertEqual(content, _CLEANED_MANIFEST) + + def test_remove_entire_manifest(self): + from distutils.msvc9compiler import MSVCCompiler + tempdir = self.mkdtemp() + manifest = os.path.join(tempdir, 'manifest') + f = open(manifest, 'w') + try: + f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE) + finally: + f.close() + + compiler = MSVCCompiler() + got = compiler._remove_visual_c_ref(manifest) + self.assertIsNone(got) + + +def test_suite(): + return unittest.makeSuite(msvc9compilerTestCase) + +if __name__ == "__main__": + run_unittest(test_suite()) diff --git a/shared/package-files/28/284ba24e3295a05042f6cabd42e257c3a1854826c5b13eb43701a5ff14baae5d/results_local_proj.R b/shared/package-files/28/284ba24e3295a05042f6cabd42e257c3a1854826c5b13eb43701a5ff14baae5d/results_local_proj.R new file mode 100644 index 0000000000000000000000000000000000000000..2f2d3ea6e9e65c2df5d6d456075825fdc827e215 --- /dev/null +++ b/shared/package-files/28/284ba24e3295a05042f6cabd42e257c3a1854826c5b13eb43701a5ff14baae5d/results_local_proj.R @@ -0,0 +1,123 @@ +## Reference values for statsmodels.tsa.vector_ar.local_proj.LocalProjections +## +## Independently replicates the LocalProjections regression construction +## (statsmodels/tsa/vector_ar/local_proj.py: _build_regressors / fit) using +## base R's lm() for OLS and sandwich::NeweyWest() for the HAC covariance, +## on the real macrodata series already used elsewhere in the docs +## (docs/source/vector_ar.rst) and shipped with statsmodels at +## statsmodels/datasets/macrodata/macrodata.csv. +## +## Python test is: statsmodels/tsa/vector_ar/tests/test_local_projection.py +## ::test_against_r_lpirfs_base_case and ::test_against_r_lpirfs_with_exog +## +## install.packages(c("sandwich")) +library(sandwich) +options(digits = 10) + +macro <- read.csv("../../../../datasets/macrodata/macrodata.csv") + +## Same transform as docs/source/vector_ar.rst: log-difference, drop NA row. +log_diff <- function(x) diff(log(x)) + +# --------------------------------------------------------------------------- +# Newey-West HAC sandwich covariance, hand-rolled to match +# statsmodels.tsa.vector_ar.local_proj._nw_cov exactly (Bartlett kernel, no +# prewhitening, no small-sample adjustment, divide by T twice). +# --------------------------------------------------------------------------- +nw_cov <- function(X, resid, nlags) { + Tn <- nrow(X) + scores <- X * resid + S <- t(scores) %*% scores / Tn + for (lag in 1:nlags) { + w <- 1 - lag / (nlags + 1) + gamma <- t(scores[(lag + 1):Tn, , drop = FALSE]) %*% + scores[1:(Tn - lag), , drop = FALSE] / Tn + S <- S + w * (gamma + t(gamma)) + } + XtX_inv <- solve(t(X) %*% X / Tn) + (XtX_inv %*% S %*% XtX_inv) / Tn +} + +# --------------------------------------------------------------------------- +# LocalProjections regression, replicated row-for-row: for lags L and a +# fixed common sample used across all horizons 0..H (t_start = L, +# t_end = T - H, matching local_proj.py's fit()), regress +# Y[t+h, response] on [shock_t, lag1(all), ..., lagL(all), (exog_t), +# const] and report the shock coefficient +/- its Newey-West SE. +# --------------------------------------------------------------------------- +fit_lp <- function(Y, shock_col, lags, horizons, nw_lag, exog = NULL) { + Tn <- nrow(Y) + n <- ncol(Y) + t_start <- lags + 1L # R row index of the first usable "t" + t_end <- Tn - horizons # R row index of the last usable "t" + idx <- t_start:t_end + n_obs <- length(idx) + + X <- Y[idx, shock_col, drop = FALSE] + for (lag in 1:lags) { + X <- cbind(X, Y[idx - lag, , drop = FALSE]) + } + if (!is.null(exog)) { + X <- cbind(X, exog[idx, , drop = FALSE]) + } + X <- cbind(X, const = rep(1, n_obs)) + X <- as.matrix(X) + + irfs <- matrix(NA_real_, nrow = horizons + 1, ncol = n) + ses <- matrix(NA_real_, nrow = horizons + 1, ncol = n) + for (h in 0:horizons) { + Yh <- Y[idx + h, , drop = FALSE] + for (i in 1:n) { + fit <- lm.fit(X, Yh[, i]) + beta <- fit$coefficients + resid <- fit$residuals + V <- nw_cov(X, resid, nw_lag) + irfs[h + 1, i] <- beta[1] + ses[h + 1, i] <- sqrt(V[1, 1]) + } + } + list(irfs = irfs, ses = ses) +} + +# --------------------------------------------------------------------------- +# Base case: realgdp shock -> (realgdp, realcons, realinv), lags=2, +# horizons=4, trend="c" (constant only), fixed nw_lags=4. +# --------------------------------------------------------------------------- +endog <- data.frame( + realgdp = log_diff(macro$realgdp), + realcons = log_diff(macro$realcons), + realinv = log_diff(macro$realinv) +) +Y <- as.matrix(endog) + +res_base <- fit_lp(Y, shock_col = 1, lags = 2, horizons = 4, nw_lag = 4) +cat("Base case irfs (rows=horizon 0..4, cols=realgdp,realcons,realinv):\n") +print(res_base$irfs) +cat("Base case stderr:\n") +print(res_base$ses) + +# Cross-check the hand-rolled HAC formula against sandwich::NeweyWest, +# using a non-degenerate response (realcons at h=1, i.e. not the shock's +# own contemporaneous response, which fits exactly by construction). +idx1 <- 3:(nrow(Y) - 4) +X1 <- cbind(shock = Y[idx1, 1], Y[idx1 - 1, ], Y[idx1 - 2, ], const = 1) +fit1 <- lm(Y[idx1 + 1, 2] ~ X1 - 1) +V_sw <- NeweyWest(fit1, lag = 4, prewhite = FALSE, adjust = FALSE) +cat("sandwich::NeweyWest se[shock] realcons h=1:", sqrt(V_sw[1, 1]), "\n") +cat("hand-rolled nw_cov se[shock] realcons h=1: ", res_base$ses[2, 2], "\n") + +# --------------------------------------------------------------------------- +# Exogenous-controls case: realgdp shock -> realgdp, lags=1, horizons=3, +# contemporaneous exog = log-diff(realgovt), fixed nw_lags=3. +# --------------------------------------------------------------------------- +endog2 <- data.frame(realgdp = log_diff(macro$realgdp)) +exog2 <- data.frame(realgovt = log_diff(macro$realgovt)) +Y2 <- as.matrix(endog2) +E2 <- as.matrix(exog2) + +res_exog <- fit_lp(Y2, shock_col = 1, lags = 1, horizons = 3, nw_lag = 3, + exog = E2) +cat("\nExog case irfs (rows=horizon 0..3, col=realgdp):\n") +print(res_exog$irfs) +cat("Exog case stderr:\n") +print(res_exog$ses) diff --git a/shared/package-files/28/285262c2d1e1a2c40bdde8196d3387b5701f7e51b4c693fab769f2cfa751677a/test_tsa_indexes.py b/shared/package-files/28/285262c2d1e1a2c40bdde8196d3387b5701f7e51b4c693fab769f2cfa751677a/test_tsa_indexes.py new file mode 100644 index 0000000000000000000000000000000000000000..dd98cd3c7b396cf8a011a00648b802bb32085eb2 --- /dev/null +++ b/shared/package-files/28/285262c2d1e1a2c40bdde8196d3387b5701f7e51b4c693fab769f2cfa751677a/test_tsa_indexes.py @@ -0,0 +1,1202 @@ +""" +Test index support in time series models + +1. Test support for passing / constructing the underlying index in __init__ +2. Test wrapping of output using the underlying index +3. Test wrapping of prediction / forecasting using the underlying index or + extensions of it. + +Author: Chad Fulton +License: BSD-3 +""" + +from statsmodels.compat.pandas import PD_LT_2_2_0, YEAR_END, is_int_index + +import warnings + +import numpy as np +from numpy.testing import assert_equal +import pandas as pd +import pytest + +from statsmodels.tools.sm_exceptions import ValueWarning +from statsmodels.tsa.base import tsa_model + +nobs = 5 +base_dta = np.arange(nobs) +dta = [ + base_dta.tolist(), + base_dta, + pd.Series(base_dta), + pd.DataFrame(base_dta), +] + +TWO_QE_DEC = "2Q-DEC" if PD_LT_2_2_0 else "2QE-DEC" +base_date_indexes = [ + # (usual candidates) + pd.date_range(start="1950-01-01", periods=nobs, freq="D"), + pd.date_range(start="1950-01-01", periods=nobs, freq="W"), + pd.date_range(start="1950-01-01", periods=nobs, freq="MS"), + pd.date_range(start="1950-01-01", periods=nobs, freq="QS"), + pd.date_range(start="1950-01-01", periods=nobs, freq=YEAR_END), + # (some more complicated frequencies) + pd.date_range(start="1950-01-01", periods=nobs, freq=TWO_QE_DEC), + pd.date_range(start="1950-01-01", periods=nobs, freq="2QS"), + pd.date_range(start="1950-01-01", periods=nobs, freq="5s"), + pd.date_range(start="1950-01-01", periods=nobs, freq="1D10min"), +] + +# Note: we separate datetime indexes and period indexes because the +# date coercion does not handle string versions of PeriodIndex objects +# most of the time. +base_period_indexes = [ + pd.period_range(start="1950-01-01", periods=nobs, freq="D"), + pd.period_range(start="1950-01-01", periods=nobs, freq="W"), + pd.period_range(start="1950-01-01", periods=nobs, freq="M"), + pd.period_range(start="1950-01-01", periods=nobs, freq="Q"), + pd.period_range(start="1950-01-01", periods=nobs, freq="Y"), +] +try: + # Only later versions of pandas support these + base_period_indexes += [ + pd.period_range(start="1950-01-01", periods=nobs, freq="2Q"), + pd.period_range(start="1950-01-01", periods=nobs, freq="5s"), + pd.period_range(start="1950-01-01", periods=nobs, freq="1D10min"), + ] +except AttributeError: + pass + +date_indexes = [(x, None) for x in base_date_indexes] +period_indexes = [(x, None) for x in base_period_indexes] + +numpy_datestr_indexes = [(x.map(str), x.freq) for x in base_date_indexes] +list_datestr_indexes = [(x.tolist(), y) for x, y in numpy_datestr_indexes] +series_datestr_indexes = [(pd.Series(x), y) for x, y in list_datestr_indexes] + +numpy_datetime_indexes = [ + (pd.to_datetime(x).to_pydatetime(), x.freq) for x in base_date_indexes +] +list_datetime_indexes = [(x.tolist(), y) for x, y in numpy_datetime_indexes] +series_datetime_indexes = [ + (pd.Series(x, dtype=object), y) for x, y in list_datetime_indexes +] + +series_timestamp_indexes = [(pd.Series(x), x.freq) for x in base_date_indexes] + +# Supported increment indexes +supported_increment_indexes = [ + (pd.Index(np.arange(nobs)), None), + (pd.RangeIndex(start=0, stop=nobs, step=1), None), + (pd.RangeIndex(start=-5, stop=nobs - 5, step=1), None), + (pd.RangeIndex(start=0, stop=nobs * 6, step=6), None), +] + +# Supported date indexes +# Only the NumericIndex and the `date_indexes` are valid without +# frequency information +supported_date_indexes = ( + numpy_datestr_indexes + + list_datestr_indexes + + series_datestr_indexes + + numpy_datetime_indexes + + list_datetime_indexes + + series_datetime_indexes + + series_timestamp_indexes +) + +# Unsupported (but still valid) indexes +unsupported_indexes = [ + # Non-incrementing-from-zero indexes + (np.arange(1, nobs + 1), None), + (np.arange(nobs)[::-1], None), + # Float indexes, even if they increment from zero + (np.arange(nobs) * 1.0, None), + # Non-date-string indexes + (list("abcde"), None), + # Non-date-object indexes + ([str, 1, "a", -30.1, {}], None), +] + +# Unsupported date indexes (i.e., those without inferrable frequency) +unsupported_date_indexes = [ + (["1950", "1952", "1941", "1954", "1991"], None), + ( + ["1950-01-01", "1950-01-02", "1950-01-03", "1950-01-04", "1950-01-06"], + None, + ), +] + + +def test_instantiation_valid(): + tsa_model.__warningregistry__ = {} + + # The primary goal of this test function is to make sure the + # combinations that are supposed to be valid are actually valid, and + # that valid but unsupported options give the appropriate warning + # Secondarily, it also has some tests that invalid combinations raise + # exceptions, although it's not intended to be comprehensive. + # + # Each of `endog`, `exog` can be in the following categories: + # 0. None (only for exog) + # 1. list + # 2. numpy array + # 3. pandas series + # 4. pandas dataframe + # + # Each pandas index (of `endog`, `exog`, or passed to `dates`) can be: + # 0. None + # 1. RangeIndex (if applicable; i.e., if Pandas >= 0.18) + # 2. Integral Indexes with values exactly equal to 0, 1, ..., nobs-1 + # 3. DatetimeIndex with frequency + # 4. PeriodIndex with frequency + # 5. Anything that does not fall into the above categories also should + # only raise an exception if it was passed to dates, and may trigger + # a warning otherwise. + # + # `date` can be one of the following: + # 0. None + # 2. Pandas index #2 + # 3. Pandas index #3 + # 4. List of date strings (requires freq) + # 5. List of datetime objects (requires freq) + # 6. Array of date strings (requires freq) + # 7. Array of datetime objects (requires freq) + # 8. Series of date strings (requires freq) + # 9. Series of datetime objects (requires freq) + # 10. Series of pandas timestamps (requires freq) + # 11. Anything that does not fall into the above categories should raise + # an exception. + # + # `freq` can be: + # 0. None + # 1. Something that can be passed to `pd.to_offset` + # 2. Anything that cannot should raise an Exception + # + # Each test will be denoted by: + # endog.index:exog.index/date/freq where the corresponding + # location is the integer from above; e.g., 1.0:0.0/9/1 corresponds to + # - List endog (with no index) + # - No exog + # - Series of datetime objects + # - Something valid for `pd.to_offset` (e.g., 'D', if that works with + # dates) + # + # Notice that the endog.index:exog.index really collapses to a single + # element, which is the evaluated `row_label`. This is first the exog + # index, if exists, then the endog index, if it exists, or None + # otherwise. **Thus, we will not test `exog` here.** + # + # Example valid combinations of row_label/date/freq include: + # - */0/0 (i.e., anything is valid if date and freq are not passed) + # - */%/% where %/% denotes a valid date/freq combination (i.e., any + # row_label is valid if a valid date/freq combination is given) + # + # Example invalid combinations include: + # - [1-2],[3-4].4/0/[1-2] (i.e., if have freq, then must have, or + # coerce, a date index) + # - */[4-10]/0 (i.e., for some types of dates, freq must be passed) + + # Baseline: list, numpy endog with no dates, no freq + for endog in dta[:2]: + # No indexes, should not raise warnings + with warnings.catch_warnings(): + warnings.simplefilter("error") + + mod = tsa_model.TimeSeriesModel(endog) + assert isinstance(mod._index, pd.RangeIndex) or np.issubdtype( + mod._index.dtype, np.integer + ) + assert_equal(mod._index_none, True) + assert_equal(mod._index_dates, False) + assert_equal(mod._index_generated, True) + assert_equal(mod.data.dates, None) + assert_equal(mod.data.freq, None) + + # Test list, numpy endog, pandas w/o index; with dates / freq argument + for endog in dta: + # Supported date indexes, should not raise warnings, do not need freq + with warnings.catch_warnings(): + warnings.simplefilter("error") + + for ix, freq in date_indexes + period_indexes: + mod = tsa_model.TimeSeriesModel(endog, dates=ix) + if freq is None: + freq = ix.freq + if not isinstance(freq, str): + freq = ix.freqstr + assert_equal( + isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)), + True, + ) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, True) + assert_equal(mod._index_generated, False) + assert_equal(mod._index.freq, mod._index_freq) + assert_equal(mod.data.dates.equals(mod._index), True) + assert_equal(mod.data.freq, freq) + + # Supported date indexes, should not raise warnings, can use valid freq + with warnings.catch_warnings(): + warnings.simplefilter("error") + + for ix, freq in date_indexes + period_indexes: + mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq) + if freq is None: + freq = ix.freq + if not isinstance(freq, str): + freq = ix.freqstr + assert_equal( + isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)), + True, + ) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, True) + assert_equal(mod._index_generated, False) + assert_equal(mod._index.freq, mod._index_freq) + assert_equal(mod.data.dates.equals(mod._index), True) + assert_equal(mod.data.freq, freq) + + # Other supported indexes, with valid freq, should not raise warnings + with warnings.catch_warnings(): + warnings.simplefilter("error") + + for ix, freq in supported_date_indexes: + mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq) + if freq is None: + freq = ix.freq + if not isinstance(freq, str): + freq = freq.freqstr + assert_equal( + isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)), + True, + ) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, True) + assert_equal(mod._index_generated, False) + assert_equal(mod._index.freq, mod._index_freq) + assert_equal(mod.data.dates.equals(mod._index), True) + assert_equal(mod.data.freq, freq) + + # Since only supported indexes are valid `dates` arguments, everything + # else is invalid here + for ix, _ in supported_increment_indexes + unsupported_indexes: + with pytest.raises(ValueError): + tsa_model.TimeSeriesModel(endog, dates=ix) + + # Test pandas (Series, DataFrame); with index (no dates/freq argument) + for base_endog in dta[2:4]: + # DatetimeIndex and PeriodIndex, should not raise warnings + with warnings.catch_warnings(): + warnings.simplefilter("error") + + for ix, freq in date_indexes + period_indexes: + endog = base_endog.copy() + endog.index = ix + + mod = tsa_model.TimeSeriesModel(endog) + if freq is None: + freq = ix.freq + if not isinstance(freq, str): + freq = ix.freqstr + assert_equal( + isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)), + True, + ) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, True) + assert_equal(mod._index_generated, False) + assert_equal(mod._index.freq, mod._index_freq) + assert_equal(mod.data.dates.equals(mod._index), True) + assert_equal(mod.data.freq, freq) + + # Increment index (this is a "supported" index in the sense that it + # does not raise a warning, but obviously not a date index) + endog = base_endog.copy() + endog.index = supported_increment_indexes[0][0] + + mod = tsa_model.TimeSeriesModel(endog) + assert is_int_index(mod._index) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, False) + assert_equal(mod._index_generated, False) + assert_equal(mod._index_freq, None) + assert_equal(mod.data.dates, None) + assert_equal(mod.data.freq, None) + + # RangeIndex (start=0, end=nobs, so equivalent to increment index) + endog = base_endog.copy() + endog.index = supported_increment_indexes[1][0] + + mod = tsa_model.TimeSeriesModel(endog) + assert type(mod._index) is pd.RangeIndex + assert not mod._index_none + assert not mod._index_dates + assert not mod._index_generated + assert mod._index_freq is None + assert mod.data.dates is None + assert mod.data.freq is None + + # Supported indexes *when a freq is given*, should not raise a warning + with warnings.catch_warnings(): + warnings.simplefilter("error") + + for ix, freq in supported_date_indexes: + # Avoid warnings due to Series with object dtype + if isinstance(ix, pd.Series) and ix.dtype == object: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + endog = pd.DataFrame(base_endog, index=ix) + else: + endog = pd.DataFrame(base_endog, index=ix) + + mod = tsa_model.TimeSeriesModel(endog, freq=freq) + if freq is None: + freq = ix.freq + if not isinstance(freq, str): + freq = freq.freqstr + assert_equal( + isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)), + True, + ) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, True) + assert_equal(mod._index_generated, False) + assert_equal(mod._index.freq, mod._index_freq) + assert_equal(mod.data.dates.equals(mod._index), True) + assert_equal(mod.data.freq, freq) + + # Unsupported (or any) indexes to the given series, *when a supported + # date and freq is given*, should not raise a warning + with warnings.catch_warnings(): + warnings.simplefilter("error") + + for ix, freq in supported_date_indexes: + endog = base_endog.copy() + endog.index = unsupported_indexes[0][0] + + mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq) + if freq is None: + freq = ix.freq + if not isinstance(freq, str): + freq = freq.freqstr + assert_equal( + isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)), + True, + ) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, True) + assert_equal(mod._index_generated, False) + assert_equal(mod._index.freq, mod._index_freq) + assert_equal(mod.data.dates.equals(mod._index), True) + assert_equal(mod.data.freq, freq) + + # Date indexes with inferrable freq, but no given freq, should all give + # warnings + message = ( + "No frequency information was provided," + " so inferred frequency %s will be used." + ) + last_len = 0 + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + for ix, freq in supported_date_indexes: + endog = base_endog.copy() + endog.index = ix + mod = tsa_model.TimeSeriesModel(endog) + if freq is None: + freq = ix.freq + if not isinstance(freq, str): + freq = freq.freqstr + assert type(mod._index) is pd.DatetimeIndex + assert not mod._index_none + assert mod._index_dates + assert not mod._index_generated + assert_equal(mod._index.freq, mod._index_freq) + assert mod.data.dates.equals(mod._index) + + # Note: here, we need to hedge the test a little bit because + # inferred frequencies are not always the same as the original + # frequency. From the examples above, when the actual freq is + # 2QS-OCT, the inferred freq is 2QS-JAN. This is an issue with + # inferred frequencies, but since we are warning the user, it's + # not a failure of the code. Thus we only test the "major" part + # of the freq, and just test that the right message is given + # (even though it will not have the actual freq of the data in + # it). + if len(w) == last_len: + continue + assert_equal(mod.data.freq.split("-")[0], freq.split("-")[0]) + assert_equal(str(w[-1].message), message % mod.data.freq) + last_len = len(w) + + # Unsupported (but valid) indexes, should all give warnings + message = ( + "An unsupported index was provided. As a result, forecasts " + "cannot be generated. To use the model for forecasting, use " + "on the supported classes of index." + ) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + for ix, _ in unsupported_indexes: + endog = base_endog.copy() + endog.index = ix + mod = tsa_model.TimeSeriesModel(endog) + assert_equal(isinstance(mod._index, (pd.Index, pd.RangeIndex)), True) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, False) + assert_equal(mod._index_generated, True) + assert_equal(mod._index_freq, None) + assert_equal(mod.data.dates, None) + assert_equal(mod.data.freq, None) + + assert_equal(str(w[0].message), message) + + # Date indexes without inferrable freq, and with no given freq, should + # all give warnings + message = ( + "A date index has been provided, but it has no" + " associated frequency information and so will be" + " ignored when e.g., forecasting." + ) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + for ix, _ in unsupported_date_indexes: + endog = base_endog.copy() + endog.index = ix + mod = tsa_model.TimeSeriesModel(endog) + assert isinstance(mod._index, pd.RangeIndex) or is_int_index(mod._index) + assert_equal(mod._index_none, False) + assert_equal(mod._index_dates, False) + assert_equal(mod._index_generated, True) + assert_equal(mod._index_freq, None) + assert_equal(mod.data.dates, None) + assert_equal(mod.data.freq, None) + + assert_equal(str(w[0].message), message) + + # Test (invalid) freq with no index + endog = dta[0] + with pytest.raises(ValueError): + tsa_model.TimeSeriesModel( + endog, + freq=date_indexes[1][0].freq, + ) + + # Test conflicting index, freq specifications + endog = dta[2].copy() + endog.index = date_indexes[0][0] + with pytest.raises(ValueError): + tsa_model.TimeSeriesModel( + endog, + freq=date_indexes[1][0].freq, + ) + + # Test unsupported index, but a freq specification + endog = dta[2].copy() + endog.index = unsupported_indexes[0][0] + with pytest.raises(ValueError): + tsa_model.TimeSeriesModel( + endog, + freq=date_indexes[1][0].freq, + ) + + # Test index that can coerce to date time but incorrect freq + endog = dta[2].copy() + endog.index = numpy_datestr_indexes[0][0] + with pytest.raises(ValueError): + tsa_model.TimeSeriesModel( + endog, + freq=date_indexes[1][0].freq, + ) + + +def test_prediction_increment_unsupported(): + # a. Generated from unsupported index + endog = dta[2].copy() + endog.index = unsupported_indexes[-2][0] + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end]; notice that since this is an in-sample + # prediction, the index returned is the (unsupported) original index + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + assert_equal(prediction_index.equals(mod.data.row_labels), True) + + # Negative index: [-2, end]; notice that since this is an in-sample + # prediction, the index returned is a piece of the (unsupported) + # original index + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + assert_equal(prediction_index.equals(mod.data.row_labels[3:]), True) + + # Forecasting: [1, 5], notice that since an unsupported index was given, + # a warning will be issued + start_key = 1 + end_key = nobs + with pytest.raises(ValueError, match="No supported index is available"): + mod._get_prediction_index(start_key, end_key) + + # Test getting a location that exists in the (internal) index + loc, index, index_was_expanded = mod._get_index_loc(2) + assert_equal(loc, 2) + desired_index = pd.RangeIndex(start=0, stop=3, step=1) + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + # Test getting a location that exists in the (internal) index + # when using the function that alternatively falls back to the row labels + loc, index, index_was_expanded = mod._get_index_label_loc(2) + assert_equal(loc, 2) + desired_index = pd.RangeIndex(start=0, stop=3, step=1) + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + # Test getting a location that exists in the given (unsupported) index + # Note that the returned index is now like the row labels + loc, index, index_was_expanded = mod._get_index_label_loc("c") + assert_equal(loc, 2) + desired_index = mod.data.row_labels[:3] + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + +def test_prediction_increment_nonpandas(): + endog = dta[0] + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end]; since there was no index at all and the data + # is not Pandas, the returned prediction_index is None + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + assert_equal(prediction_index is None, True) + + # Negative index: [-2, end]; since there was no index at all and the data + # is not Pandas, the returned prediction_index is None + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + assert_equal(prediction_index is None, True) + + # Forecasting: [1, 5]; since there was no index at all and the data + # is not Pandas, the returned prediction_index is None + start_key = 1 + end_key = nobs + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 4) + assert_equal(out_of_sample, 1) + assert_equal(prediction_index is None, True) + + # Test getting a location that exists in the (internal) index + loc, index, index_was_expanded = mod._get_index_loc(2) + assert_equal(loc, 2) + desired_index = pd.RangeIndex(start=0, stop=3, step=1) + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + # Test getting a location that exists in the (internal) index + # when using the function that alternatively falls back to the row labels + loc, index, index_was_expanded = mod._get_index_label_loc(2) + assert_equal(loc, 2) + desired_index = pd.RangeIndex(start=0, stop=3, step=1) + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + +def test_prediction_increment_pandas_noindex(): + endog = dta[2].copy() + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end]; since there was no index and the data is + # Pandas, the index is the generated incrementing index, and no warning is + # issued + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + assert_equal(prediction_index.equals(mod._index), True) + + # Negative index: [-2, end]; since there was no index and the data is + # Pandas, the index is the generated incrementing index, and no warning is + # issued + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + assert_equal(prediction_index.equals(mod._index[3:]), True) + + # Forecasting: [1, 5]; since there was no index and the data is + # Pandas, the index is the generated incrementing index, and no warning is + # issued + start_key = 1 + end_key = nobs + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 4) + assert_equal(out_of_sample, 1) + assert_equal(prediction_index.equals(pd.Index(np.arange(1, 6))), True) + + +def test_prediction_increment_pandas_dates_daily(): + # Date-based index + endog = dta[2].copy() + endog.index = date_indexes[0][0] # Daily, 1950-01-01, 1950-01-02, ... + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end]; the index is the date index + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index), True) + + # In-sample prediction: [0, 3]; the index is a subset of the date index + start_key = 0 + end_key = 3 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, 3) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index[:4]), True) + + # Negative index: [-2, end] + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index[3:]), True) + + # Forecasting: [1, 5]; the index is an extended version of the date index + start_key = 1 + end_key = nobs + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 4) + assert_equal(out_of_sample, 1) + desired_index = pd.date_range(start="1950-01-02", periods=5, freq="D") + assert_equal(prediction_index.equals(desired_index), True) + + # Date-based keys + + # In-sample prediction (equivalent to [1, 3]) + start_key = "1950-01-02" + end_key = "1950-01-04" + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 3) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index[1:4]), True) + + # Out-of-sample forecasting (equivalent to [0, 5]) + start_key = "1950-01-01" + end_key = "1950-01-08" + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, 4) + assert_equal(out_of_sample, 3) + desired_index = pd.date_range(start="1950-01-01", periods=8, freq="D") + assert_equal(prediction_index.equals(desired_index), True) + + # Test getting a location that exists in the (internal) index + loc, index, index_was_expanded = mod._get_index_loc(2) + assert_equal(loc, 2) + desired_index = pd.date_range(start="1950-01-01", periods=3, freq="D") + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + # Test getting a location that exists in the (internal) index + # when using the function that alternatively falls back to the row labels + loc, index, index_was_expanded = mod._get_index_label_loc(2) + assert_equal(loc, 2) + desired_index = pd.date_range(start="1950-01-01", periods=3, freq="D") + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + # Test getting a location that exists in the given (unsupported) index + # Note that the returned index is now like the row labels + loc, index, index_was_expanded = mod._get_index_label_loc("1950-01-03") + assert_equal(loc, 2) + desired_index = mod.data.row_labels[:3] + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + +def test_prediction_increment_pandas_dates_monthly(): + # Date-based index + endog = dta[2].copy() + endog.index = date_indexes[2][0] # Monthly, 1950-01, 1950-02, ... + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end]; the index is the date index + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index), True) + + # In-sample prediction: [0, 3]; the index is a subset of the date index + start_key = 0 + end_key = 3 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, 3) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index[:4]), True) + + # Negative index: [-2, end] + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index[3:]), True) + + # Forecasting: [1, 5]; the index is an extended version of the date index + start_key = 1 + end_key = nobs + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 4) + assert_equal(out_of_sample, 1) + desired_index = pd.date_range(start="1950-02", periods=5, freq="MS") + assert_equal(prediction_index.equals(desired_index), True) + + # Date-based keys + + # In-sample prediction (equivalent to [1, 3]) + start_key = "1950-02" + end_key = "1950-04" + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 3) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index[1:4]), True) + + # Out-of-sample forecasting (equivalent to [0, 5]) + start_key = "1950-01" + end_key = "1950-08" + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, 4) + assert_equal(out_of_sample, 3) + desired_index = pd.date_range(start="1950-01", periods=8, freq="MS") + assert_equal(prediction_index.equals(desired_index), True) + + # Test getting a location that exists in the (internal) index + loc, index, index_was_expanded = mod._get_index_loc(2) + assert_equal(loc, 2) + desired_index = pd.date_range(start="1950-01", periods=3, freq="MS") + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + # Test getting a location that exists in the (internal) index + # when using the function that alternatively falls back to the row labels + loc, index, index_was_expanded = mod._get_index_label_loc(2) + assert_equal(loc, 2) + desired_index = pd.date_range(start="1950-01", periods=3, freq="MS") + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + # Test getting a location that exists in the given (unsupported) index + # Note that the returned index is now like the row labels + loc, index, index_was_expanded = mod._get_index_label_loc("1950-03") + assert_equal(loc, slice(2, 3, None)) + desired_index = mod.data.row_labels[:3] + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + +def test_prediction_increment_pandas_dates_nanosecond(): + # Date-based index + endog = dta[2].copy() + endog.index = pd.date_range(start="1970-01-01", periods=len(endog), freq="ns") + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end]; the index is the date index + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index), True) + + # Negative index: [-2, end] + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + assert type(prediction_index) is type(endog.index) + assert_equal(prediction_index.equals(mod._index[3:]), True) + + # Forecasting: [1, 5]; the index is an extended version of the date index + start_key = 1 + end_key = nobs + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 4) + assert_equal(out_of_sample, 1) + desired_index = pd.date_range(start="1970-01-01", periods=6, freq="ns")[1:] + assert_equal(prediction_index.equals(desired_index), True) + + # Date-based keys + start_key = pd.Timestamp("1970-01-01") + end_key = pd.Timestamp(start_key.value + 7) + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, 4) + assert_equal(out_of_sample, 3) + desired_index = pd.date_range(start="1970-01-01", periods=8, freq="ns") + assert_equal(prediction_index.equals(desired_index), True) + + +def test_range_index(): + rs = np.random.RandomState(328389218) + tsa_model.__warningregistry__ = {} + + endog = pd.Series(rs.normal(size=5)) + assert_equal(isinstance(endog.index, pd.RangeIndex), True) + # Warning should not be given + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + tsa_model.TimeSeriesModel(endog) + assert_equal(len(w), 0) + + +def test_prediction_rangeindex(): + index = supported_increment_indexes[2][0] + endog = pd.Series(dta[0], index=index) + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end] + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + desired_index = pd.RangeIndex(start=-5, stop=0, step=1) + assert_equal(prediction_index.equals(desired_index), True) + + # Negative index: [-2, end] + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + desired_index = pd.RangeIndex(start=-2, stop=0, step=1) + assert_equal(prediction_index.equals(desired_index), True) + + # Forecasting: [1, 5] + start_key = 1 + end_key = nobs + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 4) + assert_equal(out_of_sample, 1) + desired_index = pd.RangeIndex(start=-4, stop=1, step=1) + assert_equal(prediction_index.equals(desired_index), True) + + +def test_prediction_rangeindex_withstep(): + index = supported_increment_indexes[3][0] + endog = pd.Series(dta[0], index=index) + mod = tsa_model.TimeSeriesModel(endog) + + # Tests three common use cases: basic prediction, negative indexes, and + # out-of-sample indexes. + + # Basic prediction: [0, end] + start_key = 0 + end_key = None + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 0) + assert_equal(end, nobs - 1) + assert_equal(out_of_sample, 0) + desired_index = pd.RangeIndex(start=0, stop=nobs * 6, step=6) + assert_equal(prediction_index.equals(desired_index), True) + + # Negative index: [-2, end] + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 3) + assert_equal(end, 4) + assert_equal(out_of_sample, 0) + desired_index = pd.RangeIndex(start=3 * 6, stop=nobs * 6, step=6) + assert_equal(prediction_index.equals(desired_index), True) + + # Forecasting: [1, 5] + start_key = 1 + end_key = nobs + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + assert_equal(start, 1) + assert_equal(end, 4) + assert_equal(out_of_sample, 1) + desired_index = pd.RangeIndex(start=1 * 6, stop=(nobs + 1) * 6, step=6) + assert_equal(prediction_index.equals(desired_index), True) + + # Test getting a location that exists in the index + loc, index, index_was_expanded = mod._get_index_loc(2) + assert_equal(loc, 2) + desired_index = pd.RangeIndex(start=0, stop=3 * 6, step=6) + assert_equal(index.equals(desired_index), True) + assert_equal(index_was_expanded, False) + + +def test_custom_index(): + rs = np.random.RandomState(328392810) + tsa_model.__warningregistry__ = {} + + endog = pd.Series(rs.normal(size=5), index=["a", "b", "c", "d", "e"]) + message = ( + "An unsupported index was provided. As a result, forecasts cannot be " + "generated. To use the model for forecasting, use on the " + "supported classes of index." + ) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + mod = tsa_model.TimeSeriesModel(endog) + # Change due to pandas changes that produce a warning + messages = [str(warn.message) for warn in w] + assert message in messages + start_key = -2 + end_key = -1 + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key + ) + + # Test the default output index + assert_equal(prediction_index.equals(pd.Index(["d", "e"])), True) + + # Test custom output index + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key, index=["f", "g"] + ) + assert_equal(prediction_index.equals(pd.Index(["f", "g"])), True) + + # Test getting a location in the index w/o fallback to row labels + loc, index, index_was_expanded = mod._get_index_loc(2) + assert_equal(loc, 2) + assert_equal(index.equals(pd.RangeIndex(0, 3)), True) + assert_equal(index_was_expanded, False) + assert_equal(index_was_expanded, False) + + # Test getting an invalid location in the index w/ fallback to row labels + with pytest.raises(KeyError): + mod._get_index_loc("c") + + # Test getting a location in the index w/ fallback to row labels + loc, index, index_was_expanded = mod._get_index_label_loc("c") + assert_equal(loc, 2) + assert_equal(index.equals(pd.Index(["a", "b", "c"])), True) + assert_equal(index_was_expanded, False) + + # Test getting an invalid location in the index w/ fallback to row labels + with pytest.raises(KeyError): + mod._get_index_label_loc("aa") + + # Test out-of-sample + start_key = 4 + end_key = 5 + with pytest.raises(ValueError, match="No supported index is available"): + mod._get_prediction_index(start_key, end_key) + + # Test out-of-sample custom index + start, end, out_of_sample, prediction_index = mod._get_prediction_index( + start_key, end_key, index=["f", "g"] + ) + assert_equal(prediction_index.equals(pd.Index(["f", "g"])), True) + + # Test invalid custom index + with pytest.raises(ValueError): + mod._get_prediction_index( + start_key, + end_key, + index=["f", "g", "h"], + ) + + +def test_nonmonotonic_periodindex(): + # Create a nonmonotonic period index + tmp = pd.period_range(start="2000", end="2002", freq="Y") + index = tmp.tolist() + tmp.tolist() + endog = pd.Series(np.zeros(len(index)), index=index) + + message = ( + "A date index has been provided, but it is not" + " monotonic and so will be ignored when e.g." + " forecasting." + ) + with pytest.warns(ValueWarning, match=message): + tsa_model.TimeSeriesModel(endog) + + +def test_nonfull_periodindex(): + index = pd.PeriodIndex(["2000-01", "2000-03"], freq="M") + endog = pd.Series(np.zeros(len(index)), index=index) + + tsa_model.TimeSeriesModel(endog) + + +def test_get_index_loc_quarterly(): + # See GH#6339 + ix = pd.period_range("2000Q1", periods=8, freq="Q").to_timestamp() + endog = pd.Series(np.zeros(8), index=ix) + + mod = tsa_model.TimeSeriesModel(endog) + loc, index, _ = mod._get_index_loc("2003Q2") + assert_equal(index[loc], pd.Period("2003Q2").to_timestamp()) diff --git a/shared/package-files/28/2852b813a11eff3679da4f616f14ba9cc14da38d5ab2ea29a6216c256f0f1842/test_ipc.py b/shared/package-files/28/2852b813a11eff3679da4f616f14ba9cc14da38d5ab2ea29a6216c256f0f1842/test_ipc.py new file mode 100644 index 0000000000000000000000000000000000000000..6813ed7772345ad166544b4083a76b171c39d302 --- /dev/null +++ b/shared/package-files/28/2852b813a11eff3679da4f616f14ba9cc14da38d5ab2ea29a6216c256f0f1842/test_ipc.py @@ -0,0 +1,1431 @@ +# 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. + +from collections import UserList +import datetime +import io +import pathlib +import pytest +import random +import socket +import threading +import weakref + +try: + import numpy as np +except ImportError: + np = None + +import pyarrow as pa +from pyarrow.tests.util import changed_environ, invoke_script + + +try: + from pandas.testing import assert_frame_equal + import pandas as pd +except ImportError: + pass + + +class IpcFixture: + write_stats = None + + def __init__(self, sink_factory=lambda: io.BytesIO()): + self._sink_factory = sink_factory + self.sink = self.get_sink() + + def get_sink(self): + return self._sink_factory() + + def get_source(self): + return self.sink.getvalue() + + def write_batches(self, num_batches=5, as_table=False): + nrows = 5 + schema = pa.schema([('one', pa.float64()), ('two', pa.utf8())]) + + writer = self._get_writer(self.sink, schema) + + batches = [] + for i in range(num_batches): + batch = pa.record_batch( + [[random.random() for _ in range(nrows)], + ['foo', None, 'bar', 'bazbaz', 'qux']], + schema=schema) + batches.append(batch) + + if as_table: + table = pa.Table.from_batches(batches) + writer.write_table(table) + else: + for batch in batches: + writer.write_batch(batch) + + self.write_stats = writer.stats + writer.close() + return batches + + +class FileFormatFixture(IpcFixture): + + is_file = True + options = None + + def _get_writer(self, sink, schema): + return pa.ipc.new_file(sink, schema, options=self.options) + + def _check_roundtrip(self, as_table=False): + batches = self.write_batches(as_table=as_table) + file_contents = pa.BufferReader(self.get_source()) + + reader = pa.ipc.open_file(file_contents) + + assert reader.num_record_batches == len(batches) + + for i, batch in enumerate(batches): + # it works. Must convert back to DataFrame + batch = reader.get_batch(i) + assert batches[i].equals(batch) + assert reader.schema.equals(batches[0].schema) + + assert isinstance(reader.stats, pa.ipc.ReadStats) + assert isinstance(self.write_stats, pa.ipc.WriteStats) + assert tuple(reader.stats) == tuple(self.write_stats) + + +class StreamFormatFixture(IpcFixture): + + # ARROW-6474, for testing writing old IPC protocol with 4-byte prefix + use_legacy_ipc_format = False + # ARROW-9395, for testing writing old metadata version + options = None + is_file = False + + def _get_writer(self, sink, schema): + return pa.ipc.new_stream( + sink, + schema, + options=self.options, + ) + + +class MessageFixture(IpcFixture): + + def _get_writer(self, sink, schema): + return pa.RecordBatchStreamWriter(sink, schema) + + +@pytest.fixture +def ipc_fixture(): + return IpcFixture() + + +@pytest.fixture +def file_fixture(): + return FileFormatFixture() + + +@pytest.fixture +def stream_fixture(): + return StreamFormatFixture() + + +@pytest.fixture(params=[ + pytest.param( + 'file_fixture', + id='File Format' + ), + pytest.param( + 'stream_fixture', + id='Stream Format' + ) +]) +def format_fixture(request): + return request.getfixturevalue(request.param) + + +def test_empty_file(): + buf = b'' + with pytest.raises(pa.ArrowInvalid): + pa.ipc.open_file(pa.BufferReader(buf)) + + +def test_file_simple_roundtrip(file_fixture): + file_fixture._check_roundtrip(as_table=False) + + +def test_file_write_table(file_fixture): + file_fixture._check_roundtrip(as_table=True) + + +@pytest.mark.parametrize("sink_factory", [ + lambda: io.BytesIO(), + lambda: pa.BufferOutputStream() +]) +def test_file_read_all(sink_factory): + fixture = FileFormatFixture(sink_factory) + + batches = fixture.write_batches() + file_contents = pa.BufferReader(fixture.get_source()) + + reader = pa.ipc.open_file(file_contents) + + result = reader.read_all() + expected = pa.Table.from_batches(batches) + assert result.equals(expected) + + +def test_open_file_from_buffer(file_fixture): + # ARROW-2859; APIs accept the buffer protocol + file_fixture.write_batches() + source = file_fixture.get_source() + + reader1 = pa.ipc.open_file(source) + reader2 = pa.ipc.open_file(pa.BufferReader(source)) + reader3 = pa.RecordBatchFileReader(source) + + result1 = reader1.read_all() + result2 = reader2.read_all() + result3 = reader3.read_all() + + assert result1.equals(result2) + assert result1.equals(result3) + + st1 = reader1.stats + assert st1.num_messages == 6 + assert st1.num_record_batches == 5 + assert reader2.stats == st1 + assert reader3.stats == st1 + + +@pytest.mark.pandas +def test_file_read_pandas(file_fixture): + frames = [batch.to_pandas() for batch in file_fixture.write_batches()] + + file_contents = pa.BufferReader(file_fixture.get_source()) + reader = pa.ipc.open_file(file_contents) + result = reader.read_pandas() + + expected = pd.concat(frames).reset_index(drop=True) + assert_frame_equal(result, expected) + + +def test_file_pathlib(file_fixture, tmpdir): + file_fixture.write_batches() + source = file_fixture.get_source() + + path = tmpdir.join('file.arrow').strpath + with open(path, 'wb') as f: + f.write(source) + + t1 = pa.ipc.open_file(pathlib.Path(path)).read_all() + t2 = pa.ipc.open_file(pa.OSFile(path)).read_all() + + assert t1.equals(t2) + + +def test_empty_stream(): + buf = io.BytesIO(b'') + with pytest.raises(pa.ArrowInvalid): + pa.ipc.open_stream(buf) + + +@pytest.mark.pandas +@pytest.mark.processes +def test_read_year_month_nano_interval(tmpdir): + """ARROW-15783: Verify to_pandas works for interval types. + + Interval types require static structures to be enabled. This test verifies + that they are when no other library functions are invoked. + """ + mdn_interval_type = pa.month_day_nano_interval() + schema = pa.schema([pa.field('nums', mdn_interval_type)]) + + path = tmpdir.join('file.arrow').strpath + with pa.OSFile(path, 'wb') as sink: + with pa.ipc.new_file(sink, schema) as writer: + interval_array = pa.array([(1, 2, 3)], type=mdn_interval_type) + batch = pa.record_batch([interval_array], schema) + writer.write(batch) + invoke_script('read_record_batch.py', path) + + +@pytest.mark.pandas +def test_stream_categorical_roundtrip(stream_fixture): + df = pd.DataFrame({ + 'one': np.random.randn(5), + 'two': pd.Categorical(['foo', np.nan, 'bar', 'foo', 'foo'], + categories=['foo', 'bar'], + ordered=True) + }) + batch = pa.RecordBatch.from_pandas(df) + with stream_fixture._get_writer(stream_fixture.sink, batch.schema) as wr: + wr.write_batch(batch) + + table = (pa.ipc.open_stream(pa.BufferReader(stream_fixture.get_source())) + .read_all()) + assert_frame_equal(table.to_pandas(), df) + + +def test_open_stream_from_buffer(stream_fixture): + # ARROW-2859 + stream_fixture.write_batches() + source = stream_fixture.get_source() + + reader1 = pa.ipc.open_stream(source) + reader2 = pa.ipc.open_stream(pa.BufferReader(source)) + reader3 = pa.RecordBatchStreamReader(source) + + result1 = reader1.read_all() + result2 = reader2.read_all() + result3 = reader3.read_all() + + assert result1.equals(result2) + assert result1.equals(result3) + + st1 = reader1.stats + assert st1.num_messages == 6 + assert st1.num_record_batches == 5 + assert reader2.stats == st1 + assert reader3.stats == st1 + + assert tuple(st1) == tuple(stream_fixture.write_stats) + + +@pytest.mark.parametrize('options', [ + pa.ipc.IpcReadOptions(), + pa.ipc.IpcReadOptions(use_threads=False), +]) +def test_open_stream_options(stream_fixture, options): + stream_fixture.write_batches() + source = stream_fixture.get_source() + + reader = pa.ipc.open_stream(source, options=options) + + reader.read_all() + st = reader.stats + assert st.num_messages == 6 + assert st.num_record_batches == 5 + + assert tuple(st) == tuple(stream_fixture.write_stats) + + +def test_open_stream_with_wrong_options(stream_fixture): + stream_fixture.write_batches() + source = stream_fixture.get_source() + + with pytest.raises(TypeError): + pa.ipc.open_stream(source, options=True) + + +@pytest.mark.parametrize('options', [ + pa.ipc.IpcReadOptions(), + pa.ipc.IpcReadOptions(use_threads=False), +]) +def test_open_file_options(file_fixture, options): + file_fixture.write_batches() + source = file_fixture.get_source() + + reader = pa.ipc.open_file(source, options=options) + + reader.read_all() + + st = reader.stats + assert st.num_messages == 6 + assert st.num_record_batches == 5 + + +def test_open_file_with_wrong_options(file_fixture): + file_fixture.write_batches() + source = file_fixture.get_source() + + with pytest.raises(TypeError): + pa.ipc.open_file(source, options=True) + + +@pytest.mark.pandas +def test_stream_write_dispatch(stream_fixture): + # ARROW-1616 + df = pd.DataFrame({ + 'one': np.random.randn(5), + 'two': pd.Categorical(['foo', np.nan, 'bar', 'foo', 'foo'], + categories=['foo', 'bar'], + ordered=True) + }) + table = pa.Table.from_pandas(df, preserve_index=False) + batch = pa.RecordBatch.from_pandas(df, preserve_index=False) + with stream_fixture._get_writer(stream_fixture.sink, table.schema) as wr: + wr.write(table) + wr.write(batch) + + table = (pa.ipc.open_stream(pa.BufferReader(stream_fixture.get_source())) + .read_all()) + assert_frame_equal(table.to_pandas(), + pd.concat([df, df], ignore_index=True)) + + +@pytest.mark.pandas +def test_stream_write_table_batches(stream_fixture): + # ARROW-504 + df = pd.DataFrame({ + 'one': np.random.randn(20), + }) + + b1 = pa.RecordBatch.from_pandas(df[:10], preserve_index=False) + b2 = pa.RecordBatch.from_pandas(df, preserve_index=False) + + table = pa.Table.from_batches([b1, b2, b1]) + + with stream_fixture._get_writer(stream_fixture.sink, table.schema) as wr: + wr.write_table(table, max_chunksize=15) + + batches = list(pa.ipc.open_stream(stream_fixture.get_source())) + + assert list(map(len, batches)) == [10, 15, 5, 10] + result_table = pa.Table.from_batches(batches) + assert_frame_equal(result_table.to_pandas(), + pd.concat([df[:10], df, df[:10]], + ignore_index=True)) + + +def test_stream_simple_roundtrip(stream_fixture): + batches = stream_fixture.write_batches() + file_contents = pa.BufferReader(stream_fixture.get_source()) + reader = pa.ipc.open_stream(file_contents) + + assert reader.schema.equals(batches[0].schema) + + total = 0 + for i, next_batch in enumerate(reader): + assert next_batch.equals(batches[i]) + total += 1 + + assert total == len(batches) + + with pytest.raises(StopIteration): + reader.read_next_batch() + + +@pytest.mark.zstd +def test_compression_roundtrip(): + sink = io.BytesIO() + values = [random.randint(0, 3) for _ in range(10000)] + table = pa.Table.from_arrays([values], names=["values"]) + + options = pa.ipc.IpcWriteOptions(compression='zstd') + with pa.ipc.RecordBatchFileWriter( + sink, table.schema, options=options) as writer: + writer.write_table(table) + len1 = len(sink.getvalue()) + + sink2 = io.BytesIO() + codec = pa.Codec('zstd', compression_level=5) + options = pa.ipc.IpcWriteOptions(compression=codec) + with pa.ipc.RecordBatchFileWriter( + sink2, table.schema, options=options) as writer: + writer.write_table(table) + len2 = len(sink2.getvalue()) + + # In theory len2 should be less than len1 but for this test we just want + # to ensure compression_level is being correctly passed down to the C++ + # layer so we don't really care if it makes it worse or better + assert len2 != len1 + + t1 = pa.ipc.open_file(sink).read_all() + t2 = pa.ipc.open_file(sink2).read_all() + + assert t1 == t2 + + +def test_write_options(): + options = pa.ipc.IpcWriteOptions() + assert options.allow_64bit is False + assert options.use_legacy_format is False + assert options.metadata_version == pa.ipc.MetadataVersion.V5 + + options.allow_64bit = True + assert options.allow_64bit is True + + options.use_legacy_format = True + assert options.use_legacy_format is True + + options.metadata_version = pa.ipc.MetadataVersion.V4 + assert options.metadata_version == pa.ipc.MetadataVersion.V4 + for value in ('V5', 42): + with pytest.raises((TypeError, ValueError)): + options.metadata_version = value + + assert options.compression is None + for value in ['lz4', 'zstd']: + if pa.Codec.is_available(value): + options.compression = value + assert options.compression == value + options.compression = value.upper() + assert options.compression == value + options.compression = None + assert options.compression is None + + with pytest.raises(TypeError): + options.compression = 0 + + assert options.use_threads is True + options.use_threads = False + assert options.use_threads is False + + if pa.Codec.is_available('lz4'): + options = pa.ipc.IpcWriteOptions( + metadata_version=pa.ipc.MetadataVersion.V4, + allow_64bit=True, + use_legacy_format=True, + compression='lz4', + use_threads=False) + assert options.metadata_version == pa.ipc.MetadataVersion.V4 + assert options.allow_64bit is True + assert options.use_legacy_format is True + assert options.compression == 'lz4' + assert options.use_threads is False + + +@pytest.mark.parametrize('options', [ + pa.ipc.IpcWriteOptions(), + pa.ipc.IpcWriteOptions(allow_64bit=True), + pa.ipc.IpcWriteOptions(use_legacy_format=True), + pa.ipc.IpcWriteOptions(metadata_version=pa.ipc.MetadataVersion.V4), + pa.ipc.IpcWriteOptions(use_legacy_format=True, + metadata_version=pa.ipc.MetadataVersion.V4), +]) +def test_stream_options_roundtrip(stream_fixture, options): + stream_fixture.options = options + batches = stream_fixture.write_batches() + file_contents = pa.BufferReader(stream_fixture.get_source()) + + message = pa.ipc.read_message(stream_fixture.get_source()) + assert message.metadata_version == options.metadata_version + + reader = pa.ipc.open_stream(file_contents) + + assert reader.schema.equals(batches[0].schema) + + total = 0 + for i, next_batch in enumerate(reader): + assert next_batch.equals(batches[i]) + total += 1 + + assert total == len(batches) + + with pytest.raises(StopIteration): + reader.read_next_batch() + + +def test_read_options(): + options = pa.ipc.IpcReadOptions() + assert options.use_threads is True + assert options.ensure_native_endian is True + assert options.ensure_alignment == pa.ipc.Alignment.Any + assert options.included_fields == [] + + options.ensure_native_endian = False + assert options.ensure_native_endian is False + + options.ensure_alignment = pa.ipc.Alignment.DataTypeSpecific + assert options.ensure_alignment == pa.ipc.Alignment.DataTypeSpecific + options.ensure_alignment = pa.ipc.Alignment.At64Byte + assert options.ensure_alignment == pa.ipc.Alignment.At64Byte + + options.use_threads = False + assert options.use_threads is False + + options.included_fields = [0, 1] + assert options.included_fields == [0, 1] + + with pytest.raises(TypeError): + options.included_fields = None + + options = pa.ipc.IpcReadOptions( + use_threads=False, ensure_native_endian=False, + ensure_alignment=pa.ipc.Alignment.DataTypeSpecific, included_fields=[1] + ) + assert options.use_threads is False + assert options.ensure_native_endian is False + assert options.ensure_alignment == pa.ipc.Alignment.DataTypeSpecific + assert options.included_fields == [1] + + +def test_read_options_included_fields(stream_fixture): + options1 = pa.ipc.IpcReadOptions() + options2 = pa.ipc.IpcReadOptions(included_fields=[1]) + table = pa.Table.from_arrays([pa.array(['foo', 'bar', 'baz', 'qux']), + pa.array([1, 2, 3, 4])], + names=['a', 'b']) + with stream_fixture._get_writer(stream_fixture.sink, table.schema) as wr: + wr.write_table(table) + source = stream_fixture.get_source() + + reader1 = pa.ipc.open_stream(source, options=options1) + reader2 = pa.ipc.open_stream( + source, options=options2, memory_pool=pa.system_memory_pool()) + + result1 = reader1.read_all() + result2 = reader2.read_all() + + assert result1.num_columns == 2 + assert result2.num_columns == 1 + + expected = pa.Table.from_arrays([pa.array([1, 2, 3, 4])], names=["b"]) + assert result2 == expected + assert result1 == table + + +def test_dictionary_delta(format_fixture): + ty = pa.dictionary(pa.int8(), pa.utf8()) + data = [["foo", "foo", None], + ["foo", "bar", "foo"], # potential delta + ["foo", "bar"], # nothing new + ["foo", None, "bar", "quux"], # potential delta + ["bar", "quux"], # replacement + ] + batches = [ + pa.RecordBatch.from_arrays([pa.array(v, type=ty)], names=['dicts']) + for v in data] + batches_delta_only = batches[:4] + schema = batches[0].schema + + def write_batches(batches, as_table=False): + with format_fixture._get_writer(pa.MockOutputStream(), + schema) as writer: + if as_table: + table = pa.Table.from_batches(batches) + writer.write_table(table) + else: + for batch in batches: + writer.write_batch(batch) + return writer.stats + + if format_fixture.is_file: + # File format cannot handle replacement + with pytest.raises(pa.ArrowInvalid): + write_batches(batches) + # File format cannot handle delta if emit_deltas + # is not provided + with pytest.raises(pa.ArrowInvalid): + write_batches(batches_delta_only) + else: + st = write_batches(batches) + assert st.num_record_batches == 5 + assert st.num_dictionary_batches == 4 + assert st.num_replaced_dictionaries == 3 + assert st.num_dictionary_deltas == 0 + + format_fixture.use_legacy_ipc_format = None + format_fixture.options = pa.ipc.IpcWriteOptions( + emit_dictionary_deltas=True) + if format_fixture.is_file: + # File format cannot handle replacement + with pytest.raises(pa.ArrowInvalid): + write_batches(batches) + else: + st = write_batches(batches) + assert st.num_record_batches == 5 + assert st.num_dictionary_batches == 4 + assert st.num_replaced_dictionaries == 1 + assert st.num_dictionary_deltas == 2 + + st = write_batches(batches_delta_only) + assert st.num_record_batches == 4 + assert st.num_dictionary_batches == 3 + assert st.num_replaced_dictionaries == 0 + assert st.num_dictionary_deltas == 2 + + format_fixture.options = pa.ipc.IpcWriteOptions( + unify_dictionaries=True + ) + st = write_batches(batches, as_table=True) + assert st.num_record_batches == 5 + if format_fixture.is_file: + assert st.num_dictionary_batches == 1 + assert st.num_replaced_dictionaries == 0 + assert st.num_dictionary_deltas == 0 + else: + assert st.num_dictionary_batches == 4 + assert st.num_replaced_dictionaries == 3 + assert st.num_dictionary_deltas == 0 + + +def test_envvar_set_legacy_ipc_format(): + schema = pa.schema([pa.field('foo', pa.int32())]) + + writer = pa.ipc.new_stream(pa.BufferOutputStream(), schema) + assert not writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V5 + writer = pa.ipc.new_file(pa.BufferOutputStream(), schema) + assert not writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V5 + + with changed_environ('ARROW_PRE_0_15_IPC_FORMAT', '1'): + writer = pa.ipc.new_stream(pa.BufferOutputStream(), schema) + assert writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V5 + writer = pa.ipc.new_file(pa.BufferOutputStream(), schema) + assert writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V5 + + with changed_environ('ARROW_PRE_1_0_METADATA_VERSION', '1'): + writer = pa.ipc.new_stream(pa.BufferOutputStream(), schema) + assert not writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V4 + writer = pa.ipc.new_file(pa.BufferOutputStream(), schema) + assert not writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V4 + + with changed_environ('ARROW_PRE_1_0_METADATA_VERSION', '1'): + with changed_environ('ARROW_PRE_0_15_IPC_FORMAT', '1'): + writer = pa.ipc.new_stream(pa.BufferOutputStream(), schema) + assert writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V4 + writer = pa.ipc.new_file(pa.BufferOutputStream(), schema) + assert writer._use_legacy_format + assert writer._metadata_version == pa.ipc.MetadataVersion.V4 + + +def test_stream_read_all(stream_fixture): + batches = stream_fixture.write_batches() + file_contents = pa.BufferReader(stream_fixture.get_source()) + reader = pa.ipc.open_stream(file_contents) + + result = reader.read_all() + expected = pa.Table.from_batches(batches) + assert result.equals(expected) + + +@pytest.mark.pandas +def test_stream_read_pandas(stream_fixture): + frames = [batch.to_pandas() for batch in stream_fixture.write_batches()] + file_contents = stream_fixture.get_source() + reader = pa.ipc.open_stream(file_contents) + result = reader.read_pandas() + + expected = pd.concat(frames).reset_index(drop=True) + assert_frame_equal(result, expected) + + +@pytest.fixture +def example_messages(stream_fixture): + batches = stream_fixture.write_batches() + file_contents = stream_fixture.get_source() + buf_reader = pa.BufferReader(file_contents) + reader = pa.MessageReader.open_stream(buf_reader) + return batches, list(reader) + + +def test_message_ctors_no_segfault(): + with pytest.raises(TypeError): + repr(pa.Message()) + + with pytest.raises(TypeError): + repr(pa.MessageReader()) + + +def test_message_reader(example_messages): + _, messages = example_messages + + assert len(messages) == 6 + assert messages[0].type == 'schema' + assert isinstance(messages[0].metadata, pa.Buffer) + assert isinstance(messages[0].body, pa.Buffer) + assert messages[0].metadata_version == pa.MetadataVersion.V5 + + for msg in messages[1:]: + assert msg.type == 'record batch' + assert isinstance(msg.metadata, pa.Buffer) + assert isinstance(msg.body, pa.Buffer) + assert msg.metadata_version == pa.MetadataVersion.V5 + + +def test_message_serialize_read_message(example_messages): + _, messages = example_messages + + msg = messages[0] + buf = msg.serialize() + reader = pa.BufferReader(buf.to_pybytes() * 2) + + restored = pa.ipc.read_message(buf) + restored2 = pa.ipc.read_message(reader) + restored3 = pa.ipc.read_message(buf.to_pybytes()) + restored4 = pa.ipc.read_message(reader) + + assert msg.equals(restored) + assert msg.equals(restored2) + assert msg.equals(restored3) + assert msg.equals(restored4) + + with pytest.raises(pa.ArrowInvalid, match="Corrupted message"): + pa.ipc.read_message(pa.BufferReader(b'ab')) + + with pytest.raises(EOFError): + pa.ipc.read_message(reader) + + +def test_message_repr_shows_actual_values(example_messages): + _, messages = example_messages + + for msg in messages: + s = str(msg) + + assert '{self.type}' not in s + assert '{metadata_len}' not in s + assert '{body_len}' not in s + assert f'type: {msg.type}' in s + + +@pytest.mark.gzip +def test_message_read_from_compressed(example_messages): + # Part of ARROW-5910 + _, messages = example_messages + for message in messages: + raw_out = pa.BufferOutputStream() + with pa.output_stream(raw_out, compression='gzip') as compressed_out: + message.serialize_to(compressed_out) + + compressed_buf = raw_out.getvalue() + + result = pa.ipc.read_message(pa.input_stream(compressed_buf, + compression='gzip')) + assert result.equals(message) + + +def test_message_read_schema(example_messages): + batches, messages = example_messages + schema = pa.ipc.read_schema(messages[0]) + assert schema.equals(batches[1].schema) + + +def test_message_read_record_batch(example_messages): + batches, messages = example_messages + + for batch, message in zip(batches, messages[1:]): + read_batch = pa.ipc.read_record_batch(message, batch.schema) + assert read_batch.equals(batch) + + +def test_read_record_batch_on_stream_error_message(): + # ARROW-5374 + batch = pa.record_batch([pa.array([b"foo"], type=pa.utf8())], + names=['strs']) + stream = pa.BufferOutputStream() + with pa.ipc.new_stream(stream, batch.schema) as writer: + writer.write_batch(batch) + buf = stream.getvalue() + with pytest.raises(IOError, + match="type record batch but got schema"): + pa.ipc.read_record_batch(buf, batch.schema) + + +# ---------------------------------------------------------------------- +# Socket streaming testa + + +class StreamReaderServer(threading.Thread): + + def init(self, do_read_all): + self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._sock.bind(('127.0.0.1', 0)) + self._sock.listen(1) + host, port = self._sock.getsockname() + self._do_read_all = do_read_all + self._schema = None + self._batches = [] + self._table = None + return port + + def run(self): + connection, client_address = self._sock.accept() + try: + source = connection.makefile(mode='rb') + reader = pa.ipc.open_stream(source) + self._schema = reader.schema + if self._do_read_all: + self._table = reader.read_all() + else: + for i, batch in enumerate(reader): + self._batches.append(batch) + finally: + connection.close() + self._sock.close() + + def get_result(self): + return (self._schema, self._table if self._do_read_all + else self._batches) + + +class SocketStreamFixture(IpcFixture): + + def __init__(self): + # XXX(wesm): test will decide when to start socket server. This should + # probably be refactored + pass + + def start_server(self, do_read_all): + self._server = StreamReaderServer() + port = self._server.init(do_read_all) + self._server.start() + self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._sock.connect(('127.0.0.1', port)) + self.sink = self.get_sink() + + def stop_and_get_result(self): + import struct + self.sink.write(struct.pack('Q', 0)) + self.sink.flush() + self._sock.close() + self._server.join() + return self._server.get_result() + + def get_sink(self): + return self._sock.makefile(mode='wb') + + def _get_writer(self, sink, schema): + return pa.RecordBatchStreamWriter(sink, schema) + + +@pytest.fixture +def socket_fixture(): + return SocketStreamFixture() + + +@pytest.mark.sockets +def test_socket_simple_roundtrip(socket_fixture): + socket_fixture.start_server(do_read_all=False) + writer_batches = socket_fixture.write_batches() + reader_schema, reader_batches = socket_fixture.stop_and_get_result() + + assert reader_schema.equals(writer_batches[0].schema) + assert len(reader_batches) == len(writer_batches) + for i, batch in enumerate(writer_batches): + assert reader_batches[i].equals(batch) + + +@pytest.mark.sockets +def test_socket_read_all(socket_fixture): + socket_fixture.start_server(do_read_all=True) + writer_batches = socket_fixture.write_batches() + _, result = socket_fixture.stop_and_get_result() + + expected = pa.Table.from_batches(writer_batches) + assert result.equals(expected) + + +# ---------------------------------------------------------------------- +# Miscellaneous IPC tests + +@pytest.mark.pandas +def test_ipc_file_stream_has_eos(): + # ARROW-5395 + df = pd.DataFrame({'foo': [1.5]}) + batch = pa.RecordBatch.from_pandas(df) + sink = pa.BufferOutputStream() + write_file(batch, sink) + buffer = sink.getvalue() + + # skip the file magic + reader = pa.ipc.open_stream(buffer[8:]) + + # will fail if encounters footer data instead of eos + rdf = reader.read_pandas() + + assert_frame_equal(df, rdf) + + +@pytest.mark.pandas +def test_ipc_zero_copy_numpy(): + df = pd.DataFrame({'foo': [1.5]}) + + batch = pa.RecordBatch.from_pandas(df) + sink = pa.BufferOutputStream() + write_file(batch, sink) + buffer = sink.getvalue() + reader = pa.BufferReader(buffer) + + batches = read_file(reader) + + data = batches[0].to_pandas() + rdf = pd.DataFrame(data) + assert_frame_equal(df, rdf) + + +@pytest.mark.pandas +@pytest.mark.parametrize("ipc_type", ["stream", "file"]) +def test_batches_with_custom_metadata_roundtrip(ipc_type): + df = pd.DataFrame({'foo': [1.5]}) + + batch = pa.RecordBatch.from_pandas(df) + sink = pa.BufferOutputStream() + + batch_count = 2 + file_factory = {"stream": pa.ipc.new_stream, + "file": pa.ipc.new_file}[ipc_type] + + with file_factory(sink, batch.schema) as writer: + for i in range(batch_count): + writer.write_batch(batch, custom_metadata={"batch_id": str(i)}) + # write a batch without custom metadata + writer.write_batch(batch) + + buffer = sink.getvalue() + + if ipc_type == "stream": + with pa.ipc.open_stream(buffer) as reader: + batch_with_metas = list(reader.iter_batches_with_custom_metadata()) + else: + with pa.ipc.open_file(buffer) as reader: + batch_with_metas = [reader.get_batch_with_custom_metadata(i) + for i in range(reader.num_record_batches)] + + for i in range(batch_count): + assert batch_with_metas[i].batch.num_rows == 1 + assert isinstance( + batch_with_metas[i].custom_metadata, pa.KeyValueMetadata) + assert batch_with_metas[i].custom_metadata == {"batch_id": str(i)} + + # the last batch has no custom metadata + assert batch_with_metas[batch_count].batch.num_rows == 1 + assert batch_with_metas[batch_count].custom_metadata is None + + +def test_ipc_stream_no_batches(): + # ARROW-2307 + table = pa.Table.from_arrays([pa.array([1, 2, 3, 4]), + pa.array(['foo', 'bar', 'baz', 'qux'])], + names=['a', 'b']) + + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, table.schema): + pass + + source = sink.getvalue() + with pa.ipc.open_stream(source) as reader: + result = reader.read_all() + + assert result.schema.equals(table.schema) + assert len(result) == 0 + + +@pytest.mark.pandas +def test_get_record_batch_size(): + N = 10 + itemsize = 8 + df = pd.DataFrame({'foo': np.random.randn(N)}) + + batch = pa.RecordBatch.from_pandas(df) + assert pa.ipc.get_record_batch_size(batch) > (N * itemsize) + + +@pytest.mark.pandas +def _check_serialize_pandas_round_trip(df, use_threads=False): + buf = pa.serialize_pandas(df, nthreads=2 if use_threads else 1) + result = pa.deserialize_pandas(buf, use_threads=use_threads) + assert_frame_equal(result, df) + + +@pytest.mark.pandas +def test_pandas_serialize_round_trip(): + index = pd.Index([1, 2, 3], name='my_index') + columns = ['foo', 'bar'] + df = pd.DataFrame( + {'foo': [1.5, 1.6, 1.7], 'bar': list('abc')}, + index=index, columns=columns + ) + _check_serialize_pandas_round_trip(df) + + +@pytest.mark.pandas +def test_pandas_serialize_round_trip_nthreads(): + index = pd.Index([1, 2, 3], name='my_index') + columns = ['foo', 'bar'] + df = pd.DataFrame( + {'foo': [1.5, 1.6, 1.7], 'bar': list('abc')}, + index=index, columns=columns + ) + _check_serialize_pandas_round_trip(df, use_threads=True) + + +@pytest.mark.pandas +def test_pandas_serialize_round_trip_multi_index(): + index1 = pd.Index([1, 2, 3], name='level_1') + index2 = pd.Index(list('def'), name=None) + index = pd.MultiIndex.from_arrays([index1, index2]) + + columns = ['foo', 'bar'] + df = pd.DataFrame( + {'foo': [1.5, 1.6, 1.7], 'bar': list('abc')}, + index=index, + columns=columns, + ) + _check_serialize_pandas_round_trip(df) + + +@pytest.mark.pandas +def test_serialize_pandas_empty_dataframe(): + df = pd.DataFrame() + _check_serialize_pandas_round_trip(df) + + +@pytest.mark.pandas +def test_pandas_serialize_round_trip_not_string_columns(): + df = pd.DataFrame(list(zip([1.5, 1.6, 1.7], 'abc'))) + buf = pa.serialize_pandas(df) + result = pa.deserialize_pandas(buf) + assert_frame_equal(result, df) + + +@pytest.mark.pandas +def test_serialize_pandas_no_preserve_index(): + df = pd.DataFrame({'a': [1, 2, 3]}, index=[1, 2, 3]) + expected = pd.DataFrame({'a': [1, 2, 3]}) + + buf = pa.serialize_pandas(df, preserve_index=False) + result = pa.deserialize_pandas(buf) + assert_frame_equal(result, expected) + + buf = pa.serialize_pandas(df, preserve_index=True) + result = pa.deserialize_pandas(buf) + assert_frame_equal(result, df) + + +@pytest.mark.pandas +def test_schema_batch_serialize_methods(): + nrows = 5 + df = pd.DataFrame({ + 'one': np.random.randn(nrows), + 'two': ['foo', np.nan, 'bar', 'bazbaz', 'qux']}) + batch = pa.RecordBatch.from_pandas(df) + + s_schema = batch.schema.serialize() + s_batch = batch.serialize() + + recons_schema = pa.ipc.read_schema(s_schema) + recons_batch = pa.ipc.read_record_batch(s_batch, recons_schema) + assert recons_batch.equals(batch) + + +def test_schema_serialization_with_metadata(): + field_metadata = {b'foo': b'bar', b'kind': b'field'} + schema_metadata = {b'foo': b'bar', b'kind': b'schema'} + + f0 = pa.field('a', pa.int8()) + f1 = pa.field('b', pa.string(), metadata=field_metadata) + + schema = pa.schema([f0, f1], metadata=schema_metadata) + + s_schema = schema.serialize() + recons_schema = pa.ipc.read_schema(s_schema) + + assert recons_schema.equals(schema) + assert recons_schema.metadata == schema_metadata + assert recons_schema[0].metadata is None + assert recons_schema[1].metadata == field_metadata + + +def write_file(batch, sink): + with pa.ipc.new_file(sink, batch.schema) as writer: + writer.write_batch(batch) + + +def read_file(source): + with pa.ipc.open_file(source) as reader: + return [reader.get_batch(i) for i in range(reader.num_record_batches)] + + +def test_write_empty_ipc_file(): + # ARROW-3894: IPC file was not being properly initialized when no record + # batches are being written + schema = pa.schema([('field', pa.int64())]) + + sink = pa.BufferOutputStream() + with pa.ipc.new_file(sink, schema): + pass + + buf = sink.getvalue() + with pa.RecordBatchFileReader(pa.BufferReader(buf)) as reader: + table = reader.read_all() + assert len(table) == 0 + assert table.schema.equals(schema) + + +def test_py_record_batch_reader(): + def make_schema(): + return pa.schema([('field', pa.int64())]) + + def make_batches(): + schema = make_schema() + batch1 = pa.record_batch([[1, 2, 3]], schema=schema) + batch2 = pa.record_batch([[4, 5]], schema=schema) + return [batch1, batch2] + + # With iterable + batches = UserList(make_batches()) # weakrefable + wr = weakref.ref(batches) + + with pa.RecordBatchReader.from_batches(make_schema(), + batches) as reader: + batches = None + assert wr() is not None + assert list(reader) == make_batches() + assert wr() is None + + # With iterator + batches = iter(UserList(make_batches())) # weakrefable + wr = weakref.ref(batches) + + with pa.RecordBatchReader.from_batches(make_schema(), + batches) as reader: + batches = None + assert wr() is not None + assert list(reader) == make_batches() + assert wr() is None + + # ensure we get proper error when not passing a schema + # (https://issues.apache.org/jira/browse/ARROW-18229) + batches = make_batches() + with pytest.raises(TypeError): + reader = pa.RecordBatchReader.from_batches( + [('field', pa.int64())], batches) + pass + + with pytest.raises(TypeError): + reader = pa.RecordBatchReader.from_batches(None, batches) + pass + + +def test_record_batch_reader_from_arrow_stream(): + + class StreamWrapper: + def __init__(self, batches): + self.batches = batches + + def __arrow_c_stream__(self, requested_schema=None): + reader = pa.RecordBatchReader.from_batches( + self.batches[0].schema, self.batches) + return reader.__arrow_c_stream__(requested_schema) + + data = [ + pa.record_batch([pa.array([1, 2, 3], type=pa.int64())], names=['a']), + pa.record_batch([pa.array([4, 5, 6], type=pa.int64())], names=['a']) + ] + wrapper = StreamWrapper(data) + + # Can roundtrip a pyarrow stream-like object + expected = pa.Table.from_batches(data) + reader = pa.RecordBatchReader.from_stream(expected) + assert reader.read_all() == expected + + # Can roundtrip through the wrapper. + reader = pa.RecordBatchReader.from_stream(wrapper) + assert reader.read_all() == expected + + # Passing schema works if already that schema + reader = pa.RecordBatchReader.from_stream(wrapper, schema=data[0].schema) + assert reader.read_all() == expected + + # Passing a different but castable schema works + good_schema = pa.schema([pa.field("a", pa.int32())]) + reader = pa.RecordBatchReader.from_stream(wrapper, schema=good_schema) + assert reader.read_all() == expected.cast(good_schema) + + # If schema doesn't match, raises TypeError + with pytest.raises(pa.lib.ArrowTypeError, match='Field 0 cannot be cast'): + pa.RecordBatchReader.from_stream( + wrapper, schema=pa.schema([pa.field('a', pa.list_(pa.int32()))]) + ) + + # Proper type errors for wrong input + with pytest.raises(TypeError): + pa.RecordBatchReader.from_stream(data[0]['a']) + + with pytest.raises(TypeError): + pa.RecordBatchReader.from_stream(expected, schema=data[0]) + + +def test_record_batch_reader_cast(): + schema_src = pa.schema([pa.field('a', pa.int64())]) + data = [ + pa.record_batch([pa.array([1, 2, 3], type=pa.int64())], names=['a']), + pa.record_batch([pa.array([4, 5, 6], type=pa.int64())], names=['a']), + ] + table_src = pa.Table.from_batches(data) + + # Cast to same type should always work + reader = pa.RecordBatchReader.from_batches(schema_src, data) + assert reader.cast(schema_src).read_all() == table_src + + # Check non-trivial cast + schema_dst = pa.schema([pa.field('a', pa.int32())]) + reader = pa.RecordBatchReader.from_batches(schema_src, data) + assert reader.cast(schema_dst).read_all() == table_src.cast(schema_dst) + + # Check error for field name/length mismatch + reader = pa.RecordBatchReader.from_batches(schema_src, data) + with pytest.raises(ValueError, match="Target schema's field names"): + reader.cast(pa.schema([])) + + # Check error for impossible cast in call to .cast() + reader = pa.RecordBatchReader.from_batches(schema_src, data) + with pytest.raises(pa.lib.ArrowTypeError, match='Field 0 cannot be cast'): + reader.cast(pa.schema([pa.field('a', pa.list_(pa.int32()))])) + + # Cast to same type should always work (also for types without a T->T cast function) + # (https://github.com/apache/arrow/issues/41884) + schema_src = pa.schema([pa.field('a', pa.date32())]) + arr = pa.array([datetime.date(2024, 6, 11)], type=pa.date32()) + data = [pa.record_batch([arr], names=['a']), pa.record_batch([arr], names=['a'])] + table_src = pa.Table.from_batches(data) + reader = pa.RecordBatchReader.from_batches(schema_src, data) + assert reader.cast(schema_src).read_all() == table_src + + +def test_record_batch_reader_cast_nulls(): + schema_src = pa.schema([pa.field('a', pa.int64())]) + data_with_nulls = [ + pa.record_batch([pa.array([1, 2, None], type=pa.int64())], names=['a']), + ] + data_without_nulls = [ + pa.record_batch([pa.array([1, 2, 3], type=pa.int64())], names=['a']), + ] + table_with_nulls = pa.Table.from_batches(data_with_nulls) + table_without_nulls = pa.Table.from_batches(data_without_nulls) + + # Cast to nullable destination should work + reader = pa.RecordBatchReader.from_batches(schema_src, data_with_nulls) + schema_dst = pa.schema([pa.field('a', pa.int32())]) + assert reader.cast(schema_dst).read_all() == table_with_nulls.cast(schema_dst) + + # Cast to non-nullable destination should work if there are no nulls + reader = pa.RecordBatchReader.from_batches(schema_src, data_without_nulls) + schema_dst = pa.schema([pa.field('a', pa.int32(), nullable=False)]) + assert reader.cast(schema_dst).read_all() == table_without_nulls.cast(schema_dst) + + # Cast to non-nullable destination should error if there are nulls + # when the batch is pulled + reader = pa.RecordBatchReader.from_batches(schema_src, data_with_nulls) + casted_reader = reader.cast(schema_dst) + with pytest.raises(pa.lib.ArrowInvalid, match="Can't cast array"): + casted_reader.read_all() + + +def test_record_batch_file_writer_with_metadata(): + # https://github.com/apache/arrow/issues/46222 + tbl = pa.table({"a": [1, 2, 3]}) + meta = {b"creator": b"test", b"version": b"0.1.0"} + sink = pa.BufferOutputStream() + + with pa.ipc.new_file(sink, tbl.schema, metadata=meta) as w: + w.write_table(tbl) + + buffer = sink.getvalue() + with pa.ipc.open_file(buffer) as r: + assert r.metadata == meta + + +def test_record_batch_file_writer_with_empty_metadata(): + # https://github.com/apache/arrow/issues/46222 + tbl = pa.table({"a": [1, 2, 3]}) + sink = pa.BufferOutputStream() + + with pa.ipc.new_file(sink, tbl.schema) as w: + w.write_table(tbl) + + buffer = sink.getvalue() + with pa.ipc.open_file(buffer) as r: + assert r.metadata is None + + +def check_ipc_options_repr(options_obj, options_args): + options = options_obj(**options_args) + repr = options.__repr__() + + for arg, val in options_args.items(): + if val is None: + continue + + value = val if not isinstance(val, str) else f"\"{val}\"" + + if arg == "ensure_alignment": + value = pa.ipc.Alignment(val).name + elif arg == "metadata_version": + value = pa.ipc.MetadataVersion(val).name + + assert f"{arg}={value}" in repr + + +@pytest.fixture +def write_options_args(request): + if request.param == "default": + return { + "allow_64bit": False, + "use_legacy_format": False, + "metadata_version": pa.ipc.MetadataVersion.V5, + "compression": None, + "use_threads": True, + "emit_dictionary_deltas": False, + "unify_dictionaries": False, + } + elif request.param == "all": + return { + "allow_64bit": True, + "use_legacy_format": True, + "metadata_version": pa.ipc.MetadataVersion.V4, + "compression": "zstd", + "use_threads": False, + "emit_dictionary_deltas": True, + "unify_dictionaries": True, + } + else: + return {} + + +@pytest.mark.zstd +@pytest.mark.parametrize( + "write_options_args", ["default", "all"], indirect=True) +def test_write_options_repr(write_options_args): + # https://github.com/apache/arrow/issues/47358 + check_ipc_options_repr(pa.ipc.IpcWriteOptions, write_options_args) + + +@pytest.fixture +def read_options_args(request): + if request.param == "default": + return { + "ensure_native_endian": True, + "ensure_alignment": pa.ipc.Alignment.Any, + "use_threads": True, + "included_fields": None, + } + elif request.param == "all": + return { + "ensure_native_endian": False, + "ensure_alignment": pa.ipc.Alignment.DataTypeSpecific, + "use_threads": False, + "included_fields": [1, 2, 3], + } + else: + return {} + + +@pytest.mark.parametrize( + "read_options_args", ["default", "all"], indirect=True) +def test_read_options_repr(read_options_args): + # https://github.com/apache/arrow/issues/47358 + check_ipc_options_repr(pa.ipc.IpcReadOptions, read_options_args) diff --git a/shared/package-files/28/28545913b507566ea1067ef5cdf05031b3ea7ae046fe3e71ba79cdecdfbba728/aas1901 b/shared/package-files/28/28545913b507566ea1067ef5cdf05031b3ea7ae046fe3e71ba79cdecdfbba728/aas1901 new file mode 100644 index 0000000000000000000000000000000000000000..6dcde9d7155779a99fb1d3755d39a87c034c74d0 Binary files /dev/null and b/shared/package-files/28/28545913b507566ea1067ef5cdf05031b3ea7ae046fe3e71ba79cdecdfbba728/aas1901 differ diff --git a/shared/package-files/28/2854647d0ea2c8b7a460c73ed1525f7cd2b37fb11e16f224db346c168430c1c2/sparse.py b/shared/package-files/28/2854647d0ea2c8b7a460c73ed1525f7cd2b37fb11e16f224db346c168430c1c2/sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..77583a3fe57292430ef8f00365b5848e5be58095 --- /dev/null +++ b/shared/package-files/28/2854647d0ea2c8b7a460c73ed1525f7cd2b37fb11e16f224db346c168430c1c2/sparse.py @@ -0,0 +1,473 @@ +from collections.abc import Callable + +from sympy.core.containers import Dict +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import is_sequence +from sympy.utilities.misc import as_int + +from .matrices import MatrixBase +from .repmatrix import MutableRepMatrix, RepMatrix + +from .utilities import _iszero + +from .decompositions import ( + _liupc, _row_structure_symbolic_cholesky, _cholesky_sparse, + _LDLdecomposition_sparse) + +from .solvers import ( + _lower_triangular_solve_sparse, _upper_triangular_solve_sparse) + + +class SparseRepMatrix(RepMatrix): + """ + A sparse matrix (a matrix with a large number of zero elements). + + Examples + ======== + + >>> from sympy import SparseMatrix, ones + >>> SparseMatrix(2, 2, range(4)) + Matrix([ + [0, 1], + [2, 3]]) + >>> SparseMatrix(2, 2, {(1, 1): 2}) + Matrix([ + [0, 0], + [0, 2]]) + + A SparseMatrix can be instantiated from a ragged list of lists: + + >>> SparseMatrix([[1, 2, 3], [1, 2], [1]]) + Matrix([ + [1, 2, 3], + [1, 2, 0], + [1, 0, 0]]) + + For safety, one may include the expected size and then an error + will be raised if the indices of any element are out of range or + (for a flat list) if the total number of elements does not match + the expected shape: + + >>> SparseMatrix(2, 2, [1, 2]) + Traceback (most recent call last): + ... + ValueError: List length (2) != rows*columns (4) + + Here, an error is not raised because the list is not flat and no + element is out of range: + + >>> SparseMatrix(2, 2, [[1, 2]]) + Matrix([ + [1, 2], + [0, 0]]) + + But adding another element to the first (and only) row will cause + an error to be raised: + + >>> SparseMatrix(2, 2, [[1, 2, 3]]) + Traceback (most recent call last): + ... + ValueError: The location (0, 2) is out of designated range: (1, 1) + + To autosize the matrix, pass None for rows: + + >>> SparseMatrix(None, [[1, 2, 3]]) + Matrix([[1, 2, 3]]) + >>> SparseMatrix(None, {(1, 1): 1, (3, 3): 3}) + Matrix([ + [0, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 3]]) + + Values that are themselves a Matrix are automatically expanded: + + >>> SparseMatrix(4, 4, {(1, 1): ones(2)}) + Matrix([ + [0, 0, 0, 0], + [0, 1, 1, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]]) + + A ValueError is raised if the expanding matrix tries to overwrite + a different element already present: + + >>> SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2}) + Traceback (most recent call last): + ... + ValueError: collision at (1, 1) + + See Also + ======== + DenseMatrix + MutableSparseMatrix + ImmutableSparseMatrix + """ + + @classmethod + def _handle_creation_inputs(cls, *args, **kwargs): + if len(args) == 1 and isinstance(args[0], MatrixBase): + rows = args[0].rows + cols = args[0].cols + smat = args[0].todok() + return rows, cols, smat + + smat = {} + # autosizing + if len(args) == 2 and args[0] is None: + args = [None, None, args[1]] + + if len(args) == 3: + r, c = args[:2] + if r is c is None: + rows = cols = None + elif None in (r, c): + raise ValueError( + 'Pass rows=None and no cols for autosizing.') + else: + rows, cols = as_int(args[0]), as_int(args[1]) + + if isinstance(args[2], Callable): + op = args[2] + + if None in (rows, cols): + raise ValueError( + "{} and {} must be integers for this " + "specification.".format(rows, cols)) + + row_indices = [cls._sympify(i) for i in range(rows)] + col_indices = [cls._sympify(j) for j in range(cols)] + + for i in row_indices: + for j in col_indices: + value = cls._sympify(op(i, j)) + if value != cls.zero: + smat[i, j] = value + + return rows, cols, smat + + elif isinstance(args[2], (dict, Dict)): + def update(i, j, v): + # update smat and make sure there are no collisions + if v: + if (i, j) in smat and v != smat[i, j]: + raise ValueError( + "There is a collision at {} for {} and {}." + .format((i, j), v, smat[i, j]) + ) + smat[i, j] = v + + # manual copy, copy.deepcopy() doesn't work + for (r, c), v in args[2].items(): + if isinstance(v, MatrixBase): + for (i, j), vv in v.todok().items(): + update(r + i, c + j, vv) + elif isinstance(v, (list, tuple)): + _, _, smat = cls._handle_creation_inputs(v, **kwargs) + for i, j in smat: + update(r + i, c + j, smat[i, j]) + else: + v = cls._sympify(v) + update(r, c, cls._sympify(v)) + + elif is_sequence(args[2]): + flat = not any(is_sequence(i) for i in args[2]) + if not flat: + _, _, smat = \ + cls._handle_creation_inputs(args[2], **kwargs) + else: + flat_list = args[2] + if len(flat_list) != rows * cols: + raise ValueError( + "The length of the flat list ({}) does not " + "match the specified size ({} * {})." + .format(len(flat_list), rows, cols) + ) + + for i in range(rows): + for j in range(cols): + value = flat_list[i*cols + j] + value = cls._sympify(value) + if value != cls.zero: + smat[i, j] = value + + if rows is None: # autosizing + keys = smat.keys() + rows = max([r for r, _ in keys]) + 1 if keys else 0 + cols = max([c for _, c in keys]) + 1 if keys else 0 + + else: + for i, j in smat.keys(): + if i and i >= rows or j and j >= cols: + raise ValueError( + "The location {} is out of the designated range" + "[{}, {}]x[{}, {}]" + .format((i, j), 0, rows - 1, 0, cols - 1) + ) + + return rows, cols, smat + + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + # list of values or lists + v = args[0] + c = 0 + for i, row in enumerate(v): + if not isinstance(row, (list, tuple)): + row = [row] + for j, vv in enumerate(row): + if vv != cls.zero: + smat[i, j] = cls._sympify(vv) + c = max(c, len(row)) + rows = len(v) if c else 0 + cols = c + return rows, cols, smat + + else: + # handle full matrix forms with _handle_creation_inputs + rows, cols, mat = super()._handle_creation_inputs(*args) + for i in range(rows): + for j in range(cols): + value = mat[cols*i + j] + if value != cls.zero: + smat[i, j] = value + + return rows, cols, smat + + @property + def _smat(self): + + sympy_deprecation_warning( + """ + The private _smat attribute of SparseMatrix is deprecated. Use the + .todok() method instead. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-private-matrix-attributes" + ) + + return self.todok() + + def _eval_inverse(self, **kwargs): + return self.inv(method=kwargs.get('method', 'LDL'), + iszerofunc=kwargs.get('iszerofunc', _iszero), + try_block_diag=kwargs.get('try_block_diag', False)) + + def applyfunc(self, f): + """Apply a function to each element of the matrix. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> m = SparseMatrix(2, 2, lambda i, j: i*2+j) + >>> m + Matrix([ + [0, 1], + [2, 3]]) + >>> m.applyfunc(lambda i: 2*i) + Matrix([ + [0, 2], + [4, 6]]) + + """ + if not callable(f): + raise TypeError("`f` must be callable.") + + # XXX: This only applies the function to the nonzero elements of the + # matrix so is inconsistent with DenseMatrix.applyfunc e.g. + # zeros(2, 2).applyfunc(lambda x: x + 1) + dok = {} + for k, v in self.todok().items(): + fv = f(v) + if fv != 0: + dok[k] = fv + + return self._new(self.rows, self.cols, dok) + + def as_immutable(self): + """Returns an Immutable version of this Matrix.""" + from .immutable import ImmutableSparseMatrix + return ImmutableSparseMatrix(self) + + def as_mutable(self): + """Returns a mutable version of this matrix. + + Examples + ======== + + >>> from sympy import ImmutableMatrix + >>> X = ImmutableMatrix([[1, 2], [3, 4]]) + >>> Y = X.as_mutable() + >>> Y[1, 1] = 5 # Can set values in Y + >>> Y + Matrix([ + [1, 2], + [3, 5]]) + """ + return MutableSparseMatrix(self) + + def col_list(self): + """Returns a column-sorted list of non-zero elements of the matrix. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> a=SparseMatrix(((1, 2), (3, 4))) + >>> a + Matrix([ + [1, 2], + [3, 4]]) + >>> a.CL + [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)] + + See Also + ======== + + sympy.matrices.sparse.SparseMatrix.row_list + """ + return [tuple(k + (self[k],)) for k in sorted(self.todok().keys(), key=lambda k: list(reversed(k)))] + + def nnz(self): + """Returns the number of non-zero elements in Matrix.""" + return len(self.todok()) + + def row_list(self): + """Returns a row-sorted list of non-zero elements of the matrix. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> a = SparseMatrix(((1, 2), (3, 4))) + >>> a + Matrix([ + [1, 2], + [3, 4]]) + >>> a.RL + [(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)] + + See Also + ======== + + sympy.matrices.sparse.SparseMatrix.col_list + """ + return [tuple(k + (self[k],)) for k in + sorted(self.todok().keys(), key=list)] + + def scalar_multiply(self, scalar): + "Scalar element-wise multiplication" + return scalar * self + + def solve_least_squares(self, rhs, method='LDL'): + """Return the least-square fit to the data. + + By default the cholesky_solve routine is used (method='CH'); other + methods of matrix inversion can be used. To find out which are + available, see the docstring of the .inv() method. + + Examples + ======== + + >>> from sympy import SparseMatrix, Matrix, ones + >>> A = Matrix([1, 2, 3]) + >>> B = Matrix([2, 3, 4]) + >>> S = SparseMatrix(A.row_join(B)) + >>> S + Matrix([ + [1, 2], + [2, 3], + [3, 4]]) + + If each line of S represent coefficients of Ax + By + and x and y are [2, 3] then S*xy is: + + >>> r = S*Matrix([2, 3]); r + Matrix([ + [ 8], + [13], + [18]]) + + But let's add 1 to the middle value and then solve for the + least-squares value of xy: + + >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy + Matrix([ + [ 5/3], + [10/3]]) + + The error is given by S*xy - r: + + >>> S*xy - r + Matrix([ + [1/3], + [1/3], + [1/3]]) + >>> _.norm().n(2) + 0.58 + + If a different xy is used, the norm will be higher: + + >>> xy += ones(2, 1)/10 + >>> (S*xy - r).norm().n(2) + 1.5 + + """ + t = self.T + return (t*self).inv(method=method)*t*rhs + + def solve(self, rhs, method='LDL'): + """Return solution to self*soln = rhs using given inversion method. + + For a list of possible inversion methods, see the .inv() docstring. + """ + if not self.is_square: + if self.rows < self.cols: + raise ValueError('Under-determined system.') + elif self.rows > self.cols: + raise ValueError('For over-determined system, M, having ' + 'more rows than columns, try M.solve_least_squares(rhs).') + else: + return self.inv(method=method).multiply(rhs) + + RL = property(row_list, None, None, "Alternate faster representation") + CL = property(col_list, None, None, "Alternate faster representation") + + def liupc(self): + return _liupc(self) + + def row_structure_symbolic_cholesky(self): + return _row_structure_symbolic_cholesky(self) + + def cholesky(self, hermitian=True): + return _cholesky_sparse(self, hermitian=hermitian) + + def LDLdecomposition(self, hermitian=True): + return _LDLdecomposition_sparse(self, hermitian=hermitian) + + def lower_triangular_solve(self, rhs): + return _lower_triangular_solve_sparse(self, rhs) + + def upper_triangular_solve(self, rhs): + return _upper_triangular_solve_sparse(self, rhs) + + liupc.__doc__ = _liupc.__doc__ + row_structure_symbolic_cholesky.__doc__ = _row_structure_symbolic_cholesky.__doc__ + cholesky.__doc__ = _cholesky_sparse.__doc__ + LDLdecomposition.__doc__ = _LDLdecomposition_sparse.__doc__ + lower_triangular_solve.__doc__ = lower_triangular_solve.__doc__ + upper_triangular_solve.__doc__ = upper_triangular_solve.__doc__ + + +class MutableSparseMatrix(SparseRepMatrix, MutableRepMatrix): + + @classmethod + def _new(cls, *args, **kwargs): + rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs) + + rep = cls._smat_to_DomainMatrix(rows, cols, smat) + + return cls._fromrep(rep) + + +SparseMatrix = MutableSparseMatrix diff --git a/shared/package-files/28/285847330d732e8c2dc5d9ae87ec6c06d3f28bfd55cc4b043f2c2694064817d3/unflatten_dense_tensors_native.h b/shared/package-files/28/285847330d732e8c2dc5d9ae87ec6c06d3f28bfd55cc4b043f2c2694064817d3/unflatten_dense_tensors_native.h new file mode 100644 index 0000000000000000000000000000000000000000..9c56cc113680cf9b47f376438c201b33b3007a31 --- /dev/null +++ b/shared/package-files/28/285847330d732e8c2dc5d9ae87ec6c06d3f28bfd55cc4b043f2c2694064817d3/unflatten_dense_tensors_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 ::std::vector unflatten_dense_tensors(const at::Tensor & flat, at::TensorList tensors); +} // namespace native +} // namespace at diff --git a/shared/package-files/28/285946b11d51cc56995b63eea835666e721ea368c1b0d0974a879b7d532637d1/__init__.pyi b/shared/package-files/28/285946b11d51cc56995b63eea835666e721ea368c1b0d0974a879b7d532637d1/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..14e3dd41ac74a6756b8a163ebe7893d4c5635905 --- /dev/null +++ b/shared/package-files/28/285946b11d51cc56995b63eea835666e721ea368c1b0d0974a879b7d532637d1/__init__.pyi @@ -0,0 +1,8 @@ +from .bdist import BDist as BDist +from .develop import Develop as Develop +from .distribution import Distribution as Distribution +from .index import Index as Index +from .installed import Installed as Installed +from .sdist import SDist as SDist, UnpackedSDist as UnpackedSDist +from .utils import get_metadata as get_metadata +from .wheel import Wheel as Wheel diff --git a/shared/package-files/28/285acb523c05c527aa1905b4039b4b2d7928987be91ec630ef8cb5ef04c2fe99/e3.dat b/shared/package-files/28/285acb523c05c527aa1905b4039b4b2d7928987be91ec630ef8cb5ef04c2fe99/e3.dat new file mode 100644 index 0000000000000000000000000000000000000000..234434d0de7b130f65b56a77d10bdcb51efe6c5f --- /dev/null +++ b/shared/package-files/28/285acb523c05c527aa1905b4039b4b2d7928987be91ec630ef8cb5ef04c2fe99/e3.dat @@ -0,0 +1,146 @@ +/*quarterly, seasonally adjusted real U.S. money (M1), +GNP in 1982 Dollars, +discount rate on 91-day treasury bills (rd), +yield on long term treasury bonds (rb), +1954Q1-1987Q4; +source: Business Conditions Digest +*/ + +<1954 Q1> +M1 gnp rd rb +450.9 1406.8 0.010800000 0.026133333 +453.0 1401.2 0.0081333333 0.025233333 +459.1 1418.0 0.0087000000 0.024900000 +464.6 1438.8 0.010366667 0.025666667 +469.6 1469.6 0.012600000 0.027466667 +473.1 1485.7 0.015133333 0.028166667 +474.6 1505.5 0.018633333 0.029266667 +474.3 1518.7 0.023466667 0.028900000 +475.4 1515.7 0.023800000 0.028866667 +472.9 1522.6 0.025966667 0.029900000 +468.7 1523.7 0.025966667 0.031266667 +467.5 1540.6 0.030633333 0.033000000 +464.7 1553.3 0.031700000 0.032733333 +461.2 1552.4 0.031566667 0.034333333 +457.1 1561.5 0.033800000 0.036300000 +453.0 1537.3 0.033433333 0.035333333 +447.5 1506.1 0.018366667 0.032566667 +449.6 1514.2 0.010200000 0.031533333 +454.2 1550.0 0.017100000 0.035700000 +458.5 1586.7 0.027866667 0.037533333 +464.1 1606.4 0.028000000 0.039166667 +466.3 1637.0 0.030200000 0.040600000 +468.1 1629.5 0.035333333 0.041566667 +460.0 1643.4 0.043000000 0.041666667 +459.2 1671.6 0.039433333 0.042233333 +455.7 1666.8 0.030900000 0.041066667 +459.5 1668.4 0.023933333 0.038300000 +455.9 1654.1 0.023600000 0.039066667 +458.0 1671.3 0.023766667 0.038266667 +461.5 1692.1 0.023266667 0.038033333 +462.2 1716.3 0.023233333 0.039733333 +465.4 1754.9 0.024766667 0.040066667 +467.4 1777.9 0.027400000 0.040600000 +468.5 1796.4 0.027166667 0.038900000 +466.5 1813.1 0.028566667 0.039800000 +467.7 1810.1 0.028033333 0.038766667 +471.9 1834.6 0.029100000 0.039133333 +474.8 1860.0 0.029433333 0.039800000 +477.7 1892.5 0.032800000 0.040133333 +479.9 1906.1 0.034966667 0.041066667 +481.9 1948.7 0.035366667 0.041566667 +484.8 1965.4 0.034800000 0.041633333 +491.3 1985.2 0.035066667 0.041433333 +495.6 1993.7 0.036866667 0.041400000 +498.3 2036.9 0.039000000 0.041500000 +497.6 2066.4 0.038800000 0.041433333 +501.7 2099.3 0.038600000 0.041966667 +507.8 2147.6 0.041566667 0.043500000 +511.8 2190.1 0.046333333 0.045566667 +511.8 2195.8 0.045966667 0.045833333 +506.2 2218.3 0.050500000 0.047800000 +503.1 2229.2 0.045800000 0.046966667 +507.1 2241.8 0.045266667 0.044400000 +510.8 2255.2 0.036566667 0.047100000 +518.0 2287.7 0.043466667 0.049333333 +521.3 2300.6 0.047866667 0.053300000 +521.9 2327.3 0.050633333 0.052433333 +525.4 2366.9 0.055066667 0.053033333 +528.3 2385.3 0.052266667 0.050733333 +533.8 2383.0 0.055800000 0.054200000 +536.5 2416.5 0.061400000 0.058833333 +532.8 2419.8 0.062400000 0.059133333 +527.6 2433.2 0.070466667 0.061366667 +523.2 2423.5 0.073166667 0.065333333 +521.4 2408.6 0.072600000 0.065633333 +518.1 2406.5 0.067533333 0.068200000 +519.4 2435.8 0.063833333 0.066500000 +521.2 2413.8 0.053600000 0.062666667 +524.7 2478.6 0.038600000 0.058233333 +530.8 2478.4 0.042066667 0.058833333 +534.1 2491.1 0.050500000 0.057500000 +536.5 2491.0 0.042333333 0.055200000 +542.6 2545.6 0.034333333 0.056500000 +547.8 2595.1 0.037466667 0.056566667 +554.4 2622.1 0.042400000 0.056266667 +562.5 2671.3 0.048500000 0.056100000 +565.2 2734.0 0.056400000 0.061000000 +560.1 2741.0 0.066100000 0.062266667 +556.1 2738.3 0.083900000 0.065966667 +548.5 2762.8 0.074633333 0.063000000 +542.1 2747.4 0.076033333 0.066366667 +532.8 2755.2 0.082666667 0.070500000 +522.8 2719.3 0.082833333 0.072700000 +511.9 2695.4 0.073333333 0.069733333 +505.3 2642.7 0.058700000 0.067033333 +506.8 2669.6 0.054000000 0.069733333 +505.5 2714.9 0.063333333 0.070933333 +501.0 2752.7 0.056833333 0.072233333 +502.2 2804.4 0.049533333 0.069100000 +505.5 2816.9 0.051666667 0.068866667 +502.6 2828.6 0.051700000 0.067900000 +505.3 2856.8 0.046966667 0.065500000 +508.1 2896.0 0.046233333 0.070133333 +507.7 2942.7 0.048266667 0.070966667 +509.4 3001.8 0.054733333 0.069766667 +513.0 2994.1 0.061366667 0.071600000 +513.7 3020.5 0.064100000 0.075800000 +514.1 3115.9 0.064833333 0.078500000 +512.5 3142.6 0.073166667 0.079333333 +509.7 3181.6 0.086800000 0.081966667 +503.3 3181.7 0.093600000 0.084366667 +496.1 3178.9 0.093733333 0.084366667 +497.2 3207.4 0.096300000 0.084833333 +487.6 3201.3 0.11803333 0.096066667 +474.0 3233.4 0.13460000 0.11150000 +451.2 3157.0 0.10050000 0.10016667 +464.9 3159.1 0.092366667 0.10433333 +465.3 3199.2 0.13710000 0.11640000 +455.3 3261.1 0.14366667 0.12010000 +453.7 3250.2 0.14830000 0.12656667 +448.9 3264.6 0.15086667 0.13600000 +447.1 3219.3 0.12023333 0.13230000 +451.2 3170.4 0.12893333 0.13446667 +447.1 3179.9 0.12360000 0.12943333 +449.1 3154.5 0.097066667 0.12200000 +464.9 3159.3 0.079333333 0.10340000 +475.8 3186.6 0.080800000 0.10436667 +484.3 3258.3 0.084200000 0.10346667 +493.6 3306.4 0.091866667 0.11260000 +496.4 3365.1 0.087933333 0.11323333 +497.5 3451.7 0.091333333 0.11543333 +500.4 3498.0 0.098433333 0.12686667 +501.5 3520.6 0.10343333 0.12340000 +502.2 3535.2 0.089733333 0.11373333 +511.0 3577.5 0.081833333 0.11426667 +518.2 3599.2 0.075233333 0.10913333 +533.9 3635.8 0.071033333 0.10590000 +543.2 3662.4 0.071466667 0.10080000 +553.4 3719.3 0.068866667 0.089033333 +576.8 3711.6 0.061300000 0.079466667 +598.0 3721.3 0.055333333 0.078866667 +620.0 3734.7 0.053400000 0.078400000 +631.9 3776.7 0.055333333 0.076366667 +634.8 3823.0 0.057333333 0.085766667 +630.1 3865.3 0.060333333 0.090833333 +630.5 3923.0 0.060033333 0.092400000 diff --git a/shared/package-files/28/286065fc5817d4a575c0122c856e045e55a33f728b711885da8a59fb355cc807/__init__.py b/shared/package-files/28/286065fc5817d4a575c0122c856e045e55a33f728b711885da8a59fb355cc807/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3974587e934cd071f14cd6f8c77dceb6cf7e0e --- /dev/null +++ b/shared/package-files/28/286065fc5817d4a575c0122c856e045e55a33f728b711885da8a59fb355cc807/__init__.py @@ -0,0 +1,631 @@ +# Use of this source code is governed by the MIT license. +__license__ = "MIT" + +from collections import defaultdict +import itertools +import re +import warnings +import sys +from bs4.element import ( + CharsetMetaAttributeValue, + ContentMetaAttributeValue, + RubyParenthesisString, + RubyTextString, + Stylesheet, + Script, + TemplateString, + nonwhitespace_re +) + +__all__ = [ + 'HTMLTreeBuilder', + 'SAXTreeBuilder', + 'TreeBuilder', + 'TreeBuilderRegistry', + ] + +# Some useful features for a TreeBuilder to have. +FAST = 'fast' +PERMISSIVE = 'permissive' +STRICT = 'strict' +XML = 'xml' +HTML = 'html' +HTML_5 = 'html5' + +class XMLParsedAsHTMLWarning(UserWarning): + """The warning issued when an HTML parser is used to parse + XML that is not XHTML. + """ + MESSAGE = """It looks like you're parsing an XML document using an HTML parser. If this really is an HTML document (maybe it's XHTML?), you can ignore or filter this warning. If it's XML, you should know that using an XML parser will be more reliable. To parse this document as XML, make sure you have the lxml package installed, and pass the keyword argument `features="xml"` into the BeautifulSoup constructor.""" + + +class TreeBuilderRegistry(object): + """A way of looking up TreeBuilder subclasses by their name or by desired + features. + """ + + def __init__(self): + self.builders_for_feature = defaultdict(list) + self.builders = [] + + def register(self, treebuilder_class): + """Register a treebuilder based on its advertised features. + + :param treebuilder_class: A subclass of Treebuilder. its .features + attribute should list its features. + """ + for feature in treebuilder_class.features: + self.builders_for_feature[feature].insert(0, treebuilder_class) + self.builders.insert(0, treebuilder_class) + + def lookup(self, *features): + """Look up a TreeBuilder subclass with the desired features. + + :param features: A list of features to look for. If none are + provided, the most recently registered TreeBuilder subclass + will be used. + :return: A TreeBuilder subclass, or None if there's no + registered subclass with all the requested features. + """ + if len(self.builders) == 0: + # There are no builders at all. + return None + + if len(features) == 0: + # They didn't ask for any features. Give them the most + # recently registered builder. + return self.builders[0] + + # Go down the list of features in order, and eliminate any builders + # that don't match every feature. + features = list(features) + features.reverse() + candidates = None + candidate_set = None + while len(features) > 0: + feature = features.pop() + we_have_the_feature = self.builders_for_feature.get(feature, []) + if len(we_have_the_feature) > 0: + if candidates is None: + candidates = we_have_the_feature + candidate_set = set(candidates) + else: + # Eliminate any candidates that don't have this feature. + candidate_set = candidate_set.intersection( + set(we_have_the_feature)) + + # The only valid candidates are the ones in candidate_set. + # Go through the original list of candidates and pick the first one + # that's in candidate_set. + if candidate_set is None: + return None + for candidate in candidates: + if candidate in candidate_set: + return candidate + return None + +# The BeautifulSoup class will take feature lists from developers and use them +# to look up builders in this registry. +builder_registry = TreeBuilderRegistry() + +class TreeBuilder(object): + """Turn a textual document into a Beautiful Soup object tree.""" + + NAME = "[Unknown tree builder]" + ALTERNATE_NAMES = [] + features = [] + + is_xml = False + picklable = False + empty_element_tags = None # A tag will be considered an empty-element + # tag when and only when it has no contents. + + # A value for these tag/attribute combinations is a space- or + # comma-separated list of CDATA, rather than a single CDATA. + DEFAULT_CDATA_LIST_ATTRIBUTES = defaultdict(list) + + # Whitespace should be preserved inside these tags. + DEFAULT_PRESERVE_WHITESPACE_TAGS = set() + + # The textual contents of tags with these names should be + # instantiated with some class other than NavigableString. + DEFAULT_STRING_CONTAINERS = {} + + USE_DEFAULT = object() + + # Most parsers don't keep track of line numbers. + TRACKS_LINE_NUMBERS = False + + def __init__(self, multi_valued_attributes=USE_DEFAULT, + preserve_whitespace_tags=USE_DEFAULT, + store_line_numbers=USE_DEFAULT, + string_containers=USE_DEFAULT, + ): + """Constructor. + + :param multi_valued_attributes: If this is set to None, the + TreeBuilder will not turn any values for attributes like + 'class' into lists. Setting this to a dictionary will + customize this behavior; look at DEFAULT_CDATA_LIST_ATTRIBUTES + for an example. + + Internally, these are called "CDATA list attributes", but that + probably doesn't make sense to an end-user, so the argument name + is `multi_valued_attributes`. + + :param preserve_whitespace_tags: A list of tags to treat + the way
 tags are treated in HTML. Tags in this list
+         are immune from pretty-printing; their contents will always be
+         output as-is.
+
+        :param string_containers: A dictionary mapping tag names to
+        the classes that should be instantiated to contain the textual
+        contents of those tags. The default is to use NavigableString
+        for every tag, no matter what the name. You can override the
+        default by changing DEFAULT_STRING_CONTAINERS.
+
+        :param store_line_numbers: If the parser keeps track of the
+         line numbers and positions of the original markup, that
+         information will, by default, be stored in each corresponding
+         `Tag` object. You can turn this off by passing
+         store_line_numbers=False. If the parser you're using doesn't 
+         keep track of this information, then setting store_line_numbers=True
+         will do nothing.
+        """
+        self.soup = None
+        if multi_valued_attributes is self.USE_DEFAULT:
+            multi_valued_attributes = self.DEFAULT_CDATA_LIST_ATTRIBUTES
+        self.cdata_list_attributes = multi_valued_attributes
+        if preserve_whitespace_tags is self.USE_DEFAULT:
+            preserve_whitespace_tags = self.DEFAULT_PRESERVE_WHITESPACE_TAGS
+        self.preserve_whitespace_tags = preserve_whitespace_tags
+        if store_line_numbers == self.USE_DEFAULT:
+            store_line_numbers = self.TRACKS_LINE_NUMBERS
+        self.store_line_numbers = store_line_numbers 
+        if string_containers == self.USE_DEFAULT:
+            string_containers = self.DEFAULT_STRING_CONTAINERS
+        self.string_containers = string_containers
+        
+    def initialize_soup(self, soup):
+        """The BeautifulSoup object has been initialized and is now
+        being associated with the TreeBuilder.
+
+        :param soup: A BeautifulSoup object.
+        """
+        self.soup = soup
+        
+    def reset(self):
+        """Do any work necessary to reset the underlying parser
+        for a new document.
+
+        By default, this does nothing.
+        """
+        pass
+
+    def can_be_empty_element(self, tag_name):
+        """Might a tag with this name be an empty-element tag?
+
+        The final markup may or may not actually present this tag as
+        self-closing.
+
+        For instance: an HTMLBuilder does not consider a 

tag to be + an empty-element tag (it's not in + HTMLBuilder.empty_element_tags). This means an empty

tag + will be presented as "

", not "

" or "

". + + The default implementation has no opinion about which tags are + empty-element tags, so a tag will be presented as an + empty-element tag if and only if it has no children. + "" will become "", and "bar" will + be left alone. + + :param tag_name: The name of a markup tag. + """ + if self.empty_element_tags is None: + return True + return tag_name in self.empty_element_tags + + def feed(self, markup): + """Run some incoming markup through some parsing process, + populating the `BeautifulSoup` object in self.soup. + + This method is not implemented in TreeBuilder; it must be + implemented in subclasses. + + :return: None. + """ + raise NotImplementedError() + + def prepare_markup(self, markup, user_specified_encoding=None, + document_declared_encoding=None, exclude_encodings=None): + """Run any preliminary steps necessary to make incoming markup + acceptable to the parser. + + :param markup: Some markup -- probably a bytestring. + :param user_specified_encoding: The user asked to try this encoding. + :param document_declared_encoding: The markup itself claims to be + in this encoding. NOTE: This argument is not used by the + calling code and can probably be removed. + :param exclude_encodings: The user asked _not_ to try any of + these encodings. + + :yield: A series of 4-tuples: + (markup, encoding, declared encoding, + has undergone character replacement) + + Each 4-tuple represents a strategy for converting the + document to Unicode and parsing it. Each strategy will be tried + in turn. + + By default, the only strategy is to parse the markup + as-is. See `LXMLTreeBuilderForXML` and + `HTMLParserTreeBuilder` for implementations that take into + account the quirks of particular parsers. + """ + yield markup, None, None, False + + def test_fragment_to_document(self, fragment): + """Wrap an HTML fragment to make it look like a document. + + Different parsers do this differently. For instance, lxml + introduces an empty tag, and html5lib + doesn't. Abstracting this away lets us write simple tests + which run HTML fragments through the parser and compare the + results against other HTML fragments. + + This method should not be used outside of tests. + + :param fragment: A string -- fragment of HTML. + :return: A string -- a full HTML document. + """ + return fragment + + def set_up_substitutions(self, tag): + """Set up any substitutions that will need to be performed on + a `Tag` when it's output as a string. + + By default, this does nothing. See `HTMLTreeBuilder` for a + case where this is used. + + :param tag: A `Tag` + :return: Whether or not a substitution was performed. + """ + return False + + def _replace_cdata_list_attribute_values(self, tag_name, attrs): + """When an attribute value is associated with a tag that can + have multiple values for that attribute, convert the string + value to a list of strings. + + Basically, replaces class="foo bar" with class=["foo", "bar"] + + NOTE: This method modifies its input in place. + + :param tag_name: The name of a tag. + :param attrs: A dictionary containing the tag's attributes. + Any appropriate attribute values will be modified in place. + """ + if not attrs: + return attrs + if self.cdata_list_attributes: + universal = self.cdata_list_attributes.get('*', []) + tag_specific = self.cdata_list_attributes.get( + tag_name.lower(), None) + for attr in list(attrs.keys()): + if attr in universal or (tag_specific and attr in tag_specific): + # We have a "class"-type attribute whose string + # value is a whitespace-separated list of + # values. Split it into a list. + value = attrs[attr] + if isinstance(value, str): + values = nonwhitespace_re.findall(value) + else: + # html5lib sometimes calls setAttributes twice + # for the same tag when rearranging the parse + # tree. On the second call the attribute value + # here is already a list. If this happens, + # leave the value alone rather than trying to + # split it again. + values = value + attrs[attr] = values + return attrs + +class SAXTreeBuilder(TreeBuilder): + """A Beautiful Soup treebuilder that listens for SAX events. + + This is not currently used for anything, but it demonstrates + how a simple TreeBuilder would work. + """ + + def feed(self, markup): + raise NotImplementedError() + + def close(self): + pass + + def startElement(self, name, attrs): + attrs = dict((key[1], value) for key, value in list(attrs.items())) + #print("Start %s, %r" % (name, attrs)) + self.soup.handle_starttag(name, attrs) + + def endElement(self, name): + #print("End %s" % name) + self.soup.handle_endtag(name) + + def startElementNS(self, nsTuple, nodeName, attrs): + # Throw away (ns, nodeName) for now. + self.startElement(nodeName, attrs) + + def endElementNS(self, nsTuple, nodeName): + # Throw away (ns, nodeName) for now. + self.endElement(nodeName) + #handler.endElementNS((ns, node.nodeName), node.nodeName) + + def startPrefixMapping(self, prefix, nodeValue): + # Ignore the prefix for now. + pass + + def endPrefixMapping(self, prefix): + # Ignore the prefix for now. + # handler.endPrefixMapping(prefix) + pass + + def characters(self, content): + self.soup.handle_data(content) + + def startDocument(self): + pass + + def endDocument(self): + pass + + +class HTMLTreeBuilder(TreeBuilder): + """This TreeBuilder knows facts about HTML. + + Such as which tags are empty-element tags. + """ + + empty_element_tags = set([ + # These are from HTML5. + 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr', + + # These are from earlier versions of HTML and are removed in HTML5. + 'basefont', 'bgsound', 'command', 'frame', 'image', 'isindex', 'nextid', 'spacer' + ]) + + # The HTML standard defines these as block-level elements. Beautiful + # Soup does not treat these elements differently from other elements, + # but it may do so eventually, and this information is available if + # you need to use it. + block_elements = set(["address", "article", "aside", "blockquote", "canvas", "dd", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video"]) + + # These HTML tags need special treatment so they can be + # represented by a string class other than NavigableString. + # + # For some of these tags, it's because the HTML standard defines + # an unusual content model for them. I made this list by going + # through the HTML spec + # (https://html.spec.whatwg.org/#metadata-content) and looking for + # "metadata content" elements that can contain strings. + # + # The Ruby tags ( and ) are here despite being normal + # "phrasing content" tags, because the content they contain is + # qualitatively different from other text in the document, and it + # can be useful to be able to distinguish it. + # + # TODO: Arguably